repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
patjak/linux-stable | drivers/scsi/libsrp.c | 8067 | 10780 | /*
* SCSI RDMA Protocol lib functions
*
* Copyright (C) 2006 FUJITA Tomonori <tomof@acm.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 St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/kfifo.h>
#include <linux/scatterlist.h>
#include <linux/dma-mapping.h>
#include <linux/module.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_tcq.h>
#include <scsi/scsi_tgt.h>
#include <scsi/srp.h>
#include <scsi/libsrp.h>
enum srp_task_attributes {
SRP_SIMPLE_TASK = 0,
SRP_HEAD_TASK = 1,
SRP_ORDERED_TASK = 2,
SRP_ACA_TASK = 4
};
/* tmp - will replace with SCSI logging stuff */
#define eprintk(fmt, args...) \
do { \
printk("%s(%d) " fmt, __func__, __LINE__, ##args); \
} while (0)
/* #define dprintk eprintk */
#define dprintk(fmt, args...)
static int srp_iu_pool_alloc(struct srp_queue *q, size_t max,
struct srp_buf **ring)
{
int i;
struct iu_entry *iue;
q->pool = kcalloc(max, sizeof(struct iu_entry *), GFP_KERNEL);
if (!q->pool)
return -ENOMEM;
q->items = kcalloc(max, sizeof(struct iu_entry), GFP_KERNEL);
if (!q->items)
goto free_pool;
spin_lock_init(&q->lock);
kfifo_init(&q->queue, (void *) q->pool, max * sizeof(void *));
for (i = 0, iue = q->items; i < max; i++) {
kfifo_in(&q->queue, (void *) &iue, sizeof(void *));
iue->sbuf = ring[i];
iue++;
}
return 0;
kfree(q->items);
free_pool:
kfree(q->pool);
return -ENOMEM;
}
static void srp_iu_pool_free(struct srp_queue *q)
{
kfree(q->items);
kfree(q->pool);
}
static struct srp_buf **srp_ring_alloc(struct device *dev,
size_t max, size_t size)
{
int i;
struct srp_buf **ring;
ring = kcalloc(max, sizeof(struct srp_buf *), GFP_KERNEL);
if (!ring)
return NULL;
for (i = 0; i < max; i++) {
ring[i] = kzalloc(sizeof(struct srp_buf), GFP_KERNEL);
if (!ring[i])
goto out;
ring[i]->buf = dma_alloc_coherent(dev, size, &ring[i]->dma,
GFP_KERNEL);
if (!ring[i]->buf)
goto out;
}
return ring;
out:
for (i = 0; i < max && ring[i]; i++) {
if (ring[i]->buf)
dma_free_coherent(dev, size, ring[i]->buf, ring[i]->dma);
kfree(ring[i]);
}
kfree(ring);
return NULL;
}
static void srp_ring_free(struct device *dev, struct srp_buf **ring, size_t max,
size_t size)
{
int i;
for (i = 0; i < max; i++) {
dma_free_coherent(dev, size, ring[i]->buf, ring[i]->dma);
kfree(ring[i]);
}
kfree(ring);
}
int srp_target_alloc(struct srp_target *target, struct device *dev,
size_t nr, size_t iu_size)
{
int err;
spin_lock_init(&target->lock);
INIT_LIST_HEAD(&target->cmd_queue);
target->dev = dev;
dev_set_drvdata(target->dev, target);
target->srp_iu_size = iu_size;
target->rx_ring_size = nr;
target->rx_ring = srp_ring_alloc(target->dev, nr, iu_size);
if (!target->rx_ring)
return -ENOMEM;
err = srp_iu_pool_alloc(&target->iu_queue, nr, target->rx_ring);
if (err)
goto free_ring;
return 0;
free_ring:
srp_ring_free(target->dev, target->rx_ring, nr, iu_size);
return -ENOMEM;
}
EXPORT_SYMBOL_GPL(srp_target_alloc);
void srp_target_free(struct srp_target *target)
{
srp_ring_free(target->dev, target->rx_ring, target->rx_ring_size,
target->srp_iu_size);
srp_iu_pool_free(&target->iu_queue);
}
EXPORT_SYMBOL_GPL(srp_target_free);
struct iu_entry *srp_iu_get(struct srp_target *target)
{
struct iu_entry *iue = NULL;
if (kfifo_out_locked(&target->iu_queue.queue, (void *) &iue,
sizeof(void *), &target->iu_queue.lock) != sizeof(void *)) {
WARN_ONCE(1, "unexpected fifo state");
return NULL;
}
if (!iue)
return iue;
iue->target = target;
INIT_LIST_HEAD(&iue->ilist);
iue->flags = 0;
return iue;
}
EXPORT_SYMBOL_GPL(srp_iu_get);
void srp_iu_put(struct iu_entry *iue)
{
kfifo_in_locked(&iue->target->iu_queue.queue, (void *) &iue,
sizeof(void *), &iue->target->iu_queue.lock);
}
EXPORT_SYMBOL_GPL(srp_iu_put);
static int srp_direct_data(struct scsi_cmnd *sc, struct srp_direct_buf *md,
enum dma_data_direction dir, srp_rdma_t rdma_io,
int dma_map, int ext_desc)
{
struct iu_entry *iue = NULL;
struct scatterlist *sg = NULL;
int err, nsg = 0, len;
if (dma_map) {
iue = (struct iu_entry *) sc->SCp.ptr;
sg = scsi_sglist(sc);
dprintk("%p %u %u %d\n", iue, scsi_bufflen(sc),
md->len, scsi_sg_count(sc));
nsg = dma_map_sg(iue->target->dev, sg, scsi_sg_count(sc),
DMA_BIDIRECTIONAL);
if (!nsg) {
printk("fail to map %p %d\n", iue, scsi_sg_count(sc));
return 0;
}
len = min(scsi_bufflen(sc), md->len);
} else
len = md->len;
err = rdma_io(sc, sg, nsg, md, 1, dir, len);
if (dma_map)
dma_unmap_sg(iue->target->dev, sg, nsg, DMA_BIDIRECTIONAL);
return err;
}
static int srp_indirect_data(struct scsi_cmnd *sc, struct srp_cmd *cmd,
struct srp_indirect_buf *id,
enum dma_data_direction dir, srp_rdma_t rdma_io,
int dma_map, int ext_desc)
{
struct iu_entry *iue = NULL;
struct srp_direct_buf *md = NULL;
struct scatterlist dummy, *sg = NULL;
dma_addr_t token = 0;
int err = 0;
int nmd, nsg = 0, len;
if (dma_map || ext_desc) {
iue = (struct iu_entry *) sc->SCp.ptr;
sg = scsi_sglist(sc);
dprintk("%p %u %u %d %d\n",
iue, scsi_bufflen(sc), id->len,
cmd->data_in_desc_cnt, cmd->data_out_desc_cnt);
}
nmd = id->table_desc.len / sizeof(struct srp_direct_buf);
if ((dir == DMA_FROM_DEVICE && nmd == cmd->data_in_desc_cnt) ||
(dir == DMA_TO_DEVICE && nmd == cmd->data_out_desc_cnt)) {
md = &id->desc_list[0];
goto rdma;
}
if (ext_desc && dma_map) {
md = dma_alloc_coherent(iue->target->dev, id->table_desc.len,
&token, GFP_KERNEL);
if (!md) {
eprintk("Can't get dma memory %u\n", id->table_desc.len);
return -ENOMEM;
}
sg_init_one(&dummy, md, id->table_desc.len);
sg_dma_address(&dummy) = token;
sg_dma_len(&dummy) = id->table_desc.len;
err = rdma_io(sc, &dummy, 1, &id->table_desc, 1, DMA_TO_DEVICE,
id->table_desc.len);
if (err) {
eprintk("Error copying indirect table %d\n", err);
goto free_mem;
}
} else {
eprintk("This command uses external indirect buffer\n");
return -EINVAL;
}
rdma:
if (dma_map) {
nsg = dma_map_sg(iue->target->dev, sg, scsi_sg_count(sc),
DMA_BIDIRECTIONAL);
if (!nsg) {
eprintk("fail to map %p %d\n", iue, scsi_sg_count(sc));
err = -EIO;
goto free_mem;
}
len = min(scsi_bufflen(sc), id->len);
} else
len = id->len;
err = rdma_io(sc, sg, nsg, md, nmd, dir, len);
if (dma_map)
dma_unmap_sg(iue->target->dev, sg, nsg, DMA_BIDIRECTIONAL);
free_mem:
if (token && dma_map)
dma_free_coherent(iue->target->dev, id->table_desc.len, md, token);
return err;
}
static int data_out_desc_size(struct srp_cmd *cmd)
{
int size = 0;
u8 fmt = cmd->buf_fmt >> 4;
switch (fmt) {
case SRP_NO_DATA_DESC:
break;
case SRP_DATA_DESC_DIRECT:
size = sizeof(struct srp_direct_buf);
break;
case SRP_DATA_DESC_INDIRECT:
size = sizeof(struct srp_indirect_buf) +
sizeof(struct srp_direct_buf) * cmd->data_out_desc_cnt;
break;
default:
eprintk("client error. Invalid data_out_format %x\n", fmt);
break;
}
return size;
}
/*
* TODO: this can be called multiple times for a single command if it
* has very long data.
*/
int srp_transfer_data(struct scsi_cmnd *sc, struct srp_cmd *cmd,
srp_rdma_t rdma_io, int dma_map, int ext_desc)
{
struct srp_direct_buf *md;
struct srp_indirect_buf *id;
enum dma_data_direction dir;
int offset, err = 0;
u8 format;
offset = cmd->add_cdb_len & ~3;
dir = srp_cmd_direction(cmd);
if (dir == DMA_FROM_DEVICE)
offset += data_out_desc_size(cmd);
if (dir == DMA_TO_DEVICE)
format = cmd->buf_fmt >> 4;
else
format = cmd->buf_fmt & ((1U << 4) - 1);
switch (format) {
case SRP_NO_DATA_DESC:
break;
case SRP_DATA_DESC_DIRECT:
md = (struct srp_direct_buf *)
(cmd->add_data + offset);
err = srp_direct_data(sc, md, dir, rdma_io, dma_map, ext_desc);
break;
case SRP_DATA_DESC_INDIRECT:
id = (struct srp_indirect_buf *)
(cmd->add_data + offset);
err = srp_indirect_data(sc, cmd, id, dir, rdma_io, dma_map,
ext_desc);
break;
default:
eprintk("Unknown format %d %x\n", dir, format);
err = -EINVAL;
}
return err;
}
EXPORT_SYMBOL_GPL(srp_transfer_data);
static int vscsis_data_length(struct srp_cmd *cmd, enum dma_data_direction dir)
{
struct srp_direct_buf *md;
struct srp_indirect_buf *id;
int len = 0, offset = cmd->add_cdb_len & ~3;
u8 fmt;
if (dir == DMA_TO_DEVICE)
fmt = cmd->buf_fmt >> 4;
else {
fmt = cmd->buf_fmt & ((1U << 4) - 1);
offset += data_out_desc_size(cmd);
}
switch (fmt) {
case SRP_NO_DATA_DESC:
break;
case SRP_DATA_DESC_DIRECT:
md = (struct srp_direct_buf *) (cmd->add_data + offset);
len = md->len;
break;
case SRP_DATA_DESC_INDIRECT:
id = (struct srp_indirect_buf *) (cmd->add_data + offset);
len = id->len;
break;
default:
eprintk("invalid data format %x\n", fmt);
break;
}
return len;
}
int srp_cmd_queue(struct Scsi_Host *shost, struct srp_cmd *cmd, void *info,
u64 itn_id, u64 addr)
{
enum dma_data_direction dir;
struct scsi_cmnd *sc;
int tag, len, err;
switch (cmd->task_attr) {
case SRP_SIMPLE_TASK:
tag = MSG_SIMPLE_TAG;
break;
case SRP_ORDERED_TASK:
tag = MSG_ORDERED_TAG;
break;
case SRP_HEAD_TASK:
tag = MSG_HEAD_TAG;
break;
default:
eprintk("Task attribute %d not supported\n", cmd->task_attr);
tag = MSG_ORDERED_TAG;
}
dir = srp_cmd_direction(cmd);
len = vscsis_data_length(cmd, dir);
dprintk("%p %x %lx %d %d %d %llx\n", info, cmd->cdb[0],
cmd->lun, dir, len, tag, (unsigned long long) cmd->tag);
sc = scsi_host_get_command(shost, dir, GFP_KERNEL);
if (!sc)
return -ENOMEM;
sc->SCp.ptr = info;
memcpy(sc->cmnd, cmd->cdb, MAX_COMMAND_SIZE);
sc->sdb.length = len;
sc->sdb.table.sgl = (void *) (unsigned long) addr;
sc->tag = tag;
err = scsi_tgt_queue_command(sc, itn_id, (struct scsi_lun *)&cmd->lun,
cmd->tag);
if (err)
scsi_host_put_command(shost, sc);
return err;
}
EXPORT_SYMBOL_GPL(srp_cmd_queue);
MODULE_DESCRIPTION("SCSI RDMA Protocol lib functions");
MODULE_AUTHOR("FUJITA Tomonori");
MODULE_LICENSE("GPL");
| gpl-2.0 |
cile381/android_kernel_m7 | arch/frv/kernel/gdb-io.c | 9091 | 4966 | /* 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/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 |
jpirko/rocker_bpf | drivers/net/wireless/b43/tables.c | 10627 | 14620 | /*
Broadcom B43 wireless driver
Copyright (c) 2005 Martin Langer <martin-langer@gmx.de>,
Copyright (c) 2005-2007 Stefano Brivio <stefano.brivio@polimi.it>
Copyright (c) 2006, 2006 Michael Buesch <m@bues.ch>
Copyright (c) 2005 Danny van Dyk <kugelfang@gentoo.org>
Copyright (c) 2005 Andreas Jaggi <andreas.jaggi@waterwave.ch>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
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 "b43.h"
#include "tables.h"
#include "phy_g.h"
const u32 b43_tab_rotor[] = {
0xFEB93FFD, 0xFEC63FFD, /* 0 */
0xFED23FFD, 0xFEDF3FFD,
0xFEEC3FFE, 0xFEF83FFE,
0xFF053FFE, 0xFF113FFE,
0xFF1E3FFE, 0xFF2A3FFF, /* 8 */
0xFF373FFF, 0xFF443FFF,
0xFF503FFF, 0xFF5D3FFF,
0xFF693FFF, 0xFF763FFF,
0xFF824000, 0xFF8F4000, /* 16 */
0xFF9B4000, 0xFFA84000,
0xFFB54000, 0xFFC14000,
0xFFCE4000, 0xFFDA4000,
0xFFE74000, 0xFFF34000, /* 24 */
0x00004000, 0x000D4000,
0x00194000, 0x00264000,
0x00324000, 0x003F4000,
0x004B4000, 0x00584000, /* 32 */
0x00654000, 0x00714000,
0x007E4000, 0x008A3FFF,
0x00973FFF, 0x00A33FFF,
0x00B03FFF, 0x00BC3FFF, /* 40 */
0x00C93FFF, 0x00D63FFF,
0x00E23FFE, 0x00EF3FFE,
0x00FB3FFE, 0x01083FFE,
0x01143FFE, 0x01213FFD, /* 48 */
0x012E3FFD, 0x013A3FFD,
0x01473FFD,
};
const u32 b43_tab_retard[] = {
0xDB93CB87, 0xD666CF64, /* 0 */
0xD1FDD358, 0xCDA6D826,
0xCA38DD9F, 0xC729E2B4,
0xC469E88E, 0xC26AEE2B,
0xC0DEF46C, 0xC073FA62, /* 8 */
0xC01D00D5, 0xC0760743,
0xC1560D1E, 0xC2E51369,
0xC4ED18FF, 0xC7AC1ED7,
0xCB2823B2, 0xCEFA28D9, /* 16 */
0xD2F62D3F, 0xD7BB3197,
0xDCE53568, 0xE1FE3875,
0xE7D13B35, 0xED663D35,
0xF39B3EC4, 0xF98E3FA7, /* 24 */
0x00004000, 0x06723FA7,
0x0C653EC4, 0x129A3D35,
0x182F3B35, 0x1E023875,
0x231B3568, 0x28453197, /* 32 */
0x2D0A2D3F, 0x310628D9,
0x34D823B2, 0x38541ED7,
0x3B1318FF, 0x3D1B1369,
0x3EAA0D1E, 0x3F8A0743, /* 40 */
0x3FE300D5, 0x3F8DFA62,
0x3F22F46C, 0x3D96EE2B,
0x3B97E88E, 0x38D7E2B4,
0x35C8DD9F, 0x325AD826, /* 48 */
0x2E03D358, 0x299ACF64,
0x246DCB87,
};
const u16 b43_tab_finefreqa[] = {
0x0082, 0x0082, 0x0102, 0x0182, /* 0 */
0x0202, 0x0282, 0x0302, 0x0382,
0x0402, 0x0482, 0x0502, 0x0582,
0x05E2, 0x0662, 0x06E2, 0x0762,
0x07E2, 0x0842, 0x08C2, 0x0942, /* 16 */
0x09C2, 0x0A22, 0x0AA2, 0x0B02,
0x0B82, 0x0BE2, 0x0C62, 0x0CC2,
0x0D42, 0x0DA2, 0x0E02, 0x0E62,
0x0EE2, 0x0F42, 0x0FA2, 0x1002, /* 32 */
0x1062, 0x10C2, 0x1122, 0x1182,
0x11E2, 0x1242, 0x12A2, 0x12E2,
0x1342, 0x13A2, 0x1402, 0x1442,
0x14A2, 0x14E2, 0x1542, 0x1582, /* 48 */
0x15E2, 0x1622, 0x1662, 0x16C1,
0x1701, 0x1741, 0x1781, 0x17E1,
0x1821, 0x1861, 0x18A1, 0x18E1,
0x1921, 0x1961, 0x19A1, 0x19E1, /* 64 */
0x1A21, 0x1A61, 0x1AA1, 0x1AC1,
0x1B01, 0x1B41, 0x1B81, 0x1BA1,
0x1BE1, 0x1C21, 0x1C41, 0x1C81,
0x1CA1, 0x1CE1, 0x1D01, 0x1D41, /* 80 */
0x1D61, 0x1DA1, 0x1DC1, 0x1E01,
0x1E21, 0x1E61, 0x1E81, 0x1EA1,
0x1EE1, 0x1F01, 0x1F21, 0x1F41,
0x1F81, 0x1FA1, 0x1FC1, 0x1FE1, /* 96 */
0x2001, 0x2041, 0x2061, 0x2081,
0x20A1, 0x20C1, 0x20E1, 0x2101,
0x2121, 0x2141, 0x2161, 0x2181,
0x21A1, 0x21C1, 0x21E1, 0x2201, /* 112 */
0x2221, 0x2241, 0x2261, 0x2281,
0x22A1, 0x22C1, 0x22C1, 0x22E1,
0x2301, 0x2321, 0x2341, 0x2361,
0x2361, 0x2381, 0x23A1, 0x23C1, /* 128 */
0x23E1, 0x23E1, 0x2401, 0x2421,
0x2441, 0x2441, 0x2461, 0x2481,
0x2481, 0x24A1, 0x24C1, 0x24C1,
0x24E1, 0x2501, 0x2501, 0x2521, /* 144 */
0x2541, 0x2541, 0x2561, 0x2561,
0x2581, 0x25A1, 0x25A1, 0x25C1,
0x25C1, 0x25E1, 0x2601, 0x2601,
0x2621, 0x2621, 0x2641, 0x2641, /* 160 */
0x2661, 0x2661, 0x2681, 0x2681,
0x26A1, 0x26A1, 0x26C1, 0x26C1,
0x26E1, 0x26E1, 0x2701, 0x2701,
0x2721, 0x2721, 0x2740, 0x2740, /* 176 */
0x2760, 0x2760, 0x2780, 0x2780,
0x2780, 0x27A0, 0x27A0, 0x27C0,
0x27C0, 0x27E0, 0x27E0, 0x27E0,
0x2800, 0x2800, 0x2820, 0x2820, /* 192 */
0x2820, 0x2840, 0x2840, 0x2840,
0x2860, 0x2860, 0x2880, 0x2880,
0x2880, 0x28A0, 0x28A0, 0x28A0,
0x28C0, 0x28C0, 0x28C0, 0x28E0, /* 208 */
0x28E0, 0x28E0, 0x2900, 0x2900,
0x2900, 0x2920, 0x2920, 0x2920,
0x2940, 0x2940, 0x2940, 0x2960,
0x2960, 0x2960, 0x2960, 0x2980, /* 224 */
0x2980, 0x2980, 0x29A0, 0x29A0,
0x29A0, 0x29A0, 0x29C0, 0x29C0,
0x29C0, 0x29E0, 0x29E0, 0x29E0,
0x29E0, 0x2A00, 0x2A00, 0x2A00, /* 240 */
0x2A00, 0x2A20, 0x2A20, 0x2A20,
0x2A20, 0x2A40, 0x2A40, 0x2A40,
0x2A40, 0x2A60, 0x2A60, 0x2A60,
};
const u16 b43_tab_finefreqg[] = {
0x0089, 0x02E9, 0x0409, 0x04E9, /* 0 */
0x05A9, 0x0669, 0x0709, 0x0789,
0x0829, 0x08A9, 0x0929, 0x0989,
0x0A09, 0x0A69, 0x0AC9, 0x0B29,
0x0BA9, 0x0BE9, 0x0C49, 0x0CA9, /* 16 */
0x0D09, 0x0D69, 0x0DA9, 0x0E09,
0x0E69, 0x0EA9, 0x0F09, 0x0F49,
0x0FA9, 0x0FE9, 0x1029, 0x1089,
0x10C9, 0x1109, 0x1169, 0x11A9, /* 32 */
0x11E9, 0x1229, 0x1289, 0x12C9,
0x1309, 0x1349, 0x1389, 0x13C9,
0x1409, 0x1449, 0x14A9, 0x14E9,
0x1529, 0x1569, 0x15A9, 0x15E9, /* 48 */
0x1629, 0x1669, 0x16A9, 0x16E8,
0x1728, 0x1768, 0x17A8, 0x17E8,
0x1828, 0x1868, 0x18A8, 0x18E8,
0x1928, 0x1968, 0x19A8, 0x19E8, /* 64 */
0x1A28, 0x1A68, 0x1AA8, 0x1AE8,
0x1B28, 0x1B68, 0x1BA8, 0x1BE8,
0x1C28, 0x1C68, 0x1CA8, 0x1CE8,
0x1D28, 0x1D68, 0x1DC8, 0x1E08, /* 80 */
0x1E48, 0x1E88, 0x1EC8, 0x1F08,
0x1F48, 0x1F88, 0x1FE8, 0x2028,
0x2068, 0x20A8, 0x2108, 0x2148,
0x2188, 0x21C8, 0x2228, 0x2268, /* 96 */
0x22C8, 0x2308, 0x2348, 0x23A8,
0x23E8, 0x2448, 0x24A8, 0x24E8,
0x2548, 0x25A8, 0x2608, 0x2668,
0x26C8, 0x2728, 0x2787, 0x27E7, /* 112 */
0x2847, 0x28C7, 0x2947, 0x29A7,
0x2A27, 0x2AC7, 0x2B47, 0x2BE7,
0x2CA7, 0x2D67, 0x2E47, 0x2F67,
0x3247, 0x3526, 0x3646, 0x3726, /* 128 */
0x3806, 0x38A6, 0x3946, 0x39E6,
0x3A66, 0x3AE6, 0x3B66, 0x3BC6,
0x3C45, 0x3CA5, 0x3D05, 0x3D85,
0x3DE5, 0x3E45, 0x3EA5, 0x3EE5, /* 144 */
0x3F45, 0x3FA5, 0x4005, 0x4045,
0x40A5, 0x40E5, 0x4145, 0x4185,
0x41E5, 0x4225, 0x4265, 0x42C5,
0x4305, 0x4345, 0x43A5, 0x43E5, /* 160 */
0x4424, 0x4464, 0x44C4, 0x4504,
0x4544, 0x4584, 0x45C4, 0x4604,
0x4644, 0x46A4, 0x46E4, 0x4724,
0x4764, 0x47A4, 0x47E4, 0x4824, /* 176 */
0x4864, 0x48A4, 0x48E4, 0x4924,
0x4964, 0x49A4, 0x49E4, 0x4A24,
0x4A64, 0x4AA4, 0x4AE4, 0x4B23,
0x4B63, 0x4BA3, 0x4BE3, 0x4C23, /* 192 */
0x4C63, 0x4CA3, 0x4CE3, 0x4D23,
0x4D63, 0x4DA3, 0x4DE3, 0x4E23,
0x4E63, 0x4EA3, 0x4EE3, 0x4F23,
0x4F63, 0x4FC3, 0x5003, 0x5043, /* 208 */
0x5083, 0x50C3, 0x5103, 0x5143,
0x5183, 0x51E2, 0x5222, 0x5262,
0x52A2, 0x52E2, 0x5342, 0x5382,
0x53C2, 0x5402, 0x5462, 0x54A2, /* 224 */
0x5502, 0x5542, 0x55A2, 0x55E2,
0x5642, 0x5682, 0x56E2, 0x5722,
0x5782, 0x57E1, 0x5841, 0x58A1,
0x5901, 0x5961, 0x59C1, 0x5A21, /* 240 */
0x5AA1, 0x5B01, 0x5B81, 0x5BE1,
0x5C61, 0x5D01, 0x5D80, 0x5E20,
0x5EE0, 0x5FA0, 0x6080, 0x61C0,
};
const u16 b43_tab_noisea2[] = {
0x0001, 0x0001, 0x0001, 0xFFFE,
0xFFFE, 0x3FFF, 0x1000, 0x0393,
};
const u16 b43_tab_noisea3[] = {
0x5E5E, 0x5E5E, 0x5E5E, 0x3F48,
0x4C4C, 0x4C4C, 0x4C4C, 0x2D36,
};
const u16 b43_tab_noiseg1[] = {
0x013C, 0x01F5, 0x031A, 0x0631,
0x0001, 0x0001, 0x0001, 0x0001,
};
const u16 b43_tab_noiseg2[] = {
0x5484, 0x3C40, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000,
};
const u16 b43_tab_noisescalea2[] = {
0x6767, 0x6767, 0x6767, 0x6767, /* 0 */
0x6767, 0x6767, 0x6767, 0x6767,
0x6767, 0x6767, 0x6767, 0x6767,
0x6767, 0x6700, 0x6767, 0x6767,
0x6767, 0x6767, 0x6767, 0x6767, /* 16 */
0x6767, 0x6767, 0x6767, 0x6767,
0x6767, 0x6767, 0x0067,
};
const u16 b43_tab_noisescalea3[] = {
0x2323, 0x2323, 0x2323, 0x2323, /* 0 */
0x2323, 0x2323, 0x2323, 0x2323,
0x2323, 0x2323, 0x2323, 0x2323,
0x2323, 0x2300, 0x2323, 0x2323,
0x2323, 0x2323, 0x2323, 0x2323, /* 16 */
0x2323, 0x2323, 0x2323, 0x2323,
0x2323, 0x2323, 0x0023,
};
const u16 b43_tab_noisescaleg1[] = {
0x6C77, 0x5162, 0x3B40, 0x3335, /* 0 */
0x2F2D, 0x2A2A, 0x2527, 0x1F21,
0x1A1D, 0x1719, 0x1616, 0x1414,
0x1414, 0x1400, 0x1414, 0x1614,
0x1716, 0x1A19, 0x1F1D, 0x2521, /* 16 */
0x2A27, 0x2F2A, 0x332D, 0x3B35,
0x5140, 0x6C62, 0x0077,
};
const u16 b43_tab_noisescaleg2[] = {
0xD8DD, 0xCBD4, 0xBCC0, 0xB6B7, /* 0 */
0xB2B0, 0xADAD, 0xA7A9, 0x9FA1,
0x969B, 0x9195, 0x8F8F, 0x8A8A,
0x8A8A, 0x8A00, 0x8A8A, 0x8F8A,
0x918F, 0x9695, 0x9F9B, 0xA7A1, /* 16 */
0xADA9, 0xB2AD, 0xB6B0, 0xBCB7,
0xCBC0, 0xD8D4, 0x00DD,
};
const u16 b43_tab_noisescaleg3[] = {
0xA4A4, 0xA4A4, 0xA4A4, 0xA4A4, /* 0 */
0xA4A4, 0xA4A4, 0xA4A4, 0xA4A4,
0xA4A4, 0xA4A4, 0xA4A4, 0xA4A4,
0xA4A4, 0xA400, 0xA4A4, 0xA4A4,
0xA4A4, 0xA4A4, 0xA4A4, 0xA4A4, /* 16 */
0xA4A4, 0xA4A4, 0xA4A4, 0xA4A4,
0xA4A4, 0xA4A4, 0x00A4,
};
const u16 b43_tab_sigmasqr1[] = {
0x007A, 0x0075, 0x0071, 0x006C, /* 0 */
0x0067, 0x0063, 0x005E, 0x0059,
0x0054, 0x0050, 0x004B, 0x0046,
0x0042, 0x003D, 0x003D, 0x003D,
0x003D, 0x003D, 0x003D, 0x003D, /* 16 */
0x003D, 0x003D, 0x003D, 0x003D,
0x003D, 0x003D, 0x0000, 0x003D,
0x003D, 0x003D, 0x003D, 0x003D,
0x003D, 0x003D, 0x003D, 0x003D, /* 32 */
0x003D, 0x003D, 0x003D, 0x003D,
0x0042, 0x0046, 0x004B, 0x0050,
0x0054, 0x0059, 0x005E, 0x0063,
0x0067, 0x006C, 0x0071, 0x0075, /* 48 */
0x007A,
};
const u16 b43_tab_sigmasqr2[] = {
0x00DE, 0x00DC, 0x00DA, 0x00D8, /* 0 */
0x00D6, 0x00D4, 0x00D2, 0x00CF,
0x00CD, 0x00CA, 0x00C7, 0x00C4,
0x00C1, 0x00BE, 0x00BE, 0x00BE,
0x00BE, 0x00BE, 0x00BE, 0x00BE, /* 16 */
0x00BE, 0x00BE, 0x00BE, 0x00BE,
0x00BE, 0x00BE, 0x0000, 0x00BE,
0x00BE, 0x00BE, 0x00BE, 0x00BE,
0x00BE, 0x00BE, 0x00BE, 0x00BE, /* 32 */
0x00BE, 0x00BE, 0x00BE, 0x00BE,
0x00C1, 0x00C4, 0x00C7, 0x00CA,
0x00CD, 0x00CF, 0x00D2, 0x00D4,
0x00D6, 0x00D8, 0x00DA, 0x00DC, /* 48 */
0x00DE,
};
const u16 b43_tab_rssiagc1[] = {
0xFFF8, 0xFFF8, 0xFFF8, 0xFFF8, /* 0 */
0xFFF8, 0xFFF9, 0xFFFC, 0xFFFE,
0xFFF8, 0xFFF8, 0xFFF8, 0xFFF8,
0xFFF8, 0xFFF8, 0xFFF8, 0xFFF8,
};
const u16 b43_tab_rssiagc2[] = {
0x0820, 0x0820, 0x0920, 0x0C38, /* 0 */
0x0820, 0x0820, 0x0820, 0x0820,
0x0820, 0x0820, 0x0920, 0x0A38,
0x0820, 0x0820, 0x0820, 0x0820,
0x0820, 0x0820, 0x0920, 0x0A38, /* 16 */
0x0820, 0x0820, 0x0820, 0x0820,
0x0820, 0x0820, 0x0920, 0x0A38,
0x0820, 0x0820, 0x0820, 0x0820,
0x0820, 0x0820, 0x0920, 0x0A38, /* 32 */
0x0820, 0x0820, 0x0820, 0x0820,
0x0820, 0x0820, 0x0920, 0x0A38,
0x0820, 0x0820, 0x0820, 0x0820,
};
static inline void assert_sizes(void)
{
BUILD_BUG_ON(B43_TAB_ROTOR_SIZE != ARRAY_SIZE(b43_tab_rotor));
BUILD_BUG_ON(B43_TAB_RETARD_SIZE != ARRAY_SIZE(b43_tab_retard));
BUILD_BUG_ON(B43_TAB_FINEFREQA_SIZE != ARRAY_SIZE(b43_tab_finefreqa));
BUILD_BUG_ON(B43_TAB_FINEFREQG_SIZE != ARRAY_SIZE(b43_tab_finefreqg));
BUILD_BUG_ON(B43_TAB_NOISEA2_SIZE != ARRAY_SIZE(b43_tab_noisea2));
BUILD_BUG_ON(B43_TAB_NOISEA3_SIZE != ARRAY_SIZE(b43_tab_noisea3));
BUILD_BUG_ON(B43_TAB_NOISEG1_SIZE != ARRAY_SIZE(b43_tab_noiseg1));
BUILD_BUG_ON(B43_TAB_NOISEG2_SIZE != ARRAY_SIZE(b43_tab_noiseg2));
BUILD_BUG_ON(B43_TAB_NOISESCALE_SIZE !=
ARRAY_SIZE(b43_tab_noisescalea2));
BUILD_BUG_ON(B43_TAB_NOISESCALE_SIZE !=
ARRAY_SIZE(b43_tab_noisescalea3));
BUILD_BUG_ON(B43_TAB_NOISESCALE_SIZE !=
ARRAY_SIZE(b43_tab_noisescaleg1));
BUILD_BUG_ON(B43_TAB_NOISESCALE_SIZE !=
ARRAY_SIZE(b43_tab_noisescaleg2));
BUILD_BUG_ON(B43_TAB_NOISESCALE_SIZE !=
ARRAY_SIZE(b43_tab_noisescaleg3));
BUILD_BUG_ON(B43_TAB_SIGMASQR_SIZE != ARRAY_SIZE(b43_tab_sigmasqr1));
BUILD_BUG_ON(B43_TAB_SIGMASQR_SIZE != ARRAY_SIZE(b43_tab_sigmasqr2));
BUILD_BUG_ON(B43_TAB_RSSIAGC1_SIZE != ARRAY_SIZE(b43_tab_rssiagc1));
BUILD_BUG_ON(B43_TAB_RSSIAGC2_SIZE != ARRAY_SIZE(b43_tab_rssiagc2));
}
u16 b43_ofdmtab_read16(struct b43_wldev *dev, u16 table, u16 offset)
{
struct b43_phy_g *gphy = dev->phy.g;
u16 addr;
addr = table + offset;
if ((gphy->ofdmtab_addr_direction != B43_OFDMTAB_DIRECTION_READ) ||
(addr - 1 != gphy->ofdmtab_addr)) {
/* The hardware has a different address in memory. Update it. */
b43_phy_write(dev, B43_PHY_OTABLECTL, addr);
gphy->ofdmtab_addr_direction = B43_OFDMTAB_DIRECTION_READ;
}
gphy->ofdmtab_addr = addr;
return b43_phy_read(dev, B43_PHY_OTABLEI);
/* Some compiletime assertions... */
assert_sizes();
}
void b43_ofdmtab_write16(struct b43_wldev *dev, u16 table,
u16 offset, u16 value)
{
struct b43_phy_g *gphy = dev->phy.g;
u16 addr;
addr = table + offset;
if ((gphy->ofdmtab_addr_direction != B43_OFDMTAB_DIRECTION_WRITE) ||
(addr - 1 != gphy->ofdmtab_addr)) {
/* The hardware has a different address in memory. Update it. */
b43_phy_write(dev, B43_PHY_OTABLECTL, addr);
gphy->ofdmtab_addr_direction = B43_OFDMTAB_DIRECTION_WRITE;
}
gphy->ofdmtab_addr = addr;
b43_phy_write(dev, B43_PHY_OTABLEI, value);
}
u32 b43_ofdmtab_read32(struct b43_wldev *dev, u16 table, u16 offset)
{
struct b43_phy_g *gphy = dev->phy.g;
u32 ret;
u16 addr;
addr = table + offset;
if ((gphy->ofdmtab_addr_direction != B43_OFDMTAB_DIRECTION_READ) ||
(addr - 1 != gphy->ofdmtab_addr)) {
/* The hardware has a different address in memory. Update it. */
b43_phy_write(dev, B43_PHY_OTABLECTL, addr);
gphy->ofdmtab_addr_direction = B43_OFDMTAB_DIRECTION_READ;
}
gphy->ofdmtab_addr = addr;
ret = b43_phy_read(dev, B43_PHY_OTABLEQ);
ret <<= 16;
ret |= b43_phy_read(dev, B43_PHY_OTABLEI);
return ret;
}
void b43_ofdmtab_write32(struct b43_wldev *dev, u16 table,
u16 offset, u32 value)
{
struct b43_phy_g *gphy = dev->phy.g;
u16 addr;
addr = table + offset;
if ((gphy->ofdmtab_addr_direction != B43_OFDMTAB_DIRECTION_WRITE) ||
(addr - 1 != gphy->ofdmtab_addr)) {
/* The hardware has a different address in memory. Update it. */
b43_phy_write(dev, B43_PHY_OTABLECTL, addr);
gphy->ofdmtab_addr_direction = B43_OFDMTAB_DIRECTION_WRITE;
}
gphy->ofdmtab_addr = addr;
b43_phy_write(dev, B43_PHY_OTABLEI, value);
b43_phy_write(dev, B43_PHY_OTABLEQ, (value >> 16));
}
u16 b43_gtab_read(struct b43_wldev *dev, u16 table, u16 offset)
{
b43_phy_write(dev, B43_PHY_GTABCTL, table + offset);
return b43_phy_read(dev, B43_PHY_GTABDATA);
}
void b43_gtab_write(struct b43_wldev *dev, u16 table, u16 offset, u16 value)
{
b43_phy_write(dev, B43_PHY_GTABCTL, table + offset);
b43_phy_write(dev, B43_PHY_GTABDATA, value);
}
| gpl-2.0 |
quanghieu/linux-DFI | drivers/staging/vt6656/main_usb.c | 132 | 25351 | /*
* Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* File: main_usb.c
*
* Purpose: driver entry for initial, open, close, tx and rx.
*
* Author: Lyndon Chen
*
* Date: Dec 8, 2005
*
* Functions:
*
* vt6656_probe - module initial (insmod) driver entry
* vnt_free_tx_bufs - free tx buffer function
* vnt_init_registers- initial MAC & BBP & RF internal registers.
*
* Revision History:
*/
#undef __NO_VERSION__
#include <linux/etherdevice.h>
#include <linux/file.h>
#include "device.h"
#include "card.h"
#include "baseband.h"
#include "mac.h"
#include "power.h"
#include "wcmd.h"
#include "rxtx.h"
#include "dpc.h"
#include "rf.h"
#include "firmware.h"
#include "usbpipe.h"
#include "channel.h"
#include "int.h"
/*
* define module options
*/
/* version information */
#define DRIVER_AUTHOR \
"VIA Networking Technologies, Inc., <lyndonchen@vntek.com.tw>"
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION(DEVICE_FULL_DRV_NAM);
#define RX_DESC_DEF0 64
static int vnt_rx_buffers = RX_DESC_DEF0;
module_param_named(rx_buffers, vnt_rx_buffers, int, 0644);
MODULE_PARM_DESC(rx_buffers, "Number of receive usb rx buffers");
#define TX_DESC_DEF0 64
static int vnt_tx_buffers = TX_DESC_DEF0;
module_param_named(tx_buffers, vnt_tx_buffers, int, 0644);
MODULE_PARM_DESC(tx_buffers, "Number of receive usb tx buffers");
#define RTS_THRESH_DEF 2347
#define FRAG_THRESH_DEF 2346
#define SHORT_RETRY_DEF 8
#define LONG_RETRY_DEF 4
/* BasebandType[] baseband type selected
0: indicate 802.11a type
1: indicate 802.11b type
2: indicate 802.11g type
*/
#define BBP_TYPE_DEF 2
/*
* Static vars definitions
*/
static struct usb_device_id vt6656_table[] = {
{USB_DEVICE(VNT_USB_VENDOR_ID, VNT_USB_PRODUCT_ID)},
{}
};
static void vnt_set_options(struct vnt_private *priv)
{
/* Set number of TX buffers */
if (vnt_tx_buffers < CB_MIN_TX_DESC || vnt_tx_buffers > CB_MAX_TX_DESC)
priv->num_tx_context = TX_DESC_DEF0;
else
priv->num_tx_context = vnt_tx_buffers;
/* Set number of RX buffers */
if (vnt_rx_buffers < CB_MIN_RX_DESC || vnt_rx_buffers > CB_MAX_RX_DESC)
priv->num_rcb = RX_DESC_DEF0;
else
priv->num_rcb = vnt_rx_buffers;
priv->short_retry_limit = SHORT_RETRY_DEF;
priv->long_retry_limit = LONG_RETRY_DEF;
priv->op_mode = NL80211_IFTYPE_UNSPECIFIED;
priv->bb_type = BBP_TYPE_DEF;
priv->packet_type = priv->bb_type;
priv->auto_fb_ctrl = AUTO_FB_0;
priv->preamble_type = 0;
priv->exist_sw_net_addr = false;
}
/*
* initialization of MAC & BBP registers
*/
static int vnt_init_registers(struct vnt_private *priv)
{
struct vnt_cmd_card_init *init_cmd = &priv->init_command;
struct vnt_rsp_card_init *init_rsp = &priv->init_response;
u8 antenna;
int ii;
int status = STATUS_SUCCESS;
u8 tmp;
u8 calib_tx_iq = 0, calib_tx_dc = 0, calib_rx_iq = 0;
dev_dbg(&priv->usb->dev, "---->INIbInitAdapter. [%d][%d]\n",
DEVICE_INIT_COLD, priv->packet_type);
if (!vnt_check_firmware_version(priv)) {
if (vnt_download_firmware(priv) == true) {
if (vnt_firmware_branch_to_sram(priv) == false) {
dev_dbg(&priv->usb->dev,
" vnt_firmware_branch_to_sram fail\n");
return false;
}
} else {
dev_dbg(&priv->usb->dev, "FIRMWAREbDownload fail\n");
return false;
}
}
if (!vnt_vt3184_init(priv)) {
dev_dbg(&priv->usb->dev, "vnt_vt3184_init fail\n");
return false;
}
init_cmd->init_class = DEVICE_INIT_COLD;
init_cmd->exist_sw_net_addr = priv->exist_sw_net_addr;
for (ii = 0; ii < 6; ii++)
init_cmd->sw_net_addr[ii] = priv->current_net_addr[ii];
init_cmd->short_retry_limit = priv->short_retry_limit;
init_cmd->long_retry_limit = priv->long_retry_limit;
/* issue card_init command to device */
status = vnt_control_out(priv,
MESSAGE_TYPE_CARDINIT, 0, 0,
sizeof(struct vnt_cmd_card_init), (u8 *)init_cmd);
if (status != STATUS_SUCCESS) {
dev_dbg(&priv->usb->dev, "Issue Card init fail\n");
return false;
}
status = vnt_control_in(priv, MESSAGE_TYPE_INIT_RSP, 0, 0,
sizeof(struct vnt_rsp_card_init), (u8 *)init_rsp);
if (status != STATUS_SUCCESS) {
dev_dbg(&priv->usb->dev,
"Cardinit request in status fail!\n");
return false;
}
/* local ID for AES functions */
status = vnt_control_in(priv, MESSAGE_TYPE_READ,
MAC_REG_LOCALID, MESSAGE_REQUEST_MACREG, 1,
&priv->local_id);
if (status != STATUS_SUCCESS)
return false;
/* do MACbSoftwareReset in MACvInitialize */
priv->top_ofdm_basic_rate = RATE_24M;
priv->top_cck_basic_rate = RATE_1M;
/* target to IF pin while programming to RF chip */
priv->power = 0xFF;
priv->cck_pwr = priv->eeprom[EEP_OFS_PWR_CCK];
priv->ofdm_pwr_g = priv->eeprom[EEP_OFS_PWR_OFDMG];
/* load power table */
for (ii = 0; ii < 14; ii++) {
priv->cck_pwr_tbl[ii] =
priv->eeprom[ii + EEP_OFS_CCK_PWR_TBL];
if (priv->cck_pwr_tbl[ii] == 0)
priv->cck_pwr_tbl[ii] = priv->cck_pwr;
priv->ofdm_pwr_tbl[ii] =
priv->eeprom[ii + EEP_OFS_OFDM_PWR_TBL];
if (priv->ofdm_pwr_tbl[ii] == 0)
priv->ofdm_pwr_tbl[ii] = priv->ofdm_pwr_g;
}
/*
* original zonetype is USA, but custom zonetype is Europe,
* then need to recover 12, 13, 14 channels with 11 channel
*/
for (ii = 11; ii < 14; ii++) {
priv->cck_pwr_tbl[ii] = priv->cck_pwr_tbl[10];
priv->ofdm_pwr_tbl[ii] = priv->ofdm_pwr_tbl[10];
}
priv->ofdm_pwr_a = 0x34; /* same as RFbMA2829SelectChannel */
/* load OFDM A power table */
for (ii = 0; ii < CB_MAX_CHANNEL_5G; ii++) {
priv->ofdm_a_pwr_tbl[ii] =
priv->eeprom[ii + EEP_OFS_OFDMA_PWR_TBL];
if (priv->ofdm_a_pwr_tbl[ii] == 0)
priv->ofdm_a_pwr_tbl[ii] = priv->ofdm_pwr_a;
}
antenna = priv->eeprom[EEP_OFS_ANTENNA];
if (antenna & EEP_ANTINV)
priv->tx_rx_ant_inv = true;
else
priv->tx_rx_ant_inv = false;
antenna &= (EEP_ANTENNA_AUX | EEP_ANTENNA_MAIN);
if (antenna == 0) /* if not set default is both */
antenna = (EEP_ANTENNA_AUX | EEP_ANTENNA_MAIN);
if (antenna == (EEP_ANTENNA_AUX | EEP_ANTENNA_MAIN)) {
priv->tx_antenna_mode = ANT_B;
priv->rx_antenna_sel = 1;
if (priv->tx_rx_ant_inv == true)
priv->rx_antenna_mode = ANT_A;
else
priv->rx_antenna_mode = ANT_B;
} else {
priv->rx_antenna_sel = 0;
if (antenna & EEP_ANTENNA_AUX) {
priv->tx_antenna_mode = ANT_A;
if (priv->tx_rx_ant_inv == true)
priv->rx_antenna_mode = ANT_B;
else
priv->rx_antenna_mode = ANT_A;
} else {
priv->tx_antenna_mode = ANT_B;
if (priv->tx_rx_ant_inv == true)
priv->rx_antenna_mode = ANT_A;
else
priv->rx_antenna_mode = ANT_B;
}
}
/* Set initial antenna mode */
vnt_set_antenna_mode(priv, priv->rx_antenna_mode);
/* get Auto Fall Back type */
priv->auto_fb_ctrl = AUTO_FB_0;
/* default Auto Mode */
priv->bb_type = BB_TYPE_11G;
/* get RFType */
priv->rf_type = init_rsp->rf_type;
/* load vt3266 calibration parameters in EEPROM */
if (priv->rf_type == RF_VT3226D0) {
if ((priv->eeprom[EEP_OFS_MAJOR_VER] == 0x1) &&
(priv->eeprom[EEP_OFS_MINOR_VER] >= 0x4)) {
calib_tx_iq = priv->eeprom[EEP_OFS_CALIB_TX_IQ];
calib_tx_dc = priv->eeprom[EEP_OFS_CALIB_TX_DC];
calib_rx_iq = priv->eeprom[EEP_OFS_CALIB_RX_IQ];
if (calib_tx_iq || calib_tx_dc || calib_rx_iq) {
/* CR255, enable TX/RX IQ and
DC compensation mode */
vnt_control_out_u8(priv,
MESSAGE_REQUEST_BBREG,
0xff,
0x03);
/* CR251, TX I/Q Imbalance Calibration */
vnt_control_out_u8(priv,
MESSAGE_REQUEST_BBREG,
0xfb,
calib_tx_iq);
/* CR252, TX DC-Offset Calibration */
vnt_control_out_u8(priv,
MESSAGE_REQUEST_BBREG,
0xfC,
calib_tx_dc);
/* CR253, RX I/Q Imbalance Calibration */
vnt_control_out_u8(priv,
MESSAGE_REQUEST_BBREG,
0xfd,
calib_rx_iq);
} else {
/* CR255, turn off
BB Calibration compensation */
vnt_control_out_u8(priv,
MESSAGE_REQUEST_BBREG,
0xff,
0x0);
}
}
}
/* get permanent network address */
memcpy(priv->permanent_net_addr, init_rsp->net_addr, 6);
ether_addr_copy(priv->current_net_addr, priv->permanent_net_addr);
/* if exist SW network address, use it */
dev_dbg(&priv->usb->dev, "Network address = %pM\n",
priv->current_net_addr);
/*
* set BB and packet type at the same time
* set Short Slot Time, xIFS, and RSPINF
*/
if (priv->bb_type == BB_TYPE_11A)
priv->short_slot_time = true;
else
priv->short_slot_time = false;
vnt_set_short_slot_time(priv);
priv->radio_ctl = priv->eeprom[EEP_OFS_RADIOCTL];
if ((priv->radio_ctl & EEP_RADIOCTL_ENABLE) != 0) {
status = vnt_control_in(priv, MESSAGE_TYPE_READ,
MAC_REG_GPIOCTL1, MESSAGE_REQUEST_MACREG, 1, &tmp);
if (status != STATUS_SUCCESS)
return false;
if ((tmp & GPIO3_DATA) == 0)
vnt_mac_reg_bits_on(priv, MAC_REG_GPIOCTL1,
GPIO3_INTMD);
else
vnt_mac_reg_bits_off(priv, MAC_REG_GPIOCTL1,
GPIO3_INTMD);
}
vnt_mac_set_led(priv, LEDSTS_TMLEN, 0x38);
vnt_mac_set_led(priv, LEDSTS_STS, LEDSTS_SLOW);
vnt_mac_reg_bits_on(priv, MAC_REG_GPIOCTL0, 0x01);
vnt_radio_power_on(priv);
dev_dbg(&priv->usb->dev, "<----INIbInitAdapter Exit\n");
return true;
}
static void vnt_free_tx_bufs(struct vnt_private *priv)
{
struct vnt_usb_send_context *tx_context;
int ii;
for (ii = 0; ii < priv->num_tx_context; ii++) {
tx_context = priv->tx_context[ii];
/* deallocate URBs */
if (tx_context->urb) {
usb_kill_urb(tx_context->urb);
usb_free_urb(tx_context->urb);
}
kfree(tx_context);
}
}
static void vnt_free_rx_bufs(struct vnt_private *priv)
{
struct vnt_rcb *rcb;
int ii;
for (ii = 0; ii < priv->num_rcb; ii++) {
rcb = priv->rcb[ii];
if (!rcb)
continue;
/* deallocate URBs */
if (rcb->urb) {
usb_kill_urb(rcb->urb);
usb_free_urb(rcb->urb);
}
/* deallocate skb */
if (rcb->skb)
dev_kfree_skb(rcb->skb);
kfree(rcb);
}
}
static void usb_device_reset(struct vnt_private *priv)
{
int status;
status = usb_reset_device(priv->usb);
if (status)
dev_warn(&priv->usb->dev,
"usb_device_reset fail status=%d\n", status);
}
static void vnt_free_int_bufs(struct vnt_private *priv)
{
kfree(priv->int_buf.data_buf);
}
static bool vnt_alloc_bufs(struct vnt_private *priv)
{
struct vnt_usb_send_context *tx_context;
struct vnt_rcb *rcb;
int ii;
for (ii = 0; ii < priv->num_tx_context; ii++) {
tx_context = kmalloc(sizeof(struct vnt_usb_send_context),
GFP_KERNEL);
if (tx_context == NULL)
goto free_tx;
priv->tx_context[ii] = tx_context;
tx_context->priv = priv;
tx_context->pkt_no = ii;
/* allocate URBs */
tx_context->urb = usb_alloc_urb(0, GFP_ATOMIC);
if (!tx_context->urb) {
dev_err(&priv->usb->dev, "alloc tx urb failed\n");
goto free_tx;
}
tx_context->in_use = false;
}
for (ii = 0; ii < priv->num_rcb; ii++) {
priv->rcb[ii] = kzalloc(sizeof(struct vnt_rcb), GFP_KERNEL);
if (!priv->rcb[ii]) {
dev_err(&priv->usb->dev,
"failed to allocate rcb no %d\n", ii);
goto free_rx_tx;
}
rcb = priv->rcb[ii];
rcb->priv = priv;
/* allocate URBs */
rcb->urb = usb_alloc_urb(0, GFP_ATOMIC);
if (rcb->urb == NULL) {
dev_err(&priv->usb->dev, "Failed to alloc rx urb\n");
goto free_rx_tx;
}
rcb->skb = dev_alloc_skb(priv->rx_buf_sz);
if (rcb->skb == NULL)
goto free_rx_tx;
rcb->in_use = false;
/* submit rx urb */
if (vnt_submit_rx_urb(priv, rcb))
goto free_rx_tx;
}
priv->interrupt_urb = usb_alloc_urb(0, GFP_ATOMIC);
if (priv->interrupt_urb == NULL) {
dev_err(&priv->usb->dev, "Failed to alloc int urb\n");
goto free_rx_tx;
}
priv->int_buf.data_buf = kmalloc(MAX_INTERRUPT_SIZE, GFP_KERNEL);
if (priv->int_buf.data_buf == NULL) {
usb_free_urb(priv->interrupt_urb);
goto free_rx_tx;
}
return true;
free_rx_tx:
vnt_free_rx_bufs(priv);
free_tx:
vnt_free_tx_bufs(priv);
return false;
}
static void vnt_tx_80211(struct ieee80211_hw *hw,
struct ieee80211_tx_control *control, struct sk_buff *skb)
{
struct vnt_private *priv = hw->priv;
if (vnt_tx_packet(priv, skb))
ieee80211_free_txskb(hw, skb);
}
static int vnt_start(struct ieee80211_hw *hw)
{
struct vnt_private *priv = hw->priv;
priv->rx_buf_sz = MAX_TOTAL_SIZE_WITH_ALL_HEADERS;
if (!vnt_alloc_bufs(priv)) {
dev_dbg(&priv->usb->dev, "vnt_alloc_bufs fail...\n");
return -ENOMEM;
}
clear_bit(DEVICE_FLAGS_DISCONNECTED, &priv->flags);
if (vnt_init_registers(priv) == false) {
dev_dbg(&priv->usb->dev, " init register fail\n");
goto free_all;
}
priv->int_interval = 1; /* bInterval is set to 1 */
vnt_int_start_interrupt(priv);
ieee80211_wake_queues(hw);
return 0;
free_all:
vnt_free_rx_bufs(priv);
vnt_free_tx_bufs(priv);
vnt_free_int_bufs(priv);
usb_kill_urb(priv->interrupt_urb);
usb_free_urb(priv->interrupt_urb);
return -ENOMEM;
}
static void vnt_stop(struct ieee80211_hw *hw)
{
struct vnt_private *priv = hw->priv;
int i;
if (!priv)
return;
for (i = 0; i < MAX_KEY_TABLE; i++)
vnt_mac_disable_keyentry(priv, i);
/* clear all keys */
priv->key_entry_inuse = 0;
if (!test_bit(DEVICE_FLAGS_UNPLUG, &priv->flags))
vnt_mac_shutdown(priv);
ieee80211_stop_queues(hw);
set_bit(DEVICE_FLAGS_DISCONNECTED, &priv->flags);
cancel_delayed_work_sync(&priv->run_command_work);
priv->cmd_running = false;
vnt_free_tx_bufs(priv);
vnt_free_rx_bufs(priv);
vnt_free_int_bufs(priv);
usb_kill_urb(priv->interrupt_urb);
usb_free_urb(priv->interrupt_urb);
}
static int vnt_add_interface(struct ieee80211_hw *hw, struct ieee80211_vif *vif)
{
struct vnt_private *priv = hw->priv;
priv->vif = vif;
switch (vif->type) {
case NL80211_IFTYPE_STATION:
break;
case NL80211_IFTYPE_ADHOC:
vnt_mac_reg_bits_off(priv, MAC_REG_RCR, RCR_UNICAST);
vnt_mac_reg_bits_on(priv, MAC_REG_HOSTCR, HOSTCR_ADHOC);
break;
case NL80211_IFTYPE_AP:
vnt_mac_reg_bits_off(priv, MAC_REG_RCR, RCR_UNICAST);
vnt_mac_reg_bits_on(priv, MAC_REG_HOSTCR, HOSTCR_AP);
break;
default:
return -EOPNOTSUPP;
}
priv->op_mode = vif->type;
vnt_set_bss_mode(priv);
/* LED blink on TX */
vnt_mac_set_led(priv, LEDSTS_STS, LEDSTS_INTER);
return 0;
}
static void vnt_remove_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct vnt_private *priv = hw->priv;
switch (vif->type) {
case NL80211_IFTYPE_STATION:
break;
case NL80211_IFTYPE_ADHOC:
vnt_mac_reg_bits_off(priv, MAC_REG_TCR, TCR_AUTOBCNTX);
vnt_mac_reg_bits_off(priv, MAC_REG_TFTCTL, TFTCTL_TSFCNTREN);
vnt_mac_reg_bits_off(priv, MAC_REG_HOSTCR, HOSTCR_ADHOC);
break;
case NL80211_IFTYPE_AP:
vnt_mac_reg_bits_off(priv, MAC_REG_TCR, TCR_AUTOBCNTX);
vnt_mac_reg_bits_off(priv, MAC_REG_TFTCTL, TFTCTL_TSFCNTREN);
vnt_mac_reg_bits_off(priv, MAC_REG_HOSTCR, HOSTCR_AP);
break;
default:
break;
}
vnt_radio_power_off(priv);
priv->op_mode = NL80211_IFTYPE_UNSPECIFIED;
/* LED slow blink */
vnt_mac_set_led(priv, LEDSTS_STS, LEDSTS_SLOW);
}
static int vnt_config(struct ieee80211_hw *hw, u32 changed)
{
struct vnt_private *priv = hw->priv;
struct ieee80211_conf *conf = &hw->conf;
u8 bb_type;
if (changed & IEEE80211_CONF_CHANGE_PS) {
if (conf->flags & IEEE80211_CONF_PS)
vnt_enable_power_saving(priv, conf->listen_interval);
else
vnt_disable_power_saving(priv);
}
if ((changed & IEEE80211_CONF_CHANGE_CHANNEL) ||
(conf->flags & IEEE80211_CONF_OFFCHANNEL)) {
vnt_set_channel(priv, conf->chandef.chan->hw_value);
if (conf->chandef.chan->band == IEEE80211_BAND_5GHZ)
bb_type = BB_TYPE_11A;
else
bb_type = BB_TYPE_11G;
if (priv->bb_type != bb_type) {
priv->bb_type = bb_type;
vnt_set_bss_mode(priv);
}
}
if (changed & IEEE80211_CONF_CHANGE_POWER) {
if (priv->bb_type == BB_TYPE_11B)
priv->current_rate = RATE_1M;
else
priv->current_rate = RATE_54M;
vnt_rf_setpower(priv, priv->current_rate,
conf->chandef.chan->hw_value);
}
return 0;
}
static void vnt_bss_info_changed(struct ieee80211_hw *hw,
struct ieee80211_vif *vif, struct ieee80211_bss_conf *conf,
u32 changed)
{
struct vnt_private *priv = hw->priv;
priv->current_aid = conf->aid;
if (changed & BSS_CHANGED_BSSID && conf->bssid)
vnt_mac_set_bssid_addr(priv, (u8 *)conf->bssid);
if (changed & BSS_CHANGED_BASIC_RATES) {
priv->basic_rates = conf->basic_rates;
vnt_update_top_rates(priv);
dev_dbg(&priv->usb->dev, "basic rates %x\n", conf->basic_rates);
}
if (changed & BSS_CHANGED_ERP_PREAMBLE) {
if (conf->use_short_preamble) {
vnt_mac_enable_barker_preamble_mode(priv);
priv->preamble_type = true;
} else {
vnt_mac_disable_barker_preamble_mode(priv);
priv->preamble_type = false;
}
}
if (changed & BSS_CHANGED_ERP_CTS_PROT) {
if (conf->use_cts_prot)
vnt_mac_enable_protect_mode(priv);
else
vnt_mac_disable_protect_mode(priv);
}
if (changed & BSS_CHANGED_ERP_SLOT) {
if (conf->use_short_slot)
priv->short_slot_time = true;
else
priv->short_slot_time = false;
vnt_set_short_slot_time(priv);
vnt_set_vga_gain_offset(priv, priv->bb_vga[0]);
vnt_update_pre_ed_threshold(priv, false);
}
if (changed & BSS_CHANGED_TXPOWER)
vnt_rf_setpower(priv, priv->current_rate,
conf->chandef.chan->hw_value);
if (changed & BSS_CHANGED_BEACON_ENABLED) {
dev_dbg(&priv->usb->dev,
"Beacon enable %d\n", conf->enable_beacon);
if (conf->enable_beacon) {
vnt_beacon_enable(priv, vif, conf);
vnt_mac_reg_bits_on(priv, MAC_REG_TCR, TCR_AUTOBCNTX);
} else {
vnt_mac_reg_bits_off(priv, MAC_REG_TCR, TCR_AUTOBCNTX);
}
}
if (changed & (BSS_CHANGED_ASSOC | BSS_CHANGED_BEACON_INFO) &&
priv->op_mode != NL80211_IFTYPE_AP) {
if (conf->assoc && conf->beacon_rate) {
vnt_mac_reg_bits_on(priv, MAC_REG_TFTCTL,
TFTCTL_TSFCNTREN);
vnt_adjust_tsf(priv, conf->beacon_rate->hw_value,
conf->sync_tsf, priv->current_tsf);
vnt_mac_set_beacon_interval(priv, conf->beacon_int);
vnt_reset_next_tbtt(priv, conf->beacon_int);
} else {
vnt_clear_current_tsf(priv);
vnt_mac_reg_bits_off(priv, MAC_REG_TFTCTL,
TFTCTL_TSFCNTREN);
}
}
}
static u64 vnt_prepare_multicast(struct ieee80211_hw *hw,
struct netdev_hw_addr_list *mc_list)
{
struct vnt_private *priv = hw->priv;
struct netdev_hw_addr *ha;
u64 mc_filter = 0;
u32 bit_nr = 0;
netdev_hw_addr_list_for_each(ha, mc_list) {
bit_nr = ether_crc(ETH_ALEN, ha->addr) >> 26;
mc_filter |= 1ULL << (bit_nr & 0x3f);
}
priv->mc_list_count = mc_list->count;
return mc_filter;
}
static void vnt_configure(struct ieee80211_hw *hw,
unsigned int changed_flags, unsigned int *total_flags, u64 multicast)
{
struct vnt_private *priv = hw->priv;
u8 rx_mode = 0;
int rc;
*total_flags &= FIF_ALLMULTI | FIF_OTHER_BSS | FIF_BCN_PRBRESP_PROMISC;
rc = vnt_control_in(priv, MESSAGE_TYPE_READ, MAC_REG_RCR,
MESSAGE_REQUEST_MACREG, sizeof(u8), &rx_mode);
if (!rc)
rx_mode = RCR_MULTICAST | RCR_BROADCAST;
dev_dbg(&priv->usb->dev, "rx mode in = %x\n", rx_mode);
if (changed_flags & FIF_ALLMULTI) {
if (*total_flags & FIF_ALLMULTI) {
if (priv->mc_list_count > 2)
vnt_mac_set_filter(priv, ~0);
else
vnt_mac_set_filter(priv, multicast);
rx_mode |= RCR_MULTICAST | RCR_BROADCAST;
} else {
rx_mode &= ~(RCR_MULTICAST | RCR_BROADCAST);
}
}
if (changed_flags & (FIF_OTHER_BSS | FIF_BCN_PRBRESP_PROMISC)) {
if (*total_flags & (FIF_OTHER_BSS | FIF_BCN_PRBRESP_PROMISC))
rx_mode &= ~RCR_BSSID;
else
rx_mode |= RCR_BSSID;
}
vnt_control_out_u8(priv, MESSAGE_REQUEST_MACREG, MAC_REG_RCR, rx_mode);
dev_dbg(&priv->usb->dev, "rx mode out= %x\n", rx_mode);
}
static int vnt_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 vnt_private *priv = hw->priv;
switch (cmd) {
case SET_KEY:
if (vnt_set_keys(hw, sta, vif, key))
return -EOPNOTSUPP;
break;
case DISABLE_KEY:
if (test_bit(key->hw_key_idx, &priv->key_entry_inuse))
clear_bit(key->hw_key_idx, &priv->key_entry_inuse);
default:
break;
}
return 0;
}
static void vnt_sw_scan_start(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
const u8 *addr)
{
struct vnt_private *priv = hw->priv;
vnt_set_bss_mode(priv);
/* Set max sensitivity*/
vnt_update_pre_ed_threshold(priv, true);
}
static void vnt_sw_scan_complete(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct vnt_private *priv = hw->priv;
/* Return sensitivity to channel level*/
vnt_update_pre_ed_threshold(priv, false);
}
static int vnt_get_stats(struct ieee80211_hw *hw,
struct ieee80211_low_level_stats *stats)
{
struct vnt_private *priv = hw->priv;
memcpy(stats, &priv->low_stats, sizeof(*stats));
return 0;
}
static u64 vnt_get_tsf(struct ieee80211_hw *hw, struct ieee80211_vif *vif)
{
struct vnt_private *priv = hw->priv;
return priv->current_tsf;
}
static void vnt_set_tsf(struct ieee80211_hw *hw, struct ieee80211_vif *vif,
u64 tsf)
{
struct vnt_private *priv = hw->priv;
vnt_update_next_tbtt(priv, tsf, vif->bss_conf.beacon_int);
}
static void vnt_reset_tsf(struct ieee80211_hw *hw, struct ieee80211_vif *vif)
{
struct vnt_private *priv = hw->priv;
vnt_mac_reg_bits_off(priv, MAC_REG_TFTCTL, TFTCTL_TSFCNTREN);
vnt_clear_current_tsf(priv);
}
static const struct ieee80211_ops vnt_mac_ops = {
.tx = vnt_tx_80211,
.start = vnt_start,
.stop = vnt_stop,
.add_interface = vnt_add_interface,
.remove_interface = vnt_remove_interface,
.config = vnt_config,
.bss_info_changed = vnt_bss_info_changed,
.prepare_multicast = vnt_prepare_multicast,
.configure_filter = vnt_configure,
.set_key = vnt_set_key,
.sw_scan_start = vnt_sw_scan_start,
.sw_scan_complete = vnt_sw_scan_complete,
.get_stats = vnt_get_stats,
.get_tsf = vnt_get_tsf,
.set_tsf = vnt_set_tsf,
.reset_tsf = vnt_reset_tsf,
};
int vnt_init(struct vnt_private *priv)
{
if (!(vnt_init_registers(priv)))
return -EAGAIN;
SET_IEEE80211_PERM_ADDR(priv->hw, priv->permanent_net_addr);
vnt_init_bands(priv);
if (ieee80211_register_hw(priv->hw))
return -ENODEV;
priv->mac_hw = true;
vnt_radio_power_off(priv);
return 0;
}
static int
vt6656_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct usb_device *udev;
struct vnt_private *priv;
struct ieee80211_hw *hw;
struct wiphy *wiphy;
int rc = 0;
udev = usb_get_dev(interface_to_usbdev(intf));
dev_notice(&udev->dev, "%s Ver. %s\n",
DEVICE_FULL_DRV_NAM, DEVICE_VERSION);
dev_notice(&udev->dev,
"Copyright (c) 2004 VIA Networking Technologies, Inc.\n");
hw = ieee80211_alloc_hw(sizeof(struct vnt_private), &vnt_mac_ops);
if (!hw) {
dev_err(&udev->dev, "could not register ieee80211_hw\n");
rc = -ENOMEM;
goto err_nomem;
}
priv = hw->priv;
priv->hw = hw;
priv->usb = udev;
vnt_set_options(priv);
spin_lock_init(&priv->lock);
mutex_init(&priv->usb_lock);
INIT_DELAYED_WORK(&priv->run_command_work, vnt_run_command);
usb_set_intfdata(intf, priv);
wiphy = priv->hw->wiphy;
wiphy->frag_threshold = FRAG_THRESH_DEF;
wiphy->rts_threshold = RTS_THRESH_DEF;
wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_ADHOC) | BIT(NL80211_IFTYPE_AP);
ieee80211_hw_set(priv->hw, TIMING_BEACON_ONLY);
ieee80211_hw_set(priv->hw, SIGNAL_DBM);
ieee80211_hw_set(priv->hw, RX_INCLUDES_FCS);
ieee80211_hw_set(priv->hw, REPORTS_TX_ACK_STATUS);
ieee80211_hw_set(priv->hw, SUPPORTS_PS);
priv->hw->max_signal = 100;
SET_IEEE80211_DEV(priv->hw, &intf->dev);
usb_device_reset(priv);
clear_bit(DEVICE_FLAGS_DISCONNECTED, &priv->flags);
vnt_reset_command_timer(priv);
vnt_schedule_command(priv, WLAN_CMD_INIT_MAC80211);
return 0;
err_nomem:
usb_put_dev(udev);
return rc;
}
static void vt6656_disconnect(struct usb_interface *intf)
{
struct vnt_private *priv = usb_get_intfdata(intf);
if (!priv)
return;
if (priv->mac_hw)
ieee80211_unregister_hw(priv->hw);
usb_set_intfdata(intf, NULL);
usb_put_dev(interface_to_usbdev(intf));
set_bit(DEVICE_FLAGS_UNPLUG, &priv->flags);
ieee80211_free_hw(priv->hw);
}
#ifdef CONFIG_PM
static int vt6656_suspend(struct usb_interface *intf, pm_message_t message)
{
return 0;
}
static int vt6656_resume(struct usb_interface *intf)
{
return 0;
}
#endif /* CONFIG_PM */
MODULE_DEVICE_TABLE(usb, vt6656_table);
static struct usb_driver vt6656_driver = {
.name = DEVICE_NAME,
.probe = vt6656_probe,
.disconnect = vt6656_disconnect,
.id_table = vt6656_table,
#ifdef CONFIG_PM
.suspend = vt6656_suspend,
.resume = vt6656_resume,
#endif /* CONFIG_PM */
};
module_usb_driver(vt6656_driver);
| gpl-2.0 |
cm-maya/android_kernel_hp_maya | drivers/usb/serial/ark3116.c | 388 | 23492 | /*
* Copyright (C) 2009 by Bart Hartgers (bart.hartgers+ark3116@gmail.com)
* Original version:
* Copyright (C) 2006
* Simon Schulz (ark3116_driver <at> auctionant.de)
*
* ark3116
* - implements a driver for the arkmicro ark3116 chipset (vendor=0x6547,
* productid=0x0232) (used in a datacable called KQ-U8A)
*
* Supports full modem status lines, break, hardware flow control. Does not
* support software flow control, since I do not know how to enable it in hw.
*
* This driver is a essentially new implementation. I initially dug
* into the old ark3116.c driver and suddenly realized the ark3116 is
* a 16450 with a USB interface glued to it. See comments at the
* bottom of this file.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/ioctl.h>
#include <linux/tty.h>
#include <linux/slab.h>
#include <linux/tty_flip.h>
#include <linux/module.h>
#include <linux/usb.h>
#include <linux/usb/serial.h>
#include <linux/serial.h>
#include <linux/serial_reg.h>
#include <linux/uaccess.h>
#include <linux/mutex.h>
#include <linux/spinlock.h>
static bool debug;
/*
* Version information
*/
#define DRIVER_VERSION "v0.7"
#define DRIVER_AUTHOR "Bart Hartgers <bart.hartgers+ark3116@gmail.com>"
#define DRIVER_DESC "USB ARK3116 serial/IrDA driver"
#define DRIVER_DEV_DESC "ARK3116 RS232/IrDA"
#define DRIVER_NAME "ark3116"
/* usb timeout of 1 second */
#define ARK_TIMEOUT 1000
static const struct usb_device_id id_table[] = {
{ USB_DEVICE(0x6547, 0x0232) },
{ USB_DEVICE(0x18ec, 0x3118) }, /* USB to IrDA adapter */
{ },
};
MODULE_DEVICE_TABLE(usb, id_table);
static int is_irda(struct usb_serial *serial)
{
struct usb_device *dev = serial->dev;
if (le16_to_cpu(dev->descriptor.idVendor) == 0x18ec &&
le16_to_cpu(dev->descriptor.idProduct) == 0x3118)
return 1;
return 0;
}
struct ark3116_private {
wait_queue_head_t delta_msr_wait;
struct async_icount icount;
int irda; /* 1 for irda device */
/* protects hw register updates */
struct mutex hw_lock;
int quot; /* baudrate divisor */
__u32 lcr; /* line control register value */
__u32 hcr; /* handshake control register (0x8)
* value */
__u32 mcr; /* modem contol register value */
/* protects the status values below */
spinlock_t status_lock;
__u32 msr; /* modem status register value */
__u32 lsr; /* line status register value */
};
static int ark3116_write_reg(struct usb_serial *serial,
unsigned reg, __u8 val)
{
int result;
/* 0xfe 0x40 are magic values taken from original driver */
result = usb_control_msg(serial->dev,
usb_sndctrlpipe(serial->dev, 0),
0xfe, 0x40, val, reg,
NULL, 0, ARK_TIMEOUT);
return result;
}
static int ark3116_read_reg(struct usb_serial *serial,
unsigned reg, unsigned char *buf)
{
int result;
/* 0xfe 0xc0 are magic values taken from original driver */
result = usb_control_msg(serial->dev,
usb_rcvctrlpipe(serial->dev, 0),
0xfe, 0xc0, 0, reg,
buf, 1, ARK_TIMEOUT);
if (result < 0)
return result;
else
return buf[0];
}
static inline int calc_divisor(int bps)
{
/* Original ark3116 made some exceptions in rounding here
* because windows did the same. Assume that is not really
* necessary.
* Crystal is 12MHz, probably because of USB, but we divide by 4?
*/
return (12000000 + 2*bps) / (4*bps);
}
static int ark3116_attach(struct usb_serial *serial)
{
struct usb_serial_port *port = serial->port[0];
struct ark3116_private *priv;
/* make sure we have our end-points */
if ((serial->num_bulk_in == 0) ||
(serial->num_bulk_out == 0) ||
(serial->num_interrupt_in == 0)) {
dev_err(&serial->dev->dev,
"%s - missing endpoint - "
"bulk in: %d, bulk out: %d, int in %d\n",
KBUILD_MODNAME,
serial->num_bulk_in,
serial->num_bulk_out,
serial->num_interrupt_in);
return -EINVAL;
}
priv = kzalloc(sizeof(struct ark3116_private),
GFP_KERNEL);
if (!priv)
return -ENOMEM;
init_waitqueue_head(&priv->delta_msr_wait);
mutex_init(&priv->hw_lock);
spin_lock_init(&priv->status_lock);
priv->irda = is_irda(serial);
usb_set_serial_port_data(port, priv);
/* setup the hardware */
ark3116_write_reg(serial, UART_IER, 0);
/* disable DMA */
ark3116_write_reg(serial, UART_FCR, 0);
/* handshake control */
priv->hcr = 0;
ark3116_write_reg(serial, 0x8 , 0);
/* modem control */
priv->mcr = 0;
ark3116_write_reg(serial, UART_MCR, 0);
if (!(priv->irda)) {
ark3116_write_reg(serial, 0xb , 0);
} else {
ark3116_write_reg(serial, 0xb , 1);
ark3116_write_reg(serial, 0xc , 0);
ark3116_write_reg(serial, 0xd , 0x41);
ark3116_write_reg(serial, 0xa , 1);
}
/* setup baudrate */
ark3116_write_reg(serial, UART_LCR, UART_LCR_DLAB);
/* setup for 9600 8N1 */
priv->quot = calc_divisor(9600);
ark3116_write_reg(serial, UART_DLL, priv->quot & 0xff);
ark3116_write_reg(serial, UART_DLM, (priv->quot>>8) & 0xff);
priv->lcr = UART_LCR_WLEN8;
ark3116_write_reg(serial, UART_LCR, UART_LCR_WLEN8);
ark3116_write_reg(serial, 0xe, 0);
if (priv->irda)
ark3116_write_reg(serial, 0x9, 0);
dev_info(&serial->dev->dev,
"%s using %s mode\n",
KBUILD_MODNAME,
priv->irda ? "IrDA" : "RS232");
return 0;
}
static void ark3116_release(struct usb_serial *serial)
{
struct usb_serial_port *port = serial->port[0];
struct ark3116_private *priv = usb_get_serial_port_data(port);
/* device is closed, so URBs and DMA should be down */
usb_set_serial_port_data(port, NULL);
mutex_destroy(&priv->hw_lock);
kfree(priv);
}
static void ark3116_init_termios(struct tty_struct *tty)
{
struct ktermios *termios = tty->termios;
*termios = tty_std_termios;
termios->c_cflag = B9600 | CS8
| CREAD | HUPCL | CLOCAL;
termios->c_ispeed = 9600;
termios->c_ospeed = 9600;
}
static void ark3116_set_termios(struct tty_struct *tty,
struct usb_serial_port *port,
struct ktermios *old_termios)
{
struct usb_serial *serial = port->serial;
struct ark3116_private *priv = usb_get_serial_port_data(port);
struct ktermios *termios = tty->termios;
unsigned int cflag = termios->c_cflag;
int bps = tty_get_baud_rate(tty);
int quot;
__u8 lcr, hcr, eval;
/* set data bit count */
switch (cflag & CSIZE) {
case CS5:
lcr = UART_LCR_WLEN5;
break;
case CS6:
lcr = UART_LCR_WLEN6;
break;
case CS7:
lcr = UART_LCR_WLEN7;
break;
default:
case CS8:
lcr = UART_LCR_WLEN8;
break;
}
if (cflag & CSTOPB)
lcr |= UART_LCR_STOP;
if (cflag & PARENB)
lcr |= UART_LCR_PARITY;
if (!(cflag & PARODD))
lcr |= UART_LCR_EPAR;
#ifdef CMSPAR
if (cflag & CMSPAR)
lcr |= UART_LCR_SPAR;
#endif
/* handshake control */
hcr = (cflag & CRTSCTS) ? 0x03 : 0x00;
/* calc baudrate */
dbg("%s - setting bps to %d", __func__, bps);
eval = 0;
switch (bps) {
case 0:
quot = calc_divisor(9600);
break;
default:
if ((bps < 75) || (bps > 3000000))
bps = 9600;
quot = calc_divisor(bps);
break;
case 460800:
eval = 1;
quot = calc_divisor(bps);
break;
case 921600:
eval = 2;
quot = calc_divisor(bps);
break;
}
/* Update state: synchronize */
mutex_lock(&priv->hw_lock);
/* keep old LCR_SBC bit */
lcr |= (priv->lcr & UART_LCR_SBC);
dbg("%s - setting hcr:0x%02x,lcr:0x%02x,quot:%d",
__func__, hcr, lcr, quot);
/* handshake control */
if (priv->hcr != hcr) {
priv->hcr = hcr;
ark3116_write_reg(serial, 0x8, hcr);
}
/* baudrate */
if (priv->quot != quot) {
priv->quot = quot;
priv->lcr = lcr; /* need to write lcr anyway */
/* disable DMA since transmit/receive is
* shadowed by UART_DLL
*/
ark3116_write_reg(serial, UART_FCR, 0);
ark3116_write_reg(serial, UART_LCR,
lcr|UART_LCR_DLAB);
ark3116_write_reg(serial, UART_DLL, quot & 0xff);
ark3116_write_reg(serial, UART_DLM, (quot>>8) & 0xff);
/* restore lcr */
ark3116_write_reg(serial, UART_LCR, lcr);
/* magic baudrate thingy: not sure what it does,
* but windows does this as well.
*/
ark3116_write_reg(serial, 0xe, eval);
/* enable DMA */
ark3116_write_reg(serial, UART_FCR, UART_FCR_DMA_SELECT);
} else if (priv->lcr != lcr) {
priv->lcr = lcr;
ark3116_write_reg(serial, UART_LCR, lcr);
}
mutex_unlock(&priv->hw_lock);
/* check for software flow control */
if (I_IXOFF(tty) || I_IXON(tty)) {
dev_warn(&serial->dev->dev,
"%s: don't know how to do software flow control\n",
KBUILD_MODNAME);
}
/* Don't rewrite B0 */
if (tty_termios_baud_rate(termios))
tty_termios_encode_baud_rate(termios, bps, bps);
}
static void ark3116_close(struct usb_serial_port *port)
{
struct usb_serial *serial = port->serial;
if (serial->dev) {
/* disable DMA */
ark3116_write_reg(serial, UART_FCR, 0);
/* deactivate interrupts */
ark3116_write_reg(serial, UART_IER, 0);
usb_serial_generic_close(port);
if (serial->num_interrupt_in)
usb_kill_urb(port->interrupt_in_urb);
}
}
static int ark3116_open(struct tty_struct *tty, struct usb_serial_port *port)
{
struct ark3116_private *priv = usb_get_serial_port_data(port);
struct usb_serial *serial = port->serial;
unsigned char *buf;
int result;
buf = kmalloc(1, GFP_KERNEL);
if (buf == NULL)
return -ENOMEM;
result = usb_serial_generic_open(tty, port);
if (result) {
dbg("%s - usb_serial_generic_open failed: %d",
__func__, result);
goto err_out;
}
/* remove any data still left: also clears error state */
ark3116_read_reg(serial, UART_RX, buf);
/* read modem status */
priv->msr = ark3116_read_reg(serial, UART_MSR, buf);
/* read line status */
priv->lsr = ark3116_read_reg(serial, UART_LSR, buf);
result = usb_submit_urb(port->interrupt_in_urb, GFP_KERNEL);
if (result) {
dev_err(&port->dev, "submit irq_in urb failed %d\n",
result);
ark3116_close(port);
goto err_out;
}
/* activate interrupts */
ark3116_write_reg(port->serial, UART_IER, UART_IER_MSI|UART_IER_RLSI);
/* enable DMA */
ark3116_write_reg(port->serial, UART_FCR, UART_FCR_DMA_SELECT);
/* setup termios */
if (tty)
ark3116_set_termios(tty, port, NULL);
err_out:
kfree(buf);
return result;
}
static int ark3116_get_icount(struct tty_struct *tty,
struct serial_icounter_struct *icount)
{
struct usb_serial_port *port = tty->driver_data;
struct ark3116_private *priv = usb_get_serial_port_data(port);
struct async_icount cnow = priv->icount;
icount->cts = cnow.cts;
icount->dsr = cnow.dsr;
icount->rng = cnow.rng;
icount->dcd = cnow.dcd;
icount->rx = cnow.rx;
icount->tx = cnow.tx;
icount->frame = cnow.frame;
icount->overrun = cnow.overrun;
icount->parity = cnow.parity;
icount->brk = cnow.brk;
icount->buf_overrun = cnow.buf_overrun;
return 0;
}
static int ark3116_ioctl(struct tty_struct *tty,
unsigned int cmd, unsigned long arg)
{
struct usb_serial_port *port = tty->driver_data;
struct ark3116_private *priv = usb_get_serial_port_data(port);
struct serial_struct serstruct;
void __user *user_arg = (void __user *)arg;
switch (cmd) {
case TIOCGSERIAL:
/* XXX: Some of these values are probably wrong. */
memset(&serstruct, 0, sizeof(serstruct));
serstruct.type = PORT_16654;
serstruct.line = port->serial->minor;
serstruct.port = port->number;
serstruct.custom_divisor = 0;
serstruct.baud_base = 460800;
if (copy_to_user(user_arg, &serstruct, sizeof(serstruct)))
return -EFAULT;
return 0;
case TIOCSSERIAL:
if (copy_from_user(&serstruct, user_arg, sizeof(serstruct)))
return -EFAULT;
return 0;
case TIOCMIWAIT:
for (;;) {
struct async_icount prev = priv->icount;
interruptible_sleep_on(&priv->delta_msr_wait);
/* see if a signal did it */
if (signal_pending(current))
return -ERESTARTSYS;
if ((prev.rng == priv->icount.rng) &&
(prev.dsr == priv->icount.dsr) &&
(prev.dcd == priv->icount.dcd) &&
(prev.cts == priv->icount.cts))
return -EIO;
if ((arg & TIOCM_RNG &&
(prev.rng != priv->icount.rng)) ||
(arg & TIOCM_DSR &&
(prev.dsr != priv->icount.dsr)) ||
(arg & TIOCM_CD &&
(prev.dcd != priv->icount.dcd)) ||
(arg & TIOCM_CTS &&
(prev.cts != priv->icount.cts)))
return 0;
}
break;
}
return -ENOIOCTLCMD;
}
static int ark3116_tiocmget(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct ark3116_private *priv = usb_get_serial_port_data(port);
__u32 status;
__u32 ctrl;
unsigned long flags;
mutex_lock(&priv->hw_lock);
ctrl = priv->mcr;
mutex_unlock(&priv->hw_lock);
spin_lock_irqsave(&priv->status_lock, flags);
status = priv->msr;
spin_unlock_irqrestore(&priv->status_lock, flags);
return (status & UART_MSR_DSR ? TIOCM_DSR : 0) |
(status & UART_MSR_CTS ? TIOCM_CTS : 0) |
(status & UART_MSR_RI ? TIOCM_RI : 0) |
(status & UART_MSR_DCD ? TIOCM_CD : 0) |
(ctrl & UART_MCR_DTR ? TIOCM_DTR : 0) |
(ctrl & UART_MCR_RTS ? TIOCM_RTS : 0) |
(ctrl & UART_MCR_OUT1 ? TIOCM_OUT1 : 0) |
(ctrl & UART_MCR_OUT2 ? TIOCM_OUT2 : 0);
}
static int ark3116_tiocmset(struct tty_struct *tty,
unsigned set, unsigned clr)
{
struct usb_serial_port *port = tty->driver_data;
struct ark3116_private *priv = usb_get_serial_port_data(port);
/* we need to take the mutex here, to make sure that the value
* in priv->mcr is actually the one that is in the hardware
*/
mutex_lock(&priv->hw_lock);
if (set & TIOCM_RTS)
priv->mcr |= UART_MCR_RTS;
if (set & TIOCM_DTR)
priv->mcr |= UART_MCR_DTR;
if (set & TIOCM_OUT1)
priv->mcr |= UART_MCR_OUT1;
if (set & TIOCM_OUT2)
priv->mcr |= UART_MCR_OUT2;
if (clr & TIOCM_RTS)
priv->mcr &= ~UART_MCR_RTS;
if (clr & TIOCM_DTR)
priv->mcr &= ~UART_MCR_DTR;
if (clr & TIOCM_OUT1)
priv->mcr &= ~UART_MCR_OUT1;
if (clr & TIOCM_OUT2)
priv->mcr &= ~UART_MCR_OUT2;
ark3116_write_reg(port->serial, UART_MCR, priv->mcr);
mutex_unlock(&priv->hw_lock);
return 0;
}
static void ark3116_break_ctl(struct tty_struct *tty, int break_state)
{
struct usb_serial_port *port = tty->driver_data;
struct ark3116_private *priv = usb_get_serial_port_data(port);
/* LCR is also used for other things: protect access */
mutex_lock(&priv->hw_lock);
if (break_state)
priv->lcr |= UART_LCR_SBC;
else
priv->lcr &= ~UART_LCR_SBC;
ark3116_write_reg(port->serial, UART_LCR, priv->lcr);
mutex_unlock(&priv->hw_lock);
}
static void ark3116_update_msr(struct usb_serial_port *port, __u8 msr)
{
struct ark3116_private *priv = usb_get_serial_port_data(port);
unsigned long flags;
spin_lock_irqsave(&priv->status_lock, flags);
priv->msr = msr;
spin_unlock_irqrestore(&priv->status_lock, flags);
if (msr & UART_MSR_ANY_DELTA) {
/* update input line counters */
if (msr & UART_MSR_DCTS)
priv->icount.cts++;
if (msr & UART_MSR_DDSR)
priv->icount.dsr++;
if (msr & UART_MSR_DDCD)
priv->icount.dcd++;
if (msr & UART_MSR_TERI)
priv->icount.rng++;
wake_up_interruptible(&priv->delta_msr_wait);
}
}
static void ark3116_update_lsr(struct usb_serial_port *port, __u8 lsr)
{
struct ark3116_private *priv = usb_get_serial_port_data(port);
unsigned long flags;
spin_lock_irqsave(&priv->status_lock, flags);
/* combine bits */
priv->lsr |= lsr;
spin_unlock_irqrestore(&priv->status_lock, flags);
if (lsr&UART_LSR_BRK_ERROR_BITS) {
if (lsr & UART_LSR_BI)
priv->icount.brk++;
if (lsr & UART_LSR_FE)
priv->icount.frame++;
if (lsr & UART_LSR_PE)
priv->icount.parity++;
if (lsr & UART_LSR_OE)
priv->icount.overrun++;
}
}
static void ark3116_read_int_callback(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
int status = urb->status;
const __u8 *data = urb->transfer_buffer;
int result;
switch (status) {
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
/* this urb is terminated, clean up */
dbg("%s - urb shutting down with status: %d",
__func__, status);
return;
default:
dbg("%s - nonzero urb status received: %d",
__func__, status);
break;
case 0: /* success */
/* discovered this by trail and error... */
if ((urb->actual_length == 4) && (data[0] == 0xe8)) {
const __u8 id = data[1]&UART_IIR_ID;
dbg("%s: iir=%02x", __func__, data[1]);
if (id == UART_IIR_MSI) {
dbg("%s: msr=%02x", __func__, data[3]);
ark3116_update_msr(port, data[3]);
break;
} else if (id == UART_IIR_RLSI) {
dbg("%s: lsr=%02x", __func__, data[2]);
ark3116_update_lsr(port, data[2]);
break;
}
}
/*
* Not sure what this data meant...
*/
usb_serial_debug_data(debug, &port->dev,
__func__,
urb->actual_length,
urb->transfer_buffer);
break;
}
result = usb_submit_urb(urb, GFP_ATOMIC);
if (result)
dev_err(&urb->dev->dev,
"%s - Error %d submitting interrupt urb\n",
__func__, result);
}
/* Data comes in via the bulk (data) URB, erors/interrupts via the int URB.
* This means that we cannot be sure which data byte has an associated error
* condition, so we report an error for all data in the next bulk read.
*
* Actually, there might even be a window between the bulk data leaving the
* ark and reading/resetting the lsr in the read_bulk_callback where an
* interrupt for the next data block could come in.
* Without somekind of ordering on the ark, we would have to report the
* error for the next block of data as well...
* For now, let's pretend this can't happen.
*/
static void ark3116_process_read_urb(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
struct ark3116_private *priv = usb_get_serial_port_data(port);
struct tty_struct *tty;
unsigned char *data = urb->transfer_buffer;
char tty_flag = TTY_NORMAL;
unsigned long flags;
__u32 lsr;
/* update line status */
spin_lock_irqsave(&priv->status_lock, flags);
lsr = priv->lsr;
priv->lsr &= ~UART_LSR_BRK_ERROR_BITS;
spin_unlock_irqrestore(&priv->status_lock, flags);
if (!urb->actual_length)
return;
tty = tty_port_tty_get(&port->port);
if (!tty)
return;
if (lsr & UART_LSR_BRK_ERROR_BITS) {
if (lsr & UART_LSR_BI)
tty_flag = TTY_BREAK;
else if (lsr & UART_LSR_PE)
tty_flag = TTY_PARITY;
else if (lsr & UART_LSR_FE)
tty_flag = TTY_FRAME;
/* overrun is special, not associated with a char */
if (lsr & UART_LSR_OE)
tty_insert_flip_char(tty, 0, TTY_OVERRUN);
}
tty_insert_flip_string_fixed_flag(tty, data, tty_flag,
urb->actual_length);
tty_flip_buffer_push(tty);
tty_kref_put(tty);
}
static struct usb_driver ark3116_driver = {
.name = "ark3116",
.probe = usb_serial_probe,
.disconnect = usb_serial_disconnect,
.id_table = id_table,
};
static struct usb_serial_driver ark3116_device = {
.driver = {
.owner = THIS_MODULE,
.name = "ark3116",
},
.id_table = id_table,
.num_ports = 1,
.attach = ark3116_attach,
.release = ark3116_release,
.set_termios = ark3116_set_termios,
.init_termios = ark3116_init_termios,
.ioctl = ark3116_ioctl,
.tiocmget = ark3116_tiocmget,
.tiocmset = ark3116_tiocmset,
.get_icount = ark3116_get_icount,
.open = ark3116_open,
.close = ark3116_close,
.break_ctl = ark3116_break_ctl,
.read_int_callback = ark3116_read_int_callback,
.process_read_urb = ark3116_process_read_urb,
};
static struct usb_serial_driver * const serial_drivers[] = {
&ark3116_device, NULL
};
module_usb_serial_driver(ark3116_driver, serial_drivers);
MODULE_LICENSE("GPL");
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
module_param(debug, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Enable debug");
/*
* The following describes what I learned from studying the old
* ark3116.c driver, disassembling the windows driver, and some lucky
* guesses. Since I do not have any datasheet or other
* documentation, inaccuracies are almost guaranteed.
*
* Some specs for the ARK3116 can be found here:
* http://web.archive.org/web/20060318000438/
* www.arkmicro.com/en/products/view.php?id=10
* On that page, 2 GPIO pins are mentioned: I assume these are the
* OUT1 and OUT2 pins of the UART, so I added support for those
* through the MCR. Since the pins are not available on my hardware,
* I could not verify this.
* Also, it states there is "on-chip hardware flow control". I have
* discovered how to enable that. Unfortunately, I do not know how to
* enable XON/XOFF (software) flow control, which would need support
* from the chip as well to work. Because of the wording on the web
* page there is a real possibility the chip simply does not support
* software flow control.
*
* I got my ark3116 as part of a mobile phone adapter cable. On the
* PCB, the following numbered contacts are present:
*
* 1:- +5V
* 2:o DTR
* 3:i RX
* 4:i DCD
* 5:o RTS
* 6:o TX
* 7:i RI
* 8:i DSR
* 10:- 0V
* 11:i CTS
*
* On my chip, all signals seem to be 3.3V, but 5V tolerant. But that
* may be different for the one you have ;-).
*
* The windows driver limits the registers to 0-F, so I assume there
* are actually 16 present on the device.
*
* On an UART interrupt, 4 bytes of data come in on the interrupt
* endpoint. The bytes are 0xe8 IIR LSR MSR.
*
* The baudrate seems to be generated from the 12MHz crystal, using
* 4-times subsampling. So quot=12e6/(4*baud). Also see description
* of register E.
*
* Registers 0-7:
* These seem to be the same as for a regular 16450. The FCR is set
* to UART_FCR_DMA_SELECT (0x8), I guess to enable transfers between
* the UART and the USB bridge/DMA engine.
*
* Register 8:
* By trial and error, I found out that bit 0 enables hardware CTS,
* stopping TX when CTS is +5V. Bit 1 does the same for RTS, making
* RTS +5V when the 3116 cannot transfer the data to the USB bus
* (verified by disabling the reading URB). Note that as far as I can
* tell, the windows driver does NOT use this, so there might be some
* hardware bug or something.
*
* According to a patch provided here
* (http://lkml.org/lkml/2009/7/26/56), the ARK3116 can also be used
* as an IrDA dongle. Since I do not have such a thing, I could not
* investigate that aspect. However, I can speculate ;-).
*
* - IrDA encodes data differently than RS232. Most likely, one of
* the bits in registers 9..E enables the IR ENDEC (encoder/decoder).
* - Depending on the IR transceiver, the input and output need to be
* inverted, so there are probably bits for that as well.
* - IrDA is half-duplex, so there should be a bit for selecting that.
*
* This still leaves at least two registers unaccounted for. Perhaps
* The chip can do XON/XOFF or CRC in HW?
*
* Register 9:
* Set to 0x00 for IrDA, when the baudrate is initialised.
*
* Register A:
* Set to 0x01 for IrDA, at init.
*
* Register B:
* Set to 0x01 for IrDA, 0x00 for RS232, at init.
*
* Register C:
* Set to 00 for IrDA, at init.
*
* Register D:
* Set to 0x41 for IrDA, at init.
*
* Register E:
* Somekind of baudrate override. The windows driver seems to set
* this to 0x00 for normal baudrates, 0x01 for 460800, 0x02 for 921600.
* Since 460800 and 921600 cannot be obtained by dividing 3MHz by an integer,
* it could be somekind of subdivisor thingy.
* However,it does not seem to do anything: selecting 921600 (divisor 3,
* reg E=2), still gets 1 MHz. I also checked if registers 9, C or F would
* work, but they don't.
*
* Register F: unknown
*/
| gpl-2.0 |
EnJens/kernel_tf101_stock | arch/blackfin/mach-common/smp.c | 900 | 12356 | /*
* IPI management based on arch/arm/kernel/smp.c (Copyright 2002 ARM Limited)
*
* Copyright 2007-2009 Analog Devices Inc.
* Philippe Gerum <rpm@xenomai.org>
*
* Licensed under the GPL-2.
*/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/cache.h>
#include <linux/profile.h>
#include <linux/errno.h>
#include <linux/mm.h>
#include <linux/cpu.h>
#include <linux/smp.h>
#include <linux/seq_file.h>
#include <linux/irq.h>
#include <linux/slab.h>
#include <asm/atomic.h>
#include <asm/cacheflush.h>
#include <asm/mmu_context.h>
#include <asm/pgtable.h>
#include <asm/pgalloc.h>
#include <asm/processor.h>
#include <asm/ptrace.h>
#include <asm/cpu.h>
#include <asm/time.h>
#include <linux/err.h>
/*
* Anomaly notes:
* 05000120 - we always define corelock as 32-bit integer in L2
*/
struct corelock_slot corelock __attribute__ ((__section__(".l2.bss")));
void __cpuinitdata *init_retx_coreb, *init_saved_retx_coreb,
*init_saved_seqstat_coreb, *init_saved_icplb_fault_addr_coreb,
*init_saved_dcplb_fault_addr_coreb;
cpumask_t cpu_possible_map;
EXPORT_SYMBOL(cpu_possible_map);
cpumask_t cpu_online_map;
EXPORT_SYMBOL(cpu_online_map);
#define BFIN_IPI_RESCHEDULE 0
#define BFIN_IPI_CALL_FUNC 1
#define BFIN_IPI_CPU_STOP 2
struct blackfin_flush_data {
unsigned long start;
unsigned long end;
};
void *secondary_stack;
struct smp_call_struct {
void (*func)(void *info);
void *info;
int wait;
cpumask_t pending;
cpumask_t waitmask;
};
static struct blackfin_flush_data smp_flush_data;
static DEFINE_SPINLOCK(stop_lock);
struct ipi_message {
struct list_head list;
unsigned long type;
struct smp_call_struct call_struct;
};
struct ipi_message_queue {
struct list_head head;
spinlock_t lock;
unsigned long count;
};
static DEFINE_PER_CPU(struct ipi_message_queue, ipi_msg_queue);
static void ipi_cpu_stop(unsigned int cpu)
{
spin_lock(&stop_lock);
printk(KERN_CRIT "CPU%u: stopping\n", cpu);
dump_stack();
spin_unlock(&stop_lock);
cpu_clear(cpu, cpu_online_map);
local_irq_disable();
while (1)
SSYNC();
}
static void ipi_flush_icache(void *info)
{
struct blackfin_flush_data *fdata = info;
/* Invalidate the memory holding the bounds of the flushed region. */
blackfin_dcache_invalidate_range((unsigned long)fdata,
(unsigned long)fdata + sizeof(*fdata));
blackfin_icache_flush_range(fdata->start, fdata->end);
}
static void ipi_call_function(unsigned int cpu, struct ipi_message *msg)
{
int wait;
void (*func)(void *info);
void *info;
func = msg->call_struct.func;
info = msg->call_struct.info;
wait = msg->call_struct.wait;
cpu_clear(cpu, msg->call_struct.pending);
func(info);
if (wait) {
#ifdef __ARCH_SYNC_CORE_DCACHE
/*
* 'wait' usually means synchronization between CPUs.
* Invalidate D cache in case shared data was changed
* by func() to ensure cache coherence.
*/
resync_core_dcache();
#endif
cpu_clear(cpu, msg->call_struct.waitmask);
} else
kfree(msg);
}
static irqreturn_t ipi_handler(int irq, void *dev_instance)
{
struct ipi_message *msg;
struct ipi_message_queue *msg_queue;
unsigned int cpu = smp_processor_id();
platform_clear_ipi(cpu);
msg_queue = &__get_cpu_var(ipi_msg_queue);
msg_queue->count++;
spin_lock(&msg_queue->lock);
while (!list_empty(&msg_queue->head)) {
msg = list_entry(msg_queue->head.next, typeof(*msg), list);
list_del(&msg->list);
switch (msg->type) {
case BFIN_IPI_RESCHEDULE:
/* That's the easiest one; leave it to
* return_from_int. */
kfree(msg);
break;
case BFIN_IPI_CALL_FUNC:
spin_unlock(&msg_queue->lock);
ipi_call_function(cpu, msg);
spin_lock(&msg_queue->lock);
break;
case BFIN_IPI_CPU_STOP:
spin_unlock(&msg_queue->lock);
ipi_cpu_stop(cpu);
spin_lock(&msg_queue->lock);
kfree(msg);
break;
default:
printk(KERN_CRIT "CPU%u: Unknown IPI message 0x%lx\n",
cpu, msg->type);
kfree(msg);
break;
}
}
spin_unlock(&msg_queue->lock);
return IRQ_HANDLED;
}
static void ipi_queue_init(void)
{
unsigned int cpu;
struct ipi_message_queue *msg_queue;
for_each_possible_cpu(cpu) {
msg_queue = &per_cpu(ipi_msg_queue, cpu);
INIT_LIST_HEAD(&msg_queue->head);
spin_lock_init(&msg_queue->lock);
msg_queue->count = 0;
}
}
int smp_call_function(void (*func)(void *info), void *info, int wait)
{
unsigned int cpu;
cpumask_t callmap;
unsigned long flags;
struct ipi_message_queue *msg_queue;
struct ipi_message *msg;
callmap = cpu_online_map;
cpu_clear(smp_processor_id(), callmap);
if (cpus_empty(callmap))
return 0;
msg = kmalloc(sizeof(*msg), GFP_ATOMIC);
if (!msg)
return -ENOMEM;
INIT_LIST_HEAD(&msg->list);
msg->call_struct.func = func;
msg->call_struct.info = info;
msg->call_struct.wait = wait;
msg->call_struct.pending = callmap;
msg->call_struct.waitmask = callmap;
msg->type = BFIN_IPI_CALL_FUNC;
for_each_cpu_mask(cpu, callmap) {
msg_queue = &per_cpu(ipi_msg_queue, cpu);
spin_lock_irqsave(&msg_queue->lock, flags);
list_add_tail(&msg->list, &msg_queue->head);
spin_unlock_irqrestore(&msg_queue->lock, flags);
platform_send_ipi_cpu(cpu);
}
if (wait) {
while (!cpus_empty(msg->call_struct.waitmask))
blackfin_dcache_invalidate_range(
(unsigned long)(&msg->call_struct.waitmask),
(unsigned long)(&msg->call_struct.waitmask));
#ifdef __ARCH_SYNC_CORE_DCACHE
/*
* Invalidate D cache in case shared data was changed by
* other processors to ensure cache coherence.
*/
resync_core_dcache();
#endif
kfree(msg);
}
return 0;
}
EXPORT_SYMBOL_GPL(smp_call_function);
int smp_call_function_single(int cpuid, void (*func) (void *info), void *info,
int wait)
{
unsigned int cpu = cpuid;
cpumask_t callmap;
unsigned long flags;
struct ipi_message_queue *msg_queue;
struct ipi_message *msg;
if (cpu_is_offline(cpu))
return 0;
cpus_clear(callmap);
cpu_set(cpu, callmap);
msg = kmalloc(sizeof(*msg), GFP_ATOMIC);
if (!msg)
return -ENOMEM;
INIT_LIST_HEAD(&msg->list);
msg->call_struct.func = func;
msg->call_struct.info = info;
msg->call_struct.wait = wait;
msg->call_struct.pending = callmap;
msg->call_struct.waitmask = callmap;
msg->type = BFIN_IPI_CALL_FUNC;
msg_queue = &per_cpu(ipi_msg_queue, cpu);
spin_lock_irqsave(&msg_queue->lock, flags);
list_add_tail(&msg->list, &msg_queue->head);
spin_unlock_irqrestore(&msg_queue->lock, flags);
platform_send_ipi_cpu(cpu);
if (wait) {
while (!cpus_empty(msg->call_struct.waitmask))
blackfin_dcache_invalidate_range(
(unsigned long)(&msg->call_struct.waitmask),
(unsigned long)(&msg->call_struct.waitmask));
#ifdef __ARCH_SYNC_CORE_DCACHE
/*
* Invalidate D cache in case shared data was changed by
* other processors to ensure cache coherence.
*/
resync_core_dcache();
#endif
kfree(msg);
}
return 0;
}
EXPORT_SYMBOL_GPL(smp_call_function_single);
void smp_send_reschedule(int cpu)
{
unsigned long flags;
struct ipi_message_queue *msg_queue;
struct ipi_message *msg;
if (cpu_is_offline(cpu))
return;
msg = kzalloc(sizeof(*msg), GFP_ATOMIC);
if (!msg)
return;
INIT_LIST_HEAD(&msg->list);
msg->type = BFIN_IPI_RESCHEDULE;
msg_queue = &per_cpu(ipi_msg_queue, cpu);
spin_lock_irqsave(&msg_queue->lock, flags);
list_add_tail(&msg->list, &msg_queue->head);
spin_unlock_irqrestore(&msg_queue->lock, flags);
platform_send_ipi_cpu(cpu);
return;
}
void smp_send_stop(void)
{
unsigned int cpu;
cpumask_t callmap;
unsigned long flags;
struct ipi_message_queue *msg_queue;
struct ipi_message *msg;
callmap = cpu_online_map;
cpu_clear(smp_processor_id(), callmap);
if (cpus_empty(callmap))
return;
msg = kzalloc(sizeof(*msg), GFP_ATOMIC);
if (!msg)
return;
INIT_LIST_HEAD(&msg->list);
msg->type = BFIN_IPI_CPU_STOP;
for_each_cpu_mask(cpu, callmap) {
msg_queue = &per_cpu(ipi_msg_queue, cpu);
spin_lock_irqsave(&msg_queue->lock, flags);
list_add_tail(&msg->list, &msg_queue->head);
spin_unlock_irqrestore(&msg_queue->lock, flags);
platform_send_ipi_cpu(cpu);
}
return;
}
int __cpuinit __cpu_up(unsigned int cpu)
{
int ret;
static struct task_struct *idle;
if (idle)
free_task(idle);
idle = fork_idle(cpu);
if (IS_ERR(idle)) {
printk(KERN_ERR "CPU%u: fork() failed\n", cpu);
return PTR_ERR(idle);
}
secondary_stack = task_stack_page(idle) + THREAD_SIZE;
ret = platform_boot_secondary(cpu, idle);
secondary_stack = NULL;
return ret;
}
static void __cpuinit setup_secondary(unsigned int cpu)
{
unsigned long ilat;
bfin_write_IMASK(0);
CSYNC();
ilat = bfin_read_ILAT();
CSYNC();
bfin_write_ILAT(ilat);
CSYNC();
/* Enable interrupt levels IVG7-15. IARs have been already
* programmed by the boot CPU. */
bfin_irq_flags |= IMASK_IVG15 |
IMASK_IVG14 | IMASK_IVG13 | IMASK_IVG12 | IMASK_IVG11 |
IMASK_IVG10 | IMASK_IVG9 | IMASK_IVG8 | IMASK_IVG7 | IMASK_IVGHW;
}
void __cpuinit secondary_start_kernel(void)
{
unsigned int cpu = smp_processor_id();
struct mm_struct *mm = &init_mm;
if (_bfin_swrst & SWRST_DBL_FAULT_B) {
printk(KERN_EMERG "CoreB Recovering from DOUBLE FAULT event\n");
#ifdef CONFIG_DEBUG_DOUBLEFAULT
printk(KERN_EMERG " While handling exception (EXCAUSE = 0x%x) at %pF\n",
(int)init_saved_seqstat_coreb & SEQSTAT_EXCAUSE, init_saved_retx_coreb);
printk(KERN_NOTICE " DCPLB_FAULT_ADDR: %pF\n", init_saved_dcplb_fault_addr_coreb);
printk(KERN_NOTICE " ICPLB_FAULT_ADDR: %pF\n", init_saved_icplb_fault_addr_coreb);
#endif
printk(KERN_NOTICE " The instruction at %pF caused a double exception\n",
init_retx_coreb);
}
/*
* We want the D-cache to be enabled early, in case the atomic
* support code emulates cache coherence (see
* __ARCH_SYNC_CORE_DCACHE).
*/
init_exception_vectors();
bfin_setup_caches(cpu);
local_irq_disable();
/* Attach the new idle task to the global mm. */
atomic_inc(&mm->mm_users);
atomic_inc(&mm->mm_count);
current->active_mm = mm;
preempt_disable();
setup_secondary(cpu);
platform_secondary_init(cpu);
/* setup local core timer */
bfin_local_timer_setup();
local_irq_enable();
/*
* Calibrate loops per jiffy value.
* IRQs need to be enabled here - D-cache can be invalidated
* in timer irq handler, so core B can read correct jiffies.
*/
calibrate_delay();
cpu_idle();
}
void __init smp_prepare_boot_cpu(void)
{
}
void __init smp_prepare_cpus(unsigned int max_cpus)
{
platform_prepare_cpus(max_cpus);
ipi_queue_init();
platform_request_ipi(&ipi_handler);
}
void __init smp_cpus_done(unsigned int max_cpus)
{
unsigned long bogosum = 0;
unsigned int cpu;
for_each_online_cpu(cpu)
bogosum += loops_per_jiffy;
printk(KERN_INFO "SMP: Total of %d processors activated "
"(%lu.%02lu BogoMIPS).\n",
num_online_cpus(),
bogosum / (500000/HZ),
(bogosum / (5000/HZ)) % 100);
}
void smp_icache_flush_range_others(unsigned long start, unsigned long end)
{
smp_flush_data.start = start;
smp_flush_data.end = end;
if (smp_call_function(&ipi_flush_icache, &smp_flush_data, 0))
printk(KERN_WARNING "SMP: failed to run I-cache flush request on other CPUs\n");
}
EXPORT_SYMBOL_GPL(smp_icache_flush_range_others);
#ifdef __ARCH_SYNC_CORE_ICACHE
unsigned long icache_invld_count[NR_CPUS];
void resync_core_icache(void)
{
unsigned int cpu = get_cpu();
blackfin_invalidate_entire_icache();
icache_invld_count[cpu]++;
put_cpu();
}
EXPORT_SYMBOL(resync_core_icache);
#endif
#ifdef __ARCH_SYNC_CORE_DCACHE
unsigned long dcache_invld_count[NR_CPUS];
unsigned long barrier_mask __attribute__ ((__section__(".l2.bss")));
void resync_core_dcache(void)
{
unsigned int cpu = get_cpu();
blackfin_invalidate_entire_dcache();
dcache_invld_count[cpu]++;
put_cpu();
}
EXPORT_SYMBOL(resync_core_dcache);
#endif
#ifdef CONFIG_HOTPLUG_CPU
int __cpuexit __cpu_disable(void)
{
unsigned int cpu = smp_processor_id();
if (cpu == 0)
return -EPERM;
set_cpu_online(cpu, false);
return 0;
}
static DECLARE_COMPLETION(cpu_killed);
int __cpuexit __cpu_die(unsigned int cpu)
{
return wait_for_completion_timeout(&cpu_killed, 5000);
}
void cpu_die(void)
{
complete(&cpu_killed);
atomic_dec(&init_mm.mm_users);
atomic_dec(&init_mm.mm_count);
local_irq_disable();
platform_cpu_die();
}
#endif
| gpl-2.0 |
xuefy/IM-A820L_GB_KERNEL | drivers/media/video/tvp514x.c | 900 | 35491 | /*
* drivers/media/video/tvp514x.c
*
* TI TVP5146/47 decoder driver
*
* Copyright (C) 2008 Texas Instruments Inc
* Author: Vaibhav Hiremath <hvaibhav@ti.com>
*
* Contributors:
* Sivaraj R <sivaraj@ti.com>
* Brijesh R Jadav <brijesh.j@ti.com>
* Hardik Shah <hardik.shah@ti.com>
* Manjunath Hadli <mrh@ti.com>
* Karicheri Muralidharan <m-karicheri2@ti.com>
*
* This package is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <linux/i2c.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/videodev2.h>
#include <media/v4l2-device.h>
#include <media/v4l2-common.h>
#include <media/v4l2-chip-ident.h>
#include <media/tvp514x.h>
#include "tvp514x_regs.h"
/* Module Name */
#define TVP514X_MODULE_NAME "tvp514x"
/* Private macros for TVP */
#define I2C_RETRY_COUNT (5)
#define LOCK_RETRY_COUNT (5)
#define LOCK_RETRY_DELAY (200)
/* Debug functions */
static int debug;
module_param(debug, bool, 0644);
MODULE_PARM_DESC(debug, "Debug level (0-1)");
MODULE_AUTHOR("Texas Instruments");
MODULE_DESCRIPTION("TVP514X linux decoder driver");
MODULE_LICENSE("GPL");
/* enum tvp514x_std - enum for supported standards */
enum tvp514x_std {
STD_NTSC_MJ = 0,
STD_PAL_BDGHIN,
STD_INVALID
};
/**
* struct tvp514x_std_info - Structure to store standard informations
* @width: Line width in pixels
* @height:Number of active lines
* @video_std: Value to write in REG_VIDEO_STD register
* @standard: v4l2 standard structure information
*/
struct tvp514x_std_info {
unsigned long width;
unsigned long height;
u8 video_std;
struct v4l2_standard standard;
};
static struct tvp514x_reg tvp514x_reg_list_default[0x40];
static int tvp514x_s_stream(struct v4l2_subdev *sd, int enable);
/**
* struct tvp514x_decoder - TVP5146/47 decoder object
* @sd: Subdevice Slave handle
* @tvp514x_regs: copy of hw's regs with preset values.
* @pdata: Board specific
* @ver: Chip version
* @streaming: TVP5146/47 decoder streaming - enabled or disabled.
* @current_std: Current standard
* @num_stds: Number of standards
* @std_list: Standards list
* @input: Input routing at chip level
* @output: Output routing at chip level
*/
struct tvp514x_decoder {
struct v4l2_subdev sd;
struct tvp514x_reg tvp514x_regs[ARRAY_SIZE(tvp514x_reg_list_default)];
const struct tvp514x_platform_data *pdata;
int ver;
int streaming;
enum tvp514x_std current_std;
int num_stds;
const struct tvp514x_std_info *std_list;
/* Input and Output Routing parameters */
u32 input;
u32 output;
};
/* TVP514x default register values */
static struct tvp514x_reg tvp514x_reg_list_default[] = {
/* Composite selected */
{TOK_WRITE, REG_INPUT_SEL, 0x05},
{TOK_WRITE, REG_AFE_GAIN_CTRL, 0x0F},
/* Auto mode */
{TOK_WRITE, REG_VIDEO_STD, 0x00},
{TOK_WRITE, REG_OPERATION_MODE, 0x00},
{TOK_SKIP, REG_AUTOSWITCH_MASK, 0x3F},
{TOK_WRITE, REG_COLOR_KILLER, 0x10},
{TOK_WRITE, REG_LUMA_CONTROL1, 0x00},
{TOK_WRITE, REG_LUMA_CONTROL2, 0x00},
{TOK_WRITE, REG_LUMA_CONTROL3, 0x02},
{TOK_WRITE, REG_BRIGHTNESS, 0x80},
{TOK_WRITE, REG_CONTRAST, 0x80},
{TOK_WRITE, REG_SATURATION, 0x80},
{TOK_WRITE, REG_HUE, 0x00},
{TOK_WRITE, REG_CHROMA_CONTROL1, 0x00},
{TOK_WRITE, REG_CHROMA_CONTROL2, 0x0E},
/* Reserved */
{TOK_SKIP, 0x0F, 0x00},
{TOK_WRITE, REG_COMP_PR_SATURATION, 0x80},
{TOK_WRITE, REG_COMP_Y_CONTRAST, 0x80},
{TOK_WRITE, REG_COMP_PB_SATURATION, 0x80},
/* Reserved */
{TOK_SKIP, 0x13, 0x00},
{TOK_WRITE, REG_COMP_Y_BRIGHTNESS, 0x80},
/* Reserved */
{TOK_SKIP, 0x15, 0x00},
/* NTSC timing */
{TOK_SKIP, REG_AVID_START_PIXEL_LSB, 0x55},
{TOK_SKIP, REG_AVID_START_PIXEL_MSB, 0x00},
{TOK_SKIP, REG_AVID_STOP_PIXEL_LSB, 0x25},
{TOK_SKIP, REG_AVID_STOP_PIXEL_MSB, 0x03},
/* NTSC timing */
{TOK_SKIP, REG_HSYNC_START_PIXEL_LSB, 0x00},
{TOK_SKIP, REG_HSYNC_START_PIXEL_MSB, 0x00},
{TOK_SKIP, REG_HSYNC_STOP_PIXEL_LSB, 0x40},
{TOK_SKIP, REG_HSYNC_STOP_PIXEL_MSB, 0x00},
/* NTSC timing */
{TOK_SKIP, REG_VSYNC_START_LINE_LSB, 0x04},
{TOK_SKIP, REG_VSYNC_START_LINE_MSB, 0x00},
{TOK_SKIP, REG_VSYNC_STOP_LINE_LSB, 0x07},
{TOK_SKIP, REG_VSYNC_STOP_LINE_MSB, 0x00},
/* NTSC timing */
{TOK_SKIP, REG_VBLK_START_LINE_LSB, 0x01},
{TOK_SKIP, REG_VBLK_START_LINE_MSB, 0x00},
{TOK_SKIP, REG_VBLK_STOP_LINE_LSB, 0x15},
{TOK_SKIP, REG_VBLK_STOP_LINE_MSB, 0x00},
/* Reserved */
{TOK_SKIP, 0x26, 0x00},
/* Reserved */
{TOK_SKIP, 0x27, 0x00},
{TOK_SKIP, REG_FAST_SWTICH_CONTROL, 0xCC},
/* Reserved */
{TOK_SKIP, 0x29, 0x00},
{TOK_SKIP, REG_FAST_SWTICH_SCART_DELAY, 0x00},
/* Reserved */
{TOK_SKIP, 0x2B, 0x00},
{TOK_SKIP, REG_SCART_DELAY, 0x00},
{TOK_SKIP, REG_CTI_DELAY, 0x00},
{TOK_SKIP, REG_CTI_CONTROL, 0x00},
/* Reserved */
{TOK_SKIP, 0x2F, 0x00},
/* Reserved */
{TOK_SKIP, 0x30, 0x00},
/* Reserved */
{TOK_SKIP, 0x31, 0x00},
/* HS, VS active high */
{TOK_WRITE, REG_SYNC_CONTROL, 0x00},
/* 10-bit BT.656 */
{TOK_WRITE, REG_OUTPUT_FORMATTER1, 0x00},
/* Enable clk & data */
{TOK_WRITE, REG_OUTPUT_FORMATTER2, 0x11},
/* Enable AVID & FLD */
{TOK_WRITE, REG_OUTPUT_FORMATTER3, 0xEE},
/* Enable VS & HS */
{TOK_WRITE, REG_OUTPUT_FORMATTER4, 0xAF},
{TOK_WRITE, REG_OUTPUT_FORMATTER5, 0xFF},
{TOK_WRITE, REG_OUTPUT_FORMATTER6, 0xFF},
/* Clear status */
{TOK_WRITE, REG_CLEAR_LOST_LOCK, 0x01},
{TOK_TERM, 0, 0},
};
/**
* Supported standards -
*
* Currently supports two standards only, need to add support for rest of the
* modes, like SECAM, etc...
*/
static const struct tvp514x_std_info tvp514x_std_list[] = {
/* Standard: STD_NTSC_MJ */
[STD_NTSC_MJ] = {
.width = NTSC_NUM_ACTIVE_PIXELS,
.height = NTSC_NUM_ACTIVE_LINES,
.video_std = VIDEO_STD_NTSC_MJ_BIT,
.standard = {
.index = 0,
.id = V4L2_STD_NTSC,
.name = "NTSC",
.frameperiod = {1001, 30000},
.framelines = 525
},
/* Standard: STD_PAL_BDGHIN */
},
[STD_PAL_BDGHIN] = {
.width = PAL_NUM_ACTIVE_PIXELS,
.height = PAL_NUM_ACTIVE_LINES,
.video_std = VIDEO_STD_PAL_BDGHIN_BIT,
.standard = {
.index = 1,
.id = V4L2_STD_PAL,
.name = "PAL",
.frameperiod = {1, 25},
.framelines = 625
},
},
/* Standard: need to add for additional standard */
};
static inline struct tvp514x_decoder *to_decoder(struct v4l2_subdev *sd)
{
return container_of(sd, struct tvp514x_decoder, sd);
}
/**
* tvp514x_read_reg() - Read a value from a register in an TVP5146/47.
* @sd: ptr to v4l2_subdev struct
* @reg: TVP5146/47 register address
*
* Returns value read if successful, or non-zero (-1) otherwise.
*/
static int tvp514x_read_reg(struct v4l2_subdev *sd, u8 reg)
{
int err, retry = 0;
struct i2c_client *client = v4l2_get_subdevdata(sd);
read_again:
err = i2c_smbus_read_byte_data(client, reg);
if (err < 0) {
if (retry <= I2C_RETRY_COUNT) {
v4l2_warn(sd, "Read: retry ... %d\n", retry);
retry++;
msleep_interruptible(10);
goto read_again;
}
}
return err;
}
/**
* dump_reg() - dump the register content of TVP5146/47.
* @sd: ptr to v4l2_subdev struct
* @reg: TVP5146/47 register address
*/
static void dump_reg(struct v4l2_subdev *sd, u8 reg)
{
u32 val;
val = tvp514x_read_reg(sd, reg);
v4l2_info(sd, "Reg(0x%.2X): 0x%.2X\n", reg, val);
}
/**
* tvp514x_write_reg() - Write a value to a register in TVP5146/47
* @sd: ptr to v4l2_subdev struct
* @reg: TVP5146/47 register address
* @val: value to be written to the register
*
* Write a value to a register in an TVP5146/47 decoder device.
* Returns zero if successful, or non-zero otherwise.
*/
static int tvp514x_write_reg(struct v4l2_subdev *sd, u8 reg, u8 val)
{
int err, retry = 0;
struct i2c_client *client = v4l2_get_subdevdata(sd);
write_again:
err = i2c_smbus_write_byte_data(client, reg, val);
if (err) {
if (retry <= I2C_RETRY_COUNT) {
v4l2_warn(sd, "Write: retry ... %d\n", retry);
retry++;
msleep_interruptible(10);
goto write_again;
}
}
return err;
}
/**
* tvp514x_write_regs() : Initializes a list of TVP5146/47 registers
* @sd: ptr to v4l2_subdev struct
* @reglist: list of TVP5146/47 registers and values
*
* Initializes a list of TVP5146/47 registers:-
* if token is TOK_TERM, then entire write operation terminates
* if token is TOK_DELAY, then a delay of 'val' msec is introduced
* if token is TOK_SKIP, then the register write is skipped
* if token is TOK_WRITE, then the register write is performed
* Returns zero if successful, or non-zero otherwise.
*/
static int tvp514x_write_regs(struct v4l2_subdev *sd,
const struct tvp514x_reg reglist[])
{
int err;
const struct tvp514x_reg *next = reglist;
for (; next->token != TOK_TERM; next++) {
if (next->token == TOK_DELAY) {
msleep(next->val);
continue;
}
if (next->token == TOK_SKIP)
continue;
err = tvp514x_write_reg(sd, next->reg, (u8) next->val);
if (err) {
v4l2_err(sd, "Write failed. Err[%d]\n", err);
return err;
}
}
return 0;
}
/**
* tvp514x_query_current_std() : Query the current standard detected by TVP5146/47
* @sd: ptr to v4l2_subdev struct
*
* Returns the current standard detected by TVP5146/47, STD_INVALID if there is no
* standard detected.
*/
static enum tvp514x_std tvp514x_query_current_std(struct v4l2_subdev *sd)
{
u8 std, std_status;
std = tvp514x_read_reg(sd, REG_VIDEO_STD);
if ((std & VIDEO_STD_MASK) == VIDEO_STD_AUTO_SWITCH_BIT)
/* use the standard status register */
std_status = tvp514x_read_reg(sd, REG_VIDEO_STD_STATUS);
else
/* use the standard register itself */
std_status = std;
switch (std_status & VIDEO_STD_MASK) {
case VIDEO_STD_NTSC_MJ_BIT:
return STD_NTSC_MJ;
case VIDEO_STD_PAL_BDGHIN_BIT:
return STD_PAL_BDGHIN;
default:
return STD_INVALID;
}
return STD_INVALID;
}
/* TVP5146/47 register dump function */
static void tvp514x_reg_dump(struct v4l2_subdev *sd)
{
dump_reg(sd, REG_INPUT_SEL);
dump_reg(sd, REG_AFE_GAIN_CTRL);
dump_reg(sd, REG_VIDEO_STD);
dump_reg(sd, REG_OPERATION_MODE);
dump_reg(sd, REG_COLOR_KILLER);
dump_reg(sd, REG_LUMA_CONTROL1);
dump_reg(sd, REG_LUMA_CONTROL2);
dump_reg(sd, REG_LUMA_CONTROL3);
dump_reg(sd, REG_BRIGHTNESS);
dump_reg(sd, REG_CONTRAST);
dump_reg(sd, REG_SATURATION);
dump_reg(sd, REG_HUE);
dump_reg(sd, REG_CHROMA_CONTROL1);
dump_reg(sd, REG_CHROMA_CONTROL2);
dump_reg(sd, REG_COMP_PR_SATURATION);
dump_reg(sd, REG_COMP_Y_CONTRAST);
dump_reg(sd, REG_COMP_PB_SATURATION);
dump_reg(sd, REG_COMP_Y_BRIGHTNESS);
dump_reg(sd, REG_AVID_START_PIXEL_LSB);
dump_reg(sd, REG_AVID_START_PIXEL_MSB);
dump_reg(sd, REG_AVID_STOP_PIXEL_LSB);
dump_reg(sd, REG_AVID_STOP_PIXEL_MSB);
dump_reg(sd, REG_HSYNC_START_PIXEL_LSB);
dump_reg(sd, REG_HSYNC_START_PIXEL_MSB);
dump_reg(sd, REG_HSYNC_STOP_PIXEL_LSB);
dump_reg(sd, REG_HSYNC_STOP_PIXEL_MSB);
dump_reg(sd, REG_VSYNC_START_LINE_LSB);
dump_reg(sd, REG_VSYNC_START_LINE_MSB);
dump_reg(sd, REG_VSYNC_STOP_LINE_LSB);
dump_reg(sd, REG_VSYNC_STOP_LINE_MSB);
dump_reg(sd, REG_VBLK_START_LINE_LSB);
dump_reg(sd, REG_VBLK_START_LINE_MSB);
dump_reg(sd, REG_VBLK_STOP_LINE_LSB);
dump_reg(sd, REG_VBLK_STOP_LINE_MSB);
dump_reg(sd, REG_SYNC_CONTROL);
dump_reg(sd, REG_OUTPUT_FORMATTER1);
dump_reg(sd, REG_OUTPUT_FORMATTER2);
dump_reg(sd, REG_OUTPUT_FORMATTER3);
dump_reg(sd, REG_OUTPUT_FORMATTER4);
dump_reg(sd, REG_OUTPUT_FORMATTER5);
dump_reg(sd, REG_OUTPUT_FORMATTER6);
dump_reg(sd, REG_CLEAR_LOST_LOCK);
}
/**
* tvp514x_configure() - Configure the TVP5146/47 registers
* @sd: ptr to v4l2_subdev struct
* @decoder: ptr to tvp514x_decoder structure
*
* Returns zero if successful, or non-zero otherwise.
*/
static int tvp514x_configure(struct v4l2_subdev *sd,
struct tvp514x_decoder *decoder)
{
int err;
/* common register initialization */
err =
tvp514x_write_regs(sd, decoder->tvp514x_regs);
if (err)
return err;
if (debug)
tvp514x_reg_dump(sd);
return 0;
}
/**
* tvp514x_detect() - Detect if an tvp514x is present, and if so which revision.
* @sd: pointer to standard V4L2 sub-device structure
* @decoder: pointer to tvp514x_decoder structure
*
* A device is considered to be detected if the chip ID (LSB and MSB)
* registers match the expected values.
* Any value of the rom version register is accepted.
* Returns ENODEV error number if no device is detected, or zero
* if a device is detected.
*/
static int tvp514x_detect(struct v4l2_subdev *sd,
struct tvp514x_decoder *decoder)
{
u8 chip_id_msb, chip_id_lsb, rom_ver;
struct i2c_client *client = v4l2_get_subdevdata(sd);
chip_id_msb = tvp514x_read_reg(sd, REG_CHIP_ID_MSB);
chip_id_lsb = tvp514x_read_reg(sd, REG_CHIP_ID_LSB);
rom_ver = tvp514x_read_reg(sd, REG_ROM_VERSION);
v4l2_dbg(1, debug, sd,
"chip id detected msb:0x%x lsb:0x%x rom version:0x%x\n",
chip_id_msb, chip_id_lsb, rom_ver);
if ((chip_id_msb != TVP514X_CHIP_ID_MSB)
|| ((chip_id_lsb != TVP5146_CHIP_ID_LSB)
&& (chip_id_lsb != TVP5147_CHIP_ID_LSB))) {
/* We didn't read the values we expected, so this must not be
* an TVP5146/47.
*/
v4l2_err(sd, "chip id mismatch msb:0x%x lsb:0x%x\n",
chip_id_msb, chip_id_lsb);
return -ENODEV;
}
decoder->ver = rom_ver;
v4l2_info(sd, "%s (Version - 0x%.2x) found at 0x%x (%s)\n",
client->name, decoder->ver,
client->addr << 1, client->adapter->name);
return 0;
}
/**
* tvp514x_querystd() - V4L2 decoder interface handler for querystd
* @sd: pointer to standard V4L2 sub-device structure
* @std_id: standard V4L2 std_id ioctl enum
*
* Returns the current standard detected by TVP5146/47. If no active input is
* detected then *std_id is set to 0 and the function returns 0.
*/
static int tvp514x_querystd(struct v4l2_subdev *sd, v4l2_std_id *std_id)
{
struct tvp514x_decoder *decoder = to_decoder(sd);
enum tvp514x_std current_std;
enum tvp514x_input input_sel;
u8 sync_lock_status, lock_mask;
if (std_id == NULL)
return -EINVAL;
*std_id = V4L2_STD_UNKNOWN;
/* query the current standard */
current_std = tvp514x_query_current_std(sd);
if (current_std == STD_INVALID)
return 0;
input_sel = decoder->input;
switch (input_sel) {
case INPUT_CVBS_VI1A:
case INPUT_CVBS_VI1B:
case INPUT_CVBS_VI1C:
case INPUT_CVBS_VI2A:
case INPUT_CVBS_VI2B:
case INPUT_CVBS_VI2C:
case INPUT_CVBS_VI3A:
case INPUT_CVBS_VI3B:
case INPUT_CVBS_VI3C:
case INPUT_CVBS_VI4A:
lock_mask = STATUS_CLR_SUBCAR_LOCK_BIT |
STATUS_HORZ_SYNC_LOCK_BIT |
STATUS_VIRT_SYNC_LOCK_BIT;
break;
case INPUT_SVIDEO_VI2A_VI1A:
case INPUT_SVIDEO_VI2B_VI1B:
case INPUT_SVIDEO_VI2C_VI1C:
case INPUT_SVIDEO_VI2A_VI3A:
case INPUT_SVIDEO_VI2B_VI3B:
case INPUT_SVIDEO_VI2C_VI3C:
case INPUT_SVIDEO_VI4A_VI1A:
case INPUT_SVIDEO_VI4A_VI1B:
case INPUT_SVIDEO_VI4A_VI1C:
case INPUT_SVIDEO_VI4A_VI3A:
case INPUT_SVIDEO_VI4A_VI3B:
case INPUT_SVIDEO_VI4A_VI3C:
lock_mask = STATUS_HORZ_SYNC_LOCK_BIT |
STATUS_VIRT_SYNC_LOCK_BIT;
break;
/*Need to add other interfaces*/
default:
return -EINVAL;
}
/* check whether signal is locked */
sync_lock_status = tvp514x_read_reg(sd, REG_STATUS1);
if (lock_mask != (sync_lock_status & lock_mask))
return 0; /* No input detected */
*std_id = decoder->std_list[current_std].standard.id;
v4l2_dbg(1, debug, sd, "Current STD: %s\n",
decoder->std_list[current_std].standard.name);
return 0;
}
/**
* tvp514x_s_std() - V4L2 decoder interface handler for s_std
* @sd: pointer to standard V4L2 sub-device structure
* @std_id: standard V4L2 v4l2_std_id ioctl enum
*
* If std_id is supported, sets the requested standard. Otherwise, returns
* -EINVAL
*/
static int tvp514x_s_std(struct v4l2_subdev *sd, v4l2_std_id std_id)
{
struct tvp514x_decoder *decoder = to_decoder(sd);
int err, i;
for (i = 0; i < decoder->num_stds; i++)
if (std_id & decoder->std_list[i].standard.id)
break;
if ((i == decoder->num_stds) || (i == STD_INVALID))
return -EINVAL;
err = tvp514x_write_reg(sd, REG_VIDEO_STD,
decoder->std_list[i].video_std);
if (err)
return err;
decoder->current_std = i;
decoder->tvp514x_regs[REG_VIDEO_STD].val =
decoder->std_list[i].video_std;
v4l2_dbg(1, debug, sd, "Standard set to: %s\n",
decoder->std_list[i].standard.name);
return 0;
}
/**
* tvp514x_s_routing() - V4L2 decoder interface handler for s_routing
* @sd: pointer to standard V4L2 sub-device structure
* @input: input selector for routing the signal
* @output: output selector for routing the signal
* @config: config value. Not used
*
* If index is valid, selects the requested input. Otherwise, returns -EINVAL if
* the input is not supported or there is no active signal present in the
* selected input.
*/
static int tvp514x_s_routing(struct v4l2_subdev *sd,
u32 input, u32 output, u32 config)
{
struct tvp514x_decoder *decoder = to_decoder(sd);
int err;
enum tvp514x_input input_sel;
enum tvp514x_output output_sel;
u8 sync_lock_status, lock_mask;
int try_count = LOCK_RETRY_COUNT;
if ((input >= INPUT_INVALID) ||
(output >= OUTPUT_INVALID))
/* Index out of bound */
return -EINVAL;
/*
* For the sequence streamon -> streamoff and again s_input
* it fails to lock the signal, since streamoff puts TVP514x
* into power off state which leads to failure in sub-sequent s_input.
*
* So power up the TVP514x device here, since it is important to lock
* the signal at this stage.
*/
if (!decoder->streaming)
tvp514x_s_stream(sd, 1);
input_sel = input;
output_sel = output;
err = tvp514x_write_reg(sd, REG_INPUT_SEL, input_sel);
if (err)
return err;
output_sel |= tvp514x_read_reg(sd,
REG_OUTPUT_FORMATTER1) & 0x7;
err = tvp514x_write_reg(sd, REG_OUTPUT_FORMATTER1,
output_sel);
if (err)
return err;
decoder->tvp514x_regs[REG_INPUT_SEL].val = input_sel;
decoder->tvp514x_regs[REG_OUTPUT_FORMATTER1].val = output_sel;
/* Clear status */
msleep(LOCK_RETRY_DELAY);
err =
tvp514x_write_reg(sd, REG_CLEAR_LOST_LOCK, 0x01);
if (err)
return err;
switch (input_sel) {
case INPUT_CVBS_VI1A:
case INPUT_CVBS_VI1B:
case INPUT_CVBS_VI1C:
case INPUT_CVBS_VI2A:
case INPUT_CVBS_VI2B:
case INPUT_CVBS_VI2C:
case INPUT_CVBS_VI3A:
case INPUT_CVBS_VI3B:
case INPUT_CVBS_VI3C:
case INPUT_CVBS_VI4A:
lock_mask = STATUS_CLR_SUBCAR_LOCK_BIT |
STATUS_HORZ_SYNC_LOCK_BIT |
STATUS_VIRT_SYNC_LOCK_BIT;
break;
case INPUT_SVIDEO_VI2A_VI1A:
case INPUT_SVIDEO_VI2B_VI1B:
case INPUT_SVIDEO_VI2C_VI1C:
case INPUT_SVIDEO_VI2A_VI3A:
case INPUT_SVIDEO_VI2B_VI3B:
case INPUT_SVIDEO_VI2C_VI3C:
case INPUT_SVIDEO_VI4A_VI1A:
case INPUT_SVIDEO_VI4A_VI1B:
case INPUT_SVIDEO_VI4A_VI1C:
case INPUT_SVIDEO_VI4A_VI3A:
case INPUT_SVIDEO_VI4A_VI3B:
case INPUT_SVIDEO_VI4A_VI3C:
lock_mask = STATUS_HORZ_SYNC_LOCK_BIT |
STATUS_VIRT_SYNC_LOCK_BIT;
break;
/* Need to add other interfaces*/
default:
return -EINVAL;
}
while (try_count-- > 0) {
/* Allow decoder to sync up with new input */
msleep(LOCK_RETRY_DELAY);
sync_lock_status = tvp514x_read_reg(sd,
REG_STATUS1);
if (lock_mask == (sync_lock_status & lock_mask))
/* Input detected */
break;
}
if (try_count < 0)
return -EINVAL;
decoder->input = input;
decoder->output = output;
v4l2_dbg(1, debug, sd, "Input set to: %d\n", input_sel);
return 0;
}
/**
* tvp514x_queryctrl() - V4L2 decoder interface handler for queryctrl
* @sd: pointer to standard V4L2 sub-device structure
* @qctrl: standard V4L2 v4l2_queryctrl structure
*
* If the requested control is supported, returns the control information.
* Otherwise, returns -EINVAL if the control is not supported.
*/
static int
tvp514x_queryctrl(struct v4l2_subdev *sd, struct v4l2_queryctrl *qctrl)
{
int err = -EINVAL;
if (qctrl == NULL)
return err;
switch (qctrl->id) {
case V4L2_CID_BRIGHTNESS:
/* Brightness supported is (0-255), */
err = v4l2_ctrl_query_fill(qctrl, 0, 255, 1, 128);
break;
case V4L2_CID_CONTRAST:
case V4L2_CID_SATURATION:
/**
* Saturation and Contrast supported is -
* Contrast: 0 - 255 (Default - 128)
* Saturation: 0 - 255 (Default - 128)
*/
err = v4l2_ctrl_query_fill(qctrl, 0, 255, 1, 128);
break;
case V4L2_CID_HUE:
/* Hue Supported is -
* Hue - -180 - +180 (Default - 0, Step - +180)
*/
err = v4l2_ctrl_query_fill(qctrl, -180, 180, 180, 0);
break;
case V4L2_CID_AUTOGAIN:
/**
* Auto Gain supported is -
* 0 - 1 (Default - 1)
*/
err = v4l2_ctrl_query_fill(qctrl, 0, 1, 1, 1);
break;
default:
v4l2_err(sd, "invalid control id %d\n", qctrl->id);
return err;
}
v4l2_dbg(1, debug, sd, "Query Control:%s: Min - %d, Max - %d, Def - %d\n",
qctrl->name, qctrl->minimum, qctrl->maximum,
qctrl->default_value);
return err;
}
/**
* tvp514x_g_ctrl() - V4L2 decoder interface handler for g_ctrl
* @sd: pointer to standard V4L2 sub-device structure
* @ctrl: pointer to v4l2_control structure
*
* If the requested control is supported, returns the control's current
* value from the decoder. Otherwise, returns -EINVAL if the control is not
* supported.
*/
static int
tvp514x_g_ctrl(struct v4l2_subdev *sd, struct v4l2_control *ctrl)
{
struct tvp514x_decoder *decoder = to_decoder(sd);
if (ctrl == NULL)
return -EINVAL;
switch (ctrl->id) {
case V4L2_CID_BRIGHTNESS:
ctrl->value = decoder->tvp514x_regs[REG_BRIGHTNESS].val;
break;
case V4L2_CID_CONTRAST:
ctrl->value = decoder->tvp514x_regs[REG_CONTRAST].val;
break;
case V4L2_CID_SATURATION:
ctrl->value = decoder->tvp514x_regs[REG_SATURATION].val;
break;
case V4L2_CID_HUE:
ctrl->value = decoder->tvp514x_regs[REG_HUE].val;
if (ctrl->value == 0x7F)
ctrl->value = 180;
else if (ctrl->value == 0x80)
ctrl->value = -180;
else
ctrl->value = 0;
break;
case V4L2_CID_AUTOGAIN:
ctrl->value = decoder->tvp514x_regs[REG_AFE_GAIN_CTRL].val;
if ((ctrl->value & 0x3) == 3)
ctrl->value = 1;
else
ctrl->value = 0;
break;
default:
v4l2_err(sd, "invalid control id %d\n", ctrl->id);
return -EINVAL;
}
v4l2_dbg(1, debug, sd, "Get Control: ID - %d - %d\n",
ctrl->id, ctrl->value);
return 0;
}
/**
* tvp514x_s_ctrl() - V4L2 decoder interface handler for s_ctrl
* @sd: pointer to standard V4L2 sub-device structure
* @ctrl: pointer to v4l2_control structure
*
* If the requested control is supported, sets the control's current
* value in HW. Otherwise, returns -EINVAL if the control is not supported.
*/
static int
tvp514x_s_ctrl(struct v4l2_subdev *sd, struct v4l2_control *ctrl)
{
struct tvp514x_decoder *decoder = to_decoder(sd);
int err = -EINVAL, value;
if (ctrl == NULL)
return err;
value = ctrl->value;
switch (ctrl->id) {
case V4L2_CID_BRIGHTNESS:
if (ctrl->value < 0 || ctrl->value > 255) {
v4l2_err(sd, "invalid brightness setting %d\n",
ctrl->value);
return -ERANGE;
}
err = tvp514x_write_reg(sd, REG_BRIGHTNESS,
value);
if (err)
return err;
decoder->tvp514x_regs[REG_BRIGHTNESS].val = value;
break;
case V4L2_CID_CONTRAST:
if (ctrl->value < 0 || ctrl->value > 255) {
v4l2_err(sd, "invalid contrast setting %d\n",
ctrl->value);
return -ERANGE;
}
err = tvp514x_write_reg(sd, REG_CONTRAST, value);
if (err)
return err;
decoder->tvp514x_regs[REG_CONTRAST].val = value;
break;
case V4L2_CID_SATURATION:
if (ctrl->value < 0 || ctrl->value > 255) {
v4l2_err(sd, "invalid saturation setting %d\n",
ctrl->value);
return -ERANGE;
}
err = tvp514x_write_reg(sd, REG_SATURATION, value);
if (err)
return err;
decoder->tvp514x_regs[REG_SATURATION].val = value;
break;
case V4L2_CID_HUE:
if (value == 180)
value = 0x7F;
else if (value == -180)
value = 0x80;
else if (value == 0)
value = 0;
else {
v4l2_err(sd, "invalid hue setting %d\n", ctrl->value);
return -ERANGE;
}
err = tvp514x_write_reg(sd, REG_HUE, value);
if (err)
return err;
decoder->tvp514x_regs[REG_HUE].val = value;
break;
case V4L2_CID_AUTOGAIN:
if (value == 1)
value = 0x0F;
else if (value == 0)
value = 0x0C;
else {
v4l2_err(sd, "invalid auto gain setting %d\n",
ctrl->value);
return -ERANGE;
}
err = tvp514x_write_reg(sd, REG_AFE_GAIN_CTRL, value);
if (err)
return err;
decoder->tvp514x_regs[REG_AFE_GAIN_CTRL].val = value;
break;
default:
v4l2_err(sd, "invalid control id %d\n", ctrl->id);
return err;
}
v4l2_dbg(1, debug, sd, "Set Control: ID - %d - %d\n",
ctrl->id, ctrl->value);
return err;
}
/**
* tvp514x_enum_fmt_cap() - V4L2 decoder interface handler for enum_fmt
* @sd: pointer to standard V4L2 sub-device structure
* @fmt: standard V4L2 VIDIOC_ENUM_FMT ioctl structure
*
* Implement the VIDIOC_ENUM_FMT ioctl to enumerate supported formats
*/
static int
tvp514x_enum_fmt_cap(struct v4l2_subdev *sd, struct v4l2_fmtdesc *fmt)
{
if (fmt == NULL || fmt->index)
return -EINVAL;
if (fmt->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
/* only capture is supported */
return -EINVAL;
/* only one format */
fmt->flags = 0;
strlcpy(fmt->description, "8-bit UYVY 4:2:2 Format",
sizeof(fmt->description));
fmt->pixelformat = V4L2_PIX_FMT_UYVY;
return 0;
}
/**
* tvp514x_fmt_cap() - V4L2 decoder interface handler for try/s/g_fmt
* @sd: pointer to standard V4L2 sub-device structure
* @f: pointer to standard V4L2 VIDIOC_TRY_FMT ioctl structure
*
* Implement the VIDIOC_TRY/S/G_FMT ioctl for the CAPTURE buffer type. This
* ioctl is used to negotiate the image capture size and pixel format.
*/
static int
tvp514x_fmt_cap(struct v4l2_subdev *sd, struct v4l2_format *f)
{
struct tvp514x_decoder *decoder = to_decoder(sd);
struct v4l2_pix_format *pix;
enum tvp514x_std current_std;
if (f == NULL)
return -EINVAL;
if (f->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
pix = &f->fmt.pix;
/* Calculate height and width based on current standard */
current_std = decoder->current_std;
pix->pixelformat = V4L2_PIX_FMT_UYVY;
pix->width = decoder->std_list[current_std].width;
pix->height = decoder->std_list[current_std].height;
pix->field = V4L2_FIELD_INTERLACED;
pix->bytesperline = pix->width * 2;
pix->sizeimage = pix->bytesperline * pix->height;
pix->colorspace = V4L2_COLORSPACE_SMPTE170M;
pix->priv = 0;
v4l2_dbg(1, debug, sd, "FMT: bytesperline - %d"
"Width - %d, Height - %d\n",
pix->bytesperline,
pix->width, pix->height);
return 0;
}
/**
* tvp514x_g_parm() - V4L2 decoder interface handler for g_parm
* @sd: pointer to standard V4L2 sub-device structure
* @a: pointer to standard V4L2 VIDIOC_G_PARM ioctl structure
*
* Returns the decoder's video CAPTURE parameters.
*/
static int
tvp514x_g_parm(struct v4l2_subdev *sd, struct v4l2_streamparm *a)
{
struct tvp514x_decoder *decoder = to_decoder(sd);
struct v4l2_captureparm *cparm;
enum tvp514x_std current_std;
if (a == NULL)
return -EINVAL;
if (a->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
/* only capture is supported */
return -EINVAL;
/* get the current standard */
current_std = decoder->current_std;
cparm = &a->parm.capture;
cparm->capability = V4L2_CAP_TIMEPERFRAME;
cparm->timeperframe =
decoder->std_list[current_std].standard.frameperiod;
return 0;
}
/**
* tvp514x_s_parm() - V4L2 decoder interface handler for s_parm
* @sd: pointer to standard V4L2 sub-device structure
* @a: pointer to standard V4L2 VIDIOC_S_PARM ioctl structure
*
* Configures the decoder to use the input parameters, if possible. If
* not possible, returns the appropriate error code.
*/
static int
tvp514x_s_parm(struct v4l2_subdev *sd, struct v4l2_streamparm *a)
{
struct tvp514x_decoder *decoder = to_decoder(sd);
struct v4l2_fract *timeperframe;
enum tvp514x_std current_std;
if (a == NULL)
return -EINVAL;
if (a->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
/* only capture is supported */
return -EINVAL;
timeperframe = &a->parm.capture.timeperframe;
/* get the current standard */
current_std = decoder->current_std;
*timeperframe =
decoder->std_list[current_std].standard.frameperiod;
return 0;
}
/**
* tvp514x_s_stream() - V4L2 decoder i/f handler for s_stream
* @sd: pointer to standard V4L2 sub-device structure
* @enable: streaming enable or disable
*
* Sets streaming to enable or disable, if possible.
*/
static int tvp514x_s_stream(struct v4l2_subdev *sd, int enable)
{
int err = 0;
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct tvp514x_decoder *decoder = to_decoder(sd);
if (decoder->streaming == enable)
return 0;
switch (enable) {
case 0:
{
/* Power Down Sequence */
err = tvp514x_write_reg(sd, REG_OPERATION_MODE, 0x01);
if (err) {
v4l2_err(sd, "Unable to turn off decoder\n");
return err;
}
decoder->streaming = enable;
break;
}
case 1:
{
struct tvp514x_reg *int_seq = (struct tvp514x_reg *)
client->driver->id_table->driver_data;
/* Power Up Sequence */
err = tvp514x_write_regs(sd, int_seq);
if (err) {
v4l2_err(sd, "Unable to turn on decoder\n");
return err;
}
/* Detect if not already detected */
err = tvp514x_detect(sd, decoder);
if (err) {
v4l2_err(sd, "Unable to detect decoder\n");
return err;
}
err = tvp514x_configure(sd, decoder);
if (err) {
v4l2_err(sd, "Unable to configure decoder\n");
return err;
}
decoder->streaming = enable;
break;
}
default:
err = -ENODEV;
break;
}
return err;
}
static const struct v4l2_subdev_core_ops tvp514x_core_ops = {
.queryctrl = tvp514x_queryctrl,
.g_ctrl = tvp514x_g_ctrl,
.s_ctrl = tvp514x_s_ctrl,
.s_std = tvp514x_s_std,
};
static const struct v4l2_subdev_video_ops tvp514x_video_ops = {
.s_routing = tvp514x_s_routing,
.querystd = tvp514x_querystd,
.enum_fmt = tvp514x_enum_fmt_cap,
.g_fmt = tvp514x_fmt_cap,
.try_fmt = tvp514x_fmt_cap,
.s_fmt = tvp514x_fmt_cap,
.g_parm = tvp514x_g_parm,
.s_parm = tvp514x_s_parm,
.s_stream = tvp514x_s_stream,
};
static const struct v4l2_subdev_ops tvp514x_ops = {
.core = &tvp514x_core_ops,
.video = &tvp514x_video_ops,
};
static struct tvp514x_decoder tvp514x_dev = {
.streaming = 0,
.current_std = STD_NTSC_MJ,
.std_list = tvp514x_std_list,
.num_stds = ARRAY_SIZE(tvp514x_std_list),
};
/**
* tvp514x_probe() - decoder driver i2c probe handler
* @client: i2c driver client device structure
* @id: i2c driver id table
*
* Register decoder as an i2c client device and V4L2
* device.
*/
static int
tvp514x_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
struct tvp514x_decoder *decoder;
struct v4l2_subdev *sd;
/* Check if the adapter supports the needed features */
if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -EIO;
if (!client->dev.platform_data) {
v4l2_err(client, "No platform data!!\n");
return -ENODEV;
}
decoder = kzalloc(sizeof(*decoder), GFP_KERNEL);
if (!decoder)
return -ENOMEM;
/* Initialize the tvp514x_decoder with default configuration */
*decoder = tvp514x_dev;
/* Copy default register configuration */
memcpy(decoder->tvp514x_regs, tvp514x_reg_list_default,
sizeof(tvp514x_reg_list_default));
/* Copy board specific information here */
decoder->pdata = client->dev.platform_data;
/**
* Fetch platform specific data, and configure the
* tvp514x_reg_list[] accordingly. Since this is one
* time configuration, no need to preserve.
*/
decoder->tvp514x_regs[REG_OUTPUT_FORMATTER2].val |=
(decoder->pdata->clk_polarity << 1);
decoder->tvp514x_regs[REG_SYNC_CONTROL].val |=
((decoder->pdata->hs_polarity << 2) |
(decoder->pdata->vs_polarity << 3));
/* Set default standard to auto */
decoder->tvp514x_regs[REG_VIDEO_STD].val =
VIDEO_STD_AUTO_SWITCH_BIT;
/* Register with V4L2 layer as slave device */
sd = &decoder->sd;
v4l2_i2c_subdev_init(sd, client, &tvp514x_ops);
v4l2_info(sd, "%s decoder driver registered !!\n", sd->name);
return 0;
}
/**
* tvp514x_remove() - decoder driver i2c remove handler
* @client: i2c driver client device structure
*
* Unregister decoder as an i2c client device and V4L2
* device. Complement of tvp514x_probe().
*/
static int tvp514x_remove(struct i2c_client *client)
{
struct v4l2_subdev *sd = i2c_get_clientdata(client);
struct tvp514x_decoder *decoder = to_decoder(sd);
v4l2_device_unregister_subdev(sd);
kfree(decoder);
return 0;
}
/* TVP5146 Init/Power on Sequence */
static const struct tvp514x_reg tvp5146_init_reg_seq[] = {
{TOK_WRITE, REG_VBUS_ADDRESS_ACCESS1, 0x02},
{TOK_WRITE, REG_VBUS_ADDRESS_ACCESS2, 0x00},
{TOK_WRITE, REG_VBUS_ADDRESS_ACCESS3, 0x80},
{TOK_WRITE, REG_VBUS_DATA_ACCESS_NO_VBUS_ADDR_INCR, 0x01},
{TOK_WRITE, REG_VBUS_ADDRESS_ACCESS1, 0x60},
{TOK_WRITE, REG_VBUS_ADDRESS_ACCESS2, 0x00},
{TOK_WRITE, REG_VBUS_ADDRESS_ACCESS3, 0xB0},
{TOK_WRITE, REG_VBUS_DATA_ACCESS_NO_VBUS_ADDR_INCR, 0x01},
{TOK_WRITE, REG_VBUS_DATA_ACCESS_NO_VBUS_ADDR_INCR, 0x00},
{TOK_WRITE, REG_OPERATION_MODE, 0x01},
{TOK_WRITE, REG_OPERATION_MODE, 0x00},
{TOK_TERM, 0, 0},
};
/* TVP5147 Init/Power on Sequence */
static const struct tvp514x_reg tvp5147_init_reg_seq[] = {
{TOK_WRITE, REG_VBUS_ADDRESS_ACCESS1, 0x02},
{TOK_WRITE, REG_VBUS_ADDRESS_ACCESS2, 0x00},
{TOK_WRITE, REG_VBUS_ADDRESS_ACCESS3, 0x80},
{TOK_WRITE, REG_VBUS_DATA_ACCESS_NO_VBUS_ADDR_INCR, 0x01},
{TOK_WRITE, REG_VBUS_ADDRESS_ACCESS1, 0x60},
{TOK_WRITE, REG_VBUS_ADDRESS_ACCESS2, 0x00},
{TOK_WRITE, REG_VBUS_ADDRESS_ACCESS3, 0xB0},
{TOK_WRITE, REG_VBUS_DATA_ACCESS_NO_VBUS_ADDR_INCR, 0x01},
{TOK_WRITE, REG_VBUS_ADDRESS_ACCESS1, 0x16},
{TOK_WRITE, REG_VBUS_ADDRESS_ACCESS2, 0x00},
{TOK_WRITE, REG_VBUS_ADDRESS_ACCESS3, 0xA0},
{TOK_WRITE, REG_VBUS_DATA_ACCESS_NO_VBUS_ADDR_INCR, 0x16},
{TOK_WRITE, REG_VBUS_ADDRESS_ACCESS1, 0x60},
{TOK_WRITE, REG_VBUS_ADDRESS_ACCESS2, 0x00},
{TOK_WRITE, REG_VBUS_ADDRESS_ACCESS3, 0xB0},
{TOK_WRITE, REG_VBUS_DATA_ACCESS_NO_VBUS_ADDR_INCR, 0x00},
{TOK_WRITE, REG_OPERATION_MODE, 0x01},
{TOK_WRITE, REG_OPERATION_MODE, 0x00},
{TOK_TERM, 0, 0},
};
/* TVP5146M2/TVP5147M1 Init/Power on Sequence */
static const struct tvp514x_reg tvp514xm_init_reg_seq[] = {
{TOK_WRITE, REG_OPERATION_MODE, 0x01},
{TOK_WRITE, REG_OPERATION_MODE, 0x00},
{TOK_TERM, 0, 0},
};
/**
* I2C Device Table -
*
* name - Name of the actual device/chip.
* driver_data - Driver data
*/
static const struct i2c_device_id tvp514x_id[] = {
{"tvp5146", (unsigned long)tvp5146_init_reg_seq},
{"tvp5146m2", (unsigned long)tvp514xm_init_reg_seq},
{"tvp5147", (unsigned long)tvp5147_init_reg_seq},
{"tvp5147m1", (unsigned long)tvp514xm_init_reg_seq},
{},
};
MODULE_DEVICE_TABLE(i2c, tvp514x_id);
static struct i2c_driver tvp514x_driver = {
.driver = {
.owner = THIS_MODULE,
.name = TVP514X_MODULE_NAME,
},
.probe = tvp514x_probe,
.remove = tvp514x_remove,
.id_table = tvp514x_id,
};
static int __init tvp514x_init(void)
{
return i2c_add_driver(&tvp514x_driver);
}
static void __exit tvp514x_exit(void)
{
i2c_del_driver(&tvp514x_driver);
}
module_init(tvp514x_init);
module_exit(tvp514x_exit);
| gpl-2.0 |
GustavoRD78/78Kernel-ZL-292 | drivers/net/wireless/ath/ath9k/xmit.c | 2692 | 65341 | /*
* Copyright (c) 2008-2011 Atheros Communications Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <linux/dma-mapping.h>
#include "ath9k.h"
#include "ar9003_mac.h"
#define BITS_PER_BYTE 8
#define OFDM_PLCP_BITS 22
#define HT_RC_2_STREAMS(_rc) ((((_rc) & 0x78) >> 3) + 1)
#define L_STF 8
#define L_LTF 8
#define L_SIG 4
#define HT_SIG 8
#define HT_STF 4
#define HT_LTF(_ns) (4 * (_ns))
#define SYMBOL_TIME(_ns) ((_ns) << 2) /* ns * 4 us */
#define SYMBOL_TIME_HALFGI(_ns) (((_ns) * 18 + 4) / 5) /* ns * 3.6 us */
#define NUM_SYMBOLS_PER_USEC(_usec) (_usec >> 2)
#define NUM_SYMBOLS_PER_USEC_HALFGI(_usec) (((_usec*5)-4)/18)
static u16 bits_per_symbol[][2] = {
/* 20MHz 40MHz */
{ 26, 54 }, /* 0: BPSK */
{ 52, 108 }, /* 1: QPSK 1/2 */
{ 78, 162 }, /* 2: QPSK 3/4 */
{ 104, 216 }, /* 3: 16-QAM 1/2 */
{ 156, 324 }, /* 4: 16-QAM 3/4 */
{ 208, 432 }, /* 5: 64-QAM 2/3 */
{ 234, 486 }, /* 6: 64-QAM 3/4 */
{ 260, 540 }, /* 7: 64-QAM 5/6 */
};
#define IS_HT_RATE(_rate) ((_rate) & 0x80)
static void ath_tx_send_normal(struct ath_softc *sc, struct ath_txq *txq,
struct ath_atx_tid *tid, struct sk_buff *skb);
static void ath_tx_complete(struct ath_softc *sc, struct sk_buff *skb,
int tx_flags, struct ath_txq *txq);
static void ath_tx_complete_buf(struct ath_softc *sc, struct ath_buf *bf,
struct ath_txq *txq, struct list_head *bf_q,
struct ath_tx_status *ts, int txok);
static void ath_tx_txqaddbuf(struct ath_softc *sc, struct ath_txq *txq,
struct list_head *head, bool internal);
static void ath_tx_rc_status(struct ath_softc *sc, struct ath_buf *bf,
struct ath_tx_status *ts, int nframes, int nbad,
int txok);
static void ath_tx_update_baw(struct ath_softc *sc, struct ath_atx_tid *tid,
int seqno);
static struct ath_buf *ath_tx_setup_buffer(struct ath_softc *sc,
struct ath_txq *txq,
struct ath_atx_tid *tid,
struct sk_buff *skb);
enum {
MCS_HT20,
MCS_HT20_SGI,
MCS_HT40,
MCS_HT40_SGI,
};
static int ath_max_4ms_framelen[4][32] = {
[MCS_HT20] = {
3212, 6432, 9648, 12864, 19300, 25736, 28952, 32172,
6424, 12852, 19280, 25708, 38568, 51424, 57852, 64280,
9628, 19260, 28896, 38528, 57792, 65532, 65532, 65532,
12828, 25656, 38488, 51320, 65532, 65532, 65532, 65532,
},
[MCS_HT20_SGI] = {
3572, 7144, 10720, 14296, 21444, 28596, 32172, 35744,
7140, 14284, 21428, 28568, 42856, 57144, 64288, 65532,
10700, 21408, 32112, 42816, 64228, 65532, 65532, 65532,
14256, 28516, 42780, 57040, 65532, 65532, 65532, 65532,
},
[MCS_HT40] = {
6680, 13360, 20044, 26724, 40092, 53456, 60140, 65532,
13348, 26700, 40052, 53400, 65532, 65532, 65532, 65532,
20004, 40008, 60016, 65532, 65532, 65532, 65532, 65532,
26644, 53292, 65532, 65532, 65532, 65532, 65532, 65532,
},
[MCS_HT40_SGI] = {
7420, 14844, 22272, 29696, 44544, 59396, 65532, 65532,
14832, 29668, 44504, 59340, 65532, 65532, 65532, 65532,
22232, 44464, 65532, 65532, 65532, 65532, 65532, 65532,
29616, 59232, 65532, 65532, 65532, 65532, 65532, 65532,
}
};
/*********************/
/* Aggregation logic */
/*********************/
static void ath_txq_lock(struct ath_softc *sc, struct ath_txq *txq)
__acquires(&txq->axq_lock)
{
spin_lock_bh(&txq->axq_lock);
}
static void ath_txq_unlock(struct ath_softc *sc, struct ath_txq *txq)
__releases(&txq->axq_lock)
{
spin_unlock_bh(&txq->axq_lock);
}
static void ath_txq_unlock_complete(struct ath_softc *sc, struct ath_txq *txq)
__releases(&txq->axq_lock)
{
struct sk_buff_head q;
struct sk_buff *skb;
__skb_queue_head_init(&q);
skb_queue_splice_init(&txq->complete_q, &q);
spin_unlock_bh(&txq->axq_lock);
while ((skb = __skb_dequeue(&q)))
ieee80211_tx_status(sc->hw, skb);
}
static void ath_tx_queue_tid(struct ath_txq *txq, struct ath_atx_tid *tid)
{
struct ath_atx_ac *ac = tid->ac;
if (tid->paused)
return;
if (tid->sched)
return;
tid->sched = true;
list_add_tail(&tid->list, &ac->tid_q);
if (ac->sched)
return;
ac->sched = true;
list_add_tail(&ac->list, &txq->axq_acq);
}
static void ath_tx_resume_tid(struct ath_softc *sc, struct ath_atx_tid *tid)
{
struct ath_txq *txq = tid->ac->txq;
WARN_ON(!tid->paused);
ath_txq_lock(sc, txq);
tid->paused = false;
if (skb_queue_empty(&tid->buf_q))
goto unlock;
ath_tx_queue_tid(txq, tid);
ath_txq_schedule(sc, txq);
unlock:
ath_txq_unlock_complete(sc, txq);
}
static struct ath_frame_info *get_frame_info(struct sk_buff *skb)
{
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
BUILD_BUG_ON(sizeof(struct ath_frame_info) >
sizeof(tx_info->rate_driver_data));
return (struct ath_frame_info *) &tx_info->rate_driver_data[0];
}
static void ath_send_bar(struct ath_atx_tid *tid, u16 seqno)
{
ieee80211_send_bar(tid->an->vif, tid->an->sta->addr, tid->tidno,
seqno << IEEE80211_SEQ_SEQ_SHIFT);
}
static void ath_tx_flush_tid(struct ath_softc *sc, struct ath_atx_tid *tid)
{
struct ath_txq *txq = tid->ac->txq;
struct sk_buff *skb;
struct ath_buf *bf;
struct list_head bf_head;
struct ath_tx_status ts;
struct ath_frame_info *fi;
bool sendbar = false;
INIT_LIST_HEAD(&bf_head);
memset(&ts, 0, sizeof(ts));
while ((skb = __skb_dequeue(&tid->buf_q))) {
fi = get_frame_info(skb);
bf = fi->bf;
if (bf && fi->retries) {
list_add_tail(&bf->list, &bf_head);
ath_tx_update_baw(sc, tid, bf->bf_state.seqno);
ath_tx_complete_buf(sc, bf, txq, &bf_head, &ts, 0);
sendbar = true;
} else {
ath_tx_send_normal(sc, txq, NULL, skb);
}
}
if (tid->baw_head == tid->baw_tail) {
tid->state &= ~AGGR_ADDBA_COMPLETE;
tid->state &= ~AGGR_CLEANUP;
}
if (sendbar) {
ath_txq_unlock(sc, txq);
ath_send_bar(tid, tid->seq_start);
ath_txq_lock(sc, txq);
}
}
static void ath_tx_update_baw(struct ath_softc *sc, struct ath_atx_tid *tid,
int seqno)
{
int index, cindex;
index = ATH_BA_INDEX(tid->seq_start, seqno);
cindex = (tid->baw_head + index) & (ATH_TID_MAX_BUFS - 1);
__clear_bit(cindex, tid->tx_buf);
while (tid->baw_head != tid->baw_tail && !test_bit(tid->baw_head, tid->tx_buf)) {
INCR(tid->seq_start, IEEE80211_SEQ_MAX);
INCR(tid->baw_head, ATH_TID_MAX_BUFS);
if (tid->bar_index >= 0)
tid->bar_index--;
}
}
static void ath_tx_addto_baw(struct ath_softc *sc, struct ath_atx_tid *tid,
u16 seqno)
{
int index, cindex;
index = ATH_BA_INDEX(tid->seq_start, seqno);
cindex = (tid->baw_head + index) & (ATH_TID_MAX_BUFS - 1);
__set_bit(cindex, tid->tx_buf);
if (index >= ((tid->baw_tail - tid->baw_head) &
(ATH_TID_MAX_BUFS - 1))) {
tid->baw_tail = cindex;
INCR(tid->baw_tail, ATH_TID_MAX_BUFS);
}
}
/*
* TODO: For frame(s) that are in the retry state, we will reuse the
* sequence number(s) without setting the retry bit. The
* alternative is to give up on these and BAR the receiver's window
* forward.
*/
static void ath_tid_drain(struct ath_softc *sc, struct ath_txq *txq,
struct ath_atx_tid *tid)
{
struct sk_buff *skb;
struct ath_buf *bf;
struct list_head bf_head;
struct ath_tx_status ts;
struct ath_frame_info *fi;
memset(&ts, 0, sizeof(ts));
INIT_LIST_HEAD(&bf_head);
while ((skb = __skb_dequeue(&tid->buf_q))) {
fi = get_frame_info(skb);
bf = fi->bf;
if (!bf) {
ath_tx_complete(sc, skb, ATH_TX_ERROR, txq);
continue;
}
list_add_tail(&bf->list, &bf_head);
if (fi->retries)
ath_tx_update_baw(sc, tid, bf->bf_state.seqno);
ath_tx_complete_buf(sc, bf, txq, &bf_head, &ts, 0);
}
tid->seq_next = tid->seq_start;
tid->baw_tail = tid->baw_head;
tid->bar_index = -1;
}
static void ath_tx_set_retry(struct ath_softc *sc, struct ath_txq *txq,
struct sk_buff *skb, int count)
{
struct ath_frame_info *fi = get_frame_info(skb);
struct ath_buf *bf = fi->bf;
struct ieee80211_hdr *hdr;
int prev = fi->retries;
TX_STAT_INC(txq->axq_qnum, a_retries);
fi->retries += count;
if (prev > 0)
return;
hdr = (struct ieee80211_hdr *)skb->data;
hdr->frame_control |= cpu_to_le16(IEEE80211_FCTL_RETRY);
dma_sync_single_for_device(sc->dev, bf->bf_buf_addr,
sizeof(*hdr), DMA_TO_DEVICE);
}
static struct ath_buf *ath_tx_get_buffer(struct ath_softc *sc)
{
struct ath_buf *bf = NULL;
spin_lock_bh(&sc->tx.txbuflock);
if (unlikely(list_empty(&sc->tx.txbuf))) {
spin_unlock_bh(&sc->tx.txbuflock);
return NULL;
}
bf = list_first_entry(&sc->tx.txbuf, struct ath_buf, list);
list_del(&bf->list);
spin_unlock_bh(&sc->tx.txbuflock);
return bf;
}
static void ath_tx_return_buffer(struct ath_softc *sc, struct ath_buf *bf)
{
spin_lock_bh(&sc->tx.txbuflock);
list_add_tail(&bf->list, &sc->tx.txbuf);
spin_unlock_bh(&sc->tx.txbuflock);
}
static struct ath_buf* ath_clone_txbuf(struct ath_softc *sc, struct ath_buf *bf)
{
struct ath_buf *tbf;
tbf = ath_tx_get_buffer(sc);
if (WARN_ON(!tbf))
return NULL;
ATH_TXBUF_RESET(tbf);
tbf->bf_mpdu = bf->bf_mpdu;
tbf->bf_buf_addr = bf->bf_buf_addr;
memcpy(tbf->bf_desc, bf->bf_desc, sc->sc_ah->caps.tx_desc_len);
tbf->bf_state = bf->bf_state;
return tbf;
}
static void ath_tx_count_frames(struct ath_softc *sc, struct ath_buf *bf,
struct ath_tx_status *ts, int txok,
int *nframes, int *nbad)
{
struct ath_frame_info *fi;
u16 seq_st = 0;
u32 ba[WME_BA_BMP_SIZE >> 5];
int ba_index;
int isaggr = 0;
*nbad = 0;
*nframes = 0;
isaggr = bf_isaggr(bf);
if (isaggr) {
seq_st = ts->ts_seqnum;
memcpy(ba, &ts->ba_low, WME_BA_BMP_SIZE >> 3);
}
while (bf) {
fi = get_frame_info(bf->bf_mpdu);
ba_index = ATH_BA_INDEX(seq_st, bf->bf_state.seqno);
(*nframes)++;
if (!txok || (isaggr && !ATH_BA_ISSET(ba, ba_index)))
(*nbad)++;
bf = bf->bf_next;
}
}
static void ath_tx_complete_aggr(struct ath_softc *sc, struct ath_txq *txq,
struct ath_buf *bf, struct list_head *bf_q,
struct ath_tx_status *ts, int txok, bool retry)
{
struct ath_node *an = NULL;
struct sk_buff *skb;
struct ieee80211_sta *sta;
struct ieee80211_hw *hw = sc->hw;
struct ieee80211_hdr *hdr;
struct ieee80211_tx_info *tx_info;
struct ath_atx_tid *tid = NULL;
struct ath_buf *bf_next, *bf_last = bf->bf_lastbf;
struct list_head bf_head;
struct sk_buff_head bf_pending;
u16 seq_st = 0, acked_cnt = 0, txfail_cnt = 0, seq_first;
u32 ba[WME_BA_BMP_SIZE >> 5];
int isaggr, txfail, txpending, sendbar = 0, needreset = 0, nbad = 0;
bool rc_update = true;
struct ieee80211_tx_rate rates[4];
struct ath_frame_info *fi;
int nframes;
u8 tidno;
bool flush = !!(ts->ts_status & ATH9K_TX_FLUSH);
int i, retries;
int bar_index = -1;
skb = bf->bf_mpdu;
hdr = (struct ieee80211_hdr *)skb->data;
tx_info = IEEE80211_SKB_CB(skb);
memcpy(rates, tx_info->control.rates, sizeof(rates));
retries = ts->ts_longretry + 1;
for (i = 0; i < ts->ts_rateindex; i++)
retries += rates[i].count;
rcu_read_lock();
sta = ieee80211_find_sta_by_ifaddr(hw, hdr->addr1, hdr->addr2);
if (!sta) {
rcu_read_unlock();
INIT_LIST_HEAD(&bf_head);
while (bf) {
bf_next = bf->bf_next;
if (!bf->bf_stale || bf_next != NULL)
list_move_tail(&bf->list, &bf_head);
ath_tx_complete_buf(sc, bf, txq, &bf_head, ts, 0);
bf = bf_next;
}
return;
}
an = (struct ath_node *)sta->drv_priv;
tidno = ieee80211_get_qos_ctl(hdr)[0] & IEEE80211_QOS_CTL_TID_MASK;
tid = ATH_AN_2_TID(an, tidno);
seq_first = tid->seq_start;
/*
* The hardware occasionally sends a tx status for the wrong TID.
* In this case, the BA status cannot be considered valid and all
* subframes need to be retransmitted
*/
if (tidno != ts->tid)
txok = false;
isaggr = bf_isaggr(bf);
memset(ba, 0, WME_BA_BMP_SIZE >> 3);
if (isaggr && txok) {
if (ts->ts_flags & ATH9K_TX_BA) {
seq_st = ts->ts_seqnum;
memcpy(ba, &ts->ba_low, WME_BA_BMP_SIZE >> 3);
} else {
/*
* AR5416 can become deaf/mute when BA
* issue happens. Chip needs to be reset.
* But AP code may have sychronization issues
* when perform internal reset in this routine.
* Only enable reset in STA mode for now.
*/
if (sc->sc_ah->opmode == NL80211_IFTYPE_STATION)
needreset = 1;
}
}
__skb_queue_head_init(&bf_pending);
ath_tx_count_frames(sc, bf, ts, txok, &nframes, &nbad);
while (bf) {
u16 seqno = bf->bf_state.seqno;
txfail = txpending = sendbar = 0;
bf_next = bf->bf_next;
skb = bf->bf_mpdu;
tx_info = IEEE80211_SKB_CB(skb);
fi = get_frame_info(skb);
if (ATH_BA_ISSET(ba, ATH_BA_INDEX(seq_st, seqno))) {
/* transmit completion, subframe is
* acked by block ack */
acked_cnt++;
} else if (!isaggr && txok) {
/* transmit completion */
acked_cnt++;
} else if ((tid->state & AGGR_CLEANUP) || !retry) {
/*
* cleanup in progress, just fail
* the un-acked sub-frames
*/
txfail = 1;
} else if (flush) {
txpending = 1;
} else if (fi->retries < ATH_MAX_SW_RETRIES) {
if (txok || !an->sleeping)
ath_tx_set_retry(sc, txq, bf->bf_mpdu,
retries);
txpending = 1;
} else {
txfail = 1;
txfail_cnt++;
bar_index = max_t(int, bar_index,
ATH_BA_INDEX(seq_first, seqno));
}
/*
* Make sure the last desc is reclaimed if it
* not a holding desc.
*/
INIT_LIST_HEAD(&bf_head);
if ((sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_EDMA) ||
bf_next != NULL || !bf_last->bf_stale)
list_move_tail(&bf->list, &bf_head);
if (!txpending || (tid->state & AGGR_CLEANUP)) {
/*
* complete the acked-ones/xretried ones; update
* block-ack window
*/
ath_tx_update_baw(sc, tid, seqno);
if (rc_update && (acked_cnt == 1 || txfail_cnt == 1)) {
memcpy(tx_info->control.rates, rates, sizeof(rates));
ath_tx_rc_status(sc, bf, ts, nframes, nbad, txok);
rc_update = false;
}
ath_tx_complete_buf(sc, bf, txq, &bf_head, ts,
!txfail);
} else {
/* retry the un-acked ones */
if (!(sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_EDMA) &&
bf->bf_next == NULL && bf_last->bf_stale) {
struct ath_buf *tbf;
tbf = ath_clone_txbuf(sc, bf_last);
/*
* Update tx baw and complete the
* frame with failed status if we
* run out of tx buf.
*/
if (!tbf) {
ath_tx_update_baw(sc, tid, seqno);
ath_tx_complete_buf(sc, bf, txq,
&bf_head, ts, 0);
bar_index = max_t(int, bar_index,
ATH_BA_INDEX(seq_first, seqno));
break;
}
fi->bf = tbf;
}
/*
* Put this buffer to the temporary pending
* queue to retain ordering
*/
__skb_queue_tail(&bf_pending, skb);
}
bf = bf_next;
}
/* prepend un-acked frames to the beginning of the pending frame queue */
if (!skb_queue_empty(&bf_pending)) {
if (an->sleeping)
ieee80211_sta_set_buffered(sta, tid->tidno, true);
skb_queue_splice(&bf_pending, &tid->buf_q);
if (!an->sleeping) {
ath_tx_queue_tid(txq, tid);
if (ts->ts_status & ATH9K_TXERR_FILT)
tid->ac->clear_ps_filter = true;
}
}
if (bar_index >= 0) {
u16 bar_seq = ATH_BA_INDEX2SEQ(seq_first, bar_index);
if (BAW_WITHIN(tid->seq_start, tid->baw_size, bar_seq))
tid->bar_index = ATH_BA_INDEX(tid->seq_start, bar_seq);
ath_txq_unlock(sc, txq);
ath_send_bar(tid, ATH_BA_INDEX2SEQ(seq_first, bar_index + 1));
ath_txq_lock(sc, txq);
}
if (tid->state & AGGR_CLEANUP)
ath_tx_flush_tid(sc, tid);
rcu_read_unlock();
if (needreset) {
RESET_STAT_INC(sc, RESET_TYPE_TX_ERROR);
ieee80211_queue_work(sc->hw, &sc->hw_reset_work);
}
}
static bool ath_lookup_legacy(struct ath_buf *bf)
{
struct sk_buff *skb;
struct ieee80211_tx_info *tx_info;
struct ieee80211_tx_rate *rates;
int i;
skb = bf->bf_mpdu;
tx_info = IEEE80211_SKB_CB(skb);
rates = tx_info->control.rates;
for (i = 0; i < 4; i++) {
if (!rates[i].count || rates[i].idx < 0)
break;
if (!(rates[i].flags & IEEE80211_TX_RC_MCS))
return true;
}
return false;
}
static u32 ath_lookup_rate(struct ath_softc *sc, struct ath_buf *bf,
struct ath_atx_tid *tid)
{
struct sk_buff *skb;
struct ieee80211_tx_info *tx_info;
struct ieee80211_tx_rate *rates;
u32 max_4ms_framelen, frmlen;
u16 aggr_limit, bt_aggr_limit, legacy = 0;
int i;
skb = bf->bf_mpdu;
tx_info = IEEE80211_SKB_CB(skb);
rates = tx_info->control.rates;
/*
* Find the lowest frame length among the rate series that will have a
* 4ms transmit duration.
* TODO - TXOP limit needs to be considered.
*/
max_4ms_framelen = ATH_AMPDU_LIMIT_MAX;
for (i = 0; i < 4; i++) {
int modeidx;
if (!rates[i].count)
continue;
if (!(rates[i].flags & IEEE80211_TX_RC_MCS)) {
legacy = 1;
break;
}
if (rates[i].flags & IEEE80211_TX_RC_40_MHZ_WIDTH)
modeidx = MCS_HT40;
else
modeidx = MCS_HT20;
if (rates[i].flags & IEEE80211_TX_RC_SHORT_GI)
modeidx++;
frmlen = ath_max_4ms_framelen[modeidx][rates[i].idx];
max_4ms_framelen = min(max_4ms_framelen, frmlen);
}
/*
* limit aggregate size by the minimum rate if rate selected is
* not a probe rate, if rate selected is a probe rate then
* avoid aggregation of this packet.
*/
if (tx_info->flags & IEEE80211_TX_CTL_RATE_CTRL_PROBE || legacy)
return 0;
aggr_limit = min(max_4ms_framelen, (u32)ATH_AMPDU_LIMIT_MAX);
/*
* Override the default aggregation limit for BTCOEX.
*/
bt_aggr_limit = ath9k_btcoex_aggr_limit(sc, max_4ms_framelen);
if (bt_aggr_limit)
aggr_limit = bt_aggr_limit;
/*
* h/w can accept aggregates up to 16 bit lengths (65535).
* The IE, however can hold up to 65536, which shows up here
* as zero. Ignore 65536 since we are constrained by hw.
*/
if (tid->an->maxampdu)
aggr_limit = min(aggr_limit, tid->an->maxampdu);
return aggr_limit;
}
/*
* Returns the number of delimiters to be added to
* meet the minimum required mpdudensity.
*/
static int ath_compute_num_delims(struct ath_softc *sc, struct ath_atx_tid *tid,
struct ath_buf *bf, u16 frmlen,
bool first_subfrm)
{
#define FIRST_DESC_NDELIMS 60
struct sk_buff *skb = bf->bf_mpdu;
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
u32 nsymbits, nsymbols;
u16 minlen;
u8 flags, rix;
int width, streams, half_gi, ndelim, mindelim;
struct ath_frame_info *fi = get_frame_info(bf->bf_mpdu);
/* Select standard number of delimiters based on frame length alone */
ndelim = ATH_AGGR_GET_NDELIM(frmlen);
/*
* If encryption enabled, hardware requires some more padding between
* subframes.
* TODO - this could be improved to be dependent on the rate.
* The hardware can keep up at lower rates, but not higher rates
*/
if ((fi->keyix != ATH9K_TXKEYIX_INVALID) &&
!(sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_EDMA))
ndelim += ATH_AGGR_ENCRYPTDELIM;
/*
* Add delimiter when using RTS/CTS with aggregation
* and non enterprise AR9003 card
*/
if (first_subfrm && !AR_SREV_9580_10_OR_LATER(sc->sc_ah) &&
(sc->sc_ah->ent_mode & AR_ENT_OTP_MIN_PKT_SIZE_DISABLE))
ndelim = max(ndelim, FIRST_DESC_NDELIMS);
/*
* Convert desired mpdu density from microeconds to bytes based
* on highest rate in rate series (i.e. first rate) to determine
* required minimum length for subframe. Take into account
* whether high rate is 20 or 40Mhz and half or full GI.
*
* If there is no mpdu density restriction, no further calculation
* is needed.
*/
if (tid->an->mpdudensity == 0)
return ndelim;
rix = tx_info->control.rates[0].idx;
flags = tx_info->control.rates[0].flags;
width = (flags & IEEE80211_TX_RC_40_MHZ_WIDTH) ? 1 : 0;
half_gi = (flags & IEEE80211_TX_RC_SHORT_GI) ? 1 : 0;
if (half_gi)
nsymbols = NUM_SYMBOLS_PER_USEC_HALFGI(tid->an->mpdudensity);
else
nsymbols = NUM_SYMBOLS_PER_USEC(tid->an->mpdudensity);
if (nsymbols == 0)
nsymbols = 1;
streams = HT_RC_2_STREAMS(rix);
nsymbits = bits_per_symbol[rix % 8][width] * streams;
minlen = (nsymbols * nsymbits) / BITS_PER_BYTE;
if (frmlen < minlen) {
mindelim = (minlen - frmlen) / ATH_AGGR_DELIM_SZ;
ndelim = max(mindelim, ndelim);
}
return ndelim;
}
static enum ATH_AGGR_STATUS ath_tx_form_aggr(struct ath_softc *sc,
struct ath_txq *txq,
struct ath_atx_tid *tid,
struct list_head *bf_q,
int *aggr_len)
{
#define PADBYTES(_len) ((4 - ((_len) % 4)) % 4)
struct ath_buf *bf, *bf_first = NULL, *bf_prev = NULL;
int rl = 0, nframes = 0, ndelim, prev_al = 0;
u16 aggr_limit = 0, al = 0, bpad = 0,
al_delta, h_baw = tid->baw_size / 2;
enum ATH_AGGR_STATUS status = ATH_AGGR_DONE;
struct ieee80211_tx_info *tx_info;
struct ath_frame_info *fi;
struct sk_buff *skb;
u16 seqno;
do {
skb = skb_peek(&tid->buf_q);
fi = get_frame_info(skb);
bf = fi->bf;
if (!fi->bf)
bf = ath_tx_setup_buffer(sc, txq, tid, skb);
if (!bf)
continue;
bf->bf_state.bf_type = BUF_AMPDU | BUF_AGGR;
seqno = bf->bf_state.seqno;
/* do not step over block-ack window */
if (!BAW_WITHIN(tid->seq_start, tid->baw_size, seqno)) {
status = ATH_AGGR_BAW_CLOSED;
break;
}
if (tid->bar_index > ATH_BA_INDEX(tid->seq_start, seqno)) {
struct ath_tx_status ts = {};
struct list_head bf_head;
INIT_LIST_HEAD(&bf_head);
list_add(&bf->list, &bf_head);
__skb_unlink(skb, &tid->buf_q);
ath_tx_update_baw(sc, tid, seqno);
ath_tx_complete_buf(sc, bf, txq, &bf_head, &ts, 0);
continue;
}
if (!bf_first)
bf_first = bf;
if (!rl) {
aggr_limit = ath_lookup_rate(sc, bf, tid);
rl = 1;
}
/* do not exceed aggregation limit */
al_delta = ATH_AGGR_DELIM_SZ + fi->framelen;
if (nframes &&
((aggr_limit < (al + bpad + al_delta + prev_al)) ||
ath_lookup_legacy(bf))) {
status = ATH_AGGR_LIMITED;
break;
}
tx_info = IEEE80211_SKB_CB(bf->bf_mpdu);
if (nframes && (tx_info->flags & IEEE80211_TX_CTL_RATE_CTRL_PROBE))
break;
/* do not exceed subframe limit */
if (nframes >= min((int)h_baw, ATH_AMPDU_SUBFRAME_DEFAULT)) {
status = ATH_AGGR_LIMITED;
break;
}
/* add padding for previous frame to aggregation length */
al += bpad + al_delta;
/*
* Get the delimiters needed to meet the MPDU
* density for this node.
*/
ndelim = ath_compute_num_delims(sc, tid, bf_first, fi->framelen,
!nframes);
bpad = PADBYTES(al_delta) + (ndelim << 2);
nframes++;
bf->bf_next = NULL;
/* link buffers of this frame to the aggregate */
if (!fi->retries)
ath_tx_addto_baw(sc, tid, seqno);
bf->bf_state.ndelim = ndelim;
__skb_unlink(skb, &tid->buf_q);
list_add_tail(&bf->list, bf_q);
if (bf_prev)
bf_prev->bf_next = bf;
bf_prev = bf;
} while (!skb_queue_empty(&tid->buf_q));
*aggr_len = al;
return status;
#undef PADBYTES
}
/*
* rix - rate index
* pktlen - total bytes (delims + data + fcs + pads + pad delims)
* width - 0 for 20 MHz, 1 for 40 MHz
* half_gi - to use 4us v/s 3.6 us for symbol time
*/
static u32 ath_pkt_duration(struct ath_softc *sc, u8 rix, int pktlen,
int width, int half_gi, bool shortPreamble)
{
u32 nbits, nsymbits, duration, nsymbols;
int streams;
/* find number of symbols: PLCP + data */
streams = HT_RC_2_STREAMS(rix);
nbits = (pktlen << 3) + OFDM_PLCP_BITS;
nsymbits = bits_per_symbol[rix % 8][width] * streams;
nsymbols = (nbits + nsymbits - 1) / nsymbits;
if (!half_gi)
duration = SYMBOL_TIME(nsymbols);
else
duration = SYMBOL_TIME_HALFGI(nsymbols);
/* addup duration for legacy/ht training and signal fields */
duration += L_STF + L_LTF + L_SIG + HT_SIG + HT_STF + HT_LTF(streams);
return duration;
}
static void ath_buf_set_rate(struct ath_softc *sc, struct ath_buf *bf,
struct ath_tx_info *info, int len)
{
struct ath_hw *ah = sc->sc_ah;
struct sk_buff *skb;
struct ieee80211_tx_info *tx_info;
struct ieee80211_tx_rate *rates;
const struct ieee80211_rate *rate;
struct ieee80211_hdr *hdr;
int i;
u8 rix = 0;
skb = bf->bf_mpdu;
tx_info = IEEE80211_SKB_CB(skb);
rates = tx_info->control.rates;
hdr = (struct ieee80211_hdr *)skb->data;
/* set dur_update_en for l-sig computation except for PS-Poll frames */
info->dur_update = !ieee80211_is_pspoll(hdr->frame_control);
/*
* We check if Short Preamble is needed for the CTS rate by
* checking the BSS's global flag.
* But for the rate series, IEEE80211_TX_RC_USE_SHORT_PREAMBLE is used.
*/
rate = ieee80211_get_rts_cts_rate(sc->hw, tx_info);
info->rtscts_rate = rate->hw_value;
if (tx_info->control.vif &&
tx_info->control.vif->bss_conf.use_short_preamble)
info->rtscts_rate |= rate->hw_value_short;
for (i = 0; i < 4; i++) {
bool is_40, is_sgi, is_sp;
int phy;
if (!rates[i].count || (rates[i].idx < 0))
continue;
rix = rates[i].idx;
info->rates[i].Tries = rates[i].count;
if (rates[i].flags & IEEE80211_TX_RC_USE_RTS_CTS) {
info->rates[i].RateFlags |= ATH9K_RATESERIES_RTS_CTS;
info->flags |= ATH9K_TXDESC_RTSENA;
} else if (rates[i].flags & IEEE80211_TX_RC_USE_CTS_PROTECT) {
info->rates[i].RateFlags |= ATH9K_RATESERIES_RTS_CTS;
info->flags |= ATH9K_TXDESC_CTSENA;
}
if (rates[i].flags & IEEE80211_TX_RC_40_MHZ_WIDTH)
info->rates[i].RateFlags |= ATH9K_RATESERIES_2040;
if (rates[i].flags & IEEE80211_TX_RC_SHORT_GI)
info->rates[i].RateFlags |= ATH9K_RATESERIES_HALFGI;
is_sgi = !!(rates[i].flags & IEEE80211_TX_RC_SHORT_GI);
is_40 = !!(rates[i].flags & IEEE80211_TX_RC_40_MHZ_WIDTH);
is_sp = !!(rates[i].flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE);
if (rates[i].flags & IEEE80211_TX_RC_MCS) {
/* MCS rates */
info->rates[i].Rate = rix | 0x80;
info->rates[i].ChSel = ath_txchainmask_reduction(sc,
ah->txchainmask, info->rates[i].Rate);
info->rates[i].PktDuration = ath_pkt_duration(sc, rix, len,
is_40, is_sgi, is_sp);
if (rix < 8 && (tx_info->flags & IEEE80211_TX_CTL_STBC))
info->rates[i].RateFlags |= ATH9K_RATESERIES_STBC;
continue;
}
/* legacy rates */
if ((tx_info->band == IEEE80211_BAND_2GHZ) &&
!(rate->flags & IEEE80211_RATE_ERP_G))
phy = WLAN_RC_PHY_CCK;
else
phy = WLAN_RC_PHY_OFDM;
rate = &sc->sbands[tx_info->band].bitrates[rates[i].idx];
info->rates[i].Rate = rate->hw_value;
if (rate->hw_value_short) {
if (rates[i].flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE)
info->rates[i].Rate |= rate->hw_value_short;
} else {
is_sp = false;
}
if (bf->bf_state.bfs_paprd)
info->rates[i].ChSel = ah->txchainmask;
else
info->rates[i].ChSel = ath_txchainmask_reduction(sc,
ah->txchainmask, info->rates[i].Rate);
info->rates[i].PktDuration = ath9k_hw_computetxtime(sc->sc_ah,
phy, rate->bitrate * 100, len, rix, is_sp);
}
/* For AR5416 - RTS cannot be followed by a frame larger than 8K */
if (bf_isaggr(bf) && (len > sc->sc_ah->caps.rts_aggr_limit))
info->flags &= ~ATH9K_TXDESC_RTSENA;
/* ATH9K_TXDESC_RTSENA and ATH9K_TXDESC_CTSENA are mutually exclusive. */
if (info->flags & ATH9K_TXDESC_RTSENA)
info->flags &= ~ATH9K_TXDESC_CTSENA;
}
static enum ath9k_pkt_type get_hw_packet_type(struct sk_buff *skb)
{
struct ieee80211_hdr *hdr;
enum ath9k_pkt_type htype;
__le16 fc;
hdr = (struct ieee80211_hdr *)skb->data;
fc = hdr->frame_control;
if (ieee80211_is_beacon(fc))
htype = ATH9K_PKT_TYPE_BEACON;
else if (ieee80211_is_probe_resp(fc))
htype = ATH9K_PKT_TYPE_PROBE_RESP;
else if (ieee80211_is_atim(fc))
htype = ATH9K_PKT_TYPE_ATIM;
else if (ieee80211_is_pspoll(fc))
htype = ATH9K_PKT_TYPE_PSPOLL;
else
htype = ATH9K_PKT_TYPE_NORMAL;
return htype;
}
static void ath_tx_fill_desc(struct ath_softc *sc, struct ath_buf *bf,
struct ath_txq *txq, int len)
{
struct ath_hw *ah = sc->sc_ah;
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(bf->bf_mpdu);
struct ath_buf *bf_first = bf;
struct ath_tx_info info;
bool aggr = !!(bf->bf_state.bf_type & BUF_AGGR);
memset(&info, 0, sizeof(info));
info.is_first = true;
info.is_last = true;
info.txpower = MAX_RATE_POWER;
info.qcu = txq->axq_qnum;
info.flags = ATH9K_TXDESC_INTREQ;
if (tx_info->flags & IEEE80211_TX_CTL_NO_ACK)
info.flags |= ATH9K_TXDESC_NOACK;
if (tx_info->flags & IEEE80211_TX_CTL_LDPC)
info.flags |= ATH9K_TXDESC_LDPC;
ath_buf_set_rate(sc, bf, &info, len);
if (tx_info->flags & IEEE80211_TX_CTL_CLEAR_PS_FILT)
info.flags |= ATH9K_TXDESC_CLRDMASK;
if (bf->bf_state.bfs_paprd)
info.flags |= (u32) bf->bf_state.bfs_paprd << ATH9K_TXDESC_PAPRD_S;
while (bf) {
struct sk_buff *skb = bf->bf_mpdu;
struct ath_frame_info *fi = get_frame_info(skb);
info.type = get_hw_packet_type(skb);
if (bf->bf_next)
info.link = bf->bf_next->bf_daddr;
else
info.link = 0;
info.buf_addr[0] = bf->bf_buf_addr;
info.buf_len[0] = skb->len;
info.pkt_len = fi->framelen;
info.keyix = fi->keyix;
info.keytype = fi->keytype;
if (aggr) {
if (bf == bf_first)
info.aggr = AGGR_BUF_FIRST;
else if (!bf->bf_next)
info.aggr = AGGR_BUF_LAST;
else
info.aggr = AGGR_BUF_MIDDLE;
info.ndelim = bf->bf_state.ndelim;
info.aggr_len = len;
}
ath9k_hw_set_txdesc(ah, bf->bf_desc, &info);
bf = bf->bf_next;
}
}
static void ath_tx_sched_aggr(struct ath_softc *sc, struct ath_txq *txq,
struct ath_atx_tid *tid)
{
struct ath_buf *bf;
enum ATH_AGGR_STATUS status;
struct ieee80211_tx_info *tx_info;
struct list_head bf_q;
int aggr_len;
do {
if (skb_queue_empty(&tid->buf_q))
return;
INIT_LIST_HEAD(&bf_q);
status = ath_tx_form_aggr(sc, txq, tid, &bf_q, &aggr_len);
/*
* no frames picked up to be aggregated;
* block-ack window is not open.
*/
if (list_empty(&bf_q))
break;
bf = list_first_entry(&bf_q, struct ath_buf, list);
bf->bf_lastbf = list_entry(bf_q.prev, struct ath_buf, list);
tx_info = IEEE80211_SKB_CB(bf->bf_mpdu);
if (tid->ac->clear_ps_filter) {
tid->ac->clear_ps_filter = false;
tx_info->flags |= IEEE80211_TX_CTL_CLEAR_PS_FILT;
} else {
tx_info->flags &= ~IEEE80211_TX_CTL_CLEAR_PS_FILT;
}
/* if only one frame, send as non-aggregate */
if (bf == bf->bf_lastbf) {
aggr_len = get_frame_info(bf->bf_mpdu)->framelen;
bf->bf_state.bf_type = BUF_AMPDU;
} else {
TX_STAT_INC(txq->axq_qnum, a_aggr);
}
ath_tx_fill_desc(sc, bf, txq, aggr_len);
ath_tx_txqaddbuf(sc, txq, &bf_q, false);
} while (txq->axq_ampdu_depth < ATH_AGGR_MIN_QDEPTH &&
status != ATH_AGGR_BAW_CLOSED);
}
int ath_tx_aggr_start(struct ath_softc *sc, struct ieee80211_sta *sta,
u16 tid, u16 *ssn)
{
struct ath_atx_tid *txtid;
struct ath_node *an;
an = (struct ath_node *)sta->drv_priv;
txtid = ATH_AN_2_TID(an, tid);
if (txtid->state & (AGGR_CLEANUP | AGGR_ADDBA_COMPLETE))
return -EAGAIN;
txtid->state |= AGGR_ADDBA_PROGRESS;
txtid->paused = true;
*ssn = txtid->seq_start = txtid->seq_next;
txtid->bar_index = -1;
memset(txtid->tx_buf, 0, sizeof(txtid->tx_buf));
txtid->baw_head = txtid->baw_tail = 0;
return 0;
}
void ath_tx_aggr_stop(struct ath_softc *sc, struct ieee80211_sta *sta, u16 tid)
{
struct ath_node *an = (struct ath_node *)sta->drv_priv;
struct ath_atx_tid *txtid = ATH_AN_2_TID(an, tid);
struct ath_txq *txq = txtid->ac->txq;
if (txtid->state & AGGR_CLEANUP)
return;
if (!(txtid->state & AGGR_ADDBA_COMPLETE)) {
txtid->state &= ~AGGR_ADDBA_PROGRESS;
return;
}
ath_txq_lock(sc, txq);
txtid->paused = true;
/*
* If frames are still being transmitted for this TID, they will be
* cleaned up during tx completion. To prevent race conditions, this
* TID can only be reused after all in-progress subframes have been
* completed.
*/
if (txtid->baw_head != txtid->baw_tail)
txtid->state |= AGGR_CLEANUP;
else
txtid->state &= ~AGGR_ADDBA_COMPLETE;
ath_tx_flush_tid(sc, txtid);
ath_txq_unlock_complete(sc, txq);
}
void ath_tx_aggr_sleep(struct ieee80211_sta *sta, struct ath_softc *sc,
struct ath_node *an)
{
struct ath_atx_tid *tid;
struct ath_atx_ac *ac;
struct ath_txq *txq;
bool buffered;
int tidno;
for (tidno = 0, tid = &an->tid[tidno];
tidno < WME_NUM_TID; tidno++, tid++) {
if (!tid->sched)
continue;
ac = tid->ac;
txq = ac->txq;
ath_txq_lock(sc, txq);
buffered = !skb_queue_empty(&tid->buf_q);
tid->sched = false;
list_del(&tid->list);
if (ac->sched) {
ac->sched = false;
list_del(&ac->list);
}
ath_txq_unlock(sc, txq);
ieee80211_sta_set_buffered(sta, tidno, buffered);
}
}
void ath_tx_aggr_wakeup(struct ath_softc *sc, struct ath_node *an)
{
struct ath_atx_tid *tid;
struct ath_atx_ac *ac;
struct ath_txq *txq;
int tidno;
for (tidno = 0, tid = &an->tid[tidno];
tidno < WME_NUM_TID; tidno++, tid++) {
ac = tid->ac;
txq = ac->txq;
ath_txq_lock(sc, txq);
ac->clear_ps_filter = true;
if (!skb_queue_empty(&tid->buf_q) && !tid->paused) {
ath_tx_queue_tid(txq, tid);
ath_txq_schedule(sc, txq);
}
ath_txq_unlock_complete(sc, txq);
}
}
void ath_tx_aggr_resume(struct ath_softc *sc, struct ieee80211_sta *sta, u16 tid)
{
struct ath_atx_tid *txtid;
struct ath_node *an;
an = (struct ath_node *)sta->drv_priv;
txtid = ATH_AN_2_TID(an, tid);
txtid->baw_size = IEEE80211_MIN_AMPDU_BUF << sta->ht_cap.ampdu_factor;
txtid->state |= AGGR_ADDBA_COMPLETE;
txtid->state &= ~AGGR_ADDBA_PROGRESS;
ath_tx_resume_tid(sc, txtid);
}
/********************/
/* Queue Management */
/********************/
static void ath_txq_drain_pending_buffers(struct ath_softc *sc,
struct ath_txq *txq)
{
struct ath_atx_ac *ac, *ac_tmp;
struct ath_atx_tid *tid, *tid_tmp;
list_for_each_entry_safe(ac, ac_tmp, &txq->axq_acq, list) {
list_del(&ac->list);
ac->sched = false;
list_for_each_entry_safe(tid, tid_tmp, &ac->tid_q, list) {
list_del(&tid->list);
tid->sched = false;
ath_tid_drain(sc, txq, tid);
}
}
}
struct ath_txq *ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
{
struct ath_hw *ah = sc->sc_ah;
struct ath9k_tx_queue_info qi;
static const int subtype_txq_to_hwq[] = {
[WME_AC_BE] = ATH_TXQ_AC_BE,
[WME_AC_BK] = ATH_TXQ_AC_BK,
[WME_AC_VI] = ATH_TXQ_AC_VI,
[WME_AC_VO] = ATH_TXQ_AC_VO,
};
int axq_qnum, i;
memset(&qi, 0, sizeof(qi));
qi.tqi_subtype = subtype_txq_to_hwq[subtype];
qi.tqi_aifs = ATH9K_TXQ_USEDEFAULT;
qi.tqi_cwmin = ATH9K_TXQ_USEDEFAULT;
qi.tqi_cwmax = ATH9K_TXQ_USEDEFAULT;
qi.tqi_physCompBuf = 0;
/*
* Enable interrupts only for EOL and DESC conditions.
* We mark tx descriptors to receive a DESC interrupt
* when a tx queue gets deep; otherwise waiting for the
* EOL to reap descriptors. Note that this is done to
* reduce interrupt load and this only defers reaping
* descriptors, never transmitting frames. Aside from
* reducing interrupts this also permits more concurrency.
* The only potential downside is if the tx queue backs
* up in which case the top half of the kernel may backup
* due to a lack of tx descriptors.
*
* The UAPSD queue is an exception, since we take a desc-
* based intr on the EOSP frames.
*/
if (ah->caps.hw_caps & ATH9K_HW_CAP_EDMA) {
qi.tqi_qflags = TXQ_FLAG_TXINT_ENABLE;
} else {
if (qtype == ATH9K_TX_QUEUE_UAPSD)
qi.tqi_qflags = TXQ_FLAG_TXDESCINT_ENABLE;
else
qi.tqi_qflags = TXQ_FLAG_TXEOLINT_ENABLE |
TXQ_FLAG_TXDESCINT_ENABLE;
}
axq_qnum = ath9k_hw_setuptxqueue(ah, qtype, &qi);
if (axq_qnum == -1) {
/*
* NB: don't print a message, this happens
* normally on parts with too few tx queues
*/
return NULL;
}
if (!ATH_TXQ_SETUP(sc, axq_qnum)) {
struct ath_txq *txq = &sc->tx.txq[axq_qnum];
txq->axq_qnum = axq_qnum;
txq->mac80211_qnum = -1;
txq->axq_link = NULL;
__skb_queue_head_init(&txq->complete_q);
INIT_LIST_HEAD(&txq->axq_q);
INIT_LIST_HEAD(&txq->axq_acq);
spin_lock_init(&txq->axq_lock);
txq->axq_depth = 0;
txq->axq_ampdu_depth = 0;
txq->axq_tx_inprogress = false;
sc->tx.txqsetup |= 1<<axq_qnum;
txq->txq_headidx = txq->txq_tailidx = 0;
for (i = 0; i < ATH_TXFIFO_DEPTH; i++)
INIT_LIST_HEAD(&txq->txq_fifo[i]);
}
return &sc->tx.txq[axq_qnum];
}
int ath_txq_update(struct ath_softc *sc, int qnum,
struct ath9k_tx_queue_info *qinfo)
{
struct ath_hw *ah = sc->sc_ah;
int error = 0;
struct ath9k_tx_queue_info qi;
if (qnum == sc->beacon.beaconq) {
/*
* XXX: for beacon queue, we just save the parameter.
* It will be picked up by ath_beaconq_config when
* it's necessary.
*/
sc->beacon.beacon_qi = *qinfo;
return 0;
}
BUG_ON(sc->tx.txq[qnum].axq_qnum != qnum);
ath9k_hw_get_txq_props(ah, qnum, &qi);
qi.tqi_aifs = qinfo->tqi_aifs;
qi.tqi_cwmin = qinfo->tqi_cwmin;
qi.tqi_cwmax = qinfo->tqi_cwmax;
qi.tqi_burstTime = qinfo->tqi_burstTime;
qi.tqi_readyTime = qinfo->tqi_readyTime;
if (!ath9k_hw_set_txq_props(ah, qnum, &qi)) {
ath_err(ath9k_hw_common(sc->sc_ah),
"Unable to update hardware queue %u!\n", qnum);
error = -EIO;
} else {
ath9k_hw_resettxqueue(ah, qnum);
}
return error;
}
int ath_cabq_update(struct ath_softc *sc)
{
struct ath9k_tx_queue_info qi;
struct ath_beacon_config *cur_conf = &sc->cur_beacon_conf;
int qnum = sc->beacon.cabq->axq_qnum;
ath9k_hw_get_txq_props(sc->sc_ah, qnum, &qi);
/*
* Ensure the readytime % is within the bounds.
*/
if (sc->config.cabqReadytime < ATH9K_READY_TIME_LO_BOUND)
sc->config.cabqReadytime = ATH9K_READY_TIME_LO_BOUND;
else if (sc->config.cabqReadytime > ATH9K_READY_TIME_HI_BOUND)
sc->config.cabqReadytime = ATH9K_READY_TIME_HI_BOUND;
qi.tqi_readyTime = (cur_conf->beacon_interval *
sc->config.cabqReadytime) / 100;
ath_txq_update(sc, qnum, &qi);
return 0;
}
static bool bf_is_ampdu_not_probing(struct ath_buf *bf)
{
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(bf->bf_mpdu);
return bf_isampdu(bf) && !(info->flags & IEEE80211_TX_CTL_RATE_CTRL_PROBE);
}
static void ath_drain_txq_list(struct ath_softc *sc, struct ath_txq *txq,
struct list_head *list, bool retry_tx)
{
struct ath_buf *bf, *lastbf;
struct list_head bf_head;
struct ath_tx_status ts;
memset(&ts, 0, sizeof(ts));
ts.ts_status = ATH9K_TX_FLUSH;
INIT_LIST_HEAD(&bf_head);
while (!list_empty(list)) {
bf = list_first_entry(list, struct ath_buf, list);
if (bf->bf_stale) {
list_del(&bf->list);
ath_tx_return_buffer(sc, bf);
continue;
}
lastbf = bf->bf_lastbf;
list_cut_position(&bf_head, list, &lastbf->list);
txq->axq_depth--;
if (bf_is_ampdu_not_probing(bf))
txq->axq_ampdu_depth--;
if (bf_isampdu(bf))
ath_tx_complete_aggr(sc, txq, bf, &bf_head, &ts, 0,
retry_tx);
else
ath_tx_complete_buf(sc, bf, txq, &bf_head, &ts, 0);
}
}
/*
* Drain a given TX queue (could be Beacon or Data)
*
* This assumes output has been stopped and
* we do not need to block ath_tx_tasklet.
*/
void ath_draintxq(struct ath_softc *sc, struct ath_txq *txq, bool retry_tx)
{
ath_txq_lock(sc, txq);
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_EDMA) {
int idx = txq->txq_tailidx;
while (!list_empty(&txq->txq_fifo[idx])) {
ath_drain_txq_list(sc, txq, &txq->txq_fifo[idx],
retry_tx);
INCR(idx, ATH_TXFIFO_DEPTH);
}
txq->txq_tailidx = idx;
}
txq->axq_link = NULL;
txq->axq_tx_inprogress = false;
ath_drain_txq_list(sc, txq, &txq->axq_q, retry_tx);
/* flush any pending frames if aggregation is enabled */
if ((sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_HT) && !retry_tx)
ath_txq_drain_pending_buffers(sc, txq);
ath_txq_unlock_complete(sc, txq);
}
bool ath_drain_all_txq(struct ath_softc *sc, bool retry_tx)
{
struct ath_hw *ah = sc->sc_ah;
struct ath_common *common = ath9k_hw_common(sc->sc_ah);
struct ath_txq *txq;
int i;
u32 npend = 0;
if (sc->sc_flags & SC_OP_INVALID)
return true;
ath9k_hw_abort_tx_dma(ah);
/* Check if any queue remains active */
for (i = 0; i < ATH9K_NUM_TX_QUEUES; i++) {
if (!ATH_TXQ_SETUP(sc, i))
continue;
if (ath9k_hw_numtxpending(ah, sc->tx.txq[i].axq_qnum))
npend |= BIT(i);
}
if (npend)
ath_err(common, "Failed to stop TX DMA, queues=0x%03x!\n", npend);
for (i = 0; i < ATH9K_NUM_TX_QUEUES; i++) {
if (!ATH_TXQ_SETUP(sc, i))
continue;
/*
* The caller will resume queues with ieee80211_wake_queues.
* Mark the queue as not stopped to prevent ath_tx_complete
* from waking the queue too early.
*/
txq = &sc->tx.txq[i];
txq->stopped = false;
ath_draintxq(sc, txq, retry_tx);
}
return !npend;
}
void ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
{
ath9k_hw_releasetxqueue(sc->sc_ah, txq->axq_qnum);
sc->tx.txqsetup &= ~(1<<txq->axq_qnum);
}
/* For each axq_acq entry, for each tid, try to schedule packets
* for transmit until ampdu_depth has reached min Q depth.
*/
void ath_txq_schedule(struct ath_softc *sc, struct ath_txq *txq)
{
struct ath_atx_ac *ac, *ac_tmp, *last_ac;
struct ath_atx_tid *tid, *last_tid;
if (work_pending(&sc->hw_reset_work) || list_empty(&txq->axq_acq) ||
txq->axq_ampdu_depth >= ATH_AGGR_MIN_QDEPTH)
return;
ac = list_first_entry(&txq->axq_acq, struct ath_atx_ac, list);
last_ac = list_entry(txq->axq_acq.prev, struct ath_atx_ac, list);
list_for_each_entry_safe(ac, ac_tmp, &txq->axq_acq, list) {
last_tid = list_entry(ac->tid_q.prev, struct ath_atx_tid, list);
list_del(&ac->list);
ac->sched = false;
while (!list_empty(&ac->tid_q)) {
tid = list_first_entry(&ac->tid_q, struct ath_atx_tid,
list);
list_del(&tid->list);
tid->sched = false;
if (tid->paused)
continue;
ath_tx_sched_aggr(sc, txq, tid);
/*
* add tid to round-robin queue if more frames
* are pending for the tid
*/
if (!skb_queue_empty(&tid->buf_q))
ath_tx_queue_tid(txq, tid);
if (tid == last_tid ||
txq->axq_ampdu_depth >= ATH_AGGR_MIN_QDEPTH)
break;
}
if (!list_empty(&ac->tid_q) && !ac->sched) {
ac->sched = true;
list_add_tail(&ac->list, &txq->axq_acq);
}
if (ac == last_ac ||
txq->axq_ampdu_depth >= ATH_AGGR_MIN_QDEPTH)
return;
}
}
/***********/
/* TX, DMA */
/***********/
/*
* Insert a chain of ath_buf (descriptors) on a txq and
* assume the descriptors are already chained together by caller.
*/
static void ath_tx_txqaddbuf(struct ath_softc *sc, struct ath_txq *txq,
struct list_head *head, bool internal)
{
struct ath_hw *ah = sc->sc_ah;
struct ath_common *common = ath9k_hw_common(ah);
struct ath_buf *bf, *bf_last;
bool puttxbuf = false;
bool edma;
/*
* Insert the frame on the outbound list and
* pass it on to the hardware.
*/
if (list_empty(head))
return;
edma = !!(ah->caps.hw_caps & ATH9K_HW_CAP_EDMA);
bf = list_first_entry(head, struct ath_buf, list);
bf_last = list_entry(head->prev, struct ath_buf, list);
ath_dbg(common, QUEUE, "qnum: %d, txq depth: %d\n",
txq->axq_qnum, txq->axq_depth);
if (edma && list_empty(&txq->txq_fifo[txq->txq_headidx])) {
list_splice_tail_init(head, &txq->txq_fifo[txq->txq_headidx]);
INCR(txq->txq_headidx, ATH_TXFIFO_DEPTH);
puttxbuf = true;
} else {
list_splice_tail_init(head, &txq->axq_q);
if (txq->axq_link) {
ath9k_hw_set_desc_link(ah, txq->axq_link, bf->bf_daddr);
ath_dbg(common, XMIT, "link[%u] (%p)=%llx (%p)\n",
txq->axq_qnum, txq->axq_link,
ito64(bf->bf_daddr), bf->bf_desc);
} else if (!edma)
puttxbuf = true;
txq->axq_link = bf_last->bf_desc;
}
if (puttxbuf) {
TX_STAT_INC(txq->axq_qnum, puttxbuf);
ath9k_hw_puttxbuf(ah, txq->axq_qnum, bf->bf_daddr);
ath_dbg(common, XMIT, "TXDP[%u] = %llx (%p)\n",
txq->axq_qnum, ito64(bf->bf_daddr), bf->bf_desc);
}
if (!edma) {
TX_STAT_INC(txq->axq_qnum, txstart);
ath9k_hw_txstart(ah, txq->axq_qnum);
}
if (!internal) {
txq->axq_depth++;
if (bf_is_ampdu_not_probing(bf))
txq->axq_ampdu_depth++;
}
}
static void ath_tx_send_ampdu(struct ath_softc *sc, struct ath_atx_tid *tid,
struct sk_buff *skb, struct ath_tx_control *txctl)
{
struct ath_frame_info *fi = get_frame_info(skb);
struct list_head bf_head;
struct ath_buf *bf;
/*
* Do not queue to h/w when any of the following conditions is true:
* - there are pending frames in software queue
* - the TID is currently paused for ADDBA/BAR request
* - seqno is not within block-ack window
* - h/w queue depth exceeds low water mark
*/
if (!skb_queue_empty(&tid->buf_q) || tid->paused ||
!BAW_WITHIN(tid->seq_start, tid->baw_size, tid->seq_next) ||
txctl->txq->axq_ampdu_depth >= ATH_AGGR_MIN_QDEPTH) {
/*
* Add this frame to software queue for scheduling later
* for aggregation.
*/
TX_STAT_INC(txctl->txq->axq_qnum, a_queued_sw);
__skb_queue_tail(&tid->buf_q, skb);
if (!txctl->an || !txctl->an->sleeping)
ath_tx_queue_tid(txctl->txq, tid);
return;
}
bf = ath_tx_setup_buffer(sc, txctl->txq, tid, skb);
if (!bf)
return;
bf->bf_state.bf_type = BUF_AMPDU;
INIT_LIST_HEAD(&bf_head);
list_add(&bf->list, &bf_head);
/* Add sub-frame to BAW */
ath_tx_addto_baw(sc, tid, bf->bf_state.seqno);
/* Queue to h/w without aggregation */
TX_STAT_INC(txctl->txq->axq_qnum, a_queued_hw);
bf->bf_lastbf = bf;
ath_tx_fill_desc(sc, bf, txctl->txq, fi->framelen);
ath_tx_txqaddbuf(sc, txctl->txq, &bf_head, false);
}
static void ath_tx_send_normal(struct ath_softc *sc, struct ath_txq *txq,
struct ath_atx_tid *tid, struct sk_buff *skb)
{
struct ath_frame_info *fi = get_frame_info(skb);
struct list_head bf_head;
struct ath_buf *bf;
bf = fi->bf;
if (!bf)
bf = ath_tx_setup_buffer(sc, txq, tid, skb);
if (!bf)
return;
INIT_LIST_HEAD(&bf_head);
list_add_tail(&bf->list, &bf_head);
bf->bf_state.bf_type = 0;
bf->bf_lastbf = bf;
ath_tx_fill_desc(sc, bf, txq, fi->framelen);
ath_tx_txqaddbuf(sc, txq, &bf_head, false);
TX_STAT_INC(txq->axq_qnum, queued);
}
static void setup_frame_info(struct ieee80211_hw *hw, struct sk_buff *skb,
int framelen)
{
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
struct ieee80211_sta *sta = tx_info->control.sta;
struct ieee80211_key_conf *hw_key = tx_info->control.hw_key;
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
struct ath_frame_info *fi = get_frame_info(skb);
struct ath_node *an = NULL;
enum ath9k_key_type keytype;
keytype = ath9k_cmn_get_hw_crypto_keytype(skb);
if (sta)
an = (struct ath_node *) sta->drv_priv;
memset(fi, 0, sizeof(*fi));
if (hw_key)
fi->keyix = hw_key->hw_key_idx;
else if (an && ieee80211_is_data(hdr->frame_control) && an->ps_key > 0)
fi->keyix = an->ps_key;
else
fi->keyix = ATH9K_TXKEYIX_INVALID;
fi->keytype = keytype;
fi->framelen = framelen;
}
u8 ath_txchainmask_reduction(struct ath_softc *sc, u8 chainmask, u32 rate)
{
struct ath_hw *ah = sc->sc_ah;
struct ath9k_channel *curchan = ah->curchan;
if ((ah->caps.hw_caps & ATH9K_HW_CAP_APM) &&
(curchan->channelFlags & CHANNEL_5GHZ) &&
(chainmask == 0x7) && (rate < 0x90))
return 0x3;
else
return chainmask;
}
/*
* Assign a descriptor (and sequence number if necessary,
* and map buffer for DMA. Frees skb on error
*/
static struct ath_buf *ath_tx_setup_buffer(struct ath_softc *sc,
struct ath_txq *txq,
struct ath_atx_tid *tid,
struct sk_buff *skb)
{
struct ath_common *common = ath9k_hw_common(sc->sc_ah);
struct ath_frame_info *fi = get_frame_info(skb);
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
struct ath_buf *bf;
int fragno;
u16 seqno;
bf = ath_tx_get_buffer(sc);
if (!bf) {
ath_dbg(common, XMIT, "TX buffers are full\n");
goto error;
}
ATH_TXBUF_RESET(bf);
if (tid) {
fragno = le16_to_cpu(hdr->seq_ctrl) & IEEE80211_SCTL_FRAG;
seqno = tid->seq_next;
hdr->seq_ctrl = cpu_to_le16(tid->seq_next << IEEE80211_SEQ_SEQ_SHIFT);
if (fragno)
hdr->seq_ctrl |= cpu_to_le16(fragno);
if (!ieee80211_has_morefrags(hdr->frame_control))
INCR(tid->seq_next, IEEE80211_SEQ_MAX);
bf->bf_state.seqno = seqno;
}
bf->bf_mpdu = skb;
bf->bf_buf_addr = dma_map_single(sc->dev, skb->data,
skb->len, DMA_TO_DEVICE);
if (unlikely(dma_mapping_error(sc->dev, bf->bf_buf_addr))) {
bf->bf_mpdu = NULL;
bf->bf_buf_addr = 0;
ath_err(ath9k_hw_common(sc->sc_ah),
"dma_mapping_error() on TX\n");
ath_tx_return_buffer(sc, bf);
goto error;
}
fi->bf = bf;
return bf;
error:
dev_kfree_skb_any(skb);
return NULL;
}
/* FIXME: tx power */
static void ath_tx_start_dma(struct ath_softc *sc, struct sk_buff *skb,
struct ath_tx_control *txctl)
{
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
struct ath_atx_tid *tid = NULL;
struct ath_buf *bf;
u8 tidno;
if ((sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_HT) && txctl->an &&
ieee80211_is_data_qos(hdr->frame_control)) {
tidno = ieee80211_get_qos_ctl(hdr)[0] &
IEEE80211_QOS_CTL_TID_MASK;
tid = ATH_AN_2_TID(txctl->an, tidno);
WARN_ON(tid->ac->txq != txctl->txq);
}
if ((tx_info->flags & IEEE80211_TX_CTL_AMPDU) && tid) {
/*
* Try aggregation if it's a unicast data frame
* and the destination is HT capable.
*/
ath_tx_send_ampdu(sc, tid, skb, txctl);
} else {
bf = ath_tx_setup_buffer(sc, txctl->txq, tid, skb);
if (!bf)
return;
bf->bf_state.bfs_paprd = txctl->paprd;
if (txctl->paprd)
bf->bf_state.bfs_paprd_timestamp = jiffies;
ath_tx_send_normal(sc, txctl->txq, tid, skb);
}
}
/* Upon failure caller should free skb */
int ath_tx_start(struct ieee80211_hw *hw, struct sk_buff *skb,
struct ath_tx_control *txctl)
{
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct ieee80211_sta *sta = info->control.sta;
struct ieee80211_vif *vif = info->control.vif;
struct ath_softc *sc = hw->priv;
struct ath_txq *txq = txctl->txq;
int padpos, padsize;
int frmlen = skb->len + FCS_LEN;
int q;
/* NOTE: sta can be NULL according to net/mac80211.h */
if (sta)
txctl->an = (struct ath_node *)sta->drv_priv;
if (info->control.hw_key)
frmlen += info->control.hw_key->icv_len;
/*
* As a temporary workaround, assign seq# here; this will likely need
* to be cleaned up to work better with Beacon transmission and virtual
* BSSes.
*/
if (info->flags & IEEE80211_TX_CTL_ASSIGN_SEQ) {
if (info->flags & IEEE80211_TX_CTL_FIRST_FRAGMENT)
sc->tx.seq_no += 0x10;
hdr->seq_ctrl &= cpu_to_le16(IEEE80211_SCTL_FRAG);
hdr->seq_ctrl |= cpu_to_le16(sc->tx.seq_no);
}
/* Add the padding after the header if this is not already done */
padpos = ath9k_cmn_padpos(hdr->frame_control);
padsize = padpos & 3;
if (padsize && skb->len > padpos) {
if (skb_headroom(skb) < padsize)
return -ENOMEM;
skb_push(skb, padsize);
memmove(skb->data, skb->data + padsize, padpos);
hdr = (struct ieee80211_hdr *) skb->data;
}
if ((vif && vif->type != NL80211_IFTYPE_AP &&
vif->type != NL80211_IFTYPE_AP_VLAN) ||
!ieee80211_is_data(hdr->frame_control))
info->flags |= IEEE80211_TX_CTL_CLEAR_PS_FILT;
setup_frame_info(hw, skb, frmlen);
/*
* At this point, the vif, hw_key and sta pointers in the tx control
* info are no longer valid (overwritten by the ath_frame_info data.
*/
q = skb_get_queue_mapping(skb);
ath_txq_lock(sc, txq);
if (txq == sc->tx.txq_map[q] &&
++txq->pending_frames > ATH_MAX_QDEPTH && !txq->stopped) {
ieee80211_stop_queue(sc->hw, q);
txq->stopped = true;
}
ath_tx_start_dma(sc, skb, txctl);
ath_txq_unlock(sc, txq);
return 0;
}
/*****************/
/* TX Completion */
/*****************/
static void ath_tx_complete(struct ath_softc *sc, struct sk_buff *skb,
int tx_flags, struct ath_txq *txq)
{
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
struct ath_common *common = ath9k_hw_common(sc->sc_ah);
struct ieee80211_hdr * hdr = (struct ieee80211_hdr *)skb->data;
int q, padpos, padsize;
ath_dbg(common, XMIT, "TX complete: skb: %p\n", skb);
if (!(tx_flags & ATH_TX_ERROR))
/* Frame was ACKed */
tx_info->flags |= IEEE80211_TX_STAT_ACK;
padpos = ath9k_cmn_padpos(hdr->frame_control);
padsize = padpos & 3;
if (padsize && skb->len>padpos+padsize) {
/*
* Remove MAC header padding before giving the frame back to
* mac80211.
*/
memmove(skb->data + padsize, skb->data, padpos);
skb_pull(skb, padsize);
}
if ((sc->ps_flags & PS_WAIT_FOR_TX_ACK) && !txq->axq_depth) {
sc->ps_flags &= ~PS_WAIT_FOR_TX_ACK;
ath_dbg(common, PS,
"Going back to sleep after having received TX status (0x%lx)\n",
sc->ps_flags & (PS_WAIT_FOR_BEACON |
PS_WAIT_FOR_CAB |
PS_WAIT_FOR_PSPOLL_DATA |
PS_WAIT_FOR_TX_ACK));
}
q = skb_get_queue_mapping(skb);
if (txq == sc->tx.txq_map[q]) {
if (WARN_ON(--txq->pending_frames < 0))
txq->pending_frames = 0;
if (txq->stopped && txq->pending_frames < ATH_MAX_QDEPTH) {
ieee80211_wake_queue(sc->hw, q);
txq->stopped = false;
}
}
__skb_queue_tail(&txq->complete_q, skb);
}
static void ath_tx_complete_buf(struct ath_softc *sc, struct ath_buf *bf,
struct ath_txq *txq, struct list_head *bf_q,
struct ath_tx_status *ts, int txok)
{
struct sk_buff *skb = bf->bf_mpdu;
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
unsigned long flags;
int tx_flags = 0;
if (!txok)
tx_flags |= ATH_TX_ERROR;
if (ts->ts_status & ATH9K_TXERR_FILT)
tx_info->flags |= IEEE80211_TX_STAT_TX_FILTERED;
dma_unmap_single(sc->dev, bf->bf_buf_addr, skb->len, DMA_TO_DEVICE);
bf->bf_buf_addr = 0;
if (bf->bf_state.bfs_paprd) {
if (time_after(jiffies,
bf->bf_state.bfs_paprd_timestamp +
msecs_to_jiffies(ATH_PAPRD_TIMEOUT)))
dev_kfree_skb_any(skb);
else
complete(&sc->paprd_complete);
} else {
ath_debug_stat_tx(sc, bf, ts, txq, tx_flags);
ath_tx_complete(sc, skb, tx_flags, txq);
}
/* At this point, skb (bf->bf_mpdu) is consumed...make sure we don't
* accidentally reference it later.
*/
bf->bf_mpdu = NULL;
/*
* Return the list of ath_buf of this mpdu to free queue
*/
spin_lock_irqsave(&sc->tx.txbuflock, flags);
list_splice_tail_init(bf_q, &sc->tx.txbuf);
spin_unlock_irqrestore(&sc->tx.txbuflock, flags);
}
static void ath_tx_rc_status(struct ath_softc *sc, struct ath_buf *bf,
struct ath_tx_status *ts, int nframes, int nbad,
int txok)
{
struct sk_buff *skb = bf->bf_mpdu;
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
struct ieee80211_hw *hw = sc->hw;
struct ath_hw *ah = sc->sc_ah;
u8 i, tx_rateindex;
if (txok)
tx_info->status.ack_signal = ts->ts_rssi;
tx_rateindex = ts->ts_rateindex;
WARN_ON(tx_rateindex >= hw->max_rates);
if (tx_info->flags & IEEE80211_TX_CTL_AMPDU) {
tx_info->flags |= IEEE80211_TX_STAT_AMPDU;
BUG_ON(nbad > nframes);
}
tx_info->status.ampdu_len = nframes;
tx_info->status.ampdu_ack_len = nframes - nbad;
if ((ts->ts_status & ATH9K_TXERR_FILT) == 0 &&
(tx_info->flags & IEEE80211_TX_CTL_NO_ACK) == 0) {
/*
* If an underrun error is seen assume it as an excessive
* retry only if max frame trigger level has been reached
* (2 KB for single stream, and 4 KB for dual stream).
* Adjust the long retry as if the frame was tried
* hw->max_rate_tries times to affect how rate control updates
* PER for the failed rate.
* In case of congestion on the bus penalizing this type of
* underruns should help hardware actually transmit new frames
* successfully by eventually preferring slower rates.
* This itself should also alleviate congestion on the bus.
*/
if (unlikely(ts->ts_flags & (ATH9K_TX_DATA_UNDERRUN |
ATH9K_TX_DELIM_UNDERRUN)) &&
ieee80211_is_data(hdr->frame_control) &&
ah->tx_trig_level >= sc->sc_ah->config.max_txtrig_level)
tx_info->status.rates[tx_rateindex].count =
hw->max_rate_tries;
}
for (i = tx_rateindex + 1; i < hw->max_rates; i++) {
tx_info->status.rates[i].count = 0;
tx_info->status.rates[i].idx = -1;
}
tx_info->status.rates[tx_rateindex].count = ts->ts_longretry + 1;
}
static void ath_tx_process_buffer(struct ath_softc *sc, struct ath_txq *txq,
struct ath_tx_status *ts, struct ath_buf *bf,
struct list_head *bf_head)
{
int txok;
txq->axq_depth--;
txok = !(ts->ts_status & ATH9K_TXERR_MASK);
txq->axq_tx_inprogress = false;
if (bf_is_ampdu_not_probing(bf))
txq->axq_ampdu_depth--;
if (!bf_isampdu(bf)) {
ath_tx_rc_status(sc, bf, ts, 1, txok ? 0 : 1, txok);
ath_tx_complete_buf(sc, bf, txq, bf_head, ts, txok);
} else
ath_tx_complete_aggr(sc, txq, bf, bf_head, ts, txok, true);
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_HT)
ath_txq_schedule(sc, txq);
}
static void ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq)
{
struct ath_hw *ah = sc->sc_ah;
struct ath_common *common = ath9k_hw_common(ah);
struct ath_buf *bf, *lastbf, *bf_held = NULL;
struct list_head bf_head;
struct ath_desc *ds;
struct ath_tx_status ts;
int status;
ath_dbg(common, QUEUE, "tx queue %d (%x), link %p\n",
txq->axq_qnum, ath9k_hw_gettxbuf(sc->sc_ah, txq->axq_qnum),
txq->axq_link);
ath_txq_lock(sc, txq);
for (;;) {
if (work_pending(&sc->hw_reset_work))
break;
if (list_empty(&txq->axq_q)) {
txq->axq_link = NULL;
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_HT)
ath_txq_schedule(sc, txq);
break;
}
bf = list_first_entry(&txq->axq_q, struct ath_buf, list);
/*
* There is a race condition that a BH gets scheduled
* after sw writes TxE and before hw re-load the last
* descriptor to get the newly chained one.
* Software must keep the last DONE descriptor as a
* holding descriptor - software does so by marking
* it with the STALE flag.
*/
bf_held = NULL;
if (bf->bf_stale) {
bf_held = bf;
if (list_is_last(&bf_held->list, &txq->axq_q))
break;
bf = list_entry(bf_held->list.next, struct ath_buf,
list);
}
lastbf = bf->bf_lastbf;
ds = lastbf->bf_desc;
memset(&ts, 0, sizeof(ts));
status = ath9k_hw_txprocdesc(ah, ds, &ts);
if (status == -EINPROGRESS)
break;
TX_STAT_INC(txq->axq_qnum, txprocdesc);
/*
* Remove ath_buf's of the same transmit unit from txq,
* however leave the last descriptor back as the holding
* descriptor for hw.
*/
lastbf->bf_stale = true;
INIT_LIST_HEAD(&bf_head);
if (!list_is_singular(&lastbf->list))
list_cut_position(&bf_head,
&txq->axq_q, lastbf->list.prev);
if (bf_held) {
list_del(&bf_held->list);
ath_tx_return_buffer(sc, bf_held);
}
ath_tx_process_buffer(sc, txq, &ts, bf, &bf_head);
}
ath_txq_unlock_complete(sc, txq);
}
static void ath_tx_complete_poll_work(struct work_struct *work)
{
struct ath_softc *sc = container_of(work, struct ath_softc,
tx_complete_work.work);
struct ath_txq *txq;
int i;
bool needreset = false;
#ifdef CONFIG_ATH9K_DEBUGFS
sc->tx_complete_poll_work_seen++;
#endif
for (i = 0; i < ATH9K_NUM_TX_QUEUES; i++)
if (ATH_TXQ_SETUP(sc, i)) {
txq = &sc->tx.txq[i];
ath_txq_lock(sc, txq);
if (txq->axq_depth) {
if (txq->axq_tx_inprogress) {
needreset = true;
ath_txq_unlock(sc, txq);
break;
} else {
txq->axq_tx_inprogress = true;
}
}
ath_txq_unlock_complete(sc, txq);
}
if (needreset) {
ath_dbg(ath9k_hw_common(sc->sc_ah), RESET,
"tx hung, resetting the chip\n");
RESET_STAT_INC(sc, RESET_TYPE_TX_HANG);
ieee80211_queue_work(sc->hw, &sc->hw_reset_work);
}
ieee80211_queue_delayed_work(sc->hw, &sc->tx_complete_work,
msecs_to_jiffies(ATH_TX_COMPLETE_POLL_INT));
}
void ath_tx_tasklet(struct ath_softc *sc)
{
struct ath_hw *ah = sc->sc_ah;
u32 qcumask = ((1 << ATH9K_NUM_TX_QUEUES) - 1) & ah->intr_txqs;
int i;
for (i = 0; i < ATH9K_NUM_TX_QUEUES; i++) {
if (ATH_TXQ_SETUP(sc, i) && (qcumask & (1 << i)))
ath_tx_processq(sc, &sc->tx.txq[i]);
}
}
void ath_tx_edma_tasklet(struct ath_softc *sc)
{
struct ath_tx_status ts;
struct ath_common *common = ath9k_hw_common(sc->sc_ah);
struct ath_hw *ah = sc->sc_ah;
struct ath_txq *txq;
struct ath_buf *bf, *lastbf;
struct list_head bf_head;
int status;
for (;;) {
if (work_pending(&sc->hw_reset_work))
break;
status = ath9k_hw_txprocdesc(ah, NULL, (void *)&ts);
if (status == -EINPROGRESS)
break;
if (status == -EIO) {
ath_dbg(common, XMIT, "Error processing tx status\n");
break;
}
/* Process beacon completions separately */
if (ts.qid == sc->beacon.beaconq) {
sc->beacon.tx_processed = true;
sc->beacon.tx_last = !(ts.ts_status & ATH9K_TXERR_MASK);
continue;
}
txq = &sc->tx.txq[ts.qid];
ath_txq_lock(sc, txq);
if (list_empty(&txq->txq_fifo[txq->txq_tailidx])) {
ath_txq_unlock(sc, txq);
return;
}
bf = list_first_entry(&txq->txq_fifo[txq->txq_tailidx],
struct ath_buf, list);
lastbf = bf->bf_lastbf;
INIT_LIST_HEAD(&bf_head);
list_cut_position(&bf_head, &txq->txq_fifo[txq->txq_tailidx],
&lastbf->list);
if (list_empty(&txq->txq_fifo[txq->txq_tailidx])) {
INCR(txq->txq_tailidx, ATH_TXFIFO_DEPTH);
if (!list_empty(&txq->axq_q)) {
struct list_head bf_q;
INIT_LIST_HEAD(&bf_q);
txq->axq_link = NULL;
list_splice_tail_init(&txq->axq_q, &bf_q);
ath_tx_txqaddbuf(sc, txq, &bf_q, true);
}
}
ath_tx_process_buffer(sc, txq, &ts, bf, &bf_head);
ath_txq_unlock_complete(sc, txq);
}
}
/*****************/
/* Init, Cleanup */
/*****************/
static int ath_txstatus_setup(struct ath_softc *sc, int size)
{
struct ath_descdma *dd = &sc->txsdma;
u8 txs_len = sc->sc_ah->caps.txs_len;
dd->dd_desc_len = size * txs_len;
dd->dd_desc = dma_alloc_coherent(sc->dev, dd->dd_desc_len,
&dd->dd_desc_paddr, GFP_KERNEL);
if (!dd->dd_desc)
return -ENOMEM;
return 0;
}
static int ath_tx_edma_init(struct ath_softc *sc)
{
int err;
err = ath_txstatus_setup(sc, ATH_TXSTATUS_RING_SIZE);
if (!err)
ath9k_hw_setup_statusring(sc->sc_ah, sc->txsdma.dd_desc,
sc->txsdma.dd_desc_paddr,
ATH_TXSTATUS_RING_SIZE);
return err;
}
static void ath_tx_edma_cleanup(struct ath_softc *sc)
{
struct ath_descdma *dd = &sc->txsdma;
dma_free_coherent(sc->dev, dd->dd_desc_len, dd->dd_desc,
dd->dd_desc_paddr);
}
int ath_tx_init(struct ath_softc *sc, int nbufs)
{
struct ath_common *common = ath9k_hw_common(sc->sc_ah);
int error = 0;
spin_lock_init(&sc->tx.txbuflock);
error = ath_descdma_setup(sc, &sc->tx.txdma, &sc->tx.txbuf,
"tx", nbufs, 1, 1);
if (error != 0) {
ath_err(common,
"Failed to allocate tx descriptors: %d\n", error);
goto err;
}
error = ath_descdma_setup(sc, &sc->beacon.bdma, &sc->beacon.bbuf,
"beacon", ATH_BCBUF, 1, 1);
if (error != 0) {
ath_err(common,
"Failed to allocate beacon descriptors: %d\n", error);
goto err;
}
INIT_DELAYED_WORK(&sc->tx_complete_work, ath_tx_complete_poll_work);
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_EDMA) {
error = ath_tx_edma_init(sc);
if (error)
goto err;
}
err:
if (error != 0)
ath_tx_cleanup(sc);
return error;
}
void ath_tx_cleanup(struct ath_softc *sc)
{
if (sc->beacon.bdma.dd_desc_len != 0)
ath_descdma_cleanup(sc, &sc->beacon.bdma, &sc->beacon.bbuf);
if (sc->tx.txdma.dd_desc_len != 0)
ath_descdma_cleanup(sc, &sc->tx.txdma, &sc->tx.txbuf);
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_EDMA)
ath_tx_edma_cleanup(sc);
}
void ath_tx_node_init(struct ath_softc *sc, struct ath_node *an)
{
struct ath_atx_tid *tid;
struct ath_atx_ac *ac;
int tidno, acno;
for (tidno = 0, tid = &an->tid[tidno];
tidno < WME_NUM_TID;
tidno++, tid++) {
tid->an = an;
tid->tidno = tidno;
tid->seq_start = tid->seq_next = 0;
tid->baw_size = WME_MAX_BA;
tid->baw_head = tid->baw_tail = 0;
tid->sched = false;
tid->paused = false;
tid->state &= ~AGGR_CLEANUP;
__skb_queue_head_init(&tid->buf_q);
acno = TID_TO_WME_AC(tidno);
tid->ac = &an->ac[acno];
tid->state &= ~AGGR_ADDBA_COMPLETE;
tid->state &= ~AGGR_ADDBA_PROGRESS;
}
for (acno = 0, ac = &an->ac[acno];
acno < WME_NUM_AC; acno++, ac++) {
ac->sched = false;
ac->txq = sc->tx.txq_map[acno];
INIT_LIST_HEAD(&ac->tid_q);
}
}
void ath_tx_node_cleanup(struct ath_softc *sc, struct ath_node *an)
{
struct ath_atx_ac *ac;
struct ath_atx_tid *tid;
struct ath_txq *txq;
int tidno;
for (tidno = 0, tid = &an->tid[tidno];
tidno < WME_NUM_TID; tidno++, tid++) {
ac = tid->ac;
txq = ac->txq;
ath_txq_lock(sc, txq);
if (tid->sched) {
list_del(&tid->list);
tid->sched = false;
}
if (ac->sched) {
list_del(&ac->list);
tid->ac->sched = false;
}
ath_tid_drain(sc, txq, tid);
tid->state &= ~AGGR_ADDBA_COMPLETE;
tid->state &= ~AGGR_CLEANUP;
ath_txq_unlock(sc, txq);
}
}
| gpl-2.0 |
Electrex/Electroactive-N6 | drivers/s390/block/scm_drv.c | 4484 | 1786 | /*
* Device driver for s390 storage class memory.
*
* Copyright IBM Corp. 2012
* Author(s): Sebastian Ott <sebott@linux.vnet.ibm.com>
*/
#define KMSG_COMPONENT "scm_block"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/module.h>
#include <linux/slab.h>
#include <asm/eadm.h>
#include "scm_blk.h"
static void scm_notify(struct scm_device *scmdev, enum scm_event event)
{
struct scm_blk_dev *bdev = dev_get_drvdata(&scmdev->dev);
switch (event) {
case SCM_CHANGE:
pr_info("%lx: The capabilities of the SCM increment changed\n",
(unsigned long) scmdev->address);
SCM_LOG(2, "State changed");
SCM_LOG_STATE(2, scmdev);
break;
case SCM_AVAIL:
SCM_LOG(2, "Increment available");
SCM_LOG_STATE(2, scmdev);
scm_blk_set_available(bdev);
break;
}
}
static int scm_probe(struct scm_device *scmdev)
{
struct scm_blk_dev *bdev;
int ret;
SCM_LOG(2, "probe");
SCM_LOG_STATE(2, scmdev);
if (scmdev->attrs.oper_state != OP_STATE_GOOD)
return -EINVAL;
bdev = kzalloc(sizeof(*bdev), GFP_KERNEL);
if (!bdev)
return -ENOMEM;
dev_set_drvdata(&scmdev->dev, bdev);
ret = scm_blk_dev_setup(bdev, scmdev);
if (ret) {
dev_set_drvdata(&scmdev->dev, NULL);
kfree(bdev);
goto out;
}
out:
return ret;
}
static int scm_remove(struct scm_device *scmdev)
{
struct scm_blk_dev *bdev = dev_get_drvdata(&scmdev->dev);
scm_blk_dev_cleanup(bdev);
dev_set_drvdata(&scmdev->dev, NULL);
kfree(bdev);
return 0;
}
static struct scm_driver scm_drv = {
.drv = {
.name = "scm_block",
.owner = THIS_MODULE,
},
.notify = scm_notify,
.probe = scm_probe,
.remove = scm_remove,
.handler = scm_blk_irq,
};
int __init scm_drv_init(void)
{
return scm_driver_register(&scm_drv);
}
void scm_drv_cleanup(void)
{
scm_driver_unregister(&scm_drv);
}
| gpl-2.0 |
mer-hybris/android_kernel_zte_msm8610 | sound/pci/au88x0/au88x0_mpu401.c | 5252 | 3657 | /*
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
* Routines for control of MPU-401 in UART mode
*
* Modified for the Aureal Vortex based Soundcards
* by Manuel Jander (mjande@embedded.cl).
*
* 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/init.h>
#include <sound/core.h>
#include <sound/mpu401.h>
#include "au88x0.h"
/* Check for mpu401 mmio support. */
/* MPU401 legacy support is only provided as a emergency fallback *
* for older versions of ALSA. Its usage is strongly discouraged. */
#ifndef MPU401_HW_AUREAL
#define VORTEX_MPU401_LEGACY
#endif
/* Vortex MPU401 defines. */
#define MIDI_CLOCK_DIV 0x61
/* Standart MPU401 defines. */
#define MPU401_RESET 0xff
#define MPU401_ENTER_UART 0x3f
#define MPU401_ACK 0xfe
static int __devinit snd_vortex_midi(vortex_t * vortex)
{
struct snd_rawmidi *rmidi;
int temp, mode;
struct snd_mpu401 *mpu;
unsigned long port;
#ifdef VORTEX_MPU401_LEGACY
/* EnableHardCodedMPU401Port() */
/* Enable Legacy MIDI Interface port. */
port = (0x03 << 5); /* FIXME: static address. 0x330 */
temp =
(hwread(vortex->mmio, VORTEX_CTRL) & ~CTRL_MIDI_PORT) |
CTRL_MIDI_EN | port;
hwwrite(vortex->mmio, VORTEX_CTRL, temp);
#else
/* Disable Legacy MIDI Interface port. */
temp =
(hwread(vortex->mmio, VORTEX_CTRL) & ~CTRL_MIDI_PORT) &
~CTRL_MIDI_EN;
hwwrite(vortex->mmio, VORTEX_CTRL, temp);
#endif
/* Mpu401UartInit() */
mode = 1;
temp = hwread(vortex->mmio, VORTEX_CTRL2) & 0xffff00cf;
temp |= (MIDI_CLOCK_DIV << 8) | ((mode >> 24) & 0xff) << 4;
hwwrite(vortex->mmio, VORTEX_CTRL2, temp);
hwwrite(vortex->mmio, VORTEX_MIDI_CMD, MPU401_RESET);
/* Check if anything is OK. */
temp = hwread(vortex->mmio, VORTEX_MIDI_DATA);
if (temp != MPU401_ACK /*0xfe */ ) {
printk(KERN_ERR "midi port doesn't acknowledge!\n");
return -ENODEV;
}
/* Enable MPU401 interrupts. */
hwwrite(vortex->mmio, VORTEX_IRQ_CTRL,
hwread(vortex->mmio, VORTEX_IRQ_CTRL) | IRQ_MIDI);
/* Create MPU401 instance. */
#ifdef VORTEX_MPU401_LEGACY
if ((temp =
snd_mpu401_uart_new(vortex->card, 0, MPU401_HW_MPU401, 0x330,
MPU401_INFO_IRQ_HOOK, -1, &rmidi)) != 0) {
hwwrite(vortex->mmio, VORTEX_CTRL,
(hwread(vortex->mmio, VORTEX_CTRL) &
~CTRL_MIDI_PORT) & ~CTRL_MIDI_EN);
return temp;
}
#else
port = (unsigned long)(vortex->mmio + VORTEX_MIDI_DATA);
if ((temp =
snd_mpu401_uart_new(vortex->card, 0, MPU401_HW_AUREAL, port,
MPU401_INFO_INTEGRATED | MPU401_INFO_MMIO |
MPU401_INFO_IRQ_HOOK, -1, &rmidi)) != 0) {
hwwrite(vortex->mmio, VORTEX_CTRL,
(hwread(vortex->mmio, VORTEX_CTRL) &
~CTRL_MIDI_PORT) & ~CTRL_MIDI_EN);
return temp;
}
mpu = rmidi->private_data;
mpu->cport = (unsigned long)(vortex->mmio + VORTEX_MIDI_CMD);
#endif
/* Overwrite MIDI name */
snprintf(rmidi->name, sizeof(rmidi->name), "%s MIDI %d", CARD_NAME_SHORT , vortex->card->number);
vortex->rmidi = rmidi;
return 0;
}
| gpl-2.0 |
CyanogenMod/android_kernel_sony_msm8974 | drivers/ata/pata_sch.c | 5508 | 5359 | /*
* pata_sch.c - Intel SCH PATA controllers
*
* Copyright (c) 2008 Alek Du <alek.du@intel.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License 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; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
/*
* Supports:
* Intel SCH (AF82US15W, AF82US15L, AF82UL11L) chipsets -- see spec at:
* http://download.intel.com/design/chipsets/embedded/datashts/319537.pdf
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#include <linux/dmi.h>
#define DRV_NAME "pata_sch"
#define DRV_VERSION "0.2"
/* see SCH datasheet page 351 */
enum {
D0TIM = 0x80, /* Device 0 Timing Register */
D1TIM = 0x84, /* Device 1 Timing Register */
PM = 0x07, /* PIO Mode Bit Mask */
MDM = (0x03 << 8), /* Multi-word DMA Mode Bit Mask */
UDM = (0x07 << 16), /* Ultra DMA Mode Bit Mask */
PPE = (1 << 30), /* Prefetch/Post Enable */
USD = (1 << 31), /* Use Synchronous DMA */
};
static int sch_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent);
static void sch_set_piomode(struct ata_port *ap, struct ata_device *adev);
static void sch_set_dmamode(struct ata_port *ap, struct ata_device *adev);
static const struct pci_device_id sch_pci_tbl[] = {
/* Intel SCH PATA Controller */
{ PCI_VDEVICE(INTEL, PCI_DEVICE_ID_INTEL_SCH_IDE), 0 },
{ } /* terminate list */
};
static struct pci_driver sch_pci_driver = {
.name = DRV_NAME,
.id_table = sch_pci_tbl,
.probe = sch_init_one,
.remove = ata_pci_remove_one,
#ifdef CONFIG_PM
.suspend = ata_pci_device_suspend,
.resume = ata_pci_device_resume,
#endif
};
static struct scsi_host_template sch_sht = {
ATA_BMDMA_SHT(DRV_NAME),
};
static struct ata_port_operations sch_pata_ops = {
.inherits = &ata_bmdma_port_ops,
.cable_detect = ata_cable_unknown,
.set_piomode = sch_set_piomode,
.set_dmamode = sch_set_dmamode,
};
static struct ata_port_info sch_port_info = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA5,
.port_ops = &sch_pata_ops,
};
MODULE_AUTHOR("Alek Du <alek.du@intel.com>");
MODULE_DESCRIPTION("SCSI low-level driver for Intel SCH PATA controllers");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, sch_pci_tbl);
MODULE_VERSION(DRV_VERSION);
/**
* sch_set_piomode - Initialize host controller PATA PIO timings
* @ap: Port whose timings we are configuring
* @adev: ATA device
*
* Set PIO mode for device, in host controller PCI config space.
*
* LOCKING:
* None (inherited from caller).
*/
static void sch_set_piomode(struct ata_port *ap, struct ata_device *adev)
{
unsigned int pio = adev->pio_mode - XFER_PIO_0;
struct pci_dev *dev = to_pci_dev(ap->host->dev);
unsigned int port = adev->devno ? D1TIM : D0TIM;
unsigned int data;
pci_read_config_dword(dev, port, &data);
/* see SCH datasheet page 351 */
/* set PIO mode */
data &= ~(PM | PPE);
data |= pio;
/* enable PPE for block device */
if (adev->class == ATA_DEV_ATA)
data |= PPE;
pci_write_config_dword(dev, port, data);
}
/**
* sch_set_dmamode - Initialize host controller PATA DMA timings
* @ap: Port whose timings we are configuring
* @adev: ATA device
*
* Set MW/UDMA mode for device, in host controller PCI config space.
*
* LOCKING:
* None (inherited from caller).
*/
static void sch_set_dmamode(struct ata_port *ap, struct ata_device *adev)
{
unsigned int dma_mode = adev->dma_mode;
struct pci_dev *dev = to_pci_dev(ap->host->dev);
unsigned int port = adev->devno ? D1TIM : D0TIM;
unsigned int data;
pci_read_config_dword(dev, port, &data);
/* see SCH datasheet page 351 */
if (dma_mode >= XFER_UDMA_0) {
/* enable Synchronous DMA mode */
data |= USD;
data &= ~UDM;
data |= (dma_mode - XFER_UDMA_0) << 16;
} else { /* must be MWDMA mode, since we masked SWDMA already */
data &= ~(USD | MDM);
data |= (dma_mode - XFER_MW_DMA_0) << 8;
}
pci_write_config_dword(dev, port, data);
}
/**
* sch_init_one - Register SCH ATA PCI device with kernel services
* @pdev: PCI device to register
* @ent: Entry in sch_pci_tbl matching with @pdev
*
* LOCKING:
* Inherited from PCI layer (may sleep).
*
* RETURNS:
* Zero on success, or -ERRNO value.
*/
static int __devinit sch_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
const struct ata_port_info *ppi[] = { &sch_port_info, NULL };
ata_print_version_once(&pdev->dev, DRV_VERSION);
return ata_pci_bmdma_init_one(pdev, ppi, &sch_sht, NULL, 0);
}
static int __init sch_init(void)
{
return pci_register_driver(&sch_pci_driver);
}
static void __exit sch_exit(void)
{
pci_unregister_driver(&sch_pci_driver);
}
module_init(sch_init);
module_exit(sch_exit);
| gpl-2.0 |
MAKO-MM/android_kernel_lge_mako | drivers/gpu/drm/via/via_dmablit.c | 8324 | 21840 | /* via_dmablit.c -- PCI DMA BitBlt support for the VIA Unichrome/Pro
*
* Copyright (C) 2005 Thomas Hellstrom, All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sub license,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Authors:
* Thomas Hellstrom.
* Partially based on code obtained from Digeo Inc.
*/
/*
* Unmaps the DMA mappings.
* FIXME: Is this a NoOp on x86? Also
* FIXME: What happens if this one is called and a pending blit has previously done
* the same DMA mappings?
*/
#include "drmP.h"
#include "via_drm.h"
#include "via_drv.h"
#include "via_dmablit.h"
#include <linux/pagemap.h>
#include <linux/slab.h>
#define VIA_PGDN(x) (((unsigned long)(x)) & PAGE_MASK)
#define VIA_PGOFF(x) (((unsigned long)(x)) & ~PAGE_MASK)
#define VIA_PFN(x) ((unsigned long)(x) >> PAGE_SHIFT)
typedef struct _drm_via_descriptor {
uint32_t mem_addr;
uint32_t dev_addr;
uint32_t size;
uint32_t next;
} drm_via_descriptor_t;
/*
* Unmap a DMA mapping.
*/
static void
via_unmap_blit_from_device(struct pci_dev *pdev, drm_via_sg_info_t *vsg)
{
int num_desc = vsg->num_desc;
unsigned cur_descriptor_page = num_desc / vsg->descriptors_per_page;
unsigned descriptor_this_page = num_desc % vsg->descriptors_per_page;
drm_via_descriptor_t *desc_ptr = vsg->desc_pages[cur_descriptor_page] +
descriptor_this_page;
dma_addr_t next = vsg->chain_start;
while (num_desc--) {
if (descriptor_this_page-- == 0) {
cur_descriptor_page--;
descriptor_this_page = vsg->descriptors_per_page - 1;
desc_ptr = vsg->desc_pages[cur_descriptor_page] +
descriptor_this_page;
}
dma_unmap_single(&pdev->dev, next, sizeof(*desc_ptr), DMA_TO_DEVICE);
dma_unmap_page(&pdev->dev, desc_ptr->mem_addr, desc_ptr->size, vsg->direction);
next = (dma_addr_t) desc_ptr->next;
desc_ptr--;
}
}
/*
* If mode = 0, count how many descriptors are needed.
* If mode = 1, Map the DMA pages for the device, put together and map also the descriptors.
* Descriptors are run in reverse order by the hardware because we are not allowed to update the
* 'next' field without syncing calls when the descriptor is already mapped.
*/
static void
via_map_blit_for_device(struct pci_dev *pdev,
const drm_via_dmablit_t *xfer,
drm_via_sg_info_t *vsg,
int mode)
{
unsigned cur_descriptor_page = 0;
unsigned num_descriptors_this_page = 0;
unsigned char *mem_addr = xfer->mem_addr;
unsigned char *cur_mem;
unsigned char *first_addr = (unsigned char *)VIA_PGDN(mem_addr);
uint32_t fb_addr = xfer->fb_addr;
uint32_t cur_fb;
unsigned long line_len;
unsigned remaining_len;
int num_desc = 0;
int cur_line;
dma_addr_t next = 0 | VIA_DMA_DPR_EC;
drm_via_descriptor_t *desc_ptr = NULL;
if (mode == 1)
desc_ptr = vsg->desc_pages[cur_descriptor_page];
for (cur_line = 0; cur_line < xfer->num_lines; ++cur_line) {
line_len = xfer->line_length;
cur_fb = fb_addr;
cur_mem = mem_addr;
while (line_len > 0) {
remaining_len = min(PAGE_SIZE-VIA_PGOFF(cur_mem), line_len);
line_len -= remaining_len;
if (mode == 1) {
desc_ptr->mem_addr =
dma_map_page(&pdev->dev,
vsg->pages[VIA_PFN(cur_mem) -
VIA_PFN(first_addr)],
VIA_PGOFF(cur_mem), remaining_len,
vsg->direction);
desc_ptr->dev_addr = cur_fb;
desc_ptr->size = remaining_len;
desc_ptr->next = (uint32_t) next;
next = dma_map_single(&pdev->dev, desc_ptr, sizeof(*desc_ptr),
DMA_TO_DEVICE);
desc_ptr++;
if (++num_descriptors_this_page >= vsg->descriptors_per_page) {
num_descriptors_this_page = 0;
desc_ptr = vsg->desc_pages[++cur_descriptor_page];
}
}
num_desc++;
cur_mem += remaining_len;
cur_fb += remaining_len;
}
mem_addr += xfer->mem_stride;
fb_addr += xfer->fb_stride;
}
if (mode == 1) {
vsg->chain_start = next;
vsg->state = dr_via_device_mapped;
}
vsg->num_desc = num_desc;
}
/*
* Function that frees up all resources for a blit. It is usable even if the
* blit info has only been partially built as long as the status enum is consistent
* with the actual status of the used resources.
*/
static void
via_free_sg_info(struct pci_dev *pdev, drm_via_sg_info_t *vsg)
{
struct page *page;
int i;
switch (vsg->state) {
case dr_via_device_mapped:
via_unmap_blit_from_device(pdev, vsg);
case dr_via_desc_pages_alloc:
for (i = 0; i < vsg->num_desc_pages; ++i) {
if (vsg->desc_pages[i] != NULL)
free_page((unsigned long)vsg->desc_pages[i]);
}
kfree(vsg->desc_pages);
case dr_via_pages_locked:
for (i = 0; i < vsg->num_pages; ++i) {
if (NULL != (page = vsg->pages[i])) {
if (!PageReserved(page) && (DMA_FROM_DEVICE == vsg->direction))
SetPageDirty(page);
page_cache_release(page);
}
}
case dr_via_pages_alloc:
vfree(vsg->pages);
default:
vsg->state = dr_via_sg_init;
}
vfree(vsg->bounce_buffer);
vsg->bounce_buffer = NULL;
vsg->free_on_sequence = 0;
}
/*
* Fire a blit engine.
*/
static void
via_fire_dmablit(struct drm_device *dev, drm_via_sg_info_t *vsg, int engine)
{
drm_via_private_t *dev_priv = (drm_via_private_t *)dev->dev_private;
VIA_WRITE(VIA_PCI_DMA_MAR0 + engine*0x10, 0);
VIA_WRITE(VIA_PCI_DMA_DAR0 + engine*0x10, 0);
VIA_WRITE(VIA_PCI_DMA_CSR0 + engine*0x04, VIA_DMA_CSR_DD | VIA_DMA_CSR_TD |
VIA_DMA_CSR_DE);
VIA_WRITE(VIA_PCI_DMA_MR0 + engine*0x04, VIA_DMA_MR_CM | VIA_DMA_MR_TDIE);
VIA_WRITE(VIA_PCI_DMA_BCR0 + engine*0x10, 0);
VIA_WRITE(VIA_PCI_DMA_DPR0 + engine*0x10, vsg->chain_start);
DRM_WRITEMEMORYBARRIER();
VIA_WRITE(VIA_PCI_DMA_CSR0 + engine*0x04, VIA_DMA_CSR_DE | VIA_DMA_CSR_TS);
VIA_READ(VIA_PCI_DMA_CSR0 + engine*0x04);
}
/*
* Obtain a page pointer array and lock all pages into system memory. A segmentation violation will
* occur here if the calling user does not have access to the submitted address.
*/
static int
via_lock_all_dma_pages(drm_via_sg_info_t *vsg, drm_via_dmablit_t *xfer)
{
int ret;
unsigned long first_pfn = VIA_PFN(xfer->mem_addr);
vsg->num_pages = VIA_PFN(xfer->mem_addr + (xfer->num_lines * xfer->mem_stride - 1)) -
first_pfn + 1;
vsg->pages = vzalloc(sizeof(struct page *) * vsg->num_pages);
if (NULL == vsg->pages)
return -ENOMEM;
down_read(¤t->mm->mmap_sem);
ret = get_user_pages(current, current->mm,
(unsigned long)xfer->mem_addr,
vsg->num_pages,
(vsg->direction == DMA_FROM_DEVICE),
0, vsg->pages, NULL);
up_read(¤t->mm->mmap_sem);
if (ret != vsg->num_pages) {
if (ret < 0)
return ret;
vsg->state = dr_via_pages_locked;
return -EINVAL;
}
vsg->state = dr_via_pages_locked;
DRM_DEBUG("DMA pages locked\n");
return 0;
}
/*
* Allocate DMA capable memory for the blit descriptor chain, and an array that keeps track of the
* pages we allocate. We don't want to use kmalloc for the descriptor chain because it may be
* quite large for some blits, and pages don't need to be contingous.
*/
static int
via_alloc_desc_pages(drm_via_sg_info_t *vsg)
{
int i;
vsg->descriptors_per_page = PAGE_SIZE / sizeof(drm_via_descriptor_t);
vsg->num_desc_pages = (vsg->num_desc + vsg->descriptors_per_page - 1) /
vsg->descriptors_per_page;
if (NULL == (vsg->desc_pages = kcalloc(vsg->num_desc_pages, sizeof(void *), GFP_KERNEL)))
return -ENOMEM;
vsg->state = dr_via_desc_pages_alloc;
for (i = 0; i < vsg->num_desc_pages; ++i) {
if (NULL == (vsg->desc_pages[i] =
(drm_via_descriptor_t *) __get_free_page(GFP_KERNEL)))
return -ENOMEM;
}
DRM_DEBUG("Allocated %d pages for %d descriptors.\n", vsg->num_desc_pages,
vsg->num_desc);
return 0;
}
static void
via_abort_dmablit(struct drm_device *dev, int engine)
{
drm_via_private_t *dev_priv = (drm_via_private_t *)dev->dev_private;
VIA_WRITE(VIA_PCI_DMA_CSR0 + engine*0x04, VIA_DMA_CSR_TA);
}
static void
via_dmablit_engine_off(struct drm_device *dev, int engine)
{
drm_via_private_t *dev_priv = (drm_via_private_t *)dev->dev_private;
VIA_WRITE(VIA_PCI_DMA_CSR0 + engine*0x04, VIA_DMA_CSR_TD | VIA_DMA_CSR_DD);
}
/*
* The dmablit part of the IRQ handler. Trying to do only reasonably fast things here.
* The rest, like unmapping and freeing memory for done blits is done in a separate workqueue
* task. Basically the task of the interrupt handler is to submit a new blit to the engine, while
* the workqueue task takes care of processing associated with the old blit.
*/
void
via_dmablit_handler(struct drm_device *dev, int engine, int from_irq)
{
drm_via_private_t *dev_priv = (drm_via_private_t *)dev->dev_private;
drm_via_blitq_t *blitq = dev_priv->blit_queues + engine;
int cur;
int done_transfer;
unsigned long irqsave = 0;
uint32_t status = 0;
DRM_DEBUG("DMA blit handler called. engine = %d, from_irq = %d, blitq = 0x%lx\n",
engine, from_irq, (unsigned long) blitq);
if (from_irq)
spin_lock(&blitq->blit_lock);
else
spin_lock_irqsave(&blitq->blit_lock, irqsave);
done_transfer = blitq->is_active &&
((status = VIA_READ(VIA_PCI_DMA_CSR0 + engine*0x04)) & VIA_DMA_CSR_TD);
done_transfer = done_transfer || (blitq->aborting && !(status & VIA_DMA_CSR_DE));
cur = blitq->cur;
if (done_transfer) {
blitq->blits[cur]->aborted = blitq->aborting;
blitq->done_blit_handle++;
DRM_WAKEUP(blitq->blit_queue + cur);
cur++;
if (cur >= VIA_NUM_BLIT_SLOTS)
cur = 0;
blitq->cur = cur;
/*
* Clear transfer done flag.
*/
VIA_WRITE(VIA_PCI_DMA_CSR0 + engine*0x04, VIA_DMA_CSR_TD);
blitq->is_active = 0;
blitq->aborting = 0;
schedule_work(&blitq->wq);
} else if (blitq->is_active && time_after_eq(jiffies, blitq->end)) {
/*
* Abort transfer after one second.
*/
via_abort_dmablit(dev, engine);
blitq->aborting = 1;
blitq->end = jiffies + DRM_HZ;
}
if (!blitq->is_active) {
if (blitq->num_outstanding) {
via_fire_dmablit(dev, blitq->blits[cur], engine);
blitq->is_active = 1;
blitq->cur = cur;
blitq->num_outstanding--;
blitq->end = jiffies + DRM_HZ;
if (!timer_pending(&blitq->poll_timer))
mod_timer(&blitq->poll_timer, jiffies + 1);
} else {
if (timer_pending(&blitq->poll_timer))
del_timer(&blitq->poll_timer);
via_dmablit_engine_off(dev, engine);
}
}
if (from_irq)
spin_unlock(&blitq->blit_lock);
else
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
}
/*
* Check whether this blit is still active, performing necessary locking.
*/
static int
via_dmablit_active(drm_via_blitq_t *blitq, int engine, uint32_t handle, wait_queue_head_t **queue)
{
unsigned long irqsave;
uint32_t slot;
int active;
spin_lock_irqsave(&blitq->blit_lock, irqsave);
/*
* Allow for handle wraparounds.
*/
active = ((blitq->done_blit_handle - handle) > (1 << 23)) &&
((blitq->cur_blit_handle - handle) <= (1 << 23));
if (queue && active) {
slot = handle - blitq->done_blit_handle + blitq->cur - 1;
if (slot >= VIA_NUM_BLIT_SLOTS)
slot -= VIA_NUM_BLIT_SLOTS;
*queue = blitq->blit_queue + slot;
}
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
return active;
}
/*
* Sync. Wait for at least three seconds for the blit to be performed.
*/
static int
via_dmablit_sync(struct drm_device *dev, uint32_t handle, int engine)
{
drm_via_private_t *dev_priv = (drm_via_private_t *)dev->dev_private;
drm_via_blitq_t *blitq = dev_priv->blit_queues + engine;
wait_queue_head_t *queue;
int ret = 0;
if (via_dmablit_active(blitq, engine, handle, &queue)) {
DRM_WAIT_ON(ret, *queue, 3 * DRM_HZ,
!via_dmablit_active(blitq, engine, handle, NULL));
}
DRM_DEBUG("DMA blit sync handle 0x%x engine %d returned %d\n",
handle, engine, ret);
return ret;
}
/*
* A timer that regularly polls the blit engine in cases where we don't have interrupts:
* a) Broken hardware (typically those that don't have any video capture facility).
* b) Blit abort. The hardware doesn't send an interrupt when a blit is aborted.
* The timer and hardware IRQ's can and do work in parallel. If the hardware has
* irqs, it will shorten the latency somewhat.
*/
static void
via_dmablit_timer(unsigned long data)
{
drm_via_blitq_t *blitq = (drm_via_blitq_t *) data;
struct drm_device *dev = blitq->dev;
int engine = (int)
(blitq - ((drm_via_private_t *)dev->dev_private)->blit_queues);
DRM_DEBUG("Polling timer called for engine %d, jiffies %lu\n", engine,
(unsigned long) jiffies);
via_dmablit_handler(dev, engine, 0);
if (!timer_pending(&blitq->poll_timer)) {
mod_timer(&blitq->poll_timer, jiffies + 1);
/*
* Rerun handler to delete timer if engines are off, and
* to shorten abort latency. This is a little nasty.
*/
via_dmablit_handler(dev, engine, 0);
}
}
/*
* Workqueue task that frees data and mappings associated with a blit.
* Also wakes up waiting processes. Each of these tasks handles one
* blit engine only and may not be called on each interrupt.
*/
static void
via_dmablit_workqueue(struct work_struct *work)
{
drm_via_blitq_t *blitq = container_of(work, drm_via_blitq_t, wq);
struct drm_device *dev = blitq->dev;
unsigned long irqsave;
drm_via_sg_info_t *cur_sg;
int cur_released;
DRM_DEBUG("Workqueue task called for blit engine %ld\n", (unsigned long)
(blitq - ((drm_via_private_t *)dev->dev_private)->blit_queues));
spin_lock_irqsave(&blitq->blit_lock, irqsave);
while (blitq->serviced != blitq->cur) {
cur_released = blitq->serviced++;
DRM_DEBUG("Releasing blit slot %d\n", cur_released);
if (blitq->serviced >= VIA_NUM_BLIT_SLOTS)
blitq->serviced = 0;
cur_sg = blitq->blits[cur_released];
blitq->num_free++;
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
DRM_WAKEUP(&blitq->busy_queue);
via_free_sg_info(dev->pdev, cur_sg);
kfree(cur_sg);
spin_lock_irqsave(&blitq->blit_lock, irqsave);
}
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
}
/*
* Init all blit engines. Currently we use two, but some hardware have 4.
*/
void
via_init_dmablit(struct drm_device *dev)
{
int i, j;
drm_via_private_t *dev_priv = (drm_via_private_t *)dev->dev_private;
drm_via_blitq_t *blitq;
pci_set_master(dev->pdev);
for (i = 0; i < VIA_NUM_BLIT_ENGINES; ++i) {
blitq = dev_priv->blit_queues + i;
blitq->dev = dev;
blitq->cur_blit_handle = 0;
blitq->done_blit_handle = 0;
blitq->head = 0;
blitq->cur = 0;
blitq->serviced = 0;
blitq->num_free = VIA_NUM_BLIT_SLOTS - 1;
blitq->num_outstanding = 0;
blitq->is_active = 0;
blitq->aborting = 0;
spin_lock_init(&blitq->blit_lock);
for (j = 0; j < VIA_NUM_BLIT_SLOTS; ++j)
DRM_INIT_WAITQUEUE(blitq->blit_queue + j);
DRM_INIT_WAITQUEUE(&blitq->busy_queue);
INIT_WORK(&blitq->wq, via_dmablit_workqueue);
setup_timer(&blitq->poll_timer, via_dmablit_timer,
(unsigned long)blitq);
}
}
/*
* Build all info and do all mappings required for a blit.
*/
static int
via_build_sg_info(struct drm_device *dev, drm_via_sg_info_t *vsg, drm_via_dmablit_t *xfer)
{
int draw = xfer->to_fb;
int ret = 0;
vsg->direction = (draw) ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
vsg->bounce_buffer = NULL;
vsg->state = dr_via_sg_init;
if (xfer->num_lines <= 0 || xfer->line_length <= 0) {
DRM_ERROR("Zero size bitblt.\n");
return -EINVAL;
}
/*
* Below check is a driver limitation, not a hardware one. We
* don't want to lock unused pages, and don't want to incoporate the
* extra logic of avoiding them. Make sure there are no.
* (Not a big limitation anyway.)
*/
if ((xfer->mem_stride - xfer->line_length) > 2*PAGE_SIZE) {
DRM_ERROR("Too large system memory stride. Stride: %d, "
"Length: %d\n", xfer->mem_stride, xfer->line_length);
return -EINVAL;
}
if ((xfer->mem_stride == xfer->line_length) &&
(xfer->fb_stride == xfer->line_length)) {
xfer->mem_stride *= xfer->num_lines;
xfer->line_length = xfer->mem_stride;
xfer->fb_stride = xfer->mem_stride;
xfer->num_lines = 1;
}
/*
* Don't lock an arbitrary large number of pages, since that causes a
* DOS security hole.
*/
if (xfer->num_lines > 2048 || (xfer->num_lines*xfer->mem_stride > (2048*2048*4))) {
DRM_ERROR("Too large PCI DMA bitblt.\n");
return -EINVAL;
}
/*
* we allow a negative fb stride to allow flipping of images in
* transfer.
*/
if (xfer->mem_stride < xfer->line_length ||
abs(xfer->fb_stride) < xfer->line_length) {
DRM_ERROR("Invalid frame-buffer / memory stride.\n");
return -EINVAL;
}
/*
* A hardware bug seems to be worked around if system memory addresses start on
* 16 byte boundaries. This seems a bit restrictive however. VIA is contacted
* about this. Meanwhile, impose the following restrictions:
*/
#ifdef VIA_BUGFREE
if ((((unsigned long)xfer->mem_addr & 3) != ((unsigned long)xfer->fb_addr & 3)) ||
((xfer->num_lines > 1) && ((xfer->mem_stride & 3) != (xfer->fb_stride & 3)))) {
DRM_ERROR("Invalid DRM bitblt alignment.\n");
return -EINVAL;
}
#else
if ((((unsigned long)xfer->mem_addr & 15) ||
((unsigned long)xfer->fb_addr & 3)) ||
((xfer->num_lines > 1) &&
((xfer->mem_stride & 15) || (xfer->fb_stride & 3)))) {
DRM_ERROR("Invalid DRM bitblt alignment.\n");
return -EINVAL;
}
#endif
if (0 != (ret = via_lock_all_dma_pages(vsg, xfer))) {
DRM_ERROR("Could not lock DMA pages.\n");
via_free_sg_info(dev->pdev, vsg);
return ret;
}
via_map_blit_for_device(dev->pdev, xfer, vsg, 0);
if (0 != (ret = via_alloc_desc_pages(vsg))) {
DRM_ERROR("Could not allocate DMA descriptor pages.\n");
via_free_sg_info(dev->pdev, vsg);
return ret;
}
via_map_blit_for_device(dev->pdev, xfer, vsg, 1);
return 0;
}
/*
* Reserve one free slot in the blit queue. Will wait for one second for one
* to become available. Otherwise -EBUSY is returned.
*/
static int
via_dmablit_grab_slot(drm_via_blitq_t *blitq, int engine)
{
int ret = 0;
unsigned long irqsave;
DRM_DEBUG("Num free is %d\n", blitq->num_free);
spin_lock_irqsave(&blitq->blit_lock, irqsave);
while (blitq->num_free == 0) {
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
DRM_WAIT_ON(ret, blitq->busy_queue, DRM_HZ, blitq->num_free > 0);
if (ret)
return (-EINTR == ret) ? -EAGAIN : ret;
spin_lock_irqsave(&blitq->blit_lock, irqsave);
}
blitq->num_free--;
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
return 0;
}
/*
* Hand back a free slot if we changed our mind.
*/
static void
via_dmablit_release_slot(drm_via_blitq_t *blitq)
{
unsigned long irqsave;
spin_lock_irqsave(&blitq->blit_lock, irqsave);
blitq->num_free++;
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
DRM_WAKEUP(&blitq->busy_queue);
}
/*
* Grab a free slot. Build blit info and queue a blit.
*/
static int
via_dmablit(struct drm_device *dev, drm_via_dmablit_t *xfer)
{
drm_via_private_t *dev_priv = (drm_via_private_t *)dev->dev_private;
drm_via_sg_info_t *vsg;
drm_via_blitq_t *blitq;
int ret;
int engine;
unsigned long irqsave;
if (dev_priv == NULL) {
DRM_ERROR("Called without initialization.\n");
return -EINVAL;
}
engine = (xfer->to_fb) ? 0 : 1;
blitq = dev_priv->blit_queues + engine;
if (0 != (ret = via_dmablit_grab_slot(blitq, engine)))
return ret;
if (NULL == (vsg = kmalloc(sizeof(*vsg), GFP_KERNEL))) {
via_dmablit_release_slot(blitq);
return -ENOMEM;
}
if (0 != (ret = via_build_sg_info(dev, vsg, xfer))) {
via_dmablit_release_slot(blitq);
kfree(vsg);
return ret;
}
spin_lock_irqsave(&blitq->blit_lock, irqsave);
blitq->blits[blitq->head++] = vsg;
if (blitq->head >= VIA_NUM_BLIT_SLOTS)
blitq->head = 0;
blitq->num_outstanding++;
xfer->sync.sync_handle = ++blitq->cur_blit_handle;
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
xfer->sync.engine = engine;
via_dmablit_handler(dev, engine, 0);
return 0;
}
/*
* Sync on a previously submitted blit. Note that the X server use signals extensively, and
* that there is a very big probability that this IOCTL will be interrupted by a signal. In that
* case it returns with -EAGAIN for the signal to be delivered.
* The caller should then reissue the IOCTL. This is similar to what is being done for drmGetLock().
*/
int
via_dma_blit_sync(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
drm_via_blitsync_t *sync = data;
int err;
if (sync->engine >= VIA_NUM_BLIT_ENGINES)
return -EINVAL;
err = via_dmablit_sync(dev, sync->sync_handle, sync->engine);
if (-EINTR == err)
err = -EAGAIN;
return err;
}
/*
* Queue a blit and hand back a handle to be used for sync. This IOCTL may be interrupted by a signal
* while waiting for a free slot in the blit queue. In that case it returns with -EAGAIN and should
* be reissued. See the above IOCTL code.
*/
int
via_dma_blit(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
drm_via_dmablit_t *xfer = data;
int err;
err = via_dmablit(dev, xfer);
return err;
}
| gpl-2.0 |
turtlepa/android_kernel_samsung_aries-old | drivers/staging/comedi/drivers/addi-data/APCI1710_Dig_io.c | 8324 | 35244 | /**
@verbatim
Copyright (C) 2004,2005 ADDI-DATA GmbH for the source code of this module.
ADDI-DATA GmbH
Dieselstrasse 3
D-77833 Ottersweier
Tel: +19(0)7223/9493-0
Fax: +49(0)7223/9493-92
http://www.addi-data.com
info@addi-data.com
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
You should also find the complete GPL in the COPYING file accompanying this source code.
@endverbatim
*/
/*
+-----------------------------------------------------------------------+
| (C) ADDI-DATA GmbH Dieselstraße 3 D-77833 Ottersweier |
+-----------------------------------------------------------------------+
| Tel : +49 (0) 7223/9493-0 | email : info@addi-data.com |
| Fax : +49 (0) 7223/9493-92 | Internet : http://www.addi-data.com |
+-----------------------------------------------------------------------+
| Project : API APCI1710 | Compiler : gcc |
| Module name : DIG_IO.C | Version : 2.96 |
+-------------------------------+---------------------------------------+
| Project manager: Eric Stolz | Date : 02/12/2002 |
+-----------------------------------------------------------------------+
| Description : APCI-1710 digital I/O module |
| |
| |
+-----------------------------------------------------------------------+
| UPDATES |
+-----------------------------------------------------------------------+
| Date | Author | Description of updates |
+----------+-----------+------------------------------------------------+
| 16/06/98 | S. Weber | Digital input / output implementation |
|----------|-----------|------------------------------------------------|
| 08/05/00 | Guinot C | - 0400/0228 All Function in RING 0 |
| | | available |
+-----------------------------------------------------------------------+
| | | |
| | | |
+-----------------------------------------------------------------------+
*/
/*
+----------------------------------------------------------------------------+
| Included files |
+----------------------------------------------------------------------------+
*/
#include "APCI1710_Dig_io.h"
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI1710_InsnConfigDigitalIO(struct comedi_device *dev, |
| struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data)|
+----------------------------------------------------------------------------+
| Task : Configure the digital I/O operating mode from selected |
| module (b_ModulNbr). You must calling this function be|
| for you call any other function witch access of digital|
| I/O. |
+----------------------------------------------------------------------------+
| Input Parameters : |
| unsigned char_ b_ModulNbr data[0]: Module number to |
| configure (0 to 3) |
| unsigned char_ b_ChannelAMode data[1] : Channel A mode selection |
| 0 : Channel used for digital |
| input |
| 1 : Channel used for digital |
| output |
| unsigned char_ b_ChannelBMode data[2] : Channel B mode selection |
| 0 : Channel used for digital |
| input |
| 1 : Channel used for digital |
| output |
data[0] memory on/off
Activates and deactivates the digital output memory.
After having |
| called up this function with memory on,the output you have previously|
| activated with the function are not reset
+----------------------------------------------------------------------------+
| Output Parameters : - |
+----------------------------------------------------------------------------+
| Return Value : 0: No error |
| -1: The handle parameter of the board is wrong |
| -2: The module parameter is wrong |
| -3: The module is not a digital I/O module |
| -4: Bi-directional channel A configuration error |
| -5: Bi-directional channel B configuration error |
+----------------------------------------------------------------------------+
*/
int i_APCI1710_InsnConfigDigitalIO(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
unsigned char b_ModulNbr, b_ChannelAMode, b_ChannelBMode;
unsigned char b_MemoryOnOff, b_ConfigType;
int i_ReturnValue = 0;
unsigned int dw_WriteConfig = 0;
b_ModulNbr = (unsigned char) CR_AREF(insn->chanspec);
b_ConfigType = (unsigned char) data[0]; /* Memory or Init */
b_ChannelAMode = (unsigned char) data[1];
b_ChannelBMode = (unsigned char) data[2];
b_MemoryOnOff = (unsigned char) data[1]; /* if memory operation */
i_ReturnValue = insn->n;
/**************************/
/* Test the module number */
/**************************/
if (b_ModulNbr >= 4) {
DPRINTK("Module Number invalid\n");
i_ReturnValue = -2;
return i_ReturnValue;
}
switch (b_ConfigType) {
case APCI1710_DIGIO_MEMORYONOFF:
if (b_MemoryOnOff) /* If Memory ON */
{
/****************************/
/* Set the output memory on */
/****************************/
devpriv->s_ModuleInfo[b_ModulNbr].
s_DigitalIOInfo.b_OutputMemoryEnabled = 1;
/***************************/
/* Clear the output memory */
/***************************/
devpriv->s_ModuleInfo[b_ModulNbr].
s_DigitalIOInfo.dw_OutputMemory = 0;
} else /* If memory off */
{
/*****************************/
/* Set the output memory off */
/*****************************/
devpriv->s_ModuleInfo[b_ModulNbr].
s_DigitalIOInfo.b_OutputMemoryEnabled = 0;
}
break;
case APCI1710_DIGIO_INIT:
/*******************************/
/* Test if digital I/O counter */
/*******************************/
if ((devpriv->s_BoardInfos.
dw_MolduleConfiguration[b_ModulNbr] &
0xFFFF0000UL) == APCI1710_DIGITAL_IO) {
/***************************************************/
/* Test the bi-directional channel A configuration */
/***************************************************/
if ((b_ChannelAMode == 0) || (b_ChannelAMode == 1)) {
/***************************************************/
/* Test the bi-directional channel B configuration */
/***************************************************/
if ((b_ChannelBMode == 0)
|| (b_ChannelBMode == 1)) {
devpriv->s_ModuleInfo[b_ModulNbr].
s_DigitalIOInfo.b_DigitalInit =
1;
/********************************/
/* Save channel A configuration */
/********************************/
devpriv->s_ModuleInfo[b_ModulNbr].
s_DigitalIOInfo.
b_ChannelAMode = b_ChannelAMode;
/********************************/
/* Save channel B configuration */
/********************************/
devpriv->s_ModuleInfo[b_ModulNbr].
s_DigitalIOInfo.
b_ChannelBMode = b_ChannelBMode;
/*****************************************/
/* Set the channel A and B configuration */
/*****************************************/
dw_WriteConfig =
(unsigned int) (b_ChannelAMode |
(b_ChannelBMode * 2));
/***************************/
/* Write the configuration */
/***************************/
outl(dw_WriteConfig,
devpriv->s_BoardInfos.
ui_Address + 4 +
(64 * b_ModulNbr));
} else {
/************************************************/
/* Bi-directional channel B configuration error */
/************************************************/
DPRINTK("Bi-directional channel B configuration error\n");
i_ReturnValue = -5;
}
} else {
/************************************************/
/* Bi-directional channel A configuration error */
/************************************************/
DPRINTK("Bi-directional channel A configuration error\n");
i_ReturnValue = -4;
}
} else {
/******************************************/
/* The module is not a digital I/O module */
/******************************************/
DPRINTK("The module is not a digital I/O module\n");
i_ReturnValue = -3;
}
} /* end of Switch */
printk("Return Value %d\n", i_ReturnValue);
return i_ReturnValue;
}
/*
+----------------------------------------------------------------------------+
| INPUT FUNCTIONS |
+----------------------------------------------------------------------------+
*/
/*
+----------------------------------------------------------------------------+
|INT i_APCI1710_InsnReadDigitalIOChlValue(struct comedi_device *dev,comedi_subdevice
*s, struct comedi_insn *insn,unsigned int *data)
+----------------------------------------------------------------------------+
| Task : Read the status from selected digital I/O digital input|
| (b_InputChannel) |
+----------------------------------------------------------------------------|
|
| unsigned char_ b_ModulNbr CR_AREF(chanspec) : Selected module number |
| (0 to 3) |
| unsigned char_ b_InputChannel CR_CHAN(chanspec) : Selection from digital |
| input ( 0 to 6) |
| 0 : Channel C |
| 1 : Channel D |
| 2 : Channel E |
| 3 : Channel F |
| 4 : Channel G |
| 5 : Channel A |
| 6 : Channel B
|
+----------------------------------------------------------------------------+
| Output Parameters : data[0] : Digital input channel |
| status |
| 0 : Channle is not active|
| 1 : Channle is active |
+----------------------------------------------------------------------------+
| Return Value : 0: No error |
| -1: The handle parameter of the board is wrong |
| -2: The module parameter is wrong |
| -3: The module is not a digital I/O module |
| -4: The selected digital I/O digital input is wrong |
| -5: Digital I/O not initialised |
| -6: The digital channel A is used for output |
| -7: The digital channel B is used for output |
+----------------------------------------------------------------------------+
*/
/* _INT_ i_APCI1710_ReadDigitalIOChlValue (unsigned char_ b_BoardHandle, */
/*
* unsigned char_ b_ModulNbr, unsigned char_ b_InputChannel,
* unsigned char *_ pb_ChannelStatus)
*/
int i_APCI1710_InsnReadDigitalIOChlValue(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
{
int i_ReturnValue = 0;
unsigned int dw_StatusReg;
unsigned char b_ModulNbr, b_InputChannel;
unsigned char *pb_ChannelStatus;
b_ModulNbr = (unsigned char) CR_AREF(insn->chanspec);
b_InputChannel = (unsigned char) CR_CHAN(insn->chanspec);
data[0] = 0;
pb_ChannelStatus = (unsigned char *) &data[0];
i_ReturnValue = insn->n;
/**************************/
/* Test the module number */
/**************************/
if (b_ModulNbr < 4) {
/*******************************/
/* Test if digital I/O counter */
/*******************************/
if ((devpriv->s_BoardInfos.
dw_MolduleConfiguration[b_ModulNbr] &
0xFFFF0000UL) == APCI1710_DIGITAL_IO) {
/******************************************/
/* Test the digital imnput channel number */
/******************************************/
if (b_InputChannel <= 6) {
/**********************************************/
/* Test if the digital I/O module initialised */
/**********************************************/
if (devpriv->s_ModuleInfo[b_ModulNbr].
s_DigitalIOInfo.b_DigitalInit == 1) {
/**********************************/
/* Test if channel A or channel B */
/**********************************/
if (b_InputChannel > 4) {
/*********************/
/* Test if channel A */
/*********************/
if (b_InputChannel == 5) {
/***************************/
/* Test the channel A mode */
/***************************/
if (devpriv->
s_ModuleInfo
[b_ModulNbr].
s_DigitalIOInfo.
b_ChannelAMode
!= 0) {
/********************************************/
/* The digital channel A is used for output */
/********************************************/
i_ReturnValue =
-6;
}
} /* if (b_InputChannel == 5) */
else {
/***************************/
/* Test the channel B mode */
/***************************/
if (devpriv->
s_ModuleInfo
[b_ModulNbr].
s_DigitalIOInfo.
b_ChannelBMode
!= 0) {
/********************************************/
/* The digital channel B is used for output */
/********************************************/
i_ReturnValue =
-7;
}
} /* if (b_InputChannel == 5) */
} /* if (b_InputChannel > 4) */
/***********************/
/* Test if error occur */
/***********************/
if (i_ReturnValue >= 0) {
/**************************/
/* Read all digital input */
/**************************/
/*
* INPDW (ps_APCI1710Variable-> s_Board [b_BoardHandle].
* s_BoardInfos. ui_Address + (64 * b_ModulNbr), &dw_StatusReg);
*/
dw_StatusReg =
inl(devpriv->
s_BoardInfos.
ui_Address +
(64 * b_ModulNbr));
*pb_ChannelStatus =
(unsigned char) ((dw_StatusReg ^
0x1C) >>
b_InputChannel) & 1;
} /* if (i_ReturnValue == 0) */
} else {
/*******************************/
/* Digital I/O not initialised */
/*******************************/
DPRINTK("Digital I/O not initialised\n");
i_ReturnValue = -5;
}
} else {
/********************************/
/* Selected digital input error */
/********************************/
DPRINTK("Selected digital input error\n");
i_ReturnValue = -4;
}
} else {
/******************************************/
/* The module is not a digital I/O module */
/******************************************/
DPRINTK("The module is not a digital I/O module\n");
i_ReturnValue = -3;
}
} else {
/***********************/
/* Module number error */
/***********************/
DPRINTK("Module number error\n");
i_ReturnValue = -2;
}
return i_ReturnValue;
}
/*
+----------------------------------------------------------------------------+
| OUTPUT FUNCTIONS |
+----------------------------------------------------------------------------+
*/
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI1710_InsnWriteDigitalIOChlOnOff(comedi_device
|*dev,struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data)
+----------------------------------------------------------------------------+
| Task : Sets or resets the output witch has been passed with the |
| parameter b_Channel. Setting an output means setting |
| an ouput high. |
+----------------------------------------------------------------------------+
| Input Parameters : unsigned char_ b_BoardHandle : Handle of board APCI-1710 |
| unsigned char_ b_ModulNbr (aref ) : Selected module number (0 to 3)|
| unsigned char_ b_OutputChannel (CR_CHAN) : Selection from digital output |
| channel (0 to 2) |
| 0 : Channel H |
| 1 : Channel A |
| 2 : Channel B |
+----------------------------------------------------------------------------+
| Output Parameters : - |
+----------------------------------------------------------------------------+
| Return Value : 0: No error |
| -1: The handle parameter of the board is wrong |
| -2: The module parameter is wrong |
| -3: The module is not a digital I/O module |
| -4: The selected digital output is wrong |
| -5: digital I/O not initialised see function |
| " i_APCI1710_InitDigitalIO" |
| -6: The digital channel A is used for input |
| -7: The digital channel B is used for input
-8: Digital Output Memory OFF. |
| Use previously the function |
| "i_APCI1710_SetDigitalIOMemoryOn". |
+----------------------------------------------------------------------------+
*/
/*
* _INT_ i_APCI1710_SetDigitalIOChlOn (unsigned char_ b_BoardHandle,
* unsigned char_ b_ModulNbr, unsigned char_ b_OutputChannel)
*/
int i_APCI1710_InsnWriteDigitalIOChlOnOff(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
{
int i_ReturnValue = 0;
unsigned int dw_WriteValue = 0;
unsigned char b_ModulNbr, b_OutputChannel;
i_ReturnValue = insn->n;
b_ModulNbr = CR_AREF(insn->chanspec);
b_OutputChannel = CR_CHAN(insn->chanspec);
/**************************/
/* Test the module number */
/**************************/
if (b_ModulNbr < 4) {
/*******************************/
/* Test if digital I/O counter */
/*******************************/
if ((devpriv->s_BoardInfos.
dw_MolduleConfiguration[b_ModulNbr] &
0xFFFF0000UL) == APCI1710_DIGITAL_IO) {
/**********************************************/
/* Test if the digital I/O module initialised */
/**********************************************/
if (devpriv->s_ModuleInfo[b_ModulNbr].
s_DigitalIOInfo.b_DigitalInit == 1) {
/******************************************/
/* Test the digital output channel number */
/******************************************/
switch (b_OutputChannel) {
/*************/
/* Channel H */
/*************/
case 0:
break;
/*************/
/* Channel A */
/*************/
case 1:
if (devpriv->s_ModuleInfo[b_ModulNbr].
s_DigitalIOInfo.
b_ChannelAMode != 1) {
/*******************************************/
/* The digital channel A is used for input */
/*******************************************/
i_ReturnValue = -6;
}
break;
/*************/
/* Channel B */
/*************/
case 2:
if (devpriv->s_ModuleInfo[b_ModulNbr].
s_DigitalIOInfo.
b_ChannelBMode != 1) {
/*******************************************/
/* The digital channel B is used for input */
/*******************************************/
i_ReturnValue = -7;
}
break;
default:
/****************************************/
/* The selected digital output is wrong */
/****************************************/
i_ReturnValue = -4;
break;
}
/***********************/
/* Test if error occur */
/***********************/
if (i_ReturnValue >= 0) {
/*********************************/
/* Test if set channel ON */
/*********************************/
if (data[0]) {
/*********************************/
/* Test if output memory enabled */
/*********************************/
if (devpriv->
s_ModuleInfo
[b_ModulNbr].
s_DigitalIOInfo.
b_OutputMemoryEnabled ==
1) {
dw_WriteValue =
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_DigitalIOInfo.
dw_OutputMemory
| (1 <<
b_OutputChannel);
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_DigitalIOInfo.
dw_OutputMemory
= dw_WriteValue;
} else {
dw_WriteValue =
1 <<
b_OutputChannel;
}
} /* set channel off */
else {
if (devpriv->
s_ModuleInfo
[b_ModulNbr].
s_DigitalIOInfo.
b_OutputMemoryEnabled ==
1) {
dw_WriteValue =
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_DigitalIOInfo.
dw_OutputMemory
& (0xFFFFFFFFUL
-
(1 << b_OutputChannel));
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_DigitalIOInfo.
dw_OutputMemory
= dw_WriteValue;
} else {
/*****************************/
/* Digital Output Memory OFF */
/*****************************/
/* +Use previously the function "i_APCI1710_SetDigitalIOMemoryOn" */
i_ReturnValue = -8;
}
}
/*******************/
/* Write the value */
/*******************/
/* OUTPDW (ps_APCI1710Variable->
* s_Board [b_BoardHandle].
* s_BoardInfos. ui_Address + (64 * b_ModulNbr),
* dw_WriteValue);
*/
*/
outl(dw_WriteValue,
devpriv->s_BoardInfos.
ui_Address + (64 * b_ModulNbr));
}
} else {
/*******************************/
/* Digital I/O not initialised */
/*******************************/
i_ReturnValue = -5;
}
} else {
/******************************************/
/* The module is not a digital I/O module */
/******************************************/
i_ReturnValue = -3;
}
} else {
/***********************/
/* Module number error */
/***********************/
i_ReturnValue = -2;
}
return i_ReturnValue;
}
/*
+----------------------------------------------------------------------------+
|INT i_APCI1710_InsnBitsDigitalIOPortOnOff(struct comedi_device *dev,comedi_subdevice
*s, struct comedi_insn *insn,unsigned int *data)
+----------------------------------------------------------------------------+
| Task : write:
Sets or resets one or several outputs from port. |
| Setting an output means setting an output high. |
| If you have switched OFF the digital output memory |
| (OFF), all the other output are set to "0".
| read:
Read the status from digital input port |
| from selected digital I/O module (b_ModulNbr)
+----------------------------------------------------------------------------+
| Input Parameters :
unsigned char_ b_BoardHandle : Handle of board APCI-1710 |
| unsigned char_ b_ModulNbr CR_AREF(aref) : Selected module number (0 to 3)|
| unsigned char_ b_PortValue CR_CHAN(chanspec) : Output Value ( 0 To 7 )
| data[0] read or write port
| data[1] if write then indicate ON or OFF
| if read : data[1] will return port status.
+----------------------------------------------------------------------------+
| Output Parameters : - |
+----------------------------------------------------------------------------+
| Return Value :
| INPUT :
0: No error |
| -1: The handle parameter of the board is wrong |
| -2: The module parameter is wrong |
| -3: The module is not a digital I/O module |
| -4: Digital I/O not initialised
OUTPUT: 0: No error |
| -1: The handle parameter of the board is wrong |
| -2: The module parameter is wrong |
| -3: The module is not a digital I/O module |
| -4: Output value wrong |
| -5: digital I/O not initialised see function |
| " i_APCI1710_InitDigitalIO" |
| -6: The digital channel A is used for input |
| -7: The digital channel B is used for input
-8: Digital Output Memory OFF. |
| Use previously the function |
| "i_APCI1710_SetDigitalIOMemoryOn". |
+----------------------------------------------------------------------------+
*/
/*
* _INT_ i_APCI1710_SetDigitalIOPortOn (unsigned char_
* b_BoardHandle, unsigned char_ b_ModulNbr, unsigned char_
* b_PortValue)
*/
int i_APCI1710_InsnBitsDigitalIOPortOnOff(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
{
int i_ReturnValue = 0;
unsigned int dw_WriteValue = 0;
unsigned int dw_StatusReg;
unsigned char b_ModulNbr, b_PortValue;
unsigned char b_PortOperation, b_PortOnOFF;
unsigned char *pb_PortValue;
b_ModulNbr = (unsigned char) CR_AREF(insn->chanspec);
b_PortOperation = (unsigned char) data[0]; /* Input or output */
b_PortOnOFF = (unsigned char) data[1]; /* if output then On or Off */
b_PortValue = (unsigned char) data[2]; /* if out put then Value */
i_ReturnValue = insn->n;
pb_PortValue = (unsigned char *) &data[0];
/* if input then read value */
switch (b_PortOperation) {
case APCI1710_INPUT:
/**************************/
/* Test the module number */
/**************************/
if (b_ModulNbr < 4) {
/*******************************/
/* Test if digital I/O counter */
/*******************************/
if ((devpriv->s_BoardInfos.
dw_MolduleConfiguration[b_ModulNbr] &
0xFFFF0000UL) == APCI1710_DIGITAL_IO) {
/**********************************************/
/* Test if the digital I/O module initialised */
/**********************************************/
if (devpriv->s_ModuleInfo[b_ModulNbr].
s_DigitalIOInfo.b_DigitalInit == 1) {
/**************************/
/* Read all digital input */
/**************************/
/* INPDW (ps_APCI1710Variable->
* s_Board [b_BoardHandle].
* s_BoardInfos.
* ui_Address + (64 * b_ModulNbr),
* &dw_StatusReg);
*/
dw_StatusReg =
inl(devpriv->s_BoardInfos.
ui_Address + (64 * b_ModulNbr));
*pb_PortValue =
(unsigned char) (dw_StatusReg ^ 0x1C);
} else {
/*******************************/
/* Digital I/O not initialised */
/*******************************/
i_ReturnValue = -4;
}
} else {
/******************************************/
/* The module is not a digital I/O module */
/******************************************/
i_ReturnValue = -3;
}
} else {
/***********************/
/* Module number error */
/***********************/
i_ReturnValue = -2;
}
break;
case APCI1710_OUTPUT:
/**************************/
/* Test the module number */
/**************************/
if (b_ModulNbr < 4) {
/*******************************/
/* Test if digital I/O counter */
/*******************************/
if ((devpriv->s_BoardInfos.
dw_MolduleConfiguration[b_ModulNbr] &
0xFFFF0000UL) == APCI1710_DIGITAL_IO) {
/**********************************************/
/* Test if the digital I/O module initialised */
/**********************************************/
if (devpriv->s_ModuleInfo[b_ModulNbr].
s_DigitalIOInfo.b_DigitalInit == 1) {
/***********************/
/* Test the port value */
/***********************/
if (b_PortValue <= 7) {
/***********************************/
/* Test the digital output channel */
/***********************************/
/**************************/
/* Test if channel A used */
/**************************/
if ((b_PortValue & 2) == 2) {
if (devpriv->
s_ModuleInfo
[b_ModulNbr].
s_DigitalIOInfo.
b_ChannelAMode
!= 1) {
/*******************************************/
/* The digital channel A is used for input */
/*******************************************/
i_ReturnValue =
-6;
}
} /* if ((b_PortValue & 2) == 2) */
/**************************/
/* Test if channel B used */
/**************************/
if ((b_PortValue & 4) == 4) {
if (devpriv->
s_ModuleInfo
[b_ModulNbr].
s_DigitalIOInfo.
b_ChannelBMode
!= 1) {
/*******************************************/
/* The digital channel B is used for input */
/*******************************************/
i_ReturnValue =
-7;
}
} /* if ((b_PortValue & 4) == 4) */
/***********************/
/* Test if error occur */
/***********************/
if (i_ReturnValue >= 0) {
/* if(data[1]) { */
switch (b_PortOnOFF) {
/*********************************/
/* Test if set Port ON */
/*********************************/
case APCI1710_ON:
/*********************************/
/* Test if output memory enabled */
/*********************************/
if (devpriv->
s_ModuleInfo
[b_ModulNbr].
s_DigitalIOInfo.
b_OutputMemoryEnabled
== 1) {
dw_WriteValue
=
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_DigitalIOInfo.
dw_OutputMemory
|
b_PortValue;
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_DigitalIOInfo.
dw_OutputMemory
=
dw_WriteValue;
} else {
dw_WriteValue
=
b_PortValue;
}
break;
/* If Set PORT OFF */
case APCI1710_OFF:
/*********************************/
/* Test if output memory enabled */
/*********************************/
if (devpriv->
s_ModuleInfo
[b_ModulNbr].
s_DigitalIOInfo.
b_OutputMemoryEnabled
== 1) {
dw_WriteValue
=
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_DigitalIOInfo.
dw_OutputMemory
&
(0xFFFFFFFFUL
-
b_PortValue);
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_DigitalIOInfo.
dw_OutputMemory
=
dw_WriteValue;
} else {
/*****************************/
/* Digital Output Memory OFF */
/*****************************/
i_ReturnValue
=
-8;
}
} /* switch */
/*******************/
/* Write the value */
/*******************/
/* OUTPDW (ps_APCI1710Variable->
* s_Board [b_BoardHandle].
* s_BoardInfos.
* ui_Address + (64 * b_ModulNbr),
* dw_WriteValue); */
outl(dw_WriteValue,
devpriv->
s_BoardInfos.
ui_Address +
(64 * b_ModulNbr));
}
} else {
/**********************/
/* Output value wrong */
/**********************/
i_ReturnValue = -4;
}
} else {
/*******************************/
/* Digital I/O not initialised */
/*******************************/
i_ReturnValue = -5;
}
} else {
/******************************************/
/* The module is not a digital I/O module */
/******************************************/
i_ReturnValue = -3;
}
} else {
/***********************/
/* Module number error */
/***********************/
i_ReturnValue = -2;
}
break;
default:
i_ReturnValue = -9;
DPRINTK("NO INPUT/OUTPUT specified\n");
} /* switch INPUT / OUTPUT */
return i_ReturnValue;
}
| gpl-2.0 |
Volidol1/android_kernel_lge_d605 | drivers/gpu/drm/via/via_dmablit.c | 8324 | 21840 | /* via_dmablit.c -- PCI DMA BitBlt support for the VIA Unichrome/Pro
*
* Copyright (C) 2005 Thomas Hellstrom, All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sub license,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Authors:
* Thomas Hellstrom.
* Partially based on code obtained from Digeo Inc.
*/
/*
* Unmaps the DMA mappings.
* FIXME: Is this a NoOp on x86? Also
* FIXME: What happens if this one is called and a pending blit has previously done
* the same DMA mappings?
*/
#include "drmP.h"
#include "via_drm.h"
#include "via_drv.h"
#include "via_dmablit.h"
#include <linux/pagemap.h>
#include <linux/slab.h>
#define VIA_PGDN(x) (((unsigned long)(x)) & PAGE_MASK)
#define VIA_PGOFF(x) (((unsigned long)(x)) & ~PAGE_MASK)
#define VIA_PFN(x) ((unsigned long)(x) >> PAGE_SHIFT)
typedef struct _drm_via_descriptor {
uint32_t mem_addr;
uint32_t dev_addr;
uint32_t size;
uint32_t next;
} drm_via_descriptor_t;
/*
* Unmap a DMA mapping.
*/
static void
via_unmap_blit_from_device(struct pci_dev *pdev, drm_via_sg_info_t *vsg)
{
int num_desc = vsg->num_desc;
unsigned cur_descriptor_page = num_desc / vsg->descriptors_per_page;
unsigned descriptor_this_page = num_desc % vsg->descriptors_per_page;
drm_via_descriptor_t *desc_ptr = vsg->desc_pages[cur_descriptor_page] +
descriptor_this_page;
dma_addr_t next = vsg->chain_start;
while (num_desc--) {
if (descriptor_this_page-- == 0) {
cur_descriptor_page--;
descriptor_this_page = vsg->descriptors_per_page - 1;
desc_ptr = vsg->desc_pages[cur_descriptor_page] +
descriptor_this_page;
}
dma_unmap_single(&pdev->dev, next, sizeof(*desc_ptr), DMA_TO_DEVICE);
dma_unmap_page(&pdev->dev, desc_ptr->mem_addr, desc_ptr->size, vsg->direction);
next = (dma_addr_t) desc_ptr->next;
desc_ptr--;
}
}
/*
* If mode = 0, count how many descriptors are needed.
* If mode = 1, Map the DMA pages for the device, put together and map also the descriptors.
* Descriptors are run in reverse order by the hardware because we are not allowed to update the
* 'next' field without syncing calls when the descriptor is already mapped.
*/
static void
via_map_blit_for_device(struct pci_dev *pdev,
const drm_via_dmablit_t *xfer,
drm_via_sg_info_t *vsg,
int mode)
{
unsigned cur_descriptor_page = 0;
unsigned num_descriptors_this_page = 0;
unsigned char *mem_addr = xfer->mem_addr;
unsigned char *cur_mem;
unsigned char *first_addr = (unsigned char *)VIA_PGDN(mem_addr);
uint32_t fb_addr = xfer->fb_addr;
uint32_t cur_fb;
unsigned long line_len;
unsigned remaining_len;
int num_desc = 0;
int cur_line;
dma_addr_t next = 0 | VIA_DMA_DPR_EC;
drm_via_descriptor_t *desc_ptr = NULL;
if (mode == 1)
desc_ptr = vsg->desc_pages[cur_descriptor_page];
for (cur_line = 0; cur_line < xfer->num_lines; ++cur_line) {
line_len = xfer->line_length;
cur_fb = fb_addr;
cur_mem = mem_addr;
while (line_len > 0) {
remaining_len = min(PAGE_SIZE-VIA_PGOFF(cur_mem), line_len);
line_len -= remaining_len;
if (mode == 1) {
desc_ptr->mem_addr =
dma_map_page(&pdev->dev,
vsg->pages[VIA_PFN(cur_mem) -
VIA_PFN(first_addr)],
VIA_PGOFF(cur_mem), remaining_len,
vsg->direction);
desc_ptr->dev_addr = cur_fb;
desc_ptr->size = remaining_len;
desc_ptr->next = (uint32_t) next;
next = dma_map_single(&pdev->dev, desc_ptr, sizeof(*desc_ptr),
DMA_TO_DEVICE);
desc_ptr++;
if (++num_descriptors_this_page >= vsg->descriptors_per_page) {
num_descriptors_this_page = 0;
desc_ptr = vsg->desc_pages[++cur_descriptor_page];
}
}
num_desc++;
cur_mem += remaining_len;
cur_fb += remaining_len;
}
mem_addr += xfer->mem_stride;
fb_addr += xfer->fb_stride;
}
if (mode == 1) {
vsg->chain_start = next;
vsg->state = dr_via_device_mapped;
}
vsg->num_desc = num_desc;
}
/*
* Function that frees up all resources for a blit. It is usable even if the
* blit info has only been partially built as long as the status enum is consistent
* with the actual status of the used resources.
*/
static void
via_free_sg_info(struct pci_dev *pdev, drm_via_sg_info_t *vsg)
{
struct page *page;
int i;
switch (vsg->state) {
case dr_via_device_mapped:
via_unmap_blit_from_device(pdev, vsg);
case dr_via_desc_pages_alloc:
for (i = 0; i < vsg->num_desc_pages; ++i) {
if (vsg->desc_pages[i] != NULL)
free_page((unsigned long)vsg->desc_pages[i]);
}
kfree(vsg->desc_pages);
case dr_via_pages_locked:
for (i = 0; i < vsg->num_pages; ++i) {
if (NULL != (page = vsg->pages[i])) {
if (!PageReserved(page) && (DMA_FROM_DEVICE == vsg->direction))
SetPageDirty(page);
page_cache_release(page);
}
}
case dr_via_pages_alloc:
vfree(vsg->pages);
default:
vsg->state = dr_via_sg_init;
}
vfree(vsg->bounce_buffer);
vsg->bounce_buffer = NULL;
vsg->free_on_sequence = 0;
}
/*
* Fire a blit engine.
*/
static void
via_fire_dmablit(struct drm_device *dev, drm_via_sg_info_t *vsg, int engine)
{
drm_via_private_t *dev_priv = (drm_via_private_t *)dev->dev_private;
VIA_WRITE(VIA_PCI_DMA_MAR0 + engine*0x10, 0);
VIA_WRITE(VIA_PCI_DMA_DAR0 + engine*0x10, 0);
VIA_WRITE(VIA_PCI_DMA_CSR0 + engine*0x04, VIA_DMA_CSR_DD | VIA_DMA_CSR_TD |
VIA_DMA_CSR_DE);
VIA_WRITE(VIA_PCI_DMA_MR0 + engine*0x04, VIA_DMA_MR_CM | VIA_DMA_MR_TDIE);
VIA_WRITE(VIA_PCI_DMA_BCR0 + engine*0x10, 0);
VIA_WRITE(VIA_PCI_DMA_DPR0 + engine*0x10, vsg->chain_start);
DRM_WRITEMEMORYBARRIER();
VIA_WRITE(VIA_PCI_DMA_CSR0 + engine*0x04, VIA_DMA_CSR_DE | VIA_DMA_CSR_TS);
VIA_READ(VIA_PCI_DMA_CSR0 + engine*0x04);
}
/*
* Obtain a page pointer array and lock all pages into system memory. A segmentation violation will
* occur here if the calling user does not have access to the submitted address.
*/
static int
via_lock_all_dma_pages(drm_via_sg_info_t *vsg, drm_via_dmablit_t *xfer)
{
int ret;
unsigned long first_pfn = VIA_PFN(xfer->mem_addr);
vsg->num_pages = VIA_PFN(xfer->mem_addr + (xfer->num_lines * xfer->mem_stride - 1)) -
first_pfn + 1;
vsg->pages = vzalloc(sizeof(struct page *) * vsg->num_pages);
if (NULL == vsg->pages)
return -ENOMEM;
down_read(¤t->mm->mmap_sem);
ret = get_user_pages(current, current->mm,
(unsigned long)xfer->mem_addr,
vsg->num_pages,
(vsg->direction == DMA_FROM_DEVICE),
0, vsg->pages, NULL);
up_read(¤t->mm->mmap_sem);
if (ret != vsg->num_pages) {
if (ret < 0)
return ret;
vsg->state = dr_via_pages_locked;
return -EINVAL;
}
vsg->state = dr_via_pages_locked;
DRM_DEBUG("DMA pages locked\n");
return 0;
}
/*
* Allocate DMA capable memory for the blit descriptor chain, and an array that keeps track of the
* pages we allocate. We don't want to use kmalloc for the descriptor chain because it may be
* quite large for some blits, and pages don't need to be contingous.
*/
static int
via_alloc_desc_pages(drm_via_sg_info_t *vsg)
{
int i;
vsg->descriptors_per_page = PAGE_SIZE / sizeof(drm_via_descriptor_t);
vsg->num_desc_pages = (vsg->num_desc + vsg->descriptors_per_page - 1) /
vsg->descriptors_per_page;
if (NULL == (vsg->desc_pages = kcalloc(vsg->num_desc_pages, sizeof(void *), GFP_KERNEL)))
return -ENOMEM;
vsg->state = dr_via_desc_pages_alloc;
for (i = 0; i < vsg->num_desc_pages; ++i) {
if (NULL == (vsg->desc_pages[i] =
(drm_via_descriptor_t *) __get_free_page(GFP_KERNEL)))
return -ENOMEM;
}
DRM_DEBUG("Allocated %d pages for %d descriptors.\n", vsg->num_desc_pages,
vsg->num_desc);
return 0;
}
static void
via_abort_dmablit(struct drm_device *dev, int engine)
{
drm_via_private_t *dev_priv = (drm_via_private_t *)dev->dev_private;
VIA_WRITE(VIA_PCI_DMA_CSR0 + engine*0x04, VIA_DMA_CSR_TA);
}
static void
via_dmablit_engine_off(struct drm_device *dev, int engine)
{
drm_via_private_t *dev_priv = (drm_via_private_t *)dev->dev_private;
VIA_WRITE(VIA_PCI_DMA_CSR0 + engine*0x04, VIA_DMA_CSR_TD | VIA_DMA_CSR_DD);
}
/*
* The dmablit part of the IRQ handler. Trying to do only reasonably fast things here.
* The rest, like unmapping and freeing memory for done blits is done in a separate workqueue
* task. Basically the task of the interrupt handler is to submit a new blit to the engine, while
* the workqueue task takes care of processing associated with the old blit.
*/
void
via_dmablit_handler(struct drm_device *dev, int engine, int from_irq)
{
drm_via_private_t *dev_priv = (drm_via_private_t *)dev->dev_private;
drm_via_blitq_t *blitq = dev_priv->blit_queues + engine;
int cur;
int done_transfer;
unsigned long irqsave = 0;
uint32_t status = 0;
DRM_DEBUG("DMA blit handler called. engine = %d, from_irq = %d, blitq = 0x%lx\n",
engine, from_irq, (unsigned long) blitq);
if (from_irq)
spin_lock(&blitq->blit_lock);
else
spin_lock_irqsave(&blitq->blit_lock, irqsave);
done_transfer = blitq->is_active &&
((status = VIA_READ(VIA_PCI_DMA_CSR0 + engine*0x04)) & VIA_DMA_CSR_TD);
done_transfer = done_transfer || (blitq->aborting && !(status & VIA_DMA_CSR_DE));
cur = blitq->cur;
if (done_transfer) {
blitq->blits[cur]->aborted = blitq->aborting;
blitq->done_blit_handle++;
DRM_WAKEUP(blitq->blit_queue + cur);
cur++;
if (cur >= VIA_NUM_BLIT_SLOTS)
cur = 0;
blitq->cur = cur;
/*
* Clear transfer done flag.
*/
VIA_WRITE(VIA_PCI_DMA_CSR0 + engine*0x04, VIA_DMA_CSR_TD);
blitq->is_active = 0;
blitq->aborting = 0;
schedule_work(&blitq->wq);
} else if (blitq->is_active && time_after_eq(jiffies, blitq->end)) {
/*
* Abort transfer after one second.
*/
via_abort_dmablit(dev, engine);
blitq->aborting = 1;
blitq->end = jiffies + DRM_HZ;
}
if (!blitq->is_active) {
if (blitq->num_outstanding) {
via_fire_dmablit(dev, blitq->blits[cur], engine);
blitq->is_active = 1;
blitq->cur = cur;
blitq->num_outstanding--;
blitq->end = jiffies + DRM_HZ;
if (!timer_pending(&blitq->poll_timer))
mod_timer(&blitq->poll_timer, jiffies + 1);
} else {
if (timer_pending(&blitq->poll_timer))
del_timer(&blitq->poll_timer);
via_dmablit_engine_off(dev, engine);
}
}
if (from_irq)
spin_unlock(&blitq->blit_lock);
else
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
}
/*
* Check whether this blit is still active, performing necessary locking.
*/
static int
via_dmablit_active(drm_via_blitq_t *blitq, int engine, uint32_t handle, wait_queue_head_t **queue)
{
unsigned long irqsave;
uint32_t slot;
int active;
spin_lock_irqsave(&blitq->blit_lock, irqsave);
/*
* Allow for handle wraparounds.
*/
active = ((blitq->done_blit_handle - handle) > (1 << 23)) &&
((blitq->cur_blit_handle - handle) <= (1 << 23));
if (queue && active) {
slot = handle - blitq->done_blit_handle + blitq->cur - 1;
if (slot >= VIA_NUM_BLIT_SLOTS)
slot -= VIA_NUM_BLIT_SLOTS;
*queue = blitq->blit_queue + slot;
}
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
return active;
}
/*
* Sync. Wait for at least three seconds for the blit to be performed.
*/
static int
via_dmablit_sync(struct drm_device *dev, uint32_t handle, int engine)
{
drm_via_private_t *dev_priv = (drm_via_private_t *)dev->dev_private;
drm_via_blitq_t *blitq = dev_priv->blit_queues + engine;
wait_queue_head_t *queue;
int ret = 0;
if (via_dmablit_active(blitq, engine, handle, &queue)) {
DRM_WAIT_ON(ret, *queue, 3 * DRM_HZ,
!via_dmablit_active(blitq, engine, handle, NULL));
}
DRM_DEBUG("DMA blit sync handle 0x%x engine %d returned %d\n",
handle, engine, ret);
return ret;
}
/*
* A timer that regularly polls the blit engine in cases where we don't have interrupts:
* a) Broken hardware (typically those that don't have any video capture facility).
* b) Blit abort. The hardware doesn't send an interrupt when a blit is aborted.
* The timer and hardware IRQ's can and do work in parallel. If the hardware has
* irqs, it will shorten the latency somewhat.
*/
static void
via_dmablit_timer(unsigned long data)
{
drm_via_blitq_t *blitq = (drm_via_blitq_t *) data;
struct drm_device *dev = blitq->dev;
int engine = (int)
(blitq - ((drm_via_private_t *)dev->dev_private)->blit_queues);
DRM_DEBUG("Polling timer called for engine %d, jiffies %lu\n", engine,
(unsigned long) jiffies);
via_dmablit_handler(dev, engine, 0);
if (!timer_pending(&blitq->poll_timer)) {
mod_timer(&blitq->poll_timer, jiffies + 1);
/*
* Rerun handler to delete timer if engines are off, and
* to shorten abort latency. This is a little nasty.
*/
via_dmablit_handler(dev, engine, 0);
}
}
/*
* Workqueue task that frees data and mappings associated with a blit.
* Also wakes up waiting processes. Each of these tasks handles one
* blit engine only and may not be called on each interrupt.
*/
static void
via_dmablit_workqueue(struct work_struct *work)
{
drm_via_blitq_t *blitq = container_of(work, drm_via_blitq_t, wq);
struct drm_device *dev = blitq->dev;
unsigned long irqsave;
drm_via_sg_info_t *cur_sg;
int cur_released;
DRM_DEBUG("Workqueue task called for blit engine %ld\n", (unsigned long)
(blitq - ((drm_via_private_t *)dev->dev_private)->blit_queues));
spin_lock_irqsave(&blitq->blit_lock, irqsave);
while (blitq->serviced != blitq->cur) {
cur_released = blitq->serviced++;
DRM_DEBUG("Releasing blit slot %d\n", cur_released);
if (blitq->serviced >= VIA_NUM_BLIT_SLOTS)
blitq->serviced = 0;
cur_sg = blitq->blits[cur_released];
blitq->num_free++;
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
DRM_WAKEUP(&blitq->busy_queue);
via_free_sg_info(dev->pdev, cur_sg);
kfree(cur_sg);
spin_lock_irqsave(&blitq->blit_lock, irqsave);
}
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
}
/*
* Init all blit engines. Currently we use two, but some hardware have 4.
*/
void
via_init_dmablit(struct drm_device *dev)
{
int i, j;
drm_via_private_t *dev_priv = (drm_via_private_t *)dev->dev_private;
drm_via_blitq_t *blitq;
pci_set_master(dev->pdev);
for (i = 0; i < VIA_NUM_BLIT_ENGINES; ++i) {
blitq = dev_priv->blit_queues + i;
blitq->dev = dev;
blitq->cur_blit_handle = 0;
blitq->done_blit_handle = 0;
blitq->head = 0;
blitq->cur = 0;
blitq->serviced = 0;
blitq->num_free = VIA_NUM_BLIT_SLOTS - 1;
blitq->num_outstanding = 0;
blitq->is_active = 0;
blitq->aborting = 0;
spin_lock_init(&blitq->blit_lock);
for (j = 0; j < VIA_NUM_BLIT_SLOTS; ++j)
DRM_INIT_WAITQUEUE(blitq->blit_queue + j);
DRM_INIT_WAITQUEUE(&blitq->busy_queue);
INIT_WORK(&blitq->wq, via_dmablit_workqueue);
setup_timer(&blitq->poll_timer, via_dmablit_timer,
(unsigned long)blitq);
}
}
/*
* Build all info and do all mappings required for a blit.
*/
static int
via_build_sg_info(struct drm_device *dev, drm_via_sg_info_t *vsg, drm_via_dmablit_t *xfer)
{
int draw = xfer->to_fb;
int ret = 0;
vsg->direction = (draw) ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
vsg->bounce_buffer = NULL;
vsg->state = dr_via_sg_init;
if (xfer->num_lines <= 0 || xfer->line_length <= 0) {
DRM_ERROR("Zero size bitblt.\n");
return -EINVAL;
}
/*
* Below check is a driver limitation, not a hardware one. We
* don't want to lock unused pages, and don't want to incoporate the
* extra logic of avoiding them. Make sure there are no.
* (Not a big limitation anyway.)
*/
if ((xfer->mem_stride - xfer->line_length) > 2*PAGE_SIZE) {
DRM_ERROR("Too large system memory stride. Stride: %d, "
"Length: %d\n", xfer->mem_stride, xfer->line_length);
return -EINVAL;
}
if ((xfer->mem_stride == xfer->line_length) &&
(xfer->fb_stride == xfer->line_length)) {
xfer->mem_stride *= xfer->num_lines;
xfer->line_length = xfer->mem_stride;
xfer->fb_stride = xfer->mem_stride;
xfer->num_lines = 1;
}
/*
* Don't lock an arbitrary large number of pages, since that causes a
* DOS security hole.
*/
if (xfer->num_lines > 2048 || (xfer->num_lines*xfer->mem_stride > (2048*2048*4))) {
DRM_ERROR("Too large PCI DMA bitblt.\n");
return -EINVAL;
}
/*
* we allow a negative fb stride to allow flipping of images in
* transfer.
*/
if (xfer->mem_stride < xfer->line_length ||
abs(xfer->fb_stride) < xfer->line_length) {
DRM_ERROR("Invalid frame-buffer / memory stride.\n");
return -EINVAL;
}
/*
* A hardware bug seems to be worked around if system memory addresses start on
* 16 byte boundaries. This seems a bit restrictive however. VIA is contacted
* about this. Meanwhile, impose the following restrictions:
*/
#ifdef VIA_BUGFREE
if ((((unsigned long)xfer->mem_addr & 3) != ((unsigned long)xfer->fb_addr & 3)) ||
((xfer->num_lines > 1) && ((xfer->mem_stride & 3) != (xfer->fb_stride & 3)))) {
DRM_ERROR("Invalid DRM bitblt alignment.\n");
return -EINVAL;
}
#else
if ((((unsigned long)xfer->mem_addr & 15) ||
((unsigned long)xfer->fb_addr & 3)) ||
((xfer->num_lines > 1) &&
((xfer->mem_stride & 15) || (xfer->fb_stride & 3)))) {
DRM_ERROR("Invalid DRM bitblt alignment.\n");
return -EINVAL;
}
#endif
if (0 != (ret = via_lock_all_dma_pages(vsg, xfer))) {
DRM_ERROR("Could not lock DMA pages.\n");
via_free_sg_info(dev->pdev, vsg);
return ret;
}
via_map_blit_for_device(dev->pdev, xfer, vsg, 0);
if (0 != (ret = via_alloc_desc_pages(vsg))) {
DRM_ERROR("Could not allocate DMA descriptor pages.\n");
via_free_sg_info(dev->pdev, vsg);
return ret;
}
via_map_blit_for_device(dev->pdev, xfer, vsg, 1);
return 0;
}
/*
* Reserve one free slot in the blit queue. Will wait for one second for one
* to become available. Otherwise -EBUSY is returned.
*/
static int
via_dmablit_grab_slot(drm_via_blitq_t *blitq, int engine)
{
int ret = 0;
unsigned long irqsave;
DRM_DEBUG("Num free is %d\n", blitq->num_free);
spin_lock_irqsave(&blitq->blit_lock, irqsave);
while (blitq->num_free == 0) {
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
DRM_WAIT_ON(ret, blitq->busy_queue, DRM_HZ, blitq->num_free > 0);
if (ret)
return (-EINTR == ret) ? -EAGAIN : ret;
spin_lock_irqsave(&blitq->blit_lock, irqsave);
}
blitq->num_free--;
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
return 0;
}
/*
* Hand back a free slot if we changed our mind.
*/
static void
via_dmablit_release_slot(drm_via_blitq_t *blitq)
{
unsigned long irqsave;
spin_lock_irqsave(&blitq->blit_lock, irqsave);
blitq->num_free++;
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
DRM_WAKEUP(&blitq->busy_queue);
}
/*
* Grab a free slot. Build blit info and queue a blit.
*/
static int
via_dmablit(struct drm_device *dev, drm_via_dmablit_t *xfer)
{
drm_via_private_t *dev_priv = (drm_via_private_t *)dev->dev_private;
drm_via_sg_info_t *vsg;
drm_via_blitq_t *blitq;
int ret;
int engine;
unsigned long irqsave;
if (dev_priv == NULL) {
DRM_ERROR("Called without initialization.\n");
return -EINVAL;
}
engine = (xfer->to_fb) ? 0 : 1;
blitq = dev_priv->blit_queues + engine;
if (0 != (ret = via_dmablit_grab_slot(blitq, engine)))
return ret;
if (NULL == (vsg = kmalloc(sizeof(*vsg), GFP_KERNEL))) {
via_dmablit_release_slot(blitq);
return -ENOMEM;
}
if (0 != (ret = via_build_sg_info(dev, vsg, xfer))) {
via_dmablit_release_slot(blitq);
kfree(vsg);
return ret;
}
spin_lock_irqsave(&blitq->blit_lock, irqsave);
blitq->blits[blitq->head++] = vsg;
if (blitq->head >= VIA_NUM_BLIT_SLOTS)
blitq->head = 0;
blitq->num_outstanding++;
xfer->sync.sync_handle = ++blitq->cur_blit_handle;
spin_unlock_irqrestore(&blitq->blit_lock, irqsave);
xfer->sync.engine = engine;
via_dmablit_handler(dev, engine, 0);
return 0;
}
/*
* Sync on a previously submitted blit. Note that the X server use signals extensively, and
* that there is a very big probability that this IOCTL will be interrupted by a signal. In that
* case it returns with -EAGAIN for the signal to be delivered.
* The caller should then reissue the IOCTL. This is similar to what is being done for drmGetLock().
*/
int
via_dma_blit_sync(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
drm_via_blitsync_t *sync = data;
int err;
if (sync->engine >= VIA_NUM_BLIT_ENGINES)
return -EINVAL;
err = via_dmablit_sync(dev, sync->sync_handle, sync->engine);
if (-EINTR == err)
err = -EAGAIN;
return err;
}
/*
* Queue a blit and hand back a handle to be used for sync. This IOCTL may be interrupted by a signal
* while waiting for a free slot in the blit queue. In that case it returns with -EAGAIN and should
* be reissued. See the above IOCTL code.
*/
int
via_dma_blit(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
drm_via_dmablit_t *xfer = data;
int err;
err = via_dmablit(dev, xfer);
return err;
}
| gpl-2.0 |
CyanogenMod/android_kernel_mediatek_sprout | arch/powerpc/platforms/cell/beat_udbg.c | 12676 | 2419 | /*
* udbg function for Beat
*
* (C) Copyright 2006 TOSHIBA CORPORATION
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <linux/kernel.h>
#include <linux/console.h>
#include <asm/machdep.h>
#include <asm/prom.h>
#include <asm/udbg.h>
#include "beat.h"
#define celleb_vtermno 0
static void udbg_putc_beat(char c)
{
unsigned long rc;
if (c == '\n')
udbg_putc_beat('\r');
rc = beat_put_term_char(celleb_vtermno, 1, (uint64_t)c << 56, 0);
}
/* Buffered chars getc */
static u64 inbuflen;
static u64 inbuf[2]; /* must be 2 u64s */
static int udbg_getc_poll_beat(void)
{
/* The interface is tricky because it may return up to 16 chars.
* We save them statically for future calls to udbg_getc().
*/
char ch, *buf = (char *)inbuf;
int i;
long rc;
if (inbuflen == 0) {
/* get some more chars. */
inbuflen = 0;
rc = beat_get_term_char(celleb_vtermno, &inbuflen,
inbuf+0, inbuf+1);
if (rc != 0)
inbuflen = 0; /* otherwise inbuflen is garbage */
}
if (inbuflen <= 0 || inbuflen > 16) {
/* Catch error case as well as other oddities (corruption) */
inbuflen = 0;
return -1;
}
ch = buf[0];
for (i = 1; i < inbuflen; i++) /* shuffle them down. */
buf[i-1] = buf[i];
inbuflen--;
return ch;
}
static int udbg_getc_beat(void)
{
int ch;
for (;;) {
ch = udbg_getc_poll_beat();
if (ch == -1) {
/* This shouldn't be needed...but... */
volatile unsigned long delay;
for (delay = 0; delay < 2000000; delay++)
;
} else {
return ch;
}
}
}
/* call this from early_init() for a working debug console on
* vterm capable LPAR machines
*/
void __init udbg_init_debug_beat(void)
{
udbg_putc = udbg_putc_beat;
udbg_getc = udbg_getc_beat;
udbg_getc_poll = udbg_getc_poll_beat;
}
| gpl-2.0 |
unusual-thoughts/linux-xps13 | drivers/i2c/busses/i2c-bcm2835.c | 133 | 8953 | /*
* BCM2835 master mode driver
*
* 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/clk.h>
#include <linux/completion.h>
#include <linux/err.h>
#include <linux/i2c.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#define BCM2835_I2C_C 0x0
#define BCM2835_I2C_S 0x4
#define BCM2835_I2C_DLEN 0x8
#define BCM2835_I2C_A 0xc
#define BCM2835_I2C_FIFO 0x10
#define BCM2835_I2C_DIV 0x14
#define BCM2835_I2C_DEL 0x18
#define BCM2835_I2C_CLKT 0x1c
#define BCM2835_I2C_C_READ BIT(0)
#define BCM2835_I2C_C_CLEAR BIT(4) /* bits 4 and 5 both clear */
#define BCM2835_I2C_C_ST BIT(7)
#define BCM2835_I2C_C_INTD BIT(8)
#define BCM2835_I2C_C_INTT BIT(9)
#define BCM2835_I2C_C_INTR BIT(10)
#define BCM2835_I2C_C_I2CEN BIT(15)
#define BCM2835_I2C_S_TA BIT(0)
#define BCM2835_I2C_S_DONE BIT(1)
#define BCM2835_I2C_S_TXW BIT(2)
#define BCM2835_I2C_S_RXR BIT(3)
#define BCM2835_I2C_S_TXD BIT(4)
#define BCM2835_I2C_S_RXD BIT(5)
#define BCM2835_I2C_S_TXE BIT(6)
#define BCM2835_I2C_S_RXF BIT(7)
#define BCM2835_I2C_S_ERR BIT(8)
#define BCM2835_I2C_S_CLKT BIT(9)
#define BCM2835_I2C_S_LEN BIT(10) /* Fake bit for SW error reporting */
#define BCM2835_I2C_BITMSK_S 0x03FF
#define BCM2835_I2C_CDIV_MIN 0x0002
#define BCM2835_I2C_CDIV_MAX 0xFFFE
#define BCM2835_I2C_TIMEOUT (msecs_to_jiffies(1000))
struct bcm2835_i2c_dev {
struct device *dev;
void __iomem *regs;
struct clk *clk;
int irq;
struct i2c_adapter adapter;
struct completion completion;
u32 msg_err;
u8 *msg_buf;
size_t msg_buf_remaining;
};
static inline void bcm2835_i2c_writel(struct bcm2835_i2c_dev *i2c_dev,
u32 reg, u32 val)
{
writel(val, i2c_dev->regs + reg);
}
static inline u32 bcm2835_i2c_readl(struct bcm2835_i2c_dev *i2c_dev, u32 reg)
{
return readl(i2c_dev->regs + reg);
}
static void bcm2835_fill_txfifo(struct bcm2835_i2c_dev *i2c_dev)
{
u32 val;
while (i2c_dev->msg_buf_remaining) {
val = bcm2835_i2c_readl(i2c_dev, BCM2835_I2C_S);
if (!(val & BCM2835_I2C_S_TXD))
break;
bcm2835_i2c_writel(i2c_dev, BCM2835_I2C_FIFO,
*i2c_dev->msg_buf);
i2c_dev->msg_buf++;
i2c_dev->msg_buf_remaining--;
}
}
static void bcm2835_drain_rxfifo(struct bcm2835_i2c_dev *i2c_dev)
{
u32 val;
while (i2c_dev->msg_buf_remaining) {
val = bcm2835_i2c_readl(i2c_dev, BCM2835_I2C_S);
if (!(val & BCM2835_I2C_S_RXD))
break;
*i2c_dev->msg_buf = bcm2835_i2c_readl(i2c_dev,
BCM2835_I2C_FIFO);
i2c_dev->msg_buf++;
i2c_dev->msg_buf_remaining--;
}
}
static irqreturn_t bcm2835_i2c_isr(int this_irq, void *data)
{
struct bcm2835_i2c_dev *i2c_dev = data;
u32 val, err;
val = bcm2835_i2c_readl(i2c_dev, BCM2835_I2C_S);
val &= BCM2835_I2C_BITMSK_S;
bcm2835_i2c_writel(i2c_dev, BCM2835_I2C_S, val);
err = val & (BCM2835_I2C_S_CLKT | BCM2835_I2C_S_ERR);
if (err) {
i2c_dev->msg_err = err;
complete(&i2c_dev->completion);
return IRQ_HANDLED;
}
if (val & BCM2835_I2C_S_RXD) {
bcm2835_drain_rxfifo(i2c_dev);
if (!(val & BCM2835_I2C_S_DONE))
return IRQ_HANDLED;
}
if (val & BCM2835_I2C_S_DONE) {
if (i2c_dev->msg_buf_remaining)
i2c_dev->msg_err = BCM2835_I2C_S_LEN;
else
i2c_dev->msg_err = 0;
complete(&i2c_dev->completion);
return IRQ_HANDLED;
}
if (val & BCM2835_I2C_S_TXD) {
bcm2835_fill_txfifo(i2c_dev);
return IRQ_HANDLED;
}
return IRQ_NONE;
}
static int bcm2835_i2c_xfer_msg(struct bcm2835_i2c_dev *i2c_dev,
struct i2c_msg *msg)
{
u32 c;
unsigned long time_left;
i2c_dev->msg_buf = msg->buf;
i2c_dev->msg_buf_remaining = msg->len;
reinit_completion(&i2c_dev->completion);
bcm2835_i2c_writel(i2c_dev, BCM2835_I2C_C, BCM2835_I2C_C_CLEAR);
if (msg->flags & I2C_M_RD) {
c = BCM2835_I2C_C_READ | BCM2835_I2C_C_INTR;
} else {
c = BCM2835_I2C_C_INTT;
bcm2835_fill_txfifo(i2c_dev);
}
c |= BCM2835_I2C_C_ST | BCM2835_I2C_C_INTD | BCM2835_I2C_C_I2CEN;
bcm2835_i2c_writel(i2c_dev, BCM2835_I2C_A, msg->addr);
bcm2835_i2c_writel(i2c_dev, BCM2835_I2C_DLEN, msg->len);
bcm2835_i2c_writel(i2c_dev, BCM2835_I2C_C, c);
time_left = wait_for_completion_timeout(&i2c_dev->completion,
BCM2835_I2C_TIMEOUT);
bcm2835_i2c_writel(i2c_dev, BCM2835_I2C_C, BCM2835_I2C_C_CLEAR);
if (!time_left) {
dev_err(i2c_dev->dev, "i2c transfer timed out\n");
return -ETIMEDOUT;
}
if (likely(!i2c_dev->msg_err))
return 0;
if ((i2c_dev->msg_err & BCM2835_I2C_S_ERR) &&
(msg->flags & I2C_M_IGNORE_NAK))
return 0;
dev_err(i2c_dev->dev, "i2c transfer failed: %x\n", i2c_dev->msg_err);
if (i2c_dev->msg_err & BCM2835_I2C_S_ERR)
return -EREMOTEIO;
else
return -EIO;
}
static int bcm2835_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg msgs[],
int num)
{
struct bcm2835_i2c_dev *i2c_dev = i2c_get_adapdata(adap);
int i;
int ret = 0;
for (i = 0; i < num; i++) {
ret = bcm2835_i2c_xfer_msg(i2c_dev, &msgs[i]);
if (ret)
break;
}
return ret ?: i;
}
static u32 bcm2835_i2c_func(struct i2c_adapter *adap)
{
return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
}
static const struct i2c_algorithm bcm2835_i2c_algo = {
.master_xfer = bcm2835_i2c_xfer,
.functionality = bcm2835_i2c_func,
};
/*
* This HW was reported to have problems with clock stretching:
* http://www.advamation.com/knowhow/raspberrypi/rpi-i2c-bug.html
* https://www.raspberrypi.org/forums/viewtopic.php?p=146272
*/
static const struct i2c_adapter_quirks bcm2835_i2c_quirks = {
.flags = I2C_AQ_NO_CLK_STRETCH,
};
static int bcm2835_i2c_probe(struct platform_device *pdev)
{
struct bcm2835_i2c_dev *i2c_dev;
struct resource *mem, *irq;
u32 bus_clk_rate, divider;
int ret;
struct i2c_adapter *adap;
i2c_dev = devm_kzalloc(&pdev->dev, sizeof(*i2c_dev), GFP_KERNEL);
if (!i2c_dev)
return -ENOMEM;
platform_set_drvdata(pdev, i2c_dev);
i2c_dev->dev = &pdev->dev;
init_completion(&i2c_dev->completion);
mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
i2c_dev->regs = devm_ioremap_resource(&pdev->dev, mem);
if (IS_ERR(i2c_dev->regs))
return PTR_ERR(i2c_dev->regs);
i2c_dev->clk = devm_clk_get(&pdev->dev, NULL);
if (IS_ERR(i2c_dev->clk)) {
dev_err(&pdev->dev, "Could not get clock\n");
return PTR_ERR(i2c_dev->clk);
}
ret = of_property_read_u32(pdev->dev.of_node, "clock-frequency",
&bus_clk_rate);
if (ret < 0) {
dev_warn(&pdev->dev,
"Could not read clock-frequency property\n");
bus_clk_rate = 100000;
}
divider = DIV_ROUND_UP(clk_get_rate(i2c_dev->clk), bus_clk_rate);
/*
* Per the datasheet, the register is always interpreted as an even
* number, by rounding down. In other words, the LSB is ignored. So,
* if the LSB is set, increment the divider to avoid any issue.
*/
if (divider & 1)
divider++;
if ((divider < BCM2835_I2C_CDIV_MIN) ||
(divider > BCM2835_I2C_CDIV_MAX)) {
dev_err(&pdev->dev, "Invalid clock-frequency\n");
return -ENODEV;
}
bcm2835_i2c_writel(i2c_dev, BCM2835_I2C_DIV, divider);
irq = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!irq) {
dev_err(&pdev->dev, "No IRQ resource\n");
return -ENODEV;
}
i2c_dev->irq = irq->start;
ret = request_irq(i2c_dev->irq, bcm2835_i2c_isr, IRQF_SHARED,
dev_name(&pdev->dev), i2c_dev);
if (ret) {
dev_err(&pdev->dev, "Could not request IRQ\n");
return -ENODEV;
}
adap = &i2c_dev->adapter;
i2c_set_adapdata(adap, i2c_dev);
adap->owner = THIS_MODULE;
adap->class = I2C_CLASS_DEPRECATED;
strlcpy(adap->name, "bcm2835 I2C adapter", sizeof(adap->name));
adap->algo = &bcm2835_i2c_algo;
adap->dev.parent = &pdev->dev;
adap->dev.of_node = pdev->dev.of_node;
adap->quirks = &bcm2835_i2c_quirks;
bcm2835_i2c_writel(i2c_dev, BCM2835_I2C_C, 0);
ret = i2c_add_adapter(adap);
if (ret)
free_irq(i2c_dev->irq, i2c_dev);
return ret;
}
static int bcm2835_i2c_remove(struct platform_device *pdev)
{
struct bcm2835_i2c_dev *i2c_dev = platform_get_drvdata(pdev);
free_irq(i2c_dev->irq, i2c_dev);
i2c_del_adapter(&i2c_dev->adapter);
return 0;
}
static const struct of_device_id bcm2835_i2c_of_match[] = {
{ .compatible = "brcm,bcm2835-i2c" },
{},
};
MODULE_DEVICE_TABLE(of, bcm2835_i2c_of_match);
static struct platform_driver bcm2835_i2c_driver = {
.probe = bcm2835_i2c_probe,
.remove = bcm2835_i2c_remove,
.driver = {
.name = "i2c-bcm2835",
.of_match_table = bcm2835_i2c_of_match,
},
};
module_platform_driver(bcm2835_i2c_driver);
MODULE_AUTHOR("Stephen Warren <swarren@wwwdotorg.org>");
MODULE_DESCRIPTION("BCM2835 I2C bus adapter");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:i2c-bcm2835");
| gpl-2.0 |
xiufeng/TCP-LTE | drivers/input/touchscreen/sun4i-ts.c | 133 | 11477 | /*
* Allwinner sunxi resistive touchscreen controller driver
*
* Copyright (C) 2013 - 2014 Hans de Goede <hdegoede@redhat.com>
*
* The hwmon parts are based on work by Corentin LABBE which is:
* Copyright (C) 2013 Corentin LABBE <clabbe.montjoie@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
/*
* The sun4i-ts controller is capable of detecting a second touch, but when a
* second touch is present then the accuracy becomes so bad the reported touch
* location is not useable.
*
* The original android driver contains some complicated heuristics using the
* aprox. distance between the 2 touches to see if the user is making a pinch
* open / close movement, and then reports emulated multi-touch events around
* the last touch coordinate (as the dual-touch coordinates are worthless).
*
* These kinds of heuristics are just asking for trouble (and don't belong
* in the kernel). So this driver offers straight forward, reliable single
* touch functionality only.
*/
#include <linux/err.h>
#include <linux/hwmon.h>
#include <linux/thermal.h>
#include <linux/init.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/of_platform.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#define TP_CTRL0 0x00
#define TP_CTRL1 0x04
#define TP_CTRL2 0x08
#define TP_CTRL3 0x0c
#define TP_INT_FIFOC 0x10
#define TP_INT_FIFOS 0x14
#define TP_TPR 0x18
#define TP_CDAT 0x1c
#define TEMP_DATA 0x20
#define TP_DATA 0x24
/* TP_CTRL0 bits */
#define ADC_FIRST_DLY(x) ((x) << 24) /* 8 bits */
#define ADC_FIRST_DLY_MODE(x) ((x) << 23)
#define ADC_CLK_SEL(x) ((x) << 22)
#define ADC_CLK_DIV(x) ((x) << 20) /* 3 bits */
#define FS_DIV(x) ((x) << 16) /* 4 bits */
#define T_ACQ(x) ((x) << 0) /* 16 bits */
/* TP_CTRL1 bits */
#define STYLUS_UP_DEBOUN(x) ((x) << 12) /* 8 bits */
#define STYLUS_UP_DEBOUN_EN(x) ((x) << 9)
#define TOUCH_PAN_CALI_EN(x) ((x) << 6)
#define TP_DUAL_EN(x) ((x) << 5)
#define TP_MODE_EN(x) ((x) << 4)
#define TP_ADC_SELECT(x) ((x) << 3)
#define ADC_CHAN_SELECT(x) ((x) << 0) /* 3 bits */
/* on sun6i, bits 3~6 are left shifted by 1 to 4~7 */
#define SUN6I_TP_MODE_EN(x) ((x) << 5)
/* TP_CTRL2 bits */
#define TP_SENSITIVE_ADJUST(x) ((x) << 28) /* 4 bits */
#define TP_MODE_SELECT(x) ((x) << 26) /* 2 bits */
#define PRE_MEA_EN(x) ((x) << 24)
#define PRE_MEA_THRE_CNT(x) ((x) << 0) /* 24 bits */
/* TP_CTRL3 bits */
#define FILTER_EN(x) ((x) << 2)
#define FILTER_TYPE(x) ((x) << 0) /* 2 bits */
/* TP_INT_FIFOC irq and fifo mask / control bits */
#define TEMP_IRQ_EN(x) ((x) << 18)
#define OVERRUN_IRQ_EN(x) ((x) << 17)
#define DATA_IRQ_EN(x) ((x) << 16)
#define TP_DATA_XY_CHANGE(x) ((x) << 13)
#define FIFO_TRIG(x) ((x) << 8) /* 5 bits */
#define DATA_DRQ_EN(x) ((x) << 7)
#define FIFO_FLUSH(x) ((x) << 4)
#define TP_UP_IRQ_EN(x) ((x) << 1)
#define TP_DOWN_IRQ_EN(x) ((x) << 0)
/* TP_INT_FIFOS irq and fifo status bits */
#define TEMP_DATA_PENDING BIT(18)
#define FIFO_OVERRUN_PENDING BIT(17)
#define FIFO_DATA_PENDING BIT(16)
#define TP_IDLE_FLG BIT(2)
#define TP_UP_PENDING BIT(1)
#define TP_DOWN_PENDING BIT(0)
/* TP_TPR bits */
#define TEMP_ENABLE(x) ((x) << 16)
#define TEMP_PERIOD(x) ((x) << 0) /* t = x * 256 * 16 / clkin */
struct sun4i_ts_data {
struct device *dev;
struct input_dev *input;
struct thermal_zone_device *tz;
void __iomem *base;
unsigned int irq;
bool ignore_fifo_data;
int temp_data;
int temp_offset;
int temp_step;
};
static void sun4i_ts_irq_handle_input(struct sun4i_ts_data *ts, u32 reg_val)
{
u32 x, y;
if (reg_val & FIFO_DATA_PENDING) {
x = readl(ts->base + TP_DATA);
y = readl(ts->base + TP_DATA);
/* The 1st location reported after an up event is unreliable */
if (!ts->ignore_fifo_data) {
input_report_abs(ts->input, ABS_X, x);
input_report_abs(ts->input, ABS_Y, y);
/*
* The hardware has a separate down status bit, but
* that gets set before we get the first location,
* resulting in reporting a click on the old location.
*/
input_report_key(ts->input, BTN_TOUCH, 1);
input_sync(ts->input);
} else {
ts->ignore_fifo_data = false;
}
}
if (reg_val & TP_UP_PENDING) {
ts->ignore_fifo_data = true;
input_report_key(ts->input, BTN_TOUCH, 0);
input_sync(ts->input);
}
}
static irqreturn_t sun4i_ts_irq(int irq, void *dev_id)
{
struct sun4i_ts_data *ts = dev_id;
u32 reg_val;
reg_val = readl(ts->base + TP_INT_FIFOS);
if (reg_val & TEMP_DATA_PENDING)
ts->temp_data = readl(ts->base + TEMP_DATA);
if (ts->input)
sun4i_ts_irq_handle_input(ts, reg_val);
writel(reg_val, ts->base + TP_INT_FIFOS);
return IRQ_HANDLED;
}
static int sun4i_ts_open(struct input_dev *dev)
{
struct sun4i_ts_data *ts = input_get_drvdata(dev);
/* Flush, set trig level to 1, enable temp, data and up irqs */
writel(TEMP_IRQ_EN(1) | DATA_IRQ_EN(1) | FIFO_TRIG(1) | FIFO_FLUSH(1) |
TP_UP_IRQ_EN(1), ts->base + TP_INT_FIFOC);
return 0;
}
static void sun4i_ts_close(struct input_dev *dev)
{
struct sun4i_ts_data *ts = input_get_drvdata(dev);
/* Deactivate all input IRQs */
writel(TEMP_IRQ_EN(1), ts->base + TP_INT_FIFOC);
}
static int sun4i_get_temp(const struct sun4i_ts_data *ts, long *temp)
{
/* No temp_data until the first irq */
if (ts->temp_data == -1)
return -EAGAIN;
*temp = (ts->temp_data - ts->temp_offset) * ts->temp_step;
return 0;
}
static int sun4i_get_tz_temp(void *data, long *temp)
{
return sun4i_get_temp(data, temp);
}
static struct thermal_zone_of_device_ops sun4i_ts_tz_ops = {
.get_temp = sun4i_get_tz_temp,
};
static ssize_t show_temp(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct sun4i_ts_data *ts = dev_get_drvdata(dev);
long temp;
int error;
error = sun4i_get_temp(ts, &temp);
if (error)
return error;
return sprintf(buf, "%ld\n", temp);
}
static ssize_t show_temp_label(struct device *dev,
struct device_attribute *devattr, char *buf)
{
return sprintf(buf, "SoC temperature\n");
}
static DEVICE_ATTR(temp1_input, S_IRUGO, show_temp, NULL);
static DEVICE_ATTR(temp1_label, S_IRUGO, show_temp_label, NULL);
static struct attribute *sun4i_ts_attrs[] = {
&dev_attr_temp1_input.attr,
&dev_attr_temp1_label.attr,
NULL
};
ATTRIBUTE_GROUPS(sun4i_ts);
static int sun4i_ts_probe(struct platform_device *pdev)
{
struct sun4i_ts_data *ts;
struct device *dev = &pdev->dev;
struct device_node *np = dev->of_node;
struct device *hwmon;
int error;
u32 reg;
bool ts_attached;
ts = devm_kzalloc(dev, sizeof(struct sun4i_ts_data), GFP_KERNEL);
if (!ts)
return -ENOMEM;
ts->dev = dev;
ts->ignore_fifo_data = true;
ts->temp_data = -1;
if (of_device_is_compatible(np, "allwinner,sun6i-a31-ts")) {
/* Allwinner SDK has temperature = -271 + (value / 6) (C) */
ts->temp_offset = 1626;
ts->temp_step = 167;
} else {
/*
* The user manuals do not contain the formula for calculating
* the temperature. The formula used here is from the AXP209,
* which is designed by X-Powers, an affiliate of Allwinner:
*
* temperature = -144.7 + (value * 0.1)
*
* Allwinner does not have any documentation whatsoever for
* this hardware. Moreover, it is claimed that the sensor
* is inaccurate and cannot work properly.
*/
ts->temp_offset = 1447;
ts->temp_step = 100;
}
ts_attached = of_property_read_bool(np, "allwinner,ts-attached");
if (ts_attached) {
ts->input = devm_input_allocate_device(dev);
if (!ts->input)
return -ENOMEM;
ts->input->name = pdev->name;
ts->input->phys = "sun4i_ts/input0";
ts->input->open = sun4i_ts_open;
ts->input->close = sun4i_ts_close;
ts->input->id.bustype = BUS_HOST;
ts->input->id.vendor = 0x0001;
ts->input->id.product = 0x0001;
ts->input->id.version = 0x0100;
ts->input->evbit[0] = BIT(EV_SYN) | BIT(EV_KEY) | BIT(EV_ABS);
__set_bit(BTN_TOUCH, ts->input->keybit);
input_set_abs_params(ts->input, ABS_X, 0, 4095, 0, 0);
input_set_abs_params(ts->input, ABS_Y, 0, 4095, 0, 0);
input_set_drvdata(ts->input, ts);
}
ts->base = devm_ioremap_resource(dev,
platform_get_resource(pdev, IORESOURCE_MEM, 0));
if (IS_ERR(ts->base))
return PTR_ERR(ts->base);
ts->irq = platform_get_irq(pdev, 0);
error = devm_request_irq(dev, ts->irq, sun4i_ts_irq, 0, "sun4i-ts", ts);
if (error)
return error;
/*
* Select HOSC clk, clkin = clk / 6, adc samplefreq = clkin / 8192,
* t_acq = clkin / (16 * 64)
*/
writel(ADC_CLK_SEL(0) | ADC_CLK_DIV(2) | FS_DIV(7) | T_ACQ(63),
ts->base + TP_CTRL0);
/*
* sensitive_adjust = 15 : max, which is not all that sensitive,
* tp_mode = 0 : only x and y coordinates, as we don't use dual touch
*/
writel(TP_SENSITIVE_ADJUST(15) | TP_MODE_SELECT(0),
ts->base + TP_CTRL2);
/* Enable median filter, type 1 : 5/3 */
writel(FILTER_EN(1) | FILTER_TYPE(1), ts->base + TP_CTRL3);
/* Enable temperature measurement, period 1953 (2 seconds) */
writel(TEMP_ENABLE(1) | TEMP_PERIOD(1953), ts->base + TP_TPR);
/*
* Set stylus up debounce to aprox 10 ms, enable debounce, and
* finally enable tp mode.
*/
reg = STYLUS_UP_DEBOUN(5) | STYLUS_UP_DEBOUN_EN(1);
if (of_device_is_compatible(np, "allwinner,sun4i-a10-ts"))
reg |= TP_MODE_EN(1);
else
reg |= SUN6I_TP_MODE_EN(1);
writel(reg, ts->base + TP_CTRL1);
/*
* The thermal core does not register hwmon devices for DT-based
* thermal zone sensors, such as this one.
*/
hwmon = devm_hwmon_device_register_with_groups(ts->dev, "sun4i_ts",
ts, sun4i_ts_groups);
if (IS_ERR(hwmon))
return PTR_ERR(hwmon);
ts->tz = thermal_zone_of_sensor_register(ts->dev, 0, ts,
&sun4i_ts_tz_ops);
if (IS_ERR(ts->tz))
ts->tz = NULL;
writel(TEMP_IRQ_EN(1), ts->base + TP_INT_FIFOC);
if (ts_attached) {
error = input_register_device(ts->input);
if (error) {
writel(0, ts->base + TP_INT_FIFOC);
thermal_zone_of_sensor_unregister(ts->dev, ts->tz);
return error;
}
}
platform_set_drvdata(pdev, ts);
return 0;
}
static int sun4i_ts_remove(struct platform_device *pdev)
{
struct sun4i_ts_data *ts = platform_get_drvdata(pdev);
/* Explicit unregister to avoid open/close changing the imask later */
if (ts->input)
input_unregister_device(ts->input);
thermal_zone_of_sensor_unregister(ts->dev, ts->tz);
/* Deactivate all IRQs */
writel(0, ts->base + TP_INT_FIFOC);
return 0;
}
static const struct of_device_id sun4i_ts_of_match[] = {
{ .compatible = "allwinner,sun4i-a10-ts", },
{ .compatible = "allwinner,sun6i-a31-ts", },
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, sun4i_ts_of_match);
static struct platform_driver sun4i_ts_driver = {
.driver = {
.name = "sun4i-ts",
.of_match_table = of_match_ptr(sun4i_ts_of_match),
},
.probe = sun4i_ts_probe,
.remove = sun4i_ts_remove,
};
module_platform_driver(sun4i_ts_driver);
MODULE_DESCRIPTION("Allwinner sun4i resistive touchscreen controller driver");
MODULE_AUTHOR("Hans de Goede <hdegoede@redhat.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
AospPlus/android_kernel_x86 | drivers/net/can/bfin_can.c | 133 | 16688 | /*
* Blackfin On-Chip CAN Driver
*
* Copyright 2004-2009 Analog Devices Inc.
*
* Enter bugs at http://blackfin.uclinux.org/
*
* Licensed under the GPL-2 or later.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/bitops.h>
#include <linux/interrupt.h>
#include <linux/errno.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <linux/platform_device.h>
#include <linux/can/dev.h>
#include <linux/can/error.h>
#include <asm/bfin_can.h>
#include <asm/portmux.h>
#define DRV_NAME "bfin_can"
#define BFIN_CAN_TIMEOUT 100
#define TX_ECHO_SKB_MAX 1
/*
* bfin can private data
*/
struct bfin_can_priv {
struct can_priv can; /* must be the first member */
struct net_device *dev;
void __iomem *membase;
int rx_irq;
int tx_irq;
int err_irq;
unsigned short *pin_list;
};
/*
* bfin can timing parameters
*/
static const struct can_bittiming_const bfin_can_bittiming_const = {
.name = DRV_NAME,
.tseg1_min = 1,
.tseg1_max = 16,
.tseg2_min = 1,
.tseg2_max = 8,
.sjw_max = 4,
/*
* Although the BRP field can be set to any value, it is recommended
* that the value be greater than or equal to 4, as restrictions
* apply to the bit timing configuration when BRP is less than 4.
*/
.brp_min = 4,
.brp_max = 1024,
.brp_inc = 1,
};
static int bfin_can_set_bittiming(struct net_device *dev)
{
struct bfin_can_priv *priv = netdev_priv(dev);
struct bfin_can_regs __iomem *reg = priv->membase;
struct can_bittiming *bt = &priv->can.bittiming;
u16 clk, timing;
clk = bt->brp - 1;
timing = ((bt->sjw - 1) << 8) | (bt->prop_seg + bt->phase_seg1 - 1) |
((bt->phase_seg2 - 1) << 4);
/*
* If the SAM bit is set, the input signal is oversampled three times
* at the SCLK rate.
*/
if (priv->can.ctrlmode & CAN_CTRLMODE_3_SAMPLES)
timing |= SAM;
bfin_write(®->clock, clk);
bfin_write(®->timing, timing);
netdev_info(dev, "setting CLOCK=0x%04x TIMING=0x%04x\n", clk, timing);
return 0;
}
static void bfin_can_set_reset_mode(struct net_device *dev)
{
struct bfin_can_priv *priv = netdev_priv(dev);
struct bfin_can_regs __iomem *reg = priv->membase;
int timeout = BFIN_CAN_TIMEOUT;
int i;
/* disable interrupts */
bfin_write(®->mbim1, 0);
bfin_write(®->mbim2, 0);
bfin_write(®->gim, 0);
/* reset can and enter configuration mode */
bfin_write(®->control, SRS | CCR);
SSYNC();
bfin_write(®->control, CCR);
SSYNC();
while (!(bfin_read(®->control) & CCA)) {
udelay(10);
if (--timeout == 0) {
netdev_err(dev, "fail to enter configuration mode\n");
BUG();
}
}
/*
* All mailbox configurations are marked as inactive
* by writing to CAN Mailbox Configuration Registers 1 and 2
* For all bits: 0 - Mailbox disabled, 1 - Mailbox enabled
*/
bfin_write(®->mc1, 0);
bfin_write(®->mc2, 0);
/* Set Mailbox Direction */
bfin_write(®->md1, 0xFFFF); /* mailbox 1-16 are RX */
bfin_write(®->md2, 0); /* mailbox 17-32 are TX */
/* RECEIVE_STD_CHL */
for (i = 0; i < 2; i++) {
bfin_write(®->chl[RECEIVE_STD_CHL + i].id0, 0);
bfin_write(®->chl[RECEIVE_STD_CHL + i].id1, AME);
bfin_write(®->chl[RECEIVE_STD_CHL + i].dlc, 0);
bfin_write(®->msk[RECEIVE_STD_CHL + i].amh, 0x1FFF);
bfin_write(®->msk[RECEIVE_STD_CHL + i].aml, 0xFFFF);
}
/* RECEIVE_EXT_CHL */
for (i = 0; i < 2; i++) {
bfin_write(®->chl[RECEIVE_EXT_CHL + i].id0, 0);
bfin_write(®->chl[RECEIVE_EXT_CHL + i].id1, AME | IDE);
bfin_write(®->chl[RECEIVE_EXT_CHL + i].dlc, 0);
bfin_write(®->msk[RECEIVE_EXT_CHL + i].amh, 0x1FFF);
bfin_write(®->msk[RECEIVE_EXT_CHL + i].aml, 0xFFFF);
}
bfin_write(®->mc2, BIT(TRANSMIT_CHL - 16));
bfin_write(®->mc1, BIT(RECEIVE_STD_CHL) + BIT(RECEIVE_EXT_CHL));
SSYNC();
priv->can.state = CAN_STATE_STOPPED;
}
static void bfin_can_set_normal_mode(struct net_device *dev)
{
struct bfin_can_priv *priv = netdev_priv(dev);
struct bfin_can_regs __iomem *reg = priv->membase;
int timeout = BFIN_CAN_TIMEOUT;
/*
* leave configuration mode
*/
bfin_write(®->control, bfin_read(®->control) & ~CCR);
while (bfin_read(®->status) & CCA) {
udelay(10);
if (--timeout == 0) {
netdev_err(dev, "fail to leave configuration mode\n");
BUG();
}
}
/*
* clear _All_ tx and rx interrupts
*/
bfin_write(®->mbtif1, 0xFFFF);
bfin_write(®->mbtif2, 0xFFFF);
bfin_write(®->mbrif1, 0xFFFF);
bfin_write(®->mbrif2, 0xFFFF);
/*
* clear global interrupt status register
*/
bfin_write(®->gis, 0x7FF); /* overwrites with '1' */
/*
* Initialize Interrupts
* - set bits in the mailbox interrupt mask register
* - global interrupt mask
*/
bfin_write(®->mbim1, BIT(RECEIVE_STD_CHL) + BIT(RECEIVE_EXT_CHL));
bfin_write(®->mbim2, BIT(TRANSMIT_CHL - 16));
bfin_write(®->gim, EPIM | BOIM | RMLIM);
SSYNC();
}
static void bfin_can_start(struct net_device *dev)
{
struct bfin_can_priv *priv = netdev_priv(dev);
/* enter reset mode */
if (priv->can.state != CAN_STATE_STOPPED)
bfin_can_set_reset_mode(dev);
/* leave reset mode */
bfin_can_set_normal_mode(dev);
}
static int bfin_can_set_mode(struct net_device *dev, enum can_mode mode)
{
switch (mode) {
case CAN_MODE_START:
bfin_can_start(dev);
if (netif_queue_stopped(dev))
netif_wake_queue(dev);
break;
default:
return -EOPNOTSUPP;
}
return 0;
}
static int bfin_can_get_berr_counter(const struct net_device *dev,
struct can_berr_counter *bec)
{
struct bfin_can_priv *priv = netdev_priv(dev);
struct bfin_can_regs __iomem *reg = priv->membase;
u16 cec = bfin_read(®->cec);
bec->txerr = cec >> 8;
bec->rxerr = cec;
return 0;
}
static int bfin_can_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct bfin_can_priv *priv = netdev_priv(dev);
struct bfin_can_regs __iomem *reg = priv->membase;
struct can_frame *cf = (struct can_frame *)skb->data;
u8 dlc = cf->can_dlc;
canid_t id = cf->can_id;
u8 *data = cf->data;
u16 val;
int i;
if (can_dropped_invalid_skb(dev, skb))
return NETDEV_TX_OK;
netif_stop_queue(dev);
/* fill id */
if (id & CAN_EFF_FLAG) {
bfin_write(®->chl[TRANSMIT_CHL].id0, id);
val = ((id & 0x1FFF0000) >> 16) | IDE;
} else
val = (id << 2);
if (id & CAN_RTR_FLAG)
val |= RTR;
bfin_write(®->chl[TRANSMIT_CHL].id1, val | AME);
/* fill payload */
for (i = 0; i < 8; i += 2) {
val = ((7 - i) < dlc ? (data[7 - i]) : 0) +
((6 - i) < dlc ? (data[6 - i] << 8) : 0);
bfin_write(®->chl[TRANSMIT_CHL].data[i], val);
}
/* fill data length code */
bfin_write(®->chl[TRANSMIT_CHL].dlc, dlc);
can_put_echo_skb(skb, dev, 0);
/* set transmit request */
bfin_write(®->trs2, BIT(TRANSMIT_CHL - 16));
return 0;
}
static void bfin_can_rx(struct net_device *dev, u16 isrc)
{
struct bfin_can_priv *priv = netdev_priv(dev);
struct net_device_stats *stats = &dev->stats;
struct bfin_can_regs __iomem *reg = priv->membase;
struct can_frame *cf;
struct sk_buff *skb;
int obj;
int i;
u16 val;
skb = alloc_can_skb(dev, &cf);
if (skb == NULL)
return;
/* get id */
if (isrc & BIT(RECEIVE_EXT_CHL)) {
/* extended frame format (EFF) */
cf->can_id = ((bfin_read(®->chl[RECEIVE_EXT_CHL].id1)
& 0x1FFF) << 16)
+ bfin_read(®->chl[RECEIVE_EXT_CHL].id0);
cf->can_id |= CAN_EFF_FLAG;
obj = RECEIVE_EXT_CHL;
} else {
/* standard frame format (SFF) */
cf->can_id = (bfin_read(®->chl[RECEIVE_STD_CHL].id1)
& 0x1ffc) >> 2;
obj = RECEIVE_STD_CHL;
}
if (bfin_read(®->chl[obj].id1) & RTR)
cf->can_id |= CAN_RTR_FLAG;
/* get data length code */
cf->can_dlc = get_can_dlc(bfin_read(®->chl[obj].dlc) & 0xF);
/* get payload */
for (i = 0; i < 8; i += 2) {
val = bfin_read(®->chl[obj].data[i]);
cf->data[7 - i] = (7 - i) < cf->can_dlc ? val : 0;
cf->data[6 - i] = (6 - i) < cf->can_dlc ? (val >> 8) : 0;
}
netif_rx(skb);
stats->rx_packets++;
stats->rx_bytes += cf->can_dlc;
}
static int bfin_can_err(struct net_device *dev, u16 isrc, u16 status)
{
struct bfin_can_priv *priv = netdev_priv(dev);
struct bfin_can_regs __iomem *reg = priv->membase;
struct net_device_stats *stats = &dev->stats;
struct can_frame *cf;
struct sk_buff *skb;
enum can_state state = priv->can.state;
skb = alloc_can_err_skb(dev, &cf);
if (skb == NULL)
return -ENOMEM;
if (isrc & RMLIS) {
/* data overrun interrupt */
netdev_dbg(dev, "data overrun interrupt\n");
cf->can_id |= CAN_ERR_CRTL;
cf->data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
stats->rx_over_errors++;
stats->rx_errors++;
}
if (isrc & BOIS) {
netdev_dbg(dev, "bus-off mode interrupt\n");
state = CAN_STATE_BUS_OFF;
cf->can_id |= CAN_ERR_BUSOFF;
priv->can.can_stats.bus_off++;
can_bus_off(dev);
}
if (isrc & EPIS) {
/* error passive interrupt */
netdev_dbg(dev, "error passive interrupt\n");
state = CAN_STATE_ERROR_PASSIVE;
}
if ((isrc & EWTIS) || (isrc & EWRIS)) {
netdev_dbg(dev, "Error Warning Transmit/Receive Interrupt\n");
state = CAN_STATE_ERROR_WARNING;
}
if (state != priv->can.state && (state == CAN_STATE_ERROR_WARNING ||
state == CAN_STATE_ERROR_PASSIVE)) {
u16 cec = bfin_read(®->cec);
u8 rxerr = cec;
u8 txerr = cec >> 8;
cf->can_id |= CAN_ERR_CRTL;
if (state == CAN_STATE_ERROR_WARNING) {
priv->can.can_stats.error_warning++;
cf->data[1] = (txerr > rxerr) ?
CAN_ERR_CRTL_TX_WARNING :
CAN_ERR_CRTL_RX_WARNING;
} else {
priv->can.can_stats.error_passive++;
cf->data[1] = (txerr > rxerr) ?
CAN_ERR_CRTL_TX_PASSIVE :
CAN_ERR_CRTL_RX_PASSIVE;
}
}
if (status) {
priv->can.can_stats.bus_error++;
cf->can_id |= CAN_ERR_PROT | CAN_ERR_BUSERROR;
if (status & BEF)
cf->data[2] |= CAN_ERR_PROT_BIT;
else if (status & FER)
cf->data[2] |= CAN_ERR_PROT_FORM;
else if (status & SER)
cf->data[2] |= CAN_ERR_PROT_STUFF;
else
cf->data[2] |= CAN_ERR_PROT_UNSPEC;
}
priv->can.state = state;
netif_rx(skb);
stats->rx_packets++;
stats->rx_bytes += cf->can_dlc;
return 0;
}
static irqreturn_t bfin_can_interrupt(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
struct bfin_can_priv *priv = netdev_priv(dev);
struct bfin_can_regs __iomem *reg = priv->membase;
struct net_device_stats *stats = &dev->stats;
u16 status, isrc;
if ((irq == priv->tx_irq) && bfin_read(®->mbtif2)) {
/* transmission complete interrupt */
bfin_write(®->mbtif2, 0xFFFF);
stats->tx_packets++;
stats->tx_bytes += bfin_read(®->chl[TRANSMIT_CHL].dlc);
can_get_echo_skb(dev, 0);
netif_wake_queue(dev);
} else if ((irq == priv->rx_irq) && bfin_read(®->mbrif1)) {
/* receive interrupt */
isrc = bfin_read(®->mbrif1);
bfin_write(®->mbrif1, 0xFFFF);
bfin_can_rx(dev, isrc);
} else if ((irq == priv->err_irq) && bfin_read(®->gis)) {
/* error interrupt */
isrc = bfin_read(®->gis);
status = bfin_read(®->esr);
bfin_write(®->gis, 0x7FF);
bfin_can_err(dev, isrc, status);
} else {
return IRQ_NONE;
}
return IRQ_HANDLED;
}
static int bfin_can_open(struct net_device *dev)
{
struct bfin_can_priv *priv = netdev_priv(dev);
int err;
/* set chip into reset mode */
bfin_can_set_reset_mode(dev);
/* common open */
err = open_candev(dev);
if (err)
goto exit_open;
/* register interrupt handler */
err = request_irq(priv->rx_irq, &bfin_can_interrupt, 0,
"bfin-can-rx", dev);
if (err)
goto exit_rx_irq;
err = request_irq(priv->tx_irq, &bfin_can_interrupt, 0,
"bfin-can-tx", dev);
if (err)
goto exit_tx_irq;
err = request_irq(priv->err_irq, &bfin_can_interrupt, 0,
"bfin-can-err", dev);
if (err)
goto exit_err_irq;
bfin_can_start(dev);
netif_start_queue(dev);
return 0;
exit_err_irq:
free_irq(priv->tx_irq, dev);
exit_tx_irq:
free_irq(priv->rx_irq, dev);
exit_rx_irq:
close_candev(dev);
exit_open:
return err;
}
static int bfin_can_close(struct net_device *dev)
{
struct bfin_can_priv *priv = netdev_priv(dev);
netif_stop_queue(dev);
bfin_can_set_reset_mode(dev);
close_candev(dev);
free_irq(priv->rx_irq, dev);
free_irq(priv->tx_irq, dev);
free_irq(priv->err_irq, dev);
return 0;
}
static struct net_device *alloc_bfin_candev(void)
{
struct net_device *dev;
struct bfin_can_priv *priv;
dev = alloc_candev(sizeof(*priv), TX_ECHO_SKB_MAX);
if (!dev)
return NULL;
priv = netdev_priv(dev);
priv->dev = dev;
priv->can.bittiming_const = &bfin_can_bittiming_const;
priv->can.do_set_bittiming = bfin_can_set_bittiming;
priv->can.do_set_mode = bfin_can_set_mode;
priv->can.do_get_berr_counter = bfin_can_get_berr_counter;
priv->can.ctrlmode_supported = CAN_CTRLMODE_3_SAMPLES;
return dev;
}
static const struct net_device_ops bfin_can_netdev_ops = {
.ndo_open = bfin_can_open,
.ndo_stop = bfin_can_close,
.ndo_start_xmit = bfin_can_start_xmit,
.ndo_change_mtu = can_change_mtu,
};
static int bfin_can_probe(struct platform_device *pdev)
{
int err;
struct net_device *dev;
struct bfin_can_priv *priv;
struct resource *res_mem, *rx_irq, *tx_irq, *err_irq;
unsigned short *pdata;
pdata = dev_get_platdata(&pdev->dev);
if (!pdata) {
dev_err(&pdev->dev, "No platform data provided!\n");
err = -EINVAL;
goto exit;
}
res_mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
rx_irq = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
tx_irq = platform_get_resource(pdev, IORESOURCE_IRQ, 1);
err_irq = platform_get_resource(pdev, IORESOURCE_IRQ, 2);
if (!res_mem || !rx_irq || !tx_irq || !err_irq) {
err = -EINVAL;
goto exit;
}
if (!request_mem_region(res_mem->start, resource_size(res_mem),
dev_name(&pdev->dev))) {
err = -EBUSY;
goto exit;
}
/* request peripheral pins */
err = peripheral_request_list(pdata, dev_name(&pdev->dev));
if (err)
goto exit_mem_release;
dev = alloc_bfin_candev();
if (!dev) {
err = -ENOMEM;
goto exit_peri_pin_free;
}
priv = netdev_priv(dev);
priv->membase = (void __iomem *)res_mem->start;
priv->rx_irq = rx_irq->start;
priv->tx_irq = tx_irq->start;
priv->err_irq = err_irq->start;
priv->pin_list = pdata;
priv->can.clock.freq = get_sclk();
platform_set_drvdata(pdev, dev);
SET_NETDEV_DEV(dev, &pdev->dev);
dev->flags |= IFF_ECHO; /* we support local echo */
dev->netdev_ops = &bfin_can_netdev_ops;
bfin_can_set_reset_mode(dev);
err = register_candev(dev);
if (err) {
dev_err(&pdev->dev, "registering failed (err=%d)\n", err);
goto exit_candev_free;
}
dev_info(&pdev->dev,
"%s device registered"
"(®_base=%p, rx_irq=%d, tx_irq=%d, err_irq=%d, sclk=%d)\n",
DRV_NAME, priv->membase, priv->rx_irq,
priv->tx_irq, priv->err_irq, priv->can.clock.freq);
return 0;
exit_candev_free:
free_candev(dev);
exit_peri_pin_free:
peripheral_free_list(pdata);
exit_mem_release:
release_mem_region(res_mem->start, resource_size(res_mem));
exit:
return err;
}
static int bfin_can_remove(struct platform_device *pdev)
{
struct net_device *dev = platform_get_drvdata(pdev);
struct bfin_can_priv *priv = netdev_priv(dev);
struct resource *res;
bfin_can_set_reset_mode(dev);
unregister_candev(dev);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(res->start, resource_size(res));
peripheral_free_list(priv->pin_list);
free_candev(dev);
return 0;
}
#ifdef CONFIG_PM
static int bfin_can_suspend(struct platform_device *pdev, pm_message_t mesg)
{
struct net_device *dev = platform_get_drvdata(pdev);
struct bfin_can_priv *priv = netdev_priv(dev);
struct bfin_can_regs __iomem *reg = priv->membase;
int timeout = BFIN_CAN_TIMEOUT;
if (netif_running(dev)) {
/* enter sleep mode */
bfin_write(®->control, bfin_read(®->control) | SMR);
SSYNC();
while (!(bfin_read(®->intr) & SMACK)) {
udelay(10);
if (--timeout == 0) {
netdev_err(dev, "fail to enter sleep mode\n");
BUG();
}
}
}
return 0;
}
static int bfin_can_resume(struct platform_device *pdev)
{
struct net_device *dev = platform_get_drvdata(pdev);
struct bfin_can_priv *priv = netdev_priv(dev);
struct bfin_can_regs __iomem *reg = priv->membase;
if (netif_running(dev)) {
/* leave sleep mode */
bfin_write(®->intr, 0);
SSYNC();
}
return 0;
}
#else
#define bfin_can_suspend NULL
#define bfin_can_resume NULL
#endif /* CONFIG_PM */
static struct platform_driver bfin_can_driver = {
.probe = bfin_can_probe,
.remove = bfin_can_remove,
.suspend = bfin_can_suspend,
.resume = bfin_can_resume,
.driver = {
.name = DRV_NAME,
},
};
module_platform_driver(bfin_can_driver);
MODULE_AUTHOR("Barry Song <21cnbao@gmail.com>");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Blackfin on-chip CAN netdevice driver");
MODULE_ALIAS("platform:" DRV_NAME);
| gpl-2.0 |
AshleyLai/vtpm | sound/soc/codecs/wm8940.c | 133 | 22504 | /*
* wm8940.c -- WM8940 ALSA Soc Audio driver
*
* Author: Jonathan Cameron <jic23@cam.ac.uk>
*
* Based on wm8510.c
* Copyright 2006 Wolfson Microelectronics PLC.
* Author: Liam Girdwood <lrg@slimlogic.co.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Not currently handled:
* Notch filter control
* AUXMode (inverting vs mixer)
* No means to obtain current gain if alc enabled.
* No use made of gpio
* Fast VMID discharge for power down
* Soft Start
* DLR and ALR Swaps not enabled
* Digital Sidetone not supported
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/pm.h>
#include <linux/i2c.h>
#include <linux/spi/spi.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/initval.h>
#include <sound/tlv.h>
#include "wm8940.h"
struct wm8940_priv {
unsigned int sysclk;
enum snd_soc_control_type control_type;
};
static int wm8940_volatile_register(struct snd_soc_codec *codec,
unsigned int reg)
{
switch (reg) {
case WM8940_SOFTRESET:
return 1;
default:
return 0;
}
}
static u16 wm8940_reg_defaults[] = {
0x8940, /* Soft Reset */
0x0000, /* Power 1 */
0x0000, /* Power 2 */
0x0000, /* Power 3 */
0x0010, /* Interface Control */
0x0000, /* Companding Control */
0x0140, /* Clock Control */
0x0000, /* Additional Controls */
0x0000, /* GPIO Control */
0x0002, /* Auto Increment Control */
0x0000, /* DAC Control */
0x00FF, /* DAC Volume */
0,
0,
0x0100, /* ADC Control */
0x00FF, /* ADC Volume */
0x0000, /* Notch Filter 1 Control 1 */
0x0000, /* Notch Filter 1 Control 2 */
0x0000, /* Notch Filter 2 Control 1 */
0x0000, /* Notch Filter 2 Control 2 */
0x0000, /* Notch Filter 3 Control 1 */
0x0000, /* Notch Filter 3 Control 2 */
0x0000, /* Notch Filter 4 Control 1 */
0x0000, /* Notch Filter 4 Control 2 */
0x0032, /* DAC Limit Control 1 */
0x0000, /* DAC Limit Control 2 */
0,
0,
0,
0,
0,
0,
0x0038, /* ALC Control 1 */
0x000B, /* ALC Control 2 */
0x0032, /* ALC Control 3 */
0x0000, /* Noise Gate */
0x0041, /* PLLN */
0x000C, /* PLLK1 */
0x0093, /* PLLK2 */
0x00E9, /* PLLK3 */
0,
0,
0x0030, /* ALC Control 4 */
0,
0x0002, /* Input Control */
0x0050, /* PGA Gain */
0,
0x0002, /* ADC Boost Control */
0,
0x0002, /* Output Control */
0x0000, /* Speaker Mixer Control */
0,
0,
0,
0x0079, /* Speaker Volume */
0,
0x0000, /* Mono Mixer Control */
};
static const char *wm8940_companding[] = { "Off", "NC", "u-law", "A-law" };
static const struct soc_enum wm8940_adc_companding_enum
= SOC_ENUM_SINGLE(WM8940_COMPANDINGCTL, 1, 4, wm8940_companding);
static const struct soc_enum wm8940_dac_companding_enum
= SOC_ENUM_SINGLE(WM8940_COMPANDINGCTL, 3, 4, wm8940_companding);
static const char *wm8940_alc_mode_text[] = {"ALC", "Limiter"};
static const struct soc_enum wm8940_alc_mode_enum
= SOC_ENUM_SINGLE(WM8940_ALC3, 8, 2, wm8940_alc_mode_text);
static const char *wm8940_mic_bias_level_text[] = {"0.9", "0.65"};
static const struct soc_enum wm8940_mic_bias_level_enum
= SOC_ENUM_SINGLE(WM8940_INPUTCTL, 8, 2, wm8940_mic_bias_level_text);
static const char *wm8940_filter_mode_text[] = {"Audio", "Application"};
static const struct soc_enum wm8940_filter_mode_enum
= SOC_ENUM_SINGLE(WM8940_ADC, 7, 2, wm8940_filter_mode_text);
static DECLARE_TLV_DB_SCALE(wm8940_spk_vol_tlv, -5700, 100, 1);
static DECLARE_TLV_DB_SCALE(wm8940_att_tlv, -1000, 1000, 0);
static DECLARE_TLV_DB_SCALE(wm8940_pga_vol_tlv, -1200, 75, 0);
static DECLARE_TLV_DB_SCALE(wm8940_alc_min_tlv, -1200, 600, 0);
static DECLARE_TLV_DB_SCALE(wm8940_alc_max_tlv, 675, 600, 0);
static DECLARE_TLV_DB_SCALE(wm8940_alc_tar_tlv, -2250, 50, 0);
static DECLARE_TLV_DB_SCALE(wm8940_lim_boost_tlv, 0, 100, 0);
static DECLARE_TLV_DB_SCALE(wm8940_lim_thresh_tlv, -600, 100, 0);
static DECLARE_TLV_DB_SCALE(wm8940_adc_tlv, -12750, 50, 1);
static DECLARE_TLV_DB_SCALE(wm8940_capture_boost_vol_tlv, 0, 2000, 0);
static const struct snd_kcontrol_new wm8940_snd_controls[] = {
SOC_SINGLE("Digital Loopback Switch", WM8940_COMPANDINGCTL,
6, 1, 0),
SOC_ENUM("DAC Companding", wm8940_dac_companding_enum),
SOC_ENUM("ADC Companding", wm8940_adc_companding_enum),
SOC_ENUM("ALC Mode", wm8940_alc_mode_enum),
SOC_SINGLE("ALC Switch", WM8940_ALC1, 8, 1, 0),
SOC_SINGLE_TLV("ALC Capture Max Gain", WM8940_ALC1,
3, 7, 1, wm8940_alc_max_tlv),
SOC_SINGLE_TLV("ALC Capture Min Gain", WM8940_ALC1,
0, 7, 0, wm8940_alc_min_tlv),
SOC_SINGLE_TLV("ALC Capture Target", WM8940_ALC2,
0, 14, 0, wm8940_alc_tar_tlv),
SOC_SINGLE("ALC Capture Hold", WM8940_ALC2, 4, 10, 0),
SOC_SINGLE("ALC Capture Decay", WM8940_ALC3, 4, 10, 0),
SOC_SINGLE("ALC Capture Attach", WM8940_ALC3, 0, 10, 0),
SOC_SINGLE("ALC ZC Switch", WM8940_ALC4, 1, 1, 0),
SOC_SINGLE("ALC Capture Noise Gate Switch", WM8940_NOISEGATE,
3, 1, 0),
SOC_SINGLE("ALC Capture Noise Gate Threshold", WM8940_NOISEGATE,
0, 7, 0),
SOC_SINGLE("DAC Playback Limiter Switch", WM8940_DACLIM1, 8, 1, 0),
SOC_SINGLE("DAC Playback Limiter Attack", WM8940_DACLIM1, 0, 9, 0),
SOC_SINGLE("DAC Playback Limiter Decay", WM8940_DACLIM1, 4, 11, 0),
SOC_SINGLE_TLV("DAC Playback Limiter Threshold", WM8940_DACLIM2,
4, 9, 1, wm8940_lim_thresh_tlv),
SOC_SINGLE_TLV("DAC Playback Limiter Boost", WM8940_DACLIM2,
0, 12, 0, wm8940_lim_boost_tlv),
SOC_SINGLE("Capture PGA ZC Switch", WM8940_PGAGAIN, 7, 1, 0),
SOC_SINGLE_TLV("Capture PGA Volume", WM8940_PGAGAIN,
0, 63, 0, wm8940_pga_vol_tlv),
SOC_SINGLE_TLV("Digital Playback Volume", WM8940_DACVOL,
0, 255, 0, wm8940_adc_tlv),
SOC_SINGLE_TLV("Digital Capture Volume", WM8940_ADCVOL,
0, 255, 0, wm8940_adc_tlv),
SOC_ENUM("Mic Bias Level", wm8940_mic_bias_level_enum),
SOC_SINGLE_TLV("Capture Boost Volue", WM8940_ADCBOOST,
8, 1, 0, wm8940_capture_boost_vol_tlv),
SOC_SINGLE_TLV("Speaker Playback Volume", WM8940_SPKVOL,
0, 63, 0, wm8940_spk_vol_tlv),
SOC_SINGLE("Speaker Playback Switch", WM8940_SPKVOL, 6, 1, 1),
SOC_SINGLE_TLV("Speaker Mixer Line Bypass Volume", WM8940_SPKVOL,
8, 1, 1, wm8940_att_tlv),
SOC_SINGLE("Speaker Playback ZC Switch", WM8940_SPKVOL, 7, 1, 0),
SOC_SINGLE("Mono Out Switch", WM8940_MONOMIX, 6, 1, 1),
SOC_SINGLE_TLV("Mono Mixer Line Bypass Volume", WM8940_MONOMIX,
7, 1, 1, wm8940_att_tlv),
SOC_SINGLE("High Pass Filter Switch", WM8940_ADC, 8, 1, 0),
SOC_ENUM("High Pass Filter Mode", wm8940_filter_mode_enum),
SOC_SINGLE("High Pass Filter Cut Off", WM8940_ADC, 4, 7, 0),
SOC_SINGLE("ADC Inversion Switch", WM8940_ADC, 0, 1, 0),
SOC_SINGLE("DAC Inversion Switch", WM8940_DAC, 0, 1, 0),
SOC_SINGLE("DAC Auto Mute Switch", WM8940_DAC, 2, 1, 0),
SOC_SINGLE("ZC Timeout Clock Switch", WM8940_ADDCNTRL, 0, 1, 0),
};
static const struct snd_kcontrol_new wm8940_speaker_mixer_controls[] = {
SOC_DAPM_SINGLE("Line Bypass Switch", WM8940_SPKMIX, 1, 1, 0),
SOC_DAPM_SINGLE("Aux Playback Switch", WM8940_SPKMIX, 5, 1, 0),
SOC_DAPM_SINGLE("PCM Playback Switch", WM8940_SPKMIX, 0, 1, 0),
};
static const struct snd_kcontrol_new wm8940_mono_mixer_controls[] = {
SOC_DAPM_SINGLE("Line Bypass Switch", WM8940_MONOMIX, 1, 1, 0),
SOC_DAPM_SINGLE("Aux Playback Switch", WM8940_MONOMIX, 2, 1, 0),
SOC_DAPM_SINGLE("PCM Playback Switch", WM8940_MONOMIX, 0, 1, 0),
};
static DECLARE_TLV_DB_SCALE(wm8940_boost_vol_tlv, -1500, 300, 1);
static const struct snd_kcontrol_new wm8940_input_boost_controls[] = {
SOC_DAPM_SINGLE("Mic PGA Switch", WM8940_PGAGAIN, 6, 1, 1),
SOC_DAPM_SINGLE_TLV("Aux Volume", WM8940_ADCBOOST,
0, 7, 0, wm8940_boost_vol_tlv),
SOC_DAPM_SINGLE_TLV("Mic Volume", WM8940_ADCBOOST,
4, 7, 0, wm8940_boost_vol_tlv),
};
static const struct snd_kcontrol_new wm8940_micpga_controls[] = {
SOC_DAPM_SINGLE("AUX Switch", WM8940_INPUTCTL, 2, 1, 0),
SOC_DAPM_SINGLE("MICP Switch", WM8940_INPUTCTL, 0, 1, 0),
SOC_DAPM_SINGLE("MICN Switch", WM8940_INPUTCTL, 1, 1, 0),
};
static const struct snd_soc_dapm_widget wm8940_dapm_widgets[] = {
SND_SOC_DAPM_MIXER("Speaker Mixer", WM8940_POWER3, 2, 0,
&wm8940_speaker_mixer_controls[0],
ARRAY_SIZE(wm8940_speaker_mixer_controls)),
SND_SOC_DAPM_MIXER("Mono Mixer", WM8940_POWER3, 3, 0,
&wm8940_mono_mixer_controls[0],
ARRAY_SIZE(wm8940_mono_mixer_controls)),
SND_SOC_DAPM_DAC("DAC", "HiFi Playback", WM8940_POWER3, 0, 0),
SND_SOC_DAPM_PGA("SpkN Out", WM8940_POWER3, 5, 0, NULL, 0),
SND_SOC_DAPM_PGA("SpkP Out", WM8940_POWER3, 6, 0, NULL, 0),
SND_SOC_DAPM_PGA("Mono Out", WM8940_POWER3, 7, 0, NULL, 0),
SND_SOC_DAPM_OUTPUT("MONOOUT"),
SND_SOC_DAPM_OUTPUT("SPKOUTP"),
SND_SOC_DAPM_OUTPUT("SPKOUTN"),
SND_SOC_DAPM_PGA("Aux Input", WM8940_POWER1, 6, 0, NULL, 0),
SND_SOC_DAPM_ADC("ADC", "HiFi Capture", WM8940_POWER2, 0, 0),
SND_SOC_DAPM_MIXER("Mic PGA", WM8940_POWER2, 2, 0,
&wm8940_micpga_controls[0],
ARRAY_SIZE(wm8940_micpga_controls)),
SND_SOC_DAPM_MIXER("Boost Mixer", WM8940_POWER2, 4, 0,
&wm8940_input_boost_controls[0],
ARRAY_SIZE(wm8940_input_boost_controls)),
SND_SOC_DAPM_MICBIAS("Mic Bias", WM8940_POWER1, 4, 0),
SND_SOC_DAPM_INPUT("MICN"),
SND_SOC_DAPM_INPUT("MICP"),
SND_SOC_DAPM_INPUT("AUX"),
};
static const struct snd_soc_dapm_route audio_map[] = {
/* Mono output mixer */
{"Mono Mixer", "PCM Playback Switch", "DAC"},
{"Mono Mixer", "Aux Playback Switch", "Aux Input"},
{"Mono Mixer", "Line Bypass Switch", "Boost Mixer"},
/* Speaker output mixer */
{"Speaker Mixer", "PCM Playback Switch", "DAC"},
{"Speaker Mixer", "Aux Playback Switch", "Aux Input"},
{"Speaker Mixer", "Line Bypass Switch", "Boost Mixer"},
/* Outputs */
{"Mono Out", NULL, "Mono Mixer"},
{"MONOOUT", NULL, "Mono Out"},
{"SpkN Out", NULL, "Speaker Mixer"},
{"SpkP Out", NULL, "Speaker Mixer"},
{"SPKOUTN", NULL, "SpkN Out"},
{"SPKOUTP", NULL, "SpkP Out"},
/* Microphone PGA */
{"Mic PGA", "MICN Switch", "MICN"},
{"Mic PGA", "MICP Switch", "MICP"},
{"Mic PGA", "AUX Switch", "AUX"},
/* Boost Mixer */
{"Boost Mixer", "Mic PGA Switch", "Mic PGA"},
{"Boost Mixer", "Mic Volume", "MICP"},
{"Boost Mixer", "Aux Volume", "Aux Input"},
{"ADC", NULL, "Boost Mixer"},
};
static int wm8940_add_widgets(struct snd_soc_codec *codec)
{
struct snd_soc_dapm_context *dapm = &codec->dapm;
int ret;
ret = snd_soc_dapm_new_controls(dapm, wm8940_dapm_widgets,
ARRAY_SIZE(wm8940_dapm_widgets));
if (ret)
goto error_ret;
ret = snd_soc_dapm_add_routes(dapm, audio_map, ARRAY_SIZE(audio_map));
error_ret:
return ret;
}
#define wm8940_reset(c) snd_soc_write(c, WM8940_SOFTRESET, 0);
static int wm8940_set_dai_fmt(struct snd_soc_dai *codec_dai,
unsigned int fmt)
{
struct snd_soc_codec *codec = codec_dai->codec;
u16 iface = snd_soc_read(codec, WM8940_IFACE) & 0xFE67;
u16 clk = snd_soc_read(codec, WM8940_CLOCK) & 0x1fe;
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM:
clk |= 1;
break;
case SND_SOC_DAIFMT_CBS_CFS:
break;
default:
return -EINVAL;
}
snd_soc_write(codec, WM8940_CLOCK, clk);
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
iface |= (2 << 3);
break;
case SND_SOC_DAIFMT_LEFT_J:
iface |= (1 << 3);
break;
case SND_SOC_DAIFMT_RIGHT_J:
break;
case SND_SOC_DAIFMT_DSP_A:
iface |= (3 << 3);
break;
case SND_SOC_DAIFMT_DSP_B:
iface |= (3 << 3) | (1 << 7);
break;
}
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
break;
case SND_SOC_DAIFMT_NB_IF:
iface |= (1 << 7);
break;
case SND_SOC_DAIFMT_IB_NF:
iface |= (1 << 8);
break;
case SND_SOC_DAIFMT_IB_IF:
iface |= (1 << 8) | (1 << 7);
break;
}
snd_soc_write(codec, WM8940_IFACE, iface);
return 0;
}
static int wm8940_i2s_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
u16 iface = snd_soc_read(codec, WM8940_IFACE) & 0xFD9F;
u16 addcntrl = snd_soc_read(codec, WM8940_ADDCNTRL) & 0xFFF1;
u16 companding = snd_soc_read(codec,
WM8940_COMPANDINGCTL) & 0xFFDF;
int ret;
/* LoutR control */
if (substream->stream == SNDRV_PCM_STREAM_CAPTURE
&& params_channels(params) == 2)
iface |= (1 << 9);
switch (params_rate(params)) {
case 8000:
addcntrl |= (0x5 << 1);
break;
case 11025:
addcntrl |= (0x4 << 1);
break;
case 16000:
addcntrl |= (0x3 << 1);
break;
case 22050:
addcntrl |= (0x2 << 1);
break;
case 32000:
addcntrl |= (0x1 << 1);
break;
case 44100:
case 48000:
break;
}
ret = snd_soc_write(codec, WM8940_ADDCNTRL, addcntrl);
if (ret)
goto error_ret;
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S8:
companding = companding | (1 << 5);
break;
case SNDRV_PCM_FORMAT_S16_LE:
break;
case SNDRV_PCM_FORMAT_S20_3LE:
iface |= (1 << 5);
break;
case SNDRV_PCM_FORMAT_S24_LE:
iface |= (2 << 5);
break;
case SNDRV_PCM_FORMAT_S32_LE:
iface |= (3 << 5);
break;
}
ret = snd_soc_write(codec, WM8940_COMPANDINGCTL, companding);
if (ret)
goto error_ret;
ret = snd_soc_write(codec, WM8940_IFACE, iface);
error_ret:
return ret;
}
static int wm8940_mute(struct snd_soc_dai *dai, int mute)
{
struct snd_soc_codec *codec = dai->codec;
u16 mute_reg = snd_soc_read(codec, WM8940_DAC) & 0xffbf;
if (mute)
mute_reg |= 0x40;
return snd_soc_write(codec, WM8940_DAC, mute_reg);
}
static int wm8940_set_bias_level(struct snd_soc_codec *codec,
enum snd_soc_bias_level level)
{
u16 val;
u16 pwr_reg = snd_soc_read(codec, WM8940_POWER1) & 0x1F0;
int ret = 0;
switch (level) {
case SND_SOC_BIAS_ON:
/* ensure bufioen and biasen */
pwr_reg |= (1 << 2) | (1 << 3);
/* Enable thermal shutdown */
val = snd_soc_read(codec, WM8940_OUTPUTCTL);
ret = snd_soc_write(codec, WM8940_OUTPUTCTL, val | 0x2);
if (ret)
break;
/* set vmid to 75k */
ret = snd_soc_write(codec, WM8940_POWER1, pwr_reg | 0x1);
break;
case SND_SOC_BIAS_PREPARE:
/* ensure bufioen and biasen */
pwr_reg |= (1 << 2) | (1 << 3);
ret = snd_soc_write(codec, WM8940_POWER1, pwr_reg | 0x1);
break;
case SND_SOC_BIAS_STANDBY:
if (codec->dapm.bias_level == SND_SOC_BIAS_OFF) {
ret = snd_soc_cache_sync(codec);
if (ret < 0) {
dev_err(codec->dev, "Failed to sync cache: %d\n", ret);
return ret;
}
}
/* ensure bufioen and biasen */
pwr_reg |= (1 << 2) | (1 << 3);
/* set vmid to 300k for standby */
ret = snd_soc_write(codec, WM8940_POWER1, pwr_reg | 0x2);
break;
case SND_SOC_BIAS_OFF:
ret = snd_soc_write(codec, WM8940_POWER1, pwr_reg);
break;
}
codec->dapm.bias_level = level;
return ret;
}
struct pll_ {
unsigned int pre_scale:2;
unsigned int n:4;
unsigned int k;
};
static struct pll_ pll_div;
/* The size in bits of the pll divide multiplied by 10
* to allow rounding later */
#define FIXED_PLL_SIZE ((1 << 24) * 10)
static void pll_factors(unsigned int target, unsigned int source)
{
unsigned long long Kpart;
unsigned int K, Ndiv, Nmod;
/* The left shift ist to avoid accuracy loss when right shifting */
Ndiv = target / source;
if (Ndiv > 12) {
source <<= 1;
/* Multiply by 2 */
pll_div.pre_scale = 0;
Ndiv = target / source;
} else if (Ndiv < 3) {
source >>= 2;
/* Divide by 4 */
pll_div.pre_scale = 3;
Ndiv = target / source;
} else if (Ndiv < 6) {
source >>= 1;
/* divide by 2 */
pll_div.pre_scale = 2;
Ndiv = target / source;
} else
pll_div.pre_scale = 1;
if ((Ndiv < 6) || (Ndiv > 12))
printk(KERN_WARNING
"WM8940 N value %d outwith recommended range!d\n",
Ndiv);
pll_div.n = Ndiv;
Nmod = target % source;
Kpart = FIXED_PLL_SIZE * (long long)Nmod;
do_div(Kpart, source);
K = Kpart & 0xFFFFFFFF;
/* Check if we need to round */
if ((K % 10) >= 5)
K += 5;
/* Move down to proper range now rounding is done */
K /= 10;
pll_div.k = K;
}
/* Untested at the moment */
static int wm8940_set_dai_pll(struct snd_soc_dai *codec_dai, int pll_id,
int source, unsigned int freq_in, unsigned int freq_out)
{
struct snd_soc_codec *codec = codec_dai->codec;
u16 reg;
/* Turn off PLL */
reg = snd_soc_read(codec, WM8940_POWER1);
snd_soc_write(codec, WM8940_POWER1, reg & 0x1df);
if (freq_in == 0 || freq_out == 0) {
/* Clock CODEC directly from MCLK */
reg = snd_soc_read(codec, WM8940_CLOCK);
snd_soc_write(codec, WM8940_CLOCK, reg & 0x0ff);
/* Pll power down */
snd_soc_write(codec, WM8940_PLLN, (1 << 7));
return 0;
}
/* Pll is followed by a frequency divide by 4 */
pll_factors(freq_out*4, freq_in);
if (pll_div.k)
snd_soc_write(codec, WM8940_PLLN,
(pll_div.pre_scale << 4) | pll_div.n | (1 << 6));
else /* No factional component */
snd_soc_write(codec, WM8940_PLLN,
(pll_div.pre_scale << 4) | pll_div.n);
snd_soc_write(codec, WM8940_PLLK1, pll_div.k >> 18);
snd_soc_write(codec, WM8940_PLLK2, (pll_div.k >> 9) & 0x1ff);
snd_soc_write(codec, WM8940_PLLK3, pll_div.k & 0x1ff);
/* Enable the PLL */
reg = snd_soc_read(codec, WM8940_POWER1);
snd_soc_write(codec, WM8940_POWER1, reg | 0x020);
/* Run CODEC from PLL instead of MCLK */
reg = snd_soc_read(codec, WM8940_CLOCK);
snd_soc_write(codec, WM8940_CLOCK, reg | 0x100);
return 0;
}
static int wm8940_set_dai_sysclk(struct snd_soc_dai *codec_dai,
int clk_id, unsigned int freq, int dir)
{
struct snd_soc_codec *codec = codec_dai->codec;
struct wm8940_priv *wm8940 = snd_soc_codec_get_drvdata(codec);
switch (freq) {
case 11289600:
case 12000000:
case 12288000:
case 16934400:
case 18432000:
wm8940->sysclk = freq;
return 0;
}
return -EINVAL;
}
static int wm8940_set_dai_clkdiv(struct snd_soc_dai *codec_dai,
int div_id, int div)
{
struct snd_soc_codec *codec = codec_dai->codec;
u16 reg;
int ret = 0;
switch (div_id) {
case WM8940_BCLKDIV:
reg = snd_soc_read(codec, WM8940_CLOCK) & 0xFFE3;
ret = snd_soc_write(codec, WM8940_CLOCK, reg | (div << 2));
break;
case WM8940_MCLKDIV:
reg = snd_soc_read(codec, WM8940_CLOCK) & 0xFF1F;
ret = snd_soc_write(codec, WM8940_CLOCK, reg | (div << 5));
break;
case WM8940_OPCLKDIV:
reg = snd_soc_read(codec, WM8940_GPIO) & 0xFFCF;
ret = snd_soc_write(codec, WM8940_GPIO, reg | (div << 4));
break;
}
return ret;
}
#define WM8940_RATES SNDRV_PCM_RATE_8000_48000
#define WM8940_FORMATS (SNDRV_PCM_FMTBIT_S8 | \
SNDRV_PCM_FMTBIT_S16_LE | \
SNDRV_PCM_FMTBIT_S20_3LE | \
SNDRV_PCM_FMTBIT_S24_LE | \
SNDRV_PCM_FMTBIT_S32_LE)
static const struct snd_soc_dai_ops wm8940_dai_ops = {
.hw_params = wm8940_i2s_hw_params,
.set_sysclk = wm8940_set_dai_sysclk,
.digital_mute = wm8940_mute,
.set_fmt = wm8940_set_dai_fmt,
.set_clkdiv = wm8940_set_dai_clkdiv,
.set_pll = wm8940_set_dai_pll,
};
static struct snd_soc_dai_driver wm8940_dai = {
.name = "wm8940-hifi",
.playback = {
.stream_name = "Playback",
.channels_min = 1,
.channels_max = 2,
.rates = WM8940_RATES,
.formats = WM8940_FORMATS,
},
.capture = {
.stream_name = "Capture",
.channels_min = 1,
.channels_max = 2,
.rates = WM8940_RATES,
.formats = WM8940_FORMATS,
},
.ops = &wm8940_dai_ops,
.symmetric_rates = 1,
};
static int wm8940_suspend(struct snd_soc_codec *codec)
{
return wm8940_set_bias_level(codec, SND_SOC_BIAS_OFF);
}
static int wm8940_resume(struct snd_soc_codec *codec)
{
wm8940_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
return 0;
}
static int wm8940_probe(struct snd_soc_codec *codec)
{
struct wm8940_priv *wm8940 = snd_soc_codec_get_drvdata(codec);
struct wm8940_setup_data *pdata = codec->dev->platform_data;
int ret;
u16 reg;
ret = snd_soc_codec_set_cache_io(codec, 8, 16, wm8940->control_type);
if (ret < 0) {
dev_err(codec->dev, "Failed to set cache I/O: %d\n", ret);
return ret;
}
ret = wm8940_reset(codec);
if (ret < 0) {
dev_err(codec->dev, "Failed to issue reset\n");
return ret;
}
wm8940_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
ret = snd_soc_write(codec, WM8940_POWER1, 0x180);
if (ret < 0)
return ret;
if (!pdata)
dev_warn(codec->dev, "No platform data supplied\n");
else {
reg = snd_soc_read(codec, WM8940_OUTPUTCTL);
ret = snd_soc_write(codec, WM8940_OUTPUTCTL, reg | pdata->vroi);
if (ret < 0)
return ret;
}
ret = snd_soc_add_codec_controls(codec, wm8940_snd_controls,
ARRAY_SIZE(wm8940_snd_controls));
if (ret)
return ret;
ret = wm8940_add_widgets(codec);
return ret;
}
static int wm8940_remove(struct snd_soc_codec *codec)
{
wm8940_set_bias_level(codec, SND_SOC_BIAS_OFF);
return 0;
}
static struct snd_soc_codec_driver soc_codec_dev_wm8940 = {
.probe = wm8940_probe,
.remove = wm8940_remove,
.suspend = wm8940_suspend,
.resume = wm8940_resume,
.set_bias_level = wm8940_set_bias_level,
.reg_cache_size = ARRAY_SIZE(wm8940_reg_defaults),
.reg_word_size = sizeof(u16),
.reg_cache_default = wm8940_reg_defaults,
.volatile_register = wm8940_volatile_register,
};
static __devinit int wm8940_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct wm8940_priv *wm8940;
int ret;
wm8940 = devm_kzalloc(&i2c->dev, sizeof(struct wm8940_priv),
GFP_KERNEL);
if (wm8940 == NULL)
return -ENOMEM;
i2c_set_clientdata(i2c, wm8940);
wm8940->control_type = SND_SOC_I2C;
ret = snd_soc_register_codec(&i2c->dev,
&soc_codec_dev_wm8940, &wm8940_dai, 1);
return ret;
}
static __devexit int wm8940_i2c_remove(struct i2c_client *client)
{
snd_soc_unregister_codec(&client->dev);
return 0;
}
static const struct i2c_device_id wm8940_i2c_id[] = {
{ "wm8940", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, wm8940_i2c_id);
static struct i2c_driver wm8940_i2c_driver = {
.driver = {
.name = "wm8940",
.owner = THIS_MODULE,
},
.probe = wm8940_i2c_probe,
.remove = __devexit_p(wm8940_i2c_remove),
.id_table = wm8940_i2c_id,
};
static int __init wm8940_modinit(void)
{
int ret = 0;
ret = i2c_add_driver(&wm8940_i2c_driver);
if (ret != 0) {
printk(KERN_ERR "Failed to register wm8940 I2C driver: %d\n",
ret);
}
return ret;
}
module_init(wm8940_modinit);
static void __exit wm8940_exit(void)
{
i2c_del_driver(&wm8940_i2c_driver);
}
module_exit(wm8940_exit);
MODULE_DESCRIPTION("ASoC WM8940 driver");
MODULE_AUTHOR("Jonathan Cameron");
MODULE_LICENSE("GPL");
| gpl-2.0 |
stev47/linux | arch/arm/mach-shmobile/cpuidle.c | 133 | 1534 | /*
* CPUIdle support code for SH-Mobile ARM
*
* Copyright (C) 2011 Magnus Damm
*
* 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/pm.h>
#include <linux/cpuidle.h>
#include <linux/suspend.h>
#include <linux/module.h>
#include <linux/err.h>
#include <asm/cpuidle.h>
#include <asm/io.h>
static void shmobile_enter_wfi(void)
{
cpu_do_idle();
}
void (*shmobile_cpuidle_modes[CPUIDLE_STATE_MAX])(void) = {
shmobile_enter_wfi, /* regular sleep mode */
};
static int shmobile_cpuidle_enter(struct cpuidle_device *dev,
struct cpuidle_driver *drv,
int index)
{
shmobile_cpuidle_modes[index]();
return index;
}
static struct cpuidle_device shmobile_cpuidle_dev;
static struct cpuidle_driver shmobile_cpuidle_driver = {
.name = "shmobile_cpuidle",
.owner = THIS_MODULE,
.en_core_tk_irqen = 1,
.states[0] = ARM_CPUIDLE_WFI_STATE,
.safe_state_index = 0, /* C1 */
.state_count = 1,
};
void (*shmobile_cpuidle_setup)(struct cpuidle_driver *drv);
int shmobile_cpuidle_init(void)
{
struct cpuidle_device *dev = &shmobile_cpuidle_dev;
struct cpuidle_driver *drv = &shmobile_cpuidle_driver;
int i;
for (i = 0; i < CPUIDLE_STATE_MAX; i++)
drv->states[i].enter = shmobile_cpuidle_enter;
if (shmobile_cpuidle_setup)
shmobile_cpuidle_setup(drv);
cpuidle_register_driver(drv);
dev->state_count = drv->state_count;
cpuidle_register_device(dev);
return 0;
}
| gpl-2.0 |
WinKarbik/android_kernel_samsung_amazing | common/drivers/media/video/cx88/cx88-mpeg.c | 901 | 24373 | /*
*
* Support for the mpeg transport stream transfers
* PCI function #2 of the cx2388x.
*
* (c) 2004 Jelle Foks <jelle@foks.us>
* (c) 2004 Chris Pascoe <c.pascoe@itee.uq.edu.au>
* (c) 2004 Gerd Knorr <kraxel@bytesex.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 <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/interrupt.h>
#include <asm/delay.h>
#include "cx88.h"
/* ------------------------------------------------------------------ */
MODULE_DESCRIPTION("mpeg driver for cx2388x based TV cards");
MODULE_AUTHOR("Jelle Foks <jelle@foks.us>");
MODULE_AUTHOR("Chris Pascoe <c.pascoe@itee.uq.edu.au>");
MODULE_AUTHOR("Gerd Knorr <kraxel@bytesex.org> [SuSE Labs]");
MODULE_LICENSE("GPL");
static unsigned int debug;
module_param(debug,int,0644);
MODULE_PARM_DESC(debug,"enable debug messages [mpeg]");
#define dprintk(level,fmt, arg...) if (debug >= level) \
printk(KERN_DEBUG "%s/2-mpeg: " fmt, dev->core->name, ## arg)
#define mpeg_dbg(level,fmt, arg...) if (debug >= level) \
printk(KERN_DEBUG "%s/2-mpeg: " fmt, core->name, ## arg)
#if defined(CONFIG_MODULES) && defined(MODULE)
static void request_module_async(struct work_struct *work)
{
struct cx8802_dev *dev=container_of(work, struct cx8802_dev, request_module_wk);
if (dev->core->board.mpeg & CX88_MPEG_DVB)
request_module("cx88-dvb");
if (dev->core->board.mpeg & CX88_MPEG_BLACKBIRD)
request_module("cx88-blackbird");
}
static void request_modules(struct cx8802_dev *dev)
{
INIT_WORK(&dev->request_module_wk, request_module_async);
schedule_work(&dev->request_module_wk);
}
#else
#define request_modules(dev)
#endif /* CONFIG_MODULES */
static LIST_HEAD(cx8802_devlist);
/* ------------------------------------------------------------------ */
static int cx8802_start_dma(struct cx8802_dev *dev,
struct cx88_dmaqueue *q,
struct cx88_buffer *buf)
{
struct cx88_core *core = dev->core;
dprintk(1, "cx8802_start_dma w: %d, h: %d, f: %d\n",
buf->vb.width, buf->vb.height, buf->vb.field);
/* setup fifo + format */
cx88_sram_channel_setup(core, &cx88_sram_channels[SRAM_CH28],
dev->ts_packet_size, buf->risc.dma);
/* write TS length to chip */
cx_write(MO_TS_LNGTH, buf->vb.width);
/* FIXME: this needs a review.
* also: move to cx88-blackbird + cx88-dvb source files? */
dprintk( 1, "core->active_type_id = 0x%08x\n", core->active_type_id);
if ( (core->active_type_id == CX88_MPEG_DVB) &&
(core->board.mpeg & CX88_MPEG_DVB) ) {
dprintk( 1, "cx8802_start_dma doing .dvb\n");
/* negedge driven & software reset */
cx_write(TS_GEN_CNTRL, 0x0040 | dev->ts_gen_cntrl);
udelay(100);
cx_write(MO_PINMUX_IO, 0x00);
cx_write(TS_HW_SOP_CNTRL, 0x47<<16|188<<4|0x01);
switch (core->boardnr) {
case CX88_BOARD_DVICO_FUSIONHDTV_3_GOLD_Q:
case CX88_BOARD_DVICO_FUSIONHDTV_3_GOLD_T:
case CX88_BOARD_DVICO_FUSIONHDTV_5_GOLD:
case CX88_BOARD_PCHDTV_HD5500:
cx_write(TS_SOP_STAT, 1<<13);
break;
case CX88_BOARD_SAMSUNG_SMT_7020:
cx_write(TS_SOP_STAT, 0x00);
break;
case CX88_BOARD_HAUPPAUGE_NOVASPLUS_S1:
case CX88_BOARD_HAUPPAUGE_NOVASE2_S1:
cx_write(MO_PINMUX_IO, 0x88); /* Enable MPEG parallel IO and video signal pins */
udelay(100);
break;
case CX88_BOARD_HAUPPAUGE_HVR1300:
/* Enable MPEG parallel IO and video signal pins */
cx_write(MO_PINMUX_IO, 0x88);
cx_write(TS_SOP_STAT, 0);
cx_write(TS_VALERR_CNTRL, 0);
break;
case CX88_BOARD_PINNACLE_PCTV_HD_800i:
/* Enable MPEG parallel IO and video signal pins */
cx_write(MO_PINMUX_IO, 0x88);
cx_write(TS_HW_SOP_CNTRL, (0x47 << 16) | (188 << 4));
dev->ts_gen_cntrl = 5;
cx_write(TS_SOP_STAT, 0);
cx_write(TS_VALERR_CNTRL, 0);
udelay(100);
break;
default:
cx_write(TS_SOP_STAT, 0x00);
break;
}
cx_write(TS_GEN_CNTRL, dev->ts_gen_cntrl);
udelay(100);
} else if ( (core->active_type_id == CX88_MPEG_BLACKBIRD) &&
(core->board.mpeg & CX88_MPEG_BLACKBIRD) ) {
dprintk( 1, "cx8802_start_dma doing .blackbird\n");
cx_write(MO_PINMUX_IO, 0x88); /* enable MPEG parallel IO */
cx_write(TS_GEN_CNTRL, 0x46); /* punctured clock TS & posedge driven & software reset */
udelay(100);
cx_write(TS_HW_SOP_CNTRL, 0x408); /* mpeg start byte */
cx_write(TS_VALERR_CNTRL, 0x2000);
cx_write(TS_GEN_CNTRL, 0x06); /* punctured clock TS & posedge driven */
udelay(100);
} else {
printk( "%s() Failed. Unsupported value in .mpeg (0x%08x)\n", __func__,
core->board.mpeg );
return -EINVAL;
}
/* reset counter */
cx_write(MO_TS_GPCNTRL, GP_COUNT_CONTROL_RESET);
q->count = 1;
/* enable irqs */
dprintk( 1, "setting the interrupt mask\n" );
cx_set(MO_PCI_INTMSK, core->pci_irqmask | PCI_INT_TSINT);
cx_set(MO_TS_INTMSK, 0x1f0011);
/* start dma */
cx_set(MO_DEV_CNTRL2, (1<<5));
cx_set(MO_TS_DMACNTRL, 0x11);
return 0;
}
static int cx8802_stop_dma(struct cx8802_dev *dev)
{
struct cx88_core *core = dev->core;
dprintk( 1, "cx8802_stop_dma\n" );
/* stop dma */
cx_clear(MO_TS_DMACNTRL, 0x11);
/* disable irqs */
cx_clear(MO_PCI_INTMSK, PCI_INT_TSINT);
cx_clear(MO_TS_INTMSK, 0x1f0011);
/* Reset the controller */
cx_write(TS_GEN_CNTRL, 0xcd);
return 0;
}
static int cx8802_restart_queue(struct cx8802_dev *dev,
struct cx88_dmaqueue *q)
{
struct cx88_buffer *buf;
dprintk( 1, "cx8802_restart_queue\n" );
if (list_empty(&q->active))
{
struct cx88_buffer *prev;
prev = NULL;
dprintk(1, "cx8802_restart_queue: queue is empty\n" );
for (;;) {
if (list_empty(&q->queued))
return 0;
buf = list_entry(q->queued.next, struct cx88_buffer, vb.queue);
if (NULL == prev) {
list_del(&buf->vb.queue);
list_add_tail(&buf->vb.queue,&q->active);
cx8802_start_dma(dev, q, buf);
buf->vb.state = VIDEOBUF_ACTIVE;
buf->count = q->count++;
mod_timer(&q->timeout, jiffies+BUFFER_TIMEOUT);
dprintk(1,"[%p/%d] restart_queue - first active\n",
buf,buf->vb.i);
} else if (prev->vb.width == buf->vb.width &&
prev->vb.height == buf->vb.height &&
prev->fmt == buf->fmt) {
list_del(&buf->vb.queue);
list_add_tail(&buf->vb.queue,&q->active);
buf->vb.state = VIDEOBUF_ACTIVE;
buf->count = q->count++;
prev->risc.jmp[1] = cpu_to_le32(buf->risc.dma);
dprintk(1,"[%p/%d] restart_queue - move to active\n",
buf,buf->vb.i);
} else {
return 0;
}
prev = buf;
}
return 0;
}
buf = list_entry(q->active.next, struct cx88_buffer, vb.queue);
dprintk(2,"restart_queue [%p/%d]: restart dma\n",
buf, buf->vb.i);
cx8802_start_dma(dev, q, buf);
list_for_each_entry(buf, &q->active, vb.queue)
buf->count = q->count++;
mod_timer(&q->timeout, jiffies+BUFFER_TIMEOUT);
return 0;
}
/* ------------------------------------------------------------------ */
int cx8802_buf_prepare(struct videobuf_queue *q, struct cx8802_dev *dev,
struct cx88_buffer *buf, enum v4l2_field field)
{
int size = dev->ts_packet_size * dev->ts_packet_count;
struct videobuf_dmabuf *dma=videobuf_to_dma(&buf->vb);
int rc;
dprintk(1, "%s: %p\n", __func__, buf);
if (0 != buf->vb.baddr && buf->vb.bsize < size)
return -EINVAL;
if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
buf->vb.width = dev->ts_packet_size;
buf->vb.height = dev->ts_packet_count;
buf->vb.size = size;
buf->vb.field = field /*V4L2_FIELD_TOP*/;
if (0 != (rc = videobuf_iolock(q,&buf->vb,NULL)))
goto fail;
cx88_risc_databuffer(dev->pci, &buf->risc,
dma->sglist,
buf->vb.width, buf->vb.height, 0);
}
buf->vb.state = VIDEOBUF_PREPARED;
return 0;
fail:
cx88_free_buffer(q,buf);
return rc;
}
void cx8802_buf_queue(struct cx8802_dev *dev, struct cx88_buffer *buf)
{
struct cx88_buffer *prev;
struct cx88_dmaqueue *cx88q = &dev->mpegq;
dprintk( 1, "cx8802_buf_queue\n" );
/* add jump to stopper */
buf->risc.jmp[0] = cpu_to_le32(RISC_JUMP | RISC_IRQ1 | RISC_CNT_INC);
buf->risc.jmp[1] = cpu_to_le32(cx88q->stopper.dma);
if (list_empty(&cx88q->active)) {
dprintk( 1, "queue is empty - first active\n" );
list_add_tail(&buf->vb.queue,&cx88q->active);
cx8802_start_dma(dev, cx88q, buf);
buf->vb.state = VIDEOBUF_ACTIVE;
buf->count = cx88q->count++;
mod_timer(&cx88q->timeout, jiffies+BUFFER_TIMEOUT);
dprintk(1,"[%p/%d] %s - first active\n",
buf, buf->vb.i, __func__);
} else {
dprintk( 1, "queue is not empty - append to active\n" );
prev = list_entry(cx88q->active.prev, struct cx88_buffer, vb.queue);
list_add_tail(&buf->vb.queue,&cx88q->active);
buf->vb.state = VIDEOBUF_ACTIVE;
buf->count = cx88q->count++;
prev->risc.jmp[1] = cpu_to_le32(buf->risc.dma);
dprintk( 1, "[%p/%d] %s - append to active\n",
buf, buf->vb.i, __func__);
}
}
/* ----------------------------------------------------------- */
static void do_cancel_buffers(struct cx8802_dev *dev, char *reason, int restart)
{
struct cx88_dmaqueue *q = &dev->mpegq;
struct cx88_buffer *buf;
unsigned long flags;
spin_lock_irqsave(&dev->slock,flags);
while (!list_empty(&q->active)) {
buf = list_entry(q->active.next, struct cx88_buffer, vb.queue);
list_del(&buf->vb.queue);
buf->vb.state = VIDEOBUF_ERROR;
wake_up(&buf->vb.done);
dprintk(1,"[%p/%d] %s - dma=0x%08lx\n",
buf, buf->vb.i, reason, (unsigned long)buf->risc.dma);
}
if (restart)
{
dprintk(1, "restarting queue\n" );
cx8802_restart_queue(dev,q);
}
spin_unlock_irqrestore(&dev->slock,flags);
}
void cx8802_cancel_buffers(struct cx8802_dev *dev)
{
struct cx88_dmaqueue *q = &dev->mpegq;
dprintk( 1, "cx8802_cancel_buffers" );
del_timer_sync(&q->timeout);
cx8802_stop_dma(dev);
do_cancel_buffers(dev,"cancel",0);
}
static void cx8802_timeout(unsigned long data)
{
struct cx8802_dev *dev = (struct cx8802_dev*)data;
dprintk(1, "%s\n",__func__);
if (debug)
cx88_sram_channel_dump(dev->core, &cx88_sram_channels[SRAM_CH28]);
cx8802_stop_dma(dev);
do_cancel_buffers(dev,"timeout",1);
}
static char *cx88_mpeg_irqs[32] = {
"ts_risci1", NULL, NULL, NULL,
"ts_risci2", NULL, NULL, NULL,
"ts_oflow", NULL, NULL, NULL,
"ts_sync", NULL, NULL, NULL,
"opc_err", "par_err", "rip_err", "pci_abort",
"ts_err?",
};
static void cx8802_mpeg_irq(struct cx8802_dev *dev)
{
struct cx88_core *core = dev->core;
u32 status, mask, count;
dprintk( 1, "cx8802_mpeg_irq\n" );
status = cx_read(MO_TS_INTSTAT);
mask = cx_read(MO_TS_INTMSK);
if (0 == (status & mask))
return;
cx_write(MO_TS_INTSTAT, status);
if (debug || (status & mask & ~0xff))
cx88_print_irqbits(core->name, "irq mpeg ",
cx88_mpeg_irqs, ARRAY_SIZE(cx88_mpeg_irqs),
status, mask);
/* risc op code error */
if (status & (1 << 16)) {
printk(KERN_WARNING "%s: mpeg risc op code error\n",core->name);
cx_clear(MO_TS_DMACNTRL, 0x11);
cx88_sram_channel_dump(dev->core, &cx88_sram_channels[SRAM_CH28]);
}
/* risc1 y */
if (status & 0x01) {
dprintk( 1, "wake up\n" );
spin_lock(&dev->slock);
count = cx_read(MO_TS_GPCNT);
cx88_wakeup(dev->core, &dev->mpegq, count);
spin_unlock(&dev->slock);
}
/* risc2 y */
if (status & 0x10) {
spin_lock(&dev->slock);
cx8802_restart_queue(dev,&dev->mpegq);
spin_unlock(&dev->slock);
}
/* other general errors */
if (status & 0x1f0100) {
dprintk( 0, "general errors: 0x%08x\n", status & 0x1f0100 );
spin_lock(&dev->slock);
cx8802_stop_dma(dev);
cx8802_restart_queue(dev,&dev->mpegq);
spin_unlock(&dev->slock);
}
}
#define MAX_IRQ_LOOP 10
static irqreturn_t cx8802_irq(int irq, void *dev_id)
{
struct cx8802_dev *dev = dev_id;
struct cx88_core *core = dev->core;
u32 status;
int loop, handled = 0;
for (loop = 0; loop < MAX_IRQ_LOOP; loop++) {
status = cx_read(MO_PCI_INTSTAT) &
(core->pci_irqmask | PCI_INT_TSINT);
if (0 == status)
goto out;
dprintk( 1, "cx8802_irq\n" );
dprintk( 1, " loop: %d/%d\n", loop, MAX_IRQ_LOOP );
dprintk( 1, " status: %d\n", status );
handled = 1;
cx_write(MO_PCI_INTSTAT, status);
if (status & core->pci_irqmask)
cx88_core_irq(core,status);
if (status & PCI_INT_TSINT)
cx8802_mpeg_irq(dev);
};
if (MAX_IRQ_LOOP == loop) {
dprintk( 0, "clearing mask\n" );
printk(KERN_WARNING "%s/0: irq loop -- clearing mask\n",
core->name);
cx_write(MO_PCI_INTMSK,0);
}
out:
return IRQ_RETVAL(handled);
}
static int cx8802_init_common(struct cx8802_dev *dev)
{
struct cx88_core *core = dev->core;
int err;
/* pci init */
if (pci_enable_device(dev->pci))
return -EIO;
pci_set_master(dev->pci);
if (!pci_dma_supported(dev->pci,DMA_BIT_MASK(32))) {
printk("%s/2: Oops: no 32bit PCI DMA ???\n",dev->core->name);
return -EIO;
}
pci_read_config_byte(dev->pci, PCI_CLASS_REVISION, &dev->pci_rev);
pci_read_config_byte(dev->pci, PCI_LATENCY_TIMER, &dev->pci_lat);
printk(KERN_INFO "%s/2: found at %s, rev: %d, irq: %d, "
"latency: %d, mmio: 0x%llx\n", dev->core->name,
pci_name(dev->pci), dev->pci_rev, dev->pci->irq,
dev->pci_lat,(unsigned long long)pci_resource_start(dev->pci,0));
/* initialize driver struct */
spin_lock_init(&dev->slock);
/* init dma queue */
INIT_LIST_HEAD(&dev->mpegq.active);
INIT_LIST_HEAD(&dev->mpegq.queued);
dev->mpegq.timeout.function = cx8802_timeout;
dev->mpegq.timeout.data = (unsigned long)dev;
init_timer(&dev->mpegq.timeout);
cx88_risc_stopper(dev->pci,&dev->mpegq.stopper,
MO_TS_DMACNTRL,0x11,0x00);
/* get irq */
err = request_irq(dev->pci->irq, cx8802_irq,
IRQF_SHARED | IRQF_DISABLED, dev->core->name, dev);
if (err < 0) {
printk(KERN_ERR "%s: can't get IRQ %d\n",
dev->core->name, dev->pci->irq);
return err;
}
cx_set(MO_PCI_INTMSK, core->pci_irqmask);
/* everything worked */
pci_set_drvdata(dev->pci,dev);
return 0;
}
static void cx8802_fini_common(struct cx8802_dev *dev)
{
dprintk( 2, "cx8802_fini_common\n" );
cx8802_stop_dma(dev);
pci_disable_device(dev->pci);
/* unregister stuff */
free_irq(dev->pci->irq, dev);
pci_set_drvdata(dev->pci, NULL);
/* free memory */
btcx_riscmem_free(dev->pci,&dev->mpegq.stopper);
}
/* ----------------------------------------------------------- */
static int cx8802_suspend_common(struct pci_dev *pci_dev, pm_message_t state)
{
struct cx8802_dev *dev = pci_get_drvdata(pci_dev);
struct cx88_core *core = dev->core;
/* stop mpeg dma */
spin_lock(&dev->slock);
if (!list_empty(&dev->mpegq.active)) {
dprintk( 2, "suspend\n" );
printk("%s: suspend mpeg\n", core->name);
cx8802_stop_dma(dev);
del_timer(&dev->mpegq.timeout);
}
spin_unlock(&dev->slock);
/* FIXME -- shutdown device */
cx88_shutdown(dev->core);
pci_save_state(pci_dev);
if (0 != pci_set_power_state(pci_dev, pci_choose_state(pci_dev, state))) {
pci_disable_device(pci_dev);
dev->state.disabled = 1;
}
return 0;
}
static int cx8802_resume_common(struct pci_dev *pci_dev)
{
struct cx8802_dev *dev = pci_get_drvdata(pci_dev);
struct cx88_core *core = dev->core;
int err;
if (dev->state.disabled) {
err=pci_enable_device(pci_dev);
if (err) {
printk(KERN_ERR "%s: can't enable device\n",
dev->core->name);
return err;
}
dev->state.disabled = 0;
}
err=pci_set_power_state(pci_dev, PCI_D0);
if (err) {
printk(KERN_ERR "%s: can't enable device\n",
dev->core->name);
pci_disable_device(pci_dev);
dev->state.disabled = 1;
return err;
}
pci_restore_state(pci_dev);
/* FIXME: re-initialize hardware */
cx88_reset(dev->core);
/* restart video+vbi capture */
spin_lock(&dev->slock);
if (!list_empty(&dev->mpegq.active)) {
printk("%s: resume mpeg\n", core->name);
cx8802_restart_queue(dev,&dev->mpegq);
}
spin_unlock(&dev->slock);
return 0;
}
struct cx8802_driver * cx8802_get_driver(struct cx8802_dev *dev, enum cx88_board_type btype)
{
struct cx8802_driver *d;
list_for_each_entry(d, &dev->drvlist, drvlist)
if (d->type_id == btype)
return d;
return NULL;
}
/* Driver asked for hardware access. */
static int cx8802_request_acquire(struct cx8802_driver *drv)
{
struct cx88_core *core = drv->core;
unsigned int i;
/* Fail a request for hardware if the device is busy. */
if (core->active_type_id != CX88_BOARD_NONE &&
core->active_type_id != drv->type_id)
return -EBUSY;
core->input = 0;
for (i = 0;
i < (sizeof(core->board.input) / sizeof(struct cx88_input));
i++) {
if (core->board.input[i].type == CX88_VMUX_DVB) {
core->input = i;
break;
}
}
if (drv->advise_acquire)
{
mutex_lock(&drv->core->lock);
core->active_ref++;
if (core->active_type_id == CX88_BOARD_NONE) {
core->active_type_id = drv->type_id;
drv->advise_acquire(drv);
}
mutex_unlock(&drv->core->lock);
mpeg_dbg(1,"%s() Post acquire GPIO=%x\n", __func__, cx_read(MO_GP0_IO));
}
return 0;
}
/* Driver asked to release hardware. */
static int cx8802_request_release(struct cx8802_driver *drv)
{
struct cx88_core *core = drv->core;
mutex_lock(&drv->core->lock);
if (drv->advise_release && --core->active_ref == 0)
{
drv->advise_release(drv);
core->active_type_id = CX88_BOARD_NONE;
mpeg_dbg(1,"%s() Post release GPIO=%x\n", __func__, cx_read(MO_GP0_IO));
}
mutex_unlock(&drv->core->lock);
return 0;
}
static int cx8802_check_driver(struct cx8802_driver *drv)
{
if (drv == NULL)
return -ENODEV;
if ((drv->type_id != CX88_MPEG_DVB) &&
(drv->type_id != CX88_MPEG_BLACKBIRD))
return -EINVAL;
if ((drv->hw_access != CX8802_DRVCTL_SHARED) &&
(drv->hw_access != CX8802_DRVCTL_EXCLUSIVE))
return -EINVAL;
if ((drv->probe == NULL) ||
(drv->remove == NULL) ||
(drv->advise_acquire == NULL) ||
(drv->advise_release == NULL))
return -EINVAL;
return 0;
}
int cx8802_register_driver(struct cx8802_driver *drv)
{
struct cx8802_dev *dev;
struct cx8802_driver *driver;
int err, i = 0;
printk(KERN_INFO
"cx88/2: registering cx8802 driver, type: %s access: %s\n",
drv->type_id == CX88_MPEG_DVB ? "dvb" : "blackbird",
drv->hw_access == CX8802_DRVCTL_SHARED ? "shared" : "exclusive");
if ((err = cx8802_check_driver(drv)) != 0) {
printk(KERN_ERR "cx88/2: cx8802_driver is invalid\n");
return err;
}
list_for_each_entry(dev, &cx8802_devlist, devlist) {
printk(KERN_INFO
"%s/2: subsystem: %04x:%04x, board: %s [card=%d]\n",
dev->core->name, dev->pci->subsystem_vendor,
dev->pci->subsystem_device, dev->core->board.name,
dev->core->boardnr);
/* Bring up a new struct for each driver instance */
driver = kzalloc(sizeof(*drv),GFP_KERNEL);
if (driver == NULL)
return -ENOMEM;
/* Snapshot of the driver registration data */
drv->core = dev->core;
drv->suspend = cx8802_suspend_common;
drv->resume = cx8802_resume_common;
drv->request_acquire = cx8802_request_acquire;
drv->request_release = cx8802_request_release;
memcpy(driver, drv, sizeof(*driver));
err = drv->probe(driver);
if (err == 0) {
i++;
mutex_lock(&drv->core->lock);
list_add_tail(&driver->drvlist, &dev->drvlist);
mutex_unlock(&drv->core->lock);
} else {
printk(KERN_ERR
"%s/2: cx8802 probe failed, err = %d\n",
dev->core->name, err);
}
}
return i ? 0 : -ENODEV;
}
int cx8802_unregister_driver(struct cx8802_driver *drv)
{
struct cx8802_dev *dev;
struct cx8802_driver *d, *dtmp;
int err = 0;
printk(KERN_INFO
"cx88/2: unregistering cx8802 driver, type: %s access: %s\n",
drv->type_id == CX88_MPEG_DVB ? "dvb" : "blackbird",
drv->hw_access == CX8802_DRVCTL_SHARED ? "shared" : "exclusive");
list_for_each_entry(dev, &cx8802_devlist, devlist) {
printk(KERN_INFO
"%s/2: subsystem: %04x:%04x, board: %s [card=%d]\n",
dev->core->name, dev->pci->subsystem_vendor,
dev->pci->subsystem_device, dev->core->board.name,
dev->core->boardnr);
list_for_each_entry_safe(d, dtmp, &dev->drvlist, drvlist) {
/* only unregister the correct driver type */
if (d->type_id != drv->type_id)
continue;
err = d->remove(d);
if (err == 0) {
mutex_lock(&drv->core->lock);
list_del(&d->drvlist);
mutex_unlock(&drv->core->lock);
kfree(d);
} else
printk(KERN_ERR "%s/2: cx8802 driver remove "
"failed (%d)\n", dev->core->name, err);
}
}
return err;
}
/* ----------------------------------------------------------- */
static int __devinit cx8802_probe(struct pci_dev *pci_dev,
const struct pci_device_id *pci_id)
{
struct cx8802_dev *dev;
struct cx88_core *core;
int err;
/* general setup */
core = cx88_core_get(pci_dev);
if (NULL == core)
return -EINVAL;
printk("%s/2: cx2388x 8802 Driver Manager\n", core->name);
err = -ENODEV;
if (!core->board.mpeg)
goto fail_core;
err = -ENOMEM;
dev = kzalloc(sizeof(*dev),GFP_KERNEL);
if (NULL == dev)
goto fail_core;
dev->pci = pci_dev;
dev->core = core;
/* Maintain a reference so cx88-video can query the 8802 device. */
core->dvbdev = dev;
err = cx8802_init_common(dev);
if (err != 0)
goto fail_free;
INIT_LIST_HEAD(&dev->drvlist);
list_add_tail(&dev->devlist,&cx8802_devlist);
/* now autoload cx88-dvb or cx88-blackbird */
request_modules(dev);
return 0;
fail_free:
kfree(dev);
fail_core:
core->dvbdev = NULL;
cx88_core_put(core,pci_dev);
return err;
}
static void __devexit cx8802_remove(struct pci_dev *pci_dev)
{
struct cx8802_dev *dev;
dev = pci_get_drvdata(pci_dev);
dprintk( 1, "%s\n", __func__);
if (!list_empty(&dev->drvlist)) {
struct cx8802_driver *drv, *tmp;
int err;
printk(KERN_WARNING "%s/2: Trying to remove cx8802 driver "
"while cx8802 sub-drivers still loaded?!\n",
dev->core->name);
list_for_each_entry_safe(drv, tmp, &dev->drvlist, drvlist) {
err = drv->remove(drv);
if (err == 0) {
mutex_lock(&drv->core->lock);
list_del(&drv->drvlist);
mutex_unlock(&drv->core->lock);
} else
printk(KERN_ERR "%s/2: cx8802 driver remove "
"failed (%d)\n", dev->core->name, err);
kfree(drv);
}
}
/* Destroy any 8802 reference. */
dev->core->dvbdev = NULL;
/* common */
cx8802_fini_common(dev);
cx88_core_put(dev->core,dev->pci);
kfree(dev);
}
static struct pci_device_id cx8802_pci_tbl[] = {
{
.vendor = 0x14f1,
.device = 0x8802,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},{
/* --- end of list --- */
}
};
MODULE_DEVICE_TABLE(pci, cx8802_pci_tbl);
static struct pci_driver cx8802_pci_driver = {
.name = "cx88-mpeg driver manager",
.id_table = cx8802_pci_tbl,
.probe = cx8802_probe,
.remove = __devexit_p(cx8802_remove),
};
static int __init cx8802_init(void)
{
printk(KERN_INFO "cx88/2: cx2388x MPEG-TS Driver Manager version %d.%d.%d loaded\n",
(CX88_VERSION_CODE >> 16) & 0xff,
(CX88_VERSION_CODE >> 8) & 0xff,
CX88_VERSION_CODE & 0xff);
#ifdef SNAPSHOT
printk(KERN_INFO "cx2388x: snapshot date %04d-%02d-%02d\n",
SNAPSHOT/10000, (SNAPSHOT/100)%100, SNAPSHOT%100);
#endif
return pci_register_driver(&cx8802_pci_driver);
}
static void __exit cx8802_fini(void)
{
pci_unregister_driver(&cx8802_pci_driver);
}
module_init(cx8802_init);
module_exit(cx8802_fini);
EXPORT_SYMBOL(cx8802_buf_prepare);
EXPORT_SYMBOL(cx8802_buf_queue);
EXPORT_SYMBOL(cx8802_cancel_buffers);
EXPORT_SYMBOL(cx8802_register_driver);
EXPORT_SYMBOL(cx8802_unregister_driver);
EXPORT_SYMBOL(cx8802_get_driver);
/* ----------------------------------------------------------- */
/*
* Local variables:
* c-basic-offset: 8
* End:
* kate: eol "unix"; indent-width 3; remove-trailing-space on; replace-trailing-space-save on; tab-width 8; replace-tabs off; space-indent off; mixed-indent off
*/
| gpl-2.0 |
d8ahazard/AngryDragon-Source | drivers/media/video/cx88/cx88-mpeg.c | 901 | 24373 | /*
*
* Support for the mpeg transport stream transfers
* PCI function #2 of the cx2388x.
*
* (c) 2004 Jelle Foks <jelle@foks.us>
* (c) 2004 Chris Pascoe <c.pascoe@itee.uq.edu.au>
* (c) 2004 Gerd Knorr <kraxel@bytesex.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 <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/interrupt.h>
#include <asm/delay.h>
#include "cx88.h"
/* ------------------------------------------------------------------ */
MODULE_DESCRIPTION("mpeg driver for cx2388x based TV cards");
MODULE_AUTHOR("Jelle Foks <jelle@foks.us>");
MODULE_AUTHOR("Chris Pascoe <c.pascoe@itee.uq.edu.au>");
MODULE_AUTHOR("Gerd Knorr <kraxel@bytesex.org> [SuSE Labs]");
MODULE_LICENSE("GPL");
static unsigned int debug;
module_param(debug,int,0644);
MODULE_PARM_DESC(debug,"enable debug messages [mpeg]");
#define dprintk(level,fmt, arg...) if (debug >= level) \
printk(KERN_DEBUG "%s/2-mpeg: " fmt, dev->core->name, ## arg)
#define mpeg_dbg(level,fmt, arg...) if (debug >= level) \
printk(KERN_DEBUG "%s/2-mpeg: " fmt, core->name, ## arg)
#if defined(CONFIG_MODULES) && defined(MODULE)
static void request_module_async(struct work_struct *work)
{
struct cx8802_dev *dev=container_of(work, struct cx8802_dev, request_module_wk);
if (dev->core->board.mpeg & CX88_MPEG_DVB)
request_module("cx88-dvb");
if (dev->core->board.mpeg & CX88_MPEG_BLACKBIRD)
request_module("cx88-blackbird");
}
static void request_modules(struct cx8802_dev *dev)
{
INIT_WORK(&dev->request_module_wk, request_module_async);
schedule_work(&dev->request_module_wk);
}
#else
#define request_modules(dev)
#endif /* CONFIG_MODULES */
static LIST_HEAD(cx8802_devlist);
/* ------------------------------------------------------------------ */
static int cx8802_start_dma(struct cx8802_dev *dev,
struct cx88_dmaqueue *q,
struct cx88_buffer *buf)
{
struct cx88_core *core = dev->core;
dprintk(1, "cx8802_start_dma w: %d, h: %d, f: %d\n",
buf->vb.width, buf->vb.height, buf->vb.field);
/* setup fifo + format */
cx88_sram_channel_setup(core, &cx88_sram_channels[SRAM_CH28],
dev->ts_packet_size, buf->risc.dma);
/* write TS length to chip */
cx_write(MO_TS_LNGTH, buf->vb.width);
/* FIXME: this needs a review.
* also: move to cx88-blackbird + cx88-dvb source files? */
dprintk( 1, "core->active_type_id = 0x%08x\n", core->active_type_id);
if ( (core->active_type_id == CX88_MPEG_DVB) &&
(core->board.mpeg & CX88_MPEG_DVB) ) {
dprintk( 1, "cx8802_start_dma doing .dvb\n");
/* negedge driven & software reset */
cx_write(TS_GEN_CNTRL, 0x0040 | dev->ts_gen_cntrl);
udelay(100);
cx_write(MO_PINMUX_IO, 0x00);
cx_write(TS_HW_SOP_CNTRL, 0x47<<16|188<<4|0x01);
switch (core->boardnr) {
case CX88_BOARD_DVICO_FUSIONHDTV_3_GOLD_Q:
case CX88_BOARD_DVICO_FUSIONHDTV_3_GOLD_T:
case CX88_BOARD_DVICO_FUSIONHDTV_5_GOLD:
case CX88_BOARD_PCHDTV_HD5500:
cx_write(TS_SOP_STAT, 1<<13);
break;
case CX88_BOARD_SAMSUNG_SMT_7020:
cx_write(TS_SOP_STAT, 0x00);
break;
case CX88_BOARD_HAUPPAUGE_NOVASPLUS_S1:
case CX88_BOARD_HAUPPAUGE_NOVASE2_S1:
cx_write(MO_PINMUX_IO, 0x88); /* Enable MPEG parallel IO and video signal pins */
udelay(100);
break;
case CX88_BOARD_HAUPPAUGE_HVR1300:
/* Enable MPEG parallel IO and video signal pins */
cx_write(MO_PINMUX_IO, 0x88);
cx_write(TS_SOP_STAT, 0);
cx_write(TS_VALERR_CNTRL, 0);
break;
case CX88_BOARD_PINNACLE_PCTV_HD_800i:
/* Enable MPEG parallel IO and video signal pins */
cx_write(MO_PINMUX_IO, 0x88);
cx_write(TS_HW_SOP_CNTRL, (0x47 << 16) | (188 << 4));
dev->ts_gen_cntrl = 5;
cx_write(TS_SOP_STAT, 0);
cx_write(TS_VALERR_CNTRL, 0);
udelay(100);
break;
default:
cx_write(TS_SOP_STAT, 0x00);
break;
}
cx_write(TS_GEN_CNTRL, dev->ts_gen_cntrl);
udelay(100);
} else if ( (core->active_type_id == CX88_MPEG_BLACKBIRD) &&
(core->board.mpeg & CX88_MPEG_BLACKBIRD) ) {
dprintk( 1, "cx8802_start_dma doing .blackbird\n");
cx_write(MO_PINMUX_IO, 0x88); /* enable MPEG parallel IO */
cx_write(TS_GEN_CNTRL, 0x46); /* punctured clock TS & posedge driven & software reset */
udelay(100);
cx_write(TS_HW_SOP_CNTRL, 0x408); /* mpeg start byte */
cx_write(TS_VALERR_CNTRL, 0x2000);
cx_write(TS_GEN_CNTRL, 0x06); /* punctured clock TS & posedge driven */
udelay(100);
} else {
printk( "%s() Failed. Unsupported value in .mpeg (0x%08x)\n", __func__,
core->board.mpeg );
return -EINVAL;
}
/* reset counter */
cx_write(MO_TS_GPCNTRL, GP_COUNT_CONTROL_RESET);
q->count = 1;
/* enable irqs */
dprintk( 1, "setting the interrupt mask\n" );
cx_set(MO_PCI_INTMSK, core->pci_irqmask | PCI_INT_TSINT);
cx_set(MO_TS_INTMSK, 0x1f0011);
/* start dma */
cx_set(MO_DEV_CNTRL2, (1<<5));
cx_set(MO_TS_DMACNTRL, 0x11);
return 0;
}
static int cx8802_stop_dma(struct cx8802_dev *dev)
{
struct cx88_core *core = dev->core;
dprintk( 1, "cx8802_stop_dma\n" );
/* stop dma */
cx_clear(MO_TS_DMACNTRL, 0x11);
/* disable irqs */
cx_clear(MO_PCI_INTMSK, PCI_INT_TSINT);
cx_clear(MO_TS_INTMSK, 0x1f0011);
/* Reset the controller */
cx_write(TS_GEN_CNTRL, 0xcd);
return 0;
}
static int cx8802_restart_queue(struct cx8802_dev *dev,
struct cx88_dmaqueue *q)
{
struct cx88_buffer *buf;
dprintk( 1, "cx8802_restart_queue\n" );
if (list_empty(&q->active))
{
struct cx88_buffer *prev;
prev = NULL;
dprintk(1, "cx8802_restart_queue: queue is empty\n" );
for (;;) {
if (list_empty(&q->queued))
return 0;
buf = list_entry(q->queued.next, struct cx88_buffer, vb.queue);
if (NULL == prev) {
list_del(&buf->vb.queue);
list_add_tail(&buf->vb.queue,&q->active);
cx8802_start_dma(dev, q, buf);
buf->vb.state = VIDEOBUF_ACTIVE;
buf->count = q->count++;
mod_timer(&q->timeout, jiffies+BUFFER_TIMEOUT);
dprintk(1,"[%p/%d] restart_queue - first active\n",
buf,buf->vb.i);
} else if (prev->vb.width == buf->vb.width &&
prev->vb.height == buf->vb.height &&
prev->fmt == buf->fmt) {
list_del(&buf->vb.queue);
list_add_tail(&buf->vb.queue,&q->active);
buf->vb.state = VIDEOBUF_ACTIVE;
buf->count = q->count++;
prev->risc.jmp[1] = cpu_to_le32(buf->risc.dma);
dprintk(1,"[%p/%d] restart_queue - move to active\n",
buf,buf->vb.i);
} else {
return 0;
}
prev = buf;
}
return 0;
}
buf = list_entry(q->active.next, struct cx88_buffer, vb.queue);
dprintk(2,"restart_queue [%p/%d]: restart dma\n",
buf, buf->vb.i);
cx8802_start_dma(dev, q, buf);
list_for_each_entry(buf, &q->active, vb.queue)
buf->count = q->count++;
mod_timer(&q->timeout, jiffies+BUFFER_TIMEOUT);
return 0;
}
/* ------------------------------------------------------------------ */
int cx8802_buf_prepare(struct videobuf_queue *q, struct cx8802_dev *dev,
struct cx88_buffer *buf, enum v4l2_field field)
{
int size = dev->ts_packet_size * dev->ts_packet_count;
struct videobuf_dmabuf *dma=videobuf_to_dma(&buf->vb);
int rc;
dprintk(1, "%s: %p\n", __func__, buf);
if (0 != buf->vb.baddr && buf->vb.bsize < size)
return -EINVAL;
if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
buf->vb.width = dev->ts_packet_size;
buf->vb.height = dev->ts_packet_count;
buf->vb.size = size;
buf->vb.field = field /*V4L2_FIELD_TOP*/;
if (0 != (rc = videobuf_iolock(q,&buf->vb,NULL)))
goto fail;
cx88_risc_databuffer(dev->pci, &buf->risc,
dma->sglist,
buf->vb.width, buf->vb.height, 0);
}
buf->vb.state = VIDEOBUF_PREPARED;
return 0;
fail:
cx88_free_buffer(q,buf);
return rc;
}
void cx8802_buf_queue(struct cx8802_dev *dev, struct cx88_buffer *buf)
{
struct cx88_buffer *prev;
struct cx88_dmaqueue *cx88q = &dev->mpegq;
dprintk( 1, "cx8802_buf_queue\n" );
/* add jump to stopper */
buf->risc.jmp[0] = cpu_to_le32(RISC_JUMP | RISC_IRQ1 | RISC_CNT_INC);
buf->risc.jmp[1] = cpu_to_le32(cx88q->stopper.dma);
if (list_empty(&cx88q->active)) {
dprintk( 1, "queue is empty - first active\n" );
list_add_tail(&buf->vb.queue,&cx88q->active);
cx8802_start_dma(dev, cx88q, buf);
buf->vb.state = VIDEOBUF_ACTIVE;
buf->count = cx88q->count++;
mod_timer(&cx88q->timeout, jiffies+BUFFER_TIMEOUT);
dprintk(1,"[%p/%d] %s - first active\n",
buf, buf->vb.i, __func__);
} else {
dprintk( 1, "queue is not empty - append to active\n" );
prev = list_entry(cx88q->active.prev, struct cx88_buffer, vb.queue);
list_add_tail(&buf->vb.queue,&cx88q->active);
buf->vb.state = VIDEOBUF_ACTIVE;
buf->count = cx88q->count++;
prev->risc.jmp[1] = cpu_to_le32(buf->risc.dma);
dprintk( 1, "[%p/%d] %s - append to active\n",
buf, buf->vb.i, __func__);
}
}
/* ----------------------------------------------------------- */
static void do_cancel_buffers(struct cx8802_dev *dev, char *reason, int restart)
{
struct cx88_dmaqueue *q = &dev->mpegq;
struct cx88_buffer *buf;
unsigned long flags;
spin_lock_irqsave(&dev->slock,flags);
while (!list_empty(&q->active)) {
buf = list_entry(q->active.next, struct cx88_buffer, vb.queue);
list_del(&buf->vb.queue);
buf->vb.state = VIDEOBUF_ERROR;
wake_up(&buf->vb.done);
dprintk(1,"[%p/%d] %s - dma=0x%08lx\n",
buf, buf->vb.i, reason, (unsigned long)buf->risc.dma);
}
if (restart)
{
dprintk(1, "restarting queue\n" );
cx8802_restart_queue(dev,q);
}
spin_unlock_irqrestore(&dev->slock,flags);
}
void cx8802_cancel_buffers(struct cx8802_dev *dev)
{
struct cx88_dmaqueue *q = &dev->mpegq;
dprintk( 1, "cx8802_cancel_buffers" );
del_timer_sync(&q->timeout);
cx8802_stop_dma(dev);
do_cancel_buffers(dev,"cancel",0);
}
static void cx8802_timeout(unsigned long data)
{
struct cx8802_dev *dev = (struct cx8802_dev*)data;
dprintk(1, "%s\n",__func__);
if (debug)
cx88_sram_channel_dump(dev->core, &cx88_sram_channels[SRAM_CH28]);
cx8802_stop_dma(dev);
do_cancel_buffers(dev,"timeout",1);
}
static char *cx88_mpeg_irqs[32] = {
"ts_risci1", NULL, NULL, NULL,
"ts_risci2", NULL, NULL, NULL,
"ts_oflow", NULL, NULL, NULL,
"ts_sync", NULL, NULL, NULL,
"opc_err", "par_err", "rip_err", "pci_abort",
"ts_err?",
};
static void cx8802_mpeg_irq(struct cx8802_dev *dev)
{
struct cx88_core *core = dev->core;
u32 status, mask, count;
dprintk( 1, "cx8802_mpeg_irq\n" );
status = cx_read(MO_TS_INTSTAT);
mask = cx_read(MO_TS_INTMSK);
if (0 == (status & mask))
return;
cx_write(MO_TS_INTSTAT, status);
if (debug || (status & mask & ~0xff))
cx88_print_irqbits(core->name, "irq mpeg ",
cx88_mpeg_irqs, ARRAY_SIZE(cx88_mpeg_irqs),
status, mask);
/* risc op code error */
if (status & (1 << 16)) {
printk(KERN_WARNING "%s: mpeg risc op code error\n",core->name);
cx_clear(MO_TS_DMACNTRL, 0x11);
cx88_sram_channel_dump(dev->core, &cx88_sram_channels[SRAM_CH28]);
}
/* risc1 y */
if (status & 0x01) {
dprintk( 1, "wake up\n" );
spin_lock(&dev->slock);
count = cx_read(MO_TS_GPCNT);
cx88_wakeup(dev->core, &dev->mpegq, count);
spin_unlock(&dev->slock);
}
/* risc2 y */
if (status & 0x10) {
spin_lock(&dev->slock);
cx8802_restart_queue(dev,&dev->mpegq);
spin_unlock(&dev->slock);
}
/* other general errors */
if (status & 0x1f0100) {
dprintk( 0, "general errors: 0x%08x\n", status & 0x1f0100 );
spin_lock(&dev->slock);
cx8802_stop_dma(dev);
cx8802_restart_queue(dev,&dev->mpegq);
spin_unlock(&dev->slock);
}
}
#define MAX_IRQ_LOOP 10
static irqreturn_t cx8802_irq(int irq, void *dev_id)
{
struct cx8802_dev *dev = dev_id;
struct cx88_core *core = dev->core;
u32 status;
int loop, handled = 0;
for (loop = 0; loop < MAX_IRQ_LOOP; loop++) {
status = cx_read(MO_PCI_INTSTAT) &
(core->pci_irqmask | PCI_INT_TSINT);
if (0 == status)
goto out;
dprintk( 1, "cx8802_irq\n" );
dprintk( 1, " loop: %d/%d\n", loop, MAX_IRQ_LOOP );
dprintk( 1, " status: %d\n", status );
handled = 1;
cx_write(MO_PCI_INTSTAT, status);
if (status & core->pci_irqmask)
cx88_core_irq(core,status);
if (status & PCI_INT_TSINT)
cx8802_mpeg_irq(dev);
};
if (MAX_IRQ_LOOP == loop) {
dprintk( 0, "clearing mask\n" );
printk(KERN_WARNING "%s/0: irq loop -- clearing mask\n",
core->name);
cx_write(MO_PCI_INTMSK,0);
}
out:
return IRQ_RETVAL(handled);
}
static int cx8802_init_common(struct cx8802_dev *dev)
{
struct cx88_core *core = dev->core;
int err;
/* pci init */
if (pci_enable_device(dev->pci))
return -EIO;
pci_set_master(dev->pci);
if (!pci_dma_supported(dev->pci,DMA_BIT_MASK(32))) {
printk("%s/2: Oops: no 32bit PCI DMA ???\n",dev->core->name);
return -EIO;
}
pci_read_config_byte(dev->pci, PCI_CLASS_REVISION, &dev->pci_rev);
pci_read_config_byte(dev->pci, PCI_LATENCY_TIMER, &dev->pci_lat);
printk(KERN_INFO "%s/2: found at %s, rev: %d, irq: %d, "
"latency: %d, mmio: 0x%llx\n", dev->core->name,
pci_name(dev->pci), dev->pci_rev, dev->pci->irq,
dev->pci_lat,(unsigned long long)pci_resource_start(dev->pci,0));
/* initialize driver struct */
spin_lock_init(&dev->slock);
/* init dma queue */
INIT_LIST_HEAD(&dev->mpegq.active);
INIT_LIST_HEAD(&dev->mpegq.queued);
dev->mpegq.timeout.function = cx8802_timeout;
dev->mpegq.timeout.data = (unsigned long)dev;
init_timer(&dev->mpegq.timeout);
cx88_risc_stopper(dev->pci,&dev->mpegq.stopper,
MO_TS_DMACNTRL,0x11,0x00);
/* get irq */
err = request_irq(dev->pci->irq, cx8802_irq,
IRQF_SHARED | IRQF_DISABLED, dev->core->name, dev);
if (err < 0) {
printk(KERN_ERR "%s: can't get IRQ %d\n",
dev->core->name, dev->pci->irq);
return err;
}
cx_set(MO_PCI_INTMSK, core->pci_irqmask);
/* everything worked */
pci_set_drvdata(dev->pci,dev);
return 0;
}
static void cx8802_fini_common(struct cx8802_dev *dev)
{
dprintk( 2, "cx8802_fini_common\n" );
cx8802_stop_dma(dev);
pci_disable_device(dev->pci);
/* unregister stuff */
free_irq(dev->pci->irq, dev);
pci_set_drvdata(dev->pci, NULL);
/* free memory */
btcx_riscmem_free(dev->pci,&dev->mpegq.stopper);
}
/* ----------------------------------------------------------- */
static int cx8802_suspend_common(struct pci_dev *pci_dev, pm_message_t state)
{
struct cx8802_dev *dev = pci_get_drvdata(pci_dev);
struct cx88_core *core = dev->core;
/* stop mpeg dma */
spin_lock(&dev->slock);
if (!list_empty(&dev->mpegq.active)) {
dprintk( 2, "suspend\n" );
printk("%s: suspend mpeg\n", core->name);
cx8802_stop_dma(dev);
del_timer(&dev->mpegq.timeout);
}
spin_unlock(&dev->slock);
/* FIXME -- shutdown device */
cx88_shutdown(dev->core);
pci_save_state(pci_dev);
if (0 != pci_set_power_state(pci_dev, pci_choose_state(pci_dev, state))) {
pci_disable_device(pci_dev);
dev->state.disabled = 1;
}
return 0;
}
static int cx8802_resume_common(struct pci_dev *pci_dev)
{
struct cx8802_dev *dev = pci_get_drvdata(pci_dev);
struct cx88_core *core = dev->core;
int err;
if (dev->state.disabled) {
err=pci_enable_device(pci_dev);
if (err) {
printk(KERN_ERR "%s: can't enable device\n",
dev->core->name);
return err;
}
dev->state.disabled = 0;
}
err=pci_set_power_state(pci_dev, PCI_D0);
if (err) {
printk(KERN_ERR "%s: can't enable device\n",
dev->core->name);
pci_disable_device(pci_dev);
dev->state.disabled = 1;
return err;
}
pci_restore_state(pci_dev);
/* FIXME: re-initialize hardware */
cx88_reset(dev->core);
/* restart video+vbi capture */
spin_lock(&dev->slock);
if (!list_empty(&dev->mpegq.active)) {
printk("%s: resume mpeg\n", core->name);
cx8802_restart_queue(dev,&dev->mpegq);
}
spin_unlock(&dev->slock);
return 0;
}
struct cx8802_driver * cx8802_get_driver(struct cx8802_dev *dev, enum cx88_board_type btype)
{
struct cx8802_driver *d;
list_for_each_entry(d, &dev->drvlist, drvlist)
if (d->type_id == btype)
return d;
return NULL;
}
/* Driver asked for hardware access. */
static int cx8802_request_acquire(struct cx8802_driver *drv)
{
struct cx88_core *core = drv->core;
unsigned int i;
/* Fail a request for hardware if the device is busy. */
if (core->active_type_id != CX88_BOARD_NONE &&
core->active_type_id != drv->type_id)
return -EBUSY;
core->input = 0;
for (i = 0;
i < (sizeof(core->board.input) / sizeof(struct cx88_input));
i++) {
if (core->board.input[i].type == CX88_VMUX_DVB) {
core->input = i;
break;
}
}
if (drv->advise_acquire)
{
mutex_lock(&drv->core->lock);
core->active_ref++;
if (core->active_type_id == CX88_BOARD_NONE) {
core->active_type_id = drv->type_id;
drv->advise_acquire(drv);
}
mutex_unlock(&drv->core->lock);
mpeg_dbg(1,"%s() Post acquire GPIO=%x\n", __func__, cx_read(MO_GP0_IO));
}
return 0;
}
/* Driver asked to release hardware. */
static int cx8802_request_release(struct cx8802_driver *drv)
{
struct cx88_core *core = drv->core;
mutex_lock(&drv->core->lock);
if (drv->advise_release && --core->active_ref == 0)
{
drv->advise_release(drv);
core->active_type_id = CX88_BOARD_NONE;
mpeg_dbg(1,"%s() Post release GPIO=%x\n", __func__, cx_read(MO_GP0_IO));
}
mutex_unlock(&drv->core->lock);
return 0;
}
static int cx8802_check_driver(struct cx8802_driver *drv)
{
if (drv == NULL)
return -ENODEV;
if ((drv->type_id != CX88_MPEG_DVB) &&
(drv->type_id != CX88_MPEG_BLACKBIRD))
return -EINVAL;
if ((drv->hw_access != CX8802_DRVCTL_SHARED) &&
(drv->hw_access != CX8802_DRVCTL_EXCLUSIVE))
return -EINVAL;
if ((drv->probe == NULL) ||
(drv->remove == NULL) ||
(drv->advise_acquire == NULL) ||
(drv->advise_release == NULL))
return -EINVAL;
return 0;
}
int cx8802_register_driver(struct cx8802_driver *drv)
{
struct cx8802_dev *dev;
struct cx8802_driver *driver;
int err, i = 0;
printk(KERN_INFO
"cx88/2: registering cx8802 driver, type: %s access: %s\n",
drv->type_id == CX88_MPEG_DVB ? "dvb" : "blackbird",
drv->hw_access == CX8802_DRVCTL_SHARED ? "shared" : "exclusive");
if ((err = cx8802_check_driver(drv)) != 0) {
printk(KERN_ERR "cx88/2: cx8802_driver is invalid\n");
return err;
}
list_for_each_entry(dev, &cx8802_devlist, devlist) {
printk(KERN_INFO
"%s/2: subsystem: %04x:%04x, board: %s [card=%d]\n",
dev->core->name, dev->pci->subsystem_vendor,
dev->pci->subsystem_device, dev->core->board.name,
dev->core->boardnr);
/* Bring up a new struct for each driver instance */
driver = kzalloc(sizeof(*drv),GFP_KERNEL);
if (driver == NULL)
return -ENOMEM;
/* Snapshot of the driver registration data */
drv->core = dev->core;
drv->suspend = cx8802_suspend_common;
drv->resume = cx8802_resume_common;
drv->request_acquire = cx8802_request_acquire;
drv->request_release = cx8802_request_release;
memcpy(driver, drv, sizeof(*driver));
err = drv->probe(driver);
if (err == 0) {
i++;
mutex_lock(&drv->core->lock);
list_add_tail(&driver->drvlist, &dev->drvlist);
mutex_unlock(&drv->core->lock);
} else {
printk(KERN_ERR
"%s/2: cx8802 probe failed, err = %d\n",
dev->core->name, err);
}
}
return i ? 0 : -ENODEV;
}
int cx8802_unregister_driver(struct cx8802_driver *drv)
{
struct cx8802_dev *dev;
struct cx8802_driver *d, *dtmp;
int err = 0;
printk(KERN_INFO
"cx88/2: unregistering cx8802 driver, type: %s access: %s\n",
drv->type_id == CX88_MPEG_DVB ? "dvb" : "blackbird",
drv->hw_access == CX8802_DRVCTL_SHARED ? "shared" : "exclusive");
list_for_each_entry(dev, &cx8802_devlist, devlist) {
printk(KERN_INFO
"%s/2: subsystem: %04x:%04x, board: %s [card=%d]\n",
dev->core->name, dev->pci->subsystem_vendor,
dev->pci->subsystem_device, dev->core->board.name,
dev->core->boardnr);
list_for_each_entry_safe(d, dtmp, &dev->drvlist, drvlist) {
/* only unregister the correct driver type */
if (d->type_id != drv->type_id)
continue;
err = d->remove(d);
if (err == 0) {
mutex_lock(&drv->core->lock);
list_del(&d->drvlist);
mutex_unlock(&drv->core->lock);
kfree(d);
} else
printk(KERN_ERR "%s/2: cx8802 driver remove "
"failed (%d)\n", dev->core->name, err);
}
}
return err;
}
/* ----------------------------------------------------------- */
static int __devinit cx8802_probe(struct pci_dev *pci_dev,
const struct pci_device_id *pci_id)
{
struct cx8802_dev *dev;
struct cx88_core *core;
int err;
/* general setup */
core = cx88_core_get(pci_dev);
if (NULL == core)
return -EINVAL;
printk("%s/2: cx2388x 8802 Driver Manager\n", core->name);
err = -ENODEV;
if (!core->board.mpeg)
goto fail_core;
err = -ENOMEM;
dev = kzalloc(sizeof(*dev),GFP_KERNEL);
if (NULL == dev)
goto fail_core;
dev->pci = pci_dev;
dev->core = core;
/* Maintain a reference so cx88-video can query the 8802 device. */
core->dvbdev = dev;
err = cx8802_init_common(dev);
if (err != 0)
goto fail_free;
INIT_LIST_HEAD(&dev->drvlist);
list_add_tail(&dev->devlist,&cx8802_devlist);
/* now autoload cx88-dvb or cx88-blackbird */
request_modules(dev);
return 0;
fail_free:
kfree(dev);
fail_core:
core->dvbdev = NULL;
cx88_core_put(core,pci_dev);
return err;
}
static void __devexit cx8802_remove(struct pci_dev *pci_dev)
{
struct cx8802_dev *dev;
dev = pci_get_drvdata(pci_dev);
dprintk( 1, "%s\n", __func__);
if (!list_empty(&dev->drvlist)) {
struct cx8802_driver *drv, *tmp;
int err;
printk(KERN_WARNING "%s/2: Trying to remove cx8802 driver "
"while cx8802 sub-drivers still loaded?!\n",
dev->core->name);
list_for_each_entry_safe(drv, tmp, &dev->drvlist, drvlist) {
err = drv->remove(drv);
if (err == 0) {
mutex_lock(&drv->core->lock);
list_del(&drv->drvlist);
mutex_unlock(&drv->core->lock);
} else
printk(KERN_ERR "%s/2: cx8802 driver remove "
"failed (%d)\n", dev->core->name, err);
kfree(drv);
}
}
/* Destroy any 8802 reference. */
dev->core->dvbdev = NULL;
/* common */
cx8802_fini_common(dev);
cx88_core_put(dev->core,dev->pci);
kfree(dev);
}
static struct pci_device_id cx8802_pci_tbl[] = {
{
.vendor = 0x14f1,
.device = 0x8802,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},{
/* --- end of list --- */
}
};
MODULE_DEVICE_TABLE(pci, cx8802_pci_tbl);
static struct pci_driver cx8802_pci_driver = {
.name = "cx88-mpeg driver manager",
.id_table = cx8802_pci_tbl,
.probe = cx8802_probe,
.remove = __devexit_p(cx8802_remove),
};
static int __init cx8802_init(void)
{
printk(KERN_INFO "cx88/2: cx2388x MPEG-TS Driver Manager version %d.%d.%d loaded\n",
(CX88_VERSION_CODE >> 16) & 0xff,
(CX88_VERSION_CODE >> 8) & 0xff,
CX88_VERSION_CODE & 0xff);
#ifdef SNAPSHOT
printk(KERN_INFO "cx2388x: snapshot date %04d-%02d-%02d\n",
SNAPSHOT/10000, (SNAPSHOT/100)%100, SNAPSHOT%100);
#endif
return pci_register_driver(&cx8802_pci_driver);
}
static void __exit cx8802_fini(void)
{
pci_unregister_driver(&cx8802_pci_driver);
}
module_init(cx8802_init);
module_exit(cx8802_fini);
EXPORT_SYMBOL(cx8802_buf_prepare);
EXPORT_SYMBOL(cx8802_buf_queue);
EXPORT_SYMBOL(cx8802_cancel_buffers);
EXPORT_SYMBOL(cx8802_register_driver);
EXPORT_SYMBOL(cx8802_unregister_driver);
EXPORT_SYMBOL(cx8802_get_driver);
/* ----------------------------------------------------------- */
/*
* Local variables:
* c-basic-offset: 8
* End:
* kate: eol "unix"; indent-width 3; remove-trailing-space on; replace-trailing-space-save on; tab-width 8; replace-tabs off; space-indent off; mixed-indent off
*/
| gpl-2.0 |
OMFGB/htc-kernel-msm7x30_omfgb | drivers/video/geode/gxfb_core.c | 901 | 14047 | /*
* Geode GX framebuffer driver.
*
* Copyright (C) 2006 Arcom Control Systems Ltd.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*
* This driver assumes that the BIOS has created a virtual PCI device header
* for the video device. The PCI header is assumed to contain the following
* BARs:
*
* BAR0 - framebuffer memory
* BAR1 - graphics processor registers
* BAR2 - display controller registers
* BAR3 - video processor and flat panel control registers.
*
* 16 MiB of framebuffer memory is assumed to be available.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/delay.h>
#include <linux/fb.h>
#include <linux/console.h>
#include <linux/suspend.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/cs5535.h>
#include "gxfb.h"
static char *mode_option;
static int vram;
static int vt_switch;
/* Modes relevant to the GX (taken from modedb.c) */
static struct fb_videomode gx_modedb[] __devinitdata = {
/* 640x480-60 VESA */
{ NULL, 60, 640, 480, 39682, 48, 16, 33, 10, 96, 2,
0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 640x480-75 VESA */
{ NULL, 75, 640, 480, 31746, 120, 16, 16, 01, 64, 3,
0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 640x480-85 VESA */
{ NULL, 85, 640, 480, 27777, 80, 56, 25, 01, 56, 3,
0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 800x600-60 VESA */
{ NULL, 60, 800, 600, 25000, 88, 40, 23, 01, 128, 4,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 800x600-75 VESA */
{ NULL, 75, 800, 600, 20202, 160, 16, 21, 01, 80, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 800x600-85 VESA */
{ NULL, 85, 800, 600, 17761, 152, 32, 27, 01, 64, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1024x768-60 VESA */
{ NULL, 60, 1024, 768, 15384, 160, 24, 29, 3, 136, 6,
0, FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1024x768-75 VESA */
{ NULL, 75, 1024, 768, 12690, 176, 16, 28, 1, 96, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1024x768-85 VESA */
{ NULL, 85, 1024, 768, 10582, 208, 48, 36, 1, 96, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1280x960-60 VESA */
{ NULL, 60, 1280, 960, 9259, 312, 96, 36, 1, 112, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1280x960-85 VESA */
{ NULL, 85, 1280, 960, 6734, 224, 64, 47, 1, 160, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1280x1024-60 VESA */
{ NULL, 60, 1280, 1024, 9259, 248, 48, 38, 1, 112, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1280x1024-75 VESA */
{ NULL, 75, 1280, 1024, 7407, 248, 16, 38, 1, 144, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1280x1024-85 VESA */
{ NULL, 85, 1280, 1024, 6349, 224, 64, 44, 1, 160, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1600x1200-60 VESA */
{ NULL, 60, 1600, 1200, 6172, 304, 64, 46, 1, 192, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1600x1200-75 VESA */
{ NULL, 75, 1600, 1200, 4938, 304, 64, 46, 1, 192, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
/* 1600x1200-85 VESA */
{ NULL, 85, 1600, 1200, 4357, 304, 64, 46, 1, 192, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, FB_MODE_IS_VESA },
};
#ifdef CONFIG_OLPC
#include <asm/olpc.h>
static struct fb_videomode gx_dcon_modedb[] __devinitdata = {
/* The only mode the DCON has is 1200x900 */
{ NULL, 50, 1200, 900, 17460, 24, 8, 4, 5, 8, 3,
FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
FB_VMODE_NONINTERLACED, 0 }
};
static void __devinit get_modedb(struct fb_videomode **modedb,
unsigned int *size)
{
if (olpc_has_dcon()) {
*modedb = (struct fb_videomode *) gx_dcon_modedb;
*size = ARRAY_SIZE(gx_dcon_modedb);
} else {
*modedb = (struct fb_videomode *) gx_modedb;
*size = ARRAY_SIZE(gx_modedb);
}
}
#else
static void __devinit get_modedb(struct fb_videomode **modedb,
unsigned int *size)
{
*modedb = (struct fb_videomode *) gx_modedb;
*size = ARRAY_SIZE(gx_modedb);
}
#endif
static int gxfb_check_var(struct fb_var_screeninfo *var, struct fb_info *info)
{
if (var->xres > 1600 || var->yres > 1200)
return -EINVAL;
if ((var->xres > 1280 || var->yres > 1024) && var->bits_per_pixel > 16)
return -EINVAL;
if (var->bits_per_pixel == 32) {
var->red.offset = 16; var->red.length = 8;
var->green.offset = 8; var->green.length = 8;
var->blue.offset = 0; var->blue.length = 8;
} else if (var->bits_per_pixel == 16) {
var->red.offset = 11; var->red.length = 5;
var->green.offset = 5; var->green.length = 6;
var->blue.offset = 0; var->blue.length = 5;
} else if (var->bits_per_pixel == 8) {
var->red.offset = 0; var->red.length = 8;
var->green.offset = 0; var->green.length = 8;
var->blue.offset = 0; var->blue.length = 8;
} else
return -EINVAL;
var->transp.offset = 0; var->transp.length = 0;
/* Enough video memory? */
if (gx_line_delta(var->xres, var->bits_per_pixel) * var->yres > info->fix.smem_len)
return -EINVAL;
/* FIXME: Check timing parameters here? */
return 0;
}
static int gxfb_set_par(struct fb_info *info)
{
if (info->var.bits_per_pixel > 8)
info->fix.visual = FB_VISUAL_TRUECOLOR;
else
info->fix.visual = FB_VISUAL_PSEUDOCOLOR;
info->fix.line_length = gx_line_delta(info->var.xres, info->var.bits_per_pixel);
gx_set_mode(info);
return 0;
}
static inline u_int chan_to_field(u_int chan, struct fb_bitfield *bf)
{
chan &= 0xffff;
chan >>= 16 - bf->length;
return chan << bf->offset;
}
static int gxfb_setcolreg(unsigned regno, unsigned red, unsigned green,
unsigned blue, unsigned transp,
struct fb_info *info)
{
if (info->var.grayscale) {
/* grayscale = 0.30*R + 0.59*G + 0.11*B */
red = green = blue = (red * 77 + green * 151 + blue * 28) >> 8;
}
/* Truecolor has hardware independent palette */
if (info->fix.visual == FB_VISUAL_TRUECOLOR) {
u32 *pal = info->pseudo_palette;
u32 v;
if (regno >= 16)
return -EINVAL;
v = chan_to_field(red, &info->var.red);
v |= chan_to_field(green, &info->var.green);
v |= chan_to_field(blue, &info->var.blue);
pal[regno] = v;
} else {
if (regno >= 256)
return -EINVAL;
gx_set_hw_palette_reg(info, regno, red, green, blue);
}
return 0;
}
static int gxfb_blank(int blank_mode, struct fb_info *info)
{
return gx_blank_display(info, blank_mode);
}
static int __devinit gxfb_map_video_memory(struct fb_info *info,
struct pci_dev *dev)
{
struct gxfb_par *par = info->par;
int ret;
ret = pci_enable_device(dev);
if (ret < 0)
return ret;
ret = pci_request_region(dev, 3, "gxfb (video processor)");
if (ret < 0)
return ret;
par->vid_regs = pci_ioremap_bar(dev, 3);
if (!par->vid_regs)
return -ENOMEM;
ret = pci_request_region(dev, 2, "gxfb (display controller)");
if (ret < 0)
return ret;
par->dc_regs = pci_ioremap_bar(dev, 2);
if (!par->dc_regs)
return -ENOMEM;
ret = pci_request_region(dev, 1, "gxfb (graphics processor)");
if (ret < 0)
return ret;
par->gp_regs = pci_ioremap_bar(dev, 1);
if (!par->gp_regs)
return -ENOMEM;
ret = pci_request_region(dev, 0, "gxfb (framebuffer)");
if (ret < 0)
return ret;
info->fix.smem_start = pci_resource_start(dev, 0);
info->fix.smem_len = vram ? vram : gx_frame_buffer_size();
info->screen_base = ioremap(info->fix.smem_start, info->fix.smem_len);
if (!info->screen_base)
return -ENOMEM;
/* Set the 16MiB aligned base address of the graphics memory region
* in the display controller */
write_dc(par, DC_GLIU0_MEM_OFFSET, info->fix.smem_start & 0xFF000000);
dev_info(&dev->dev, "%d KiB of video memory at 0x%lx\n",
info->fix.smem_len / 1024, info->fix.smem_start);
return 0;
}
static struct fb_ops gxfb_ops = {
.owner = THIS_MODULE,
.fb_check_var = gxfb_check_var,
.fb_set_par = gxfb_set_par,
.fb_setcolreg = gxfb_setcolreg,
.fb_blank = gxfb_blank,
/* No HW acceleration for now. */
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
};
static struct fb_info *__devinit gxfb_init_fbinfo(struct device *dev)
{
struct gxfb_par *par;
struct fb_info *info;
/* Alloc enough space for the pseudo palette. */
info = framebuffer_alloc(sizeof(struct gxfb_par) + sizeof(u32) * 16,
dev);
if (!info)
return NULL;
par = info->par;
strcpy(info->fix.id, "Geode GX");
info->fix.type = FB_TYPE_PACKED_PIXELS;
info->fix.type_aux = 0;
info->fix.xpanstep = 0;
info->fix.ypanstep = 0;
info->fix.ywrapstep = 0;
info->fix.accel = FB_ACCEL_NONE;
info->var.nonstd = 0;
info->var.activate = FB_ACTIVATE_NOW;
info->var.height = -1;
info->var.width = -1;
info->var.accel_flags = 0;
info->var.vmode = FB_VMODE_NONINTERLACED;
info->fbops = &gxfb_ops;
info->flags = FBINFO_DEFAULT;
info->node = -1;
info->pseudo_palette = (void *)par + sizeof(struct gxfb_par);
info->var.grayscale = 0;
if (fb_alloc_cmap(&info->cmap, 256, 0) < 0) {
framebuffer_release(info);
return NULL;
}
return info;
}
#ifdef CONFIG_PM
static int gxfb_suspend(struct pci_dev *pdev, pm_message_t state)
{
struct fb_info *info = pci_get_drvdata(pdev);
if (state.event == PM_EVENT_SUSPEND) {
acquire_console_sem();
gx_powerdown(info);
fb_set_suspend(info, 1);
release_console_sem();
}
/* there's no point in setting PCI states; we emulate PCI, so
* we don't end up getting power savings anyways */
return 0;
}
static int gxfb_resume(struct pci_dev *pdev)
{
struct fb_info *info = pci_get_drvdata(pdev);
int ret;
acquire_console_sem();
ret = gx_powerup(info);
if (ret) {
printk(KERN_ERR "gxfb: power up failed!\n");
return ret;
}
fb_set_suspend(info, 0);
release_console_sem();
return 0;
}
#endif
static int __devinit gxfb_probe(struct pci_dev *pdev,
const struct pci_device_id *id)
{
struct gxfb_par *par;
struct fb_info *info;
int ret;
unsigned long val;
struct fb_videomode *modedb_ptr;
unsigned int modedb_size;
info = gxfb_init_fbinfo(&pdev->dev);
if (!info)
return -ENOMEM;
par = info->par;
if ((ret = gxfb_map_video_memory(info, pdev)) < 0) {
dev_err(&pdev->dev, "failed to map frame buffer or controller registers\n");
goto err;
}
/* Figure out if this is a TFT or CRT part */
rdmsrl(MSR_GX_GLD_MSR_CONFIG, val);
if ((val & MSR_GX_GLD_MSR_CONFIG_FP) == MSR_GX_GLD_MSR_CONFIG_FP)
par->enable_crt = 0;
else
par->enable_crt = 1;
get_modedb(&modedb_ptr, &modedb_size);
ret = fb_find_mode(&info->var, info, mode_option,
modedb_ptr, modedb_size, NULL, 16);
if (ret == 0 || ret == 4) {
dev_err(&pdev->dev, "could not find valid video mode\n");
ret = -EINVAL;
goto err;
}
/* Clear the frame buffer of garbage. */
memset_io(info->screen_base, 0, info->fix.smem_len);
gxfb_check_var(&info->var, info);
gxfb_set_par(info);
pm_set_vt_switch(vt_switch);
if (register_framebuffer(info) < 0) {
ret = -EINVAL;
goto err;
}
pci_set_drvdata(pdev, info);
printk(KERN_INFO "fb%d: %s frame buffer device\n", info->node, info->fix.id);
return 0;
err:
if (info->screen_base) {
iounmap(info->screen_base);
pci_release_region(pdev, 0);
}
if (par->vid_regs) {
iounmap(par->vid_regs);
pci_release_region(pdev, 3);
}
if (par->dc_regs) {
iounmap(par->dc_regs);
pci_release_region(pdev, 2);
}
if (par->gp_regs) {
iounmap(par->gp_regs);
pci_release_region(pdev, 1);
}
if (info) {
fb_dealloc_cmap(&info->cmap);
framebuffer_release(info);
}
return ret;
}
static void __devexit gxfb_remove(struct pci_dev *pdev)
{
struct fb_info *info = pci_get_drvdata(pdev);
struct gxfb_par *par = info->par;
unregister_framebuffer(info);
iounmap((void __iomem *)info->screen_base);
pci_release_region(pdev, 0);
iounmap(par->vid_regs);
pci_release_region(pdev, 3);
iounmap(par->dc_regs);
pci_release_region(pdev, 2);
iounmap(par->gp_regs);
pci_release_region(pdev, 1);
fb_dealloc_cmap(&info->cmap);
pci_set_drvdata(pdev, NULL);
framebuffer_release(info);
}
static struct pci_device_id gxfb_id_table[] = {
{ PCI_DEVICE(PCI_VENDOR_ID_NS, PCI_DEVICE_ID_NS_GX_VIDEO) },
{ 0, }
};
MODULE_DEVICE_TABLE(pci, gxfb_id_table);
static struct pci_driver gxfb_driver = {
.name = "gxfb",
.id_table = gxfb_id_table,
.probe = gxfb_probe,
.remove = gxfb_remove,
#ifdef CONFIG_PM
.suspend = gxfb_suspend,
.resume = gxfb_resume,
#endif
};
#ifndef MODULE
static int __init gxfb_setup(char *options)
{
char *opt;
if (!options || !*options)
return 0;
while ((opt = strsep(&options, ",")) != NULL) {
if (!*opt)
continue;
mode_option = opt;
}
return 0;
}
#endif
static int __init gxfb_init(void)
{
#ifndef MODULE
char *option = NULL;
if (fb_get_options("gxfb", &option))
return -ENODEV;
gxfb_setup(option);
#endif
return pci_register_driver(&gxfb_driver);
}
static void __exit gxfb_cleanup(void)
{
pci_unregister_driver(&gxfb_driver);
}
module_init(gxfb_init);
module_exit(gxfb_cleanup);
module_param(mode_option, charp, 0);
MODULE_PARM_DESC(mode_option, "video mode (<x>x<y>[-<bpp>][@<refr>])");
module_param(vram, int, 0);
MODULE_PARM_DESC(vram, "video memory size");
module_param(vt_switch, int, 0);
MODULE_PARM_DESC(vt_switch, "enable VT switch during suspend/resume");
MODULE_DESCRIPTION("Framebuffer driver for the AMD Geode GX");
MODULE_LICENSE("GPL");
| gpl-2.0 |
underdarkonsole/huawei_vision_kernel_JB | arch/sh/kernel/cpu/sh2/setup-sh7619.c | 901 | 5248 | /*
* SH7619 Setup
*
* Copyright (C) 2006 Yoshinori Sato
* Copyright (C) 2009 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/platform_device.h>
#include <linux/init.h>
#include <linux/serial.h>
#include <linux/serial_sci.h>
#include <linux/sh_timer.h>
#include <linux/io.h>
enum {
UNUSED = 0,
/* interrupt sources */
IRQ0, IRQ1, IRQ2, IRQ3, IRQ4, IRQ5, IRQ6, IRQ7,
WDT, EDMAC, CMT0, CMT1,
SCIF0, SCIF1, SCIF2,
HIF_HIFI, HIF_HIFBI,
DMAC0, DMAC1, DMAC2, DMAC3,
SIOF,
};
static struct intc_vect vectors[] __initdata = {
INTC_IRQ(IRQ0, 64), INTC_IRQ(IRQ1, 65),
INTC_IRQ(IRQ2, 66), INTC_IRQ(IRQ3, 67),
INTC_IRQ(IRQ4, 80), INTC_IRQ(IRQ5, 81),
INTC_IRQ(IRQ6, 82), INTC_IRQ(IRQ7, 83),
INTC_IRQ(WDT, 84), INTC_IRQ(EDMAC, 85),
INTC_IRQ(CMT0, 86), INTC_IRQ(CMT1, 87),
INTC_IRQ(SCIF0, 88), INTC_IRQ(SCIF0, 89),
INTC_IRQ(SCIF0, 90), INTC_IRQ(SCIF0, 91),
INTC_IRQ(SCIF1, 92), INTC_IRQ(SCIF1, 93),
INTC_IRQ(SCIF1, 94), INTC_IRQ(SCIF1, 95),
INTC_IRQ(SCIF2, 96), INTC_IRQ(SCIF2, 97),
INTC_IRQ(SCIF2, 98), INTC_IRQ(SCIF2, 99),
INTC_IRQ(HIF_HIFI, 100), INTC_IRQ(HIF_HIFBI, 101),
INTC_IRQ(DMAC0, 104), INTC_IRQ(DMAC1, 105),
INTC_IRQ(DMAC2, 106), INTC_IRQ(DMAC3, 107),
INTC_IRQ(SIOF, 108),
};
static struct intc_prio_reg prio_registers[] __initdata = {
{ 0xf8140006, 0, 16, 4, /* IPRA */ { IRQ0, IRQ1, IRQ2, IRQ3 } },
{ 0xf8140008, 0, 16, 4, /* IPRB */ { IRQ4, IRQ5, IRQ6, IRQ7 } },
{ 0xf8080000, 0, 16, 4, /* IPRC */ { WDT, EDMAC, CMT0, CMT1 } },
{ 0xf8080002, 0, 16, 4, /* IPRD */ { SCIF0, SCIF1, SCIF2 } },
{ 0xf8080004, 0, 16, 4, /* IPRE */ { HIF_HIFI, HIF_HIFBI } },
{ 0xf8080006, 0, 16, 4, /* IPRF */ { DMAC0, DMAC1, DMAC2, DMAC3 } },
{ 0xf8080008, 0, 16, 4, /* IPRG */ { SIOF } },
};
static DECLARE_INTC_DESC(intc_desc, "sh7619", vectors, NULL,
NULL, prio_registers, NULL);
static struct plat_sci_port scif0_platform_data = {
.mapbase = 0xf8400000,
.flags = UPF_BOOT_AUTOCONF,
.type = PORT_SCIF,
.irqs = { 88, 88, 88, 88 },
};
static struct platform_device scif0_device = {
.name = "sh-sci",
.id = 0,
.dev = {
.platform_data = &scif0_platform_data,
},
};
static struct plat_sci_port scif1_platform_data = {
.mapbase = 0xf8410000,
.flags = UPF_BOOT_AUTOCONF,
.type = PORT_SCIF,
.irqs = { 92, 92, 92, 92 },
};
static struct platform_device scif1_device = {
.name = "sh-sci",
.id = 1,
.dev = {
.platform_data = &scif1_platform_data,
},
};
static struct plat_sci_port scif2_platform_data = {
.mapbase = 0xf8420000,
.flags = UPF_BOOT_AUTOCONF,
.type = PORT_SCIF,
.irqs = { 96, 96, 96, 96 },
};
static struct platform_device scif2_device = {
.name = "sh-sci",
.id = 2,
.dev = {
.platform_data = &scif2_platform_data,
},
};
static struct resource eth_resources[] = {
[0] = {
.start = 0xfb000000,
.end = 0xfb0001c8,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 85,
.end = 85,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device eth_device = {
.name = "sh-eth",
.id = -1,
.dev = {
.platform_data = (void *)1,
},
.num_resources = ARRAY_SIZE(eth_resources),
.resource = eth_resources,
};
static struct sh_timer_config cmt0_platform_data = {
.channel_offset = 0x02,
.timer_bit = 0,
.clockevent_rating = 125,
.clocksource_rating = 0, /* disabled due to code generation issues */
};
static struct resource cmt0_resources[] = {
[0] = {
.start = 0xf84a0072,
.end = 0xf84a0077,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 86,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device cmt0_device = {
.name = "sh_cmt",
.id = 0,
.dev = {
.platform_data = &cmt0_platform_data,
},
.resource = cmt0_resources,
.num_resources = ARRAY_SIZE(cmt0_resources),
};
static struct sh_timer_config cmt1_platform_data = {
.channel_offset = 0x08,
.timer_bit = 1,
.clockevent_rating = 125,
.clocksource_rating = 0, /* disabled due to code generation issues */
};
static struct resource cmt1_resources[] = {
[0] = {
.start = 0xf84a0078,
.end = 0xf84a007d,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 87,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device cmt1_device = {
.name = "sh_cmt",
.id = 1,
.dev = {
.platform_data = &cmt1_platform_data,
},
.resource = cmt1_resources,
.num_resources = ARRAY_SIZE(cmt1_resources),
};
static struct platform_device *sh7619_devices[] __initdata = {
&scif0_device,
&scif1_device,
&scif2_device,
ð_device,
&cmt0_device,
&cmt1_device,
};
static int __init sh7619_devices_setup(void)
{
return platform_add_devices(sh7619_devices,
ARRAY_SIZE(sh7619_devices));
}
arch_initcall(sh7619_devices_setup);
void __init plat_irq_setup(void)
{
register_intc_controller(&intc_desc);
}
static struct platform_device *sh7619_early_devices[] __initdata = {
&scif0_device,
&scif1_device,
&scif2_device,
&cmt0_device,
&cmt1_device,
};
#define STBCR3 0xf80a0000
void __init plat_early_device_setup(void)
{
/* enable CMT clock */
__raw_writeb(__raw_readb(STBCR3) & ~0x10, STBCR3);
early_platform_add_devices(sh7619_early_devices,
ARRAY_SIZE(sh7619_early_devices));
}
| gpl-2.0 |
djvoleur/V_S6 | arch/mips/kernel/proc.c | 1925 | 4181 | /*
* Copyright (C) 1995, 1996, 2001 Ralf Baechle
* Copyright (C) 2001, 2004 MIPS Technologies, Inc.
* Copyright (C) 2004 Maciej W. Rozycki
*/
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/seq_file.h>
#include <asm/bootinfo.h>
#include <asm/cpu.h>
#include <asm/cpu-features.h>
#include <asm/idle.h>
#include <asm/mipsregs.h>
#include <asm/processor.h>
#include <asm/prom.h>
unsigned int vced_count, vcei_count;
static int show_cpuinfo(struct seq_file *m, void *v)
{
unsigned long n = (unsigned long) v - 1;
unsigned int version = cpu_data[n].processor_id;
unsigned int fp_vers = cpu_data[n].fpu_id;
char fmt [64];
int i;
#ifdef CONFIG_SMP
if (!cpu_online(n))
return 0;
#endif
/*
* For the first processor also print the system type
*/
if (n == 0) {
seq_printf(m, "system type\t\t: %s\n", get_system_type());
if (mips_get_machine_name())
seq_printf(m, "machine\t\t\t: %s\n",
mips_get_machine_name());
}
seq_printf(m, "processor\t\t: %ld\n", n);
sprintf(fmt, "cpu model\t\t: %%s V%%d.%%d%s\n",
cpu_data[n].options & MIPS_CPU_FPU ? " FPU V%d.%d" : "");
seq_printf(m, fmt, __cpu_name[n],
(version >> 4) & 0x0f, version & 0x0f,
(fp_vers >> 4) & 0x0f, fp_vers & 0x0f);
seq_printf(m, "BogoMIPS\t\t: %u.%02u\n",
cpu_data[n].udelay_val / (500000/HZ),
(cpu_data[n].udelay_val / (5000/HZ)) % 100);
seq_printf(m, "wait instruction\t: %s\n", cpu_wait ? "yes" : "no");
seq_printf(m, "microsecond timers\t: %s\n",
cpu_has_counter ? "yes" : "no");
seq_printf(m, "tlb_entries\t\t: %d\n", cpu_data[n].tlbsize);
seq_printf(m, "extra interrupt vector\t: %s\n",
cpu_has_divec ? "yes" : "no");
seq_printf(m, "hardware watchpoint\t: %s",
cpu_has_watch ? "yes, " : "no\n");
if (cpu_has_watch) {
seq_printf(m, "count: %d, address/irw mask: [",
cpu_data[n].watch_reg_count);
for (i = 0; i < cpu_data[n].watch_reg_count; i++)
seq_printf(m, "%s0x%04x", i ? ", " : "" ,
cpu_data[n].watch_reg_masks[i]);
seq_printf(m, "]\n");
}
if (cpu_has_mips_r) {
seq_printf(m, "isa\t\t\t:");
if (cpu_has_mips_1)
seq_printf(m, "%s", " mips1");
if (cpu_has_mips_2)
seq_printf(m, "%s", " mips2");
if (cpu_has_mips_3)
seq_printf(m, "%s", " mips3");
if (cpu_has_mips_4)
seq_printf(m, "%s", " mips4");
if (cpu_has_mips_5)
seq_printf(m, "%s", " mips5");
if (cpu_has_mips32r1)
seq_printf(m, "%s", " mips32r1");
if (cpu_has_mips32r2)
seq_printf(m, "%s", " mips32r2");
if (cpu_has_mips64r1)
seq_printf(m, "%s", " mips64r1");
if (cpu_has_mips64r2)
seq_printf(m, "%s", " mips64r2");
seq_printf(m, "\n");
}
seq_printf(m, "ASEs implemented\t:");
if (cpu_has_mips16) seq_printf(m, "%s", " mips16");
if (cpu_has_mdmx) seq_printf(m, "%s", " mdmx");
if (cpu_has_mips3d) seq_printf(m, "%s", " mips3d");
if (cpu_has_smartmips) seq_printf(m, "%s", " smartmips");
if (cpu_has_dsp) seq_printf(m, "%s", " dsp");
if (cpu_has_dsp2) seq_printf(m, "%s", " dsp2");
if (cpu_has_mipsmt) seq_printf(m, "%s", " mt");
if (cpu_has_mmips) seq_printf(m, "%s", " micromips");
if (cpu_has_vz) seq_printf(m, "%s", " vz");
seq_printf(m, "\n");
if (cpu_has_mmips) {
seq_printf(m, "micromips kernel\t: %s\n",
(read_c0_config3() & MIPS_CONF3_ISA_OE) ? "yes" : "no");
}
seq_printf(m, "shadow register sets\t: %d\n",
cpu_data[n].srsets);
seq_printf(m, "kscratch registers\t: %d\n",
hweight8(cpu_data[n].kscratch_mask));
seq_printf(m, "core\t\t\t: %d\n", cpu_data[n].core);
sprintf(fmt, "VCE%%c exceptions\t\t: %s\n",
cpu_has_vce ? "%u" : "not available");
seq_printf(m, fmt, 'D', vced_count);
seq_printf(m, fmt, 'I', vcei_count);
seq_printf(m, "\n");
return 0;
}
static void *c_start(struct seq_file *m, loff_t *pos)
{
unsigned long i = *pos;
return i < NR_CPUS ? (void *) (i + 1) : 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,
};
| gpl-2.0 |
SlothMellow/android_kernel_moto_shamu | arch/mips/kernel/proc.c | 1925 | 4181 | /*
* Copyright (C) 1995, 1996, 2001 Ralf Baechle
* Copyright (C) 2001, 2004 MIPS Technologies, Inc.
* Copyright (C) 2004 Maciej W. Rozycki
*/
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/seq_file.h>
#include <asm/bootinfo.h>
#include <asm/cpu.h>
#include <asm/cpu-features.h>
#include <asm/idle.h>
#include <asm/mipsregs.h>
#include <asm/processor.h>
#include <asm/prom.h>
unsigned int vced_count, vcei_count;
static int show_cpuinfo(struct seq_file *m, void *v)
{
unsigned long n = (unsigned long) v - 1;
unsigned int version = cpu_data[n].processor_id;
unsigned int fp_vers = cpu_data[n].fpu_id;
char fmt [64];
int i;
#ifdef CONFIG_SMP
if (!cpu_online(n))
return 0;
#endif
/*
* For the first processor also print the system type
*/
if (n == 0) {
seq_printf(m, "system type\t\t: %s\n", get_system_type());
if (mips_get_machine_name())
seq_printf(m, "machine\t\t\t: %s\n",
mips_get_machine_name());
}
seq_printf(m, "processor\t\t: %ld\n", n);
sprintf(fmt, "cpu model\t\t: %%s V%%d.%%d%s\n",
cpu_data[n].options & MIPS_CPU_FPU ? " FPU V%d.%d" : "");
seq_printf(m, fmt, __cpu_name[n],
(version >> 4) & 0x0f, version & 0x0f,
(fp_vers >> 4) & 0x0f, fp_vers & 0x0f);
seq_printf(m, "BogoMIPS\t\t: %u.%02u\n",
cpu_data[n].udelay_val / (500000/HZ),
(cpu_data[n].udelay_val / (5000/HZ)) % 100);
seq_printf(m, "wait instruction\t: %s\n", cpu_wait ? "yes" : "no");
seq_printf(m, "microsecond timers\t: %s\n",
cpu_has_counter ? "yes" : "no");
seq_printf(m, "tlb_entries\t\t: %d\n", cpu_data[n].tlbsize);
seq_printf(m, "extra interrupt vector\t: %s\n",
cpu_has_divec ? "yes" : "no");
seq_printf(m, "hardware watchpoint\t: %s",
cpu_has_watch ? "yes, " : "no\n");
if (cpu_has_watch) {
seq_printf(m, "count: %d, address/irw mask: [",
cpu_data[n].watch_reg_count);
for (i = 0; i < cpu_data[n].watch_reg_count; i++)
seq_printf(m, "%s0x%04x", i ? ", " : "" ,
cpu_data[n].watch_reg_masks[i]);
seq_printf(m, "]\n");
}
if (cpu_has_mips_r) {
seq_printf(m, "isa\t\t\t:");
if (cpu_has_mips_1)
seq_printf(m, "%s", " mips1");
if (cpu_has_mips_2)
seq_printf(m, "%s", " mips2");
if (cpu_has_mips_3)
seq_printf(m, "%s", " mips3");
if (cpu_has_mips_4)
seq_printf(m, "%s", " mips4");
if (cpu_has_mips_5)
seq_printf(m, "%s", " mips5");
if (cpu_has_mips32r1)
seq_printf(m, "%s", " mips32r1");
if (cpu_has_mips32r2)
seq_printf(m, "%s", " mips32r2");
if (cpu_has_mips64r1)
seq_printf(m, "%s", " mips64r1");
if (cpu_has_mips64r2)
seq_printf(m, "%s", " mips64r2");
seq_printf(m, "\n");
}
seq_printf(m, "ASEs implemented\t:");
if (cpu_has_mips16) seq_printf(m, "%s", " mips16");
if (cpu_has_mdmx) seq_printf(m, "%s", " mdmx");
if (cpu_has_mips3d) seq_printf(m, "%s", " mips3d");
if (cpu_has_smartmips) seq_printf(m, "%s", " smartmips");
if (cpu_has_dsp) seq_printf(m, "%s", " dsp");
if (cpu_has_dsp2) seq_printf(m, "%s", " dsp2");
if (cpu_has_mipsmt) seq_printf(m, "%s", " mt");
if (cpu_has_mmips) seq_printf(m, "%s", " micromips");
if (cpu_has_vz) seq_printf(m, "%s", " vz");
seq_printf(m, "\n");
if (cpu_has_mmips) {
seq_printf(m, "micromips kernel\t: %s\n",
(read_c0_config3() & MIPS_CONF3_ISA_OE) ? "yes" : "no");
}
seq_printf(m, "shadow register sets\t: %d\n",
cpu_data[n].srsets);
seq_printf(m, "kscratch registers\t: %d\n",
hweight8(cpu_data[n].kscratch_mask));
seq_printf(m, "core\t\t\t: %d\n", cpu_data[n].core);
sprintf(fmt, "VCE%%c exceptions\t\t: %s\n",
cpu_has_vce ? "%u" : "not available");
seq_printf(m, fmt, 'D', vced_count);
seq_printf(m, fmt, 'I', vcei_count);
seq_printf(m, "\n");
return 0;
}
static void *c_start(struct seq_file *m, loff_t *pos)
{
unsigned long i = *pos;
return i < NR_CPUS ? (void *) (i + 1) : 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,
};
| gpl-2.0 |
chris41g/android_kernel_samsung_epic4gtouch | sound/isa/sb/sb16.c | 3973 | 20372 | /*
* Driver for SoundBlaster 16/AWE32/AWE64 soundcards
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <asm/dma.h>
#include <linux/init.h>
#include <linux/pnp.h>
#include <linux/err.h>
#include <linux/isa.h>
#include <linux/moduleparam.h>
#include <sound/core.h>
#include <sound/sb.h>
#include <sound/sb16_csp.h>
#include <sound/mpu401.h>
#include <sound/opl3.h>
#include <sound/emu8000.h>
#include <sound/seq_device.h>
#define SNDRV_LEGACY_FIND_FREE_IRQ
#define SNDRV_LEGACY_FIND_FREE_DMA
#include <sound/initval.h>
#ifdef SNDRV_SBAWE
#define PFX "sbawe: "
#else
#define PFX "sb16: "
#endif
MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>");
MODULE_LICENSE("GPL");
#ifndef SNDRV_SBAWE
MODULE_DESCRIPTION("Sound Blaster 16");
MODULE_SUPPORTED_DEVICE("{{Creative Labs,SB 16},"
"{Creative Labs,SB Vibra16S},"
"{Creative Labs,SB Vibra16C},"
"{Creative Labs,SB Vibra16CL},"
"{Creative Labs,SB Vibra16X}}");
#else
MODULE_DESCRIPTION("Sound Blaster AWE");
MODULE_SUPPORTED_DEVICE("{{Creative Labs,SB AWE 32},"
"{Creative Labs,SB AWE 64},"
"{Creative Labs,SB AWE 64 Gold}}");
#endif
#if 0
#define SNDRV_DEBUG_IRQ
#endif
#if defined(SNDRV_SBAWE) && (defined(CONFIG_SND_SEQUENCER) || (defined(MODULE) && defined(CONFIG_SND_SEQUENCER_MODULE)))
#define SNDRV_SBAWE_EMU8000
#endif
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_ISAPNP; /* Enable this card */
#ifdef CONFIG_PNP
static int isapnp[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 1};
#endif
static long port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* 0x220,0x240,0x260,0x280 */
static long mpu_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* 0x330,0x300 */
static long fm_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT;
#ifdef SNDRV_SBAWE_EMU8000
static long awe_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT;
#endif
static int irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* 5,7,9,10 */
static int dma8[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* 0,1,3 */
static int dma16[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* 5,6,7 */
static int mic_agc[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 1};
#ifdef CONFIG_SND_SB16_CSP
static int csp[SNDRV_CARDS];
#endif
#ifdef SNDRV_SBAWE_EMU8000
static int seq_ports[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 4};
#endif
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for SoundBlaster 16 soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for SoundBlaster 16 soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable SoundBlaster 16 soundcard.");
#ifdef CONFIG_PNP
module_param_array(isapnp, bool, NULL, 0444);
MODULE_PARM_DESC(isapnp, "PnP detection for specified soundcard.");
#endif
module_param_array(port, long, NULL, 0444);
MODULE_PARM_DESC(port, "Port # for SB16 driver.");
module_param_array(mpu_port, long, NULL, 0444);
MODULE_PARM_DESC(mpu_port, "MPU-401 port # for SB16 driver.");
module_param_array(fm_port, long, NULL, 0444);
MODULE_PARM_DESC(fm_port, "FM port # for SB16 PnP driver.");
#ifdef SNDRV_SBAWE_EMU8000
module_param_array(awe_port, long, NULL, 0444);
MODULE_PARM_DESC(awe_port, "AWE port # for SB16 PnP driver.");
#endif
module_param_array(irq, int, NULL, 0444);
MODULE_PARM_DESC(irq, "IRQ # for SB16 driver.");
module_param_array(dma8, int, NULL, 0444);
MODULE_PARM_DESC(dma8, "8-bit DMA # for SB16 driver.");
module_param_array(dma16, int, NULL, 0444);
MODULE_PARM_DESC(dma16, "16-bit DMA # for SB16 driver.");
module_param_array(mic_agc, int, NULL, 0444);
MODULE_PARM_DESC(mic_agc, "Mic Auto-Gain-Control switch.");
#ifdef CONFIG_SND_SB16_CSP
module_param_array(csp, int, NULL, 0444);
MODULE_PARM_DESC(csp, "ASP/CSP chip support.");
#endif
#ifdef SNDRV_SBAWE_EMU8000
module_param_array(seq_ports, int, NULL, 0444);
MODULE_PARM_DESC(seq_ports, "Number of sequencer ports for WaveTable synth.");
#endif
#ifdef CONFIG_PNP
static int isa_registered;
static int pnp_registered;
#endif
struct snd_card_sb16 {
struct resource *fm_res; /* used to block FM i/o region for legacy cards */
struct snd_sb *chip;
#ifdef CONFIG_PNP
int dev_no;
struct pnp_dev *dev;
#ifdef SNDRV_SBAWE_EMU8000
struct pnp_dev *devwt;
#endif
#endif
};
#ifdef CONFIG_PNP
static struct pnp_card_device_id snd_sb16_pnpids[] = {
#ifndef SNDRV_SBAWE
/* Sound Blaster 16 PnP */
{ .id = "CTL0024", .devs = { { "CTL0031" } } },
/* Sound Blaster 16 PnP */
{ .id = "CTL0025", .devs = { { "CTL0031" } } },
/* Sound Blaster 16 PnP */
{ .id = "CTL0026", .devs = { { "CTL0031" } } },
/* Sound Blaster 16 PnP */
{ .id = "CTL0027", .devs = { { "CTL0031" } } },
/* Sound Blaster 16 PnP */
{ .id = "CTL0028", .devs = { { "CTL0031" } } },
/* Sound Blaster 16 PnP */
{ .id = "CTL0029", .devs = { { "CTL0031" } } },
/* Sound Blaster 16 PnP */
{ .id = "CTL002a", .devs = { { "CTL0031" } } },
/* Sound Blaster 16 PnP */
/* Note: This card has also a CTL0051:StereoEnhance device!!! */
{ .id = "CTL002b", .devs = { { "CTL0031" } } },
/* Sound Blaster 16 PnP */
{ .id = "CTL002c", .devs = { { "CTL0031" } } },
/* Sound Blaster Vibra16S */
{ .id = "CTL0051", .devs = { { "CTL0001" } } },
/* Sound Blaster Vibra16C */
{ .id = "CTL0070", .devs = { { "CTL0001" } } },
/* Sound Blaster Vibra16CL - added by ctm@ardi.com */
{ .id = "CTL0080", .devs = { { "CTL0041" } } },
/* Sound Blaster 16 'value' PnP. It says model ct4130 on the pcb, */
/* but ct4131 on a sticker on the board.. */
{ .id = "CTL0086", .devs = { { "CTL0041" } } },
/* Sound Blaster Vibra16X */
{ .id = "CTL00f0", .devs = { { "CTL0043" } } },
/* Sound Blaster 16 (Virtual PC 2004) */
{ .id = "tBA03b0", .devs = { {.id="PNPb003" } } },
#else /* SNDRV_SBAWE defined */
/* Sound Blaster AWE 32 PnP */
{ .id = "CTL0035", .devs = { { "CTL0031" }, { "CTL0021" } } },
/* Sound Blaster AWE 32 PnP */
{ .id = "CTL0039", .devs = { { "CTL0031" }, { "CTL0021" } } },
/* Sound Blaster AWE 32 PnP */
{ .id = "CTL0042", .devs = { { "CTL0031" }, { "CTL0021" } } },
/* Sound Blaster AWE 32 PnP */
{ .id = "CTL0043", .devs = { { "CTL0031" }, { "CTL0021" } } },
/* Sound Blaster AWE 32 PnP */
/* Note: This card has also a CTL0051:StereoEnhance device!!! */
{ .id = "CTL0044", .devs = { { "CTL0031" }, { "CTL0021" } } },
/* Sound Blaster AWE 32 PnP */
/* Note: This card has also a CTL0051:StereoEnhance device!!! */
{ .id = "CTL0045", .devs = { { "CTL0031" }, { "CTL0021" } } },
/* Sound Blaster AWE 32 PnP */
{ .id = "CTL0046", .devs = { { "CTL0031" }, { "CTL0021" } } },
/* Sound Blaster AWE 32 PnP */
{ .id = "CTL0047", .devs = { { "CTL0031" }, { "CTL0021" } } },
/* Sound Blaster AWE 32 PnP */
{ .id = "CTL0048", .devs = { { "CTL0031" }, { "CTL0021" } } },
/* Sound Blaster AWE 32 PnP */
{ .id = "CTL0054", .devs = { { "CTL0031" }, { "CTL0021" } } },
/* Sound Blaster AWE 32 PnP */
{ .id = "CTL009a", .devs = { { "CTL0041" }, { "CTL0021" } } },
/* Sound Blaster AWE 32 PnP */
{ .id = "CTL009c", .devs = { { "CTL0041" }, { "CTL0021" } } },
/* Sound Blaster 32 PnP */
{ .id = "CTL009f", .devs = { { "CTL0041" }, { "CTL0021" } } },
/* Sound Blaster AWE 64 PnP */
{ .id = "CTL009d", .devs = { { "CTL0042" }, { "CTL0022" } } },
/* Sound Blaster AWE 64 PnP Gold */
{ .id = "CTL009e", .devs = { { "CTL0044" }, { "CTL0023" } } },
/* Sound Blaster AWE 64 PnP Gold */
{ .id = "CTL00b2", .devs = { { "CTL0044" }, { "CTL0023" } } },
/* Sound Blaster AWE 64 PnP */
{ .id = "CTL00c1", .devs = { { "CTL0042" }, { "CTL0022" } } },
/* Sound Blaster AWE 64 PnP */
{ .id = "CTL00c3", .devs = { { "CTL0045" }, { "CTL0022" } } },
/* Sound Blaster AWE 64 PnP */
{ .id = "CTL00c5", .devs = { { "CTL0045" }, { "CTL0022" } } },
/* Sound Blaster AWE 64 PnP */
{ .id = "CTL00c7", .devs = { { "CTL0045" }, { "CTL0022" } } },
/* Sound Blaster AWE 64 PnP */
{ .id = "CTL00e4", .devs = { { "CTL0045" }, { "CTL0022" } } },
/* Sound Blaster AWE 64 PnP */
{ .id = "CTL00e9", .devs = { { "CTL0045" }, { "CTL0022" } } },
/* Sound Blaster 16 PnP (AWE) */
{ .id = "CTL00ed", .devs = { { "CTL0041" }, { "CTL0070" } } },
/* Generic entries */
{ .id = "CTLXXXX" , .devs = { { "CTL0031" }, { "CTL0021" } } },
{ .id = "CTLXXXX" , .devs = { { "CTL0041" }, { "CTL0021" } } },
{ .id = "CTLXXXX" , .devs = { { "CTL0042" }, { "CTL0022" } } },
{ .id = "CTLXXXX" , .devs = { { "CTL0044" }, { "CTL0023" } } },
{ .id = "CTLXXXX" , .devs = { { "CTL0045" }, { "CTL0022" } } },
#endif /* SNDRV_SBAWE */
{ .id = "", }
};
MODULE_DEVICE_TABLE(pnp_card, snd_sb16_pnpids);
#endif /* CONFIG_PNP */
#ifdef SNDRV_SBAWE_EMU8000
#define DRIVER_NAME "snd-card-sbawe"
#else
#define DRIVER_NAME "snd-card-sb16"
#endif
#ifdef CONFIG_PNP
static int __devinit snd_card_sb16_pnp(int dev, struct snd_card_sb16 *acard,
struct pnp_card_link *card,
const struct pnp_card_device_id *id)
{
struct pnp_dev *pdev;
int err;
acard->dev = pnp_request_card_device(card, id->devs[0].id, NULL);
if (acard->dev == NULL)
return -ENODEV;
#ifdef SNDRV_SBAWE_EMU8000
acard->devwt = pnp_request_card_device(card, id->devs[1].id, acard->dev);
#endif
/* Audio initialization */
pdev = acard->dev;
err = pnp_activate_dev(pdev);
if (err < 0) {
snd_printk(KERN_ERR PFX "AUDIO pnp configure failure\n");
return err;
}
port[dev] = pnp_port_start(pdev, 0);
mpu_port[dev] = pnp_port_start(pdev, 1);
fm_port[dev] = pnp_port_start(pdev, 2);
dma8[dev] = pnp_dma(pdev, 0);
dma16[dev] = pnp_dma(pdev, 1);
irq[dev] = pnp_irq(pdev, 0);
snd_printdd("pnp SB16: port=0x%lx, mpu port=0x%lx, fm port=0x%lx\n",
port[dev], mpu_port[dev], fm_port[dev]);
snd_printdd("pnp SB16: dma1=%i, dma2=%i, irq=%i\n",
dma8[dev], dma16[dev], irq[dev]);
#ifdef SNDRV_SBAWE_EMU8000
/* WaveTable initialization */
pdev = acard->devwt;
if (pdev != NULL) {
err = pnp_activate_dev(pdev);
if (err < 0) {
goto __wt_error;
}
awe_port[dev] = pnp_port_start(pdev, 0);
snd_printdd("pnp SB16: wavetable port=0x%llx\n",
(unsigned long long)pnp_port_start(pdev, 0));
} else {
__wt_error:
if (pdev) {
pnp_release_card_device(pdev);
snd_printk(KERN_ERR PFX "WaveTable pnp configure failure\n");
}
acard->devwt = NULL;
awe_port[dev] = -1;
}
#endif
return 0;
}
#endif /* CONFIG_PNP */
static void snd_sb16_free(struct snd_card *card)
{
struct snd_card_sb16 *acard = card->private_data;
if (acard == NULL)
return;
release_and_free_resource(acard->fm_res);
}
#ifdef CONFIG_PNP
#define is_isapnp_selected(dev) isapnp[dev]
#else
#define is_isapnp_selected(dev) 0
#endif
static int snd_sb16_card_new(int dev, struct snd_card **cardp)
{
struct snd_card *card;
int err;
err = snd_card_create(index[dev], id[dev], THIS_MODULE,
sizeof(struct snd_card_sb16), &card);
if (err < 0)
return err;
card->private_free = snd_sb16_free;
*cardp = card;
return 0;
}
static int __devinit snd_sb16_probe(struct snd_card *card, int dev)
{
int xirq, xdma8, xdma16;
struct snd_sb *chip;
struct snd_card_sb16 *acard = card->private_data;
struct snd_opl3 *opl3;
struct snd_hwdep *synth = NULL;
#ifdef CONFIG_SND_SB16_CSP
struct snd_hwdep *xcsp = NULL;
#endif
unsigned long flags;
int err;
xirq = irq[dev];
xdma8 = dma8[dev];
xdma16 = dma16[dev];
if ((err = snd_sbdsp_create(card,
port[dev],
xirq,
snd_sb16dsp_interrupt,
xdma8,
xdma16,
SB_HW_AUTO,
&chip)) < 0)
return err;
acard->chip = chip;
if (chip->hardware != SB_HW_16) {
snd_printk(KERN_ERR PFX "SB 16 chip was not detected at 0x%lx\n", port[dev]);
return -ENODEV;
}
chip->mpu_port = mpu_port[dev];
if (! is_isapnp_selected(dev) && (err = snd_sb16dsp_configure(chip)) < 0)
return err;
if ((err = snd_sb16dsp_pcm(chip, 0, &chip->pcm)) < 0)
return err;
strcpy(card->driver,
#ifdef SNDRV_SBAWE_EMU8000
awe_port[dev] > 0 ? "SB AWE" :
#endif
"SB16");
strcpy(card->shortname, chip->name);
sprintf(card->longname, "%s at 0x%lx, irq %i, dma ",
chip->name,
chip->port,
xirq);
if (xdma8 >= 0)
sprintf(card->longname + strlen(card->longname), "%d", xdma8);
if (xdma16 >= 0)
sprintf(card->longname + strlen(card->longname), "%s%d",
xdma8 >= 0 ? "&" : "", xdma16);
if (chip->mpu_port > 0 && chip->mpu_port != SNDRV_AUTO_PORT) {
if ((err = snd_mpu401_uart_new(card, 0, MPU401_HW_SB,
chip->mpu_port, 0,
xirq, 0, &chip->rmidi)) < 0)
return err;
chip->rmidi_callback = snd_mpu401_uart_interrupt;
}
#ifdef SNDRV_SBAWE_EMU8000
if (awe_port[dev] == SNDRV_AUTO_PORT)
awe_port[dev] = 0; /* disable */
#endif
if (fm_port[dev] > 0 && fm_port[dev] != SNDRV_AUTO_PORT) {
if (snd_opl3_create(card, fm_port[dev], fm_port[dev] + 2,
OPL3_HW_OPL3,
acard->fm_res != NULL || fm_port[dev] == port[dev],
&opl3) < 0) {
snd_printk(KERN_ERR PFX "no OPL device at 0x%lx-0x%lx\n",
fm_port[dev], fm_port[dev] + 2);
} else {
#ifdef SNDRV_SBAWE_EMU8000
int seqdev = awe_port[dev] > 0 ? 2 : 1;
#else
int seqdev = 1;
#endif
if ((err = snd_opl3_hwdep_new(opl3, 0, seqdev, &synth)) < 0)
return err;
}
}
if ((err = snd_sbmixer_new(chip)) < 0)
return err;
#ifdef CONFIG_SND_SB16_CSP
/* CSP chip on SB16ASP/AWE32 */
if ((chip->hardware == SB_HW_16) && csp[dev]) {
snd_sb_csp_new(chip, synth != NULL ? 1 : 0, &xcsp);
if (xcsp) {
chip->csp = xcsp->private_data;
chip->hardware = SB_HW_16CSP;
} else {
snd_printk(KERN_INFO PFX "warning - CSP chip not detected on soundcard #%i\n", dev + 1);
}
}
#endif
#ifdef SNDRV_SBAWE_EMU8000
if (awe_port[dev] > 0) {
if ((err = snd_emu8000_new(card, 1, awe_port[dev],
seq_ports[dev], NULL)) < 0) {
snd_printk(KERN_ERR PFX "fatal error - EMU-8000 synthesizer not detected at 0x%lx\n", awe_port[dev]);
return err;
}
}
#endif
/* setup Mic AGC */
spin_lock_irqsave(&chip->mixer_lock, flags);
snd_sbmixer_write(chip, SB_DSP4_MIC_AGC,
(snd_sbmixer_read(chip, SB_DSP4_MIC_AGC) & 0x01) |
(mic_agc[dev] ? 0x00 : 0x01));
spin_unlock_irqrestore(&chip->mixer_lock, flags);
if ((err = snd_card_register(card)) < 0)
return err;
return 0;
}
#ifdef CONFIG_PM
static int snd_sb16_suspend(struct snd_card *card, pm_message_t state)
{
struct snd_card_sb16 *acard = card->private_data;
struct snd_sb *chip = acard->chip;
snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
snd_pcm_suspend_all(chip->pcm);
snd_sbmixer_suspend(chip);
return 0;
}
static int snd_sb16_resume(struct snd_card *card)
{
struct snd_card_sb16 *acard = card->private_data;
struct snd_sb *chip = acard->chip;
snd_sbdsp_reset(chip);
snd_sbmixer_resume(chip);
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
#endif
static int __devinit snd_sb16_isa_probe1(int dev, struct device *pdev)
{
struct snd_card_sb16 *acard;
struct snd_card *card;
int err;
err = snd_sb16_card_new(dev, &card);
if (err < 0)
return err;
acard = card->private_data;
/* non-PnP FM port address is hardwired with base port address */
fm_port[dev] = port[dev];
/* block the 0x388 port to avoid PnP conflicts */
acard->fm_res = request_region(0x388, 4, "SoundBlaster FM");
#ifdef SNDRV_SBAWE_EMU8000
/* non-PnP AWE port address is hardwired with base port address */
awe_port[dev] = port[dev] + 0x400;
#endif
snd_card_set_dev(card, pdev);
if ((err = snd_sb16_probe(card, dev)) < 0) {
snd_card_free(card);
return err;
}
dev_set_drvdata(pdev, card);
return 0;
}
static int __devinit snd_sb16_isa_match(struct device *pdev, unsigned int dev)
{
return enable[dev] && !is_isapnp_selected(dev);
}
static int __devinit snd_sb16_isa_probe(struct device *pdev, unsigned int dev)
{
int err;
static int possible_irqs[] = {5, 9, 10, 7, -1};
static int possible_dmas8[] = {1, 3, 0, -1};
static int possible_dmas16[] = {5, 6, 7, -1};
if (irq[dev] == SNDRV_AUTO_IRQ) {
if ((irq[dev] = snd_legacy_find_free_irq(possible_irqs)) < 0) {
snd_printk(KERN_ERR PFX "unable to find a free IRQ\n");
return -EBUSY;
}
}
if (dma8[dev] == SNDRV_AUTO_DMA) {
if ((dma8[dev] = snd_legacy_find_free_dma(possible_dmas8)) < 0) {
snd_printk(KERN_ERR PFX "unable to find a free 8-bit DMA\n");
return -EBUSY;
}
}
if (dma16[dev] == SNDRV_AUTO_DMA) {
if ((dma16[dev] = snd_legacy_find_free_dma(possible_dmas16)) < 0) {
snd_printk(KERN_ERR PFX "unable to find a free 16-bit DMA\n");
return -EBUSY;
}
}
if (port[dev] != SNDRV_AUTO_PORT)
return snd_sb16_isa_probe1(dev, pdev);
else {
static int possible_ports[] = {0x220, 0x240, 0x260, 0x280};
int i;
for (i = 0; i < ARRAY_SIZE(possible_ports); i++) {
port[dev] = possible_ports[i];
err = snd_sb16_isa_probe1(dev, pdev);
if (! err)
return 0;
}
return err;
}
}
static int __devexit snd_sb16_isa_remove(struct device *pdev, unsigned int dev)
{
snd_card_free(dev_get_drvdata(pdev));
dev_set_drvdata(pdev, NULL);
return 0;
}
#ifdef CONFIG_PM
static int snd_sb16_isa_suspend(struct device *dev, unsigned int n,
pm_message_t state)
{
return snd_sb16_suspend(dev_get_drvdata(dev), state);
}
static int snd_sb16_isa_resume(struct device *dev, unsigned int n)
{
return snd_sb16_resume(dev_get_drvdata(dev));
}
#endif
#ifdef SNDRV_SBAWE
#define DEV_NAME "sbawe"
#else
#define DEV_NAME "sb16"
#endif
static struct isa_driver snd_sb16_isa_driver = {
.match = snd_sb16_isa_match,
.probe = snd_sb16_isa_probe,
.remove = __devexit_p(snd_sb16_isa_remove),
#ifdef CONFIG_PM
.suspend = snd_sb16_isa_suspend,
.resume = snd_sb16_isa_resume,
#endif
.driver = {
.name = DEV_NAME
},
};
#ifdef CONFIG_PNP
static int __devinit snd_sb16_pnp_detect(struct pnp_card_link *pcard,
const struct pnp_card_device_id *pid)
{
static int dev;
struct snd_card *card;
int res;
for ( ; dev < SNDRV_CARDS; dev++) {
if (!enable[dev] || !isapnp[dev])
continue;
res = snd_sb16_card_new(dev, &card);
if (res < 0)
return res;
snd_card_set_dev(card, &pcard->card->dev);
if ((res = snd_card_sb16_pnp(dev, card->private_data, pcard, pid)) < 0 ||
(res = snd_sb16_probe(card, dev)) < 0) {
snd_card_free(card);
return res;
}
pnp_set_card_drvdata(pcard, card);
dev++;
return 0;
}
return -ENODEV;
}
static void __devexit snd_sb16_pnp_remove(struct pnp_card_link * pcard)
{
snd_card_free(pnp_get_card_drvdata(pcard));
pnp_set_card_drvdata(pcard, NULL);
}
#ifdef CONFIG_PM
static int snd_sb16_pnp_suspend(struct pnp_card_link *pcard, pm_message_t state)
{
return snd_sb16_suspend(pnp_get_card_drvdata(pcard), state);
}
static int snd_sb16_pnp_resume(struct pnp_card_link *pcard)
{
return snd_sb16_resume(pnp_get_card_drvdata(pcard));
}
#endif
static struct pnp_card_driver sb16_pnpc_driver = {
.flags = PNP_DRIVER_RES_DISABLE,
#ifdef SNDRV_SBAWE
.name = "sbawe",
#else
.name = "sb16",
#endif
.id_table = snd_sb16_pnpids,
.probe = snd_sb16_pnp_detect,
.remove = __devexit_p(snd_sb16_pnp_remove),
#ifdef CONFIG_PM
.suspend = snd_sb16_pnp_suspend,
.resume = snd_sb16_pnp_resume,
#endif
};
#endif /* CONFIG_PNP */
static int __init alsa_card_sb16_init(void)
{
int err;
err = isa_register_driver(&snd_sb16_isa_driver, SNDRV_CARDS);
#ifdef CONFIG_PNP
if (!err)
isa_registered = 1;
err = pnp_register_card_driver(&sb16_pnpc_driver);
if (!err)
pnp_registered = 1;
if (isa_registered)
err = 0;
#endif
return err;
}
static void __exit alsa_card_sb16_exit(void)
{
#ifdef CONFIG_PNP
if (pnp_registered)
pnp_unregister_card_driver(&sb16_pnpc_driver);
if (isa_registered)
#endif
isa_unregister_driver(&snd_sb16_isa_driver);
}
module_init(alsa_card_sb16_init)
module_exit(alsa_card_sb16_exit)
| gpl-2.0 |
vSlipenchuk/ac100hd | sound/isa/gus/interwave.c | 3973 | 27273 | /*
* Driver for AMD InterWave soundcard
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* 1999/07/22 Erik Inge Bolso <knan@mo.himolde.no>
* * mixer group handlers
*
*/
#include <linux/init.h>
#include <linux/err.h>
#include <linux/isa.h>
#include <linux/delay.h>
#include <linux/pnp.h>
#include <linux/moduleparam.h>
#include <asm/dma.h>
#include <sound/core.h>
#include <sound/gus.h>
#include <sound/wss.h>
#ifdef SNDRV_STB
#include <sound/tea6330t.h>
#endif
#define SNDRV_LEGACY_FIND_FREE_IRQ
#define SNDRV_LEGACY_FIND_FREE_DMA
#include <sound/initval.h>
MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>");
MODULE_LICENSE("GPL");
#ifndef SNDRV_STB
MODULE_DESCRIPTION("AMD InterWave");
MODULE_SUPPORTED_DEVICE("{{Gravis,UltraSound Plug & Play},"
"{STB,SoundRage32},"
"{MED,MED3210},"
"{Dynasonix,Dynasonix Pro},"
"{Panasonic,PCA761AW}}");
#else
MODULE_DESCRIPTION("AMD InterWave STB with TEA6330T");
MODULE_SUPPORTED_DEVICE("{{AMD,InterWave STB with TEA6330T}}");
#endif
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_ISAPNP; /* Enable this card */
#ifdef CONFIG_PNP
static int isapnp[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 1};
#endif
static long port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* 0x210,0x220,0x230,0x240,0x250,0x260 */
#ifdef SNDRV_STB
static long port_tc[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* 0x350,0x360,0x370,0x380 */
#endif
static int irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* 2,3,5,9,11,12,15 */
static int dma1[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* 0,1,3,5,6,7 */
static int dma2[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* 0,1,3,5,6,7 */
static int joystick_dac[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 29};
/* 0 to 31, (0.59V-4.52V or 0.389V-2.98V) */
static int midi[SNDRV_CARDS];
static int pcm_channels[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 2};
static int effect[SNDRV_CARDS];
#ifdef SNDRV_STB
#define PFX "interwave-stb: "
#define INTERWAVE_DRIVER "snd_interwave_stb"
#define INTERWAVE_PNP_DRIVER "interwave-stb"
#else
#define PFX "interwave: "
#define INTERWAVE_DRIVER "snd_interwave"
#define INTERWAVE_PNP_DRIVER "interwave"
#endif
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for InterWave soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for InterWave soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable InterWave soundcard.");
#ifdef CONFIG_PNP
module_param_array(isapnp, bool, NULL, 0444);
MODULE_PARM_DESC(isapnp, "ISA PnP detection for specified soundcard.");
#endif
module_param_array(port, long, NULL, 0444);
MODULE_PARM_DESC(port, "Port # for InterWave driver.");
#ifdef SNDRV_STB
module_param_array(port_tc, long, NULL, 0444);
MODULE_PARM_DESC(port_tc, "Tone control (TEA6330T - i2c bus) port # for InterWave driver.");
#endif
module_param_array(irq, int, NULL, 0444);
MODULE_PARM_DESC(irq, "IRQ # for InterWave driver.");
module_param_array(dma1, int, NULL, 0444);
MODULE_PARM_DESC(dma1, "DMA1 # for InterWave driver.");
module_param_array(dma2, int, NULL, 0444);
MODULE_PARM_DESC(dma2, "DMA2 # for InterWave driver.");
module_param_array(joystick_dac, int, NULL, 0444);
MODULE_PARM_DESC(joystick_dac, "Joystick DAC level 0.59V-4.52V or 0.389V-2.98V for InterWave driver.");
module_param_array(midi, int, NULL, 0444);
MODULE_PARM_DESC(midi, "MIDI UART enable for InterWave driver.");
module_param_array(pcm_channels, int, NULL, 0444);
MODULE_PARM_DESC(pcm_channels, "Reserved PCM channels for InterWave driver.");
module_param_array(effect, int, NULL, 0444);
MODULE_PARM_DESC(effect, "Effects enable for InterWave driver.");
struct snd_interwave {
int irq;
struct snd_card *card;
struct snd_gus_card *gus;
struct snd_wss *wss;
#ifdef SNDRV_STB
struct resource *i2c_res;
#endif
unsigned short gus_status_reg;
unsigned short pcm_status_reg;
#ifdef CONFIG_PNP
struct pnp_dev *dev;
#ifdef SNDRV_STB
struct pnp_dev *devtc;
#endif
#endif
};
#ifdef CONFIG_PNP
static int isa_registered;
static int pnp_registered;
static struct pnp_card_device_id snd_interwave_pnpids[] = {
#ifndef SNDRV_STB
/* Gravis UltraSound Plug & Play */
{ .id = "GRV0001", .devs = { { .id = "GRV0000" } } },
/* STB SoundRage32 */
{ .id = "STB011a", .devs = { { .id = "STB0010" } } },
/* MED3210 */
{ .id = "DXP3201", .devs = { { .id = "DXP0010" } } },
/* Dynasonic Pro */
/* This device also have CDC1117:DynaSonix Pro Audio Effects Processor */
{ .id = "CDC1111", .devs = { { .id = "CDC1112" } } },
/* Panasonic PCA761AW Audio Card */
{ .id = "ADV55ff", .devs = { { .id = "ADV0010" } } },
/* InterWave STB without TEA6330T */
{ .id = "ADV550a", .devs = { { .id = "ADV0010" } } },
#else
/* InterWave STB with TEA6330T */
{ .id = "ADV550a", .devs = { { .id = "ADV0010" }, { .id = "ADV0015" } } },
#endif
{ .id = "" }
};
MODULE_DEVICE_TABLE(pnp_card, snd_interwave_pnpids);
#endif /* CONFIG_PNP */
#ifdef SNDRV_STB
static void snd_interwave_i2c_setlines(struct snd_i2c_bus *bus, int ctrl, int data)
{
unsigned long port = bus->private_value;
#if 0
printk(KERN_DEBUG "i2c_setlines - 0x%lx <- %i,%i\n", port, ctrl, data);
#endif
outb((data << 1) | ctrl, port);
udelay(10);
}
static int snd_interwave_i2c_getclockline(struct snd_i2c_bus *bus)
{
unsigned long port = bus->private_value;
unsigned char res;
res = inb(port) & 1;
#if 0
printk(KERN_DEBUG "i2c_getclockline - 0x%lx -> %i\n", port, res);
#endif
return res;
}
static int snd_interwave_i2c_getdataline(struct snd_i2c_bus *bus, int ack)
{
unsigned long port = bus->private_value;
unsigned char res;
if (ack)
udelay(10);
res = (inb(port) & 2) >> 1;
#if 0
printk(KERN_DEBUG "i2c_getdataline - 0x%lx -> %i\n", port, res);
#endif
return res;
}
static struct snd_i2c_bit_ops snd_interwave_i2c_bit_ops = {
.setlines = snd_interwave_i2c_setlines,
.getclock = snd_interwave_i2c_getclockline,
.getdata = snd_interwave_i2c_getdataline,
};
static int __devinit snd_interwave_detect_stb(struct snd_interwave *iwcard,
struct snd_gus_card * gus, int dev,
struct snd_i2c_bus **rbus)
{
unsigned long port;
struct snd_i2c_bus *bus;
struct snd_card *card = iwcard->card;
char name[32];
int err;
*rbus = NULL;
port = port_tc[dev];
if (port == SNDRV_AUTO_PORT) {
port = 0x350;
if (gus->gf1.port == 0x250) {
port = 0x360;
}
while (port <= 0x380) {
if ((iwcard->i2c_res = request_region(port, 1, "InterWave (I2C bus)")) != NULL)
break;
port += 0x10;
}
} else {
iwcard->i2c_res = request_region(port, 1, "InterWave (I2C bus)");
}
if (iwcard->i2c_res == NULL) {
snd_printk(KERN_ERR "interwave: can't grab i2c bus port\n");
return -ENODEV;
}
sprintf(name, "InterWave-%i", card->number);
if ((err = snd_i2c_bus_create(card, name, NULL, &bus)) < 0)
return err;
bus->private_value = port;
bus->hw_ops.bit = &snd_interwave_i2c_bit_ops;
if ((err = snd_tea6330t_detect(bus, 0)) < 0)
return err;
*rbus = bus;
return 0;
}
#endif
static int __devinit snd_interwave_detect(struct snd_interwave *iwcard,
struct snd_gus_card * gus,
int dev
#ifdef SNDRV_STB
, struct snd_i2c_bus **rbus
#endif
)
{
unsigned long flags;
unsigned char rev1, rev2;
int d;
snd_gf1_i_write8(gus, SNDRV_GF1_GB_RESET, 0); /* reset GF1 */
if (((d = snd_gf1_i_look8(gus, SNDRV_GF1_GB_RESET)) & 0x07) != 0) {
snd_printdd("[0x%lx] check 1 failed - 0x%x\n", gus->gf1.port, d);
return -ENODEV;
}
udelay(160);
snd_gf1_i_write8(gus, SNDRV_GF1_GB_RESET, 1); /* release reset */
udelay(160);
if (((d = snd_gf1_i_look8(gus, SNDRV_GF1_GB_RESET)) & 0x07) != 1) {
snd_printdd("[0x%lx] check 2 failed - 0x%x\n", gus->gf1.port, d);
return -ENODEV;
}
spin_lock_irqsave(&gus->reg_lock, flags);
rev1 = snd_gf1_look8(gus, SNDRV_GF1_GB_VERSION_NUMBER);
snd_gf1_write8(gus, SNDRV_GF1_GB_VERSION_NUMBER, ~rev1);
rev2 = snd_gf1_look8(gus, SNDRV_GF1_GB_VERSION_NUMBER);
snd_gf1_write8(gus, SNDRV_GF1_GB_VERSION_NUMBER, rev1);
spin_unlock_irqrestore(&gus->reg_lock, flags);
snd_printdd("[0x%lx] InterWave check - rev1=0x%x, rev2=0x%x\n", gus->gf1.port, rev1, rev2);
if ((rev1 & 0xf0) == (rev2 & 0xf0) &&
(rev1 & 0x0f) != (rev2 & 0x0f)) {
snd_printdd("[0x%lx] InterWave check - passed\n", gus->gf1.port);
gus->interwave = 1;
strcpy(gus->card->shortname, "AMD InterWave");
gus->revision = rev1 >> 4;
#ifndef SNDRV_STB
return 0; /* ok.. We have an InterWave board */
#else
return snd_interwave_detect_stb(iwcard, gus, dev, rbus);
#endif
}
snd_printdd("[0x%lx] InterWave check - failed\n", gus->gf1.port);
return -ENODEV;
}
static irqreturn_t snd_interwave_interrupt(int irq, void *dev_id)
{
struct snd_interwave *iwcard = dev_id;
int loop, max = 5;
int handled = 0;
do {
loop = 0;
if (inb(iwcard->gus_status_reg)) {
handled = 1;
snd_gus_interrupt(irq, iwcard->gus);
loop++;
}
if (inb(iwcard->pcm_status_reg) & 0x01) { /* IRQ bit is set? */
handled = 1;
snd_wss_interrupt(irq, iwcard->wss);
loop++;
}
} while (loop && --max > 0);
return IRQ_RETVAL(handled);
}
static void __devinit snd_interwave_reset(struct snd_gus_card * gus)
{
snd_gf1_write8(gus, SNDRV_GF1_GB_RESET, 0x00);
udelay(160);
snd_gf1_write8(gus, SNDRV_GF1_GB_RESET, 0x01);
udelay(160);
}
static void __devinit snd_interwave_bank_sizes(struct snd_gus_card * gus, int *sizes)
{
unsigned int idx;
unsigned int local;
unsigned char d;
for (idx = 0; idx < 4; idx++) {
sizes[idx] = 0;
d = 0x55;
for (local = idx << 22;
local < (idx << 22) + 0x400000;
local += 0x40000, d++) {
snd_gf1_poke(gus, local, d);
snd_gf1_poke(gus, local + 1, d + 1);
#if 0
printk(KERN_DEBUG "d = 0x%x, local = 0x%x, "
"local + 1 = 0x%x, idx << 22 = 0x%x\n",
d,
snd_gf1_peek(gus, local),
snd_gf1_peek(gus, local + 1),
snd_gf1_peek(gus, idx << 22));
#endif
if (snd_gf1_peek(gus, local) != d ||
snd_gf1_peek(gus, local + 1) != d + 1 ||
snd_gf1_peek(gus, idx << 22) != 0x55)
break;
sizes[idx]++;
}
}
#if 0
printk(KERN_DEBUG "sizes: %i %i %i %i\n",
sizes[0], sizes[1], sizes[2], sizes[3]);
#endif
}
struct rom_hdr {
/* 000 */ unsigned char iwave[8];
/* 008 */ unsigned char rom_hdr_revision;
/* 009 */ unsigned char series_number;
/* 010 */ unsigned char series_name[16];
/* 026 */ unsigned char date[10];
/* 036 */ unsigned short vendor_revision_major;
/* 038 */ unsigned short vendor_revision_minor;
/* 040 */ unsigned int rom_size;
/* 044 */ unsigned char copyright[128];
/* 172 */ unsigned char vendor_name[64];
/* 236 */ unsigned char rom_description[128];
/* 364 */ unsigned char pad[147];
/* 511 */ unsigned char csum;
};
static void __devinit snd_interwave_detect_memory(struct snd_gus_card * gus)
{
static unsigned int lmc[13] =
{
0x00000001, 0x00000101, 0x01010101, 0x00000401,
0x04040401, 0x00040101, 0x04040101, 0x00000004,
0x00000404, 0x04040404, 0x00000010, 0x00001010,
0x10101010
};
int bank_pos, pages;
unsigned int i, lmct;
int psizes[4];
unsigned char iwave[8];
unsigned char csum;
snd_interwave_reset(gus);
snd_gf1_write8(gus, SNDRV_GF1_GB_GLOBAL_MODE, snd_gf1_read8(gus, SNDRV_GF1_GB_GLOBAL_MODE) | 0x01); /* enhanced mode */
snd_gf1_write8(gus, SNDRV_GF1_GB_MEMORY_CONTROL, 0x01); /* DRAM I/O cycles selected */
snd_gf1_write16(gus, SNDRV_GF1_GW_MEMORY_CONFIG, (snd_gf1_look16(gus, SNDRV_GF1_GW_MEMORY_CONFIG) & 0xff10) | 0x004c);
/* ok.. simple test of memory size */
pages = 0;
snd_gf1_poke(gus, 0, 0x55);
snd_gf1_poke(gus, 1, 0xaa);
#if 1
if (snd_gf1_peek(gus, 0) == 0x55 && snd_gf1_peek(gus, 1) == 0xaa)
#else
if (0) /* ok.. for testing of 0k RAM */
#endif
{
snd_interwave_bank_sizes(gus, psizes);
lmct = (psizes[3] << 24) | (psizes[2] << 16) |
(psizes[1] << 8) | psizes[0];
#if 0
printk(KERN_DEBUG "lmct = 0x%08x\n", lmct);
#endif
for (i = 0; i < ARRAY_SIZE(lmc); i++)
if (lmct == lmc[i]) {
#if 0
printk(KERN_DEBUG "found !!! %i\n", i);
#endif
snd_gf1_write16(gus, SNDRV_GF1_GW_MEMORY_CONFIG, (snd_gf1_look16(gus, SNDRV_GF1_GW_MEMORY_CONFIG) & 0xfff0) | i);
snd_interwave_bank_sizes(gus, psizes);
break;
}
if (i >= ARRAY_SIZE(lmc) && !gus->gf1.enh_mode)
snd_gf1_write16(gus, SNDRV_GF1_GW_MEMORY_CONFIG, (snd_gf1_look16(gus, SNDRV_GF1_GW_MEMORY_CONFIG) & 0xfff0) | 2);
for (i = 0; i < 4; i++) {
gus->gf1.mem_alloc.banks_8[i].address =
gus->gf1.mem_alloc.banks_16[i].address = i << 22;
gus->gf1.mem_alloc.banks_8[i].size =
gus->gf1.mem_alloc.banks_16[i].size = psizes[i] << 18;
pages += psizes[i];
}
}
pages <<= 18;
gus->gf1.memory = pages;
snd_gf1_write8(gus, SNDRV_GF1_GB_MEMORY_CONTROL, 0x03); /* select ROM */
snd_gf1_write16(gus, SNDRV_GF1_GW_MEMORY_CONFIG, (snd_gf1_look16(gus, SNDRV_GF1_GW_MEMORY_CONFIG) & 0xff1f) | (4 << 5));
gus->gf1.rom_banks = 0;
gus->gf1.rom_memory = 0;
for (bank_pos = 0; bank_pos < 16L * 1024L * 1024L; bank_pos += 4L * 1024L * 1024L) {
for (i = 0; i < 8; ++i)
iwave[i] = snd_gf1_peek(gus, bank_pos + i);
#ifdef CONFIG_SND_DEBUG_ROM
printk(KERN_DEBUG "ROM at 0x%06x = %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n", bank_pos,
iwave[0], iwave[1], iwave[2], iwave[3],
iwave[4], iwave[5], iwave[6], iwave[7]);
#endif
if (strncmp(iwave, "INTRWAVE", 8))
continue; /* first check */
csum = 0;
for (i = 0; i < sizeof(struct rom_hdr); i++)
csum += snd_gf1_peek(gus, bank_pos + i);
#ifdef CONFIG_SND_DEBUG_ROM
printk(KERN_DEBUG "ROM checksum = 0x%x (computed)\n", csum);
#endif
if (csum != 0)
continue; /* not valid rom */
gus->gf1.rom_banks++;
gus->gf1.rom_present |= 1 << (bank_pos >> 22);
gus->gf1.rom_memory = snd_gf1_peek(gus, bank_pos + 40) |
(snd_gf1_peek(gus, bank_pos + 41) << 8) |
(snd_gf1_peek(gus, bank_pos + 42) << 16) |
(snd_gf1_peek(gus, bank_pos + 43) << 24);
}
#if 0
if (gus->gf1.rom_memory > 0) {
if (gus->gf1.rom_banks == 1 && gus->gf1.rom_present == 8)
gus->card->type = SNDRV_CARD_TYPE_IW_DYNASONIC;
}
#endif
snd_gf1_write8(gus, SNDRV_GF1_GB_MEMORY_CONTROL, 0x00); /* select RAM */
if (!gus->gf1.enh_mode)
snd_interwave_reset(gus);
}
static void __devinit snd_interwave_init(int dev, struct snd_gus_card * gus)
{
unsigned long flags;
/* ok.. some InterWave specific initialization */
spin_lock_irqsave(&gus->reg_lock, flags);
snd_gf1_write8(gus, SNDRV_GF1_GB_SOUND_BLASTER_CONTROL, 0x00);
snd_gf1_write8(gus, SNDRV_GF1_GB_COMPATIBILITY, 0x1f);
snd_gf1_write8(gus, SNDRV_GF1_GB_DECODE_CONTROL, 0x49);
snd_gf1_write8(gus, SNDRV_GF1_GB_VERSION_NUMBER, 0x11);
snd_gf1_write8(gus, SNDRV_GF1_GB_MPU401_CONTROL_A, 0x00);
snd_gf1_write8(gus, SNDRV_GF1_GB_MPU401_CONTROL_B, 0x30);
snd_gf1_write8(gus, SNDRV_GF1_GB_EMULATION_IRQ, 0x00);
spin_unlock_irqrestore(&gus->reg_lock, flags);
gus->equal_irq = 1;
gus->codec_flag = 1;
gus->interwave = 1;
gus->max_flag = 1;
gus->joystick_dac = joystick_dac[dev];
}
static struct snd_kcontrol_new snd_interwave_controls[] = {
WSS_DOUBLE("Master Playback Switch", 0,
CS4231_LINE_LEFT_OUTPUT, CS4231_LINE_RIGHT_OUTPUT, 7, 7, 1, 1),
WSS_DOUBLE("Master Playback Volume", 0,
CS4231_LINE_LEFT_OUTPUT, CS4231_LINE_RIGHT_OUTPUT, 0, 0, 31, 1),
WSS_DOUBLE("Mic Playback Switch", 0,
CS4231_LEFT_MIC_INPUT, CS4231_RIGHT_MIC_INPUT, 7, 7, 1, 1),
WSS_DOUBLE("Mic Playback Volume", 0,
CS4231_LEFT_MIC_INPUT, CS4231_RIGHT_MIC_INPUT, 0, 0, 31, 1)
};
static int __devinit snd_interwave_mixer(struct snd_wss *chip)
{
struct snd_card *card = chip->card;
struct snd_ctl_elem_id id1, id2;
unsigned int idx;
int err;
memset(&id1, 0, sizeof(id1));
memset(&id2, 0, sizeof(id2));
id1.iface = id2.iface = SNDRV_CTL_ELEM_IFACE_MIXER;
#if 0
/* remove mono microphone controls */
strcpy(id1.name, "Mic Playback Switch");
if ((err = snd_ctl_remove_id(card, &id1)) < 0)
return err;
strcpy(id1.name, "Mic Playback Volume");
if ((err = snd_ctl_remove_id(card, &id1)) < 0)
return err;
#endif
/* add new master and mic controls */
for (idx = 0; idx < ARRAY_SIZE(snd_interwave_controls); idx++)
if ((err = snd_ctl_add(card, snd_ctl_new1(&snd_interwave_controls[idx], chip))) < 0)
return err;
snd_wss_out(chip, CS4231_LINE_LEFT_OUTPUT, 0x9f);
snd_wss_out(chip, CS4231_LINE_RIGHT_OUTPUT, 0x9f);
snd_wss_out(chip, CS4231_LEFT_MIC_INPUT, 0x9f);
snd_wss_out(chip, CS4231_RIGHT_MIC_INPUT, 0x9f);
/* reassign AUXA to SYNTHESIZER */
strcpy(id1.name, "Aux Playback Switch");
strcpy(id2.name, "Synth Playback Switch");
if ((err = snd_ctl_rename_id(card, &id1, &id2)) < 0)
return err;
strcpy(id1.name, "Aux Playback Volume");
strcpy(id2.name, "Synth Playback Volume");
if ((err = snd_ctl_rename_id(card, &id1, &id2)) < 0)
return err;
/* reassign AUXB to CD */
strcpy(id1.name, "Aux Playback Switch"); id1.index = 1;
strcpy(id2.name, "CD Playback Switch");
if ((err = snd_ctl_rename_id(card, &id1, &id2)) < 0)
return err;
strcpy(id1.name, "Aux Playback Volume");
strcpy(id2.name, "CD Playback Volume");
if ((err = snd_ctl_rename_id(card, &id1, &id2)) < 0)
return err;
return 0;
}
#ifdef CONFIG_PNP
static int __devinit snd_interwave_pnp(int dev, struct snd_interwave *iwcard,
struct pnp_card_link *card,
const struct pnp_card_device_id *id)
{
struct pnp_dev *pdev;
int err;
iwcard->dev = pnp_request_card_device(card, id->devs[0].id, NULL);
if (iwcard->dev == NULL)
return -EBUSY;
#ifdef SNDRV_STB
iwcard->devtc = pnp_request_card_device(card, id->devs[1].id, NULL);
if (iwcard->devtc == NULL)
return -EBUSY;
#endif
/* Synth & Codec initialization */
pdev = iwcard->dev;
err = pnp_activate_dev(pdev);
if (err < 0) {
snd_printk(KERN_ERR "InterWave PnP configure failure (out of resources?)\n");
return err;
}
if (pnp_port_start(pdev, 0) + 0x100 != pnp_port_start(pdev, 1) ||
pnp_port_start(pdev, 0) + 0x10c != pnp_port_start(pdev, 2)) {
snd_printk(KERN_ERR "PnP configure failure (wrong ports)\n");
return -ENOENT;
}
port[dev] = pnp_port_start(pdev, 0);
dma1[dev] = pnp_dma(pdev, 0);
if (dma2[dev] >= 0)
dma2[dev] = pnp_dma(pdev, 1);
irq[dev] = pnp_irq(pdev, 0);
snd_printdd("isapnp IW: sb port=0x%llx, gf1 port=0x%llx, codec port=0x%llx\n",
(unsigned long long)pnp_port_start(pdev, 0),
(unsigned long long)pnp_port_start(pdev, 1),
(unsigned long long)pnp_port_start(pdev, 2));
snd_printdd("isapnp IW: dma1=%i, dma2=%i, irq=%i\n", dma1[dev], dma2[dev], irq[dev]);
#ifdef SNDRV_STB
/* Tone Control initialization */
pdev = iwcard->devtc;
err = pnp_activate_dev(pdev);
if (err < 0) {
snd_printk(KERN_ERR "InterWave ToneControl PnP configure failure (out of resources?)\n");
return err;
}
port_tc[dev] = pnp_port_start(pdev, 0);
snd_printdd("isapnp IW: tone control port=0x%lx\n", port_tc[dev]);
#endif
return 0;
}
#endif /* CONFIG_PNP */
static void snd_interwave_free(struct snd_card *card)
{
struct snd_interwave *iwcard = card->private_data;
if (iwcard == NULL)
return;
#ifdef SNDRV_STB
release_and_free_resource(iwcard->i2c_res);
#endif
if (iwcard->irq >= 0)
free_irq(iwcard->irq, (void *)iwcard);
}
static int snd_interwave_card_new(int dev, struct snd_card **cardp)
{
struct snd_card *card;
struct snd_interwave *iwcard;
int err;
err = snd_card_create(index[dev], id[dev], THIS_MODULE,
sizeof(struct snd_interwave), &card);
if (err < 0)
return err;
iwcard = card->private_data;
iwcard->card = card;
iwcard->irq = -1;
card->private_free = snd_interwave_free;
*cardp = card;
return 0;
}
static int __devinit snd_interwave_probe(struct snd_card *card, int dev)
{
int xirq, xdma1, xdma2;
struct snd_interwave *iwcard = card->private_data;
struct snd_wss *wss;
struct snd_gus_card *gus;
#ifdef SNDRV_STB
struct snd_i2c_bus *i2c_bus;
#endif
struct snd_pcm *pcm;
char *str;
int err;
xirq = irq[dev];
xdma1 = dma1[dev];
xdma2 = dma2[dev];
if ((err = snd_gus_create(card,
port[dev],
-xirq, xdma1, xdma2,
0, 32,
pcm_channels[dev], effect[dev], &gus)) < 0)
return err;
if ((err = snd_interwave_detect(iwcard, gus, dev
#ifdef SNDRV_STB
, &i2c_bus
#endif
)) < 0)
return err;
iwcard->gus_status_reg = gus->gf1.reg_irqstat;
iwcard->pcm_status_reg = gus->gf1.port + 0x10c + 2;
snd_interwave_init(dev, gus);
snd_interwave_detect_memory(gus);
if ((err = snd_gus_initialize(gus)) < 0)
return err;
if (request_irq(xirq, snd_interwave_interrupt, IRQF_DISABLED,
"InterWave", iwcard)) {
snd_printk(KERN_ERR PFX "unable to grab IRQ %d\n", xirq);
return -EBUSY;
}
iwcard->irq = xirq;
err = snd_wss_create(card,
gus->gf1.port + 0x10c, -1, xirq,
xdma2 < 0 ? xdma1 : xdma2, xdma1,
WSS_HW_INTERWAVE,
WSS_HWSHARE_IRQ |
WSS_HWSHARE_DMA1 |
WSS_HWSHARE_DMA2,
&wss);
if (err < 0)
return err;
err = snd_wss_pcm(wss, 0, &pcm);
if (err < 0)
return err;
sprintf(pcm->name + strlen(pcm->name), " rev %c", gus->revision + 'A');
strcat(pcm->name, " (codec)");
err = snd_wss_timer(wss, 2, NULL);
if (err < 0)
return err;
err = snd_wss_mixer(wss);
if (err < 0)
return err;
if (pcm_channels[dev] > 0) {
err = snd_gf1_pcm_new(gus, 1, 1, NULL);
if (err < 0)
return err;
}
err = snd_interwave_mixer(wss);
if (err < 0)
return err;
#ifdef SNDRV_STB
{
struct snd_ctl_elem_id id1, id2;
memset(&id1, 0, sizeof(id1));
memset(&id2, 0, sizeof(id2));
id1.iface = id2.iface = SNDRV_CTL_ELEM_IFACE_MIXER;
strcpy(id1.name, "Master Playback Switch");
strcpy(id2.name, id1.name);
id2.index = 1;
if ((err = snd_ctl_rename_id(card, &id1, &id2)) < 0)
return err;
strcpy(id1.name, "Master Playback Volume");
strcpy(id2.name, id1.name);
if ((err = snd_ctl_rename_id(card, &id1, &id2)) < 0)
return err;
if ((err = snd_tea6330t_update_mixer(card, i2c_bus, 0, 1)) < 0)
return err;
}
#endif
gus->uart_enable = midi[dev];
if ((err = snd_gf1_rawmidi_new(gus, 0, NULL)) < 0)
return err;
#ifndef SNDRV_STB
str = "AMD InterWave";
if (gus->gf1.rom_banks == 1 && gus->gf1.rom_present == 8)
str = "Dynasonic 3-D";
#else
str = "InterWave STB";
#endif
strcpy(card->driver, str);
strcpy(card->shortname, str);
sprintf(card->longname, "%s at 0x%lx, irq %i, dma %d",
str,
gus->gf1.port,
xirq,
xdma1);
if (xdma2 >= 0)
sprintf(card->longname + strlen(card->longname), "&%d", xdma2);
err = snd_card_register(card);
if (err < 0)
return err;
iwcard->wss = wss;
iwcard->gus = gus;
return 0;
}
static int __devinit snd_interwave_isa_probe1(int dev, struct device *devptr)
{
struct snd_card *card;
int err;
err = snd_interwave_card_new(dev, &card);
if (err < 0)
return err;
snd_card_set_dev(card, devptr);
if ((err = snd_interwave_probe(card, dev)) < 0) {
snd_card_free(card);
return err;
}
dev_set_drvdata(devptr, card);
return 0;
}
static int __devinit snd_interwave_isa_match(struct device *pdev,
unsigned int dev)
{
if (!enable[dev])
return 0;
#ifdef CONFIG_PNP
if (isapnp[dev])
return 0;
#endif
return 1;
}
static int __devinit snd_interwave_isa_probe(struct device *pdev,
unsigned int dev)
{
int err;
static int possible_irqs[] = {5, 11, 12, 9, 7, 15, 3, -1};
static int possible_dmas[] = {0, 1, 3, 5, 6, 7, -1};
if (irq[dev] == SNDRV_AUTO_IRQ) {
if ((irq[dev] = snd_legacy_find_free_irq(possible_irqs)) < 0) {
snd_printk(KERN_ERR PFX "unable to find a free IRQ\n");
return -EBUSY;
}
}
if (dma1[dev] == SNDRV_AUTO_DMA) {
if ((dma1[dev] = snd_legacy_find_free_dma(possible_dmas)) < 0) {
snd_printk(KERN_ERR PFX "unable to find a free DMA1\n");
return -EBUSY;
}
}
if (dma2[dev] == SNDRV_AUTO_DMA) {
if ((dma2[dev] = snd_legacy_find_free_dma(possible_dmas)) < 0) {
snd_printk(KERN_ERR PFX "unable to find a free DMA2\n");
return -EBUSY;
}
}
if (port[dev] != SNDRV_AUTO_PORT)
return snd_interwave_isa_probe1(dev, pdev);
else {
static long possible_ports[] = {0x210, 0x220, 0x230, 0x240, 0x250, 0x260};
int i;
for (i = 0; i < ARRAY_SIZE(possible_ports); i++) {
port[dev] = possible_ports[i];
err = snd_interwave_isa_probe1(dev, pdev);
if (! err)
return 0;
}
return err;
}
}
static int __devexit snd_interwave_isa_remove(struct device *devptr, unsigned int dev)
{
snd_card_free(dev_get_drvdata(devptr));
dev_set_drvdata(devptr, NULL);
return 0;
}
static struct isa_driver snd_interwave_driver = {
.match = snd_interwave_isa_match,
.probe = snd_interwave_isa_probe,
.remove = __devexit_p(snd_interwave_isa_remove),
/* FIXME: suspend,resume */
.driver = {
.name = INTERWAVE_DRIVER
},
};
#ifdef CONFIG_PNP
static int __devinit snd_interwave_pnp_detect(struct pnp_card_link *pcard,
const struct pnp_card_device_id *pid)
{
static int dev;
struct snd_card *card;
int res;
for ( ; dev < SNDRV_CARDS; dev++) {
if (enable[dev] && isapnp[dev])
break;
}
if (dev >= SNDRV_CARDS)
return -ENODEV;
res = snd_interwave_card_new(dev, &card);
if (res < 0)
return res;
if ((res = snd_interwave_pnp(dev, card->private_data, pcard, pid)) < 0) {
snd_card_free(card);
return res;
}
snd_card_set_dev(card, &pcard->card->dev);
if ((res = snd_interwave_probe(card, dev)) < 0) {
snd_card_free(card);
return res;
}
pnp_set_card_drvdata(pcard, card);
dev++;
return 0;
}
static void __devexit snd_interwave_pnp_remove(struct pnp_card_link * pcard)
{
snd_card_free(pnp_get_card_drvdata(pcard));
pnp_set_card_drvdata(pcard, NULL);
}
static struct pnp_card_driver interwave_pnpc_driver = {
.flags = PNP_DRIVER_RES_DISABLE,
.name = INTERWAVE_PNP_DRIVER,
.id_table = snd_interwave_pnpids,
.probe = snd_interwave_pnp_detect,
.remove = __devexit_p(snd_interwave_pnp_remove),
/* FIXME: suspend,resume */
};
#endif /* CONFIG_PNP */
static int __init alsa_card_interwave_init(void)
{
int err;
err = isa_register_driver(&snd_interwave_driver, SNDRV_CARDS);
#ifdef CONFIG_PNP
if (!err)
isa_registered = 1;
err = pnp_register_card_driver(&interwave_pnpc_driver);
if (!err)
pnp_registered = 1;
if (isa_registered)
err = 0;
#endif
return err;
}
static void __exit alsa_card_interwave_exit(void)
{
#ifdef CONFIG_PNP
if (pnp_registered)
pnp_unregister_card_driver(&interwave_pnpc_driver);
if (isa_registered)
#endif
isa_unregister_driver(&snd_interwave_driver);
}
module_init(alsa_card_interwave_init)
module_exit(alsa_card_interwave_exit)
| gpl-2.0 |
CyanogenMod/android_kernel_amazon_hdx-common | arch/openrisc/kernel/traps.c | 4741 | 9749 | /*
* OpenRISC traps.c
*
* Linux architectural port borrowing liberally from similar works of
* others. All original copyrights apply as per the original source
* declaration.
*
* Modifications for the OpenRISC architecture:
* Copyright (C) 2003 Matjaz Breskvar <phoenix@bsemi.com>
* Copyright (C) 2010-2011 Jonas Bonn <jonas@southpole.se>
*
* 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.
*
* Here we handle the break vectors not used by the system call
* mechanism, as well as some general stack/register dumping
* things.
*
*/
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/kmod.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/ptrace.h>
#include <linux/timer.h>
#include <linux/mm.h>
#include <linux/kallsyms.h>
#include <asm/uaccess.h>
#include <asm/segment.h>
#include <asm/io.h>
#include <asm/pgtable.h>
extern char _etext, _stext;
int kstack_depth_to_print = 0x180;
static inline int valid_stack_ptr(struct thread_info *tinfo, void *p)
{
return p > (void *)tinfo && p < (void *)tinfo + THREAD_SIZE - 3;
}
void show_trace(struct task_struct *task, unsigned long *stack)
{
struct thread_info *context;
unsigned long addr;
context = (struct thread_info *)
((unsigned long)stack & (~(THREAD_SIZE - 1)));
while (valid_stack_ptr(context, stack)) {
addr = *stack++;
if (__kernel_text_address(addr)) {
printk(" [<%08lx>]", addr);
print_symbol(" %s", addr);
printk("\n");
}
}
printk(" =======================\n");
}
/* displays a short stack trace */
void show_stack(struct task_struct *task, unsigned long *esp)
{
unsigned long addr, *stack;
int i;
if (esp == NULL)
esp = (unsigned long *)&esp;
stack = esp;
printk("Stack dump [0x%08lx]:\n", (unsigned long)esp);
for (i = 0; i < kstack_depth_to_print; i++) {
if (kstack_end(stack))
break;
if (__get_user(addr, stack)) {
/* This message matches "failing address" marked
s390 in ksymoops, so lines containing it will
not be filtered out by ksymoops. */
printk("Failing address 0x%lx\n", (unsigned long)stack);
break;
}
stack++;
printk("sp + %02d: 0x%08lx\n", i * 4, addr);
}
printk("\n");
show_trace(task, esp);
return;
}
void show_trace_task(struct task_struct *tsk)
{
/*
* TODO: SysRq-T trace dump...
*/
}
/*
* The architecture-independent backtrace generator
*/
void dump_stack(void)
{
unsigned long stack;
show_stack(current, &stack);
}
EXPORT_SYMBOL(dump_stack);
void show_registers(struct pt_regs *regs)
{
int i;
int in_kernel = 1;
unsigned long esp;
esp = (unsigned long)(®s->sp);
if (user_mode(regs))
in_kernel = 0;
printk("CPU #: %d\n"
" PC: %08lx SR: %08lx SP: %08lx\n",
smp_processor_id(), regs->pc, regs->sr, regs->sp);
printk("GPR00: %08lx GPR01: %08lx GPR02: %08lx GPR03: %08lx\n",
0L, regs->gpr[1], regs->gpr[2], regs->gpr[3]);
printk("GPR04: %08lx GPR05: %08lx GPR06: %08lx GPR07: %08lx\n",
regs->gpr[4], regs->gpr[5], regs->gpr[6], regs->gpr[7]);
printk("GPR08: %08lx GPR09: %08lx GPR10: %08lx GPR11: %08lx\n",
regs->gpr[8], regs->gpr[9], regs->gpr[10], regs->gpr[11]);
printk("GPR12: %08lx GPR13: %08lx GPR14: %08lx GPR15: %08lx\n",
regs->gpr[12], regs->gpr[13], regs->gpr[14], regs->gpr[15]);
printk("GPR16: %08lx GPR17: %08lx GPR18: %08lx GPR19: %08lx\n",
regs->gpr[16], regs->gpr[17], regs->gpr[18], regs->gpr[19]);
printk("GPR20: %08lx GPR21: %08lx GPR22: %08lx GPR23: %08lx\n",
regs->gpr[20], regs->gpr[21], regs->gpr[22], regs->gpr[23]);
printk("GPR24: %08lx GPR25: %08lx GPR26: %08lx GPR27: %08lx\n",
regs->gpr[24], regs->gpr[25], regs->gpr[26], regs->gpr[27]);
printk("GPR28: %08lx GPR29: %08lx GPR30: %08lx GPR31: %08lx\n",
regs->gpr[28], regs->gpr[29], regs->gpr[30], regs->gpr[31]);
printk(" RES: %08lx oGPR11: %08lx\n",
regs->gpr[11], regs->orig_gpr11);
printk("Process %s (pid: %d, stackpage=%08lx)\n",
current->comm, current->pid, (unsigned long)current);
/*
* When in-kernel, we also print out the stack and code at the
* time of the fault..
*/
if (in_kernel) {
printk("\nStack: ");
show_stack(NULL, (unsigned long *)esp);
printk("\nCode: ");
if (regs->pc < PAGE_OFFSET)
goto bad;
for (i = -24; i < 24; i++) {
unsigned char c;
if (__get_user(c, &((unsigned char *)regs->pc)[i])) {
bad:
printk(" Bad PC value.");
break;
}
if (i == 0)
printk("(%02x) ", c);
else
printk("%02x ", c);
}
}
printk("\n");
}
void nommu_dump_state(struct pt_regs *regs,
unsigned long ea, unsigned long vector)
{
int i;
unsigned long addr, stack = regs->sp;
printk("\n\r[nommu_dump_state] :: ea %lx, vector %lx\n\r", ea, vector);
printk("CPU #: %d\n"
" PC: %08lx SR: %08lx SP: %08lx\n",
0, regs->pc, regs->sr, regs->sp);
printk("GPR00: %08lx GPR01: %08lx GPR02: %08lx GPR03: %08lx\n",
0L, regs->gpr[1], regs->gpr[2], regs->gpr[3]);
printk("GPR04: %08lx GPR05: %08lx GPR06: %08lx GPR07: %08lx\n",
regs->gpr[4], regs->gpr[5], regs->gpr[6], regs->gpr[7]);
printk("GPR08: %08lx GPR09: %08lx GPR10: %08lx GPR11: %08lx\n",
regs->gpr[8], regs->gpr[9], regs->gpr[10], regs->gpr[11]);
printk("GPR12: %08lx GPR13: %08lx GPR14: %08lx GPR15: %08lx\n",
regs->gpr[12], regs->gpr[13], regs->gpr[14], regs->gpr[15]);
printk("GPR16: %08lx GPR17: %08lx GPR18: %08lx GPR19: %08lx\n",
regs->gpr[16], regs->gpr[17], regs->gpr[18], regs->gpr[19]);
printk("GPR20: %08lx GPR21: %08lx GPR22: %08lx GPR23: %08lx\n",
regs->gpr[20], regs->gpr[21], regs->gpr[22], regs->gpr[23]);
printk("GPR24: %08lx GPR25: %08lx GPR26: %08lx GPR27: %08lx\n",
regs->gpr[24], regs->gpr[25], regs->gpr[26], regs->gpr[27]);
printk("GPR28: %08lx GPR29: %08lx GPR30: %08lx GPR31: %08lx\n",
regs->gpr[28], regs->gpr[29], regs->gpr[30], regs->gpr[31]);
printk(" RES: %08lx oGPR11: %08lx\n",
regs->gpr[11], regs->orig_gpr11);
printk("Process %s (pid: %d, stackpage=%08lx)\n",
((struct task_struct *)(__pa(current)))->comm,
((struct task_struct *)(__pa(current)))->pid,
(unsigned long)current);
printk("\nStack: ");
printk("Stack dump [0x%08lx]:\n", (unsigned long)stack);
for (i = 0; i < kstack_depth_to_print; i++) {
if (((long)stack & (THREAD_SIZE - 1)) == 0)
break;
stack++;
printk("%lx :: sp + %02d: 0x%08lx\n", stack, i * 4,
*((unsigned long *)(__pa(stack))));
}
printk("\n");
printk("Call Trace: ");
i = 1;
while (((long)stack & (THREAD_SIZE - 1)) != 0) {
addr = *((unsigned long *)__pa(stack));
stack++;
if (kernel_text_address(addr)) {
if (i && ((i % 6) == 0))
printk("\n ");
printk(" [<%08lx>]", addr);
i++;
}
}
printk("\n");
printk("\nCode: ");
for (i = -24; i < 24; i++) {
unsigned char c;
c = ((unsigned char *)(__pa(regs->pc)))[i];
if (i == 0)
printk("(%02x) ", c);
else
printk("%02x ", c);
}
printk("\n");
}
/* This is normally the 'Oops' routine */
void die(const char *str, struct pt_regs *regs, long err)
{
console_verbose();
printk("\n%s#: %04lx\n", str, err & 0xffff);
show_registers(regs);
#ifdef CONFIG_JUMP_UPON_UNHANDLED_EXCEPTION
printk("\n\nUNHANDLED_EXCEPTION: entering infinite loop\n");
/* shut down interrupts */
local_irq_disable();
__asm__ __volatile__("l.nop 1");
do {} while (1);
#endif
do_exit(SIGSEGV);
}
/* This is normally the 'Oops' routine */
void die_if_kernel(const char *str, struct pt_regs *regs, long err)
{
if (user_mode(regs))
return;
die(str, regs, err);
}
void unhandled_exception(struct pt_regs *regs, int ea, int vector)
{
printk("Unable to handle exception at EA =0x%x, vector 0x%x",
ea, vector);
die("Oops", regs, 9);
}
void __init trap_init(void)
{
/* Nothing needs to be done */
}
asmlinkage void do_trap(struct pt_regs *regs, unsigned long address)
{
siginfo_t info;
memset(&info, 0, sizeof(info));
info.si_signo = SIGTRAP;
info.si_code = TRAP_TRACE;
info.si_addr = (void *)address;
force_sig_info(SIGTRAP, &info, current);
regs->pc += 4;
}
asmlinkage void do_unaligned_access(struct pt_regs *regs, unsigned long address)
{
siginfo_t info;
if (user_mode(regs)) {
/* Send a SIGSEGV */
info.si_signo = SIGSEGV;
info.si_errno = 0;
/* info.si_code has been set above */
info.si_addr = (void *)address;
force_sig_info(SIGSEGV, &info, current);
} else {
printk("KERNEL: Unaligned Access 0x%.8lx\n", address);
show_registers(regs);
die("Die:", regs, address);
}
}
asmlinkage void do_bus_fault(struct pt_regs *regs, unsigned long address)
{
siginfo_t info;
if (user_mode(regs)) {
/* Send a SIGBUS */
info.si_signo = SIGBUS;
info.si_errno = 0;
info.si_code = BUS_ADRERR;
info.si_addr = (void *)address;
force_sig_info(SIGBUS, &info, current);
} else { /* Kernel mode */
printk("KERNEL: Bus error (SIGBUS) 0x%.8lx\n", address);
show_registers(regs);
die("Die:", regs, address);
}
}
asmlinkage void do_illegal_instruction(struct pt_regs *regs,
unsigned long address)
{
siginfo_t info;
if (user_mode(regs)) {
/* Send a SIGILL */
info.si_signo = SIGILL;
info.si_errno = 0;
info.si_code = ILL_ILLOPC;
info.si_addr = (void *)address;
force_sig_info(SIGBUS, &info, current);
} else { /* Kernel mode */
printk("KERNEL: Illegal instruction (SIGILL) 0x%.8lx\n",
address);
show_registers(regs);
die("Die:", regs, address);
}
}
| gpl-2.0 |
ResurrectionRemix-Devices/android_kernel_lge_msm8974 | drivers/power/ab8500_charger.c | 4741 | 76012 | /*
* Copyright (C) ST-Ericsson SA 2012
*
* Charger driver for AB8500
*
* License Terms: GNU General Public License v2
* Author:
* Johan Palsson <johan.palsson@stericsson.com>
* Karl Komierowski <karl.komierowski@stericsson.com>
* Arun R Murthy <arun.murthy@stericsson.com>
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <linux/power_supply.h>
#include <linux/completion.h>
#include <linux/regulator/consumer.h>
#include <linux/err.h>
#include <linux/workqueue.h>
#include <linux/kobject.h>
#include <linux/mfd/abx500/ab8500.h>
#include <linux/mfd/abx500.h>
#include <linux/mfd/abx500/ab8500-bm.h>
#include <linux/mfd/abx500/ab8500-gpadc.h>
#include <linux/mfd/abx500/ux500_chargalg.h>
#include <linux/usb/otg.h>
/* Charger constants */
#define NO_PW_CONN 0
#define AC_PW_CONN 1
#define USB_PW_CONN 2
#define MAIN_WDOG_ENA 0x01
#define MAIN_WDOG_KICK 0x02
#define MAIN_WDOG_DIS 0x00
#define CHARG_WD_KICK 0x01
#define MAIN_CH_ENA 0x01
#define MAIN_CH_NO_OVERSHOOT_ENA_N 0x02
#define USB_CH_ENA 0x01
#define USB_CHG_NO_OVERSHOOT_ENA_N 0x02
#define MAIN_CH_DET 0x01
#define MAIN_CH_CV_ON 0x04
#define USB_CH_CV_ON 0x08
#define VBUS_DET_DBNC100 0x02
#define VBUS_DET_DBNC1 0x01
#define OTP_ENABLE_WD 0x01
#define MAIN_CH_INPUT_CURR_SHIFT 4
#define VBUS_IN_CURR_LIM_SHIFT 4
#define LED_INDICATOR_PWM_ENA 0x01
#define LED_INDICATOR_PWM_DIS 0x00
#define LED_IND_CUR_5MA 0x04
#define LED_INDICATOR_PWM_DUTY_252_256 0xBF
/* HW failure constants */
#define MAIN_CH_TH_PROT 0x02
#define VBUS_CH_NOK 0x08
#define USB_CH_TH_PROT 0x02
#define VBUS_OVV_TH 0x01
#define MAIN_CH_NOK 0x01
#define VBUS_DET 0x80
/* UsbLineStatus register bit masks */
#define AB8500_USB_LINK_STATUS 0x78
#define AB8500_STD_HOST_SUSP 0x18
/* Watchdog timeout constant */
#define WD_TIMER 0x30 /* 4min */
#define WD_KICK_INTERVAL (60 * HZ)
/* Lowest charger voltage is 3.39V -> 0x4E */
#define LOW_VOLT_REG 0x4E
/* UsbLineStatus register - usb types */
enum ab8500_charger_link_status {
USB_STAT_NOT_CONFIGURED,
USB_STAT_STD_HOST_NC,
USB_STAT_STD_HOST_C_NS,
USB_STAT_STD_HOST_C_S,
USB_STAT_HOST_CHG_NM,
USB_STAT_HOST_CHG_HS,
USB_STAT_HOST_CHG_HS_CHIRP,
USB_STAT_DEDICATED_CHG,
USB_STAT_ACA_RID_A,
USB_STAT_ACA_RID_B,
USB_STAT_ACA_RID_C_NM,
USB_STAT_ACA_RID_C_HS,
USB_STAT_ACA_RID_C_HS_CHIRP,
USB_STAT_HM_IDGND,
USB_STAT_RESERVED,
USB_STAT_NOT_VALID_LINK,
};
enum ab8500_usb_state {
AB8500_BM_USB_STATE_RESET_HS, /* HighSpeed Reset */
AB8500_BM_USB_STATE_RESET_FS, /* FullSpeed/LowSpeed Reset */
AB8500_BM_USB_STATE_CONFIGURED,
AB8500_BM_USB_STATE_SUSPEND,
AB8500_BM_USB_STATE_RESUME,
AB8500_BM_USB_STATE_MAX,
};
/* VBUS input current limits supported in AB8500 in mA */
#define USB_CH_IP_CUR_LVL_0P05 50
#define USB_CH_IP_CUR_LVL_0P09 98
#define USB_CH_IP_CUR_LVL_0P19 193
#define USB_CH_IP_CUR_LVL_0P29 290
#define USB_CH_IP_CUR_LVL_0P38 380
#define USB_CH_IP_CUR_LVL_0P45 450
#define USB_CH_IP_CUR_LVL_0P5 500
#define USB_CH_IP_CUR_LVL_0P6 600
#define USB_CH_IP_CUR_LVL_0P7 700
#define USB_CH_IP_CUR_LVL_0P8 800
#define USB_CH_IP_CUR_LVL_0P9 900
#define USB_CH_IP_CUR_LVL_1P0 1000
#define USB_CH_IP_CUR_LVL_1P1 1100
#define USB_CH_IP_CUR_LVL_1P3 1300
#define USB_CH_IP_CUR_LVL_1P4 1400
#define USB_CH_IP_CUR_LVL_1P5 1500
#define VBAT_TRESH_IP_CUR_RED 3800
#define to_ab8500_charger_usb_device_info(x) container_of((x), \
struct ab8500_charger, usb_chg)
#define to_ab8500_charger_ac_device_info(x) container_of((x), \
struct ab8500_charger, ac_chg)
/**
* struct ab8500_charger_interrupts - ab8500 interupts
* @name: name of the interrupt
* @isr function pointer to the isr
*/
struct ab8500_charger_interrupts {
char *name;
irqreturn_t (*isr)(int irq, void *data);
};
struct ab8500_charger_info {
int charger_connected;
int charger_online;
int charger_voltage;
int cv_active;
bool wd_expired;
};
struct ab8500_charger_event_flags {
bool mainextchnotok;
bool main_thermal_prot;
bool usb_thermal_prot;
bool vbus_ovv;
bool usbchargernotok;
bool chgwdexp;
bool vbus_collapse;
};
struct ab8500_charger_usb_state {
bool usb_changed;
int usb_current;
enum ab8500_usb_state state;
spinlock_t usb_lock;
};
/**
* struct ab8500_charger - ab8500 Charger device information
* @dev: Pointer to the structure device
* @max_usb_in_curr: Max USB charger input current
* @vbus_detected: VBUS detected
* @vbus_detected_start:
* VBUS detected during startup
* @ac_conn: This will be true when the AC charger has been plugged
* @vddadc_en_ac: Indicate if VDD ADC supply is enabled because AC
* charger is enabled
* @vddadc_en_usb: Indicate if VDD ADC supply is enabled because USB
* charger is enabled
* @vbat Battery voltage
* @old_vbat Previously measured battery voltage
* @autopower Indicate if we should have automatic pwron after pwrloss
* @parent: Pointer to the struct ab8500
* @gpadc: Pointer to the struct gpadc
* @pdata: Pointer to the abx500_charger platform data
* @bat: Pointer to the abx500_bm platform data
* @flags: Structure for information about events triggered
* @usb_state: Structure for usb stack information
* @ac_chg: AC charger power supply
* @usb_chg: USB charger power supply
* @ac: Structure that holds the AC charger properties
* @usb: Structure that holds the USB charger properties
* @regu: Pointer to the struct regulator
* @charger_wq: Work queue for the IRQs and checking HW state
* @check_vbat_work Work for checking vbat threshold to adjust vbus current
* @check_hw_failure_work: Work for checking HW state
* @check_usbchgnotok_work: Work for checking USB charger not ok status
* @kick_wd_work: Work for kicking the charger watchdog in case
* of ABB rev 1.* due to the watchog logic bug
* @ac_work: Work for checking AC charger connection
* @detect_usb_type_work: Work for detecting the USB type connected
* @usb_link_status_work: Work for checking the new USB link status
* @usb_state_changed_work: Work for checking USB state
* @check_main_thermal_prot_work:
* Work for checking Main thermal status
* @check_usb_thermal_prot_work:
* Work for checking USB thermal status
*/
struct ab8500_charger {
struct device *dev;
int max_usb_in_curr;
bool vbus_detected;
bool vbus_detected_start;
bool ac_conn;
bool vddadc_en_ac;
bool vddadc_en_usb;
int vbat;
int old_vbat;
bool autopower;
struct ab8500 *parent;
struct ab8500_gpadc *gpadc;
struct abx500_charger_platform_data *pdata;
struct abx500_bm_data *bat;
struct ab8500_charger_event_flags flags;
struct ab8500_charger_usb_state usb_state;
struct ux500_charger ac_chg;
struct ux500_charger usb_chg;
struct ab8500_charger_info ac;
struct ab8500_charger_info usb;
struct regulator *regu;
struct workqueue_struct *charger_wq;
struct delayed_work check_vbat_work;
struct delayed_work check_hw_failure_work;
struct delayed_work check_usbchgnotok_work;
struct delayed_work kick_wd_work;
struct work_struct ac_work;
struct work_struct detect_usb_type_work;
struct work_struct usb_link_status_work;
struct work_struct usb_state_changed_work;
struct work_struct check_main_thermal_prot_work;
struct work_struct check_usb_thermal_prot_work;
struct usb_phy *usb_phy;
struct notifier_block nb;
};
/* AC properties */
static enum power_supply_property ab8500_charger_ac_props[] = {
POWER_SUPPLY_PROP_HEALTH,
POWER_SUPPLY_PROP_PRESENT,
POWER_SUPPLY_PROP_ONLINE,
POWER_SUPPLY_PROP_VOLTAGE_NOW,
POWER_SUPPLY_PROP_VOLTAGE_AVG,
POWER_SUPPLY_PROP_CURRENT_NOW,
};
/* USB properties */
static enum power_supply_property ab8500_charger_usb_props[] = {
POWER_SUPPLY_PROP_HEALTH,
POWER_SUPPLY_PROP_CURRENT_AVG,
POWER_SUPPLY_PROP_PRESENT,
POWER_SUPPLY_PROP_ONLINE,
POWER_SUPPLY_PROP_VOLTAGE_NOW,
POWER_SUPPLY_PROP_VOLTAGE_AVG,
POWER_SUPPLY_PROP_CURRENT_NOW,
};
/**
* ab8500_power_loss_handling - set how we handle powerloss.
* @di: pointer to the ab8500_charger structure
*
* Magic nummbers are from STE HW department.
*/
static void ab8500_power_loss_handling(struct ab8500_charger *di)
{
u8 reg;
int ret;
dev_dbg(di->dev, "Autopower : %d\n", di->autopower);
/* read the autopower register */
ret = abx500_get_register_interruptible(di->dev, 0x15, 0x00, ®);
if (ret) {
dev_err(di->dev, "%d write failed\n", __LINE__);
return;
}
/* enable the OPT emulation registers */
ret = abx500_set_register_interruptible(di->dev, 0x11, 0x00, 0x2);
if (ret) {
dev_err(di->dev, "%d write failed\n", __LINE__);
return;
}
if (di->autopower)
reg |= 0x8;
else
reg &= ~0x8;
/* write back the changed value to autopower reg */
ret = abx500_set_register_interruptible(di->dev, 0x15, 0x00, reg);
if (ret) {
dev_err(di->dev, "%d write failed\n", __LINE__);
return;
}
/* disable the set OTP registers again */
ret = abx500_set_register_interruptible(di->dev, 0x11, 0x00, 0x0);
if (ret) {
dev_err(di->dev, "%d write failed\n", __LINE__);
return;
}
}
/**
* ab8500_power_supply_changed - a wrapper with local extentions for
* power_supply_changed
* @di: pointer to the ab8500_charger structure
* @psy: pointer to power_supply_that have changed.
*
*/
static void ab8500_power_supply_changed(struct ab8500_charger *di,
struct power_supply *psy)
{
if (di->pdata->autopower_cfg) {
if (!di->usb.charger_connected &&
!di->ac.charger_connected &&
di->autopower) {
di->autopower = false;
ab8500_power_loss_handling(di);
} else if (!di->autopower &&
(di->ac.charger_connected ||
di->usb.charger_connected)) {
di->autopower = true;
ab8500_power_loss_handling(di);
}
}
power_supply_changed(psy);
}
static void ab8500_charger_set_usb_connected(struct ab8500_charger *di,
bool connected)
{
if (connected != di->usb.charger_connected) {
dev_dbg(di->dev, "USB connected:%i\n", connected);
di->usb.charger_connected = connected;
sysfs_notify(&di->usb_chg.psy.dev->kobj, NULL, "present");
}
}
/**
* ab8500_charger_get_ac_voltage() - get ac charger voltage
* @di: pointer to the ab8500_charger structure
*
* Returns ac charger voltage (on success)
*/
static int ab8500_charger_get_ac_voltage(struct ab8500_charger *di)
{
int vch;
/* Only measure voltage if the charger is connected */
if (di->ac.charger_connected) {
vch = ab8500_gpadc_convert(di->gpadc, MAIN_CHARGER_V);
if (vch < 0)
dev_err(di->dev, "%s gpadc conv failed,\n", __func__);
} else {
vch = 0;
}
return vch;
}
/**
* ab8500_charger_ac_cv() - check if the main charger is in CV mode
* @di: pointer to the ab8500_charger structure
*
* Returns ac charger CV mode (on success) else error code
*/
static int ab8500_charger_ac_cv(struct ab8500_charger *di)
{
u8 val;
int ret = 0;
/* Only check CV mode if the charger is online */
if (di->ac.charger_online) {
ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CH_STATUS1_REG, &val);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return 0;
}
if (val & MAIN_CH_CV_ON)
ret = 1;
else
ret = 0;
}
return ret;
}
/**
* ab8500_charger_get_vbus_voltage() - get vbus voltage
* @di: pointer to the ab8500_charger structure
*
* This function returns the vbus voltage.
* Returns vbus voltage (on success)
*/
static int ab8500_charger_get_vbus_voltage(struct ab8500_charger *di)
{
int vch;
/* Only measure voltage if the charger is connected */
if (di->usb.charger_connected) {
vch = ab8500_gpadc_convert(di->gpadc, VBUS_V);
if (vch < 0)
dev_err(di->dev, "%s gpadc conv failed\n", __func__);
} else {
vch = 0;
}
return vch;
}
/**
* ab8500_charger_get_usb_current() - get usb charger current
* @di: pointer to the ab8500_charger structure
*
* This function returns the usb charger current.
* Returns usb current (on success) and error code on failure
*/
static int ab8500_charger_get_usb_current(struct ab8500_charger *di)
{
int ich;
/* Only measure current if the charger is online */
if (di->usb.charger_online) {
ich = ab8500_gpadc_convert(di->gpadc, USB_CHARGER_C);
if (ich < 0)
dev_err(di->dev, "%s gpadc conv failed\n", __func__);
} else {
ich = 0;
}
return ich;
}
/**
* ab8500_charger_get_ac_current() - get ac charger current
* @di: pointer to the ab8500_charger structure
*
* This function returns the ac charger current.
* Returns ac current (on success) and error code on failure.
*/
static int ab8500_charger_get_ac_current(struct ab8500_charger *di)
{
int ich;
/* Only measure current if the charger is online */
if (di->ac.charger_online) {
ich = ab8500_gpadc_convert(di->gpadc, MAIN_CHARGER_C);
if (ich < 0)
dev_err(di->dev, "%s gpadc conv failed\n", __func__);
} else {
ich = 0;
}
return ich;
}
/**
* ab8500_charger_usb_cv() - check if the usb charger is in CV mode
* @di: pointer to the ab8500_charger structure
*
* Returns ac charger CV mode (on success) else error code
*/
static int ab8500_charger_usb_cv(struct ab8500_charger *di)
{
int ret;
u8 val;
/* Only check CV mode if the charger is online */
if (di->usb.charger_online) {
ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CH_USBCH_STAT1_REG, &val);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return 0;
}
if (val & USB_CH_CV_ON)
ret = 1;
else
ret = 0;
} else {
ret = 0;
}
return ret;
}
/**
* ab8500_charger_detect_chargers() - Detect the connected chargers
* @di: pointer to the ab8500_charger structure
*
* Returns the type of charger connected.
* For USB it will not mean we can actually charge from it
* but that there is a USB cable connected that we have to
* identify. This is used during startup when we don't get
* interrupts of the charger detection
*
* Returns an integer value, that means,
* NO_PW_CONN no power supply is connected
* AC_PW_CONN if the AC power supply is connected
* USB_PW_CONN if the USB power supply is connected
* AC_PW_CONN + USB_PW_CONN if USB and AC power supplies are both connected
*/
static int ab8500_charger_detect_chargers(struct ab8500_charger *di)
{
int result = NO_PW_CONN;
int ret;
u8 val;
/* Check for AC charger */
ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CH_STATUS1_REG, &val);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return ret;
}
if (val & MAIN_CH_DET)
result = AC_PW_CONN;
/* Check for USB charger */
ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CH_USBCH_STAT1_REG, &val);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return ret;
}
if ((val & VBUS_DET_DBNC1) && (val & VBUS_DET_DBNC100))
result |= USB_PW_CONN;
return result;
}
/**
* ab8500_charger_max_usb_curr() - get the max curr for the USB type
* @di: pointer to the ab8500_charger structure
* @link_status: the identified USB type
*
* Get the maximum current that is allowed to be drawn from the host
* based on the USB type.
* Returns error code in case of failure else 0 on success
*/
static int ab8500_charger_max_usb_curr(struct ab8500_charger *di,
enum ab8500_charger_link_status link_status)
{
int ret = 0;
switch (link_status) {
case USB_STAT_STD_HOST_NC:
case USB_STAT_STD_HOST_C_NS:
case USB_STAT_STD_HOST_C_S:
dev_dbg(di->dev, "USB Type - Standard host is "
"detected through USB driver\n");
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_0P09;
break;
case USB_STAT_HOST_CHG_HS_CHIRP:
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_0P5;
break;
case USB_STAT_HOST_CHG_HS:
case USB_STAT_ACA_RID_C_HS:
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_0P9;
break;
case USB_STAT_ACA_RID_A:
/*
* Dedicated charger level minus maximum current accessory
* can consume (300mA). Closest level is 1100mA
*/
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_1P1;
break;
case USB_STAT_ACA_RID_B:
/*
* Dedicated charger level minus 120mA (20mA for ACA and
* 100mA for potential accessory). Closest level is 1300mA
*/
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_1P3;
break;
case USB_STAT_DEDICATED_CHG:
case USB_STAT_HOST_CHG_NM:
case USB_STAT_ACA_RID_C_HS_CHIRP:
case USB_STAT_ACA_RID_C_NM:
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_1P5;
break;
case USB_STAT_RESERVED:
/*
* This state is used to indicate that VBUS has dropped below
* the detection level 4 times in a row. This is due to the
* charger output current is set to high making the charger
* voltage collapse. This have to be propagated through to
* chargalg. This is done using the property
* POWER_SUPPLY_PROP_CURRENT_AVG = 1
*/
di->flags.vbus_collapse = true;
dev_dbg(di->dev, "USB Type - USB_STAT_RESERVED "
"VBUS has collapsed\n");
ret = -1;
break;
case USB_STAT_HM_IDGND:
case USB_STAT_NOT_CONFIGURED:
case USB_STAT_NOT_VALID_LINK:
dev_err(di->dev, "USB Type - Charging not allowed\n");
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_0P05;
ret = -ENXIO;
break;
default:
dev_err(di->dev, "USB Type - Unknown\n");
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_0P05;
ret = -ENXIO;
break;
};
dev_dbg(di->dev, "USB Type - 0x%02x MaxCurr: %d",
link_status, di->max_usb_in_curr);
return ret;
}
/**
* ab8500_charger_read_usb_type() - read the type of usb connected
* @di: pointer to the ab8500_charger structure
*
* Detect the type of the plugged USB
* Returns error code in case of failure else 0 on success
*/
static int ab8500_charger_read_usb_type(struct ab8500_charger *di)
{
int ret;
u8 val;
ret = abx500_get_register_interruptible(di->dev,
AB8500_INTERRUPT, AB8500_IT_SOURCE21_REG, &val);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return ret;
}
ret = abx500_get_register_interruptible(di->dev, AB8500_USB,
AB8500_USB_LINE_STAT_REG, &val);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return ret;
}
/* get the USB type */
val = (val & AB8500_USB_LINK_STATUS) >> 3;
ret = ab8500_charger_max_usb_curr(di,
(enum ab8500_charger_link_status) val);
return ret;
}
/**
* ab8500_charger_detect_usb_type() - get the type of usb connected
* @di: pointer to the ab8500_charger structure
*
* Detect the type of the plugged USB
* Returns error code in case of failure else 0 on success
*/
static int ab8500_charger_detect_usb_type(struct ab8500_charger *di)
{
int i, ret;
u8 val;
/*
* On getting the VBUS rising edge detect interrupt there
* is a 250ms delay after which the register UsbLineStatus
* is filled with valid data.
*/
for (i = 0; i < 10; i++) {
msleep(250);
ret = abx500_get_register_interruptible(di->dev,
AB8500_INTERRUPT, AB8500_IT_SOURCE21_REG,
&val);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return ret;
}
ret = abx500_get_register_interruptible(di->dev, AB8500_USB,
AB8500_USB_LINE_STAT_REG, &val);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return ret;
}
/*
* Until the IT source register is read the UsbLineStatus
* register is not updated, hence doing the same
* Revisit this:
*/
/* get the USB type */
val = (val & AB8500_USB_LINK_STATUS) >> 3;
if (val)
break;
}
ret = ab8500_charger_max_usb_curr(di,
(enum ab8500_charger_link_status) val);
return ret;
}
/*
* This array maps the raw hex value to charger voltage used by the AB8500
* Values taken from the UM0836
*/
static int ab8500_charger_voltage_map[] = {
3500 ,
3525 ,
3550 ,
3575 ,
3600 ,
3625 ,
3650 ,
3675 ,
3700 ,
3725 ,
3750 ,
3775 ,
3800 ,
3825 ,
3850 ,
3875 ,
3900 ,
3925 ,
3950 ,
3975 ,
4000 ,
4025 ,
4050 ,
4060 ,
4070 ,
4080 ,
4090 ,
4100 ,
4110 ,
4120 ,
4130 ,
4140 ,
4150 ,
4160 ,
4170 ,
4180 ,
4190 ,
4200 ,
4210 ,
4220 ,
4230 ,
4240 ,
4250 ,
4260 ,
4270 ,
4280 ,
4290 ,
4300 ,
4310 ,
4320 ,
4330 ,
4340 ,
4350 ,
4360 ,
4370 ,
4380 ,
4390 ,
4400 ,
4410 ,
4420 ,
4430 ,
4440 ,
4450 ,
4460 ,
4470 ,
4480 ,
4490 ,
4500 ,
4510 ,
4520 ,
4530 ,
4540 ,
4550 ,
4560 ,
4570 ,
4580 ,
4590 ,
4600 ,
};
/*
* This array maps the raw hex value to charger current used by the AB8500
* Values taken from the UM0836
*/
static int ab8500_charger_current_map[] = {
100 ,
200 ,
300 ,
400 ,
500 ,
600 ,
700 ,
800 ,
900 ,
1000 ,
1100 ,
1200 ,
1300 ,
1400 ,
1500 ,
};
/*
* This array maps the raw hex value to VBUS input current used by the AB8500
* Values taken from the UM0836
*/
static int ab8500_charger_vbus_in_curr_map[] = {
USB_CH_IP_CUR_LVL_0P05,
USB_CH_IP_CUR_LVL_0P09,
USB_CH_IP_CUR_LVL_0P19,
USB_CH_IP_CUR_LVL_0P29,
USB_CH_IP_CUR_LVL_0P38,
USB_CH_IP_CUR_LVL_0P45,
USB_CH_IP_CUR_LVL_0P5,
USB_CH_IP_CUR_LVL_0P6,
USB_CH_IP_CUR_LVL_0P7,
USB_CH_IP_CUR_LVL_0P8,
USB_CH_IP_CUR_LVL_0P9,
USB_CH_IP_CUR_LVL_1P0,
USB_CH_IP_CUR_LVL_1P1,
USB_CH_IP_CUR_LVL_1P3,
USB_CH_IP_CUR_LVL_1P4,
USB_CH_IP_CUR_LVL_1P5,
};
static int ab8500_voltage_to_regval(int voltage)
{
int i;
/* Special case for voltage below 3.5V */
if (voltage < ab8500_charger_voltage_map[0])
return LOW_VOLT_REG;
for (i = 1; i < ARRAY_SIZE(ab8500_charger_voltage_map); i++) {
if (voltage < ab8500_charger_voltage_map[i])
return i - 1;
}
/* If not last element, return error */
i = ARRAY_SIZE(ab8500_charger_voltage_map) - 1;
if (voltage == ab8500_charger_voltage_map[i])
return i;
else
return -1;
}
static int ab8500_current_to_regval(int curr)
{
int i;
if (curr < ab8500_charger_current_map[0])
return 0;
for (i = 0; i < ARRAY_SIZE(ab8500_charger_current_map); i++) {
if (curr < ab8500_charger_current_map[i])
return i - 1;
}
/* If not last element, return error */
i = ARRAY_SIZE(ab8500_charger_current_map) - 1;
if (curr == ab8500_charger_current_map[i])
return i;
else
return -1;
}
static int ab8500_vbus_in_curr_to_regval(int curr)
{
int i;
if (curr < ab8500_charger_vbus_in_curr_map[0])
return 0;
for (i = 0; i < ARRAY_SIZE(ab8500_charger_vbus_in_curr_map); i++) {
if (curr < ab8500_charger_vbus_in_curr_map[i])
return i - 1;
}
/* If not last element, return error */
i = ARRAY_SIZE(ab8500_charger_vbus_in_curr_map) - 1;
if (curr == ab8500_charger_vbus_in_curr_map[i])
return i;
else
return -1;
}
/**
* ab8500_charger_get_usb_cur() - get usb current
* @di: pointer to the ab8500_charger structre
*
* The usb stack provides the maximum current that can be drawn from
* the standard usb host. This will be in mA.
* This function converts current in mA to a value that can be written
* to the register. Returns -1 if charging is not allowed
*/
static int ab8500_charger_get_usb_cur(struct ab8500_charger *di)
{
switch (di->usb_state.usb_current) {
case 100:
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_0P09;
break;
case 200:
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_0P19;
break;
case 300:
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_0P29;
break;
case 400:
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_0P38;
break;
case 500:
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_0P5;
break;
default:
di->max_usb_in_curr = USB_CH_IP_CUR_LVL_0P05;
return -1;
break;
};
return 0;
}
/**
* ab8500_charger_set_vbus_in_curr() - set VBUS input current limit
* @di: pointer to the ab8500_charger structure
* @ich_in: charger input current limit
*
* Sets the current that can be drawn from the USB host
* Returns error code in case of failure else 0(on success)
*/
static int ab8500_charger_set_vbus_in_curr(struct ab8500_charger *di,
int ich_in)
{
int ret;
int input_curr_index;
int min_value;
/* We should always use to lowest current limit */
min_value = min(di->bat->chg_params->usb_curr_max, ich_in);
switch (min_value) {
case 100:
if (di->vbat < VBAT_TRESH_IP_CUR_RED)
min_value = USB_CH_IP_CUR_LVL_0P05;
break;
case 500:
if (di->vbat < VBAT_TRESH_IP_CUR_RED)
min_value = USB_CH_IP_CUR_LVL_0P45;
break;
default:
break;
}
input_curr_index = ab8500_vbus_in_curr_to_regval(min_value);
if (input_curr_index < 0) {
dev_err(di->dev, "VBUS input current limit too high\n");
return -ENXIO;
}
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_USBCH_IPT_CRNTLVL_REG,
input_curr_index << VBUS_IN_CURR_LIM_SHIFT);
if (ret)
dev_err(di->dev, "%s write failed\n", __func__);
return ret;
}
/**
* ab8500_charger_led_en() - turn on/off chargign led
* @di: pointer to the ab8500_charger structure
* @on: flag to turn on/off the chargign led
*
* Power ON/OFF charging LED indication
* Returns error code in case of failure else 0(on success)
*/
static int ab8500_charger_led_en(struct ab8500_charger *di, int on)
{
int ret;
if (on) {
/* Power ON charging LED indicator, set LED current to 5mA */
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_LED_INDICATOR_PWM_CTRL,
(LED_IND_CUR_5MA | LED_INDICATOR_PWM_ENA));
if (ret) {
dev_err(di->dev, "Power ON LED failed\n");
return ret;
}
/* LED indicator PWM duty cycle 252/256 */
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_LED_INDICATOR_PWM_DUTY,
LED_INDICATOR_PWM_DUTY_252_256);
if (ret) {
dev_err(di->dev, "Set LED PWM duty cycle failed\n");
return ret;
}
} else {
/* Power off charging LED indicator */
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_LED_INDICATOR_PWM_CTRL,
LED_INDICATOR_PWM_DIS);
if (ret) {
dev_err(di->dev, "Power-off LED failed\n");
return ret;
}
}
return ret;
}
/**
* ab8500_charger_ac_en() - enable or disable ac charging
* @di: pointer to the ab8500_charger structure
* @enable: enable/disable flag
* @vset: charging voltage
* @iset: charging current
*
* Enable/Disable AC/Mains charging and turns on/off the charging led
* respectively.
**/
static int ab8500_charger_ac_en(struct ux500_charger *charger,
int enable, int vset, int iset)
{
int ret;
int volt_index;
int curr_index;
int input_curr_index;
u8 overshoot = 0;
struct ab8500_charger *di = to_ab8500_charger_ac_device_info(charger);
if (enable) {
/* Check if AC is connected */
if (!di->ac.charger_connected) {
dev_err(di->dev, "AC charger not connected\n");
return -ENXIO;
}
/* Enable AC charging */
dev_dbg(di->dev, "Enable AC: %dmV %dmA\n", vset, iset);
/*
* Due to a bug in AB8500, BTEMP_HIGH/LOW interrupts
* will be triggered everytime we enable the VDD ADC supply.
* This will turn off charging for a short while.
* It can be avoided by having the supply on when
* there is a charger enabled. Normally the VDD ADC supply
* is enabled everytime a GPADC conversion is triggered. We will
* force it to be enabled from this driver to have
* the GPADC module independant of the AB8500 chargers
*/
if (!di->vddadc_en_ac) {
regulator_enable(di->regu);
di->vddadc_en_ac = true;
}
/* Check if the requested voltage or current is valid */
volt_index = ab8500_voltage_to_regval(vset);
curr_index = ab8500_current_to_regval(iset);
input_curr_index = ab8500_current_to_regval(
di->bat->chg_params->ac_curr_max);
if (volt_index < 0 || curr_index < 0 || input_curr_index < 0) {
dev_err(di->dev,
"Charger voltage or current too high, "
"charging not started\n");
return -ENXIO;
}
/* ChVoltLevel: maximum battery charging voltage */
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CH_VOLT_LVL_REG, (u8) volt_index);
if (ret) {
dev_err(di->dev, "%s write failed\n", __func__);
return ret;
}
/* MainChInputCurr: current that can be drawn from the charger*/
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_MCH_IPT_CURLVL_REG,
input_curr_index << MAIN_CH_INPUT_CURR_SHIFT);
if (ret) {
dev_err(di->dev, "%s write failed\n", __func__);
return ret;
}
/* ChOutputCurentLevel: protected output current */
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CH_OPT_CRNTLVL_REG, (u8) curr_index);
if (ret) {
dev_err(di->dev, "%s write failed\n", __func__);
return ret;
}
/* Check if VBAT overshoot control should be enabled */
if (!di->bat->enable_overshoot)
overshoot = MAIN_CH_NO_OVERSHOOT_ENA_N;
/* Enable Main Charger */
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_MCH_CTRL1, MAIN_CH_ENA | overshoot);
if (ret) {
dev_err(di->dev, "%s write failed\n", __func__);
return ret;
}
/* Power on charging LED indication */
ret = ab8500_charger_led_en(di, true);
if (ret < 0)
dev_err(di->dev, "failed to enable LED\n");
di->ac.charger_online = 1;
} else {
/* Disable AC charging */
if (is_ab8500_1p1_or_earlier(di->parent)) {
/*
* For ABB revision 1.0 and 1.1 there is a bug in the
* watchdog logic. That means we have to continously
* kick the charger watchdog even when no charger is
* connected. This is only valid once the AC charger
* has been enabled. This is a bug that is not handled
* by the algorithm and the watchdog have to be kicked
* by the charger driver when the AC charger
* is disabled
*/
if (di->ac_conn) {
queue_delayed_work(di->charger_wq,
&di->kick_wd_work,
round_jiffies(WD_KICK_INTERVAL));
}
/*
* We can't turn off charging completely
* due to a bug in AB8500 cut1.
* If we do, charging will not start again.
* That is why we set the lowest voltage
* and current possible
*/
ret = abx500_set_register_interruptible(di->dev,
AB8500_CHARGER,
AB8500_CH_VOLT_LVL_REG, CH_VOL_LVL_3P5);
if (ret) {
dev_err(di->dev,
"%s write failed\n", __func__);
return ret;
}
ret = abx500_set_register_interruptible(di->dev,
AB8500_CHARGER,
AB8500_CH_OPT_CRNTLVL_REG, CH_OP_CUR_LVL_0P1);
if (ret) {
dev_err(di->dev,
"%s write failed\n", __func__);
return ret;
}
} else {
ret = abx500_set_register_interruptible(di->dev,
AB8500_CHARGER,
AB8500_MCH_CTRL1, 0);
if (ret) {
dev_err(di->dev,
"%s write failed\n", __func__);
return ret;
}
}
ret = ab8500_charger_led_en(di, false);
if (ret < 0)
dev_err(di->dev, "failed to disable LED\n");
di->ac.charger_online = 0;
di->ac.wd_expired = false;
/* Disable regulator if enabled */
if (di->vddadc_en_ac) {
regulator_disable(di->regu);
di->vddadc_en_ac = false;
}
dev_dbg(di->dev, "%s Disabled AC charging\n", __func__);
}
ab8500_power_supply_changed(di, &di->ac_chg.psy);
return ret;
}
/**
* ab8500_charger_usb_en() - enable usb charging
* @di: pointer to the ab8500_charger structure
* @enable: enable/disable flag
* @vset: charging voltage
* @ich_out: charger output current
*
* Enable/Disable USB charging and turns on/off the charging led respectively.
* Returns error code in case of failure else 0(on success)
*/
static int ab8500_charger_usb_en(struct ux500_charger *charger,
int enable, int vset, int ich_out)
{
int ret;
int volt_index;
int curr_index;
u8 overshoot = 0;
struct ab8500_charger *di = to_ab8500_charger_usb_device_info(charger);
if (enable) {
/* Check if USB is connected */
if (!di->usb.charger_connected) {
dev_err(di->dev, "USB charger not connected\n");
return -ENXIO;
}
/*
* Due to a bug in AB8500, BTEMP_HIGH/LOW interrupts
* will be triggered everytime we enable the VDD ADC supply.
* This will turn off charging for a short while.
* It can be avoided by having the supply on when
* there is a charger enabled. Normally the VDD ADC supply
* is enabled everytime a GPADC conversion is triggered. We will
* force it to be enabled from this driver to have
* the GPADC module independant of the AB8500 chargers
*/
if (!di->vddadc_en_usb) {
regulator_enable(di->regu);
di->vddadc_en_usb = true;
}
/* Enable USB charging */
dev_dbg(di->dev, "Enable USB: %dmV %dmA\n", vset, ich_out);
/* Check if the requested voltage or current is valid */
volt_index = ab8500_voltage_to_regval(vset);
curr_index = ab8500_current_to_regval(ich_out);
if (volt_index < 0 || curr_index < 0) {
dev_err(di->dev,
"Charger voltage or current too high, "
"charging not started\n");
return -ENXIO;
}
/* ChVoltLevel: max voltage upto which battery can be charged */
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CH_VOLT_LVL_REG, (u8) volt_index);
if (ret) {
dev_err(di->dev, "%s write failed\n", __func__);
return ret;
}
/* USBChInputCurr: current that can be drawn from the usb */
ret = ab8500_charger_set_vbus_in_curr(di, di->max_usb_in_curr);
if (ret) {
dev_err(di->dev, "setting USBChInputCurr failed\n");
return ret;
}
/* ChOutputCurentLevel: protected output current */
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CH_OPT_CRNTLVL_REG, (u8) curr_index);
if (ret) {
dev_err(di->dev, "%s write failed\n", __func__);
return ret;
}
/* Check if VBAT overshoot control should be enabled */
if (!di->bat->enable_overshoot)
overshoot = USB_CHG_NO_OVERSHOOT_ENA_N;
/* Enable USB Charger */
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_USBCH_CTRL1_REG, USB_CH_ENA | overshoot);
if (ret) {
dev_err(di->dev, "%s write failed\n", __func__);
return ret;
}
/* If success power on charging LED indication */
ret = ab8500_charger_led_en(di, true);
if (ret < 0)
dev_err(di->dev, "failed to enable LED\n");
queue_delayed_work(di->charger_wq, &di->check_vbat_work, HZ);
di->usb.charger_online = 1;
} else {
/* Disable USB charging */
ret = abx500_set_register_interruptible(di->dev,
AB8500_CHARGER,
AB8500_USBCH_CTRL1_REG, 0);
if (ret) {
dev_err(di->dev,
"%s write failed\n", __func__);
return ret;
}
ret = ab8500_charger_led_en(di, false);
if (ret < 0)
dev_err(di->dev, "failed to disable LED\n");
di->usb.charger_online = 0;
di->usb.wd_expired = false;
/* Disable regulator if enabled */
if (di->vddadc_en_usb) {
regulator_disable(di->regu);
di->vddadc_en_usb = false;
}
dev_dbg(di->dev, "%s Disabled USB charging\n", __func__);
/* Cancel any pending Vbat check work */
if (delayed_work_pending(&di->check_vbat_work))
cancel_delayed_work(&di->check_vbat_work);
}
ab8500_power_supply_changed(di, &di->usb_chg.psy);
return ret;
}
/**
* ab8500_charger_watchdog_kick() - kick charger watchdog
* @di: pointer to the ab8500_charger structure
*
* Kick charger watchdog
* Returns error code in case of failure else 0(on success)
*/
static int ab8500_charger_watchdog_kick(struct ux500_charger *charger)
{
int ret;
struct ab8500_charger *di;
if (charger->psy.type == POWER_SUPPLY_TYPE_MAINS)
di = to_ab8500_charger_ac_device_info(charger);
else if (charger->psy.type == POWER_SUPPLY_TYPE_USB)
di = to_ab8500_charger_usb_device_info(charger);
else
return -ENXIO;
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CHARG_WD_CTRL, CHARG_WD_KICK);
if (ret)
dev_err(di->dev, "Failed to kick WD!\n");
return ret;
}
/**
* ab8500_charger_update_charger_current() - update charger current
* @di: pointer to the ab8500_charger structure
*
* Update the charger output current for the specified charger
* Returns error code in case of failure else 0(on success)
*/
static int ab8500_charger_update_charger_current(struct ux500_charger *charger,
int ich_out)
{
int ret;
int curr_index;
struct ab8500_charger *di;
if (charger->psy.type == POWER_SUPPLY_TYPE_MAINS)
di = to_ab8500_charger_ac_device_info(charger);
else if (charger->psy.type == POWER_SUPPLY_TYPE_USB)
di = to_ab8500_charger_usb_device_info(charger);
else
return -ENXIO;
curr_index = ab8500_current_to_regval(ich_out);
if (curr_index < 0) {
dev_err(di->dev,
"Charger current too high, "
"charging not started\n");
return -ENXIO;
}
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CH_OPT_CRNTLVL_REG, (u8) curr_index);
if (ret) {
dev_err(di->dev, "%s write failed\n", __func__);
return ret;
}
/* Reset the main and usb drop input current measurement counter */
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CHARGER_CTRL,
0x1);
if (ret) {
dev_err(di->dev, "%s write failed\n", __func__);
return ret;
}
return ret;
}
static int ab8500_charger_get_ext_psy_data(struct device *dev, void *data)
{
struct power_supply *psy;
struct power_supply *ext;
struct ab8500_charger *di;
union power_supply_propval ret;
int i, j;
bool psy_found = false;
struct ux500_charger *usb_chg;
usb_chg = (struct ux500_charger *)data;
psy = &usb_chg->psy;
di = to_ab8500_charger_usb_device_info(usb_chg);
ext = dev_get_drvdata(dev);
/* For all psy where the driver name appears in any supplied_to */
for (i = 0; i < ext->num_supplicants; i++) {
if (!strcmp(ext->supplied_to[i], psy->name))
psy_found = true;
}
if (!psy_found)
return 0;
/* Go through all properties for the psy */
for (j = 0; j < ext->num_properties; j++) {
enum power_supply_property prop;
prop = ext->properties[j];
if (ext->get_property(ext, prop, &ret))
continue;
switch (prop) {
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
switch (ext->type) {
case POWER_SUPPLY_TYPE_BATTERY:
di->vbat = ret.intval / 1000;
break;
default:
break;
}
break;
default:
break;
}
}
return 0;
}
/**
* ab8500_charger_check_vbat_work() - keep vbus current within spec
* @work pointer to the work_struct structure
*
* Due to a asic bug it is necessary to lower the input current to the vbus
* charger when charging with at some specific levels. This issue is only valid
* for below a certain battery voltage. This function makes sure that the
* the allowed current limit isn't exceeded.
*/
static void ab8500_charger_check_vbat_work(struct work_struct *work)
{
int t = 10;
struct ab8500_charger *di = container_of(work,
struct ab8500_charger, check_vbat_work.work);
class_for_each_device(power_supply_class, NULL,
&di->usb_chg.psy, ab8500_charger_get_ext_psy_data);
/* First run old_vbat is 0. */
if (di->old_vbat == 0)
di->old_vbat = di->vbat;
if (!((di->old_vbat <= VBAT_TRESH_IP_CUR_RED &&
di->vbat <= VBAT_TRESH_IP_CUR_RED) ||
(di->old_vbat > VBAT_TRESH_IP_CUR_RED &&
di->vbat > VBAT_TRESH_IP_CUR_RED))) {
dev_dbg(di->dev, "Vbat did cross threshold, curr: %d, new: %d,"
" old: %d\n", di->max_usb_in_curr, di->vbat,
di->old_vbat);
ab8500_charger_set_vbus_in_curr(di, di->max_usb_in_curr);
power_supply_changed(&di->usb_chg.psy);
}
di->old_vbat = di->vbat;
/*
* No need to check the battery voltage every second when not close to
* the threshold.
*/
if (di->vbat < (VBAT_TRESH_IP_CUR_RED + 100) &&
(di->vbat > (VBAT_TRESH_IP_CUR_RED - 100)))
t = 1;
queue_delayed_work(di->charger_wq, &di->check_vbat_work, t * HZ);
}
/**
* ab8500_charger_check_hw_failure_work() - check main charger failure
* @work: pointer to the work_struct structure
*
* Work queue function for checking the main charger status
*/
static void ab8500_charger_check_hw_failure_work(struct work_struct *work)
{
int ret;
u8 reg_value;
struct ab8500_charger *di = container_of(work,
struct ab8500_charger, check_hw_failure_work.work);
/* Check if the status bits for HW failure is still active */
if (di->flags.mainextchnotok) {
ret = abx500_get_register_interruptible(di->dev,
AB8500_CHARGER, AB8500_CH_STATUS2_REG, ®_value);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return;
}
if (!(reg_value & MAIN_CH_NOK)) {
di->flags.mainextchnotok = false;
ab8500_power_supply_changed(di, &di->ac_chg.psy);
}
}
if (di->flags.vbus_ovv) {
ret = abx500_get_register_interruptible(di->dev,
AB8500_CHARGER, AB8500_CH_USBCH_STAT2_REG,
®_value);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return;
}
if (!(reg_value & VBUS_OVV_TH)) {
di->flags.vbus_ovv = false;
ab8500_power_supply_changed(di, &di->usb_chg.psy);
}
}
/* If we still have a failure, schedule a new check */
if (di->flags.mainextchnotok || di->flags.vbus_ovv) {
queue_delayed_work(di->charger_wq,
&di->check_hw_failure_work, round_jiffies(HZ));
}
}
/**
* ab8500_charger_kick_watchdog_work() - kick the watchdog
* @work: pointer to the work_struct structure
*
* Work queue function for kicking the charger watchdog.
*
* For ABB revision 1.0 and 1.1 there is a bug in the watchdog
* logic. That means we have to continously kick the charger
* watchdog even when no charger is connected. This is only
* valid once the AC charger has been enabled. This is
* a bug that is not handled by the algorithm and the
* watchdog have to be kicked by the charger driver
* when the AC charger is disabled
*/
static void ab8500_charger_kick_watchdog_work(struct work_struct *work)
{
int ret;
struct ab8500_charger *di = container_of(work,
struct ab8500_charger, kick_wd_work.work);
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CHARG_WD_CTRL, CHARG_WD_KICK);
if (ret)
dev_err(di->dev, "Failed to kick WD!\n");
/* Schedule a new watchdog kick */
queue_delayed_work(di->charger_wq,
&di->kick_wd_work, round_jiffies(WD_KICK_INTERVAL));
}
/**
* ab8500_charger_ac_work() - work to get and set main charger status
* @work: pointer to the work_struct structure
*
* Work queue function for checking the main charger status
*/
static void ab8500_charger_ac_work(struct work_struct *work)
{
int ret;
struct ab8500_charger *di = container_of(work,
struct ab8500_charger, ac_work);
/*
* Since we can't be sure that the events are received
* synchronously, we have the check if the main charger is
* connected by reading the status register
*/
ret = ab8500_charger_detect_chargers(di);
if (ret < 0)
return;
if (ret & AC_PW_CONN) {
di->ac.charger_connected = 1;
di->ac_conn = true;
} else {
di->ac.charger_connected = 0;
}
ab8500_power_supply_changed(di, &di->ac_chg.psy);
sysfs_notify(&di->ac_chg.psy.dev->kobj, NULL, "present");
}
/**
* ab8500_charger_detect_usb_type_work() - work to detect USB type
* @work: Pointer to the work_struct structure
*
* Detect the type of USB plugged
*/
static void ab8500_charger_detect_usb_type_work(struct work_struct *work)
{
int ret;
struct ab8500_charger *di = container_of(work,
struct ab8500_charger, detect_usb_type_work);
/*
* Since we can't be sure that the events are received
* synchronously, we have the check if is
* connected by reading the status register
*/
ret = ab8500_charger_detect_chargers(di);
if (ret < 0)
return;
if (!(ret & USB_PW_CONN)) {
di->vbus_detected = 0;
ab8500_charger_set_usb_connected(di, false);
ab8500_power_supply_changed(di, &di->usb_chg.psy);
} else {
di->vbus_detected = 1;
if (is_ab8500_1p1_or_earlier(di->parent)) {
ret = ab8500_charger_detect_usb_type(di);
if (!ret) {
ab8500_charger_set_usb_connected(di, true);
ab8500_power_supply_changed(di,
&di->usb_chg.psy);
}
} else {
/* For ABB cut2.0 and onwards we have an IRQ,
* USB_LINK_STATUS that will be triggered when the USB
* link status changes. The exception is USB connected
* during startup. Then we don't get a
* USB_LINK_STATUS IRQ
*/
if (di->vbus_detected_start) {
di->vbus_detected_start = false;
ret = ab8500_charger_detect_usb_type(di);
if (!ret) {
ab8500_charger_set_usb_connected(di,
true);
ab8500_power_supply_changed(di,
&di->usb_chg.psy);
}
}
}
}
}
/**
* ab8500_charger_usb_link_status_work() - work to detect USB type
* @work: pointer to the work_struct structure
*
* Detect the type of USB plugged
*/
static void ab8500_charger_usb_link_status_work(struct work_struct *work)
{
int ret;
struct ab8500_charger *di = container_of(work,
struct ab8500_charger, usb_link_status_work);
/*
* Since we can't be sure that the events are received
* synchronously, we have the check if is
* connected by reading the status register
*/
ret = ab8500_charger_detect_chargers(di);
if (ret < 0)
return;
if (!(ret & USB_PW_CONN)) {
di->vbus_detected = 0;
ab8500_charger_set_usb_connected(di, false);
ab8500_power_supply_changed(di, &di->usb_chg.psy);
} else {
di->vbus_detected = 1;
ret = ab8500_charger_read_usb_type(di);
if (!ret) {
/* Update maximum input current */
ret = ab8500_charger_set_vbus_in_curr(di,
di->max_usb_in_curr);
if (ret)
return;
ab8500_charger_set_usb_connected(di, true);
ab8500_power_supply_changed(di, &di->usb_chg.psy);
} else if (ret == -ENXIO) {
/* No valid charger type detected */
ab8500_charger_set_usb_connected(di, false);
ab8500_power_supply_changed(di, &di->usb_chg.psy);
}
}
}
static void ab8500_charger_usb_state_changed_work(struct work_struct *work)
{
int ret;
unsigned long flags;
struct ab8500_charger *di = container_of(work,
struct ab8500_charger, usb_state_changed_work);
if (!di->vbus_detected)
return;
spin_lock_irqsave(&di->usb_state.usb_lock, flags);
di->usb_state.usb_changed = false;
spin_unlock_irqrestore(&di->usb_state.usb_lock, flags);
/*
* wait for some time until you get updates from the usb stack
* and negotiations are completed
*/
msleep(250);
if (di->usb_state.usb_changed)
return;
dev_dbg(di->dev, "%s USB state: 0x%02x mA: %d\n",
__func__, di->usb_state.state, di->usb_state.usb_current);
switch (di->usb_state.state) {
case AB8500_BM_USB_STATE_RESET_HS:
case AB8500_BM_USB_STATE_RESET_FS:
case AB8500_BM_USB_STATE_SUSPEND:
case AB8500_BM_USB_STATE_MAX:
ab8500_charger_set_usb_connected(di, false);
ab8500_power_supply_changed(di, &di->usb_chg.psy);
break;
case AB8500_BM_USB_STATE_RESUME:
/*
* when suspend->resume there should be delay
* of 1sec for enabling charging
*/
msleep(1000);
/* Intentional fall through */
case AB8500_BM_USB_STATE_CONFIGURED:
/*
* USB is configured, enable charging with the charging
* input current obtained from USB driver
*/
if (!ab8500_charger_get_usb_cur(di)) {
/* Update maximum input current */
ret = ab8500_charger_set_vbus_in_curr(di,
di->max_usb_in_curr);
if (ret)
return;
ab8500_charger_set_usb_connected(di, true);
ab8500_power_supply_changed(di, &di->usb_chg.psy);
}
break;
default:
break;
};
}
/**
* ab8500_charger_check_usbchargernotok_work() - check USB chg not ok status
* @work: pointer to the work_struct structure
*
* Work queue function for checking the USB charger Not OK status
*/
static void ab8500_charger_check_usbchargernotok_work(struct work_struct *work)
{
int ret;
u8 reg_value;
bool prev_status;
struct ab8500_charger *di = container_of(work,
struct ab8500_charger, check_usbchgnotok_work.work);
/* Check if the status bit for usbchargernotok is still active */
ret = abx500_get_register_interruptible(di->dev,
AB8500_CHARGER, AB8500_CH_USBCH_STAT2_REG, ®_value);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return;
}
prev_status = di->flags.usbchargernotok;
if (reg_value & VBUS_CH_NOK) {
di->flags.usbchargernotok = true;
/* Check again in 1sec */
queue_delayed_work(di->charger_wq,
&di->check_usbchgnotok_work, HZ);
} else {
di->flags.usbchargernotok = false;
di->flags.vbus_collapse = false;
}
if (prev_status != di->flags.usbchargernotok)
ab8500_power_supply_changed(di, &di->usb_chg.psy);
}
/**
* ab8500_charger_check_main_thermal_prot_work() - check main thermal status
* @work: pointer to the work_struct structure
*
* Work queue function for checking the Main thermal prot status
*/
static void ab8500_charger_check_main_thermal_prot_work(
struct work_struct *work)
{
int ret;
u8 reg_value;
struct ab8500_charger *di = container_of(work,
struct ab8500_charger, check_main_thermal_prot_work);
/* Check if the status bit for main_thermal_prot is still active */
ret = abx500_get_register_interruptible(di->dev,
AB8500_CHARGER, AB8500_CH_STATUS2_REG, ®_value);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return;
}
if (reg_value & MAIN_CH_TH_PROT)
di->flags.main_thermal_prot = true;
else
di->flags.main_thermal_prot = false;
ab8500_power_supply_changed(di, &di->ac_chg.psy);
}
/**
* ab8500_charger_check_usb_thermal_prot_work() - check usb thermal status
* @work: pointer to the work_struct structure
*
* Work queue function for checking the USB thermal prot status
*/
static void ab8500_charger_check_usb_thermal_prot_work(
struct work_struct *work)
{
int ret;
u8 reg_value;
struct ab8500_charger *di = container_of(work,
struct ab8500_charger, check_usb_thermal_prot_work);
/* Check if the status bit for usb_thermal_prot is still active */
ret = abx500_get_register_interruptible(di->dev,
AB8500_CHARGER, AB8500_CH_USBCH_STAT2_REG, ®_value);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
return;
}
if (reg_value & USB_CH_TH_PROT)
di->flags.usb_thermal_prot = true;
else
di->flags.usb_thermal_prot = false;
ab8500_power_supply_changed(di, &di->usb_chg.psy);
}
/**
* ab8500_charger_mainchunplugdet_handler() - main charger unplugged
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_mainchunplugdet_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev, "Main charger unplugged\n");
queue_work(di->charger_wq, &di->ac_work);
return IRQ_HANDLED;
}
/**
* ab8500_charger_mainchplugdet_handler() - main charger plugged
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_mainchplugdet_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev, "Main charger plugged\n");
queue_work(di->charger_wq, &di->ac_work);
return IRQ_HANDLED;
}
/**
* ab8500_charger_mainextchnotok_handler() - main charger not ok
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_mainextchnotok_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev, "Main charger not ok\n");
di->flags.mainextchnotok = true;
ab8500_power_supply_changed(di, &di->ac_chg.psy);
/* Schedule a new HW failure check */
queue_delayed_work(di->charger_wq, &di->check_hw_failure_work, 0);
return IRQ_HANDLED;
}
/**
* ab8500_charger_mainchthprotr_handler() - Die temp is above main charger
* thermal protection threshold
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_mainchthprotr_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev,
"Die temp above Main charger thermal protection threshold\n");
queue_work(di->charger_wq, &di->check_main_thermal_prot_work);
return IRQ_HANDLED;
}
/**
* ab8500_charger_mainchthprotf_handler() - Die temp is below main charger
* thermal protection threshold
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_mainchthprotf_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev,
"Die temp ok for Main charger thermal protection threshold\n");
queue_work(di->charger_wq, &di->check_main_thermal_prot_work);
return IRQ_HANDLED;
}
/**
* ab8500_charger_vbusdetf_handler() - VBUS falling detected
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_vbusdetf_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev, "VBUS falling detected\n");
queue_work(di->charger_wq, &di->detect_usb_type_work);
return IRQ_HANDLED;
}
/**
* ab8500_charger_vbusdetr_handler() - VBUS rising detected
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_vbusdetr_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
di->vbus_detected = true;
dev_dbg(di->dev, "VBUS rising detected\n");
queue_work(di->charger_wq, &di->detect_usb_type_work);
return IRQ_HANDLED;
}
/**
* ab8500_charger_usblinkstatus_handler() - USB link status has changed
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_usblinkstatus_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev, "USB link status changed\n");
queue_work(di->charger_wq, &di->usb_link_status_work);
return IRQ_HANDLED;
}
/**
* ab8500_charger_usbchthprotr_handler() - Die temp is above usb charger
* thermal protection threshold
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_usbchthprotr_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev,
"Die temp above USB charger thermal protection threshold\n");
queue_work(di->charger_wq, &di->check_usb_thermal_prot_work);
return IRQ_HANDLED;
}
/**
* ab8500_charger_usbchthprotf_handler() - Die temp is below usb charger
* thermal protection threshold
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_usbchthprotf_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev,
"Die temp ok for USB charger thermal protection threshold\n");
queue_work(di->charger_wq, &di->check_usb_thermal_prot_work);
return IRQ_HANDLED;
}
/**
* ab8500_charger_usbchargernotokr_handler() - USB charger not ok detected
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_usbchargernotokr_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev, "Not allowed USB charger detected\n");
queue_delayed_work(di->charger_wq, &di->check_usbchgnotok_work, 0);
return IRQ_HANDLED;
}
/**
* ab8500_charger_chwdexp_handler() - Charger watchdog expired
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_chwdexp_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev, "Charger watchdog expired\n");
/*
* The charger that was online when the watchdog expired
* needs to be restarted for charging to start again
*/
if (di->ac.charger_online) {
di->ac.wd_expired = true;
ab8500_power_supply_changed(di, &di->ac_chg.psy);
}
if (di->usb.charger_online) {
di->usb.wd_expired = true;
ab8500_power_supply_changed(di, &di->usb_chg.psy);
}
return IRQ_HANDLED;
}
/**
* ab8500_charger_vbusovv_handler() - VBUS overvoltage detected
* @irq: interrupt number
* @_di: pointer to the ab8500_charger structure
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_charger_vbusovv_handler(int irq, void *_di)
{
struct ab8500_charger *di = _di;
dev_dbg(di->dev, "VBUS overvoltage detected\n");
di->flags.vbus_ovv = true;
ab8500_power_supply_changed(di, &di->usb_chg.psy);
/* Schedule a new HW failure check */
queue_delayed_work(di->charger_wq, &di->check_hw_failure_work, 0);
return IRQ_HANDLED;
}
/**
* ab8500_charger_ac_get_property() - get the ac/mains properties
* @psy: pointer to the power_supply structure
* @psp: pointer to the power_supply_property structure
* @val: pointer to the power_supply_propval union
*
* This function gets called when an application tries to get the ac/mains
* properties by reading the sysfs files.
* AC/Mains properties are online, present and voltage.
* online: ac/mains charging is in progress or not
* present: presence of the ac/mains
* voltage: AC/Mains voltage
* Returns error code in case of failure else 0(on success)
*/
static int ab8500_charger_ac_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct ab8500_charger *di;
di = to_ab8500_charger_ac_device_info(psy_to_ux500_charger(psy));
switch (psp) {
case POWER_SUPPLY_PROP_HEALTH:
if (di->flags.mainextchnotok)
val->intval = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE;
else if (di->ac.wd_expired || di->usb.wd_expired)
val->intval = POWER_SUPPLY_HEALTH_DEAD;
else if (di->flags.main_thermal_prot)
val->intval = POWER_SUPPLY_HEALTH_OVERHEAT;
else
val->intval = POWER_SUPPLY_HEALTH_GOOD;
break;
case POWER_SUPPLY_PROP_ONLINE:
val->intval = di->ac.charger_online;
break;
case POWER_SUPPLY_PROP_PRESENT:
val->intval = di->ac.charger_connected;
break;
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
di->ac.charger_voltage = ab8500_charger_get_ac_voltage(di);
val->intval = di->ac.charger_voltage * 1000;
break;
case POWER_SUPPLY_PROP_VOLTAGE_AVG:
/*
* This property is used to indicate when CV mode is entered
* for the AC charger
*/
di->ac.cv_active = ab8500_charger_ac_cv(di);
val->intval = di->ac.cv_active;
break;
case POWER_SUPPLY_PROP_CURRENT_NOW:
val->intval = ab8500_charger_get_ac_current(di) * 1000;
break;
default:
return -EINVAL;
}
return 0;
}
/**
* ab8500_charger_usb_get_property() - get the usb properties
* @psy: pointer to the power_supply structure
* @psp: pointer to the power_supply_property structure
* @val: pointer to the power_supply_propval union
*
* This function gets called when an application tries to get the usb
* properties by reading the sysfs files.
* USB properties are online, present and voltage.
* online: usb charging is in progress or not
* present: presence of the usb
* voltage: vbus voltage
* Returns error code in case of failure else 0(on success)
*/
static int ab8500_charger_usb_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct ab8500_charger *di;
di = to_ab8500_charger_usb_device_info(psy_to_ux500_charger(psy));
switch (psp) {
case POWER_SUPPLY_PROP_HEALTH:
if (di->flags.usbchargernotok)
val->intval = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE;
else if (di->ac.wd_expired || di->usb.wd_expired)
val->intval = POWER_SUPPLY_HEALTH_DEAD;
else if (di->flags.usb_thermal_prot)
val->intval = POWER_SUPPLY_HEALTH_OVERHEAT;
else if (di->flags.vbus_ovv)
val->intval = POWER_SUPPLY_HEALTH_OVERVOLTAGE;
else
val->intval = POWER_SUPPLY_HEALTH_GOOD;
break;
case POWER_SUPPLY_PROP_ONLINE:
val->intval = di->usb.charger_online;
break;
case POWER_SUPPLY_PROP_PRESENT:
val->intval = di->usb.charger_connected;
break;
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
di->usb.charger_voltage = ab8500_charger_get_vbus_voltage(di);
val->intval = di->usb.charger_voltage * 1000;
break;
case POWER_SUPPLY_PROP_VOLTAGE_AVG:
/*
* This property is used to indicate when CV mode is entered
* for the USB charger
*/
di->usb.cv_active = ab8500_charger_usb_cv(di);
val->intval = di->usb.cv_active;
break;
case POWER_SUPPLY_PROP_CURRENT_NOW:
val->intval = ab8500_charger_get_usb_current(di) * 1000;
break;
case POWER_SUPPLY_PROP_CURRENT_AVG:
/*
* This property is used to indicate when VBUS has collapsed
* due to too high output current from the USB charger
*/
if (di->flags.vbus_collapse)
val->intval = 1;
else
val->intval = 0;
break;
default:
return -EINVAL;
}
return 0;
}
/**
* ab8500_charger_init_hw_registers() - Set up charger related registers
* @di: pointer to the ab8500_charger structure
*
* Set up charger OVV, watchdog and maximum voltage registers as well as
* charging of the backup battery
*/
static int ab8500_charger_init_hw_registers(struct ab8500_charger *di)
{
int ret = 0;
/* Setup maximum charger current and voltage for ABB cut2.0 */
if (!is_ab8500_1p1_or_earlier(di->parent)) {
ret = abx500_set_register_interruptible(di->dev,
AB8500_CHARGER,
AB8500_CH_VOLT_LVL_MAX_REG, CH_VOL_LVL_4P6);
if (ret) {
dev_err(di->dev,
"failed to set CH_VOLT_LVL_MAX_REG\n");
goto out;
}
ret = abx500_set_register_interruptible(di->dev,
AB8500_CHARGER,
AB8500_CH_OPT_CRNTLVL_MAX_REG, CH_OP_CUR_LVL_1P6);
if (ret) {
dev_err(di->dev,
"failed to set CH_OPT_CRNTLVL_MAX_REG\n");
goto out;
}
}
/* VBUS OVV set to 6.3V and enable automatic current limitiation */
ret = abx500_set_register_interruptible(di->dev,
AB8500_CHARGER,
AB8500_USBCH_CTRL2_REG,
VBUS_OVV_SELECT_6P3V | VBUS_AUTO_IN_CURR_LIM_ENA);
if (ret) {
dev_err(di->dev, "failed to set VBUS OVV\n");
goto out;
}
/* Enable main watchdog in OTP */
ret = abx500_set_register_interruptible(di->dev,
AB8500_OTP_EMUL, AB8500_OTP_CONF_15, OTP_ENABLE_WD);
if (ret) {
dev_err(di->dev, "failed to enable main WD in OTP\n");
goto out;
}
/* Enable main watchdog */
ret = abx500_set_register_interruptible(di->dev,
AB8500_SYS_CTRL2_BLOCK,
AB8500_MAIN_WDOG_CTRL_REG, MAIN_WDOG_ENA);
if (ret) {
dev_err(di->dev, "faile to enable main watchdog\n");
goto out;
}
/*
* Due to internal synchronisation, Enable and Kick watchdog bits
* cannot be enabled in a single write.
* A minimum delay of 2*32 kHz period (62.5µs) must be inserted
* between writing Enable then Kick bits.
*/
udelay(63);
/* Kick main watchdog */
ret = abx500_set_register_interruptible(di->dev,
AB8500_SYS_CTRL2_BLOCK,
AB8500_MAIN_WDOG_CTRL_REG,
(MAIN_WDOG_ENA | MAIN_WDOG_KICK));
if (ret) {
dev_err(di->dev, "failed to kick main watchdog\n");
goto out;
}
/* Disable main watchdog */
ret = abx500_set_register_interruptible(di->dev,
AB8500_SYS_CTRL2_BLOCK,
AB8500_MAIN_WDOG_CTRL_REG, MAIN_WDOG_DIS);
if (ret) {
dev_err(di->dev, "failed to disable main watchdog\n");
goto out;
}
/* Set watchdog timeout */
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CH_WD_TIMER_REG, WD_TIMER);
if (ret) {
dev_err(di->dev, "failed to set charger watchdog timeout\n");
goto out;
}
/* Backup battery voltage and current */
ret = abx500_set_register_interruptible(di->dev,
AB8500_RTC,
AB8500_RTC_BACKUP_CHG_REG,
di->bat->bkup_bat_v |
di->bat->bkup_bat_i);
if (ret) {
dev_err(di->dev, "failed to setup backup battery charging\n");
goto out;
}
/* Enable backup battery charging */
abx500_mask_and_set_register_interruptible(di->dev,
AB8500_RTC, AB8500_RTC_CTRL_REG,
RTC_BUP_CH_ENA, RTC_BUP_CH_ENA);
if (ret < 0)
dev_err(di->dev, "%s mask and set failed\n", __func__);
out:
return ret;
}
/*
* ab8500 charger driver interrupts and their respective isr
*/
static struct ab8500_charger_interrupts ab8500_charger_irq[] = {
{"MAIN_CH_UNPLUG_DET", ab8500_charger_mainchunplugdet_handler},
{"MAIN_CHARGE_PLUG_DET", ab8500_charger_mainchplugdet_handler},
{"MAIN_EXT_CH_NOT_OK", ab8500_charger_mainextchnotok_handler},
{"MAIN_CH_TH_PROT_R", ab8500_charger_mainchthprotr_handler},
{"MAIN_CH_TH_PROT_F", ab8500_charger_mainchthprotf_handler},
{"VBUS_DET_F", ab8500_charger_vbusdetf_handler},
{"VBUS_DET_R", ab8500_charger_vbusdetr_handler},
{"USB_LINK_STATUS", ab8500_charger_usblinkstatus_handler},
{"USB_CH_TH_PROT_R", ab8500_charger_usbchthprotr_handler},
{"USB_CH_TH_PROT_F", ab8500_charger_usbchthprotf_handler},
{"USB_CHARGER_NOT_OKR", ab8500_charger_usbchargernotokr_handler},
{"VBUS_OVV", ab8500_charger_vbusovv_handler},
{"CH_WD_EXP", ab8500_charger_chwdexp_handler},
};
static int ab8500_charger_usb_notifier_call(struct notifier_block *nb,
unsigned long event, void *power)
{
struct ab8500_charger *di =
container_of(nb, struct ab8500_charger, nb);
enum ab8500_usb_state bm_usb_state;
unsigned mA = *((unsigned *)power);
if (event != USB_EVENT_VBUS) {
dev_dbg(di->dev, "not a standard host, returning\n");
return NOTIFY_DONE;
}
/* TODO: State is fabricate here. See if charger really needs USB
* state or if mA is enough
*/
if ((di->usb_state.usb_current == 2) && (mA > 2))
bm_usb_state = AB8500_BM_USB_STATE_RESUME;
else if (mA == 0)
bm_usb_state = AB8500_BM_USB_STATE_RESET_HS;
else if (mA == 2)
bm_usb_state = AB8500_BM_USB_STATE_SUSPEND;
else if (mA >= 8) /* 8, 100, 500 */
bm_usb_state = AB8500_BM_USB_STATE_CONFIGURED;
else /* Should never occur */
bm_usb_state = AB8500_BM_USB_STATE_RESET_FS;
dev_dbg(di->dev, "%s usb_state: 0x%02x mA: %d\n",
__func__, bm_usb_state, mA);
spin_lock(&di->usb_state.usb_lock);
di->usb_state.usb_changed = true;
spin_unlock(&di->usb_state.usb_lock);
di->usb_state.state = bm_usb_state;
di->usb_state.usb_current = mA;
queue_work(di->charger_wq, &di->usb_state_changed_work);
return NOTIFY_OK;
}
#if defined(CONFIG_PM)
static int ab8500_charger_resume(struct platform_device *pdev)
{
int ret;
struct ab8500_charger *di = platform_get_drvdata(pdev);
/*
* For ABB revision 1.0 and 1.1 there is a bug in the watchdog
* logic. That means we have to continously kick the charger
* watchdog even when no charger is connected. This is only
* valid once the AC charger has been enabled. This is
* a bug that is not handled by the algorithm and the
* watchdog have to be kicked by the charger driver
* when the AC charger is disabled
*/
if (di->ac_conn && is_ab8500_1p1_or_earlier(di->parent)) {
ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_CHARG_WD_CTRL, CHARG_WD_KICK);
if (ret)
dev_err(di->dev, "Failed to kick WD!\n");
/* If not already pending start a new timer */
if (!delayed_work_pending(
&di->kick_wd_work)) {
queue_delayed_work(di->charger_wq, &di->kick_wd_work,
round_jiffies(WD_KICK_INTERVAL));
}
}
/* If we still have a HW failure, schedule a new check */
if (di->flags.mainextchnotok || di->flags.vbus_ovv) {
queue_delayed_work(di->charger_wq,
&di->check_hw_failure_work, 0);
}
return 0;
}
static int ab8500_charger_suspend(struct platform_device *pdev,
pm_message_t state)
{
struct ab8500_charger *di = platform_get_drvdata(pdev);
/* Cancel any pending HW failure check */
if (delayed_work_pending(&di->check_hw_failure_work))
cancel_delayed_work(&di->check_hw_failure_work);
return 0;
}
#else
#define ab8500_charger_suspend NULL
#define ab8500_charger_resume NULL
#endif
static int __devexit ab8500_charger_remove(struct platform_device *pdev)
{
struct ab8500_charger *di = platform_get_drvdata(pdev);
int i, irq, ret;
/* Disable AC charging */
ab8500_charger_ac_en(&di->ac_chg, false, 0, 0);
/* Disable USB charging */
ab8500_charger_usb_en(&di->usb_chg, false, 0, 0);
/* Disable interrupts */
for (i = 0; i < ARRAY_SIZE(ab8500_charger_irq); i++) {
irq = platform_get_irq_byname(pdev, ab8500_charger_irq[i].name);
free_irq(irq, di);
}
/* disable the regulator */
regulator_put(di->regu);
/* Backup battery voltage and current disable */
ret = abx500_mask_and_set_register_interruptible(di->dev,
AB8500_RTC, AB8500_RTC_CTRL_REG, RTC_BUP_CH_ENA, 0);
if (ret < 0)
dev_err(di->dev, "%s mask and set failed\n", __func__);
usb_unregister_notifier(di->usb_phy, &di->nb);
usb_put_transceiver(di->usb_phy);
/* Delete the work queue */
destroy_workqueue(di->charger_wq);
flush_scheduled_work();
power_supply_unregister(&di->usb_chg.psy);
power_supply_unregister(&di->ac_chg.psy);
platform_set_drvdata(pdev, NULL);
kfree(di);
return 0;
}
static int __devinit ab8500_charger_probe(struct platform_device *pdev)
{
int irq, i, charger_status, ret = 0;
struct abx500_bm_plat_data *plat_data;
struct ab8500_charger *di =
kzalloc(sizeof(struct ab8500_charger), GFP_KERNEL);
if (!di)
return -ENOMEM;
/* get parent data */
di->dev = &pdev->dev;
di->parent = dev_get_drvdata(pdev->dev.parent);
di->gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
/* initialize lock */
spin_lock_init(&di->usb_state.usb_lock);
/* get charger specific platform data */
plat_data = pdev->dev.platform_data;
di->pdata = plat_data->charger;
if (!di->pdata) {
dev_err(di->dev, "no charger platform data supplied\n");
ret = -EINVAL;
goto free_device_info;
}
/* get battery specific platform data */
di->bat = plat_data->battery;
if (!di->bat) {
dev_err(di->dev, "no battery platform data supplied\n");
ret = -EINVAL;
goto free_device_info;
}
di->autopower = false;
/* AC supply */
/* power_supply base class */
di->ac_chg.psy.name = "ab8500_ac";
di->ac_chg.psy.type = POWER_SUPPLY_TYPE_MAINS;
di->ac_chg.psy.properties = ab8500_charger_ac_props;
di->ac_chg.psy.num_properties = ARRAY_SIZE(ab8500_charger_ac_props);
di->ac_chg.psy.get_property = ab8500_charger_ac_get_property;
di->ac_chg.psy.supplied_to = di->pdata->supplied_to;
di->ac_chg.psy.num_supplicants = di->pdata->num_supplicants;
/* ux500_charger sub-class */
di->ac_chg.ops.enable = &ab8500_charger_ac_en;
di->ac_chg.ops.kick_wd = &ab8500_charger_watchdog_kick;
di->ac_chg.ops.update_curr = &ab8500_charger_update_charger_current;
di->ac_chg.max_out_volt = ab8500_charger_voltage_map[
ARRAY_SIZE(ab8500_charger_voltage_map) - 1];
di->ac_chg.max_out_curr = ab8500_charger_current_map[
ARRAY_SIZE(ab8500_charger_current_map) - 1];
/* USB supply */
/* power_supply base class */
di->usb_chg.psy.name = "ab8500_usb";
di->usb_chg.psy.type = POWER_SUPPLY_TYPE_USB;
di->usb_chg.psy.properties = ab8500_charger_usb_props;
di->usb_chg.psy.num_properties = ARRAY_SIZE(ab8500_charger_usb_props);
di->usb_chg.psy.get_property = ab8500_charger_usb_get_property;
di->usb_chg.psy.supplied_to = di->pdata->supplied_to;
di->usb_chg.psy.num_supplicants = di->pdata->num_supplicants;
/* ux500_charger sub-class */
di->usb_chg.ops.enable = &ab8500_charger_usb_en;
di->usb_chg.ops.kick_wd = &ab8500_charger_watchdog_kick;
di->usb_chg.ops.update_curr = &ab8500_charger_update_charger_current;
di->usb_chg.max_out_volt = ab8500_charger_voltage_map[
ARRAY_SIZE(ab8500_charger_voltage_map) - 1];
di->usb_chg.max_out_curr = ab8500_charger_current_map[
ARRAY_SIZE(ab8500_charger_current_map) - 1];
/* Create a work queue for the charger */
di->charger_wq =
create_singlethread_workqueue("ab8500_charger_wq");
if (di->charger_wq == NULL) {
dev_err(di->dev, "failed to create work queue\n");
goto free_device_info;
}
/* Init work for HW failure check */
INIT_DELAYED_WORK_DEFERRABLE(&di->check_hw_failure_work,
ab8500_charger_check_hw_failure_work);
INIT_DELAYED_WORK_DEFERRABLE(&di->check_usbchgnotok_work,
ab8500_charger_check_usbchargernotok_work);
/*
* For ABB revision 1.0 and 1.1 there is a bug in the watchdog
* logic. That means we have to continously kick the charger
* watchdog even when no charger is connected. This is only
* valid once the AC charger has been enabled. This is
* a bug that is not handled by the algorithm and the
* watchdog have to be kicked by the charger driver
* when the AC charger is disabled
*/
INIT_DELAYED_WORK_DEFERRABLE(&di->kick_wd_work,
ab8500_charger_kick_watchdog_work);
INIT_DELAYED_WORK_DEFERRABLE(&di->check_vbat_work,
ab8500_charger_check_vbat_work);
/* Init work for charger detection */
INIT_WORK(&di->usb_link_status_work,
ab8500_charger_usb_link_status_work);
INIT_WORK(&di->ac_work, ab8500_charger_ac_work);
INIT_WORK(&di->detect_usb_type_work,
ab8500_charger_detect_usb_type_work);
INIT_WORK(&di->usb_state_changed_work,
ab8500_charger_usb_state_changed_work);
/* Init work for checking HW status */
INIT_WORK(&di->check_main_thermal_prot_work,
ab8500_charger_check_main_thermal_prot_work);
INIT_WORK(&di->check_usb_thermal_prot_work,
ab8500_charger_check_usb_thermal_prot_work);
/*
* VDD ADC supply needs to be enabled from this driver when there
* is a charger connected to avoid erroneous BTEMP_HIGH/LOW
* interrupts during charging
*/
di->regu = regulator_get(di->dev, "vddadc");
if (IS_ERR(di->regu)) {
ret = PTR_ERR(di->regu);
dev_err(di->dev, "failed to get vddadc regulator\n");
goto free_charger_wq;
}
/* Initialize OVV, and other registers */
ret = ab8500_charger_init_hw_registers(di);
if (ret) {
dev_err(di->dev, "failed to initialize ABB registers\n");
goto free_regulator;
}
/* Register AC charger class */
ret = power_supply_register(di->dev, &di->ac_chg.psy);
if (ret) {
dev_err(di->dev, "failed to register AC charger\n");
goto free_regulator;
}
/* Register USB charger class */
ret = power_supply_register(di->dev, &di->usb_chg.psy);
if (ret) {
dev_err(di->dev, "failed to register USB charger\n");
goto free_ac;
}
di->usb_phy = usb_get_transceiver();
if (!di->usb_phy) {
dev_err(di->dev, "failed to get usb transceiver\n");
ret = -EINVAL;
goto free_usb;
}
di->nb.notifier_call = ab8500_charger_usb_notifier_call;
ret = usb_register_notifier(di->usb_phy, &di->nb);
if (ret) {
dev_err(di->dev, "failed to register usb notifier\n");
goto put_usb_phy;
}
/* Identify the connected charger types during startup */
charger_status = ab8500_charger_detect_chargers(di);
if (charger_status & AC_PW_CONN) {
di->ac.charger_connected = 1;
di->ac_conn = true;
ab8500_power_supply_changed(di, &di->ac_chg.psy);
sysfs_notify(&di->ac_chg.psy.dev->kobj, NULL, "present");
}
if (charger_status & USB_PW_CONN) {
dev_dbg(di->dev, "VBUS Detect during startup\n");
di->vbus_detected = true;
di->vbus_detected_start = true;
queue_work(di->charger_wq,
&di->detect_usb_type_work);
}
/* Register interrupts */
for (i = 0; i < ARRAY_SIZE(ab8500_charger_irq); i++) {
irq = platform_get_irq_byname(pdev, ab8500_charger_irq[i].name);
ret = request_threaded_irq(irq, NULL, ab8500_charger_irq[i].isr,
IRQF_SHARED | IRQF_NO_SUSPEND,
ab8500_charger_irq[i].name, di);
if (ret != 0) {
dev_err(di->dev, "failed to request %s IRQ %d: %d\n"
, ab8500_charger_irq[i].name, irq, ret);
goto free_irq;
}
dev_dbg(di->dev, "Requested %s IRQ %d: %d\n",
ab8500_charger_irq[i].name, irq, ret);
}
platform_set_drvdata(pdev, di);
return ret;
free_irq:
usb_unregister_notifier(di->usb_phy, &di->nb);
/* We also have to free all successfully registered irqs */
for (i = i - 1; i >= 0; i--) {
irq = platform_get_irq_byname(pdev, ab8500_charger_irq[i].name);
free_irq(irq, di);
}
put_usb_phy:
usb_put_transceiver(di->usb_phy);
free_usb:
power_supply_unregister(&di->usb_chg.psy);
free_ac:
power_supply_unregister(&di->ac_chg.psy);
free_regulator:
regulator_put(di->regu);
free_charger_wq:
destroy_workqueue(di->charger_wq);
free_device_info:
kfree(di);
return ret;
}
static struct platform_driver ab8500_charger_driver = {
.probe = ab8500_charger_probe,
.remove = __devexit_p(ab8500_charger_remove),
.suspend = ab8500_charger_suspend,
.resume = ab8500_charger_resume,
.driver = {
.name = "ab8500-charger",
.owner = THIS_MODULE,
},
};
static int __init ab8500_charger_init(void)
{
return platform_driver_register(&ab8500_charger_driver);
}
static void __exit ab8500_charger_exit(void)
{
platform_driver_unregister(&ab8500_charger_driver);
}
subsys_initcall_sync(ab8500_charger_init);
module_exit(ab8500_charger_exit);
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Johan Palsson, Karl Komierowski, Arun R Murthy");
MODULE_ALIAS("platform:ab8500-charger");
MODULE_DESCRIPTION("AB8500 charger management driver");
| gpl-2.0 |
qiubing/vanet-linux-3.2.4 | arch/alpha/kernel/core_tsunami.c | 4741 | 13148 | /*
* linux/arch/alpha/kernel/core_tsunami.c
*
* Based on code written by David A. Rusling (david.rusling@reo.mts.dec.com).
*
* Code common to all TSUNAMI core logic chips.
*/
#define __EXTERN_INLINE inline
#include <asm/io.h>
#include <asm/core_tsunami.h>
#undef __EXTERN_INLINE
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/bootmem.h>
#include <asm/ptrace.h>
#include <asm/smp.h>
#include <asm/vga.h>
#include "proto.h"
#include "pci_impl.h"
/* Save Tsunami configuration data as the console had it set up. */
struct
{
unsigned long wsba[4];
unsigned long wsm[4];
unsigned long tba[4];
} saved_config[2] __attribute__((common));
/*
* NOTE: Herein lie back-to-back mb instructions. They are magic.
* One plausible explanation is that the I/O controller does not properly
* handle the system transaction. Another involves timing. Ho hum.
*/
/*
* BIOS32-style PCI interface:
*/
#define DEBUG_CONFIG 0
#if DEBUG_CONFIG
# define DBG_CFG(args) printk args
#else
# define DBG_CFG(args)
#endif
/*
* Given a bus, device, and function number, compute resulting
* configuration space address
* accordingly. It is therefore not safe to have concurrent
* invocations to configuration space access routines, but there
* really shouldn't be any need for this.
*
* Note that all config space accesses use Type 1 address format.
*
* Note also that type 1 is determined by non-zero bus number.
*
* Type 1:
*
* 3 3|3 3 2 2|2 2 2 2|2 2 2 2|1 1 1 1|1 1 1 1|1 1
* 3 2|1 0 9 8|7 6 5 4|3 2 1 0|9 8 7 6|5 4 3 2|1 0 9 8|7 6 5 4|3 2 1 0
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | | | | | | | | | | |B|B|B|B|B|B|B|B|D|D|D|D|D|F|F|F|R|R|R|R|R|R|0|1|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* 31:24 reserved
* 23:16 bus number (8 bits = 128 possible buses)
* 15:11 Device number (5 bits)
* 10:8 function number
* 7:2 register number
*
* Notes:
* The function number selects which function of a multi-function device
* (e.g., SCSI and Ethernet).
*
* The register selects a DWORD (32 bit) register offset. Hence it
* doesn't get shifted by 2 bits as we want to "drop" the bottom two
* bits.
*/
static int
mk_conf_addr(struct pci_bus *pbus, unsigned int device_fn, int where,
unsigned long *pci_addr, unsigned char *type1)
{
struct pci_controller *hose = pbus->sysdata;
unsigned long addr;
u8 bus = pbus->number;
DBG_CFG(("mk_conf_addr(bus=%d ,device_fn=0x%x, where=0x%x, "
"pci_addr=0x%p, type1=0x%p)\n",
bus, device_fn, where, pci_addr, type1));
if (!pbus->parent) /* No parent means peer PCI bus. */
bus = 0;
*type1 = (bus != 0);
addr = (bus << 16) | (device_fn << 8) | where;
addr |= hose->config_space_base;
*pci_addr = addr;
DBG_CFG(("mk_conf_addr: returning pci_addr 0x%lx\n", addr));
return 0;
}
static int
tsunami_read_config(struct pci_bus *bus, unsigned int devfn, int where,
int size, u32 *value)
{
unsigned long addr;
unsigned char type1;
if (mk_conf_addr(bus, devfn, where, &addr, &type1))
return PCIBIOS_DEVICE_NOT_FOUND;
switch (size) {
case 1:
*value = __kernel_ldbu(*(vucp)addr);
break;
case 2:
*value = __kernel_ldwu(*(vusp)addr);
break;
case 4:
*value = *(vuip)addr;
break;
}
return PCIBIOS_SUCCESSFUL;
}
static int
tsunami_write_config(struct pci_bus *bus, unsigned int devfn, int where,
int size, u32 value)
{
unsigned long addr;
unsigned char type1;
if (mk_conf_addr(bus, devfn, where, &addr, &type1))
return PCIBIOS_DEVICE_NOT_FOUND;
switch (size) {
case 1:
__kernel_stb(value, *(vucp)addr);
mb();
__kernel_ldbu(*(vucp)addr);
break;
case 2:
__kernel_stw(value, *(vusp)addr);
mb();
__kernel_ldwu(*(vusp)addr);
break;
case 4:
*(vuip)addr = value;
mb();
*(vuip)addr;
break;
}
return PCIBIOS_SUCCESSFUL;
}
struct pci_ops tsunami_pci_ops =
{
.read = tsunami_read_config,
.write = tsunami_write_config,
};
void
tsunami_pci_tbi(struct pci_controller *hose, dma_addr_t start, dma_addr_t end)
{
tsunami_pchip *pchip = hose->index ? TSUNAMI_pchip1 : TSUNAMI_pchip0;
volatile unsigned long *csr;
unsigned long value;
/* We can invalidate up to 8 tlb entries in a go. The flush
matches against <31:16> in the pci address. */
csr = &pchip->tlbia.csr;
if (((start ^ end) & 0xffff0000) == 0)
csr = &pchip->tlbiv.csr;
/* For TBIA, it doesn't matter what value we write. For TBI,
it's the shifted tag bits. */
value = (start & 0xffff0000) >> 12;
*csr = value;
mb();
*csr;
}
#ifdef NXM_MACHINE_CHECKS_ON_TSUNAMI
static long __init
tsunami_probe_read(volatile unsigned long *vaddr)
{
long dont_care, probe_result;
int cpu = smp_processor_id();
int s = swpipl(IPL_MCHECK - 1);
mcheck_taken(cpu) = 0;
mcheck_expected(cpu) = 1;
mb();
dont_care = *vaddr;
draina();
mcheck_expected(cpu) = 0;
probe_result = !mcheck_taken(cpu);
mcheck_taken(cpu) = 0;
setipl(s);
printk("dont_care == 0x%lx\n", dont_care);
return probe_result;
}
static long __init
tsunami_probe_write(volatile unsigned long *vaddr)
{
long true_contents, probe_result = 1;
TSUNAMI_cchip->misc.csr |= (1L << 28); /* clear NXM... */
true_contents = *vaddr;
*vaddr = 0;
draina();
if (TSUNAMI_cchip->misc.csr & (1L << 28)) {
int source = (TSUNAMI_cchip->misc.csr >> 29) & 7;
TSUNAMI_cchip->misc.csr |= (1L << 28); /* ...and unlock NXS. */
probe_result = 0;
printk("tsunami_probe_write: unit %d at 0x%016lx\n", source,
(unsigned long)vaddr);
}
if (probe_result)
*vaddr = true_contents;
return probe_result;
}
#else
#define tsunami_probe_read(ADDR) 1
#endif /* NXM_MACHINE_CHECKS_ON_TSUNAMI */
static void __init
tsunami_init_one_pchip(tsunami_pchip *pchip, int index)
{
struct pci_controller *hose;
if (tsunami_probe_read(&pchip->pctl.csr) == 0)
return;
hose = alloc_pci_controller();
if (index == 0)
pci_isa_hose = hose;
hose->io_space = alloc_resource();
hose->mem_space = alloc_resource();
/* This is for userland consumption. For some reason, the 40-bit
PIO bias that we use in the kernel through KSEG didn't work for
the page table based user mappings. So make sure we get the
43-bit PIO bias. */
hose->sparse_mem_base = 0;
hose->sparse_io_base = 0;
hose->dense_mem_base
= (TSUNAMI_MEM(index) & 0xffffffffffL) | 0x80000000000L;
hose->dense_io_base
= (TSUNAMI_IO(index) & 0xffffffffffL) | 0x80000000000L;
hose->config_space_base = TSUNAMI_CONF(index);
hose->index = index;
hose->io_space->start = TSUNAMI_IO(index) - TSUNAMI_IO_BIAS;
hose->io_space->end = hose->io_space->start + TSUNAMI_IO_SPACE - 1;
hose->io_space->name = pci_io_names[index];
hose->io_space->flags = IORESOURCE_IO;
hose->mem_space->start = TSUNAMI_MEM(index) - TSUNAMI_MEM_BIAS;
hose->mem_space->end = hose->mem_space->start + 0xffffffff;
hose->mem_space->name = pci_mem_names[index];
hose->mem_space->flags = IORESOURCE_MEM;
if (request_resource(&ioport_resource, hose->io_space) < 0)
printk(KERN_ERR "Failed to request IO on hose %d\n", index);
if (request_resource(&iomem_resource, hose->mem_space) < 0)
printk(KERN_ERR "Failed to request MEM on hose %d\n", index);
/*
* Save the existing PCI window translations. SRM will
* need them when we go to reboot.
*/
saved_config[index].wsba[0] = pchip->wsba[0].csr;
saved_config[index].wsm[0] = pchip->wsm[0].csr;
saved_config[index].tba[0] = pchip->tba[0].csr;
saved_config[index].wsba[1] = pchip->wsba[1].csr;
saved_config[index].wsm[1] = pchip->wsm[1].csr;
saved_config[index].tba[1] = pchip->tba[1].csr;
saved_config[index].wsba[2] = pchip->wsba[2].csr;
saved_config[index].wsm[2] = pchip->wsm[2].csr;
saved_config[index].tba[2] = pchip->tba[2].csr;
saved_config[index].wsba[3] = pchip->wsba[3].csr;
saved_config[index].wsm[3] = pchip->wsm[3].csr;
saved_config[index].tba[3] = pchip->tba[3].csr;
/*
* Set up the PCI to main memory translation windows.
*
* Note: Window 3 is scatter-gather only
*
* Window 0 is scatter-gather 8MB at 8MB (for isa)
* Window 1 is scatter-gather (up to) 1GB at 1GB
* Window 2 is direct access 2GB at 2GB
*
* NOTE: we need the align_entry settings for Acer devices on ES40,
* specifically floppy and IDE when memory is larger than 2GB.
*/
hose->sg_isa = iommu_arena_new(hose, 0x00800000, 0x00800000, 0);
/* Initially set for 4 PTEs, but will be overridden to 64K for ISA. */
hose->sg_isa->align_entry = 4;
hose->sg_pci = iommu_arena_new(hose, 0x40000000,
size_for_memory(0x40000000), 0);
hose->sg_pci->align_entry = 4; /* Tsunami caches 4 PTEs at a time */
__direct_map_base = 0x80000000;
__direct_map_size = 0x80000000;
pchip->wsba[0].csr = hose->sg_isa->dma_base | 3;
pchip->wsm[0].csr = (hose->sg_isa->size - 1) & 0xfff00000;
pchip->tba[0].csr = virt_to_phys(hose->sg_isa->ptes);
pchip->wsba[1].csr = hose->sg_pci->dma_base | 3;
pchip->wsm[1].csr = (hose->sg_pci->size - 1) & 0xfff00000;
pchip->tba[1].csr = virt_to_phys(hose->sg_pci->ptes);
pchip->wsba[2].csr = 0x80000000 | 1;
pchip->wsm[2].csr = (0x80000000 - 1) & 0xfff00000;
pchip->tba[2].csr = 0;
pchip->wsba[3].csr = 0;
/* Enable the Monster Window to make DAC pci64 possible. */
pchip->pctl.csr |= pctl_m_mwin;
tsunami_pci_tbi(hose, 0, -1);
}
void __iomem *
tsunami_ioportmap(unsigned long addr)
{
FIXUP_IOADDR_VGA(addr);
return (void __iomem *)(addr + TSUNAMI_IO_BIAS);
}
void __iomem *
tsunami_ioremap(unsigned long addr, unsigned long size)
{
FIXUP_MEMADDR_VGA(addr);
return (void __iomem *)(addr + TSUNAMI_MEM_BIAS);
}
#ifndef CONFIG_ALPHA_GENERIC
EXPORT_SYMBOL(tsunami_ioportmap);
EXPORT_SYMBOL(tsunami_ioremap);
#endif
void __init
tsunami_init_arch(void)
{
#ifdef NXM_MACHINE_CHECKS_ON_TSUNAMI
unsigned long tmp;
/* Ho hum.. init_arch is called before init_IRQ, but we need to be
able to handle machine checks. So install the handler now. */
wrent(entInt, 0);
/* NXMs just don't matter to Tsunami--unless they make it
choke completely. */
tmp = (unsigned long)(TSUNAMI_cchip - 1);
printk("%s: probing bogus address: 0x%016lx\n", __func__, bogus_addr);
printk("\tprobe %s\n",
tsunami_probe_write((unsigned long *)bogus_addr)
? "succeeded" : "failed");
#endif /* NXM_MACHINE_CHECKS_ON_TSUNAMI */
#if 0
printk("%s: CChip registers:\n", __func__);
printk("%s: CSR_CSC 0x%lx\n", __func__, TSUNAMI_cchip->csc.csr);
printk("%s: CSR_MTR 0x%lx\n", __func__, TSUNAMI_cchip.mtr.csr);
printk("%s: CSR_MISC 0x%lx\n", __func__, TSUNAMI_cchip->misc.csr);
printk("%s: CSR_DIM0 0x%lx\n", __func__, TSUNAMI_cchip->dim0.csr);
printk("%s: CSR_DIM1 0x%lx\n", __func__, TSUNAMI_cchip->dim1.csr);
printk("%s: CSR_DIR0 0x%lx\n", __func__, TSUNAMI_cchip->dir0.csr);
printk("%s: CSR_DIR1 0x%lx\n", __func__, TSUNAMI_cchip->dir1.csr);
printk("%s: CSR_DRIR 0x%lx\n", __func__, TSUNAMI_cchip->drir.csr);
printk("%s: DChip registers:\n");
printk("%s: CSR_DSC 0x%lx\n", __func__, TSUNAMI_dchip->dsc.csr);
printk("%s: CSR_STR 0x%lx\n", __func__, TSUNAMI_dchip->str.csr);
printk("%s: CSR_DREV 0x%lx\n", __func__, TSUNAMI_dchip->drev.csr);
#endif
/* With multiple PCI busses, we play with I/O as physical addrs. */
ioport_resource.end = ~0UL;
/* Find how many hoses we have, and initialize them. TSUNAMI
and TYPHOON can have 2, but might only have 1 (DS10). */
tsunami_init_one_pchip(TSUNAMI_pchip0, 0);
if (TSUNAMI_cchip->csc.csr & 1L<<14)
tsunami_init_one_pchip(TSUNAMI_pchip1, 1);
/* Check for graphic console location (if any). */
find_console_vga_hose();
}
static void
tsunami_kill_one_pchip(tsunami_pchip *pchip, int index)
{
pchip->wsba[0].csr = saved_config[index].wsba[0];
pchip->wsm[0].csr = saved_config[index].wsm[0];
pchip->tba[0].csr = saved_config[index].tba[0];
pchip->wsba[1].csr = saved_config[index].wsba[1];
pchip->wsm[1].csr = saved_config[index].wsm[1];
pchip->tba[1].csr = saved_config[index].tba[1];
pchip->wsba[2].csr = saved_config[index].wsba[2];
pchip->wsm[2].csr = saved_config[index].wsm[2];
pchip->tba[2].csr = saved_config[index].tba[2];
pchip->wsba[3].csr = saved_config[index].wsba[3];
pchip->wsm[3].csr = saved_config[index].wsm[3];
pchip->tba[3].csr = saved_config[index].tba[3];
}
void
tsunami_kill_arch(int mode)
{
tsunami_kill_one_pchip(TSUNAMI_pchip0, 0);
if (TSUNAMI_cchip->csc.csr & 1L<<14)
tsunami_kill_one_pchip(TSUNAMI_pchip1, 1);
}
static inline void
tsunami_pci_clr_err_1(tsunami_pchip *pchip)
{
pchip->perror.csr;
pchip->perror.csr = 0x040;
mb();
pchip->perror.csr;
}
static inline void
tsunami_pci_clr_err(void)
{
tsunami_pci_clr_err_1(TSUNAMI_pchip0);
/* TSUNAMI and TYPHOON can have 2, but might only have 1 (DS10) */
if (TSUNAMI_cchip->csc.csr & 1L<<14)
tsunami_pci_clr_err_1(TSUNAMI_pchip1);
}
void
tsunami_machine_check(unsigned long vector, unsigned long la_ptr)
{
/* Clear error before any reporting. */
mb();
mb(); /* magic */
draina();
tsunami_pci_clr_err();
wrmces(0x7);
mb();
process_mcheck_info(vector, la_ptr, "TSUNAMI",
mcheck_expected(smp_processor_id()));
}
| gpl-2.0 |
SamsungGalaxyS6/Hacker_Kernel_SM-G92X | drivers/net/wireless/rtlwifi/rtl8192cu/phy.c | 7557 | 18741 | /******************************************************************************
*
* Copyright(c) 2009-2012 Realtek Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <wlanfae@realtek.com>
* Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park,
* Hsinchu 300, Taiwan.
*
* Larry Finger <Larry.Finger@lwfinger.net>
*
*****************************************************************************/
#include "../wifi.h"
#include "../pci.h"
#include "../ps.h"
#include "reg.h"
#include "def.h"
#include "phy.h"
#include "rf.h"
#include "dm.h"
#include "table.h"
u32 rtl92cu_phy_query_rf_reg(struct ieee80211_hw *hw,
enum radio_path rfpath, u32 regaddr, u32 bitmask)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u32 original_value, readback_value, bitshift;
struct rtl_phy *rtlphy = &(rtlpriv->phy);
RT_TRACE(rtlpriv, COMP_RF, DBG_TRACE,
"regaddr(%#x), rfpath(%#x), bitmask(%#x)\n",
regaddr, rfpath, bitmask);
if (rtlphy->rf_mode != RF_OP_BY_FW) {
original_value = _rtl92c_phy_rf_serial_read(hw,
rfpath, regaddr);
} else {
original_value = _rtl92c_phy_fw_rf_serial_read(hw,
rfpath, regaddr);
}
bitshift = _rtl92c_phy_calculate_bit_shift(bitmask);
readback_value = (original_value & bitmask) >> bitshift;
RT_TRACE(rtlpriv, COMP_RF, DBG_TRACE,
"regaddr(%#x), rfpath(%#x), bitmask(%#x), original_value(%#x)\n",
regaddr, rfpath, bitmask, original_value);
return readback_value;
}
void rtl92cu_phy_set_rf_reg(struct ieee80211_hw *hw,
enum radio_path rfpath,
u32 regaddr, u32 bitmask, u32 data)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
u32 original_value, bitshift;
RT_TRACE(rtlpriv, COMP_RF, DBG_TRACE,
"regaddr(%#x), bitmask(%#x), data(%#x), rfpath(%#x)\n",
regaddr, bitmask, data, rfpath);
if (rtlphy->rf_mode != RF_OP_BY_FW) {
if (bitmask != RFREG_OFFSET_MASK) {
original_value = _rtl92c_phy_rf_serial_read(hw,
rfpath,
regaddr);
bitshift = _rtl92c_phy_calculate_bit_shift(bitmask);
data =
((original_value & (~bitmask)) |
(data << bitshift));
}
_rtl92c_phy_rf_serial_write(hw, rfpath, regaddr, data);
} else {
if (bitmask != RFREG_OFFSET_MASK) {
original_value = _rtl92c_phy_fw_rf_serial_read(hw,
rfpath,
regaddr);
bitshift = _rtl92c_phy_calculate_bit_shift(bitmask);
data =
((original_value & (~bitmask)) |
(data << bitshift));
}
_rtl92c_phy_fw_rf_serial_write(hw, rfpath, regaddr, data);
}
RT_TRACE(rtlpriv, COMP_RF, DBG_TRACE,
"regaddr(%#x), bitmask(%#x), data(%#x), rfpath(%#x)\n",
regaddr, bitmask, data, rfpath);
}
bool rtl92cu_phy_mac_config(struct ieee80211_hw *hw)
{
bool rtstatus;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
bool is92c = IS_92C_SERIAL(rtlhal->version);
rtstatus = _rtl92cu_phy_config_mac_with_headerfile(hw);
if (is92c && IS_HARDWARE_TYPE_8192CE(rtlhal))
rtl_write_byte(rtlpriv, 0x14, 0x71);
return rtstatus;
}
bool rtl92cu_phy_bb_config(struct ieee80211_hw *hw)
{
bool rtstatus = true;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
u16 regval;
u8 b_reg_hwparafile = 1;
_rtl92c_phy_init_bb_rf_register_definition(hw);
regval = rtl_read_word(rtlpriv, REG_SYS_FUNC_EN);
rtl_write_word(rtlpriv, REG_SYS_FUNC_EN, regval | BIT(13) |
BIT(0) | BIT(1));
rtl_write_byte(rtlpriv, REG_AFE_PLL_CTRL, 0x83);
rtl_write_byte(rtlpriv, REG_AFE_PLL_CTRL + 1, 0xdb);
rtl_write_byte(rtlpriv, REG_RF_CTRL, RF_EN | RF_RSTB | RF_SDMRSTB);
if (IS_HARDWARE_TYPE_8192CE(rtlhal)) {
rtl_write_byte(rtlpriv, REG_SYS_FUNC_EN, FEN_PPLL | FEN_PCIEA |
FEN_DIO_PCIE | FEN_BB_GLB_RSTn | FEN_BBRSTB);
} else if (IS_HARDWARE_TYPE_8192CU(rtlhal)) {
rtl_write_byte(rtlpriv, REG_SYS_FUNC_EN, FEN_USBA | FEN_USBD |
FEN_BB_GLB_RSTn | FEN_BBRSTB);
rtl_write_byte(rtlpriv, REG_LDOHCI12_CTRL, 0x0f);
}
rtl_write_byte(rtlpriv, REG_AFE_XTAL_CTRL + 1, 0x80);
if (b_reg_hwparafile == 1)
rtstatus = _rtl92c_phy_bb8192c_config_parafile(hw);
return rtstatus;
}
bool _rtl92cu_phy_config_mac_with_headerfile(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
u32 i;
u32 arraylength;
u32 *ptrarray;
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE, "Read Rtl819XMACPHY_Array\n");
arraylength = rtlphy->hwparam_tables[MAC_REG].length ;
ptrarray = rtlphy->hwparam_tables[MAC_REG].pdata;
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE, "Img:RTL8192CEMAC_2T_ARRAY\n");
for (i = 0; i < arraylength; i = i + 2)
rtl_write_byte(rtlpriv, ptrarray[i], (u8) ptrarray[i + 1]);
return true;
}
bool _rtl92cu_phy_config_bb_with_headerfile(struct ieee80211_hw *hw,
u8 configtype)
{
int i;
u32 *phy_regarray_table;
u32 *agctab_array_table;
u16 phy_reg_arraylen, agctab_arraylen;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_phy *rtlphy = &(rtlpriv->phy);
if (IS_92C_SERIAL(rtlhal->version)) {
agctab_arraylen = rtlphy->hwparam_tables[AGCTAB_2T].length;
agctab_array_table = rtlphy->hwparam_tables[AGCTAB_2T].pdata;
phy_reg_arraylen = rtlphy->hwparam_tables[PHY_REG_2T].length;
phy_regarray_table = rtlphy->hwparam_tables[PHY_REG_2T].pdata;
} else {
agctab_arraylen = rtlphy->hwparam_tables[AGCTAB_1T].length;
agctab_array_table = rtlphy->hwparam_tables[AGCTAB_1T].pdata;
phy_reg_arraylen = rtlphy->hwparam_tables[PHY_REG_1T].length;
phy_regarray_table = rtlphy->hwparam_tables[PHY_REG_1T].pdata;
}
if (configtype == BASEBAND_CONFIG_PHY_REG) {
for (i = 0; i < phy_reg_arraylen; i = i + 2) {
if (phy_regarray_table[i] == 0xfe)
mdelay(50);
else if (phy_regarray_table[i] == 0xfd)
mdelay(5);
else if (phy_regarray_table[i] == 0xfc)
mdelay(1);
else if (phy_regarray_table[i] == 0xfb)
udelay(50);
else if (phy_regarray_table[i] == 0xfa)
udelay(5);
else if (phy_regarray_table[i] == 0xf9)
udelay(1);
rtl_set_bbreg(hw, phy_regarray_table[i], MASKDWORD,
phy_regarray_table[i + 1]);
udelay(1);
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"The phy_regarray_table[0] is %x Rtl819XPHY_REGArray[1] is %x\n",
phy_regarray_table[i],
phy_regarray_table[i + 1]);
}
} else if (configtype == BASEBAND_CONFIG_AGC_TAB) {
for (i = 0; i < agctab_arraylen; i = i + 2) {
rtl_set_bbreg(hw, agctab_array_table[i], MASKDWORD,
agctab_array_table[i + 1]);
udelay(1);
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"The agctab_array_table[0] is %x Rtl819XPHY_REGArray[1] is %x\n",
agctab_array_table[i],
agctab_array_table[i + 1]);
}
}
return true;
}
bool _rtl92cu_phy_config_bb_with_pgheaderfile(struct ieee80211_hw *hw,
u8 configtype)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
int i;
u32 *phy_regarray_table_pg;
u16 phy_regarray_pg_len;
rtlphy->pwrgroup_cnt = 0;
phy_regarray_pg_len = rtlphy->hwparam_tables[PHY_REG_PG].length;
phy_regarray_table_pg = rtlphy->hwparam_tables[PHY_REG_PG].pdata;
if (configtype == BASEBAND_CONFIG_PHY_REG) {
for (i = 0; i < phy_regarray_pg_len; i = i + 3) {
if (phy_regarray_table_pg[i] == 0xfe)
mdelay(50);
else if (phy_regarray_table_pg[i] == 0xfd)
mdelay(5);
else if (phy_regarray_table_pg[i] == 0xfc)
mdelay(1);
else if (phy_regarray_table_pg[i] == 0xfb)
udelay(50);
else if (phy_regarray_table_pg[i] == 0xfa)
udelay(5);
else if (phy_regarray_table_pg[i] == 0xf9)
udelay(1);
_rtl92c_store_pwrIndex_diffrate_offset(hw,
phy_regarray_table_pg[i],
phy_regarray_table_pg[i + 1],
phy_regarray_table_pg[i + 2]);
}
} else {
RT_TRACE(rtlpriv, COMP_SEND, DBG_TRACE,
"configtype != BaseBand_Config_PHY_REG\n");
}
return true;
}
bool rtl92cu_phy_config_rf_with_headerfile(struct ieee80211_hw *hw,
enum radio_path rfpath)
{
int i;
u32 *radioa_array_table;
u32 *radiob_array_table;
u16 radioa_arraylen, radiob_arraylen;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_phy *rtlphy = &(rtlpriv->phy);
if (IS_92C_SERIAL(rtlhal->version)) {
radioa_arraylen = rtlphy->hwparam_tables[RADIOA_2T].length;
radioa_array_table = rtlphy->hwparam_tables[RADIOA_2T].pdata;
radiob_arraylen = rtlphy->hwparam_tables[RADIOB_2T].length;
radiob_array_table = rtlphy->hwparam_tables[RADIOB_2T].pdata;
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"Radio_A:RTL8192CERADIOA_2TARRAY\n");
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"Radio_B:RTL8192CE_RADIOB_2TARRAY\n");
} else {
radioa_arraylen = rtlphy->hwparam_tables[RADIOA_1T].length;
radioa_array_table = rtlphy->hwparam_tables[RADIOA_1T].pdata;
radiob_arraylen = rtlphy->hwparam_tables[RADIOB_1T].length;
radiob_array_table = rtlphy->hwparam_tables[RADIOB_1T].pdata;
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"Radio_A:RTL8192CE_RADIOA_1TARRAY\n");
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"Radio_B:RTL8192CE_RADIOB_1TARRAY\n");
}
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE, "Radio No %x\n", rfpath);
switch (rfpath) {
case RF90_PATH_A:
for (i = 0; i < radioa_arraylen; i = i + 2) {
if (radioa_array_table[i] == 0xfe)
mdelay(50);
else if (radioa_array_table[i] == 0xfd)
mdelay(5);
else if (radioa_array_table[i] == 0xfc)
mdelay(1);
else if (radioa_array_table[i] == 0xfb)
udelay(50);
else if (radioa_array_table[i] == 0xfa)
udelay(5);
else if (radioa_array_table[i] == 0xf9)
udelay(1);
else {
rtl_set_rfreg(hw, rfpath, radioa_array_table[i],
RFREG_OFFSET_MASK,
radioa_array_table[i + 1]);
udelay(1);
}
}
break;
case RF90_PATH_B:
for (i = 0; i < radiob_arraylen; i = i + 2) {
if (radiob_array_table[i] == 0xfe) {
mdelay(50);
} else if (radiob_array_table[i] == 0xfd)
mdelay(5);
else if (radiob_array_table[i] == 0xfc)
mdelay(1);
else if (radiob_array_table[i] == 0xfb)
udelay(50);
else if (radiob_array_table[i] == 0xfa)
udelay(5);
else if (radiob_array_table[i] == 0xf9)
udelay(1);
else {
rtl_set_rfreg(hw, rfpath, radiob_array_table[i],
RFREG_OFFSET_MASK,
radiob_array_table[i + 1]);
udelay(1);
}
}
break;
case RF90_PATH_C:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"switch case not processed\n");
break;
case RF90_PATH_D:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"switch case not processed\n");
break;
}
return true;
}
void rtl92cu_phy_set_bw_mode_callback(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_phy *rtlphy = &(rtlpriv->phy);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
u8 reg_bw_opmode;
u8 reg_prsr_rsc;
RT_TRACE(rtlpriv, COMP_SCAN, DBG_TRACE, "Switch to %s bandwidth\n",
rtlphy->current_chan_bw == HT_CHANNEL_WIDTH_20 ?
"20MHz" : "40MHz");
if (is_hal_stop(rtlhal)) {
rtlphy->set_bwmode_inprogress = false;
return;
}
reg_bw_opmode = rtl_read_byte(rtlpriv, REG_BWOPMODE);
reg_prsr_rsc = rtl_read_byte(rtlpriv, REG_RRSR + 2);
switch (rtlphy->current_chan_bw) {
case HT_CHANNEL_WIDTH_20:
reg_bw_opmode |= BW_OPMODE_20MHZ;
rtl_write_byte(rtlpriv, REG_BWOPMODE, reg_bw_opmode);
break;
case HT_CHANNEL_WIDTH_20_40:
reg_bw_opmode &= ~BW_OPMODE_20MHZ;
rtl_write_byte(rtlpriv, REG_BWOPMODE, reg_bw_opmode);
reg_prsr_rsc =
(reg_prsr_rsc & 0x90) | (mac->cur_40_prime_sc << 5);
rtl_write_byte(rtlpriv, REG_RRSR + 2, reg_prsr_rsc);
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"unknown bandwidth: %#X\n", rtlphy->current_chan_bw);
break;
}
switch (rtlphy->current_chan_bw) {
case HT_CHANNEL_WIDTH_20:
rtl_set_bbreg(hw, RFPGA0_RFMOD, BRFMOD, 0x0);
rtl_set_bbreg(hw, RFPGA1_RFMOD, BRFMOD, 0x0);
rtl_set_bbreg(hw, RFPGA0_ANALOGPARAMETER2, BIT(10), 1);
break;
case HT_CHANNEL_WIDTH_20_40:
rtl_set_bbreg(hw, RFPGA0_RFMOD, BRFMOD, 0x1);
rtl_set_bbreg(hw, RFPGA1_RFMOD, BRFMOD, 0x1);
rtl_set_bbreg(hw, RCCK0_SYSTEM, BCCK_SIDEBAND,
(mac->cur_40_prime_sc >> 1));
rtl_set_bbreg(hw, ROFDM1_LSTF, 0xC00, mac->cur_40_prime_sc);
rtl_set_bbreg(hw, RFPGA0_ANALOGPARAMETER2, BIT(10), 0);
rtl_set_bbreg(hw, 0x818, (BIT(26) | BIT(27)),
(mac->cur_40_prime_sc ==
HAL_PRIME_CHNL_OFFSET_LOWER) ? 2 : 1);
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"unknown bandwidth: %#X\n", rtlphy->current_chan_bw);
break;
}
rtl92cu_phy_rf6052_set_bandwidth(hw, rtlphy->current_chan_bw);
rtlphy->set_bwmode_inprogress = false;
RT_TRACE(rtlpriv, COMP_SCAN, DBG_TRACE, "<==\n");
}
void rtl92cu_bb_block_on(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
mutex_lock(&rtlpriv->io.bb_mutex);
rtl_set_bbreg(hw, RFPGA0_RFMOD, BCCKEN, 0x1);
rtl_set_bbreg(hw, RFPGA0_RFMOD, BOFDMEN, 0x1);
mutex_unlock(&rtlpriv->io.bb_mutex);
}
void _rtl92cu_phy_lc_calibrate(struct ieee80211_hw *hw, bool is2t)
{
u8 tmpreg;
u32 rf_a_mode = 0, rf_b_mode = 0, lc_cal;
struct rtl_priv *rtlpriv = rtl_priv(hw);
tmpreg = rtl_read_byte(rtlpriv, 0xd03);
if ((tmpreg & 0x70) != 0)
rtl_write_byte(rtlpriv, 0xd03, tmpreg & 0x8F);
else
rtl_write_byte(rtlpriv, REG_TXPAUSE, 0xFF);
if ((tmpreg & 0x70) != 0) {
rf_a_mode = rtl_get_rfreg(hw, RF90_PATH_A, 0x00, MASK12BITS);
if (is2t)
rf_b_mode = rtl_get_rfreg(hw, RF90_PATH_B, 0x00,
MASK12BITS);
rtl_set_rfreg(hw, RF90_PATH_A, 0x00, MASK12BITS,
(rf_a_mode & 0x8FFFF) | 0x10000);
if (is2t)
rtl_set_rfreg(hw, RF90_PATH_B, 0x00, MASK12BITS,
(rf_b_mode & 0x8FFFF) | 0x10000);
}
lc_cal = rtl_get_rfreg(hw, RF90_PATH_A, 0x18, MASK12BITS);
rtl_set_rfreg(hw, RF90_PATH_A, 0x18, MASK12BITS, lc_cal | 0x08000);
mdelay(100);
if ((tmpreg & 0x70) != 0) {
rtl_write_byte(rtlpriv, 0xd03, tmpreg);
rtl_set_rfreg(hw, RF90_PATH_A, 0x00, MASK12BITS, rf_a_mode);
if (is2t)
rtl_set_rfreg(hw, RF90_PATH_B, 0x00, MASK12BITS,
rf_b_mode);
} else {
rtl_write_byte(rtlpriv, REG_TXPAUSE, 0x00);
}
}
static bool _rtl92cu_phy_set_rf_power_state(struct ieee80211_hw *hw,
enum rf_pwrstate rfpwr_state)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
bool bresult = true;
u8 i, queue_id;
struct rtl8192_tx_ring *ring = NULL;
switch (rfpwr_state) {
case ERFON:
if ((ppsc->rfpwr_state == ERFOFF) &&
RT_IN_PS_LEVEL(ppsc, RT_RF_OFF_LEVL_HALT_NIC)) {
bool rtstatus;
u32 InitializeCount = 0;
do {
InitializeCount++;
RT_TRACE(rtlpriv, COMP_RF, DBG_DMESG,
"IPS Set eRf nic enable\n");
rtstatus = rtl_ps_enable_nic(hw);
} while (!rtstatus && (InitializeCount < 10));
RT_CLEAR_PS_LEVEL(ppsc,
RT_RF_OFF_LEVL_HALT_NIC);
} else {
RT_TRACE(rtlpriv, COMP_RF, DBG_DMESG,
"Set ERFON sleeped:%d ms\n",
jiffies_to_msecs(jiffies -
ppsc->last_sleep_jiffies));
ppsc->last_awake_jiffies = jiffies;
rtl92ce_phy_set_rf_on(hw);
}
if (mac->link_state == MAC80211_LINKED) {
rtlpriv->cfg->ops->led_control(hw,
LED_CTL_LINK);
} else {
rtlpriv->cfg->ops->led_control(hw,
LED_CTL_NO_LINK);
}
break;
case ERFOFF:
for (queue_id = 0, i = 0;
queue_id < RTL_PCI_MAX_TX_QUEUE_COUNT;) {
ring = &pcipriv->dev.tx_ring[queue_id];
if (skb_queue_len(&ring->queue) == 0 ||
queue_id == BEACON_QUEUE) {
queue_id++;
continue;
} else {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"eRf Off/Sleep: %d times TcbBusyQueue[%d] =%d before doze!\n",
i + 1,
queue_id,
skb_queue_len(&ring->queue));
udelay(10);
i++;
}
if (i >= MAX_DOZE_WAITING_TIMES_9x) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"ERFOFF: %d times TcbBusyQueue[%d] = %d !\n",
MAX_DOZE_WAITING_TIMES_9x,
queue_id,
skb_queue_len(&ring->queue));
break;
}
}
if (ppsc->reg_rfps_level & RT_RF_OFF_LEVL_HALT_NIC) {
RT_TRACE(rtlpriv, COMP_RF, DBG_DMESG,
"IPS Set eRf nic disable\n");
rtl_ps_disable_nic(hw);
RT_SET_PS_LEVEL(ppsc, RT_RF_OFF_LEVL_HALT_NIC);
} else {
if (ppsc->rfoff_reason == RF_CHANGE_BY_IPS) {
rtlpriv->cfg->ops->led_control(hw,
LED_CTL_NO_LINK);
} else {
rtlpriv->cfg->ops->led_control(hw,
LED_CTL_POWER_OFF);
}
}
break;
case ERFSLEEP:
if (ppsc->rfpwr_state == ERFOFF)
return false;
for (queue_id = 0, i = 0;
queue_id < RTL_PCI_MAX_TX_QUEUE_COUNT;) {
ring = &pcipriv->dev.tx_ring[queue_id];
if (skb_queue_len(&ring->queue) == 0) {
queue_id++;
continue;
} else {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"eRf Off/Sleep: %d times TcbBusyQueue[%d] =%d before doze!\n",
i + 1, queue_id,
skb_queue_len(&ring->queue));
udelay(10);
i++;
}
if (i >= MAX_DOZE_WAITING_TIMES_9x) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"ERFSLEEP: %d times TcbBusyQueue[%d] = %d !\n",
MAX_DOZE_WAITING_TIMES_9x,
queue_id,
skb_queue_len(&ring->queue));
break;
}
}
RT_TRACE(rtlpriv, COMP_RF, DBG_DMESG,
"Set ERFSLEEP awaked:%d ms\n",
jiffies_to_msecs(jiffies - ppsc->last_awake_jiffies));
ppsc->last_sleep_jiffies = jiffies;
_rtl92c_phy_set_rf_sleep(hw);
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"switch case not processed\n");
bresult = false;
break;
}
if (bresult)
ppsc->rfpwr_state = rfpwr_state;
return bresult;
}
bool rtl92cu_phy_set_rf_power_state(struct ieee80211_hw *hw,
enum rf_pwrstate rfpwr_state)
{
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
bool bresult = false;
if (rfpwr_state == ppsc->rfpwr_state)
return bresult;
bresult = _rtl92cu_phy_set_rf_power_state(hw, rfpwr_state);
return bresult;
}
| gpl-2.0 |
sachinthomaspj/android_kernel_htc_pico | arch/h8300/kernel/timer/timer16.c | 7813 | 1603 | /*
* linux/arch/h8300/kernel/timer/timer16.c
*
* Yoshinori Sato <ysato@users.sourcefoge.jp>
*
* 16bit Timer Handler
*
*/
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/param.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/timex.h>
#include <asm/segment.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/regs306x.h>
/* 16bit timer */
#if CONFIG_H8300_TIMER16_CH == 0
#define _16BASE 0xffff78
#define _16IRQ 24
#elif CONFIG_H8300_TIMER16_CH == 1
#define _16BASE 0xffff80
#define _16IRQ 28
#elif CONFIG_H8300_TIMER16_CH == 2
#define _16BASE 0xffff88
#define _16IRQ 32
#else
#error Unknown timer channel.
#endif
#define TCR 0
#define TIOR 1
#define TCNT 2
#define GRA 4
#define GRB 6
#define H8300_TIMER_FREQ CONFIG_CPU_CLOCK*10000 /* Timer input freq. */
static irqreturn_t timer_interrupt(int irq, void *dev_id)
{
h8300_timer_tick();
ctrl_bclr(CONFIG_H8300_TIMER16_CH, TISRA);
return IRQ_HANDLED;
}
static struct irqaction timer16_irq = {
.name = "timer-16",
.handler = timer_interrupt,
.flags = IRQF_DISABLED | IRQF_TIMER,
};
static const int __initdata divide_rate[] = {1, 2, 4, 8};
void __init h8300_timer_setup(void)
{
unsigned int div;
unsigned int cnt;
calc_param(cnt, div, divide_rate, 0x10000);
setup_irq(_16IRQ, &timer16_irq);
/* initialize timer */
ctrl_outb(0, TSTR);
ctrl_outb(CCLR0 | div, _16BASE + TCR);
ctrl_outw(cnt, _16BASE + GRA);
ctrl_bset(4 + CONFIG_H8300_TIMER16_CH, TISRA);
ctrl_bset(CONFIG_H8300_TIMER16_CH, TSTR);
}
| gpl-2.0 |
pio-masaki/android_kernel_samsung_jf | drivers/staging/cxt1e1/sbeproc.c | 8325 | 11466 | /* Copyright (C) 2004-2005 SBE, 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 program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/types.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/proc_fs.h>
#include <linux/sched.h>
#include <asm/uaccess.h>
#include "pmcc4_sysdep.h"
#include "sbecom_inline_linux.h"
#include "pmcc4_private.h"
#include "sbeproc.h"
/* forwards */
void sbecom_get_brdinfo (ci_t *, struct sbe_brd_info *, u_int8_t *);
extern struct s_hdw_info hdw_info[MAX_BOARDS];
#ifdef CONFIG_PROC_FS
/********************************************************************/
/* procfs stuff */
/********************************************************************/
void
sbecom_proc_brd_cleanup (ci_t * ci)
{
if (ci->dir_dev)
{
char dir[7 + SBE_IFACETMPL_SIZE + 1];
snprintf(dir, sizeof(dir), "driver/%s", ci->devname);
remove_proc_entry("info", ci->dir_dev);
remove_proc_entry(dir, NULL);
ci->dir_dev = NULL;
}
}
static int
sbecom_proc_get_sbe_info (char *buffer, char **start, off_t offset,
int length, int *eof, void *priv)
{
ci_t *ci = (ci_t *) priv;
int len = 0;
char *spd;
struct sbe_brd_info *bip;
if (!(bip = OS_kmalloc (sizeof (struct sbe_brd_info))))
{
return -ENOMEM;
}
#if 0
/** RLD DEBUG **/
pr_info(">> sbecom_proc_get_sbe_info: entered, offset %d. length %d.\n",
(int) offset, (int) length);
#endif
{
hdw_info_t *hi = &hdw_info[ci->brdno];
u_int8_t *bsn = 0;
switch (hi->promfmt)
{
case PROM_FORMAT_TYPE1:
bsn = (u_int8_t *) hi->mfg_info.pft1.Serial;
break;
case PROM_FORMAT_TYPE2:
bsn = (u_int8_t *) hi->mfg_info.pft2.Serial;
break;
}
sbecom_get_brdinfo (ci, bip, bsn);
}
#if 0
/** RLD DEBUG **/
pr_info(">> sbecom_get_brdinfo: returned, first_if %p <%s> last_if %p <%s>\n",
(char *) &bip->first_iname, (char *) &bip->first_iname,
(char *) &bip->last_iname, (char *) &bip->last_iname);
#endif
len += sprintf (buffer + len, "Board Type: ");
switch (bip->brd_id)
{
case SBE_BOARD_ID (PCI_VENDOR_ID_SBE, PCI_DEVICE_ID_WANPMC_C1T3):
len += sprintf (buffer + len, "wanPMC-C1T3");
break;
case SBE_BOARD_ID (PCI_VENDOR_ID_SBE, PCI_DEVICE_ID_WANPTMC_256T3_E1):
len += sprintf (buffer + len, "wanPTMC-256T3 <E1>");
break;
case SBE_BOARD_ID (PCI_VENDOR_ID_SBE, PCI_DEVICE_ID_WANPTMC_256T3_T1):
len += sprintf (buffer + len, "wanPTMC-256T3 <T1>");
break;
case SBE_BOARD_ID (PCI_VENDOR_ID_SBE, PCI_DEVICE_ID_WANPTMC_C24TE1):
len += sprintf (buffer + len, "wanPTMC-C24TE1");
break;
case SBE_BOARD_ID (PCI_VENDOR_ID_SBE, PCI_DEVICE_ID_WANPMC_C4T1E1):
case SBE_BOARD_ID (PCI_VENDOR_ID_SBE, PCI_DEVICE_ID_WANPMC_C4T1E1_L):
len += sprintf (buffer + len, "wanPMC-C4T1E1");
break;
case SBE_BOARD_ID (PCI_VENDOR_ID_SBE, PCI_DEVICE_ID_WANPMC_C2T1E1):
case SBE_BOARD_ID (PCI_VENDOR_ID_SBE, PCI_DEVICE_ID_WANPMC_C2T1E1_L):
len += sprintf (buffer + len, "wanPMC-C2T1E1");
break;
case SBE_BOARD_ID (PCI_VENDOR_ID_SBE, PCI_DEVICE_ID_WANPMC_C1T1E1):
case SBE_BOARD_ID (PCI_VENDOR_ID_SBE, PCI_DEVICE_ID_WANPMC_C1T1E1_L):
len += sprintf (buffer + len, "wanPMC-C1T1E1");
break;
case SBE_BOARD_ID (PCI_VENDOR_ID_SBE, PCI_DEVICE_ID_WANPCI_C4T1E1):
len += sprintf (buffer + len, "wanPCI-C4T1E1");
break;
case SBE_BOARD_ID (PCI_VENDOR_ID_SBE, PCI_DEVICE_ID_WANPCI_C2T1E1):
len += sprintf (buffer + len, "wanPCI-C2T1E1");
break;
case SBE_BOARD_ID (PCI_VENDOR_ID_SBE, PCI_DEVICE_ID_WANPCI_C1T1E1):
len += sprintf (buffer + len, "wanPCI-C1T1E1");
break;
default:
len += sprintf (buffer + len, "unknown");
break;
}
len += sprintf (buffer + len, " [%08X]\n", bip->brd_id);
len += sprintf (buffer + len, "Board Number: %d\n", bip->brdno);
len += sprintf (buffer + len, "Hardware ID: 0x%02X\n", ci->hdw_bid);
len += sprintf (buffer + len, "Board SN: %06X\n", bip->brd_sn);
len += sprintf(buffer + len, "Board MAC: %pMF\n",
bip->brd_mac_addr);
len += sprintf (buffer + len, "Ports: %d\n", ci->max_port);
len += sprintf (buffer + len, "Channels: %d\n", bip->brd_chan_cnt);
#if 1
len += sprintf (buffer + len, "Interface: %s -> %s\n",
(char *) &bip->first_iname, (char *) &bip->last_iname);
#else
len += sprintf (buffer + len, "Interface: <not available> 1st %p lst %p\n",
(char *) &bip->first_iname, (char *) &bip->last_iname);
#endif
switch (bip->brd_pci_speed)
{
case BINFO_PCI_SPEED_33:
spd = "33Mhz";
break;
case BINFO_PCI_SPEED_66:
spd = "66Mhz";
break;
default:
spd = "<not available>";
break;
}
len += sprintf (buffer + len, "PCI Bus Speed: %s\n", spd);
len += sprintf (buffer + len, "Release: %s\n", ci->release);
#ifdef SBE_PMCC4_ENABLE
{
extern int cxt1e1_max_mru;
#if 0
extern int max_chans_used;
extern int cxt1e1_max_mtu;
#endif
extern int max_rxdesc_used, max_txdesc_used;
len += sprintf (buffer + len, "\ncxt1e1_max_mru: %d\n", cxt1e1_max_mru);
#if 0
len += sprintf (buffer + len, "\nmax_chans_used: %d\n", max_chans_used);
len += sprintf (buffer + len, "cxt1e1_max_mtu: %d\n", cxt1e1_max_mtu);
#endif
len += sprintf (buffer + len, "max_rxdesc_used: %d\n", max_rxdesc_used);
len += sprintf (buffer + len, "max_txdesc_used: %d\n", max_txdesc_used);
}
#endif
OS_kfree (bip); /* cleanup */
/***
* How to be a proc read function
* ------------------------------
* Prototype:
* int f(char *buffer, char **start, off_t offset,
* int count, int *peof, void *dat)
*
* Assume that the buffer is "count" bytes in size.
*
* If you know you have supplied all the data you
* have, set *peof.
*
* You have three ways to return data:
* 0) Leave *start = NULL. (This is the default.)
* Put the data of the requested offset at that
* offset within the buffer. Return the number (n)
* of bytes there are from the beginning of the
* buffer up to the last byte of data. If the
* number of supplied bytes (= n - offset) is
* greater than zero and you didn't signal eof
* and the reader is prepared to take more data
* you will be called again with the requested
* offset advanced by the number of bytes
* absorbed. This interface is useful for files
* no larger than the buffer.
* 1) Set *start = an unsigned long value less than
* the buffer address but greater than zero.
* Put the data of the requested offset at the
* beginning of the buffer. Return the number of
* bytes of data placed there. If this number is
* greater than zero and you didn't signal eof
* and the reader is prepared to take more data
* you will be called again with the requested
* offset advanced by *start. This interface is
* useful when you have a large file consisting
* of a series of blocks which you want to count
* and return as wholes.
* (Hack by Paul.Russell@rustcorp.com.au)
* 2) Set *start = an address within the buffer.
* Put the data of the requested offset at *start.
* Return the number of bytes of data placed there.
* If this number is greater than zero and you
* didn't signal eof and the reader is prepared to
* take more data you will be called again with the
* requested offset advanced by the number of bytes
* absorbed.
*/
#if 1
/* #4 - interpretation of above = set EOF, return len */
*eof = 1;
#endif
#if 0
/*
* #1 - from net/wireless/atmel.c RLD NOTE -there's something wrong with
* this plagarized code which results in this routine being called TWICE.
* The second call returns ZERO, resulting in hidden failure, but at
* least only a single message set is being displayed.
*/
if (len <= offset + length)
*eof = 1;
*start = buffer + offset;
len -= offset;
if (len > length)
len = length;
if (len < 0)
len = 0;
#endif
#if 0 /* #2 from net/tokenring/olympic.c +
* lanstreamer.c */
{
off_t begin = 0;
int size = 0;
off_t pos = 0;
size = len;
pos = begin + size;
if (pos < offset)
{
len = 0;
begin = pos;
}
*start = buffer + (offset - begin); /* Start of wanted data */
len -= (offset - begin); /* Start slop */
if (len > length)
len = length; /* Ending slop */
}
#endif
#if 0 /* #3 from
* char/ftape/lowlevel/ftape-proc.c */
len = strlen (buffer);
*start = NULL;
if (offset + length >= len)
*eof = 1;
else
*eof = 0;
#endif
#if 0
pr_info(">> proc_fs: returned len = %d., start %p\n", len, start); /* RLD DEBUG */
#endif
/***
using NONE: returns = 314.314.314.
using #1 : returns = 314, 0.
using #2 : returns = 314, 0, 0.
using #3 : returns = 314, 314.
using #4 : returns = 314, 314.
***/
return len;
}
/* initialize the /proc subsystem for the specific SBE driver */
int __init
sbecom_proc_brd_init (ci_t * ci)
{
struct proc_dir_entry *e;
char dir[7 + SBE_IFACETMPL_SIZE + 1];
/* create a directory in the root procfs */
snprintf(dir, sizeof(dir), "driver/%s", ci->devname);
ci->dir_dev = proc_mkdir(dir, NULL);
if (!ci->dir_dev)
{
pr_err("Unable to create directory /proc/driver/%s\n", ci->devname);
goto fail;
}
e = create_proc_read_entry ("info", S_IFREG | S_IRUGO,
ci->dir_dev, sbecom_proc_get_sbe_info, ci);
if (!e)
{
pr_err("Unable to create entry /proc/driver/%s/info\n", ci->devname);
goto fail;
}
return 0;
fail:
sbecom_proc_brd_cleanup (ci);
return 1;
}
#else /*** ! CONFIG_PROC_FS ***/
/* stubbed off dummy routines */
void
sbecom_proc_brd_cleanup (ci_t * ci)
{
}
int __init
sbecom_proc_brd_init (ci_t * ci)
{
return 0;
}
#endif /*** CONFIG_PROC_FS ***/
/*** End-of-File ***/
| gpl-2.0 |
cometzero/cometzero_e210s | drivers/video/riva/rivafb-i2c.c | 8325 | 3720 | /*
* linux/drivers/video/riva/fbdev-i2c.c - nVidia i2c
*
* Maintained by Ani Joshi <ajoshi@shell.unixbox.com>
*
* Copyright 2004 Antonino A. Daplas <adaplas @pol.net>
*
* Based on radeonfb-i2c.c
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive
* for more details.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/pci.h>
#include <linux/fb.h>
#include <linux/jiffies.h>
#include <asm/io.h>
#include "rivafb.h"
#include "../edid.h"
static void riva_gpio_setscl(void* data, int state)
{
struct riva_i2c_chan *chan = data;
struct riva_par *par = chan->par;
u32 val;
VGA_WR08(par->riva.PCIO, 0x3d4, chan->ddc_base + 1);
val = VGA_RD08(par->riva.PCIO, 0x3d5) & 0xf0;
if (state)
val |= 0x20;
else
val &= ~0x20;
VGA_WR08(par->riva.PCIO, 0x3d4, chan->ddc_base + 1);
VGA_WR08(par->riva.PCIO, 0x3d5, val | 0x1);
}
static void riva_gpio_setsda(void* data, int state)
{
struct riva_i2c_chan *chan = data;
struct riva_par *par = chan->par;
u32 val;
VGA_WR08(par->riva.PCIO, 0x3d4, chan->ddc_base + 1);
val = VGA_RD08(par->riva.PCIO, 0x3d5) & 0xf0;
if (state)
val |= 0x10;
else
val &= ~0x10;
VGA_WR08(par->riva.PCIO, 0x3d4, chan->ddc_base + 1);
VGA_WR08(par->riva.PCIO, 0x3d5, val | 0x1);
}
static int riva_gpio_getscl(void* data)
{
struct riva_i2c_chan *chan = data;
struct riva_par *par = chan->par;
u32 val = 0;
VGA_WR08(par->riva.PCIO, 0x3d4, chan->ddc_base);
if (VGA_RD08(par->riva.PCIO, 0x3d5) & 0x04)
val = 1;
return val;
}
static int riva_gpio_getsda(void* data)
{
struct riva_i2c_chan *chan = data;
struct riva_par *par = chan->par;
u32 val = 0;
VGA_WR08(par->riva.PCIO, 0x3d4, chan->ddc_base);
if (VGA_RD08(par->riva.PCIO, 0x3d5) & 0x08)
val = 1;
return val;
}
static int __devinit riva_setup_i2c_bus(struct riva_i2c_chan *chan,
const char *name,
unsigned int i2c_class)
{
int rc;
strcpy(chan->adapter.name, name);
chan->adapter.owner = THIS_MODULE;
chan->adapter.class = i2c_class;
chan->adapter.algo_data = &chan->algo;
chan->adapter.dev.parent = &chan->par->pdev->dev;
chan->algo.setsda = riva_gpio_setsda;
chan->algo.setscl = riva_gpio_setscl;
chan->algo.getsda = riva_gpio_getsda;
chan->algo.getscl = riva_gpio_getscl;
chan->algo.udelay = 40;
chan->algo.timeout = msecs_to_jiffies(2);
chan->algo.data = chan;
i2c_set_adapdata(&chan->adapter, chan);
/* Raise SCL and SDA */
riva_gpio_setsda(chan, 1);
riva_gpio_setscl(chan, 1);
udelay(20);
rc = i2c_bit_add_bus(&chan->adapter);
if (rc == 0)
dev_dbg(&chan->par->pdev->dev, "I2C bus %s registered.\n", name);
else {
dev_warn(&chan->par->pdev->dev,
"Failed to register I2C bus %s.\n", name);
chan->par = NULL;
}
return rc;
}
void __devinit riva_create_i2c_busses(struct riva_par *par)
{
par->chan[0].par = par;
par->chan[1].par = par;
par->chan[2].par = par;
par->chan[0].ddc_base = 0x36;
par->chan[1].ddc_base = 0x3e;
par->chan[2].ddc_base = 0x50;
riva_setup_i2c_bus(&par->chan[0], "BUS1", I2C_CLASS_HWMON);
riva_setup_i2c_bus(&par->chan[1], "BUS2", 0);
riva_setup_i2c_bus(&par->chan[2], "BUS3", 0);
}
void riva_delete_i2c_busses(struct riva_par *par)
{
int i;
for (i = 0; i < 3; i++) {
if (!par->chan[i].par)
continue;
i2c_del_adapter(&par->chan[i].adapter);
par->chan[i].par = NULL;
}
}
int __devinit riva_probe_i2c_connector(struct riva_par *par, int conn, u8 **out_edid)
{
u8 *edid = NULL;
if (par->chan[conn].par)
edid = fb_ddc_read(&par->chan[conn].adapter);
if (out_edid)
*out_edid = edid;
if (!edid)
return 1;
return 0;
}
| gpl-2.0 |
MozOpenHard/linux-rockchip | drivers/staging/comedi/drivers/addi-data/APCI1710_Inp_cpt.c | 8325 | 32512 | /**
@verbatim
Copyright (C) 2004,2005 ADDI-DATA GmbH for the source code of this module.
ADDI-DATA GmbH
Dieselstrasse 3
D-77833 Ottersweier
Tel: +19(0)7223/9493-0
Fax: +49(0)7223/9493-92
http://www.addi-data.com
info@addi-data.com
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
You should also find the complete GPL in the COPYING file accompanying this source code.
@endverbatim
*/
/*
+-----------------------------------------------------------------------+
| (C) ADDI-DATA GmbH Dieselstraße 3 D-77833 Ottersweier |
+-----------------------------------------------------------------------+
| Tel : +49 (0) 7223/9493-0 | email : info@addi-data.com |
| Fax : +49 (0) 7223/9493-92 | Internet : http://www.addi-data.com |
+-----------------------------------------------------------------------+
| Project : API APCI1710 | Compiler : gcc |
| Module name : Inp_CPT.C | Version : 2.96 |
+-------------------------------+---------------------------------------+
| Project manager: Eric Stolz | Date : 02/12/2002 |
+-----------------------------------------------------------------------+
| Description : APCI-1710 pulse encoder module |
| |
| |
+-----------------------------------------------------------------------+
| UPDATES |
+-----------------------------------------------------------------------+
| Date | Author | Description of updates |
+----------+-----------+------------------------------------------------+
| | | |
|----------|-----------|------------------------------------------------|
| 08/05/00 | Guinot C | - 0400/0228 All Function in RING 0 |
| | | available |
+-----------------------------------------------------------------------+
*/
/*
+----------------------------------------------------------------------------+
| Included files |
+----------------------------------------------------------------------------+
*/
#include "APCI1710_Inp_cpt.h"
/*
+----------------------------------------------------------------------------+
| Function Name : _INT_ i_APCI1710_InitPulseEncoder |
| (unsigned char_ b_BoardHandle, |
| unsigned char_ b_ModulNbr, |
| unsigned char_ b_PulseEncoderNbr, |
| unsigned char_ b_InputLevelSelection, |
| unsigned char_ b_TriggerOutputAction, |
| ULONG_ ul_StartValue) |
+----------------------------------------------------------------------------+
| Task : Configure the pulse encoder operating mode selected via|
| b_ModulNbr and b_PulseEncoderNbr. The pulse encoder |
| after each pulse decrement the counter value from 1. |
| |
| You must calling this function be for you call any |
| other function witch access of pulse encoders. |
+----------------------------------------------------------------------------+
| Input Parameters : unsigned char_ b_BoardHandle : Handle of board APCI-1710|
| unsigned char_ b_ModulNbr : Module number to |
| configure (0 to 3) |
| unsigned char_ b_PulseEncoderNbr : Pulse encoder selection |
| (0 to 3) |
| unsigned char_ b_InputLevelSelection : Input level selection |
| (0 or 1) |
| 0 : Set pulse encoder|
| count the the low|
| level pulse. |
| 1 : Set pulse encoder|
| count the the |
| high level pulse.|
| unsigned char_ b_TriggerOutputAction : Digital TRIGGER output |
| action |
| 0 : No action |
| 1 : Set the trigger |
| output to "1" |
| (high) after the |
| passage from 1 to|
| 0 from pulse |
| encoder. |
| 2 : Set the trigger |
| output to "0" |
| (low) after the |
| passage from 1 to|
| 0 from pulse |
| encoder |
| ULONG_ ul_StartValue : Pulse encoder start value|
| (1 to 4294967295)
b_ModulNbr =(unsigned char) CR_AREF(insn->chanspec);
b_PulseEncoderNbr =(unsigned char) data[0];
b_InputLevelSelection =(unsigned char) data[1];
b_TriggerOutputAction =(unsigned char) data[2];
ul_StartValue =(unsigned int) data[3];
|
+----------------------------------------------------------------------------+
| Output Parameters : - |
+----------------------------------------------------------------------------+
| Return Value : 0: No error |
| -1: The handle parameter of the board is wrong |
| -2: The module is not a pulse encoder module |
| -3: Pulse encoder selection is wrong |
| -4: Input level selection is wrong |
| -5: Digital TRIGGER output action selection is wrong |
| -6: Pulse encoder start value is wrong |
+----------------------------------------------------------------------------+
*/
int i_APCI1710_InsnConfigInitPulseEncoder(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
{
int i_ReturnValue = 0;
unsigned int dw_IntRegister;
unsigned char b_ModulNbr;
unsigned char b_PulseEncoderNbr;
unsigned char b_InputLevelSelection;
unsigned char b_TriggerOutputAction;
unsigned int ul_StartValue;
b_ModulNbr = (unsigned char) CR_AREF(insn->chanspec);
b_PulseEncoderNbr = (unsigned char) data[0];
b_InputLevelSelection = (unsigned char) data[1];
b_TriggerOutputAction = (unsigned char) data[2];
ul_StartValue = (unsigned int) data[3];
i_ReturnValue = insn->n;
/***********************************/
/* Test the selected module number */
/***********************************/
if (b_ModulNbr <= 3) {
/*************************/
/* Test if pulse encoder */
/*************************/
if ((devpriv->s_BoardInfos.
dw_MolduleConfiguration[b_ModulNbr] &
APCI1710_PULSE_ENCODER) ==
APCI1710_PULSE_ENCODER) {
/******************************************/
/* Test the selected pulse encoder number */
/******************************************/
if (b_PulseEncoderNbr <= 3) {
/************************/
/* Test the input level */
/************************/
if ((b_InputLevelSelection == 0)
|| (b_InputLevelSelection == 1)) {
/*******************************************/
/* Test the ouput TRIGGER action selection */
/*******************************************/
if ((b_TriggerOutputAction <= 2)
|| (b_PulseEncoderNbr > 0)) {
if (ul_StartValue > 1) {
dw_IntRegister =
inl(devpriv->
s_BoardInfos.
ui_Address +
20 +
(64 * b_ModulNbr));
/***********************/
/* Set the start value */
/***********************/
outl(ul_StartValue,
devpriv->
s_BoardInfos.
ui_Address +
(b_PulseEncoderNbr
* 4) +
(64 * b_ModulNbr));
/***********************/
/* Set the input level */
/***********************/
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_SetRegister =
(devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_SetRegister &
(0xFFFFFFFFUL -
(1UL << (8 + b_PulseEncoderNbr)))) | ((1UL & (~b_InputLevelSelection)) << (8 + b_PulseEncoderNbr));
/*******************************/
/* Test if output trigger used */
/*******************************/
if ((b_TriggerOutputAction > 0) && (b_PulseEncoderNbr > 1)) {
/****************************/
/* Enable the output action */
/****************************/
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_SetRegister
=
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_SetRegister
| (1UL
<< (4 + b_PulseEncoderNbr));
/*********************************/
/* Set the output TRIGGER action */
/*********************************/
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_SetRegister
=
(devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_SetRegister
&
(0xFFFFFFFFUL
-
(1UL << (12 + b_PulseEncoderNbr)))) | ((1UL & (b_TriggerOutputAction - 1)) << (12 + b_PulseEncoderNbr));
} else {
/*****************************/
/* Disable the output action */
/*****************************/
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_SetRegister
=
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_SetRegister
&
(0xFFFFFFFFUL
-
(1UL << (4 + b_PulseEncoderNbr)));
}
/*************************/
/* Set the configuration */
/*************************/
outl(devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_SetRegister,
devpriv->
s_BoardInfos.
ui_Address +
20 +
(64 * b_ModulNbr));
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PulseEncoderModuleInfo.
s_PulseEncoderInfo
[b_PulseEncoderNbr].
b_PulseEncoderInit
= 1;
} else {
/**************************************/
/* Pulse encoder start value is wrong */
/**************************************/
DPRINTK("Pulse encoder start value is wrong\n");
i_ReturnValue = -6;
}
} else {
/****************************************************/
/* Digital TRIGGER output action selection is wrong */
/****************************************************/
DPRINTK("Digital TRIGGER output action selection is wrong\n");
i_ReturnValue = -5;
}
} else {
/**********************************/
/* Input level selection is wrong */
/**********************************/
DPRINTK("Input level selection is wrong\n");
i_ReturnValue = -4;
}
} else {
/************************************/
/* Pulse encoder selection is wrong */
/************************************/
DPRINTK("Pulse encoder selection is wrong\n");
i_ReturnValue = -3;
}
} else {
/********************************************/
/* The module is not a pulse encoder module */
/********************************************/
DPRINTK("The module is not a pulse encoder module\n");
i_ReturnValue = -2;
}
} else {
/********************************************/
/* The module is not a pulse encoder module */
/********************************************/
DPRINTK("The module is not a pulse encoder module\n");
i_ReturnValue = -2;
}
return i_ReturnValue;
}
/*
+----------------------------------------------------------------------------+
| Function Name : _INT_ i_APCI1710_EnablePulseEncoder |
| (unsigned char_ b_BoardHandle, |
| unsigned char_ b_ModulNbr, |
| unsigned char_ b_PulseEncoderNbr, |
| unsigned char_ b_CycleSelection, |
| unsigned char_ b_InterruptHandling) |
+----------------------------------------------------------------------------+
| Task : Enableor disable the selected pulse encoder (b_PulseEncoderNbr) |
| from selected module (b_ModulNbr). Each input pulse |
| decrement the pulse encoder counter value from 1. |
| If you enabled the interrupt (b_InterruptHandling), a |
| interrupt is generated when the pulse encoder has run |
| down. |
+----------------------------------------------------------------------------+
| Input Parameters : unsigned char_ b_BoardHandle : Handle of board APCI-1710|
| unsigned char_ b_ModulNbr : Module number to |
| configure (0 to 3) |
| unsigned char_ b_PulseEncoderNbr : Pulse encoder selection |
| (0 to 3) |
| unsigned char_ b_CycleSelection : APCI1710_CONTINUOUS: |
| Each time the |
| counting value is set|
| on "0", the pulse |
| encoder load the |
| start value after |
| the next pulse. |
| APCI1710_SINGLE: |
| If the counter is set|
| on "0", the pulse |
| encoder is stopped. |
| unsigned char_ b_InterruptHandling : Interrupts can be |
| generated, when the pulse|
| encoder has run down. |
| With this parameter the |
| user decides if |
| interrupts are used or |
| not. |
| APCI1710_ENABLE: |
| Interrupts are enabled |
| APCI1710_DISABLE: |
| Interrupts are disabled
b_ModulNbr =(unsigned char) CR_AREF(insn->chanspec);
b_Action =(unsigned char) data[0];
b_PulseEncoderNbr =(unsigned char) data[1];
b_CycleSelection =(unsigned char) data[2];
b_InterruptHandling =(unsigned char) data[3];|
+----------------------------------------------------------------------------+
| Output Parameters : - |
+----------------------------------------------------------------------------+
| Return Value : 0: No error |
| -1: The handle parameter of the board is wrong |
| -2: Module selection is wrong |
| -3: Pulse encoder selection is wrong |
| -4: Pulse encoder not initialised. |
| See function "i_APCI1710_InitPulseEncoder" |
| -5: Cycle selection mode is wrong |
| -6: Interrupt handling mode is wrong |
| -7: Interrupt routine not installed. |
| See function "i_APCI1710_SetBoardIntRoutineX" |
+----------------------------------------------------------------------------+
*/
int i_APCI1710_InsnWriteEnableDisablePulseEncoder(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
{
int i_ReturnValue = 0;
unsigned char b_ModulNbr;
unsigned char b_PulseEncoderNbr;
unsigned char b_CycleSelection;
unsigned char b_InterruptHandling;
unsigned char b_Action;
i_ReturnValue = insn->n;
b_ModulNbr = (unsigned char) CR_AREF(insn->chanspec);
b_Action = (unsigned char) data[0];
b_PulseEncoderNbr = (unsigned char) data[1];
b_CycleSelection = (unsigned char) data[2];
b_InterruptHandling = (unsigned char) data[3];
/***********************************/
/* Test the selected module number */
/***********************************/
if (b_ModulNbr <= 3) {
/******************************************/
/* Test the selected pulse encoder number */
/******************************************/
if (b_PulseEncoderNbr <= 3) {
/*************************************/
/* Test if pulse encoder initialised */
/*************************************/
if (devpriv->s_ModuleInfo[b_ModulNbr].
s_PulseEncoderModuleInfo.
s_PulseEncoderInfo[b_PulseEncoderNbr].
b_PulseEncoderInit == 1) {
switch (b_Action) {
case APCI1710_ENABLE:
/****************************/
/* Test the cycle selection */
/****************************/
if (b_CycleSelection ==
APCI1710_CONTINUOUS
|| b_CycleSelection ==
APCI1710_SINGLE) {
/*******************************/
/* Test the interrupt handling */
/*******************************/
if (b_InterruptHandling ==
APCI1710_ENABLE
|| b_InterruptHandling
== APCI1710_DISABLE) {
/******************************/
/* Test if interrupt not used */
/******************************/
if (b_InterruptHandling
==
APCI1710_DISABLE)
{
/*************************/
/* Disable the interrupt */
/*************************/
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_SetRegister
=
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_SetRegister
&
(0xFFFFFFFFUL
-
(1UL << b_PulseEncoderNbr));
} else {
/************************/
/* Enable the interrupt */
/************************/
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_SetRegister
=
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_SetRegister
| (1UL
<<
b_PulseEncoderNbr);
devpriv->tsk_Current = current; /* Save the current process task structure */
}
if (i_ReturnValue >= 0) {
/***********************************/
/* Enable or disable the interrupt */
/***********************************/
outl(devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_SetRegister,
devpriv->
s_BoardInfos.
ui_Address
+ 20 +
(64 * b_ModulNbr));
/****************************/
/* Enable the pulse encoder */
/****************************/
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_ControlRegister
=
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_ControlRegister
| (1UL
<<
b_PulseEncoderNbr);
/**********************/
/* Set the cycle mode */
/**********************/
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_ControlRegister
=
(devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_ControlRegister
&
(0xFFFFFFFFUL
-
(1 << (b_PulseEncoderNbr + 4)))) | ((b_CycleSelection & 1UL) << (4 + b_PulseEncoderNbr));
/****************************/
/* Enable the pulse encoder */
/****************************/
outl(devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_ControlRegister,
devpriv->
s_BoardInfos.
ui_Address
+ 16 +
(64 * b_ModulNbr));
}
} else {
/************************************/
/* Interrupt handling mode is wrong */
/************************************/
DPRINTK("Interrupt handling mode is wrong\n");
i_ReturnValue = -6;
}
} else {
/*********************************/
/* Cycle selection mode is wrong */
/*********************************/
DPRINTK("Cycle selection mode is wrong\n");
i_ReturnValue = -5;
}
break;
case APCI1710_DISABLE:
devpriv->s_ModuleInfo[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_ControlRegister =
devpriv->
s_ModuleInfo[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_ControlRegister &
(0xFFFFFFFFUL -
(1UL << b_PulseEncoderNbr));
/*****************************/
/* Disable the pulse encoder */
/*****************************/
outl(devpriv->s_ModuleInfo[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_ControlRegister,
devpriv->s_BoardInfos.
ui_Address + 16 +
(64 * b_ModulNbr));
break;
} /* switch End */
} else {
/*********************************/
/* Pulse encoder not initialised */
/*********************************/
DPRINTK("Pulse encoder not initialised\n");
i_ReturnValue = -4;
}
} else {
/************************************/
/* Pulse encoder selection is wrong */
/************************************/
DPRINTK("Pulse encoder selection is wrong\n");
i_ReturnValue = -3;
}
} else {
/*****************************/
/* Module selection is wrong */
/*****************************/
DPRINTK("Module selection is wrong\n");
i_ReturnValue = -2;
}
return i_ReturnValue;
}
/*
+----------------------------------------------------------------------------+
| Function Name : _INT_ i_APCI1710_ReadPulseEncoderStatus |
| (unsigned char_ b_BoardHandle, |
| unsigned char_ b_ModulNbr, |
| unsigned char_ b_PulseEncoderNbr, |
| unsigned char *_ pb_Status) |
+----------------------------------------------------------------------------+
| Task APCI1710_PULSEENCODER_READ : Reads the pulse encoder status
and valuefrom selected pulse |
| encoder (b_PulseEncoderNbr) from selected module |
| (b_ModulNbr). |
+----------------------------------------------------------------------------+
unsigned char b_Type; data[0]
APCI1710_PULSEENCODER_WRITE
Writes a 32-bit value (ul_WriteValue) into the selected|
| pulse encoder (b_PulseEncoderNbr) from selected module |
| (b_ModulNbr). This operation set the new start pulse |
| encoder value.
APCI1710_PULSEENCODER_READ
| Input Parameters : unsigned char_ b_BoardHandle : Handle of board APCI-1710|
| CRAREF() unsigned char_ b_ModulNbr : Module number to |
| configure (0 to 3) |
| data[1] unsigned char_ b_PulseEncoderNbr : Pulse encoder selection |
| (0 to 3)
APCI1710_PULSEENCODER_WRITE
data[2] ULONG_ ul_WriteValue : 32-bit value to be |
| written |
+----------------------------------------------------------------------------+
| Output Parameters : unsigned char *_ pb_Status : Pulse encoder status. |
| 0 : No overflow occur|
| 1 : Overflow occur
PULONG_ pul_ReadValue : Pulse encoder value | |
+----------------------------------------------------------------------------+
| Return Value : 0: No error |
| -1: The handle parameter of the board is wrong |
| -2: Module selection is wrong |
| -3: Pulse encoder selection is wrong |
| -4: Pulse encoder not initialised. |
| See function "i_APCI1710_InitPulseEncoder" |
+----------------------------------------------------------------------------+
*/
/*_INT_ i_APCI1710_ReadPulseEncoderStatus (unsigned char_ b_BoardHandle,
unsigned char_ b_ModulNbr,
unsigned char_ b_PulseEncoderNbr,
unsigned char *_ pb_Status)
*/
int i_APCI1710_InsnBitsReadWritePulseEncoder(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
{
int i_ReturnValue = 0;
unsigned int dw_StatusRegister;
unsigned char b_ModulNbr;
unsigned char b_PulseEncoderNbr;
unsigned char *pb_Status;
unsigned char b_Type;
unsigned int *pul_ReadValue;
unsigned int ul_WriteValue;
i_ReturnValue = insn->n;
b_ModulNbr = (unsigned char) CR_AREF(insn->chanspec);
b_Type = (unsigned char) data[0];
b_PulseEncoderNbr = (unsigned char) data[1];
pb_Status = (unsigned char *) &data[0];
pul_ReadValue = (unsigned int *) &data[1];
/***********************************/
/* Test the selected module number */
/***********************************/
if (b_ModulNbr <= 3) {
/******************************************/
/* Test the selected pulse encoder number */
/******************************************/
if (b_PulseEncoderNbr <= 3) {
/*************************************/
/* Test if pulse encoder initialised */
/*************************************/
if (devpriv->s_ModuleInfo[b_ModulNbr].
s_PulseEncoderModuleInfo.
s_PulseEncoderInfo[b_PulseEncoderNbr].
b_PulseEncoderInit == 1) {
switch (b_Type) {
case APCI1710_PULSEENCODER_READ:
/****************************/
/* Read the status register */
/****************************/
dw_StatusRegister =
inl(devpriv->s_BoardInfos.
ui_Address + 16 +
(64 * b_ModulNbr));
devpriv->s_ModuleInfo[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_StatusRegister = devpriv->
s_ModuleInfo[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_StatusRegister |
dw_StatusRegister;
*pb_Status =
(unsigned char) (devpriv->
s_ModuleInfo[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_StatusRegister >> (1 +
b_PulseEncoderNbr)) & 1;
devpriv->s_ModuleInfo[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_StatusRegister =
devpriv->
s_ModuleInfo[b_ModulNbr].
s_PulseEncoderModuleInfo.
dw_StatusRegister &
(0xFFFFFFFFUL - (1 << (1 +
b_PulseEncoderNbr)));
/******************/
/* Read the value */
/******************/
*pul_ReadValue =
inl(devpriv->s_BoardInfos.
ui_Address +
(4 * b_PulseEncoderNbr) +
(64 * b_ModulNbr));
break;
case APCI1710_PULSEENCODER_WRITE:
ul_WriteValue = (unsigned int) data[2];
/*******************/
/* Write the value */
/*******************/
outl(ul_WriteValue,
devpriv->s_BoardInfos.
ui_Address +
(4 * b_PulseEncoderNbr) +
(64 * b_ModulNbr));
} /* end of switch */
} else {
/*********************************/
/* Pulse encoder not initialised */
/*********************************/
DPRINTK("Pulse encoder not initialised\n");
i_ReturnValue = -4;
}
} else {
/************************************/
/* Pulse encoder selection is wrong */
/************************************/
DPRINTK("Pulse encoder selection is wrong\n");
i_ReturnValue = -3;
}
} else {
/*****************************/
/* Module selection is wrong */
/*****************************/
DPRINTK("Module selection is wrong\n");
i_ReturnValue = -2;
}
return i_ReturnValue;
}
int i_APCI1710_InsnReadInterruptPulseEncoder(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
{
data[0] = devpriv->s_InterruptParameters.
s_FIFOInterruptParameters[devpriv->
s_InterruptParameters.ui_Read].b_OldModuleMask;
data[1] = devpriv->s_InterruptParameters.
s_FIFOInterruptParameters[devpriv->
s_InterruptParameters.ui_Read].ul_OldInterruptMask;
data[2] = devpriv->s_InterruptParameters.
s_FIFOInterruptParameters[devpriv->
s_InterruptParameters.ui_Read].ul_OldCounterLatchValue;
/***************************/
/* Increment the read FIFO */
/***************************/
devpriv->s_InterruptParameters.
ui_Read = (devpriv->
s_InterruptParameters.ui_Read + 1) % APCI1710_SAVE_INTERRUPT;
return insn->n;
}
| gpl-2.0 |
TheDarkestObscrurity/mako | tools/testing/selftests/breakpoints/breakpoint_test.c | 8325 | 7343 | /*
* Copyright (C) 2011 Red Hat, Inc., Frederic Weisbecker <fweisbec@redhat.com>
*
* Licensed under the terms of the GNU GPL License version 2
*
* Selftests for breakpoints (and more generally the do_debug() path) in x86.
*/
#include <sys/ptrace.h>
#include <unistd.h>
#include <stddef.h>
#include <sys/user.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
/* Breakpoint access modes */
enum {
BP_X = 1,
BP_RW = 2,
BP_W = 4,
};
static pid_t child_pid;
/*
* Ensures the child and parent are always "talking" about
* the same test sequence. (ie: that we haven't forgotten
* to call check_trapped() somewhere).
*/
static int nr_tests;
static void set_breakpoint_addr(void *addr, int n)
{
int ret;
ret = ptrace(PTRACE_POKEUSER, child_pid,
offsetof(struct user, u_debugreg[n]), addr);
if (ret) {
perror("Can't set breakpoint addr\n");
exit(-1);
}
}
static void toggle_breakpoint(int n, int type, int len,
int local, int global, int set)
{
int ret;
int xtype, xlen;
unsigned long vdr7, dr7;
switch (type) {
case BP_X:
xtype = 0;
break;
case BP_W:
xtype = 1;
break;
case BP_RW:
xtype = 3;
break;
}
switch (len) {
case 1:
xlen = 0;
break;
case 2:
xlen = 4;
break;
case 4:
xlen = 0xc;
break;
case 8:
xlen = 8;
break;
}
dr7 = ptrace(PTRACE_PEEKUSER, child_pid,
offsetof(struct user, u_debugreg[7]), 0);
vdr7 = (xlen | xtype) << 16;
vdr7 <<= 4 * n;
if (local) {
vdr7 |= 1 << (2 * n);
vdr7 |= 1 << 8;
}
if (global) {
vdr7 |= 2 << (2 * n);
vdr7 |= 1 << 9;
}
if (set)
dr7 |= vdr7;
else
dr7 &= ~vdr7;
ret = ptrace(PTRACE_POKEUSER, child_pid,
offsetof(struct user, u_debugreg[7]), dr7);
if (ret) {
perror("Can't set dr7");
exit(-1);
}
}
/* Dummy variables to test read/write accesses */
static unsigned long long dummy_var[4];
/* Dummy functions to test execution accesses */
static void dummy_func(void) { }
static void dummy_func1(void) { }
static void dummy_func2(void) { }
static void dummy_func3(void) { }
static void (*dummy_funcs[])(void) = {
dummy_func,
dummy_func1,
dummy_func2,
dummy_func3,
};
static int trapped;
static void check_trapped(void)
{
/*
* If we haven't trapped, wake up the parent
* so that it notices the failure.
*/
if (!trapped)
kill(getpid(), SIGUSR1);
trapped = 0;
nr_tests++;
}
static void write_var(int len)
{
char *pcval; short *psval; int *pival; long long *plval;
int i;
for (i = 0; i < 4; i++) {
switch (len) {
case 1:
pcval = (char *)&dummy_var[i];
*pcval = 0xff;
break;
case 2:
psval = (short *)&dummy_var[i];
*psval = 0xffff;
break;
case 4:
pival = (int *)&dummy_var[i];
*pival = 0xffffffff;
break;
case 8:
plval = (long long *)&dummy_var[i];
*plval = 0xffffffffffffffffLL;
break;
}
check_trapped();
}
}
static void read_var(int len)
{
char cval; short sval; int ival; long long lval;
int i;
for (i = 0; i < 4; i++) {
switch (len) {
case 1:
cval = *(char *)&dummy_var[i];
break;
case 2:
sval = *(short *)&dummy_var[i];
break;
case 4:
ival = *(int *)&dummy_var[i];
break;
case 8:
lval = *(long long *)&dummy_var[i];
break;
}
check_trapped();
}
}
/*
* Do the r/w/x accesses to trigger the breakpoints. And run
* the usual traps.
*/
static void trigger_tests(void)
{
int len, local, global, i;
char val;
int ret;
ret = ptrace(PTRACE_TRACEME, 0, NULL, 0);
if (ret) {
perror("Can't be traced?\n");
return;
}
/* Wake up father so that it sets up the first test */
kill(getpid(), SIGUSR1);
/* Test instruction breakpoints */
for (local = 0; local < 2; local++) {
for (global = 0; global < 2; global++) {
if (!local && !global)
continue;
for (i = 0; i < 4; i++) {
dummy_funcs[i]();
check_trapped();
}
}
}
/* Test write watchpoints */
for (len = 1; len <= sizeof(long); len <<= 1) {
for (local = 0; local < 2; local++) {
for (global = 0; global < 2; global++) {
if (!local && !global)
continue;
write_var(len);
}
}
}
/* Test read/write watchpoints (on read accesses) */
for (len = 1; len <= sizeof(long); len <<= 1) {
for (local = 0; local < 2; local++) {
for (global = 0; global < 2; global++) {
if (!local && !global)
continue;
read_var(len);
}
}
}
/* Icebp trap */
asm(".byte 0xf1\n");
check_trapped();
/* Int 3 trap */
asm("int $3\n");
check_trapped();
kill(getpid(), SIGUSR1);
}
static void check_success(const char *msg)
{
const char *msg2;
int child_nr_tests;
int status;
/* Wait for the child to SIGTRAP */
wait(&status);
msg2 = "Failed";
if (WSTOPSIG(status) == SIGTRAP) {
child_nr_tests = ptrace(PTRACE_PEEKDATA, child_pid,
&nr_tests, 0);
if (child_nr_tests == nr_tests)
msg2 = "Ok";
if (ptrace(PTRACE_POKEDATA, child_pid, &trapped, 1)) {
perror("Can't poke\n");
exit(-1);
}
}
nr_tests++;
printf("%s [%s]\n", msg, msg2);
}
static void launch_instruction_breakpoints(char *buf, int local, int global)
{
int i;
for (i = 0; i < 4; i++) {
set_breakpoint_addr(dummy_funcs[i], i);
toggle_breakpoint(i, BP_X, 1, local, global, 1);
ptrace(PTRACE_CONT, child_pid, NULL, 0);
sprintf(buf, "Test breakpoint %d with local: %d global: %d",
i, local, global);
check_success(buf);
toggle_breakpoint(i, BP_X, 1, local, global, 0);
}
}
static void launch_watchpoints(char *buf, int mode, int len,
int local, int global)
{
const char *mode_str;
int i;
if (mode == BP_W)
mode_str = "write";
else
mode_str = "read";
for (i = 0; i < 4; i++) {
set_breakpoint_addr(&dummy_var[i], i);
toggle_breakpoint(i, mode, len, local, global, 1);
ptrace(PTRACE_CONT, child_pid, NULL, 0);
sprintf(buf, "Test %s watchpoint %d with len: %d local: "
"%d global: %d", mode_str, i, len, local, global);
check_success(buf);
toggle_breakpoint(i, mode, len, local, global, 0);
}
}
/* Set the breakpoints and check the child successfully trigger them */
static void launch_tests(void)
{
char buf[1024];
int len, local, global, i;
/* Instruction breakpoints */
for (local = 0; local < 2; local++) {
for (global = 0; global < 2; global++) {
if (!local && !global)
continue;
launch_instruction_breakpoints(buf, local, global);
}
}
/* Write watchpoint */
for (len = 1; len <= sizeof(long); len <<= 1) {
for (local = 0; local < 2; local++) {
for (global = 0; global < 2; global++) {
if (!local && !global)
continue;
launch_watchpoints(buf, BP_W, len,
local, global);
}
}
}
/* Read-Write watchpoint */
for (len = 1; len <= sizeof(long); len <<= 1) {
for (local = 0; local < 2; local++) {
for (global = 0; global < 2; global++) {
if (!local && !global)
continue;
launch_watchpoints(buf, BP_RW, len,
local, global);
}
}
}
/* Icebp traps */
ptrace(PTRACE_CONT, child_pid, NULL, 0);
check_success("Test icebp");
/* Int 3 traps */
ptrace(PTRACE_CONT, child_pid, NULL, 0);
check_success("Test int 3 trap");
ptrace(PTRACE_CONT, child_pid, NULL, 0);
}
int main(int argc, char **argv)
{
pid_t pid;
int ret;
pid = fork();
if (!pid) {
trigger_tests();
return 0;
}
child_pid = pid;
wait(NULL);
launch_tests();
wait(NULL);
return 0;
}
| gpl-2.0 |
ion-storm/Unleashed-N5 | arch/powerpc/platforms/cell/spufs/backing_ops.c | 9349 | 11126 | /* backing_ops.c - query/set operations on saved SPU context.
*
* Copyright (C) IBM 2005
* Author: Mark Nutter <mnutter@us.ibm.com>
*
* These register operations allow SPUFS to operate on saved
* SPU contexts rather than hardware.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/vmalloc.h>
#include <linux/smp.h>
#include <linux/stddef.h>
#include <linux/unistd.h>
#include <linux/poll.h>
#include <asm/io.h>
#include <asm/spu.h>
#include <asm/spu_csa.h>
#include <asm/spu_info.h>
#include <asm/mmu_context.h>
#include "spufs.h"
/*
* Reads/writes to various problem and priv2 registers require
* state changes, i.e. generate SPU events, modify channel
* counts, etc.
*/
static void gen_spu_event(struct spu_context *ctx, u32 event)
{
u64 ch0_cnt;
u64 ch0_data;
u64 ch1_data;
ch0_cnt = ctx->csa.spu_chnlcnt_RW[0];
ch0_data = ctx->csa.spu_chnldata_RW[0];
ch1_data = ctx->csa.spu_chnldata_RW[1];
ctx->csa.spu_chnldata_RW[0] |= event;
if ((ch0_cnt == 0) && !(ch0_data & event) && (ch1_data & event)) {
ctx->csa.spu_chnlcnt_RW[0] = 1;
}
}
static int spu_backing_mbox_read(struct spu_context *ctx, u32 * data)
{
u32 mbox_stat;
int ret = 0;
spin_lock(&ctx->csa.register_lock);
mbox_stat = ctx->csa.prob.mb_stat_R;
if (mbox_stat & 0x0000ff) {
/* Read the first available word.
* Implementation note: the depth
* of pu_mb_R is currently 1.
*/
*data = ctx->csa.prob.pu_mb_R;
ctx->csa.prob.mb_stat_R &= ~(0x0000ff);
ctx->csa.spu_chnlcnt_RW[28] = 1;
gen_spu_event(ctx, MFC_PU_MAILBOX_AVAILABLE_EVENT);
ret = 4;
}
spin_unlock(&ctx->csa.register_lock);
return ret;
}
static u32 spu_backing_mbox_stat_read(struct spu_context *ctx)
{
return ctx->csa.prob.mb_stat_R;
}
static unsigned int spu_backing_mbox_stat_poll(struct spu_context *ctx,
unsigned int events)
{
int ret;
u32 stat;
ret = 0;
spin_lock_irq(&ctx->csa.register_lock);
stat = ctx->csa.prob.mb_stat_R;
/* if the requested event is there, return the poll
mask, otherwise enable the interrupt to get notified,
but first mark any pending interrupts as done so
we don't get woken up unnecessarily */
if (events & (POLLIN | POLLRDNORM)) {
if (stat & 0xff0000)
ret |= POLLIN | POLLRDNORM;
else {
ctx->csa.priv1.int_stat_class2_RW &=
~CLASS2_MAILBOX_INTR;
ctx->csa.priv1.int_mask_class2_RW |=
CLASS2_ENABLE_MAILBOX_INTR;
}
}
if (events & (POLLOUT | POLLWRNORM)) {
if (stat & 0x00ff00)
ret = POLLOUT | POLLWRNORM;
else {
ctx->csa.priv1.int_stat_class2_RW &=
~CLASS2_MAILBOX_THRESHOLD_INTR;
ctx->csa.priv1.int_mask_class2_RW |=
CLASS2_ENABLE_MAILBOX_THRESHOLD_INTR;
}
}
spin_unlock_irq(&ctx->csa.register_lock);
return ret;
}
static int spu_backing_ibox_read(struct spu_context *ctx, u32 * data)
{
int ret;
spin_lock(&ctx->csa.register_lock);
if (ctx->csa.prob.mb_stat_R & 0xff0000) {
/* Read the first available word.
* Implementation note: the depth
* of puint_mb_R is currently 1.
*/
*data = ctx->csa.priv2.puint_mb_R;
ctx->csa.prob.mb_stat_R &= ~(0xff0000);
ctx->csa.spu_chnlcnt_RW[30] = 1;
gen_spu_event(ctx, MFC_PU_INT_MAILBOX_AVAILABLE_EVENT);
ret = 4;
} else {
/* make sure we get woken up by the interrupt */
ctx->csa.priv1.int_mask_class2_RW |= CLASS2_ENABLE_MAILBOX_INTR;
ret = 0;
}
spin_unlock(&ctx->csa.register_lock);
return ret;
}
static int spu_backing_wbox_write(struct spu_context *ctx, u32 data)
{
int ret;
spin_lock(&ctx->csa.register_lock);
if ((ctx->csa.prob.mb_stat_R) & 0x00ff00) {
int slot = ctx->csa.spu_chnlcnt_RW[29];
int avail = (ctx->csa.prob.mb_stat_R & 0x00ff00) >> 8;
/* We have space to write wbox_data.
* Implementation note: the depth
* of spu_mb_W is currently 4.
*/
BUG_ON(avail != (4 - slot));
ctx->csa.spu_mailbox_data[slot] = data;
ctx->csa.spu_chnlcnt_RW[29] = ++slot;
ctx->csa.prob.mb_stat_R &= ~(0x00ff00);
ctx->csa.prob.mb_stat_R |= (((4 - slot) & 0xff) << 8);
gen_spu_event(ctx, MFC_SPU_MAILBOX_WRITTEN_EVENT);
ret = 4;
} else {
/* make sure we get woken up by the interrupt when space
becomes available */
ctx->csa.priv1.int_mask_class2_RW |=
CLASS2_ENABLE_MAILBOX_THRESHOLD_INTR;
ret = 0;
}
spin_unlock(&ctx->csa.register_lock);
return ret;
}
static u32 spu_backing_signal1_read(struct spu_context *ctx)
{
return ctx->csa.spu_chnldata_RW[3];
}
static void spu_backing_signal1_write(struct spu_context *ctx, u32 data)
{
spin_lock(&ctx->csa.register_lock);
if (ctx->csa.priv2.spu_cfg_RW & 0x1)
ctx->csa.spu_chnldata_RW[3] |= data;
else
ctx->csa.spu_chnldata_RW[3] = data;
ctx->csa.spu_chnlcnt_RW[3] = 1;
gen_spu_event(ctx, MFC_SIGNAL_1_EVENT);
spin_unlock(&ctx->csa.register_lock);
}
static u32 spu_backing_signal2_read(struct spu_context *ctx)
{
return ctx->csa.spu_chnldata_RW[4];
}
static void spu_backing_signal2_write(struct spu_context *ctx, u32 data)
{
spin_lock(&ctx->csa.register_lock);
if (ctx->csa.priv2.spu_cfg_RW & 0x2)
ctx->csa.spu_chnldata_RW[4] |= data;
else
ctx->csa.spu_chnldata_RW[4] = data;
ctx->csa.spu_chnlcnt_RW[4] = 1;
gen_spu_event(ctx, MFC_SIGNAL_2_EVENT);
spin_unlock(&ctx->csa.register_lock);
}
static void spu_backing_signal1_type_set(struct spu_context *ctx, u64 val)
{
u64 tmp;
spin_lock(&ctx->csa.register_lock);
tmp = ctx->csa.priv2.spu_cfg_RW;
if (val)
tmp |= 1;
else
tmp &= ~1;
ctx->csa.priv2.spu_cfg_RW = tmp;
spin_unlock(&ctx->csa.register_lock);
}
static u64 spu_backing_signal1_type_get(struct spu_context *ctx)
{
return ((ctx->csa.priv2.spu_cfg_RW & 1) != 0);
}
static void spu_backing_signal2_type_set(struct spu_context *ctx, u64 val)
{
u64 tmp;
spin_lock(&ctx->csa.register_lock);
tmp = ctx->csa.priv2.spu_cfg_RW;
if (val)
tmp |= 2;
else
tmp &= ~2;
ctx->csa.priv2.spu_cfg_RW = tmp;
spin_unlock(&ctx->csa.register_lock);
}
static u64 spu_backing_signal2_type_get(struct spu_context *ctx)
{
return ((ctx->csa.priv2.spu_cfg_RW & 2) != 0);
}
static u32 spu_backing_npc_read(struct spu_context *ctx)
{
return ctx->csa.prob.spu_npc_RW;
}
static void spu_backing_npc_write(struct spu_context *ctx, u32 val)
{
ctx->csa.prob.spu_npc_RW = val;
}
static u32 spu_backing_status_read(struct spu_context *ctx)
{
return ctx->csa.prob.spu_status_R;
}
static char *spu_backing_get_ls(struct spu_context *ctx)
{
return ctx->csa.lscsa->ls;
}
static void spu_backing_privcntl_write(struct spu_context *ctx, u64 val)
{
ctx->csa.priv2.spu_privcntl_RW = val;
}
static u32 spu_backing_runcntl_read(struct spu_context *ctx)
{
return ctx->csa.prob.spu_runcntl_RW;
}
static void spu_backing_runcntl_write(struct spu_context *ctx, u32 val)
{
spin_lock(&ctx->csa.register_lock);
ctx->csa.prob.spu_runcntl_RW = val;
if (val & SPU_RUNCNTL_RUNNABLE) {
ctx->csa.prob.spu_status_R &=
~SPU_STATUS_STOPPED_BY_STOP &
~SPU_STATUS_STOPPED_BY_HALT &
~SPU_STATUS_SINGLE_STEP &
~SPU_STATUS_INVALID_INSTR &
~SPU_STATUS_INVALID_CH;
ctx->csa.prob.spu_status_R |= SPU_STATUS_RUNNING;
} else {
ctx->csa.prob.spu_status_R &= ~SPU_STATUS_RUNNING;
}
spin_unlock(&ctx->csa.register_lock);
}
static void spu_backing_runcntl_stop(struct spu_context *ctx)
{
spu_backing_runcntl_write(ctx, SPU_RUNCNTL_STOP);
}
static void spu_backing_master_start(struct spu_context *ctx)
{
struct spu_state *csa = &ctx->csa;
u64 sr1;
spin_lock(&csa->register_lock);
sr1 = csa->priv1.mfc_sr1_RW | MFC_STATE1_MASTER_RUN_CONTROL_MASK;
csa->priv1.mfc_sr1_RW = sr1;
spin_unlock(&csa->register_lock);
}
static void spu_backing_master_stop(struct spu_context *ctx)
{
struct spu_state *csa = &ctx->csa;
u64 sr1;
spin_lock(&csa->register_lock);
sr1 = csa->priv1.mfc_sr1_RW & ~MFC_STATE1_MASTER_RUN_CONTROL_MASK;
csa->priv1.mfc_sr1_RW = sr1;
spin_unlock(&csa->register_lock);
}
static int spu_backing_set_mfc_query(struct spu_context * ctx, u32 mask,
u32 mode)
{
struct spu_problem_collapsed *prob = &ctx->csa.prob;
int ret;
spin_lock(&ctx->csa.register_lock);
ret = -EAGAIN;
if (prob->dma_querytype_RW)
goto out;
ret = 0;
/* FIXME: what are the side-effects of this? */
prob->dma_querymask_RW = mask;
prob->dma_querytype_RW = mode;
/* In the current implementation, the SPU context is always
* acquired in runnable state when new bits are added to the
* mask (tagwait), so it's sufficient just to mask
* dma_tagstatus_R with the 'mask' parameter here.
*/
ctx->csa.prob.dma_tagstatus_R &= mask;
out:
spin_unlock(&ctx->csa.register_lock);
return ret;
}
static u32 spu_backing_read_mfc_tagstatus(struct spu_context * ctx)
{
return ctx->csa.prob.dma_tagstatus_R;
}
static u32 spu_backing_get_mfc_free_elements(struct spu_context *ctx)
{
return ctx->csa.prob.dma_qstatus_R;
}
static int spu_backing_send_mfc_command(struct spu_context *ctx,
struct mfc_dma_command *cmd)
{
int ret;
spin_lock(&ctx->csa.register_lock);
ret = -EAGAIN;
/* FIXME: set up priv2->puq */
spin_unlock(&ctx->csa.register_lock);
return ret;
}
static void spu_backing_restart_dma(struct spu_context *ctx)
{
ctx->csa.priv2.mfc_control_RW |= MFC_CNTL_RESTART_DMA_COMMAND;
}
struct spu_context_ops spu_backing_ops = {
.mbox_read = spu_backing_mbox_read,
.mbox_stat_read = spu_backing_mbox_stat_read,
.mbox_stat_poll = spu_backing_mbox_stat_poll,
.ibox_read = spu_backing_ibox_read,
.wbox_write = spu_backing_wbox_write,
.signal1_read = spu_backing_signal1_read,
.signal1_write = spu_backing_signal1_write,
.signal2_read = spu_backing_signal2_read,
.signal2_write = spu_backing_signal2_write,
.signal1_type_set = spu_backing_signal1_type_set,
.signal1_type_get = spu_backing_signal1_type_get,
.signal2_type_set = spu_backing_signal2_type_set,
.signal2_type_get = spu_backing_signal2_type_get,
.npc_read = spu_backing_npc_read,
.npc_write = spu_backing_npc_write,
.status_read = spu_backing_status_read,
.get_ls = spu_backing_get_ls,
.privcntl_write = spu_backing_privcntl_write,
.runcntl_read = spu_backing_runcntl_read,
.runcntl_write = spu_backing_runcntl_write,
.runcntl_stop = spu_backing_runcntl_stop,
.master_start = spu_backing_master_start,
.master_stop = spu_backing_master_stop,
.set_mfc_query = spu_backing_set_mfc_query,
.read_mfc_tagstatus = spu_backing_read_mfc_tagstatus,
.get_mfc_free_elements = spu_backing_get_mfc_free_elements,
.send_mfc_command = spu_backing_send_mfc_command,
.restart_dma = spu_backing_restart_dma,
};
| gpl-2.0 |
ics2/kernelics | arch/sh/drivers/superhyway/ops-sh4-202.c | 13189 | 4205 | /*
* arch/sh/drivers/superhyway/ops-sh4-202.c
*
* SuperHyway bus support for SH4-202
*
* Copyright (C) 2005 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/kernel.h>
#include <linux/init.h>
#include <linux/superhyway.h>
#include <linux/string.h>
#include <asm/addrspace.h>
#include <asm/io.h>
#define PHYS_EMI_CBLOCK P4SEGADDR(0x1ec00000)
#define PHYS_EMI_DBLOCK P4SEGADDR(0x08000000)
#define PHYS_FEMI_CBLOCK P4SEGADDR(0x1f800000)
#define PHYS_FEMI_DBLOCK P4SEGADDR(0x00000000)
#define PHYS_EPBR_BLOCK P4SEGADDR(0x1de00000)
#define PHYS_DMAC_BLOCK P4SEGADDR(0x1fa00000)
#define PHYS_PBR_BLOCK P4SEGADDR(0x1fc00000)
static struct resource emi_resources[] = {
[0] = {
.start = PHYS_EMI_CBLOCK,
.end = PHYS_EMI_CBLOCK + 0x00300000 - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = PHYS_EMI_DBLOCK,
.end = PHYS_EMI_DBLOCK + 0x08000000 - 1,
.flags = IORESOURCE_MEM,
},
};
static struct superhyway_device emi_device = {
.name = "emi",
.num_resources = ARRAY_SIZE(emi_resources),
.resource = emi_resources,
};
static struct resource femi_resources[] = {
[0] = {
.start = PHYS_FEMI_CBLOCK,
.end = PHYS_FEMI_CBLOCK + 0x00100000 - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = PHYS_FEMI_DBLOCK,
.end = PHYS_FEMI_DBLOCK + 0x08000000 - 1,
.flags = IORESOURCE_MEM,
},
};
static struct superhyway_device femi_device = {
.name = "femi",
.num_resources = ARRAY_SIZE(femi_resources),
.resource = femi_resources,
};
static struct resource epbr_resources[] = {
[0] = {
.start = P4SEGADDR(0x1e7ffff8),
.end = P4SEGADDR(0x1e7ffff8 + (sizeof(u32) * 2) - 1),
.flags = IORESOURCE_MEM,
},
[1] = {
.start = PHYS_EPBR_BLOCK,
.end = PHYS_EPBR_BLOCK + 0x00a00000 - 1,
.flags = IORESOURCE_MEM,
},
};
static struct superhyway_device epbr_device = {
.name = "epbr",
.num_resources = ARRAY_SIZE(epbr_resources),
.resource = epbr_resources,
};
static struct resource dmac_resource = {
.start = PHYS_DMAC_BLOCK,
.end = PHYS_DMAC_BLOCK + 0x00100000 - 1,
.flags = IORESOURCE_MEM,
};
static struct superhyway_device dmac_device = {
.name = "dmac",
.num_resources = 1,
.resource = &dmac_resource,
};
static struct resource pbr_resources[] = {
[0] = {
.start = P4SEGADDR(0x1ffffff8),
.end = P4SEGADDR(0x1ffffff8 + (sizeof(u32) * 2) - 1),
.flags = IORESOURCE_MEM,
},
[1] = {
.start = PHYS_PBR_BLOCK,
.end = PHYS_PBR_BLOCK + 0x00400000 - (sizeof(u32) * 2) - 1,
.flags = IORESOURCE_MEM,
},
};
static struct superhyway_device pbr_device = {
.name = "pbr",
.num_resources = ARRAY_SIZE(pbr_resources),
.resource = pbr_resources,
};
static struct superhyway_device *sh4202_devices[] __initdata = {
&emi_device, &femi_device, &epbr_device, &dmac_device, &pbr_device,
};
static int sh4202_read_vcr(unsigned long base, struct superhyway_vcr_info *vcr)
{
u32 vcrh, vcrl;
u64 tmp;
/*
* XXX: Even though the SH4-202 Evaluation Device documentation
* indicates that VCRL is mapped first with VCRH at a + 0x04
* offset, the opposite seems to be true.
*
* Some modules (PBR and ePBR for instance) also appear to have
* VCRL/VCRH flipped in the documentation, but on the SH4-202
* itself it appears that these are all consistently mapped with
* VCRH preceding VCRL.
*
* Do not trust the documentation, for it is evil.
*/
vcrh = __raw_readl(base);
vcrl = __raw_readl(base + sizeof(u32));
tmp = ((u64)vcrh << 32) | vcrl;
memcpy(vcr, &tmp, sizeof(u64));
return 0;
}
static int sh4202_write_vcr(unsigned long base, struct superhyway_vcr_info vcr)
{
u64 tmp = *(u64 *)&vcr;
__raw_writel((tmp >> 32) & 0xffffffff, base);
__raw_writel(tmp & 0xffffffff, base + sizeof(u32));
return 0;
}
static struct superhyway_ops sh4202_superhyway_ops = {
.read_vcr = sh4202_read_vcr,
.write_vcr = sh4202_write_vcr,
};
struct superhyway_bus superhyway_channels[] = {
{ &sh4202_superhyway_ops, },
{ 0, },
};
int __init superhyway_scan_bus(struct superhyway_bus *bus)
{
return superhyway_add_devices(bus, sh4202_devices,
ARRAY_SIZE(sh4202_devices));
}
| gpl-2.0 |
golden-guy/android_kernel_asus_grouper | drivers/parisc/ccio-rm-dma.c | 13701 | 5226 | /*
* ccio-rm-dma.c:
* DMA management routines for first generation cache-coherent machines.
* "Real Mode" operation refers to U2/Uturn chip operation. The chip
* can perform coherency checks w/o using the I/O MMU. That's all we
* need until support for more than 4GB phys mem is needed.
*
* This is the trivial case - basically what x86 does.
*
* Drawbacks of using Real Mode are:
* o outbound DMA is slower since one isn't using the prefetching
* U2 can do for outbound DMA.
* o Ability to do scatter/gather in HW is also lost.
* o only known to work with PCX-W processor. (eg C360)
* (PCX-U/U+ are not coherent with U2 in real mode.)
*
*
* 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.
*
*
* Original version/author:
* CVSROOT=:pserver:anonymous@198.186.203.37:/cvsroot/linux-parisc
* cvs -z3 co linux/arch/parisc/kernel/dma-rm.c
*
* (C) Copyright 2000 Philipp Rumpf <prumpf@tux.org>
*
*
* Adopted for The Puffin Group's parisc-linux port by Grant Grundler.
* (C) Copyright 2000 Grant Grundler <grundler@puffin.external.hp.com>
*
*/
#include <linux/types.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/string.h>
#include <linux/pci.h>
#include <linux/gfp.h>
#include <asm/uaccess.h>
#include <asm/io.h>
#include <asm/hardware.h>
#include <asm/page.h>
/* Only chose "ccio" since that's what HP-UX calls it....
** Make it easier for folks to migrate from one to the other :^)
*/
#define MODULE_NAME "ccio"
#define U2_IOA_RUNWAY 0x580
#define U2_BC_GSC 0x501
#define UTURN_IOA_RUNWAY 0x581
#define UTURN_BC_GSC 0x502
#define IS_U2(id) ( \
(((id)->hw_type == HPHW_IOA) && ((id)->hversion == U2_IOA_RUNWAY)) || \
(((id)->hw_type == HPHW_BCPORT) && ((id)->hversion == U2_BC_GSC)) \
)
#define IS_UTURN(id) ( \
(((id)->hw_type == HPHW_IOA) && ((id)->hversion == UTURN_IOA_RUNWAY)) || \
(((id)->hw_type == HPHW_BCPORT) && ((id)->hversion == UTURN_BC_GSC)) \
)
static int ccio_dma_supported( struct pci_dev *dev, u64 mask)
{
if (dev == NULL) {
printk(KERN_ERR MODULE_NAME ": EISA/ISA/et al not supported\n");
BUG();
return(0);
}
/* only support 32-bit devices (ie PCI/GSC) */
return((int) (mask >= 0xffffffffUL));
}
static void *ccio_alloc_consistent(struct pci_dev *dev, size_t size,
dma_addr_t *handle)
{
void *ret;
ret = (void *)__get_free_pages(GFP_ATOMIC, get_order(size));
if (ret != NULL) {
memset(ret, 0, size);
*handle = virt_to_phys(ret);
}
return ret;
}
static void ccio_free_consistent(struct pci_dev *dev, size_t size,
void *vaddr, dma_addr_t handle)
{
free_pages((unsigned long)vaddr, get_order(size));
}
static dma_addr_t ccio_map_single(struct pci_dev *dev, void *ptr, size_t size,
int direction)
{
return virt_to_phys(ptr);
}
static void ccio_unmap_single(struct pci_dev *dev, dma_addr_t dma_addr,
size_t size, int direction)
{
/* Nothing to do */
}
static int ccio_map_sg(struct pci_dev *dev, struct scatterlist *sglist, int nents, int direction)
{
int tmp = nents;
/* KISS: map each buffer separately. */
while (nents) {
sg_dma_address(sglist) = ccio_map_single(dev, sglist->address, sglist->length, direction);
sg_dma_len(sglist) = sglist->length;
nents--;
sglist++;
}
return tmp;
}
static void ccio_unmap_sg(struct pci_dev *dev, struct scatterlist *sglist, int nents, int direction)
{
#if 0
while (nents) {
ccio_unmap_single(dev, sg_dma_address(sglist), sg_dma_len(sglist), direction);
nents--;
sglist++;
}
return;
#else
/* Do nothing (copied from current ccio_unmap_single() :^) */
#endif
}
static struct pci_dma_ops ccio_ops = {
ccio_dma_supported,
ccio_alloc_consistent,
ccio_free_consistent,
ccio_map_single,
ccio_unmap_single,
ccio_map_sg,
ccio_unmap_sg,
NULL, /* dma_sync_single_for_cpu : NOP for U2 */
NULL, /* dma_sync_single_for_device : NOP for U2 */
NULL, /* dma_sync_sg_for_cpu : ditto */
NULL, /* dma_sync_sg_for_device : ditto */
};
/*
** Determine if u2 should claim this chip (return 0) or not (return 1).
** If so, initialize the chip and tell other partners in crime they
** have work to do.
*/
static int
ccio_probe(struct parisc_device *dev)
{
printk(KERN_INFO "%s found %s at 0x%lx\n", MODULE_NAME,
dev->id.hversion == U2_BC_GSC ? "U2" : "UTurn",
dev->hpa.start);
/*
** FIXME - should check U2 registers to verify it's really running
** in "Real Mode".
*/
#if 0
/* will need this for "Virtual Mode" operation */
ccio_hw_init(ccio_dev);
ccio_common_init(ccio_dev);
#endif
hppa_dma_ops = &ccio_ops;
return 0;
}
static struct parisc_device_id ccio_tbl[] = {
{ HPHW_BCPORT, HVERSION_REV_ANY_ID, U2_BC_GSC, 0xc },
{ HPHW_BCPORT, HVERSION_REV_ANY_ID, UTURN_BC_GSC, 0xc },
{ 0, }
};
static struct parisc_driver ccio_driver = {
.name = "U2/Uturn",
.id_table = ccio_tbl,
.probe = ccio_probe,
};
void __init ccio_init(void)
{
register_parisc_driver(&ccio_driver);
}
| gpl-2.0 |
loongson-community/linux-3A | drivers/staging/comedi/drivers/adv_pci1710.c | 134 | 48263 | /*
* comedi/drivers/adv_pci1710.c
*
* Author: Michal Dobes <dobes@tesnet.cz>
*
* Thanks to ZhenGang Shang <ZhenGang.Shang@Advantech.com.cn>
* for testing and informations.
*
* hardware driver for Advantech cards:
* card: PCI-1710, PCI-1710HG, PCI-1711, PCI-1713, PCI-1720, PCI-1731
* driver: pci1710, pci1710hg, pci1711, pci1713, pci1720, pci1731
*
* Options:
* [0] - PCI bus number - if bus number and slot number are 0,
* then driver search for first unused card
* [1] - PCI slot number
*
*/
/*
Driver: adv_pci1710
Description: Advantech PCI-1710, PCI-1710HG, PCI-1711, PCI-1713,
Advantech PCI-1720, PCI-1731
Author: Michal Dobes <dobes@tesnet.cz>
Devices: [Advantech] PCI-1710 (adv_pci1710), PCI-1710HG (pci1710hg),
PCI-1711 (adv_pci1710), PCI-1713, PCI-1720,
PCI-1731
Status: works
This driver supports AI, AO, DI and DO subdevices.
AI subdevice supports cmd and insn interface,
other subdevices support only insn interface.
The PCI-1710 and PCI-1710HG have the same PCI device ID, so the
driver cannot distinguish between them, as would be normal for a
PCI driver.
Configuration options:
[0] - PCI bus of device (optional)
[1] - PCI slot of device (optional)
If bus/slot is not specified, the first available PCI
device will be used.
*/
#include <linux/interrupt.h>
#include "../comedidev.h"
#include "comedi_pci.h"
#include "8253.h"
#include "amcc_s5933.h"
#define PCI171x_PARANOIDCHECK /* if defined, then is used code which control
* correct channel number on every 12 bit
* sample */
#undef PCI171X_EXTDEBUG
#define DRV_NAME "adv_pci1710"
#undef DPRINTK
#ifdef PCI171X_EXTDEBUG
#define DPRINTK(fmt, args...) printk(fmt, ## args)
#else
#define DPRINTK(fmt, args...)
#endif
#define PCI_VENDOR_ID_ADVANTECH 0x13fe
/* hardware types of the cards */
#define TYPE_PCI171X 0
#define TYPE_PCI1713 2
#define TYPE_PCI1720 3
#define IORANGE_171x 32
#define IORANGE_1720 16
#define PCI171x_AD_DATA 0 /* R: A/D data */
#define PCI171x_SOFTTRG 0 /* W: soft trigger for A/D */
#define PCI171x_RANGE 2 /* W: A/D gain/range register */
#define PCI171x_MUX 4 /* W: A/D multiplexor control */
#define PCI171x_STATUS 6 /* R: status register */
#define PCI171x_CONTROL 6 /* W: control register */
#define PCI171x_CLRINT 8 /* W: clear interrupts request */
#define PCI171x_CLRFIFO 9 /* W: clear FIFO */
#define PCI171x_DA1 10 /* W: D/A register */
#define PCI171x_DA2 12 /* W: D/A register */
#define PCI171x_DAREF 14 /* W: D/A reference control */
#define PCI171x_DI 16 /* R: digi inputs */
#define PCI171x_DO 16 /* R: digi inputs */
#define PCI171x_CNT0 24 /* R/W: 8254 counter 0 */
#define PCI171x_CNT1 26 /* R/W: 8254 counter 1 */
#define PCI171x_CNT2 28 /* R/W: 8254 counter 2 */
#define PCI171x_CNTCTRL 30 /* W: 8254 counter control */
/* upper bits from status register (PCI171x_STATUS) (lower is same with control
* reg) */
#define Status_FE 0x0100 /* 1=FIFO is empty */
#define Status_FH 0x0200 /* 1=FIFO is half full */
#define Status_FF 0x0400 /* 1=FIFO is full, fatal error */
#define Status_IRQ 0x0800 /* 1=IRQ occured */
/* bits from control register (PCI171x_CONTROL) */
#define Control_CNT0 0x0040 /* 1=CNT0 have external source,
* 0=have internal 100kHz source */
#define Control_ONEFH 0x0020 /* 1=IRQ on FIFO is half full, 0=every sample */
#define Control_IRQEN 0x0010 /* 1=enable IRQ */
#define Control_GATE 0x0008 /* 1=enable external trigger GATE (8254?) */
#define Control_EXT 0x0004 /* 1=external trigger source */
#define Control_PACER 0x0002 /* 1=enable internal 8254 trigger source */
#define Control_SW 0x0001 /* 1=enable software trigger source */
/* bits from counter control register (PCI171x_CNTCTRL) */
#define Counter_BCD 0x0001 /* 0 = binary counter, 1 = BCD counter */
#define Counter_M0 0x0002 /* M0-M2 select modes 0-5 */
#define Counter_M1 0x0004 /* 000 = mode 0, 010 = mode 2 ... */
#define Counter_M2 0x0008
#define Counter_RW0 0x0010 /* RW0/RW1 select read/write mode */
#define Counter_RW1 0x0020
#define Counter_SC0 0x0040 /* Select Counter. Only 00 or 11 may */
#define Counter_SC1 0x0080 /* be used, 00 for CNT0,
* 11 for read-back command */
#define PCI1720_DA0 0 /* W: D/A register 0 */
#define PCI1720_DA1 2 /* W: D/A register 1 */
#define PCI1720_DA2 4 /* W: D/A register 2 */
#define PCI1720_DA3 6 /* W: D/A register 3 */
#define PCI1720_RANGE 8 /* R/W: D/A range register */
#define PCI1720_SYNCOUT 9 /* W: D/A synchronized output register */
#define PCI1720_SYNCONT 15 /* R/W: D/A synchronized control */
/* D/A synchronized control (PCI1720_SYNCONT) */
#define Syncont_SC0 1 /* set synchronous output mode */
static const struct comedi_lrange range_pci1710_3 = { 9, {
BIP_RANGE(5),
BIP_RANGE(2.5),
BIP_RANGE(1.25),
BIP_RANGE(0.625),
BIP_RANGE(10),
UNI_RANGE(10),
UNI_RANGE(5),
UNI_RANGE(2.5),
UNI_RANGE(1.25)
}
};
static const char range_codes_pci1710_3[] = { 0x00, 0x01, 0x02, 0x03, 0x04,
0x10, 0x11, 0x12, 0x13 };
static const struct comedi_lrange range_pci1710hg = { 12, {
BIP_RANGE(5),
BIP_RANGE(0.5),
BIP_RANGE(0.05),
BIP_RANGE(0.005),
BIP_RANGE(10),
BIP_RANGE(1),
BIP_RANGE(0.1),
BIP_RANGE(0.01),
UNI_RANGE(10),
UNI_RANGE(1),
UNI_RANGE(0.1),
UNI_RANGE(0.01)
}
};
static const char range_codes_pci1710hg[] = { 0x00, 0x01, 0x02, 0x03, 0x04,
0x05, 0x06, 0x07, 0x10, 0x11,
0x12, 0x13 };
static const struct comedi_lrange range_pci17x1 = { 5, {
BIP_RANGE(10),
BIP_RANGE(5),
BIP_RANGE(2.5),
BIP_RANGE(1.25),
BIP_RANGE(0.625)
}
};
static const char range_codes_pci17x1[] = { 0x00, 0x01, 0x02, 0x03, 0x04 };
static const struct comedi_lrange range_pci1720 = { 4, {
UNI_RANGE(5),
UNI_RANGE(10),
BIP_RANGE(5),
BIP_RANGE(10)
}
};
static const struct comedi_lrange range_pci171x_da = { 2, {
UNI_RANGE(5),
UNI_RANGE(10),
}
};
static int pci1710_attach(struct comedi_device *dev,
struct comedi_devconfig *it);
static int pci1710_detach(struct comedi_device *dev);
struct boardtype {
const char *name; /* board name */
int device_id;
int iorange; /* I/O range len */
char have_irq; /* 1=card support IRQ */
char cardtype; /* 0=1710& co. 2=1713, ... */
int n_aichan; /* num of A/D chans */
int n_aichand; /* num of A/D chans in diff mode */
int n_aochan; /* num of D/A chans */
int n_dichan; /* num of DI chans */
int n_dochan; /* num of DO chans */
int n_counter; /* num of counters */
int ai_maxdata; /* resolution of A/D */
int ao_maxdata; /* resolution of D/A */
const struct comedi_lrange *rangelist_ai; /* rangelist for A/D */
const char *rangecode_ai; /* range codes for programming */
const struct comedi_lrange *rangelist_ao; /* rangelist for D/A */
unsigned int ai_ns_min; /* max sample speed of card v ns */
unsigned int fifo_half_size; /* size of FIFO/2 */
};
static DEFINE_PCI_DEVICE_TABLE(pci1710_pci_table) = {
{
PCI_VENDOR_ID_ADVANTECH, 0x1710, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {
PCI_VENDOR_ID_ADVANTECH, 0x1711, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {
PCI_VENDOR_ID_ADVANTECH, 0x1713, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {
PCI_VENDOR_ID_ADVANTECH, 0x1720, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {
PCI_VENDOR_ID_ADVANTECH, 0x1731, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, {
0}
};
MODULE_DEVICE_TABLE(pci, pci1710_pci_table);
static const struct boardtype boardtypes[] = {
{"pci1710", 0x1710,
IORANGE_171x, 1, TYPE_PCI171X,
16, 8, 2, 16, 16, 1, 0x0fff, 0x0fff,
&range_pci1710_3, range_codes_pci1710_3,
&range_pci171x_da,
10000, 2048},
{"pci1710hg", 0x1710,
IORANGE_171x, 1, TYPE_PCI171X,
16, 8, 2, 16, 16, 1, 0x0fff, 0x0fff,
&range_pci1710hg, range_codes_pci1710hg,
&range_pci171x_da,
10000, 2048},
{"pci1711", 0x1711,
IORANGE_171x, 1, TYPE_PCI171X,
16, 0, 2, 16, 16, 1, 0x0fff, 0x0fff,
&range_pci17x1, range_codes_pci17x1, &range_pci171x_da,
10000, 512},
{"pci1713", 0x1713,
IORANGE_171x, 1, TYPE_PCI1713,
32, 16, 0, 0, 0, 0, 0x0fff, 0x0000,
&range_pci1710_3, range_codes_pci1710_3, NULL,
10000, 2048},
{"pci1720", 0x1720,
IORANGE_1720, 0, TYPE_PCI1720,
0, 0, 4, 0, 0, 0, 0x0000, 0x0fff,
NULL, NULL, &range_pci1720,
0, 0},
{"pci1731", 0x1731,
IORANGE_171x, 1, TYPE_PCI171X,
16, 0, 0, 16, 16, 0, 0x0fff, 0x0000,
&range_pci17x1, range_codes_pci17x1, NULL,
10000, 512},
/* dummy entry corresponding to driver name */
{.name = DRV_NAME},
};
#define n_boardtypes (sizeof(boardtypes)/sizeof(struct boardtype))
static struct comedi_driver driver_pci1710 = {
.driver_name = DRV_NAME,
.module = THIS_MODULE,
.attach = pci1710_attach,
.detach = pci1710_detach,
.num_names = n_boardtypes,
.board_name = &boardtypes[0].name,
.offset = sizeof(struct boardtype),
};
struct pci1710_private {
struct pci_dev *pcidev; /* ptr to PCI device */
char valid; /* card is usable */
char neverending_ai; /* we do unlimited AI */
unsigned int CntrlReg; /* Control register */
unsigned int i8254_osc_base; /* frequence of onboard oscilator */
unsigned int ai_do; /* what do AI? 0=nothing, 1 to 4 mode */
unsigned int ai_act_scan; /* how many scans we finished */
unsigned int ai_act_chan; /* actual position in actual scan */
unsigned int ai_buf_ptr; /* data buffer ptr in samples */
unsigned char ai_eos; /* 1=EOS wake up */
unsigned char ai_et;
unsigned int ai_et_CntrlReg;
unsigned int ai_et_MuxVal;
unsigned int ai_et_div1, ai_et_div2;
unsigned int act_chanlist[32]; /* list of scaned channel */
unsigned char act_chanlist_len; /* len of scanlist */
unsigned char act_chanlist_pos; /* actual position in MUX list */
unsigned char da_ranges; /* copy of D/A outpit range register */
unsigned int ai_scans; /* len of scanlist */
unsigned int ai_n_chan; /* how many channels is measured */
unsigned int *ai_chanlist; /* actaul chanlist */
unsigned int ai_flags; /* flaglist */
unsigned int ai_data_len; /* len of data buffer */
short *ai_data; /* data buffer */
unsigned int ai_timer1; /* timers */
unsigned int ai_timer2;
short ao_data[4]; /* data output buffer */
unsigned int cnt0_write_wait; /* after a write, wait for update of the
* internal state */
};
#define devpriv ((struct pci1710_private *)dev->private)
#define this_board ((const struct boardtype *)dev->board_ptr)
/*
==============================================================================
*/
static int check_channel_list(struct comedi_device *dev,
struct comedi_subdevice *s,
unsigned int *chanlist, unsigned int n_chan);
static void setup_channel_list(struct comedi_device *dev,
struct comedi_subdevice *s,
unsigned int *chanlist, unsigned int n_chan,
unsigned int seglen);
static void start_pacer(struct comedi_device *dev, int mode,
unsigned int divisor1, unsigned int divisor2);
static int pci1710_reset(struct comedi_device *dev);
static int pci171x_ai_cancel(struct comedi_device *dev,
struct comedi_subdevice *s);
/* used for gain list programming */
static const unsigned int muxonechan[] = {
0x0000, 0x0101, 0x0202, 0x0303, 0x0404, 0x0505, 0x0606, 0x0707,
0x0808, 0x0909, 0x0a0a, 0x0b0b, 0x0c0c, 0x0d0d, 0x0e0e, 0x0f0f,
0x1010, 0x1111, 0x1212, 0x1313, 0x1414, 0x1515, 0x1616, 0x1717,
0x1818, 0x1919, 0x1a1a, 0x1b1b, 0x1c1c, 0x1d1d, 0x1e1e, 0x1f1f
};
/*
==============================================================================
*/
static int pci171x_insn_read_ai(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int n, timeout;
#ifdef PCI171x_PARANOIDCHECK
unsigned int idata;
#endif
DPRINTK("adv_pci1710 EDBG: BGN: pci171x_insn_read_ai(...)\n");
devpriv->CntrlReg &= Control_CNT0;
devpriv->CntrlReg |= Control_SW; /* set software trigger */
outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL);
outb(0, dev->iobase + PCI171x_CLRFIFO);
outb(0, dev->iobase + PCI171x_CLRINT);
setup_channel_list(dev, s, &insn->chanspec, 1, 1);
DPRINTK("adv_pci1710 A ST=%4x IO=%x\n",
inw(dev->iobase + PCI171x_STATUS),
dev->iobase + PCI171x_STATUS);
for (n = 0; n < insn->n; n++) {
outw(0, dev->iobase + PCI171x_SOFTTRG); /* start conversion */
DPRINTK("adv_pci1710 B n=%d ST=%4x\n", n,
inw(dev->iobase + PCI171x_STATUS));
/* udelay(1); */
DPRINTK("adv_pci1710 C n=%d ST=%4x\n", n,
inw(dev->iobase + PCI171x_STATUS));
timeout = 100;
while (timeout--) {
if (!(inw(dev->iobase + PCI171x_STATUS) & Status_FE))
goto conv_finish;
if (!(timeout % 10))
DPRINTK("adv_pci1710 D n=%d tm=%d ST=%4x\n", n,
timeout,
inw(dev->iobase + PCI171x_STATUS));
}
comedi_error(dev, "A/D insn timeout");
outb(0, dev->iobase + PCI171x_CLRFIFO);
outb(0, dev->iobase + PCI171x_CLRINT);
data[n] = 0;
DPRINTK
("adv_pci1710 EDBG: END: pci171x_insn_read_ai(...) n=%d\n",
n);
return -ETIME;
conv_finish:
#ifdef PCI171x_PARANOIDCHECK
idata = inw(dev->iobase + PCI171x_AD_DATA);
if (this_board->cardtype != TYPE_PCI1713)
if ((idata & 0xf000) != devpriv->act_chanlist[0]) {
comedi_error(dev, "A/D insn data droput!");
return -ETIME;
}
data[n] = idata & 0x0fff;
#else
data[n] = inw(dev->iobase + PCI171x_AD_DATA) & 0x0fff;
#endif
}
outb(0, dev->iobase + PCI171x_CLRFIFO);
outb(0, dev->iobase + PCI171x_CLRINT);
DPRINTK("adv_pci1710 EDBG: END: pci171x_insn_read_ai(...) n=%d\n", n);
return n;
}
/*
==============================================================================
*/
static int pci171x_insn_write_ao(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int n, chan, range, ofs;
chan = CR_CHAN(insn->chanspec);
range = CR_RANGE(insn->chanspec);
if (chan) {
devpriv->da_ranges &= 0xfb;
devpriv->da_ranges |= (range << 2);
outw(devpriv->da_ranges, dev->iobase + PCI171x_DAREF);
ofs = PCI171x_DA2;
} else {
devpriv->da_ranges &= 0xfe;
devpriv->da_ranges |= range;
outw(devpriv->da_ranges, dev->iobase + PCI171x_DAREF);
ofs = PCI171x_DA1;
}
for (n = 0; n < insn->n; n++)
outw(data[n], dev->iobase + ofs);
devpriv->ao_data[chan] = data[n];
return n;
}
/*
==============================================================================
*/
static int pci171x_insn_read_ao(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int n, chan;
chan = CR_CHAN(insn->chanspec);
for (n = 0; n < insn->n; n++)
data[n] = devpriv->ao_data[chan];
return n;
}
/*
==============================================================================
*/
static int pci171x_insn_bits_di(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
data[1] = inw(dev->iobase + PCI171x_DI);
return 2;
}
/*
==============================================================================
*/
static int pci171x_insn_bits_do(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
if (data[0]) {
s->state &= ~data[0];
s->state |= (data[0] & data[1]);
outw(s->state, dev->iobase + PCI171x_DO);
}
data[1] = s->state;
return 2;
}
/*
==============================================================================
*/
static int pci171x_insn_counter_read(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
unsigned int msb, lsb, ccntrl;
int i;
ccntrl = 0xD2; /* count only */
for (i = 0; i < insn->n; i++) {
outw(ccntrl, dev->iobase + PCI171x_CNTCTRL);
lsb = inw(dev->iobase + PCI171x_CNT0) & 0xFF;
msb = inw(dev->iobase + PCI171x_CNT0) & 0xFF;
data[0] = lsb | (msb << 8);
}
return insn->n;
}
/*
==============================================================================
*/
static int pci171x_insn_counter_write(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
uint msb, lsb, ccntrl, status;
lsb = data[0] & 0x00FF;
msb = (data[0] & 0xFF00) >> 8;
/* write lsb, then msb */
outw(lsb, dev->iobase + PCI171x_CNT0);
outw(msb, dev->iobase + PCI171x_CNT0);
if (devpriv->cnt0_write_wait) {
/* wait for the new count to be loaded */
ccntrl = 0xE2;
do {
outw(ccntrl, dev->iobase + PCI171x_CNTCTRL);
status = inw(dev->iobase + PCI171x_CNT0) & 0xFF;
} while (status & 0x40);
}
return insn->n;
}
/*
==============================================================================
*/
static int pci171x_insn_counter_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
#ifdef unused
/* This doesn't work like a normal Comedi counter config */
uint ccntrl = 0;
devpriv->cnt0_write_wait = data[0] & 0x20;
/* internal or external clock? */
if (!(data[0] & 0x10)) { /* internal */
devpriv->CntrlReg &= ~Control_CNT0;
} else {
devpriv->CntrlReg |= Control_CNT0;
}
outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL);
if (data[0] & 0x01)
ccntrl |= Counter_M0;
if (data[0] & 0x02)
ccntrl |= Counter_M1;
if (data[0] & 0x04)
ccntrl |= Counter_M2;
if (data[0] & 0x08)
ccntrl |= Counter_BCD;
ccntrl |= Counter_RW0; /* set read/write mode */
ccntrl |= Counter_RW1;
outw(ccntrl, dev->iobase + PCI171x_CNTCTRL);
#endif
return 1;
}
/*
==============================================================================
*/
static int pci1720_insn_write_ao(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int n, rangereg, chan;
chan = CR_CHAN(insn->chanspec);
rangereg = devpriv->da_ranges & (~(0x03 << (chan << 1)));
rangereg |= (CR_RANGE(insn->chanspec) << (chan << 1));
if (rangereg != devpriv->da_ranges) {
outb(rangereg, dev->iobase + PCI1720_RANGE);
devpriv->da_ranges = rangereg;
}
for (n = 0; n < insn->n; n++) {
outw(data[n], dev->iobase + PCI1720_DA0 + (chan << 1));
outb(0, dev->iobase + PCI1720_SYNCOUT); /* update outputs */
}
devpriv->ao_data[chan] = data[n];
return n;
}
/*
==============================================================================
*/
static void interrupt_pci1710_every_sample(void *d)
{
struct comedi_device *dev = d;
struct comedi_subdevice *s = dev->subdevices + 0;
int m;
#ifdef PCI171x_PARANOIDCHECK
short sampl;
#endif
DPRINTK("adv_pci1710 EDBG: BGN: interrupt_pci1710_every_sample(...)\n");
m = inw(dev->iobase + PCI171x_STATUS);
if (m & Status_FE) {
printk("comedi%d: A/D FIFO empty (%4x)\n", dev->minor, m);
pci171x_ai_cancel(dev, s);
s->async->events |= COMEDI_CB_EOA | COMEDI_CB_ERROR;
comedi_event(dev, s);
return;
}
if (m & Status_FF) {
printk
("comedi%d: A/D FIFO Full status (Fatal Error!) (%4x)\n",
dev->minor, m);
pci171x_ai_cancel(dev, s);
s->async->events |= COMEDI_CB_EOA | COMEDI_CB_ERROR;
comedi_event(dev, s);
return;
}
outb(0, dev->iobase + PCI171x_CLRINT); /* clear our INT request */
DPRINTK("FOR ");
for (; !(inw(dev->iobase + PCI171x_STATUS) & Status_FE);) {
#ifdef PCI171x_PARANOIDCHECK
sampl = inw(dev->iobase + PCI171x_AD_DATA);
DPRINTK("%04x:", sampl);
if (this_board->cardtype != TYPE_PCI1713)
if ((sampl & 0xf000) !=
devpriv->act_chanlist[s->async->cur_chan]) {
printk
("comedi: A/D data dropout: received data from channel %d, expected %d!\n",
(sampl & 0xf000) >> 12,
(devpriv->
act_chanlist[s->
async->cur_chan] & 0xf000) >>
12);
pci171x_ai_cancel(dev, s);
s->async->events |=
COMEDI_CB_EOA | COMEDI_CB_ERROR;
comedi_event(dev, s);
return;
}
DPRINTK("%8d %2d %8d~", s->async->buf_int_ptr,
s->async->cur_chan, s->async->buf_int_count);
comedi_buf_put(s->async, sampl & 0x0fff);
#else
comedi_buf_put(s->async,
inw(dev->iobase + PCI171x_AD_DATA) & 0x0fff);
#endif
++s->async->cur_chan;
if (s->async->cur_chan >= devpriv->ai_n_chan)
s->async->cur_chan = 0;
if (s->async->cur_chan == 0) { /* one scan done */
devpriv->ai_act_scan++;
DPRINTK
("adv_pci1710 EDBG: EOS1 bic %d bip %d buc %d bup %d\n",
s->async->buf_int_count, s->async->buf_int_ptr,
s->async->buf_user_count, s->async->buf_user_ptr);
DPRINTK("adv_pci1710 EDBG: EOS2\n");
if ((!devpriv->neverending_ai) && (devpriv->ai_act_scan >= devpriv->ai_scans)) { /* all data sampled */
pci171x_ai_cancel(dev, s);
s->async->events |= COMEDI_CB_EOA;
comedi_event(dev, s);
return;
}
}
}
outb(0, dev->iobase + PCI171x_CLRINT); /* clear our INT request */
DPRINTK("adv_pci1710 EDBG: END: interrupt_pci1710_every_sample(...)\n");
comedi_event(dev, s);
}
/*
==============================================================================
*/
static int move_block_from_fifo(struct comedi_device *dev,
struct comedi_subdevice *s, int n, int turn)
{
int i, j;
#ifdef PCI171x_PARANOIDCHECK
int sampl;
#endif
DPRINTK("adv_pci1710 EDBG: BGN: move_block_from_fifo(...,%d,%d)\n", n,
turn);
j = s->async->cur_chan;
for (i = 0; i < n; i++) {
#ifdef PCI171x_PARANOIDCHECK
sampl = inw(dev->iobase + PCI171x_AD_DATA);
if (this_board->cardtype != TYPE_PCI1713)
if ((sampl & 0xf000) != devpriv->act_chanlist[j]) {
printk
("comedi%d: A/D FIFO data dropout: received data from channel %d, expected %d! (%d/%d/%d/%d/%d/%4x)\n",
dev->minor, (sampl & 0xf000) >> 12,
(devpriv->act_chanlist[j] & 0xf000) >> 12,
i, j, devpriv->ai_act_scan, n, turn,
sampl);
pci171x_ai_cancel(dev, s);
s->async->events |=
COMEDI_CB_EOA | COMEDI_CB_ERROR;
comedi_event(dev, s);
return 1;
}
comedi_buf_put(s->async, sampl & 0x0fff);
#else
comedi_buf_put(s->async,
inw(dev->iobase + PCI171x_AD_DATA) & 0x0fff);
#endif
j++;
if (j >= devpriv->ai_n_chan) {
j = 0;
devpriv->ai_act_scan++;
}
}
s->async->cur_chan = j;
DPRINTK("adv_pci1710 EDBG: END: move_block_from_fifo(...)\n");
return 0;
}
/*
==============================================================================
*/
static void interrupt_pci1710_half_fifo(void *d)
{
struct comedi_device *dev = d;
struct comedi_subdevice *s = dev->subdevices + 0;
int m, samplesinbuf;
DPRINTK("adv_pci1710 EDBG: BGN: interrupt_pci1710_half_fifo(...)\n");
m = inw(dev->iobase + PCI171x_STATUS);
if (!(m & Status_FH)) {
printk("comedi%d: A/D FIFO not half full! (%4x)\n",
dev->minor, m);
pci171x_ai_cancel(dev, s);
s->async->events |= COMEDI_CB_EOA | COMEDI_CB_ERROR;
comedi_event(dev, s);
return;
}
if (m & Status_FF) {
printk
("comedi%d: A/D FIFO Full status (Fatal Error!) (%4x)\n",
dev->minor, m);
pci171x_ai_cancel(dev, s);
s->async->events |= COMEDI_CB_EOA | COMEDI_CB_ERROR;
comedi_event(dev, s);
return;
}
samplesinbuf = this_board->fifo_half_size;
if (samplesinbuf * sizeof(short) >= devpriv->ai_data_len) {
m = devpriv->ai_data_len / sizeof(short);
if (move_block_from_fifo(dev, s, m, 0))
return;
samplesinbuf -= m;
}
if (samplesinbuf) {
if (move_block_from_fifo(dev, s, samplesinbuf, 1))
return;
}
if (!devpriv->neverending_ai)
if (devpriv->ai_act_scan >= devpriv->ai_scans) { /* all data
sampled */
pci171x_ai_cancel(dev, s);
s->async->events |= COMEDI_CB_EOA;
comedi_event(dev, s);
return;
}
outb(0, dev->iobase + PCI171x_CLRINT); /* clear our INT request */
DPRINTK("adv_pci1710 EDBG: END: interrupt_pci1710_half_fifo(...)\n");
comedi_event(dev, s);
}
/*
==============================================================================
*/
static irqreturn_t interrupt_service_pci1710(int irq, void *d)
{
struct comedi_device *dev = d;
DPRINTK("adv_pci1710 EDBG: BGN: interrupt_service_pci1710(%d,...)\n",
irq);
if (!dev->attached) /* is device attached? */
return IRQ_NONE; /* no, exit */
if (!(inw(dev->iobase + PCI171x_STATUS) & Status_IRQ)) /* is this interrupt from our board? */
return IRQ_NONE; /* no, exit */
DPRINTK("adv_pci1710 EDBG: interrupt_service_pci1710() ST: %4x\n",
inw(dev->iobase + PCI171x_STATUS));
if (devpriv->ai_et) { /* Switch from initial TRIG_EXT to TRIG_xxx. */
devpriv->ai_et = 0;
devpriv->CntrlReg &= Control_CNT0;
devpriv->CntrlReg |= Control_SW; /* set software trigger */
outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL);
devpriv->CntrlReg = devpriv->ai_et_CntrlReg;
outb(0, dev->iobase + PCI171x_CLRFIFO);
outb(0, dev->iobase + PCI171x_CLRINT);
outw(devpriv->ai_et_MuxVal, dev->iobase + PCI171x_MUX);
outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL);
/* start pacer */
start_pacer(dev, 1, devpriv->ai_et_div1, devpriv->ai_et_div2);
return IRQ_HANDLED;
}
if (devpriv->ai_eos) { /* We use FIFO half full INT or not? */
interrupt_pci1710_every_sample(d);
} else {
interrupt_pci1710_half_fifo(d);
}
DPRINTK("adv_pci1710 EDBG: END: interrupt_service_pci1710(...)\n");
return IRQ_HANDLED;
}
/*
==============================================================================
*/
static int pci171x_ai_docmd_and_mode(int mode, struct comedi_device *dev,
struct comedi_subdevice *s)
{
unsigned int divisor1 = 0, divisor2 = 0;
unsigned int seglen;
DPRINTK("adv_pci1710 EDBG: BGN: pci171x_ai_docmd_and_mode(%d,...)\n",
mode);
start_pacer(dev, -1, 0, 0); /* stop pacer */
seglen = check_channel_list(dev, s, devpriv->ai_chanlist,
devpriv->ai_n_chan);
if (seglen < 1)
return -EINVAL;
setup_channel_list(dev, s, devpriv->ai_chanlist,
devpriv->ai_n_chan, seglen);
outb(0, dev->iobase + PCI171x_CLRFIFO);
outb(0, dev->iobase + PCI171x_CLRINT);
devpriv->ai_do = mode;
devpriv->ai_act_scan = 0;
s->async->cur_chan = 0;
devpriv->ai_buf_ptr = 0;
devpriv->neverending_ai = 0;
devpriv->CntrlReg &= Control_CNT0;
if ((devpriv->ai_flags & TRIG_WAKE_EOS)) { /* don't we want wake up every scan? devpriv->ai_eos=1; */
devpriv->ai_eos = 1;
} else {
devpriv->CntrlReg |= Control_ONEFH;
devpriv->ai_eos = 0;
}
if ((devpriv->ai_scans == 0) || (devpriv->ai_scans == -1))
devpriv->neverending_ai = 1;
/* well, user want neverending */
else
devpriv->neverending_ai = 0;
switch (mode) {
case 1:
case 2:
if (devpriv->ai_timer1 < this_board->ai_ns_min)
devpriv->ai_timer1 = this_board->ai_ns_min;
devpriv->CntrlReg |= Control_PACER | Control_IRQEN;
if (mode == 2) {
devpriv->ai_et_CntrlReg = devpriv->CntrlReg;
devpriv->CntrlReg &=
~(Control_PACER | Control_ONEFH | Control_GATE);
devpriv->CntrlReg |= Control_EXT;
devpriv->ai_et = 1;
} else {
devpriv->ai_et = 0;
}
i8253_cascade_ns_to_timer(devpriv->i8254_osc_base, &divisor1,
&divisor2, &devpriv->ai_timer1,
devpriv->ai_flags & TRIG_ROUND_MASK);
DPRINTK
("adv_pci1710 EDBG: OSC base=%u div1=%u div2=%u timer=%u\n",
devpriv->i8254_osc_base, divisor1, divisor2,
devpriv->ai_timer1);
outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL);
if (mode != 2) {
/* start pacer */
start_pacer(dev, mode, divisor1, divisor2);
} else {
devpriv->ai_et_div1 = divisor1;
devpriv->ai_et_div2 = divisor2;
}
break;
case 3:
devpriv->CntrlReg |= Control_EXT | Control_IRQEN;
outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL);
break;
}
DPRINTK("adv_pci1710 EDBG: END: pci171x_ai_docmd_and_mode(...)\n");
return 0;
}
#ifdef PCI171X_EXTDEBUG
/*
==============================================================================
*/
static void pci171x_cmdtest_out(int e, struct comedi_cmd *cmd)
{
printk("adv_pci1710 e=%d startsrc=%x scansrc=%x convsrc=%x\n", e,
cmd->start_src, cmd->scan_begin_src, cmd->convert_src);
printk("adv_pci1710 e=%d startarg=%d scanarg=%d convarg=%d\n", e,
cmd->start_arg, cmd->scan_begin_arg, cmd->convert_arg);
printk("adv_pci1710 e=%d stopsrc=%x scanend=%x\n", e, cmd->stop_src,
cmd->scan_end_src);
printk("adv_pci1710 e=%d stoparg=%d scanendarg=%d chanlistlen=%d\n",
e, cmd->stop_arg, cmd->scan_end_arg, cmd->chanlist_len);
}
#endif
/*
==============================================================================
*/
static int pci171x_ai_cmdtest(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_cmd *cmd)
{
int err = 0;
int tmp;
unsigned int divisor1 = 0, divisor2 = 0;
DPRINTK("adv_pci1710 EDBG: BGN: pci171x_ai_cmdtest(...)\n");
#ifdef PCI171X_EXTDEBUG
pci171x_cmdtest_out(-1, cmd);
#endif
/* step 1: make sure trigger sources are trivially valid */
tmp = cmd->start_src;
cmd->start_src &= TRIG_NOW | TRIG_EXT;
if (!cmd->start_src || tmp != cmd->start_src)
err++;
tmp = cmd->scan_begin_src;
cmd->scan_begin_src &= TRIG_FOLLOW;
if (!cmd->scan_begin_src || tmp != cmd->scan_begin_src)
err++;
tmp = cmd->convert_src;
cmd->convert_src &= TRIG_TIMER | TRIG_EXT;
if (!cmd->convert_src || tmp != cmd->convert_src)
err++;
tmp = cmd->scan_end_src;
cmd->scan_end_src &= TRIG_COUNT;
if (!cmd->scan_end_src || tmp != cmd->scan_end_src)
err++;
tmp = cmd->stop_src;
cmd->stop_src &= TRIG_COUNT | TRIG_NONE;
if (!cmd->stop_src || tmp != cmd->stop_src)
err++;
if (err) {
#ifdef PCI171X_EXTDEBUG
pci171x_cmdtest_out(1, cmd);
#endif
DPRINTK
("adv_pci1710 EDBG: BGN: pci171x_ai_cmdtest(...) err=%d ret=1\n",
err);
return 1;
}
/* step 2: make sure trigger sources are unique and mutually compatible */
if (cmd->start_src != TRIG_NOW && cmd->start_src != TRIG_EXT) {
cmd->start_src = TRIG_NOW;
err++;
}
if (cmd->scan_begin_src != TRIG_FOLLOW) {
cmd->scan_begin_src = TRIG_FOLLOW;
err++;
}
if (cmd->convert_src != TRIG_TIMER && cmd->convert_src != TRIG_EXT)
err++;
if (cmd->scan_end_src != TRIG_COUNT) {
cmd->scan_end_src = TRIG_COUNT;
err++;
}
if (cmd->stop_src != TRIG_NONE && cmd->stop_src != TRIG_COUNT)
err++;
if (err) {
#ifdef PCI171X_EXTDEBUG
pci171x_cmdtest_out(2, cmd);
#endif
DPRINTK
("adv_pci1710 EDBG: BGN: pci171x_ai_cmdtest(...) err=%d ret=2\n",
err);
return 2;
}
/* step 3: make sure arguments are trivially compatible */
if (cmd->start_arg != 0) {
cmd->start_arg = 0;
err++;
}
if (cmd->scan_begin_arg != 0) {
cmd->scan_begin_arg = 0;
err++;
}
if (cmd->convert_src == TRIG_TIMER) {
if (cmd->convert_arg < this_board->ai_ns_min) {
cmd->convert_arg = this_board->ai_ns_min;
err++;
}
} else { /* TRIG_FOLLOW */
if (cmd->convert_arg != 0) {
cmd->convert_arg = 0;
err++;
}
}
if (cmd->scan_end_arg != cmd->chanlist_len) {
cmd->scan_end_arg = cmd->chanlist_len;
err++;
}
if (cmd->stop_src == TRIG_COUNT) {
if (!cmd->stop_arg) {
cmd->stop_arg = 1;
err++;
}
} else { /* TRIG_NONE */
if (cmd->stop_arg != 0) {
cmd->stop_arg = 0;
err++;
}
}
if (err) {
#ifdef PCI171X_EXTDEBUG
pci171x_cmdtest_out(3, cmd);
#endif
DPRINTK
("adv_pci1710 EDBG: BGN: pci171x_ai_cmdtest(...) err=%d ret=3\n",
err);
return 3;
}
/* step 4: fix up any arguments */
if (cmd->convert_src == TRIG_TIMER) {
tmp = cmd->convert_arg;
i8253_cascade_ns_to_timer(devpriv->i8254_osc_base, &divisor1,
&divisor2, &cmd->convert_arg,
cmd->flags & TRIG_ROUND_MASK);
if (cmd->convert_arg < this_board->ai_ns_min)
cmd->convert_arg = this_board->ai_ns_min;
if (tmp != cmd->convert_arg)
err++;
}
if (err) {
DPRINTK
("adv_pci1710 EDBG: BGN: pci171x_ai_cmdtest(...) err=%d ret=4\n",
err);
return 4;
}
/* step 5: complain about special chanlist considerations */
if (cmd->chanlist) {
if (!check_channel_list(dev, s, cmd->chanlist,
cmd->chanlist_len))
return 5; /* incorrect channels list */
}
DPRINTK("adv_pci1710 EDBG: BGN: pci171x_ai_cmdtest(...) ret=0\n");
return 0;
}
/*
==============================================================================
*/
static int pci171x_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
{
struct comedi_cmd *cmd = &s->async->cmd;
DPRINTK("adv_pci1710 EDBG: BGN: pci171x_ai_cmd(...)\n");
devpriv->ai_n_chan = cmd->chanlist_len;
devpriv->ai_chanlist = cmd->chanlist;
devpriv->ai_flags = cmd->flags;
devpriv->ai_data_len = s->async->prealloc_bufsz;
devpriv->ai_data = s->async->prealloc_buf;
devpriv->ai_timer1 = 0;
devpriv->ai_timer2 = 0;
if (cmd->stop_src == TRIG_COUNT)
devpriv->ai_scans = cmd->stop_arg;
else
devpriv->ai_scans = 0;
if (cmd->scan_begin_src == TRIG_FOLLOW) { /* mode 1, 2, 3 */
if (cmd->convert_src == TRIG_TIMER) { /* mode 1 and 2 */
devpriv->ai_timer1 = cmd->convert_arg;
return pci171x_ai_docmd_and_mode(cmd->start_src ==
TRIG_EXT ? 2 : 1, dev,
s);
}
if (cmd->convert_src == TRIG_EXT) { /* mode 3 */
return pci171x_ai_docmd_and_mode(3, dev, s);
}
}
return -1;
}
/*
==============================================================================
Check if channel list from user is builded correctly
If it's ok, then program scan/gain logic.
This works for all cards.
*/
static int check_channel_list(struct comedi_device *dev,
struct comedi_subdevice *s,
unsigned int *chanlist, unsigned int n_chan)
{
unsigned int chansegment[32];
unsigned int i, nowmustbechan, seglen, segpos;
DPRINTK("adv_pci1710 EDBG: check_channel_list(...,%d)\n", n_chan);
/* correct channel and range number check itself comedi/range.c */
if (n_chan < 1) {
comedi_error(dev, "range/channel list is empty!");
return 0;
}
if (n_chan > 1) {
chansegment[0] = chanlist[0]; /* first channel is everytime ok */
for (i = 1, seglen = 1; i < n_chan; i++, seglen++) { /* build part of chanlist */
/* printk("%d. %d %d\n",i,CR_CHAN(chanlist[i]),CR_RANGE(chanlist[i])); */
if (chanlist[0] == chanlist[i])
break; /* we detect loop, this must by finish */
if (CR_CHAN(chanlist[i]) & 1) /* odd channel cann't by differencial */
if (CR_AREF(chanlist[i]) == AREF_DIFF) {
comedi_error(dev,
"Odd channel can't be differential input!\n");
return 0;
}
nowmustbechan =
(CR_CHAN(chansegment[i - 1]) + 1) % s->n_chan;
if (CR_AREF(chansegment[i - 1]) == AREF_DIFF)
nowmustbechan = (nowmustbechan + 1) % s->n_chan;
if (nowmustbechan != CR_CHAN(chanlist[i])) { /* channel list isn't continous :-( */
printk
("channel list must be continous! chanlist[%i]=%d but must be %d or %d!\n",
i, CR_CHAN(chanlist[i]), nowmustbechan,
CR_CHAN(chanlist[0]));
return 0;
}
chansegment[i] = chanlist[i]; /* well, this is next correct channel in list */
}
for (i = 0, segpos = 0; i < n_chan; i++) { /* check whole chanlist */
/* printk("%d %d=%d %d\n",CR_CHAN(chansegment[i%seglen]),CR_RANGE(chansegment[i%seglen]),CR_CHAN(chanlist[i]),CR_RANGE(chanlist[i])); */
if (chanlist[i] != chansegment[i % seglen]) {
printk
("bad channel, reference or range number! chanlist[%i]=%d,%d,%d and not %d,%d,%d!\n",
i, CR_CHAN(chansegment[i]),
CR_RANGE(chansegment[i]),
CR_AREF(chansegment[i]),
CR_CHAN(chanlist[i % seglen]),
CR_RANGE(chanlist[i % seglen]),
CR_AREF(chansegment[i % seglen]));
return 0; /* chan/gain list is strange */
}
}
} else {
seglen = 1;
}
return seglen;
}
static void setup_channel_list(struct comedi_device *dev,
struct comedi_subdevice *s,
unsigned int *chanlist, unsigned int n_chan,
unsigned int seglen)
{
unsigned int i, range, chanprog;
DPRINTK("adv_pci1710 EDBG: setup_channel_list(...,%d,%d)\n", n_chan,
seglen);
devpriv->act_chanlist_len = seglen;
devpriv->act_chanlist_pos = 0;
DPRINTK("SegLen: %d\n", seglen);
for (i = 0; i < seglen; i++) { /* store range list to card */
chanprog = muxonechan[CR_CHAN(chanlist[i])];
outw(chanprog, dev->iobase + PCI171x_MUX); /* select channel */
range = this_board->rangecode_ai[CR_RANGE(chanlist[i])];
if (CR_AREF(chanlist[i]) == AREF_DIFF)
range |= 0x0020;
outw(range, dev->iobase + PCI171x_RANGE); /* select gain */
#ifdef PCI171x_PARANOIDCHECK
devpriv->act_chanlist[i] =
(CR_CHAN(chanlist[i]) << 12) & 0xf000;
#endif
DPRINTK("GS: %2d. [%4x]=%4x %4x\n", i, chanprog, range,
devpriv->act_chanlist[i]);
}
#ifdef PCI171x_PARANOIDCHECK
for ( ; i < n_chan; i++) { /* store remainder of channel list */
devpriv->act_chanlist[i] =
(CR_CHAN(chanlist[i]) << 12) & 0xf000;
}
#endif
devpriv->ai_et_MuxVal =
CR_CHAN(chanlist[0]) | (CR_CHAN(chanlist[seglen - 1]) << 8);
outw(devpriv->ai_et_MuxVal, dev->iobase + PCI171x_MUX); /* select channel interval to scan */
DPRINTK("MUX: %4x L%4x.H%4x\n",
CR_CHAN(chanlist[0]) | (CR_CHAN(chanlist[seglen - 1]) << 8),
CR_CHAN(chanlist[0]), CR_CHAN(chanlist[seglen - 1]));
}
/*
==============================================================================
*/
static void start_pacer(struct comedi_device *dev, int mode,
unsigned int divisor1, unsigned int divisor2)
{
DPRINTK("adv_pci1710 EDBG: BGN: start_pacer(%d,%u,%u)\n", mode,
divisor1, divisor2);
outw(0xb4, dev->iobase + PCI171x_CNTCTRL);
outw(0x74, dev->iobase + PCI171x_CNTCTRL);
if (mode == 1) {
outw(divisor2 & 0xff, dev->iobase + PCI171x_CNT2);
outw((divisor2 >> 8) & 0xff, dev->iobase + PCI171x_CNT2);
outw(divisor1 & 0xff, dev->iobase + PCI171x_CNT1);
outw((divisor1 >> 8) & 0xff, dev->iobase + PCI171x_CNT1);
}
DPRINTK("adv_pci1710 EDBG: END: start_pacer(...)\n");
}
/*
==============================================================================
*/
static int pci171x_ai_cancel(struct comedi_device *dev,
struct comedi_subdevice *s)
{
DPRINTK("adv_pci1710 EDBG: BGN: pci171x_ai_cancel(...)\n");
switch (this_board->cardtype) {
default:
devpriv->CntrlReg &= Control_CNT0;
devpriv->CntrlReg |= Control_SW;
outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL); /* reset any operations */
start_pacer(dev, -1, 0, 0);
outb(0, dev->iobase + PCI171x_CLRFIFO);
outb(0, dev->iobase + PCI171x_CLRINT);
break;
}
devpriv->ai_do = 0;
devpriv->ai_act_scan = 0;
s->async->cur_chan = 0;
devpriv->ai_buf_ptr = 0;
devpriv->neverending_ai = 0;
DPRINTK("adv_pci1710 EDBG: END: pci171x_ai_cancel(...)\n");
return 0;
}
/*
==============================================================================
*/
static int pci171x_reset(struct comedi_device *dev)
{
DPRINTK("adv_pci1710 EDBG: BGN: pci171x_reset(...)\n");
outw(0x30, dev->iobase + PCI171x_CNTCTRL);
devpriv->CntrlReg = Control_SW | Control_CNT0; /* Software trigger, CNT0=external */
outw(devpriv->CntrlReg, dev->iobase + PCI171x_CONTROL); /* reset any operations */
outb(0, dev->iobase + PCI171x_CLRFIFO); /* clear FIFO */
outb(0, dev->iobase + PCI171x_CLRINT); /* clear INT request */
start_pacer(dev, -1, 0, 0); /* stop 8254 */
devpriv->da_ranges = 0;
if (this_board->n_aochan) {
outb(devpriv->da_ranges, dev->iobase + PCI171x_DAREF); /* set DACs to 0..5V */
outw(0, dev->iobase + PCI171x_DA1); /* set DA outputs to 0V */
devpriv->ao_data[0] = 0x0000;
if (this_board->n_aochan > 1) {
outw(0, dev->iobase + PCI171x_DA2);
devpriv->ao_data[1] = 0x0000;
}
}
outw(0, dev->iobase + PCI171x_DO); /* digital outputs to 0 */
outb(0, dev->iobase + PCI171x_CLRFIFO); /* clear FIFO */
outb(0, dev->iobase + PCI171x_CLRINT); /* clear INT request */
DPRINTK("adv_pci1710 EDBG: END: pci171x_reset(...)\n");
return 0;
}
/*
==============================================================================
*/
static int pci1720_reset(struct comedi_device *dev)
{
DPRINTK("adv_pci1710 EDBG: BGN: pci1720_reset(...)\n");
outb(Syncont_SC0, dev->iobase + PCI1720_SYNCONT); /* set synchronous output mode */
devpriv->da_ranges = 0xAA;
outb(devpriv->da_ranges, dev->iobase + PCI1720_RANGE); /* set all ranges to +/-5V */
outw(0x0800, dev->iobase + PCI1720_DA0); /* set outputs to 0V */
outw(0x0800, dev->iobase + PCI1720_DA1);
outw(0x0800, dev->iobase + PCI1720_DA2);
outw(0x0800, dev->iobase + PCI1720_DA3);
outb(0, dev->iobase + PCI1720_SYNCOUT); /* update outputs */
devpriv->ao_data[0] = 0x0800;
devpriv->ao_data[1] = 0x0800;
devpriv->ao_data[2] = 0x0800;
devpriv->ao_data[3] = 0x0800;
DPRINTK("adv_pci1710 EDBG: END: pci1720_reset(...)\n");
return 0;
}
/*
==============================================================================
*/
static int pci1710_reset(struct comedi_device *dev)
{
DPRINTK("adv_pci1710 EDBG: BGN: pci1710_reset(...)\n");
switch (this_board->cardtype) {
case TYPE_PCI1720:
return pci1720_reset(dev);
default:
return pci171x_reset(dev);
}
DPRINTK("adv_pci1710 EDBG: END: pci1710_reset(...)\n");
}
/*
==============================================================================
*/
static int pci1710_attach(struct comedi_device *dev,
struct comedi_devconfig *it)
{
struct comedi_subdevice *s;
int ret, subdev, n_subdevices;
unsigned int irq;
unsigned long iobase;
struct pci_dev *pcidev;
int opt_bus, opt_slot;
const char *errstr;
unsigned char pci_bus, pci_slot, pci_func;
int i;
int board_index;
printk("comedi%d: adv_pci1710: ", dev->minor);
opt_bus = it->options[0];
opt_slot = it->options[1];
ret = alloc_private(dev, sizeof(struct pci1710_private));
if (ret < 0) {
printk(" - Allocation failed!\n");
return -ENOMEM;
}
/* Look for matching PCI device */
errstr = "not found!";
pcidev = NULL;
board_index = this_board - boardtypes;
while (NULL != (pcidev = pci_get_device(PCI_VENDOR_ID_ADVANTECH,
PCI_ANY_ID, pcidev))) {
if (strcmp(this_board->name, DRV_NAME) == 0) {
for (i = 0; i < n_boardtypes; ++i) {
if (pcidev->device == boardtypes[i].device_id) {
board_index = i;
break;
}
}
if (i == n_boardtypes)
continue;
} else {
if (pcidev->device != boardtypes[board_index].device_id)
continue;
}
/* Found matching vendor/device. */
if (opt_bus || opt_slot) {
/* Check bus/slot. */
if (opt_bus != pcidev->bus->number
|| opt_slot != PCI_SLOT(pcidev->devfn))
continue; /* no match */
}
/*
* Look for device that isn't in use.
* Enable PCI device and request regions.
*/
if (comedi_pci_enable(pcidev, DRV_NAME)) {
errstr =
"failed to enable PCI device and request regions!";
continue;
}
/* fixup board_ptr in case we were using the dummy entry with the driver name */
dev->board_ptr = &boardtypes[board_index];
break;
}
if (!pcidev) {
if (opt_bus || opt_slot) {
printk(" - Card at b:s %d:%d %s\n",
opt_bus, opt_slot, errstr);
} else {
printk(" - Card %s\n", errstr);
}
return -EIO;
}
pci_bus = pcidev->bus->number;
pci_slot = PCI_SLOT(pcidev->devfn);
pci_func = PCI_FUNC(pcidev->devfn);
irq = pcidev->irq;
iobase = pci_resource_start(pcidev, 2);
printk(", b:s:f=%d:%d:%d, io=0x%4lx", pci_bus, pci_slot, pci_func,
iobase);
dev->iobase = iobase;
dev->board_name = this_board->name;
devpriv->pcidev = pcidev;
n_subdevices = 0;
if (this_board->n_aichan)
n_subdevices++;
if (this_board->n_aochan)
n_subdevices++;
if (this_board->n_dichan)
n_subdevices++;
if (this_board->n_dochan)
n_subdevices++;
if (this_board->n_counter)
n_subdevices++;
ret = alloc_subdevices(dev, n_subdevices);
if (ret < 0) {
printk(" - Allocation failed!\n");
return ret;
}
pci1710_reset(dev);
if (this_board->have_irq) {
if (irq) {
if (request_irq(irq, interrupt_service_pci1710,
IRQF_SHARED, "Advantech PCI-1710",
dev)) {
printk
(", unable to allocate IRQ %d, DISABLING IT",
irq);
irq = 0; /* Can't use IRQ */
} else {
printk(", irq=%u", irq);
}
} else {
printk(", IRQ disabled");
}
} else {
irq = 0;
}
dev->irq = irq;
printk(".\n");
subdev = 0;
if (this_board->n_aichan) {
s = dev->subdevices + subdev;
dev->read_subdev = s;
s->type = COMEDI_SUBD_AI;
s->subdev_flags = SDF_READABLE | SDF_COMMON | SDF_GROUND;
if (this_board->n_aichand)
s->subdev_flags |= SDF_DIFF;
s->n_chan = this_board->n_aichan;
s->maxdata = this_board->ai_maxdata;
s->len_chanlist = this_board->n_aichan;
s->range_table = this_board->rangelist_ai;
s->cancel = pci171x_ai_cancel;
s->insn_read = pci171x_insn_read_ai;
if (irq) {
s->subdev_flags |= SDF_CMD_READ;
s->do_cmdtest = pci171x_ai_cmdtest;
s->do_cmd = pci171x_ai_cmd;
}
devpriv->i8254_osc_base = 100; /* 100ns=10MHz */
subdev++;
}
if (this_board->n_aochan) {
s = dev->subdevices + subdev;
s->type = COMEDI_SUBD_AO;
s->subdev_flags = SDF_WRITABLE | SDF_GROUND | SDF_COMMON;
s->n_chan = this_board->n_aochan;
s->maxdata = this_board->ao_maxdata;
s->len_chanlist = this_board->n_aochan;
s->range_table = this_board->rangelist_ao;
switch (this_board->cardtype) {
case TYPE_PCI1720:
s->insn_write = pci1720_insn_write_ao;
break;
default:
s->insn_write = pci171x_insn_write_ao;
break;
}
s->insn_read = pci171x_insn_read_ao;
subdev++;
}
if (this_board->n_dichan) {
s = dev->subdevices + subdev;
s->type = COMEDI_SUBD_DI;
s->subdev_flags = SDF_READABLE | SDF_GROUND | SDF_COMMON;
s->n_chan = this_board->n_dichan;
s->maxdata = 1;
s->len_chanlist = this_board->n_dichan;
s->range_table = &range_digital;
s->io_bits = 0; /* all bits input */
s->insn_bits = pci171x_insn_bits_di;
subdev++;
}
if (this_board->n_dochan) {
s = dev->subdevices + subdev;
s->type = COMEDI_SUBD_DO;
s->subdev_flags = SDF_WRITABLE | SDF_GROUND | SDF_COMMON;
s->n_chan = this_board->n_dochan;
s->maxdata = 1;
s->len_chanlist = this_board->n_dochan;
s->range_table = &range_digital;
/* all bits output */
s->io_bits = (1 << this_board->n_dochan) - 1;
s->state = 0;
s->insn_bits = pci171x_insn_bits_do;
subdev++;
}
if (this_board->n_counter) {
s = dev->subdevices + subdev;
s->type = COMEDI_SUBD_COUNTER;
s->subdev_flags = SDF_READABLE | SDF_WRITABLE;
s->n_chan = this_board->n_counter;
s->len_chanlist = this_board->n_counter;
s->maxdata = 0xffff;
s->range_table = &range_unknown;
s->insn_read = pci171x_insn_counter_read;
s->insn_write = pci171x_insn_counter_write;
s->insn_config = pci171x_insn_counter_config;
subdev++;
}
devpriv->valid = 1;
return 0;
}
/*
==============================================================================
*/
static int pci1710_detach(struct comedi_device *dev)
{
if (dev->private) {
if (devpriv->valid)
pci1710_reset(dev);
if (dev->irq)
free_irq(dev->irq, dev);
if (devpriv->pcidev) {
if (dev->iobase)
comedi_pci_disable(devpriv->pcidev);
pci_dev_put(devpriv->pcidev);
}
}
return 0;
}
/*
==============================================================================
*/
static int __devinit driver_pci1710_pci_probe(struct pci_dev *dev,
const struct pci_device_id *ent)
{
return comedi_pci_auto_config(dev, driver_pci1710.driver_name);
}
static void __devexit driver_pci1710_pci_remove(struct pci_dev *dev)
{
comedi_pci_auto_unconfig(dev);
}
static struct pci_driver driver_pci1710_pci_driver = {
.id_table = pci1710_pci_table,
.probe = &driver_pci1710_pci_probe,
.remove = __devexit_p(&driver_pci1710_pci_remove)
};
static int __init driver_pci1710_init_module(void)
{
int retval;
retval = comedi_driver_register(&driver_pci1710);
if (retval < 0)
return retval;
driver_pci1710_pci_driver.name = (char *)driver_pci1710.driver_name;
return pci_register_driver(&driver_pci1710_pci_driver);
}
static void __exit driver_pci1710_cleanup_module(void)
{
pci_unregister_driver(&driver_pci1710_pci_driver);
comedi_driver_unregister(&driver_pci1710);
}
module_init(driver_pci1710_init_module);
module_exit(driver_pci1710_cleanup_module);
/*
==============================================================================
*/
MODULE_AUTHOR("Comedi http://www.comedi.org");
MODULE_DESCRIPTION("Comedi low-level driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
ParanoidAndroid/android_kernel_grouper | block/blk-throttle.c | 390 | 32721 | /*
* Interface for controlling IO bandwidth on a request queue
*
* Copyright (C) 2010 Vivek Goyal <vgoyal@redhat.com>
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/blkdev.h>
#include <linux/bio.h>
#include <linux/blktrace_api.h>
#include "blk-cgroup.h"
/* Max dispatch from a group in 1 round */
static int throtl_grp_quantum = 8;
/* Total max dispatch from all groups in one round */
static int throtl_quantum = 32;
/* Throttling is performed over 100ms slice and after that slice is renewed */
static unsigned long throtl_slice = HZ/10; /* 100 ms */
/* A workqueue to queue throttle related work */
static struct workqueue_struct *kthrotld_workqueue;
static void throtl_schedule_delayed_work(struct throtl_data *td,
unsigned long delay);
struct throtl_rb_root {
struct rb_root rb;
struct rb_node *left;
unsigned int count;
unsigned long min_disptime;
};
#define THROTL_RB_ROOT (struct throtl_rb_root) { .rb = RB_ROOT, .left = NULL, \
.count = 0, .min_disptime = 0}
#define rb_entry_tg(node) rb_entry((node), struct throtl_grp, rb_node)
struct throtl_grp {
/* List of throtl groups on the request queue*/
struct hlist_node tg_node;
/* active throtl group service_tree member */
struct rb_node rb_node;
/*
* Dispatch time in jiffies. This is the estimated time when group
* will unthrottle and is ready to dispatch more bio. It is used as
* key to sort active groups in service tree.
*/
unsigned long disptime;
struct blkio_group blkg;
atomic_t ref;
unsigned int flags;
/* Two lists for READ and WRITE */
struct bio_list bio_lists[2];
/* Number of queued bios on READ and WRITE lists */
unsigned int nr_queued[2];
/* bytes per second rate limits */
uint64_t bps[2];
/* IOPS limits */
unsigned int iops[2];
/* Number of bytes disptached in current slice */
uint64_t bytes_disp[2];
/* Number of bio's dispatched in current slice */
unsigned int io_disp[2];
/* When did we start a new slice */
unsigned long slice_start[2];
unsigned long slice_end[2];
/* Some throttle limits got updated for the group */
int limits_changed;
struct rcu_head rcu_head;
};
struct throtl_data
{
/* List of throtl groups */
struct hlist_head tg_list;
/* service tree for active throtl groups */
struct throtl_rb_root tg_service_tree;
struct throtl_grp *root_tg;
struct request_queue *queue;
/* Total Number of queued bios on READ and WRITE lists */
unsigned int nr_queued[2];
/*
* number of total undestroyed groups
*/
unsigned int nr_undestroyed_grps;
/* Work for dispatching throttled bios */
struct delayed_work throtl_work;
int limits_changed;
};
enum tg_state_flags {
THROTL_TG_FLAG_on_rr = 0, /* on round-robin busy list */
};
#define THROTL_TG_FNS(name) \
static inline void throtl_mark_tg_##name(struct throtl_grp *tg) \
{ \
(tg)->flags |= (1 << THROTL_TG_FLAG_##name); \
} \
static inline void throtl_clear_tg_##name(struct throtl_grp *tg) \
{ \
(tg)->flags &= ~(1 << THROTL_TG_FLAG_##name); \
} \
static inline int throtl_tg_##name(const struct throtl_grp *tg) \
{ \
return ((tg)->flags & (1 << THROTL_TG_FLAG_##name)) != 0; \
}
THROTL_TG_FNS(on_rr);
#define throtl_log_tg(td, tg, fmt, args...) \
blk_add_trace_msg((td)->queue, "throtl %s " fmt, \
blkg_path(&(tg)->blkg), ##args); \
#define throtl_log(td, fmt, args...) \
blk_add_trace_msg((td)->queue, "throtl " fmt, ##args)
static inline struct throtl_grp *tg_of_blkg(struct blkio_group *blkg)
{
if (blkg)
return container_of(blkg, struct throtl_grp, blkg);
return NULL;
}
static inline unsigned int total_nr_queued(struct throtl_data *td)
{
return td->nr_queued[0] + td->nr_queued[1];
}
static inline struct throtl_grp *throtl_ref_get_tg(struct throtl_grp *tg)
{
atomic_inc(&tg->ref);
return tg;
}
static void throtl_free_tg(struct rcu_head *head)
{
struct throtl_grp *tg;
tg = container_of(head, struct throtl_grp, rcu_head);
free_percpu(tg->blkg.stats_cpu);
kfree(tg);
}
static void throtl_put_tg(struct throtl_grp *tg)
{
BUG_ON(atomic_read(&tg->ref) <= 0);
if (!atomic_dec_and_test(&tg->ref))
return;
/*
* A group is freed in rcu manner. But having an rcu lock does not
* mean that one can access all the fields of blkg and assume these
* are valid. For example, don't try to follow throtl_data and
* request queue links.
*
* Having a reference to blkg under an rcu allows acess to only
* values local to groups like group stats and group rate limits
*/
call_rcu(&tg->rcu_head, throtl_free_tg);
}
static void throtl_init_group(struct throtl_grp *tg)
{
INIT_HLIST_NODE(&tg->tg_node);
RB_CLEAR_NODE(&tg->rb_node);
bio_list_init(&tg->bio_lists[0]);
bio_list_init(&tg->bio_lists[1]);
tg->limits_changed = false;
/* Practically unlimited BW */
tg->bps[0] = tg->bps[1] = -1;
tg->iops[0] = tg->iops[1] = -1;
/*
* Take the initial reference that will be released on destroy
* This can be thought of a joint reference by cgroup and
* request queue which will be dropped by either request queue
* exit or cgroup deletion path depending on who is exiting first.
*/
atomic_set(&tg->ref, 1);
}
/* Should be called with rcu read lock held (needed for blkcg) */
static void
throtl_add_group_to_td_list(struct throtl_data *td, struct throtl_grp *tg)
{
hlist_add_head(&tg->tg_node, &td->tg_list);
td->nr_undestroyed_grps++;
}
static void
__throtl_tg_fill_dev_details(struct throtl_data *td, struct throtl_grp *tg)
{
struct backing_dev_info *bdi = &td->queue->backing_dev_info;
unsigned int major, minor;
if (!tg || tg->blkg.dev)
return;
/*
* Fill in device details for a group which might not have been
* filled at group creation time as queue was being instantiated
* and driver had not attached a device yet
*/
if (bdi->dev && dev_name(bdi->dev)) {
sscanf(dev_name(bdi->dev), "%u:%u", &major, &minor);
tg->blkg.dev = MKDEV(major, minor);
}
}
/*
* Should be called with without queue lock held. Here queue lock will be
* taken rarely. It will be taken only once during life time of a group
* if need be
*/
static void
throtl_tg_fill_dev_details(struct throtl_data *td, struct throtl_grp *tg)
{
if (!tg || tg->blkg.dev)
return;
spin_lock_irq(td->queue->queue_lock);
__throtl_tg_fill_dev_details(td, tg);
spin_unlock_irq(td->queue->queue_lock);
}
static void throtl_init_add_tg_lists(struct throtl_data *td,
struct throtl_grp *tg, struct blkio_cgroup *blkcg)
{
__throtl_tg_fill_dev_details(td, tg);
/* Add group onto cgroup list */
blkiocg_add_blkio_group(blkcg, &tg->blkg, (void *)td,
tg->blkg.dev, BLKIO_POLICY_THROTL);
tg->bps[READ] = blkcg_get_read_bps(blkcg, tg->blkg.dev);
tg->bps[WRITE] = blkcg_get_write_bps(blkcg, tg->blkg.dev);
tg->iops[READ] = blkcg_get_read_iops(blkcg, tg->blkg.dev);
tg->iops[WRITE] = blkcg_get_write_iops(blkcg, tg->blkg.dev);
throtl_add_group_to_td_list(td, tg);
}
/* Should be called without queue lock and outside of rcu period */
static struct throtl_grp *throtl_alloc_tg(struct throtl_data *td)
{
struct throtl_grp *tg = NULL;
int ret;
tg = kzalloc_node(sizeof(*tg), GFP_ATOMIC, td->queue->node);
if (!tg)
return NULL;
ret = blkio_alloc_blkg_stats(&tg->blkg);
if (ret) {
kfree(tg);
return NULL;
}
throtl_init_group(tg);
return tg;
}
static struct
throtl_grp *throtl_find_tg(struct throtl_data *td, struct blkio_cgroup *blkcg)
{
struct throtl_grp *tg = NULL;
void *key = td;
/*
* This is the common case when there are no blkio cgroups.
* Avoid lookup in this case
*/
if (blkcg == &blkio_root_cgroup)
tg = td->root_tg;
else
tg = tg_of_blkg(blkiocg_lookup_group(blkcg, key));
__throtl_tg_fill_dev_details(td, tg);
return tg;
}
/*
* This function returns with queue lock unlocked in case of error, like
* request queue is no more
*/
static struct throtl_grp * throtl_get_tg(struct throtl_data *td)
{
struct throtl_grp *tg = NULL, *__tg = NULL;
struct blkio_cgroup *blkcg;
struct request_queue *q = td->queue;
rcu_read_lock();
blkcg = task_blkio_cgroup(current);
tg = throtl_find_tg(td, blkcg);
if (tg) {
rcu_read_unlock();
return tg;
}
/*
* Need to allocate a group. Allocation of group also needs allocation
* of per cpu stats which in-turn takes a mutex() and can block. Hence
* we need to drop rcu lock and queue_lock before we call alloc
*
* Take the request queue reference to make sure queue does not
* go away once we return from allocation.
*/
blk_get_queue(q);
rcu_read_unlock();
spin_unlock_irq(q->queue_lock);
tg = throtl_alloc_tg(td);
/*
* We might have slept in group allocation. Make sure queue is not
* dead
*/
if (unlikely(test_bit(QUEUE_FLAG_DEAD, &q->queue_flags))) {
blk_put_queue(q);
if (tg)
kfree(tg);
return ERR_PTR(-ENODEV);
}
blk_put_queue(q);
/* Group allocated and queue is still alive. take the lock */
spin_lock_irq(q->queue_lock);
/*
* Initialize the new group. After sleeping, read the blkcg again.
*/
rcu_read_lock();
blkcg = task_blkio_cgroup(current);
/*
* If some other thread already allocated the group while we were
* not holding queue lock, free up the group
*/
__tg = throtl_find_tg(td, blkcg);
if (__tg) {
kfree(tg);
rcu_read_unlock();
return __tg;
}
/* Group allocation failed. Account the IO to root group */
if (!tg) {
tg = td->root_tg;
return tg;
}
throtl_init_add_tg_lists(td, tg, blkcg);
rcu_read_unlock();
return tg;
}
static struct throtl_grp *throtl_rb_first(struct throtl_rb_root *root)
{
/* Service tree is empty */
if (!root->count)
return NULL;
if (!root->left)
root->left = rb_first(&root->rb);
if (root->left)
return rb_entry_tg(root->left);
return NULL;
}
static void rb_erase_init(struct rb_node *n, struct rb_root *root)
{
rb_erase(n, root);
RB_CLEAR_NODE(n);
}
static void throtl_rb_erase(struct rb_node *n, struct throtl_rb_root *root)
{
if (root->left == n)
root->left = NULL;
rb_erase_init(n, &root->rb);
--root->count;
}
static void update_min_dispatch_time(struct throtl_rb_root *st)
{
struct throtl_grp *tg;
tg = throtl_rb_first(st);
if (!tg)
return;
st->min_disptime = tg->disptime;
}
static void
tg_service_tree_add(struct throtl_rb_root *st, struct throtl_grp *tg)
{
struct rb_node **node = &st->rb.rb_node;
struct rb_node *parent = NULL;
struct throtl_grp *__tg;
unsigned long key = tg->disptime;
int left = 1;
while (*node != NULL) {
parent = *node;
__tg = rb_entry_tg(parent);
if (time_before(key, __tg->disptime))
node = &parent->rb_left;
else {
node = &parent->rb_right;
left = 0;
}
}
if (left)
st->left = &tg->rb_node;
rb_link_node(&tg->rb_node, parent, node);
rb_insert_color(&tg->rb_node, &st->rb);
}
static void __throtl_enqueue_tg(struct throtl_data *td, struct throtl_grp *tg)
{
struct throtl_rb_root *st = &td->tg_service_tree;
tg_service_tree_add(st, tg);
throtl_mark_tg_on_rr(tg);
st->count++;
}
static void throtl_enqueue_tg(struct throtl_data *td, struct throtl_grp *tg)
{
if (!throtl_tg_on_rr(tg))
__throtl_enqueue_tg(td, tg);
}
static void __throtl_dequeue_tg(struct throtl_data *td, struct throtl_grp *tg)
{
throtl_rb_erase(&tg->rb_node, &td->tg_service_tree);
throtl_clear_tg_on_rr(tg);
}
static void throtl_dequeue_tg(struct throtl_data *td, struct throtl_grp *tg)
{
if (throtl_tg_on_rr(tg))
__throtl_dequeue_tg(td, tg);
}
static void throtl_schedule_next_dispatch(struct throtl_data *td)
{
struct throtl_rb_root *st = &td->tg_service_tree;
/*
* If there are more bios pending, schedule more work.
*/
if (!total_nr_queued(td))
return;
BUG_ON(!st->count);
update_min_dispatch_time(st);
if (time_before_eq(st->min_disptime, jiffies))
throtl_schedule_delayed_work(td, 0);
else
throtl_schedule_delayed_work(td, (st->min_disptime - jiffies));
}
static inline void
throtl_start_new_slice(struct throtl_data *td, struct throtl_grp *tg, bool rw)
{
tg->bytes_disp[rw] = 0;
tg->io_disp[rw] = 0;
tg->slice_start[rw] = jiffies;
tg->slice_end[rw] = jiffies + throtl_slice;
throtl_log_tg(td, tg, "[%c] new slice start=%lu end=%lu jiffies=%lu",
rw == READ ? 'R' : 'W', tg->slice_start[rw],
tg->slice_end[rw], jiffies);
}
static inline void throtl_set_slice_end(struct throtl_data *td,
struct throtl_grp *tg, bool rw, unsigned long jiffy_end)
{
tg->slice_end[rw] = roundup(jiffy_end, throtl_slice);
}
static inline void throtl_extend_slice(struct throtl_data *td,
struct throtl_grp *tg, bool rw, unsigned long jiffy_end)
{
tg->slice_end[rw] = roundup(jiffy_end, throtl_slice);
throtl_log_tg(td, tg, "[%c] extend slice start=%lu end=%lu jiffies=%lu",
rw == READ ? 'R' : 'W', tg->slice_start[rw],
tg->slice_end[rw], jiffies);
}
/* Determine if previously allocated or extended slice is complete or not */
static bool
throtl_slice_used(struct throtl_data *td, struct throtl_grp *tg, bool rw)
{
if (time_in_range(jiffies, tg->slice_start[rw], tg->slice_end[rw]))
return 0;
return 1;
}
/* Trim the used slices and adjust slice start accordingly */
static inline void
throtl_trim_slice(struct throtl_data *td, struct throtl_grp *tg, bool rw)
{
unsigned long nr_slices, time_elapsed, io_trim;
u64 bytes_trim, tmp;
BUG_ON(time_before(tg->slice_end[rw], tg->slice_start[rw]));
/*
* If bps are unlimited (-1), then time slice don't get
* renewed. Don't try to trim the slice if slice is used. A new
* slice will start when appropriate.
*/
if (throtl_slice_used(td, tg, rw))
return;
/*
* A bio has been dispatched. Also adjust slice_end. It might happen
* that initially cgroup limit was very low resulting in high
* slice_end, but later limit was bumped up and bio was dispached
* sooner, then we need to reduce slice_end. A high bogus slice_end
* is bad because it does not allow new slice to start.
*/
throtl_set_slice_end(td, tg, rw, jiffies + throtl_slice);
time_elapsed = jiffies - tg->slice_start[rw];
nr_slices = time_elapsed / throtl_slice;
if (!nr_slices)
return;
tmp = tg->bps[rw] * throtl_slice * nr_slices;
do_div(tmp, HZ);
bytes_trim = tmp;
io_trim = (tg->iops[rw] * throtl_slice * nr_slices)/HZ;
if (!bytes_trim && !io_trim)
return;
if (tg->bytes_disp[rw] >= bytes_trim)
tg->bytes_disp[rw] -= bytes_trim;
else
tg->bytes_disp[rw] = 0;
if (tg->io_disp[rw] >= io_trim)
tg->io_disp[rw] -= io_trim;
else
tg->io_disp[rw] = 0;
tg->slice_start[rw] += nr_slices * throtl_slice;
throtl_log_tg(td, tg, "[%c] trim slice nr=%lu bytes=%llu io=%lu"
" start=%lu end=%lu jiffies=%lu",
rw == READ ? 'R' : 'W', nr_slices, bytes_trim, io_trim,
tg->slice_start[rw], tg->slice_end[rw], jiffies);
}
static bool tg_with_in_iops_limit(struct throtl_data *td, struct throtl_grp *tg,
struct bio *bio, unsigned long *wait)
{
bool rw = bio_data_dir(bio);
unsigned int io_allowed;
unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
u64 tmp;
jiffy_elapsed = jiffy_elapsed_rnd = jiffies - tg->slice_start[rw];
/* Slice has just started. Consider one slice interval */
if (!jiffy_elapsed)
jiffy_elapsed_rnd = throtl_slice;
jiffy_elapsed_rnd = roundup(jiffy_elapsed_rnd, throtl_slice);
/*
* jiffy_elapsed_rnd should not be a big value as minimum iops can be
* 1 then at max jiffy elapsed should be equivalent of 1 second as we
* will allow dispatch after 1 second and after that slice should
* have been trimmed.
*/
tmp = (u64)tg->iops[rw] * jiffy_elapsed_rnd;
do_div(tmp, HZ);
if (tmp > UINT_MAX)
io_allowed = UINT_MAX;
else
io_allowed = tmp;
if (tg->io_disp[rw] + 1 <= io_allowed) {
if (wait)
*wait = 0;
return 1;
}
/* Calc approx time to dispatch */
jiffy_wait = ((tg->io_disp[rw] + 1) * HZ)/tg->iops[rw] + 1;
if (jiffy_wait > jiffy_elapsed)
jiffy_wait = jiffy_wait - jiffy_elapsed;
else
jiffy_wait = 1;
if (wait)
*wait = jiffy_wait;
return 0;
}
static bool tg_with_in_bps_limit(struct throtl_data *td, struct throtl_grp *tg,
struct bio *bio, unsigned long *wait)
{
bool rw = bio_data_dir(bio);
u64 bytes_allowed, extra_bytes, tmp;
unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
jiffy_elapsed = jiffy_elapsed_rnd = jiffies - tg->slice_start[rw];
/* Slice has just started. Consider one slice interval */
if (!jiffy_elapsed)
jiffy_elapsed_rnd = throtl_slice;
jiffy_elapsed_rnd = roundup(jiffy_elapsed_rnd, throtl_slice);
tmp = tg->bps[rw] * jiffy_elapsed_rnd;
do_div(tmp, HZ);
bytes_allowed = tmp;
if (tg->bytes_disp[rw] + bio->bi_size <= bytes_allowed) {
if (wait)
*wait = 0;
return 1;
}
/* Calc approx time to dispatch */
extra_bytes = tg->bytes_disp[rw] + bio->bi_size - bytes_allowed;
jiffy_wait = div64_u64(extra_bytes * HZ, tg->bps[rw]);
if (!jiffy_wait)
jiffy_wait = 1;
/*
* This wait time is without taking into consideration the rounding
* up we did. Add that time also.
*/
jiffy_wait = jiffy_wait + (jiffy_elapsed_rnd - jiffy_elapsed);
if (wait)
*wait = jiffy_wait;
return 0;
}
static bool tg_no_rule_group(struct throtl_grp *tg, bool rw) {
if (tg->bps[rw] == -1 && tg->iops[rw] == -1)
return 1;
return 0;
}
/*
* Returns whether one can dispatch a bio or not. Also returns approx number
* of jiffies to wait before this bio is with-in IO rate and can be dispatched
*/
static bool tg_may_dispatch(struct throtl_data *td, struct throtl_grp *tg,
struct bio *bio, unsigned long *wait)
{
bool rw = bio_data_dir(bio);
unsigned long bps_wait = 0, iops_wait = 0, max_wait = 0;
/*
* Currently whole state machine of group depends on first bio
* queued in the group bio list. So one should not be calling
* this function with a different bio if there are other bios
* queued.
*/
BUG_ON(tg->nr_queued[rw] && bio != bio_list_peek(&tg->bio_lists[rw]));
/* If tg->bps = -1, then BW is unlimited */
if (tg->bps[rw] == -1 && tg->iops[rw] == -1) {
if (wait)
*wait = 0;
return 1;
}
/*
* If previous slice expired, start a new one otherwise renew/extend
* existing slice to make sure it is at least throtl_slice interval
* long since now.
*/
if (throtl_slice_used(td, tg, rw))
throtl_start_new_slice(td, tg, rw);
else {
if (time_before(tg->slice_end[rw], jiffies + throtl_slice))
throtl_extend_slice(td, tg, rw, jiffies + throtl_slice);
}
if (tg_with_in_bps_limit(td, tg, bio, &bps_wait)
&& tg_with_in_iops_limit(td, tg, bio, &iops_wait)) {
if (wait)
*wait = 0;
return 1;
}
max_wait = max(bps_wait, iops_wait);
if (wait)
*wait = max_wait;
if (time_before(tg->slice_end[rw], jiffies + max_wait))
throtl_extend_slice(td, tg, rw, jiffies + max_wait);
return 0;
}
static void throtl_charge_bio(struct throtl_grp *tg, struct bio *bio)
{
bool rw = bio_data_dir(bio);
bool sync = rw_is_sync(bio->bi_rw);
/* Charge the bio to the group */
tg->bytes_disp[rw] += bio->bi_size;
tg->io_disp[rw]++;
blkiocg_update_dispatch_stats(&tg->blkg, bio->bi_size, rw, sync);
}
static void throtl_add_bio_tg(struct throtl_data *td, struct throtl_grp *tg,
struct bio *bio)
{
bool rw = bio_data_dir(bio);
bio_list_add(&tg->bio_lists[rw], bio);
/* Take a bio reference on tg */
throtl_ref_get_tg(tg);
tg->nr_queued[rw]++;
td->nr_queued[rw]++;
throtl_enqueue_tg(td, tg);
}
static void tg_update_disptime(struct throtl_data *td, struct throtl_grp *tg)
{
unsigned long read_wait = -1, write_wait = -1, min_wait = -1, disptime;
struct bio *bio;
if ((bio = bio_list_peek(&tg->bio_lists[READ])))
tg_may_dispatch(td, tg, bio, &read_wait);
if ((bio = bio_list_peek(&tg->bio_lists[WRITE])))
tg_may_dispatch(td, tg, bio, &write_wait);
min_wait = min(read_wait, write_wait);
disptime = jiffies + min_wait;
/* Update dispatch time */
throtl_dequeue_tg(td, tg);
tg->disptime = disptime;
throtl_enqueue_tg(td, tg);
}
static void tg_dispatch_one_bio(struct throtl_data *td, struct throtl_grp *tg,
bool rw, struct bio_list *bl)
{
struct bio *bio;
bio = bio_list_pop(&tg->bio_lists[rw]);
tg->nr_queued[rw]--;
/* Drop bio reference on tg */
throtl_put_tg(tg);
BUG_ON(td->nr_queued[rw] <= 0);
td->nr_queued[rw]--;
throtl_charge_bio(tg, bio);
bio_list_add(bl, bio);
bio->bi_rw |= REQ_THROTTLED;
throtl_trim_slice(td, tg, rw);
}
static int throtl_dispatch_tg(struct throtl_data *td, struct throtl_grp *tg,
struct bio_list *bl)
{
unsigned int nr_reads = 0, nr_writes = 0;
unsigned int max_nr_reads = throtl_grp_quantum*3/4;
unsigned int max_nr_writes = throtl_grp_quantum - max_nr_reads;
struct bio *bio;
/* Try to dispatch 75% READS and 25% WRITES */
while ((bio = bio_list_peek(&tg->bio_lists[READ]))
&& tg_may_dispatch(td, tg, bio, NULL)) {
tg_dispatch_one_bio(td, tg, bio_data_dir(bio), bl);
nr_reads++;
if (nr_reads >= max_nr_reads)
break;
}
while ((bio = bio_list_peek(&tg->bio_lists[WRITE]))
&& tg_may_dispatch(td, tg, bio, NULL)) {
tg_dispatch_one_bio(td, tg, bio_data_dir(bio), bl);
nr_writes++;
if (nr_writes >= max_nr_writes)
break;
}
return nr_reads + nr_writes;
}
static int throtl_select_dispatch(struct throtl_data *td, struct bio_list *bl)
{
unsigned int nr_disp = 0;
struct throtl_grp *tg;
struct throtl_rb_root *st = &td->tg_service_tree;
while (1) {
tg = throtl_rb_first(st);
if (!tg)
break;
if (time_before(jiffies, tg->disptime))
break;
throtl_dequeue_tg(td, tg);
nr_disp += throtl_dispatch_tg(td, tg, bl);
if (tg->nr_queued[0] || tg->nr_queued[1]) {
tg_update_disptime(td, tg);
throtl_enqueue_tg(td, tg);
}
if (nr_disp >= throtl_quantum)
break;
}
return nr_disp;
}
static void throtl_process_limit_change(struct throtl_data *td)
{
struct throtl_grp *tg;
struct hlist_node *pos, *n;
if (!td->limits_changed)
return;
xchg(&td->limits_changed, false);
throtl_log(td, "limits changed");
hlist_for_each_entry_safe(tg, pos, n, &td->tg_list, tg_node) {
if (!tg->limits_changed)
continue;
if (!xchg(&tg->limits_changed, false))
continue;
throtl_log_tg(td, tg, "limit change rbps=%llu wbps=%llu"
" riops=%u wiops=%u", tg->bps[READ], tg->bps[WRITE],
tg->iops[READ], tg->iops[WRITE]);
/*
* Restart the slices for both READ and WRITES. It
* might happen that a group's limit are dropped
* suddenly and we don't want to account recently
* dispatched IO with new low rate
*/
throtl_start_new_slice(td, tg, 0);
throtl_start_new_slice(td, tg, 1);
if (throtl_tg_on_rr(tg))
tg_update_disptime(td, tg);
}
}
/* Dispatch throttled bios. Should be called without queue lock held. */
static int throtl_dispatch(struct request_queue *q)
{
struct throtl_data *td = q->td;
unsigned int nr_disp = 0;
struct bio_list bio_list_on_stack;
struct bio *bio;
struct blk_plug plug;
spin_lock_irq(q->queue_lock);
throtl_process_limit_change(td);
if (!total_nr_queued(td))
goto out;
bio_list_init(&bio_list_on_stack);
throtl_log(td, "dispatch nr_queued=%u read=%u write=%u",
total_nr_queued(td), td->nr_queued[READ],
td->nr_queued[WRITE]);
nr_disp = throtl_select_dispatch(td, &bio_list_on_stack);
if (nr_disp)
throtl_log(td, "bios disp=%u", nr_disp);
throtl_schedule_next_dispatch(td);
out:
spin_unlock_irq(q->queue_lock);
/*
* If we dispatched some requests, unplug the queue to make sure
* immediate dispatch
*/
if (nr_disp) {
blk_start_plug(&plug);
while((bio = bio_list_pop(&bio_list_on_stack)))
generic_make_request(bio);
blk_finish_plug(&plug);
}
return nr_disp;
}
void blk_throtl_work(struct work_struct *work)
{
struct throtl_data *td = container_of(work, struct throtl_data,
throtl_work.work);
struct request_queue *q = td->queue;
throtl_dispatch(q);
}
/* Call with queue lock held */
static void
throtl_schedule_delayed_work(struct throtl_data *td, unsigned long delay)
{
struct delayed_work *dwork = &td->throtl_work;
/* schedule work if limits changed even if no bio is queued */
if (total_nr_queued(td) || td->limits_changed) {
/*
* We might have a work scheduled to be executed in future.
* Cancel that and schedule a new one.
*/
__cancel_delayed_work(dwork);
queue_delayed_work(kthrotld_workqueue, dwork, delay);
throtl_log(td, "schedule work. delay=%lu jiffies=%lu",
delay, jiffies);
}
}
static void
throtl_destroy_tg(struct throtl_data *td, struct throtl_grp *tg)
{
/* Something wrong if we are trying to remove same group twice */
BUG_ON(hlist_unhashed(&tg->tg_node));
hlist_del_init(&tg->tg_node);
/*
* Put the reference taken at the time of creation so that when all
* queues are gone, group can be destroyed.
*/
throtl_put_tg(tg);
td->nr_undestroyed_grps--;
}
static void throtl_release_tgs(struct throtl_data *td)
{
struct hlist_node *pos, *n;
struct throtl_grp *tg;
hlist_for_each_entry_safe(tg, pos, n, &td->tg_list, tg_node) {
/*
* If cgroup removal path got to blk_group first and removed
* it from cgroup list, then it will take care of destroying
* cfqg also.
*/
if (!blkiocg_del_blkio_group(&tg->blkg))
throtl_destroy_tg(td, tg);
}
}
static void throtl_td_free(struct throtl_data *td)
{
kfree(td);
}
/*
* Blk cgroup controller notification saying that blkio_group object is being
* delinked as associated cgroup object is going away. That also means that
* no new IO will come in this group. So get rid of this group as soon as
* any pending IO in the group is finished.
*
* This function is called under rcu_read_lock(). key is the rcu protected
* pointer. That means "key" is a valid throtl_data pointer as long as we are
* rcu read lock.
*
* "key" was fetched from blkio_group under blkio_cgroup->lock. That means
* it should not be NULL as even if queue was going away, cgroup deltion
* path got to it first.
*/
void throtl_unlink_blkio_group(void *key, struct blkio_group *blkg)
{
unsigned long flags;
struct throtl_data *td = key;
spin_lock_irqsave(td->queue->queue_lock, flags);
throtl_destroy_tg(td, tg_of_blkg(blkg));
spin_unlock_irqrestore(td->queue->queue_lock, flags);
}
static void throtl_update_blkio_group_common(struct throtl_data *td,
struct throtl_grp *tg)
{
xchg(&tg->limits_changed, true);
xchg(&td->limits_changed, true);
/* Schedule a work now to process the limit change */
throtl_schedule_delayed_work(td, 0);
}
/*
* For all update functions, key should be a valid pointer because these
* update functions are called under blkcg_lock, that means, blkg is
* valid and in turn key is valid. queue exit path can not race because
* of blkcg_lock
*
* Can not take queue lock in update functions as queue lock under blkcg_lock
* is not allowed. Under other paths we take blkcg_lock under queue_lock.
*/
static void throtl_update_blkio_group_read_bps(void *key,
struct blkio_group *blkg, u64 read_bps)
{
struct throtl_data *td = key;
struct throtl_grp *tg = tg_of_blkg(blkg);
tg->bps[READ] = read_bps;
throtl_update_blkio_group_common(td, tg);
}
static void throtl_update_blkio_group_write_bps(void *key,
struct blkio_group *blkg, u64 write_bps)
{
struct throtl_data *td = key;
struct throtl_grp *tg = tg_of_blkg(blkg);
tg->bps[WRITE] = write_bps;
throtl_update_blkio_group_common(td, tg);
}
static void throtl_update_blkio_group_read_iops(void *key,
struct blkio_group *blkg, unsigned int read_iops)
{
struct throtl_data *td = key;
struct throtl_grp *tg = tg_of_blkg(blkg);
tg->iops[READ] = read_iops;
throtl_update_blkio_group_common(td, tg);
}
static void throtl_update_blkio_group_write_iops(void *key,
struct blkio_group *blkg, unsigned int write_iops)
{
struct throtl_data *td = key;
struct throtl_grp *tg = tg_of_blkg(blkg);
tg->iops[WRITE] = write_iops;
throtl_update_blkio_group_common(td, tg);
}
static void throtl_shutdown_wq(struct request_queue *q)
{
struct throtl_data *td = q->td;
cancel_delayed_work_sync(&td->throtl_work);
}
static struct blkio_policy_type blkio_policy_throtl = {
.ops = {
.blkio_unlink_group_fn = throtl_unlink_blkio_group,
.blkio_update_group_read_bps_fn =
throtl_update_blkio_group_read_bps,
.blkio_update_group_write_bps_fn =
throtl_update_blkio_group_write_bps,
.blkio_update_group_read_iops_fn =
throtl_update_blkio_group_read_iops,
.blkio_update_group_write_iops_fn =
throtl_update_blkio_group_write_iops,
},
.plid = BLKIO_POLICY_THROTL,
};
int blk_throtl_bio(struct request_queue *q, struct bio **biop)
{
struct throtl_data *td = q->td;
struct throtl_grp *tg;
struct bio *bio = *biop;
bool rw = bio_data_dir(bio), update_disptime = true;
struct blkio_cgroup *blkcg;
if (bio->bi_rw & REQ_THROTTLED) {
bio->bi_rw &= ~REQ_THROTTLED;
return 0;
}
/*
* A throtl_grp pointer retrieved under rcu can be used to access
* basic fields like stats and io rates. If a group has no rules,
* just update the dispatch stats in lockless manner and return.
*/
rcu_read_lock();
blkcg = task_blkio_cgroup(current);
tg = throtl_find_tg(td, blkcg);
if (tg) {
throtl_tg_fill_dev_details(td, tg);
if (tg_no_rule_group(tg, rw)) {
blkiocg_update_dispatch_stats(&tg->blkg, bio->bi_size,
rw, rw_is_sync(bio->bi_rw));
rcu_read_unlock();
return 0;
}
}
rcu_read_unlock();
/*
* Either group has not been allocated yet or it is not an unlimited
* IO group
*/
spin_lock_irq(q->queue_lock);
tg = throtl_get_tg(td);
if (IS_ERR(tg)) {
if (PTR_ERR(tg) == -ENODEV) {
/*
* Queue is gone. No queue lock held here.
*/
return -ENODEV;
}
}
if (tg->nr_queued[rw]) {
/*
* There is already another bio queued in same dir. No
* need to update dispatch time.
*/
update_disptime = false;
goto queue_bio;
}
/* Bio is with-in rate limit of group */
if (tg_may_dispatch(td, tg, bio, NULL)) {
throtl_charge_bio(tg, bio);
/*
* We need to trim slice even when bios are not being queued
* otherwise it might happen that a bio is not queued for
* a long time and slice keeps on extending and trim is not
* called for a long time. Now if limits are reduced suddenly
* we take into account all the IO dispatched so far at new
* low rate and * newly queued IO gets a really long dispatch
* time.
*
* So keep on trimming slice even if bio is not queued.
*/
throtl_trim_slice(td, tg, rw);
goto out;
}
queue_bio:
throtl_log_tg(td, tg, "[%c] bio. bdisp=%llu sz=%u bps=%llu"
" iodisp=%u iops=%u queued=%d/%d",
rw == READ ? 'R' : 'W',
tg->bytes_disp[rw], bio->bi_size, tg->bps[rw],
tg->io_disp[rw], tg->iops[rw],
tg->nr_queued[READ], tg->nr_queued[WRITE]);
throtl_add_bio_tg(q->td, tg, bio);
*biop = NULL;
if (update_disptime) {
tg_update_disptime(td, tg);
throtl_schedule_next_dispatch(td);
}
out:
spin_unlock_irq(q->queue_lock);
return 0;
}
int blk_throtl_init(struct request_queue *q)
{
struct throtl_data *td;
struct throtl_grp *tg;
td = kzalloc_node(sizeof(*td), GFP_KERNEL, q->node);
if (!td)
return -ENOMEM;
INIT_HLIST_HEAD(&td->tg_list);
td->tg_service_tree = THROTL_RB_ROOT;
td->limits_changed = false;
INIT_DELAYED_WORK(&td->throtl_work, blk_throtl_work);
/* alloc and Init root group. */
td->queue = q;
tg = throtl_alloc_tg(td);
if (!tg) {
kfree(td);
return -ENOMEM;
}
td->root_tg = tg;
rcu_read_lock();
throtl_init_add_tg_lists(td, tg, &blkio_root_cgroup);
rcu_read_unlock();
/* Attach throtl data to request queue */
q->td = td;
return 0;
}
void blk_throtl_exit(struct request_queue *q)
{
struct throtl_data *td = q->td;
bool wait = false;
BUG_ON(!td);
throtl_shutdown_wq(q);
spin_lock_irq(q->queue_lock);
throtl_release_tgs(td);
/* If there are other groups */
if (td->nr_undestroyed_grps > 0)
wait = true;
spin_unlock_irq(q->queue_lock);
/*
* Wait for tg->blkg->key accessors to exit their grace periods.
* Do this wait only if there are other undestroyed groups out
* there (other than root group). This can happen if cgroup deletion
* path claimed the responsibility of cleaning up a group before
* queue cleanup code get to the group.
*
* Do not call synchronize_rcu() unconditionally as there are drivers
* which create/delete request queue hundreds of times during scan/boot
* and synchronize_rcu() can take significant time and slow down boot.
*/
if (wait)
synchronize_rcu();
/*
* Just being safe to make sure after previous flush if some body did
* update limits through cgroup and another work got queued, cancel
* it.
*/
throtl_shutdown_wq(q);
throtl_td_free(td);
}
static int __init throtl_init(void)
{
kthrotld_workqueue = alloc_workqueue("kthrotld", WQ_MEM_RECLAIM, 0);
if (!kthrotld_workqueue)
panic("Failed to create kthrotld\n");
blkio_policy_register(&blkio_policy_throtl);
return 0;
}
module_init(throtl_init);
| gpl-2.0 |
behind2/git | mergesort.c | 390 | 1514 | #include "cache.h"
#include "mergesort.h"
struct mergesort_sublist {
void *ptr;
unsigned long len;
};
static void *get_nth_next(void *list, unsigned long n,
void *(*get_next_fn)(const void *))
{
while (n-- && list)
list = get_next_fn(list);
return list;
}
static void *pop_item(struct mergesort_sublist *l,
void *(*get_next_fn)(const void *))
{
void *p = l->ptr;
l->ptr = get_next_fn(l->ptr);
l->len = l->ptr ? (l->len - 1) : 0;
return p;
}
void *llist_mergesort(void *list,
void *(*get_next_fn)(const void *),
void (*set_next_fn)(void *, void *),
int (*compare_fn)(const void *, const void *))
{
unsigned long l;
if (!list)
return NULL;
for (l = 1; ; l *= 2) {
void *curr;
struct mergesort_sublist p, q;
p.ptr = list;
q.ptr = get_nth_next(p.ptr, l, get_next_fn);
if (!q.ptr)
break;
p.len = q.len = l;
if (compare_fn(p.ptr, q.ptr) > 0)
list = curr = pop_item(&q, get_next_fn);
else
list = curr = pop_item(&p, get_next_fn);
while (p.ptr) {
while (p.len || q.len) {
void *prev = curr;
if (!p.len)
curr = pop_item(&q, get_next_fn);
else if (!q.len)
curr = pop_item(&p, get_next_fn);
else if (compare_fn(p.ptr, q.ptr) > 0)
curr = pop_item(&q, get_next_fn);
else
curr = pop_item(&p, get_next_fn);
set_next_fn(prev, curr);
}
p.ptr = q.ptr;
p.len = l;
q.ptr = get_nth_next(p.ptr, l, get_next_fn);
q.len = q.ptr ? l : 0;
}
set_next_fn(curr, NULL);
}
return list;
}
| gpl-2.0 |
jyunyen/Nexus7_Kernal | fs/xfs/xfs_trans_inode.c | 390 | 4794 | /*
* Copyright (c) 2000,2005 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_types.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_mount.h"
#include "xfs_bmap_btree.h"
#include "xfs_alloc_btree.h"
#include "xfs_ialloc_btree.h"
#include "xfs_dinode.h"
#include "xfs_inode.h"
#include "xfs_btree.h"
#include "xfs_trans_priv.h"
#include "xfs_inode_item.h"
#include "xfs_trace.h"
#ifdef XFS_TRANS_DEBUG
STATIC void
xfs_trans_inode_broot_debug(
xfs_inode_t *ip);
#else
#define xfs_trans_inode_broot_debug(ip)
#endif
/*
* Add a locked inode to the transaction.
*
* The inode must be locked, and it cannot be associated with any transaction.
*/
void
xfs_trans_ijoin(
struct xfs_trans *tp,
struct xfs_inode *ip)
{
xfs_inode_log_item_t *iip;
ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
if (ip->i_itemp == NULL)
xfs_inode_item_init(ip, ip->i_mount);
iip = ip->i_itemp;
ASSERT(iip->ili_lock_flags == 0);
/*
* Get a log_item_desc to point at the new item.
*/
xfs_trans_add_item(tp, &iip->ili_item);
xfs_trans_inode_broot_debug(ip);
}
/*
* Add a locked inode to the transaction.
*
*
* Grabs a reference to the inode which will be dropped when the transaction
* is committed. The inode will also be unlocked at that point. The inode
* must be locked, and it cannot be associated with any transaction.
*/
void
xfs_trans_ijoin_ref(
struct xfs_trans *tp,
struct xfs_inode *ip,
uint lock_flags)
{
xfs_trans_ijoin(tp, ip);
IHOLD(ip);
ip->i_itemp->ili_lock_flags = lock_flags;
}
/*
* Transactional inode timestamp update. Requires the inode to be locked and
* joined to the transaction supplied. Relies on the transaction subsystem to
* track dirty state and update/writeback the inode accordingly.
*/
void
xfs_trans_ichgtime(
struct xfs_trans *tp,
struct xfs_inode *ip,
int flags)
{
struct inode *inode = VFS_I(ip);
timespec_t tv;
ASSERT(tp);
ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
tv = current_fs_time(inode->i_sb);
if ((flags & XFS_ICHGTIME_MOD) &&
!timespec_equal(&inode->i_mtime, &tv)) {
inode->i_mtime = tv;
}
if ((flags & XFS_ICHGTIME_CHG) &&
!timespec_equal(&inode->i_ctime, &tv)) {
inode->i_ctime = tv;
}
}
/*
* This is called to mark the fields indicated in fieldmask as needing
* to be logged when the transaction is committed. The inode must
* already be associated with the given transaction.
*
* The values for fieldmask are defined in xfs_inode_item.h. We always
* log all of the core inode if any of it has changed, and we always log
* all of the inline data/extents/b-tree root if any of them has changed.
*/
void
xfs_trans_log_inode(
xfs_trans_t *tp,
xfs_inode_t *ip,
uint flags)
{
ASSERT(ip->i_itemp != NULL);
ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
tp->t_flags |= XFS_TRANS_DIRTY;
ip->i_itemp->ili_item.li_desc->lid_flags |= XFS_LID_DIRTY;
/*
* Always OR in the bits from the ili_last_fields field.
* This is to coordinate with the xfs_iflush() and xfs_iflush_done()
* routines in the eventual clearing of the ilf_fields bits.
* See the big comment in xfs_iflush() for an explanation of
* this coordination mechanism.
*/
flags |= ip->i_itemp->ili_last_fields;
ip->i_itemp->ili_format.ilf_fields |= flags;
}
#ifdef XFS_TRANS_DEBUG
/*
* Keep track of the state of the inode btree root to make sure we
* log it properly.
*/
STATIC void
xfs_trans_inode_broot_debug(
xfs_inode_t *ip)
{
xfs_inode_log_item_t *iip;
ASSERT(ip->i_itemp != NULL);
iip = ip->i_itemp;
if (iip->ili_root_size != 0) {
ASSERT(iip->ili_orig_root != NULL);
kmem_free(iip->ili_orig_root);
iip->ili_root_size = 0;
iip->ili_orig_root = NULL;
}
if (ip->i_d.di_format == XFS_DINODE_FMT_BTREE) {
ASSERT((ip->i_df.if_broot != NULL) &&
(ip->i_df.if_broot_bytes > 0));
iip->ili_root_size = ip->i_df.if_broot_bytes;
iip->ili_orig_root =
(char*)kmem_alloc(iip->ili_root_size, KM_SLEEP);
memcpy(iip->ili_orig_root, (char*)(ip->i_df.if_broot),
iip->ili_root_size);
}
}
#endif
| gpl-2.0 |
tobetter/board-config | arch/um/os-Linux/process.c | 390 | 5144 | /*
* Copyright (C) 2002 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
* Licensed under the GPL
*/
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <asm/unistd.h>
#include <init.h>
#include <longjmp.h>
#include <os.h>
#include <skas_ptrace.h>
#define ARBITRARY_ADDR -1
#define FAILURE_PID -1
#define STAT_PATH_LEN sizeof("/proc/#######/stat\0")
#define COMM_SCANF "%*[^)])"
unsigned long os_process_pc(int pid)
{
char proc_stat[STAT_PATH_LEN], buf[256];
unsigned long pc = ARBITRARY_ADDR;
int fd, err;
sprintf(proc_stat, "/proc/%d/stat", pid);
fd = open(proc_stat, O_RDONLY, 0);
if (fd < 0) {
printk(UM_KERN_ERR "os_process_pc - couldn't open '%s', "
"errno = %d\n", proc_stat, errno);
goto out;
}
CATCH_EINTR(err = read(fd, buf, sizeof(buf)));
if (err < 0) {
printk(UM_KERN_ERR "os_process_pc - couldn't read '%s', "
"err = %d\n", proc_stat, errno);
goto out_close;
}
os_close_file(fd);
pc = ARBITRARY_ADDR;
if (sscanf(buf, "%*d " COMM_SCANF " %*c %*d %*d %*d %*d %*d %*d %*d "
"%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
"%*d %*d %*d %*d %*d %lu", &pc) != 1)
printk(UM_KERN_ERR "os_process_pc - couldn't find pc in '%s'\n",
buf);
out_close:
close(fd);
out:
return pc;
}
int os_process_parent(int pid)
{
char stat[STAT_PATH_LEN];
char data[256];
int parent = FAILURE_PID, n, fd;
if (pid == -1)
return parent;
snprintf(stat, sizeof(stat), "/proc/%d/stat", pid);
fd = open(stat, O_RDONLY, 0);
if (fd < 0) {
printk(UM_KERN_ERR "Couldn't open '%s', errno = %d\n", stat,
errno);
return parent;
}
CATCH_EINTR(n = read(fd, data, sizeof(data)));
close(fd);
if (n < 0) {
printk(UM_KERN_ERR "Couldn't read '%s', errno = %d\n", stat,
errno);
return parent;
}
parent = FAILURE_PID;
n = sscanf(data, "%*d " COMM_SCANF " %*c %d", &parent);
if (n != 1)
printk(UM_KERN_ERR "Failed to scan '%s'\n", data);
return parent;
}
void os_stop_process(int pid)
{
kill(pid, SIGSTOP);
}
void os_kill_process(int pid, int reap_child)
{
kill(pid, SIGKILL);
if (reap_child)
CATCH_EINTR(waitpid(pid, NULL, __WALL));
}
/* This is here uniquely to have access to the userspace errno, i.e. the one
* used by ptrace in case of error.
*/
long os_ptrace_ldt(long pid, long addr, long data)
{
int ret;
ret = ptrace(PTRACE_LDT, pid, addr, data);
if (ret < 0)
return -errno;
return ret;
}
/* Kill off a ptraced child by all means available. kill it normally first,
* then PTRACE_KILL it, then PTRACE_CONT it in case it's in a run state from
* which it can't exit directly.
*/
void os_kill_ptraced_process(int pid, int reap_child)
{
kill(pid, SIGKILL);
ptrace(PTRACE_KILL, pid);
ptrace(PTRACE_CONT, pid);
if (reap_child)
CATCH_EINTR(waitpid(pid, NULL, __WALL));
}
/* Don't use the glibc version, which caches the result in TLS. It misses some
* syscalls, and also breaks with clone(), which does not unshare the TLS.
*/
int os_getpid(void)
{
return syscall(__NR_getpid);
}
int os_getpgrp(void)
{
return getpgrp();
}
int os_map_memory(void *virt, int fd, unsigned long long off, unsigned long len,
int r, int w, int x)
{
void *loc;
int prot;
prot = (r ? PROT_READ : 0) | (w ? PROT_WRITE : 0) |
(x ? PROT_EXEC : 0);
loc = mmap64((void *) virt, len, prot, MAP_SHARED | MAP_FIXED,
fd, off);
if (loc == MAP_FAILED)
return -errno;
return 0;
}
int os_protect_memory(void *addr, unsigned long len, int r, int w, int x)
{
int prot = ((r ? PROT_READ : 0) | (w ? PROT_WRITE : 0) |
(x ? PROT_EXEC : 0));
if (mprotect(addr, len, prot) < 0)
return -errno;
return 0;
}
int os_unmap_memory(void *addr, int len)
{
int err;
err = munmap(addr, len);
if (err < 0)
return -errno;
return 0;
}
#ifndef MADV_REMOVE
#define MADV_REMOVE KERNEL_MADV_REMOVE
#endif
int os_drop_memory(void *addr, int length)
{
int err;
err = madvise(addr, length, MADV_REMOVE);
if (err < 0)
err = -errno;
return err;
}
int __init can_drop_memory(void)
{
void *addr;
int fd, ok = 0;
printk(UM_KERN_INFO "Checking host MADV_REMOVE support...");
fd = create_mem_file(UM_KERN_PAGE_SIZE);
if (fd < 0) {
printk(UM_KERN_ERR "Creating test memory file failed, "
"err = %d\n", -fd);
goto out;
}
addr = mmap64(NULL, UM_KERN_PAGE_SIZE, PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0);
if (addr == MAP_FAILED) {
printk(UM_KERN_ERR "Mapping test memory file failed, "
"err = %d\n", -errno);
goto out_close;
}
if (madvise(addr, UM_KERN_PAGE_SIZE, MADV_REMOVE) != 0) {
printk(UM_KERN_ERR "MADV_REMOVE failed, err = %d\n", -errno);
goto out_unmap;
}
printk(UM_KERN_CONT "OK\n");
ok = 1;
out_unmap:
munmap(addr, UM_KERN_PAGE_SIZE);
out_close:
close(fd);
out:
return ok;
}
void init_new_thread_signals(void)
{
set_handler(SIGSEGV);
set_handler(SIGTRAP);
set_handler(SIGFPE);
set_handler(SIGILL);
set_handler(SIGBUS);
signal(SIGHUP, SIG_IGN);
set_handler(SIGIO);
signal(SIGWINCH, SIG_IGN);
signal(SIGTERM, SIG_DFL);
}
| gpl-2.0 |
gslate-cm9/android_kernel_lge_v909 | lib/radix-tree.c | 390 | 40460 | /*
* Copyright (C) 2001 Momchil Velikov
* Portions Copyright (C) 2001 Christoph Hellwig
* Copyright (C) 2005 SGI, Christoph Lameter
* Copyright (C) 2006 Nick Piggin
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/radix-tree.h>
#include <linux/percpu.h>
#include <linux/slab.h>
#include <linux/notifier.h>
#include <linux/cpu.h>
#include <linux/string.h>
#include <linux/bitops.h>
#include <linux/rcupdate.h>
#ifdef __KERNEL__
#define RADIX_TREE_MAP_SHIFT (CONFIG_BASE_SMALL ? 4 : 6)
#else
#define RADIX_TREE_MAP_SHIFT 3 /* For more stressful testing */
#endif
#define RADIX_TREE_MAP_SIZE (1UL << RADIX_TREE_MAP_SHIFT)
#define RADIX_TREE_MAP_MASK (RADIX_TREE_MAP_SIZE-1)
#define RADIX_TREE_TAG_LONGS \
((RADIX_TREE_MAP_SIZE + BITS_PER_LONG - 1) / BITS_PER_LONG)
struct radix_tree_node {
unsigned int height; /* Height from the bottom */
unsigned int count;
struct rcu_head rcu_head;
void __rcu *slots[RADIX_TREE_MAP_SIZE];
unsigned long tags[RADIX_TREE_MAX_TAGS][RADIX_TREE_TAG_LONGS];
};
struct radix_tree_path {
struct radix_tree_node *node;
int offset;
};
#define RADIX_TREE_INDEX_BITS (8 /* CHAR_BIT */ * sizeof(unsigned long))
#define RADIX_TREE_MAX_PATH (DIV_ROUND_UP(RADIX_TREE_INDEX_BITS, \
RADIX_TREE_MAP_SHIFT))
/*
* The height_to_maxindex array needs to be one deeper than the maximum
* path as height 0 holds only 1 entry.
*/
static unsigned long height_to_maxindex[RADIX_TREE_MAX_PATH + 1] __read_mostly;
/*
* Radix tree node cache.
*/
static struct kmem_cache *radix_tree_node_cachep;
/*
* Per-cpu pool of preloaded nodes
*/
struct radix_tree_preload {
int nr;
struct radix_tree_node *nodes[RADIX_TREE_MAX_PATH];
};
static DEFINE_PER_CPU(struct radix_tree_preload, radix_tree_preloads) = { 0, };
static inline void *ptr_to_indirect(void *ptr)
{
return (void *)((unsigned long)ptr | RADIX_TREE_INDIRECT_PTR);
}
static inline void *indirect_to_ptr(void *ptr)
{
return (void *)((unsigned long)ptr & ~RADIX_TREE_INDIRECT_PTR);
}
static inline gfp_t root_gfp_mask(struct radix_tree_root *root)
{
return root->gfp_mask & __GFP_BITS_MASK;
}
static inline void tag_set(struct radix_tree_node *node, unsigned int tag,
int offset)
{
__set_bit(offset, node->tags[tag]);
}
static inline void tag_clear(struct radix_tree_node *node, unsigned int tag,
int offset)
{
__clear_bit(offset, node->tags[tag]);
}
static inline int tag_get(struct radix_tree_node *node, unsigned int tag,
int offset)
{
return test_bit(offset, node->tags[tag]);
}
static inline void root_tag_set(struct radix_tree_root *root, unsigned int tag)
{
root->gfp_mask |= (__force gfp_t)(1 << (tag + __GFP_BITS_SHIFT));
}
static inline void root_tag_clear(struct radix_tree_root *root, unsigned int tag)
{
root->gfp_mask &= (__force gfp_t)~(1 << (tag + __GFP_BITS_SHIFT));
}
static inline void root_tag_clear_all(struct radix_tree_root *root)
{
root->gfp_mask &= __GFP_BITS_MASK;
}
static inline int root_tag_get(struct radix_tree_root *root, unsigned int tag)
{
return (__force unsigned)root->gfp_mask & (1 << (tag + __GFP_BITS_SHIFT));
}
/*
* Returns 1 if any slot in the node has this tag set.
* Otherwise returns 0.
*/
static inline int any_tag_set(struct radix_tree_node *node, unsigned int tag)
{
int idx;
for (idx = 0; idx < RADIX_TREE_TAG_LONGS; idx++) {
if (node->tags[tag][idx])
return 1;
}
return 0;
}
/*
* This assumes that the caller has performed appropriate preallocation, and
* that the caller has pinned this thread of control to the current CPU.
*/
static struct radix_tree_node *
radix_tree_node_alloc(struct radix_tree_root *root)
{
struct radix_tree_node *ret = NULL;
gfp_t gfp_mask = root_gfp_mask(root);
if (!(gfp_mask & __GFP_WAIT)) {
struct radix_tree_preload *rtp;
/*
* Provided the caller has preloaded here, we will always
* succeed in getting a node here (and never reach
* kmem_cache_alloc)
*/
rtp = &__get_cpu_var(radix_tree_preloads);
if (rtp->nr) {
ret = rtp->nodes[rtp->nr - 1];
rtp->nodes[rtp->nr - 1] = NULL;
rtp->nr--;
}
}
if (ret == NULL)
ret = kmem_cache_alloc(radix_tree_node_cachep, gfp_mask);
BUG_ON(radix_tree_is_indirect_ptr(ret));
return ret;
}
static void radix_tree_node_rcu_free(struct rcu_head *head)
{
struct radix_tree_node *node =
container_of(head, struct radix_tree_node, rcu_head);
int i;
/*
* must only free zeroed nodes into the slab. radix_tree_shrink
* can leave us with a non-NULL entry in the first slot, so clear
* that here to make sure.
*/
for (i = 0; i < RADIX_TREE_MAX_TAGS; i++)
tag_clear(node, i, 0);
node->slots[0] = NULL;
node->count = 0;
kmem_cache_free(radix_tree_node_cachep, node);
}
static inline void
radix_tree_node_free(struct radix_tree_node *node)
{
call_rcu(&node->rcu_head, radix_tree_node_rcu_free);
}
/*
* Load up this CPU's radix_tree_node buffer with sufficient objects to
* ensure that the addition of a single element in the tree cannot fail. On
* success, return zero, with preemption disabled. On error, return -ENOMEM
* with preemption not disabled.
*
* To make use of this facility, the radix tree must be initialised without
* __GFP_WAIT being passed to INIT_RADIX_TREE().
*/
int radix_tree_preload(gfp_t gfp_mask)
{
struct radix_tree_preload *rtp;
struct radix_tree_node *node;
int ret = -ENOMEM;
preempt_disable();
rtp = &__get_cpu_var(radix_tree_preloads);
while (rtp->nr < ARRAY_SIZE(rtp->nodes)) {
preempt_enable();
node = kmem_cache_alloc(radix_tree_node_cachep, gfp_mask);
if (node == NULL)
goto out;
preempt_disable();
rtp = &__get_cpu_var(radix_tree_preloads);
if (rtp->nr < ARRAY_SIZE(rtp->nodes))
rtp->nodes[rtp->nr++] = node;
else
kmem_cache_free(radix_tree_node_cachep, node);
}
ret = 0;
out:
return ret;
}
EXPORT_SYMBOL(radix_tree_preload);
/*
* Return the maximum key which can be store into a
* radix tree with height HEIGHT.
*/
static inline unsigned long radix_tree_maxindex(unsigned int height)
{
return height_to_maxindex[height];
}
/*
* Extend a radix tree so it can store key @index.
*/
static int radix_tree_extend(struct radix_tree_root *root, unsigned long index)
{
struct radix_tree_node *node;
unsigned int height;
int tag;
/* Figure out what the height should be. */
height = root->height + 1;
while (index > radix_tree_maxindex(height))
height++;
if (root->rnode == NULL) {
root->height = height;
goto out;
}
do {
unsigned int newheight;
if (!(node = radix_tree_node_alloc(root)))
return -ENOMEM;
/* Increase the height. */
node->slots[0] = indirect_to_ptr(root->rnode);
/* Propagate the aggregated tag info into the new root */
for (tag = 0; tag < RADIX_TREE_MAX_TAGS; tag++) {
if (root_tag_get(root, tag))
tag_set(node, tag, 0);
}
newheight = root->height+1;
node->height = newheight;
node->count = 1;
node = ptr_to_indirect(node);
rcu_assign_pointer(root->rnode, node);
root->height = newheight;
} while (height > root->height);
out:
return 0;
}
/**
* radix_tree_insert - insert into a radix tree
* @root: radix tree root
* @index: index key
* @item: item to insert
*
* Insert an item into the radix tree at position @index.
*/
int radix_tree_insert(struct radix_tree_root *root,
unsigned long index, void *item)
{
struct radix_tree_node *node = NULL, *slot;
unsigned int height, shift;
int offset;
int error;
BUG_ON(radix_tree_is_indirect_ptr(item));
/* Make sure the tree is high enough. */
if (index > radix_tree_maxindex(root->height)) {
error = radix_tree_extend(root, index);
if (error)
return error;
}
slot = indirect_to_ptr(root->rnode);
height = root->height;
shift = (height-1) * RADIX_TREE_MAP_SHIFT;
offset = 0; /* uninitialised var warning */
while (height > 0) {
if (slot == NULL) {
/* Have to add a child node. */
if (!(slot = radix_tree_node_alloc(root)))
return -ENOMEM;
slot->height = height;
if (node) {
rcu_assign_pointer(node->slots[offset], slot);
node->count++;
} else
rcu_assign_pointer(root->rnode, ptr_to_indirect(slot));
}
/* Go a level down */
offset = (index >> shift) & RADIX_TREE_MAP_MASK;
node = slot;
slot = node->slots[offset];
shift -= RADIX_TREE_MAP_SHIFT;
height--;
}
if (slot != NULL)
return -EEXIST;
if (node) {
node->count++;
rcu_assign_pointer(node->slots[offset], item);
BUG_ON(tag_get(node, 0, offset));
BUG_ON(tag_get(node, 1, offset));
} else {
rcu_assign_pointer(root->rnode, item);
BUG_ON(root_tag_get(root, 0));
BUG_ON(root_tag_get(root, 1));
}
return 0;
}
EXPORT_SYMBOL(radix_tree_insert);
/*
* is_slot == 1 : search for the slot.
* is_slot == 0 : search for the node.
*/
static void *radix_tree_lookup_element(struct radix_tree_root *root,
unsigned long index, int is_slot)
{
unsigned int height, shift;
struct radix_tree_node *node, **slot;
node = rcu_dereference_raw(root->rnode);
if (node == NULL)
return NULL;
if (!radix_tree_is_indirect_ptr(node)) {
if (index > 0)
return NULL;
return is_slot ? (void *)&root->rnode : node;
}
node = indirect_to_ptr(node);
height = node->height;
if (index > radix_tree_maxindex(height))
return NULL;
shift = (height-1) * RADIX_TREE_MAP_SHIFT;
do {
slot = (struct radix_tree_node **)
(node->slots + ((index>>shift) & RADIX_TREE_MAP_MASK));
node = rcu_dereference_raw(*slot);
if (node == NULL)
return NULL;
shift -= RADIX_TREE_MAP_SHIFT;
height--;
} while (height > 0);
return is_slot ? (void *)slot : indirect_to_ptr(node);
}
/**
* radix_tree_lookup_slot - lookup a slot in a radix tree
* @root: radix tree root
* @index: index key
*
* Returns: the slot corresponding to the position @index in the
* radix tree @root. This is useful for update-if-exists operations.
*
* This function can be called under rcu_read_lock iff the slot is not
* modified by radix_tree_replace_slot, otherwise it must be called
* exclusive from other writers. Any dereference of the slot must be done
* using radix_tree_deref_slot.
*/
void **radix_tree_lookup_slot(struct radix_tree_root *root, unsigned long index)
{
return (void **)radix_tree_lookup_element(root, index, 1);
}
EXPORT_SYMBOL(radix_tree_lookup_slot);
/**
* radix_tree_lookup - perform lookup operation on a radix tree
* @root: radix tree root
* @index: index key
*
* Lookup the item at the position @index in the radix tree @root.
*
* This function can be called under rcu_read_lock, however the caller
* must manage lifetimes of leaf nodes (eg. RCU may also be used to free
* them safely). No RCU barriers are required to access or modify the
* returned item, however.
*/
void *radix_tree_lookup(struct radix_tree_root *root, unsigned long index)
{
return radix_tree_lookup_element(root, index, 0);
}
EXPORT_SYMBOL(radix_tree_lookup);
/**
* radix_tree_tag_set - set a tag on a radix tree node
* @root: radix tree root
* @index: index key
* @tag: tag index
*
* Set the search tag (which must be < RADIX_TREE_MAX_TAGS)
* corresponding to @index in the radix tree. From
* the root all the way down to the leaf node.
*
* Returns the address of the tagged item. Setting a tag on a not-present
* item is a bug.
*/
void *radix_tree_tag_set(struct radix_tree_root *root,
unsigned long index, unsigned int tag)
{
unsigned int height, shift;
struct radix_tree_node *slot;
height = root->height;
BUG_ON(index > radix_tree_maxindex(height));
slot = indirect_to_ptr(root->rnode);
shift = (height - 1) * RADIX_TREE_MAP_SHIFT;
while (height > 0) {
int offset;
offset = (index >> shift) & RADIX_TREE_MAP_MASK;
if (!tag_get(slot, tag, offset))
tag_set(slot, tag, offset);
slot = slot->slots[offset];
BUG_ON(slot == NULL);
shift -= RADIX_TREE_MAP_SHIFT;
height--;
}
/* set the root's tag bit */
if (slot && !root_tag_get(root, tag))
root_tag_set(root, tag);
return slot;
}
EXPORT_SYMBOL(radix_tree_tag_set);
/**
* radix_tree_tag_clear - clear a tag on a radix tree node
* @root: radix tree root
* @index: index key
* @tag: tag index
*
* Clear the search tag (which must be < RADIX_TREE_MAX_TAGS)
* corresponding to @index in the radix tree. If
* this causes the leaf node to have no tags set then clear the tag in the
* next-to-leaf node, etc.
*
* Returns the address of the tagged item on success, else NULL. ie:
* has the same return value and semantics as radix_tree_lookup().
*/
void *radix_tree_tag_clear(struct radix_tree_root *root,
unsigned long index, unsigned int tag)
{
/*
* The radix tree path needs to be one longer than the maximum path
* since the "list" is null terminated.
*/
struct radix_tree_path path[RADIX_TREE_MAX_PATH + 1], *pathp = path;
struct radix_tree_node *slot = NULL;
unsigned int height, shift;
height = root->height;
if (index > radix_tree_maxindex(height))
goto out;
shift = (height - 1) * RADIX_TREE_MAP_SHIFT;
pathp->node = NULL;
slot = indirect_to_ptr(root->rnode);
while (height > 0) {
int offset;
if (slot == NULL)
goto out;
offset = (index >> shift) & RADIX_TREE_MAP_MASK;
pathp[1].offset = offset;
pathp[1].node = slot;
slot = slot->slots[offset];
pathp++;
shift -= RADIX_TREE_MAP_SHIFT;
height--;
}
if (slot == NULL)
goto out;
while (pathp->node) {
if (!tag_get(pathp->node, tag, pathp->offset))
goto out;
tag_clear(pathp->node, tag, pathp->offset);
if (any_tag_set(pathp->node, tag))
goto out;
pathp--;
}
/* clear the root's tag bit */
if (root_tag_get(root, tag))
root_tag_clear(root, tag);
out:
return slot;
}
EXPORT_SYMBOL(radix_tree_tag_clear);
/**
* radix_tree_tag_get - get a tag on a radix tree node
* @root: radix tree root
* @index: index key
* @tag: tag index (< RADIX_TREE_MAX_TAGS)
*
* Return values:
*
* 0: tag not present or not set
* 1: tag set
*
* Note that the return value of this function may not be relied on, even if
* the RCU lock is held, unless tag modification and node deletion are excluded
* from concurrency.
*/
int radix_tree_tag_get(struct radix_tree_root *root,
unsigned long index, unsigned int tag)
{
unsigned int height, shift;
struct radix_tree_node *node;
int saw_unset_tag = 0;
/* check the root's tag bit */
if (!root_tag_get(root, tag))
return 0;
node = rcu_dereference_raw(root->rnode);
if (node == NULL)
return 0;
if (!radix_tree_is_indirect_ptr(node))
return (index == 0);
node = indirect_to_ptr(node);
height = node->height;
if (index > radix_tree_maxindex(height))
return 0;
shift = (height - 1) * RADIX_TREE_MAP_SHIFT;
for ( ; ; ) {
int offset;
if (node == NULL)
return 0;
offset = (index >> shift) & RADIX_TREE_MAP_MASK;
/*
* This is just a debug check. Later, we can bale as soon as
* we see an unset tag.
*/
if (!tag_get(node, tag, offset))
saw_unset_tag = 1;
if (height == 1)
return !!tag_get(node, tag, offset);
node = rcu_dereference_raw(node->slots[offset]);
shift -= RADIX_TREE_MAP_SHIFT;
height--;
}
}
EXPORT_SYMBOL(radix_tree_tag_get);
/**
* radix_tree_range_tag_if_tagged - for each item in given range set given
* tag if item has another tag set
* @root: radix tree root
* @first_indexp: pointer to a starting index of a range to scan
* @last_index: last index of a range to scan
* @nr_to_tag: maximum number items to tag
* @iftag: tag index to test
* @settag: tag index to set if tested tag is set
*
* This function scans range of radix tree from first_index to last_index
* (inclusive). For each item in the range if iftag is set, the function sets
* also settag. The function stops either after tagging nr_to_tag items or
* after reaching last_index.
*
* The tags must be set from the leaf level only and propagated back up the
* path to the root. We must do this so that we resolve the full path before
* setting any tags on intermediate nodes. If we set tags as we descend, then
* we can get to the leaf node and find that the index that has the iftag
* set is outside the range we are scanning. This reults in dangling tags and
* can lead to problems with later tag operations (e.g. livelocks on lookups).
*
* The function returns number of leaves where the tag was set and sets
* *first_indexp to the first unscanned index.
* WARNING! *first_indexp can wrap if last_index is ULONG_MAX. Caller must
* be prepared to handle that.
*/
unsigned long radix_tree_range_tag_if_tagged(struct radix_tree_root *root,
unsigned long *first_indexp, unsigned long last_index,
unsigned long nr_to_tag,
unsigned int iftag, unsigned int settag)
{
unsigned int height = root->height;
struct radix_tree_path path[height];
struct radix_tree_path *pathp = path;
struct radix_tree_node *slot;
unsigned int shift;
unsigned long tagged = 0;
unsigned long index = *first_indexp;
last_index = min(last_index, radix_tree_maxindex(height));
if (index > last_index)
return 0;
if (!nr_to_tag)
return 0;
if (!root_tag_get(root, iftag)) {
*first_indexp = last_index + 1;
return 0;
}
if (height == 0) {
*first_indexp = last_index + 1;
root_tag_set(root, settag);
return 1;
}
shift = (height - 1) * RADIX_TREE_MAP_SHIFT;
slot = indirect_to_ptr(root->rnode);
/*
* we fill the path from (root->height - 2) to 0, leaving the index at
* (root->height - 1) as a terminator. Zero the node in the terminator
* so that we can use this to end walk loops back up the path.
*/
path[height - 1].node = NULL;
for (;;) {
int offset;
offset = (index >> shift) & RADIX_TREE_MAP_MASK;
if (!slot->slots[offset])
goto next;
if (!tag_get(slot, iftag, offset))
goto next;
if (height > 1) {
/* Go down one level */
height--;
shift -= RADIX_TREE_MAP_SHIFT;
path[height - 1].node = slot;
path[height - 1].offset = offset;
slot = slot->slots[offset];
continue;
}
/* tag the leaf */
tagged++;
tag_set(slot, settag, offset);
/* walk back up the path tagging interior nodes */
pathp = &path[0];
while (pathp->node) {
/* stop if we find a node with the tag already set */
if (tag_get(pathp->node, settag, pathp->offset))
break;
tag_set(pathp->node, settag, pathp->offset);
pathp++;
}
next:
/* Go to next item at level determined by 'shift' */
index = ((index >> shift) + 1) << shift;
/* Overflow can happen when last_index is ~0UL... */
if (index > last_index || !index)
break;
if (tagged >= nr_to_tag)
break;
while (((index >> shift) & RADIX_TREE_MAP_MASK) == 0) {
/*
* We've fully scanned this node. Go up. Because
* last_index is guaranteed to be in the tree, what
* we do below cannot wander astray.
*/
slot = path[height - 1].node;
height++;
shift += RADIX_TREE_MAP_SHIFT;
}
}
/*
* We need not to tag the root tag if there is no tag which is set with
* settag within the range from *first_indexp to last_index.
*/
if (tagged > 0)
root_tag_set(root, settag);
*first_indexp = index;
return tagged;
}
EXPORT_SYMBOL(radix_tree_range_tag_if_tagged);
/**
* radix_tree_next_hole - find the next hole (not-present entry)
* @root: tree root
* @index: index key
* @max_scan: maximum range to search
*
* Search the set [index, min(index+max_scan-1, MAX_INDEX)] for the lowest
* indexed hole.
*
* Returns: the index of the hole if found, otherwise returns an index
* outside of the set specified (in which case 'return - index >= max_scan'
* will be true). In rare cases of index wrap-around, 0 will be returned.
*
* radix_tree_next_hole may be called under rcu_read_lock. However, like
* radix_tree_gang_lookup, this will not atomically search a snapshot of
* the tree at a single point in time. For example, if a hole is created
* at index 5, then subsequently a hole is created at index 10,
* radix_tree_next_hole covering both indexes may return 10 if called
* under rcu_read_lock.
*/
unsigned long radix_tree_next_hole(struct radix_tree_root *root,
unsigned long index, unsigned long max_scan)
{
unsigned long i;
for (i = 0; i < max_scan; i++) {
if (!radix_tree_lookup(root, index))
break;
index++;
if (index == 0)
break;
}
return index;
}
EXPORT_SYMBOL(radix_tree_next_hole);
/**
* radix_tree_prev_hole - find the prev hole (not-present entry)
* @root: tree root
* @index: index key
* @max_scan: maximum range to search
*
* Search backwards in the range [max(index-max_scan+1, 0), index]
* for the first hole.
*
* Returns: the index of the hole if found, otherwise returns an index
* outside of the set specified (in which case 'index - return >= max_scan'
* will be true). In rare cases of wrap-around, ULONG_MAX will be returned.
*
* radix_tree_next_hole may be called under rcu_read_lock. However, like
* radix_tree_gang_lookup, this will not atomically search a snapshot of
* the tree at a single point in time. For example, if a hole is created
* at index 10, then subsequently a hole is created at index 5,
* radix_tree_prev_hole covering both indexes may return 5 if called under
* rcu_read_lock.
*/
unsigned long radix_tree_prev_hole(struct radix_tree_root *root,
unsigned long index, unsigned long max_scan)
{
unsigned long i;
for (i = 0; i < max_scan; i++) {
if (!radix_tree_lookup(root, index))
break;
index--;
if (index == ULONG_MAX)
break;
}
return index;
}
EXPORT_SYMBOL(radix_tree_prev_hole);
static unsigned int
__lookup(struct radix_tree_node *slot, void ***results, unsigned long *indices,
unsigned long index, unsigned int max_items, unsigned long *next_index)
{
unsigned int nr_found = 0;
unsigned int shift, height;
unsigned long i;
height = slot->height;
if (height == 0)
goto out;
shift = (height-1) * RADIX_TREE_MAP_SHIFT;
for ( ; height > 1; height--) {
i = (index >> shift) & RADIX_TREE_MAP_MASK;
for (;;) {
if (slot->slots[i] != NULL)
break;
index &= ~((1UL << shift) - 1);
index += 1UL << shift;
if (index == 0)
goto out; /* 32-bit wraparound */
i++;
if (i == RADIX_TREE_MAP_SIZE)
goto out;
}
shift -= RADIX_TREE_MAP_SHIFT;
slot = rcu_dereference_raw(slot->slots[i]);
if (slot == NULL)
goto out;
}
/* Bottom level: grab some items */
for (i = index & RADIX_TREE_MAP_MASK; i < RADIX_TREE_MAP_SIZE; i++) {
if (slot->slots[i]) {
results[nr_found] = &(slot->slots[i]);
if (indices)
indices[nr_found] = index;
if (++nr_found == max_items) {
index++;
goto out;
}
}
index++;
}
out:
*next_index = index;
return nr_found;
}
/**
* radix_tree_gang_lookup - perform multiple lookup on a radix tree
* @root: radix tree root
* @results: where the results of the lookup are placed
* @first_index: start the lookup from this key
* @max_items: place up to this many items at *results
*
* Performs an index-ascending scan of the tree for present items. Places
* them at *@results and returns the number of items which were placed at
* *@results.
*
* The implementation is naive.
*
* Like radix_tree_lookup, radix_tree_gang_lookup may be called under
* rcu_read_lock. In this case, rather than the returned results being
* an atomic snapshot of the tree at a single point in time, the semantics
* of an RCU protected gang lookup are as though multiple radix_tree_lookups
* have been issued in individual locks, and results stored in 'results'.
*/
unsigned int
radix_tree_gang_lookup(struct radix_tree_root *root, void **results,
unsigned long first_index, unsigned int max_items)
{
unsigned long max_index;
struct radix_tree_node *node;
unsigned long cur_index = first_index;
unsigned int ret;
node = rcu_dereference_raw(root->rnode);
if (!node)
return 0;
if (!radix_tree_is_indirect_ptr(node)) {
if (first_index > 0)
return 0;
results[0] = node;
return 1;
}
node = indirect_to_ptr(node);
max_index = radix_tree_maxindex(node->height);
ret = 0;
while (ret < max_items) {
unsigned int nr_found, slots_found, i;
unsigned long next_index; /* Index of next search */
if (cur_index > max_index)
break;
slots_found = __lookup(node, (void ***)results + ret, NULL,
cur_index, max_items - ret, &next_index);
nr_found = 0;
for (i = 0; i < slots_found; i++) {
struct radix_tree_node *slot;
slot = *(((void ***)results)[ret + i]);
if (!slot)
continue;
results[ret + nr_found] =
indirect_to_ptr(rcu_dereference_raw(slot));
nr_found++;
}
ret += nr_found;
if (next_index == 0)
break;
cur_index = next_index;
}
return ret;
}
EXPORT_SYMBOL(radix_tree_gang_lookup);
/**
* radix_tree_gang_lookup_slot - perform multiple slot lookup on radix tree
* @root: radix tree root
* @results: where the results of the lookup are placed
* @indices: where their indices should be placed (but usually NULL)
* @first_index: start the lookup from this key
* @max_items: place up to this many items at *results
*
* Performs an index-ascending scan of the tree for present items. Places
* their slots at *@results and returns the number of items which were
* placed at *@results.
*
* The implementation is naive.
*
* Like radix_tree_gang_lookup as far as RCU and locking goes. Slots must
* be dereferenced with radix_tree_deref_slot, and if using only RCU
* protection, radix_tree_deref_slot may fail requiring a retry.
*/
unsigned int
radix_tree_gang_lookup_slot(struct radix_tree_root *root,
void ***results, unsigned long *indices,
unsigned long first_index, unsigned int max_items)
{
unsigned long max_index;
struct radix_tree_node *node;
unsigned long cur_index = first_index;
unsigned int ret;
node = rcu_dereference_raw(root->rnode);
if (!node)
return 0;
if (!radix_tree_is_indirect_ptr(node)) {
if (first_index > 0)
return 0;
results[0] = (void **)&root->rnode;
if (indices)
indices[0] = 0;
return 1;
}
node = indirect_to_ptr(node);
max_index = radix_tree_maxindex(node->height);
ret = 0;
while (ret < max_items) {
unsigned int slots_found;
unsigned long next_index; /* Index of next search */
if (cur_index > max_index)
break;
slots_found = __lookup(node, results + ret,
indices ? indices + ret : NULL,
cur_index, max_items - ret, &next_index);
ret += slots_found;
if (next_index == 0)
break;
cur_index = next_index;
}
return ret;
}
EXPORT_SYMBOL(radix_tree_gang_lookup_slot);
/*
* FIXME: the two tag_get()s here should use find_next_bit() instead of
* open-coding the search.
*/
static unsigned int
__lookup_tag(struct radix_tree_node *slot, void ***results, unsigned long index,
unsigned int max_items, unsigned long *next_index, unsigned int tag)
{
unsigned int nr_found = 0;
unsigned int shift, height;
height = slot->height;
if (height == 0)
goto out;
shift = (height-1) * RADIX_TREE_MAP_SHIFT;
while (height > 0) {
unsigned long i = (index >> shift) & RADIX_TREE_MAP_MASK ;
for (;;) {
if (tag_get(slot, tag, i))
break;
index &= ~((1UL << shift) - 1);
index += 1UL << shift;
if (index == 0)
goto out; /* 32-bit wraparound */
i++;
if (i == RADIX_TREE_MAP_SIZE)
goto out;
}
height--;
if (height == 0) { /* Bottom level: grab some items */
unsigned long j = index & RADIX_TREE_MAP_MASK;
for ( ; j < RADIX_TREE_MAP_SIZE; j++) {
index++;
if (!tag_get(slot, tag, j))
continue;
/*
* Even though the tag was found set, we need to
* recheck that we have a non-NULL node, because
* if this lookup is lockless, it may have been
* subsequently deleted.
*
* Similar care must be taken in any place that
* lookup ->slots[x] without a lock (ie. can't
* rely on its value remaining the same).
*/
if (slot->slots[j]) {
results[nr_found++] = &(slot->slots[j]);
if (nr_found == max_items)
goto out;
}
}
}
shift -= RADIX_TREE_MAP_SHIFT;
slot = rcu_dereference_raw(slot->slots[i]);
if (slot == NULL)
break;
}
out:
*next_index = index;
return nr_found;
}
/**
* radix_tree_gang_lookup_tag - perform multiple lookup on a radix tree
* based on a tag
* @root: radix tree root
* @results: where the results of the lookup are placed
* @first_index: start the lookup from this key
* @max_items: place up to this many items at *results
* @tag: the tag index (< RADIX_TREE_MAX_TAGS)
*
* Performs an index-ascending scan of the tree for present items which
* have the tag indexed by @tag set. Places the items at *@results and
* returns the number of items which were placed at *@results.
*/
unsigned int
radix_tree_gang_lookup_tag(struct radix_tree_root *root, void **results,
unsigned long first_index, unsigned int max_items,
unsigned int tag)
{
struct radix_tree_node *node;
unsigned long max_index;
unsigned long cur_index = first_index;
unsigned int ret;
/* check the root's tag bit */
if (!root_tag_get(root, tag))
return 0;
node = rcu_dereference_raw(root->rnode);
if (!node)
return 0;
if (!radix_tree_is_indirect_ptr(node)) {
if (first_index > 0)
return 0;
results[0] = node;
return 1;
}
node = indirect_to_ptr(node);
max_index = radix_tree_maxindex(node->height);
ret = 0;
while (ret < max_items) {
unsigned int nr_found, slots_found, i;
unsigned long next_index; /* Index of next search */
if (cur_index > max_index)
break;
slots_found = __lookup_tag(node, (void ***)results + ret,
cur_index, max_items - ret, &next_index, tag);
nr_found = 0;
for (i = 0; i < slots_found; i++) {
struct radix_tree_node *slot;
slot = *(((void ***)results)[ret + i]);
if (!slot)
continue;
results[ret + nr_found] =
indirect_to_ptr(rcu_dereference_raw(slot));
nr_found++;
}
ret += nr_found;
if (next_index == 0)
break;
cur_index = next_index;
}
return ret;
}
EXPORT_SYMBOL(radix_tree_gang_lookup_tag);
/**
* radix_tree_gang_lookup_tag_slot - perform multiple slot lookup on a
* radix tree based on a tag
* @root: radix tree root
* @results: where the results of the lookup are placed
* @first_index: start the lookup from this key
* @max_items: place up to this many items at *results
* @tag: the tag index (< RADIX_TREE_MAX_TAGS)
*
* Performs an index-ascending scan of the tree for present items which
* have the tag indexed by @tag set. Places the slots at *@results and
* returns the number of slots which were placed at *@results.
*/
unsigned int
radix_tree_gang_lookup_tag_slot(struct radix_tree_root *root, void ***results,
unsigned long first_index, unsigned int max_items,
unsigned int tag)
{
struct radix_tree_node *node;
unsigned long max_index;
unsigned long cur_index = first_index;
unsigned int ret;
/* check the root's tag bit */
if (!root_tag_get(root, tag))
return 0;
node = rcu_dereference_raw(root->rnode);
if (!node)
return 0;
if (!radix_tree_is_indirect_ptr(node)) {
if (first_index > 0)
return 0;
results[0] = (void **)&root->rnode;
return 1;
}
node = indirect_to_ptr(node);
max_index = radix_tree_maxindex(node->height);
ret = 0;
while (ret < max_items) {
unsigned int slots_found;
unsigned long next_index; /* Index of next search */
if (cur_index > max_index)
break;
slots_found = __lookup_tag(node, results + ret,
cur_index, max_items - ret, &next_index, tag);
ret += slots_found;
if (next_index == 0)
break;
cur_index = next_index;
}
return ret;
}
EXPORT_SYMBOL(radix_tree_gang_lookup_tag_slot);
#if defined(CONFIG_SHMEM) && defined(CONFIG_SWAP)
#include <linux/sched.h> /* for cond_resched() */
/*
* This linear search is at present only useful to shmem_unuse_inode().
*/
static unsigned long __locate(struct radix_tree_node *slot, void *item,
unsigned long index, unsigned long *found_index)
{
unsigned int shift, height;
unsigned long i;
height = slot->height;
shift = (height-1) * RADIX_TREE_MAP_SHIFT;
for ( ; height > 1; height--) {
i = (index >> shift) & RADIX_TREE_MAP_MASK;
for (;;) {
if (slot->slots[i] != NULL)
break;
index &= ~((1UL << shift) - 1);
index += 1UL << shift;
if (index == 0)
goto out; /* 32-bit wraparound */
i++;
if (i == RADIX_TREE_MAP_SIZE)
goto out;
}
shift -= RADIX_TREE_MAP_SHIFT;
slot = rcu_dereference_raw(slot->slots[i]);
if (slot == NULL)
goto out;
}
/* Bottom level: check items */
for (i = 0; i < RADIX_TREE_MAP_SIZE; i++) {
if (slot->slots[i] == item) {
*found_index = index + i;
index = 0;
goto out;
}
}
index += RADIX_TREE_MAP_SIZE;
out:
return index;
}
/**
* radix_tree_locate_item - search through radix tree for item
* @root: radix tree root
* @item: item to be found
*
* Returns index where item was found, or -1 if not found.
* Caller must hold no lock (since this time-consuming function needs
* to be preemptible), and must check afterwards if item is still there.
*/
unsigned long radix_tree_locate_item(struct radix_tree_root *root, void *item)
{
struct radix_tree_node *node;
unsigned long max_index;
unsigned long cur_index = 0;
unsigned long found_index = -1;
do {
rcu_read_lock();
node = rcu_dereference_raw(root->rnode);
if (!radix_tree_is_indirect_ptr(node)) {
rcu_read_unlock();
if (node == item)
found_index = 0;
break;
}
node = indirect_to_ptr(node);
max_index = radix_tree_maxindex(node->height);
if (cur_index > max_index)
break;
cur_index = __locate(node, item, cur_index, &found_index);
rcu_read_unlock();
cond_resched();
} while (cur_index != 0 && cur_index <= max_index);
return found_index;
}
#else
unsigned long radix_tree_locate_item(struct radix_tree_root *root, void *item)
{
return -1;
}
#endif /* CONFIG_SHMEM && CONFIG_SWAP */
/**
* radix_tree_shrink - shrink height of a radix tree to minimal
* @root radix tree root
*/
static inline void radix_tree_shrink(struct radix_tree_root *root)
{
/* try to shrink tree height */
while (root->height > 0) {
struct radix_tree_node *to_free = root->rnode;
void *newptr;
BUG_ON(!radix_tree_is_indirect_ptr(to_free));
to_free = indirect_to_ptr(to_free);
/*
* The candidate node has more than one child, or its child
* is not at the leftmost slot, we cannot shrink.
*/
if (to_free->count != 1)
break;
if (!to_free->slots[0])
break;
/*
* We don't need rcu_assign_pointer(), since we are simply
* moving the node from one part of the tree to another: if it
* was safe to dereference the old pointer to it
* (to_free->slots[0]), it will be safe to dereference the new
* one (root->rnode) as far as dependent read barriers go.
*/
newptr = to_free->slots[0];
if (root->height > 1)
newptr = ptr_to_indirect(newptr);
root->rnode = newptr;
root->height--;
/*
* We have a dilemma here. The node's slot[0] must not be
* NULLed in case there are concurrent lookups expecting to
* find the item. However if this was a bottom-level node,
* then it may be subject to the slot pointer being visible
* to callers dereferencing it. If item corresponding to
* slot[0] is subsequently deleted, these callers would expect
* their slot to become empty sooner or later.
*
* For example, lockless pagecache will look up a slot, deref
* the page pointer, and if the page is 0 refcount it means it
* was concurrently deleted from pagecache so try the deref
* again. Fortunately there is already a requirement for logic
* to retry the entire slot lookup -- the indirect pointer
* problem (replacing direct root node with an indirect pointer
* also results in a stale slot). So tag the slot as indirect
* to force callers to retry.
*/
if (root->height == 0)
*((unsigned long *)&to_free->slots[0]) |=
RADIX_TREE_INDIRECT_PTR;
radix_tree_node_free(to_free);
}
}
/**
* radix_tree_delete - delete an item from a radix tree
* @root: radix tree root
* @index: index key
*
* Remove the item at @index from the radix tree rooted at @root.
*
* Returns the address of the deleted item, or NULL if it was not present.
*/
void *radix_tree_delete(struct radix_tree_root *root, unsigned long index)
{
/*
* The radix tree path needs to be one longer than the maximum path
* since the "list" is null terminated.
*/
struct radix_tree_path path[RADIX_TREE_MAX_PATH + 1], *pathp = path;
struct radix_tree_node *slot = NULL;
struct radix_tree_node *to_free;
unsigned int height, shift;
int tag;
int offset;
height = root->height;
if (index > radix_tree_maxindex(height))
goto out;
slot = root->rnode;
if (height == 0) {
root_tag_clear_all(root);
root->rnode = NULL;
goto out;
}
slot = indirect_to_ptr(slot);
shift = (height - 1) * RADIX_TREE_MAP_SHIFT;
pathp->node = NULL;
do {
if (slot == NULL)
goto out;
pathp++;
offset = (index >> shift) & RADIX_TREE_MAP_MASK;
pathp->offset = offset;
pathp->node = slot;
slot = slot->slots[offset];
shift -= RADIX_TREE_MAP_SHIFT;
height--;
} while (height > 0);
if (slot == NULL)
goto out;
/*
* Clear all tags associated with the just-deleted item
*/
for (tag = 0; tag < RADIX_TREE_MAX_TAGS; tag++) {
if (tag_get(pathp->node, tag, pathp->offset))
radix_tree_tag_clear(root, index, tag);
}
to_free = NULL;
/* Now free the nodes we do not need anymore */
while (pathp->node) {
pathp->node->slots[pathp->offset] = NULL;
pathp->node->count--;
/*
* Queue the node for deferred freeing after the
* last reference to it disappears (set NULL, above).
*/
if (to_free)
radix_tree_node_free(to_free);
if (pathp->node->count) {
if (pathp->node == indirect_to_ptr(root->rnode))
radix_tree_shrink(root);
goto out;
}
/* Node with zero slots in use so free it */
to_free = pathp->node;
pathp--;
}
root_tag_clear_all(root);
root->height = 0;
root->rnode = NULL;
if (to_free)
radix_tree_node_free(to_free);
out:
return slot;
}
EXPORT_SYMBOL(radix_tree_delete);
/**
* radix_tree_tagged - test whether any items in the tree are tagged
* @root: radix tree root
* @tag: tag to test
*/
int radix_tree_tagged(struct radix_tree_root *root, unsigned int tag)
{
return root_tag_get(root, tag);
}
EXPORT_SYMBOL(radix_tree_tagged);
static void
radix_tree_node_ctor(void *node)
{
memset(node, 0, sizeof(struct radix_tree_node));
}
static __init unsigned long __maxindex(unsigned int height)
{
unsigned int width = height * RADIX_TREE_MAP_SHIFT;
int shift = RADIX_TREE_INDEX_BITS - width;
if (shift < 0)
return ~0UL;
if (shift >= BITS_PER_LONG)
return 0UL;
return ~0UL >> shift;
}
static __init void radix_tree_init_maxindex(void)
{
unsigned int i;
for (i = 0; i < ARRAY_SIZE(height_to_maxindex); i++)
height_to_maxindex[i] = __maxindex(i);
}
static int radix_tree_callback(struct notifier_block *nfb,
unsigned long action,
void *hcpu)
{
int cpu = (long)hcpu;
struct radix_tree_preload *rtp;
/* Free per-cpu pool of perloaded nodes */
if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
rtp = &per_cpu(radix_tree_preloads, cpu);
while (rtp->nr) {
kmem_cache_free(radix_tree_node_cachep,
rtp->nodes[rtp->nr-1]);
rtp->nodes[rtp->nr-1] = NULL;
rtp->nr--;
}
}
return NOTIFY_OK;
}
void __init radix_tree_init(void)
{
radix_tree_node_cachep = kmem_cache_create("radix_tree_node",
sizeof(struct radix_tree_node), 0,
SLAB_PANIC | SLAB_RECLAIM_ACCOUNT,
radix_tree_node_ctor);
radix_tree_init_maxindex();
hotcpu_notifier(radix_tree_callback, 0);
}
| gpl-2.0 |
Tommy-Geenexus/android_kernel_sony_msm8994_suzuran_6.0.x | drivers/mtd/mtdchar.c | 1158 | 27395 | /*
* Copyright © 1999-2010 David Woodhouse <dwmw2@infradead.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <linux/device.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/mutex.h>
#include <linux/backing-dev.h>
#include <linux/compat.h>
#include <linux/mount.h>
#include <linux/blkpg.h>
#include <linux/magic.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/map.h>
#include <linux/mtd/partitions.h>
#include <asm/uaccess.h>
#include "mtdcore.h"
static DEFINE_MUTEX(mtd_mutex);
/*
* Data structure to hold the pointer to the mtd device as well
* as mode information of various use cases.
*/
struct mtd_file_info {
struct mtd_info *mtd;
struct inode *ino;
enum mtd_file_modes mode;
};
static loff_t mtdchar_lseek(struct file *file, loff_t offset, int orig)
{
struct mtd_file_info *mfi = file->private_data;
struct mtd_info *mtd = mfi->mtd;
switch (orig) {
case SEEK_SET:
break;
case SEEK_CUR:
offset += file->f_pos;
break;
case SEEK_END:
offset += mtd->size;
break;
default:
return -EINVAL;
}
if (offset >= 0 && offset <= mtd->size)
return file->f_pos = offset;
return -EINVAL;
}
static int count;
static struct vfsmount *mnt;
static struct file_system_type mtd_inodefs_type;
static int mtdchar_open(struct inode *inode, struct file *file)
{
int minor = iminor(inode);
int devnum = minor >> 1;
int ret = 0;
struct mtd_info *mtd;
struct mtd_file_info *mfi;
struct inode *mtd_ino;
pr_debug("MTD_open\n");
/* You can't open the RO devices RW */
if ((file->f_mode & FMODE_WRITE) && (minor & 1))
return -EACCES;
ret = simple_pin_fs(&mtd_inodefs_type, &mnt, &count);
if (ret)
return ret;
mutex_lock(&mtd_mutex);
mtd = get_mtd_device(NULL, devnum);
if (IS_ERR(mtd)) {
ret = PTR_ERR(mtd);
goto out;
}
if (mtd->type == MTD_ABSENT) {
ret = -ENODEV;
goto out1;
}
mtd_ino = iget_locked(mnt->mnt_sb, devnum);
if (!mtd_ino) {
ret = -ENOMEM;
goto out1;
}
if (mtd_ino->i_state & I_NEW) {
mtd_ino->i_private = mtd;
mtd_ino->i_mode = S_IFCHR;
mtd_ino->i_data.backing_dev_info = mtd->backing_dev_info;
unlock_new_inode(mtd_ino);
}
file->f_mapping = mtd_ino->i_mapping;
/* You can't open it RW if it's not a writeable device */
if ((file->f_mode & FMODE_WRITE) && !(mtd->flags & MTD_WRITEABLE)) {
ret = -EACCES;
goto out2;
}
mfi = kzalloc(sizeof(*mfi), GFP_KERNEL);
if (!mfi) {
ret = -ENOMEM;
goto out2;
}
mfi->ino = mtd_ino;
mfi->mtd = mtd;
file->private_data = mfi;
mutex_unlock(&mtd_mutex);
return 0;
out2:
iput(mtd_ino);
out1:
put_mtd_device(mtd);
out:
mutex_unlock(&mtd_mutex);
simple_release_fs(&mnt, &count);
return ret;
} /* mtdchar_open */
/*====================================================================*/
static int mtdchar_close(struct inode *inode, struct file *file)
{
struct mtd_file_info *mfi = file->private_data;
struct mtd_info *mtd = mfi->mtd;
pr_debug("MTD_close\n");
/* Only sync if opened RW */
if ((file->f_mode & FMODE_WRITE))
mtd_sync(mtd);
iput(mfi->ino);
put_mtd_device(mtd);
file->private_data = NULL;
kfree(mfi);
simple_release_fs(&mnt, &count);
return 0;
} /* mtdchar_close */
/* Back in June 2001, dwmw2 wrote:
*
* FIXME: This _really_ needs to die. In 2.5, we should lock the
* userspace buffer down and use it directly with readv/writev.
*
* The implementation below, using mtd_kmalloc_up_to, mitigates
* allocation failures when the system is under low-memory situations
* or if memory is highly fragmented at the cost of reducing the
* performance of the requested transfer due to a smaller buffer size.
*
* A more complex but more memory-efficient implementation based on
* get_user_pages and iovecs to cover extents of those pages is a
* longer-term goal, as intimated by dwmw2 above. However, for the
* write case, this requires yet more complex head and tail transfer
* handling when those head and tail offsets and sizes are such that
* alignment requirements are not met in the NAND subdriver.
*/
static ssize_t mtdchar_read(struct file *file, char __user *buf, size_t count,
loff_t *ppos)
{
struct mtd_file_info *mfi = file->private_data;
struct mtd_info *mtd = mfi->mtd;
size_t retlen;
size_t total_retlen=0;
int ret=0;
int len;
size_t size = count;
char *kbuf;
pr_debug("MTD_read\n");
if (*ppos + count > mtd->size)
count = mtd->size - *ppos;
if (!count)
return 0;
kbuf = mtd_kmalloc_up_to(mtd, &size);
if (!kbuf)
return -ENOMEM;
while (count) {
len = min_t(size_t, count, size);
switch (mfi->mode) {
case MTD_FILE_MODE_OTP_FACTORY:
ret = mtd_read_fact_prot_reg(mtd, *ppos, len,
&retlen, kbuf);
break;
case MTD_FILE_MODE_OTP_USER:
ret = mtd_read_user_prot_reg(mtd, *ppos, len,
&retlen, kbuf);
break;
case MTD_FILE_MODE_RAW:
{
struct mtd_oob_ops ops;
ops.mode = MTD_OPS_RAW;
ops.datbuf = kbuf;
ops.oobbuf = NULL;
ops.len = len;
ret = mtd_read_oob(mtd, *ppos, &ops);
retlen = ops.retlen;
break;
}
default:
ret = mtd_read(mtd, *ppos, len, &retlen, kbuf);
}
/* Nand returns -EBADMSG on ECC errors, but it returns
* the data. For our userspace tools it is important
* to dump areas with ECC errors!
* For kernel internal usage it also might return -EUCLEAN
* to signal the caller that a bitflip has occurred and has
* been corrected by the ECC algorithm.
* Userspace software which accesses NAND this way
* must be aware of the fact that it deals with NAND
*/
if (!ret || mtd_is_bitflip_or_eccerr(ret)) {
*ppos += retlen;
if (copy_to_user(buf, kbuf, retlen)) {
kfree(kbuf);
return -EFAULT;
}
else
total_retlen += retlen;
count -= retlen;
buf += retlen;
if (retlen == 0)
count = 0;
}
else {
kfree(kbuf);
return ret;
}
}
kfree(kbuf);
return total_retlen;
} /* mtdchar_read */
static ssize_t mtdchar_write(struct file *file, const char __user *buf, size_t count,
loff_t *ppos)
{
struct mtd_file_info *mfi = file->private_data;
struct mtd_info *mtd = mfi->mtd;
size_t size = count;
char *kbuf;
size_t retlen;
size_t total_retlen=0;
int ret=0;
int len;
pr_debug("MTD_write\n");
if (*ppos == mtd->size)
return -ENOSPC;
if (*ppos + count > mtd->size)
count = mtd->size - *ppos;
if (!count)
return 0;
kbuf = mtd_kmalloc_up_to(mtd, &size);
if (!kbuf)
return -ENOMEM;
while (count) {
len = min_t(size_t, count, size);
if (copy_from_user(kbuf, buf, len)) {
kfree(kbuf);
return -EFAULT;
}
switch (mfi->mode) {
case MTD_FILE_MODE_OTP_FACTORY:
ret = -EROFS;
break;
case MTD_FILE_MODE_OTP_USER:
ret = mtd_write_user_prot_reg(mtd, *ppos, len,
&retlen, kbuf);
break;
case MTD_FILE_MODE_RAW:
{
struct mtd_oob_ops ops;
ops.mode = MTD_OPS_RAW;
ops.datbuf = kbuf;
ops.oobbuf = NULL;
ops.ooboffs = 0;
ops.len = len;
ret = mtd_write_oob(mtd, *ppos, &ops);
retlen = ops.retlen;
break;
}
default:
ret = mtd_write(mtd, *ppos, len, &retlen, kbuf);
}
if (!ret) {
*ppos += retlen;
total_retlen += retlen;
count -= retlen;
buf += retlen;
}
else {
kfree(kbuf);
return ret;
}
}
kfree(kbuf);
return total_retlen;
} /* mtdchar_write */
/*======================================================================
IOCTL calls for getting device parameters.
======================================================================*/
static void mtdchar_erase_callback (struct erase_info *instr)
{
wake_up((wait_queue_head_t *)instr->priv);
}
static int otp_select_filemode(struct mtd_file_info *mfi, int mode)
{
struct mtd_info *mtd = mfi->mtd;
size_t retlen;
switch (mode) {
case MTD_OTP_FACTORY:
if (mtd_read_fact_prot_reg(mtd, -1, 0, &retlen, NULL) ==
-EOPNOTSUPP)
return -EOPNOTSUPP;
mfi->mode = MTD_FILE_MODE_OTP_FACTORY;
break;
case MTD_OTP_USER:
if (mtd_read_user_prot_reg(mtd, -1, 0, &retlen, NULL) ==
-EOPNOTSUPP)
return -EOPNOTSUPP;
mfi->mode = MTD_FILE_MODE_OTP_USER;
break;
case MTD_OTP_OFF:
mfi->mode = MTD_FILE_MODE_NORMAL;
break;
default:
return -EINVAL;
}
return 0;
}
static int mtdchar_writeoob(struct file *file, struct mtd_info *mtd,
uint64_t start, uint32_t length, void __user *ptr,
uint32_t __user *retp)
{
struct mtd_file_info *mfi = file->private_data;
struct mtd_oob_ops ops;
uint32_t retlen;
int ret = 0;
if (!(file->f_mode & FMODE_WRITE))
return -EPERM;
if (length > 4096)
return -EINVAL;
if (!mtd->_write_oob)
ret = -EOPNOTSUPP;
else
ret = access_ok(VERIFY_READ, ptr, length) ? 0 : -EFAULT;
if (ret)
return ret;
ops.ooblen = length;
ops.ooboffs = start & (mtd->writesize - 1);
ops.datbuf = NULL;
ops.mode = (mfi->mode == MTD_FILE_MODE_RAW) ? MTD_OPS_RAW :
MTD_OPS_PLACE_OOB;
if (ops.ooboffs && ops.ooblen > (mtd->oobsize - ops.ooboffs))
return -EINVAL;
ops.oobbuf = memdup_user(ptr, length);
if (IS_ERR(ops.oobbuf))
return PTR_ERR(ops.oobbuf);
start &= ~((uint64_t)mtd->writesize - 1);
ret = mtd_write_oob(mtd, start, &ops);
if (ops.oobretlen > 0xFFFFFFFFU)
ret = -EOVERFLOW;
retlen = ops.oobretlen;
if (copy_to_user(retp, &retlen, sizeof(length)))
ret = -EFAULT;
kfree(ops.oobbuf);
return ret;
}
static int mtdchar_readoob(struct file *file, struct mtd_info *mtd,
uint64_t start, uint32_t length, void __user *ptr,
uint32_t __user *retp)
{
struct mtd_file_info *mfi = file->private_data;
struct mtd_oob_ops ops;
int ret = 0;
if (length > 4096)
return -EINVAL;
if (!access_ok(VERIFY_WRITE, ptr, length))
return -EFAULT;
ops.ooblen = length;
ops.ooboffs = start & (mtd->writesize - 1);
ops.datbuf = NULL;
ops.mode = (mfi->mode == MTD_FILE_MODE_RAW) ? MTD_OPS_RAW :
MTD_OPS_PLACE_OOB;
if (ops.ooboffs && ops.ooblen > (mtd->oobsize - ops.ooboffs))
return -EINVAL;
ops.oobbuf = kmalloc(length, GFP_KERNEL);
if (!ops.oobbuf)
return -ENOMEM;
start &= ~((uint64_t)mtd->writesize - 1);
ret = mtd_read_oob(mtd, start, &ops);
if (put_user(ops.oobretlen, retp))
ret = -EFAULT;
else if (ops.oobretlen && copy_to_user(ptr, ops.oobbuf,
ops.oobretlen))
ret = -EFAULT;
kfree(ops.oobbuf);
/*
* NAND returns -EBADMSG on ECC errors, but it returns the OOB
* data. For our userspace tools it is important to dump areas
* with ECC errors!
* For kernel internal usage it also might return -EUCLEAN
* to signal the caller that a bitflip has occured and has
* been corrected by the ECC algorithm.
*
* Note: currently the standard NAND function, nand_read_oob_std,
* does not calculate ECC for the OOB area, so do not rely on
* this behavior unless you have replaced it with your own.
*/
if (mtd_is_bitflip_or_eccerr(ret))
return 0;
return ret;
}
/*
* Copies (and truncates, if necessary) data from the larger struct,
* nand_ecclayout, to the smaller, deprecated layout struct,
* nand_ecclayout_user. This is necessary only to support the deprecated
* API ioctl ECCGETLAYOUT while allowing all new functionality to use
* nand_ecclayout flexibly (i.e. the struct may change size in new
* releases without requiring major rewrites).
*/
static int shrink_ecclayout(const struct nand_ecclayout *from,
struct nand_ecclayout_user *to)
{
int i;
if (!from || !to)
return -EINVAL;
memset(to, 0, sizeof(*to));
to->eccbytes = min((int)from->eccbytes, MTD_MAX_ECCPOS_ENTRIES);
for (i = 0; i < to->eccbytes; i++)
to->eccpos[i] = from->eccpos[i];
for (i = 0; i < MTD_MAX_OOBFREE_ENTRIES; i++) {
if (from->oobfree[i].length == 0 &&
from->oobfree[i].offset == 0)
break;
to->oobavail += from->oobfree[i].length;
to->oobfree[i] = from->oobfree[i];
}
return 0;
}
static int mtdchar_blkpg_ioctl(struct mtd_info *mtd,
struct blkpg_ioctl_arg __user *arg)
{
struct blkpg_ioctl_arg a;
struct blkpg_partition p;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (copy_from_user(&a, arg, sizeof(struct blkpg_ioctl_arg)))
return -EFAULT;
if (copy_from_user(&p, a.data, sizeof(struct blkpg_partition)))
return -EFAULT;
switch (a.op) {
case BLKPG_ADD_PARTITION:
/* Only master mtd device must be used to add partitions */
if (mtd_is_partition(mtd))
return -EINVAL;
return mtd_add_partition(mtd, p.devname, p.start, p.length);
case BLKPG_DEL_PARTITION:
if (p.pno < 0)
return -EINVAL;
return mtd_del_partition(mtd, p.pno);
default:
return -EINVAL;
}
}
static int mtdchar_write_ioctl(struct mtd_info *mtd,
struct mtd_write_req __user *argp)
{
struct mtd_write_req req;
struct mtd_oob_ops ops;
void __user *usr_data, *usr_oob;
int ret;
if (copy_from_user(&req, argp, sizeof(req)) ||
!access_ok(VERIFY_READ, req.usr_data, req.len) ||
!access_ok(VERIFY_READ, req.usr_oob, req.ooblen))
return -EFAULT;
if (!mtd->_write_oob)
return -EOPNOTSUPP;
ops.mode = req.mode;
ops.len = (size_t)req.len;
ops.ooblen = (size_t)req.ooblen;
ops.ooboffs = 0;
usr_data = (void __user *)(uintptr_t)req.usr_data;
usr_oob = (void __user *)(uintptr_t)req.usr_oob;
if (req.usr_data) {
ops.datbuf = memdup_user(usr_data, ops.len);
if (IS_ERR(ops.datbuf))
return PTR_ERR(ops.datbuf);
} else {
ops.datbuf = NULL;
}
if (req.usr_oob) {
ops.oobbuf = memdup_user(usr_oob, ops.ooblen);
if (IS_ERR(ops.oobbuf)) {
kfree(ops.datbuf);
return PTR_ERR(ops.oobbuf);
}
} else {
ops.oobbuf = NULL;
}
ret = mtd_write_oob(mtd, (loff_t)req.start, &ops);
kfree(ops.datbuf);
kfree(ops.oobbuf);
return ret;
}
static int mtdchar_ioctl(struct file *file, u_int cmd, u_long arg)
{
struct mtd_file_info *mfi = file->private_data;
struct mtd_info *mtd = mfi->mtd;
void __user *argp = (void __user *)arg;
int ret = 0;
u_long size;
struct mtd_info_user info;
pr_debug("MTD_ioctl\n");
size = (cmd & IOCSIZE_MASK) >> IOCSIZE_SHIFT;
if (cmd & IOC_IN) {
if (!access_ok(VERIFY_READ, argp, size))
return -EFAULT;
}
if (cmd & IOC_OUT) {
if (!access_ok(VERIFY_WRITE, argp, size))
return -EFAULT;
}
switch (cmd) {
case MEMGETREGIONCOUNT:
if (copy_to_user(argp, &(mtd->numeraseregions), sizeof(int)))
return -EFAULT;
break;
case MEMGETREGIONINFO:
{
uint32_t ur_idx;
struct mtd_erase_region_info *kr;
struct region_info_user __user *ur = argp;
if (get_user(ur_idx, &(ur->regionindex)))
return -EFAULT;
if (ur_idx >= mtd->numeraseregions)
return -EINVAL;
kr = &(mtd->eraseregions[ur_idx]);
if (put_user(kr->offset, &(ur->offset))
|| put_user(kr->erasesize, &(ur->erasesize))
|| put_user(kr->numblocks, &(ur->numblocks)))
return -EFAULT;
break;
}
case MEMGETINFO:
memset(&info, 0, sizeof(info));
info.type = mtd->type;
info.flags = mtd->flags;
info.size = mtd->size;
info.erasesize = mtd->erasesize;
info.writesize = mtd->writesize;
info.oobsize = mtd->oobsize;
/* The below field is obsolete */
info.padding = 0;
if (copy_to_user(argp, &info, sizeof(struct mtd_info_user)))
return -EFAULT;
break;
case MEMERASE:
case MEMERASE64:
{
struct erase_info *erase;
if(!(file->f_mode & FMODE_WRITE))
return -EPERM;
erase=kzalloc(sizeof(struct erase_info),GFP_KERNEL);
if (!erase)
ret = -ENOMEM;
else {
wait_queue_head_t waitq;
DECLARE_WAITQUEUE(wait, current);
init_waitqueue_head(&waitq);
if (cmd == MEMERASE64) {
struct erase_info_user64 einfo64;
if (copy_from_user(&einfo64, argp,
sizeof(struct erase_info_user64))) {
kfree(erase);
return -EFAULT;
}
erase->addr = einfo64.start;
erase->len = einfo64.length;
} else {
struct erase_info_user einfo32;
if (copy_from_user(&einfo32, argp,
sizeof(struct erase_info_user))) {
kfree(erase);
return -EFAULT;
}
erase->addr = einfo32.start;
erase->len = einfo32.length;
}
erase->mtd = mtd;
erase->callback = mtdchar_erase_callback;
erase->priv = (unsigned long)&waitq;
/*
FIXME: Allow INTERRUPTIBLE. Which means
not having the wait_queue head on the stack.
If the wq_head is on the stack, and we
leave because we got interrupted, then the
wq_head is no longer there when the
callback routine tries to wake us up.
*/
ret = mtd_erase(mtd, erase);
if (!ret) {
set_current_state(TASK_UNINTERRUPTIBLE);
add_wait_queue(&waitq, &wait);
if (erase->state != MTD_ERASE_DONE &&
erase->state != MTD_ERASE_FAILED)
schedule();
remove_wait_queue(&waitq, &wait);
set_current_state(TASK_RUNNING);
ret = (erase->state == MTD_ERASE_FAILED)?-EIO:0;
}
kfree(erase);
}
break;
}
case MEMWRITEOOB:
{
struct mtd_oob_buf buf;
struct mtd_oob_buf __user *buf_user = argp;
/* NOTE: writes return length to buf_user->length */
if (copy_from_user(&buf, argp, sizeof(buf)))
ret = -EFAULT;
else
ret = mtdchar_writeoob(file, mtd, buf.start, buf.length,
buf.ptr, &buf_user->length);
break;
}
case MEMREADOOB:
{
struct mtd_oob_buf buf;
struct mtd_oob_buf __user *buf_user = argp;
/* NOTE: writes return length to buf_user->start */
if (copy_from_user(&buf, argp, sizeof(buf)))
ret = -EFAULT;
else
ret = mtdchar_readoob(file, mtd, buf.start, buf.length,
buf.ptr, &buf_user->start);
break;
}
case MEMWRITEOOB64:
{
struct mtd_oob_buf64 buf;
struct mtd_oob_buf64 __user *buf_user = argp;
if (copy_from_user(&buf, argp, sizeof(buf)))
ret = -EFAULT;
else
ret = mtdchar_writeoob(file, mtd, buf.start, buf.length,
(void __user *)(uintptr_t)buf.usr_ptr,
&buf_user->length);
break;
}
case MEMREADOOB64:
{
struct mtd_oob_buf64 buf;
struct mtd_oob_buf64 __user *buf_user = argp;
if (copy_from_user(&buf, argp, sizeof(buf)))
ret = -EFAULT;
else
ret = mtdchar_readoob(file, mtd, buf.start, buf.length,
(void __user *)(uintptr_t)buf.usr_ptr,
&buf_user->length);
break;
}
case MEMWRITE:
{
ret = mtdchar_write_ioctl(mtd,
(struct mtd_write_req __user *)arg);
break;
}
case MEMLOCK:
{
struct erase_info_user einfo;
if (copy_from_user(&einfo, argp, sizeof(einfo)))
return -EFAULT;
ret = mtd_lock(mtd, einfo.start, einfo.length);
break;
}
case MEMUNLOCK:
{
struct erase_info_user einfo;
if (copy_from_user(&einfo, argp, sizeof(einfo)))
return -EFAULT;
ret = mtd_unlock(mtd, einfo.start, einfo.length);
break;
}
case MEMISLOCKED:
{
struct erase_info_user einfo;
if (copy_from_user(&einfo, argp, sizeof(einfo)))
return -EFAULT;
ret = mtd_is_locked(mtd, einfo.start, einfo.length);
break;
}
/* Legacy interface */
case MEMGETOOBSEL:
{
struct nand_oobinfo oi;
if (!mtd->ecclayout)
return -EOPNOTSUPP;
if (mtd->ecclayout->eccbytes > ARRAY_SIZE(oi.eccpos))
return -EINVAL;
oi.useecc = MTD_NANDECC_AUTOPLACE;
memcpy(&oi.eccpos, mtd->ecclayout->eccpos, sizeof(oi.eccpos));
memcpy(&oi.oobfree, mtd->ecclayout->oobfree,
sizeof(oi.oobfree));
oi.eccbytes = mtd->ecclayout->eccbytes;
if (copy_to_user(argp, &oi, sizeof(struct nand_oobinfo)))
return -EFAULT;
break;
}
case MEMGETBADBLOCK:
{
loff_t offs;
if (copy_from_user(&offs, argp, sizeof(loff_t)))
return -EFAULT;
return mtd_block_isbad(mtd, offs);
break;
}
case MEMSETBADBLOCK:
{
loff_t offs;
if (copy_from_user(&offs, argp, sizeof(loff_t)))
return -EFAULT;
return mtd_block_markbad(mtd, offs);
break;
}
case OTPSELECT:
{
int mode;
if (copy_from_user(&mode, argp, sizeof(int)))
return -EFAULT;
mfi->mode = MTD_FILE_MODE_NORMAL;
ret = otp_select_filemode(mfi, mode);
file->f_pos = 0;
break;
}
case OTPGETREGIONCOUNT:
case OTPGETREGIONINFO:
{
struct otp_info *buf = kmalloc(4096, GFP_KERNEL);
if (!buf)
return -ENOMEM;
switch (mfi->mode) {
case MTD_FILE_MODE_OTP_FACTORY:
ret = mtd_get_fact_prot_info(mtd, buf, 4096);
break;
case MTD_FILE_MODE_OTP_USER:
ret = mtd_get_user_prot_info(mtd, buf, 4096);
break;
default:
ret = -EINVAL;
break;
}
if (ret >= 0) {
if (cmd == OTPGETREGIONCOUNT) {
int nbr = ret / sizeof(struct otp_info);
ret = copy_to_user(argp, &nbr, sizeof(int));
} else
ret = copy_to_user(argp, buf, ret);
if (ret)
ret = -EFAULT;
}
kfree(buf);
break;
}
case OTPLOCK:
{
struct otp_info oinfo;
if (mfi->mode != MTD_FILE_MODE_OTP_USER)
return -EINVAL;
if (copy_from_user(&oinfo, argp, sizeof(oinfo)))
return -EFAULT;
ret = mtd_lock_user_prot_reg(mtd, oinfo.start, oinfo.length);
break;
}
/* This ioctl is being deprecated - it truncates the ECC layout */
case ECCGETLAYOUT:
{
struct nand_ecclayout_user *usrlay;
if (!mtd->ecclayout)
return -EOPNOTSUPP;
usrlay = kmalloc(sizeof(*usrlay), GFP_KERNEL);
if (!usrlay)
return -ENOMEM;
shrink_ecclayout(mtd->ecclayout, usrlay);
if (copy_to_user(argp, usrlay, sizeof(*usrlay)))
ret = -EFAULT;
kfree(usrlay);
break;
}
case ECCGETSTATS:
{
#ifdef CONFIG_MTD_LAZYECCSTATS
part_fill_badblockstats(mtd);
#endif
if (copy_to_user(argp, &mtd->ecc_stats,
sizeof(struct mtd_ecc_stats)))
return -EFAULT;
break;
}
case MTDFILEMODE:
{
mfi->mode = 0;
switch(arg) {
case MTD_FILE_MODE_OTP_FACTORY:
case MTD_FILE_MODE_OTP_USER:
ret = otp_select_filemode(mfi, arg);
break;
case MTD_FILE_MODE_RAW:
if (!mtd_has_oob(mtd))
return -EOPNOTSUPP;
mfi->mode = arg;
case MTD_FILE_MODE_NORMAL:
break;
default:
ret = -EINVAL;
}
file->f_pos = 0;
break;
}
case BLKPG:
{
ret = mtdchar_blkpg_ioctl(mtd,
(struct blkpg_ioctl_arg __user *)arg);
break;
}
case BLKRRPART:
{
/* No reread partition feature. Just return ok */
ret = 0;
break;
}
default:
ret = -ENOTTY;
}
return ret;
} /* memory_ioctl */
static long mtdchar_unlocked_ioctl(struct file *file, u_int cmd, u_long arg)
{
int ret;
mutex_lock(&mtd_mutex);
ret = mtdchar_ioctl(file, cmd, arg);
mutex_unlock(&mtd_mutex);
return ret;
}
#ifdef CONFIG_COMPAT
struct mtd_oob_buf32 {
u_int32_t start;
u_int32_t length;
compat_caddr_t ptr; /* unsigned char* */
};
#define MEMWRITEOOB32 _IOWR('M', 3, struct mtd_oob_buf32)
#define MEMREADOOB32 _IOWR('M', 4, struct mtd_oob_buf32)
static long mtdchar_compat_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
struct mtd_file_info *mfi = file->private_data;
struct mtd_info *mtd = mfi->mtd;
void __user *argp = compat_ptr(arg);
int ret = 0;
mutex_lock(&mtd_mutex);
switch (cmd) {
case MEMWRITEOOB32:
{
struct mtd_oob_buf32 buf;
struct mtd_oob_buf32 __user *buf_user = argp;
if (copy_from_user(&buf, argp, sizeof(buf)))
ret = -EFAULT;
else
ret = mtdchar_writeoob(file, mtd, buf.start,
buf.length, compat_ptr(buf.ptr),
&buf_user->length);
break;
}
case MEMREADOOB32:
{
struct mtd_oob_buf32 buf;
struct mtd_oob_buf32 __user *buf_user = argp;
/* NOTE: writes return length to buf->start */
if (copy_from_user(&buf, argp, sizeof(buf)))
ret = -EFAULT;
else
ret = mtdchar_readoob(file, mtd, buf.start,
buf.length, compat_ptr(buf.ptr),
&buf_user->start);
break;
}
default:
ret = mtdchar_ioctl(file, cmd, (unsigned long)argp);
}
mutex_unlock(&mtd_mutex);
return ret;
}
#endif /* CONFIG_COMPAT */
/*
* try to determine where a shared mapping can be made
* - only supported for NOMMU at the moment (MMU can't doesn't copy private
* mappings)
*/
#ifndef CONFIG_MMU
static unsigned long mtdchar_get_unmapped_area(struct file *file,
unsigned long addr,
unsigned long len,
unsigned long pgoff,
unsigned long flags)
{
struct mtd_file_info *mfi = file->private_data;
struct mtd_info *mtd = mfi->mtd;
unsigned long offset;
int ret;
if (addr != 0)
return (unsigned long) -EINVAL;
if (len > mtd->size || pgoff >= (mtd->size >> PAGE_SHIFT))
return (unsigned long) -EINVAL;
offset = pgoff << PAGE_SHIFT;
if (offset > mtd->size - len)
return (unsigned long) -EINVAL;
ret = mtd_get_unmapped_area(mtd, len, offset, flags);
return ret == -EOPNOTSUPP ? -ENOSYS : ret;
}
#endif
/*
* set up a mapping for shared memory segments
*/
static int mtdchar_mmap(struct file *file, struct vm_area_struct *vma)
{
#ifdef CONFIG_MMU
struct mtd_file_info *mfi = file->private_data;
struct mtd_info *mtd = mfi->mtd;
struct map_info *map = mtd->priv;
/* This is broken because it assumes the MTD device is map-based
and that mtd->priv is a valid struct map_info. It should be
replaced with something that uses the mtd_get_unmapped_area()
operation properly. */
if (0 /*mtd->type == MTD_RAM || mtd->type == MTD_ROM*/) {
#ifdef pgprot_noncached
if (file->f_flags & O_DSYNC || map->phys >= __pa(high_memory))
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
#endif
return vm_iomap_memory(vma, map->phys, map->size);
}
return -ENOSYS;
#else
return vma->vm_flags & VM_SHARED ? 0 : -ENOSYS;
#endif
}
static const struct file_operations mtd_fops = {
.owner = THIS_MODULE,
.llseek = mtdchar_lseek,
.read = mtdchar_read,
.write = mtdchar_write,
.unlocked_ioctl = mtdchar_unlocked_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = mtdchar_compat_ioctl,
#endif
.open = mtdchar_open,
.release = mtdchar_close,
.mmap = mtdchar_mmap,
#ifndef CONFIG_MMU
.get_unmapped_area = mtdchar_get_unmapped_area,
#endif
};
static const struct super_operations mtd_ops = {
.drop_inode = generic_delete_inode,
.statfs = simple_statfs,
};
static struct dentry *mtd_inodefs_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
return mount_pseudo(fs_type, "mtd_inode:", &mtd_ops, NULL, MTD_INODE_FS_MAGIC);
}
static struct file_system_type mtd_inodefs_type = {
.name = "mtd_inodefs",
.mount = mtd_inodefs_mount,
.kill_sb = kill_anon_super,
};
MODULE_ALIAS_FS("mtd_inodefs");
int __init init_mtdchar(void)
{
int ret;
ret = __register_chrdev(MTD_CHAR_MAJOR, 0, 1 << MINORBITS,
"mtd", &mtd_fops);
if (ret < 0) {
pr_err("Can't allocate major number %d for MTD\n",
MTD_CHAR_MAJOR);
return ret;
}
ret = register_filesystem(&mtd_inodefs_type);
if (ret) {
pr_err("Can't register mtd_inodefs filesystem, error %d\n",
ret);
goto err_unregister_chdev;
}
return ret;
err_unregister_chdev:
__unregister_chrdev(MTD_CHAR_MAJOR, 0, 1 << MINORBITS, "mtd");
return ret;
}
void __exit cleanup_mtdchar(void)
{
unregister_filesystem(&mtd_inodefs_type);
__unregister_chrdev(MTD_CHAR_MAJOR, 0, 1 << MINORBITS, "mtd");
}
MODULE_ALIAS_CHARDEV_MAJOR(MTD_CHAR_MAJOR);
| gpl-2.0 |
necsst-nms/PMAL_NOTRACE | drivers/hwmon/da9055-hwmon.c | 1414 | 8631 | /*
* HWMON Driver for Dialog DA9055
*
* Copyright(c) 2012 Dialog Semiconductor Ltd.
*
* Author: David Dajun Chen <dchen@diasemi.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/completion.h>
#include <linux/mfd/da9055/core.h>
#include <linux/mfd/da9055/reg.h>
#define DA9055_ADCIN_DIV 102
#define DA9055_VSYS_DIV 85
#define DA9055_ADC_VSYS 0
#define DA9055_ADC_ADCIN1 1
#define DA9055_ADC_ADCIN2 2
#define DA9055_ADC_ADCIN3 3
#define DA9055_ADC_TJUNC 4
struct da9055_hwmon {
struct da9055 *da9055;
struct device *class_device;
struct mutex hwmon_lock;
struct mutex irq_lock;
struct completion done;
};
static const char * const input_names[] = {
[DA9055_ADC_VSYS] = "VSYS",
[DA9055_ADC_ADCIN1] = "ADC IN1",
[DA9055_ADC_ADCIN2] = "ADC IN2",
[DA9055_ADC_ADCIN3] = "ADC IN3",
[DA9055_ADC_TJUNC] = "CHIP TEMP",
};
static const u8 chan_mux[DA9055_ADC_TJUNC + 1] = {
[DA9055_ADC_VSYS] = DA9055_ADC_MUX_VSYS,
[DA9055_ADC_ADCIN1] = DA9055_ADC_MUX_ADCIN1,
[DA9055_ADC_ADCIN2] = DA9055_ADC_MUX_ADCIN2,
[DA9055_ADC_ADCIN3] = DA9055_ADC_MUX_ADCIN3,
[DA9055_ADC_TJUNC] = DA9055_ADC_MUX_T_SENSE,
};
static int da9055_adc_manual_read(struct da9055_hwmon *hwmon,
unsigned char channel)
{
int ret;
unsigned short calc_data;
unsigned short data;
unsigned char mux_sel;
struct da9055 *da9055 = hwmon->da9055;
if (channel > DA9055_ADC_TJUNC)
return -EINVAL;
mutex_lock(&hwmon->irq_lock);
/* Selects desired MUX for manual conversion */
mux_sel = chan_mux[channel] | DA9055_ADC_MAN_CONV;
ret = da9055_reg_write(da9055, DA9055_REG_ADC_MAN, mux_sel);
if (ret < 0)
goto err;
/* Wait for an interrupt */
if (!wait_for_completion_timeout(&hwmon->done,
msecs_to_jiffies(500))) {
dev_err(da9055->dev,
"timeout waiting for ADC conversion interrupt\n");
ret = -ETIMEDOUT;
goto err;
}
ret = da9055_reg_read(da9055, DA9055_REG_ADC_RES_H);
if (ret < 0)
goto err;
calc_data = (unsigned short)ret;
data = calc_data << 2;
ret = da9055_reg_read(da9055, DA9055_REG_ADC_RES_L);
if (ret < 0)
goto err;
calc_data = (unsigned short)(ret & DA9055_ADC_LSB_MASK);
data |= calc_data;
ret = data;
err:
mutex_unlock(&hwmon->irq_lock);
return ret;
}
static irqreturn_t da9055_auxadc_irq(int irq, void *irq_data)
{
struct da9055_hwmon *hwmon = irq_data;
complete(&hwmon->done);
return IRQ_HANDLED;
}
/* Conversion function for VSYS and ADCINx */
static inline int volt_reg_to_mv(int value, int channel)
{
if (channel == DA9055_ADC_VSYS)
return DIV_ROUND_CLOSEST(value * 1000, DA9055_VSYS_DIV) + 2500;
else
return DIV_ROUND_CLOSEST(value * 1000, DA9055_ADCIN_DIV);
}
static int da9055_enable_auto_mode(struct da9055 *da9055, int channel)
{
return da9055_reg_update(da9055, DA9055_REG_ADC_CONT, 1 << channel,
1 << channel);
}
static int da9055_disable_auto_mode(struct da9055 *da9055, int channel)
{
return da9055_reg_update(da9055, DA9055_REG_ADC_CONT, 1 << channel, 0);
}
static ssize_t da9055_read_auto_ch(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct da9055_hwmon *hwmon = dev_get_drvdata(dev);
int ret, adc;
int channel = to_sensor_dev_attr(devattr)->index;
mutex_lock(&hwmon->hwmon_lock);
ret = da9055_enable_auto_mode(hwmon->da9055, channel);
if (ret < 0)
goto hwmon_err;
usleep_range(10000, 10500);
adc = da9055_reg_read(hwmon->da9055, DA9055_REG_VSYS_RES + channel);
if (adc < 0) {
ret = adc;
goto hwmon_err_release;
}
ret = da9055_disable_auto_mode(hwmon->da9055, channel);
if (ret < 0)
goto hwmon_err;
mutex_unlock(&hwmon->hwmon_lock);
return sprintf(buf, "%d\n", volt_reg_to_mv(adc, channel));
hwmon_err_release:
da9055_disable_auto_mode(hwmon->da9055, channel);
hwmon_err:
mutex_unlock(&hwmon->hwmon_lock);
return ret;
}
static ssize_t da9055_read_tjunc(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct da9055_hwmon *hwmon = dev_get_drvdata(dev);
int tjunc;
int toffset;
tjunc = da9055_adc_manual_read(hwmon, DA9055_ADC_TJUNC);
if (tjunc < 0)
return tjunc;
toffset = da9055_reg_read(hwmon->da9055, DA9055_REG_T_OFFSET);
if (toffset < 0)
return toffset;
/*
* Degrees celsius = -0.4084 * (ADC_RES - T_OFFSET) + 307.6332
* T_OFFSET is a trim value used to improve accuracy of the result
*/
return sprintf(buf, "%d\n", DIV_ROUND_CLOSEST(-4084 * (tjunc - toffset)
+ 3076332, 10000));
}
static ssize_t da9055_hwmon_show_name(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
return sprintf(buf, "da9055-hwmon\n");
}
static ssize_t show_label(struct device *dev,
struct device_attribute *devattr, char *buf)
{
return sprintf(buf, "%s\n",
input_names[to_sensor_dev_attr(devattr)->index]);
}
static SENSOR_DEVICE_ATTR(in0_input, S_IRUGO, da9055_read_auto_ch, NULL,
DA9055_ADC_VSYS);
static SENSOR_DEVICE_ATTR(in0_label, S_IRUGO, show_label, NULL,
DA9055_ADC_VSYS);
static SENSOR_DEVICE_ATTR(in1_input, S_IRUGO, da9055_read_auto_ch, NULL,
DA9055_ADC_ADCIN1);
static SENSOR_DEVICE_ATTR(in1_label, S_IRUGO, show_label, NULL,
DA9055_ADC_ADCIN1);
static SENSOR_DEVICE_ATTR(in2_input, S_IRUGO, da9055_read_auto_ch, NULL,
DA9055_ADC_ADCIN2);
static SENSOR_DEVICE_ATTR(in2_label, S_IRUGO, show_label, NULL,
DA9055_ADC_ADCIN2);
static SENSOR_DEVICE_ATTR(in3_input, S_IRUGO, da9055_read_auto_ch, NULL,
DA9055_ADC_ADCIN3);
static SENSOR_DEVICE_ATTR(in3_label, S_IRUGO, show_label, NULL,
DA9055_ADC_ADCIN3);
static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, da9055_read_tjunc, NULL,
DA9055_ADC_TJUNC);
static SENSOR_DEVICE_ATTR(temp1_label, S_IRUGO, show_label, NULL,
DA9055_ADC_TJUNC);
static DEVICE_ATTR(name, S_IRUGO, da9055_hwmon_show_name, NULL);
static struct attribute *da9055_attr[] = {
&dev_attr_name.attr,
&sensor_dev_attr_in0_input.dev_attr.attr,
&sensor_dev_attr_in0_label.dev_attr.attr,
&sensor_dev_attr_in1_input.dev_attr.attr,
&sensor_dev_attr_in1_label.dev_attr.attr,
&sensor_dev_attr_in2_input.dev_attr.attr,
&sensor_dev_attr_in2_label.dev_attr.attr,
&sensor_dev_attr_in3_input.dev_attr.attr,
&sensor_dev_attr_in3_label.dev_attr.attr,
&sensor_dev_attr_temp1_input.dev_attr.attr,
&sensor_dev_attr_temp1_label.dev_attr.attr,
NULL
};
static const struct attribute_group da9055_attr_group = {.attrs = da9055_attr};
static int da9055_hwmon_probe(struct platform_device *pdev)
{
struct da9055_hwmon *hwmon;
int hwmon_irq, ret;
hwmon = devm_kzalloc(&pdev->dev, sizeof(struct da9055_hwmon),
GFP_KERNEL);
if (!hwmon)
return -ENOMEM;
mutex_init(&hwmon->hwmon_lock);
mutex_init(&hwmon->irq_lock);
init_completion(&hwmon->done);
hwmon->da9055 = dev_get_drvdata(pdev->dev.parent);
platform_set_drvdata(pdev, hwmon);
hwmon_irq = platform_get_irq_byname(pdev, "HWMON");
if (hwmon_irq < 0)
return hwmon_irq;
hwmon_irq = regmap_irq_get_virq(hwmon->da9055->irq_data, hwmon_irq);
if (hwmon_irq < 0)
return hwmon_irq;
ret = devm_request_threaded_irq(&pdev->dev, hwmon_irq,
NULL, da9055_auxadc_irq,
IRQF_TRIGGER_HIGH | IRQF_ONESHOT,
"adc-irq", hwmon);
if (ret != 0) {
dev_err(hwmon->da9055->dev, "DA9055 ADC IRQ failed ret=%d\n",
ret);
return ret;
}
ret = sysfs_create_group(&pdev->dev.kobj, &da9055_attr_group);
if (ret)
return ret;
hwmon->class_device = hwmon_device_register(&pdev->dev);
if (IS_ERR(hwmon->class_device)) {
ret = PTR_ERR(hwmon->class_device);
goto err;
}
return 0;
err:
sysfs_remove_group(&pdev->dev.kobj, &da9055_attr_group);
return ret;
}
static int da9055_hwmon_remove(struct platform_device *pdev)
{
struct da9055_hwmon *hwmon = platform_get_drvdata(pdev);
sysfs_remove_group(&pdev->dev.kobj, &da9055_attr_group);
hwmon_device_unregister(hwmon->class_device);
return 0;
}
static struct platform_driver da9055_hwmon_driver = {
.probe = da9055_hwmon_probe,
.remove = da9055_hwmon_remove,
.driver = {
.name = "da9055-hwmon",
.owner = THIS_MODULE,
},
};
module_platform_driver(da9055_hwmon_driver);
MODULE_AUTHOR("David Dajun Chen <dchen@diasemi.com>");
MODULE_DESCRIPTION("DA9055 HWMON driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:da9055-hwmon");
| gpl-2.0 |
ian700518/kernel_imx | drivers/ide/ide-cd.c | 1414 | 46952 | /*
* ATAPI CD-ROM driver.
*
* Copyright (C) 1994-1996 Scott Snyder <snyder@fnald0.fnal.gov>
* Copyright (C) 1996-1998 Erik Andersen <andersee@debian.org>
* Copyright (C) 1998-2000 Jens Axboe <axboe@suse.de>
* Copyright (C) 2005, 2007-2009 Bartlomiej Zolnierkiewicz
*
* May be copied or modified under the terms of the GNU General Public
* License. See linux/COPYING for more information.
*
* See Documentation/cdrom/ide-cd for usage information.
*
* Suggestions are welcome. Patches that work are more welcome though. ;-)
*
* Documentation:
* Mt. Fuji (SFF8090 version 4) and ATAPI (SFF-8020i rev 2.6) standards.
*
* For historical changelog please see:
* Documentation/ide/ChangeLog.ide-cd.1994-2004
*/
#define DRV_NAME "ide-cd"
#define PFX DRV_NAME ": "
#define IDECD_VERSION "5.00"
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/timer.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/errno.h>
#include <linux/cdrom.h>
#include <linux/ide.h>
#include <linux/completion.h>
#include <linux/mutex.h>
#include <linux/bcd.h>
/* For SCSI -> ATAPI command conversion */
#include <scsi/scsi.h>
#include <linux/io.h>
#include <asm/byteorder.h>
#include <linux/uaccess.h>
#include <asm/unaligned.h>
#include "ide-cd.h"
static DEFINE_MUTEX(ide_cd_mutex);
static DEFINE_MUTEX(idecd_ref_mutex);
static void ide_cd_release(struct device *);
static struct cdrom_info *ide_cd_get(struct gendisk *disk)
{
struct cdrom_info *cd = NULL;
mutex_lock(&idecd_ref_mutex);
cd = ide_drv_g(disk, cdrom_info);
if (cd) {
if (ide_device_get(cd->drive))
cd = NULL;
else
get_device(&cd->dev);
}
mutex_unlock(&idecd_ref_mutex);
return cd;
}
static void ide_cd_put(struct cdrom_info *cd)
{
ide_drive_t *drive = cd->drive;
mutex_lock(&idecd_ref_mutex);
put_device(&cd->dev);
ide_device_put(drive);
mutex_unlock(&idecd_ref_mutex);
}
/*
* Generic packet command support and error handling routines.
*/
/* Mark that we've seen a media change and invalidate our internal buffers. */
static void cdrom_saw_media_change(ide_drive_t *drive)
{
drive->dev_flags |= IDE_DFLAG_MEDIA_CHANGED;
drive->atapi_flags &= ~IDE_AFLAG_TOC_VALID;
}
static int cdrom_log_sense(ide_drive_t *drive, struct request *rq)
{
struct request_sense *sense = &drive->sense_data;
int log = 0;
if (!sense || !rq || (rq->cmd_flags & REQ_QUIET))
return 0;
ide_debug_log(IDE_DBG_SENSE, "sense_key: 0x%x", sense->sense_key);
switch (sense->sense_key) {
case NO_SENSE:
case RECOVERED_ERROR:
break;
case NOT_READY:
/*
* don't care about tray state messages for e.g. capacity
* commands or in-progress or becoming ready
*/
if (sense->asc == 0x3a || sense->asc == 0x04)
break;
log = 1;
break;
case ILLEGAL_REQUEST:
/*
* don't log START_STOP unit with LoEj set, since we cannot
* reliably check if drive can auto-close
*/
if (rq->cmd[0] == GPCMD_START_STOP_UNIT && sense->asc == 0x24)
break;
log = 1;
break;
case UNIT_ATTENTION:
/*
* Make good and sure we've seen this potential media change.
* Some drives (i.e. Creative) fail to present the correct sense
* key in the error register.
*/
cdrom_saw_media_change(drive);
break;
default:
log = 1;
break;
}
return log;
}
static void cdrom_analyze_sense_data(ide_drive_t *drive,
struct request *failed_command)
{
struct request_sense *sense = &drive->sense_data;
struct cdrom_info *info = drive->driver_data;
unsigned long sector;
unsigned long bio_sectors;
ide_debug_log(IDE_DBG_SENSE, "error_code: 0x%x, sense_key: 0x%x",
sense->error_code, sense->sense_key);
if (failed_command)
ide_debug_log(IDE_DBG_SENSE, "failed cmd: 0x%x",
failed_command->cmd[0]);
if (!cdrom_log_sense(drive, failed_command))
return;
/*
* If a read toc is executed for a CD-R or CD-RW medium where the first
* toc has not been recorded yet, it will fail with 05/24/00 (which is a
* confusing error)
*/
if (failed_command && failed_command->cmd[0] == GPCMD_READ_TOC_PMA_ATIP)
if (sense->sense_key == 0x05 && sense->asc == 0x24)
return;
/* current error */
if (sense->error_code == 0x70) {
switch (sense->sense_key) {
case MEDIUM_ERROR:
case VOLUME_OVERFLOW:
case ILLEGAL_REQUEST:
if (!sense->valid)
break;
if (failed_command == NULL ||
failed_command->cmd_type != REQ_TYPE_FS)
break;
sector = (sense->information[0] << 24) |
(sense->information[1] << 16) |
(sense->information[2] << 8) |
(sense->information[3]);
if (queue_logical_block_size(drive->queue) == 2048)
/* device sector size is 2K */
sector <<= 2;
bio_sectors = max(bio_sectors(failed_command->bio), 4U);
sector &= ~(bio_sectors - 1);
/*
* The SCSI specification allows for the value
* returned by READ CAPACITY to be up to 75 2K
* sectors past the last readable block.
* Therefore, if we hit a medium error within the
* last 75 2K sectors, we decrease the saved size
* value.
*/
if (sector < get_capacity(info->disk) &&
drive->probed_capacity - sector < 4 * 75)
set_capacity(info->disk, sector);
}
}
ide_cd_log_error(drive->name, failed_command, sense);
}
static void ide_cd_complete_failed_rq(ide_drive_t *drive, struct request *rq)
{
/*
* For REQ_TYPE_SENSE, "rq->special" points to the original
* failed request. Also, the sense data should be read
* directly from rq which might be different from the original
* sense buffer if it got copied during mapping.
*/
struct request *failed = (struct request *)rq->special;
void *sense = bio_data(rq->bio);
if (failed) {
if (failed->sense) {
/*
* Sense is always read into drive->sense_data.
* Copy back if the failed request has its
* sense pointer set.
*/
memcpy(failed->sense, sense, 18);
failed->sense_len = rq->sense_len;
}
cdrom_analyze_sense_data(drive, failed);
if (ide_end_rq(drive, failed, -EIO, blk_rq_bytes(failed)))
BUG();
} else
cdrom_analyze_sense_data(drive, NULL);
}
/*
* Allow the drive 5 seconds to recover; some devices will return NOT_READY
* while flushing data from cache.
*
* returns: 0 failed (write timeout expired)
* 1 success
*/
static int ide_cd_breathe(ide_drive_t *drive, struct request *rq)
{
struct cdrom_info *info = drive->driver_data;
if (!rq->errors)
info->write_timeout = jiffies + ATAPI_WAIT_WRITE_BUSY;
rq->errors = 1;
if (time_after(jiffies, info->write_timeout))
return 0;
else {
/*
* take a breather
*/
blk_delay_queue(drive->queue, 1);
return 1;
}
}
/**
* Returns:
* 0: if the request should be continued.
* 1: if the request will be going through error recovery.
* 2: if the request should be ended.
*/
static int cdrom_decode_status(ide_drive_t *drive, u8 stat)
{
ide_hwif_t *hwif = drive->hwif;
struct request *rq = hwif->rq;
int err, sense_key, do_end_request = 0;
/* get the IDE error register */
err = ide_read_error(drive);
sense_key = err >> 4;
ide_debug_log(IDE_DBG_RQ, "cmd: 0x%x, rq->cmd_type: 0x%x, err: 0x%x, "
"stat 0x%x",
rq->cmd[0], rq->cmd_type, err, stat);
if (rq->cmd_type == REQ_TYPE_SENSE) {
/*
* We got an error trying to get sense info from the drive
* (probably while trying to recover from a former error).
* Just give up.
*/
rq->cmd_flags |= REQ_FAILED;
return 2;
}
/* if we have an error, pass CHECK_CONDITION as the SCSI status byte */
if (rq->cmd_type == REQ_TYPE_BLOCK_PC && !rq->errors)
rq->errors = SAM_STAT_CHECK_CONDITION;
if (blk_noretry_request(rq))
do_end_request = 1;
switch (sense_key) {
case NOT_READY:
if (rq->cmd_type == REQ_TYPE_FS && rq_data_dir(rq) == WRITE) {
if (ide_cd_breathe(drive, rq))
return 1;
} else {
cdrom_saw_media_change(drive);
if (rq->cmd_type == REQ_TYPE_FS &&
!(rq->cmd_flags & REQ_QUIET))
printk(KERN_ERR PFX "%s: tray open\n",
drive->name);
}
do_end_request = 1;
break;
case UNIT_ATTENTION:
cdrom_saw_media_change(drive);
if (rq->cmd_type != REQ_TYPE_FS)
return 0;
/*
* Arrange to retry the request but be sure to give up if we've
* retried too many times.
*/
if (++rq->errors > ERROR_MAX)
do_end_request = 1;
break;
case ILLEGAL_REQUEST:
/*
* Don't print error message for this condition -- SFF8090i
* indicates that 5/24/00 is the correct response to a request
* to close the tray if the drive doesn't have that capability.
*
* cdrom_log_sense() knows this!
*/
if (rq->cmd[0] == GPCMD_START_STOP_UNIT)
break;
/* fall-through */
case DATA_PROTECT:
/*
* No point in retrying after an illegal request or data
* protect error.
*/
if (!(rq->cmd_flags & REQ_QUIET))
ide_dump_status(drive, "command error", stat);
do_end_request = 1;
break;
case MEDIUM_ERROR:
/*
* No point in re-trying a zillion times on a bad sector.
* If we got here the error is not correctable.
*/
if (!(rq->cmd_flags & REQ_QUIET))
ide_dump_status(drive, "media error "
"(bad sector)", stat);
do_end_request = 1;
break;
case BLANK_CHECK:
/* disk appears blank? */
if (!(rq->cmd_flags & REQ_QUIET))
ide_dump_status(drive, "media error (blank)",
stat);
do_end_request = 1;
break;
default:
if (rq->cmd_type != REQ_TYPE_FS)
break;
if (err & ~ATA_ABORTED) {
/* go to the default handler for other errors */
ide_error(drive, "cdrom_decode_status", stat);
return 1;
} else if (++rq->errors > ERROR_MAX)
/* we've racked up too many retries, abort */
do_end_request = 1;
}
if (rq->cmd_type != REQ_TYPE_FS) {
rq->cmd_flags |= REQ_FAILED;
do_end_request = 1;
}
/*
* End a request through request sense analysis when we have sense data.
* We need this in order to perform end of media processing.
*/
if (do_end_request)
goto end_request;
/* if we got a CHECK_CONDITION status, queue a request sense command */
if (stat & ATA_ERR)
return ide_queue_sense_rq(drive, NULL) ? 2 : 1;
return 1;
end_request:
if (stat & ATA_ERR) {
hwif->rq = NULL;
return ide_queue_sense_rq(drive, rq) ? 2 : 1;
} else
return 2;
}
static void ide_cd_request_sense_fixup(ide_drive_t *drive, struct ide_cmd *cmd)
{
struct request *rq = cmd->rq;
ide_debug_log(IDE_DBG_FUNC, "rq->cmd[0]: 0x%x", rq->cmd[0]);
/*
* Some of the trailing request sense fields are optional,
* and some drives don't send them. Sigh.
*/
if (rq->cmd[0] == GPCMD_REQUEST_SENSE &&
cmd->nleft > 0 && cmd->nleft <= 5)
cmd->nleft = 0;
}
int ide_cd_queue_pc(ide_drive_t *drive, const unsigned char *cmd,
int write, void *buffer, unsigned *bufflen,
struct request_sense *sense, int timeout,
unsigned int cmd_flags)
{
struct cdrom_info *info = drive->driver_data;
struct request_sense local_sense;
int retries = 10;
unsigned int flags = 0;
if (!sense)
sense = &local_sense;
ide_debug_log(IDE_DBG_PC, "cmd[0]: 0x%x, write: 0x%x, timeout: %d, "
"cmd_flags: 0x%x",
cmd[0], write, timeout, cmd_flags);
/* start of retry loop */
do {
struct request *rq;
int error;
rq = blk_get_request(drive->queue, write, __GFP_WAIT);
memcpy(rq->cmd, cmd, BLK_MAX_CDB);
rq->cmd_type = REQ_TYPE_ATA_PC;
rq->sense = sense;
rq->cmd_flags |= cmd_flags;
rq->timeout = timeout;
if (buffer) {
error = blk_rq_map_kern(drive->queue, rq, buffer,
*bufflen, GFP_NOIO);
if (error) {
blk_put_request(rq);
return error;
}
}
error = blk_execute_rq(drive->queue, info->disk, rq, 0);
if (buffer)
*bufflen = rq->resid_len;
flags = rq->cmd_flags;
blk_put_request(rq);
/*
* FIXME: we should probably abort/retry or something in case of
* failure.
*/
if (flags & REQ_FAILED) {
/*
* The request failed. Retry if it was due to a unit
* attention status (usually means media was changed).
*/
struct request_sense *reqbuf = sense;
if (reqbuf->sense_key == UNIT_ATTENTION)
cdrom_saw_media_change(drive);
else if (reqbuf->sense_key == NOT_READY &&
reqbuf->asc == 4 && reqbuf->ascq != 4) {
/*
* The drive is in the process of loading
* a disk. Retry, but wait a little to give
* the drive time to complete the load.
*/
ssleep(2);
} else {
/* otherwise, don't retry */
retries = 0;
}
--retries;
}
/* end of retry loop */
} while ((flags & REQ_FAILED) && retries >= 0);
/* return an error if the command failed */
return (flags & REQ_FAILED) ? -EIO : 0;
}
/*
* returns true if rq has been completed
*/
static bool ide_cd_error_cmd(ide_drive_t *drive, struct ide_cmd *cmd)
{
unsigned int nr_bytes = cmd->nbytes - cmd->nleft;
if (cmd->tf_flags & IDE_TFLAG_WRITE)
nr_bytes -= cmd->last_xfer_len;
if (nr_bytes > 0) {
ide_complete_rq(drive, 0, nr_bytes);
return true;
}
return false;
}
static ide_startstop_t cdrom_newpc_intr(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
struct ide_cmd *cmd = &hwif->cmd;
struct request *rq = hwif->rq;
ide_expiry_t *expiry = NULL;
int dma_error = 0, dma, thislen, uptodate = 0;
int write = (rq_data_dir(rq) == WRITE) ? 1 : 0, rc = 0;
int sense = (rq->cmd_type == REQ_TYPE_SENSE);
unsigned int timeout;
u16 len;
u8 ireason, stat;
ide_debug_log(IDE_DBG_PC, "cmd: 0x%x, write: 0x%x", rq->cmd[0], write);
/* check for errors */
dma = drive->dma;
if (dma) {
drive->dma = 0;
drive->waiting_for_dma = 0;
dma_error = hwif->dma_ops->dma_end(drive);
ide_dma_unmap_sg(drive, cmd);
if (dma_error) {
printk(KERN_ERR PFX "%s: DMA %s error\n", drive->name,
write ? "write" : "read");
ide_dma_off(drive);
}
}
/* check status */
stat = hwif->tp_ops->read_status(hwif);
if (!OK_STAT(stat, 0, BAD_R_STAT)) {
rc = cdrom_decode_status(drive, stat);
if (rc) {
if (rc == 2)
goto out_end;
return ide_stopped;
}
}
/* using dma, transfer is complete now */
if (dma) {
if (dma_error)
return ide_error(drive, "dma error", stat);
uptodate = 1;
goto out_end;
}
ide_read_bcount_and_ireason(drive, &len, &ireason);
thislen = (rq->cmd_type == REQ_TYPE_FS) ? len : cmd->nleft;
if (thislen > len)
thislen = len;
ide_debug_log(IDE_DBG_PC, "DRQ: stat: 0x%x, thislen: %d",
stat, thislen);
/* If DRQ is clear, the command has completed. */
if ((stat & ATA_DRQ) == 0) {
if (rq->cmd_type == REQ_TYPE_FS) {
/*
* If we're not done reading/writing, complain.
* Otherwise, complete the command normally.
*/
uptodate = 1;
if (cmd->nleft > 0) {
printk(KERN_ERR PFX "%s: %s: data underrun "
"(%u bytes)\n", drive->name, __func__,
cmd->nleft);
if (!write)
rq->cmd_flags |= REQ_FAILED;
uptodate = 0;
}
} else if (rq->cmd_type != REQ_TYPE_BLOCK_PC) {
ide_cd_request_sense_fixup(drive, cmd);
uptodate = cmd->nleft ? 0 : 1;
/*
* suck out the remaining bytes from the drive in an
* attempt to complete the data xfer. (see BZ#13399)
*/
if (!(stat & ATA_ERR) && !uptodate && thislen) {
ide_pio_bytes(drive, cmd, write, thislen);
uptodate = cmd->nleft ? 0 : 1;
}
if (!uptodate)
rq->cmd_flags |= REQ_FAILED;
}
goto out_end;
}
rc = ide_check_ireason(drive, rq, len, ireason, write);
if (rc)
goto out_end;
cmd->last_xfer_len = 0;
ide_debug_log(IDE_DBG_PC, "data transfer, rq->cmd_type: 0x%x, "
"ireason: 0x%x",
rq->cmd_type, ireason);
/* transfer data */
while (thislen > 0) {
int blen = min_t(int, thislen, cmd->nleft);
if (cmd->nleft == 0)
break;
ide_pio_bytes(drive, cmd, write, blen);
cmd->last_xfer_len += blen;
thislen -= blen;
len -= blen;
if (sense && write == 0)
rq->sense_len += blen;
}
/* pad, if necessary */
if (len > 0) {
if (rq->cmd_type != REQ_TYPE_FS || write == 0)
ide_pad_transfer(drive, write, len);
else {
printk(KERN_ERR PFX "%s: confused, missing data\n",
drive->name);
blk_dump_rq_flags(rq, "cdrom_newpc_intr");
}
}
if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
timeout = rq->timeout;
} else {
timeout = ATAPI_WAIT_PC;
if (rq->cmd_type != REQ_TYPE_FS)
expiry = ide_cd_expiry;
}
hwif->expiry = expiry;
ide_set_handler(drive, cdrom_newpc_intr, timeout);
return ide_started;
out_end:
if (rq->cmd_type == REQ_TYPE_BLOCK_PC && rc == 0) {
rq->resid_len = 0;
blk_end_request_all(rq, 0);
hwif->rq = NULL;
} else {
if (sense && uptodate)
ide_cd_complete_failed_rq(drive, rq);
if (rq->cmd_type == REQ_TYPE_FS) {
if (cmd->nleft == 0)
uptodate = 1;
} else {
if (uptodate <= 0 && rq->errors == 0)
rq->errors = -EIO;
}
if (uptodate == 0 && rq->bio)
if (ide_cd_error_cmd(drive, cmd))
return ide_stopped;
/* make sure it's fully ended */
if (rq->cmd_type != REQ_TYPE_FS) {
rq->resid_len -= cmd->nbytes - cmd->nleft;
if (uptodate == 0 && (cmd->tf_flags & IDE_TFLAG_WRITE))
rq->resid_len += cmd->last_xfer_len;
}
ide_complete_rq(drive, uptodate ? 0 : -EIO, blk_rq_bytes(rq));
if (sense && rc == 2)
ide_error(drive, "request sense failure", stat);
}
return ide_stopped;
}
static ide_startstop_t cdrom_start_rw(ide_drive_t *drive, struct request *rq)
{
struct cdrom_info *cd = drive->driver_data;
struct request_queue *q = drive->queue;
int write = rq_data_dir(rq) == WRITE;
unsigned short sectors_per_frame =
queue_logical_block_size(q) >> SECTOR_BITS;
ide_debug_log(IDE_DBG_RQ, "rq->cmd[0]: 0x%x, rq->cmd_flags: 0x%x, "
"secs_per_frame: %u",
rq->cmd[0], rq->cmd_flags, sectors_per_frame);
if (write) {
/* disk has become write protected */
if (get_disk_ro(cd->disk))
return ide_stopped;
} else {
/*
* We may be retrying this request after an error. Fix up any
* weirdness which might be present in the request packet.
*/
q->prep_rq_fn(q, rq);
}
/* fs requests *must* be hardware frame aligned */
if ((blk_rq_sectors(rq) & (sectors_per_frame - 1)) ||
(blk_rq_pos(rq) & (sectors_per_frame - 1)))
return ide_stopped;
/* use DMA, if possible */
drive->dma = !!(drive->dev_flags & IDE_DFLAG_USING_DMA);
if (write)
cd->devinfo.media_written = 1;
rq->timeout = ATAPI_WAIT_PC;
return ide_started;
}
static void cdrom_do_block_pc(ide_drive_t *drive, struct request *rq)
{
ide_debug_log(IDE_DBG_PC, "rq->cmd[0]: 0x%x, rq->cmd_type: 0x%x",
rq->cmd[0], rq->cmd_type);
if (rq->cmd_type == REQ_TYPE_BLOCK_PC)
rq->cmd_flags |= REQ_QUIET;
else
rq->cmd_flags &= ~REQ_FAILED;
drive->dma = 0;
/* sg request */
if (rq->bio) {
struct request_queue *q = drive->queue;
char *buf = bio_data(rq->bio);
unsigned int alignment;
drive->dma = !!(drive->dev_flags & IDE_DFLAG_USING_DMA);
/*
* check if dma is safe
*
* NOTE! The "len" and "addr" checks should possibly have
* separate masks.
*/
alignment = queue_dma_alignment(q) | q->dma_pad_mask;
if ((unsigned long)buf & alignment
|| blk_rq_bytes(rq) & q->dma_pad_mask
|| object_is_on_stack(buf))
drive->dma = 0;
}
}
static ide_startstop_t ide_cd_do_request(ide_drive_t *drive, struct request *rq,
sector_t block)
{
struct ide_cmd cmd;
int uptodate = 0;
unsigned int nsectors;
ide_debug_log(IDE_DBG_RQ, "cmd: 0x%x, block: %llu",
rq->cmd[0], (unsigned long long)block);
if (drive->debug_mask & IDE_DBG_RQ)
blk_dump_rq_flags(rq, "ide_cd_do_request");
switch (rq->cmd_type) {
case REQ_TYPE_FS:
if (cdrom_start_rw(drive, rq) == ide_stopped)
goto out_end;
break;
case REQ_TYPE_SENSE:
case REQ_TYPE_BLOCK_PC:
case REQ_TYPE_ATA_PC:
if (!rq->timeout)
rq->timeout = ATAPI_WAIT_PC;
cdrom_do_block_pc(drive, rq);
break;
case REQ_TYPE_SPECIAL:
/* right now this can only be a reset... */
uptodate = 1;
goto out_end;
default:
BUG();
}
/* prepare sense request for this command */
ide_prep_sense(drive, rq);
memset(&cmd, 0, sizeof(cmd));
if (rq_data_dir(rq))
cmd.tf_flags |= IDE_TFLAG_WRITE;
cmd.rq = rq;
if (rq->cmd_type == REQ_TYPE_FS || blk_rq_bytes(rq)) {
ide_init_sg_cmd(&cmd, blk_rq_bytes(rq));
ide_map_sg(drive, &cmd);
}
return ide_issue_pc(drive, &cmd);
out_end:
nsectors = blk_rq_sectors(rq);
if (nsectors == 0)
nsectors = 1;
ide_complete_rq(drive, uptodate ? 0 : -EIO, nsectors << 9);
return ide_stopped;
}
/*
* Ioctl handling.
*
* Routines which queue packet commands take as a final argument a pointer to a
* request_sense struct. If execution of the command results in an error with a
* CHECK CONDITION status, this structure will be filled with the results of the
* subsequent request sense command. The pointer can also be NULL, in which case
* no sense information is returned.
*/
static void msf_from_bcd(struct atapi_msf *msf)
{
msf->minute = bcd2bin(msf->minute);
msf->second = bcd2bin(msf->second);
msf->frame = bcd2bin(msf->frame);
}
int cdrom_check_status(ide_drive_t *drive, struct request_sense *sense)
{
struct cdrom_info *info = drive->driver_data;
struct cdrom_device_info *cdi = &info->devinfo;
unsigned char cmd[BLK_MAX_CDB];
ide_debug_log(IDE_DBG_FUNC, "enter");
memset(cmd, 0, BLK_MAX_CDB);
cmd[0] = GPCMD_TEST_UNIT_READY;
/*
* Sanyo 3 CD changer uses byte 7 of TEST_UNIT_READY to switch CDs
* instead of supporting the LOAD_UNLOAD opcode.
*/
cmd[7] = cdi->sanyo_slot % 3;
return ide_cd_queue_pc(drive, cmd, 0, NULL, NULL, sense, 0, REQ_QUIET);
}
static int cdrom_read_capacity(ide_drive_t *drive, unsigned long *capacity,
unsigned long *sectors_per_frame,
struct request_sense *sense)
{
struct {
__be32 lba;
__be32 blocklen;
} capbuf;
int stat;
unsigned char cmd[BLK_MAX_CDB];
unsigned len = sizeof(capbuf);
u32 blocklen;
ide_debug_log(IDE_DBG_FUNC, "enter");
memset(cmd, 0, BLK_MAX_CDB);
cmd[0] = GPCMD_READ_CDVD_CAPACITY;
stat = ide_cd_queue_pc(drive, cmd, 0, &capbuf, &len, sense, 0,
REQ_QUIET);
if (stat)
return stat;
/*
* Sanity check the given block size, in so far as making
* sure the sectors_per_frame we give to the caller won't
* end up being bogus.
*/
blocklen = be32_to_cpu(capbuf.blocklen);
blocklen = (blocklen >> SECTOR_BITS) << SECTOR_BITS;
switch (blocklen) {
case 512:
case 1024:
case 2048:
case 4096:
break;
default:
printk_once(KERN_ERR PFX "%s: weird block size %u; "
"setting default block size to 2048\n",
drive->name, blocklen);
blocklen = 2048;
break;
}
*capacity = 1 + be32_to_cpu(capbuf.lba);
*sectors_per_frame = blocklen >> SECTOR_BITS;
ide_debug_log(IDE_DBG_PROBE, "cap: %lu, sectors_per_frame: %lu",
*capacity, *sectors_per_frame);
return 0;
}
static int cdrom_read_tocentry(ide_drive_t *drive, int trackno, int msf_flag,
int format, char *buf, int buflen,
struct request_sense *sense)
{
unsigned char cmd[BLK_MAX_CDB];
ide_debug_log(IDE_DBG_FUNC, "enter");
memset(cmd, 0, BLK_MAX_CDB);
cmd[0] = GPCMD_READ_TOC_PMA_ATIP;
cmd[6] = trackno;
cmd[7] = (buflen >> 8);
cmd[8] = (buflen & 0xff);
cmd[9] = (format << 6);
if (msf_flag)
cmd[1] = 2;
return ide_cd_queue_pc(drive, cmd, 0, buf, &buflen, sense, 0, REQ_QUIET);
}
/* Try to read the entire TOC for the disk into our internal buffer. */
int ide_cd_read_toc(ide_drive_t *drive, struct request_sense *sense)
{
int stat, ntracks, i;
struct cdrom_info *info = drive->driver_data;
struct cdrom_device_info *cdi = &info->devinfo;
struct atapi_toc *toc = info->toc;
struct {
struct atapi_toc_header hdr;
struct atapi_toc_entry ent;
} ms_tmp;
long last_written;
unsigned long sectors_per_frame = SECTORS_PER_FRAME;
ide_debug_log(IDE_DBG_FUNC, "enter");
if (toc == NULL) {
/* try to allocate space */
toc = kmalloc(sizeof(struct atapi_toc), GFP_KERNEL);
if (toc == NULL) {
printk(KERN_ERR PFX "%s: No cdrom TOC buffer!\n",
drive->name);
return -ENOMEM;
}
info->toc = toc;
}
/*
* Check to see if the existing data is still valid. If it is,
* just return.
*/
(void) cdrom_check_status(drive, sense);
if (drive->atapi_flags & IDE_AFLAG_TOC_VALID)
return 0;
/* try to get the total cdrom capacity and sector size */
stat = cdrom_read_capacity(drive, &toc->capacity, §ors_per_frame,
sense);
if (stat)
toc->capacity = 0x1fffff;
set_capacity(info->disk, toc->capacity * sectors_per_frame);
/* save a private copy of the TOC capacity for error handling */
drive->probed_capacity = toc->capacity * sectors_per_frame;
blk_queue_logical_block_size(drive->queue,
sectors_per_frame << SECTOR_BITS);
/* first read just the header, so we know how long the TOC is */
stat = cdrom_read_tocentry(drive, 0, 1, 0, (char *) &toc->hdr,
sizeof(struct atapi_toc_header), sense);
if (stat)
return stat;
if (drive->atapi_flags & IDE_AFLAG_TOCTRACKS_AS_BCD) {
toc->hdr.first_track = bcd2bin(toc->hdr.first_track);
toc->hdr.last_track = bcd2bin(toc->hdr.last_track);
}
ntracks = toc->hdr.last_track - toc->hdr.first_track + 1;
if (ntracks <= 0)
return -EIO;
if (ntracks > MAX_TRACKS)
ntracks = MAX_TRACKS;
/* now read the whole schmeer */
stat = cdrom_read_tocentry(drive, toc->hdr.first_track, 1, 0,
(char *)&toc->hdr,
sizeof(struct atapi_toc_header) +
(ntracks + 1) *
sizeof(struct atapi_toc_entry), sense);
if (stat && toc->hdr.first_track > 1) {
/*
* Cds with CDI tracks only don't have any TOC entries, despite
* of this the returned values are
* first_track == last_track = number of CDI tracks + 1,
* so that this case is indistinguishable from the same layout
* plus an additional audio track. If we get an error for the
* regular case, we assume a CDI without additional audio
* tracks. In this case the readable TOC is empty (CDI tracks
* are not included) and only holds the Leadout entry.
*
* Heiko Eißfeldt.
*/
ntracks = 0;
stat = cdrom_read_tocentry(drive, CDROM_LEADOUT, 1, 0,
(char *)&toc->hdr,
sizeof(struct atapi_toc_header) +
(ntracks + 1) *
sizeof(struct atapi_toc_entry),
sense);
if (stat)
return stat;
if (drive->atapi_flags & IDE_AFLAG_TOCTRACKS_AS_BCD) {
toc->hdr.first_track = (u8)bin2bcd(CDROM_LEADOUT);
toc->hdr.last_track = (u8)bin2bcd(CDROM_LEADOUT);
} else {
toc->hdr.first_track = CDROM_LEADOUT;
toc->hdr.last_track = CDROM_LEADOUT;
}
}
if (stat)
return stat;
toc->hdr.toc_length = be16_to_cpu(toc->hdr.toc_length);
if (drive->atapi_flags & IDE_AFLAG_TOCTRACKS_AS_BCD) {
toc->hdr.first_track = bcd2bin(toc->hdr.first_track);
toc->hdr.last_track = bcd2bin(toc->hdr.last_track);
}
for (i = 0; i <= ntracks; i++) {
if (drive->atapi_flags & IDE_AFLAG_TOCADDR_AS_BCD) {
if (drive->atapi_flags & IDE_AFLAG_TOCTRACKS_AS_BCD)
toc->ent[i].track = bcd2bin(toc->ent[i].track);
msf_from_bcd(&toc->ent[i].addr.msf);
}
toc->ent[i].addr.lba = msf_to_lba(toc->ent[i].addr.msf.minute,
toc->ent[i].addr.msf.second,
toc->ent[i].addr.msf.frame);
}
if (toc->hdr.first_track != CDROM_LEADOUT) {
/* read the multisession information */
stat = cdrom_read_tocentry(drive, 0, 0, 1, (char *)&ms_tmp,
sizeof(ms_tmp), sense);
if (stat)
return stat;
toc->last_session_lba = be32_to_cpu(ms_tmp.ent.addr.lba);
} else {
ms_tmp.hdr.last_track = CDROM_LEADOUT;
ms_tmp.hdr.first_track = ms_tmp.hdr.last_track;
toc->last_session_lba = msf_to_lba(0, 2, 0); /* 0m 2s 0f */
}
if (drive->atapi_flags & IDE_AFLAG_TOCADDR_AS_BCD) {
/* re-read multisession information using MSF format */
stat = cdrom_read_tocentry(drive, 0, 1, 1, (char *)&ms_tmp,
sizeof(ms_tmp), sense);
if (stat)
return stat;
msf_from_bcd(&ms_tmp.ent.addr.msf);
toc->last_session_lba = msf_to_lba(ms_tmp.ent.addr.msf.minute,
ms_tmp.ent.addr.msf.second,
ms_tmp.ent.addr.msf.frame);
}
toc->xa_flag = (ms_tmp.hdr.first_track != ms_tmp.hdr.last_track);
/* now try to get the total cdrom capacity */
stat = cdrom_get_last_written(cdi, &last_written);
if (!stat && (last_written > toc->capacity)) {
toc->capacity = last_written;
set_capacity(info->disk, toc->capacity * sectors_per_frame);
drive->probed_capacity = toc->capacity * sectors_per_frame;
}
/* Remember that we've read this stuff. */
drive->atapi_flags |= IDE_AFLAG_TOC_VALID;
return 0;
}
int ide_cdrom_get_capabilities(ide_drive_t *drive, u8 *buf)
{
struct cdrom_info *info = drive->driver_data;
struct cdrom_device_info *cdi = &info->devinfo;
struct packet_command cgc;
int stat, attempts = 3, size = ATAPI_CAPABILITIES_PAGE_SIZE;
ide_debug_log(IDE_DBG_FUNC, "enter");
if ((drive->atapi_flags & IDE_AFLAG_FULL_CAPS_PAGE) == 0)
size -= ATAPI_CAPABILITIES_PAGE_PAD_SIZE;
init_cdrom_command(&cgc, buf, size, CGC_DATA_UNKNOWN);
do {
/* we seem to get stat=0x01,err=0x00 the first time (??) */
stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CAPABILITIES_PAGE, 0);
if (!stat)
break;
} while (--attempts);
return stat;
}
void ide_cdrom_update_speed(ide_drive_t *drive, u8 *buf)
{
struct cdrom_info *cd = drive->driver_data;
u16 curspeed, maxspeed;
ide_debug_log(IDE_DBG_FUNC, "enter");
if (drive->atapi_flags & IDE_AFLAG_LE_SPEED_FIELDS) {
curspeed = le16_to_cpup((__le16 *)&buf[8 + 14]);
maxspeed = le16_to_cpup((__le16 *)&buf[8 + 8]);
} else {
curspeed = be16_to_cpup((__be16 *)&buf[8 + 14]);
maxspeed = be16_to_cpup((__be16 *)&buf[8 + 8]);
}
ide_debug_log(IDE_DBG_PROBE, "curspeed: %u, maxspeed: %u",
curspeed, maxspeed);
cd->current_speed = DIV_ROUND_CLOSEST(curspeed, 176);
cd->max_speed = DIV_ROUND_CLOSEST(maxspeed, 176);
}
#define IDE_CD_CAPABILITIES \
(CDC_CLOSE_TRAY | CDC_OPEN_TRAY | CDC_LOCK | CDC_SELECT_SPEED | \
CDC_SELECT_DISC | CDC_MULTI_SESSION | CDC_MCN | CDC_MEDIA_CHANGED | \
CDC_PLAY_AUDIO | CDC_RESET | CDC_DRIVE_STATUS | CDC_CD_R | \
CDC_CD_RW | CDC_DVD | CDC_DVD_R | CDC_DVD_RAM | CDC_GENERIC_PACKET | \
CDC_MO_DRIVE | CDC_MRW | CDC_MRW_W | CDC_RAM)
static struct cdrom_device_ops ide_cdrom_dops = {
.open = ide_cdrom_open_real,
.release = ide_cdrom_release_real,
.drive_status = ide_cdrom_drive_status,
.check_events = ide_cdrom_check_events_real,
.tray_move = ide_cdrom_tray_move,
.lock_door = ide_cdrom_lock_door,
.select_speed = ide_cdrom_select_speed,
.get_last_session = ide_cdrom_get_last_session,
.get_mcn = ide_cdrom_get_mcn,
.reset = ide_cdrom_reset,
.audio_ioctl = ide_cdrom_audio_ioctl,
.capability = IDE_CD_CAPABILITIES,
.generic_packet = ide_cdrom_packet,
};
static int ide_cdrom_register(ide_drive_t *drive, int nslots)
{
struct cdrom_info *info = drive->driver_data;
struct cdrom_device_info *devinfo = &info->devinfo;
ide_debug_log(IDE_DBG_PROBE, "nslots: %d", nslots);
devinfo->ops = &ide_cdrom_dops;
devinfo->speed = info->current_speed;
devinfo->capacity = nslots;
devinfo->handle = drive;
strcpy(devinfo->name, drive->name);
if (drive->atapi_flags & IDE_AFLAG_NO_SPEED_SELECT)
devinfo->mask |= CDC_SELECT_SPEED;
devinfo->disk = info->disk;
return register_cdrom(devinfo);
}
static int ide_cdrom_probe_capabilities(ide_drive_t *drive)
{
struct cdrom_info *cd = drive->driver_data;
struct cdrom_device_info *cdi = &cd->devinfo;
u8 buf[ATAPI_CAPABILITIES_PAGE_SIZE];
mechtype_t mechtype;
int nslots = 1;
ide_debug_log(IDE_DBG_PROBE, "media: 0x%x, atapi_flags: 0x%lx",
drive->media, drive->atapi_flags);
cdi->mask = (CDC_CD_R | CDC_CD_RW | CDC_DVD | CDC_DVD_R |
CDC_DVD_RAM | CDC_SELECT_DISC | CDC_PLAY_AUDIO |
CDC_MO_DRIVE | CDC_RAM);
if (drive->media == ide_optical) {
cdi->mask &= ~(CDC_MO_DRIVE | CDC_RAM);
printk(KERN_ERR PFX "%s: ATAPI magneto-optical drive\n",
drive->name);
return nslots;
}
if (drive->atapi_flags & IDE_AFLAG_PRE_ATAPI12) {
drive->atapi_flags &= ~IDE_AFLAG_NO_EJECT;
cdi->mask &= ~CDC_PLAY_AUDIO;
return nslots;
}
/*
* We have to cheat a little here. the packet will eventually be queued
* with ide_cdrom_packet(), which extracts the drive from cdi->handle.
* Since this device hasn't been registered with the Uniform layer yet,
* it can't do this. Same goes for cdi->ops.
*/
cdi->handle = drive;
cdi->ops = &ide_cdrom_dops;
if (ide_cdrom_get_capabilities(drive, buf))
return 0;
if ((buf[8 + 6] & 0x01) == 0)
drive->dev_flags &= ~IDE_DFLAG_DOORLOCKING;
if (buf[8 + 6] & 0x08)
drive->atapi_flags &= ~IDE_AFLAG_NO_EJECT;
if (buf[8 + 3] & 0x01)
cdi->mask &= ~CDC_CD_R;
if (buf[8 + 3] & 0x02)
cdi->mask &= ~(CDC_CD_RW | CDC_RAM);
if (buf[8 + 2] & 0x38)
cdi->mask &= ~CDC_DVD;
if (buf[8 + 3] & 0x20)
cdi->mask &= ~(CDC_DVD_RAM | CDC_RAM);
if (buf[8 + 3] & 0x10)
cdi->mask &= ~CDC_DVD_R;
if ((buf[8 + 4] & 0x01) || (drive->atapi_flags & IDE_AFLAG_PLAY_AUDIO_OK))
cdi->mask &= ~CDC_PLAY_AUDIO;
mechtype = buf[8 + 6] >> 5;
if (mechtype == mechtype_caddy ||
mechtype == mechtype_popup ||
(drive->atapi_flags & IDE_AFLAG_NO_AUTOCLOSE))
cdi->mask |= CDC_CLOSE_TRAY;
if (cdi->sanyo_slot > 0) {
cdi->mask &= ~CDC_SELECT_DISC;
nslots = 3;
} else if (mechtype == mechtype_individual_changer ||
mechtype == mechtype_cartridge_changer) {
nslots = cdrom_number_of_slots(cdi);
if (nslots > 1)
cdi->mask &= ~CDC_SELECT_DISC;
}
ide_cdrom_update_speed(drive, buf);
printk(KERN_INFO PFX "%s: ATAPI", drive->name);
/* don't print speed if the drive reported 0 */
if (cd->max_speed)
printk(KERN_CONT " %dX", cd->max_speed);
printk(KERN_CONT " %s", (cdi->mask & CDC_DVD) ? "CD-ROM" : "DVD-ROM");
if ((cdi->mask & CDC_DVD_R) == 0 || (cdi->mask & CDC_DVD_RAM) == 0)
printk(KERN_CONT " DVD%s%s",
(cdi->mask & CDC_DVD_R) ? "" : "-R",
(cdi->mask & CDC_DVD_RAM) ? "" : "/RAM");
if ((cdi->mask & CDC_CD_R) == 0 || (cdi->mask & CDC_CD_RW) == 0)
printk(KERN_CONT " CD%s%s",
(cdi->mask & CDC_CD_R) ? "" : "-R",
(cdi->mask & CDC_CD_RW) ? "" : "/RW");
if ((cdi->mask & CDC_SELECT_DISC) == 0)
printk(KERN_CONT " changer w/%d slots", nslots);
else
printk(KERN_CONT " drive");
printk(KERN_CONT ", %dkB Cache\n",
be16_to_cpup((__be16 *)&buf[8 + 12]));
return nslots;
}
/* standard prep_rq_fn that builds 10 byte cmds */
static int ide_cdrom_prep_fs(struct request_queue *q, struct request *rq)
{
int hard_sect = queue_logical_block_size(q);
long block = (long)blk_rq_pos(rq) / (hard_sect >> 9);
unsigned long blocks = blk_rq_sectors(rq) / (hard_sect >> 9);
memset(rq->cmd, 0, BLK_MAX_CDB);
if (rq_data_dir(rq) == READ)
rq->cmd[0] = GPCMD_READ_10;
else
rq->cmd[0] = GPCMD_WRITE_10;
/*
* fill in lba
*/
rq->cmd[2] = (block >> 24) & 0xff;
rq->cmd[3] = (block >> 16) & 0xff;
rq->cmd[4] = (block >> 8) & 0xff;
rq->cmd[5] = block & 0xff;
/*
* and transfer length
*/
rq->cmd[7] = (blocks >> 8) & 0xff;
rq->cmd[8] = blocks & 0xff;
rq->cmd_len = 10;
return BLKPREP_OK;
}
/*
* Most of the SCSI commands are supported directly by ATAPI devices.
* This transform handles the few exceptions.
*/
static int ide_cdrom_prep_pc(struct request *rq)
{
u8 *c = rq->cmd;
/* transform 6-byte read/write commands to the 10-byte version */
if (c[0] == READ_6 || c[0] == WRITE_6) {
c[8] = c[4];
c[5] = c[3];
c[4] = c[2];
c[3] = c[1] & 0x1f;
c[2] = 0;
c[1] &= 0xe0;
c[0] += (READ_10 - READ_6);
rq->cmd_len = 10;
return BLKPREP_OK;
}
/*
* it's silly to pretend we understand 6-byte sense commands, just
* reject with ILLEGAL_REQUEST and the caller should take the
* appropriate action
*/
if (c[0] == MODE_SENSE || c[0] == MODE_SELECT) {
rq->errors = ILLEGAL_REQUEST;
return BLKPREP_KILL;
}
return BLKPREP_OK;
}
static int ide_cdrom_prep_fn(struct request_queue *q, struct request *rq)
{
if (rq->cmd_type == REQ_TYPE_FS)
return ide_cdrom_prep_fs(q, rq);
else if (rq->cmd_type == REQ_TYPE_BLOCK_PC)
return ide_cdrom_prep_pc(rq);
return 0;
}
struct cd_list_entry {
const char *id_model;
const char *id_firmware;
unsigned int cd_flags;
};
#ifdef CONFIG_IDE_PROC_FS
static sector_t ide_cdrom_capacity(ide_drive_t *drive)
{
unsigned long capacity, sectors_per_frame;
if (cdrom_read_capacity(drive, &capacity, §ors_per_frame, NULL))
return 0;
return capacity * sectors_per_frame;
}
static int idecd_capacity_proc_show(struct seq_file *m, void *v)
{
ide_drive_t *drive = m->private;
seq_printf(m, "%llu\n", (long long)ide_cdrom_capacity(drive));
return 0;
}
static int idecd_capacity_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, idecd_capacity_proc_show, PDE_DATA(inode));
}
static const struct file_operations idecd_capacity_proc_fops = {
.owner = THIS_MODULE,
.open = idecd_capacity_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static ide_proc_entry_t idecd_proc[] = {
{ "capacity", S_IFREG|S_IRUGO, &idecd_capacity_proc_fops },
{}
};
static ide_proc_entry_t *ide_cd_proc_entries(ide_drive_t *drive)
{
return idecd_proc;
}
static const struct ide_proc_devset *ide_cd_proc_devsets(ide_drive_t *drive)
{
return NULL;
}
#endif
static const struct cd_list_entry ide_cd_quirks_list[] = {
/* SCR-3231 doesn't support the SET_CD_SPEED command. */
{ "SAMSUNG CD-ROM SCR-3231", NULL, IDE_AFLAG_NO_SPEED_SELECT },
/* Old NEC260 (not R) was released before ATAPI 1.2 spec. */
{ "NEC CD-ROM DRIVE:260", "1.01", IDE_AFLAG_TOCADDR_AS_BCD |
IDE_AFLAG_PRE_ATAPI12, },
/* Vertos 300, some versions of this drive like to talk BCD. */
{ "V003S0DS", NULL, IDE_AFLAG_VERTOS_300_SSD, },
/* Vertos 600 ESD. */
{ "V006E0DS", NULL, IDE_AFLAG_VERTOS_600_ESD, },
/*
* Sanyo 3 CD changer uses a non-standard command for CD changing
* (by default standard ATAPI support for CD changers is used).
*/
{ "CD-ROM CDR-C3 G", NULL, IDE_AFLAG_SANYO_3CD },
{ "CD-ROM CDR-C3G", NULL, IDE_AFLAG_SANYO_3CD },
{ "CD-ROM CDR_C36", NULL, IDE_AFLAG_SANYO_3CD },
/* Stingray 8X CD-ROM. */
{ "STINGRAY 8422 IDE 8X CD-ROM 7-27-95", NULL, IDE_AFLAG_PRE_ATAPI12 },
/*
* ACER 50X CD-ROM and WPI 32X CD-ROM require the full spec length
* mode sense page capabilities size, but older drives break.
*/
{ "ATAPI CD ROM DRIVE 50X MAX", NULL, IDE_AFLAG_FULL_CAPS_PAGE },
{ "WPI CDS-32X", NULL, IDE_AFLAG_FULL_CAPS_PAGE },
/* ACER/AOpen 24X CD-ROM has the speed fields byte-swapped. */
{ "", "241N", IDE_AFLAG_LE_SPEED_FIELDS },
/*
* Some drives used by Apple don't advertise audio play
* but they do support reading TOC & audio datas.
*/
{ "MATSHITADVD-ROM SR-8187", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "MATSHITADVD-ROM SR-8186", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "MATSHITADVD-ROM SR-8176", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "MATSHITADVD-ROM SR-8174", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "Optiarc DVD RW AD-5200A", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "Optiarc DVD RW AD-7200A", NULL, IDE_AFLAG_PLAY_AUDIO_OK },
{ "Optiarc DVD RW AD-7543A", NULL, IDE_AFLAG_NO_AUTOCLOSE },
{ "TEAC CD-ROM CD-224E", NULL, IDE_AFLAG_NO_AUTOCLOSE },
{ NULL, NULL, 0 }
};
static unsigned int ide_cd_flags(u16 *id)
{
const struct cd_list_entry *cle = ide_cd_quirks_list;
while (cle->id_model) {
if (strcmp(cle->id_model, (char *)&id[ATA_ID_PROD]) == 0 &&
(cle->id_firmware == NULL ||
strstr((char *)&id[ATA_ID_FW_REV], cle->id_firmware)))
return cle->cd_flags;
cle++;
}
return 0;
}
static int ide_cdrom_setup(ide_drive_t *drive)
{
struct cdrom_info *cd = drive->driver_data;
struct cdrom_device_info *cdi = &cd->devinfo;
struct request_queue *q = drive->queue;
u16 *id = drive->id;
char *fw_rev = (char *)&id[ATA_ID_FW_REV];
int nslots;
ide_debug_log(IDE_DBG_PROBE, "enter");
blk_queue_prep_rq(q, ide_cdrom_prep_fn);
blk_queue_dma_alignment(q, 31);
blk_queue_update_dma_pad(q, 15);
drive->dev_flags |= IDE_DFLAG_MEDIA_CHANGED;
drive->atapi_flags = IDE_AFLAG_NO_EJECT | ide_cd_flags(id);
if ((drive->atapi_flags & IDE_AFLAG_VERTOS_300_SSD) &&
fw_rev[4] == '1' && fw_rev[6] <= '2')
drive->atapi_flags |= (IDE_AFLAG_TOCTRACKS_AS_BCD |
IDE_AFLAG_TOCADDR_AS_BCD);
else if ((drive->atapi_flags & IDE_AFLAG_VERTOS_600_ESD) &&
fw_rev[4] == '1' && fw_rev[6] <= '2')
drive->atapi_flags |= IDE_AFLAG_TOCTRACKS_AS_BCD;
else if (drive->atapi_flags & IDE_AFLAG_SANYO_3CD)
/* 3 => use CD in slot 0 */
cdi->sanyo_slot = 3;
nslots = ide_cdrom_probe_capabilities(drive);
blk_queue_logical_block_size(q, CD_FRAMESIZE);
if (ide_cdrom_register(drive, nslots)) {
printk(KERN_ERR PFX "%s: %s failed to register device with the"
" cdrom driver.\n", drive->name, __func__);
cd->devinfo.handle = NULL;
return 1;
}
ide_proc_register_driver(drive, cd->driver);
return 0;
}
static void ide_cd_remove(ide_drive_t *drive)
{
struct cdrom_info *info = drive->driver_data;
ide_debug_log(IDE_DBG_FUNC, "enter");
ide_proc_unregister_driver(drive, info->driver);
device_del(&info->dev);
del_gendisk(info->disk);
mutex_lock(&idecd_ref_mutex);
put_device(&info->dev);
mutex_unlock(&idecd_ref_mutex);
}
static void ide_cd_release(struct device *dev)
{
struct cdrom_info *info = to_ide_drv(dev, cdrom_info);
struct cdrom_device_info *devinfo = &info->devinfo;
ide_drive_t *drive = info->drive;
struct gendisk *g = info->disk;
ide_debug_log(IDE_DBG_FUNC, "enter");
kfree(info->toc);
if (devinfo->handle == drive)
unregister_cdrom(devinfo);
drive->driver_data = NULL;
blk_queue_prep_rq(drive->queue, NULL);
g->private_data = NULL;
put_disk(g);
kfree(info);
}
static int ide_cd_probe(ide_drive_t *);
static struct ide_driver ide_cdrom_driver = {
.gen_driver = {
.owner = THIS_MODULE,
.name = "ide-cdrom",
.bus = &ide_bus_type,
},
.probe = ide_cd_probe,
.remove = ide_cd_remove,
.version = IDECD_VERSION,
.do_request = ide_cd_do_request,
#ifdef CONFIG_IDE_PROC_FS
.proc_entries = ide_cd_proc_entries,
.proc_devsets = ide_cd_proc_devsets,
#endif
};
static int idecd_open(struct block_device *bdev, fmode_t mode)
{
struct cdrom_info *info;
int rc = -ENXIO;
mutex_lock(&ide_cd_mutex);
info = ide_cd_get(bdev->bd_disk);
if (!info)
goto out;
rc = cdrom_open(&info->devinfo, bdev, mode);
if (rc < 0)
ide_cd_put(info);
out:
mutex_unlock(&ide_cd_mutex);
return rc;
}
static void idecd_release(struct gendisk *disk, fmode_t mode)
{
struct cdrom_info *info = ide_drv_g(disk, cdrom_info);
mutex_lock(&ide_cd_mutex);
cdrom_release(&info->devinfo, mode);
ide_cd_put(info);
mutex_unlock(&ide_cd_mutex);
}
static int idecd_set_spindown(struct cdrom_device_info *cdi, unsigned long arg)
{
struct packet_command cgc;
char buffer[16];
int stat;
char spindown;
if (copy_from_user(&spindown, (void __user *)arg, sizeof(char)))
return -EFAULT;
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_UNKNOWN);
stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CDROM_PAGE, 0);
if (stat)
return stat;
buffer[11] = (buffer[11] & 0xf0) | (spindown & 0x0f);
return cdrom_mode_select(cdi, &cgc);
}
static int idecd_get_spindown(struct cdrom_device_info *cdi, unsigned long arg)
{
struct packet_command cgc;
char buffer[16];
int stat;
char spindown;
init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_UNKNOWN);
stat = cdrom_mode_sense(cdi, &cgc, GPMODE_CDROM_PAGE, 0);
if (stat)
return stat;
spindown = buffer[11] & 0x0f;
if (copy_to_user((void __user *)arg, &spindown, sizeof(char)))
return -EFAULT;
return 0;
}
static int idecd_locked_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
struct cdrom_info *info = ide_drv_g(bdev->bd_disk, cdrom_info);
int err;
switch (cmd) {
case CDROMSETSPINDOWN:
return idecd_set_spindown(&info->devinfo, arg);
case CDROMGETSPINDOWN:
return idecd_get_spindown(&info->devinfo, arg);
default:
break;
}
err = generic_ide_ioctl(info->drive, bdev, cmd, arg);
if (err == -EINVAL)
err = cdrom_ioctl(&info->devinfo, bdev, mode, cmd, arg);
return err;
}
static int idecd_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
int ret;
mutex_lock(&ide_cd_mutex);
ret = idecd_locked_ioctl(bdev, mode, cmd, arg);
mutex_unlock(&ide_cd_mutex);
return ret;
}
static unsigned int idecd_check_events(struct gendisk *disk,
unsigned int clearing)
{
struct cdrom_info *info = ide_drv_g(disk, cdrom_info);
return cdrom_check_events(&info->devinfo, clearing);
}
static int idecd_revalidate_disk(struct gendisk *disk)
{
struct cdrom_info *info = ide_drv_g(disk, cdrom_info);
struct request_sense sense;
ide_cd_read_toc(info->drive, &sense);
return 0;
}
static const struct block_device_operations idecd_ops = {
.owner = THIS_MODULE,
.open = idecd_open,
.release = idecd_release,
.ioctl = idecd_ioctl,
.check_events = idecd_check_events,
.revalidate_disk = idecd_revalidate_disk
};
/* module options */
static unsigned long debug_mask;
module_param(debug_mask, ulong, 0644);
MODULE_DESCRIPTION("ATAPI CD-ROM Driver");
static int ide_cd_probe(ide_drive_t *drive)
{
struct cdrom_info *info;
struct gendisk *g;
struct request_sense sense;
ide_debug_log(IDE_DBG_PROBE, "driver_req: %s, media: 0x%x",
drive->driver_req, drive->media);
if (!strstr("ide-cdrom", drive->driver_req))
goto failed;
if (drive->media != ide_cdrom && drive->media != ide_optical)
goto failed;
drive->debug_mask = debug_mask;
drive->irq_handler = cdrom_newpc_intr;
info = kzalloc(sizeof(struct cdrom_info), GFP_KERNEL);
if (info == NULL) {
printk(KERN_ERR PFX "%s: Can't allocate a cdrom structure\n",
drive->name);
goto failed;
}
g = alloc_disk(1 << PARTN_BITS);
if (!g)
goto out_free_cd;
ide_init_disk(g, drive);
info->dev.parent = &drive->gendev;
info->dev.release = ide_cd_release;
dev_set_name(&info->dev, "%s", dev_name(&drive->gendev));
if (device_register(&info->dev))
goto out_free_disk;
info->drive = drive;
info->driver = &ide_cdrom_driver;
info->disk = g;
g->private_data = &info->driver;
drive->driver_data = info;
g->minors = 1;
g->driverfs_dev = &drive->gendev;
g->flags = GENHD_FL_CD | GENHD_FL_REMOVABLE;
if (ide_cdrom_setup(drive)) {
put_device(&info->dev);
goto failed;
}
ide_cd_read_toc(drive, &sense);
g->fops = &idecd_ops;
g->flags |= GENHD_FL_REMOVABLE | GENHD_FL_BLOCK_EVENTS_ON_EXCL_WRITE;
add_disk(g);
return 0;
out_free_disk:
put_disk(g);
out_free_cd:
kfree(info);
failed:
return -ENODEV;
}
static void __exit ide_cdrom_exit(void)
{
driver_unregister(&ide_cdrom_driver.gen_driver);
}
static int __init ide_cdrom_init(void)
{
printk(KERN_INFO DRV_NAME " driver " IDECD_VERSION "\n");
return driver_register(&ide_cdrom_driver.gen_driver);
}
MODULE_ALIAS("ide:*m-cdrom*");
MODULE_ALIAS("ide-cd");
module_init(ide_cdrom_init);
module_exit(ide_cdrom_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
GoinsWithTheWind/drm-prime-sync | sound/drivers/opl3/opl3_synth.c | 1926 | 16924 | /*
* Copyright (c) by Uros Bizjak <uros@kss-loka.si>
*
* Routines for OPL2/OPL3/OPL4 control
*
* 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/slab.h>
#include <linux/export.h>
#include <sound/opl3.h>
#include <sound/asound_fm.h>
#if IS_ENABLED(CONFIG_SND_SEQUENCER)
#define OPL3_SUPPORT_SYNTH
#endif
/*
* There is 18 possible 2 OP voices
* (9 in the left and 9 in the right).
* The first OP is the modulator and 2nd is the carrier.
*
* The first three voices in the both sides may be connected
* with another voice to a 4 OP voice. For example voice 0
* can be connected with voice 3. The operators of voice 3 are
* used as operators 3 and 4 of the new 4 OP voice.
* In this case the 2 OP voice number 0 is the 'first half' and
* voice 3 is the second.
*/
/*
* Register offset table for OPL2/3 voices,
* OPL2 / one OPL3 register array side only
*/
char snd_opl3_regmap[MAX_OPL2_VOICES][4] =
{
/* OP1 OP2 OP3 OP4 */
/* ------------------------ */
{ 0x00, 0x03, 0x08, 0x0b },
{ 0x01, 0x04, 0x09, 0x0c },
{ 0x02, 0x05, 0x0a, 0x0d },
{ 0x08, 0x0b, 0x00, 0x00 },
{ 0x09, 0x0c, 0x00, 0x00 },
{ 0x0a, 0x0d, 0x00, 0x00 },
{ 0x10, 0x13, 0x00, 0x00 }, /* used by percussive voices */
{ 0x11, 0x14, 0x00, 0x00 }, /* if the percussive mode */
{ 0x12, 0x15, 0x00, 0x00 } /* is selected (only left reg block) */
};
EXPORT_SYMBOL(snd_opl3_regmap);
/*
* prototypes
*/
static int snd_opl3_play_note(struct snd_opl3 * opl3, struct snd_dm_fm_note * note);
static int snd_opl3_set_voice(struct snd_opl3 * opl3, struct snd_dm_fm_voice * voice);
static int snd_opl3_set_params(struct snd_opl3 * opl3, struct snd_dm_fm_params * params);
static int snd_opl3_set_mode(struct snd_opl3 * opl3, int mode);
static int snd_opl3_set_connection(struct snd_opl3 * opl3, int connection);
/* ------------------------------ */
/*
* open the device exclusively
*/
int snd_opl3_open(struct snd_hwdep * hw, struct file *file)
{
return 0;
}
/*
* ioctl for hwdep device:
*/
int snd_opl3_ioctl(struct snd_hwdep * hw, struct file *file,
unsigned int cmd, unsigned long arg)
{
struct snd_opl3 *opl3 = hw->private_data;
void __user *argp = (void __user *)arg;
if (snd_BUG_ON(!opl3))
return -EINVAL;
switch (cmd) {
/* get information */
case SNDRV_DM_FM_IOCTL_INFO:
{
struct snd_dm_fm_info info;
info.fm_mode = opl3->fm_mode;
info.rhythm = opl3->rhythm;
if (copy_to_user(argp, &info, sizeof(struct snd_dm_fm_info)))
return -EFAULT;
return 0;
}
case SNDRV_DM_FM_IOCTL_RESET:
#ifdef CONFIG_SND_OSSEMUL
case SNDRV_DM_FM_OSS_IOCTL_RESET:
#endif
snd_opl3_reset(opl3);
return 0;
case SNDRV_DM_FM_IOCTL_PLAY_NOTE:
#ifdef CONFIG_SND_OSSEMUL
case SNDRV_DM_FM_OSS_IOCTL_PLAY_NOTE:
#endif
{
struct snd_dm_fm_note note;
if (copy_from_user(¬e, argp, sizeof(struct snd_dm_fm_note)))
return -EFAULT;
return snd_opl3_play_note(opl3, ¬e);
}
case SNDRV_DM_FM_IOCTL_SET_VOICE:
#ifdef CONFIG_SND_OSSEMUL
case SNDRV_DM_FM_OSS_IOCTL_SET_VOICE:
#endif
{
struct snd_dm_fm_voice voice;
if (copy_from_user(&voice, argp, sizeof(struct snd_dm_fm_voice)))
return -EFAULT;
return snd_opl3_set_voice(opl3, &voice);
}
case SNDRV_DM_FM_IOCTL_SET_PARAMS:
#ifdef CONFIG_SND_OSSEMUL
case SNDRV_DM_FM_OSS_IOCTL_SET_PARAMS:
#endif
{
struct snd_dm_fm_params params;
if (copy_from_user(¶ms, argp, sizeof(struct snd_dm_fm_params)))
return -EFAULT;
return snd_opl3_set_params(opl3, ¶ms);
}
case SNDRV_DM_FM_IOCTL_SET_MODE:
#ifdef CONFIG_SND_OSSEMUL
case SNDRV_DM_FM_OSS_IOCTL_SET_MODE:
#endif
return snd_opl3_set_mode(opl3, (int) arg);
case SNDRV_DM_FM_IOCTL_SET_CONNECTION:
#ifdef CONFIG_SND_OSSEMUL
case SNDRV_DM_FM_OSS_IOCTL_SET_OPL:
#endif
return snd_opl3_set_connection(opl3, (int) arg);
#ifdef OPL3_SUPPORT_SYNTH
case SNDRV_DM_FM_IOCTL_CLEAR_PATCHES:
snd_opl3_clear_patches(opl3);
return 0;
#endif
#ifdef CONFIG_SND_DEBUG
default:
snd_printk(KERN_WARNING "unknown IOCTL: 0x%x\n", cmd);
#endif
}
return -ENOTTY;
}
/*
* close the device
*/
int snd_opl3_release(struct snd_hwdep * hw, struct file *file)
{
struct snd_opl3 *opl3 = hw->private_data;
snd_opl3_reset(opl3);
return 0;
}
#ifdef OPL3_SUPPORT_SYNTH
/*
* write the device - load patches
*/
long snd_opl3_write(struct snd_hwdep *hw, const char __user *buf, long count,
loff_t *offset)
{
struct snd_opl3 *opl3 = hw->private_data;
long result = 0;
int err = 0;
struct sbi_patch inst;
while (count >= sizeof(inst)) {
unsigned char type;
if (copy_from_user(&inst, buf, sizeof(inst)))
return -EFAULT;
if (!memcmp(inst.key, FM_KEY_SBI, 4) ||
!memcmp(inst.key, FM_KEY_2OP, 4))
type = FM_PATCH_OPL2;
else if (!memcmp(inst.key, FM_KEY_4OP, 4))
type = FM_PATCH_OPL3;
else /* invalid type */
break;
err = snd_opl3_load_patch(opl3, inst.prog, inst.bank, type,
inst.name, inst.extension,
inst.data);
if (err < 0)
break;
result += sizeof(inst);
count -= sizeof(inst);
}
return result > 0 ? result : err;
}
/*
* Patch management
*/
/* offsets for SBI params */
#define AM_VIB 0
#define KSL_LEVEL 2
#define ATTACK_DECAY 4
#define SUSTAIN_RELEASE 6
#define WAVE_SELECT 8
/* offset for SBI instrument */
#define CONNECTION 10
#define OFFSET_4OP 11
/*
* load a patch, obviously.
*
* loaded on the given program and bank numbers with the given type
* (FM_PATCH_OPLx).
* data is the pointer of SBI record _without_ header (key and name).
* name is the name string of the patch.
* ext is the extension data of 7 bytes long (stored in name of SBI
* data up to offset 25), or NULL to skip.
* return 0 if successful or a negative error code.
*/
int snd_opl3_load_patch(struct snd_opl3 *opl3,
int prog, int bank, int type,
const char *name,
const unsigned char *ext,
const unsigned char *data)
{
struct fm_patch *patch;
int i;
patch = snd_opl3_find_patch(opl3, prog, bank, 1);
if (!patch)
return -ENOMEM;
patch->type = type;
for (i = 0; i < 2; i++) {
patch->inst.op[i].am_vib = data[AM_VIB + i];
patch->inst.op[i].ksl_level = data[KSL_LEVEL + i];
patch->inst.op[i].attack_decay = data[ATTACK_DECAY + i];
patch->inst.op[i].sustain_release = data[SUSTAIN_RELEASE + i];
patch->inst.op[i].wave_select = data[WAVE_SELECT + i];
}
patch->inst.feedback_connection[0] = data[CONNECTION];
if (type == FM_PATCH_OPL3) {
for (i = 0; i < 2; i++) {
patch->inst.op[i+2].am_vib =
data[OFFSET_4OP + AM_VIB + i];
patch->inst.op[i+2].ksl_level =
data[OFFSET_4OP + KSL_LEVEL + i];
patch->inst.op[i+2].attack_decay =
data[OFFSET_4OP + ATTACK_DECAY + i];
patch->inst.op[i+2].sustain_release =
data[OFFSET_4OP + SUSTAIN_RELEASE + i];
patch->inst.op[i+2].wave_select =
data[OFFSET_4OP + WAVE_SELECT + i];
}
patch->inst.feedback_connection[1] =
data[OFFSET_4OP + CONNECTION];
}
if (ext) {
patch->inst.echo_delay = ext[0];
patch->inst.echo_atten = ext[1];
patch->inst.chorus_spread = ext[2];
patch->inst.trnsps = ext[3];
patch->inst.fix_dur = ext[4];
patch->inst.modes = ext[5];
patch->inst.fix_key = ext[6];
}
if (name)
strlcpy(patch->name, name, sizeof(patch->name));
return 0;
}
EXPORT_SYMBOL(snd_opl3_load_patch);
/*
* find a patch with the given program and bank numbers, returns its pointer
* if no matching patch is found and create_patch is set, it creates a
* new patch object.
*/
struct fm_patch *snd_opl3_find_patch(struct snd_opl3 *opl3, int prog, int bank,
int create_patch)
{
/* pretty dumb hash key */
unsigned int key = (prog + bank) % OPL3_PATCH_HASH_SIZE;
struct fm_patch *patch;
for (patch = opl3->patch_table[key]; patch; patch = patch->next) {
if (patch->prog == prog && patch->bank == bank)
return patch;
}
if (!create_patch)
return NULL;
patch = kzalloc(sizeof(*patch), GFP_KERNEL);
if (!patch)
return NULL;
patch->prog = prog;
patch->bank = bank;
patch->next = opl3->patch_table[key];
opl3->patch_table[key] = patch;
return patch;
}
EXPORT_SYMBOL(snd_opl3_find_patch);
/*
* Clear all patches of the given OPL3 instance
*/
void snd_opl3_clear_patches(struct snd_opl3 *opl3)
{
int i;
for (i = 0; i < OPL3_PATCH_HASH_SIZE; i++) {
struct fm_patch *patch, *next;
for (patch = opl3->patch_table[i]; patch; patch = next) {
next = patch->next;
kfree(patch);
}
}
memset(opl3->patch_table, 0, sizeof(opl3->patch_table));
}
#endif /* OPL3_SUPPORT_SYNTH */
/* ------------------------------ */
void snd_opl3_reset(struct snd_opl3 * opl3)
{
unsigned short opl3_reg;
unsigned short reg_side;
unsigned char voice_offset;
int max_voices, i;
max_voices = (opl3->hardware < OPL3_HW_OPL3) ?
MAX_OPL2_VOICES : MAX_OPL3_VOICES;
for (i = 0; i < max_voices; i++) {
/* Get register array side and offset of voice */
if (i < MAX_OPL2_VOICES) {
/* Left register block for voices 0 .. 8 */
reg_side = OPL3_LEFT;
voice_offset = i;
} else {
/* Right register block for voices 9 .. 17 */
reg_side = OPL3_RIGHT;
voice_offset = i - MAX_OPL2_VOICES;
}
opl3_reg = reg_side | (OPL3_REG_KSL_LEVEL + snd_opl3_regmap[voice_offset][0]);
opl3->command(opl3, opl3_reg, OPL3_TOTAL_LEVEL_MASK); /* Operator 1 volume */
opl3_reg = reg_side | (OPL3_REG_KSL_LEVEL + snd_opl3_regmap[voice_offset][1]);
opl3->command(opl3, opl3_reg, OPL3_TOTAL_LEVEL_MASK); /* Operator 2 volume */
opl3_reg = reg_side | (OPL3_REG_KEYON_BLOCK + voice_offset);
opl3->command(opl3, opl3_reg, 0x00); /* Note off */
}
opl3->max_voices = MAX_OPL2_VOICES;
opl3->fm_mode = SNDRV_DM_FM_MODE_OPL2;
opl3->command(opl3, OPL3_LEFT | OPL3_REG_TEST, OPL3_ENABLE_WAVE_SELECT);
opl3->command(opl3, OPL3_LEFT | OPL3_REG_PERCUSSION, 0x00); /* Melodic mode */
opl3->rhythm = 0;
}
EXPORT_SYMBOL(snd_opl3_reset);
static int snd_opl3_play_note(struct snd_opl3 * opl3, struct snd_dm_fm_note * note)
{
unsigned short reg_side;
unsigned char voice_offset;
unsigned short opl3_reg;
unsigned char reg_val;
/* Voices 0 - 8 in OPL2 mode */
/* Voices 0 - 17 in OPL3 mode */
if (note->voice >= ((opl3->fm_mode == SNDRV_DM_FM_MODE_OPL3) ?
MAX_OPL3_VOICES : MAX_OPL2_VOICES))
return -EINVAL;
/* Get register array side and offset of voice */
if (note->voice < MAX_OPL2_VOICES) {
/* Left register block for voices 0 .. 8 */
reg_side = OPL3_LEFT;
voice_offset = note->voice;
} else {
/* Right register block for voices 9 .. 17 */
reg_side = OPL3_RIGHT;
voice_offset = note->voice - MAX_OPL2_VOICES;
}
/* Set lower 8 bits of note frequency */
reg_val = (unsigned char) note->fnum;
opl3_reg = reg_side | (OPL3_REG_FNUM_LOW + voice_offset);
opl3->command(opl3, opl3_reg, reg_val);
reg_val = 0x00;
/* Set output sound flag */
if (note->key_on)
reg_val |= OPL3_KEYON_BIT;
/* Set octave */
reg_val |= (note->octave << 2) & OPL3_BLOCKNUM_MASK;
/* Set higher 2 bits of note frequency */
reg_val |= (unsigned char) (note->fnum >> 8) & OPL3_FNUM_HIGH_MASK;
/* Set OPL3 KEYON_BLOCK register of requested voice */
opl3_reg = reg_side | (OPL3_REG_KEYON_BLOCK + voice_offset);
opl3->command(opl3, opl3_reg, reg_val);
return 0;
}
static int snd_opl3_set_voice(struct snd_opl3 * opl3, struct snd_dm_fm_voice * voice)
{
unsigned short reg_side;
unsigned char op_offset;
unsigned char voice_offset;
unsigned short opl3_reg;
unsigned char reg_val;
/* Only operators 1 and 2 */
if (voice->op > 1)
return -EINVAL;
/* Voices 0 - 8 in OPL2 mode */
/* Voices 0 - 17 in OPL3 mode */
if (voice->voice >= ((opl3->fm_mode == SNDRV_DM_FM_MODE_OPL3) ?
MAX_OPL3_VOICES : MAX_OPL2_VOICES))
return -EINVAL;
/* Get register array side and offset of voice */
if (voice->voice < MAX_OPL2_VOICES) {
/* Left register block for voices 0 .. 8 */
reg_side = OPL3_LEFT;
voice_offset = voice->voice;
} else {
/* Right register block for voices 9 .. 17 */
reg_side = OPL3_RIGHT;
voice_offset = voice->voice - MAX_OPL2_VOICES;
}
/* Get register offset of operator */
op_offset = snd_opl3_regmap[voice_offset][voice->op];
reg_val = 0x00;
/* Set amplitude modulation (tremolo) effect */
if (voice->am)
reg_val |= OPL3_TREMOLO_ON;
/* Set vibrato effect */
if (voice->vibrato)
reg_val |= OPL3_VIBRATO_ON;
/* Set sustaining sound phase */
if (voice->do_sustain)
reg_val |= OPL3_SUSTAIN_ON;
/* Set keyboard scaling bit */
if (voice->kbd_scale)
reg_val |= OPL3_KSR;
/* Set harmonic or frequency multiplier */
reg_val |= voice->harmonic & OPL3_MULTIPLE_MASK;
/* Set OPL3 AM_VIB register of requested voice/operator */
opl3_reg = reg_side | (OPL3_REG_AM_VIB + op_offset);
opl3->command(opl3, opl3_reg, reg_val);
/* Set decreasing volume of higher notes */
reg_val = (voice->scale_level << 6) & OPL3_KSL_MASK;
/* Set output volume */
reg_val |= ~voice->volume & OPL3_TOTAL_LEVEL_MASK;
/* Set OPL3 KSL_LEVEL register of requested voice/operator */
opl3_reg = reg_side | (OPL3_REG_KSL_LEVEL + op_offset);
opl3->command(opl3, opl3_reg, reg_val);
/* Set attack phase level */
reg_val = (voice->attack << 4) & OPL3_ATTACK_MASK;
/* Set decay phase level */
reg_val |= voice->decay & OPL3_DECAY_MASK;
/* Set OPL3 ATTACK_DECAY register of requested voice/operator */
opl3_reg = reg_side | (OPL3_REG_ATTACK_DECAY + op_offset);
opl3->command(opl3, opl3_reg, reg_val);
/* Set sustain phase level */
reg_val = (voice->sustain << 4) & OPL3_SUSTAIN_MASK;
/* Set release phase level */
reg_val |= voice->release & OPL3_RELEASE_MASK;
/* Set OPL3 SUSTAIN_RELEASE register of requested voice/operator */
opl3_reg = reg_side | (OPL3_REG_SUSTAIN_RELEASE + op_offset);
opl3->command(opl3, opl3_reg, reg_val);
/* Set inter-operator feedback */
reg_val = (voice->feedback << 1) & OPL3_FEEDBACK_MASK;
/* Set inter-operator connection */
if (voice->connection)
reg_val |= OPL3_CONNECTION_BIT;
/* OPL-3 only */
if (opl3->fm_mode == SNDRV_DM_FM_MODE_OPL3) {
if (voice->left)
reg_val |= OPL3_VOICE_TO_LEFT;
if (voice->right)
reg_val |= OPL3_VOICE_TO_RIGHT;
}
/* Feedback/connection bits are applicable to voice */
opl3_reg = reg_side | (OPL3_REG_FEEDBACK_CONNECTION + voice_offset);
opl3->command(opl3, opl3_reg, reg_val);
/* Select waveform */
reg_val = voice->waveform & OPL3_WAVE_SELECT_MASK;
opl3_reg = reg_side | (OPL3_REG_WAVE_SELECT + op_offset);
opl3->command(opl3, opl3_reg, reg_val);
return 0;
}
static int snd_opl3_set_params(struct snd_opl3 * opl3, struct snd_dm_fm_params * params)
{
unsigned char reg_val;
reg_val = 0x00;
/* Set keyboard split method */
if (params->kbd_split)
reg_val |= OPL3_KEYBOARD_SPLIT;
opl3->command(opl3, OPL3_LEFT | OPL3_REG_KBD_SPLIT, reg_val);
reg_val = 0x00;
/* Set amplitude modulation (tremolo) depth */
if (params->am_depth)
reg_val |= OPL3_TREMOLO_DEPTH;
/* Set vibrato depth */
if (params->vib_depth)
reg_val |= OPL3_VIBRATO_DEPTH;
/* Set percussion mode */
if (params->rhythm) {
reg_val |= OPL3_PERCUSSION_ENABLE;
opl3->rhythm = 1;
} else {
opl3->rhythm = 0;
}
/* Play percussion instruments */
if (params->bass)
reg_val |= OPL3_BASSDRUM_ON;
if (params->snare)
reg_val |= OPL3_SNAREDRUM_ON;
if (params->tomtom)
reg_val |= OPL3_TOMTOM_ON;
if (params->cymbal)
reg_val |= OPL3_CYMBAL_ON;
if (params->hihat)
reg_val |= OPL3_HIHAT_ON;
opl3->command(opl3, OPL3_LEFT | OPL3_REG_PERCUSSION, reg_val);
return 0;
}
static int snd_opl3_set_mode(struct snd_opl3 * opl3, int mode)
{
if ((mode == SNDRV_DM_FM_MODE_OPL3) && (opl3->hardware < OPL3_HW_OPL3))
return -EINVAL;
opl3->fm_mode = mode;
if (opl3->hardware >= OPL3_HW_OPL3)
opl3->command(opl3, OPL3_RIGHT | OPL3_REG_CONNECTION_SELECT, 0x00); /* Clear 4-op connections */
return 0;
}
static int snd_opl3_set_connection(struct snd_opl3 * opl3, int connection)
{
unsigned char reg_val;
/* OPL-3 only */
if (opl3->fm_mode != SNDRV_DM_FM_MODE_OPL3)
return -EINVAL;
reg_val = connection & (OPL3_RIGHT_4OP_0 | OPL3_RIGHT_4OP_1 | OPL3_RIGHT_4OP_2 |
OPL3_LEFT_4OP_0 | OPL3_LEFT_4OP_1 | OPL3_LEFT_4OP_2);
/* Set 4-op connections */
opl3->command(opl3, OPL3_RIGHT | OPL3_REG_CONNECTION_SELECT, reg_val);
return 0;
}
| gpl-2.0 |
GalaxyTab4/android_kernel_samsung_millet | arch/unicore32/mm/init.c | 3718 | 12947 | /*
* linux/arch/unicore32/mm/init.c
*
* Copyright (C) 2010 GUAN Xue-tao
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/swap.h>
#include <linux/init.h>
#include <linux/bootmem.h>
#include <linux/mman.h>
#include <linux/nodemask.h>
#include <linux/initrd.h>
#include <linux/highmem.h>
#include <linux/gfp.h>
#include <linux/memblock.h>
#include <linux/sort.h>
#include <linux/dma-mapping.h>
#include <linux/export.h>
#include <asm/sections.h>
#include <asm/setup.h>
#include <asm/sizes.h>
#include <asm/tlb.h>
#include <asm/memblock.h>
#include <mach/map.h>
#include "mm.h"
static unsigned long phys_initrd_start __initdata = 0x01000000;
static unsigned long phys_initrd_size __initdata = SZ_8M;
static int __init early_initrd(char *p)
{
unsigned long start, size;
char *endp;
start = memparse(p, &endp);
if (*endp == ',') {
size = memparse(endp + 1, NULL);
phys_initrd_start = start;
phys_initrd_size = size;
}
return 0;
}
early_param("initrd", early_initrd);
/*
* This keeps memory configuration data used by a couple memory
* initialization functions, as well as show_mem() for the skipping
* of holes in the memory map. It is populated by uc32_add_memory().
*/
struct meminfo meminfo;
void show_mem(unsigned int filter)
{
int free = 0, total = 0, reserved = 0;
int shared = 0, cached = 0, slab = 0, i;
struct meminfo *mi = &meminfo;
printk(KERN_DEFAULT "Mem-info:\n");
show_free_areas(filter);
for_each_bank(i, mi) {
struct membank *bank = &mi->bank[i];
unsigned int pfn1, pfn2;
struct page *page, *end;
pfn1 = bank_pfn_start(bank);
pfn2 = bank_pfn_end(bank);
page = pfn_to_page(pfn1);
end = pfn_to_page(pfn2 - 1) + 1;
do {
total++;
if (PageReserved(page))
reserved++;
else if (PageSwapCache(page))
cached++;
else if (PageSlab(page))
slab++;
else if (!page_count(page))
free++;
else
shared += page_count(page) - 1;
page++;
} while (page < end);
}
printk(KERN_DEFAULT "%d pages of RAM\n", total);
printk(KERN_DEFAULT "%d free pages\n", free);
printk(KERN_DEFAULT "%d reserved pages\n", reserved);
printk(KERN_DEFAULT "%d slab pages\n", slab);
printk(KERN_DEFAULT "%d pages shared\n", shared);
printk(KERN_DEFAULT "%d pages swap cached\n", cached);
}
static void __init find_limits(unsigned long *min, unsigned long *max_low,
unsigned long *max_high)
{
struct meminfo *mi = &meminfo;
int i;
*min = -1UL;
*max_low = *max_high = 0;
for_each_bank(i, mi) {
struct membank *bank = &mi->bank[i];
unsigned long start, end;
start = bank_pfn_start(bank);
end = bank_pfn_end(bank);
if (*min > start)
*min = start;
if (*max_high < end)
*max_high = end;
if (bank->highmem)
continue;
if (*max_low < end)
*max_low = end;
}
}
static void __init uc32_bootmem_init(unsigned long start_pfn,
unsigned long end_pfn)
{
struct memblock_region *reg;
unsigned int boot_pages;
phys_addr_t bitmap;
pg_data_t *pgdat;
/*
* Allocate the bootmem bitmap page. This must be in a region
* of memory which has already been mapped.
*/
boot_pages = bootmem_bootmap_pages(end_pfn - start_pfn);
bitmap = memblock_alloc_base(boot_pages << PAGE_SHIFT, L1_CACHE_BYTES,
__pfn_to_phys(end_pfn));
/*
* Initialise the bootmem allocator, handing the
* memory banks over to bootmem.
*/
node_set_online(0);
pgdat = NODE_DATA(0);
init_bootmem_node(pgdat, __phys_to_pfn(bitmap), start_pfn, end_pfn);
/* Free the lowmem regions from memblock into bootmem. */
for_each_memblock(memory, reg) {
unsigned long start = memblock_region_memory_base_pfn(reg);
unsigned long end = memblock_region_memory_end_pfn(reg);
if (end >= end_pfn)
end = end_pfn;
if (start >= end)
break;
free_bootmem(__pfn_to_phys(start), (end - start) << PAGE_SHIFT);
}
/* Reserve the lowmem memblock reserved regions in bootmem. */
for_each_memblock(reserved, reg) {
unsigned long start = memblock_region_reserved_base_pfn(reg);
unsigned long end = memblock_region_reserved_end_pfn(reg);
if (end >= end_pfn)
end = end_pfn;
if (start >= end)
break;
reserve_bootmem(__pfn_to_phys(start),
(end - start) << PAGE_SHIFT, BOOTMEM_DEFAULT);
}
}
static void __init uc32_bootmem_free(unsigned long min, unsigned long max_low,
unsigned long max_high)
{
unsigned long zone_size[MAX_NR_ZONES], zhole_size[MAX_NR_ZONES];
struct memblock_region *reg;
/*
* initialise the zones.
*/
memset(zone_size, 0, sizeof(zone_size));
/*
* The memory size has already been determined. If we need
* to do anything fancy with the allocation of this memory
* to the zones, now is the time to do it.
*/
zone_size[0] = max_low - min;
/*
* Calculate the size of the holes.
* holes = node_size - sum(bank_sizes)
*/
memcpy(zhole_size, zone_size, sizeof(zhole_size));
for_each_memblock(memory, reg) {
unsigned long start = memblock_region_memory_base_pfn(reg);
unsigned long end = memblock_region_memory_end_pfn(reg);
if (start < max_low) {
unsigned long low_end = min(end, max_low);
zhole_size[0] -= low_end - start;
}
}
/*
* Adjust the sizes according to any special requirements for
* this machine type.
*/
arch_adjust_zones(zone_size, zhole_size);
free_area_init_node(0, zone_size, min, zhole_size);
}
int pfn_valid(unsigned long pfn)
{
return memblock_is_memory(pfn << PAGE_SHIFT);
}
EXPORT_SYMBOL(pfn_valid);
static void uc32_memory_present(void)
{
}
static int __init meminfo_cmp(const void *_a, const void *_b)
{
const struct membank *a = _a, *b = _b;
long cmp = bank_pfn_start(a) - bank_pfn_start(b);
return cmp < 0 ? -1 : cmp > 0 ? 1 : 0;
}
void __init uc32_memblock_init(struct meminfo *mi)
{
int i;
sort(&meminfo.bank, meminfo.nr_banks, sizeof(meminfo.bank[0]),
meminfo_cmp, NULL);
for (i = 0; i < mi->nr_banks; i++)
memblock_add(mi->bank[i].start, mi->bank[i].size);
/* Register the kernel text, kernel data and initrd with memblock. */
memblock_reserve(__pa(_text), _end - _text);
#ifdef CONFIG_BLK_DEV_INITRD
if (phys_initrd_size) {
memblock_reserve(phys_initrd_start, phys_initrd_size);
/* Now convert initrd to virtual addresses */
initrd_start = __phys_to_virt(phys_initrd_start);
initrd_end = initrd_start + phys_initrd_size;
}
#endif
uc32_mm_memblock_reserve();
memblock_allow_resize();
memblock_dump_all();
}
void __init bootmem_init(void)
{
unsigned long min, max_low, max_high;
max_low = max_high = 0;
find_limits(&min, &max_low, &max_high);
uc32_bootmem_init(min, max_low);
#ifdef CONFIG_SWIOTLB
swiotlb_init(1);
#endif
/*
* Sparsemem tries to allocate bootmem in memory_present(),
* so must be done after the fixed reservations
*/
uc32_memory_present();
/*
* sparse_init() needs the bootmem allocator up and running.
*/
sparse_init();
/*
* Now free the memory - free_area_init_node needs
* the sparse mem_map arrays initialized by sparse_init()
* for memmap_init_zone(), otherwise all PFNs are invalid.
*/
uc32_bootmem_free(min, max_low, max_high);
high_memory = __va((max_low << PAGE_SHIFT) - 1) + 1;
/*
* This doesn't seem to be used by the Linux memory manager any
* more, but is used by ll_rw_block. If we can get rid of it, we
* also get rid of some of the stuff above as well.
*
* Note: max_low_pfn and max_pfn reflect the number of _pages_ in
* the system, not the maximum PFN.
*/
max_low_pfn = max_low - PHYS_PFN_OFFSET;
max_pfn = max_high - PHYS_PFN_OFFSET;
}
static inline int free_area(unsigned long pfn, unsigned long end, char *s)
{
unsigned int pages = 0, size = (end - pfn) << (PAGE_SHIFT - 10);
for (; pfn < end; pfn++) {
struct page *page = pfn_to_page(pfn);
ClearPageReserved(page);
init_page_count(page);
__free_page(page);
pages++;
}
if (size && s)
printk(KERN_INFO "Freeing %s memory: %dK\n", s, size);
return pages;
}
static inline void
free_memmap(unsigned long start_pfn, unsigned long end_pfn)
{
struct page *start_pg, *end_pg;
unsigned long pg, pgend;
/*
* Convert start_pfn/end_pfn to a struct page pointer.
*/
start_pg = pfn_to_page(start_pfn - 1) + 1;
end_pg = pfn_to_page(end_pfn);
/*
* Convert to physical addresses, and
* round start upwards and end downwards.
*/
pg = PAGE_ALIGN(__pa(start_pg));
pgend = __pa(end_pg) & PAGE_MASK;
/*
* If there are free pages between these,
* free the section of the memmap array.
*/
if (pg < pgend)
free_bootmem(pg, pgend - pg);
}
/*
* The mem_map array can get very big. Free the unused area of the memory map.
*/
static void __init free_unused_memmap(struct meminfo *mi)
{
unsigned long bank_start, prev_bank_end = 0;
unsigned int i;
/*
* This relies on each bank being in address order.
* The banks are sorted previously in bootmem_init().
*/
for_each_bank(i, mi) {
struct membank *bank = &mi->bank[i];
bank_start = bank_pfn_start(bank);
/*
* If we had a previous bank, and there is a space
* between the current bank and the previous, free it.
*/
if (prev_bank_end && prev_bank_end < bank_start)
free_memmap(prev_bank_end, bank_start);
/*
* Align up here since the VM subsystem insists that the
* memmap entries are valid from the bank end aligned to
* MAX_ORDER_NR_PAGES.
*/
prev_bank_end = ALIGN(bank_pfn_end(bank), MAX_ORDER_NR_PAGES);
}
}
/*
* mem_init() marks the free areas in the mem_map and tells us how much
* memory is free. This is done after various parts of the system have
* claimed their memory after the kernel image.
*/
void __init mem_init(void)
{
unsigned long reserved_pages, free_pages;
struct memblock_region *reg;
int i;
max_mapnr = pfn_to_page(max_pfn + PHYS_PFN_OFFSET) - mem_map;
/* this will put all unused low memory onto the freelists */
free_unused_memmap(&meminfo);
totalram_pages += free_all_bootmem();
reserved_pages = free_pages = 0;
for_each_bank(i, &meminfo) {
struct membank *bank = &meminfo.bank[i];
unsigned int pfn1, pfn2;
struct page *page, *end;
pfn1 = bank_pfn_start(bank);
pfn2 = bank_pfn_end(bank);
page = pfn_to_page(pfn1);
end = pfn_to_page(pfn2 - 1) + 1;
do {
if (PageReserved(page))
reserved_pages++;
else if (!page_count(page))
free_pages++;
page++;
} while (page < end);
}
/*
* Since our memory may not be contiguous, calculate the
* real number of pages we have in this system
*/
printk(KERN_INFO "Memory:");
num_physpages = 0;
for_each_memblock(memory, reg) {
unsigned long pages = memblock_region_memory_end_pfn(reg) -
memblock_region_memory_base_pfn(reg);
num_physpages += pages;
printk(" %ldMB", pages >> (20 - PAGE_SHIFT));
}
printk(" = %luMB total\n", num_physpages >> (20 - PAGE_SHIFT));
printk(KERN_NOTICE "Memory: %luk/%luk available, %luk reserved, %luK highmem\n",
nr_free_pages() << (PAGE_SHIFT-10),
free_pages << (PAGE_SHIFT-10),
reserved_pages << (PAGE_SHIFT-10),
totalhigh_pages << (PAGE_SHIFT-10));
printk(KERN_NOTICE "Virtual kernel memory layout:\n"
" vector : 0x%08lx - 0x%08lx (%4ld kB)\n"
" vmalloc : 0x%08lx - 0x%08lx (%4ld MB)\n"
" lowmem : 0x%08lx - 0x%08lx (%4ld MB)\n"
" modules : 0x%08lx - 0x%08lx (%4ld MB)\n"
" .init : 0x%p" " - 0x%p" " (%4d kB)\n"
" .text : 0x%p" " - 0x%p" " (%4d kB)\n"
" .data : 0x%p" " - 0x%p" " (%4d kB)\n",
VECTORS_BASE, VECTORS_BASE + PAGE_SIZE,
DIV_ROUND_UP(PAGE_SIZE, SZ_1K),
VMALLOC_START, VMALLOC_END,
DIV_ROUND_UP((VMALLOC_END - VMALLOC_START), SZ_1M),
PAGE_OFFSET, (unsigned long)high_memory,
DIV_ROUND_UP(((unsigned long)high_memory - PAGE_OFFSET), SZ_1M),
MODULES_VADDR, MODULES_END,
DIV_ROUND_UP((MODULES_END - MODULES_VADDR), SZ_1M),
__init_begin, __init_end,
DIV_ROUND_UP((__init_end - __init_begin), SZ_1K),
_stext, _etext,
DIV_ROUND_UP((_etext - _stext), SZ_1K),
_sdata, _edata,
DIV_ROUND_UP((_edata - _sdata), SZ_1K));
BUILD_BUG_ON(TASK_SIZE > MODULES_VADDR);
BUG_ON(TASK_SIZE > MODULES_VADDR);
if (PAGE_SIZE >= 16384 && num_physpages <= 128) {
/*
* On a machine this small we won't get
* anywhere without overcommit, so turn
* it on by default.
*/
sysctl_overcommit_memory = OVERCOMMIT_ALWAYS;
}
}
void free_initmem(void)
{
totalram_pages += free_area(__phys_to_pfn(__pa(__init_begin)),
__phys_to_pfn(__pa(__init_end)),
"init");
}
#ifdef CONFIG_BLK_DEV_INITRD
static int keep_initrd;
void free_initrd_mem(unsigned long start, unsigned long end)
{
if (!keep_initrd)
totalram_pages += free_area(__phys_to_pfn(__pa(start)),
__phys_to_pfn(__pa(end)),
"initrd");
}
static int __init keepinitrd_setup(char *__unused)
{
keep_initrd = 1;
return 1;
}
__setup("keepinitrd", keepinitrd_setup);
#endif
| gpl-2.0 |
Myself5/android_kernel_sony_nbx03 | drivers/leds/leds-wrap.c | 4742 | 3300 | /*
* LEDs driver for PCEngines WRAP
*
* Copyright (C) 2006 Kristian Kielhofner <kris@krisk.org>
*
* Based on leds-net48xx.c
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/leds.h>
#include <linux/err.h>
#include <asm/io.h>
#include <linux/scx200_gpio.h>
#define DRVNAME "wrap-led"
#define WRAP_POWER_LED_GPIO 2
#define WRAP_ERROR_LED_GPIO 3
#define WRAP_EXTRA_LED_GPIO 18
static struct platform_device *pdev;
static void wrap_power_led_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
if (value)
scx200_gpio_set_low(WRAP_POWER_LED_GPIO);
else
scx200_gpio_set_high(WRAP_POWER_LED_GPIO);
}
static void wrap_error_led_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
if (value)
scx200_gpio_set_low(WRAP_ERROR_LED_GPIO);
else
scx200_gpio_set_high(WRAP_ERROR_LED_GPIO);
}
static void wrap_extra_led_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
if (value)
scx200_gpio_set_low(WRAP_EXTRA_LED_GPIO);
else
scx200_gpio_set_high(WRAP_EXTRA_LED_GPIO);
}
static struct led_classdev wrap_power_led = {
.name = "wrap::power",
.brightness_set = wrap_power_led_set,
.default_trigger = "default-on",
.flags = LED_CORE_SUSPENDRESUME,
};
static struct led_classdev wrap_error_led = {
.name = "wrap::error",
.brightness_set = wrap_error_led_set,
.flags = LED_CORE_SUSPENDRESUME,
};
static struct led_classdev wrap_extra_led = {
.name = "wrap::extra",
.brightness_set = wrap_extra_led_set,
.flags = LED_CORE_SUSPENDRESUME,
};
static int wrap_led_probe(struct platform_device *pdev)
{
int ret;
ret = led_classdev_register(&pdev->dev, &wrap_power_led);
if (ret < 0)
return ret;
ret = led_classdev_register(&pdev->dev, &wrap_error_led);
if (ret < 0)
goto err1;
ret = led_classdev_register(&pdev->dev, &wrap_extra_led);
if (ret < 0)
goto err2;
return ret;
err2:
led_classdev_unregister(&wrap_error_led);
err1:
led_classdev_unregister(&wrap_power_led);
return ret;
}
static int wrap_led_remove(struct platform_device *pdev)
{
led_classdev_unregister(&wrap_power_led);
led_classdev_unregister(&wrap_error_led);
led_classdev_unregister(&wrap_extra_led);
return 0;
}
static struct platform_driver wrap_led_driver = {
.probe = wrap_led_probe,
.remove = wrap_led_remove,
.driver = {
.name = DRVNAME,
.owner = THIS_MODULE,
},
};
static int __init wrap_led_init(void)
{
int ret;
if (!scx200_gpio_present()) {
ret = -ENODEV;
goto out;
}
ret = platform_driver_register(&wrap_led_driver);
if (ret < 0)
goto out;
pdev = platform_device_register_simple(DRVNAME, -1, NULL, 0);
if (IS_ERR(pdev)) {
ret = PTR_ERR(pdev);
platform_driver_unregister(&wrap_led_driver);
goto out;
}
out:
return ret;
}
static void __exit wrap_led_exit(void)
{
platform_device_unregister(pdev);
platform_driver_unregister(&wrap_led_driver);
}
module_init(wrap_led_init);
module_exit(wrap_led_exit);
MODULE_AUTHOR("Kristian Kielhofner <kris@krisk.org>");
MODULE_DESCRIPTION("PCEngines WRAP LED driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
xXminiWHOOPERxX/dlxpul-kernel-final | fs/gfs2/lock_dlm.c | 4742 | 39187 | /*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright 2004-2011 Red Hat, Inc.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*/
#include <linux/fs.h>
#include <linux/dlm.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/delay.h>
#include <linux/gfs2_ondisk.h>
#include "incore.h"
#include "glock.h"
#include "util.h"
#include "sys.h"
#include "trace_gfs2.h"
extern struct workqueue_struct *gfs2_control_wq;
/**
* gfs2_update_stats - Update time based stats
* @mv: Pointer to mean/variance structure to update
* @sample: New data to include
*
* @delta is the difference between the current rtt sample and the
* running average srtt. We add 1/8 of that to the srtt in order to
* update the current srtt estimate. The varience estimate is a bit
* more complicated. We subtract the abs value of the @delta from
* the current variance estimate and add 1/4 of that to the running
* total.
*
* Note that the index points at the array entry containing the smoothed
* mean value, and the variance is always in the following entry
*
* Reference: TCP/IP Illustrated, vol 2, p. 831,832
* All times are in units of integer nanoseconds. Unlike the TCP/IP case,
* they are not scaled fixed point.
*/
static inline void gfs2_update_stats(struct gfs2_lkstats *s, unsigned index,
s64 sample)
{
s64 delta = sample - s->stats[index];
s->stats[index] += (delta >> 3);
index++;
s->stats[index] += ((abs64(delta) - s->stats[index]) >> 2);
}
/**
* gfs2_update_reply_times - Update locking statistics
* @gl: The glock to update
*
* This assumes that gl->gl_dstamp has been set earlier.
*
* The rtt (lock round trip time) is an estimate of the time
* taken to perform a dlm lock request. We update it on each
* reply from the dlm.
*
* The blocking flag is set on the glock for all dlm requests
* which may potentially block due to lock requests from other nodes.
* DLM requests where the current lock state is exclusive, the
* requested state is null (or unlocked) or where the TRY or
* TRY_1CB flags are set are classified as non-blocking. All
* other DLM requests are counted as (potentially) blocking.
*/
static inline void gfs2_update_reply_times(struct gfs2_glock *gl)
{
struct gfs2_pcpu_lkstats *lks;
const unsigned gltype = gl->gl_name.ln_type;
unsigned index = test_bit(GLF_BLOCKING, &gl->gl_flags) ?
GFS2_LKS_SRTTB : GFS2_LKS_SRTT;
s64 rtt;
preempt_disable();
rtt = ktime_to_ns(ktime_sub(ktime_get_real(), gl->gl_dstamp));
lks = this_cpu_ptr(gl->gl_sbd->sd_lkstats);
gfs2_update_stats(&gl->gl_stats, index, rtt); /* Local */
gfs2_update_stats(&lks->lkstats[gltype], index, rtt); /* Global */
preempt_enable();
trace_gfs2_glock_lock_time(gl, rtt);
}
/**
* gfs2_update_request_times - Update locking statistics
* @gl: The glock to update
*
* The irt (lock inter-request times) measures the average time
* between requests to the dlm. It is updated immediately before
* each dlm call.
*/
static inline void gfs2_update_request_times(struct gfs2_glock *gl)
{
struct gfs2_pcpu_lkstats *lks;
const unsigned gltype = gl->gl_name.ln_type;
ktime_t dstamp;
s64 irt;
preempt_disable();
dstamp = gl->gl_dstamp;
gl->gl_dstamp = ktime_get_real();
irt = ktime_to_ns(ktime_sub(gl->gl_dstamp, dstamp));
lks = this_cpu_ptr(gl->gl_sbd->sd_lkstats);
gfs2_update_stats(&gl->gl_stats, GFS2_LKS_SIRT, irt); /* Local */
gfs2_update_stats(&lks->lkstats[gltype], GFS2_LKS_SIRT, irt); /* Global */
preempt_enable();
}
static void gdlm_ast(void *arg)
{
struct gfs2_glock *gl = arg;
unsigned ret = gl->gl_state;
gfs2_update_reply_times(gl);
BUG_ON(gl->gl_lksb.sb_flags & DLM_SBF_DEMOTED);
if (gl->gl_lksb.sb_flags & DLM_SBF_VALNOTVALID)
memset(gl->gl_lvb, 0, GDLM_LVB_SIZE);
switch (gl->gl_lksb.sb_status) {
case -DLM_EUNLOCK: /* Unlocked, so glock can be freed */
gfs2_glock_free(gl);
return;
case -DLM_ECANCEL: /* Cancel while getting lock */
ret |= LM_OUT_CANCELED;
goto out;
case -EAGAIN: /* Try lock fails */
case -EDEADLK: /* Deadlock detected */
goto out;
case -ETIMEDOUT: /* Canceled due to timeout */
ret |= LM_OUT_ERROR;
goto out;
case 0: /* Success */
break;
default: /* Something unexpected */
BUG();
}
ret = gl->gl_req;
if (gl->gl_lksb.sb_flags & DLM_SBF_ALTMODE) {
if (gl->gl_req == LM_ST_SHARED)
ret = LM_ST_DEFERRED;
else if (gl->gl_req == LM_ST_DEFERRED)
ret = LM_ST_SHARED;
else
BUG();
}
set_bit(GLF_INITIAL, &gl->gl_flags);
gfs2_glock_complete(gl, ret);
return;
out:
if (!test_bit(GLF_INITIAL, &gl->gl_flags))
gl->gl_lksb.sb_lkid = 0;
gfs2_glock_complete(gl, ret);
}
static void gdlm_bast(void *arg, int mode)
{
struct gfs2_glock *gl = arg;
switch (mode) {
case DLM_LOCK_EX:
gfs2_glock_cb(gl, LM_ST_UNLOCKED);
break;
case DLM_LOCK_CW:
gfs2_glock_cb(gl, LM_ST_DEFERRED);
break;
case DLM_LOCK_PR:
gfs2_glock_cb(gl, LM_ST_SHARED);
break;
default:
printk(KERN_ERR "unknown bast mode %d", mode);
BUG();
}
}
/* convert gfs lock-state to dlm lock-mode */
static int make_mode(const unsigned int lmstate)
{
switch (lmstate) {
case LM_ST_UNLOCKED:
return DLM_LOCK_NL;
case LM_ST_EXCLUSIVE:
return DLM_LOCK_EX;
case LM_ST_DEFERRED:
return DLM_LOCK_CW;
case LM_ST_SHARED:
return DLM_LOCK_PR;
}
printk(KERN_ERR "unknown LM state %d", lmstate);
BUG();
return -1;
}
static u32 make_flags(struct gfs2_glock *gl, const unsigned int gfs_flags,
const int req)
{
u32 lkf = DLM_LKF_VALBLK;
u32 lkid = gl->gl_lksb.sb_lkid;
if (gfs_flags & LM_FLAG_TRY)
lkf |= DLM_LKF_NOQUEUE;
if (gfs_flags & LM_FLAG_TRY_1CB) {
lkf |= DLM_LKF_NOQUEUE;
lkf |= DLM_LKF_NOQUEUEBAST;
}
if (gfs_flags & LM_FLAG_PRIORITY) {
lkf |= DLM_LKF_NOORDER;
lkf |= DLM_LKF_HEADQUE;
}
if (gfs_flags & LM_FLAG_ANY) {
if (req == DLM_LOCK_PR)
lkf |= DLM_LKF_ALTCW;
else if (req == DLM_LOCK_CW)
lkf |= DLM_LKF_ALTPR;
else
BUG();
}
if (lkid != 0) {
lkf |= DLM_LKF_CONVERT;
if (test_bit(GLF_BLOCKING, &gl->gl_flags))
lkf |= DLM_LKF_QUECVT;
}
return lkf;
}
static void gfs2_reverse_hex(char *c, u64 value)
{
while (value) {
*c-- = hex_asc[value & 0x0f];
value >>= 4;
}
}
static int gdlm_lock(struct gfs2_glock *gl, unsigned int req_state,
unsigned int flags)
{
struct lm_lockstruct *ls = &gl->gl_sbd->sd_lockstruct;
int req;
u32 lkf;
char strname[GDLM_STRNAME_BYTES] = "";
req = make_mode(req_state);
lkf = make_flags(gl, flags, req);
gfs2_glstats_inc(gl, GFS2_LKS_DCOUNT);
gfs2_sbstats_inc(gl, GFS2_LKS_DCOUNT);
if (gl->gl_lksb.sb_lkid) {
gfs2_update_request_times(gl);
} else {
memset(strname, ' ', GDLM_STRNAME_BYTES - 1);
strname[GDLM_STRNAME_BYTES - 1] = '\0';
gfs2_reverse_hex(strname + 7, gl->gl_name.ln_type);
gfs2_reverse_hex(strname + 23, gl->gl_name.ln_number);
gl->gl_dstamp = ktime_get_real();
}
/*
* Submit the actual lock request.
*/
return dlm_lock(ls->ls_dlm, req, &gl->gl_lksb, lkf, strname,
GDLM_STRNAME_BYTES - 1, 0, gdlm_ast, gl, gdlm_bast);
}
static void gdlm_put_lock(struct gfs2_glock *gl)
{
struct gfs2_sbd *sdp = gl->gl_sbd;
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
int error;
if (gl->gl_lksb.sb_lkid == 0) {
gfs2_glock_free(gl);
return;
}
clear_bit(GLF_BLOCKING, &gl->gl_flags);
gfs2_glstats_inc(gl, GFS2_LKS_DCOUNT);
gfs2_sbstats_inc(gl, GFS2_LKS_DCOUNT);
gfs2_update_request_times(gl);
error = dlm_unlock(ls->ls_dlm, gl->gl_lksb.sb_lkid, DLM_LKF_VALBLK,
NULL, gl);
if (error) {
printk(KERN_ERR "gdlm_unlock %x,%llx err=%d\n",
gl->gl_name.ln_type,
(unsigned long long)gl->gl_name.ln_number, error);
return;
}
}
static void gdlm_cancel(struct gfs2_glock *gl)
{
struct lm_lockstruct *ls = &gl->gl_sbd->sd_lockstruct;
dlm_unlock(ls->ls_dlm, gl->gl_lksb.sb_lkid, DLM_LKF_CANCEL, NULL, gl);
}
/*
* dlm/gfs2 recovery coordination using dlm_recover callbacks
*
* 1. dlm_controld sees lockspace members change
* 2. dlm_controld blocks dlm-kernel locking activity
* 3. dlm_controld within dlm-kernel notifies gfs2 (recover_prep)
* 4. dlm_controld starts and finishes its own user level recovery
* 5. dlm_controld starts dlm-kernel dlm_recoverd to do kernel recovery
* 6. dlm_recoverd notifies gfs2 of failed nodes (recover_slot)
* 7. dlm_recoverd does its own lock recovery
* 8. dlm_recoverd unblocks dlm-kernel locking activity
* 9. dlm_recoverd notifies gfs2 when done (recover_done with new generation)
* 10. gfs2_control updates control_lock lvb with new generation and jid bits
* 11. gfs2_control enqueues journals for gfs2_recover to recover (maybe none)
* 12. gfs2_recover dequeues and recovers journals of failed nodes
* 13. gfs2_recover provides recovery results to gfs2_control (recovery_result)
* 14. gfs2_control updates control_lock lvb jid bits for recovered journals
* 15. gfs2_control unblocks normal locking when all journals are recovered
*
* - failures during recovery
*
* recover_prep() may set BLOCK_LOCKS (step 3) again before gfs2_control
* clears BLOCK_LOCKS (step 15), e.g. another node fails while still
* recovering for a prior failure. gfs2_control needs a way to detect
* this so it can leave BLOCK_LOCKS set in step 15. This is managed using
* the recover_block and recover_start values.
*
* recover_done() provides a new lockspace generation number each time it
* is called (step 9). This generation number is saved as recover_start.
* When recover_prep() is called, it sets BLOCK_LOCKS and sets
* recover_block = recover_start. So, while recover_block is equal to
* recover_start, BLOCK_LOCKS should remain set. (recover_spin must
* be held around the BLOCK_LOCKS/recover_block/recover_start logic.)
*
* - more specific gfs2 steps in sequence above
*
* 3. recover_prep sets BLOCK_LOCKS and sets recover_block = recover_start
* 6. recover_slot records any failed jids (maybe none)
* 9. recover_done sets recover_start = new generation number
* 10. gfs2_control sets control_lock lvb = new gen + bits for failed jids
* 12. gfs2_recover does journal recoveries for failed jids identified above
* 14. gfs2_control clears control_lock lvb bits for recovered jids
* 15. gfs2_control checks if recover_block == recover_start (step 3 occured
* again) then do nothing, otherwise if recover_start > recover_block
* then clear BLOCK_LOCKS.
*
* - parallel recovery steps across all nodes
*
* All nodes attempt to update the control_lock lvb with the new generation
* number and jid bits, but only the first to get the control_lock EX will
* do so; others will see that it's already done (lvb already contains new
* generation number.)
*
* . All nodes get the same recover_prep/recover_slot/recover_done callbacks
* . All nodes attempt to set control_lock lvb gen + bits for the new gen
* . One node gets control_lock first and writes the lvb, others see it's done
* . All nodes attempt to recover jids for which they see control_lock bits set
* . One node succeeds for a jid, and that one clears the jid bit in the lvb
* . All nodes will eventually see all lvb bits clear and unblock locks
*
* - is there a problem with clearing an lvb bit that should be set
* and missing a journal recovery?
*
* 1. jid fails
* 2. lvb bit set for step 1
* 3. jid recovered for step 1
* 4. jid taken again (new mount)
* 5. jid fails (for step 4)
* 6. lvb bit set for step 5 (will already be set)
* 7. lvb bit cleared for step 3
*
* This is not a problem because the failure in step 5 does not
* require recovery, because the mount in step 4 could not have
* progressed far enough to unblock locks and access the fs. The
* control_mount() function waits for all recoveries to be complete
* for the latest lockspace generation before ever unblocking locks
* and returning. The mount in step 4 waits until the recovery in
* step 1 is done.
*
* - special case of first mounter: first node to mount the fs
*
* The first node to mount a gfs2 fs needs to check all the journals
* and recover any that need recovery before other nodes are allowed
* to mount the fs. (Others may begin mounting, but they must wait
* for the first mounter to be done before taking locks on the fs
* or accessing the fs.) This has two parts:
*
* 1. The mounted_lock tells a node it's the first to mount the fs.
* Each node holds the mounted_lock in PR while it's mounted.
* Each node tries to acquire the mounted_lock in EX when it mounts.
* If a node is granted the mounted_lock EX it means there are no
* other mounted nodes (no PR locks exist), and it is the first mounter.
* The mounted_lock is demoted to PR when first recovery is done, so
* others will fail to get an EX lock, but will get a PR lock.
*
* 2. The control_lock blocks others in control_mount() while the first
* mounter is doing first mount recovery of all journals.
* A mounting node needs to acquire control_lock in EX mode before
* it can proceed. The first mounter holds control_lock in EX while doing
* the first mount recovery, blocking mounts from other nodes, then demotes
* control_lock to NL when it's done (others_may_mount/first_done),
* allowing other nodes to continue mounting.
*
* first mounter:
* control_lock EX/NOQUEUE success
* mounted_lock EX/NOQUEUE success (no other PR, so no other mounters)
* set first=1
* do first mounter recovery
* mounted_lock EX->PR
* control_lock EX->NL, write lvb generation
*
* other mounter:
* control_lock EX/NOQUEUE success (if fail -EAGAIN, retry)
* mounted_lock EX/NOQUEUE fail -EAGAIN (expected due to other mounters PR)
* mounted_lock PR/NOQUEUE success
* read lvb generation
* control_lock EX->NL
* set first=0
*
* - mount during recovery
*
* If a node mounts while others are doing recovery (not first mounter),
* the mounting node will get its initial recover_done() callback without
* having seen any previous failures/callbacks.
*
* It must wait for all recoveries preceding its mount to be finished
* before it unblocks locks. It does this by repeating the "other mounter"
* steps above until the lvb generation number is >= its mount generation
* number (from initial recover_done) and all lvb bits are clear.
*
* - control_lock lvb format
*
* 4 bytes generation number: the latest dlm lockspace generation number
* from recover_done callback. Indicates the jid bitmap has been updated
* to reflect all slot failures through that generation.
* 4 bytes unused.
* GDLM_LVB_SIZE-8 bytes of jid bit map. If bit N is set, it indicates
* that jid N needs recovery.
*/
#define JID_BITMAP_OFFSET 8 /* 4 byte generation number + 4 byte unused */
static void control_lvb_read(struct lm_lockstruct *ls, uint32_t *lvb_gen,
char *lvb_bits)
{
uint32_t gen;
memcpy(lvb_bits, ls->ls_control_lvb, GDLM_LVB_SIZE);
memcpy(&gen, lvb_bits, sizeof(uint32_t));
*lvb_gen = le32_to_cpu(gen);
}
static void control_lvb_write(struct lm_lockstruct *ls, uint32_t lvb_gen,
char *lvb_bits)
{
uint32_t gen;
memcpy(ls->ls_control_lvb, lvb_bits, GDLM_LVB_SIZE);
gen = cpu_to_le32(lvb_gen);
memcpy(ls->ls_control_lvb, &gen, sizeof(uint32_t));
}
static int all_jid_bits_clear(char *lvb)
{
int i;
for (i = JID_BITMAP_OFFSET; i < GDLM_LVB_SIZE; i++) {
if (lvb[i])
return 0;
}
return 1;
}
static void sync_wait_cb(void *arg)
{
struct lm_lockstruct *ls = arg;
complete(&ls->ls_sync_wait);
}
static int sync_unlock(struct gfs2_sbd *sdp, struct dlm_lksb *lksb, char *name)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
int error;
error = dlm_unlock(ls->ls_dlm, lksb->sb_lkid, 0, lksb, ls);
if (error) {
fs_err(sdp, "%s lkid %x error %d\n",
name, lksb->sb_lkid, error);
return error;
}
wait_for_completion(&ls->ls_sync_wait);
if (lksb->sb_status != -DLM_EUNLOCK) {
fs_err(sdp, "%s lkid %x status %d\n",
name, lksb->sb_lkid, lksb->sb_status);
return -1;
}
return 0;
}
static int sync_lock(struct gfs2_sbd *sdp, int mode, uint32_t flags,
unsigned int num, struct dlm_lksb *lksb, char *name)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
char strname[GDLM_STRNAME_BYTES];
int error, status;
memset(strname, 0, GDLM_STRNAME_BYTES);
snprintf(strname, GDLM_STRNAME_BYTES, "%8x%16x", LM_TYPE_NONDISK, num);
error = dlm_lock(ls->ls_dlm, mode, lksb, flags,
strname, GDLM_STRNAME_BYTES - 1,
0, sync_wait_cb, ls, NULL);
if (error) {
fs_err(sdp, "%s lkid %x flags %x mode %d error %d\n",
name, lksb->sb_lkid, flags, mode, error);
return error;
}
wait_for_completion(&ls->ls_sync_wait);
status = lksb->sb_status;
if (status && status != -EAGAIN) {
fs_err(sdp, "%s lkid %x flags %x mode %d status %d\n",
name, lksb->sb_lkid, flags, mode, status);
}
return status;
}
static int mounted_unlock(struct gfs2_sbd *sdp)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
return sync_unlock(sdp, &ls->ls_mounted_lksb, "mounted_lock");
}
static int mounted_lock(struct gfs2_sbd *sdp, int mode, uint32_t flags)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
return sync_lock(sdp, mode, flags, GFS2_MOUNTED_LOCK,
&ls->ls_mounted_lksb, "mounted_lock");
}
static int control_unlock(struct gfs2_sbd *sdp)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
return sync_unlock(sdp, &ls->ls_control_lksb, "control_lock");
}
static int control_lock(struct gfs2_sbd *sdp, int mode, uint32_t flags)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
return sync_lock(sdp, mode, flags, GFS2_CONTROL_LOCK,
&ls->ls_control_lksb, "control_lock");
}
static void gfs2_control_func(struct work_struct *work)
{
struct gfs2_sbd *sdp = container_of(work, struct gfs2_sbd, sd_control_work.work);
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
char lvb_bits[GDLM_LVB_SIZE];
uint32_t block_gen, start_gen, lvb_gen, flags;
int recover_set = 0;
int write_lvb = 0;
int recover_size;
int i, error;
spin_lock(&ls->ls_recover_spin);
/*
* No MOUNT_DONE means we're still mounting; control_mount()
* will set this flag, after which this thread will take over
* all further clearing of BLOCK_LOCKS.
*
* FIRST_MOUNT means this node is doing first mounter recovery,
* for which recovery control is handled by
* control_mount()/control_first_done(), not this thread.
*/
if (!test_bit(DFL_MOUNT_DONE, &ls->ls_recover_flags) ||
test_bit(DFL_FIRST_MOUNT, &ls->ls_recover_flags)) {
spin_unlock(&ls->ls_recover_spin);
return;
}
block_gen = ls->ls_recover_block;
start_gen = ls->ls_recover_start;
spin_unlock(&ls->ls_recover_spin);
/*
* Equal block_gen and start_gen implies we are between
* recover_prep and recover_done callbacks, which means
* dlm recovery is in progress and dlm locking is blocked.
* There's no point trying to do any work until recover_done.
*/
if (block_gen == start_gen)
return;
/*
* Propagate recover_submit[] and recover_result[] to lvb:
* dlm_recoverd adds to recover_submit[] jids needing recovery
* gfs2_recover adds to recover_result[] journal recovery results
*
* set lvb bit for jids in recover_submit[] if the lvb has not
* yet been updated for the generation of the failure
*
* clear lvb bit for jids in recover_result[] if the result of
* the journal recovery is SUCCESS
*/
error = control_lock(sdp, DLM_LOCK_EX, DLM_LKF_CONVERT|DLM_LKF_VALBLK);
if (error) {
fs_err(sdp, "control lock EX error %d\n", error);
return;
}
control_lvb_read(ls, &lvb_gen, lvb_bits);
spin_lock(&ls->ls_recover_spin);
if (block_gen != ls->ls_recover_block ||
start_gen != ls->ls_recover_start) {
fs_info(sdp, "recover generation %u block1 %u %u\n",
start_gen, block_gen, ls->ls_recover_block);
spin_unlock(&ls->ls_recover_spin);
control_lock(sdp, DLM_LOCK_NL, DLM_LKF_CONVERT);
return;
}
recover_size = ls->ls_recover_size;
if (lvb_gen <= start_gen) {
/*
* Clear lvb bits for jids we've successfully recovered.
* Because all nodes attempt to recover failed journals,
* a journal can be recovered multiple times successfully
* in succession. Only the first will really do recovery,
* the others find it clean, but still report a successful
* recovery. So, another node may have already recovered
* the jid and cleared the lvb bit for it.
*/
for (i = 0; i < recover_size; i++) {
if (ls->ls_recover_result[i] != LM_RD_SUCCESS)
continue;
ls->ls_recover_result[i] = 0;
if (!test_bit_le(i, lvb_bits + JID_BITMAP_OFFSET))
continue;
__clear_bit_le(i, lvb_bits + JID_BITMAP_OFFSET);
write_lvb = 1;
}
}
if (lvb_gen == start_gen) {
/*
* Failed slots before start_gen are already set in lvb.
*/
for (i = 0; i < recover_size; i++) {
if (!ls->ls_recover_submit[i])
continue;
if (ls->ls_recover_submit[i] < lvb_gen)
ls->ls_recover_submit[i] = 0;
}
} else if (lvb_gen < start_gen) {
/*
* Failed slots before start_gen are not yet set in lvb.
*/
for (i = 0; i < recover_size; i++) {
if (!ls->ls_recover_submit[i])
continue;
if (ls->ls_recover_submit[i] < start_gen) {
ls->ls_recover_submit[i] = 0;
__set_bit_le(i, lvb_bits + JID_BITMAP_OFFSET);
}
}
/* even if there are no bits to set, we need to write the
latest generation to the lvb */
write_lvb = 1;
} else {
/*
* we should be getting a recover_done() for lvb_gen soon
*/
}
spin_unlock(&ls->ls_recover_spin);
if (write_lvb) {
control_lvb_write(ls, start_gen, lvb_bits);
flags = DLM_LKF_CONVERT | DLM_LKF_VALBLK;
} else {
flags = DLM_LKF_CONVERT;
}
error = control_lock(sdp, DLM_LOCK_NL, flags);
if (error) {
fs_err(sdp, "control lock NL error %d\n", error);
return;
}
/*
* Everyone will see jid bits set in the lvb, run gfs2_recover_set(),
* and clear a jid bit in the lvb if the recovery is a success.
* Eventually all journals will be recovered, all jid bits will
* be cleared in the lvb, and everyone will clear BLOCK_LOCKS.
*/
for (i = 0; i < recover_size; i++) {
if (test_bit_le(i, lvb_bits + JID_BITMAP_OFFSET)) {
fs_info(sdp, "recover generation %u jid %d\n",
start_gen, i);
gfs2_recover_set(sdp, i);
recover_set++;
}
}
if (recover_set)
return;
/*
* No more jid bits set in lvb, all recovery is done, unblock locks
* (unless a new recover_prep callback has occured blocking locks
* again while working above)
*/
spin_lock(&ls->ls_recover_spin);
if (ls->ls_recover_block == block_gen &&
ls->ls_recover_start == start_gen) {
clear_bit(DFL_BLOCK_LOCKS, &ls->ls_recover_flags);
spin_unlock(&ls->ls_recover_spin);
fs_info(sdp, "recover generation %u done\n", start_gen);
gfs2_glock_thaw(sdp);
} else {
fs_info(sdp, "recover generation %u block2 %u %u\n",
start_gen, block_gen, ls->ls_recover_block);
spin_unlock(&ls->ls_recover_spin);
}
}
static int control_mount(struct gfs2_sbd *sdp)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
char lvb_bits[GDLM_LVB_SIZE];
uint32_t start_gen, block_gen, mount_gen, lvb_gen;
int mounted_mode;
int retries = 0;
int error;
memset(&ls->ls_mounted_lksb, 0, sizeof(struct dlm_lksb));
memset(&ls->ls_control_lksb, 0, sizeof(struct dlm_lksb));
memset(&ls->ls_control_lvb, 0, GDLM_LVB_SIZE);
ls->ls_control_lksb.sb_lvbptr = ls->ls_control_lvb;
init_completion(&ls->ls_sync_wait);
set_bit(DFL_BLOCK_LOCKS, &ls->ls_recover_flags);
error = control_lock(sdp, DLM_LOCK_NL, DLM_LKF_VALBLK);
if (error) {
fs_err(sdp, "control_mount control_lock NL error %d\n", error);
return error;
}
error = mounted_lock(sdp, DLM_LOCK_NL, 0);
if (error) {
fs_err(sdp, "control_mount mounted_lock NL error %d\n", error);
control_unlock(sdp);
return error;
}
mounted_mode = DLM_LOCK_NL;
restart:
if (retries++ && signal_pending(current)) {
error = -EINTR;
goto fail;
}
/*
* We always start with both locks in NL. control_lock is
* demoted to NL below so we don't need to do it here.
*/
if (mounted_mode != DLM_LOCK_NL) {
error = mounted_lock(sdp, DLM_LOCK_NL, DLM_LKF_CONVERT);
if (error)
goto fail;
mounted_mode = DLM_LOCK_NL;
}
/*
* Other nodes need to do some work in dlm recovery and gfs2_control
* before the recover_done and control_lock will be ready for us below.
* A delay here is not required but often avoids having to retry.
*/
msleep_interruptible(500);
/*
* Acquire control_lock in EX and mounted_lock in either EX or PR.
* control_lock lvb keeps track of any pending journal recoveries.
* mounted_lock indicates if any other nodes have the fs mounted.
*/
error = control_lock(sdp, DLM_LOCK_EX, DLM_LKF_CONVERT|DLM_LKF_NOQUEUE|DLM_LKF_VALBLK);
if (error == -EAGAIN) {
goto restart;
} else if (error) {
fs_err(sdp, "control_mount control_lock EX error %d\n", error);
goto fail;
}
error = mounted_lock(sdp, DLM_LOCK_EX, DLM_LKF_CONVERT|DLM_LKF_NOQUEUE);
if (!error) {
mounted_mode = DLM_LOCK_EX;
goto locks_done;
} else if (error != -EAGAIN) {
fs_err(sdp, "control_mount mounted_lock EX error %d\n", error);
goto fail;
}
error = mounted_lock(sdp, DLM_LOCK_PR, DLM_LKF_CONVERT|DLM_LKF_NOQUEUE);
if (!error) {
mounted_mode = DLM_LOCK_PR;
goto locks_done;
} else {
/* not even -EAGAIN should happen here */
fs_err(sdp, "control_mount mounted_lock PR error %d\n", error);
goto fail;
}
locks_done:
/*
* If we got both locks above in EX, then we're the first mounter.
* If not, then we need to wait for the control_lock lvb to be
* updated by other mounted nodes to reflect our mount generation.
*
* In simple first mounter cases, first mounter will see zero lvb_gen,
* but in cases where all existing nodes leave/fail before mounting
* nodes finish control_mount, then all nodes will be mounting and
* lvb_gen will be non-zero.
*/
control_lvb_read(ls, &lvb_gen, lvb_bits);
if (lvb_gen == 0xFFFFFFFF) {
/* special value to force mount attempts to fail */
fs_err(sdp, "control_mount control_lock disabled\n");
error = -EINVAL;
goto fail;
}
if (mounted_mode == DLM_LOCK_EX) {
/* first mounter, keep both EX while doing first recovery */
spin_lock(&ls->ls_recover_spin);
clear_bit(DFL_BLOCK_LOCKS, &ls->ls_recover_flags);
set_bit(DFL_MOUNT_DONE, &ls->ls_recover_flags);
set_bit(DFL_FIRST_MOUNT, &ls->ls_recover_flags);
spin_unlock(&ls->ls_recover_spin);
fs_info(sdp, "first mounter control generation %u\n", lvb_gen);
return 0;
}
error = control_lock(sdp, DLM_LOCK_NL, DLM_LKF_CONVERT);
if (error)
goto fail;
/*
* We are not first mounter, now we need to wait for the control_lock
* lvb generation to be >= the generation from our first recover_done
* and all lvb bits to be clear (no pending journal recoveries.)
*/
if (!all_jid_bits_clear(lvb_bits)) {
/* journals need recovery, wait until all are clear */
fs_info(sdp, "control_mount wait for journal recovery\n");
goto restart;
}
spin_lock(&ls->ls_recover_spin);
block_gen = ls->ls_recover_block;
start_gen = ls->ls_recover_start;
mount_gen = ls->ls_recover_mount;
if (lvb_gen < mount_gen) {
/* wait for mounted nodes to update control_lock lvb to our
generation, which might include new recovery bits set */
fs_info(sdp, "control_mount wait1 block %u start %u mount %u "
"lvb %u flags %lx\n", block_gen, start_gen, mount_gen,
lvb_gen, ls->ls_recover_flags);
spin_unlock(&ls->ls_recover_spin);
goto restart;
}
if (lvb_gen != start_gen) {
/* wait for mounted nodes to update control_lock lvb to the
latest recovery generation */
fs_info(sdp, "control_mount wait2 block %u start %u mount %u "
"lvb %u flags %lx\n", block_gen, start_gen, mount_gen,
lvb_gen, ls->ls_recover_flags);
spin_unlock(&ls->ls_recover_spin);
goto restart;
}
if (block_gen == start_gen) {
/* dlm recovery in progress, wait for it to finish */
fs_info(sdp, "control_mount wait3 block %u start %u mount %u "
"lvb %u flags %lx\n", block_gen, start_gen, mount_gen,
lvb_gen, ls->ls_recover_flags);
spin_unlock(&ls->ls_recover_spin);
goto restart;
}
clear_bit(DFL_BLOCK_LOCKS, &ls->ls_recover_flags);
set_bit(DFL_MOUNT_DONE, &ls->ls_recover_flags);
memset(ls->ls_recover_submit, 0, ls->ls_recover_size*sizeof(uint32_t));
memset(ls->ls_recover_result, 0, ls->ls_recover_size*sizeof(uint32_t));
spin_unlock(&ls->ls_recover_spin);
return 0;
fail:
mounted_unlock(sdp);
control_unlock(sdp);
return error;
}
static int dlm_recovery_wait(void *word)
{
schedule();
return 0;
}
static int control_first_done(struct gfs2_sbd *sdp)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
char lvb_bits[GDLM_LVB_SIZE];
uint32_t start_gen, block_gen;
int error;
restart:
spin_lock(&ls->ls_recover_spin);
start_gen = ls->ls_recover_start;
block_gen = ls->ls_recover_block;
if (test_bit(DFL_BLOCK_LOCKS, &ls->ls_recover_flags) ||
!test_bit(DFL_MOUNT_DONE, &ls->ls_recover_flags) ||
!test_bit(DFL_FIRST_MOUNT, &ls->ls_recover_flags)) {
/* sanity check, should not happen */
fs_err(sdp, "control_first_done start %u block %u flags %lx\n",
start_gen, block_gen, ls->ls_recover_flags);
spin_unlock(&ls->ls_recover_spin);
control_unlock(sdp);
return -1;
}
if (start_gen == block_gen) {
/*
* Wait for the end of a dlm recovery cycle to switch from
* first mounter recovery. We can ignore any recover_slot
* callbacks between the recover_prep and next recover_done
* because we are still the first mounter and any failed nodes
* have not fully mounted, so they don't need recovery.
*/
spin_unlock(&ls->ls_recover_spin);
fs_info(sdp, "control_first_done wait gen %u\n", start_gen);
wait_on_bit(&ls->ls_recover_flags, DFL_DLM_RECOVERY,
dlm_recovery_wait, TASK_UNINTERRUPTIBLE);
goto restart;
}
clear_bit(DFL_FIRST_MOUNT, &ls->ls_recover_flags);
set_bit(DFL_FIRST_MOUNT_DONE, &ls->ls_recover_flags);
memset(ls->ls_recover_submit, 0, ls->ls_recover_size*sizeof(uint32_t));
memset(ls->ls_recover_result, 0, ls->ls_recover_size*sizeof(uint32_t));
spin_unlock(&ls->ls_recover_spin);
memset(lvb_bits, 0, sizeof(lvb_bits));
control_lvb_write(ls, start_gen, lvb_bits);
error = mounted_lock(sdp, DLM_LOCK_PR, DLM_LKF_CONVERT);
if (error)
fs_err(sdp, "control_first_done mounted PR error %d\n", error);
error = control_lock(sdp, DLM_LOCK_NL, DLM_LKF_CONVERT|DLM_LKF_VALBLK);
if (error)
fs_err(sdp, "control_first_done control NL error %d\n", error);
return error;
}
/*
* Expand static jid arrays if necessary (by increments of RECOVER_SIZE_INC)
* to accomodate the largest slot number. (NB dlm slot numbers start at 1,
* gfs2 jids start at 0, so jid = slot - 1)
*/
#define RECOVER_SIZE_INC 16
static int set_recover_size(struct gfs2_sbd *sdp, struct dlm_slot *slots,
int num_slots)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
uint32_t *submit = NULL;
uint32_t *result = NULL;
uint32_t old_size, new_size;
int i, max_jid;
max_jid = 0;
for (i = 0; i < num_slots; i++) {
if (max_jid < slots[i].slot - 1)
max_jid = slots[i].slot - 1;
}
old_size = ls->ls_recover_size;
if (old_size >= max_jid + 1)
return 0;
new_size = old_size + RECOVER_SIZE_INC;
submit = kzalloc(new_size * sizeof(uint32_t), GFP_NOFS);
result = kzalloc(new_size * sizeof(uint32_t), GFP_NOFS);
if (!submit || !result) {
kfree(submit);
kfree(result);
return -ENOMEM;
}
spin_lock(&ls->ls_recover_spin);
memcpy(submit, ls->ls_recover_submit, old_size * sizeof(uint32_t));
memcpy(result, ls->ls_recover_result, old_size * sizeof(uint32_t));
kfree(ls->ls_recover_submit);
kfree(ls->ls_recover_result);
ls->ls_recover_submit = submit;
ls->ls_recover_result = result;
ls->ls_recover_size = new_size;
spin_unlock(&ls->ls_recover_spin);
return 0;
}
static void free_recover_size(struct lm_lockstruct *ls)
{
kfree(ls->ls_recover_submit);
kfree(ls->ls_recover_result);
ls->ls_recover_submit = NULL;
ls->ls_recover_result = NULL;
ls->ls_recover_size = 0;
}
/* dlm calls before it does lock recovery */
static void gdlm_recover_prep(void *arg)
{
struct gfs2_sbd *sdp = arg;
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
spin_lock(&ls->ls_recover_spin);
ls->ls_recover_block = ls->ls_recover_start;
set_bit(DFL_DLM_RECOVERY, &ls->ls_recover_flags);
if (!test_bit(DFL_MOUNT_DONE, &ls->ls_recover_flags) ||
test_bit(DFL_FIRST_MOUNT, &ls->ls_recover_flags)) {
spin_unlock(&ls->ls_recover_spin);
return;
}
set_bit(DFL_BLOCK_LOCKS, &ls->ls_recover_flags);
spin_unlock(&ls->ls_recover_spin);
}
/* dlm calls after recover_prep has been completed on all lockspace members;
identifies slot/jid of failed member */
static void gdlm_recover_slot(void *arg, struct dlm_slot *slot)
{
struct gfs2_sbd *sdp = arg;
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
int jid = slot->slot - 1;
spin_lock(&ls->ls_recover_spin);
if (ls->ls_recover_size < jid + 1) {
fs_err(sdp, "recover_slot jid %d gen %u short size %d",
jid, ls->ls_recover_block, ls->ls_recover_size);
spin_unlock(&ls->ls_recover_spin);
return;
}
if (ls->ls_recover_submit[jid]) {
fs_info(sdp, "recover_slot jid %d gen %u prev %u",
jid, ls->ls_recover_block, ls->ls_recover_submit[jid]);
}
ls->ls_recover_submit[jid] = ls->ls_recover_block;
spin_unlock(&ls->ls_recover_spin);
}
/* dlm calls after recover_slot and after it completes lock recovery */
static void gdlm_recover_done(void *arg, struct dlm_slot *slots, int num_slots,
int our_slot, uint32_t generation)
{
struct gfs2_sbd *sdp = arg;
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
/* ensure the ls jid arrays are large enough */
set_recover_size(sdp, slots, num_slots);
spin_lock(&ls->ls_recover_spin);
ls->ls_recover_start = generation;
if (!ls->ls_recover_mount) {
ls->ls_recover_mount = generation;
ls->ls_jid = our_slot - 1;
}
if (!test_bit(DFL_UNMOUNT, &ls->ls_recover_flags))
queue_delayed_work(gfs2_control_wq, &sdp->sd_control_work, 0);
clear_bit(DFL_DLM_RECOVERY, &ls->ls_recover_flags);
smp_mb__after_clear_bit();
wake_up_bit(&ls->ls_recover_flags, DFL_DLM_RECOVERY);
spin_unlock(&ls->ls_recover_spin);
}
/* gfs2_recover thread has a journal recovery result */
static void gdlm_recovery_result(struct gfs2_sbd *sdp, unsigned int jid,
unsigned int result)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
if (test_bit(DFL_NO_DLM_OPS, &ls->ls_recover_flags))
return;
/* don't care about the recovery of own journal during mount */
if (jid == ls->ls_jid)
return;
spin_lock(&ls->ls_recover_spin);
if (test_bit(DFL_FIRST_MOUNT, &ls->ls_recover_flags)) {
spin_unlock(&ls->ls_recover_spin);
return;
}
if (ls->ls_recover_size < jid + 1) {
fs_err(sdp, "recovery_result jid %d short size %d",
jid, ls->ls_recover_size);
spin_unlock(&ls->ls_recover_spin);
return;
}
fs_info(sdp, "recover jid %d result %s\n", jid,
result == LM_RD_GAVEUP ? "busy" : "success");
ls->ls_recover_result[jid] = result;
/* GAVEUP means another node is recovering the journal; delay our
next attempt to recover it, to give the other node a chance to
finish before trying again */
if (!test_bit(DFL_UNMOUNT, &ls->ls_recover_flags))
queue_delayed_work(gfs2_control_wq, &sdp->sd_control_work,
result == LM_RD_GAVEUP ? HZ : 0);
spin_unlock(&ls->ls_recover_spin);
}
const struct dlm_lockspace_ops gdlm_lockspace_ops = {
.recover_prep = gdlm_recover_prep,
.recover_slot = gdlm_recover_slot,
.recover_done = gdlm_recover_done,
};
static int gdlm_mount(struct gfs2_sbd *sdp, const char *table)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
char cluster[GFS2_LOCKNAME_LEN];
const char *fsname;
uint32_t flags;
int error, ops_result;
/*
* initialize everything
*/
INIT_DELAYED_WORK(&sdp->sd_control_work, gfs2_control_func);
spin_lock_init(&ls->ls_recover_spin);
ls->ls_recover_flags = 0;
ls->ls_recover_mount = 0;
ls->ls_recover_start = 0;
ls->ls_recover_block = 0;
ls->ls_recover_size = 0;
ls->ls_recover_submit = NULL;
ls->ls_recover_result = NULL;
error = set_recover_size(sdp, NULL, 0);
if (error)
goto fail;
/*
* prepare dlm_new_lockspace args
*/
fsname = strchr(table, ':');
if (!fsname) {
fs_info(sdp, "no fsname found\n");
error = -EINVAL;
goto fail_free;
}
memset(cluster, 0, sizeof(cluster));
memcpy(cluster, table, strlen(table) - strlen(fsname));
fsname++;
flags = DLM_LSFL_FS | DLM_LSFL_NEWEXCL;
if (ls->ls_nodir)
flags |= DLM_LSFL_NODIR;
/*
* create/join lockspace
*/
error = dlm_new_lockspace(fsname, cluster, flags, GDLM_LVB_SIZE,
&gdlm_lockspace_ops, sdp, &ops_result,
&ls->ls_dlm);
if (error) {
fs_err(sdp, "dlm_new_lockspace error %d\n", error);
goto fail_free;
}
if (ops_result < 0) {
/*
* dlm does not support ops callbacks,
* old dlm_controld/gfs_controld are used, try without ops.
*/
fs_info(sdp, "dlm lockspace ops not used\n");
free_recover_size(ls);
set_bit(DFL_NO_DLM_OPS, &ls->ls_recover_flags);
return 0;
}
if (!test_bit(SDF_NOJOURNALID, &sdp->sd_flags)) {
fs_err(sdp, "dlm lockspace ops disallow jid preset\n");
error = -EINVAL;
goto fail_release;
}
/*
* control_mount() uses control_lock to determine first mounter,
* and for later mounts, waits for any recoveries to be cleared.
*/
error = control_mount(sdp);
if (error) {
fs_err(sdp, "mount control error %d\n", error);
goto fail_release;
}
ls->ls_first = !!test_bit(DFL_FIRST_MOUNT, &ls->ls_recover_flags);
clear_bit(SDF_NOJOURNALID, &sdp->sd_flags);
smp_mb__after_clear_bit();
wake_up_bit(&sdp->sd_flags, SDF_NOJOURNALID);
return 0;
fail_release:
dlm_release_lockspace(ls->ls_dlm, 2);
fail_free:
free_recover_size(ls);
fail:
return error;
}
static void gdlm_first_done(struct gfs2_sbd *sdp)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
int error;
if (test_bit(DFL_NO_DLM_OPS, &ls->ls_recover_flags))
return;
error = control_first_done(sdp);
if (error)
fs_err(sdp, "mount first_done error %d\n", error);
}
static void gdlm_unmount(struct gfs2_sbd *sdp)
{
struct lm_lockstruct *ls = &sdp->sd_lockstruct;
if (test_bit(DFL_NO_DLM_OPS, &ls->ls_recover_flags))
goto release;
/* wait for gfs2_control_wq to be done with this mount */
spin_lock(&ls->ls_recover_spin);
set_bit(DFL_UNMOUNT, &ls->ls_recover_flags);
spin_unlock(&ls->ls_recover_spin);
flush_delayed_work_sync(&sdp->sd_control_work);
/* mounted_lock and control_lock will be purged in dlm recovery */
release:
if (ls->ls_dlm) {
dlm_release_lockspace(ls->ls_dlm, 2);
ls->ls_dlm = NULL;
}
free_recover_size(ls);
}
static const match_table_t dlm_tokens = {
{ Opt_jid, "jid=%d"},
{ Opt_id, "id=%d"},
{ Opt_first, "first=%d"},
{ Opt_nodir, "nodir=%d"},
{ Opt_err, NULL },
};
const struct lm_lockops gfs2_dlm_ops = {
.lm_proto_name = "lock_dlm",
.lm_mount = gdlm_mount,
.lm_first_done = gdlm_first_done,
.lm_recovery_result = gdlm_recovery_result,
.lm_unmount = gdlm_unmount,
.lm_put_lock = gdlm_put_lock,
.lm_lock = gdlm_lock,
.lm_cancel = gdlm_cancel,
.lm_tokens = &dlm_tokens,
};
| gpl-2.0 |
fronti90/kernel_lge_geefhd | drivers/gpu/drm/nouveau/nv50_dac.c | 5254 | 9006 | /*
* Copyright (C) 2008 Maarten Maathuis.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include "drmP.h"
#include "drm_crtc_helper.h"
#define NOUVEAU_DMA_DEBUG (nouveau_reg_debug & NOUVEAU_REG_DEBUG_EVO)
#include "nouveau_reg.h"
#include "nouveau_drv.h"
#include "nouveau_dma.h"
#include "nouveau_encoder.h"
#include "nouveau_connector.h"
#include "nouveau_crtc.h"
#include "nv50_display.h"
static void
nv50_dac_disconnect(struct drm_encoder *encoder)
{
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
struct drm_device *dev = encoder->dev;
struct nouveau_channel *evo = nv50_display(dev)->master;
int ret;
if (!nv_encoder->crtc)
return;
nv50_crtc_blank(nouveau_crtc(nv_encoder->crtc), true);
NV_DEBUG_KMS(dev, "Disconnecting DAC %d\n", nv_encoder->or);
ret = RING_SPACE(evo, 4);
if (ret) {
NV_ERROR(dev, "no space while disconnecting DAC\n");
return;
}
BEGIN_RING(evo, 0, NV50_EVO_DAC(nv_encoder->or, MODE_CTRL), 1);
OUT_RING (evo, 0);
BEGIN_RING(evo, 0, NV50_EVO_UPDATE, 1);
OUT_RING (evo, 0);
nv_encoder->crtc = NULL;
}
static enum drm_connector_status
nv50_dac_detect(struct drm_encoder *encoder, struct drm_connector *connector)
{
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
struct drm_device *dev = encoder->dev;
struct drm_nouveau_private *dev_priv = dev->dev_private;
enum drm_connector_status status = connector_status_disconnected;
uint32_t dpms_state, load_pattern, load_state;
int or = nv_encoder->or;
nv_wr32(dev, NV50_PDISPLAY_DAC_CLK_CTRL1(or), 0x00000001);
dpms_state = nv_rd32(dev, NV50_PDISPLAY_DAC_DPMS_CTRL(or));
nv_wr32(dev, NV50_PDISPLAY_DAC_DPMS_CTRL(or),
0x00150000 | NV50_PDISPLAY_DAC_DPMS_CTRL_PENDING);
if (!nv_wait(dev, NV50_PDISPLAY_DAC_DPMS_CTRL(or),
NV50_PDISPLAY_DAC_DPMS_CTRL_PENDING, 0)) {
NV_ERROR(dev, "timeout: DAC_DPMS_CTRL_PENDING(%d) == 0\n", or);
NV_ERROR(dev, "DAC_DPMS_CTRL(%d) = 0x%08x\n", or,
nv_rd32(dev, NV50_PDISPLAY_DAC_DPMS_CTRL(or)));
return status;
}
/* Use bios provided value if possible. */
if (dev_priv->vbios.dactestval) {
load_pattern = dev_priv->vbios.dactestval;
NV_DEBUG_KMS(dev, "Using bios provided load_pattern of %d\n",
load_pattern);
} else {
load_pattern = 340;
NV_DEBUG_KMS(dev, "Using default load_pattern of %d\n",
load_pattern);
}
nv_wr32(dev, NV50_PDISPLAY_DAC_LOAD_CTRL(or),
NV50_PDISPLAY_DAC_LOAD_CTRL_ACTIVE | load_pattern);
mdelay(45); /* give it some time to process */
load_state = nv_rd32(dev, NV50_PDISPLAY_DAC_LOAD_CTRL(or));
nv_wr32(dev, NV50_PDISPLAY_DAC_LOAD_CTRL(or), 0);
nv_wr32(dev, NV50_PDISPLAY_DAC_DPMS_CTRL(or), dpms_state |
NV50_PDISPLAY_DAC_DPMS_CTRL_PENDING);
if ((load_state & NV50_PDISPLAY_DAC_LOAD_CTRL_PRESENT) ==
NV50_PDISPLAY_DAC_LOAD_CTRL_PRESENT)
status = connector_status_connected;
if (status == connector_status_connected)
NV_DEBUG_KMS(dev, "Load was detected on output with or %d\n", or);
else
NV_DEBUG_KMS(dev, "Load was not detected on output with or %d\n", or);
return status;
}
static void
nv50_dac_dpms(struct drm_encoder *encoder, int mode)
{
struct drm_device *dev = encoder->dev;
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
uint32_t val;
int or = nv_encoder->or;
NV_DEBUG_KMS(dev, "or %d mode %d\n", or, mode);
/* wait for it to be done */
if (!nv_wait(dev, NV50_PDISPLAY_DAC_DPMS_CTRL(or),
NV50_PDISPLAY_DAC_DPMS_CTRL_PENDING, 0)) {
NV_ERROR(dev, "timeout: DAC_DPMS_CTRL_PENDING(%d) == 0\n", or);
NV_ERROR(dev, "DAC_DPMS_CTRL(%d) = 0x%08x\n", or,
nv_rd32(dev, NV50_PDISPLAY_DAC_DPMS_CTRL(or)));
return;
}
val = nv_rd32(dev, NV50_PDISPLAY_DAC_DPMS_CTRL(or)) & ~0x7F;
if (mode != DRM_MODE_DPMS_ON)
val |= NV50_PDISPLAY_DAC_DPMS_CTRL_BLANKED;
switch (mode) {
case DRM_MODE_DPMS_STANDBY:
val |= NV50_PDISPLAY_DAC_DPMS_CTRL_HSYNC_OFF;
break;
case DRM_MODE_DPMS_SUSPEND:
val |= NV50_PDISPLAY_DAC_DPMS_CTRL_VSYNC_OFF;
break;
case DRM_MODE_DPMS_OFF:
val |= NV50_PDISPLAY_DAC_DPMS_CTRL_OFF;
val |= NV50_PDISPLAY_DAC_DPMS_CTRL_HSYNC_OFF;
val |= NV50_PDISPLAY_DAC_DPMS_CTRL_VSYNC_OFF;
break;
default:
break;
}
nv_wr32(dev, NV50_PDISPLAY_DAC_DPMS_CTRL(or), val |
NV50_PDISPLAY_DAC_DPMS_CTRL_PENDING);
}
static void
nv50_dac_save(struct drm_encoder *encoder)
{
NV_ERROR(encoder->dev, "!!\n");
}
static void
nv50_dac_restore(struct drm_encoder *encoder)
{
NV_ERROR(encoder->dev, "!!\n");
}
static bool
nv50_dac_mode_fixup(struct drm_encoder *encoder, struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
struct nouveau_connector *connector;
NV_DEBUG_KMS(encoder->dev, "or %d\n", nv_encoder->or);
connector = nouveau_encoder_connector_get(nv_encoder);
if (!connector) {
NV_ERROR(encoder->dev, "Encoder has no connector\n");
return false;
}
if (connector->scaling_mode != DRM_MODE_SCALE_NONE &&
connector->native_mode)
drm_mode_copy(adjusted_mode, connector->native_mode);
return true;
}
static void
nv50_dac_commit(struct drm_encoder *encoder)
{
}
static void
nv50_dac_mode_set(struct drm_encoder *encoder, struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
struct drm_device *dev = encoder->dev;
struct nouveau_channel *evo = nv50_display(dev)->master;
struct nouveau_crtc *crtc = nouveau_crtc(encoder->crtc);
uint32_t mode_ctl = 0, mode_ctl2 = 0;
int ret;
NV_DEBUG_KMS(dev, "or %d type %d crtc %d\n",
nv_encoder->or, nv_encoder->dcb->type, crtc->index);
nv50_dac_dpms(encoder, DRM_MODE_DPMS_ON);
if (crtc->index == 1)
mode_ctl |= NV50_EVO_DAC_MODE_CTRL_CRTC1;
else
mode_ctl |= NV50_EVO_DAC_MODE_CTRL_CRTC0;
/* Lacking a working tv-out, this is not a 100% sure. */
if (nv_encoder->dcb->type == OUTPUT_ANALOG)
mode_ctl |= 0x40;
else
if (nv_encoder->dcb->type == OUTPUT_TV)
mode_ctl |= 0x100;
if (adjusted_mode->flags & DRM_MODE_FLAG_NHSYNC)
mode_ctl2 |= NV50_EVO_DAC_MODE_CTRL2_NHSYNC;
if (adjusted_mode->flags & DRM_MODE_FLAG_NVSYNC)
mode_ctl2 |= NV50_EVO_DAC_MODE_CTRL2_NVSYNC;
ret = RING_SPACE(evo, 3);
if (ret) {
NV_ERROR(dev, "no space while connecting DAC\n");
return;
}
BEGIN_RING(evo, 0, NV50_EVO_DAC(nv_encoder->or, MODE_CTRL), 2);
OUT_RING(evo, mode_ctl);
OUT_RING(evo, mode_ctl2);
nv_encoder->crtc = encoder->crtc;
}
static struct drm_crtc *
nv50_dac_crtc_get(struct drm_encoder *encoder)
{
return nouveau_encoder(encoder)->crtc;
}
static const struct drm_encoder_helper_funcs nv50_dac_helper_funcs = {
.dpms = nv50_dac_dpms,
.save = nv50_dac_save,
.restore = nv50_dac_restore,
.mode_fixup = nv50_dac_mode_fixup,
.prepare = nv50_dac_disconnect,
.commit = nv50_dac_commit,
.mode_set = nv50_dac_mode_set,
.get_crtc = nv50_dac_crtc_get,
.detect = nv50_dac_detect,
.disable = nv50_dac_disconnect
};
static void
nv50_dac_destroy(struct drm_encoder *encoder)
{
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
if (!encoder)
return;
NV_DEBUG_KMS(encoder->dev, "\n");
drm_encoder_cleanup(encoder);
kfree(nv_encoder);
}
static const struct drm_encoder_funcs nv50_dac_encoder_funcs = {
.destroy = nv50_dac_destroy,
};
int
nv50_dac_create(struct drm_connector *connector, struct dcb_entry *entry)
{
struct nouveau_encoder *nv_encoder;
struct drm_encoder *encoder;
nv_encoder = kzalloc(sizeof(*nv_encoder), GFP_KERNEL);
if (!nv_encoder)
return -ENOMEM;
encoder = to_drm_encoder(nv_encoder);
nv_encoder->dcb = entry;
nv_encoder->or = ffs(entry->or) - 1;
drm_encoder_init(connector->dev, encoder, &nv50_dac_encoder_funcs,
DRM_MODE_ENCODER_DAC);
drm_encoder_helper_add(encoder, &nv50_dac_helper_funcs);
encoder->possible_crtcs = entry->heads;
encoder->possible_clones = 0;
drm_mode_connector_attach_encoder(connector, encoder);
return 0;
}
| gpl-2.0 |
pec0ra/android_kernel_sony_msm8x60 | drivers/gpu/drm/nouveau/nv50_dac.c | 5254 | 9006 | /*
* Copyright (C) 2008 Maarten Maathuis.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include "drmP.h"
#include "drm_crtc_helper.h"
#define NOUVEAU_DMA_DEBUG (nouveau_reg_debug & NOUVEAU_REG_DEBUG_EVO)
#include "nouveau_reg.h"
#include "nouveau_drv.h"
#include "nouveau_dma.h"
#include "nouveau_encoder.h"
#include "nouveau_connector.h"
#include "nouveau_crtc.h"
#include "nv50_display.h"
static void
nv50_dac_disconnect(struct drm_encoder *encoder)
{
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
struct drm_device *dev = encoder->dev;
struct nouveau_channel *evo = nv50_display(dev)->master;
int ret;
if (!nv_encoder->crtc)
return;
nv50_crtc_blank(nouveau_crtc(nv_encoder->crtc), true);
NV_DEBUG_KMS(dev, "Disconnecting DAC %d\n", nv_encoder->or);
ret = RING_SPACE(evo, 4);
if (ret) {
NV_ERROR(dev, "no space while disconnecting DAC\n");
return;
}
BEGIN_RING(evo, 0, NV50_EVO_DAC(nv_encoder->or, MODE_CTRL), 1);
OUT_RING (evo, 0);
BEGIN_RING(evo, 0, NV50_EVO_UPDATE, 1);
OUT_RING (evo, 0);
nv_encoder->crtc = NULL;
}
static enum drm_connector_status
nv50_dac_detect(struct drm_encoder *encoder, struct drm_connector *connector)
{
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
struct drm_device *dev = encoder->dev;
struct drm_nouveau_private *dev_priv = dev->dev_private;
enum drm_connector_status status = connector_status_disconnected;
uint32_t dpms_state, load_pattern, load_state;
int or = nv_encoder->or;
nv_wr32(dev, NV50_PDISPLAY_DAC_CLK_CTRL1(or), 0x00000001);
dpms_state = nv_rd32(dev, NV50_PDISPLAY_DAC_DPMS_CTRL(or));
nv_wr32(dev, NV50_PDISPLAY_DAC_DPMS_CTRL(or),
0x00150000 | NV50_PDISPLAY_DAC_DPMS_CTRL_PENDING);
if (!nv_wait(dev, NV50_PDISPLAY_DAC_DPMS_CTRL(or),
NV50_PDISPLAY_DAC_DPMS_CTRL_PENDING, 0)) {
NV_ERROR(dev, "timeout: DAC_DPMS_CTRL_PENDING(%d) == 0\n", or);
NV_ERROR(dev, "DAC_DPMS_CTRL(%d) = 0x%08x\n", or,
nv_rd32(dev, NV50_PDISPLAY_DAC_DPMS_CTRL(or)));
return status;
}
/* Use bios provided value if possible. */
if (dev_priv->vbios.dactestval) {
load_pattern = dev_priv->vbios.dactestval;
NV_DEBUG_KMS(dev, "Using bios provided load_pattern of %d\n",
load_pattern);
} else {
load_pattern = 340;
NV_DEBUG_KMS(dev, "Using default load_pattern of %d\n",
load_pattern);
}
nv_wr32(dev, NV50_PDISPLAY_DAC_LOAD_CTRL(or),
NV50_PDISPLAY_DAC_LOAD_CTRL_ACTIVE | load_pattern);
mdelay(45); /* give it some time to process */
load_state = nv_rd32(dev, NV50_PDISPLAY_DAC_LOAD_CTRL(or));
nv_wr32(dev, NV50_PDISPLAY_DAC_LOAD_CTRL(or), 0);
nv_wr32(dev, NV50_PDISPLAY_DAC_DPMS_CTRL(or), dpms_state |
NV50_PDISPLAY_DAC_DPMS_CTRL_PENDING);
if ((load_state & NV50_PDISPLAY_DAC_LOAD_CTRL_PRESENT) ==
NV50_PDISPLAY_DAC_LOAD_CTRL_PRESENT)
status = connector_status_connected;
if (status == connector_status_connected)
NV_DEBUG_KMS(dev, "Load was detected on output with or %d\n", or);
else
NV_DEBUG_KMS(dev, "Load was not detected on output with or %d\n", or);
return status;
}
static void
nv50_dac_dpms(struct drm_encoder *encoder, int mode)
{
struct drm_device *dev = encoder->dev;
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
uint32_t val;
int or = nv_encoder->or;
NV_DEBUG_KMS(dev, "or %d mode %d\n", or, mode);
/* wait for it to be done */
if (!nv_wait(dev, NV50_PDISPLAY_DAC_DPMS_CTRL(or),
NV50_PDISPLAY_DAC_DPMS_CTRL_PENDING, 0)) {
NV_ERROR(dev, "timeout: DAC_DPMS_CTRL_PENDING(%d) == 0\n", or);
NV_ERROR(dev, "DAC_DPMS_CTRL(%d) = 0x%08x\n", or,
nv_rd32(dev, NV50_PDISPLAY_DAC_DPMS_CTRL(or)));
return;
}
val = nv_rd32(dev, NV50_PDISPLAY_DAC_DPMS_CTRL(or)) & ~0x7F;
if (mode != DRM_MODE_DPMS_ON)
val |= NV50_PDISPLAY_DAC_DPMS_CTRL_BLANKED;
switch (mode) {
case DRM_MODE_DPMS_STANDBY:
val |= NV50_PDISPLAY_DAC_DPMS_CTRL_HSYNC_OFF;
break;
case DRM_MODE_DPMS_SUSPEND:
val |= NV50_PDISPLAY_DAC_DPMS_CTRL_VSYNC_OFF;
break;
case DRM_MODE_DPMS_OFF:
val |= NV50_PDISPLAY_DAC_DPMS_CTRL_OFF;
val |= NV50_PDISPLAY_DAC_DPMS_CTRL_HSYNC_OFF;
val |= NV50_PDISPLAY_DAC_DPMS_CTRL_VSYNC_OFF;
break;
default:
break;
}
nv_wr32(dev, NV50_PDISPLAY_DAC_DPMS_CTRL(or), val |
NV50_PDISPLAY_DAC_DPMS_CTRL_PENDING);
}
static void
nv50_dac_save(struct drm_encoder *encoder)
{
NV_ERROR(encoder->dev, "!!\n");
}
static void
nv50_dac_restore(struct drm_encoder *encoder)
{
NV_ERROR(encoder->dev, "!!\n");
}
static bool
nv50_dac_mode_fixup(struct drm_encoder *encoder, struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
struct nouveau_connector *connector;
NV_DEBUG_KMS(encoder->dev, "or %d\n", nv_encoder->or);
connector = nouveau_encoder_connector_get(nv_encoder);
if (!connector) {
NV_ERROR(encoder->dev, "Encoder has no connector\n");
return false;
}
if (connector->scaling_mode != DRM_MODE_SCALE_NONE &&
connector->native_mode)
drm_mode_copy(adjusted_mode, connector->native_mode);
return true;
}
static void
nv50_dac_commit(struct drm_encoder *encoder)
{
}
static void
nv50_dac_mode_set(struct drm_encoder *encoder, struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
struct drm_device *dev = encoder->dev;
struct nouveau_channel *evo = nv50_display(dev)->master;
struct nouveau_crtc *crtc = nouveau_crtc(encoder->crtc);
uint32_t mode_ctl = 0, mode_ctl2 = 0;
int ret;
NV_DEBUG_KMS(dev, "or %d type %d crtc %d\n",
nv_encoder->or, nv_encoder->dcb->type, crtc->index);
nv50_dac_dpms(encoder, DRM_MODE_DPMS_ON);
if (crtc->index == 1)
mode_ctl |= NV50_EVO_DAC_MODE_CTRL_CRTC1;
else
mode_ctl |= NV50_EVO_DAC_MODE_CTRL_CRTC0;
/* Lacking a working tv-out, this is not a 100% sure. */
if (nv_encoder->dcb->type == OUTPUT_ANALOG)
mode_ctl |= 0x40;
else
if (nv_encoder->dcb->type == OUTPUT_TV)
mode_ctl |= 0x100;
if (adjusted_mode->flags & DRM_MODE_FLAG_NHSYNC)
mode_ctl2 |= NV50_EVO_DAC_MODE_CTRL2_NHSYNC;
if (adjusted_mode->flags & DRM_MODE_FLAG_NVSYNC)
mode_ctl2 |= NV50_EVO_DAC_MODE_CTRL2_NVSYNC;
ret = RING_SPACE(evo, 3);
if (ret) {
NV_ERROR(dev, "no space while connecting DAC\n");
return;
}
BEGIN_RING(evo, 0, NV50_EVO_DAC(nv_encoder->or, MODE_CTRL), 2);
OUT_RING(evo, mode_ctl);
OUT_RING(evo, mode_ctl2);
nv_encoder->crtc = encoder->crtc;
}
static struct drm_crtc *
nv50_dac_crtc_get(struct drm_encoder *encoder)
{
return nouveau_encoder(encoder)->crtc;
}
static const struct drm_encoder_helper_funcs nv50_dac_helper_funcs = {
.dpms = nv50_dac_dpms,
.save = nv50_dac_save,
.restore = nv50_dac_restore,
.mode_fixup = nv50_dac_mode_fixup,
.prepare = nv50_dac_disconnect,
.commit = nv50_dac_commit,
.mode_set = nv50_dac_mode_set,
.get_crtc = nv50_dac_crtc_get,
.detect = nv50_dac_detect,
.disable = nv50_dac_disconnect
};
static void
nv50_dac_destroy(struct drm_encoder *encoder)
{
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
if (!encoder)
return;
NV_DEBUG_KMS(encoder->dev, "\n");
drm_encoder_cleanup(encoder);
kfree(nv_encoder);
}
static const struct drm_encoder_funcs nv50_dac_encoder_funcs = {
.destroy = nv50_dac_destroy,
};
int
nv50_dac_create(struct drm_connector *connector, struct dcb_entry *entry)
{
struct nouveau_encoder *nv_encoder;
struct drm_encoder *encoder;
nv_encoder = kzalloc(sizeof(*nv_encoder), GFP_KERNEL);
if (!nv_encoder)
return -ENOMEM;
encoder = to_drm_encoder(nv_encoder);
nv_encoder->dcb = entry;
nv_encoder->or = ffs(entry->or) - 1;
drm_encoder_init(connector->dev, encoder, &nv50_dac_encoder_funcs,
DRM_MODE_ENCODER_DAC);
drm_encoder_helper_add(encoder, &nv50_dac_helper_funcs);
encoder->possible_crtcs = entry->heads;
encoder->possible_clones = 0;
drm_mode_connector_attach_encoder(connector, encoder);
return 0;
}
| gpl-2.0 |
jeboo/kernel_JB_i337_ATT_MJ9 | net/netlabel/netlabel_addrlist.c | 7558 | 10564 | /*
* NetLabel Network Address Lists
*
* This file contains network address list functions used to manage ordered
* lists of network addresses for use by the NetLabel subsystem. The NetLabel
* system manages static and dynamic label mappings for network protocols such
* as CIPSO and RIPSO.
*
* Author: Paul Moore <paul@paul-moore.com>
*
*/
/*
* (c) Copyright Hewlett-Packard Development Company, L.P., 2008
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/types.h>
#include <linux/rcupdate.h>
#include <linux/list.h>
#include <linux/spinlock.h>
#include <linux/in.h>
#include <linux/in6.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <linux/audit.h>
#include "netlabel_addrlist.h"
/*
* Address List Functions
*/
/**
* netlbl_af4list_search - Search for a matching IPv4 address entry
* @addr: IPv4 address
* @head: the list head
*
* Description:
* Searches the IPv4 address list given by @head. If a matching address entry
* is found it is returned, otherwise NULL is returned. The caller is
* responsible for calling the rcu_read_[un]lock() functions.
*
*/
struct netlbl_af4list *netlbl_af4list_search(__be32 addr,
struct list_head *head)
{
struct netlbl_af4list *iter;
list_for_each_entry_rcu(iter, head, list)
if (iter->valid && (addr & iter->mask) == iter->addr)
return iter;
return NULL;
}
/**
* netlbl_af4list_search_exact - Search for an exact IPv4 address entry
* @addr: IPv4 address
* @mask: IPv4 address mask
* @head: the list head
*
* Description:
* Searches the IPv4 address list given by @head. If an exact match if found
* it is returned, otherwise NULL is returned. The caller is responsible for
* calling the rcu_read_[un]lock() functions.
*
*/
struct netlbl_af4list *netlbl_af4list_search_exact(__be32 addr,
__be32 mask,
struct list_head *head)
{
struct netlbl_af4list *iter;
list_for_each_entry_rcu(iter, head, list)
if (iter->valid && iter->addr == addr && iter->mask == mask)
return iter;
return NULL;
}
#if IS_ENABLED(CONFIG_IPV6)
/**
* netlbl_af6list_search - Search for a matching IPv6 address entry
* @addr: IPv6 address
* @head: the list head
*
* Description:
* Searches the IPv6 address list given by @head. If a matching address entry
* is found it is returned, otherwise NULL is returned. The caller is
* responsible for calling the rcu_read_[un]lock() functions.
*
*/
struct netlbl_af6list *netlbl_af6list_search(const struct in6_addr *addr,
struct list_head *head)
{
struct netlbl_af6list *iter;
list_for_each_entry_rcu(iter, head, list)
if (iter->valid &&
ipv6_masked_addr_cmp(&iter->addr, &iter->mask, addr) == 0)
return iter;
return NULL;
}
/**
* netlbl_af6list_search_exact - Search for an exact IPv6 address entry
* @addr: IPv6 address
* @mask: IPv6 address mask
* @head: the list head
*
* Description:
* Searches the IPv6 address list given by @head. If an exact match if found
* it is returned, otherwise NULL is returned. The caller is responsible for
* calling the rcu_read_[un]lock() functions.
*
*/
struct netlbl_af6list *netlbl_af6list_search_exact(const struct in6_addr *addr,
const struct in6_addr *mask,
struct list_head *head)
{
struct netlbl_af6list *iter;
list_for_each_entry_rcu(iter, head, list)
if (iter->valid &&
ipv6_addr_equal(&iter->addr, addr) &&
ipv6_addr_equal(&iter->mask, mask))
return iter;
return NULL;
}
#endif /* IPv6 */
/**
* netlbl_af4list_add - Add a new IPv4 address entry to a list
* @entry: address entry
* @head: the list head
*
* Description:
* Add a new address entry to the list pointed to by @head. On success zero is
* returned, otherwise a negative value is returned. The caller is responsible
* for calling the necessary locking functions.
*
*/
int netlbl_af4list_add(struct netlbl_af4list *entry, struct list_head *head)
{
struct netlbl_af4list *iter;
iter = netlbl_af4list_search(entry->addr, head);
if (iter != NULL &&
iter->addr == entry->addr && iter->mask == entry->mask)
return -EEXIST;
/* in order to speed up address searches through the list (the common
* case) we need to keep the list in order based on the size of the
* address mask such that the entry with the widest mask (smallest
* numerical value) appears first in the list */
list_for_each_entry_rcu(iter, head, list)
if (iter->valid &&
ntohl(entry->mask) > ntohl(iter->mask)) {
__list_add_rcu(&entry->list,
iter->list.prev,
&iter->list);
return 0;
}
list_add_tail_rcu(&entry->list, head);
return 0;
}
#if IS_ENABLED(CONFIG_IPV6)
/**
* netlbl_af6list_add - Add a new IPv6 address entry to a list
* @entry: address entry
* @head: the list head
*
* Description:
* Add a new address entry to the list pointed to by @head. On success zero is
* returned, otherwise a negative value is returned. The caller is responsible
* for calling the necessary locking functions.
*
*/
int netlbl_af6list_add(struct netlbl_af6list *entry, struct list_head *head)
{
struct netlbl_af6list *iter;
iter = netlbl_af6list_search(&entry->addr, head);
if (iter != NULL &&
ipv6_addr_equal(&iter->addr, &entry->addr) &&
ipv6_addr_equal(&iter->mask, &entry->mask))
return -EEXIST;
/* in order to speed up address searches through the list (the common
* case) we need to keep the list in order based on the size of the
* address mask such that the entry with the widest mask (smallest
* numerical value) appears first in the list */
list_for_each_entry_rcu(iter, head, list)
if (iter->valid &&
ipv6_addr_cmp(&entry->mask, &iter->mask) > 0) {
__list_add_rcu(&entry->list,
iter->list.prev,
&iter->list);
return 0;
}
list_add_tail_rcu(&entry->list, head);
return 0;
}
#endif /* IPv6 */
/**
* netlbl_af4list_remove_entry - Remove an IPv4 address entry
* @entry: address entry
*
* Description:
* Remove the specified IP address entry. The caller is responsible for
* calling the necessary locking functions.
*
*/
void netlbl_af4list_remove_entry(struct netlbl_af4list *entry)
{
entry->valid = 0;
list_del_rcu(&entry->list);
}
/**
* netlbl_af4list_remove - Remove an IPv4 address entry
* @addr: IP address
* @mask: IP address mask
* @head: the list head
*
* Description:
* Remove an IP address entry from the list pointed to by @head. Returns the
* entry on success, NULL on failure. The caller is responsible for calling
* the necessary locking functions.
*
*/
struct netlbl_af4list *netlbl_af4list_remove(__be32 addr, __be32 mask,
struct list_head *head)
{
struct netlbl_af4list *entry;
entry = netlbl_af4list_search_exact(addr, mask, head);
if (entry == NULL)
return NULL;
netlbl_af4list_remove_entry(entry);
return entry;
}
#if IS_ENABLED(CONFIG_IPV6)
/**
* netlbl_af6list_remove_entry - Remove an IPv6 address entry
* @entry: address entry
*
* Description:
* Remove the specified IP address entry. The caller is responsible for
* calling the necessary locking functions.
*
*/
void netlbl_af6list_remove_entry(struct netlbl_af6list *entry)
{
entry->valid = 0;
list_del_rcu(&entry->list);
}
/**
* netlbl_af6list_remove - Remove an IPv6 address entry
* @addr: IP address
* @mask: IP address mask
* @head: the list head
*
* Description:
* Remove an IP address entry from the list pointed to by @head. Returns the
* entry on success, NULL on failure. The caller is responsible for calling
* the necessary locking functions.
*
*/
struct netlbl_af6list *netlbl_af6list_remove(const struct in6_addr *addr,
const struct in6_addr *mask,
struct list_head *head)
{
struct netlbl_af6list *entry;
entry = netlbl_af6list_search_exact(addr, mask, head);
if (entry == NULL)
return NULL;
netlbl_af6list_remove_entry(entry);
return entry;
}
#endif /* IPv6 */
/*
* Audit Helper Functions
*/
#ifdef CONFIG_AUDIT
/**
* netlbl_af4list_audit_addr - Audit an IPv4 address
* @audit_buf: audit buffer
* @src: true if source address, false if destination
* @dev: network interface
* @addr: IP address
* @mask: IP address mask
*
* Description:
* Write the IPv4 address and address mask, if necessary, to @audit_buf.
*
*/
void netlbl_af4list_audit_addr(struct audit_buffer *audit_buf,
int src, const char *dev,
__be32 addr, __be32 mask)
{
u32 mask_val = ntohl(mask);
char *dir = (src ? "src" : "dst");
if (dev != NULL)
audit_log_format(audit_buf, " netif=%s", dev);
audit_log_format(audit_buf, " %s=%pI4", dir, &addr);
if (mask_val != 0xffffffff) {
u32 mask_len = 0;
while (mask_val > 0) {
mask_val <<= 1;
mask_len++;
}
audit_log_format(audit_buf, " %s_prefixlen=%d", dir, mask_len);
}
}
#if IS_ENABLED(CONFIG_IPV6)
/**
* netlbl_af6list_audit_addr - Audit an IPv6 address
* @audit_buf: audit buffer
* @src: true if source address, false if destination
* @dev: network interface
* @addr: IP address
* @mask: IP address mask
*
* Description:
* Write the IPv6 address and address mask, if necessary, to @audit_buf.
*
*/
void netlbl_af6list_audit_addr(struct audit_buffer *audit_buf,
int src,
const char *dev,
const struct in6_addr *addr,
const struct in6_addr *mask)
{
char *dir = (src ? "src" : "dst");
if (dev != NULL)
audit_log_format(audit_buf, " netif=%s", dev);
audit_log_format(audit_buf, " %s=%pI6", dir, addr);
if (ntohl(mask->s6_addr32[3]) != 0xffffffff) {
u32 mask_len = 0;
u32 mask_val;
int iter = -1;
while (ntohl(mask->s6_addr32[++iter]) == 0xffffffff)
mask_len += 32;
mask_val = ntohl(mask->s6_addr32[iter]);
while (mask_val > 0) {
mask_val <<= 1;
mask_len++;
}
audit_log_format(audit_buf, " %s_prefixlen=%d", dir, mask_len);
}
}
#endif /* IPv6 */
#endif /* CONFIG_AUDIT */
| gpl-2.0 |
WesternStar/tilinux | drivers/firmware/iscsi_ibft.c | 7814 | 19695 | /*
* Copyright 2007-2010 Red Hat, Inc.
* by Peter Jones <pjones@redhat.com>
* Copyright 2008 IBM, Inc.
* by Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Copyright 2008
* by Konrad Rzeszutek <ketuzsezr@darnok.org>
*
* This code exposes the iSCSI Boot Format Table to userland via sysfs.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License v2.0 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.
*
* Changelog:
*
* 06 Jan 2010 - Peter Jones <pjones@redhat.com>
* New changelog entries are in the git log from now on. Not here.
*
* 14 Mar 2008 - Konrad Rzeszutek <ketuzsezr@darnok.org>
* Updated comments and copyrights. (v0.4.9)
*
* 11 Feb 2008 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Converted to using ibft_addr. (v0.4.8)
*
* 8 Feb 2008 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Combined two functions in one: reserve_ibft_region. (v0.4.7)
*
* 30 Jan 2008 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Added logic to handle IPv6 addresses. (v0.4.6)
*
* 25 Jan 2008 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Added logic to handle badly not-to-spec iBFT. (v0.4.5)
*
* 4 Jan 2008 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Added __init to function declarations. (v0.4.4)
*
* 21 Dec 2007 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Updated kobject registration, combined unregister functions in one
* and code and style cleanup. (v0.4.3)
*
* 5 Dec 2007 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Added end-markers to enums and re-organized kobject registration. (v0.4.2)
*
* 4 Dec 2007 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Created 'device' sysfs link to the NIC and style cleanup. (v0.4.1)
*
* 28 Nov 2007 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Added sysfs-ibft documentation, moved 'find_ibft' function to
* in its own file and added text attributes for every struct field. (v0.4)
*
* 21 Nov 2007 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Added text attributes emulating OpenFirmware /proc/device-tree naming.
* Removed binary /sysfs interface (v0.3)
*
* 29 Aug 2007 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* Added functionality in setup.c to reserve iBFT region. (v0.2)
*
* 27 Aug 2007 - Konrad Rzeszutek <konradr@linux.vnet.ibm.com>
* First version exposing iBFT data via a binary /sysfs. (v0.1)
*
*/
#include <linux/blkdev.h>
#include <linux/capability.h>
#include <linux/ctype.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/iscsi_ibft.h>
#include <linux/limits.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/stat.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/acpi.h>
#include <linux/iscsi_boot_sysfs.h>
#define IBFT_ISCSI_VERSION "0.5.0"
#define IBFT_ISCSI_DATE "2010-Feb-25"
MODULE_AUTHOR("Peter Jones <pjones@redhat.com> and "
"Konrad Rzeszutek <ketuzsezr@darnok.org>");
MODULE_DESCRIPTION("sysfs interface to BIOS iBFT information");
MODULE_LICENSE("GPL");
MODULE_VERSION(IBFT_ISCSI_VERSION);
struct ibft_hdr {
u8 id;
u8 version;
u16 length;
u8 index;
u8 flags;
} __attribute__((__packed__));
struct ibft_control {
struct ibft_hdr hdr;
u16 extensions;
u16 initiator_off;
u16 nic0_off;
u16 tgt0_off;
u16 nic1_off;
u16 tgt1_off;
} __attribute__((__packed__));
struct ibft_initiator {
struct ibft_hdr hdr;
char isns_server[16];
char slp_server[16];
char pri_radius_server[16];
char sec_radius_server[16];
u16 initiator_name_len;
u16 initiator_name_off;
} __attribute__((__packed__));
struct ibft_nic {
struct ibft_hdr hdr;
char ip_addr[16];
u8 subnet_mask_prefix;
u8 origin;
char gateway[16];
char primary_dns[16];
char secondary_dns[16];
char dhcp[16];
u16 vlan;
char mac[6];
u16 pci_bdf;
u16 hostname_len;
u16 hostname_off;
} __attribute__((__packed__));
struct ibft_tgt {
struct ibft_hdr hdr;
char ip_addr[16];
u16 port;
char lun[8];
u8 chap_type;
u8 nic_assoc;
u16 tgt_name_len;
u16 tgt_name_off;
u16 chap_name_len;
u16 chap_name_off;
u16 chap_secret_len;
u16 chap_secret_off;
u16 rev_chap_name_len;
u16 rev_chap_name_off;
u16 rev_chap_secret_len;
u16 rev_chap_secret_off;
} __attribute__((__packed__));
/*
* The kobject different types and its names.
*
*/
enum ibft_id {
id_reserved = 0, /* We don't support. */
id_control = 1, /* Should show up only once and is not exported. */
id_initiator = 2,
id_nic = 3,
id_target = 4,
id_extensions = 5, /* We don't support. */
id_end_marker,
};
/*
* The kobject and attribute structures.
*/
struct ibft_kobject {
struct acpi_table_ibft *header;
union {
struct ibft_initiator *initiator;
struct ibft_nic *nic;
struct ibft_tgt *tgt;
struct ibft_hdr *hdr;
};
};
static struct iscsi_boot_kset *boot_kset;
static const char nulls[16];
/*
* Helper functions to parse data properly.
*/
static ssize_t sprintf_ipaddr(char *buf, u8 *ip)
{
char *str = buf;
if (ip[0] == 0 && ip[1] == 0 && ip[2] == 0 && ip[3] == 0 &&
ip[4] == 0 && ip[5] == 0 && ip[6] == 0 && ip[7] == 0 &&
ip[8] == 0 && ip[9] == 0 && ip[10] == 0xff && ip[11] == 0xff) {
/*
* IPV4
*/
str += sprintf(buf, "%pI4", ip + 12);
} else {
/*
* IPv6
*/
str += sprintf(str, "%pI6", ip);
}
str += sprintf(str, "\n");
return str - buf;
}
static ssize_t sprintf_string(char *str, int len, char *buf)
{
return sprintf(str, "%.*s\n", len, buf);
}
/*
* Helper function to verify the IBFT header.
*/
static int ibft_verify_hdr(char *t, struct ibft_hdr *hdr, int id, int length)
{
if (hdr->id != id) {
printk(KERN_ERR "iBFT error: We expected the %s " \
"field header.id to have %d but " \
"found %d instead!\n", t, id, hdr->id);
return -ENODEV;
}
if (hdr->length != length) {
printk(KERN_ERR "iBFT error: We expected the %s " \
"field header.length to have %d but " \
"found %d instead!\n", t, length, hdr->length);
return -ENODEV;
}
return 0;
}
/*
* Routines for parsing the iBFT data to be human readable.
*/
static ssize_t ibft_attr_show_initiator(void *data, int type, char *buf)
{
struct ibft_kobject *entry = data;
struct ibft_initiator *initiator = entry->initiator;
void *ibft_loc = entry->header;
char *str = buf;
if (!initiator)
return 0;
switch (type) {
case ISCSI_BOOT_INI_INDEX:
str += sprintf(str, "%d\n", initiator->hdr.index);
break;
case ISCSI_BOOT_INI_FLAGS:
str += sprintf(str, "%d\n", initiator->hdr.flags);
break;
case ISCSI_BOOT_INI_ISNS_SERVER:
str += sprintf_ipaddr(str, initiator->isns_server);
break;
case ISCSI_BOOT_INI_SLP_SERVER:
str += sprintf_ipaddr(str, initiator->slp_server);
break;
case ISCSI_BOOT_INI_PRI_RADIUS_SERVER:
str += sprintf_ipaddr(str, initiator->pri_radius_server);
break;
case ISCSI_BOOT_INI_SEC_RADIUS_SERVER:
str += sprintf_ipaddr(str, initiator->sec_radius_server);
break;
case ISCSI_BOOT_INI_INITIATOR_NAME:
str += sprintf_string(str, initiator->initiator_name_len,
(char *)ibft_loc +
initiator->initiator_name_off);
break;
default:
break;
}
return str - buf;
}
static ssize_t ibft_attr_show_nic(void *data, int type, char *buf)
{
struct ibft_kobject *entry = data;
struct ibft_nic *nic = entry->nic;
void *ibft_loc = entry->header;
char *str = buf;
__be32 val;
if (!nic)
return 0;
switch (type) {
case ISCSI_BOOT_ETH_INDEX:
str += sprintf(str, "%d\n", nic->hdr.index);
break;
case ISCSI_BOOT_ETH_FLAGS:
str += sprintf(str, "%d\n", nic->hdr.flags);
break;
case ISCSI_BOOT_ETH_IP_ADDR:
str += sprintf_ipaddr(str, nic->ip_addr);
break;
case ISCSI_BOOT_ETH_SUBNET_MASK:
val = cpu_to_be32(~((1 << (32-nic->subnet_mask_prefix))-1));
str += sprintf(str, "%pI4", &val);
break;
case ISCSI_BOOT_ETH_ORIGIN:
str += sprintf(str, "%d\n", nic->origin);
break;
case ISCSI_BOOT_ETH_GATEWAY:
str += sprintf_ipaddr(str, nic->gateway);
break;
case ISCSI_BOOT_ETH_PRIMARY_DNS:
str += sprintf_ipaddr(str, nic->primary_dns);
break;
case ISCSI_BOOT_ETH_SECONDARY_DNS:
str += sprintf_ipaddr(str, nic->secondary_dns);
break;
case ISCSI_BOOT_ETH_DHCP:
str += sprintf_ipaddr(str, nic->dhcp);
break;
case ISCSI_BOOT_ETH_VLAN:
str += sprintf(str, "%d\n", nic->vlan);
break;
case ISCSI_BOOT_ETH_MAC:
str += sprintf(str, "%pM\n", nic->mac);
break;
case ISCSI_BOOT_ETH_HOSTNAME:
str += sprintf_string(str, nic->hostname_len,
(char *)ibft_loc + nic->hostname_off);
break;
default:
break;
}
return str - buf;
};
static ssize_t ibft_attr_show_target(void *data, int type, char *buf)
{
struct ibft_kobject *entry = data;
struct ibft_tgt *tgt = entry->tgt;
void *ibft_loc = entry->header;
char *str = buf;
int i;
if (!tgt)
return 0;
switch (type) {
case ISCSI_BOOT_TGT_INDEX:
str += sprintf(str, "%d\n", tgt->hdr.index);
break;
case ISCSI_BOOT_TGT_FLAGS:
str += sprintf(str, "%d\n", tgt->hdr.flags);
break;
case ISCSI_BOOT_TGT_IP_ADDR:
str += sprintf_ipaddr(str, tgt->ip_addr);
break;
case ISCSI_BOOT_TGT_PORT:
str += sprintf(str, "%d\n", tgt->port);
break;
case ISCSI_BOOT_TGT_LUN:
for (i = 0; i < 8; i++)
str += sprintf(str, "%x", (u8)tgt->lun[i]);
str += sprintf(str, "\n");
break;
case ISCSI_BOOT_TGT_NIC_ASSOC:
str += sprintf(str, "%d\n", tgt->nic_assoc);
break;
case ISCSI_BOOT_TGT_CHAP_TYPE:
str += sprintf(str, "%d\n", tgt->chap_type);
break;
case ISCSI_BOOT_TGT_NAME:
str += sprintf_string(str, tgt->tgt_name_len,
(char *)ibft_loc + tgt->tgt_name_off);
break;
case ISCSI_BOOT_TGT_CHAP_NAME:
str += sprintf_string(str, tgt->chap_name_len,
(char *)ibft_loc + tgt->chap_name_off);
break;
case ISCSI_BOOT_TGT_CHAP_SECRET:
str += sprintf_string(str, tgt->chap_secret_len,
(char *)ibft_loc + tgt->chap_secret_off);
break;
case ISCSI_BOOT_TGT_REV_CHAP_NAME:
str += sprintf_string(str, tgt->rev_chap_name_len,
(char *)ibft_loc +
tgt->rev_chap_name_off);
break;
case ISCSI_BOOT_TGT_REV_CHAP_SECRET:
str += sprintf_string(str, tgt->rev_chap_secret_len,
(char *)ibft_loc +
tgt->rev_chap_secret_off);
break;
default:
break;
}
return str - buf;
}
static int __init ibft_check_device(void)
{
int len;
u8 *pos;
u8 csum = 0;
len = ibft_addr->header.length;
/* Sanity checking of iBFT. */
if (ibft_addr->header.revision != 1) {
printk(KERN_ERR "iBFT module supports only revision 1, " \
"while this is %d.\n",
ibft_addr->header.revision);
return -ENOENT;
}
for (pos = (u8 *)ibft_addr; pos < (u8 *)ibft_addr + len; pos++)
csum += *pos;
if (csum) {
printk(KERN_ERR "iBFT has incorrect checksum (0x%x)!\n", csum);
return -ENOENT;
}
return 0;
}
/*
* Helper routiners to check to determine if the entry is valid
* in the proper iBFT structure.
*/
static umode_t ibft_check_nic_for(void *data, int type)
{
struct ibft_kobject *entry = data;
struct ibft_nic *nic = entry->nic;
umode_t rc = 0;
switch (type) {
case ISCSI_BOOT_ETH_INDEX:
case ISCSI_BOOT_ETH_FLAGS:
rc = S_IRUGO;
break;
case ISCSI_BOOT_ETH_IP_ADDR:
if (memcmp(nic->ip_addr, nulls, sizeof(nic->ip_addr)))
rc = S_IRUGO;
break;
case ISCSI_BOOT_ETH_SUBNET_MASK:
if (nic->subnet_mask_prefix)
rc = S_IRUGO;
break;
case ISCSI_BOOT_ETH_ORIGIN:
rc = S_IRUGO;
break;
case ISCSI_BOOT_ETH_GATEWAY:
if (memcmp(nic->gateway, nulls, sizeof(nic->gateway)))
rc = S_IRUGO;
break;
case ISCSI_BOOT_ETH_PRIMARY_DNS:
if (memcmp(nic->primary_dns, nulls,
sizeof(nic->primary_dns)))
rc = S_IRUGO;
break;
case ISCSI_BOOT_ETH_SECONDARY_DNS:
if (memcmp(nic->secondary_dns, nulls,
sizeof(nic->secondary_dns)))
rc = S_IRUGO;
break;
case ISCSI_BOOT_ETH_DHCP:
if (memcmp(nic->dhcp, nulls, sizeof(nic->dhcp)))
rc = S_IRUGO;
break;
case ISCSI_BOOT_ETH_VLAN:
case ISCSI_BOOT_ETH_MAC:
rc = S_IRUGO;
break;
case ISCSI_BOOT_ETH_HOSTNAME:
if (nic->hostname_off)
rc = S_IRUGO;
break;
default:
break;
}
return rc;
}
static umode_t __init ibft_check_tgt_for(void *data, int type)
{
struct ibft_kobject *entry = data;
struct ibft_tgt *tgt = entry->tgt;
umode_t rc = 0;
switch (type) {
case ISCSI_BOOT_TGT_INDEX:
case ISCSI_BOOT_TGT_FLAGS:
case ISCSI_BOOT_TGT_IP_ADDR:
case ISCSI_BOOT_TGT_PORT:
case ISCSI_BOOT_TGT_LUN:
case ISCSI_BOOT_TGT_NIC_ASSOC:
case ISCSI_BOOT_TGT_CHAP_TYPE:
rc = S_IRUGO;
case ISCSI_BOOT_TGT_NAME:
if (tgt->tgt_name_len)
rc = S_IRUGO;
break;
case ISCSI_BOOT_TGT_CHAP_NAME:
case ISCSI_BOOT_TGT_CHAP_SECRET:
if (tgt->chap_name_len)
rc = S_IRUGO;
break;
case ISCSI_BOOT_TGT_REV_CHAP_NAME:
case ISCSI_BOOT_TGT_REV_CHAP_SECRET:
if (tgt->rev_chap_name_len)
rc = S_IRUGO;
break;
default:
break;
}
return rc;
}
static umode_t __init ibft_check_initiator_for(void *data, int type)
{
struct ibft_kobject *entry = data;
struct ibft_initiator *init = entry->initiator;
umode_t rc = 0;
switch (type) {
case ISCSI_BOOT_INI_INDEX:
case ISCSI_BOOT_INI_FLAGS:
rc = S_IRUGO;
break;
case ISCSI_BOOT_INI_ISNS_SERVER:
if (memcmp(init->isns_server, nulls,
sizeof(init->isns_server)))
rc = S_IRUGO;
break;
case ISCSI_BOOT_INI_SLP_SERVER:
if (memcmp(init->slp_server, nulls,
sizeof(init->slp_server)))
rc = S_IRUGO;
break;
case ISCSI_BOOT_INI_PRI_RADIUS_SERVER:
if (memcmp(init->pri_radius_server, nulls,
sizeof(init->pri_radius_server)))
rc = S_IRUGO;
break;
case ISCSI_BOOT_INI_SEC_RADIUS_SERVER:
if (memcmp(init->sec_radius_server, nulls,
sizeof(init->sec_radius_server)))
rc = S_IRUGO;
break;
case ISCSI_BOOT_INI_INITIATOR_NAME:
if (init->initiator_name_len)
rc = S_IRUGO;
break;
default:
break;
}
return rc;
}
static void ibft_kobj_release(void *data)
{
kfree(data);
}
/*
* Helper function for ibft_register_kobjects.
*/
static int __init ibft_create_kobject(struct acpi_table_ibft *header,
struct ibft_hdr *hdr)
{
struct iscsi_boot_kobj *boot_kobj = NULL;
struct ibft_kobject *ibft_kobj = NULL;
struct ibft_nic *nic = (struct ibft_nic *)hdr;
struct pci_dev *pci_dev;
int rc = 0;
ibft_kobj = kzalloc(sizeof(*ibft_kobj), GFP_KERNEL);
if (!ibft_kobj)
return -ENOMEM;
ibft_kobj->header = header;
ibft_kobj->hdr = hdr;
switch (hdr->id) {
case id_initiator:
rc = ibft_verify_hdr("initiator", hdr, id_initiator,
sizeof(*ibft_kobj->initiator));
if (rc)
break;
boot_kobj = iscsi_boot_create_initiator(boot_kset, hdr->index,
ibft_kobj,
ibft_attr_show_initiator,
ibft_check_initiator_for,
ibft_kobj_release);
if (!boot_kobj) {
rc = -ENOMEM;
goto free_ibft_obj;
}
break;
case id_nic:
rc = ibft_verify_hdr("ethernet", hdr, id_nic,
sizeof(*ibft_kobj->nic));
if (rc)
break;
boot_kobj = iscsi_boot_create_ethernet(boot_kset, hdr->index,
ibft_kobj,
ibft_attr_show_nic,
ibft_check_nic_for,
ibft_kobj_release);
if (!boot_kobj) {
rc = -ENOMEM;
goto free_ibft_obj;
}
break;
case id_target:
rc = ibft_verify_hdr("target", hdr, id_target,
sizeof(*ibft_kobj->tgt));
if (rc)
break;
boot_kobj = iscsi_boot_create_target(boot_kset, hdr->index,
ibft_kobj,
ibft_attr_show_target,
ibft_check_tgt_for,
ibft_kobj_release);
if (!boot_kobj) {
rc = -ENOMEM;
goto free_ibft_obj;
}
break;
case id_reserved:
case id_control:
case id_extensions:
/* Fields which we don't support. Ignore them */
rc = 1;
break;
default:
printk(KERN_ERR "iBFT has unknown structure type (%d). " \
"Report this bug to %.6s!\n", hdr->id,
header->header.oem_id);
rc = 1;
break;
}
if (rc) {
/* Skip adding this kobject, but exit with non-fatal error. */
rc = 0;
goto free_ibft_obj;
}
if (hdr->id == id_nic) {
/*
* We don't search for the device in other domains than
* zero. This is because on x86 platforms the BIOS
* executes only devices which are in domain 0. Furthermore, the
* iBFT spec doesn't have a domain id field :-(
*/
pci_dev = pci_get_bus_and_slot((nic->pci_bdf & 0xff00) >> 8,
(nic->pci_bdf & 0xff));
if (pci_dev) {
rc = sysfs_create_link(&boot_kobj->kobj,
&pci_dev->dev.kobj, "device");
pci_dev_put(pci_dev);
}
}
return 0;
free_ibft_obj:
kfree(ibft_kobj);
return rc;
}
/*
* Scan the IBFT table structure for the NIC and Target fields. When
* found add them on the passed-in list. We do not support the other
* fields at this point, so they are skipped.
*/
static int __init ibft_register_kobjects(struct acpi_table_ibft *header)
{
struct ibft_control *control = NULL;
void *ptr, *end;
int rc = 0;
u16 offset;
u16 eot_offset;
control = (void *)header + sizeof(*header);
end = (void *)control + control->hdr.length;
eot_offset = (void *)header + header->header.length - (void *)control;
rc = ibft_verify_hdr("control", (struct ibft_hdr *)control, id_control,
sizeof(*control));
/* iBFT table safety checking */
rc |= ((control->hdr.index) ? -ENODEV : 0);
if (rc) {
printk(KERN_ERR "iBFT error: Control header is invalid!\n");
return rc;
}
for (ptr = &control->initiator_off; ptr < end; ptr += sizeof(u16)) {
offset = *(u16 *)ptr;
if (offset && offset < header->header.length &&
offset < eot_offset) {
rc = ibft_create_kobject(header,
(void *)header + offset);
if (rc)
break;
}
}
return rc;
}
static void ibft_unregister(void)
{
struct iscsi_boot_kobj *boot_kobj, *tmp_kobj;
struct ibft_kobject *ibft_kobj;
list_for_each_entry_safe(boot_kobj, tmp_kobj,
&boot_kset->kobj_list, list) {
ibft_kobj = boot_kobj->data;
if (ibft_kobj->hdr->id == id_nic)
sysfs_remove_link(&boot_kobj->kobj, "device");
};
}
static void ibft_cleanup(void)
{
if (boot_kset) {
ibft_unregister();
iscsi_boot_destroy_kset(boot_kset);
}
}
static void __exit ibft_exit(void)
{
ibft_cleanup();
}
#ifdef CONFIG_ACPI
static const struct {
char *sign;
} ibft_signs[] = {
/*
* One spec says "IBFT", the other says "iBFT". We have to check
* for both.
*/
{ ACPI_SIG_IBFT },
{ "iBFT" },
};
static void __init acpi_find_ibft_region(void)
{
int i;
struct acpi_table_header *table = NULL;
if (acpi_disabled)
return;
for (i = 0; i < ARRAY_SIZE(ibft_signs) && !ibft_addr; i++) {
acpi_get_table(ibft_signs[i].sign, 0, &table);
ibft_addr = (struct acpi_table_ibft *)table;
}
}
#else
static void __init acpi_find_ibft_region(void)
{
}
#endif
/*
* ibft_init() - creates sysfs tree entries for the iBFT data.
*/
static int __init ibft_init(void)
{
int rc = 0;
/*
As on UEFI systems the setup_arch()/find_ibft_region()
is called before ACPI tables are parsed and it only does
legacy finding.
*/
if (!ibft_addr)
acpi_find_ibft_region();
if (ibft_addr) {
pr_info("iBFT detected.\n");
rc = ibft_check_device();
if (rc)
return rc;
boot_kset = iscsi_boot_create_kset("ibft");
if (!boot_kset)
return -ENOMEM;
/* Scan the IBFT for data and register the kobjects. */
rc = ibft_register_kobjects(ibft_addr);
if (rc)
goto out_free;
} else
printk(KERN_INFO "No iBFT detected.\n");
return 0;
out_free:
ibft_cleanup();
return rc;
}
module_init(ibft_init);
module_exit(ibft_exit);
| gpl-2.0 |
agat63/L900_MA7_kernel | net/ipv4/tcp_westwood.c | 8326 | 8222 | /*
* TCP Westwood+: end-to-end bandwidth estimation for TCP
*
* Angelo Dell'Aera: author of the first version of TCP Westwood+ in Linux 2.4
*
* Support at http://c3lab.poliba.it/index.php/Westwood
* Main references in literature:
*
* - Mascolo S, Casetti, M. Gerla et al.
* "TCP Westwood: bandwidth estimation for TCP" Proc. ACM Mobicom 2001
*
* - A. Grieco, s. Mascolo
* "Performance evaluation of New Reno, Vegas, Westwood+ TCP" ACM Computer
* Comm. Review, 2004
*
* - A. Dell'Aera, L. Grieco, S. Mascolo.
* "Linux 2.4 Implementation of Westwood+ TCP with Rate-Halving :
* A Performance Evaluation Over the Internet" (ICC 2004), Paris, June 2004
*
* Westwood+ employs end-to-end bandwidth measurement to set cwnd and
* ssthresh after packet loss. The probing phase is as the original Reno.
*/
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/inet_diag.h>
#include <net/tcp.h>
/* TCP Westwood structure */
struct westwood {
u32 bw_ns_est; /* first bandwidth estimation..not too smoothed 8) */
u32 bw_est; /* bandwidth estimate */
u32 rtt_win_sx; /* here starts a new evaluation... */
u32 bk;
u32 snd_una; /* used for evaluating the number of acked bytes */
u32 cumul_ack;
u32 accounted;
u32 rtt;
u32 rtt_min; /* minimum observed RTT */
u8 first_ack; /* flag which infers that this is the first ack */
u8 reset_rtt_min; /* Reset RTT min to next RTT sample*/
};
/* TCP Westwood functions and constants */
#define TCP_WESTWOOD_RTT_MIN (HZ/20) /* 50ms */
#define TCP_WESTWOOD_INIT_RTT (20*HZ) /* maybe too conservative?! */
/*
* @tcp_westwood_create
* This function initializes fields used in TCP Westwood+,
* it is called after the initial SYN, so the sequence numbers
* are correct but new passive connections we have no
* information about RTTmin at this time so we simply set it to
* TCP_WESTWOOD_INIT_RTT. This value was chosen to be too conservative
* since in this way we're sure it will be updated in a consistent
* way as soon as possible. It will reasonably happen within the first
* RTT period of the connection lifetime.
*/
static void tcp_westwood_init(struct sock *sk)
{
struct westwood *w = inet_csk_ca(sk);
w->bk = 0;
w->bw_ns_est = 0;
w->bw_est = 0;
w->accounted = 0;
w->cumul_ack = 0;
w->reset_rtt_min = 1;
w->rtt_min = w->rtt = TCP_WESTWOOD_INIT_RTT;
w->rtt_win_sx = tcp_time_stamp;
w->snd_una = tcp_sk(sk)->snd_una;
w->first_ack = 1;
}
/*
* @westwood_do_filter
* Low-pass filter. Implemented using constant coefficients.
*/
static inline u32 westwood_do_filter(u32 a, u32 b)
{
return ((7 * a) + b) >> 3;
}
static void westwood_filter(struct westwood *w, u32 delta)
{
/* If the filter is empty fill it with the first sample of bandwidth */
if (w->bw_ns_est == 0 && w->bw_est == 0) {
w->bw_ns_est = w->bk / delta;
w->bw_est = w->bw_ns_est;
} else {
w->bw_ns_est = westwood_do_filter(w->bw_ns_est, w->bk / delta);
w->bw_est = westwood_do_filter(w->bw_est, w->bw_ns_est);
}
}
/*
* @westwood_pkts_acked
* Called after processing group of packets.
* but all westwood needs is the last sample of srtt.
*/
static void tcp_westwood_pkts_acked(struct sock *sk, u32 cnt, s32 rtt)
{
struct westwood *w = inet_csk_ca(sk);
if (rtt > 0)
w->rtt = usecs_to_jiffies(rtt);
}
/*
* @westwood_update_window
* It updates RTT evaluation window if it is the right moment to do
* it. If so it calls filter for evaluating bandwidth.
*/
static void westwood_update_window(struct sock *sk)
{
struct westwood *w = inet_csk_ca(sk);
s32 delta = tcp_time_stamp - w->rtt_win_sx;
/* Initialize w->snd_una with the first acked sequence number in order
* to fix mismatch between tp->snd_una and w->snd_una for the first
* bandwidth sample
*/
if (w->first_ack) {
w->snd_una = tcp_sk(sk)->snd_una;
w->first_ack = 0;
}
/*
* See if a RTT-window has passed.
* Be careful since if RTT is less than
* 50ms we don't filter but we continue 'building the sample'.
* This minimum limit was chosen since an estimation on small
* time intervals is better to avoid...
* Obviously on a LAN we reasonably will always have
* right_bound = left_bound + WESTWOOD_RTT_MIN
*/
if (w->rtt && delta > max_t(u32, w->rtt, TCP_WESTWOOD_RTT_MIN)) {
westwood_filter(w, delta);
w->bk = 0;
w->rtt_win_sx = tcp_time_stamp;
}
}
static inline void update_rtt_min(struct westwood *w)
{
if (w->reset_rtt_min) {
w->rtt_min = w->rtt;
w->reset_rtt_min = 0;
} else
w->rtt_min = min(w->rtt, w->rtt_min);
}
/*
* @westwood_fast_bw
* It is called when we are in fast path. In particular it is called when
* header prediction is successful. In such case in fact update is
* straight forward and doesn't need any particular care.
*/
static inline void westwood_fast_bw(struct sock *sk)
{
const struct tcp_sock *tp = tcp_sk(sk);
struct westwood *w = inet_csk_ca(sk);
westwood_update_window(sk);
w->bk += tp->snd_una - w->snd_una;
w->snd_una = tp->snd_una;
update_rtt_min(w);
}
/*
* @westwood_acked_count
* This function evaluates cumul_ack for evaluating bk in case of
* delayed or partial acks.
*/
static inline u32 westwood_acked_count(struct sock *sk)
{
const struct tcp_sock *tp = tcp_sk(sk);
struct westwood *w = inet_csk_ca(sk);
w->cumul_ack = tp->snd_una - w->snd_una;
/* If cumul_ack is 0 this is a dupack since it's not moving
* tp->snd_una.
*/
if (!w->cumul_ack) {
w->accounted += tp->mss_cache;
w->cumul_ack = tp->mss_cache;
}
if (w->cumul_ack > tp->mss_cache) {
/* Partial or delayed ack */
if (w->accounted >= w->cumul_ack) {
w->accounted -= w->cumul_ack;
w->cumul_ack = tp->mss_cache;
} else {
w->cumul_ack -= w->accounted;
w->accounted = 0;
}
}
w->snd_una = tp->snd_una;
return w->cumul_ack;
}
/*
* TCP Westwood
* Here limit is evaluated as Bw estimation*RTTmin (for obtaining it
* in packets we use mss_cache). Rttmin is guaranteed to be >= 2
* so avoids ever returning 0.
*/
static u32 tcp_westwood_bw_rttmin(const struct sock *sk)
{
const struct tcp_sock *tp = tcp_sk(sk);
const struct westwood *w = inet_csk_ca(sk);
return max_t(u32, (w->bw_est * w->rtt_min) / tp->mss_cache, 2);
}
static void tcp_westwood_event(struct sock *sk, enum tcp_ca_event event)
{
struct tcp_sock *tp = tcp_sk(sk);
struct westwood *w = inet_csk_ca(sk);
switch (event) {
case CA_EVENT_FAST_ACK:
westwood_fast_bw(sk);
break;
case CA_EVENT_COMPLETE_CWR:
tp->snd_cwnd = tp->snd_ssthresh = tcp_westwood_bw_rttmin(sk);
break;
case CA_EVENT_FRTO:
tp->snd_ssthresh = tcp_westwood_bw_rttmin(sk);
/* Update RTT_min when next ack arrives */
w->reset_rtt_min = 1;
break;
case CA_EVENT_SLOW_ACK:
westwood_update_window(sk);
w->bk += westwood_acked_count(sk);
update_rtt_min(w);
break;
default:
/* don't care */
break;
}
}
/* Extract info for Tcp socket info provided via netlink. */
static void tcp_westwood_info(struct sock *sk, u32 ext,
struct sk_buff *skb)
{
const struct westwood *ca = inet_csk_ca(sk);
if (ext & (1 << (INET_DIAG_VEGASINFO - 1))) {
struct tcpvegas_info info = {
.tcpv_enabled = 1,
.tcpv_rtt = jiffies_to_usecs(ca->rtt),
.tcpv_minrtt = jiffies_to_usecs(ca->rtt_min),
};
nla_put(skb, INET_DIAG_VEGASINFO, sizeof(info), &info);
}
}
static struct tcp_congestion_ops tcp_westwood __read_mostly = {
.init = tcp_westwood_init,
.ssthresh = tcp_reno_ssthresh,
.cong_avoid = tcp_reno_cong_avoid,
.min_cwnd = tcp_westwood_bw_rttmin,
.cwnd_event = tcp_westwood_event,
.get_info = tcp_westwood_info,
.pkts_acked = tcp_westwood_pkts_acked,
.owner = THIS_MODULE,
.name = "westwood"
};
static int __init tcp_westwood_register(void)
{
BUILD_BUG_ON(sizeof(struct westwood) > ICSK_CA_PRIV_SIZE);
return tcp_register_congestion_control(&tcp_westwood);
}
static void __exit tcp_westwood_unregister(void)
{
tcp_unregister_congestion_control(&tcp_westwood);
}
module_init(tcp_westwood_register);
module_exit(tcp_westwood_unregister);
MODULE_AUTHOR("Stephen Hemminger, Angelo Dell'Aera");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("TCP Westwood+");
| gpl-2.0 |
andr7e/rk3188_tablet_jb | kernel/lib/crc-t10dif.c | 12422 | 2965 | /*
* T10 Data Integrity Field CRC16 calculation
*
* Copyright (c) 2007 Oracle Corporation. All rights reserved.
* Written by Martin K. Petersen <martin.petersen@oracle.com>
*
* This source code is licensed under the GNU General Public License,
* Version 2. See the file COPYING for more details.
*/
#include <linux/types.h>
#include <linux/module.h>
#include <linux/crc-t10dif.h>
/* Table generated using the following polynomium:
* x^16 + x^15 + x^11 + x^9 + x^8 + x^7 + x^5 + x^4 + x^2 + x + 1
* gt: 0x8bb7
*/
static const __u16 t10_dif_crc_table[256] = {
0x0000, 0x8BB7, 0x9CD9, 0x176E, 0xB205, 0x39B2, 0x2EDC, 0xA56B,
0xEFBD, 0x640A, 0x7364, 0xF8D3, 0x5DB8, 0xD60F, 0xC161, 0x4AD6,
0x54CD, 0xDF7A, 0xC814, 0x43A3, 0xE6C8, 0x6D7F, 0x7A11, 0xF1A6,
0xBB70, 0x30C7, 0x27A9, 0xAC1E, 0x0975, 0x82C2, 0x95AC, 0x1E1B,
0xA99A, 0x222D, 0x3543, 0xBEF4, 0x1B9F, 0x9028, 0x8746, 0x0CF1,
0x4627, 0xCD90, 0xDAFE, 0x5149, 0xF422, 0x7F95, 0x68FB, 0xE34C,
0xFD57, 0x76E0, 0x618E, 0xEA39, 0x4F52, 0xC4E5, 0xD38B, 0x583C,
0x12EA, 0x995D, 0x8E33, 0x0584, 0xA0EF, 0x2B58, 0x3C36, 0xB781,
0xD883, 0x5334, 0x445A, 0xCFED, 0x6A86, 0xE131, 0xF65F, 0x7DE8,
0x373E, 0xBC89, 0xABE7, 0x2050, 0x853B, 0x0E8C, 0x19E2, 0x9255,
0x8C4E, 0x07F9, 0x1097, 0x9B20, 0x3E4B, 0xB5FC, 0xA292, 0x2925,
0x63F3, 0xE844, 0xFF2A, 0x749D, 0xD1F6, 0x5A41, 0x4D2F, 0xC698,
0x7119, 0xFAAE, 0xEDC0, 0x6677, 0xC31C, 0x48AB, 0x5FC5, 0xD472,
0x9EA4, 0x1513, 0x027D, 0x89CA, 0x2CA1, 0xA716, 0xB078, 0x3BCF,
0x25D4, 0xAE63, 0xB90D, 0x32BA, 0x97D1, 0x1C66, 0x0B08, 0x80BF,
0xCA69, 0x41DE, 0x56B0, 0xDD07, 0x786C, 0xF3DB, 0xE4B5, 0x6F02,
0x3AB1, 0xB106, 0xA668, 0x2DDF, 0x88B4, 0x0303, 0x146D, 0x9FDA,
0xD50C, 0x5EBB, 0x49D5, 0xC262, 0x6709, 0xECBE, 0xFBD0, 0x7067,
0x6E7C, 0xE5CB, 0xF2A5, 0x7912, 0xDC79, 0x57CE, 0x40A0, 0xCB17,
0x81C1, 0x0A76, 0x1D18, 0x96AF, 0x33C4, 0xB873, 0xAF1D, 0x24AA,
0x932B, 0x189C, 0x0FF2, 0x8445, 0x212E, 0xAA99, 0xBDF7, 0x3640,
0x7C96, 0xF721, 0xE04F, 0x6BF8, 0xCE93, 0x4524, 0x524A, 0xD9FD,
0xC7E6, 0x4C51, 0x5B3F, 0xD088, 0x75E3, 0xFE54, 0xE93A, 0x628D,
0x285B, 0xA3EC, 0xB482, 0x3F35, 0x9A5E, 0x11E9, 0x0687, 0x8D30,
0xE232, 0x6985, 0x7EEB, 0xF55C, 0x5037, 0xDB80, 0xCCEE, 0x4759,
0x0D8F, 0x8638, 0x9156, 0x1AE1, 0xBF8A, 0x343D, 0x2353, 0xA8E4,
0xB6FF, 0x3D48, 0x2A26, 0xA191, 0x04FA, 0x8F4D, 0x9823, 0x1394,
0x5942, 0xD2F5, 0xC59B, 0x4E2C, 0xEB47, 0x60F0, 0x779E, 0xFC29,
0x4BA8, 0xC01F, 0xD771, 0x5CC6, 0xF9AD, 0x721A, 0x6574, 0xEEC3,
0xA415, 0x2FA2, 0x38CC, 0xB37B, 0x1610, 0x9DA7, 0x8AC9, 0x017E,
0x1F65, 0x94D2, 0x83BC, 0x080B, 0xAD60, 0x26D7, 0x31B9, 0xBA0E,
0xF0D8, 0x7B6F, 0x6C01, 0xE7B6, 0x42DD, 0xC96A, 0xDE04, 0x55B3
};
__u16 crc_t10dif(const unsigned char *buffer, size_t len)
{
__u16 crc = 0;
unsigned int i;
for (i = 0 ; i < len ; i++)
crc = (crc << 8) ^ t10_dif_crc_table[((crc >> 8) ^ buffer[i]) & 0xff];
return crc;
}
EXPORT_SYMBOL(crc_t10dif);
MODULE_DESCRIPTION("T10 DIF CRC calculation");
MODULE_LICENSE("GPL");
| gpl-2.0 |
archfan/xu4-linux | lib/mpi/mpicoder.c | 135 | 11633 | /* mpicoder.c - Coder for the external representation of MPIs
* Copyright (C) 1998, 1999 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* GnuPG 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.
*
* GnuPG 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/bitops.h>
#include <linux/count_zeros.h>
#include "mpi-internal.h"
#define MAX_EXTERN_MPI_BITS 16384
/**
* mpi_read_raw_data - Read a raw byte stream as a positive integer
* @xbuffer: The data to read
* @nbytes: The amount of data to read
*/
MPI mpi_read_raw_data(const void *xbuffer, size_t nbytes)
{
const uint8_t *buffer = xbuffer;
int i, j;
unsigned nbits, nlimbs;
mpi_limb_t a;
MPI val = NULL;
while (nbytes > 0 && buffer[0] == 0) {
buffer++;
nbytes--;
}
nbits = nbytes * 8;
if (nbits > MAX_EXTERN_MPI_BITS) {
pr_info("MPI: mpi too large (%u bits)\n", nbits);
return NULL;
}
if (nbytes > 0)
nbits -= count_leading_zeros(buffer[0]);
else
nbits = 0;
nlimbs = DIV_ROUND_UP(nbytes, BYTES_PER_MPI_LIMB);
val = mpi_alloc(nlimbs);
if (!val)
return NULL;
val->nbits = nbits;
val->sign = 0;
val->nlimbs = nlimbs;
if (nbytes > 0) {
i = BYTES_PER_MPI_LIMB - nbytes % BYTES_PER_MPI_LIMB;
i %= BYTES_PER_MPI_LIMB;
for (j = nlimbs; j > 0; j--) {
a = 0;
for (; i < BYTES_PER_MPI_LIMB; i++) {
a <<= 8;
a |= *buffer++;
}
i = 0;
val->d[j - 1] = a;
}
}
return val;
}
EXPORT_SYMBOL_GPL(mpi_read_raw_data);
MPI mpi_read_from_buffer(const void *xbuffer, unsigned *ret_nread)
{
const uint8_t *buffer = xbuffer;
int i, j;
unsigned nbits, nbytes, nlimbs, nread = 0;
mpi_limb_t a;
MPI val = NULL;
if (*ret_nread < 2)
goto leave;
nbits = buffer[0] << 8 | buffer[1];
if (nbits > MAX_EXTERN_MPI_BITS) {
pr_info("MPI: mpi too large (%u bits)\n", nbits);
goto leave;
}
buffer += 2;
nread = 2;
nbytes = DIV_ROUND_UP(nbits, 8);
nlimbs = DIV_ROUND_UP(nbytes, BYTES_PER_MPI_LIMB);
val = mpi_alloc(nlimbs);
if (!val)
return NULL;
i = BYTES_PER_MPI_LIMB - nbytes % BYTES_PER_MPI_LIMB;
i %= BYTES_PER_MPI_LIMB;
val->nbits = nbits;
j = val->nlimbs = nlimbs;
val->sign = 0;
for (; j > 0; j--) {
a = 0;
for (; i < BYTES_PER_MPI_LIMB; i++) {
if (++nread > *ret_nread) {
printk
("MPI: mpi larger than buffer nread=%d ret_nread=%d\n",
nread, *ret_nread);
goto leave;
}
a <<= 8;
a |= *buffer++;
}
i = 0;
val->d[j - 1] = a;
}
leave:
*ret_nread = nread;
return val;
}
EXPORT_SYMBOL_GPL(mpi_read_from_buffer);
/**
* mpi_read_buffer() - read MPI to a bufer provided by user (msb first)
*
* @a: a multi precision integer
* @buf: bufer to which the output will be written to. Needs to be at
* leaset mpi_get_size(a) long.
* @buf_len: size of the buf.
* @nbytes: receives the actual length of the data written.
* @sign: if not NULL, it will be set to the sign of a.
*
* Return: 0 on success or error code in case of error
*/
int mpi_read_buffer(MPI a, uint8_t *buf, unsigned buf_len, unsigned *nbytes,
int *sign)
{
uint8_t *p;
mpi_limb_t alimb;
unsigned int n = mpi_get_size(a);
int i, lzeros = 0;
if (buf_len < n || !buf || !nbytes)
return -EINVAL;
if (sign)
*sign = a->sign;
p = (void *)&a->d[a->nlimbs] - 1;
for (i = a->nlimbs * sizeof(alimb) - 1; i >= 0; i--, p--) {
if (!*p)
lzeros++;
else
break;
}
p = buf;
*nbytes = n - lzeros;
for (i = a->nlimbs - 1; i >= 0; i--) {
alimb = a->d[i];
#if BYTES_PER_MPI_LIMB == 4
*p++ = alimb >> 24;
*p++ = alimb >> 16;
*p++ = alimb >> 8;
*p++ = alimb;
#elif BYTES_PER_MPI_LIMB == 8
*p++ = alimb >> 56;
*p++ = alimb >> 48;
*p++ = alimb >> 40;
*p++ = alimb >> 32;
*p++ = alimb >> 24;
*p++ = alimb >> 16;
*p++ = alimb >> 8;
*p++ = alimb;
#else
#error please implement for this limb size.
#endif
if (lzeros > 0) {
if (lzeros >= sizeof(alimb)) {
p -= sizeof(alimb);
} else {
mpi_limb_t *limb1 = (void *)p - sizeof(alimb);
mpi_limb_t *limb2 = (void *)p - sizeof(alimb)
+ lzeros;
*limb1 = *limb2;
p -= lzeros;
}
lzeros -= sizeof(alimb);
}
}
return 0;
}
EXPORT_SYMBOL_GPL(mpi_read_buffer);
/*
* mpi_get_buffer() - Returns an allocated buffer with the MPI (msb first).
* Caller must free the return string.
* This function does return a 0 byte buffer with nbytes set to zero if the
* value of A is zero.
*
* @a: a multi precision integer.
* @nbytes: receives the length of this buffer.
* @sign: if not NULL, it will be set to the sign of the a.
*
* Return: Pointer to MPI buffer or NULL on error
*/
void *mpi_get_buffer(MPI a, unsigned *nbytes, int *sign)
{
uint8_t *buf;
unsigned int n;
int ret;
if (!nbytes)
return NULL;
n = mpi_get_size(a);
if (!n)
n++;
buf = kmalloc(n, GFP_KERNEL);
if (!buf)
return NULL;
ret = mpi_read_buffer(a, buf, n, nbytes, sign);
if (ret) {
kfree(buf);
return NULL;
}
return buf;
}
EXPORT_SYMBOL_GPL(mpi_get_buffer);
/****************
* Use BUFFER to update MPI.
*/
int mpi_set_buffer(MPI a, const void *xbuffer, unsigned nbytes, int sign)
{
const uint8_t *buffer = xbuffer, *p;
mpi_limb_t alimb;
int nlimbs;
int i;
nlimbs = DIV_ROUND_UP(nbytes, BYTES_PER_MPI_LIMB);
if (RESIZE_IF_NEEDED(a, nlimbs) < 0)
return -ENOMEM;
a->sign = sign;
for (i = 0, p = buffer + nbytes - 1; p >= buffer + BYTES_PER_MPI_LIMB;) {
#if BYTES_PER_MPI_LIMB == 4
alimb = (mpi_limb_t) *p--;
alimb |= (mpi_limb_t) *p-- << 8;
alimb |= (mpi_limb_t) *p-- << 16;
alimb |= (mpi_limb_t) *p-- << 24;
#elif BYTES_PER_MPI_LIMB == 8
alimb = (mpi_limb_t) *p--;
alimb |= (mpi_limb_t) *p-- << 8;
alimb |= (mpi_limb_t) *p-- << 16;
alimb |= (mpi_limb_t) *p-- << 24;
alimb |= (mpi_limb_t) *p-- << 32;
alimb |= (mpi_limb_t) *p-- << 40;
alimb |= (mpi_limb_t) *p-- << 48;
alimb |= (mpi_limb_t) *p-- << 56;
#else
#error please implement for this limb size.
#endif
a->d[i++] = alimb;
}
if (p >= buffer) {
#if BYTES_PER_MPI_LIMB == 4
alimb = *p--;
if (p >= buffer)
alimb |= (mpi_limb_t) *p-- << 8;
if (p >= buffer)
alimb |= (mpi_limb_t) *p-- << 16;
if (p >= buffer)
alimb |= (mpi_limb_t) *p-- << 24;
#elif BYTES_PER_MPI_LIMB == 8
alimb = (mpi_limb_t) *p--;
if (p >= buffer)
alimb |= (mpi_limb_t) *p-- << 8;
if (p >= buffer)
alimb |= (mpi_limb_t) *p-- << 16;
if (p >= buffer)
alimb |= (mpi_limb_t) *p-- << 24;
if (p >= buffer)
alimb |= (mpi_limb_t) *p-- << 32;
if (p >= buffer)
alimb |= (mpi_limb_t) *p-- << 40;
if (p >= buffer)
alimb |= (mpi_limb_t) *p-- << 48;
if (p >= buffer)
alimb |= (mpi_limb_t) *p-- << 56;
#else
#error please implement for this limb size.
#endif
a->d[i++] = alimb;
}
a->nlimbs = i;
if (i != nlimbs) {
pr_emerg("MPI: mpi_set_buffer: Assertion failed (%d != %d)", i,
nlimbs);
BUG();
}
return 0;
}
EXPORT_SYMBOL_GPL(mpi_set_buffer);
/**
* mpi_write_to_sgl() - Funnction exports MPI to an sgl (msb first)
*
* This function works in the same way as the mpi_read_buffer, but it
* takes an sgl instead of u8 * buf.
*
* @a: a multi precision integer
* @sgl: scatterlist to write to. Needs to be at least
* mpi_get_size(a) long.
* @nbytes: in/out param - it has the be set to the maximum number of
* bytes that can be written to sgl. This has to be at least
* the size of the integer a. On return it receives the actual
* length of the data written.
* @sign: if not NULL, it will be set to the sign of a.
*
* Return: 0 on success or error code in case of error
*/
int mpi_write_to_sgl(MPI a, struct scatterlist *sgl, unsigned *nbytes,
int *sign)
{
u8 *p, *p2;
mpi_limb_t alimb, alimb2;
unsigned int n = mpi_get_size(a);
int i, x, y = 0, lzeros = 0, buf_len;
if (!nbytes || *nbytes < n)
return -EINVAL;
if (sign)
*sign = a->sign;
p = (void *)&a->d[a->nlimbs] - 1;
for (i = a->nlimbs * sizeof(alimb) - 1; i >= 0; i--, p--) {
if (!*p)
lzeros++;
else
break;
}
*nbytes = n - lzeros;
buf_len = sgl->length;
p2 = sg_virt(sgl);
for (i = a->nlimbs - 1; i >= 0; i--) {
alimb = a->d[i];
p = (u8 *)&alimb2;
#if BYTES_PER_MPI_LIMB == 4
*p++ = alimb >> 24;
*p++ = alimb >> 16;
*p++ = alimb >> 8;
*p++ = alimb;
#elif BYTES_PER_MPI_LIMB == 8
*p++ = alimb >> 56;
*p++ = alimb >> 48;
*p++ = alimb >> 40;
*p++ = alimb >> 32;
*p++ = alimb >> 24;
*p++ = alimb >> 16;
*p++ = alimb >> 8;
*p++ = alimb;
#else
#error please implement for this limb size.
#endif
if (lzeros > 0) {
if (lzeros >= sizeof(alimb)) {
p -= sizeof(alimb);
continue;
} else {
mpi_limb_t *limb1 = (void *)p - sizeof(alimb);
mpi_limb_t *limb2 = (void *)p - sizeof(alimb)
+ lzeros;
*limb1 = *limb2;
p -= lzeros;
y = lzeros;
}
lzeros -= sizeof(alimb);
}
p = p - (sizeof(alimb) - y);
for (x = 0; x < sizeof(alimb) - y; x++) {
if (!buf_len) {
sgl = sg_next(sgl);
if (!sgl)
return -EINVAL;
buf_len = sgl->length;
p2 = sg_virt(sgl);
}
*p2++ = *p++;
buf_len--;
}
y = 0;
}
return 0;
}
EXPORT_SYMBOL_GPL(mpi_write_to_sgl);
/*
* mpi_read_raw_from_sgl() - Function allocates an MPI and populates it with
* data from the sgl
*
* This function works in the same way as the mpi_read_raw_data, but it
* takes an sgl instead of void * buffer. i.e. it allocates
* a new MPI and reads the content of the sgl to the MPI.
*
* @sgl: scatterlist to read from
* @len: number of bytes to read
*
* Return: Pointer to a new MPI or NULL on error
*/
MPI mpi_read_raw_from_sgl(struct scatterlist *sgl, unsigned int len)
{
struct scatterlist *sg;
int x, i, j, z, lzeros, ents;
unsigned int nbits, nlimbs, nbytes;
mpi_limb_t a;
MPI val = NULL;
lzeros = 0;
ents = sg_nents(sgl);
for_each_sg(sgl, sg, ents, i) {
const u8 *buff = sg_virt(sg);
int len = sg->length;
while (len && !*buff) {
lzeros++;
len--;
buff++;
}
if (len && *buff)
break;
ents--;
lzeros = 0;
}
sgl = sg;
if (!ents)
nbytes = 0;
else
nbytes = len - lzeros;
nbits = nbytes * 8;
if (nbits > MAX_EXTERN_MPI_BITS) {
pr_info("MPI: mpi too large (%u bits)\n", nbits);
return NULL;
}
if (nbytes > 0)
nbits -= count_leading_zeros(*(u8 *)(sg_virt(sgl) + lzeros));
else
nbits = 0;
nlimbs = DIV_ROUND_UP(nbytes, BYTES_PER_MPI_LIMB);
val = mpi_alloc(nlimbs);
if (!val)
return NULL;
val->nbits = nbits;
val->sign = 0;
val->nlimbs = nlimbs;
if (nbytes == 0)
return val;
j = nlimbs - 1;
a = 0;
z = 0;
x = BYTES_PER_MPI_LIMB - nbytes % BYTES_PER_MPI_LIMB;
x %= BYTES_PER_MPI_LIMB;
for_each_sg(sgl, sg, ents, i) {
const u8 *buffer = sg_virt(sg) + lzeros;
int len = sg->length - lzeros;
int buf_shift = x;
if (sg_is_last(sg) && (len % BYTES_PER_MPI_LIMB))
len += BYTES_PER_MPI_LIMB - (len % BYTES_PER_MPI_LIMB);
for (; x < len + buf_shift; x++) {
a <<= 8;
a |= *buffer++;
if (((z + x + 1) % BYTES_PER_MPI_LIMB) == 0) {
val->d[j--] = a;
a = 0;
}
}
z += x;
x = 0;
lzeros = 0;
}
return val;
}
EXPORT_SYMBOL_GPL(mpi_read_raw_from_sgl);
| gpl-2.0 |
Krabappel2548/tf300_jb_kernel | arch/s390/kernel/signal.c | 391 | 14436 | /*
* arch/s390/kernel/signal.c
*
* Copyright (C) IBM Corp. 1999,2006
* Author(s): Denis Joseph Barrow (djbarrow@de.ibm.com,barrow_dj@yahoo.com)
*
* Based on Intel version
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* 1997-11-28 Modified for POSIX.1b signals by Richard Henderson
*/
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/errno.h>
#include <linux/wait.h>
#include <linux/ptrace.h>
#include <linux/unistd.h>
#include <linux/stddef.h>
#include <linux/tty.h>
#include <linux/personality.h>
#include <linux/binfmts.h>
#include <linux/tracehook.h>
#include <linux/syscalls.h>
#include <linux/compat.h>
#include <asm/ucontext.h>
#include <asm/uaccess.h>
#include <asm/lowcore.h>
#include "entry.h"
#define _BLOCKABLE (~(sigmask(SIGKILL) | sigmask(SIGSTOP)))
typedef struct
{
__u8 callee_used_stack[__SIGNAL_FRAMESIZE];
struct sigcontext sc;
_sigregs sregs;
int signo;
__u8 retcode[S390_SYSCALL_SIZE];
} sigframe;
typedef struct
{
__u8 callee_used_stack[__SIGNAL_FRAMESIZE];
__u8 retcode[S390_SYSCALL_SIZE];
struct siginfo info;
struct ucontext uc;
} rt_sigframe;
/*
* Atomically swap in the new signal mask, and wait for a signal.
*/
SYSCALL_DEFINE3(sigsuspend, int, history0, int, history1, old_sigset_t, mask)
{
sigset_t blocked;
current->saved_sigmask = current->blocked;
mask &= _BLOCKABLE;
siginitset(&blocked, mask);
set_current_blocked(&blocked);
set_current_state(TASK_INTERRUPTIBLE);
schedule();
set_restore_sigmask();
return -ERESTARTNOHAND;
}
SYSCALL_DEFINE3(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) ||
__get_user(new_ka.sa.sa_flags, &act->sa_flags) ||
__get_user(mask, &act->sa_mask))
return -EFAULT;
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) ||
__put_user(old_ka.sa.sa_flags, &oact->sa_flags) ||
__put_user(old_ka.sa.sa_mask.sig[0], &oact->sa_mask))
return -EFAULT;
}
return ret;
}
SYSCALL_DEFINE2(sigaltstack, const stack_t __user *, uss,
stack_t __user *, uoss)
{
struct pt_regs *regs = task_pt_regs(current);
return do_sigaltstack(uss, uoss, regs->gprs[15]);
}
/* Returns non-zero on fault. */
static int save_sigregs(struct pt_regs *regs, _sigregs __user *sregs)
{
_sigregs user_sregs;
save_access_regs(current->thread.acrs);
/* Copy a 'clean' PSW mask to the user to avoid leaking
information about whether PER is currently on. */
user_sregs.regs.psw.mask = PSW_MASK_MERGE(psw_user_bits, regs->psw.mask);
user_sregs.regs.psw.addr = regs->psw.addr;
memcpy(&user_sregs.regs.gprs, ®s->gprs, sizeof(sregs->regs.gprs));
memcpy(&user_sregs.regs.acrs, current->thread.acrs,
sizeof(sregs->regs.acrs));
/*
* We have to store the fp registers to current->thread.fp_regs
* to merge them with the emulated registers.
*/
save_fp_regs(¤t->thread.fp_regs);
memcpy(&user_sregs.fpregs, ¤t->thread.fp_regs,
sizeof(s390_fp_regs));
return __copy_to_user(sregs, &user_sregs, sizeof(_sigregs));
}
/* Returns positive number on error */
static int restore_sigregs(struct pt_regs *regs, _sigregs __user *sregs)
{
int err;
_sigregs user_sregs;
/* Alwys make any pending restarted system call return -EINTR */
current_thread_info()->restart_block.fn = do_no_restart_syscall;
err = __copy_from_user(&user_sregs, sregs, sizeof(_sigregs));
if (err)
return err;
regs->psw.mask = PSW_MASK_MERGE(regs->psw.mask,
user_sregs.regs.psw.mask);
regs->psw.addr = PSW_ADDR_AMODE | user_sregs.regs.psw.addr;
memcpy(®s->gprs, &user_sregs.regs.gprs, sizeof(sregs->regs.gprs));
memcpy(¤t->thread.acrs, &user_sregs.regs.acrs,
sizeof(sregs->regs.acrs));
restore_access_regs(current->thread.acrs);
memcpy(¤t->thread.fp_regs, &user_sregs.fpregs,
sizeof(s390_fp_regs));
current->thread.fp_regs.fpc &= FPC_VALID_MASK;
restore_fp_regs(¤t->thread.fp_regs);
regs->svcnr = 0; /* disable syscall checks */
return 0;
}
SYSCALL_DEFINE0(sigreturn)
{
struct pt_regs *regs = task_pt_regs(current);
sigframe __user *frame = (sigframe __user *)regs->gprs[15];
sigset_t set;
if (!access_ok(VERIFY_READ, frame, sizeof(*frame)))
goto badframe;
if (__copy_from_user(&set.sig, &frame->sc.oldmask, _SIGMASK_COPY_SIZE))
goto badframe;
sigdelsetmask(&set, ~_BLOCKABLE);
set_current_blocked(&set);
if (restore_sigregs(regs, &frame->sregs))
goto badframe;
return regs->gprs[2];
badframe:
force_sig(SIGSEGV, current);
return 0;
}
SYSCALL_DEFINE0(rt_sigreturn)
{
struct pt_regs *regs = task_pt_regs(current);
rt_sigframe __user *frame = (rt_sigframe __user *)regs->gprs[15];
sigset_t set;
if (!access_ok(VERIFY_READ, frame, sizeof(*frame)))
goto badframe;
if (__copy_from_user(&set.sig, &frame->uc.uc_sigmask, sizeof(set)))
goto badframe;
sigdelsetmask(&set, ~_BLOCKABLE);
set_current_blocked(&set);
if (restore_sigregs(regs, &frame->uc.uc_mcontext))
goto badframe;
if (do_sigaltstack(&frame->uc.uc_stack, NULL,
regs->gprs[15]) == -EFAULT)
goto badframe;
return regs->gprs[2];
badframe:
force_sig(SIGSEGV, current);
return 0;
}
/*
* Set up a signal frame.
*/
/*
* Determine which stack to use..
*/
static inline void __user *
get_sigframe(struct k_sigaction *ka, struct pt_regs * regs, size_t frame_size)
{
unsigned long sp;
/* Default to using normal stack */
sp = regs->gprs[15];
/* Overflow on alternate signal stack gives SIGSEGV. */
if (on_sig_stack(sp) && !on_sig_stack((sp - frame_size) & -8UL))
return (void __user *) -1UL;
/* This is the X/Open sanctioned signal stack switching. */
if (ka->sa.sa_flags & SA_ONSTACK) {
if (! sas_ss_flags(sp))
sp = current->sas_ss_sp + current->sas_ss_size;
}
/* This is the legacy signal stack switching. */
else if (!user_mode(regs) &&
!(ka->sa.sa_flags & SA_RESTORER) &&
ka->sa.sa_restorer) {
sp = (unsigned long) ka->sa.sa_restorer;
}
return (void __user *)((sp - frame_size) & -8ul);
}
static inline int map_signal(int sig)
{
if (current_thread_info()->exec_domain
&& current_thread_info()->exec_domain->signal_invmap
&& sig < 32)
return current_thread_info()->exec_domain->signal_invmap[sig];
else
return sig;
}
static int setup_frame(int sig, struct k_sigaction *ka,
sigset_t *set, struct pt_regs * regs)
{
sigframe __user *frame;
frame = get_sigframe(ka, regs, sizeof(sigframe));
if (!access_ok(VERIFY_WRITE, frame, sizeof(sigframe)))
goto give_sigsegv;
if (frame == (void __user *) -1UL)
goto give_sigsegv;
if (__copy_to_user(&frame->sc.oldmask, &set->sig, _SIGMASK_COPY_SIZE))
goto give_sigsegv;
if (save_sigregs(regs, &frame->sregs))
goto give_sigsegv;
if (__put_user(&frame->sregs, &frame->sc.sregs))
goto give_sigsegv;
/* Set up to return from userspace. If provided, use a stub
already in userspace. */
if (ka->sa.sa_flags & SA_RESTORER) {
regs->gprs[14] = (unsigned long)
ka->sa.sa_restorer | PSW_ADDR_AMODE;
} else {
regs->gprs[14] = (unsigned long)
frame->retcode | PSW_ADDR_AMODE;
if (__put_user(S390_SYSCALL_OPCODE | __NR_sigreturn,
(u16 __user *)(frame->retcode)))
goto give_sigsegv;
}
/* Set up backchain. */
if (__put_user(regs->gprs[15], (addr_t __user *) frame))
goto give_sigsegv;
/* Set up registers for signal handler */
regs->gprs[15] = (unsigned long) frame;
regs->psw.addr = (unsigned long) ka->sa.sa_handler | PSW_ADDR_AMODE;
regs->gprs[2] = map_signal(sig);
regs->gprs[3] = (unsigned long) &frame->sc;
/* We forgot to include these in the sigcontext.
To avoid breaking binary compatibility, they are passed as args. */
regs->gprs[4] = current->thread.trap_no;
regs->gprs[5] = current->thread.prot_addr;
regs->gprs[6] = task_thread_info(current)->last_break;
/* Place signal number on stack to allow backtrace from handler. */
if (__put_user(regs->gprs[2], (int __user *) &frame->signo))
goto give_sigsegv;
return 0;
give_sigsegv:
force_sigsegv(sig, current);
return -EFAULT;
}
static int setup_rt_frame(int sig, struct k_sigaction *ka, siginfo_t *info,
sigset_t *set, struct pt_regs * regs)
{
int err = 0;
rt_sigframe __user *frame;
frame = get_sigframe(ka, regs, sizeof(rt_sigframe));
if (!access_ok(VERIFY_WRITE, frame, sizeof(rt_sigframe)))
goto give_sigsegv;
if (frame == (void __user *) -1UL)
goto give_sigsegv;
if (copy_siginfo_to_user(&frame->info, info))
goto give_sigsegv;
/* Create the ucontext. */
err |= __put_user(0, &frame->uc.uc_flags);
err |= __put_user(NULL, &frame->uc.uc_link);
err |= __put_user((void __user *)current->sas_ss_sp, &frame->uc.uc_stack.ss_sp);
err |= __put_user(sas_ss_flags(regs->gprs[15]),
&frame->uc.uc_stack.ss_flags);
err |= __put_user(current->sas_ss_size, &frame->uc.uc_stack.ss_size);
err |= save_sigregs(regs, &frame->uc.uc_mcontext);
err |= __copy_to_user(&frame->uc.uc_sigmask, set, sizeof(*set));
if (err)
goto give_sigsegv;
/* Set up to return from userspace. If provided, use a stub
already in userspace. */
if (ka->sa.sa_flags & SA_RESTORER) {
regs->gprs[14] = (unsigned long)
ka->sa.sa_restorer | PSW_ADDR_AMODE;
} else {
regs->gprs[14] = (unsigned long)
frame->retcode | PSW_ADDR_AMODE;
if (__put_user(S390_SYSCALL_OPCODE | __NR_rt_sigreturn,
(u16 __user *)(frame->retcode)))
goto give_sigsegv;
}
/* Set up backchain. */
if (__put_user(regs->gprs[15], (addr_t __user *) frame))
goto give_sigsegv;
/* Set up registers for signal handler */
regs->gprs[15] = (unsigned long) frame;
regs->psw.addr = (unsigned long) ka->sa.sa_handler | PSW_ADDR_AMODE;
regs->gprs[2] = map_signal(sig);
regs->gprs[3] = (unsigned long) &frame->info;
regs->gprs[4] = (unsigned long) &frame->uc;
regs->gprs[5] = task_thread_info(current)->last_break;
return 0;
give_sigsegv:
force_sigsegv(sig, current);
return -EFAULT;
}
static int handle_signal(unsigned long sig, struct k_sigaction *ka,
siginfo_t *info, sigset_t *oldset,
struct pt_regs *regs)
{
sigset_t blocked;
int ret;
/* Set up the stack frame */
if (ka->sa.sa_flags & SA_SIGINFO)
ret = setup_rt_frame(sig, ka, info, oldset, regs);
else
ret = setup_frame(sig, ka, oldset, regs);
if (ret)
return ret;
sigorsets(&blocked, ¤t->blocked, &ka->sa.sa_mask);
if (!(ka->sa.sa_flags & SA_NODEFER))
sigaddset(&blocked, sig);
set_current_blocked(&blocked);
return 0;
}
/*
* Note that 'init' is a special process: it doesn't get signals it doesn't
* want to handle. Thus you cannot kill init even with a SIGKILL even by
* mistake.
*
* Note that we go through the signals twice: once to check the signals that
* the kernel can handle, and then we build all the user-level signal handling
* stack-frames in one go after that.
*/
void do_signal(struct pt_regs *regs)
{
unsigned long retval = 0, continue_addr = 0, restart_addr = 0;
siginfo_t info;
int signr;
struct k_sigaction ka;
sigset_t *oldset;
/*
* We want the common case to go fast, which
* is why we may in certain cases get here from
* kernel mode. Just return without doing anything
* if so.
*/
if (!user_mode(regs))
return;
if (test_thread_flag(TIF_RESTORE_SIGMASK))
oldset = ¤t->saved_sigmask;
else
oldset = ¤t->blocked;
/* Are we from a system call? */
if (regs->svcnr) {
continue_addr = regs->psw.addr;
restart_addr = continue_addr - regs->ilc;
retval = regs->gprs[2];
/* Prepare for system call restart. We do this here so that a
debugger will see the already changed PSW. */
switch (retval) {
case -ERESTARTNOHAND:
case -ERESTARTSYS:
case -ERESTARTNOINTR:
regs->gprs[2] = regs->orig_gpr2;
regs->psw.addr = restart_addr;
break;
case -ERESTART_RESTARTBLOCK:
regs->gprs[2] = -EINTR;
}
regs->svcnr = 0; /* Don't deal with this again. */
}
/* Get signal to deliver. When running under ptrace, at this point
the debugger may change all our registers ... */
signr = get_signal_to_deliver(&info, &ka, regs, NULL);
/* Depending on the signal settings we may need to revert the
decision to restart the system call. */
if (signr > 0 && regs->psw.addr == restart_addr) {
if (retval == -ERESTARTNOHAND
|| (retval == -ERESTARTSYS
&& !(current->sighand->action[signr-1].sa.sa_flags
& SA_RESTART))) {
regs->gprs[2] = -EINTR;
regs->psw.addr = continue_addr;
}
}
if (signr > 0) {
/* Whee! Actually deliver the signal. */
int ret;
#ifdef CONFIG_COMPAT
if (is_compat_task()) {
ret = handle_signal32(signr, &ka, &info, oldset, regs);
}
else
#endif
ret = handle_signal(signr, &ka, &info, oldset, regs);
if (!ret) {
/*
* A signal was successfully delivered; the saved
* sigmask will have been stored in the signal frame,
* and will be restored by sigreturn, so we can simply
* clear the TIF_RESTORE_SIGMASK flag.
*/
if (test_thread_flag(TIF_RESTORE_SIGMASK))
clear_thread_flag(TIF_RESTORE_SIGMASK);
/*
* Let tracing know that we've done the handler setup.
*/
tracehook_signal_handler(signr, &info, &ka, regs,
test_thread_flag(TIF_SINGLE_STEP));
}
return;
}
/*
* If there's no signal to deliver, we just put the saved sigmask back.
*/
if (test_thread_flag(TIF_RESTORE_SIGMASK)) {
clear_thread_flag(TIF_RESTORE_SIGMASK);
sigprocmask(SIG_SETMASK, ¤t->saved_sigmask, NULL);
}
/* Restart a different system call. */
if (retval == -ERESTART_RESTARTBLOCK
&& regs->psw.addr == continue_addr) {
regs->gprs[2] = __NR_restart_syscall;
set_thread_flag(TIF_RESTART_SVC);
}
}
void do_notify_resume(struct pt_regs *regs)
{
clear_thread_flag(TIF_NOTIFY_RESUME);
tracehook_notify_resume(regs);
if (current->replacement_session_keyring)
key_replace_session_keyring();
}
| gpl-2.0 |
MagicDevTeam/lge-kernel-p880 | arch/m68k/platform/68360/ints.c | 647 | 4327 | /*
* linux/arch/$(ARCH)/platform/$(PLATFORM)/ints.c
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive
* for more details.
*
* Copyright (c) 2000 Michael Leslie <mleslie@lineo.com>
* Copyright (c) 1996 Roman Zippel
* Copyright (c) 1999 D. Jeff Dionne <jeff@uclinux.org>
*/
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <asm/traps.h>
#include <asm/machdep.h>
#include <asm/m68360.h>
/* from quicc/commproc.c: */
extern QUICC *pquicc;
extern void cpm_interrupt_init(void);
#define INTERNAL_IRQS (96)
/* assembler routines */
asmlinkage void system_call(void);
asmlinkage void buserr(void);
asmlinkage void trap(void);
asmlinkage void bad_interrupt(void);
asmlinkage void inthandler(void);
extern void *_ramvec[];
static void intc_irq_unmask(struct irq_data *d)
{
pquicc->intr_cimr |= (1 << d->irq);
}
static void intc_irq_mask(struct irq_data *d)
{
pquicc->intr_cimr &= ~(1 << d->irq);
}
static void intc_irq_ack(struct irq_data *d)
{
pquicc->intr_cisr = (1 << d->irq);
}
static struct irq_chip intc_irq_chip = {
.name = "M68K-INTC",
.irq_mask = intc_irq_mask,
.irq_unmask = intc_irq_unmask,
.irq_ack = intc_irq_ack,
};
/*
* This function should be called during kernel startup to initialize
* the vector table.
*/
void __init trap_init(void)
{
int vba = (CPM_VECTOR_BASE<<4);
/* set up the vectors */
_ramvec[2] = buserr;
_ramvec[3] = trap;
_ramvec[4] = trap;
_ramvec[5] = trap;
_ramvec[6] = trap;
_ramvec[7] = trap;
_ramvec[8] = trap;
_ramvec[9] = trap;
_ramvec[10] = trap;
_ramvec[11] = trap;
_ramvec[12] = trap;
_ramvec[13] = trap;
_ramvec[14] = trap;
_ramvec[15] = trap;
_ramvec[32] = system_call;
_ramvec[33] = trap;
cpm_interrupt_init();
/* set up CICR for vector base address and irq level */
/* irl = 4, hp = 1f - see MC68360UM p 7-377 */
pquicc->intr_cicr = 0x00e49f00 | vba;
/* CPM interrupt vectors: (p 7-376) */
_ramvec[vba+CPMVEC_ERROR] = bad_interrupt; /* Error */
_ramvec[vba+CPMVEC_PIO_PC11] = inthandler; /* pio - pc11 */
_ramvec[vba+CPMVEC_PIO_PC10] = inthandler; /* pio - pc10 */
_ramvec[vba+CPMVEC_SMC2] = inthandler; /* smc2/pip */
_ramvec[vba+CPMVEC_SMC1] = inthandler; /* smc1 */
_ramvec[vba+CPMVEC_SPI] = inthandler; /* spi */
_ramvec[vba+CPMVEC_PIO_PC9] = inthandler; /* pio - pc9 */
_ramvec[vba+CPMVEC_TIMER4] = inthandler; /* timer 4 */
_ramvec[vba+CPMVEC_RESERVED1] = inthandler; /* reserved */
_ramvec[vba+CPMVEC_PIO_PC8] = inthandler; /* pio - pc8 */
_ramvec[vba+CPMVEC_PIO_PC7] = inthandler; /* pio - pc7 */
_ramvec[vba+CPMVEC_PIO_PC6] = inthandler; /* pio - pc6 */
_ramvec[vba+CPMVEC_TIMER3] = inthandler; /* timer 3 */
_ramvec[vba+CPMVEC_PIO_PC5] = inthandler; /* pio - pc5 */
_ramvec[vba+CPMVEC_PIO_PC4] = inthandler; /* pio - pc4 */
_ramvec[vba+CPMVEC_RESERVED2] = inthandler; /* reserved */
_ramvec[vba+CPMVEC_RISCTIMER] = inthandler; /* timer table */
_ramvec[vba+CPMVEC_TIMER2] = inthandler; /* timer 2 */
_ramvec[vba+CPMVEC_RESERVED3] = inthandler; /* reserved */
_ramvec[vba+CPMVEC_IDMA2] = inthandler; /* idma 2 */
_ramvec[vba+CPMVEC_IDMA1] = inthandler; /* idma 1 */
_ramvec[vba+CPMVEC_SDMA_CB_ERR] = inthandler; /* sdma channel bus error */
_ramvec[vba+CPMVEC_PIO_PC3] = inthandler; /* pio - pc3 */
_ramvec[vba+CPMVEC_PIO_PC2] = inthandler; /* pio - pc2 */
/* _ramvec[vba+CPMVEC_TIMER1] = cpm_isr_timer1; */ /* timer 1 */
_ramvec[vba+CPMVEC_TIMER1] = inthandler; /* timer 1 */
_ramvec[vba+CPMVEC_PIO_PC1] = inthandler; /* pio - pc1 */
_ramvec[vba+CPMVEC_SCC4] = inthandler; /* scc 4 */
_ramvec[vba+CPMVEC_SCC3] = inthandler; /* scc 3 */
_ramvec[vba+CPMVEC_SCC2] = inthandler; /* scc 2 */
_ramvec[vba+CPMVEC_SCC1] = inthandler; /* scc 1 */
_ramvec[vba+CPMVEC_PIO_PC0] = inthandler; /* pio - pc0 */
/* turn off all CPM interrupts */
pquicc->intr_cimr = 0x00000000;
}
void init_IRQ(void)
{
int i;
for (i = 0; (i < NR_IRQS); i++) {
irq_set_chip(i, &intc_irq_chip);
irq_set_handler(i, handle_level_irq);
}
}
| gpl-2.0 |
cattleprod/XCeLL-X69 | drivers/input/gameport/gameport.c | 903 | 19954 | /*
* Generic gameport layer
*
* Copyright (c) 1999-2002 Vojtech Pavlik
* Copyright (c) 2005 Dmitry Torokhov
*/
/*
* 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/stddef.h>
#include <linux/module.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/gameport.h>
#include <linux/wait.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/sched.h> /* HZ */
#include <linux/mutex.h>
#include <linux/freezer.h>
/*#include <asm/io.h>*/
MODULE_AUTHOR("Vojtech Pavlik <vojtech@ucw.cz>");
MODULE_DESCRIPTION("Generic gameport layer");
MODULE_LICENSE("GPL");
/*
* gameport_mutex protects entire gameport subsystem and is taken
* every time gameport port or driver registrered or unregistered.
*/
static DEFINE_MUTEX(gameport_mutex);
static LIST_HEAD(gameport_list);
static struct bus_type gameport_bus;
static void gameport_add_port(struct gameport *gameport);
static void gameport_attach_driver(struct gameport_driver *drv);
static void gameport_reconnect_port(struct gameport *gameport);
static void gameport_disconnect_port(struct gameport *gameport);
#if defined(__i386__)
#include <asm/i8253.h>
#define DELTA(x,y) ((y)-(x)+((y)<(x)?1193182/HZ:0))
#define GET_TIME(x) do { x = get_time_pit(); } while (0)
static unsigned int get_time_pit(void)
{
unsigned long flags;
unsigned int count;
raw_spin_lock_irqsave(&i8253_lock, flags);
outb_p(0x00, 0x43);
count = inb_p(0x40);
count |= inb_p(0x40) << 8;
raw_spin_unlock_irqrestore(&i8253_lock, flags);
return count;
}
#endif
/*
* gameport_measure_speed() measures the gameport i/o speed.
*/
static int gameport_measure_speed(struct gameport *gameport)
{
#if defined(__i386__)
unsigned int i, t, t1, t2, t3, tx;
unsigned long flags;
if (gameport_open(gameport, NULL, GAMEPORT_MODE_RAW))
return 0;
tx = 1 << 30;
for(i = 0; i < 50; i++) {
local_irq_save(flags);
GET_TIME(t1);
for (t = 0; t < 50; t++) gameport_read(gameport);
GET_TIME(t2);
GET_TIME(t3);
local_irq_restore(flags);
udelay(i * 10);
if ((t = DELTA(t2,t1) - DELTA(t3,t2)) < tx) tx = t;
}
gameport_close(gameport);
return 59659 / (tx < 1 ? 1 : tx);
#elif defined (__x86_64__)
unsigned int i, t;
unsigned long tx, t1, t2, flags;
if (gameport_open(gameport, NULL, GAMEPORT_MODE_RAW))
return 0;
tx = 1 << 30;
for(i = 0; i < 50; i++) {
local_irq_save(flags);
rdtscl(t1);
for (t = 0; t < 50; t++) gameport_read(gameport);
rdtscl(t2);
local_irq_restore(flags);
udelay(i * 10);
if (t2 - t1 < tx) tx = t2 - t1;
}
gameport_close(gameport);
return (cpu_data(raw_smp_processor_id()).loops_per_jiffy *
(unsigned long)HZ / (1000 / 50)) / (tx < 1 ? 1 : tx);
#else
unsigned int j, t = 0;
if (gameport_open(gameport, NULL, GAMEPORT_MODE_RAW))
return 0;
j = jiffies; while (j == jiffies);
j = jiffies; while (j == jiffies) { t++; gameport_read(gameport); }
gameport_close(gameport);
return t * HZ / 1000;
#endif
}
void gameport_start_polling(struct gameport *gameport)
{
spin_lock(&gameport->timer_lock);
if (!gameport->poll_cnt++) {
BUG_ON(!gameport->poll_handler);
BUG_ON(!gameport->poll_interval);
mod_timer(&gameport->poll_timer, jiffies + msecs_to_jiffies(gameport->poll_interval));
}
spin_unlock(&gameport->timer_lock);
}
EXPORT_SYMBOL(gameport_start_polling);
void gameport_stop_polling(struct gameport *gameport)
{
spin_lock(&gameport->timer_lock);
if (!--gameport->poll_cnt)
del_timer(&gameport->poll_timer);
spin_unlock(&gameport->timer_lock);
}
EXPORT_SYMBOL(gameport_stop_polling);
static void gameport_run_poll_handler(unsigned long d)
{
struct gameport *gameport = (struct gameport *)d;
gameport->poll_handler(gameport);
if (gameport->poll_cnt)
mod_timer(&gameport->poll_timer, jiffies + msecs_to_jiffies(gameport->poll_interval));
}
/*
* Basic gameport -> driver core mappings
*/
static int gameport_bind_driver(struct gameport *gameport, struct gameport_driver *drv)
{
int error;
gameport->dev.driver = &drv->driver;
if (drv->connect(gameport, drv)) {
gameport->dev.driver = NULL;
return -ENODEV;
}
error = device_bind_driver(&gameport->dev);
if (error) {
dev_warn(&gameport->dev,
"device_bind_driver() failed for %s (%s) and %s, error: %d\n",
gameport->phys, gameport->name,
drv->description, error);
drv->disconnect(gameport);
gameport->dev.driver = NULL;
return error;
}
return 0;
}
static void gameport_find_driver(struct gameport *gameport)
{
int error;
error = device_attach(&gameport->dev);
if (error < 0)
dev_warn(&gameport->dev,
"device_attach() failed for %s (%s), error: %d\n",
gameport->phys, gameport->name, error);
}
/*
* Gameport event processing.
*/
enum gameport_event_type {
GAMEPORT_REGISTER_PORT,
GAMEPORT_ATTACH_DRIVER,
};
struct gameport_event {
enum gameport_event_type type;
void *object;
struct module *owner;
struct list_head node;
};
static DEFINE_SPINLOCK(gameport_event_lock); /* protects gameport_event_list */
static LIST_HEAD(gameport_event_list);
static DECLARE_WAIT_QUEUE_HEAD(gameport_wait);
static struct task_struct *gameport_task;
static int gameport_queue_event(void *object, struct module *owner,
enum gameport_event_type event_type)
{
unsigned long flags;
struct gameport_event *event;
int retval = 0;
spin_lock_irqsave(&gameport_event_lock, flags);
/*
* Scan event list for the other events for the same gameport port,
* starting with the most recent one. If event is the same we
* do not need add new one. If event is of different type we
* need to add this event and should not look further because
* we need to preseve sequence of distinct events.
*/
list_for_each_entry_reverse(event, &gameport_event_list, node) {
if (event->object == object) {
if (event->type == event_type)
goto out;
break;
}
}
event = kmalloc(sizeof(struct gameport_event), GFP_ATOMIC);
if (!event) {
pr_err("Not enough memory to queue event %d\n", event_type);
retval = -ENOMEM;
goto out;
}
if (!try_module_get(owner)) {
pr_warning("Can't get module reference, dropping event %d\n",
event_type);
kfree(event);
retval = -EINVAL;
goto out;
}
event->type = event_type;
event->object = object;
event->owner = owner;
list_add_tail(&event->node, &gameport_event_list);
wake_up(&gameport_wait);
out:
spin_unlock_irqrestore(&gameport_event_lock, flags);
return retval;
}
static void gameport_free_event(struct gameport_event *event)
{
module_put(event->owner);
kfree(event);
}
static void gameport_remove_duplicate_events(struct gameport_event *event)
{
struct gameport_event *e, *next;
unsigned long flags;
spin_lock_irqsave(&gameport_event_lock, flags);
list_for_each_entry_safe(e, next, &gameport_event_list, node) {
if (event->object == e->object) {
/*
* If this event is of different type we should not
* look further - we only suppress duplicate events
* that were sent back-to-back.
*/
if (event->type != e->type)
break;
list_del_init(&e->node);
gameport_free_event(e);
}
}
spin_unlock_irqrestore(&gameport_event_lock, flags);
}
static struct gameport_event *gameport_get_event(void)
{
struct gameport_event *event = NULL;
unsigned long flags;
spin_lock_irqsave(&gameport_event_lock, flags);
if (!list_empty(&gameport_event_list)) {
event = list_first_entry(&gameport_event_list,
struct gameport_event, node);
list_del_init(&event->node);
}
spin_unlock_irqrestore(&gameport_event_lock, flags);
return event;
}
static void gameport_handle_event(void)
{
struct gameport_event *event;
mutex_lock(&gameport_mutex);
/*
* Note that we handle only one event here to give swsusp
* a chance to freeze kgameportd thread. Gameport events
* should be pretty rare so we are not concerned about
* taking performance hit.
*/
if ((event = gameport_get_event())) {
switch (event->type) {
case GAMEPORT_REGISTER_PORT:
gameport_add_port(event->object);
break;
case GAMEPORT_ATTACH_DRIVER:
gameport_attach_driver(event->object);
break;
}
gameport_remove_duplicate_events(event);
gameport_free_event(event);
}
mutex_unlock(&gameport_mutex);
}
/*
* Remove all events that have been submitted for a given object,
* be it a gameport port or a driver.
*/
static void gameport_remove_pending_events(void *object)
{
struct gameport_event *event, *next;
unsigned long flags;
spin_lock_irqsave(&gameport_event_lock, flags);
list_for_each_entry_safe(event, next, &gameport_event_list, node) {
if (event->object == object) {
list_del_init(&event->node);
gameport_free_event(event);
}
}
spin_unlock_irqrestore(&gameport_event_lock, flags);
}
/*
* Destroy child gameport port (if any) that has not been fully registered yet.
*
* Note that we rely on the fact that port can have only one child and therefore
* only one child registration request can be pending. Additionally, children
* are registered by driver's connect() handler so there can't be a grandchild
* pending registration together with a child.
*/
static struct gameport *gameport_get_pending_child(struct gameport *parent)
{
struct gameport_event *event;
struct gameport *gameport, *child = NULL;
unsigned long flags;
spin_lock_irqsave(&gameport_event_lock, flags);
list_for_each_entry(event, &gameport_event_list, node) {
if (event->type == GAMEPORT_REGISTER_PORT) {
gameport = event->object;
if (gameport->parent == parent) {
child = gameport;
break;
}
}
}
spin_unlock_irqrestore(&gameport_event_lock, flags);
return child;
}
static int gameport_thread(void *nothing)
{
set_freezable();
do {
gameport_handle_event();
wait_event_freezable(gameport_wait,
kthread_should_stop() || !list_empty(&gameport_event_list));
} while (!kthread_should_stop());
return 0;
}
/*
* Gameport port operations
*/
static ssize_t gameport_show_description(struct device *dev, struct device_attribute *attr, char *buf)
{
struct gameport *gameport = to_gameport_port(dev);
return sprintf(buf, "%s\n", gameport->name);
}
static ssize_t gameport_rebind_driver(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
{
struct gameport *gameport = to_gameport_port(dev);
struct device_driver *drv;
int error;
error = mutex_lock_interruptible(&gameport_mutex);
if (error)
return error;
if (!strncmp(buf, "none", count)) {
gameport_disconnect_port(gameport);
} else if (!strncmp(buf, "reconnect", count)) {
gameport_reconnect_port(gameport);
} else if (!strncmp(buf, "rescan", count)) {
gameport_disconnect_port(gameport);
gameport_find_driver(gameport);
} else if ((drv = driver_find(buf, &gameport_bus)) != NULL) {
gameport_disconnect_port(gameport);
error = gameport_bind_driver(gameport, to_gameport_driver(drv));
put_driver(drv);
} else {
error = -EINVAL;
}
mutex_unlock(&gameport_mutex);
return error ? error : count;
}
static struct device_attribute gameport_device_attrs[] = {
__ATTR(description, S_IRUGO, gameport_show_description, NULL),
__ATTR(drvctl, S_IWUSR, NULL, gameport_rebind_driver),
__ATTR_NULL
};
static void gameport_release_port(struct device *dev)
{
struct gameport *gameport = to_gameport_port(dev);
kfree(gameport);
module_put(THIS_MODULE);
}
void gameport_set_phys(struct gameport *gameport, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vsnprintf(gameport->phys, sizeof(gameport->phys), fmt, args);
va_end(args);
}
EXPORT_SYMBOL(gameport_set_phys);
/*
* Prepare gameport port for registration.
*/
static void gameport_init_port(struct gameport *gameport)
{
static atomic_t gameport_no = ATOMIC_INIT(0);
__module_get(THIS_MODULE);
mutex_init(&gameport->drv_mutex);
device_initialize(&gameport->dev);
dev_set_name(&gameport->dev, "gameport%lu",
(unsigned long)atomic_inc_return(&gameport_no) - 1);
gameport->dev.bus = &gameport_bus;
gameport->dev.release = gameport_release_port;
if (gameport->parent)
gameport->dev.parent = &gameport->parent->dev;
INIT_LIST_HEAD(&gameport->node);
spin_lock_init(&gameport->timer_lock);
init_timer(&gameport->poll_timer);
gameport->poll_timer.function = gameport_run_poll_handler;
gameport->poll_timer.data = (unsigned long)gameport;
}
/*
* Complete gameport port registration.
* Driver core will attempt to find appropriate driver for the port.
*/
static void gameport_add_port(struct gameport *gameport)
{
int error;
if (gameport->parent)
gameport->parent->child = gameport;
gameport->speed = gameport_measure_speed(gameport);
list_add_tail(&gameport->node, &gameport_list);
if (gameport->io)
dev_info(&gameport->dev, "%s is %s, io %#x, speed %dkHz\n",
gameport->name, gameport->phys, gameport->io, gameport->speed);
else
dev_info(&gameport->dev, "%s is %s, speed %dkHz\n",
gameport->name, gameport->phys, gameport->speed);
error = device_add(&gameport->dev);
if (error)
dev_err(&gameport->dev,
"device_add() failed for %s (%s), error: %d\n",
gameport->phys, gameport->name, error);
}
/*
* gameport_destroy_port() completes deregistration process and removes
* port from the system
*/
static void gameport_destroy_port(struct gameport *gameport)
{
struct gameport *child;
child = gameport_get_pending_child(gameport);
if (child) {
gameport_remove_pending_events(child);
put_device(&child->dev);
}
if (gameport->parent) {
gameport->parent->child = NULL;
gameport->parent = NULL;
}
if (device_is_registered(&gameport->dev))
device_del(&gameport->dev);
list_del_init(&gameport->node);
gameport_remove_pending_events(gameport);
put_device(&gameport->dev);
}
/*
* Reconnect gameport port and all its children (re-initialize attached devices)
*/
static void gameport_reconnect_port(struct gameport *gameport)
{
do {
if (!gameport->drv || !gameport->drv->reconnect || gameport->drv->reconnect(gameport)) {
gameport_disconnect_port(gameport);
gameport_find_driver(gameport);
/* Ok, old children are now gone, we are done */
break;
}
gameport = gameport->child;
} while (gameport);
}
/*
* gameport_disconnect_port() unbinds a port from its driver. As a side effect
* all child ports are unbound and destroyed.
*/
static void gameport_disconnect_port(struct gameport *gameport)
{
struct gameport *s, *parent;
if (gameport->child) {
/*
* Children ports should be disconnected and destroyed
* first, staring with the leaf one, since we don't want
* to do recursion
*/
for (s = gameport; s->child; s = s->child)
/* empty */;
do {
parent = s->parent;
device_release_driver(&s->dev);
gameport_destroy_port(s);
} while ((s = parent) != gameport);
}
/*
* Ok, no children left, now disconnect this port
*/
device_release_driver(&gameport->dev);
}
/*
* Submits register request to kgameportd for subsequent execution.
* Note that port registration is always asynchronous.
*/
void __gameport_register_port(struct gameport *gameport, struct module *owner)
{
gameport_init_port(gameport);
gameport_queue_event(gameport, owner, GAMEPORT_REGISTER_PORT);
}
EXPORT_SYMBOL(__gameport_register_port);
/*
* Synchronously unregisters gameport port.
*/
void gameport_unregister_port(struct gameport *gameport)
{
mutex_lock(&gameport_mutex);
gameport_disconnect_port(gameport);
gameport_destroy_port(gameport);
mutex_unlock(&gameport_mutex);
}
EXPORT_SYMBOL(gameport_unregister_port);
/*
* Gameport driver operations
*/
static ssize_t gameport_driver_show_description(struct device_driver *drv, char *buf)
{
struct gameport_driver *driver = to_gameport_driver(drv);
return sprintf(buf, "%s\n", driver->description ? driver->description : "(none)");
}
static struct driver_attribute gameport_driver_attrs[] = {
__ATTR(description, S_IRUGO, gameport_driver_show_description, NULL),
__ATTR_NULL
};
static int gameport_driver_probe(struct device *dev)
{
struct gameport *gameport = to_gameport_port(dev);
struct gameport_driver *drv = to_gameport_driver(dev->driver);
drv->connect(gameport, drv);
return gameport->drv ? 0 : -ENODEV;
}
static int gameport_driver_remove(struct device *dev)
{
struct gameport *gameport = to_gameport_port(dev);
struct gameport_driver *drv = to_gameport_driver(dev->driver);
drv->disconnect(gameport);
return 0;
}
static void gameport_attach_driver(struct gameport_driver *drv)
{
int error;
error = driver_attach(&drv->driver);
if (error)
pr_err("driver_attach() failed for %s, error: %d\n",
drv->driver.name, error);
}
int __gameport_register_driver(struct gameport_driver *drv, struct module *owner,
const char *mod_name)
{
int error;
drv->driver.bus = &gameport_bus;
drv->driver.owner = owner;
drv->driver.mod_name = mod_name;
/*
* Temporarily disable automatic binding because probing
* takes long time and we are better off doing it in kgameportd
*/
drv->ignore = true;
error = driver_register(&drv->driver);
if (error) {
pr_err("driver_register() failed for %s, error: %d\n",
drv->driver.name, error);
return error;
}
/*
* Reset ignore flag and let kgameportd bind the driver to free ports
*/
drv->ignore = false;
error = gameport_queue_event(drv, NULL, GAMEPORT_ATTACH_DRIVER);
if (error) {
driver_unregister(&drv->driver);
return error;
}
return 0;
}
EXPORT_SYMBOL(__gameport_register_driver);
void gameport_unregister_driver(struct gameport_driver *drv)
{
struct gameport *gameport;
mutex_lock(&gameport_mutex);
drv->ignore = true; /* so gameport_find_driver ignores it */
gameport_remove_pending_events(drv);
start_over:
list_for_each_entry(gameport, &gameport_list, node) {
if (gameport->drv == drv) {
gameport_disconnect_port(gameport);
gameport_find_driver(gameport);
/* we could've deleted some ports, restart */
goto start_over;
}
}
driver_unregister(&drv->driver);
mutex_unlock(&gameport_mutex);
}
EXPORT_SYMBOL(gameport_unregister_driver);
static int gameport_bus_match(struct device *dev, struct device_driver *drv)
{
struct gameport_driver *gameport_drv = to_gameport_driver(drv);
return !gameport_drv->ignore;
}
static struct bus_type gameport_bus = {
.name = "gameport",
.dev_attrs = gameport_device_attrs,
.drv_attrs = gameport_driver_attrs,
.match = gameport_bus_match,
.probe = gameport_driver_probe,
.remove = gameport_driver_remove,
};
static void gameport_set_drv(struct gameport *gameport, struct gameport_driver *drv)
{
mutex_lock(&gameport->drv_mutex);
gameport->drv = drv;
mutex_unlock(&gameport->drv_mutex);
}
int gameport_open(struct gameport *gameport, struct gameport_driver *drv, int mode)
{
if (gameport->open) {
if (gameport->open(gameport, mode)) {
return -1;
}
} else {
if (mode != GAMEPORT_MODE_RAW)
return -1;
}
gameport_set_drv(gameport, drv);
return 0;
}
EXPORT_SYMBOL(gameport_open);
void gameport_close(struct gameport *gameport)
{
del_timer_sync(&gameport->poll_timer);
gameport->poll_handler = NULL;
gameport->poll_interval = 0;
gameport_set_drv(gameport, NULL);
if (gameport->close)
gameport->close(gameport);
}
EXPORT_SYMBOL(gameport_close);
static int __init gameport_init(void)
{
int error;
error = bus_register(&gameport_bus);
if (error) {
pr_err("failed to register gameport bus, error: %d\n", error);
return error;
}
gameport_task = kthread_run(gameport_thread, NULL, "kgameportd");
if (IS_ERR(gameport_task)) {
bus_unregister(&gameport_bus);
error = PTR_ERR(gameport_task);
pr_err("Failed to start kgameportd, error: %d\n", error);
return error;
}
return 0;
}
static void __exit gameport_exit(void)
{
bus_unregister(&gameport_bus);
kthread_stop(gameport_task);
}
subsys_initcall(gameport_init);
module_exit(gameport_exit);
| gpl-2.0 |
crpalmer/android_kernel_sony_tetra | arch/arm64/mm/context.c | 903 | 4418 | /*
* Based on arch/arm/mm/context.c
*
* Copyright (C) 2002-2003 Deep Blue Solutions Ltd, all rights reserved.
* Copyright (C) 2012 ARM Ltd.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/percpu.h>
#include <asm/mmu_context.h>
#include <asm/tlbflush.h>
#include <asm/cachetype.h>
#define asid_bits(reg) \
(((read_cpuid(ID_AA64MMFR0_EL1) & 0xf0) >> 2) + 8)
#define ASID_FIRST_VERSION (1 << MAX_ASID_BITS)
static DEFINE_RAW_SPINLOCK(cpu_asid_lock);
unsigned int cpu_last_asid = ASID_FIRST_VERSION;
/*
* We fork()ed a process, and we need a new context for the child to run in.
*/
void __init_new_context(struct task_struct *tsk, struct mm_struct *mm)
{
mm->context.id = 0;
raw_spin_lock_init(&mm->context.id_lock);
}
static void flush_context(void)
{
/* set the reserved TTBR0 before flushing the TLB */
cpu_set_reserved_ttbr0();
flush_tlb_all();
if (icache_is_aivivt())
__flush_icache_all();
}
#ifdef CONFIG_SMP
static void set_mm_context(struct mm_struct *mm, unsigned int asid)
{
unsigned long flags;
/*
* Locking needed for multi-threaded applications where the same
* mm->context.id could be set from different CPUs during the
* broadcast. This function is also called via IPI so the
* mm->context.id_lock has to be IRQ-safe.
*/
raw_spin_lock_irqsave(&mm->context.id_lock, flags);
if (likely((mm->context.id ^ cpu_last_asid) >> MAX_ASID_BITS)) {
/*
* Old version of ASID found. Set the new one and reset
* mm_cpumask(mm).
*/
mm->context.id = asid;
cpumask_clear(mm_cpumask(mm));
}
raw_spin_unlock_irqrestore(&mm->context.id_lock, flags);
/*
* Set the mm_cpumask(mm) bit for the current CPU.
*/
cpumask_set_cpu(smp_processor_id(), mm_cpumask(mm));
}
/*
* Reset the ASID on the current CPU. This function call is broadcast from the
* CPU handling the ASID rollover and holding cpu_asid_lock.
*/
static void reset_context(void *info)
{
unsigned int asid;
unsigned int cpu = smp_processor_id();
struct mm_struct *mm = current->active_mm;
/*
* current->active_mm could be init_mm for the idle thread immediately
* after secondary CPU boot or hotplug. TTBR0_EL1 is already set to
* the reserved value, so no need to reset any context.
*/
if (mm == &init_mm)
return;
smp_rmb();
asid = cpu_last_asid + cpu;
flush_context();
set_mm_context(mm, asid);
/* set the new ASID */
cpu_switch_mm(mm->pgd, mm);
}
#else
static inline void set_mm_context(struct mm_struct *mm, unsigned int asid)
{
mm->context.id = asid;
cpumask_copy(mm_cpumask(mm), cpumask_of(smp_processor_id()));
}
#endif
void __new_context(struct mm_struct *mm)
{
unsigned int asid;
unsigned int bits = asid_bits();
raw_spin_lock(&cpu_asid_lock);
#ifdef CONFIG_SMP
/*
* Check the ASID again, in case the change was broadcast from another
* CPU before we acquired the lock.
*/
if (!unlikely((mm->context.id ^ cpu_last_asid) >> MAX_ASID_BITS)) {
cpumask_set_cpu(smp_processor_id(), mm_cpumask(mm));
raw_spin_unlock(&cpu_asid_lock);
return;
}
#endif
/*
* At this point, it is guaranteed that the current mm (with an old
* ASID) isn't active on any other CPU since the ASIDs are changed
* simultaneously via IPI.
*/
asid = ++cpu_last_asid;
/*
* If we've used up all our ASIDs, we need to start a new version and
* flush the TLB.
*/
if (unlikely((asid & ((1 << bits) - 1)) == 0)) {
/* increment the ASID version */
cpu_last_asid += (1 << MAX_ASID_BITS) - (1 << bits);
if (cpu_last_asid == 0)
cpu_last_asid = ASID_FIRST_VERSION;
asid = cpu_last_asid + smp_processor_id();
flush_context();
#ifdef CONFIG_SMP
smp_wmb();
smp_call_function(reset_context, NULL, 1);
#endif
cpu_last_asid += NR_CPUS - 1;
}
set_mm_context(mm, asid);
raw_spin_unlock(&cpu_asid_lock);
}
| gpl-2.0 |
friedrich420/Sprint-Note-4-Android-5.1.1-Kernel | KernelN910P-5_1_1GIT/drivers/net/ethernet/smsc/smsc911x.c | 1159 | 70960 | /***************************************************************************
*
* Copyright (C) 2004-2008 SMSC
* Copyright (C) 2005-2008 ARM
*
* 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.
*
***************************************************************************
* Rewritten, heavily based on smsc911x simple driver by SMSC.
* Partly uses io macros from smc91x.c by Nicolas Pitre
*
* Supported devices:
* LAN9115, LAN9116, LAN9117, LAN9118
* LAN9215, LAN9216, LAN9217, LAN9218
* LAN9210, LAN9211
* LAN9220, LAN9221
* LAN89218
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/crc32.h>
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/regulator/consumer.h>
#include <linux/sched.h>
#include <linux/timer.h>
#include <linux/bug.h>
#include <linux/bitops.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <linux/swab.h>
#include <linux/phy.h>
#include <linux/smsc911x.h>
#include <linux/device.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/of_gpio.h>
#include <linux/of_net.h>
#include "smsc911x.h"
#define SMSC_CHIPNAME "smsc911x"
#define SMSC_MDIONAME "smsc911x-mdio"
#define SMSC_DRV_VERSION "2008-10-21"
MODULE_LICENSE("GPL");
MODULE_VERSION(SMSC_DRV_VERSION);
MODULE_ALIAS("platform:smsc911x");
#if USE_DEBUG > 0
static int debug = 16;
#else
static int debug = 3;
#endif
module_param(debug, int, 0);
MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all)");
struct smsc911x_data;
struct smsc911x_ops {
u32 (*reg_read)(struct smsc911x_data *pdata, u32 reg);
void (*reg_write)(struct smsc911x_data *pdata, u32 reg, u32 val);
void (*rx_readfifo)(struct smsc911x_data *pdata,
unsigned int *buf, unsigned int wordcount);
void (*tx_writefifo)(struct smsc911x_data *pdata,
unsigned int *buf, unsigned int wordcount);
};
#define SMSC911X_NUM_SUPPLIES 2
struct smsc911x_data {
void __iomem *ioaddr;
unsigned int idrev;
/* used to decide which workarounds apply */
unsigned int generation;
/* device configuration (copied from platform_data during probe) */
struct smsc911x_platform_config config;
/* This needs to be acquired before calling any of below:
* smsc911x_mac_read(), smsc911x_mac_write()
*/
spinlock_t mac_lock;
/* spinlock to ensure register accesses are serialised */
spinlock_t dev_lock;
struct phy_device *phy_dev;
struct mii_bus *mii_bus;
int phy_irq[PHY_MAX_ADDR];
unsigned int using_extphy;
int last_duplex;
int last_carrier;
u32 msg_enable;
unsigned int gpio_setting;
unsigned int gpio_orig_setting;
struct net_device *dev;
struct napi_struct napi;
unsigned int software_irq_signal;
#ifdef USE_PHY_WORK_AROUND
#define MIN_PACKET_SIZE (64)
char loopback_tx_pkt[MIN_PACKET_SIZE];
char loopback_rx_pkt[MIN_PACKET_SIZE];
unsigned int resetcount;
#endif
/* Members for Multicast filter workaround */
unsigned int multicast_update_pending;
unsigned int set_bits_mask;
unsigned int clear_bits_mask;
unsigned int hashhi;
unsigned int hashlo;
/* register access functions */
const struct smsc911x_ops *ops;
/* regulators */
struct regulator_bulk_data supplies[SMSC911X_NUM_SUPPLIES];
/* clock */
struct clk *clk;
};
/* Easy access to information */
#define __smsc_shift(pdata, reg) ((reg) << ((pdata)->config.shift))
static inline u32 __smsc911x_reg_read(struct smsc911x_data *pdata, u32 reg)
{
if (pdata->config.flags & SMSC911X_USE_32BIT)
return readl(pdata->ioaddr + reg);
if (pdata->config.flags & SMSC911X_USE_16BIT)
return ((readw(pdata->ioaddr + reg) & 0xFFFF) |
((readw(pdata->ioaddr + reg + 2) & 0xFFFF) << 16));
BUG();
return 0;
}
static inline u32
__smsc911x_reg_read_shift(struct smsc911x_data *pdata, u32 reg)
{
if (pdata->config.flags & SMSC911X_USE_32BIT)
return readl(pdata->ioaddr + __smsc_shift(pdata, reg));
if (pdata->config.flags & SMSC911X_USE_16BIT)
return (readw(pdata->ioaddr +
__smsc_shift(pdata, reg)) & 0xFFFF) |
((readw(pdata->ioaddr +
__smsc_shift(pdata, reg + 2)) & 0xFFFF) << 16);
BUG();
return 0;
}
static inline u32 smsc911x_reg_read(struct smsc911x_data *pdata, u32 reg)
{
u32 data;
unsigned long flags;
spin_lock_irqsave(&pdata->dev_lock, flags);
data = pdata->ops->reg_read(pdata, reg);
spin_unlock_irqrestore(&pdata->dev_lock, flags);
return data;
}
static inline void __smsc911x_reg_write(struct smsc911x_data *pdata, u32 reg,
u32 val)
{
if (pdata->config.flags & SMSC911X_USE_32BIT) {
writel(val, pdata->ioaddr + reg);
return;
}
if (pdata->config.flags & SMSC911X_USE_16BIT) {
writew(val & 0xFFFF, pdata->ioaddr + reg);
writew((val >> 16) & 0xFFFF, pdata->ioaddr + reg + 2);
return;
}
BUG();
}
static inline void
__smsc911x_reg_write_shift(struct smsc911x_data *pdata, u32 reg, u32 val)
{
if (pdata->config.flags & SMSC911X_USE_32BIT) {
writel(val, pdata->ioaddr + __smsc_shift(pdata, reg));
return;
}
if (pdata->config.flags & SMSC911X_USE_16BIT) {
writew(val & 0xFFFF,
pdata->ioaddr + __smsc_shift(pdata, reg));
writew((val >> 16) & 0xFFFF,
pdata->ioaddr + __smsc_shift(pdata, reg + 2));
return;
}
BUG();
}
static inline void smsc911x_reg_write(struct smsc911x_data *pdata, u32 reg,
u32 val)
{
unsigned long flags;
spin_lock_irqsave(&pdata->dev_lock, flags);
pdata->ops->reg_write(pdata, reg, val);
spin_unlock_irqrestore(&pdata->dev_lock, flags);
}
/* Writes a packet to the TX_DATA_FIFO */
static inline void
smsc911x_tx_writefifo(struct smsc911x_data *pdata, unsigned int *buf,
unsigned int wordcount)
{
unsigned long flags;
spin_lock_irqsave(&pdata->dev_lock, flags);
if (pdata->config.flags & SMSC911X_SWAP_FIFO) {
while (wordcount--)
__smsc911x_reg_write(pdata, TX_DATA_FIFO,
swab32(*buf++));
goto out;
}
if (pdata->config.flags & SMSC911X_USE_32BIT) {
iowrite32_rep(pdata->ioaddr + TX_DATA_FIFO, buf, wordcount);
goto out;
}
if (pdata->config.flags & SMSC911X_USE_16BIT) {
while (wordcount--)
__smsc911x_reg_write(pdata, TX_DATA_FIFO, *buf++);
goto out;
}
BUG();
out:
spin_unlock_irqrestore(&pdata->dev_lock, flags);
}
/* Writes a packet to the TX_DATA_FIFO - shifted version */
static inline void
smsc911x_tx_writefifo_shift(struct smsc911x_data *pdata, unsigned int *buf,
unsigned int wordcount)
{
unsigned long flags;
spin_lock_irqsave(&pdata->dev_lock, flags);
if (pdata->config.flags & SMSC911X_SWAP_FIFO) {
while (wordcount--)
__smsc911x_reg_write_shift(pdata, TX_DATA_FIFO,
swab32(*buf++));
goto out;
}
if (pdata->config.flags & SMSC911X_USE_32BIT) {
iowrite32_rep(pdata->ioaddr + __smsc_shift(pdata,
TX_DATA_FIFO), buf, wordcount);
goto out;
}
if (pdata->config.flags & SMSC911X_USE_16BIT) {
while (wordcount--)
__smsc911x_reg_write_shift(pdata,
TX_DATA_FIFO, *buf++);
goto out;
}
BUG();
out:
spin_unlock_irqrestore(&pdata->dev_lock, flags);
}
/* Reads a packet out of the RX_DATA_FIFO */
static inline void
smsc911x_rx_readfifo(struct smsc911x_data *pdata, unsigned int *buf,
unsigned int wordcount)
{
unsigned long flags;
spin_lock_irqsave(&pdata->dev_lock, flags);
if (pdata->config.flags & SMSC911X_SWAP_FIFO) {
while (wordcount--)
*buf++ = swab32(__smsc911x_reg_read(pdata,
RX_DATA_FIFO));
goto out;
}
if (pdata->config.flags & SMSC911X_USE_32BIT) {
ioread32_rep(pdata->ioaddr + RX_DATA_FIFO, buf, wordcount);
goto out;
}
if (pdata->config.flags & SMSC911X_USE_16BIT) {
while (wordcount--)
*buf++ = __smsc911x_reg_read(pdata, RX_DATA_FIFO);
goto out;
}
BUG();
out:
spin_unlock_irqrestore(&pdata->dev_lock, flags);
}
/* Reads a packet out of the RX_DATA_FIFO - shifted version */
static inline void
smsc911x_rx_readfifo_shift(struct smsc911x_data *pdata, unsigned int *buf,
unsigned int wordcount)
{
unsigned long flags;
spin_lock_irqsave(&pdata->dev_lock, flags);
if (pdata->config.flags & SMSC911X_SWAP_FIFO) {
while (wordcount--)
*buf++ = swab32(__smsc911x_reg_read_shift(pdata,
RX_DATA_FIFO));
goto out;
}
if (pdata->config.flags & SMSC911X_USE_32BIT) {
ioread32_rep(pdata->ioaddr + __smsc_shift(pdata,
RX_DATA_FIFO), buf, wordcount);
goto out;
}
if (pdata->config.flags & SMSC911X_USE_16BIT) {
while (wordcount--)
*buf++ = __smsc911x_reg_read_shift(pdata,
RX_DATA_FIFO);
goto out;
}
BUG();
out:
spin_unlock_irqrestore(&pdata->dev_lock, flags);
}
/*
* enable regulator and clock resources.
*/
static int smsc911x_enable_resources(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct smsc911x_data *pdata = netdev_priv(ndev);
int ret = 0;
ret = regulator_bulk_enable(ARRAY_SIZE(pdata->supplies),
pdata->supplies);
if (ret)
netdev_err(ndev, "failed to enable regulators %d\n",
ret);
if (!IS_ERR(pdata->clk)) {
ret = clk_prepare_enable(pdata->clk);
if (ret < 0)
netdev_err(ndev, "failed to enable clock %d\n", ret);
}
return ret;
}
/*
* disable resources, currently just regulators.
*/
static int smsc911x_disable_resources(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct smsc911x_data *pdata = netdev_priv(ndev);
int ret = 0;
ret = regulator_bulk_disable(ARRAY_SIZE(pdata->supplies),
pdata->supplies);
if (!IS_ERR(pdata->clk))
clk_disable_unprepare(pdata->clk);
return ret;
}
/*
* Request resources, currently just regulators.
*
* The SMSC911x has two power pins: vddvario and vdd33a, in designs where
* these are not always-on we need to request regulators to be turned on
* before we can try to access the device registers.
*/
static int smsc911x_request_resources(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct smsc911x_data *pdata = netdev_priv(ndev);
int ret = 0;
/* Request regulators */
pdata->supplies[0].supply = "vdd33a";
pdata->supplies[1].supply = "vddvario";
ret = regulator_bulk_get(&pdev->dev,
ARRAY_SIZE(pdata->supplies),
pdata->supplies);
if (ret)
netdev_err(ndev, "couldn't get regulators %d\n",
ret);
/* Request clock */
pdata->clk = clk_get(&pdev->dev, NULL);
if (IS_ERR(pdata->clk))
netdev_warn(ndev, "couldn't get clock %li\n", PTR_ERR(pdata->clk));
return ret;
}
/*
* Free resources, currently just regulators.
*
*/
static void smsc911x_free_resources(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct smsc911x_data *pdata = netdev_priv(ndev);
/* Free regulators */
regulator_bulk_free(ARRAY_SIZE(pdata->supplies),
pdata->supplies);
/* Free clock */
if (!IS_ERR(pdata->clk)) {
clk_put(pdata->clk);
pdata->clk = NULL;
}
}
/* waits for MAC not busy, with timeout. Only called by smsc911x_mac_read
* and smsc911x_mac_write, so assumes mac_lock is held */
static int smsc911x_mac_complete(struct smsc911x_data *pdata)
{
int i;
u32 val;
SMSC_ASSERT_MAC_LOCK(pdata);
for (i = 0; i < 40; i++) {
val = smsc911x_reg_read(pdata, MAC_CSR_CMD);
if (!(val & MAC_CSR_CMD_CSR_BUSY_))
return 0;
}
SMSC_WARN(pdata, hw, "Timed out waiting for MAC not BUSY. "
"MAC_CSR_CMD: 0x%08X", val);
return -EIO;
}
/* Fetches a MAC register value. Assumes mac_lock is acquired */
static u32 smsc911x_mac_read(struct smsc911x_data *pdata, unsigned int offset)
{
unsigned int temp;
SMSC_ASSERT_MAC_LOCK(pdata);
temp = smsc911x_reg_read(pdata, MAC_CSR_CMD);
if (unlikely(temp & MAC_CSR_CMD_CSR_BUSY_)) {
SMSC_WARN(pdata, hw, "MAC busy at entry");
return 0xFFFFFFFF;
}
/* Send the MAC cmd */
smsc911x_reg_write(pdata, MAC_CSR_CMD, ((offset & 0xFF) |
MAC_CSR_CMD_CSR_BUSY_ | MAC_CSR_CMD_R_NOT_W_));
/* Workaround for hardware read-after-write restriction */
temp = smsc911x_reg_read(pdata, BYTE_TEST);
/* Wait for the read to complete */
if (likely(smsc911x_mac_complete(pdata) == 0))
return smsc911x_reg_read(pdata, MAC_CSR_DATA);
SMSC_WARN(pdata, hw, "MAC busy after read");
return 0xFFFFFFFF;
}
/* Set a mac register, mac_lock must be acquired before calling */
static void smsc911x_mac_write(struct smsc911x_data *pdata,
unsigned int offset, u32 val)
{
unsigned int temp;
SMSC_ASSERT_MAC_LOCK(pdata);
temp = smsc911x_reg_read(pdata, MAC_CSR_CMD);
if (unlikely(temp & MAC_CSR_CMD_CSR_BUSY_)) {
SMSC_WARN(pdata, hw,
"smsc911x_mac_write failed, MAC busy at entry");
return;
}
/* Send data to write */
smsc911x_reg_write(pdata, MAC_CSR_DATA, val);
/* Write the actual data */
smsc911x_reg_write(pdata, MAC_CSR_CMD, ((offset & 0xFF) |
MAC_CSR_CMD_CSR_BUSY_));
/* Workaround for hardware read-after-write restriction */
temp = smsc911x_reg_read(pdata, BYTE_TEST);
/* Wait for the write to complete */
if (likely(smsc911x_mac_complete(pdata) == 0))
return;
SMSC_WARN(pdata, hw, "smsc911x_mac_write failed, MAC busy after write");
}
/* Get a phy register */
static int smsc911x_mii_read(struct mii_bus *bus, int phyaddr, int regidx)
{
struct smsc911x_data *pdata = (struct smsc911x_data *)bus->priv;
unsigned long flags;
unsigned int addr;
int i, reg;
spin_lock_irqsave(&pdata->mac_lock, flags);
/* Confirm MII not busy */
if (unlikely(smsc911x_mac_read(pdata, MII_ACC) & MII_ACC_MII_BUSY_)) {
SMSC_WARN(pdata, hw, "MII is busy in smsc911x_mii_read???");
reg = -EIO;
goto out;
}
/* Set the address, index & direction (read from PHY) */
addr = ((phyaddr & 0x1F) << 11) | ((regidx & 0x1F) << 6);
smsc911x_mac_write(pdata, MII_ACC, addr);
/* Wait for read to complete w/ timeout */
for (i = 0; i < 100; i++)
if (!(smsc911x_mac_read(pdata, MII_ACC) & MII_ACC_MII_BUSY_)) {
reg = smsc911x_mac_read(pdata, MII_DATA);
goto out;
}
SMSC_WARN(pdata, hw, "Timed out waiting for MII read to finish");
reg = -EIO;
out:
spin_unlock_irqrestore(&pdata->mac_lock, flags);
return reg;
}
/* Set a phy register */
static int smsc911x_mii_write(struct mii_bus *bus, int phyaddr, int regidx,
u16 val)
{
struct smsc911x_data *pdata = (struct smsc911x_data *)bus->priv;
unsigned long flags;
unsigned int addr;
int i, reg;
spin_lock_irqsave(&pdata->mac_lock, flags);
/* Confirm MII not busy */
if (unlikely(smsc911x_mac_read(pdata, MII_ACC) & MII_ACC_MII_BUSY_)) {
SMSC_WARN(pdata, hw, "MII is busy in smsc911x_mii_write???");
reg = -EIO;
goto out;
}
/* Put the data to write in the MAC */
smsc911x_mac_write(pdata, MII_DATA, val);
/* Set the address, index & direction (write to PHY) */
addr = ((phyaddr & 0x1F) << 11) | ((regidx & 0x1F) << 6) |
MII_ACC_MII_WRITE_;
smsc911x_mac_write(pdata, MII_ACC, addr);
/* Wait for write to complete w/ timeout */
for (i = 0; i < 100; i++)
if (!(smsc911x_mac_read(pdata, MII_ACC) & MII_ACC_MII_BUSY_)) {
reg = 0;
goto out;
}
SMSC_WARN(pdata, hw, "Timed out waiting for MII write to finish");
reg = -EIO;
out:
spin_unlock_irqrestore(&pdata->mac_lock, flags);
return reg;
}
/* Switch to external phy. Assumes tx and rx are stopped. */
static void smsc911x_phy_enable_external(struct smsc911x_data *pdata)
{
unsigned int hwcfg = smsc911x_reg_read(pdata, HW_CFG);
/* Disable phy clocks to the MAC */
hwcfg &= (~HW_CFG_PHY_CLK_SEL_);
hwcfg |= HW_CFG_PHY_CLK_SEL_CLK_DIS_;
smsc911x_reg_write(pdata, HW_CFG, hwcfg);
udelay(10); /* Enough time for clocks to stop */
/* Switch to external phy */
hwcfg |= HW_CFG_EXT_PHY_EN_;
smsc911x_reg_write(pdata, HW_CFG, hwcfg);
/* Enable phy clocks to the MAC */
hwcfg &= (~HW_CFG_PHY_CLK_SEL_);
hwcfg |= HW_CFG_PHY_CLK_SEL_EXT_PHY_;
smsc911x_reg_write(pdata, HW_CFG, hwcfg);
udelay(10); /* Enough time for clocks to restart */
hwcfg |= HW_CFG_SMI_SEL_;
smsc911x_reg_write(pdata, HW_CFG, hwcfg);
}
/* Autodetects and enables external phy if present on supported chips.
* autodetection can be overridden by specifying SMSC911X_FORCE_INTERNAL_PHY
* or SMSC911X_FORCE_EXTERNAL_PHY in the platform_data flags. */
static void smsc911x_phy_initialise_external(struct smsc911x_data *pdata)
{
unsigned int hwcfg = smsc911x_reg_read(pdata, HW_CFG);
if (pdata->config.flags & SMSC911X_FORCE_INTERNAL_PHY) {
SMSC_TRACE(pdata, hw, "Forcing internal PHY");
pdata->using_extphy = 0;
} else if (pdata->config.flags & SMSC911X_FORCE_EXTERNAL_PHY) {
SMSC_TRACE(pdata, hw, "Forcing external PHY");
smsc911x_phy_enable_external(pdata);
pdata->using_extphy = 1;
} else if (hwcfg & HW_CFG_EXT_PHY_DET_) {
SMSC_TRACE(pdata, hw,
"HW_CFG EXT_PHY_DET set, using external PHY");
smsc911x_phy_enable_external(pdata);
pdata->using_extphy = 1;
} else {
SMSC_TRACE(pdata, hw,
"HW_CFG EXT_PHY_DET clear, using internal PHY");
pdata->using_extphy = 0;
}
}
/* Fetches a tx status out of the status fifo */
static unsigned int smsc911x_tx_get_txstatus(struct smsc911x_data *pdata)
{
unsigned int result =
smsc911x_reg_read(pdata, TX_FIFO_INF) & TX_FIFO_INF_TSUSED_;
if (result != 0)
result = smsc911x_reg_read(pdata, TX_STATUS_FIFO);
return result;
}
/* Fetches the next rx status */
static unsigned int smsc911x_rx_get_rxstatus(struct smsc911x_data *pdata)
{
unsigned int result =
smsc911x_reg_read(pdata, RX_FIFO_INF) & RX_FIFO_INF_RXSUSED_;
if (result != 0)
result = smsc911x_reg_read(pdata, RX_STATUS_FIFO);
return result;
}
#ifdef USE_PHY_WORK_AROUND
static int smsc911x_phy_check_loopbackpkt(struct smsc911x_data *pdata)
{
unsigned int tries;
u32 wrsz;
u32 rdsz;
ulong bufp;
for (tries = 0; tries < 10; tries++) {
unsigned int txcmd_a;
unsigned int txcmd_b;
unsigned int status;
unsigned int pktlength;
unsigned int i;
/* Zero-out rx packet memory */
memset(pdata->loopback_rx_pkt, 0, MIN_PACKET_SIZE);
/* Write tx packet to 118 */
txcmd_a = (u32)((ulong)pdata->loopback_tx_pkt & 0x03) << 16;
txcmd_a |= TX_CMD_A_FIRST_SEG_ | TX_CMD_A_LAST_SEG_;
txcmd_a |= MIN_PACKET_SIZE;
txcmd_b = MIN_PACKET_SIZE << 16 | MIN_PACKET_SIZE;
smsc911x_reg_write(pdata, TX_DATA_FIFO, txcmd_a);
smsc911x_reg_write(pdata, TX_DATA_FIFO, txcmd_b);
bufp = (ulong)pdata->loopback_tx_pkt & (~0x3);
wrsz = MIN_PACKET_SIZE + 3;
wrsz += (u32)((ulong)pdata->loopback_tx_pkt & 0x3);
wrsz >>= 2;
pdata->ops->tx_writefifo(pdata, (unsigned int *)bufp, wrsz);
/* Wait till transmit is done */
i = 60;
do {
udelay(5);
status = smsc911x_tx_get_txstatus(pdata);
} while ((i--) && (!status));
if (!status) {
SMSC_WARN(pdata, hw,
"Failed to transmit during loopback test");
continue;
}
if (status & TX_STS_ES_) {
SMSC_WARN(pdata, hw,
"Transmit encountered errors during loopback test");
continue;
}
/* Wait till receive is done */
i = 60;
do {
udelay(5);
status = smsc911x_rx_get_rxstatus(pdata);
} while ((i--) && (!status));
if (!status) {
SMSC_WARN(pdata, hw,
"Failed to receive during loopback test");
continue;
}
if (status & RX_STS_ES_) {
SMSC_WARN(pdata, hw,
"Receive encountered errors during loopback test");
continue;
}
pktlength = ((status & 0x3FFF0000UL) >> 16);
bufp = (ulong)pdata->loopback_rx_pkt;
rdsz = pktlength + 3;
rdsz += (u32)((ulong)pdata->loopback_rx_pkt & 0x3);
rdsz >>= 2;
pdata->ops->rx_readfifo(pdata, (unsigned int *)bufp, rdsz);
if (pktlength != (MIN_PACKET_SIZE + 4)) {
SMSC_WARN(pdata, hw, "Unexpected packet size "
"during loop back test, size=%d, will retry",
pktlength);
} else {
unsigned int j;
int mismatch = 0;
for (j = 0; j < MIN_PACKET_SIZE; j++) {
if (pdata->loopback_tx_pkt[j]
!= pdata->loopback_rx_pkt[j]) {
mismatch = 1;
break;
}
}
if (!mismatch) {
SMSC_TRACE(pdata, hw, "Successfully verified "
"loopback packet");
return 0;
} else {
SMSC_WARN(pdata, hw, "Data mismatch "
"during loop back test, will retry");
}
}
}
return -EIO;
}
static int smsc911x_phy_reset(struct smsc911x_data *pdata)
{
struct phy_device *phy_dev = pdata->phy_dev;
unsigned int temp;
unsigned int i = 100000;
BUG_ON(!phy_dev);
BUG_ON(!phy_dev->bus);
SMSC_TRACE(pdata, hw, "Performing PHY BCR Reset");
smsc911x_mii_write(phy_dev->bus, phy_dev->addr, MII_BMCR, BMCR_RESET);
do {
msleep(1);
temp = smsc911x_mii_read(phy_dev->bus, phy_dev->addr,
MII_BMCR);
} while ((i--) && (temp & BMCR_RESET));
if (temp & BMCR_RESET) {
SMSC_WARN(pdata, hw, "PHY reset failed to complete");
return -EIO;
}
/* Extra delay required because the phy may not be completed with
* its reset when BMCR_RESET is cleared. Specs say 256 uS is
* enough delay but using 1ms here to be safe */
msleep(1);
return 0;
}
static int smsc911x_phy_loopbacktest(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
struct phy_device *phy_dev = pdata->phy_dev;
int result = -EIO;
unsigned int i, val;
unsigned long flags;
/* Initialise tx packet using broadcast destination address */
memset(pdata->loopback_tx_pkt, 0xff, ETH_ALEN);
/* Use incrementing source address */
for (i = 6; i < 12; i++)
pdata->loopback_tx_pkt[i] = (char)i;
/* Set length type field */
pdata->loopback_tx_pkt[12] = 0x00;
pdata->loopback_tx_pkt[13] = 0x00;
for (i = 14; i < MIN_PACKET_SIZE; i++)
pdata->loopback_tx_pkt[i] = (char)i;
val = smsc911x_reg_read(pdata, HW_CFG);
val &= HW_CFG_TX_FIF_SZ_;
val |= HW_CFG_SF_;
smsc911x_reg_write(pdata, HW_CFG, val);
smsc911x_reg_write(pdata, TX_CFG, TX_CFG_TX_ON_);
smsc911x_reg_write(pdata, RX_CFG,
(u32)((ulong)pdata->loopback_rx_pkt & 0x03) << 8);
for (i = 0; i < 10; i++) {
/* Set PHY to 10/FD, no ANEG, and loopback mode */
smsc911x_mii_write(phy_dev->bus, phy_dev->addr, MII_BMCR,
BMCR_LOOPBACK | BMCR_FULLDPLX);
/* Enable MAC tx/rx, FD */
spin_lock_irqsave(&pdata->mac_lock, flags);
smsc911x_mac_write(pdata, MAC_CR, MAC_CR_FDPX_
| MAC_CR_TXEN_ | MAC_CR_RXEN_);
spin_unlock_irqrestore(&pdata->mac_lock, flags);
if (smsc911x_phy_check_loopbackpkt(pdata) == 0) {
result = 0;
break;
}
pdata->resetcount++;
/* Disable MAC rx */
spin_lock_irqsave(&pdata->mac_lock, flags);
smsc911x_mac_write(pdata, MAC_CR, 0);
spin_unlock_irqrestore(&pdata->mac_lock, flags);
smsc911x_phy_reset(pdata);
}
/* Disable MAC */
spin_lock_irqsave(&pdata->mac_lock, flags);
smsc911x_mac_write(pdata, MAC_CR, 0);
spin_unlock_irqrestore(&pdata->mac_lock, flags);
/* Cancel PHY loopback mode */
smsc911x_mii_write(phy_dev->bus, phy_dev->addr, MII_BMCR, 0);
smsc911x_reg_write(pdata, TX_CFG, 0);
smsc911x_reg_write(pdata, RX_CFG, 0);
return result;
}
#endif /* USE_PHY_WORK_AROUND */
static void smsc911x_phy_update_flowcontrol(struct smsc911x_data *pdata)
{
struct phy_device *phy_dev = pdata->phy_dev;
u32 afc = smsc911x_reg_read(pdata, AFC_CFG);
u32 flow;
unsigned long flags;
if (phy_dev->duplex == DUPLEX_FULL) {
u16 lcladv = phy_read(phy_dev, MII_ADVERTISE);
u16 rmtadv = phy_read(phy_dev, MII_LPA);
u8 cap = mii_resolve_flowctrl_fdx(lcladv, rmtadv);
if (cap & FLOW_CTRL_RX)
flow = 0xFFFF0002;
else
flow = 0;
if (cap & FLOW_CTRL_TX)
afc |= 0xF;
else
afc &= ~0xF;
SMSC_TRACE(pdata, hw, "rx pause %s, tx pause %s",
(cap & FLOW_CTRL_RX ? "enabled" : "disabled"),
(cap & FLOW_CTRL_TX ? "enabled" : "disabled"));
} else {
SMSC_TRACE(pdata, hw, "half duplex");
flow = 0;
afc |= 0xF;
}
spin_lock_irqsave(&pdata->mac_lock, flags);
smsc911x_mac_write(pdata, FLOW, flow);
spin_unlock_irqrestore(&pdata->mac_lock, flags);
smsc911x_reg_write(pdata, AFC_CFG, afc);
}
/* Update link mode if anything has changed. Called periodically when the
* PHY is in polling mode, even if nothing has changed. */
static void smsc911x_phy_adjust_link(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
struct phy_device *phy_dev = pdata->phy_dev;
unsigned long flags;
int carrier;
if (phy_dev->duplex != pdata->last_duplex) {
unsigned int mac_cr;
SMSC_TRACE(pdata, hw, "duplex state has changed");
spin_lock_irqsave(&pdata->mac_lock, flags);
mac_cr = smsc911x_mac_read(pdata, MAC_CR);
if (phy_dev->duplex) {
SMSC_TRACE(pdata, hw,
"configuring for full duplex mode");
mac_cr |= MAC_CR_FDPX_;
} else {
SMSC_TRACE(pdata, hw,
"configuring for half duplex mode");
mac_cr &= ~MAC_CR_FDPX_;
}
smsc911x_mac_write(pdata, MAC_CR, mac_cr);
spin_unlock_irqrestore(&pdata->mac_lock, flags);
smsc911x_phy_update_flowcontrol(pdata);
pdata->last_duplex = phy_dev->duplex;
}
carrier = netif_carrier_ok(dev);
if (carrier != pdata->last_carrier) {
SMSC_TRACE(pdata, hw, "carrier state has changed");
if (carrier) {
SMSC_TRACE(pdata, hw, "configuring for carrier OK");
if ((pdata->gpio_orig_setting & GPIO_CFG_LED1_EN_) &&
(!pdata->using_extphy)) {
/* Restore original GPIO configuration */
pdata->gpio_setting = pdata->gpio_orig_setting;
smsc911x_reg_write(pdata, SMSC_GPIO_CFG,
pdata->gpio_setting);
}
} else {
SMSC_TRACE(pdata, hw, "configuring for no carrier");
/* Check global setting that LED1
* usage is 10/100 indicator */
pdata->gpio_setting = smsc911x_reg_read(pdata,
SMSC_GPIO_CFG);
if ((pdata->gpio_setting & GPIO_CFG_LED1_EN_) &&
(!pdata->using_extphy)) {
/* Force 10/100 LED off, after saving
* original GPIO configuration */
pdata->gpio_orig_setting = pdata->gpio_setting;
pdata->gpio_setting &= ~GPIO_CFG_LED1_EN_;
pdata->gpio_setting |= (GPIO_CFG_GPIOBUF0_
| GPIO_CFG_GPIODIR0_
| GPIO_CFG_GPIOD0_);
smsc911x_reg_write(pdata, SMSC_GPIO_CFG,
pdata->gpio_setting);
}
}
pdata->last_carrier = carrier;
}
}
static int smsc911x_mii_probe(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
struct phy_device *phydev = NULL;
int ret;
/* find the first phy */
phydev = phy_find_first(pdata->mii_bus);
if (!phydev) {
netdev_err(dev, "no PHY found\n");
return -ENODEV;
}
SMSC_TRACE(pdata, probe, "PHY: addr %d, phy_id 0x%08X",
phydev->addr, phydev->phy_id);
ret = phy_connect_direct(dev, phydev, &smsc911x_phy_adjust_link,
pdata->config.phy_interface);
if (ret) {
netdev_err(dev, "Could not attach to PHY\n");
return ret;
}
netdev_info(dev,
"attached PHY driver [%s] (mii_bus:phy_addr=%s, irq=%d)\n",
phydev->drv->name, dev_name(&phydev->dev), phydev->irq);
/* mask with MAC supported features */
phydev->supported &= (PHY_BASIC_FEATURES | SUPPORTED_Pause |
SUPPORTED_Asym_Pause);
phydev->advertising = phydev->supported;
pdata->phy_dev = phydev;
pdata->last_duplex = -1;
pdata->last_carrier = -1;
#ifdef USE_PHY_WORK_AROUND
if (smsc911x_phy_loopbacktest(dev) < 0) {
SMSC_WARN(pdata, hw, "Failed Loop Back Test");
return -ENODEV;
}
SMSC_TRACE(pdata, hw, "Passed Loop Back Test");
#endif /* USE_PHY_WORK_AROUND */
SMSC_TRACE(pdata, hw, "phy initialised successfully");
return 0;
}
static int smsc911x_mii_init(struct platform_device *pdev,
struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
int err = -ENXIO, i;
pdata->mii_bus = mdiobus_alloc();
if (!pdata->mii_bus) {
err = -ENOMEM;
goto err_out_1;
}
pdata->mii_bus->name = SMSC_MDIONAME;
snprintf(pdata->mii_bus->id, MII_BUS_ID_SIZE, "%s-%x",
pdev->name, pdev->id);
pdata->mii_bus->priv = pdata;
pdata->mii_bus->read = smsc911x_mii_read;
pdata->mii_bus->write = smsc911x_mii_write;
pdata->mii_bus->irq = pdata->phy_irq;
for (i = 0; i < PHY_MAX_ADDR; ++i)
pdata->mii_bus->irq[i] = PHY_POLL;
pdata->mii_bus->parent = &pdev->dev;
switch (pdata->idrev & 0xFFFF0000) {
case 0x01170000:
case 0x01150000:
case 0x117A0000:
case 0x115A0000:
/* External PHY supported, try to autodetect */
smsc911x_phy_initialise_external(pdata);
break;
default:
SMSC_TRACE(pdata, hw, "External PHY is not supported, "
"using internal PHY");
pdata->using_extphy = 0;
break;
}
if (!pdata->using_extphy) {
/* Mask all PHYs except ID 1 (internal) */
pdata->mii_bus->phy_mask = ~(1 << 1);
}
if (mdiobus_register(pdata->mii_bus)) {
SMSC_WARN(pdata, probe, "Error registering mii bus");
goto err_out_free_bus_2;
}
if (smsc911x_mii_probe(dev) < 0) {
SMSC_WARN(pdata, probe, "Error registering mii bus");
goto err_out_unregister_bus_3;
}
return 0;
err_out_unregister_bus_3:
mdiobus_unregister(pdata->mii_bus);
err_out_free_bus_2:
mdiobus_free(pdata->mii_bus);
err_out_1:
return err;
}
/* Gets the number of tx statuses in the fifo */
static unsigned int smsc911x_tx_get_txstatcount(struct smsc911x_data *pdata)
{
return (smsc911x_reg_read(pdata, TX_FIFO_INF)
& TX_FIFO_INF_TSUSED_) >> 16;
}
/* Reads tx statuses and increments counters where necessary */
static void smsc911x_tx_update_txcounters(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
unsigned int tx_stat;
while ((tx_stat = smsc911x_tx_get_txstatus(pdata)) != 0) {
if (unlikely(tx_stat & 0x80000000)) {
/* In this driver the packet tag is used as the packet
* length. Since a packet length can never reach the
* size of 0x8000, this bit is reserved. It is worth
* noting that the "reserved bit" in the warning above
* does not reference a hardware defined reserved bit
* but rather a driver defined one.
*/
SMSC_WARN(pdata, hw, "Packet tag reserved bit is high");
} else {
if (unlikely(tx_stat & TX_STS_ES_)) {
dev->stats.tx_errors++;
} else {
dev->stats.tx_packets++;
dev->stats.tx_bytes += (tx_stat >> 16);
}
if (unlikely(tx_stat & TX_STS_EXCESS_COL_)) {
dev->stats.collisions += 16;
dev->stats.tx_aborted_errors += 1;
} else {
dev->stats.collisions +=
((tx_stat >> 3) & 0xF);
}
if (unlikely(tx_stat & TX_STS_LOST_CARRIER_))
dev->stats.tx_carrier_errors += 1;
if (unlikely(tx_stat & TX_STS_LATE_COL_)) {
dev->stats.collisions++;
dev->stats.tx_aborted_errors++;
}
}
}
}
/* Increments the Rx error counters */
static void
smsc911x_rx_counterrors(struct net_device *dev, unsigned int rxstat)
{
int crc_err = 0;
if (unlikely(rxstat & RX_STS_ES_)) {
dev->stats.rx_errors++;
if (unlikely(rxstat & RX_STS_CRC_ERR_)) {
dev->stats.rx_crc_errors++;
crc_err = 1;
}
}
if (likely(!crc_err)) {
if (unlikely((rxstat & RX_STS_FRAME_TYPE_) &&
(rxstat & RX_STS_LENGTH_ERR_)))
dev->stats.rx_length_errors++;
if (rxstat & RX_STS_MCAST_)
dev->stats.multicast++;
}
}
/* Quickly dumps bad packets */
static void
smsc911x_rx_fastforward(struct smsc911x_data *pdata, unsigned int pktwords)
{
if (likely(pktwords >= 4)) {
unsigned int timeout = 500;
unsigned int val;
smsc911x_reg_write(pdata, RX_DP_CTRL, RX_DP_CTRL_RX_FFWD_);
do {
udelay(1);
val = smsc911x_reg_read(pdata, RX_DP_CTRL);
} while ((val & RX_DP_CTRL_RX_FFWD_) && --timeout);
if (unlikely(timeout == 0))
SMSC_WARN(pdata, hw, "Timed out waiting for "
"RX FFWD to finish, RX_DP_CTRL: 0x%08X", val);
} else {
unsigned int temp;
while (pktwords--)
temp = smsc911x_reg_read(pdata, RX_DATA_FIFO);
}
}
/* NAPI poll function */
static int smsc911x_poll(struct napi_struct *napi, int budget)
{
struct smsc911x_data *pdata =
container_of(napi, struct smsc911x_data, napi);
struct net_device *dev = pdata->dev;
int npackets = 0;
while (npackets < budget) {
unsigned int pktlength;
unsigned int pktwords;
struct sk_buff *skb;
unsigned int rxstat = smsc911x_rx_get_rxstatus(pdata);
if (!rxstat) {
unsigned int temp;
/* We processed all packets available. Tell NAPI it can
* stop polling then re-enable rx interrupts */
smsc911x_reg_write(pdata, INT_STS, INT_STS_RSFL_);
napi_complete(napi);
temp = smsc911x_reg_read(pdata, INT_EN);
temp |= INT_EN_RSFL_EN_;
smsc911x_reg_write(pdata, INT_EN, temp);
break;
}
/* Count packet for NAPI scheduling, even if it has an error.
* Error packets still require cycles to discard */
npackets++;
pktlength = ((rxstat & 0x3FFF0000) >> 16);
pktwords = (pktlength + NET_IP_ALIGN + 3) >> 2;
smsc911x_rx_counterrors(dev, rxstat);
if (unlikely(rxstat & RX_STS_ES_)) {
SMSC_WARN(pdata, rx_err,
"Discarding packet with error bit set");
/* Packet has an error, discard it and continue with
* the next */
smsc911x_rx_fastforward(pdata, pktwords);
dev->stats.rx_dropped++;
continue;
}
skb = netdev_alloc_skb(dev, pktwords << 2);
if (unlikely(!skb)) {
SMSC_WARN(pdata, rx_err,
"Unable to allocate skb for rx packet");
/* Drop the packet and stop this polling iteration */
smsc911x_rx_fastforward(pdata, pktwords);
dev->stats.rx_dropped++;
break;
}
pdata->ops->rx_readfifo(pdata,
(unsigned int *)skb->data, pktwords);
/* Align IP on 16B boundary */
skb_reserve(skb, NET_IP_ALIGN);
skb_put(skb, pktlength - 4);
skb->protocol = eth_type_trans(skb, dev);
skb_checksum_none_assert(skb);
netif_receive_skb(skb);
/* Update counters */
dev->stats.rx_packets++;
dev->stats.rx_bytes += (pktlength - 4);
}
/* Return total received packets */
return npackets;
}
/* Returns hash bit number for given MAC address
* Example:
* 01 00 5E 00 00 01 -> returns bit number 31 */
static unsigned int smsc911x_hash(char addr[ETH_ALEN])
{
return (ether_crc(ETH_ALEN, addr) >> 26) & 0x3f;
}
static void smsc911x_rx_multicast_update(struct smsc911x_data *pdata)
{
/* Performs the multicast & mac_cr update. This is called when
* safe on the current hardware, and with the mac_lock held */
unsigned int mac_cr;
SMSC_ASSERT_MAC_LOCK(pdata);
mac_cr = smsc911x_mac_read(pdata, MAC_CR);
mac_cr |= pdata->set_bits_mask;
mac_cr &= ~(pdata->clear_bits_mask);
smsc911x_mac_write(pdata, MAC_CR, mac_cr);
smsc911x_mac_write(pdata, HASHH, pdata->hashhi);
smsc911x_mac_write(pdata, HASHL, pdata->hashlo);
SMSC_TRACE(pdata, hw, "maccr 0x%08X, HASHH 0x%08X, HASHL 0x%08X",
mac_cr, pdata->hashhi, pdata->hashlo);
}
static void smsc911x_rx_multicast_update_workaround(struct smsc911x_data *pdata)
{
unsigned int mac_cr;
/* This function is only called for older LAN911x devices
* (revA or revB), where MAC_CR, HASHH and HASHL should not
* be modified during Rx - newer devices immediately update the
* registers.
*
* This is called from interrupt context */
spin_lock(&pdata->mac_lock);
/* Check Rx has stopped */
if (smsc911x_mac_read(pdata, MAC_CR) & MAC_CR_RXEN_)
SMSC_WARN(pdata, drv, "Rx not stopped");
/* Perform the update - safe to do now Rx has stopped */
smsc911x_rx_multicast_update(pdata);
/* Re-enable Rx */
mac_cr = smsc911x_mac_read(pdata, MAC_CR);
mac_cr |= MAC_CR_RXEN_;
smsc911x_mac_write(pdata, MAC_CR, mac_cr);
pdata->multicast_update_pending = 0;
spin_unlock(&pdata->mac_lock);
}
static int smsc911x_phy_disable_energy_detect(struct smsc911x_data *pdata)
{
int rc = 0;
if (!pdata->phy_dev)
return rc;
rc = phy_read(pdata->phy_dev, MII_LAN83C185_CTRL_STATUS);
if (rc < 0) {
SMSC_WARN(pdata, drv, "Failed reading PHY control reg");
return rc;
}
/*
* If energy is detected the PHY is already awake so is not necessary
* to disable the energy detect power-down mode.
*/
if ((rc & MII_LAN83C185_EDPWRDOWN) &&
!(rc & MII_LAN83C185_ENERGYON)) {
/* Disable energy detect mode for this SMSC Transceivers */
rc = phy_write(pdata->phy_dev, MII_LAN83C185_CTRL_STATUS,
rc & (~MII_LAN83C185_EDPWRDOWN));
if (rc < 0) {
SMSC_WARN(pdata, drv, "Failed writing PHY control reg");
return rc;
}
mdelay(1);
}
return 0;
}
static int smsc911x_phy_enable_energy_detect(struct smsc911x_data *pdata)
{
int rc = 0;
if (!pdata->phy_dev)
return rc;
rc = phy_read(pdata->phy_dev, MII_LAN83C185_CTRL_STATUS);
if (rc < 0) {
SMSC_WARN(pdata, drv, "Failed reading PHY control reg");
return rc;
}
/* Only enable if energy detect mode is already disabled */
if (!(rc & MII_LAN83C185_EDPWRDOWN)) {
mdelay(100);
/* Enable energy detect mode for this SMSC Transceivers */
rc = phy_write(pdata->phy_dev, MII_LAN83C185_CTRL_STATUS,
rc | MII_LAN83C185_EDPWRDOWN);
if (rc < 0) {
SMSC_WARN(pdata, drv, "Failed writing PHY control reg");
return rc;
}
mdelay(1);
}
return 0;
}
static int smsc911x_soft_reset(struct smsc911x_data *pdata)
{
unsigned int timeout;
unsigned int temp;
int ret;
/*
* LAN9210/LAN9211/LAN9220/LAN9221 chips have an internal PHY that
* are initialized in a Energy Detect Power-Down mode that prevents
* the MAC chip to be software reseted. So we have to wakeup the PHY
* before.
*/
if (pdata->generation == 4) {
ret = smsc911x_phy_disable_energy_detect(pdata);
if (ret) {
SMSC_WARN(pdata, drv, "Failed to wakeup the PHY chip");
return ret;
}
}
/* Reset the LAN911x */
smsc911x_reg_write(pdata, HW_CFG, HW_CFG_SRST_);
timeout = 10;
do {
udelay(10);
temp = smsc911x_reg_read(pdata, HW_CFG);
} while ((--timeout) && (temp & HW_CFG_SRST_));
if (unlikely(temp & HW_CFG_SRST_)) {
SMSC_WARN(pdata, drv, "Failed to complete reset");
return -EIO;
}
if (pdata->generation == 4) {
ret = smsc911x_phy_enable_energy_detect(pdata);
if (ret) {
SMSC_WARN(pdata, drv, "Failed to wakeup the PHY chip");
return ret;
}
}
return 0;
}
/* Sets the device MAC address to dev_addr, called with mac_lock held */
static void
smsc911x_set_hw_mac_address(struct smsc911x_data *pdata, u8 dev_addr[6])
{
u32 mac_high16 = (dev_addr[5] << 8) | dev_addr[4];
u32 mac_low32 = (dev_addr[3] << 24) | (dev_addr[2] << 16) |
(dev_addr[1] << 8) | dev_addr[0];
SMSC_ASSERT_MAC_LOCK(pdata);
smsc911x_mac_write(pdata, ADDRH, mac_high16);
smsc911x_mac_write(pdata, ADDRL, mac_low32);
}
static void smsc911x_disable_irq_chip(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
smsc911x_reg_write(pdata, INT_EN, 0);
smsc911x_reg_write(pdata, INT_STS, 0xFFFFFFFF);
}
static int smsc911x_open(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
unsigned int timeout;
unsigned int temp;
unsigned int intcfg;
/* if the phy is not yet registered, retry later*/
if (!pdata->phy_dev) {
SMSC_WARN(pdata, hw, "phy_dev is NULL");
return -EAGAIN;
}
/* Reset the LAN911x */
if (smsc911x_soft_reset(pdata)) {
SMSC_WARN(pdata, hw, "soft reset failed");
return -EIO;
}
smsc911x_reg_write(pdata, HW_CFG, 0x00050000);
smsc911x_reg_write(pdata, AFC_CFG, 0x006E3740);
/* Increase the legal frame size of VLAN tagged frames to 1522 bytes */
spin_lock_irq(&pdata->mac_lock);
smsc911x_mac_write(pdata, VLAN1, ETH_P_8021Q);
spin_unlock_irq(&pdata->mac_lock);
/* Make sure EEPROM has finished loading before setting GPIO_CFG */
timeout = 50;
while ((smsc911x_reg_read(pdata, E2P_CMD) & E2P_CMD_EPC_BUSY_) &&
--timeout) {
udelay(10);
}
if (unlikely(timeout == 0))
SMSC_WARN(pdata, ifup,
"Timed out waiting for EEPROM busy bit to clear");
smsc911x_reg_write(pdata, SMSC_GPIO_CFG, 0x70070000);
/* The soft reset above cleared the device's MAC address,
* restore it from local copy (set in probe) */
spin_lock_irq(&pdata->mac_lock);
smsc911x_set_hw_mac_address(pdata, dev->dev_addr);
spin_unlock_irq(&pdata->mac_lock);
/* Initialise irqs, but leave all sources disabled */
smsc911x_disable_irq_chip(dev);
/* Set interrupt deassertion to 100uS */
intcfg = ((10 << 24) | INT_CFG_IRQ_EN_);
if (pdata->config.irq_polarity) {
SMSC_TRACE(pdata, ifup, "irq polarity: active high");
intcfg |= INT_CFG_IRQ_POL_;
} else {
SMSC_TRACE(pdata, ifup, "irq polarity: active low");
}
if (pdata->config.irq_type) {
SMSC_TRACE(pdata, ifup, "irq type: push-pull");
intcfg |= INT_CFG_IRQ_TYPE_;
} else {
SMSC_TRACE(pdata, ifup, "irq type: open drain");
}
smsc911x_reg_write(pdata, INT_CFG, intcfg);
SMSC_TRACE(pdata, ifup, "Testing irq handler using IRQ %d", dev->irq);
pdata->software_irq_signal = 0;
smp_wmb();
temp = smsc911x_reg_read(pdata, INT_EN);
temp |= INT_EN_SW_INT_EN_;
smsc911x_reg_write(pdata, INT_EN, temp);
timeout = 1000;
while (timeout--) {
if (pdata->software_irq_signal)
break;
msleep(1);
}
if (!pdata->software_irq_signal) {
netdev_warn(dev, "ISR failed signaling test (IRQ %d)\n",
dev->irq);
return -ENODEV;
}
SMSC_TRACE(pdata, ifup, "IRQ handler passed test using IRQ %d",
dev->irq);
netdev_info(dev, "SMSC911x/921x identified at %#08lx, IRQ: %d\n",
(unsigned long)pdata->ioaddr, dev->irq);
/* Reset the last known duplex and carrier */
pdata->last_duplex = -1;
pdata->last_carrier = -1;
/* Bring the PHY up */
phy_start(pdata->phy_dev);
temp = smsc911x_reg_read(pdata, HW_CFG);
/* Preserve TX FIFO size and external PHY configuration */
temp &= (HW_CFG_TX_FIF_SZ_|0x00000FFF);
temp |= HW_CFG_SF_;
smsc911x_reg_write(pdata, HW_CFG, temp);
temp = smsc911x_reg_read(pdata, FIFO_INT);
temp |= FIFO_INT_TX_AVAIL_LEVEL_;
temp &= ~(FIFO_INT_RX_STS_LEVEL_);
smsc911x_reg_write(pdata, FIFO_INT, temp);
/* set RX Data offset to 2 bytes for alignment */
smsc911x_reg_write(pdata, RX_CFG, (NET_IP_ALIGN << 8));
/* enable NAPI polling before enabling RX interrupts */
napi_enable(&pdata->napi);
temp = smsc911x_reg_read(pdata, INT_EN);
temp |= (INT_EN_TDFA_EN_ | INT_EN_RSFL_EN_ | INT_EN_RXSTOP_INT_EN_);
smsc911x_reg_write(pdata, INT_EN, temp);
spin_lock_irq(&pdata->mac_lock);
temp = smsc911x_mac_read(pdata, MAC_CR);
temp |= (MAC_CR_TXEN_ | MAC_CR_RXEN_ | MAC_CR_HBDIS_);
smsc911x_mac_write(pdata, MAC_CR, temp);
spin_unlock_irq(&pdata->mac_lock);
smsc911x_reg_write(pdata, TX_CFG, TX_CFG_TX_ON_);
netif_start_queue(dev);
return 0;
}
/* Entry point for stopping the interface */
static int smsc911x_stop(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
unsigned int temp;
/* Disable all device interrupts */
temp = smsc911x_reg_read(pdata, INT_CFG);
temp &= ~INT_CFG_IRQ_EN_;
smsc911x_reg_write(pdata, INT_CFG, temp);
/* Stop Tx and Rx polling */
netif_stop_queue(dev);
napi_disable(&pdata->napi);
/* At this point all Rx and Tx activity is stopped */
dev->stats.rx_dropped += smsc911x_reg_read(pdata, RX_DROP);
smsc911x_tx_update_txcounters(dev);
/* Bring the PHY down */
if (pdata->phy_dev)
phy_stop(pdata->phy_dev);
SMSC_TRACE(pdata, ifdown, "Interface stopped");
return 0;
}
/* Entry point for transmitting a packet */
static int smsc911x_hard_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
unsigned int freespace;
unsigned int tx_cmd_a;
unsigned int tx_cmd_b;
unsigned int temp;
u32 wrsz;
ulong bufp;
freespace = smsc911x_reg_read(pdata, TX_FIFO_INF) & TX_FIFO_INF_TDFREE_;
if (unlikely(freespace < TX_FIFO_LOW_THRESHOLD))
SMSC_WARN(pdata, tx_err,
"Tx data fifo low, space available: %d", freespace);
/* Word alignment adjustment */
tx_cmd_a = (u32)((ulong)skb->data & 0x03) << 16;
tx_cmd_a |= TX_CMD_A_FIRST_SEG_ | TX_CMD_A_LAST_SEG_;
tx_cmd_a |= (unsigned int)skb->len;
tx_cmd_b = ((unsigned int)skb->len) << 16;
tx_cmd_b |= (unsigned int)skb->len;
smsc911x_reg_write(pdata, TX_DATA_FIFO, tx_cmd_a);
smsc911x_reg_write(pdata, TX_DATA_FIFO, tx_cmd_b);
bufp = (ulong)skb->data & (~0x3);
wrsz = (u32)skb->len + 3;
wrsz += (u32)((ulong)skb->data & 0x3);
wrsz >>= 2;
pdata->ops->tx_writefifo(pdata, (unsigned int *)bufp, wrsz);
freespace -= (skb->len + 32);
skb_tx_timestamp(skb);
dev_kfree_skb(skb);
if (unlikely(smsc911x_tx_get_txstatcount(pdata) >= 30))
smsc911x_tx_update_txcounters(dev);
if (freespace < TX_FIFO_LOW_THRESHOLD) {
netif_stop_queue(dev);
temp = smsc911x_reg_read(pdata, FIFO_INT);
temp &= 0x00FFFFFF;
temp |= 0x32000000;
smsc911x_reg_write(pdata, FIFO_INT, temp);
}
return NETDEV_TX_OK;
}
/* Entry point for getting status counters */
static struct net_device_stats *smsc911x_get_stats(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
smsc911x_tx_update_txcounters(dev);
dev->stats.rx_dropped += smsc911x_reg_read(pdata, RX_DROP);
return &dev->stats;
}
/* Entry point for setting addressing modes */
static void smsc911x_set_multicast_list(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
unsigned long flags;
if (dev->flags & IFF_PROMISC) {
/* Enabling promiscuous mode */
pdata->set_bits_mask = MAC_CR_PRMS_;
pdata->clear_bits_mask = (MAC_CR_MCPAS_ | MAC_CR_HPFILT_);
pdata->hashhi = 0;
pdata->hashlo = 0;
} else if (dev->flags & IFF_ALLMULTI) {
/* Enabling all multicast mode */
pdata->set_bits_mask = MAC_CR_MCPAS_;
pdata->clear_bits_mask = (MAC_CR_PRMS_ | MAC_CR_HPFILT_);
pdata->hashhi = 0;
pdata->hashlo = 0;
} else if (!netdev_mc_empty(dev)) {
/* Enabling specific multicast addresses */
unsigned int hash_high = 0;
unsigned int hash_low = 0;
struct netdev_hw_addr *ha;
pdata->set_bits_mask = MAC_CR_HPFILT_;
pdata->clear_bits_mask = (MAC_CR_PRMS_ | MAC_CR_MCPAS_);
netdev_for_each_mc_addr(ha, dev) {
unsigned int bitnum = smsc911x_hash(ha->addr);
unsigned int mask = 0x01 << (bitnum & 0x1F);
if (bitnum & 0x20)
hash_high |= mask;
else
hash_low |= mask;
}
pdata->hashhi = hash_high;
pdata->hashlo = hash_low;
} else {
/* Enabling local MAC address only */
pdata->set_bits_mask = 0;
pdata->clear_bits_mask =
(MAC_CR_PRMS_ | MAC_CR_MCPAS_ | MAC_CR_HPFILT_);
pdata->hashhi = 0;
pdata->hashlo = 0;
}
spin_lock_irqsave(&pdata->mac_lock, flags);
if (pdata->generation <= 1) {
/* Older hardware revision - cannot change these flags while
* receiving data */
if (!pdata->multicast_update_pending) {
unsigned int temp;
SMSC_TRACE(pdata, hw, "scheduling mcast update");
pdata->multicast_update_pending = 1;
/* Request the hardware to stop, then perform the
* update when we get an RX_STOP interrupt */
temp = smsc911x_mac_read(pdata, MAC_CR);
temp &= ~(MAC_CR_RXEN_);
smsc911x_mac_write(pdata, MAC_CR, temp);
} else {
/* There is another update pending, this should now
* use the newer values */
}
} else {
/* Newer hardware revision - can write immediately */
smsc911x_rx_multicast_update(pdata);
}
spin_unlock_irqrestore(&pdata->mac_lock, flags);
}
static irqreturn_t smsc911x_irqhandler(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
struct smsc911x_data *pdata = netdev_priv(dev);
u32 intsts = smsc911x_reg_read(pdata, INT_STS);
u32 inten = smsc911x_reg_read(pdata, INT_EN);
int serviced = IRQ_NONE;
u32 temp;
if (unlikely(intsts & inten & INT_STS_SW_INT_)) {
temp = smsc911x_reg_read(pdata, INT_EN);
temp &= (~INT_EN_SW_INT_EN_);
smsc911x_reg_write(pdata, INT_EN, temp);
smsc911x_reg_write(pdata, INT_STS, INT_STS_SW_INT_);
pdata->software_irq_signal = 1;
smp_wmb();
serviced = IRQ_HANDLED;
}
if (unlikely(intsts & inten & INT_STS_RXSTOP_INT_)) {
/* Called when there is a multicast update scheduled and
* it is now safe to complete the update */
SMSC_TRACE(pdata, intr, "RX Stop interrupt");
smsc911x_reg_write(pdata, INT_STS, INT_STS_RXSTOP_INT_);
if (pdata->multicast_update_pending)
smsc911x_rx_multicast_update_workaround(pdata);
serviced = IRQ_HANDLED;
}
if (intsts & inten & INT_STS_TDFA_) {
temp = smsc911x_reg_read(pdata, FIFO_INT);
temp |= FIFO_INT_TX_AVAIL_LEVEL_;
smsc911x_reg_write(pdata, FIFO_INT, temp);
smsc911x_reg_write(pdata, INT_STS, INT_STS_TDFA_);
netif_wake_queue(dev);
serviced = IRQ_HANDLED;
}
if (unlikely(intsts & inten & INT_STS_RXE_)) {
SMSC_TRACE(pdata, intr, "RX Error interrupt");
smsc911x_reg_write(pdata, INT_STS, INT_STS_RXE_);
serviced = IRQ_HANDLED;
}
if (likely(intsts & inten & INT_STS_RSFL_)) {
if (likely(napi_schedule_prep(&pdata->napi))) {
/* Disable Rx interrupts */
temp = smsc911x_reg_read(pdata, INT_EN);
temp &= (~INT_EN_RSFL_EN_);
smsc911x_reg_write(pdata, INT_EN, temp);
/* Schedule a NAPI poll */
__napi_schedule(&pdata->napi);
} else {
SMSC_WARN(pdata, rx_err, "napi_schedule_prep failed");
}
serviced = IRQ_HANDLED;
}
return serviced;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void smsc911x_poll_controller(struct net_device *dev)
{
disable_irq(dev->irq);
smsc911x_irqhandler(0, dev);
enable_irq(dev->irq);
}
#endif /* CONFIG_NET_POLL_CONTROLLER */
static int smsc911x_set_mac_address(struct net_device *dev, void *p)
{
struct smsc911x_data *pdata = netdev_priv(dev);
struct sockaddr *addr = p;
/* On older hardware revisions we cannot change the mac address
* registers while receiving data. Newer devices can safely change
* this at any time. */
if (pdata->generation <= 1 && netif_running(dev))
return -EBUSY;
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
memcpy(dev->dev_addr, addr->sa_data, ETH_ALEN);
spin_lock_irq(&pdata->mac_lock);
smsc911x_set_hw_mac_address(pdata, dev->dev_addr);
spin_unlock_irq(&pdata->mac_lock);
netdev_info(dev, "MAC Address: %pM\n", dev->dev_addr);
return 0;
}
/* Standard ioctls for mii-tool */
static int smsc911x_do_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
struct smsc911x_data *pdata = netdev_priv(dev);
if (!netif_running(dev) || !pdata->phy_dev)
return -EINVAL;
return phy_mii_ioctl(pdata->phy_dev, ifr, cmd);
}
static int
smsc911x_ethtool_getsettings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct smsc911x_data *pdata = netdev_priv(dev);
cmd->maxtxpkt = 1;
cmd->maxrxpkt = 1;
return phy_ethtool_gset(pdata->phy_dev, cmd);
}
static int
smsc911x_ethtool_setsettings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct smsc911x_data *pdata = netdev_priv(dev);
return phy_ethtool_sset(pdata->phy_dev, cmd);
}
static void smsc911x_ethtool_getdrvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
strlcpy(info->driver, SMSC_CHIPNAME, sizeof(info->driver));
strlcpy(info->version, SMSC_DRV_VERSION, sizeof(info->version));
strlcpy(info->bus_info, dev_name(dev->dev.parent),
sizeof(info->bus_info));
}
static int smsc911x_ethtool_nwayreset(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
return phy_start_aneg(pdata->phy_dev);
}
static u32 smsc911x_ethtool_getmsglevel(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
return pdata->msg_enable;
}
static void smsc911x_ethtool_setmsglevel(struct net_device *dev, u32 level)
{
struct smsc911x_data *pdata = netdev_priv(dev);
pdata->msg_enable = level;
}
static int smsc911x_ethtool_getregslen(struct net_device *dev)
{
return (((E2P_DATA - ID_REV) / 4 + 1) + (WUCSR - MAC_CR) + 1 + 32) *
sizeof(u32);
}
static void
smsc911x_ethtool_getregs(struct net_device *dev, struct ethtool_regs *regs,
void *buf)
{
struct smsc911x_data *pdata = netdev_priv(dev);
struct phy_device *phy_dev = pdata->phy_dev;
unsigned long flags;
unsigned int i;
unsigned int j = 0;
u32 *data = buf;
regs->version = pdata->idrev;
for (i = ID_REV; i <= E2P_DATA; i += (sizeof(u32)))
data[j++] = smsc911x_reg_read(pdata, i);
for (i = MAC_CR; i <= WUCSR; i++) {
spin_lock_irqsave(&pdata->mac_lock, flags);
data[j++] = smsc911x_mac_read(pdata, i);
spin_unlock_irqrestore(&pdata->mac_lock, flags);
}
for (i = 0; i <= 31; i++)
data[j++] = smsc911x_mii_read(phy_dev->bus, phy_dev->addr, i);
}
static void smsc911x_eeprom_enable_access(struct smsc911x_data *pdata)
{
unsigned int temp = smsc911x_reg_read(pdata, SMSC_GPIO_CFG);
temp &= ~GPIO_CFG_EEPR_EN_;
smsc911x_reg_write(pdata, SMSC_GPIO_CFG, temp);
msleep(1);
}
static int smsc911x_eeprom_send_cmd(struct smsc911x_data *pdata, u32 op)
{
int timeout = 100;
u32 e2cmd;
SMSC_TRACE(pdata, drv, "op 0x%08x", op);
if (smsc911x_reg_read(pdata, E2P_CMD) & E2P_CMD_EPC_BUSY_) {
SMSC_WARN(pdata, drv, "Busy at start");
return -EBUSY;
}
e2cmd = op | E2P_CMD_EPC_BUSY_;
smsc911x_reg_write(pdata, E2P_CMD, e2cmd);
do {
msleep(1);
e2cmd = smsc911x_reg_read(pdata, E2P_CMD);
} while ((e2cmd & E2P_CMD_EPC_BUSY_) && (--timeout));
if (!timeout) {
SMSC_TRACE(pdata, drv, "TIMED OUT");
return -EAGAIN;
}
if (e2cmd & E2P_CMD_EPC_TIMEOUT_) {
SMSC_TRACE(pdata, drv, "Error occurred during eeprom operation");
return -EINVAL;
}
return 0;
}
static int smsc911x_eeprom_read_location(struct smsc911x_data *pdata,
u8 address, u8 *data)
{
u32 op = E2P_CMD_EPC_CMD_READ_ | address;
int ret;
SMSC_TRACE(pdata, drv, "address 0x%x", address);
ret = smsc911x_eeprom_send_cmd(pdata, op);
if (!ret)
data[address] = smsc911x_reg_read(pdata, E2P_DATA);
return ret;
}
static int smsc911x_eeprom_write_location(struct smsc911x_data *pdata,
u8 address, u8 data)
{
u32 op = E2P_CMD_EPC_CMD_ERASE_ | address;
u32 temp;
int ret;
SMSC_TRACE(pdata, drv, "address 0x%x, data 0x%x", address, data);
ret = smsc911x_eeprom_send_cmd(pdata, op);
if (!ret) {
op = E2P_CMD_EPC_CMD_WRITE_ | address;
smsc911x_reg_write(pdata, E2P_DATA, (u32)data);
/* Workaround for hardware read-after-write restriction */
temp = smsc911x_reg_read(pdata, BYTE_TEST);
ret = smsc911x_eeprom_send_cmd(pdata, op);
}
return ret;
}
static int smsc911x_ethtool_get_eeprom_len(struct net_device *dev)
{
return SMSC911X_EEPROM_SIZE;
}
static int smsc911x_ethtool_get_eeprom(struct net_device *dev,
struct ethtool_eeprom *eeprom, u8 *data)
{
struct smsc911x_data *pdata = netdev_priv(dev);
u8 eeprom_data[SMSC911X_EEPROM_SIZE];
int len;
int i;
smsc911x_eeprom_enable_access(pdata);
len = min(eeprom->len, SMSC911X_EEPROM_SIZE);
for (i = 0; i < len; i++) {
int ret = smsc911x_eeprom_read_location(pdata, i, eeprom_data);
if (ret < 0) {
eeprom->len = 0;
return ret;
}
}
memcpy(data, &eeprom_data[eeprom->offset], len);
eeprom->len = len;
return 0;
}
static int smsc911x_ethtool_set_eeprom(struct net_device *dev,
struct ethtool_eeprom *eeprom, u8 *data)
{
int ret;
struct smsc911x_data *pdata = netdev_priv(dev);
smsc911x_eeprom_enable_access(pdata);
smsc911x_eeprom_send_cmd(pdata, E2P_CMD_EPC_CMD_EWEN_);
ret = smsc911x_eeprom_write_location(pdata, eeprom->offset, *data);
smsc911x_eeprom_send_cmd(pdata, E2P_CMD_EPC_CMD_EWDS_);
/* Single byte write, according to man page */
eeprom->len = 1;
return ret;
}
static const struct ethtool_ops smsc911x_ethtool_ops = {
.get_settings = smsc911x_ethtool_getsettings,
.set_settings = smsc911x_ethtool_setsettings,
.get_link = ethtool_op_get_link,
.get_drvinfo = smsc911x_ethtool_getdrvinfo,
.nway_reset = smsc911x_ethtool_nwayreset,
.get_msglevel = smsc911x_ethtool_getmsglevel,
.set_msglevel = smsc911x_ethtool_setmsglevel,
.get_regs_len = smsc911x_ethtool_getregslen,
.get_regs = smsc911x_ethtool_getregs,
.get_eeprom_len = smsc911x_ethtool_get_eeprom_len,
.get_eeprom = smsc911x_ethtool_get_eeprom,
.set_eeprom = smsc911x_ethtool_set_eeprom,
.get_ts_info = ethtool_op_get_ts_info,
};
static const struct net_device_ops smsc911x_netdev_ops = {
.ndo_open = smsc911x_open,
.ndo_stop = smsc911x_stop,
.ndo_start_xmit = smsc911x_hard_start_xmit,
.ndo_get_stats = smsc911x_get_stats,
.ndo_set_rx_mode = smsc911x_set_multicast_list,
.ndo_do_ioctl = smsc911x_do_ioctl,
.ndo_change_mtu = eth_change_mtu,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = smsc911x_set_mac_address,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = smsc911x_poll_controller,
#endif
};
/* copies the current mac address from hardware to dev->dev_addr */
static void smsc911x_read_mac_address(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
u32 mac_high16 = smsc911x_mac_read(pdata, ADDRH);
u32 mac_low32 = smsc911x_mac_read(pdata, ADDRL);
dev->dev_addr[0] = (u8)(mac_low32);
dev->dev_addr[1] = (u8)(mac_low32 >> 8);
dev->dev_addr[2] = (u8)(mac_low32 >> 16);
dev->dev_addr[3] = (u8)(mac_low32 >> 24);
dev->dev_addr[4] = (u8)(mac_high16);
dev->dev_addr[5] = (u8)(mac_high16 >> 8);
}
/* Initializing private device structures, only called from probe */
static int smsc911x_init(struct net_device *dev)
{
struct smsc911x_data *pdata = netdev_priv(dev);
unsigned int byte_test, mask;
unsigned int to = 100;
SMSC_TRACE(pdata, probe, "Driver Parameters:");
SMSC_TRACE(pdata, probe, "LAN base: 0x%08lX",
(unsigned long)pdata->ioaddr);
SMSC_TRACE(pdata, probe, "IRQ: %d", dev->irq);
SMSC_TRACE(pdata, probe, "PHY will be autodetected.");
spin_lock_init(&pdata->dev_lock);
spin_lock_init(&pdata->mac_lock);
if (pdata->ioaddr == NULL) {
SMSC_WARN(pdata, probe, "pdata->ioaddr: 0x00000000");
return -ENODEV;
}
/*
* poll the READY bit in PMT_CTRL. Any other access to the device is
* forbidden while this bit isn't set. Try for 100ms
*
* Note that this test is done before the WORD_SWAP register is
* programmed. So in some configurations the READY bit is at 16 before
* WORD_SWAP is written to. This issue is worked around by waiting
* until either bit 0 or bit 16 gets set in PMT_CTRL.
*
* SMSC has confirmed that checking bit 16 (marked as reserved in
* the datasheet) is fine since these bits "will either never be set
* or can only go high after READY does (so also indicate the device
* is ready)".
*/
mask = PMT_CTRL_READY_ | swahw32(PMT_CTRL_READY_);
while (!(smsc911x_reg_read(pdata, PMT_CTRL) & mask) && --to)
udelay(1000);
if (to == 0) {
pr_err("Device not READY in 100ms aborting\n");
return -ENODEV;
}
/* Check byte ordering */
byte_test = smsc911x_reg_read(pdata, BYTE_TEST);
SMSC_TRACE(pdata, probe, "BYTE_TEST: 0x%08X", byte_test);
if (byte_test == 0x43218765) {
SMSC_TRACE(pdata, probe, "BYTE_TEST looks swapped, "
"applying WORD_SWAP");
smsc911x_reg_write(pdata, WORD_SWAP, 0xffffffff);
/* 1 dummy read of BYTE_TEST is needed after a write to
* WORD_SWAP before its contents are valid */
byte_test = smsc911x_reg_read(pdata, BYTE_TEST);
byte_test = smsc911x_reg_read(pdata, BYTE_TEST);
}
if (byte_test != 0x87654321) {
SMSC_WARN(pdata, drv, "BYTE_TEST: 0x%08X", byte_test);
if (((byte_test >> 16) & 0xFFFF) == (byte_test & 0xFFFF)) {
SMSC_WARN(pdata, probe,
"top 16 bits equal to bottom 16 bits");
SMSC_TRACE(pdata, probe,
"This may mean the chip is set "
"for 32 bit while the bus is reading 16 bit");
}
return -ENODEV;
}
/* Default generation to zero (all workarounds apply) */
pdata->generation = 0;
pdata->idrev = smsc911x_reg_read(pdata, ID_REV);
switch (pdata->idrev & 0xFFFF0000) {
case 0x01180000:
case 0x01170000:
case 0x01160000:
case 0x01150000:
case 0x218A0000:
/* LAN911[5678] family */
pdata->generation = pdata->idrev & 0x0000FFFF;
break;
case 0x118A0000:
case 0x117A0000:
case 0x116A0000:
case 0x115A0000:
/* LAN921[5678] family */
pdata->generation = 3;
break;
case 0x92100000:
case 0x92110000:
case 0x92200000:
case 0x92210000:
/* LAN9210/LAN9211/LAN9220/LAN9221 */
pdata->generation = 4;
break;
default:
SMSC_WARN(pdata, probe, "LAN911x not identified, idrev: 0x%08X",
pdata->idrev);
return -ENODEV;
}
SMSC_TRACE(pdata, probe,
"LAN911x identified, idrev: 0x%08X, generation: %d",
pdata->idrev, pdata->generation);
if (pdata->generation == 0)
SMSC_WARN(pdata, probe,
"This driver is not intended for this chip revision");
/* workaround for platforms without an eeprom, where the mac address
* is stored elsewhere and set by the bootloader. This saves the
* mac address before resetting the device */
if (pdata->config.flags & SMSC911X_SAVE_MAC_ADDRESS) {
spin_lock_irq(&pdata->mac_lock);
smsc911x_read_mac_address(dev);
spin_unlock_irq(&pdata->mac_lock);
}
/* Reset the LAN911x */
if (smsc911x_soft_reset(pdata))
return -ENODEV;
ether_setup(dev);
dev->flags |= IFF_MULTICAST;
netif_napi_add(dev, &pdata->napi, smsc911x_poll, SMSC_NAPI_WEIGHT);
dev->netdev_ops = &smsc911x_netdev_ops;
dev->ethtool_ops = &smsc911x_ethtool_ops;
return 0;
}
static int smsc911x_drv_remove(struct platform_device *pdev)
{
struct net_device *dev;
struct smsc911x_data *pdata;
struct resource *res;
dev = platform_get_drvdata(pdev);
BUG_ON(!dev);
pdata = netdev_priv(dev);
BUG_ON(!pdata);
BUG_ON(!pdata->ioaddr);
BUG_ON(!pdata->phy_dev);
SMSC_TRACE(pdata, ifdown, "Stopping driver");
if (pdata->config.has_reset_gpio) {
gpio_set_value_cansleep(pdata->config.reset_gpio, 0);
gpio_free(pdata->config.reset_gpio);
}
phy_disconnect(pdata->phy_dev);
pdata->phy_dev = NULL;
mdiobus_unregister(pdata->mii_bus);
mdiobus_free(pdata->mii_bus);
platform_set_drvdata(pdev, NULL);
unregister_netdev(dev);
free_irq(dev->irq, dev);
res = platform_get_resource_byname(pdev, IORESOURCE_MEM,
"smsc911x-memory");
if (!res)
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(res->start, resource_size(res));
iounmap(pdata->ioaddr);
(void)smsc911x_disable_resources(pdev);
smsc911x_free_resources(pdev);
free_netdev(dev);
return 0;
}
/* standard register acces */
static const struct smsc911x_ops standard_smsc911x_ops = {
.reg_read = __smsc911x_reg_read,
.reg_write = __smsc911x_reg_write,
.rx_readfifo = smsc911x_rx_readfifo,
.tx_writefifo = smsc911x_tx_writefifo,
};
/* shifted register access */
static const struct smsc911x_ops shifted_smsc911x_ops = {
.reg_read = __smsc911x_reg_read_shift,
.reg_write = __smsc911x_reg_write_shift,
.rx_readfifo = smsc911x_rx_readfifo_shift,
.tx_writefifo = smsc911x_tx_writefifo_shift,
};
#ifdef CONFIG_OF
static int smsc911x_probe_config_dt(struct smsc911x_platform_config *config,
struct device_node *np)
{
const char *mac;
u32 width = 0;
if (!np)
return -ENODEV;
config->phy_interface = of_get_phy_mode(np);
mac = of_get_mac_address(np);
if (mac)
memcpy(config->mac, mac, ETH_ALEN);
of_property_read_u32(np, "reg-shift", &config->shift);
of_property_read_u32(np, "reg-io-width", &width);
if (width == 4)
config->flags |= SMSC911X_USE_32BIT;
else
config->flags |= SMSC911X_USE_16BIT;
if (of_get_property(np, "smsc,irq-active-high", NULL))
config->irq_polarity = SMSC911X_IRQ_POLARITY_ACTIVE_HIGH;
if (of_get_property(np, "smsc,irq-push-pull", NULL))
config->irq_type = SMSC911X_IRQ_TYPE_PUSH_PULL;
if (of_get_property(np, "smsc,force-internal-phy", NULL))
config->flags |= SMSC911X_FORCE_INTERNAL_PHY;
if (of_get_property(np, "smsc,force-external-phy", NULL))
config->flags |= SMSC911X_FORCE_EXTERNAL_PHY;
if (of_get_property(np, "smsc,save-mac-address", NULL))
config->flags |= SMSC911X_SAVE_MAC_ADDRESS;
return 0;
}
#else
static inline int smsc911x_probe_config_dt(
struct smsc911x_platform_config *config,
struct device_node *np)
{
return -ENODEV;
}
#endif /* CONFIG_OF */
static int smsc911x_drv_probe(struct platform_device *pdev)
{
struct device_node *np = pdev->dev.of_node;
struct net_device *dev;
struct smsc911x_data *pdata;
struct smsc911x_platform_config *config = pdev->dev.platform_data;
struct resource *res, *irq_res;
unsigned int intcfg = 0;
int res_size, irq_flags;
int retval;
pr_info("Driver version %s\n", SMSC_DRV_VERSION);
res = platform_get_resource_byname(pdev, IORESOURCE_MEM,
"smsc911x-memory");
if (!res)
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
pr_warn("Could not allocate resource\n");
retval = -ENODEV;
goto out_0;
}
res_size = resource_size(res);
irq_res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!irq_res) {
pr_warn("Could not allocate irq resource\n");
retval = -ENODEV;
goto out_0;
}
if (!request_mem_region(res->start, res_size, SMSC_CHIPNAME)) {
retval = -EBUSY;
goto out_0;
}
dev = alloc_etherdev(sizeof(struct smsc911x_data));
if (!dev) {
retval = -ENOMEM;
goto out_release_io_1;
}
SET_NETDEV_DEV(dev, &pdev->dev);
pdata = netdev_priv(dev);
dev->irq = irq_res->start;
irq_flags = irq_res->flags & IRQF_TRIGGER_MASK;
pdata->ioaddr = ioremap_nocache(res->start, res_size);
pdata->dev = dev;
pdata->msg_enable = ((1 << debug) - 1);
platform_set_drvdata(pdev, dev);
retval = smsc911x_request_resources(pdev);
if (retval)
goto out_request_resources_fail;
retval = smsc911x_enable_resources(pdev);
if (retval)
goto out_enable_resources_fail;
if (pdata->ioaddr == NULL) {
SMSC_WARN(pdata, probe, "Error smsc911x base address invalid");
retval = -ENOMEM;
goto out_disable_resources;
}
retval = smsc911x_probe_config_dt(&pdata->config, np);
if (retval && config) {
/* copy config parameters across to pdata */
memcpy(&pdata->config, config, sizeof(pdata->config));
retval = 0;
}
if (retval) {
SMSC_WARN(pdata, probe, "Error smsc911x config not found");
goto out_disable_resources;
}
/* assume standard, non-shifted, access to HW registers */
pdata->ops = &standard_smsc911x_ops;
/* apply the right access if shifting is needed */
if (pdata->config.shift)
pdata->ops = &shifted_smsc911x_ops;
retval = smsc911x_init(dev);
if (retval < 0)
goto out_disable_resources;
/* configure irq polarity and type before connecting isr */
if (pdata->config.irq_polarity == SMSC911X_IRQ_POLARITY_ACTIVE_HIGH)
intcfg |= INT_CFG_IRQ_POL_;
if (pdata->config.irq_type == SMSC911X_IRQ_TYPE_PUSH_PULL)
intcfg |= INT_CFG_IRQ_TYPE_;
smsc911x_reg_write(pdata, INT_CFG, intcfg);
/* Ensure interrupts are globally disabled before connecting ISR */
smsc911x_disable_irq_chip(dev);
retval = request_any_context_irq(dev->irq, smsc911x_irqhandler,
irq_flags | IRQF_SHARED, dev->name,
dev);
if (retval < 0) {
SMSC_WARN(pdata, probe,
"Unable to claim requested irq: %d", dev->irq);
goto out_disable_resources;
}
retval = register_netdev(dev);
if (retval) {
SMSC_WARN(pdata, probe, "Error %i registering device", retval);
goto out_free_irq;
} else {
SMSC_TRACE(pdata, probe,
"Network interface: \"%s\"", dev->name);
}
retval = smsc911x_mii_init(pdev, dev);
if (retval) {
SMSC_WARN(pdata, probe, "Error %i initialising mii", retval);
goto out_unregister_netdev_5;
}
spin_lock_irq(&pdata->mac_lock);
/* Check if mac address has been specified when bringing interface up */
if (is_valid_ether_addr(dev->dev_addr)) {
smsc911x_set_hw_mac_address(pdata, dev->dev_addr);
SMSC_TRACE(pdata, probe,
"MAC Address is specified by configuration");
} else if (is_valid_ether_addr(pdata->config.mac)) {
memcpy(dev->dev_addr, pdata->config.mac, 6);
SMSC_TRACE(pdata, probe,
"MAC Address specified by platform data");
} else {
/* Try reading mac address from device. if EEPROM is present
* it will already have been set */
smsc_get_mac(dev);
if (is_valid_ether_addr(dev->dev_addr)) {
/* eeprom values are valid so use them */
SMSC_TRACE(pdata, probe,
"Mac Address is read from LAN911x EEPROM");
} else {
/* eeprom values are invalid, generate random MAC */
eth_hw_addr_random(dev);
smsc911x_set_hw_mac_address(pdata, dev->dev_addr);
SMSC_TRACE(pdata, probe,
"MAC Address is set to eth_random_addr");
}
}
spin_unlock_irq(&pdata->mac_lock);
netdev_info(dev, "MAC Address: %pM\n", dev->dev_addr);
return 0;
out_unregister_netdev_5:
unregister_netdev(dev);
out_free_irq:
free_irq(dev->irq, dev);
out_disable_resources:
(void)smsc911x_disable_resources(pdev);
out_enable_resources_fail:
smsc911x_free_resources(pdev);
out_request_resources_fail:
platform_set_drvdata(pdev, NULL);
iounmap(pdata->ioaddr);
free_netdev(dev);
out_release_io_1:
release_mem_region(res->start, resource_size(res));
out_0:
return retval;
}
#ifdef CONFIG_PM
/* This implementation assumes the devices remains powered on its VDDVARIO
* pins during suspend. */
/* TODO: implement freeze/thaw callbacks for hibernation.*/
static int smsc911x_suspend(struct device *dev)
{
struct net_device *ndev = dev_get_drvdata(dev);
struct smsc911x_data *pdata = netdev_priv(ndev);
/* enable wake on LAN, energy detection and the external PME
* signal. */
smsc911x_reg_write(pdata, PMT_CTRL,
PMT_CTRL_PM_MODE_D1_ | PMT_CTRL_WOL_EN_ |
PMT_CTRL_ED_EN_ | PMT_CTRL_PME_EN_);
/* Drive the GPIO Ethernet_Reset Line low to Suspend */
if (pdata->config.has_reset_gpio)
gpio_set_value_cansleep(pdata->config.reset_gpio, 0);
return 0;
}
static int smsc911x_resume(struct device *dev)
{
struct net_device *ndev = dev_get_drvdata(dev);
struct smsc911x_data *pdata = netdev_priv(ndev);
unsigned int to = 100;
if (pdata->config.has_reset_gpio)
gpio_set_value_cansleep(pdata->config.reset_gpio, 1);
/* Note 3.11 from the datasheet:
* "When the LAN9220 is in a power saving state, a write of any
* data to the BYTE_TEST register will wake-up the device."
*/
smsc911x_reg_write(pdata, BYTE_TEST, 0);
/* poll the READY bit in PMT_CTRL. Any other access to the device is
* forbidden while this bit isn't set. Try for 100ms and return -EIO
* if it failed. */
while (!(smsc911x_reg_read(pdata, PMT_CTRL) & PMT_CTRL_READY_) && --to)
udelay(1000);
return (to == 0) ? -EIO : 0;
}
static const struct dev_pm_ops smsc911x_pm_ops = {
.suspend = smsc911x_suspend,
.resume = smsc911x_resume,
};
#define SMSC911X_PM_OPS (&smsc911x_pm_ops)
#else
#define SMSC911X_PM_OPS NULL
#endif
#ifdef CONFIG_OF
static const struct of_device_id smsc911x_dt_ids[] = {
{ .compatible = "smsc,lan9115", },
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, smsc911x_dt_ids);
#endif
static struct platform_driver smsc911x_driver = {
.probe = smsc911x_drv_probe,
.remove = smsc911x_drv_remove,
.driver = {
.name = SMSC_CHIPNAME,
.owner = THIS_MODULE,
.pm = SMSC911X_PM_OPS,
.of_match_table = of_match_ptr(smsc911x_dt_ids),
},
};
/* Entry point for loading the module */
static int __init smsc911x_init_module(void)
{
SMSC_INITIALIZE();
return platform_driver_register(&smsc911x_driver);
}
/* entry point for unloading the module */
static void __exit smsc911x_cleanup_module(void)
{
platform_driver_unregister(&smsc911x_driver);
}
module_init(smsc911x_init_module);
module_exit(smsc911x_cleanup_module);
| gpl-2.0 |
loveboylion/android_kernel_yu_msm8916 | drivers/media/rc/ir-nec-decoder.c | 1159 | 5936 | /* ir-nec-decoder.c - handle NEC IR Pulse/Space protocol
*
* Copyright (C) 2010 by Mauro Carvalho Chehab <mchehab@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 version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/bitrev.h>
#include <linux/module.h>
#include "rc-core-priv.h"
#define NEC_NBITS 32
#define NEC_UNIT 562500 /* ns */
#define NEC_HEADER_PULSE (16 * NEC_UNIT)
#define NECX_HEADER_PULSE (8 * NEC_UNIT) /* Less common NEC variant */
#define NEC_HEADER_SPACE (8 * NEC_UNIT)
#define NEC_REPEAT_SPACE (4 * NEC_UNIT)
#define NEC_BIT_PULSE (1 * NEC_UNIT)
#define NEC_BIT_0_SPACE (1 * NEC_UNIT)
#define NEC_BIT_1_SPACE (3 * NEC_UNIT)
#define NEC_TRAILER_PULSE (1 * NEC_UNIT)
#define NEC_TRAILER_SPACE (10 * NEC_UNIT) /* even longer in reality */
#define NECX_REPEAT_BITS 1
enum nec_state {
STATE_INACTIVE,
STATE_HEADER_SPACE,
STATE_BIT_PULSE,
STATE_BIT_SPACE,
STATE_TRAILER_PULSE,
STATE_TRAILER_SPACE,
};
/**
* ir_nec_decode() - Decode one NEC pulse or space
* @dev: the struct rc_dev descriptor of the device
* @duration: the struct ir_raw_event descriptor of the pulse/space
*
* This function returns -EINVAL if the pulse violates the state machine
*/
static int ir_nec_decode(struct rc_dev *dev, struct ir_raw_event ev)
{
struct nec_dec *data = &dev->raw->nec;
u32 scancode;
u8 address, not_address, command, not_command;
bool send_32bits = false;
if (!(dev->enabled_protocols & RC_BIT_NEC))
return 0;
if (!is_timing_event(ev)) {
if (ev.reset)
data->state = STATE_INACTIVE;
return 0;
}
IR_dprintk(2, "NEC decode started at state %d (%uus %s)\n",
data->state, TO_US(ev.duration), TO_STR(ev.pulse));
switch (data->state) {
case STATE_INACTIVE:
if (!ev.pulse)
break;
if (eq_margin(ev.duration, NEC_HEADER_PULSE, NEC_UNIT * 2)) {
data->is_nec_x = false;
data->necx_repeat = false;
} else if (eq_margin(ev.duration, NECX_HEADER_PULSE, NEC_UNIT / 2))
data->is_nec_x = true;
else
break;
data->count = 0;
data->state = STATE_HEADER_SPACE;
return 0;
case STATE_HEADER_SPACE:
if (ev.pulse)
break;
if (eq_margin(ev.duration, NEC_HEADER_SPACE, NEC_UNIT)) {
data->state = STATE_BIT_PULSE;
return 0;
} else if (eq_margin(ev.duration, NEC_REPEAT_SPACE, NEC_UNIT / 2)) {
if (!dev->keypressed) {
IR_dprintk(1, "Discarding last key repeat: event after key up\n");
} else {
rc_repeat(dev);
IR_dprintk(1, "Repeat last key\n");
data->state = STATE_TRAILER_PULSE;
}
return 0;
}
break;
case STATE_BIT_PULSE:
if (!ev.pulse)
break;
if (!eq_margin(ev.duration, NEC_BIT_PULSE, NEC_UNIT / 2))
break;
data->state = STATE_BIT_SPACE;
return 0;
case STATE_BIT_SPACE:
if (ev.pulse)
break;
if (data->necx_repeat && data->count == NECX_REPEAT_BITS &&
geq_margin(ev.duration,
NEC_TRAILER_SPACE, NEC_UNIT / 2)) {
IR_dprintk(1, "Repeat last key\n");
rc_repeat(dev);
data->state = STATE_INACTIVE;
return 0;
} else if (data->count > NECX_REPEAT_BITS)
data->necx_repeat = false;
data->bits <<= 1;
if (eq_margin(ev.duration, NEC_BIT_1_SPACE, NEC_UNIT / 2))
data->bits |= 1;
else if (!eq_margin(ev.duration, NEC_BIT_0_SPACE, NEC_UNIT / 2))
break;
data->count++;
if (data->count == NEC_NBITS)
data->state = STATE_TRAILER_PULSE;
else
data->state = STATE_BIT_PULSE;
return 0;
case STATE_TRAILER_PULSE:
if (!ev.pulse)
break;
if (!eq_margin(ev.duration, NEC_TRAILER_PULSE, NEC_UNIT / 2))
break;
data->state = STATE_TRAILER_SPACE;
if (data->is_nec_x)
goto rc_data;
return 0;
case STATE_TRAILER_SPACE:
if (ev.pulse)
break;
if (!geq_margin(ev.duration, NEC_TRAILER_SPACE, NEC_UNIT / 2))
break;
rc_data:
address = bitrev8((data->bits >> 24) & 0xff);
not_address = bitrev8((data->bits >> 16) & 0xff);
command = bitrev8((data->bits >> 8) & 0xff);
not_command = bitrev8((data->bits >> 0) & 0xff);
if ((command ^ not_command) != 0xff) {
IR_dprintk(1, "NEC checksum error: received 0x%08x\n",
data->bits);
send_32bits = true;
}
if (send_32bits) {
/* NEC transport, but modified protocol, used by at
* least Apple and TiVo remotes */
scancode = data->bits;
IR_dprintk(1, "NEC (modified) scancode 0x%08x\n", scancode);
} else if ((address ^ not_address) != 0xff) {
/* Extended NEC */
scancode = address << 16 |
not_address << 8 |
command;
IR_dprintk(1, "NEC (Ext) scancode 0x%06x\n", scancode);
} else {
/* Normal NEC */
scancode = address << 8 | command;
IR_dprintk(1, "NEC scancode 0x%04x\n", scancode);
}
if (data->is_nec_x)
data->necx_repeat = true;
rc_keydown(dev, scancode, 0);
data->state = STATE_INACTIVE;
return 0;
}
IR_dprintk(1, "NEC decode failed at count %d state %d (%uus %s)\n",
data->count, data->state, TO_US(ev.duration), TO_STR(ev.pulse));
data->state = STATE_INACTIVE;
return -EINVAL;
}
static struct ir_raw_handler nec_handler = {
.protocols = RC_BIT_NEC,
.decode = ir_nec_decode,
};
static int __init ir_nec_decode_init(void)
{
ir_raw_handler_register(&nec_handler);
printk(KERN_INFO "IR NEC protocol handler initialized\n");
return 0;
}
static void __exit ir_nec_decode_exit(void)
{
ir_raw_handler_unregister(&nec_handler);
}
module_init(ir_nec_decode_init);
module_exit(ir_nec_decode_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
MODULE_AUTHOR("Red Hat Inc. (http://www.redhat.com)");
MODULE_DESCRIPTION("NEC IR protocol decoder");
| gpl-2.0 |
smipi1/bbb_kernel | drivers/mtd/chips/cfi_probe.c | 1927 | 11899 | /*
Common Flash Interface probe code.
(C) 2000 Red Hat. GPL'd.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <asm/io.h>
#include <asm/byteorder.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/mtd/xip.h>
#include <linux/mtd/map.h>
#include <linux/mtd/cfi.h>
#include <linux/mtd/gen_probe.h>
//#define DEBUG_CFI
#ifdef DEBUG_CFI
static void print_cfi_ident(struct cfi_ident *);
#endif
static int cfi_probe_chip(struct map_info *map, __u32 base,
unsigned long *chip_map, struct cfi_private *cfi);
static int cfi_chip_setup(struct map_info *map, struct cfi_private *cfi);
struct mtd_info *cfi_probe(struct map_info *map);
#ifdef CONFIG_MTD_XIP
/* only needed for short periods, so this is rather simple */
#define xip_disable() local_irq_disable()
#define xip_allowed(base, map) \
do { \
(void) map_read(map, base); \
xip_iprefetch(); \
local_irq_enable(); \
} while (0)
#define xip_enable(base, map, cfi) \
do { \
cfi_qry_mode_off(base, map, cfi); \
xip_allowed(base, map); \
} while (0)
#define xip_disable_qry(base, map, cfi) \
do { \
xip_disable(); \
cfi_qry_mode_on(base, map, cfi); \
} while (0)
#else
#define xip_disable() do { } while (0)
#define xip_allowed(base, map) do { } while (0)
#define xip_enable(base, map, cfi) do { } while (0)
#define xip_disable_qry(base, map, cfi) do { } while (0)
#endif
/* check for QRY.
in: interleave,type,mode
ret: table index, <0 for error
*/
static int __xipram cfi_probe_chip(struct map_info *map, __u32 base,
unsigned long *chip_map, struct cfi_private *cfi)
{
int i;
if ((base + 0) >= map->size) {
printk(KERN_NOTICE
"Probe at base[0x00](0x%08lx) past the end of the map(0x%08lx)\n",
(unsigned long)base, map->size -1);
return 0;
}
if ((base + 0xff) >= map->size) {
printk(KERN_NOTICE
"Probe at base[0x55](0x%08lx) past the end of the map(0x%08lx)\n",
(unsigned long)base + 0x55, map->size -1);
return 0;
}
xip_disable();
if (!cfi_qry_mode_on(base, map, cfi)) {
xip_enable(base, map, cfi);
return 0;
}
if (!cfi->numchips) {
/* This is the first time we're called. Set up the CFI
stuff accordingly and return */
return cfi_chip_setup(map, cfi);
}
/* Check each previous chip to see if it's an alias */
for (i=0; i < (base >> cfi->chipshift); i++) {
unsigned long start;
if(!test_bit(i, chip_map)) {
/* Skip location; no valid chip at this address */
continue;
}
start = i << cfi->chipshift;
/* This chip should be in read mode if it's one
we've already touched. */
if (cfi_qry_present(map, start, cfi)) {
/* Eep. This chip also had the QRY marker.
* Is it an alias for the new one? */
cfi_qry_mode_off(start, map, cfi);
/* If the QRY marker goes away, it's an alias */
if (!cfi_qry_present(map, start, cfi)) {
xip_allowed(base, map);
printk(KERN_DEBUG "%s: Found an alias at 0x%x for the chip at 0x%lx\n",
map->name, base, start);
return 0;
}
/* Yes, it's actually got QRY for data. Most
* unfortunate. Stick the new chip in read mode
* too and if it's the same, assume it's an alias. */
/* FIXME: Use other modes to do a proper check */
cfi_qry_mode_off(base, map, cfi);
if (cfi_qry_present(map, base, cfi)) {
xip_allowed(base, map);
printk(KERN_DEBUG "%s: Found an alias at 0x%x for the chip at 0x%lx\n",
map->name, base, start);
return 0;
}
}
}
/* OK, if we got to here, then none of the previous chips appear to
be aliases for the current one. */
set_bit((base >> cfi->chipshift), chip_map); /* Update chip map */
cfi->numchips++;
/* Put it back into Read Mode */
cfi_qry_mode_off(base, map, cfi);
xip_allowed(base, map);
printk(KERN_INFO "%s: Found %d x%d devices at 0x%x in %d-bit bank\n",
map->name, cfi->interleave, cfi->device_type*8, base,
map->bankwidth*8);
return 1;
}
static int __xipram cfi_chip_setup(struct map_info *map,
struct cfi_private *cfi)
{
int ofs_factor = cfi->interleave*cfi->device_type;
__u32 base = 0;
int num_erase_regions = cfi_read_query(map, base + (0x10 + 28)*ofs_factor);
int i;
int addr_unlock1 = 0x555, addr_unlock2 = 0x2AA;
xip_enable(base, map, cfi);
#ifdef DEBUG_CFI
printk("Number of erase regions: %d\n", num_erase_regions);
#endif
if (!num_erase_regions)
return 0;
cfi->cfiq = kmalloc(sizeof(struct cfi_ident) + num_erase_regions * 4, GFP_KERNEL);
if (!cfi->cfiq)
return 0;
memset(cfi->cfiq,0,sizeof(struct cfi_ident));
cfi->cfi_mode = CFI_MODE_CFI;
cfi->sector_erase_cmd = CMD(0x30);
/* Read the CFI info structure */
xip_disable_qry(base, map, cfi);
for (i=0; i<(sizeof(struct cfi_ident) + num_erase_regions * 4); i++)
((unsigned char *)cfi->cfiq)[i] = cfi_read_query(map,base + (0x10 + i)*ofs_factor);
/* Do any necessary byteswapping */
cfi->cfiq->P_ID = le16_to_cpu(cfi->cfiq->P_ID);
cfi->cfiq->P_ADR = le16_to_cpu(cfi->cfiq->P_ADR);
cfi->cfiq->A_ID = le16_to_cpu(cfi->cfiq->A_ID);
cfi->cfiq->A_ADR = le16_to_cpu(cfi->cfiq->A_ADR);
cfi->cfiq->InterfaceDesc = le16_to_cpu(cfi->cfiq->InterfaceDesc);
cfi->cfiq->MaxBufWriteSize = le16_to_cpu(cfi->cfiq->MaxBufWriteSize);
#ifdef DEBUG_CFI
/* Dump the information therein */
print_cfi_ident(cfi->cfiq);
#endif
for (i=0; i<cfi->cfiq->NumEraseRegions; i++) {
cfi->cfiq->EraseRegionInfo[i] = le32_to_cpu(cfi->cfiq->EraseRegionInfo[i]);
#ifdef DEBUG_CFI
printk(" Erase Region #%d: BlockSize 0x%4.4X bytes, %d blocks\n",
i, (cfi->cfiq->EraseRegionInfo[i] >> 8) & ~0xff,
(cfi->cfiq->EraseRegionInfo[i] & 0xffff) + 1);
#endif
}
if (cfi->cfiq->P_ID == P_ID_SST_OLD) {
addr_unlock1 = 0x5555;
addr_unlock2 = 0x2AAA;
}
/*
* Note we put the device back into Read Mode BEFORE going into Auto
* Select Mode, as some devices support nesting of modes, others
* don't. This way should always work.
* On cmdset 0001 the writes of 0xaa and 0x55 are not needed, and
* so should be treated as nops or illegal (and so put the device
* back into Read Mode, which is a nop in this case).
*/
cfi_send_gen_cmd(0xf0, 0, base, map, cfi, cfi->device_type, NULL);
cfi_send_gen_cmd(0xaa, addr_unlock1, base, map, cfi, cfi->device_type, NULL);
cfi_send_gen_cmd(0x55, addr_unlock2, base, map, cfi, cfi->device_type, NULL);
cfi_send_gen_cmd(0x90, addr_unlock1, base, map, cfi, cfi->device_type, NULL);
cfi->mfr = cfi_read_query16(map, base);
cfi->id = cfi_read_query16(map, base + ofs_factor);
/* Get AMD/Spansion extended JEDEC ID */
if (cfi->mfr == CFI_MFR_AMD && (cfi->id & 0xff) == 0x7e)
cfi->id = cfi_read_query(map, base + 0xe * ofs_factor) << 8 |
cfi_read_query(map, base + 0xf * ofs_factor);
/* Put it back into Read Mode */
cfi_qry_mode_off(base, map, cfi);
xip_allowed(base, map);
printk(KERN_INFO "%s: Found %d x%d devices at 0x%x in %d-bit bank. Manufacturer ID %#08x Chip ID %#08x\n",
map->name, cfi->interleave, cfi->device_type*8, base,
map->bankwidth*8, cfi->mfr, cfi->id);
return 1;
}
#ifdef DEBUG_CFI
static char *vendorname(__u16 vendor)
{
switch (vendor) {
case P_ID_NONE:
return "None";
case P_ID_INTEL_EXT:
return "Intel/Sharp Extended";
case P_ID_AMD_STD:
return "AMD/Fujitsu Standard";
case P_ID_INTEL_STD:
return "Intel/Sharp Standard";
case P_ID_AMD_EXT:
return "AMD/Fujitsu Extended";
case P_ID_WINBOND:
return "Winbond Standard";
case P_ID_ST_ADV:
return "ST Advanced";
case P_ID_MITSUBISHI_STD:
return "Mitsubishi Standard";
case P_ID_MITSUBISHI_EXT:
return "Mitsubishi Extended";
case P_ID_SST_PAGE:
return "SST Page Write";
case P_ID_SST_OLD:
return "SST 39VF160x/39VF320x";
case P_ID_INTEL_PERFORMANCE:
return "Intel Performance Code";
case P_ID_INTEL_DATA:
return "Intel Data";
case P_ID_RESERVED:
return "Not Allowed / Reserved for Future Use";
default:
return "Unknown";
}
}
static void print_cfi_ident(struct cfi_ident *cfip)
{
#if 0
if (cfip->qry[0] != 'Q' || cfip->qry[1] != 'R' || cfip->qry[2] != 'Y') {
printk("Invalid CFI ident structure.\n");
return;
}
#endif
printk("Primary Vendor Command Set: %4.4X (%s)\n", cfip->P_ID, vendorname(cfip->P_ID));
if (cfip->P_ADR)
printk("Primary Algorithm Table at %4.4X\n", cfip->P_ADR);
else
printk("No Primary Algorithm Table\n");
printk("Alternative Vendor Command Set: %4.4X (%s)\n", cfip->A_ID, vendorname(cfip->A_ID));
if (cfip->A_ADR)
printk("Alternate Algorithm Table at %4.4X\n", cfip->A_ADR);
else
printk("No Alternate Algorithm Table\n");
printk("Vcc Minimum: %2d.%d V\n", cfip->VccMin >> 4, cfip->VccMin & 0xf);
printk("Vcc Maximum: %2d.%d V\n", cfip->VccMax >> 4, cfip->VccMax & 0xf);
if (cfip->VppMin) {
printk("Vpp Minimum: %2d.%d V\n", cfip->VppMin >> 4, cfip->VppMin & 0xf);
printk("Vpp Maximum: %2d.%d V\n", cfip->VppMax >> 4, cfip->VppMax & 0xf);
}
else
printk("No Vpp line\n");
printk("Typical byte/word write timeout: %d µs\n", 1<<cfip->WordWriteTimeoutTyp);
printk("Maximum byte/word write timeout: %d µs\n", (1<<cfip->WordWriteTimeoutMax) * (1<<cfip->WordWriteTimeoutTyp));
if (cfip->BufWriteTimeoutTyp || cfip->BufWriteTimeoutMax) {
printk("Typical full buffer write timeout: %d µs\n", 1<<cfip->BufWriteTimeoutTyp);
printk("Maximum full buffer write timeout: %d µs\n", (1<<cfip->BufWriteTimeoutMax) * (1<<cfip->BufWriteTimeoutTyp));
}
else
printk("Full buffer write not supported\n");
printk("Typical block erase timeout: %d ms\n", 1<<cfip->BlockEraseTimeoutTyp);
printk("Maximum block erase timeout: %d ms\n", (1<<cfip->BlockEraseTimeoutMax) * (1<<cfip->BlockEraseTimeoutTyp));
if (cfip->ChipEraseTimeoutTyp || cfip->ChipEraseTimeoutMax) {
printk("Typical chip erase timeout: %d ms\n", 1<<cfip->ChipEraseTimeoutTyp);
printk("Maximum chip erase timeout: %d ms\n", (1<<cfip->ChipEraseTimeoutMax) * (1<<cfip->ChipEraseTimeoutTyp));
}
else
printk("Chip erase not supported\n");
printk("Device size: 0x%X bytes (%d MiB)\n", 1 << cfip->DevSize, 1<< (cfip->DevSize - 20));
printk("Flash Device Interface description: 0x%4.4X\n", cfip->InterfaceDesc);
switch(cfip->InterfaceDesc) {
case CFI_INTERFACE_X8_ASYNC:
printk(" - x8-only asynchronous interface\n");
break;
case CFI_INTERFACE_X16_ASYNC:
printk(" - x16-only asynchronous interface\n");
break;
case CFI_INTERFACE_X8_BY_X16_ASYNC:
printk(" - supports x8 and x16 via BYTE# with asynchronous interface\n");
break;
case CFI_INTERFACE_X32_ASYNC:
printk(" - x32-only asynchronous interface\n");
break;
case CFI_INTERFACE_X16_BY_X32_ASYNC:
printk(" - supports x16 and x32 via Word# with asynchronous interface\n");
break;
case CFI_INTERFACE_NOT_ALLOWED:
printk(" - Not Allowed / Reserved\n");
break;
default:
printk(" - Unknown\n");
break;
}
printk("Max. bytes in buffer write: 0x%x\n", 1<< cfip->MaxBufWriteSize);
printk("Number of Erase Block Regions: %d\n", cfip->NumEraseRegions);
}
#endif /* DEBUG_CFI */
static struct chip_probe cfi_chip_probe = {
.name = "CFI",
.probe_chip = cfi_probe_chip
};
struct mtd_info *cfi_probe(struct map_info *map)
{
/*
* Just use the generic probe stuff to call our CFI-specific
* chip_probe routine in all the possible permutations, etc.
*/
return mtd_do_chip_probe(map, &cfi_chip_probe);
}
static struct mtd_chip_driver cfi_chipdrv = {
.probe = cfi_probe,
.name = "cfi_probe",
.module = THIS_MODULE
};
static int __init cfi_probe_init(void)
{
register_mtd_chip_driver(&cfi_chipdrv);
return 0;
}
static void __exit cfi_probe_exit(void)
{
unregister_mtd_chip_driver(&cfi_chipdrv);
}
module_init(cfi_probe_init);
module_exit(cfi_probe_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("David Woodhouse <dwmw2@infradead.org> et al.");
MODULE_DESCRIPTION("Probe code for CFI-compliant flash chips");
| gpl-2.0 |
shirishpargaonkar/cifsclient | arch/sh/kernel/cpu/sh4a/smp-shx3.c | 2183 | 4000 | /*
* SH-X3 SMP
*
* Copyright (C) 2007 - 2010 Paul Mundt
* Copyright (C) 2007 Magnus Damm
*
* 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/kernel.h>
#include <linux/cpumask.h>
#include <linux/smp.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/sched.h>
#include <linux/delay.h>
#include <linux/cpu.h>
#include <asm/sections.h>
#define STBCR_REG(phys_id) (0xfe400004 | (phys_id << 12))
#define RESET_REG(phys_id) (0xfe400008 | (phys_id << 12))
#define STBCR_MSTP 0x00000001
#define STBCR_RESET 0x00000002
#define STBCR_SLEEP 0x00000004
#define STBCR_LTSLP 0x80000000
static irqreturn_t ipi_interrupt_handler(int irq, void *arg)
{
unsigned int message = (unsigned int)(long)arg;
unsigned int cpu = hard_smp_processor_id();
unsigned int offs = 4 * cpu;
unsigned int x;
x = __raw_readl(0xfe410070 + offs); /* C0INITICI..CnINTICI */
x &= (1 << (message << 2));
__raw_writel(x, 0xfe410080 + offs); /* C0INTICICLR..CnINTICICLR */
smp_message_recv(message);
return IRQ_HANDLED;
}
static void shx3_smp_setup(void)
{
unsigned int cpu = 0;
int i, num;
init_cpu_possible(cpumask_of(cpu));
/* Enable light sleep for the boot CPU */
__raw_writel(__raw_readl(STBCR_REG(cpu)) | STBCR_LTSLP, STBCR_REG(cpu));
__cpu_number_map[0] = 0;
__cpu_logical_map[0] = 0;
/*
* Do this stupidly for now.. we don't have an easy way to probe
* for the total number of cores.
*/
for (i = 1, num = 0; i < NR_CPUS; i++) {
set_cpu_possible(i, true);
__cpu_number_map[i] = ++num;
__cpu_logical_map[num] = i;
}
printk(KERN_INFO "Detected %i available secondary CPU(s)\n", num);
}
static void shx3_prepare_cpus(unsigned int max_cpus)
{
int i;
local_timer_setup(0);
BUILD_BUG_ON(SMP_MSG_NR >= 8);
for (i = 0; i < SMP_MSG_NR; i++)
request_irq(104 + i, ipi_interrupt_handler,
IRQF_PERCPU, "IPI", (void *)(long)i);
for (i = 0; i < max_cpus; i++)
set_cpu_present(i, true);
}
static void shx3_start_cpu(unsigned int cpu, unsigned long entry_point)
{
if (__in_29bit_mode())
__raw_writel(entry_point, RESET_REG(cpu));
else
__raw_writel(virt_to_phys(entry_point), RESET_REG(cpu));
if (!(__raw_readl(STBCR_REG(cpu)) & STBCR_MSTP))
__raw_writel(STBCR_MSTP, STBCR_REG(cpu));
while (!(__raw_readl(STBCR_REG(cpu)) & STBCR_MSTP))
cpu_relax();
/* Start up secondary processor by sending a reset */
__raw_writel(STBCR_RESET | STBCR_LTSLP, STBCR_REG(cpu));
}
static unsigned int shx3_smp_processor_id(void)
{
return __raw_readl(0xff000048); /* CPIDR */
}
static void shx3_send_ipi(unsigned int cpu, unsigned int message)
{
unsigned long addr = 0xfe410070 + (cpu * 4);
BUG_ON(cpu >= 4);
__raw_writel(1 << (message << 2), addr); /* C0INTICI..CnINTICI */
}
static void shx3_update_boot_vector(unsigned int cpu)
{
__raw_writel(STBCR_MSTP, STBCR_REG(cpu));
while (!(__raw_readl(STBCR_REG(cpu)) & STBCR_MSTP))
cpu_relax();
__raw_writel(STBCR_RESET, STBCR_REG(cpu));
}
static int
shx3_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu)
{
unsigned int cpu = (unsigned int)hcpu;
switch (action) {
case CPU_UP_PREPARE:
shx3_update_boot_vector(cpu);
break;
case CPU_ONLINE:
pr_info("CPU %u is now online\n", cpu);
break;
case CPU_DEAD:
break;
}
return NOTIFY_OK;
}
static struct notifier_block shx3_cpu_notifier = {
.notifier_call = shx3_cpu_callback,
};
static int register_shx3_cpu_notifier(void)
{
register_hotcpu_notifier(&shx3_cpu_notifier);
return 0;
}
late_initcall(register_shx3_cpu_notifier);
struct plat_smp_ops shx3_smp_ops = {
.smp_setup = shx3_smp_setup,
.prepare_cpus = shx3_prepare_cpus,
.start_cpu = shx3_start_cpu,
.smp_processor_id = shx3_smp_processor_id,
.send_ipi = shx3_send_ipi,
.cpu_die = native_cpu_die,
.cpu_disable = native_cpu_disable,
.play_dead = native_play_dead,
};
| gpl-2.0 |
NukeAOSP/android_kernel_samsung_tuna | arch/powerpc/kernel/setup-common.c | 2183 | 17585 | /*
* Common boot and setup code for both 32-bit and 64-bit.
* Extracted from arch/powerpc/kernel/setup_64.c.
*
* Copyright (C) 2001 PPC64 Team, 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.
*/
#undef DEBUG
#include <linux/module.h>
#include <linux/string.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/reboot.h>
#include <linux/delay.h>
#include <linux/initrd.h>
#include <linux/platform_device.h>
#include <linux/seq_file.h>
#include <linux/ioport.h>
#include <linux/console.h>
#include <linux/screen_info.h>
#include <linux/root_dev.h>
#include <linux/notifier.h>
#include <linux/cpu.h>
#include <linux/unistd.h>
#include <linux/serial.h>
#include <linux/serial_8250.h>
#include <linux/debugfs.h>
#include <linux/percpu.h>
#include <linux/memblock.h>
#include <linux/of_platform.h>
#include <asm/io.h>
#include <asm/paca.h>
#include <asm/prom.h>
#include <asm/processor.h>
#include <asm/vdso_datapage.h>
#include <asm/pgtable.h>
#include <asm/smp.h>
#include <asm/elf.h>
#include <asm/machdep.h>
#include <asm/time.h>
#include <asm/cputable.h>
#include <asm/sections.h>
#include <asm/firmware.h>
#include <asm/btext.h>
#include <asm/nvram.h>
#include <asm/setup.h>
#include <asm/system.h>
#include <asm/rtas.h>
#include <asm/iommu.h>
#include <asm/serial.h>
#include <asm/cache.h>
#include <asm/page.h>
#include <asm/mmu.h>
#include <asm/xmon.h>
#include <asm/cputhreads.h>
#include <mm/mmu_decl.h>
#include "setup.h"
#ifdef DEBUG
#include <asm/udbg.h>
#define DBG(fmt...) udbg_printf(fmt)
#else
#define DBG(fmt...)
#endif
/* The main machine-dep calls structure
*/
struct machdep_calls ppc_md;
EXPORT_SYMBOL(ppc_md);
struct machdep_calls *machine_id;
EXPORT_SYMBOL(machine_id);
unsigned long klimit = (unsigned long) _end;
char cmd_line[COMMAND_LINE_SIZE];
/*
* This still seems to be needed... -- paulus
*/
struct screen_info screen_info = {
.orig_x = 0,
.orig_y = 25,
.orig_video_cols = 80,
.orig_video_lines = 25,
.orig_video_isVGA = 1,
.orig_video_points = 16
};
/* Variables required to store legacy IO irq routing */
int of_i8042_kbd_irq;
EXPORT_SYMBOL_GPL(of_i8042_kbd_irq);
int of_i8042_aux_irq;
EXPORT_SYMBOL_GPL(of_i8042_aux_irq);
#ifdef __DO_IRQ_CANON
/* XXX should go elsewhere eventually */
int ppc_do_canonicalize_irqs;
EXPORT_SYMBOL(ppc_do_canonicalize_irqs);
#endif
/* also used by kexec */
void machine_shutdown(void)
{
if (ppc_md.machine_shutdown)
ppc_md.machine_shutdown();
}
void machine_restart(char *cmd)
{
machine_shutdown();
if (ppc_md.restart)
ppc_md.restart(cmd);
#ifdef CONFIG_SMP
smp_send_stop();
#endif
printk(KERN_EMERG "System Halted, OK to turn off power\n");
local_irq_disable();
while (1) ;
}
void machine_power_off(void)
{
machine_shutdown();
if (ppc_md.power_off)
ppc_md.power_off();
#ifdef CONFIG_SMP
smp_send_stop();
#endif
printk(KERN_EMERG "System Halted, OK to turn off power\n");
local_irq_disable();
while (1) ;
}
/* Used by the G5 thermal driver */
EXPORT_SYMBOL_GPL(machine_power_off);
void (*pm_power_off)(void) = machine_power_off;
EXPORT_SYMBOL_GPL(pm_power_off);
void machine_halt(void)
{
machine_shutdown();
if (ppc_md.halt)
ppc_md.halt();
#ifdef CONFIG_SMP
smp_send_stop();
#endif
printk(KERN_EMERG "System Halted, OK to turn off power\n");
local_irq_disable();
while (1) ;
}
#ifdef CONFIG_TAU
extern u32 cpu_temp(unsigned long cpu);
extern u32 cpu_temp_both(unsigned long cpu);
#endif /* CONFIG_TAU */
#ifdef CONFIG_SMP
DEFINE_PER_CPU(unsigned int, cpu_pvr);
#endif
static void show_cpuinfo_summary(struct seq_file *m)
{
struct device_node *root;
const char *model = NULL;
#if defined(CONFIG_SMP) && defined(CONFIG_PPC32)
unsigned long bogosum = 0;
int i;
for_each_online_cpu(i)
bogosum += loops_per_jiffy;
seq_printf(m, "total bogomips\t: %lu.%02lu\n",
bogosum/(500000/HZ), bogosum/(5000/HZ) % 100);
#endif /* CONFIG_SMP && CONFIG_PPC32 */
seq_printf(m, "timebase\t: %lu\n", ppc_tb_freq);
if (ppc_md.name)
seq_printf(m, "platform\t: %s\n", ppc_md.name);
root = of_find_node_by_path("/");
if (root)
model = of_get_property(root, "model", NULL);
if (model)
seq_printf(m, "model\t\t: %s\n", model);
of_node_put(root);
if (ppc_md.show_cpuinfo != NULL)
ppc_md.show_cpuinfo(m);
#ifdef CONFIG_PPC32
/* Display the amount of memory */
seq_printf(m, "Memory\t\t: %d MB\n",
(unsigned int)(total_memory / (1024 * 1024)));
#endif
}
static int show_cpuinfo(struct seq_file *m, void *v)
{
unsigned long cpu_id = (unsigned long)v - 1;
unsigned int pvr;
unsigned short maj;
unsigned short min;
/* We only show online cpus: disable preempt (overzealous, I
* knew) to prevent cpu going down. */
preempt_disable();
if (!cpu_online(cpu_id)) {
preempt_enable();
return 0;
}
#ifdef CONFIG_SMP
pvr = per_cpu(cpu_pvr, cpu_id);
#else
pvr = mfspr(SPRN_PVR);
#endif
maj = (pvr >> 8) & 0xFF;
min = pvr & 0xFF;
seq_printf(m, "processor\t: %lu\n", cpu_id);
seq_printf(m, "cpu\t\t: ");
if (cur_cpu_spec->pvr_mask)
seq_printf(m, "%s", cur_cpu_spec->cpu_name);
else
seq_printf(m, "unknown (%08x)", pvr);
#ifdef CONFIG_ALTIVEC
if (cpu_has_feature(CPU_FTR_ALTIVEC))
seq_printf(m, ", altivec supported");
#endif /* CONFIG_ALTIVEC */
seq_printf(m, "\n");
#ifdef CONFIG_TAU
if (cur_cpu_spec->cpu_features & CPU_FTR_TAU) {
#ifdef CONFIG_TAU_AVERAGE
/* more straightforward, but potentially misleading */
seq_printf(m, "temperature \t: %u C (uncalibrated)\n",
cpu_temp(cpu_id));
#else
/* show the actual temp sensor range */
u32 temp;
temp = cpu_temp_both(cpu_id);
seq_printf(m, "temperature \t: %u-%u C (uncalibrated)\n",
temp & 0xff, temp >> 16);
#endif
}
#endif /* CONFIG_TAU */
/*
* Assume here that all clock rates are the same in a
* smp system. -- Cort
*/
if (ppc_proc_freq)
seq_printf(m, "clock\t\t: %lu.%06luMHz\n",
ppc_proc_freq / 1000000, ppc_proc_freq % 1000000);
if (ppc_md.show_percpuinfo != NULL)
ppc_md.show_percpuinfo(m, cpu_id);
/* If we are a Freescale core do a simple check so
* we dont have to keep adding cases in the future */
if (PVR_VER(pvr) & 0x8000) {
switch (PVR_VER(pvr)) {
case 0x8000: /* 7441/7450/7451, Voyager */
case 0x8001: /* 7445/7455, Apollo 6 */
case 0x8002: /* 7447/7457, Apollo 7 */
case 0x8003: /* 7447A, Apollo 7 PM */
case 0x8004: /* 7448, Apollo 8 */
case 0x800c: /* 7410, Nitro */
maj = ((pvr >> 8) & 0xF);
min = PVR_MIN(pvr);
break;
default: /* e500/book-e */
maj = PVR_MAJ(pvr);
min = PVR_MIN(pvr);
break;
}
} else {
switch (PVR_VER(pvr)) {
case 0x0020: /* 403 family */
maj = PVR_MAJ(pvr) + 1;
min = PVR_MIN(pvr);
break;
case 0x1008: /* 740P/750P ?? */
maj = ((pvr >> 8) & 0xFF) - 1;
min = pvr & 0xFF;
break;
default:
maj = (pvr >> 8) & 0xFF;
min = pvr & 0xFF;
break;
}
}
seq_printf(m, "revision\t: %hd.%hd (pvr %04x %04x)\n",
maj, min, PVR_VER(pvr), PVR_REV(pvr));
#ifdef CONFIG_PPC32
seq_printf(m, "bogomips\t: %lu.%02lu\n",
loops_per_jiffy / (500000/HZ),
(loops_per_jiffy / (5000/HZ)) % 100);
#endif
#ifdef CONFIG_SMP
seq_printf(m, "\n");
#endif
preempt_enable();
/* If this is the last cpu, print the summary */
if (cpumask_next(cpu_id, cpu_online_mask) >= nr_cpu_ids)
show_cpuinfo_summary(m);
return 0;
}
static void *c_start(struct seq_file *m, loff_t *pos)
{
if (*pos == 0) /* just in case, cpu 0 is not the first */
*pos = cpumask_first(cpu_online_mask);
else
*pos = cpumask_next(*pos - 1, cpu_online_mask);
if ((*pos) < nr_cpu_ids)
return (void *)(unsigned long)(*pos + 1);
return 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,
};
void __init check_for_initrd(void)
{
#ifdef CONFIG_BLK_DEV_INITRD
DBG(" -> check_for_initrd() initrd_start=0x%lx initrd_end=0x%lx\n",
initrd_start, initrd_end);
/* If we were passed an initrd, set the ROOT_DEV properly if the values
* look sensible. If not, clear initrd reference.
*/
if (is_kernel_addr(initrd_start) && is_kernel_addr(initrd_end) &&
initrd_end > initrd_start)
ROOT_DEV = Root_RAM0;
else
initrd_start = initrd_end = 0;
if (initrd_start)
printk("Found initrd at 0x%lx:0x%lx\n", initrd_start, initrd_end);
DBG(" <- check_for_initrd()\n");
#endif /* CONFIG_BLK_DEV_INITRD */
}
#ifdef CONFIG_SMP
int threads_per_core, threads_shift;
cpumask_t threads_core_mask;
static void __init cpu_init_thread_core_maps(int tpc)
{
int i;
threads_per_core = tpc;
cpumask_clear(&threads_core_mask);
/* This implementation only supports power of 2 number of threads
* for simplicity and performance
*/
threads_shift = ilog2(tpc);
BUG_ON(tpc != (1 << threads_shift));
for (i = 0; i < tpc; i++)
cpumask_set_cpu(i, &threads_core_mask);
printk(KERN_INFO "CPU maps initialized for %d thread%s per core\n",
tpc, tpc > 1 ? "s" : "");
printk(KERN_DEBUG " (thread shift is %d)\n", threads_shift);
}
/**
* setup_cpu_maps - initialize the following cpu maps:
* cpu_possible_mask
* cpu_present_mask
*
* Having the possible map set up early allows us to restrict allocations
* of things like irqstacks to nr_cpu_ids rather than NR_CPUS.
*
* We do not initialize the online map here; cpus set their own bits in
* cpu_online_mask as they come up.
*
* This function is valid only for Open Firmware systems. finish_device_tree
* must be called before using this.
*
* While we're here, we may as well set the "physical" cpu ids in the paca.
*
* NOTE: This must match the parsing done in early_init_dt_scan_cpus.
*/
void __init smp_setup_cpu_maps(void)
{
struct device_node *dn = NULL;
int cpu = 0;
int nthreads = 1;
DBG("smp_setup_cpu_maps()\n");
while ((dn = of_find_node_by_type(dn, "cpu")) && cpu < nr_cpu_ids) {
const int *intserv;
int j, len;
DBG(" * %s...\n", dn->full_name);
intserv = of_get_property(dn, "ibm,ppc-interrupt-server#s",
&len);
if (intserv) {
nthreads = len / sizeof(int);
DBG(" ibm,ppc-interrupt-server#s -> %d threads\n",
nthreads);
} else {
DBG(" no ibm,ppc-interrupt-server#s -> 1 thread\n");
intserv = of_get_property(dn, "reg", NULL);
if (!intserv)
intserv = &cpu; /* assume logical == phys */
}
for (j = 0; j < nthreads && cpu < nr_cpu_ids; j++) {
DBG(" thread %d -> cpu %d (hard id %d)\n",
j, cpu, intserv[j]);
set_cpu_present(cpu, true);
set_hard_smp_processor_id(cpu, intserv[j]);
set_cpu_possible(cpu, true);
cpu++;
}
}
/* If no SMT supported, nthreads is forced to 1 */
if (!cpu_has_feature(CPU_FTR_SMT)) {
DBG(" SMT disabled ! nthreads forced to 1\n");
nthreads = 1;
}
#ifdef CONFIG_PPC64
/*
* On pSeries LPAR, we need to know how many cpus
* could possibly be added to this partition.
*/
if (machine_is(pseries) && firmware_has_feature(FW_FEATURE_LPAR) &&
(dn = of_find_node_by_path("/rtas"))) {
int num_addr_cell, num_size_cell, maxcpus;
const unsigned int *ireg;
num_addr_cell = of_n_addr_cells(dn);
num_size_cell = of_n_size_cells(dn);
ireg = of_get_property(dn, "ibm,lrdr-capacity", NULL);
if (!ireg)
goto out;
maxcpus = ireg[num_addr_cell + num_size_cell];
/* Double maxcpus for processors which have SMT capability */
if (cpu_has_feature(CPU_FTR_SMT))
maxcpus *= nthreads;
if (maxcpus > nr_cpu_ids) {
printk(KERN_WARNING
"Partition configured for %d cpus, "
"operating system maximum is %d.\n",
maxcpus, nr_cpu_ids);
maxcpus = nr_cpu_ids;
} else
printk(KERN_INFO "Partition configured for %d cpus.\n",
maxcpus);
for (cpu = 0; cpu < maxcpus; cpu++)
set_cpu_possible(cpu, true);
out:
of_node_put(dn);
}
vdso_data->processorCount = num_present_cpus();
#endif /* CONFIG_PPC64 */
/* Initialize CPU <=> thread mapping/
*
* WARNING: We assume that the number of threads is the same for
* every CPU in the system. If that is not the case, then some code
* here will have to be reworked
*/
cpu_init_thread_core_maps(nthreads);
/* Now that possible cpus are set, set nr_cpu_ids for later use */
setup_nr_cpu_ids();
free_unused_pacas();
}
#endif /* CONFIG_SMP */
#ifdef CONFIG_PCSPKR_PLATFORM
static __init int add_pcspkr(void)
{
struct device_node *np;
struct platform_device *pd;
int ret;
np = of_find_compatible_node(NULL, NULL, "pnpPNP,100");
of_node_put(np);
if (!np)
return -ENODEV;
pd = platform_device_alloc("pcspkr", -1);
if (!pd)
return -ENOMEM;
ret = platform_device_add(pd);
if (ret)
platform_device_put(pd);
return ret;
}
device_initcall(add_pcspkr);
#endif /* CONFIG_PCSPKR_PLATFORM */
void probe_machine(void)
{
extern struct machdep_calls __machine_desc_start;
extern struct machdep_calls __machine_desc_end;
/*
* Iterate all ppc_md structures until we find the proper
* one for the current machine type
*/
DBG("Probing machine type ...\n");
for (machine_id = &__machine_desc_start;
machine_id < &__machine_desc_end;
machine_id++) {
DBG(" %s ...", machine_id->name);
memcpy(&ppc_md, machine_id, sizeof(struct machdep_calls));
if (ppc_md.probe()) {
DBG(" match !\n");
break;
}
DBG("\n");
}
/* What can we do if we didn't find ? */
if (machine_id >= &__machine_desc_end) {
DBG("No suitable machine found !\n");
for (;;);
}
printk(KERN_INFO "Using %s machine description\n", ppc_md.name);
}
/* Match a class of boards, not a specific device configuration. */
int check_legacy_ioport(unsigned long base_port)
{
struct device_node *parent, *np = NULL;
int ret = -ENODEV;
switch(base_port) {
case I8042_DATA_REG:
if (!(np = of_find_compatible_node(NULL, NULL, "pnpPNP,303")))
np = of_find_compatible_node(NULL, NULL, "pnpPNP,f03");
if (np) {
parent = of_get_parent(np);
of_i8042_kbd_irq = irq_of_parse_and_map(parent, 0);
if (!of_i8042_kbd_irq)
of_i8042_kbd_irq = 1;
of_i8042_aux_irq = irq_of_parse_and_map(parent, 1);
if (!of_i8042_aux_irq)
of_i8042_aux_irq = 12;
of_node_put(np);
np = parent;
break;
}
np = of_find_node_by_type(NULL, "8042");
/* Pegasos has no device_type on its 8042 node, look for the
* name instead */
if (!np)
np = of_find_node_by_name(NULL, "8042");
if (np) {
of_i8042_kbd_irq = 1;
of_i8042_aux_irq = 12;
}
break;
case FDC_BASE: /* FDC1 */
np = of_find_node_by_type(NULL, "fdc");
break;
#ifdef CONFIG_PPC_PREP
case _PIDXR:
case _PNPWRP:
case PNPBIOS_BASE:
/* implement me */
#endif
default:
/* ipmi is supposed to fail here */
break;
}
if (!np)
return ret;
parent = of_get_parent(np);
if (parent) {
if (strcmp(parent->type, "isa") == 0)
ret = 0;
of_node_put(parent);
}
of_node_put(np);
return ret;
}
EXPORT_SYMBOL(check_legacy_ioport);
static int ppc_panic_event(struct notifier_block *this,
unsigned long event, void *ptr)
{
ppc_md.panic(ptr); /* May not return */
return NOTIFY_DONE;
}
static struct notifier_block ppc_panic_block = {
.notifier_call = ppc_panic_event,
.priority = INT_MIN /* may not return; must be done last */
};
void __init setup_panic(void)
{
atomic_notifier_chain_register(&panic_notifier_list, &ppc_panic_block);
}
#ifdef CONFIG_CHECK_CACHE_COHERENCY
/*
* For platforms that have configurable cache-coherency. This function
* checks that the cache coherency setting of the kernel matches the setting
* left by the firmware, as indicated in the device tree. Since a mismatch
* will eventually result in DMA failures, we print * and error and call
* BUG() in that case.
*/
#ifdef CONFIG_NOT_COHERENT_CACHE
#define KERNEL_COHERENCY 0
#else
#define KERNEL_COHERENCY 1
#endif
static int __init check_cache_coherency(void)
{
struct device_node *np;
const void *prop;
int devtree_coherency;
np = of_find_node_by_path("/");
prop = of_get_property(np, "coherency-off", NULL);
of_node_put(np);
devtree_coherency = prop ? 0 : 1;
if (devtree_coherency != KERNEL_COHERENCY) {
printk(KERN_ERR
"kernel coherency:%s != device tree_coherency:%s\n",
KERNEL_COHERENCY ? "on" : "off",
devtree_coherency ? "on" : "off");
BUG();
}
return 0;
}
late_initcall(check_cache_coherency);
#endif /* CONFIG_CHECK_CACHE_COHERENCY */
#ifdef CONFIG_DEBUG_FS
struct dentry *powerpc_debugfs_root;
EXPORT_SYMBOL(powerpc_debugfs_root);
static int powerpc_debugfs_init(void)
{
powerpc_debugfs_root = debugfs_create_dir("powerpc", NULL);
return powerpc_debugfs_root == NULL;
}
arch_initcall(powerpc_debugfs_init);
#endif
static int ppc_dflt_bus_notify(struct notifier_block *nb,
unsigned long action, void *data)
{
struct device *dev = data;
/* We are only intereted in device addition */
if (action != BUS_NOTIFY_ADD_DEVICE)
return 0;
set_dma_ops(dev, &dma_direct_ops);
return NOTIFY_DONE;
}
static struct notifier_block ppc_dflt_plat_bus_notifier = {
.notifier_call = ppc_dflt_bus_notify,
.priority = INT_MAX,
};
static int __init setup_bus_notifier(void)
{
bus_register_notifier(&platform_bus_type, &ppc_dflt_plat_bus_notifier);
return 0;
}
arch_initcall(setup_bus_notifier);
| gpl-2.0 |
emceethemouth/kernel_android | drivers/media/radio/radio-mr800.c | 2695 | 17562 | /*
* A driver for the AverMedia MR 800 USB FM radio. This device plugs
* into both the USB and an analog audio input, so this thing
* only deals with initialization and frequency setting, the
* audio data has to be handled by a sound driver.
*
* Copyright (c) 2008 Alexey Klimov <klimov.linux@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* Big thanks to authors and contributors of dsbr100.c and radio-si470x.c
*
* When work was looked pretty good, i discover this:
* http://av-usbradio.sourceforge.net/index.php
* http://sourceforge.net/projects/av-usbradio/
* Latest release of theirs project was in 2005.
* Probably, this driver could be improved through using their
* achievements (specifications given).
* Also, Faidon Liambotis <paravoid@debian.org> wrote nice driver for this radio
* in 2007. He allowed to use his driver to improve current mr800 radio driver.
* http://kerneltrap.org/mailarchive/linux-usb-devel/2007/10/11/342492
*
* Version 0.01: First working version.
* It's required to blacklist AverMedia USB Radio
* in usbhid/hid-quirks.c
* Version 0.10: A lot of cleanups and fixes: unpluging the device,
* few mutex locks were added, codinstyle issues, etc.
* Added stereo support. Thanks to
* Douglas Schilling Landgraf <dougsland@gmail.com> and
* David Ellingsworth <david@identd.dyndns.org>
* for discussion, help and support.
* Version 0.11: Converted to v4l2_device.
*
* Many things to do:
* - Correct power management of device (suspend & resume)
* - Add code for scanning and smooth tuning
* - Add code for sensitivity value
* - Correct mistakes
* - In Japan another FREQ_MIN and FREQ_MAX
*/
/* kernel includes */
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/videodev2.h>
#include <media/v4l2-device.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-ctrls.h>
#include <media/v4l2-event.h>
#include <linux/usb.h>
#include <linux/mutex.h>
/* driver and module definitions */
#define DRIVER_AUTHOR "Alexey Klimov <klimov.linux@gmail.com>"
#define DRIVER_DESC "AverMedia MR 800 USB FM radio driver"
#define DRIVER_VERSION "0.1.2"
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
MODULE_VERSION(DRIVER_VERSION);
#define USB_AMRADIO_VENDOR 0x07ca
#define USB_AMRADIO_PRODUCT 0xb800
/* dev_warn macro with driver name */
#define MR800_DRIVER_NAME "radio-mr800"
#define amradio_dev_warn(dev, fmt, arg...) \
dev_warn(dev, MR800_DRIVER_NAME " - " fmt, ##arg)
#define amradio_dev_err(dev, fmt, arg...) \
dev_err(dev, MR800_DRIVER_NAME " - " fmt, ##arg)
/* Probably USB_TIMEOUT should be modified in module parameter */
#define BUFFER_LENGTH 8
#define USB_TIMEOUT 500
/* Frequency limits in MHz -- these are European values. For Japanese
devices, that would be 76 and 91. */
#define FREQ_MIN 87.5
#define FREQ_MAX 108.0
#define FREQ_MUL 16000
/*
* Commands that device should understand
* List isn't full and will be updated with implementation of new functions
*/
#define AMRADIO_SET_FREQ 0xa4
#define AMRADIO_GET_READY_FLAG 0xa5
#define AMRADIO_GET_SIGNAL 0xa7
#define AMRADIO_GET_FREQ 0xa8
#define AMRADIO_SET_SEARCH_UP 0xa9
#define AMRADIO_SET_SEARCH_DOWN 0xaa
#define AMRADIO_SET_MUTE 0xab
#define AMRADIO_SET_RIGHT_MUTE 0xac
#define AMRADIO_SET_LEFT_MUTE 0xad
#define AMRADIO_SET_MONO 0xae
#define AMRADIO_SET_SEARCH_LVL 0xb0
#define AMRADIO_STOP_SEARCH 0xb1
/* Comfortable defines for amradio_set_stereo */
#define WANT_STEREO 0x00
#define WANT_MONO 0x01
/* module parameter */
static int radio_nr = -1;
module_param(radio_nr, int, 0);
MODULE_PARM_DESC(radio_nr, "Radio Nr");
/* Data for one (physical) device */
struct amradio_device {
/* reference to USB and video device */
struct usb_device *usbdev;
struct usb_interface *intf;
struct video_device vdev;
struct v4l2_device v4l2_dev;
struct v4l2_ctrl_handler hdl;
u8 *buffer;
struct mutex lock; /* buffer locking */
int curfreq;
int stereo;
int muted;
};
static inline struct amradio_device *to_amradio_dev(struct v4l2_device *v4l2_dev)
{
return container_of(v4l2_dev, struct amradio_device, v4l2_dev);
}
static int amradio_send_cmd(struct amradio_device *radio, u8 cmd, u8 arg,
u8 *extra, u8 extralen, bool reply)
{
int retval;
int size;
radio->buffer[0] = 0x00;
radio->buffer[1] = 0x55;
radio->buffer[2] = 0xaa;
radio->buffer[3] = extralen;
radio->buffer[4] = cmd;
radio->buffer[5] = arg;
radio->buffer[6] = 0x00;
radio->buffer[7] = extra || reply ? 8 : 0;
retval = usb_bulk_msg(radio->usbdev, usb_sndintpipe(radio->usbdev, 2),
radio->buffer, BUFFER_LENGTH, &size, USB_TIMEOUT);
if (retval < 0 || size != BUFFER_LENGTH) {
if (video_is_registered(&radio->vdev))
amradio_dev_warn(&radio->vdev.dev,
"cmd %02x failed\n", cmd);
return retval ? retval : -EIO;
}
if (!extra && !reply)
return 0;
if (extra) {
memcpy(radio->buffer, extra, extralen);
memset(radio->buffer + extralen, 0, 8 - extralen);
retval = usb_bulk_msg(radio->usbdev, usb_sndintpipe(radio->usbdev, 2),
radio->buffer, BUFFER_LENGTH, &size, USB_TIMEOUT);
} else {
memset(radio->buffer, 0, 8);
retval = usb_bulk_msg(radio->usbdev, usb_rcvbulkpipe(radio->usbdev, 0x81),
radio->buffer, BUFFER_LENGTH, &size, USB_TIMEOUT);
}
if (retval == 0 && size == BUFFER_LENGTH)
return 0;
if (video_is_registered(&radio->vdev) && cmd != AMRADIO_GET_READY_FLAG)
amradio_dev_warn(&radio->vdev.dev, "follow-up to cmd %02x failed\n", cmd);
return retval ? retval : -EIO;
}
/* switch on/off the radio. Send 8 bytes to device */
static int amradio_set_mute(struct amradio_device *radio, bool mute)
{
int ret = amradio_send_cmd(radio,
AMRADIO_SET_MUTE, mute, NULL, 0, false);
if (!ret)
radio->muted = mute;
return ret;
}
/* set a frequency, freq is defined by v4l's TUNER_LOW, i.e. 1/16th kHz */
static int amradio_set_freq(struct amradio_device *radio, int freq)
{
unsigned short freq_send;
u8 buf[3];
int retval;
/* we need to be sure that frequency isn't out of range */
freq = clamp_t(unsigned, freq, FREQ_MIN * FREQ_MUL, FREQ_MAX * FREQ_MUL);
freq_send = 0x10 + (freq >> 3) / 25;
/* frequency is calculated from freq_send and placed in first 2 bytes */
buf[0] = (freq_send >> 8) & 0xff;
buf[1] = freq_send & 0xff;
buf[2] = 0x01;
retval = amradio_send_cmd(radio, AMRADIO_SET_FREQ, 0, buf, 3, false);
if (retval)
return retval;
radio->curfreq = freq;
msleep(40);
return 0;
}
static int amradio_set_stereo(struct amradio_device *radio, bool stereo)
{
int ret = amradio_send_cmd(radio,
AMRADIO_SET_MONO, !stereo, NULL, 0, false);
if (!ret)
radio->stereo = stereo;
return ret;
}
static int amradio_get_stat(struct amradio_device *radio, bool *is_stereo, u32 *signal)
{
int ret = amradio_send_cmd(radio,
AMRADIO_GET_SIGNAL, 0, NULL, 0, true);
if (ret)
return ret;
*is_stereo = radio->buffer[2] >> 7;
*signal = (radio->buffer[3] & 0xf0) << 8;
return 0;
}
/* Handle unplugging the device.
* We call video_unregister_device in any case.
* The last function called in this procedure is
* usb_amradio_device_release.
*/
static void usb_amradio_disconnect(struct usb_interface *intf)
{
struct amradio_device *radio = to_amradio_dev(usb_get_intfdata(intf));
mutex_lock(&radio->lock);
video_unregister_device(&radio->vdev);
amradio_set_mute(radio, true);
usb_set_intfdata(intf, NULL);
v4l2_device_disconnect(&radio->v4l2_dev);
mutex_unlock(&radio->lock);
v4l2_device_put(&radio->v4l2_dev);
}
/* vidioc_querycap - query device capabilities */
static int vidioc_querycap(struct file *file, void *priv,
struct v4l2_capability *v)
{
struct amradio_device *radio = video_drvdata(file);
strlcpy(v->driver, "radio-mr800", sizeof(v->driver));
strlcpy(v->card, "AverMedia MR 800 USB FM Radio", sizeof(v->card));
usb_make_path(radio->usbdev, v->bus_info, sizeof(v->bus_info));
v->device_caps = V4L2_CAP_RADIO | V4L2_CAP_TUNER |
V4L2_CAP_HW_FREQ_SEEK;
v->capabilities = v->device_caps | V4L2_CAP_DEVICE_CAPS;
return 0;
}
/* vidioc_g_tuner - get tuner attributes */
static int vidioc_g_tuner(struct file *file, void *priv,
struct v4l2_tuner *v)
{
struct amradio_device *radio = video_drvdata(file);
bool is_stereo = false;
int retval;
if (v->index > 0)
return -EINVAL;
v->signal = 0;
retval = amradio_get_stat(radio, &is_stereo, &v->signal);
if (retval)
return retval;
strcpy(v->name, "FM");
v->type = V4L2_TUNER_RADIO;
v->rangelow = FREQ_MIN * FREQ_MUL;
v->rangehigh = FREQ_MAX * FREQ_MUL;
v->capability = V4L2_TUNER_CAP_LOW | V4L2_TUNER_CAP_STEREO |
V4L2_TUNER_CAP_HWSEEK_WRAP;
v->rxsubchans = is_stereo ? V4L2_TUNER_SUB_STEREO : V4L2_TUNER_SUB_MONO;
v->audmode = radio->stereo ?
V4L2_TUNER_MODE_STEREO : V4L2_TUNER_MODE_MONO;
return 0;
}
/* vidioc_s_tuner - set tuner attributes */
static int vidioc_s_tuner(struct file *file, void *priv,
const struct v4l2_tuner *v)
{
struct amradio_device *radio = video_drvdata(file);
if (v->index > 0)
return -EINVAL;
/* mono/stereo selector */
switch (v->audmode) {
case V4L2_TUNER_MODE_MONO:
return amradio_set_stereo(radio, WANT_MONO);
default:
return amradio_set_stereo(radio, WANT_STEREO);
}
}
/* vidioc_s_frequency - set tuner radio frequency */
static int vidioc_s_frequency(struct file *file, void *priv,
const struct v4l2_frequency *f)
{
struct amradio_device *radio = video_drvdata(file);
if (f->tuner != 0)
return -EINVAL;
return amradio_set_freq(radio, f->frequency);
}
/* vidioc_g_frequency - get tuner radio frequency */
static int vidioc_g_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
struct amradio_device *radio = video_drvdata(file);
if (f->tuner != 0 || f->type != V4L2_TUNER_RADIO)
return -EINVAL;
f->type = V4L2_TUNER_RADIO;
f->frequency = radio->curfreq;
return 0;
}
static int vidioc_s_hw_freq_seek(struct file *file, void *priv,
const struct v4l2_hw_freq_seek *seek)
{
static u8 buf[8] = {
0x3d, 0x32, 0x0f, 0x08, 0x3d, 0x32, 0x0f, 0x08
};
struct amradio_device *radio = video_drvdata(file);
unsigned long timeout;
int retval;
if (seek->tuner != 0 || !seek->wrap_around)
return -EINVAL;
if (file->f_flags & O_NONBLOCK)
return -EWOULDBLOCK;
retval = amradio_send_cmd(radio,
AMRADIO_SET_SEARCH_LVL, 0, buf, 8, false);
if (retval)
return retval;
amradio_set_freq(radio, radio->curfreq);
retval = amradio_send_cmd(radio,
seek->seek_upward ? AMRADIO_SET_SEARCH_UP : AMRADIO_SET_SEARCH_DOWN,
0, NULL, 0, false);
if (retval)
return retval;
timeout = jiffies + msecs_to_jiffies(30000);
for (;;) {
if (time_after(jiffies, timeout)) {
retval = -ENODATA;
break;
}
if (schedule_timeout_interruptible(msecs_to_jiffies(10))) {
retval = -ERESTARTSYS;
break;
}
retval = amradio_send_cmd(radio, AMRADIO_GET_READY_FLAG,
0, NULL, 0, true);
if (retval)
continue;
amradio_send_cmd(radio, AMRADIO_GET_FREQ, 0, NULL, 0, true);
if (radio->buffer[1] || radio->buffer[2]) {
/* To check: sometimes radio->curfreq is set to out of range value */
radio->curfreq = (radio->buffer[1] << 8) | radio->buffer[2];
radio->curfreq = (radio->curfreq - 0x10) * 200;
amradio_send_cmd(radio, AMRADIO_STOP_SEARCH,
0, NULL, 0, false);
amradio_set_freq(radio, radio->curfreq);
retval = 0;
break;
}
}
amradio_send_cmd(radio, AMRADIO_STOP_SEARCH, 0, NULL, 0, false);
amradio_set_freq(radio, radio->curfreq);
return retval;
}
static int usb_amradio_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct amradio_device *radio =
container_of(ctrl->handler, struct amradio_device, hdl);
switch (ctrl->id) {
case V4L2_CID_AUDIO_MUTE:
return amradio_set_mute(radio, ctrl->val);
}
return -EINVAL;
}
static int usb_amradio_init(struct amradio_device *radio)
{
int retval;
retval = amradio_set_mute(radio, true);
if (retval)
goto out_err;
retval = amradio_set_stereo(radio, true);
if (retval)
goto out_err;
retval = amradio_set_freq(radio, radio->curfreq);
if (retval)
goto out_err;
return 0;
out_err:
amradio_dev_err(&radio->vdev.dev, "initialization failed\n");
return retval;
}
/* Suspend device - stop device. Need to be checked and fixed */
static int usb_amradio_suspend(struct usb_interface *intf, pm_message_t message)
{
struct amradio_device *radio = to_amradio_dev(usb_get_intfdata(intf));
mutex_lock(&radio->lock);
if (!radio->muted) {
amradio_set_mute(radio, true);
radio->muted = false;
}
mutex_unlock(&radio->lock);
dev_info(&intf->dev, "going into suspend..\n");
return 0;
}
/* Resume device - start device. Need to be checked and fixed */
static int usb_amradio_resume(struct usb_interface *intf)
{
struct amradio_device *radio = to_amradio_dev(usb_get_intfdata(intf));
mutex_lock(&radio->lock);
amradio_set_stereo(radio, radio->stereo);
amradio_set_freq(radio, radio->curfreq);
if (!radio->muted)
amradio_set_mute(radio, false);
mutex_unlock(&radio->lock);
dev_info(&intf->dev, "coming out of suspend..\n");
return 0;
}
static const struct v4l2_ctrl_ops usb_amradio_ctrl_ops = {
.s_ctrl = usb_amradio_s_ctrl,
};
/* File system interface */
static const struct v4l2_file_operations usb_amradio_fops = {
.owner = THIS_MODULE,
.open = v4l2_fh_open,
.release = v4l2_fh_release,
.poll = v4l2_ctrl_poll,
.unlocked_ioctl = video_ioctl2,
};
static const struct v4l2_ioctl_ops usb_amradio_ioctl_ops = {
.vidioc_querycap = vidioc_querycap,
.vidioc_g_tuner = vidioc_g_tuner,
.vidioc_s_tuner = vidioc_s_tuner,
.vidioc_g_frequency = vidioc_g_frequency,
.vidioc_s_frequency = vidioc_s_frequency,
.vidioc_s_hw_freq_seek = vidioc_s_hw_freq_seek,
.vidioc_log_status = v4l2_ctrl_log_status,
.vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
};
static void usb_amradio_release(struct v4l2_device *v4l2_dev)
{
struct amradio_device *radio = to_amradio_dev(v4l2_dev);
/* free rest memory */
v4l2_ctrl_handler_free(&radio->hdl);
v4l2_device_unregister(&radio->v4l2_dev);
kfree(radio->buffer);
kfree(radio);
}
/* check if the device is present and register with v4l and usb if it is */
static int usb_amradio_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct amradio_device *radio;
int retval = 0;
radio = kzalloc(sizeof(struct amradio_device), GFP_KERNEL);
if (!radio) {
dev_err(&intf->dev, "kmalloc for amradio_device failed\n");
retval = -ENOMEM;
goto err;
}
radio->buffer = kmalloc(BUFFER_LENGTH, GFP_KERNEL);
if (!radio->buffer) {
dev_err(&intf->dev, "kmalloc for radio->buffer failed\n");
retval = -ENOMEM;
goto err_nobuf;
}
retval = v4l2_device_register(&intf->dev, &radio->v4l2_dev);
if (retval < 0) {
dev_err(&intf->dev, "couldn't register v4l2_device\n");
goto err_v4l2;
}
v4l2_ctrl_handler_init(&radio->hdl, 1);
v4l2_ctrl_new_std(&radio->hdl, &usb_amradio_ctrl_ops,
V4L2_CID_AUDIO_MUTE, 0, 1, 1, 1);
if (radio->hdl.error) {
retval = radio->hdl.error;
dev_err(&intf->dev, "couldn't register control\n");
goto err_ctrl;
}
mutex_init(&radio->lock);
radio->v4l2_dev.ctrl_handler = &radio->hdl;
radio->v4l2_dev.release = usb_amradio_release;
strlcpy(radio->vdev.name, radio->v4l2_dev.name,
sizeof(radio->vdev.name));
radio->vdev.v4l2_dev = &radio->v4l2_dev;
radio->vdev.fops = &usb_amradio_fops;
radio->vdev.ioctl_ops = &usb_amradio_ioctl_ops;
radio->vdev.release = video_device_release_empty;
radio->vdev.lock = &radio->lock;
set_bit(V4L2_FL_USE_FH_PRIO, &radio->vdev.flags);
radio->usbdev = interface_to_usbdev(intf);
radio->intf = intf;
usb_set_intfdata(intf, &radio->v4l2_dev);
radio->curfreq = 95.16 * FREQ_MUL;
video_set_drvdata(&radio->vdev, radio);
retval = usb_amradio_init(radio);
if (retval)
goto err_vdev;
retval = video_register_device(&radio->vdev, VFL_TYPE_RADIO,
radio_nr);
if (retval < 0) {
dev_err(&intf->dev, "could not register video device\n");
goto err_vdev;
}
return 0;
err_vdev:
v4l2_ctrl_handler_free(&radio->hdl);
err_ctrl:
v4l2_device_unregister(&radio->v4l2_dev);
err_v4l2:
kfree(radio->buffer);
err_nobuf:
kfree(radio);
err:
return retval;
}
/* USB Device ID List */
static struct usb_device_id usb_amradio_device_table[] = {
{ USB_DEVICE_AND_INTERFACE_INFO(USB_AMRADIO_VENDOR, USB_AMRADIO_PRODUCT,
USB_CLASS_HID, 0, 0) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, usb_amradio_device_table);
/* USB subsystem interface */
static struct usb_driver usb_amradio_driver = {
.name = MR800_DRIVER_NAME,
.probe = usb_amradio_probe,
.disconnect = usb_amradio_disconnect,
.suspend = usb_amradio_suspend,
.resume = usb_amradio_resume,
.reset_resume = usb_amradio_resume,
.id_table = usb_amradio_device_table,
};
module_usb_driver(usb_amradio_driver);
| gpl-2.0 |
archil-p/EZMotoLinux | drivers/input/mouse/trackpoint.c | 2695 | 12105 | /*
* Stephen Evanchik <evanchsa@gmail.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.
*
* Trademarks are the property of their respective owners.
*/
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/serio.h>
#include <linux/module.h>
#include <linux/input.h>
#include <linux/libps2.h>
#include <linux/proc_fs.h>
#include <asm/uaccess.h>
#include "psmouse.h"
#include "trackpoint.h"
/*
* Power-on Reset: Resets all trackpoint parameters, including RAM values,
* to defaults.
* Returns zero on success, non-zero on failure.
*/
static int trackpoint_power_on_reset(struct ps2dev *ps2dev)
{
unsigned char results[2];
int tries = 0;
/* Issue POR command, and repeat up to once if 0xFC00 received */
do {
if (ps2_command(ps2dev, NULL, MAKE_PS2_CMD(0, 0, TP_COMMAND)) ||
ps2_command(ps2dev, results, MAKE_PS2_CMD(0, 2, TP_POR)))
return -1;
} while (results[0] == 0xFC && results[1] == 0x00 && ++tries < 2);
/* Check for success response -- 0xAA00 */
if (results[0] != 0xAA || results[1] != 0x00)
return -1;
return 0;
}
/*
* Device IO: read, write and toggle bit
*/
static int trackpoint_read(struct ps2dev *ps2dev,
unsigned char loc, unsigned char *results)
{
if (ps2_command(ps2dev, NULL, MAKE_PS2_CMD(0, 0, TP_COMMAND)) ||
ps2_command(ps2dev, results, MAKE_PS2_CMD(0, 1, loc))) {
return -1;
}
return 0;
}
static int trackpoint_write(struct ps2dev *ps2dev,
unsigned char loc, unsigned char val)
{
if (ps2_command(ps2dev, NULL, MAKE_PS2_CMD(0, 0, TP_COMMAND)) ||
ps2_command(ps2dev, NULL, MAKE_PS2_CMD(0, 0, TP_WRITE_MEM)) ||
ps2_command(ps2dev, NULL, MAKE_PS2_CMD(0, 0, loc)) ||
ps2_command(ps2dev, NULL, MAKE_PS2_CMD(0, 0, val))) {
return -1;
}
return 0;
}
static int trackpoint_toggle_bit(struct ps2dev *ps2dev,
unsigned char loc, unsigned char mask)
{
/* Bad things will happen if the loc param isn't in this range */
if (loc < 0x20 || loc >= 0x2F)
return -1;
if (ps2_command(ps2dev, NULL, MAKE_PS2_CMD(0, 0, TP_COMMAND)) ||
ps2_command(ps2dev, NULL, MAKE_PS2_CMD(0, 0, TP_TOGGLE)) ||
ps2_command(ps2dev, NULL, MAKE_PS2_CMD(0, 0, loc)) ||
ps2_command(ps2dev, NULL, MAKE_PS2_CMD(0, 0, mask))) {
return -1;
}
return 0;
}
static int trackpoint_update_bit(struct ps2dev *ps2dev, unsigned char loc,
unsigned char mask, unsigned char value)
{
int retval = 0;
unsigned char data;
trackpoint_read(ps2dev, loc, &data);
if (((data & mask) == mask) != !!value)
retval = trackpoint_toggle_bit(ps2dev, loc, mask);
return retval;
}
/*
* Trackpoint-specific attributes
*/
struct trackpoint_attr_data {
size_t field_offset;
unsigned char command;
unsigned char mask;
unsigned char inverted;
unsigned char power_on_default;
};
static ssize_t trackpoint_show_int_attr(struct psmouse *psmouse, void *data, char *buf)
{
struct trackpoint_data *tp = psmouse->private;
struct trackpoint_attr_data *attr = data;
unsigned char value = *(unsigned char *)((char *)tp + attr->field_offset);
if (attr->inverted)
value = !value;
return sprintf(buf, "%u\n", value);
}
static ssize_t trackpoint_set_int_attr(struct psmouse *psmouse, void *data,
const char *buf, size_t count)
{
struct trackpoint_data *tp = psmouse->private;
struct trackpoint_attr_data *attr = data;
unsigned char *field = (unsigned char *)((char *)tp + attr->field_offset);
unsigned char value;
int err;
err = kstrtou8(buf, 10, &value);
if (err)
return err;
*field = value;
trackpoint_write(&psmouse->ps2dev, attr->command, value);
return count;
}
#define TRACKPOINT_INT_ATTR(_name, _command, _default) \
static struct trackpoint_attr_data trackpoint_attr_##_name = { \
.field_offset = offsetof(struct trackpoint_data, _name), \
.command = _command, \
.power_on_default = _default, \
}; \
PSMOUSE_DEFINE_ATTR(_name, S_IWUSR | S_IRUGO, \
&trackpoint_attr_##_name, \
trackpoint_show_int_attr, trackpoint_set_int_attr)
static ssize_t trackpoint_set_bit_attr(struct psmouse *psmouse, void *data,
const char *buf, size_t count)
{
struct trackpoint_data *tp = psmouse->private;
struct trackpoint_attr_data *attr = data;
unsigned char *field = (unsigned char *)((char *)tp + attr->field_offset);
unsigned int value;
int err;
err = kstrtouint(buf, 10, &value);
if (err)
return err;
if (value > 1)
return -EINVAL;
if (attr->inverted)
value = !value;
if (*field != value) {
*field = value;
trackpoint_toggle_bit(&psmouse->ps2dev, attr->command, attr->mask);
}
return count;
}
#define TRACKPOINT_BIT_ATTR(_name, _command, _mask, _inv, _default) \
static struct trackpoint_attr_data trackpoint_attr_##_name = { \
.field_offset = offsetof(struct trackpoint_data, \
_name), \
.command = _command, \
.mask = _mask, \
.inverted = _inv, \
.power_on_default = _default, \
}; \
PSMOUSE_DEFINE_ATTR(_name, S_IWUSR | S_IRUGO, \
&trackpoint_attr_##_name, \
trackpoint_show_int_attr, trackpoint_set_bit_attr)
#define TRACKPOINT_UPDATE_BIT(_psmouse, _tp, _name) \
do { \
struct trackpoint_attr_data *_attr = &trackpoint_attr_##_name; \
\
trackpoint_update_bit(&_psmouse->ps2dev, \
_attr->command, _attr->mask, _tp->_name); \
} while (0)
#define TRACKPOINT_UPDATE(_power_on, _psmouse, _tp, _name) \
do { \
if (!_power_on || \
_tp->_name != trackpoint_attr_##_name.power_on_default) { \
if (!trackpoint_attr_##_name.mask) \
trackpoint_write(&_psmouse->ps2dev, \
trackpoint_attr_##_name.command, \
_tp->_name); \
else \
TRACKPOINT_UPDATE_BIT(_psmouse, _tp, _name); \
} \
} while (0)
#define TRACKPOINT_SET_POWER_ON_DEFAULT(_tp, _name) \
(_tp->_name = trackpoint_attr_##_name.power_on_default)
TRACKPOINT_INT_ATTR(sensitivity, TP_SENS, TP_DEF_SENS);
TRACKPOINT_INT_ATTR(speed, TP_SPEED, TP_DEF_SPEED);
TRACKPOINT_INT_ATTR(inertia, TP_INERTIA, TP_DEF_INERTIA);
TRACKPOINT_INT_ATTR(reach, TP_REACH, TP_DEF_REACH);
TRACKPOINT_INT_ATTR(draghys, TP_DRAGHYS, TP_DEF_DRAGHYS);
TRACKPOINT_INT_ATTR(mindrag, TP_MINDRAG, TP_DEF_MINDRAG);
TRACKPOINT_INT_ATTR(thresh, TP_THRESH, TP_DEF_THRESH);
TRACKPOINT_INT_ATTR(upthresh, TP_UP_THRESH, TP_DEF_UP_THRESH);
TRACKPOINT_INT_ATTR(ztime, TP_Z_TIME, TP_DEF_Z_TIME);
TRACKPOINT_INT_ATTR(jenks, TP_JENKS_CURV, TP_DEF_JENKS_CURV);
TRACKPOINT_BIT_ATTR(press_to_select, TP_TOGGLE_PTSON, TP_MASK_PTSON, 0,
TP_DEF_PTSON);
TRACKPOINT_BIT_ATTR(skipback, TP_TOGGLE_SKIPBACK, TP_MASK_SKIPBACK, 0,
TP_DEF_SKIPBACK);
TRACKPOINT_BIT_ATTR(ext_dev, TP_TOGGLE_EXT_DEV, TP_MASK_EXT_DEV, 1,
TP_DEF_EXT_DEV);
static struct attribute *trackpoint_attrs[] = {
&psmouse_attr_sensitivity.dattr.attr,
&psmouse_attr_speed.dattr.attr,
&psmouse_attr_inertia.dattr.attr,
&psmouse_attr_reach.dattr.attr,
&psmouse_attr_draghys.dattr.attr,
&psmouse_attr_mindrag.dattr.attr,
&psmouse_attr_thresh.dattr.attr,
&psmouse_attr_upthresh.dattr.attr,
&psmouse_attr_ztime.dattr.attr,
&psmouse_attr_jenks.dattr.attr,
&psmouse_attr_press_to_select.dattr.attr,
&psmouse_attr_skipback.dattr.attr,
&psmouse_attr_ext_dev.dattr.attr,
NULL
};
static struct attribute_group trackpoint_attr_group = {
.attrs = trackpoint_attrs,
};
static int trackpoint_start_protocol(struct psmouse *psmouse, unsigned char *firmware_id)
{
unsigned char param[2] = { 0 };
if (ps2_command(&psmouse->ps2dev, param, MAKE_PS2_CMD(0, 2, TP_READ_ID)))
return -1;
if (param[0] != TP_MAGIC_IDENT)
return -1;
if (firmware_id)
*firmware_id = param[1];
return 0;
}
/*
* Write parameters to trackpad.
* in_power_on_state: Set to true if TP is in default / power-on state (ex. if
* power-on reset was run). If so, values will only be
* written to TP if they differ from power-on default.
*/
static int trackpoint_sync(struct psmouse *psmouse, bool in_power_on_state)
{
struct trackpoint_data *tp = psmouse->private;
if (!in_power_on_state) {
/*
* Disable features that may make device unusable
* with this driver.
*/
trackpoint_update_bit(&psmouse->ps2dev, TP_TOGGLE_TWOHAND,
TP_MASK_TWOHAND, TP_DEF_TWOHAND);
trackpoint_update_bit(&psmouse->ps2dev, TP_TOGGLE_SOURCE_TAG,
TP_MASK_SOURCE_TAG, TP_DEF_SOURCE_TAG);
trackpoint_update_bit(&psmouse->ps2dev, TP_TOGGLE_MB,
TP_MASK_MB, TP_DEF_MB);
}
/*
* These properties can be changed in this driver. Only
* configure them if the values are non-default or if the TP is in
* an unknown state.
*/
TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, sensitivity);
TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, inertia);
TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, speed);
TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, reach);
TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, draghys);
TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, mindrag);
TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, thresh);
TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, upthresh);
TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, ztime);
TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, jenks);
/* toggles */
TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, press_to_select);
TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, skipback);
TRACKPOINT_UPDATE(in_power_on_state, psmouse, tp, ext_dev);
return 0;
}
static void trackpoint_defaults(struct trackpoint_data *tp)
{
TRACKPOINT_SET_POWER_ON_DEFAULT(tp, sensitivity);
TRACKPOINT_SET_POWER_ON_DEFAULT(tp, speed);
TRACKPOINT_SET_POWER_ON_DEFAULT(tp, reach);
TRACKPOINT_SET_POWER_ON_DEFAULT(tp, draghys);
TRACKPOINT_SET_POWER_ON_DEFAULT(tp, mindrag);
TRACKPOINT_SET_POWER_ON_DEFAULT(tp, thresh);
TRACKPOINT_SET_POWER_ON_DEFAULT(tp, upthresh);
TRACKPOINT_SET_POWER_ON_DEFAULT(tp, ztime);
TRACKPOINT_SET_POWER_ON_DEFAULT(tp, jenks);
TRACKPOINT_SET_POWER_ON_DEFAULT(tp, inertia);
/* toggles */
TRACKPOINT_SET_POWER_ON_DEFAULT(tp, press_to_select);
TRACKPOINT_SET_POWER_ON_DEFAULT(tp, skipback);
TRACKPOINT_SET_POWER_ON_DEFAULT(tp, ext_dev);
}
static void trackpoint_disconnect(struct psmouse *psmouse)
{
sysfs_remove_group(&psmouse->ps2dev.serio->dev.kobj, &trackpoint_attr_group);
kfree(psmouse->private);
psmouse->private = NULL;
}
static int trackpoint_reconnect(struct psmouse *psmouse)
{
int reset_fail;
if (trackpoint_start_protocol(psmouse, NULL))
return -1;
reset_fail = trackpoint_power_on_reset(&psmouse->ps2dev);
if (trackpoint_sync(psmouse, !reset_fail))
return -1;
return 0;
}
int trackpoint_detect(struct psmouse *psmouse, bool set_properties)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char firmware_id;
unsigned char button_info;
int error;
if (trackpoint_start_protocol(psmouse, &firmware_id))
return -1;
if (!set_properties)
return 0;
if (trackpoint_read(&psmouse->ps2dev, TP_EXT_BTN, &button_info)) {
psmouse_warn(psmouse, "failed to get extended button data\n");
button_info = 0;
}
psmouse->private = kzalloc(sizeof(struct trackpoint_data), GFP_KERNEL);
if (!psmouse->private)
return -ENOMEM;
psmouse->vendor = "IBM";
psmouse->name = "TrackPoint";
psmouse->reconnect = trackpoint_reconnect;
psmouse->disconnect = trackpoint_disconnect;
if ((button_info & 0x0f) >= 3)
__set_bit(BTN_MIDDLE, psmouse->dev->keybit);
trackpoint_defaults(psmouse->private);
error = trackpoint_power_on_reset(&psmouse->ps2dev);
/* Write defaults to TP only if reset fails. */
if (error)
trackpoint_sync(psmouse, false);
error = sysfs_create_group(&ps2dev->serio->dev.kobj, &trackpoint_attr_group);
if (error) {
psmouse_err(psmouse,
"failed to create sysfs attributes, error: %d\n",
error);
kfree(psmouse->private);
psmouse->private = NULL;
return -1;
}
psmouse_info(psmouse,
"IBM TrackPoint firmware: 0x%02x, buttons: %d/%d\n",
firmware_id,
(button_info & 0xf0) >> 4, button_info & 0x0f);
return 0;
}
| gpl-2.0 |
peremen/gzone_ics_kernel | drivers/pci/hotplug/pciehp_hpc.c | 2695 | 24060 | /*
* PCI Express PCI Hot Plug Driver
*
* Copyright (C) 1995,2001 Compaq Computer Corporation
* Copyright (C) 2001 Greg Kroah-Hartman (greg@kroah.com)
* Copyright (C) 2001 IBM Corp.
* Copyright (C) 2003-2004 Intel Corporation
*
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; 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, GOOD TITLE or
* NON INFRINGEMENT. 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.
*
* Send feedback to <greg@kroah.com>,<kristen.c.accardi@intel.com>
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/signal.h>
#include <linux/jiffies.h>
#include <linux/timer.h>
#include <linux/pci.h>
#include <linux/interrupt.h>
#include <linux/time.h>
#include <linux/slab.h>
#include "../pci.h"
#include "pciehp.h"
static inline int pciehp_readw(struct controller *ctrl, int reg, u16 *value)
{
struct pci_dev *dev = ctrl->pcie->port;
return pci_read_config_word(dev, pci_pcie_cap(dev) + reg, value);
}
static inline int pciehp_readl(struct controller *ctrl, int reg, u32 *value)
{
struct pci_dev *dev = ctrl->pcie->port;
return pci_read_config_dword(dev, pci_pcie_cap(dev) + reg, value);
}
static inline int pciehp_writew(struct controller *ctrl, int reg, u16 value)
{
struct pci_dev *dev = ctrl->pcie->port;
return pci_write_config_word(dev, pci_pcie_cap(dev) + reg, value);
}
static inline int pciehp_writel(struct controller *ctrl, int reg, u32 value)
{
struct pci_dev *dev = ctrl->pcie->port;
return pci_write_config_dword(dev, pci_pcie_cap(dev) + reg, value);
}
/* Power Control Command */
#define POWER_ON 0
#define POWER_OFF PCI_EXP_SLTCTL_PCC
static irqreturn_t pcie_isr(int irq, void *dev_id);
static void start_int_poll_timer(struct controller *ctrl, int sec);
/* This is the interrupt polling timeout function. */
static void int_poll_timeout(unsigned long data)
{
struct controller *ctrl = (struct controller *)data;
/* Poll for interrupt events. regs == NULL => polling */
pcie_isr(0, ctrl);
init_timer(&ctrl->poll_timer);
if (!pciehp_poll_time)
pciehp_poll_time = 2; /* default polling interval is 2 sec */
start_int_poll_timer(ctrl, pciehp_poll_time);
}
/* This function starts the interrupt polling timer. */
static void start_int_poll_timer(struct controller *ctrl, int sec)
{
/* Clamp to sane value */
if ((sec <= 0) || (sec > 60))
sec = 2;
ctrl->poll_timer.function = &int_poll_timeout;
ctrl->poll_timer.data = (unsigned long)ctrl;
ctrl->poll_timer.expires = jiffies + sec * HZ;
add_timer(&ctrl->poll_timer);
}
static inline int pciehp_request_irq(struct controller *ctrl)
{
int retval, irq = ctrl->pcie->irq;
/* Install interrupt polling timer. Start with 10 sec delay */
if (pciehp_poll_mode) {
init_timer(&ctrl->poll_timer);
start_int_poll_timer(ctrl, 10);
return 0;
}
/* Installs the interrupt handler */
retval = request_irq(irq, pcie_isr, IRQF_SHARED, MY_NAME, ctrl);
if (retval)
ctrl_err(ctrl, "Cannot get irq %d for the hotplug controller\n",
irq);
return retval;
}
static inline void pciehp_free_irq(struct controller *ctrl)
{
if (pciehp_poll_mode)
del_timer_sync(&ctrl->poll_timer);
else
free_irq(ctrl->pcie->irq, ctrl);
}
static int pcie_poll_cmd(struct controller *ctrl)
{
u16 slot_status;
int err, timeout = 1000;
err = pciehp_readw(ctrl, PCI_EXP_SLTSTA, &slot_status);
if (!err && (slot_status & PCI_EXP_SLTSTA_CC)) {
pciehp_writew(ctrl, PCI_EXP_SLTSTA, PCI_EXP_SLTSTA_CC);
return 1;
}
while (timeout > 0) {
msleep(10);
timeout -= 10;
err = pciehp_readw(ctrl, PCI_EXP_SLTSTA, &slot_status);
if (!err && (slot_status & PCI_EXP_SLTSTA_CC)) {
pciehp_writew(ctrl, PCI_EXP_SLTSTA, PCI_EXP_SLTSTA_CC);
return 1;
}
}
return 0; /* timeout */
}
static void pcie_wait_cmd(struct controller *ctrl, int poll)
{
unsigned int msecs = pciehp_poll_mode ? 2500 : 1000;
unsigned long timeout = msecs_to_jiffies(msecs);
int rc;
if (poll)
rc = pcie_poll_cmd(ctrl);
else
rc = wait_event_timeout(ctrl->queue, !ctrl->cmd_busy, timeout);
if (!rc)
ctrl_dbg(ctrl, "Command not completed in 1000 msec\n");
}
/**
* pcie_write_cmd - Issue controller command
* @ctrl: controller to which the command is issued
* @cmd: command value written to slot control register
* @mask: bitmask of slot control register to be modified
*/
static int pcie_write_cmd(struct controller *ctrl, u16 cmd, u16 mask)
{
int retval = 0;
u16 slot_status;
u16 slot_ctrl;
mutex_lock(&ctrl->ctrl_lock);
retval = pciehp_readw(ctrl, PCI_EXP_SLTSTA, &slot_status);
if (retval) {
ctrl_err(ctrl, "%s: Cannot read SLOTSTATUS register\n",
__func__);
goto out;
}
if (slot_status & PCI_EXP_SLTSTA_CC) {
if (!ctrl->no_cmd_complete) {
/*
* After 1 sec and CMD_COMPLETED still not set, just
* proceed forward to issue the next command according
* to spec. Just print out the error message.
*/
ctrl_dbg(ctrl, "CMD_COMPLETED not clear after 1 sec\n");
} else if (!NO_CMD_CMPL(ctrl)) {
/*
* This controller semms to notify of command completed
* event even though it supports none of power
* controller, attention led, power led and EMI.
*/
ctrl_dbg(ctrl, "Unexpected CMD_COMPLETED. Need to "
"wait for command completed event.\n");
ctrl->no_cmd_complete = 0;
} else {
ctrl_dbg(ctrl, "Unexpected CMD_COMPLETED. Maybe "
"the controller is broken.\n");
}
}
retval = pciehp_readw(ctrl, PCI_EXP_SLTCTL, &slot_ctrl);
if (retval) {
ctrl_err(ctrl, "%s: Cannot read SLOTCTRL register\n", __func__);
goto out;
}
slot_ctrl &= ~mask;
slot_ctrl |= (cmd & mask);
ctrl->cmd_busy = 1;
smp_mb();
retval = pciehp_writew(ctrl, PCI_EXP_SLTCTL, slot_ctrl);
if (retval)
ctrl_err(ctrl, "Cannot write to SLOTCTRL register\n");
/*
* Wait for command completion.
*/
if (!retval && !ctrl->no_cmd_complete) {
int poll = 0;
/*
* if hotplug interrupt is not enabled or command
* completed interrupt is not enabled, we need to poll
* command completed event.
*/
if (!(slot_ctrl & PCI_EXP_SLTCTL_HPIE) ||
!(slot_ctrl & PCI_EXP_SLTCTL_CCIE))
poll = 1;
pcie_wait_cmd(ctrl, poll);
}
out:
mutex_unlock(&ctrl->ctrl_lock);
return retval;
}
static inline int check_link_active(struct controller *ctrl)
{
u16 link_status;
if (pciehp_readw(ctrl, PCI_EXP_LNKSTA, &link_status))
return 0;
return !!(link_status & PCI_EXP_LNKSTA_DLLLA);
}
static void pcie_wait_link_active(struct controller *ctrl)
{
int timeout = 1000;
if (check_link_active(ctrl))
return;
while (timeout > 0) {
msleep(10);
timeout -= 10;
if (check_link_active(ctrl))
return;
}
ctrl_dbg(ctrl, "Data Link Layer Link Active not set in 1000 msec\n");
}
int pciehp_check_link_status(struct controller *ctrl)
{
u16 lnk_status;
int retval = 0;
/*
* Data Link Layer Link Active Reporting must be capable for
* hot-plug capable downstream port. But old controller might
* not implement it. In this case, we wait for 1000 ms.
*/
if (ctrl->link_active_reporting){
/* Wait for Data Link Layer Link Active bit to be set */
pcie_wait_link_active(ctrl);
/*
* We must wait for 100 ms after the Data Link Layer
* Link Active bit reads 1b before initiating a
* configuration access to the hot added device.
*/
msleep(100);
} else
msleep(1000);
retval = pciehp_readw(ctrl, PCI_EXP_LNKSTA, &lnk_status);
if (retval) {
ctrl_err(ctrl, "Cannot read LNKSTATUS register\n");
return retval;
}
ctrl_dbg(ctrl, "%s: lnk_status = %x\n", __func__, lnk_status);
if ((lnk_status & PCI_EXP_LNKSTA_LT) ||
!(lnk_status & PCI_EXP_LNKSTA_NLW)) {
ctrl_err(ctrl, "Link Training Error occurs \n");
retval = -1;
return retval;
}
return retval;
}
int pciehp_get_attention_status(struct slot *slot, u8 *status)
{
struct controller *ctrl = slot->ctrl;
u16 slot_ctrl;
u8 atten_led_state;
int retval = 0;
retval = pciehp_readw(ctrl, PCI_EXP_SLTCTL, &slot_ctrl);
if (retval) {
ctrl_err(ctrl, "%s: Cannot read SLOTCTRL register\n", __func__);
return retval;
}
ctrl_dbg(ctrl, "%s: SLOTCTRL %x, value read %x\n", __func__,
pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, slot_ctrl);
atten_led_state = (slot_ctrl & PCI_EXP_SLTCTL_AIC) >> 6;
switch (atten_led_state) {
case 0:
*status = 0xFF; /* Reserved */
break;
case 1:
*status = 1; /* On */
break;
case 2:
*status = 2; /* Blink */
break;
case 3:
*status = 0; /* Off */
break;
default:
*status = 0xFF;
break;
}
return 0;
}
int pciehp_get_power_status(struct slot *slot, u8 *status)
{
struct controller *ctrl = slot->ctrl;
u16 slot_ctrl;
u8 pwr_state;
int retval = 0;
retval = pciehp_readw(ctrl, PCI_EXP_SLTCTL, &slot_ctrl);
if (retval) {
ctrl_err(ctrl, "%s: Cannot read SLOTCTRL register\n", __func__);
return retval;
}
ctrl_dbg(ctrl, "%s: SLOTCTRL %x value read %x\n", __func__,
pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, slot_ctrl);
pwr_state = (slot_ctrl & PCI_EXP_SLTCTL_PCC) >> 10;
switch (pwr_state) {
case 0:
*status = 1;
break;
case 1:
*status = 0;
break;
default:
*status = 0xFF;
break;
}
return retval;
}
int pciehp_get_latch_status(struct slot *slot, u8 *status)
{
struct controller *ctrl = slot->ctrl;
u16 slot_status;
int retval;
retval = pciehp_readw(ctrl, PCI_EXP_SLTSTA, &slot_status);
if (retval) {
ctrl_err(ctrl, "%s: Cannot read SLOTSTATUS register\n",
__func__);
return retval;
}
*status = !!(slot_status & PCI_EXP_SLTSTA_MRLSS);
return 0;
}
int pciehp_get_adapter_status(struct slot *slot, u8 *status)
{
struct controller *ctrl = slot->ctrl;
u16 slot_status;
int retval;
retval = pciehp_readw(ctrl, PCI_EXP_SLTSTA, &slot_status);
if (retval) {
ctrl_err(ctrl, "%s: Cannot read SLOTSTATUS register\n",
__func__);
return retval;
}
*status = !!(slot_status & PCI_EXP_SLTSTA_PDS);
return 0;
}
int pciehp_query_power_fault(struct slot *slot)
{
struct controller *ctrl = slot->ctrl;
u16 slot_status;
int retval;
retval = pciehp_readw(ctrl, PCI_EXP_SLTSTA, &slot_status);
if (retval) {
ctrl_err(ctrl, "Cannot check for power fault\n");
return retval;
}
return !!(slot_status & PCI_EXP_SLTSTA_PFD);
}
int pciehp_set_attention_status(struct slot *slot, u8 value)
{
struct controller *ctrl = slot->ctrl;
u16 slot_cmd;
u16 cmd_mask;
cmd_mask = PCI_EXP_SLTCTL_AIC;
switch (value) {
case 0 : /* turn off */
slot_cmd = 0x00C0;
break;
case 1: /* turn on */
slot_cmd = 0x0040;
break;
case 2: /* turn blink */
slot_cmd = 0x0080;
break;
default:
return -EINVAL;
}
ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__,
pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, slot_cmd);
return pcie_write_cmd(ctrl, slot_cmd, cmd_mask);
}
void pciehp_green_led_on(struct slot *slot)
{
struct controller *ctrl = slot->ctrl;
u16 slot_cmd;
u16 cmd_mask;
slot_cmd = 0x0100;
cmd_mask = PCI_EXP_SLTCTL_PIC;
pcie_write_cmd(ctrl, slot_cmd, cmd_mask);
ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__,
pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, slot_cmd);
}
void pciehp_green_led_off(struct slot *slot)
{
struct controller *ctrl = slot->ctrl;
u16 slot_cmd;
u16 cmd_mask;
slot_cmd = 0x0300;
cmd_mask = PCI_EXP_SLTCTL_PIC;
pcie_write_cmd(ctrl, slot_cmd, cmd_mask);
ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__,
pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, slot_cmd);
}
void pciehp_green_led_blink(struct slot *slot)
{
struct controller *ctrl = slot->ctrl;
u16 slot_cmd;
u16 cmd_mask;
slot_cmd = 0x0200;
cmd_mask = PCI_EXP_SLTCTL_PIC;
pcie_write_cmd(ctrl, slot_cmd, cmd_mask);
ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__,
pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, slot_cmd);
}
int pciehp_power_on_slot(struct slot * slot)
{
struct controller *ctrl = slot->ctrl;
u16 slot_cmd;
u16 cmd_mask;
u16 slot_status;
u16 lnk_status;
int retval = 0;
/* Clear sticky power-fault bit from previous power failures */
retval = pciehp_readw(ctrl, PCI_EXP_SLTSTA, &slot_status);
if (retval) {
ctrl_err(ctrl, "%s: Cannot read SLOTSTATUS register\n",
__func__);
return retval;
}
slot_status &= PCI_EXP_SLTSTA_PFD;
if (slot_status) {
retval = pciehp_writew(ctrl, PCI_EXP_SLTSTA, slot_status);
if (retval) {
ctrl_err(ctrl,
"%s: Cannot write to SLOTSTATUS register\n",
__func__);
return retval;
}
}
ctrl->power_fault_detected = 0;
slot_cmd = POWER_ON;
cmd_mask = PCI_EXP_SLTCTL_PCC;
retval = pcie_write_cmd(ctrl, slot_cmd, cmd_mask);
if (retval) {
ctrl_err(ctrl, "Write %x command failed!\n", slot_cmd);
return retval;
}
ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__,
pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, slot_cmd);
retval = pciehp_readw(ctrl, PCI_EXP_LNKSTA, &lnk_status);
if (retval) {
ctrl_err(ctrl, "%s: Cannot read LNKSTA register\n",
__func__);
return retval;
}
pcie_update_link_speed(ctrl->pcie->port->subordinate, lnk_status);
return retval;
}
int pciehp_power_off_slot(struct slot * slot)
{
struct controller *ctrl = slot->ctrl;
u16 slot_cmd;
u16 cmd_mask;
int retval;
slot_cmd = POWER_OFF;
cmd_mask = PCI_EXP_SLTCTL_PCC;
retval = pcie_write_cmd(ctrl, slot_cmd, cmd_mask);
if (retval) {
ctrl_err(ctrl, "Write command failed!\n");
return retval;
}
ctrl_dbg(ctrl, "%s: SLOTCTRL %x write cmd %x\n", __func__,
pci_pcie_cap(ctrl->pcie->port) + PCI_EXP_SLTCTL, slot_cmd);
return 0;
}
static irqreturn_t pcie_isr(int irq, void *dev_id)
{
struct controller *ctrl = (struct controller *)dev_id;
struct slot *slot = ctrl->slot;
u16 detected, intr_loc;
/*
* In order to guarantee that all interrupt events are
* serviced, we need to re-inspect Slot Status register after
* clearing what is presumed to be the last pending interrupt.
*/
intr_loc = 0;
do {
if (pciehp_readw(ctrl, PCI_EXP_SLTSTA, &detected)) {
ctrl_err(ctrl, "%s: Cannot read SLOTSTATUS\n",
__func__);
return IRQ_NONE;
}
detected &= (PCI_EXP_SLTSTA_ABP | PCI_EXP_SLTSTA_PFD |
PCI_EXP_SLTSTA_MRLSC | PCI_EXP_SLTSTA_PDC |
PCI_EXP_SLTSTA_CC);
detected &= ~intr_loc;
intr_loc |= detected;
if (!intr_loc)
return IRQ_NONE;
if (detected && pciehp_writew(ctrl, PCI_EXP_SLTSTA, intr_loc)) {
ctrl_err(ctrl, "%s: Cannot write to SLOTSTATUS\n",
__func__);
return IRQ_NONE;
}
} while (detected);
ctrl_dbg(ctrl, "%s: intr_loc %x\n", __func__, intr_loc);
/* Check Command Complete Interrupt Pending */
if (intr_loc & PCI_EXP_SLTSTA_CC) {
ctrl->cmd_busy = 0;
smp_mb();
wake_up(&ctrl->queue);
}
if (!(intr_loc & ~PCI_EXP_SLTSTA_CC))
return IRQ_HANDLED;
/* Check MRL Sensor Changed */
if (intr_loc & PCI_EXP_SLTSTA_MRLSC)
pciehp_handle_switch_change(slot);
/* Check Attention Button Pressed */
if (intr_loc & PCI_EXP_SLTSTA_ABP)
pciehp_handle_attention_button(slot);
/* Check Presence Detect Changed */
if (intr_loc & PCI_EXP_SLTSTA_PDC)
pciehp_handle_presence_change(slot);
/* Check Power Fault Detected */
if ((intr_loc & PCI_EXP_SLTSTA_PFD) && !ctrl->power_fault_detected) {
ctrl->power_fault_detected = 1;
pciehp_handle_power_fault(slot);
}
return IRQ_HANDLED;
}
int pciehp_get_max_lnk_width(struct slot *slot,
enum pcie_link_width *value)
{
struct controller *ctrl = slot->ctrl;
enum pcie_link_width lnk_wdth;
u32 lnk_cap;
int retval = 0;
retval = pciehp_readl(ctrl, PCI_EXP_LNKCAP, &lnk_cap);
if (retval) {
ctrl_err(ctrl, "%s: Cannot read LNKCAP register\n", __func__);
return retval;
}
switch ((lnk_cap & PCI_EXP_LNKSTA_NLW) >> 4){
case 0:
lnk_wdth = PCIE_LNK_WIDTH_RESRV;
break;
case 1:
lnk_wdth = PCIE_LNK_X1;
break;
case 2:
lnk_wdth = PCIE_LNK_X2;
break;
case 4:
lnk_wdth = PCIE_LNK_X4;
break;
case 8:
lnk_wdth = PCIE_LNK_X8;
break;
case 12:
lnk_wdth = PCIE_LNK_X12;
break;
case 16:
lnk_wdth = PCIE_LNK_X16;
break;
case 32:
lnk_wdth = PCIE_LNK_X32;
break;
default:
lnk_wdth = PCIE_LNK_WIDTH_UNKNOWN;
break;
}
*value = lnk_wdth;
ctrl_dbg(ctrl, "Max link width = %d\n", lnk_wdth);
return retval;
}
int pciehp_get_cur_lnk_width(struct slot *slot,
enum pcie_link_width *value)
{
struct controller *ctrl = slot->ctrl;
enum pcie_link_width lnk_wdth = PCIE_LNK_WIDTH_UNKNOWN;
int retval = 0;
u16 lnk_status;
retval = pciehp_readw(ctrl, PCI_EXP_LNKSTA, &lnk_status);
if (retval) {
ctrl_err(ctrl, "%s: Cannot read LNKSTATUS register\n",
__func__);
return retval;
}
switch ((lnk_status & PCI_EXP_LNKSTA_NLW) >> 4){
case 0:
lnk_wdth = PCIE_LNK_WIDTH_RESRV;
break;
case 1:
lnk_wdth = PCIE_LNK_X1;
break;
case 2:
lnk_wdth = PCIE_LNK_X2;
break;
case 4:
lnk_wdth = PCIE_LNK_X4;
break;
case 8:
lnk_wdth = PCIE_LNK_X8;
break;
case 12:
lnk_wdth = PCIE_LNK_X12;
break;
case 16:
lnk_wdth = PCIE_LNK_X16;
break;
case 32:
lnk_wdth = PCIE_LNK_X32;
break;
default:
lnk_wdth = PCIE_LNK_WIDTH_UNKNOWN;
break;
}
*value = lnk_wdth;
ctrl_dbg(ctrl, "Current link width = %d\n", lnk_wdth);
return retval;
}
int pcie_enable_notification(struct controller *ctrl)
{
u16 cmd, mask;
/*
* TBD: Power fault detected software notification support.
*
* Power fault detected software notification is not enabled
* now, because it caused power fault detected interrupt storm
* on some machines. On those machines, power fault detected
* bit in the slot status register was set again immediately
* when it is cleared in the interrupt service routine, and
* next power fault detected interrupt was notified again.
*/
cmd = PCI_EXP_SLTCTL_PDCE;
if (ATTN_BUTTN(ctrl))
cmd |= PCI_EXP_SLTCTL_ABPE;
if (MRL_SENS(ctrl))
cmd |= PCI_EXP_SLTCTL_MRLSCE;
if (!pciehp_poll_mode)
cmd |= PCI_EXP_SLTCTL_HPIE | PCI_EXP_SLTCTL_CCIE;
mask = (PCI_EXP_SLTCTL_PDCE | PCI_EXP_SLTCTL_ABPE |
PCI_EXP_SLTCTL_MRLSCE | PCI_EXP_SLTCTL_PFDE |
PCI_EXP_SLTCTL_HPIE | PCI_EXP_SLTCTL_CCIE);
if (pcie_write_cmd(ctrl, cmd, mask)) {
ctrl_err(ctrl, "Cannot enable software notification\n");
return -1;
}
return 0;
}
static void pcie_disable_notification(struct controller *ctrl)
{
u16 mask;
mask = (PCI_EXP_SLTCTL_PDCE | PCI_EXP_SLTCTL_ABPE |
PCI_EXP_SLTCTL_MRLSCE | PCI_EXP_SLTCTL_PFDE |
PCI_EXP_SLTCTL_HPIE | PCI_EXP_SLTCTL_CCIE |
PCI_EXP_SLTCTL_DLLSCE);
if (pcie_write_cmd(ctrl, 0, mask))
ctrl_warn(ctrl, "Cannot disable software notification\n");
}
int pcie_init_notification(struct controller *ctrl)
{
if (pciehp_request_irq(ctrl))
return -1;
if (pcie_enable_notification(ctrl)) {
pciehp_free_irq(ctrl);
return -1;
}
ctrl->notification_enabled = 1;
return 0;
}
static void pcie_shutdown_notification(struct controller *ctrl)
{
if (ctrl->notification_enabled) {
pcie_disable_notification(ctrl);
pciehp_free_irq(ctrl);
ctrl->notification_enabled = 0;
}
}
static int pcie_init_slot(struct controller *ctrl)
{
struct slot *slot;
slot = kzalloc(sizeof(*slot), GFP_KERNEL);
if (!slot)
return -ENOMEM;
slot->ctrl = ctrl;
mutex_init(&slot->lock);
INIT_DELAYED_WORK(&slot->work, pciehp_queue_pushbutton_work);
ctrl->slot = slot;
return 0;
}
static void pcie_cleanup_slot(struct controller *ctrl)
{
struct slot *slot = ctrl->slot;
cancel_delayed_work(&slot->work);
flush_workqueue(pciehp_wq);
flush_workqueue(pciehp_ordered_wq);
kfree(slot);
}
static inline void dbg_ctrl(struct controller *ctrl)
{
int i;
u16 reg16;
struct pci_dev *pdev = ctrl->pcie->port;
if (!pciehp_debug)
return;
ctrl_info(ctrl, "Hotplug Controller:\n");
ctrl_info(ctrl, " Seg/Bus/Dev/Func/IRQ : %s IRQ %d\n",
pci_name(pdev), pdev->irq);
ctrl_info(ctrl, " Vendor ID : 0x%04x\n", pdev->vendor);
ctrl_info(ctrl, " Device ID : 0x%04x\n", pdev->device);
ctrl_info(ctrl, " Subsystem ID : 0x%04x\n",
pdev->subsystem_device);
ctrl_info(ctrl, " Subsystem Vendor ID : 0x%04x\n",
pdev->subsystem_vendor);
ctrl_info(ctrl, " PCIe Cap offset : 0x%02x\n",
pci_pcie_cap(pdev));
for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
if (!pci_resource_len(pdev, i))
continue;
ctrl_info(ctrl, " PCI resource [%d] : %pR\n",
i, &pdev->resource[i]);
}
ctrl_info(ctrl, "Slot Capabilities : 0x%08x\n", ctrl->slot_cap);
ctrl_info(ctrl, " Physical Slot Number : %d\n", PSN(ctrl));
ctrl_info(ctrl, " Attention Button : %3s\n",
ATTN_BUTTN(ctrl) ? "yes" : "no");
ctrl_info(ctrl, " Power Controller : %3s\n",
POWER_CTRL(ctrl) ? "yes" : "no");
ctrl_info(ctrl, " MRL Sensor : %3s\n",
MRL_SENS(ctrl) ? "yes" : "no");
ctrl_info(ctrl, " Attention Indicator : %3s\n",
ATTN_LED(ctrl) ? "yes" : "no");
ctrl_info(ctrl, " Power Indicator : %3s\n",
PWR_LED(ctrl) ? "yes" : "no");
ctrl_info(ctrl, " Hot-Plug Surprise : %3s\n",
HP_SUPR_RM(ctrl) ? "yes" : "no");
ctrl_info(ctrl, " EMI Present : %3s\n",
EMI(ctrl) ? "yes" : "no");
ctrl_info(ctrl, " Command Completed : %3s\n",
NO_CMD_CMPL(ctrl) ? "no" : "yes");
pciehp_readw(ctrl, PCI_EXP_SLTSTA, ®16);
ctrl_info(ctrl, "Slot Status : 0x%04x\n", reg16);
pciehp_readw(ctrl, PCI_EXP_SLTCTL, ®16);
ctrl_info(ctrl, "Slot Control : 0x%04x\n", reg16);
}
struct controller *pcie_init(struct pcie_device *dev)
{
struct controller *ctrl;
u32 slot_cap, link_cap;
struct pci_dev *pdev = dev->port;
ctrl = kzalloc(sizeof(*ctrl), GFP_KERNEL);
if (!ctrl) {
dev_err(&dev->device, "%s: Out of memory\n", __func__);
goto abort;
}
ctrl->pcie = dev;
if (!pci_pcie_cap(pdev)) {
ctrl_err(ctrl, "Cannot find PCI Express capability\n");
goto abort_ctrl;
}
if (pciehp_readl(ctrl, PCI_EXP_SLTCAP, &slot_cap)) {
ctrl_err(ctrl, "Cannot read SLOTCAP register\n");
goto abort_ctrl;
}
ctrl->slot_cap = slot_cap;
mutex_init(&ctrl->ctrl_lock);
init_waitqueue_head(&ctrl->queue);
dbg_ctrl(ctrl);
/*
* Controller doesn't notify of command completion if the "No
* Command Completed Support" bit is set in Slot Capability
* register or the controller supports none of power
* controller, attention led, power led and EMI.
*/
if (NO_CMD_CMPL(ctrl) ||
!(POWER_CTRL(ctrl) | ATTN_LED(ctrl) | PWR_LED(ctrl) | EMI(ctrl)))
ctrl->no_cmd_complete = 1;
/* Check if Data Link Layer Link Active Reporting is implemented */
if (pciehp_readl(ctrl, PCI_EXP_LNKCAP, &link_cap)) {
ctrl_err(ctrl, "%s: Cannot read LNKCAP register\n", __func__);
goto abort_ctrl;
}
if (link_cap & PCI_EXP_LNKCAP_DLLLARC) {
ctrl_dbg(ctrl, "Link Active Reporting supported\n");
ctrl->link_active_reporting = 1;
}
/* Clear all remaining event bits in Slot Status register */
if (pciehp_writew(ctrl, PCI_EXP_SLTSTA, 0x1f))
goto abort_ctrl;
/* Disable sotfware notification */
pcie_disable_notification(ctrl);
ctrl_info(ctrl, "HPC vendor_id %x device_id %x ss_vid %x ss_did %x\n",
pdev->vendor, pdev->device, pdev->subsystem_vendor,
pdev->subsystem_device);
if (pcie_init_slot(ctrl))
goto abort_ctrl;
return ctrl;
abort_ctrl:
kfree(ctrl);
abort:
return NULL;
}
void pciehp_release_ctrl(struct controller *ctrl)
{
pcie_shutdown_notification(ctrl);
pcie_cleanup_slot(ctrl);
kfree(ctrl);
}
| gpl-2.0 |
derekhe-hardware/huawei-g330d-u8825d-kernel | drivers/staging/speakup/devsynth.c | 2695 | 2029 | #include <linux/errno.h>
#include <linux/miscdevice.h> /* for misc_register, and SYNTH_MINOR */
#include <linux/types.h>
#include <linux/uaccess.h>
#include "speakup.h"
#include "spk_priv.h"
#ifndef SYNTH_MINOR
#define SYNTH_MINOR 25
#endif
static int misc_registered;
static int dev_opened;
static ssize_t speakup_file_write(struct file *fp, const char *buffer,
size_t nbytes, loff_t *ppos)
{
size_t count = nbytes;
const char *ptr = buffer;
int bytes;
unsigned long flags;
u_char buf[256];
if (synth == NULL)
return -ENODEV;
while (count > 0) {
bytes = min_t(size_t, count, sizeof(buf));
if (copy_from_user(buf, ptr, bytes))
return -EFAULT;
count -= bytes;
ptr += bytes;
spk_lock(flags);
synth_write(buf, bytes);
spk_unlock(flags);
}
return (ssize_t) nbytes;
}
static ssize_t speakup_file_read(struct file *fp, char *buf, size_t nbytes,
loff_t *ppos)
{
return 0;
}
static int speakup_file_open(struct inode *ip, struct file *fp)
{
if (synth == NULL)
return -ENODEV;
if (xchg(&dev_opened, 1))
return -EBUSY;
return 0;
}
static int speakup_file_release(struct inode *ip, struct file *fp)
{
dev_opened = 0;
return 0;
}
static const struct file_operations synth_fops = {
.read = speakup_file_read,
.write = speakup_file_write,
.open = speakup_file_open,
.release = speakup_file_release,
};
static struct miscdevice synth_device = {
.minor = SYNTH_MINOR,
.name = "synth",
.fops = &synth_fops,
};
void speakup_register_devsynth(void)
{
if (misc_registered != 0)
return;
/* zero it so if register fails, deregister will not ref invalid ptrs */
if (misc_register(&synth_device))
pr_warn("Couldn't initialize miscdevice /dev/synth.\n");
else {
pr_info("initialized device: /dev/synth, node (MAJOR %d, MINOR %d)\n",
MISC_MAJOR, SYNTH_MINOR);
misc_registered = 1;
}
}
void speakup_unregister_devsynth(void)
{
if (!misc_registered)
return;
pr_info("speakup: unregistering synth device /dev/synth\n");
misc_deregister(&synth_device);
misc_registered = 0;
}
| gpl-2.0 |
Shaky156/Shield-Tablet-CPU2.5Ghz-GPU060Mhz-Overclock | fs/lockd/clntlock.c | 4231 | 7682 | /*
* linux/fs/lockd/clntlock.c
*
* Lock handling for the client side NLM implementation
*
* Copyright (C) 1996, Olaf Kirch <okir@monad.swb.de>
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/time.h>
#include <linux/nfs_fs.h>
#include <linux/sunrpc/addr.h>
#include <linux/sunrpc/svc.h>
#include <linux/lockd/lockd.h>
#include <linux/kthread.h>
#define NLMDBG_FACILITY NLMDBG_CLIENT
/*
* Local function prototypes
*/
static int reclaimer(void *ptr);
/*
* The following functions handle blocking and granting from the
* client perspective.
*/
/*
* This is the representation of a blocked client lock.
*/
struct nlm_wait {
struct list_head b_list; /* linked list */
wait_queue_head_t b_wait; /* where to wait on */
struct nlm_host * b_host;
struct file_lock * b_lock; /* local file lock */
unsigned short b_reclaim; /* got to reclaim lock */
__be32 b_status; /* grant callback status */
};
static LIST_HEAD(nlm_blocked);
static DEFINE_SPINLOCK(nlm_blocked_lock);
/**
* nlmclnt_init - Set up per-NFS mount point lockd data structures
* @nlm_init: pointer to arguments structure
*
* Returns pointer to an appropriate nlm_host struct,
* or an ERR_PTR value.
*/
struct nlm_host *nlmclnt_init(const struct nlmclnt_initdata *nlm_init)
{
struct nlm_host *host;
u32 nlm_version = (nlm_init->nfs_version == 2) ? 1 : 4;
int status;
status = lockd_up(nlm_init->net);
if (status < 0)
return ERR_PTR(status);
host = nlmclnt_lookup_host(nlm_init->address, nlm_init->addrlen,
nlm_init->protocol, nlm_version,
nlm_init->hostname, nlm_init->noresvport,
nlm_init->net);
if (host == NULL)
goto out_nohost;
if (host->h_rpcclnt == NULL && nlm_bind_host(host) == NULL)
goto out_nobind;
return host;
out_nobind:
nlmclnt_release_host(host);
out_nohost:
lockd_down(nlm_init->net);
return ERR_PTR(-ENOLCK);
}
EXPORT_SYMBOL_GPL(nlmclnt_init);
/**
* nlmclnt_done - Release resources allocated by nlmclnt_init()
* @host: nlm_host structure reserved by nlmclnt_init()
*
*/
void nlmclnt_done(struct nlm_host *host)
{
struct net *net = host->net;
nlmclnt_release_host(host);
lockd_down(net);
}
EXPORT_SYMBOL_GPL(nlmclnt_done);
/*
* Queue up a lock for blocking so that the GRANTED request can see it
*/
struct nlm_wait *nlmclnt_prepare_block(struct nlm_host *host, struct file_lock *fl)
{
struct nlm_wait *block;
block = kmalloc(sizeof(*block), GFP_KERNEL);
if (block != NULL) {
block->b_host = host;
block->b_lock = fl;
init_waitqueue_head(&block->b_wait);
block->b_status = nlm_lck_blocked;
spin_lock(&nlm_blocked_lock);
list_add(&block->b_list, &nlm_blocked);
spin_unlock(&nlm_blocked_lock);
}
return block;
}
void nlmclnt_finish_block(struct nlm_wait *block)
{
if (block == NULL)
return;
spin_lock(&nlm_blocked_lock);
list_del(&block->b_list);
spin_unlock(&nlm_blocked_lock);
kfree(block);
}
/*
* Block on a lock
*/
int nlmclnt_block(struct nlm_wait *block, struct nlm_rqst *req, long timeout)
{
long ret;
/* A borken server might ask us to block even if we didn't
* request it. Just say no!
*/
if (block == NULL)
return -EAGAIN;
/* Go to sleep waiting for GRANT callback. Some servers seem
* to lose callbacks, however, so we're going to poll from
* time to time just to make sure.
*
* For now, the retry frequency is pretty high; normally
* a 1 minute timeout would do. See the comment before
* nlmclnt_lock for an explanation.
*/
ret = wait_event_interruptible_timeout(block->b_wait,
block->b_status != nlm_lck_blocked,
timeout);
if (ret < 0)
return -ERESTARTSYS;
/* Reset the lock status after a server reboot so we resend */
if (block->b_status == nlm_lck_denied_grace_period)
block->b_status = nlm_lck_blocked;
req->a_res.status = block->b_status;
return 0;
}
/*
* The server lockd has called us back to tell us the lock was granted
*/
__be32 nlmclnt_grant(const struct sockaddr *addr, const struct nlm_lock *lock)
{
const struct file_lock *fl = &lock->fl;
const struct nfs_fh *fh = &lock->fh;
struct nlm_wait *block;
__be32 res = nlm_lck_denied;
/*
* Look up blocked request based on arguments.
* Warning: must not use cookie to match it!
*/
spin_lock(&nlm_blocked_lock);
list_for_each_entry(block, &nlm_blocked, b_list) {
struct file_lock *fl_blocked = block->b_lock;
if (fl_blocked->fl_start != fl->fl_start)
continue;
if (fl_blocked->fl_end != fl->fl_end)
continue;
/*
* Careful! The NLM server will return the 32-bit "pid" that
* we put on the wire: in this case the lockowner "pid".
*/
if (fl_blocked->fl_u.nfs_fl.owner->pid != lock->svid)
continue;
if (!rpc_cmp_addr(nlm_addr(block->b_host), addr))
continue;
if (nfs_compare_fh(NFS_FH(file_inode(fl_blocked->fl_file)) ,fh) != 0)
continue;
/* Alright, we found a lock. Set the return status
* and wake up the caller
*/
block->b_status = nlm_granted;
wake_up(&block->b_wait);
res = nlm_granted;
}
spin_unlock(&nlm_blocked_lock);
return res;
}
/*
* The following procedures deal with the recovery of locks after a
* server crash.
*/
/*
* Reclaim all locks on server host. We do this by spawning a separate
* reclaimer thread.
*/
void
nlmclnt_recovery(struct nlm_host *host)
{
struct task_struct *task;
if (!host->h_reclaiming++) {
nlm_get_host(host);
task = kthread_run(reclaimer, host, "%s-reclaim", host->h_name);
if (IS_ERR(task))
printk(KERN_ERR "lockd: unable to spawn reclaimer "
"thread. Locks for %s won't be reclaimed! "
"(%ld)\n", host->h_name, PTR_ERR(task));
}
}
static int
reclaimer(void *ptr)
{
struct nlm_host *host = (struct nlm_host *) ptr;
struct nlm_wait *block;
struct nlm_rqst *req;
struct file_lock *fl, *next;
u32 nsmstate;
struct net *net = host->net;
req = kmalloc(sizeof(*req), GFP_KERNEL);
if (!req) {
printk(KERN_ERR "lockd: reclaimer unable to alloc memory."
" Locks for %s won't be reclaimed!\n",
host->h_name);
return 0;
}
allow_signal(SIGKILL);
down_write(&host->h_rwsem);
lockd_up(net); /* note: this cannot fail as lockd is already running */
dprintk("lockd: reclaiming locks for host %s\n", host->h_name);
restart:
nsmstate = host->h_nsmstate;
/* Force a portmap getport - the peer's lockd will
* most likely end up on a different port.
*/
host->h_nextrebind = jiffies;
nlm_rebind_host(host);
/* First, reclaim all locks that have been granted. */
list_splice_init(&host->h_granted, &host->h_reclaim);
list_for_each_entry_safe(fl, next, &host->h_reclaim, fl_u.nfs_fl.list) {
list_del_init(&fl->fl_u.nfs_fl.list);
/*
* sending this thread a SIGKILL will result in any unreclaimed
* locks being removed from the h_granted list. This means that
* the kernel will not attempt to reclaim them again if a new
* reclaimer thread is spawned for this host.
*/
if (signalled())
continue;
if (nlmclnt_reclaim(host, fl, req) != 0)
continue;
list_add_tail(&fl->fl_u.nfs_fl.list, &host->h_granted);
if (host->h_nsmstate != nsmstate) {
/* Argh! The server rebooted again! */
goto restart;
}
}
host->h_reclaiming = 0;
up_write(&host->h_rwsem);
dprintk("NLM: done reclaiming locks for host %s\n", host->h_name);
/* Now, wake up all processes that sleep on a blocked lock */
spin_lock(&nlm_blocked_lock);
list_for_each_entry(block, &nlm_blocked, b_list) {
if (block->b_host == host) {
block->b_status = nlm_lck_denied_grace_period;
wake_up(&block->b_wait);
}
}
spin_unlock(&nlm_blocked_lock);
/* Release host handle after use */
nlmclnt_release_host(host);
lockd_down(net);
kfree(req);
return 0;
}
| gpl-2.0 |
BrokenDev/kernel_samsung_msm8660-common | arch/arm/mach-omap2/opp4xxx_data.c | 7559 | 3742 | /*
* OMAP4 OPP table definitions.
*
* Copyright (C) 2010 Texas Instruments Incorporated - http://www.ti.com/
* Nishanth Menon
* Kevin Hilman
* Thara Gopinath
* Copyright (C) 2010-2011 Nokia Corporation.
* Eduardo Valentin
* Paul Walmsley
*
* 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 "as is" WITHOUT ANY WARRANTY of any
* kind, whether express or implied; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/module.h>
#include <plat/cpu.h>
#include "control.h"
#include "omap_opp_data.h"
#include "pm.h"
/*
* Structures containing OMAP4430 voltage supported and various
* voltage dependent data for each VDD.
*/
#define OMAP4430_VDD_MPU_OPP50_UV 1025000
#define OMAP4430_VDD_MPU_OPP100_UV 1200000
#define OMAP4430_VDD_MPU_OPPTURBO_UV 1313000
#define OMAP4430_VDD_MPU_OPPNITRO_UV 1375000
struct omap_volt_data omap44xx_vdd_mpu_volt_data[] = {
VOLT_DATA_DEFINE(OMAP4430_VDD_MPU_OPP50_UV, OMAP44XX_CONTROL_FUSE_MPU_OPP50, 0xf4, 0x0c),
VOLT_DATA_DEFINE(OMAP4430_VDD_MPU_OPP100_UV, OMAP44XX_CONTROL_FUSE_MPU_OPP100, 0xf9, 0x16),
VOLT_DATA_DEFINE(OMAP4430_VDD_MPU_OPPTURBO_UV, OMAP44XX_CONTROL_FUSE_MPU_OPPTURBO, 0xfa, 0x23),
VOLT_DATA_DEFINE(OMAP4430_VDD_MPU_OPPNITRO_UV, OMAP44XX_CONTROL_FUSE_MPU_OPPNITRO, 0xfa, 0x27),
VOLT_DATA_DEFINE(0, 0, 0, 0),
};
#define OMAP4430_VDD_IVA_OPP50_UV 1013000
#define OMAP4430_VDD_IVA_OPP100_UV 1188000
#define OMAP4430_VDD_IVA_OPPTURBO_UV 1300000
struct omap_volt_data omap44xx_vdd_iva_volt_data[] = {
VOLT_DATA_DEFINE(OMAP4430_VDD_IVA_OPP50_UV, OMAP44XX_CONTROL_FUSE_IVA_OPP50, 0xf4, 0x0c),
VOLT_DATA_DEFINE(OMAP4430_VDD_IVA_OPP100_UV, OMAP44XX_CONTROL_FUSE_IVA_OPP100, 0xf9, 0x16),
VOLT_DATA_DEFINE(OMAP4430_VDD_IVA_OPPTURBO_UV, OMAP44XX_CONTROL_FUSE_IVA_OPPTURBO, 0xfa, 0x23),
VOLT_DATA_DEFINE(0, 0, 0, 0),
};
#define OMAP4430_VDD_CORE_OPP50_UV 1025000
#define OMAP4430_VDD_CORE_OPP100_UV 1200000
struct omap_volt_data omap44xx_vdd_core_volt_data[] = {
VOLT_DATA_DEFINE(OMAP4430_VDD_CORE_OPP50_UV, OMAP44XX_CONTROL_FUSE_CORE_OPP50, 0xf4, 0x0c),
VOLT_DATA_DEFINE(OMAP4430_VDD_CORE_OPP100_UV, OMAP44XX_CONTROL_FUSE_CORE_OPP100, 0xf9, 0x16),
VOLT_DATA_DEFINE(0, 0, 0, 0),
};
static struct omap_opp_def __initdata omap44xx_opp_def_list[] = {
/* MPU OPP1 - OPP50 */
OPP_INITIALIZER("mpu", true, 300000000, OMAP4430_VDD_MPU_OPP50_UV),
/* MPU OPP2 - OPP100 */
OPP_INITIALIZER("mpu", true, 600000000, OMAP4430_VDD_MPU_OPP100_UV),
/* MPU OPP3 - OPP-Turbo */
OPP_INITIALIZER("mpu", true, 800000000, OMAP4430_VDD_MPU_OPPTURBO_UV),
/* MPU OPP4 - OPP-SB */
OPP_INITIALIZER("mpu", true, 1008000000, OMAP4430_VDD_MPU_OPPNITRO_UV),
/* L3 OPP1 - OPP50 */
OPP_INITIALIZER("l3_main_1", true, 100000000, OMAP4430_VDD_CORE_OPP50_UV),
/* L3 OPP2 - OPP100, OPP-Turbo, OPP-SB */
OPP_INITIALIZER("l3_main_1", true, 200000000, OMAP4430_VDD_CORE_OPP100_UV),
/* IVA OPP1 - OPP50 */
OPP_INITIALIZER("iva", true, 133000000, OMAP4430_VDD_IVA_OPP50_UV),
/* IVA OPP2 - OPP100 */
OPP_INITIALIZER("iva", true, 266100000, OMAP4430_VDD_IVA_OPP100_UV),
/* IVA OPP3 - OPP-Turbo */
OPP_INITIALIZER("iva", false, 332000000, OMAP4430_VDD_IVA_OPPTURBO_UV),
/* TODO: add DSP, aess, fdif, gpu */
};
/**
* omap4_opp_init() - initialize omap4 opp table
*/
int __init omap4_opp_init(void)
{
int r = -ENODEV;
if (!cpu_is_omap44xx())
return r;
r = omap_init_opp_table(omap44xx_opp_def_list,
ARRAY_SIZE(omap44xx_opp_def_list));
return r;
}
device_initcall(omap4_opp_init);
| gpl-2.0 |
JB1tz/kernel-msm | arch/arm/plat-versatile/fpga-irq.c | 7815 | 1601 | /*
* Support for Versatile FPGA-based IRQ controllers
*/
#include <linux/irq.h>
#include <linux/io.h>
#include <asm/mach/irq.h>
#include <plat/fpga-irq.h>
#define IRQ_STATUS 0x00
#define IRQ_RAW_STATUS 0x04
#define IRQ_ENABLE_SET 0x08
#define IRQ_ENABLE_CLEAR 0x0c
static void fpga_irq_mask(struct irq_data *d)
{
struct fpga_irq_data *f = irq_data_get_irq_chip_data(d);
u32 mask = 1 << (d->irq - f->irq_start);
writel(mask, f->base + IRQ_ENABLE_CLEAR);
}
static void fpga_irq_unmask(struct irq_data *d)
{
struct fpga_irq_data *f = irq_data_get_irq_chip_data(d);
u32 mask = 1 << (d->irq - f->irq_start);
writel(mask, f->base + IRQ_ENABLE_SET);
}
static void fpga_irq_handle(unsigned int irq, struct irq_desc *desc)
{
struct fpga_irq_data *f = irq_desc_get_handler_data(desc);
u32 status = readl(f->base + IRQ_STATUS);
if (status == 0) {
do_bad_IRQ(irq, desc);
return;
}
do {
irq = ffs(status) - 1;
status &= ~(1 << irq);
generic_handle_irq(irq + f->irq_start);
} while (status);
}
void __init fpga_irq_init(int parent_irq, u32 valid, struct fpga_irq_data *f)
{
unsigned int i;
f->chip.irq_ack = fpga_irq_mask;
f->chip.irq_mask = fpga_irq_mask;
f->chip.irq_unmask = fpga_irq_unmask;
if (parent_irq != -1) {
irq_set_handler_data(parent_irq, f);
irq_set_chained_handler(parent_irq, fpga_irq_handle);
}
for (i = 0; i < 32; i++) {
if (valid & (1 << i)) {
unsigned int irq = f->irq_start + i;
irq_set_chip_data(irq, f);
irq_set_chip_and_handler(irq, &f->chip,
handle_level_irq);
set_irq_flags(irq, IRQF_VALID | IRQF_PROBE);
}
}
}
| gpl-2.0 |
santod/google_kernel_m7_3.4.10-g1a25406 | drivers/net/wimax/i2400m/sdio-tx.c | 9095 | 5653 | /*
* Intel Wireless WiMAX Connection 2400m
* SDIO TX transaction backends
*
*
* Copyright (C) 2007-2008 Intel Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE 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.
*
*
* Intel Corporation <linux-wimax@intel.com>
* Dirk Brandewie <dirk.j.brandewie@intel.com>
* - Initial implementation
*
*
* Takes the TX messages in the i2400m's driver TX FIFO and sends them
* to the device until there are no more.
*
* If we fail sending the message, we just drop it. There isn't much
* we can do at this point. Most of the traffic is network, which has
* recovery methods for dropped packets.
*
* The SDIO functions are not atomic, so we can't run from the context
* where i2400m->bus_tx_kick() [i2400ms_bus_tx_kick()] is being called
* (some times atomic). Thus, the actual TX work is deferred to a
* workqueue.
*
* ROADMAP
*
* i2400ms_bus_tx_kick()
* i2400ms_tx_submit() [through workqueue]
*
* i2400m_tx_setup()
*
* i2400m_tx_release()
*/
#include <linux/mmc/sdio_func.h>
#include "i2400m-sdio.h"
#define D_SUBMODULE tx
#include "sdio-debug-levels.h"
/*
* Pull TX transations from the TX FIFO and send them to the device
* until there are no more.
*/
static
void i2400ms_tx_submit(struct work_struct *ws)
{
int result;
struct i2400ms *i2400ms = container_of(ws, struct i2400ms, tx_worker);
struct i2400m *i2400m = &i2400ms->i2400m;
struct sdio_func *func = i2400ms->func;
struct device *dev = &func->dev;
struct i2400m_msg_hdr *tx_msg;
size_t tx_msg_size;
d_fnstart(4, dev, "(i2400ms %p, i2400m %p)\n", i2400ms, i2400ms);
while (NULL != (tx_msg = i2400m_tx_msg_get(i2400m, &tx_msg_size))) {
d_printf(2, dev, "TX: submitting %zu bytes\n", tx_msg_size);
d_dump(5, dev, tx_msg, tx_msg_size);
sdio_claim_host(func);
result = sdio_memcpy_toio(func, 0, tx_msg, tx_msg_size);
sdio_release_host(func);
i2400m_tx_msg_sent(i2400m);
if (result < 0) {
dev_err(dev, "TX: cannot submit TX; tx_msg @%zu %zu B:"
" %d\n", (void *) tx_msg - i2400m->tx_buf,
tx_msg_size, result);
}
if (result == -ETIMEDOUT) {
i2400m_error_recovery(i2400m);
break;
}
d_printf(2, dev, "TX: %zub submitted\n", tx_msg_size);
}
d_fnend(4, dev, "(i2400ms %p) = void\n", i2400ms);
}
/*
* The generic driver notifies us that there is data ready for TX
*
* Schedule a run of i2400ms_tx_submit() to handle it.
*/
void i2400ms_bus_tx_kick(struct i2400m *i2400m)
{
struct i2400ms *i2400ms = container_of(i2400m, struct i2400ms, i2400m);
struct device *dev = &i2400ms->func->dev;
unsigned long flags;
d_fnstart(3, dev, "(i2400m %p) = void\n", i2400m);
/* schedule tx work, this is because tx may block, therefore
* it has to run in a thread context.
*/
spin_lock_irqsave(&i2400m->tx_lock, flags);
if (i2400ms->tx_workqueue != NULL)
queue_work(i2400ms->tx_workqueue, &i2400ms->tx_worker);
spin_unlock_irqrestore(&i2400m->tx_lock, flags);
d_fnend(3, dev, "(i2400m %p) = void\n", i2400m);
}
int i2400ms_tx_setup(struct i2400ms *i2400ms)
{
int result;
struct device *dev = &i2400ms->func->dev;
struct i2400m *i2400m = &i2400ms->i2400m;
struct workqueue_struct *tx_workqueue;
unsigned long flags;
d_fnstart(5, dev, "(i2400ms %p)\n", i2400ms);
INIT_WORK(&i2400ms->tx_worker, i2400ms_tx_submit);
snprintf(i2400ms->tx_wq_name, sizeof(i2400ms->tx_wq_name),
"%s-tx", i2400m->wimax_dev.name);
tx_workqueue =
create_singlethread_workqueue(i2400ms->tx_wq_name);
if (tx_workqueue == NULL) {
dev_err(dev, "TX: failed to create workqueue\n");
result = -ENOMEM;
} else
result = 0;
spin_lock_irqsave(&i2400m->tx_lock, flags);
i2400ms->tx_workqueue = tx_workqueue;
spin_unlock_irqrestore(&i2400m->tx_lock, flags);
d_fnend(5, dev, "(i2400ms %p) = %d\n", i2400ms, result);
return result;
}
void i2400ms_tx_release(struct i2400ms *i2400ms)
{
struct i2400m *i2400m = &i2400ms->i2400m;
struct workqueue_struct *tx_workqueue;
unsigned long flags;
tx_workqueue = i2400ms->tx_workqueue;
spin_lock_irqsave(&i2400m->tx_lock, flags);
i2400ms->tx_workqueue = NULL;
spin_unlock_irqrestore(&i2400m->tx_lock, flags);
if (tx_workqueue)
destroy_workqueue(tx_workqueue);
}
| gpl-2.0 |
jied83/kernel_back | drivers/media/dvb/frontends/stv0900_sw.c | 9095 | 51504 | /*
* stv0900_sw.c
*
* Driver for ST STV0900 satellite demodulator IC.
*
* Copyright (C) ST Microelectronics.
* Copyright (C) 2009 NetUP Inc.
* Copyright (C) 2009 Igor M. Liplianin <liplianin@netup.ru>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "stv0900.h"
#include "stv0900_reg.h"
#include "stv0900_priv.h"
s32 shiftx(s32 x, int demod, s32 shift)
{
if (demod == 1)
return x - shift;
return x;
}
int stv0900_check_signal_presence(struct stv0900_internal *intp,
enum fe_stv0900_demod_num demod)
{
s32 carr_offset,
agc2_integr,
max_carrier;
int no_signal = FALSE;
carr_offset = (stv0900_read_reg(intp, CFR2) << 8)
| stv0900_read_reg(intp, CFR1);
carr_offset = ge2comp(carr_offset, 16);
agc2_integr = (stv0900_read_reg(intp, AGC2I1) << 8)
| stv0900_read_reg(intp, AGC2I0);
max_carrier = intp->srch_range[demod] / 1000;
max_carrier += (max_carrier / 10);
max_carrier = 65536 * (max_carrier / 2);
max_carrier /= intp->mclk / 1000;
if (max_carrier > 0x4000)
max_carrier = 0x4000;
if ((agc2_integr > 0x2000)
|| (carr_offset > (2 * max_carrier))
|| (carr_offset < (-2 * max_carrier)))
no_signal = TRUE;
return no_signal;
}
static void stv0900_get_sw_loop_params(struct stv0900_internal *intp,
s32 *frequency_inc, s32 *sw_timeout,
s32 *steps,
enum fe_stv0900_demod_num demod)
{
s32 timeout, freq_inc, max_steps, srate, max_carrier;
enum fe_stv0900_search_standard standard;
srate = intp->symbol_rate[demod];
max_carrier = intp->srch_range[demod] / 1000;
max_carrier += max_carrier / 10;
standard = intp->srch_standard[demod];
max_carrier = 65536 * (max_carrier / 2);
max_carrier /= intp->mclk / 1000;
if (max_carrier > 0x4000)
max_carrier = 0x4000;
freq_inc = srate;
freq_inc /= intp->mclk >> 10;
freq_inc = freq_inc << 6;
switch (standard) {
case STV0900_SEARCH_DVBS1:
case STV0900_SEARCH_DSS:
freq_inc *= 3;
timeout = 20;
break;
case STV0900_SEARCH_DVBS2:
freq_inc *= 4;
timeout = 25;
break;
case STV0900_AUTO_SEARCH:
default:
freq_inc *= 3;
timeout = 25;
break;
}
freq_inc /= 100;
if ((freq_inc > max_carrier) || (freq_inc < 0))
freq_inc = max_carrier / 2;
timeout *= 27500;
if (srate > 0)
timeout /= srate / 1000;
if ((timeout > 100) || (timeout < 0))
timeout = 100;
max_steps = (max_carrier / freq_inc) + 1;
if ((max_steps > 100) || (max_steps < 0)) {
max_steps = 100;
freq_inc = max_carrier / max_steps;
}
*frequency_inc = freq_inc;
*sw_timeout = timeout;
*steps = max_steps;
}
static int stv0900_search_carr_sw_loop(struct stv0900_internal *intp,
s32 FreqIncr, s32 Timeout, int zigzag,
s32 MaxStep, enum fe_stv0900_demod_num demod)
{
int no_signal,
lock = FALSE;
s32 stepCpt,
freqOffset,
max_carrier;
max_carrier = intp->srch_range[demod] / 1000;
max_carrier += (max_carrier / 10);
max_carrier = 65536 * (max_carrier / 2);
max_carrier /= intp->mclk / 1000;
if (max_carrier > 0x4000)
max_carrier = 0x4000;
if (zigzag == TRUE)
freqOffset = 0;
else
freqOffset = -max_carrier + FreqIncr;
stepCpt = 0;
do {
stv0900_write_reg(intp, DMDISTATE, 0x1c);
stv0900_write_reg(intp, CFRINIT1, (freqOffset / 256) & 0xff);
stv0900_write_reg(intp, CFRINIT0, freqOffset & 0xff);
stv0900_write_reg(intp, DMDISTATE, 0x18);
stv0900_write_bits(intp, ALGOSWRST, 1);
if (intp->chip_id == 0x12) {
stv0900_write_bits(intp, RST_HWARE, 1);
stv0900_write_bits(intp, RST_HWARE, 0);
}
if (zigzag == TRUE) {
if (freqOffset >= 0)
freqOffset = -freqOffset - 2 * FreqIncr;
else
freqOffset = -freqOffset;
} else
freqOffset += + 2 * FreqIncr;
stepCpt++;
lock = stv0900_get_demod_lock(intp, demod, Timeout);
no_signal = stv0900_check_signal_presence(intp, demod);
} while ((lock == FALSE)
&& (no_signal == FALSE)
&& ((freqOffset - FreqIncr) < max_carrier)
&& ((freqOffset + FreqIncr) > -max_carrier)
&& (stepCpt < MaxStep));
stv0900_write_bits(intp, ALGOSWRST, 0);
return lock;
}
static int stv0900_sw_algo(struct stv0900_internal *intp,
enum fe_stv0900_demod_num demod)
{
int lock = FALSE,
no_signal,
zigzag;
s32 s2fw,
fqc_inc,
sft_stp_tout,
trial_cntr,
max_steps;
stv0900_get_sw_loop_params(intp, &fqc_inc, &sft_stp_tout,
&max_steps, demod);
switch (intp->srch_standard[demod]) {
case STV0900_SEARCH_DVBS1:
case STV0900_SEARCH_DSS:
if (intp->chip_id >= 0x20)
stv0900_write_reg(intp, CARFREQ, 0x3b);
else
stv0900_write_reg(intp, CARFREQ, 0xef);
stv0900_write_reg(intp, DMDCFGMD, 0x49);
zigzag = FALSE;
break;
case STV0900_SEARCH_DVBS2:
if (intp->chip_id >= 0x20)
stv0900_write_reg(intp, CORRELABS, 0x79);
else
stv0900_write_reg(intp, CORRELABS, 0x68);
stv0900_write_reg(intp, DMDCFGMD, 0x89);
zigzag = TRUE;
break;
case STV0900_AUTO_SEARCH:
default:
if (intp->chip_id >= 0x20) {
stv0900_write_reg(intp, CARFREQ, 0x3b);
stv0900_write_reg(intp, CORRELABS, 0x79);
} else {
stv0900_write_reg(intp, CARFREQ, 0xef);
stv0900_write_reg(intp, CORRELABS, 0x68);
}
stv0900_write_reg(intp, DMDCFGMD, 0xc9);
zigzag = FALSE;
break;
}
trial_cntr = 0;
do {
lock = stv0900_search_carr_sw_loop(intp,
fqc_inc,
sft_stp_tout,
zigzag,
max_steps,
demod);
no_signal = stv0900_check_signal_presence(intp, demod);
trial_cntr++;
if ((lock == TRUE)
|| (no_signal == TRUE)
|| (trial_cntr == 2)) {
if (intp->chip_id >= 0x20) {
stv0900_write_reg(intp, CARFREQ, 0x49);
stv0900_write_reg(intp, CORRELABS, 0x9e);
} else {
stv0900_write_reg(intp, CARFREQ, 0xed);
stv0900_write_reg(intp, CORRELABS, 0x88);
}
if ((stv0900_get_bits(intp, HEADER_MODE) ==
STV0900_DVBS2_FOUND) &&
(lock == TRUE)) {
msleep(sft_stp_tout);
s2fw = stv0900_get_bits(intp, FLYWHEEL_CPT);
if (s2fw < 0xd) {
msleep(sft_stp_tout);
s2fw = stv0900_get_bits(intp,
FLYWHEEL_CPT);
}
if (s2fw < 0xd) {
lock = FALSE;
if (trial_cntr < 2) {
if (intp->chip_id >= 0x20)
stv0900_write_reg(intp,
CORRELABS,
0x79);
else
stv0900_write_reg(intp,
CORRELABS,
0x68);
stv0900_write_reg(intp,
DMDCFGMD,
0x89);
}
}
}
}
} while ((lock == FALSE)
&& (trial_cntr < 2)
&& (no_signal == FALSE));
return lock;
}
static u32 stv0900_get_symbol_rate(struct stv0900_internal *intp,
u32 mclk,
enum fe_stv0900_demod_num demod)
{
s32 rem1, rem2, intval1, intval2, srate;
srate = (stv0900_get_bits(intp, SYMB_FREQ3) << 24) +
(stv0900_get_bits(intp, SYMB_FREQ2) << 16) +
(stv0900_get_bits(intp, SYMB_FREQ1) << 8) +
(stv0900_get_bits(intp, SYMB_FREQ0));
dprintk("lock: srate=%d r0=0x%x r1=0x%x r2=0x%x r3=0x%x \n",
srate, stv0900_get_bits(intp, SYMB_FREQ0),
stv0900_get_bits(intp, SYMB_FREQ1),
stv0900_get_bits(intp, SYMB_FREQ2),
stv0900_get_bits(intp, SYMB_FREQ3));
intval1 = (mclk) >> 16;
intval2 = (srate) >> 16;
rem1 = (mclk) % 0x10000;
rem2 = (srate) % 0x10000;
srate = (intval1 * intval2) +
((intval1 * rem2) >> 16) +
((intval2 * rem1) >> 16);
return srate;
}
static void stv0900_set_symbol_rate(struct stv0900_internal *intp,
u32 mclk, u32 srate,
enum fe_stv0900_demod_num demod)
{
u32 symb;
dprintk("%s: Mclk %d, SR %d, Dmd %d\n", __func__, mclk,
srate, demod);
if (srate > 60000000) {
symb = srate << 4;
symb /= (mclk >> 12);
} else if (srate > 6000000) {
symb = srate << 6;
symb /= (mclk >> 10);
} else {
symb = srate << 9;
symb /= (mclk >> 7);
}
stv0900_write_reg(intp, SFRINIT1, (symb >> 8) & 0x7f);
stv0900_write_reg(intp, SFRINIT1 + 1, (symb & 0xff));
}
static void stv0900_set_max_symbol_rate(struct stv0900_internal *intp,
u32 mclk, u32 srate,
enum fe_stv0900_demod_num demod)
{
u32 symb;
srate = 105 * (srate / 100);
if (srate > 60000000) {
symb = srate << 4;
symb /= (mclk >> 12);
} else if (srate > 6000000) {
symb = srate << 6;
symb /= (mclk >> 10);
} else {
symb = srate << 9;
symb /= (mclk >> 7);
}
if (symb < 0x7fff) {
stv0900_write_reg(intp, SFRUP1, (symb >> 8) & 0x7f);
stv0900_write_reg(intp, SFRUP1 + 1, (symb & 0xff));
} else {
stv0900_write_reg(intp, SFRUP1, 0x7f);
stv0900_write_reg(intp, SFRUP1 + 1, 0xff);
}
}
static void stv0900_set_min_symbol_rate(struct stv0900_internal *intp,
u32 mclk, u32 srate,
enum fe_stv0900_demod_num demod)
{
u32 symb;
srate = 95 * (srate / 100);
if (srate > 60000000) {
symb = srate << 4;
symb /= (mclk >> 12);
} else if (srate > 6000000) {
symb = srate << 6;
symb /= (mclk >> 10);
} else {
symb = srate << 9;
symb /= (mclk >> 7);
}
stv0900_write_reg(intp, SFRLOW1, (symb >> 8) & 0xff);
stv0900_write_reg(intp, SFRLOW1 + 1, (symb & 0xff));
}
static s32 stv0900_get_timing_offst(struct stv0900_internal *intp,
u32 srate,
enum fe_stv0900_demod_num demod)
{
s32 timingoffset;
timingoffset = (stv0900_read_reg(intp, TMGREG2) << 16) +
(stv0900_read_reg(intp, TMGREG2 + 1) << 8) +
(stv0900_read_reg(intp, TMGREG2 + 2));
timingoffset = ge2comp(timingoffset, 24);
if (timingoffset == 0)
timingoffset = 1;
timingoffset = ((s32)srate * 10) / ((s32)0x1000000 / timingoffset);
timingoffset /= 320;
return timingoffset;
}
static void stv0900_set_dvbs2_rolloff(struct stv0900_internal *intp,
enum fe_stv0900_demod_num demod)
{
s32 rolloff;
if (intp->chip_id == 0x10) {
stv0900_write_bits(intp, MANUALSX_ROLLOFF, 1);
rolloff = stv0900_read_reg(intp, MATSTR1) & 0x03;
stv0900_write_bits(intp, ROLLOFF_CONTROL, rolloff);
} else if (intp->chip_id <= 0x20)
stv0900_write_bits(intp, MANUALSX_ROLLOFF, 0);
else /* cut 3.0 */
stv0900_write_bits(intp, MANUALS2_ROLLOFF, 0);
}
static u32 stv0900_carrier_width(u32 srate, enum fe_stv0900_rolloff ro)
{
u32 rolloff;
switch (ro) {
case STV0900_20:
rolloff = 20;
break;
case STV0900_25:
rolloff = 25;
break;
case STV0900_35:
default:
rolloff = 35;
break;
}
return srate + (srate * rolloff) / 100;
}
static int stv0900_check_timing_lock(struct stv0900_internal *intp,
enum fe_stv0900_demod_num demod)
{
int timingLock = FALSE;
s32 i,
timingcpt = 0;
u8 car_freq,
tmg_th_high,
tmg_th_low;
car_freq = stv0900_read_reg(intp, CARFREQ);
tmg_th_high = stv0900_read_reg(intp, TMGTHRISE);
tmg_th_low = stv0900_read_reg(intp, TMGTHFALL);
stv0900_write_reg(intp, TMGTHRISE, 0x20);
stv0900_write_reg(intp, TMGTHFALL, 0x0);
stv0900_write_bits(intp, CFR_AUTOSCAN, 0);
stv0900_write_reg(intp, RTC, 0x80);
stv0900_write_reg(intp, RTCS2, 0x40);
stv0900_write_reg(intp, CARFREQ, 0x0);
stv0900_write_reg(intp, CFRINIT1, 0x0);
stv0900_write_reg(intp, CFRINIT0, 0x0);
stv0900_write_reg(intp, AGC2REF, 0x65);
stv0900_write_reg(intp, DMDISTATE, 0x18);
msleep(7);
for (i = 0; i < 10; i++) {
if (stv0900_get_bits(intp, TMGLOCK_QUALITY) >= 2)
timingcpt++;
msleep(1);
}
if (timingcpt >= 3)
timingLock = TRUE;
stv0900_write_reg(intp, AGC2REF, 0x38);
stv0900_write_reg(intp, RTC, 0x88);
stv0900_write_reg(intp, RTCS2, 0x68);
stv0900_write_reg(intp, CARFREQ, car_freq);
stv0900_write_reg(intp, TMGTHRISE, tmg_th_high);
stv0900_write_reg(intp, TMGTHFALL, tmg_th_low);
return timingLock;
}
static int stv0900_get_demod_cold_lock(struct dvb_frontend *fe,
s32 demod_timeout)
{
struct stv0900_state *state = fe->demodulator_priv;
struct stv0900_internal *intp = state->internal;
enum fe_stv0900_demod_num demod = state->demod;
int lock = FALSE,
d = demod;
s32 srate,
search_range,
locktimeout,
currier_step,
nb_steps,
current_step,
direction,
tuner_freq,
timeout,
freq;
srate = intp->symbol_rate[d];
search_range = intp->srch_range[d];
if (srate >= 10000000)
locktimeout = demod_timeout / 3;
else
locktimeout = demod_timeout / 2;
lock = stv0900_get_demod_lock(intp, d, locktimeout);
if (lock != FALSE)
return lock;
if (srate >= 10000000) {
if (stv0900_check_timing_lock(intp, d) == TRUE) {
stv0900_write_reg(intp, DMDISTATE, 0x1f);
stv0900_write_reg(intp, DMDISTATE, 0x15);
lock = stv0900_get_demod_lock(intp, d, demod_timeout);
} else
lock = FALSE;
return lock;
}
if (intp->chip_id <= 0x20) {
if (srate <= 1000000)
currier_step = 500;
else if (srate <= 4000000)
currier_step = 1000;
else if (srate <= 7000000)
currier_step = 2000;
else if (srate <= 10000000)
currier_step = 3000;
else
currier_step = 5000;
if (srate >= 2000000) {
timeout = (demod_timeout / 3);
if (timeout > 1000)
timeout = 1000;
} else
timeout = (demod_timeout / 2);
} else {
/*cut 3.0 */
currier_step = srate / 4000;
timeout = (demod_timeout * 3) / 4;
}
nb_steps = ((search_range / 1000) / currier_step);
if ((nb_steps % 2) != 0)
nb_steps += 1;
if (nb_steps <= 0)
nb_steps = 2;
else if (nb_steps > 12)
nb_steps = 12;
current_step = 1;
direction = 1;
if (intp->chip_id <= 0x20) {
tuner_freq = intp->freq[d];
intp->bw[d] = stv0900_carrier_width(intp->symbol_rate[d],
intp->rolloff) + intp->symbol_rate[d];
} else
tuner_freq = 0;
while ((current_step <= nb_steps) && (lock == FALSE)) {
if (direction > 0)
tuner_freq += (current_step * currier_step);
else
tuner_freq -= (current_step * currier_step);
if (intp->chip_id <= 0x20) {
if (intp->tuner_type[d] == 3)
stv0900_set_tuner_auto(intp, tuner_freq,
intp->bw[d], demod);
else
stv0900_set_tuner(fe, tuner_freq, intp->bw[d]);
stv0900_write_reg(intp, DMDISTATE, 0x1c);
stv0900_write_reg(intp, CFRINIT1, 0);
stv0900_write_reg(intp, CFRINIT0, 0);
stv0900_write_reg(intp, DMDISTATE, 0x1f);
stv0900_write_reg(intp, DMDISTATE, 0x15);
} else {
stv0900_write_reg(intp, DMDISTATE, 0x1c);
freq = (tuner_freq * 65536) / (intp->mclk / 1000);
stv0900_write_bits(intp, CFR_INIT1, MSB(freq));
stv0900_write_bits(intp, CFR_INIT0, LSB(freq));
stv0900_write_reg(intp, DMDISTATE, 0x1f);
stv0900_write_reg(intp, DMDISTATE, 0x05);
}
lock = stv0900_get_demod_lock(intp, d, timeout);
direction *= -1;
current_step++;
}
return lock;
}
static void stv0900_get_lock_timeout(s32 *demod_timeout, s32 *fec_timeout,
s32 srate,
enum fe_stv0900_search_algo algo)
{
switch (algo) {
case STV0900_BLIND_SEARCH:
if (srate <= 1500000) {
(*demod_timeout) = 1500;
(*fec_timeout) = 400;
} else if (srate <= 5000000) {
(*demod_timeout) = 1000;
(*fec_timeout) = 300;
} else {
(*demod_timeout) = 700;
(*fec_timeout) = 100;
}
break;
case STV0900_COLD_START:
case STV0900_WARM_START:
default:
if (srate <= 1000000) {
(*demod_timeout) = 3000;
(*fec_timeout) = 1700;
} else if (srate <= 2000000) {
(*demod_timeout) = 2500;
(*fec_timeout) = 1100;
} else if (srate <= 5000000) {
(*demod_timeout) = 1000;
(*fec_timeout) = 550;
} else if (srate <= 10000000) {
(*demod_timeout) = 700;
(*fec_timeout) = 250;
} else if (srate <= 20000000) {
(*demod_timeout) = 400;
(*fec_timeout) = 130;
} else {
(*demod_timeout) = 300;
(*fec_timeout) = 100;
}
break;
}
if (algo == STV0900_WARM_START)
(*demod_timeout) /= 2;
}
static void stv0900_set_viterbi_tracq(struct stv0900_internal *intp,
enum fe_stv0900_demod_num demod)
{
s32 vth_reg = VTH12;
dprintk("%s\n", __func__);
stv0900_write_reg(intp, vth_reg++, 0xd0);
stv0900_write_reg(intp, vth_reg++, 0x7d);
stv0900_write_reg(intp, vth_reg++, 0x53);
stv0900_write_reg(intp, vth_reg++, 0x2f);
stv0900_write_reg(intp, vth_reg++, 0x24);
stv0900_write_reg(intp, vth_reg++, 0x1f);
}
static void stv0900_set_viterbi_standard(struct stv0900_internal *intp,
enum fe_stv0900_search_standard standard,
enum fe_stv0900_fec fec,
enum fe_stv0900_demod_num demod)
{
dprintk("%s: ViterbiStandard = ", __func__);
switch (standard) {
case STV0900_AUTO_SEARCH:
dprintk("Auto\n");
stv0900_write_reg(intp, FECM, 0x10);
stv0900_write_reg(intp, PRVIT, 0x3f);
break;
case STV0900_SEARCH_DVBS1:
dprintk("DVBS1\n");
stv0900_write_reg(intp, FECM, 0x00);
switch (fec) {
case STV0900_FEC_UNKNOWN:
default:
stv0900_write_reg(intp, PRVIT, 0x2f);
break;
case STV0900_FEC_1_2:
stv0900_write_reg(intp, PRVIT, 0x01);
break;
case STV0900_FEC_2_3:
stv0900_write_reg(intp, PRVIT, 0x02);
break;
case STV0900_FEC_3_4:
stv0900_write_reg(intp, PRVIT, 0x04);
break;
case STV0900_FEC_5_6:
stv0900_write_reg(intp, PRVIT, 0x08);
break;
case STV0900_FEC_7_8:
stv0900_write_reg(intp, PRVIT, 0x20);
break;
}
break;
case STV0900_SEARCH_DSS:
dprintk("DSS\n");
stv0900_write_reg(intp, FECM, 0x80);
switch (fec) {
case STV0900_FEC_UNKNOWN:
default:
stv0900_write_reg(intp, PRVIT, 0x13);
break;
case STV0900_FEC_1_2:
stv0900_write_reg(intp, PRVIT, 0x01);
break;
case STV0900_FEC_2_3:
stv0900_write_reg(intp, PRVIT, 0x02);
break;
case STV0900_FEC_6_7:
stv0900_write_reg(intp, PRVIT, 0x10);
break;
}
break;
default:
break;
}
}
static enum fe_stv0900_fec stv0900_get_vit_fec(struct stv0900_internal *intp,
enum fe_stv0900_demod_num demod)
{
enum fe_stv0900_fec prate;
s32 rate_fld = stv0900_get_bits(intp, VIT_CURPUN);
switch (rate_fld) {
case 13:
prate = STV0900_FEC_1_2;
break;
case 18:
prate = STV0900_FEC_2_3;
break;
case 21:
prate = STV0900_FEC_3_4;
break;
case 24:
prate = STV0900_FEC_5_6;
break;
case 25:
prate = STV0900_FEC_6_7;
break;
case 26:
prate = STV0900_FEC_7_8;
break;
default:
prate = STV0900_FEC_UNKNOWN;
break;
}
return prate;
}
static void stv0900_set_dvbs1_track_car_loop(struct stv0900_internal *intp,
enum fe_stv0900_demod_num demod,
u32 srate)
{
if (intp->chip_id >= 0x30) {
if (srate >= 15000000) {
stv0900_write_reg(intp, ACLC, 0x2b);
stv0900_write_reg(intp, BCLC, 0x1a);
} else if ((srate >= 7000000) && (15000000 > srate)) {
stv0900_write_reg(intp, ACLC, 0x0c);
stv0900_write_reg(intp, BCLC, 0x1b);
} else if (srate < 7000000) {
stv0900_write_reg(intp, ACLC, 0x2c);
stv0900_write_reg(intp, BCLC, 0x1c);
}
} else { /*cut 2.0 and 1.x*/
stv0900_write_reg(intp, ACLC, 0x1a);
stv0900_write_reg(intp, BCLC, 0x09);
}
}
static void stv0900_track_optimization(struct dvb_frontend *fe)
{
struct stv0900_state *state = fe->demodulator_priv;
struct stv0900_internal *intp = state->internal;
enum fe_stv0900_demod_num demod = state->demod;
s32 srate,
pilots,
aclc,
freq1,
freq0,
i = 0,
timed,
timef,
blind_tun_sw = 0,
modulation;
enum fe_stv0900_rolloff rolloff;
enum fe_stv0900_modcode foundModcod;
dprintk("%s\n", __func__);
srate = stv0900_get_symbol_rate(intp, intp->mclk, demod);
srate += stv0900_get_timing_offst(intp, srate, demod);
switch (intp->result[demod].standard) {
case STV0900_DVBS1_STANDARD:
case STV0900_DSS_STANDARD:
dprintk("%s: found DVB-S or DSS\n", __func__);
if (intp->srch_standard[demod] == STV0900_AUTO_SEARCH) {
stv0900_write_bits(intp, DVBS1_ENABLE, 1);
stv0900_write_bits(intp, DVBS2_ENABLE, 0);
}
stv0900_write_bits(intp, ROLLOFF_CONTROL, intp->rolloff);
stv0900_write_bits(intp, MANUALSX_ROLLOFF, 1);
if (intp->chip_id < 0x30) {
stv0900_write_reg(intp, ERRCTRL1, 0x75);
break;
}
if (stv0900_get_vit_fec(intp, demod) == STV0900_FEC_1_2) {
stv0900_write_reg(intp, GAUSSR0, 0x98);
stv0900_write_reg(intp, CCIR0, 0x18);
} else {
stv0900_write_reg(intp, GAUSSR0, 0x18);
stv0900_write_reg(intp, CCIR0, 0x18);
}
stv0900_write_reg(intp, ERRCTRL1, 0x75);
break;
case STV0900_DVBS2_STANDARD:
dprintk("%s: found DVB-S2\n", __func__);
stv0900_write_bits(intp, DVBS1_ENABLE, 0);
stv0900_write_bits(intp, DVBS2_ENABLE, 1);
stv0900_write_reg(intp, ACLC, 0);
stv0900_write_reg(intp, BCLC, 0);
if (intp->result[demod].frame_len == STV0900_LONG_FRAME) {
foundModcod = stv0900_get_bits(intp, DEMOD_MODCOD);
pilots = stv0900_get_bits(intp, DEMOD_TYPE) & 0x01;
aclc = stv0900_get_optim_carr_loop(srate,
foundModcod,
pilots,
intp->chip_id);
if (foundModcod <= STV0900_QPSK_910)
stv0900_write_reg(intp, ACLC2S2Q, aclc);
else if (foundModcod <= STV0900_8PSK_910) {
stv0900_write_reg(intp, ACLC2S2Q, 0x2a);
stv0900_write_reg(intp, ACLC2S28, aclc);
}
if ((intp->demod_mode == STV0900_SINGLE) &&
(foundModcod > STV0900_8PSK_910)) {
if (foundModcod <= STV0900_16APSK_910) {
stv0900_write_reg(intp, ACLC2S2Q, 0x2a);
stv0900_write_reg(intp, ACLC2S216A,
aclc);
} else if (foundModcod <= STV0900_32APSK_910) {
stv0900_write_reg(intp, ACLC2S2Q, 0x2a);
stv0900_write_reg(intp, ACLC2S232A,
aclc);
}
}
} else {
modulation = intp->result[demod].modulation;
aclc = stv0900_get_optim_short_carr_loop(srate,
modulation, intp->chip_id);
if (modulation == STV0900_QPSK)
stv0900_write_reg(intp, ACLC2S2Q, aclc);
else if (modulation == STV0900_8PSK) {
stv0900_write_reg(intp, ACLC2S2Q, 0x2a);
stv0900_write_reg(intp, ACLC2S28, aclc);
} else if (modulation == STV0900_16APSK) {
stv0900_write_reg(intp, ACLC2S2Q, 0x2a);
stv0900_write_reg(intp, ACLC2S216A, aclc);
} else if (modulation == STV0900_32APSK) {
stv0900_write_reg(intp, ACLC2S2Q, 0x2a);
stv0900_write_reg(intp, ACLC2S232A, aclc);
}
}
if (intp->chip_id <= 0x11) {
if (intp->demod_mode != STV0900_SINGLE)
stv0900_activate_s2_modcod(intp, demod);
}
stv0900_write_reg(intp, ERRCTRL1, 0x67);
break;
case STV0900_UNKNOWN_STANDARD:
default:
dprintk("%s: found unknown standard\n", __func__);
stv0900_write_bits(intp, DVBS1_ENABLE, 1);
stv0900_write_bits(intp, DVBS2_ENABLE, 1);
break;
}
freq1 = stv0900_read_reg(intp, CFR2);
freq0 = stv0900_read_reg(intp, CFR1);
rolloff = stv0900_get_bits(intp, ROLLOFF_STATUS);
if (intp->srch_algo[demod] == STV0900_BLIND_SEARCH) {
stv0900_write_reg(intp, SFRSTEP, 0x00);
stv0900_write_bits(intp, SCAN_ENABLE, 0);
stv0900_write_bits(intp, CFR_AUTOSCAN, 0);
stv0900_write_reg(intp, TMGCFG2, 0xc1);
stv0900_set_symbol_rate(intp, intp->mclk, srate, demod);
blind_tun_sw = 1;
if (intp->result[demod].standard != STV0900_DVBS2_STANDARD)
stv0900_set_dvbs1_track_car_loop(intp, demod, srate);
}
if (intp->chip_id >= 0x20) {
if ((intp->srch_standard[demod] == STV0900_SEARCH_DVBS1) ||
(intp->srch_standard[demod] ==
STV0900_SEARCH_DSS) ||
(intp->srch_standard[demod] ==
STV0900_AUTO_SEARCH)) {
stv0900_write_reg(intp, VAVSRVIT, 0x0a);
stv0900_write_reg(intp, VITSCALE, 0x0);
}
}
if (intp->chip_id < 0x20)
stv0900_write_reg(intp, CARHDR, 0x08);
if (intp->chip_id == 0x10)
stv0900_write_reg(intp, CORRELEXP, 0x0a);
stv0900_write_reg(intp, AGC2REF, 0x38);
if ((intp->chip_id >= 0x20) ||
(blind_tun_sw == 1) ||
(intp->symbol_rate[demod] < 10000000)) {
stv0900_write_reg(intp, CFRINIT1, freq1);
stv0900_write_reg(intp, CFRINIT0, freq0);
intp->bw[demod] = stv0900_carrier_width(srate,
intp->rolloff) + 10000000;
if ((intp->chip_id >= 0x20) || (blind_tun_sw == 1)) {
if (intp->srch_algo[demod] != STV0900_WARM_START) {
if (intp->tuner_type[demod] == 3)
stv0900_set_tuner_auto(intp,
intp->freq[demod],
intp->bw[demod],
demod);
else
stv0900_set_bandwidth(fe,
intp->bw[demod]);
}
}
if ((intp->srch_algo[demod] == STV0900_BLIND_SEARCH) ||
(intp->symbol_rate[demod] < 10000000))
msleep(50);
else
msleep(5);
stv0900_get_lock_timeout(&timed, &timef, srate,
STV0900_WARM_START);
if (stv0900_get_demod_lock(intp, demod, timed / 2) == FALSE) {
stv0900_write_reg(intp, DMDISTATE, 0x1f);
stv0900_write_reg(intp, CFRINIT1, freq1);
stv0900_write_reg(intp, CFRINIT0, freq0);
stv0900_write_reg(intp, DMDISTATE, 0x18);
i = 0;
while ((stv0900_get_demod_lock(intp,
demod,
timed / 2) == FALSE) &&
(i <= 2)) {
stv0900_write_reg(intp, DMDISTATE, 0x1f);
stv0900_write_reg(intp, CFRINIT1, freq1);
stv0900_write_reg(intp, CFRINIT0, freq0);
stv0900_write_reg(intp, DMDISTATE, 0x18);
i++;
}
}
}
if (intp->chip_id >= 0x20)
stv0900_write_reg(intp, CARFREQ, 0x49);
if ((intp->result[demod].standard == STV0900_DVBS1_STANDARD) ||
(intp->result[demod].standard == STV0900_DSS_STANDARD))
stv0900_set_viterbi_tracq(intp, demod);
}
static int stv0900_get_fec_lock(struct stv0900_internal *intp,
enum fe_stv0900_demod_num demod, s32 time_out)
{
s32 timer = 0, lock = 0;
enum fe_stv0900_search_state dmd_state;
dprintk("%s\n", __func__);
dmd_state = stv0900_get_bits(intp, HEADER_MODE);
while ((timer < time_out) && (lock == 0)) {
switch (dmd_state) {
case STV0900_SEARCH:
case STV0900_PLH_DETECTED:
default:
lock = 0;
break;
case STV0900_DVBS2_FOUND:
lock = stv0900_get_bits(intp, PKTDELIN_LOCK);
break;
case STV0900_DVBS_FOUND:
lock = stv0900_get_bits(intp, LOCKEDVIT);
break;
}
if (lock == 0) {
msleep(10);
timer += 10;
}
}
if (lock)
dprintk("%s: DEMOD FEC LOCK OK\n", __func__);
else
dprintk("%s: DEMOD FEC LOCK FAIL\n", __func__);
return lock;
}
static int stv0900_wait_for_lock(struct stv0900_internal *intp,
enum fe_stv0900_demod_num demod,
s32 dmd_timeout, s32 fec_timeout)
{
s32 timer = 0, lock = 0;
dprintk("%s\n", __func__);
lock = stv0900_get_demod_lock(intp, demod, dmd_timeout);
if (lock)
lock = lock && stv0900_get_fec_lock(intp, demod, fec_timeout);
if (lock) {
lock = 0;
dprintk("%s: Timer = %d, time_out = %d\n",
__func__, timer, fec_timeout);
while ((timer < fec_timeout) && (lock == 0)) {
lock = stv0900_get_bits(intp, TSFIFO_LINEOK);
msleep(1);
timer++;
}
}
if (lock)
dprintk("%s: DEMOD LOCK OK\n", __func__);
else
dprintk("%s: DEMOD LOCK FAIL\n", __func__);
if (lock)
return TRUE;
else
return FALSE;
}
enum fe_stv0900_tracking_standard stv0900_get_standard(struct dvb_frontend *fe,
enum fe_stv0900_demod_num demod)
{
struct stv0900_state *state = fe->demodulator_priv;
struct stv0900_internal *intp = state->internal;
enum fe_stv0900_tracking_standard fnd_standard;
int hdr_mode = stv0900_get_bits(intp, HEADER_MODE);
switch (hdr_mode) {
case 2:
fnd_standard = STV0900_DVBS2_STANDARD;
break;
case 3:
if (stv0900_get_bits(intp, DSS_DVB) == 1)
fnd_standard = STV0900_DSS_STANDARD;
else
fnd_standard = STV0900_DVBS1_STANDARD;
break;
default:
fnd_standard = STV0900_UNKNOWN_STANDARD;
}
dprintk("%s: standard %d\n", __func__, fnd_standard);
return fnd_standard;
}
static s32 stv0900_get_carr_freq(struct stv0900_internal *intp, u32 mclk,
enum fe_stv0900_demod_num demod)
{
s32 derot,
rem1,
rem2,
intval1,
intval2;
derot = (stv0900_get_bits(intp, CAR_FREQ2) << 16) +
(stv0900_get_bits(intp, CAR_FREQ1) << 8) +
(stv0900_get_bits(intp, CAR_FREQ0));
derot = ge2comp(derot, 24);
intval1 = mclk >> 12;
intval2 = derot >> 12;
rem1 = mclk % 0x1000;
rem2 = derot % 0x1000;
derot = (intval1 * intval2) +
((intval1 * rem2) >> 12) +
((intval2 * rem1) >> 12);
return derot;
}
static u32 stv0900_get_tuner_freq(struct dvb_frontend *fe)
{
struct dvb_frontend_ops *frontend_ops = NULL;
struct dvb_tuner_ops *tuner_ops = NULL;
u32 freq = 0;
if (&fe->ops)
frontend_ops = &fe->ops;
if (&frontend_ops->tuner_ops)
tuner_ops = &frontend_ops->tuner_ops;
if (tuner_ops->get_frequency) {
if ((tuner_ops->get_frequency(fe, &freq)) < 0)
dprintk("%s: Invalid parameter\n", __func__);
else
dprintk("%s: Frequency=%d\n", __func__, freq);
}
return freq;
}
static enum
fe_stv0900_signal_type stv0900_get_signal_params(struct dvb_frontend *fe)
{
struct stv0900_state *state = fe->demodulator_priv;
struct stv0900_internal *intp = state->internal;
enum fe_stv0900_demod_num demod = state->demod;
enum fe_stv0900_signal_type range = STV0900_OUTOFRANGE;
struct stv0900_signal_info *result = &intp->result[demod];
s32 offsetFreq,
srate_offset;
int i = 0,
d = demod;
u8 timing;
msleep(5);
if (intp->srch_algo[d] == STV0900_BLIND_SEARCH) {
timing = stv0900_read_reg(intp, TMGREG2);
i = 0;
stv0900_write_reg(intp, SFRSTEP, 0x5c);
while ((i <= 50) && (timing != 0) && (timing != 0xff)) {
timing = stv0900_read_reg(intp, TMGREG2);
msleep(5);
i += 5;
}
}
result->standard = stv0900_get_standard(fe, d);
if (intp->tuner_type[demod] == 3)
result->frequency = stv0900_get_freq_auto(intp, d);
else
result->frequency = stv0900_get_tuner_freq(fe);
offsetFreq = stv0900_get_carr_freq(intp, intp->mclk, d) / 1000;
result->frequency += offsetFreq;
result->symbol_rate = stv0900_get_symbol_rate(intp, intp->mclk, d);
srate_offset = stv0900_get_timing_offst(intp, result->symbol_rate, d);
result->symbol_rate += srate_offset;
result->fec = stv0900_get_vit_fec(intp, d);
result->modcode = stv0900_get_bits(intp, DEMOD_MODCOD);
result->pilot = stv0900_get_bits(intp, DEMOD_TYPE) & 0x01;
result->frame_len = ((u32)stv0900_get_bits(intp, DEMOD_TYPE)) >> 1;
result->rolloff = stv0900_get_bits(intp, ROLLOFF_STATUS);
dprintk("%s: modcode=0x%x \n", __func__, result->modcode);
switch (result->standard) {
case STV0900_DVBS2_STANDARD:
result->spectrum = stv0900_get_bits(intp, SPECINV_DEMOD);
if (result->modcode <= STV0900_QPSK_910)
result->modulation = STV0900_QPSK;
else if (result->modcode <= STV0900_8PSK_910)
result->modulation = STV0900_8PSK;
else if (result->modcode <= STV0900_16APSK_910)
result->modulation = STV0900_16APSK;
else if (result->modcode <= STV0900_32APSK_910)
result->modulation = STV0900_32APSK;
else
result->modulation = STV0900_UNKNOWN;
break;
case STV0900_DVBS1_STANDARD:
case STV0900_DSS_STANDARD:
result->spectrum = stv0900_get_bits(intp, IQINV);
result->modulation = STV0900_QPSK;
break;
default:
break;
}
if ((intp->srch_algo[d] == STV0900_BLIND_SEARCH) ||
(intp->symbol_rate[d] < 10000000)) {
offsetFreq = result->frequency - intp->freq[d];
if (intp->tuner_type[demod] == 3)
intp->freq[d] = stv0900_get_freq_auto(intp, d);
else
intp->freq[d] = stv0900_get_tuner_freq(fe);
if (ABS(offsetFreq) <= ((intp->srch_range[d] / 2000) + 500))
range = STV0900_RANGEOK;
else if (ABS(offsetFreq) <=
(stv0900_carrier_width(result->symbol_rate,
result->rolloff) / 2000))
range = STV0900_RANGEOK;
} else if (ABS(offsetFreq) <= ((intp->srch_range[d] / 2000) + 500))
range = STV0900_RANGEOK;
dprintk("%s: range %d\n", __func__, range);
return range;
}
static enum
fe_stv0900_signal_type stv0900_dvbs1_acq_workaround(struct dvb_frontend *fe)
{
struct stv0900_state *state = fe->demodulator_priv;
struct stv0900_internal *intp = state->internal;
enum fe_stv0900_demod_num demod = state->demod;
enum fe_stv0900_signal_type signal_type = STV0900_NODATA;
s32 srate,
demod_timeout,
fec_timeout,
freq1,
freq0;
intp->result[demod].locked = FALSE;
if (stv0900_get_bits(intp, HEADER_MODE) == STV0900_DVBS_FOUND) {
srate = stv0900_get_symbol_rate(intp, intp->mclk, demod);
srate += stv0900_get_timing_offst(intp, srate, demod);
if (intp->srch_algo[demod] == STV0900_BLIND_SEARCH)
stv0900_set_symbol_rate(intp, intp->mclk, srate, demod);
stv0900_get_lock_timeout(&demod_timeout, &fec_timeout,
srate, STV0900_WARM_START);
freq1 = stv0900_read_reg(intp, CFR2);
freq0 = stv0900_read_reg(intp, CFR1);
stv0900_write_bits(intp, CFR_AUTOSCAN, 0);
stv0900_write_bits(intp, SPECINV_CONTROL,
STV0900_IQ_FORCE_SWAPPED);
stv0900_write_reg(intp, DMDISTATE, 0x1c);
stv0900_write_reg(intp, CFRINIT1, freq1);
stv0900_write_reg(intp, CFRINIT0, freq0);
stv0900_write_reg(intp, DMDISTATE, 0x18);
if (stv0900_wait_for_lock(intp, demod,
demod_timeout, fec_timeout) == TRUE) {
intp->result[demod].locked = TRUE;
signal_type = stv0900_get_signal_params(fe);
stv0900_track_optimization(fe);
} else {
stv0900_write_bits(intp, SPECINV_CONTROL,
STV0900_IQ_FORCE_NORMAL);
stv0900_write_reg(intp, DMDISTATE, 0x1c);
stv0900_write_reg(intp, CFRINIT1, freq1);
stv0900_write_reg(intp, CFRINIT0, freq0);
stv0900_write_reg(intp, DMDISTATE, 0x18);
if (stv0900_wait_for_lock(intp, demod,
demod_timeout, fec_timeout) == TRUE) {
intp->result[demod].locked = TRUE;
signal_type = stv0900_get_signal_params(fe);
stv0900_track_optimization(fe);
}
}
} else
intp->result[demod].locked = FALSE;
return signal_type;
}
static u16 stv0900_blind_check_agc2_min_level(struct stv0900_internal *intp,
enum fe_stv0900_demod_num demod)
{
u32 minagc2level = 0xffff,
agc2level,
init_freq, freq_step;
s32 i, j, nb_steps, direction;
dprintk("%s\n", __func__);
stv0900_write_reg(intp, AGC2REF, 0x38);
stv0900_write_bits(intp, SCAN_ENABLE, 0);
stv0900_write_bits(intp, CFR_AUTOSCAN, 0);
stv0900_write_bits(intp, AUTO_GUP, 1);
stv0900_write_bits(intp, AUTO_GLOW, 1);
stv0900_write_reg(intp, DMDT0M, 0x0);
stv0900_set_symbol_rate(intp, intp->mclk, 1000000, demod);
nb_steps = -1 + (intp->srch_range[demod] / 1000000);
nb_steps /= 2;
nb_steps = (2 * nb_steps) + 1;
if (nb_steps < 0)
nb_steps = 1;
direction = 1;
freq_step = (1000000 << 8) / (intp->mclk >> 8);
init_freq = 0;
for (i = 0; i < nb_steps; i++) {
if (direction > 0)
init_freq = init_freq + (freq_step * i);
else
init_freq = init_freq - (freq_step * i);
direction *= -1;
stv0900_write_reg(intp, DMDISTATE, 0x5C);
stv0900_write_reg(intp, CFRINIT1, (init_freq >> 8) & 0xff);
stv0900_write_reg(intp, CFRINIT0, init_freq & 0xff);
stv0900_write_reg(intp, DMDISTATE, 0x58);
msleep(10);
agc2level = 0;
for (j = 0; j < 10; j++)
agc2level += (stv0900_read_reg(intp, AGC2I1) << 8)
| stv0900_read_reg(intp, AGC2I0);
agc2level /= 10;
if (agc2level < minagc2level)
minagc2level = agc2level;
}
return (u16)minagc2level;
}
static u32 stv0900_search_srate_coarse(struct dvb_frontend *fe)
{
struct stv0900_state *state = fe->demodulator_priv;
struct stv0900_internal *intp = state->internal;
enum fe_stv0900_demod_num demod = state->demod;
int timing_lck = FALSE;
s32 i, timingcpt = 0,
direction = 1,
nb_steps,
current_step = 0,
tuner_freq;
u32 agc2_th,
coarse_srate = 0,
agc2_integr = 0,
currier_step = 1200;
if (intp->chip_id >= 0x30)
agc2_th = 0x2e00;
else
agc2_th = 0x1f00;
stv0900_write_bits(intp, DEMOD_MODE, 0x1f);
stv0900_write_reg(intp, TMGCFG, 0x12);
stv0900_write_reg(intp, TMGTHRISE, 0xf0);
stv0900_write_reg(intp, TMGTHFALL, 0xe0);
stv0900_write_bits(intp, SCAN_ENABLE, 1);
stv0900_write_bits(intp, CFR_AUTOSCAN, 1);
stv0900_write_reg(intp, SFRUP1, 0x83);
stv0900_write_reg(intp, SFRUP0, 0xc0);
stv0900_write_reg(intp, SFRLOW1, 0x82);
stv0900_write_reg(intp, SFRLOW0, 0xa0);
stv0900_write_reg(intp, DMDT0M, 0x0);
stv0900_write_reg(intp, AGC2REF, 0x50);
if (intp->chip_id >= 0x30) {
stv0900_write_reg(intp, CARFREQ, 0x99);
stv0900_write_reg(intp, SFRSTEP, 0x98);
} else if (intp->chip_id >= 0x20) {
stv0900_write_reg(intp, CARFREQ, 0x6a);
stv0900_write_reg(intp, SFRSTEP, 0x95);
} else {
stv0900_write_reg(intp, CARFREQ, 0xed);
stv0900_write_reg(intp, SFRSTEP, 0x73);
}
if (intp->symbol_rate[demod] <= 2000000)
currier_step = 1000;
else if (intp->symbol_rate[demod] <= 5000000)
currier_step = 2000;
else if (intp->symbol_rate[demod] <= 12000000)
currier_step = 3000;
else
currier_step = 5000;
nb_steps = -1 + ((intp->srch_range[demod] / 1000) / currier_step);
nb_steps /= 2;
nb_steps = (2 * nb_steps) + 1;
if (nb_steps < 0)
nb_steps = 1;
else if (nb_steps > 10) {
nb_steps = 11;
currier_step = (intp->srch_range[demod] / 1000) / 10;
}
current_step = 0;
direction = 1;
tuner_freq = intp->freq[demod];
while ((timing_lck == FALSE) && (current_step < nb_steps)) {
stv0900_write_reg(intp, DMDISTATE, 0x5f);
stv0900_write_bits(intp, DEMOD_MODE, 0);
msleep(50);
for (i = 0; i < 10; i++) {
if (stv0900_get_bits(intp, TMGLOCK_QUALITY) >= 2)
timingcpt++;
agc2_integr += (stv0900_read_reg(intp, AGC2I1) << 8) |
stv0900_read_reg(intp, AGC2I0);
}
agc2_integr /= 10;
coarse_srate = stv0900_get_symbol_rate(intp, intp->mclk, demod);
current_step++;
direction *= -1;
dprintk("lock: I2C_DEMOD_MODE_FIELD =0. Search started."
" tuner freq=%d agc2=0x%x srate_coarse=%d tmg_cpt=%d\n",
tuner_freq, agc2_integr, coarse_srate, timingcpt);
if ((timingcpt >= 5) &&
(agc2_integr < agc2_th) &&
(coarse_srate < 55000000) &&
(coarse_srate > 850000))
timing_lck = TRUE;
else if (current_step < nb_steps) {
if (direction > 0)
tuner_freq += (current_step * currier_step);
else
tuner_freq -= (current_step * currier_step);
if (intp->tuner_type[demod] == 3)
stv0900_set_tuner_auto(intp, tuner_freq,
intp->bw[demod], demod);
else
stv0900_set_tuner(fe, tuner_freq,
intp->bw[demod]);
}
}
if (timing_lck == FALSE)
coarse_srate = 0;
else
coarse_srate = stv0900_get_symbol_rate(intp, intp->mclk, demod);
return coarse_srate;
}
static u32 stv0900_search_srate_fine(struct dvb_frontend *fe)
{
struct stv0900_state *state = fe->demodulator_priv;
struct stv0900_internal *intp = state->internal;
enum fe_stv0900_demod_num demod = state->demod;
u32 coarse_srate,
coarse_freq,
symb,
symbmax,
symbmin,
symbcomp;
coarse_srate = stv0900_get_symbol_rate(intp, intp->mclk, demod);
if (coarse_srate > 3000000) {
symbmax = 13 * (coarse_srate / 10);
symbmax = (symbmax / 1000) * 65536;
symbmax /= (intp->mclk / 1000);
symbmin = 10 * (coarse_srate / 13);
symbmin = (symbmin / 1000)*65536;
symbmin /= (intp->mclk / 1000);
symb = (coarse_srate / 1000) * 65536;
symb /= (intp->mclk / 1000);
} else {
symbmax = 13 * (coarse_srate / 10);
symbmax = (symbmax / 100) * 65536;
symbmax /= (intp->mclk / 100);
symbmin = 10 * (coarse_srate / 14);
symbmin = (symbmin / 100) * 65536;
symbmin /= (intp->mclk / 100);
symb = (coarse_srate / 100) * 65536;
symb /= (intp->mclk / 100);
}
symbcomp = 13 * (coarse_srate / 10);
coarse_freq = (stv0900_read_reg(intp, CFR2) << 8)
| stv0900_read_reg(intp, CFR1);
if (symbcomp < intp->symbol_rate[demod])
coarse_srate = 0;
else {
stv0900_write_reg(intp, DMDISTATE, 0x1f);
stv0900_write_reg(intp, TMGCFG2, 0xc1);
stv0900_write_reg(intp, TMGTHRISE, 0x20);
stv0900_write_reg(intp, TMGTHFALL, 0x00);
stv0900_write_reg(intp, TMGCFG, 0xd2);
stv0900_write_bits(intp, CFR_AUTOSCAN, 0);
stv0900_write_reg(intp, AGC2REF, 0x38);
if (intp->chip_id >= 0x30)
stv0900_write_reg(intp, CARFREQ, 0x79);
else if (intp->chip_id >= 0x20)
stv0900_write_reg(intp, CARFREQ, 0x49);
else
stv0900_write_reg(intp, CARFREQ, 0xed);
stv0900_write_reg(intp, SFRUP1, (symbmax >> 8) & 0x7f);
stv0900_write_reg(intp, SFRUP0, (symbmax & 0xff));
stv0900_write_reg(intp, SFRLOW1, (symbmin >> 8) & 0x7f);
stv0900_write_reg(intp, SFRLOW0, (symbmin & 0xff));
stv0900_write_reg(intp, SFRINIT1, (symb >> 8) & 0xff);
stv0900_write_reg(intp, SFRINIT0, (symb & 0xff));
stv0900_write_reg(intp, DMDT0M, 0x20);
stv0900_write_reg(intp, CFRINIT1, (coarse_freq >> 8) & 0xff);
stv0900_write_reg(intp, CFRINIT0, coarse_freq & 0xff);
stv0900_write_reg(intp, DMDISTATE, 0x15);
}
return coarse_srate;
}
static int stv0900_blind_search_algo(struct dvb_frontend *fe)
{
struct stv0900_state *state = fe->demodulator_priv;
struct stv0900_internal *intp = state->internal;
enum fe_stv0900_demod_num demod = state->demod;
u8 k_ref_tmg,
k_ref_tmg_max,
k_ref_tmg_min;
u32 coarse_srate,
agc2_th;
int lock = FALSE,
coarse_fail = FALSE;
s32 demod_timeout = 500,
fec_timeout = 50,
fail_cpt,
i,
agc2_overflow;
u16 agc2_int;
u8 dstatus2;
dprintk("%s\n", __func__);
if (intp->chip_id < 0x20) {
k_ref_tmg_max = 233;
k_ref_tmg_min = 143;
} else {
k_ref_tmg_max = 110;
k_ref_tmg_min = 10;
}
if (intp->chip_id <= 0x20)
agc2_th = STV0900_BLIND_SEARCH_AGC2_TH;
else
agc2_th = STV0900_BLIND_SEARCH_AGC2_TH_CUT30;
agc2_int = stv0900_blind_check_agc2_min_level(intp, demod);
dprintk("%s agc2_int=%d agc2_th=%d \n", __func__, agc2_int, agc2_th);
if (agc2_int > agc2_th)
return FALSE;
if (intp->chip_id == 0x10)
stv0900_write_reg(intp, CORRELEXP, 0xaa);
if (intp->chip_id < 0x20)
stv0900_write_reg(intp, CARHDR, 0x55);
else
stv0900_write_reg(intp, CARHDR, 0x20);
if (intp->chip_id <= 0x20)
stv0900_write_reg(intp, CARCFG, 0xc4);
else
stv0900_write_reg(intp, CARCFG, 0x6);
stv0900_write_reg(intp, RTCS2, 0x44);
if (intp->chip_id >= 0x20) {
stv0900_write_reg(intp, EQUALCFG, 0x41);
stv0900_write_reg(intp, FFECFG, 0x41);
stv0900_write_reg(intp, VITSCALE, 0x82);
stv0900_write_reg(intp, VAVSRVIT, 0x0);
}
k_ref_tmg = k_ref_tmg_max;
do {
stv0900_write_reg(intp, KREFTMG, k_ref_tmg);
if (stv0900_search_srate_coarse(fe) != 0) {
coarse_srate = stv0900_search_srate_fine(fe);
if (coarse_srate != 0) {
stv0900_get_lock_timeout(&demod_timeout,
&fec_timeout,
coarse_srate,
STV0900_BLIND_SEARCH);
lock = stv0900_get_demod_lock(intp,
demod,
demod_timeout);
} else
lock = FALSE;
} else {
fail_cpt = 0;
agc2_overflow = 0;
for (i = 0; i < 10; i++) {
agc2_int = (stv0900_read_reg(intp, AGC2I1) << 8)
| stv0900_read_reg(intp, AGC2I0);
if (agc2_int >= 0xff00)
agc2_overflow++;
dstatus2 = stv0900_read_reg(intp, DSTATUS2);
if (((dstatus2 & 0x1) == 0x1) &&
((dstatus2 >> 7) == 1))
fail_cpt++;
}
if ((fail_cpt > 7) || (agc2_overflow > 7))
coarse_fail = TRUE;
lock = FALSE;
}
k_ref_tmg -= 30;
} while ((k_ref_tmg >= k_ref_tmg_min) &&
(lock == FALSE) &&
(coarse_fail == FALSE));
return lock;
}
static void stv0900_set_viterbi_acq(struct stv0900_internal *intp,
enum fe_stv0900_demod_num demod)
{
s32 vth_reg = VTH12;
dprintk("%s\n", __func__);
stv0900_write_reg(intp, vth_reg++, 0x96);
stv0900_write_reg(intp, vth_reg++, 0x64);
stv0900_write_reg(intp, vth_reg++, 0x36);
stv0900_write_reg(intp, vth_reg++, 0x23);
stv0900_write_reg(intp, vth_reg++, 0x1e);
stv0900_write_reg(intp, vth_reg++, 0x19);
}
static void stv0900_set_search_standard(struct stv0900_internal *intp,
enum fe_stv0900_demod_num demod)
{
dprintk("%s\n", __func__);
switch (intp->srch_standard[demod]) {
case STV0900_SEARCH_DVBS1:
dprintk("Search Standard = DVBS1\n");
break;
case STV0900_SEARCH_DSS:
dprintk("Search Standard = DSS\n");
case STV0900_SEARCH_DVBS2:
break;
dprintk("Search Standard = DVBS2\n");
case STV0900_AUTO_SEARCH:
default:
dprintk("Search Standard = AUTO\n");
break;
}
switch (intp->srch_standard[demod]) {
case STV0900_SEARCH_DVBS1:
case STV0900_SEARCH_DSS:
stv0900_write_bits(intp, DVBS1_ENABLE, 1);
stv0900_write_bits(intp, DVBS2_ENABLE, 0);
stv0900_write_bits(intp, STOP_CLKVIT, 0);
stv0900_set_dvbs1_track_car_loop(intp,
demod,
intp->symbol_rate[demod]);
stv0900_write_reg(intp, CAR2CFG, 0x22);
stv0900_set_viterbi_acq(intp, demod);
stv0900_set_viterbi_standard(intp,
intp->srch_standard[demod],
intp->fec[demod], demod);
break;
case STV0900_SEARCH_DVBS2:
stv0900_write_bits(intp, DVBS1_ENABLE, 0);
stv0900_write_bits(intp, DVBS2_ENABLE, 1);
stv0900_write_bits(intp, STOP_CLKVIT, 1);
stv0900_write_reg(intp, ACLC, 0x1a);
stv0900_write_reg(intp, BCLC, 0x09);
if (intp->chip_id <= 0x20) /*cut 1.x and 2.0*/
stv0900_write_reg(intp, CAR2CFG, 0x26);
else
stv0900_write_reg(intp, CAR2CFG, 0x66);
if (intp->demod_mode != STV0900_SINGLE) {
if (intp->chip_id <= 0x11)
stv0900_stop_all_s2_modcod(intp, demod);
else
stv0900_activate_s2_modcod(intp, demod);
} else
stv0900_activate_s2_modcod_single(intp, demod);
stv0900_set_viterbi_tracq(intp, demod);
break;
case STV0900_AUTO_SEARCH:
default:
stv0900_write_bits(intp, DVBS1_ENABLE, 1);
stv0900_write_bits(intp, DVBS2_ENABLE, 1);
stv0900_write_bits(intp, STOP_CLKVIT, 0);
stv0900_write_reg(intp, ACLC, 0x1a);
stv0900_write_reg(intp, BCLC, 0x09);
stv0900_set_dvbs1_track_car_loop(intp,
demod,
intp->symbol_rate[demod]);
if (intp->chip_id <= 0x20) /*cut 1.x and 2.0*/
stv0900_write_reg(intp, CAR2CFG, 0x26);
else
stv0900_write_reg(intp, CAR2CFG, 0x66);
if (intp->demod_mode != STV0900_SINGLE) {
if (intp->chip_id <= 0x11)
stv0900_stop_all_s2_modcod(intp, demod);
else
stv0900_activate_s2_modcod(intp, demod);
} else
stv0900_activate_s2_modcod_single(intp, demod);
stv0900_set_viterbi_tracq(intp, demod);
stv0900_set_viterbi_standard(intp,
intp->srch_standard[demod],
intp->fec[demod], demod);
break;
}
}
enum fe_stv0900_signal_type stv0900_algo(struct dvb_frontend *fe)
{
struct stv0900_state *state = fe->demodulator_priv;
struct stv0900_internal *intp = state->internal;
enum fe_stv0900_demod_num demod = state->demod;
s32 demod_timeout = 500, fec_timeout = 50;
s32 aq_power, agc1_power, i;
int lock = FALSE, low_sr = FALSE;
enum fe_stv0900_signal_type signal_type = STV0900_NOCARRIER;
enum fe_stv0900_search_algo algo;
int no_signal = FALSE;
dprintk("%s\n", __func__);
algo = intp->srch_algo[demod];
stv0900_write_bits(intp, RST_HWARE, 1);
stv0900_write_reg(intp, DMDISTATE, 0x5c);
if (intp->chip_id >= 0x20) {
if (intp->symbol_rate[demod] > 5000000)
stv0900_write_reg(intp, CORRELABS, 0x9e);
else
stv0900_write_reg(intp, CORRELABS, 0x82);
} else
stv0900_write_reg(intp, CORRELABS, 0x88);
stv0900_get_lock_timeout(&demod_timeout, &fec_timeout,
intp->symbol_rate[demod],
intp->srch_algo[demod]);
if (intp->srch_algo[demod] == STV0900_BLIND_SEARCH) {
intp->bw[demod] = 2 * 36000000;
stv0900_write_reg(intp, TMGCFG2, 0xc0);
stv0900_write_reg(intp, CORRELMANT, 0x70);
stv0900_set_symbol_rate(intp, intp->mclk, 1000000, demod);
} else {
stv0900_write_reg(intp, DMDT0M, 0x20);
stv0900_write_reg(intp, TMGCFG, 0xd2);
if (intp->symbol_rate[demod] < 2000000)
stv0900_write_reg(intp, CORRELMANT, 0x63);
else
stv0900_write_reg(intp, CORRELMANT, 0x70);
stv0900_write_reg(intp, AGC2REF, 0x38);
intp->bw[demod] =
stv0900_carrier_width(intp->symbol_rate[demod],
intp->rolloff);
if (intp->chip_id >= 0x20) {
stv0900_write_reg(intp, KREFTMG, 0x5a);
if (intp->srch_algo[demod] == STV0900_COLD_START) {
intp->bw[demod] += 10000000;
intp->bw[demod] *= 15;
intp->bw[demod] /= 10;
} else if (intp->srch_algo[demod] == STV0900_WARM_START)
intp->bw[demod] += 10000000;
} else {
stv0900_write_reg(intp, KREFTMG, 0xc1);
intp->bw[demod] += 10000000;
intp->bw[demod] *= 15;
intp->bw[demod] /= 10;
}
stv0900_write_reg(intp, TMGCFG2, 0xc1);
stv0900_set_symbol_rate(intp, intp->mclk,
intp->symbol_rate[demod], demod);
stv0900_set_max_symbol_rate(intp, intp->mclk,
intp->symbol_rate[demod], demod);
stv0900_set_min_symbol_rate(intp, intp->mclk,
intp->symbol_rate[demod], demod);
if (intp->symbol_rate[demod] >= 10000000)
low_sr = FALSE;
else
low_sr = TRUE;
}
if (intp->tuner_type[demod] == 3)
stv0900_set_tuner_auto(intp, intp->freq[demod],
intp->bw[demod], demod);
else
stv0900_set_tuner(fe, intp->freq[demod], intp->bw[demod]);
agc1_power = MAKEWORD(stv0900_get_bits(intp, AGCIQ_VALUE1),
stv0900_get_bits(intp, AGCIQ_VALUE0));
aq_power = 0;
if (agc1_power == 0) {
for (i = 0; i < 5; i++)
aq_power += (stv0900_get_bits(intp, POWER_I) +
stv0900_get_bits(intp, POWER_Q)) / 2;
aq_power /= 5;
}
if ((agc1_power == 0) && (aq_power < IQPOWER_THRESHOLD)) {
intp->result[demod].locked = FALSE;
signal_type = STV0900_NOAGC1;
dprintk("%s: NO AGC1, POWERI, POWERQ\n", __func__);
} else {
stv0900_write_bits(intp, SPECINV_CONTROL,
intp->srch_iq_inv[demod]);
if (intp->chip_id <= 0x20) /*cut 2.0*/
stv0900_write_bits(intp, MANUALSX_ROLLOFF, 1);
else /*cut 3.0*/
stv0900_write_bits(intp, MANUALS2_ROLLOFF, 1);
stv0900_set_search_standard(intp, demod);
if (intp->srch_algo[demod] != STV0900_BLIND_SEARCH)
stv0900_start_search(intp, demod);
}
if (signal_type == STV0900_NOAGC1)
return signal_type;
if (intp->chip_id == 0x12) {
stv0900_write_bits(intp, RST_HWARE, 0);
msleep(3);
stv0900_write_bits(intp, RST_HWARE, 1);
stv0900_write_bits(intp, RST_HWARE, 0);
}
if (algo == STV0900_BLIND_SEARCH)
lock = stv0900_blind_search_algo(fe);
else if (algo == STV0900_COLD_START)
lock = stv0900_get_demod_cold_lock(fe, demod_timeout);
else if (algo == STV0900_WARM_START)
lock = stv0900_get_demod_lock(intp, demod, demod_timeout);
if ((lock == FALSE) && (algo == STV0900_COLD_START)) {
if (low_sr == FALSE) {
if (stv0900_check_timing_lock(intp, demod) == TRUE)
lock = stv0900_sw_algo(intp, demod);
}
}
if (lock == TRUE)
signal_type = stv0900_get_signal_params(fe);
if ((lock == TRUE) && (signal_type == STV0900_RANGEOK)) {
stv0900_track_optimization(fe);
if (intp->chip_id <= 0x11) {
if ((stv0900_get_standard(fe, 0) ==
STV0900_DVBS1_STANDARD) &&
(stv0900_get_standard(fe, 1) ==
STV0900_DVBS1_STANDARD)) {
msleep(20);
stv0900_write_bits(intp, RST_HWARE, 0);
} else {
stv0900_write_bits(intp, RST_HWARE, 0);
msleep(3);
stv0900_write_bits(intp, RST_HWARE, 1);
stv0900_write_bits(intp, RST_HWARE, 0);
}
} else if (intp->chip_id >= 0x20) {
stv0900_write_bits(intp, RST_HWARE, 0);
msleep(3);
stv0900_write_bits(intp, RST_HWARE, 1);
stv0900_write_bits(intp, RST_HWARE, 0);
}
if (stv0900_wait_for_lock(intp, demod,
fec_timeout, fec_timeout) == TRUE) {
lock = TRUE;
intp->result[demod].locked = TRUE;
if (intp->result[demod].standard ==
STV0900_DVBS2_STANDARD) {
stv0900_set_dvbs2_rolloff(intp, demod);
stv0900_write_bits(intp, RESET_UPKO_COUNT, 1);
stv0900_write_bits(intp, RESET_UPKO_COUNT, 0);
stv0900_write_reg(intp, ERRCTRL1, 0x67);
} else {
stv0900_write_reg(intp, ERRCTRL1, 0x75);
}
stv0900_write_reg(intp, FBERCPT4, 0);
stv0900_write_reg(intp, ERRCTRL2, 0xc1);
} else {
lock = FALSE;
signal_type = STV0900_NODATA;
no_signal = stv0900_check_signal_presence(intp, demod);
intp->result[demod].locked = FALSE;
}
}
if ((signal_type != STV0900_NODATA) || (no_signal != FALSE))
return signal_type;
if (intp->chip_id > 0x11) {
intp->result[demod].locked = FALSE;
return signal_type;
}
if ((stv0900_get_bits(intp, HEADER_MODE) == STV0900_DVBS_FOUND) &&
(intp->srch_iq_inv[demod] <= STV0900_IQ_AUTO_NORMAL_FIRST))
signal_type = stv0900_dvbs1_acq_workaround(fe);
return signal_type;
}
| gpl-2.0 |
rcoscali/nethunter-kernel-samsung-tuna | arch/mips/vr41xx/common/siu.c | 12423 | 3400 | /*
* NEC VR4100 series SIU platform device.
*
* Copyright (C) 2007-2008 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/errno.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/platform_device.h>
#include <linux/serial_core.h>
#include <linux/irq.h>
#include <asm/cpu.h>
#include <asm/vr41xx/siu.h>
static unsigned int siu_type1_ports[SIU_PORTS_MAX] __initdata = {
PORT_VR41XX_SIU,
PORT_UNKNOWN,
};
static struct resource siu_type1_resource[] __initdata = {
{
.start = 0x0c000000,
.end = 0x0c00000a,
.flags = IORESOURCE_MEM,
},
{
.start = SIU_IRQ,
.end = SIU_IRQ,
.flags = IORESOURCE_IRQ,
},
};
static unsigned int siu_type2_ports[SIU_PORTS_MAX] __initdata = {
PORT_VR41XX_SIU,
PORT_VR41XX_DSIU,
};
static struct resource siu_type2_resource[] __initdata = {
{
.start = 0x0f000800,
.end = 0x0f00080a,
.flags = IORESOURCE_MEM,
},
{
.start = 0x0f000820,
.end = 0x0f000829,
.flags = IORESOURCE_MEM,
},
{
.start = SIU_IRQ,
.end = SIU_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = DSIU_IRQ,
.end = DSIU_IRQ,
.flags = IORESOURCE_IRQ,
},
};
static int __init vr41xx_siu_add(void)
{
struct platform_device *pdev;
struct resource *res;
unsigned int num;
int retval;
pdev = platform_device_alloc("SIU", -1);
if (!pdev)
return -ENOMEM;
switch (current_cpu_type()) {
case CPU_VR4111:
case CPU_VR4121:
pdev->dev.platform_data = siu_type1_ports;
res = siu_type1_resource;
num = ARRAY_SIZE(siu_type1_resource);
break;
case CPU_VR4122:
case CPU_VR4131:
case CPU_VR4133:
pdev->dev.platform_data = siu_type2_ports;
res = siu_type2_resource;
num = ARRAY_SIZE(siu_type2_resource);
break;
default:
retval = -ENODEV;
goto err_free_device;
}
retval = platform_device_add_resources(pdev, res, num);
if (retval)
goto err_free_device;
retval = platform_device_add(pdev);
if (retval)
goto err_free_device;
return 0;
err_free_device:
platform_device_put(pdev);
return retval;
}
device_initcall(vr41xx_siu_add);
void __init vr41xx_siu_setup(void)
{
struct uart_port port;
struct resource *res;
unsigned int *type;
int i;
switch (current_cpu_type()) {
case CPU_VR4111:
case CPU_VR4121:
type = siu_type1_ports;
res = siu_type1_resource;
break;
case CPU_VR4122:
case CPU_VR4131:
case CPU_VR4133:
type = siu_type2_ports;
res = siu_type2_resource;
break;
default:
return;
}
for (i = 0; i < SIU_PORTS_MAX; i++) {
port.line = i;
port.type = type[i];
if (port.type == PORT_UNKNOWN)
break;
port.mapbase = res[i].start;
port.membase = (unsigned char __iomem *)KSEG1ADDR(res[i].start);
vr41xx_siu_early_setup(&port);
}
}
| gpl-2.0 |
targetnull/nkvm | net/ipv6/xfrm6_mode_transport.c | 14215 | 2307 | /*
* xfrm6_mode_transport.c - Transport mode encapsulation for IPv6.
*
* Copyright (C) 2002 USAGI/WIDE Project
* Copyright (c) 2004-2006 Herbert Xu <herbert@gondor.apana.org.au>
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/stringify.h>
#include <net/dst.h>
#include <net/ipv6.h>
#include <net/xfrm.h>
/* Add encapsulation header.
*
* The IP header and mutable extension headers will be moved forward to make
* space for the encapsulation header.
*/
static int xfrm6_transport_output(struct xfrm_state *x, struct sk_buff *skb)
{
struct ipv6hdr *iph;
u8 *prevhdr;
int hdr_len;
iph = ipv6_hdr(skb);
hdr_len = x->type->hdr_offset(x, skb, &prevhdr);
skb_set_mac_header(skb, (prevhdr - x->props.header_len) - skb->data);
skb_set_network_header(skb, -x->props.header_len);
skb->transport_header = skb->network_header + hdr_len;
__skb_pull(skb, hdr_len);
memmove(ipv6_hdr(skb), iph, hdr_len);
return 0;
}
/* Remove encapsulation header.
*
* The IP header will be moved over the top of the encapsulation header.
*
* On entry, skb->h shall point to where the IP header should be and skb->nh
* shall be set to where the IP header currently is. skb->data shall point
* to the start of the payload.
*/
static int xfrm6_transport_input(struct xfrm_state *x, struct sk_buff *skb)
{
int ihl = skb->data - skb_transport_header(skb);
if (skb->transport_header != skb->network_header) {
memmove(skb_transport_header(skb),
skb_network_header(skb), ihl);
skb->network_header = skb->transport_header;
}
ipv6_hdr(skb)->payload_len = htons(skb->len + ihl -
sizeof(struct ipv6hdr));
skb_reset_transport_header(skb);
return 0;
}
static struct xfrm_mode xfrm6_transport_mode = {
.input = xfrm6_transport_input,
.output = xfrm6_transport_output,
.owner = THIS_MODULE,
.encap = XFRM_MODE_TRANSPORT,
};
static int __init xfrm6_transport_init(void)
{
return xfrm_register_mode(&xfrm6_transport_mode, AF_INET6);
}
static void __exit xfrm6_transport_exit(void)
{
int err;
err = xfrm_unregister_mode(&xfrm6_transport_mode, AF_INET6);
BUG_ON(err);
}
module_init(xfrm6_transport_init);
module_exit(xfrm6_transport_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_XFRM_MODE(AF_INET6, XFRM_MODE_TRANSPORT);
| gpl-2.0 |
guard163/linux | drivers/spi/spi-meson-spifc.c | 648 | 11476 | /*
* Driver for Amlogic Meson SPI flash controller (SPIFC)
*
* Copyright (C) 2014 Beniamino Galvani <b.galvani@gmail.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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/regmap.h>
#include <linux/spi/spi.h>
#include <linux/types.h>
/* register map */
#define REG_CMD 0x00
#define REG_ADDR 0x04
#define REG_CTRL 0x08
#define REG_CTRL1 0x0c
#define REG_STATUS 0x10
#define REG_CTRL2 0x14
#define REG_CLOCK 0x18
#define REG_USER 0x1c
#define REG_USER1 0x20
#define REG_USER2 0x24
#define REG_USER3 0x28
#define REG_USER4 0x2c
#define REG_SLAVE 0x30
#define REG_SLAVE1 0x34
#define REG_SLAVE2 0x38
#define REG_SLAVE3 0x3c
#define REG_C0 0x40
#define REG_B8 0x60
#define REG_MAX 0x7c
/* register fields */
#define CMD_USER BIT(18)
#define CTRL_ENABLE_AHB BIT(17)
#define CLOCK_SOURCE BIT(31)
#define CLOCK_DIV_SHIFT 12
#define CLOCK_DIV_MASK (0x3f << CLOCK_DIV_SHIFT)
#define CLOCK_CNT_HIGH_SHIFT 6
#define CLOCK_CNT_HIGH_MASK (0x3f << CLOCK_CNT_HIGH_SHIFT)
#define CLOCK_CNT_LOW_SHIFT 0
#define CLOCK_CNT_LOW_MASK (0x3f << CLOCK_CNT_LOW_SHIFT)
#define USER_DIN_EN_MS BIT(0)
#define USER_CMP_MODE BIT(2)
#define USER_UC_DOUT_SEL BIT(27)
#define USER_UC_DIN_SEL BIT(28)
#define USER_UC_MASK ((BIT(5) - 1) << 27)
#define USER1_BN_UC_DOUT_SHIFT 17
#define USER1_BN_UC_DOUT_MASK (0xff << 16)
#define USER1_BN_UC_DIN_SHIFT 8
#define USER1_BN_UC_DIN_MASK (0xff << 8)
#define USER4_CS_ACT BIT(30)
#define SLAVE_TRST_DONE BIT(4)
#define SLAVE_OP_MODE BIT(30)
#define SLAVE_SW_RST BIT(31)
#define SPIFC_BUFFER_SIZE 64
/**
* struct meson_spifc
* @master: the SPI master
* @regmap: regmap for device registers
* @clk: input clock of the built-in baud rate generator
* @device: the device structure
*/
struct meson_spifc {
struct spi_master *master;
struct regmap *regmap;
struct clk *clk;
struct device *dev;
};
static const struct regmap_config spifc_regmap_config = {
.reg_bits = 32,
.val_bits = 32,
.reg_stride = 4,
.max_register = REG_MAX,
};
/**
* meson_spifc_wait_ready() - wait for the current operation to terminate
* @spifc: the Meson SPI device
* Return: 0 on success, a negative value on error
*/
static int meson_spifc_wait_ready(struct meson_spifc *spifc)
{
unsigned long deadline = jiffies + msecs_to_jiffies(5);
u32 data;
do {
regmap_read(spifc->regmap, REG_SLAVE, &data);
if (data & SLAVE_TRST_DONE)
return 0;
cond_resched();
} while (!time_after(jiffies, deadline));
return -ETIMEDOUT;
}
/**
* meson_spifc_drain_buffer() - copy data from device buffer to memory
* @spifc: the Meson SPI device
* @buf: the destination buffer
* @len: number of bytes to copy
*/
static void meson_spifc_drain_buffer(struct meson_spifc *spifc, u8 *buf,
int len)
{
u32 data;
int i = 0;
while (i < len) {
regmap_read(spifc->regmap, REG_C0 + i, &data);
if (len - i >= 4) {
*((u32 *)buf) = data;
buf += 4;
} else {
memcpy(buf, &data, len - i);
break;
}
i += 4;
}
}
/**
* meson_spifc_fill_buffer() - copy data from memory to device buffer
* @spifc: the Meson SPI device
* @buf: the source buffer
* @len: number of bytes to copy
*/
static void meson_spifc_fill_buffer(struct meson_spifc *spifc, const u8 *buf,
int len)
{
u32 data;
int i = 0;
while (i < len) {
if (len - i >= 4)
data = *(u32 *)buf;
else
memcpy(&data, buf, len - i);
regmap_write(spifc->regmap, REG_C0 + i, data);
buf += 4;
i += 4;
}
}
/**
* meson_spifc_setup_speed() - program the clock divider
* @spifc: the Meson SPI device
* @speed: desired speed in Hz
*/
static void meson_spifc_setup_speed(struct meson_spifc *spifc, u32 speed)
{
unsigned long parent, value;
int n;
parent = clk_get_rate(spifc->clk);
n = max_t(int, parent / speed - 1, 1);
dev_dbg(spifc->dev, "parent %lu, speed %u, n %d\n", parent,
speed, n);
value = (n << CLOCK_DIV_SHIFT) & CLOCK_DIV_MASK;
value |= (n << CLOCK_CNT_LOW_SHIFT) & CLOCK_CNT_LOW_MASK;
value |= (((n + 1) / 2 - 1) << CLOCK_CNT_HIGH_SHIFT) &
CLOCK_CNT_HIGH_MASK;
regmap_write(spifc->regmap, REG_CLOCK, value);
}
/**
* meson_spifc_txrx() - transfer a chunk of data
* @spifc: the Meson SPI device
* @xfer: the current SPI transfer
* @offset: offset of the data to transfer
* @len: length of the data to transfer
* @last_xfer: whether this is the last transfer of the message
* @last_chunk: whether this is the last chunk of the transfer
* Return: 0 on success, a negative value on error
*/
static int meson_spifc_txrx(struct meson_spifc *spifc,
struct spi_transfer *xfer,
int offset, int len, bool last_xfer,
bool last_chunk)
{
bool keep_cs = true;
int ret;
if (xfer->tx_buf)
meson_spifc_fill_buffer(spifc, xfer->tx_buf + offset, len);
/* enable DOUT stage */
regmap_update_bits(spifc->regmap, REG_USER, USER_UC_MASK,
USER_UC_DOUT_SEL);
regmap_write(spifc->regmap, REG_USER1,
(8 * len - 1) << USER1_BN_UC_DOUT_SHIFT);
/* enable data input during DOUT */
regmap_update_bits(spifc->regmap, REG_USER, USER_DIN_EN_MS,
USER_DIN_EN_MS);
if (last_chunk) {
if (last_xfer)
keep_cs = xfer->cs_change;
else
keep_cs = !xfer->cs_change;
}
regmap_update_bits(spifc->regmap, REG_USER4, USER4_CS_ACT,
keep_cs ? USER4_CS_ACT : 0);
/* clear transition done bit */
regmap_update_bits(spifc->regmap, REG_SLAVE, SLAVE_TRST_DONE, 0);
/* start transfer */
regmap_update_bits(spifc->regmap, REG_CMD, CMD_USER, CMD_USER);
ret = meson_spifc_wait_ready(spifc);
if (!ret && xfer->rx_buf)
meson_spifc_drain_buffer(spifc, xfer->rx_buf + offset, len);
return ret;
}
/**
* meson_spifc_transfer_one() - perform a single transfer
* @master: the SPI master
* @spi: the SPI device
* @xfer: the current SPI transfer
* Return: 0 on success, a negative value on error
*/
static int meson_spifc_transfer_one(struct spi_master *master,
struct spi_device *spi,
struct spi_transfer *xfer)
{
struct meson_spifc *spifc = spi_master_get_devdata(master);
int len, done = 0, ret = 0;
meson_spifc_setup_speed(spifc, xfer->speed_hz);
regmap_update_bits(spifc->regmap, REG_CTRL, CTRL_ENABLE_AHB, 0);
while (done < xfer->len && !ret) {
len = min_t(int, xfer->len - done, SPIFC_BUFFER_SIZE);
ret = meson_spifc_txrx(spifc, xfer, done, len,
spi_transfer_is_last(master, xfer),
done + len >= xfer->len);
done += len;
}
regmap_update_bits(spifc->regmap, REG_CTRL, CTRL_ENABLE_AHB,
CTRL_ENABLE_AHB);
return ret;
}
/**
* meson_spifc_hw_init() - reset and initialize the SPI controller
* @spifc: the Meson SPI device
*/
static void meson_spifc_hw_init(struct meson_spifc *spifc)
{
/* reset device */
regmap_update_bits(spifc->regmap, REG_SLAVE, SLAVE_SW_RST,
SLAVE_SW_RST);
/* disable compatible mode */
regmap_update_bits(spifc->regmap, REG_USER, USER_CMP_MODE, 0);
/* set master mode */
regmap_update_bits(spifc->regmap, REG_SLAVE, SLAVE_OP_MODE, 0);
}
static int meson_spifc_probe(struct platform_device *pdev)
{
struct spi_master *master;
struct meson_spifc *spifc;
struct resource *res;
void __iomem *base;
unsigned int rate;
int ret = 0;
master = spi_alloc_master(&pdev->dev, sizeof(struct meson_spifc));
if (!master)
return -ENOMEM;
platform_set_drvdata(pdev, master);
spifc = spi_master_get_devdata(master);
spifc->dev = &pdev->dev;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
base = devm_ioremap_resource(spifc->dev, res);
if (IS_ERR(base)) {
ret = PTR_ERR(base);
goto out_err;
}
spifc->regmap = devm_regmap_init_mmio(spifc->dev, base,
&spifc_regmap_config);
if (IS_ERR(spifc->regmap)) {
ret = PTR_ERR(spifc->regmap);
goto out_err;
}
spifc->clk = devm_clk_get(spifc->dev, NULL);
if (IS_ERR(spifc->clk)) {
dev_err(spifc->dev, "missing clock\n");
ret = PTR_ERR(spifc->clk);
goto out_err;
}
ret = clk_prepare_enable(spifc->clk);
if (ret) {
dev_err(spifc->dev, "can't prepare clock\n");
goto out_err;
}
rate = clk_get_rate(spifc->clk);
master->num_chipselect = 1;
master->dev.of_node = pdev->dev.of_node;
master->bits_per_word_mask = SPI_BPW_MASK(8);
master->auto_runtime_pm = true;
master->transfer_one = meson_spifc_transfer_one;
master->min_speed_hz = rate >> 6;
master->max_speed_hz = rate >> 1;
meson_spifc_hw_init(spifc);
pm_runtime_set_active(spifc->dev);
pm_runtime_enable(spifc->dev);
ret = devm_spi_register_master(spifc->dev, master);
if (ret) {
dev_err(spifc->dev, "failed to register spi master\n");
goto out_clk;
}
return 0;
out_clk:
clk_disable_unprepare(spifc->clk);
out_err:
spi_master_put(master);
return ret;
}
static int meson_spifc_remove(struct platform_device *pdev)
{
struct spi_master *master = platform_get_drvdata(pdev);
struct meson_spifc *spifc = spi_master_get_devdata(master);
pm_runtime_get_sync(&pdev->dev);
clk_disable_unprepare(spifc->clk);
pm_runtime_disable(&pdev->dev);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int meson_spifc_suspend(struct device *dev)
{
struct spi_master *master = dev_get_drvdata(dev);
struct meson_spifc *spifc = spi_master_get_devdata(master);
int ret;
ret = spi_master_suspend(master);
if (ret)
return ret;
if (!pm_runtime_suspended(dev))
clk_disable_unprepare(spifc->clk);
return 0;
}
static int meson_spifc_resume(struct device *dev)
{
struct spi_master *master = dev_get_drvdata(dev);
struct meson_spifc *spifc = spi_master_get_devdata(master);
int ret;
if (!pm_runtime_suspended(dev)) {
ret = clk_prepare_enable(spifc->clk);
if (ret)
return ret;
}
meson_spifc_hw_init(spifc);
ret = spi_master_resume(master);
if (ret)
clk_disable_unprepare(spifc->clk);
return ret;
}
#endif /* CONFIG_PM_SLEEP */
#ifdef CONFIG_PM
static int meson_spifc_runtime_suspend(struct device *dev)
{
struct spi_master *master = dev_get_drvdata(dev);
struct meson_spifc *spifc = spi_master_get_devdata(master);
clk_disable_unprepare(spifc->clk);
return 0;
}
static int meson_spifc_runtime_resume(struct device *dev)
{
struct spi_master *master = dev_get_drvdata(dev);
struct meson_spifc *spifc = spi_master_get_devdata(master);
return clk_prepare_enable(spifc->clk);
}
#endif /* CONFIG_PM */
static const struct dev_pm_ops meson_spifc_pm_ops = {
SET_SYSTEM_SLEEP_PM_OPS(meson_spifc_suspend, meson_spifc_resume)
SET_RUNTIME_PM_OPS(meson_spifc_runtime_suspend,
meson_spifc_runtime_resume,
NULL)
};
static const struct of_device_id meson_spifc_dt_match[] = {
{ .compatible = "amlogic,meson6-spifc", },
{ },
};
static struct platform_driver meson_spifc_driver = {
.probe = meson_spifc_probe,
.remove = meson_spifc_remove,
.driver = {
.name = "meson-spifc",
.of_match_table = of_match_ptr(meson_spifc_dt_match),
.pm = &meson_spifc_pm_ops,
},
};
module_platform_driver(meson_spifc_driver);
MODULE_AUTHOR("Beniamino Galvani <b.galvani@gmail.com>");
MODULE_DESCRIPTION("Amlogic Meson SPIFC driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
KlinkOnE/android_kernel_kyleoc2 | arch/x86/kernel/cpu/perf_event_intel_ds.c | 648 | 18512 | #ifdef CONFIG_CPU_SUP_INTEL
/* The maximal number of PEBS events: */
#define MAX_PEBS_EVENTS 4
/* The size of a BTS record in bytes: */
#define BTS_RECORD_SIZE 24
#define BTS_BUFFER_SIZE (PAGE_SIZE << 4)
#define PEBS_BUFFER_SIZE PAGE_SIZE
/*
* pebs_record_32 for p4 and core not supported
struct pebs_record_32 {
u32 flags, ip;
u32 ax, bc, cx, dx;
u32 si, di, bp, sp;
};
*/
struct pebs_record_core {
u64 flags, ip;
u64 ax, bx, cx, dx;
u64 si, di, bp, sp;
u64 r8, r9, r10, r11;
u64 r12, r13, r14, r15;
};
struct pebs_record_nhm {
u64 flags, ip;
u64 ax, bx, cx, dx;
u64 si, di, bp, sp;
u64 r8, r9, r10, r11;
u64 r12, r13, r14, r15;
u64 status, dla, dse, lat;
};
/*
* A debug store configuration.
*
* We only support architectures that use 64bit fields.
*/
struct debug_store {
u64 bts_buffer_base;
u64 bts_index;
u64 bts_absolute_maximum;
u64 bts_interrupt_threshold;
u64 pebs_buffer_base;
u64 pebs_index;
u64 pebs_absolute_maximum;
u64 pebs_interrupt_threshold;
u64 pebs_event_reset[MAX_PEBS_EVENTS];
};
static void init_debug_store_on_cpu(int cpu)
{
struct debug_store *ds = per_cpu(cpu_hw_events, cpu).ds;
if (!ds)
return;
wrmsr_on_cpu(cpu, MSR_IA32_DS_AREA,
(u32)((u64)(unsigned long)ds),
(u32)((u64)(unsigned long)ds >> 32));
}
static void fini_debug_store_on_cpu(int cpu)
{
if (!per_cpu(cpu_hw_events, cpu).ds)
return;
wrmsr_on_cpu(cpu, MSR_IA32_DS_AREA, 0, 0);
}
static int alloc_pebs_buffer(int cpu)
{
struct debug_store *ds = per_cpu(cpu_hw_events, cpu).ds;
int node = cpu_to_node(cpu);
int max, thresh = 1; /* always use a single PEBS record */
void *buffer;
if (!x86_pmu.pebs)
return 0;
buffer = kmalloc_node(PEBS_BUFFER_SIZE, GFP_KERNEL | __GFP_ZERO, node);
if (unlikely(!buffer))
return -ENOMEM;
max = PEBS_BUFFER_SIZE / x86_pmu.pebs_record_size;
ds->pebs_buffer_base = (u64)(unsigned long)buffer;
ds->pebs_index = ds->pebs_buffer_base;
ds->pebs_absolute_maximum = ds->pebs_buffer_base +
max * x86_pmu.pebs_record_size;
ds->pebs_interrupt_threshold = ds->pebs_buffer_base +
thresh * x86_pmu.pebs_record_size;
return 0;
}
static void release_pebs_buffer(int cpu)
{
struct debug_store *ds = per_cpu(cpu_hw_events, cpu).ds;
if (!ds || !x86_pmu.pebs)
return;
kfree((void *)(unsigned long)ds->pebs_buffer_base);
ds->pebs_buffer_base = 0;
}
static int alloc_bts_buffer(int cpu)
{
struct debug_store *ds = per_cpu(cpu_hw_events, cpu).ds;
int node = cpu_to_node(cpu);
int max, thresh;
void *buffer;
if (!x86_pmu.bts)
return 0;
buffer = kmalloc_node(BTS_BUFFER_SIZE, GFP_KERNEL | __GFP_ZERO, node);
if (unlikely(!buffer))
return -ENOMEM;
max = BTS_BUFFER_SIZE / BTS_RECORD_SIZE;
thresh = max / 16;
ds->bts_buffer_base = (u64)(unsigned long)buffer;
ds->bts_index = ds->bts_buffer_base;
ds->bts_absolute_maximum = ds->bts_buffer_base +
max * BTS_RECORD_SIZE;
ds->bts_interrupt_threshold = ds->bts_absolute_maximum -
thresh * BTS_RECORD_SIZE;
return 0;
}
static void release_bts_buffer(int cpu)
{
struct debug_store *ds = per_cpu(cpu_hw_events, cpu).ds;
if (!ds || !x86_pmu.bts)
return;
kfree((void *)(unsigned long)ds->bts_buffer_base);
ds->bts_buffer_base = 0;
}
static int alloc_ds_buffer(int cpu)
{
int node = cpu_to_node(cpu);
struct debug_store *ds;
ds = kmalloc_node(sizeof(*ds), GFP_KERNEL | __GFP_ZERO, node);
if (unlikely(!ds))
return -ENOMEM;
per_cpu(cpu_hw_events, cpu).ds = ds;
return 0;
}
static void release_ds_buffer(int cpu)
{
struct debug_store *ds = per_cpu(cpu_hw_events, cpu).ds;
if (!ds)
return;
per_cpu(cpu_hw_events, cpu).ds = NULL;
kfree(ds);
}
static void release_ds_buffers(void)
{
int cpu;
if (!x86_pmu.bts && !x86_pmu.pebs)
return;
get_online_cpus();
for_each_online_cpu(cpu)
fini_debug_store_on_cpu(cpu);
for_each_possible_cpu(cpu) {
release_pebs_buffer(cpu);
release_bts_buffer(cpu);
release_ds_buffer(cpu);
}
put_online_cpus();
}
static void reserve_ds_buffers(void)
{
int bts_err = 0, pebs_err = 0;
int cpu;
x86_pmu.bts_active = 0;
x86_pmu.pebs_active = 0;
if (!x86_pmu.bts && !x86_pmu.pebs)
return;
if (!x86_pmu.bts)
bts_err = 1;
if (!x86_pmu.pebs)
pebs_err = 1;
get_online_cpus();
for_each_possible_cpu(cpu) {
if (alloc_ds_buffer(cpu)) {
bts_err = 1;
pebs_err = 1;
}
if (!bts_err && alloc_bts_buffer(cpu))
bts_err = 1;
if (!pebs_err && alloc_pebs_buffer(cpu))
pebs_err = 1;
if (bts_err && pebs_err)
break;
}
if (bts_err) {
for_each_possible_cpu(cpu)
release_bts_buffer(cpu);
}
if (pebs_err) {
for_each_possible_cpu(cpu)
release_pebs_buffer(cpu);
}
if (bts_err && pebs_err) {
for_each_possible_cpu(cpu)
release_ds_buffer(cpu);
} else {
if (x86_pmu.bts && !bts_err)
x86_pmu.bts_active = 1;
if (x86_pmu.pebs && !pebs_err)
x86_pmu.pebs_active = 1;
for_each_online_cpu(cpu)
init_debug_store_on_cpu(cpu);
}
put_online_cpus();
}
/*
* BTS
*/
static struct event_constraint bts_constraint =
EVENT_CONSTRAINT(0, 1ULL << X86_PMC_IDX_FIXED_BTS, 0);
static void intel_pmu_enable_bts(u64 config)
{
unsigned long debugctlmsr;
debugctlmsr = get_debugctlmsr();
debugctlmsr |= DEBUGCTLMSR_TR;
debugctlmsr |= DEBUGCTLMSR_BTS;
debugctlmsr |= DEBUGCTLMSR_BTINT;
if (!(config & ARCH_PERFMON_EVENTSEL_OS))
debugctlmsr |= DEBUGCTLMSR_BTS_OFF_OS;
if (!(config & ARCH_PERFMON_EVENTSEL_USR))
debugctlmsr |= DEBUGCTLMSR_BTS_OFF_USR;
update_debugctlmsr(debugctlmsr);
}
static void intel_pmu_disable_bts(void)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
unsigned long debugctlmsr;
if (!cpuc->ds)
return;
debugctlmsr = get_debugctlmsr();
debugctlmsr &=
~(DEBUGCTLMSR_TR | DEBUGCTLMSR_BTS | DEBUGCTLMSR_BTINT |
DEBUGCTLMSR_BTS_OFF_OS | DEBUGCTLMSR_BTS_OFF_USR);
update_debugctlmsr(debugctlmsr);
}
static int intel_pmu_drain_bts_buffer(void)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
struct debug_store *ds = cpuc->ds;
struct bts_record {
u64 from;
u64 to;
u64 flags;
};
struct perf_event *event = cpuc->events[X86_PMC_IDX_FIXED_BTS];
struct bts_record *at, *top;
struct perf_output_handle handle;
struct perf_event_header header;
struct perf_sample_data data;
struct pt_regs regs;
if (!event)
return 0;
if (!x86_pmu.bts_active)
return 0;
at = (struct bts_record *)(unsigned long)ds->bts_buffer_base;
top = (struct bts_record *)(unsigned long)ds->bts_index;
if (top <= at)
return 0;
ds->bts_index = ds->bts_buffer_base;
perf_sample_data_init(&data, 0);
data.period = event->hw.last_period;
regs.ip = 0;
/*
* Prepare a generic sample, i.e. fill in the invariant fields.
* We will overwrite the from and to address before we output
* the sample.
*/
perf_prepare_sample(&header, &data, event, ®s);
if (perf_output_begin(&handle, event, header.size * (top - at), 1, 1))
return 1;
for (; at < top; at++) {
data.ip = at->from;
data.addr = at->to;
perf_output_sample(&handle, &header, &data, event);
}
perf_output_end(&handle);
/* There's new data available. */
event->hw.interrupts++;
event->pending_kill = POLL_IN;
return 1;
}
/*
* PEBS
*/
static struct event_constraint intel_core2_pebs_event_constraints[] = {
INTEL_UEVENT_CONSTRAINT(0x00c0, 0x1), /* INST_RETIRED.ANY */
INTEL_UEVENT_CONSTRAINT(0xfec1, 0x1), /* X87_OPS_RETIRED.ANY */
INTEL_UEVENT_CONSTRAINT(0x00c5, 0x1), /* BR_INST_RETIRED.MISPRED */
INTEL_UEVENT_CONSTRAINT(0x1fc7, 0x1), /* SIMD_INST_RETURED.ANY */
INTEL_EVENT_CONSTRAINT(0xcb, 0x1), /* MEM_LOAD_RETIRED.* */
EVENT_CONSTRAINT_END
};
static struct event_constraint intel_atom_pebs_event_constraints[] = {
INTEL_UEVENT_CONSTRAINT(0x00c0, 0x1), /* INST_RETIRED.ANY */
INTEL_UEVENT_CONSTRAINT(0x00c5, 0x1), /* MISPREDICTED_BRANCH_RETIRED */
INTEL_EVENT_CONSTRAINT(0xcb, 0x1), /* MEM_LOAD_RETIRED.* */
EVENT_CONSTRAINT_END
};
static struct event_constraint intel_nehalem_pebs_event_constraints[] = {
INTEL_EVENT_CONSTRAINT(0x0b, 0xf), /* MEM_INST_RETIRED.* */
INTEL_EVENT_CONSTRAINT(0x0f, 0xf), /* MEM_UNCORE_RETIRED.* */
INTEL_UEVENT_CONSTRAINT(0x010c, 0xf), /* MEM_STORE_RETIRED.DTLB_MISS */
INTEL_EVENT_CONSTRAINT(0xc0, 0xf), /* INST_RETIRED.ANY */
INTEL_EVENT_CONSTRAINT(0xc2, 0xf), /* UOPS_RETIRED.* */
INTEL_EVENT_CONSTRAINT(0xc4, 0xf), /* BR_INST_RETIRED.* */
INTEL_UEVENT_CONSTRAINT(0x02c5, 0xf), /* BR_MISP_RETIRED.NEAR_CALL */
INTEL_EVENT_CONSTRAINT(0xc7, 0xf), /* SSEX_UOPS_RETIRED.* */
INTEL_UEVENT_CONSTRAINT(0x20c8, 0xf), /* ITLB_MISS_RETIRED */
INTEL_EVENT_CONSTRAINT(0xcb, 0xf), /* MEM_LOAD_RETIRED.* */
INTEL_EVENT_CONSTRAINT(0xf7, 0xf), /* FP_ASSIST.* */
EVENT_CONSTRAINT_END
};
static struct event_constraint intel_westmere_pebs_event_constraints[] = {
INTEL_EVENT_CONSTRAINT(0x0b, 0xf), /* MEM_INST_RETIRED.* */
INTEL_EVENT_CONSTRAINT(0x0f, 0xf), /* MEM_UNCORE_RETIRED.* */
INTEL_UEVENT_CONSTRAINT(0x010c, 0xf), /* MEM_STORE_RETIRED.DTLB_MISS */
INTEL_EVENT_CONSTRAINT(0xc0, 0xf), /* INSTR_RETIRED.* */
INTEL_EVENT_CONSTRAINT(0xc2, 0xf), /* UOPS_RETIRED.* */
INTEL_EVENT_CONSTRAINT(0xc4, 0xf), /* BR_INST_RETIRED.* */
INTEL_EVENT_CONSTRAINT(0xc5, 0xf), /* BR_MISP_RETIRED.* */
INTEL_EVENT_CONSTRAINT(0xc7, 0xf), /* SSEX_UOPS_RETIRED.* */
INTEL_UEVENT_CONSTRAINT(0x20c8, 0xf), /* ITLB_MISS_RETIRED */
INTEL_EVENT_CONSTRAINT(0xcb, 0xf), /* MEM_LOAD_RETIRED.* */
INTEL_EVENT_CONSTRAINT(0xf7, 0xf), /* FP_ASSIST.* */
EVENT_CONSTRAINT_END
};
static struct event_constraint intel_snb_pebs_events[] = {
INTEL_UEVENT_CONSTRAINT(0x01c0, 0x2), /* INST_RETIRED.PRECDIST */
INTEL_UEVENT_CONSTRAINT(0x01c2, 0xf), /* UOPS_RETIRED.ALL */
INTEL_UEVENT_CONSTRAINT(0x02c2, 0xf), /* UOPS_RETIRED.RETIRE_SLOTS */
INTEL_EVENT_CONSTRAINT(0xc4, 0xf), /* BR_INST_RETIRED.* */
INTEL_EVENT_CONSTRAINT(0xc5, 0xf), /* BR_MISP_RETIRED.* */
INTEL_EVENT_CONSTRAINT(0xcd, 0x8), /* MEM_TRANS_RETIRED.* */
INTEL_UEVENT_CONSTRAINT(0x11d0, 0xf), /* MEM_UOP_RETIRED.STLB_MISS_LOADS */
INTEL_UEVENT_CONSTRAINT(0x12d0, 0xf), /* MEM_UOP_RETIRED.STLB_MISS_STORES */
INTEL_UEVENT_CONSTRAINT(0x21d0, 0xf), /* MEM_UOP_RETIRED.LOCK_LOADS */
INTEL_UEVENT_CONSTRAINT(0x22d0, 0xf), /* MEM_UOP_RETIRED.LOCK_STORES */
INTEL_UEVENT_CONSTRAINT(0x41d0, 0xf), /* MEM_UOP_RETIRED.SPLIT_LOADS */
INTEL_UEVENT_CONSTRAINT(0x42d0, 0xf), /* MEM_UOP_RETIRED.SPLIT_STORES */
INTEL_UEVENT_CONSTRAINT(0x81d0, 0xf), /* MEM_UOP_RETIRED.ANY_LOADS */
INTEL_UEVENT_CONSTRAINT(0x82d0, 0xf), /* MEM_UOP_RETIRED.ANY_STORES */
INTEL_EVENT_CONSTRAINT(0xd1, 0xf), /* MEM_LOAD_UOPS_RETIRED.* */
INTEL_EVENT_CONSTRAINT(0xd2, 0xf), /* MEM_LOAD_UOPS_LLC_HIT_RETIRED.* */
INTEL_UEVENT_CONSTRAINT(0x02d4, 0xf), /* MEM_LOAD_UOPS_MISC_RETIRED.LLC_MISS */
EVENT_CONSTRAINT_END
};
static struct event_constraint *
intel_pebs_constraints(struct perf_event *event)
{
struct event_constraint *c;
if (!event->attr.precise_ip)
return NULL;
if (x86_pmu.pebs_constraints) {
for_each_event_constraint(c, x86_pmu.pebs_constraints) {
if ((event->hw.config & c->cmask) == c->code)
return c;
}
}
return &emptyconstraint;
}
static void intel_pmu_pebs_enable(struct perf_event *event)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
struct hw_perf_event *hwc = &event->hw;
hwc->config &= ~ARCH_PERFMON_EVENTSEL_INT;
cpuc->pebs_enabled |= 1ULL << hwc->idx;
WARN_ON_ONCE(cpuc->enabled);
if (x86_pmu.intel_cap.pebs_trap && event->attr.precise_ip > 1)
intel_pmu_lbr_enable(event);
}
static void intel_pmu_pebs_disable(struct perf_event *event)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
struct hw_perf_event *hwc = &event->hw;
cpuc->pebs_enabled &= ~(1ULL << hwc->idx);
if (cpuc->enabled)
wrmsrl(MSR_IA32_PEBS_ENABLE, cpuc->pebs_enabled);
hwc->config |= ARCH_PERFMON_EVENTSEL_INT;
if (x86_pmu.intel_cap.pebs_trap && event->attr.precise_ip > 1)
intel_pmu_lbr_disable(event);
}
static void intel_pmu_pebs_enable_all(void)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
if (cpuc->pebs_enabled)
wrmsrl(MSR_IA32_PEBS_ENABLE, cpuc->pebs_enabled);
}
static void intel_pmu_pebs_disable_all(void)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
if (cpuc->pebs_enabled)
wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
}
#include <asm/insn.h>
static inline bool kernel_ip(unsigned long ip)
{
#ifdef CONFIG_X86_32
return ip > PAGE_OFFSET;
#else
return (long)ip < 0;
#endif
}
static int intel_pmu_pebs_fixup_ip(struct pt_regs *regs)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
unsigned long from = cpuc->lbr_entries[0].from;
unsigned long old_to, to = cpuc->lbr_entries[0].to;
unsigned long ip = regs->ip;
int is_64bit = 0;
/*
* We don't need to fixup if the PEBS assist is fault like
*/
if (!x86_pmu.intel_cap.pebs_trap)
return 1;
/*
* No LBR entry, no basic block, no rewinding
*/
if (!cpuc->lbr_stack.nr || !from || !to)
return 0;
/*
* Basic blocks should never cross user/kernel boundaries
*/
if (kernel_ip(ip) != kernel_ip(to))
return 0;
/*
* unsigned math, either ip is before the start (impossible) or
* the basic block is larger than 1 page (sanity)
*/
if ((ip - to) > PAGE_SIZE)
return 0;
/*
* We sampled a branch insn, rewind using the LBR stack
*/
if (ip == to) {
regs->ip = from;
return 1;
}
do {
struct insn insn;
u8 buf[MAX_INSN_SIZE];
void *kaddr;
old_to = to;
if (!kernel_ip(ip)) {
int bytes, size = MAX_INSN_SIZE;
bytes = copy_from_user_nmi(buf, (void __user *)to, size);
if (bytes != size)
return 0;
kaddr = buf;
} else
kaddr = (void *)to;
#ifdef CONFIG_X86_64
is_64bit = kernel_ip(to) || !test_thread_flag(TIF_IA32);
#endif
insn_init(&insn, kaddr, is_64bit);
insn_get_length(&insn);
to += insn.length;
} while (to < ip);
if (to == ip) {
regs->ip = old_to;
return 1;
}
/*
* Even though we decoded the basic block, the instruction stream
* never matched the given IP, either the TO or the IP got corrupted.
*/
return 0;
}
static int intel_pmu_save_and_restart(struct perf_event *event);
static void __intel_pmu_pebs_event(struct perf_event *event,
struct pt_regs *iregs, void *__pebs)
{
/*
* We cast to pebs_record_core since that is a subset of
* both formats and we don't use the other fields in this
* routine.
*/
struct pebs_record_core *pebs = __pebs;
struct perf_sample_data data;
struct pt_regs regs;
if (!intel_pmu_save_and_restart(event))
return;
perf_sample_data_init(&data, 0);
data.period = event->hw.last_period;
/*
* We use the interrupt regs as a base because the PEBS record
* does not contain a full regs set, specifically it seems to
* lack segment descriptors, which get used by things like
* user_mode().
*
* In the simple case fix up only the IP and BP,SP regs, for
* PERF_SAMPLE_IP and PERF_SAMPLE_CALLCHAIN to function properly.
* A possible PERF_SAMPLE_REGS will have to transfer all regs.
*/
regs = *iregs;
regs.ip = pebs->ip;
regs.bp = pebs->bp;
regs.sp = pebs->sp;
if (event->attr.precise_ip > 1 && intel_pmu_pebs_fixup_ip(®s))
regs.flags |= PERF_EFLAGS_EXACT;
else
regs.flags &= ~PERF_EFLAGS_EXACT;
if (perf_event_overflow(event, 1, &data, ®s))
x86_pmu_stop(event, 0);
}
static void intel_pmu_drain_pebs_core(struct pt_regs *iregs)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
struct debug_store *ds = cpuc->ds;
struct perf_event *event = cpuc->events[0]; /* PMC0 only */
struct pebs_record_core *at, *top;
int n;
if (!x86_pmu.pebs_active)
return;
at = (struct pebs_record_core *)(unsigned long)ds->pebs_buffer_base;
top = (struct pebs_record_core *)(unsigned long)ds->pebs_index;
/*
* Whatever else happens, drain the thing
*/
ds->pebs_index = ds->pebs_buffer_base;
if (!test_bit(0, cpuc->active_mask))
return;
WARN_ON_ONCE(!event);
if (!event->attr.precise_ip)
return;
n = top - at;
if (n <= 0)
return;
/*
* Should not happen, we program the threshold at 1 and do not
* set a reset value.
*/
WARN_ON_ONCE(n > 1);
at += n - 1;
__intel_pmu_pebs_event(event, iregs, at);
}
static void intel_pmu_drain_pebs_nhm(struct pt_regs *iregs)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
struct debug_store *ds = cpuc->ds;
struct pebs_record_nhm *at, *top;
struct perf_event *event = NULL;
u64 status = 0;
int bit, n;
if (!x86_pmu.pebs_active)
return;
at = (struct pebs_record_nhm *)(unsigned long)ds->pebs_buffer_base;
top = (struct pebs_record_nhm *)(unsigned long)ds->pebs_index;
ds->pebs_index = ds->pebs_buffer_base;
n = top - at;
if (n <= 0)
return;
/*
* Should not happen, we program the threshold at 1 and do not
* set a reset value.
*/
WARN_ON_ONCE(n > MAX_PEBS_EVENTS);
for ( ; at < top; at++) {
for_each_set_bit(bit, (unsigned long *)&at->status, MAX_PEBS_EVENTS) {
event = cpuc->events[bit];
if (!test_bit(bit, cpuc->active_mask))
continue;
WARN_ON_ONCE(!event);
if (!event->attr.precise_ip)
continue;
if (__test_and_set_bit(bit, (unsigned long *)&status))
continue;
break;
}
if (!event || bit >= MAX_PEBS_EVENTS)
continue;
__intel_pmu_pebs_event(event, iregs, at);
}
}
/*
* BTS, PEBS probe and setup
*/
static void intel_ds_init(void)
{
/*
* No support for 32bit formats
*/
if (!boot_cpu_has(X86_FEATURE_DTES64))
return;
x86_pmu.bts = boot_cpu_has(X86_FEATURE_BTS);
x86_pmu.pebs = boot_cpu_has(X86_FEATURE_PEBS);
if (x86_pmu.pebs) {
char pebs_type = x86_pmu.intel_cap.pebs_trap ? '+' : '-';
int format = x86_pmu.intel_cap.pebs_format;
switch (format) {
case 0:
printk(KERN_CONT "PEBS fmt0%c, ", pebs_type);
x86_pmu.pebs_record_size = sizeof(struct pebs_record_core);
x86_pmu.drain_pebs = intel_pmu_drain_pebs_core;
break;
case 1:
printk(KERN_CONT "PEBS fmt1%c, ", pebs_type);
x86_pmu.pebs_record_size = sizeof(struct pebs_record_nhm);
x86_pmu.drain_pebs = intel_pmu_drain_pebs_nhm;
break;
default:
printk(KERN_CONT "no PEBS fmt%d%c, ", format, pebs_type);
x86_pmu.pebs = 0;
}
}
}
void perf_restore_debug_store(void)
{
struct debug_store *ds = __this_cpu_read(cpu_hw_events.ds);
if (!x86_pmu.bts && !x86_pmu.pebs)
return;
wrmsrl(MSR_IA32_DS_AREA, (unsigned long)ds);
}
#else /* CONFIG_CPU_SUP_INTEL */
static void reserve_ds_buffers(void)
{
}
static void release_ds_buffers(void)
{
}
#endif /* CONFIG_CPU_SUP_INTEL */
| gpl-2.0 |
lehmanju/kernel_lenovo_lifetab_e10312 | mm/ashmem.c | 904 | 18726 | /* mm/ashmem.c
**
** Anonymous Shared Memory Subsystem, ashmem
**
** Copyright (C) 2008 Google, Inc.
**
** Robert Love <rlove@google.com>
**
** This software is licensed under the terms of the GNU General Public
** License version 2, as published by the Free Software Foundation, and
** may be copied, distributed, and modified under those terms.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
*/
#include <linux/module.h>
#include <linux/file.h>
#include <linux/fs.h>
#include <linux/miscdevice.h>
#include <linux/security.h>
#include <linux/mm.h>
#include <linux/mman.h>
#include <linux/uaccess.h>
#include <linux/personality.h>
#include <linux/bitops.h>
#include <linux/mutex.h>
#include <linux/shmem_fs.h>
#include <linux/ashmem.h>
#define ASHMEM_NAME_PREFIX "dev/ashmem/"
#define ASHMEM_NAME_PREFIX_LEN (sizeof(ASHMEM_NAME_PREFIX) - 1)
#define ASHMEM_FULL_NAME_LEN (ASHMEM_NAME_LEN + ASHMEM_NAME_PREFIX_LEN)
/*
* ashmem_area - anonymous shared memory area
* Lifecycle: From our parent file's open() until its release()
* Locking: Protected by `ashmem_mutex'
* Big Note: Mappings do NOT pin this structure; it dies on close()
*/
struct ashmem_area {
char name[ASHMEM_FULL_NAME_LEN];/* optional name for /proc/pid/maps */
struct list_head unpinned_list; /* list of all ashmem areas */
struct file *file; /* the shmem-based backing file */
size_t size; /* size of the mapping, in bytes */
unsigned long prot_mask; /* allowed prot bits, as vm_flags */
};
/*
* ashmem_range - represents an interval of unpinned (evictable) pages
* Lifecycle: From unpin to pin
* Locking: Protected by `ashmem_mutex'
*/
struct ashmem_range {
struct list_head lru; /* entry in LRU list */
struct list_head unpinned; /* entry in its area's unpinned list */
struct ashmem_area *asma; /* associated area */
size_t pgstart; /* starting page, inclusive */
size_t pgend; /* ending page, inclusive */
unsigned int purged; /* ASHMEM_NOT or ASHMEM_WAS_PURGED */
};
/* LRU list of unpinned pages, protected by ashmem_mutex */
static LIST_HEAD(ashmem_lru_list);
/* Count of pages on our LRU list, protected by ashmem_mutex */
static unsigned long lru_count;
/*
* ashmem_mutex - protects the list of and each individual ashmem_area
*
* Lock Ordering: ashmex_mutex -> i_mutex -> i_alloc_sem
*/
static DEFINE_MUTEX(ashmem_mutex);
static struct kmem_cache *ashmem_area_cachep __read_mostly;
static struct kmem_cache *ashmem_range_cachep __read_mostly;
#define range_size(range) \
((range)->pgend - (range)->pgstart + 1)
#define range_on_lru(range) \
((range)->purged == ASHMEM_NOT_PURGED)
#define page_range_subsumes_range(range, start, end) \
(((range)->pgstart >= (start)) && ((range)->pgend <= (end)))
#define page_range_subsumed_by_range(range, start, end) \
(((range)->pgstart <= (start)) && ((range)->pgend >= (end)))
#define page_in_range(range, page) \
(((range)->pgstart <= (page)) && ((range)->pgend >= (page)))
#define page_range_in_range(range, start, end) \
(page_in_range(range, start) || page_in_range(range, end) || \
page_range_subsumes_range(range, start, end))
#define range_before_page(range, page) \
((range)->pgend < (page))
#define PROT_MASK (PROT_EXEC | PROT_READ | PROT_WRITE)
static inline void lru_add(struct ashmem_range *range)
{
list_add_tail(&range->lru, &ashmem_lru_list);
lru_count += range_size(range);
}
static inline void lru_del(struct ashmem_range *range)
{
list_del(&range->lru);
lru_count -= range_size(range);
}
/*
* range_alloc - allocate and initialize a new ashmem_range structure
*
* 'asma' - associated ashmem_area
* 'prev_range' - the previous ashmem_range in the sorted asma->unpinned list
* 'purged' - initial purge value (ASMEM_NOT_PURGED or ASHMEM_WAS_PURGED)
* 'start' - starting page, inclusive
* 'end' - ending page, inclusive
*
* Caller must hold ashmem_mutex.
*/
static int range_alloc(struct ashmem_area *asma,
struct ashmem_range *prev_range, unsigned int purged,
size_t start, size_t end)
{
struct ashmem_range *range;
range = kmem_cache_zalloc(ashmem_range_cachep, GFP_KERNEL);
if (unlikely(!range))
return -ENOMEM;
range->asma = asma;
range->pgstart = start;
range->pgend = end;
range->purged = purged;
list_add_tail(&range->unpinned, &prev_range->unpinned);
if (range_on_lru(range))
lru_add(range);
return 0;
}
static void range_del(struct ashmem_range *range)
{
list_del(&range->unpinned);
if (range_on_lru(range))
lru_del(range);
kmem_cache_free(ashmem_range_cachep, range);
}
/*
* range_shrink - shrinks a range
*
* Caller must hold ashmem_mutex.
*/
static inline void range_shrink(struct ashmem_range *range,
size_t start, size_t end)
{
size_t pre = range_size(range);
range->pgstart = start;
range->pgend = end;
if (range_on_lru(range))
lru_count -= pre - range_size(range);
}
static int ashmem_open(struct inode *inode, struct file *file)
{
struct ashmem_area *asma;
int ret;
ret = generic_file_open(inode, file);
if (unlikely(ret))
return ret;
asma = kmem_cache_zalloc(ashmem_area_cachep, GFP_KERNEL);
if (unlikely(!asma))
return -ENOMEM;
INIT_LIST_HEAD(&asma->unpinned_list);
memcpy(asma->name, ASHMEM_NAME_PREFIX, ASHMEM_NAME_PREFIX_LEN);
asma->prot_mask = PROT_MASK;
file->private_data = asma;
return 0;
}
static int ashmem_release(struct inode *ignored, struct file *file)
{
struct ashmem_area *asma = file->private_data;
struct ashmem_range *range, *next;
mutex_lock(&ashmem_mutex);
list_for_each_entry_safe(range, next, &asma->unpinned_list, unpinned)
range_del(range);
mutex_unlock(&ashmem_mutex);
if (asma->file)
fput(asma->file);
kmem_cache_free(ashmem_area_cachep, asma);
return 0;
}
static ssize_t ashmem_read(struct file *file, char __user *buf,
size_t len, loff_t *pos)
{
struct ashmem_area *asma = file->private_data;
int ret = 0;
mutex_lock(&ashmem_mutex);
/* If size is not set, or set to 0, always return EOF. */
if (asma->size == 0) {
goto out;
}
if (!asma->file) {
ret = -EBADF;
goto out;
}
ret = asma->file->f_op->read(asma->file, buf, len, pos);
if (ret < 0) {
goto out;
}
/** Update backing file pos, since f_ops->read() doesn't */
asma->file->f_pos = *pos;
out:
mutex_unlock(&ashmem_mutex);
return ret;
}
static loff_t ashmem_llseek(struct file *file, loff_t offset, int origin)
{
struct ashmem_area *asma = file->private_data;
int ret;
mutex_lock(&ashmem_mutex);
if (asma->size == 0) {
ret = -EINVAL;
goto out;
}
if (!asma->file) {
ret = -EBADF;
goto out;
}
ret = asma->file->f_op->llseek(asma->file, offset, origin);
if (ret < 0) {
goto out;
}
/** Copy f_pos from backing file, since f_ops->llseek() sets it */
file->f_pos = asma->file->f_pos;
out:
mutex_unlock(&ashmem_mutex);
return ret;
}
static inline unsigned long
calc_vm_may_flags(unsigned long prot)
{
return _calc_vm_trans(prot, PROT_READ, VM_MAYREAD ) |
_calc_vm_trans(prot, PROT_WRITE, VM_MAYWRITE) |
_calc_vm_trans(prot, PROT_EXEC, VM_MAYEXEC);
}
static int ashmem_mmap(struct file *file, struct vm_area_struct *vma)
{
struct ashmem_area *asma = file->private_data;
int ret = 0;
mutex_lock(&ashmem_mutex);
/* user needs to SET_SIZE before mapping */
if (unlikely(!asma->size)) {
ret = -EINVAL;
goto out;
}
/* requested protection bits must match our allowed protection mask */
if (unlikely((vma->vm_flags & ~calc_vm_prot_bits(asma->prot_mask)) &
calc_vm_prot_bits(PROT_MASK))) {
ret = -EPERM;
goto out;
}
vma->vm_flags &= ~calc_vm_may_flags(~asma->prot_mask);
if (!asma->file) {
char *name = ASHMEM_NAME_DEF;
struct file *vmfile;
if (asma->name[ASHMEM_NAME_PREFIX_LEN] != '\0')
name = asma->name;
/* ... and allocate the backing shmem file */
vmfile = shmem_file_setup(name, asma->size, vma->vm_flags);
if (unlikely(IS_ERR(vmfile))) {
ret = PTR_ERR(vmfile);
goto out;
}
asma->file = vmfile;
}
get_file(asma->file);
if (vma->vm_flags & VM_SHARED)
shmem_set_file(vma, asma->file);
else {
if (vma->vm_file)
fput(vma->vm_file);
vma->vm_file = asma->file;
}
vma->vm_flags |= VM_CAN_NONLINEAR;
out:
mutex_unlock(&ashmem_mutex);
return ret;
}
/*
* ashmem_shrink - our cache shrinker, called from mm/vmscan.c :: shrink_slab
*
* 'nr_to_scan' is the number of objects (pages) to prune, or 0 to query how
* many objects (pages) we have in total.
*
* 'gfp_mask' is the mask of the allocation that got us into this mess.
*
* Return value is the number of objects (pages) remaining, or -1 if we cannot
* proceed without risk of deadlock (due to gfp_mask).
*
* We approximate LRU via least-recently-unpinned, jettisoning unpinned partial
* chunks of ashmem regions LRU-wise one-at-a-time until we hit 'nr_to_scan'
* pages freed.
*/
static int ashmem_shrink(struct shrinker *s, struct shrink_control *sc)
{
struct ashmem_range *range, *next;
/* We might recurse into filesystem code, so bail out if necessary */
if (sc->nr_to_scan && !(sc->gfp_mask & __GFP_FS))
return -1;
if (!sc->nr_to_scan)
return lru_count;
mutex_lock(&ashmem_mutex);
list_for_each_entry_safe(range, next, &ashmem_lru_list, lru) {
struct inode *inode = range->asma->file->f_dentry->d_inode;
loff_t start = range->pgstart * PAGE_SIZE;
loff_t end = (range->pgend + 1) * PAGE_SIZE - 1;
vmtruncate_range(inode, start, end);
range->purged = ASHMEM_WAS_PURGED;
lru_del(range);
sc->nr_to_scan -= range_size(range);
if (sc->nr_to_scan <= 0)
break;
}
mutex_unlock(&ashmem_mutex);
return lru_count;
}
static struct shrinker ashmem_shrinker = {
.shrink = ashmem_shrink,
.seeks = DEFAULT_SEEKS * 4,
};
static int set_prot_mask(struct ashmem_area *asma, unsigned long prot)
{
int ret = 0;
mutex_lock(&ashmem_mutex);
/* the user can only remove, not add, protection bits */
if (unlikely((asma->prot_mask & prot) != prot)) {
ret = -EINVAL;
goto out;
}
/* does the application expect PROT_READ to imply PROT_EXEC? */
if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
prot |= PROT_EXEC;
asma->prot_mask = prot;
out:
mutex_unlock(&ashmem_mutex);
return ret;
}
static int set_name(struct ashmem_area *asma, void __user *name)
{
int ret = 0;
mutex_lock(&ashmem_mutex);
/* cannot change an existing mapping's name */
if (unlikely(asma->file)) {
ret = -EINVAL;
goto out;
}
if (unlikely(copy_from_user(asma->name + ASHMEM_NAME_PREFIX_LEN,
name, ASHMEM_NAME_LEN)))
ret = -EFAULT;
asma->name[ASHMEM_FULL_NAME_LEN-1] = '\0';
out:
mutex_unlock(&ashmem_mutex);
return ret;
}
static int get_name(struct ashmem_area *asma, void __user *name)
{
int ret = 0;
mutex_lock(&ashmem_mutex);
if (asma->name[ASHMEM_NAME_PREFIX_LEN] != '\0') {
size_t len;
/*
* Copying only `len', instead of ASHMEM_NAME_LEN, bytes
* prevents us from revealing one user's stack to another.
*/
len = strlen(asma->name + ASHMEM_NAME_PREFIX_LEN) + 1;
if (unlikely(copy_to_user(name,
asma->name + ASHMEM_NAME_PREFIX_LEN, len)))
ret = -EFAULT;
} else {
if (unlikely(copy_to_user(name, ASHMEM_NAME_DEF,
sizeof(ASHMEM_NAME_DEF))))
ret = -EFAULT;
}
mutex_unlock(&ashmem_mutex);
return ret;
}
/*
* ashmem_pin - pin the given ashmem region, returning whether it was
* previously purged (ASHMEM_WAS_PURGED) or not (ASHMEM_NOT_PURGED).
*
* Caller must hold ashmem_mutex.
*/
static int ashmem_pin(struct ashmem_area *asma, size_t pgstart, size_t pgend)
{
struct ashmem_range *range, *next;
int ret = ASHMEM_NOT_PURGED;
list_for_each_entry_safe(range, next, &asma->unpinned_list, unpinned) {
/* moved past last applicable page; we can short circuit */
if (range_before_page(range, pgstart))
break;
/*
* The user can ask us to pin pages that span multiple ranges,
* or to pin pages that aren't even unpinned, so this is messy.
*
* Four cases:
* 1. The requested range subsumes an existing range, so we
* just remove the entire matching range.
* 2. The requested range overlaps the start of an existing
* range, so we just update that range.
* 3. The requested range overlaps the end of an existing
* range, so we just update that range.
* 4. The requested range punches a hole in an existing range,
* so we have to update one side of the range and then
* create a new range for the other side.
*/
if (page_range_in_range(range, pgstart, pgend)) {
ret |= range->purged;
/* Case #1: Easy. Just nuke the whole thing. */
if (page_range_subsumes_range(range, pgstart, pgend)) {
range_del(range);
continue;
}
/* Case #2: We overlap from the start, so adjust it */
if (range->pgstart >= pgstart) {
range_shrink(range, pgend + 1, range->pgend);
continue;
}
/* Case #3: We overlap from the rear, so adjust it */
if (range->pgend <= pgend) {
range_shrink(range, range->pgstart, pgstart-1);
continue;
}
/*
* Case #4: We eat a chunk out of the middle. A bit
* more complicated, we allocate a new range for the
* second half and adjust the first chunk's endpoint.
*/
range_alloc(asma, range, range->purged,
pgend + 1, range->pgend);
range_shrink(range, range->pgstart, pgstart - 1);
break;
}
}
return ret;
}
/*
* ashmem_unpin - unpin the given range of pages. Returns zero on success.
*
* Caller must hold ashmem_mutex.
*/
static int ashmem_unpin(struct ashmem_area *asma, size_t pgstart, size_t pgend)
{
struct ashmem_range *range, *next;
unsigned int purged = ASHMEM_NOT_PURGED;
restart:
list_for_each_entry_safe(range, next, &asma->unpinned_list, unpinned) {
/* short circuit: this is our insertion point */
if (range_before_page(range, pgstart))
break;
/*
* The user can ask us to unpin pages that are already entirely
* or partially pinned. We handle those two cases here.
*/
if (page_range_subsumed_by_range(range, pgstart, pgend))
return 0;
if (page_range_in_range(range, pgstart, pgend)) {
pgstart = min_t(size_t, range->pgstart, pgstart),
pgend = max_t(size_t, range->pgend, pgend);
purged |= range->purged;
range_del(range);
goto restart;
}
}
return range_alloc(asma, range, purged, pgstart, pgend);
}
/*
* ashmem_get_pin_status - Returns ASHMEM_IS_UNPINNED if _any_ pages in the
* given interval are unpinned and ASHMEM_IS_PINNED otherwise.
*
* Caller must hold ashmem_mutex.
*/
static int ashmem_get_pin_status(struct ashmem_area *asma, size_t pgstart,
size_t pgend)
{
struct ashmem_range *range;
int ret = ASHMEM_IS_PINNED;
list_for_each_entry(range, &asma->unpinned_list, unpinned) {
if (range_before_page(range, pgstart))
break;
if (page_range_in_range(range, pgstart, pgend)) {
ret = ASHMEM_IS_UNPINNED;
break;
}
}
return ret;
}
static int ashmem_pin_unpin(struct ashmem_area *asma, unsigned long cmd,
void __user *p)
{
struct ashmem_pin pin;
size_t pgstart, pgend;
int ret = -EINVAL;
if (unlikely(!asma->file))
return -EINVAL;
if (unlikely(copy_from_user(&pin, p, sizeof(pin))))
return -EFAULT;
/* per custom, you can pass zero for len to mean "everything onward" */
if (!pin.len)
pin.len = PAGE_ALIGN(asma->size) - pin.offset;
if (unlikely((pin.offset | pin.len) & ~PAGE_MASK))
return -EINVAL;
if (unlikely(((__u32) -1) - pin.offset < pin.len))
return -EINVAL;
if (unlikely(PAGE_ALIGN(asma->size) < pin.offset + pin.len))
return -EINVAL;
pgstart = pin.offset / PAGE_SIZE;
pgend = pgstart + (pin.len / PAGE_SIZE) - 1;
mutex_lock(&ashmem_mutex);
switch (cmd) {
case ASHMEM_PIN:
ret = ashmem_pin(asma, pgstart, pgend);
break;
case ASHMEM_UNPIN:
ret = ashmem_unpin(asma, pgstart, pgend);
break;
case ASHMEM_GET_PIN_STATUS:
ret = ashmem_get_pin_status(asma, pgstart, pgend);
break;
}
mutex_unlock(&ashmem_mutex);
return ret;
}
static long ashmem_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct ashmem_area *asma = file->private_data;
long ret = -ENOTTY;
switch (cmd) {
case ASHMEM_SET_NAME:
ret = set_name(asma, (void __user *) arg);
break;
case ASHMEM_GET_NAME:
ret = get_name(asma, (void __user *) arg);
break;
case ASHMEM_SET_SIZE:
ret = -EINVAL;
if (!asma->file) {
ret = 0;
asma->size = (size_t) arg;
}
break;
case ASHMEM_GET_SIZE:
ret = asma->size;
break;
case ASHMEM_SET_PROT_MASK:
ret = set_prot_mask(asma, arg);
break;
case ASHMEM_GET_PROT_MASK:
ret = asma->prot_mask;
break;
case ASHMEM_PIN:
case ASHMEM_UNPIN:
case ASHMEM_GET_PIN_STATUS:
ret = ashmem_pin_unpin(asma, cmd, (void __user *) arg);
break;
case ASHMEM_PURGE_ALL_CACHES:
ret = -EPERM;
if (capable(CAP_SYS_ADMIN)) {
struct shrink_control sc = {
.gfp_mask = GFP_KERNEL,
.nr_to_scan = 0,
};
ret = ashmem_shrink(&ashmem_shrinker, &sc);
sc.nr_to_scan = ret;
ashmem_shrink(&ashmem_shrinker, &sc);
}
break;
}
return ret;
}
static struct file_operations ashmem_fops = {
.owner = THIS_MODULE,
.open = ashmem_open,
.release = ashmem_release,
.read = ashmem_read,
.llseek = ashmem_llseek,
.mmap = ashmem_mmap,
.unlocked_ioctl = ashmem_ioctl,
.compat_ioctl = ashmem_ioctl,
};
static struct miscdevice ashmem_misc = {
.minor = MISC_DYNAMIC_MINOR,
.name = "ashmem",
.fops = &ashmem_fops,
};
static int __init ashmem_init(void)
{
int ret;
ashmem_area_cachep = kmem_cache_create("ashmem_area_cache",
sizeof(struct ashmem_area),
0, 0, NULL);
if (unlikely(!ashmem_area_cachep)) {
printk(KERN_ERR "ashmem: failed to create slab cache\n");
return -ENOMEM;
}
ashmem_range_cachep = kmem_cache_create("ashmem_range_cache",
sizeof(struct ashmem_range),
0, 0, NULL);
if (unlikely(!ashmem_range_cachep)) {
printk(KERN_ERR "ashmem: failed to create slab cache\n");
return -ENOMEM;
}
ret = misc_register(&ashmem_misc);
if (unlikely(ret)) {
printk(KERN_ERR "ashmem: failed to register misc device!\n");
return ret;
}
register_shrinker(&ashmem_shrinker);
printk(KERN_INFO "ashmem: initialized\n");
return 0;
}
static void __exit ashmem_exit(void)
{
int ret;
unregister_shrinker(&ashmem_shrinker);
ret = misc_deregister(&ashmem_misc);
if (unlikely(ret))
printk(KERN_ERR "ashmem: failed to unregister misc device!\n");
kmem_cache_destroy(ashmem_range_cachep);
kmem_cache_destroy(ashmem_area_cachep);
printk(KERN_INFO "ashmem: unloaded\n");
}
module_init(ashmem_init);
module_exit(ashmem_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
DirtyUnicorns/android_kernel_samsung_tuna | arch/blackfin/mach-bf527/boards/cm_bf527.c | 2440 | 24348 | /*
* Copyright 2004-2009 Analog Devices Inc.
* 2008-2009 Bluetechnix
* 2005 National ICT Australia (NICTA)
* Aidan Williams <aidan@nicta.com.au>
*
* Licensed under the GPL-2 or later.
*/
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/physmap.h>
#include <linux/spi/spi.h>
#include <linux/spi/flash.h>
#include <linux/etherdevice.h>
#include <linux/i2c.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/usb/musb.h>
#include <asm/dma.h>
#include <asm/bfin5xx_spi.h>
#include <asm/reboot.h>
#include <asm/nand.h>
#include <asm/portmux.h>
#include <asm/dpmc.h>
#include <linux/spi/ad7877.h>
/*
* Name the Board for the /proc/cpuinfo
*/
const char bfin_board_name[] = "Bluetechnix CM-BF527";
/*
* Driver needs to know address, irq and flag pin.
*/
#if defined(CONFIG_USB_ISP1760_HCD) || defined(CONFIG_USB_ISP1760_HCD_MODULE)
#include <linux/usb/isp1760.h>
static struct resource bfin_isp1760_resources[] = {
[0] = {
.start = 0x203C0000,
.end = 0x203C0000 + 0x000fffff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_PF7,
.end = IRQ_PF7,
.flags = IORESOURCE_IRQ,
},
};
static struct isp1760_platform_data isp1760_priv = {
.is_isp1761 = 0,
.bus_width_16 = 1,
.port1_otg = 0,
.analog_oc = 0,
.dack_polarity_high = 0,
.dreq_polarity_high = 0,
};
static struct platform_device bfin_isp1760_device = {
.name = "isp1760",
.id = 0,
.dev = {
.platform_data = &isp1760_priv,
},
.num_resources = ARRAY_SIZE(bfin_isp1760_resources),
.resource = bfin_isp1760_resources,
};
#endif
#if defined(CONFIG_USB_MUSB_HDRC) || defined(CONFIG_USB_MUSB_HDRC_MODULE)
static struct resource musb_resources[] = {
[0] = {
.start = 0xffc03800,
.end = 0xffc03cff,
.flags = IORESOURCE_MEM,
},
[1] = { /* general IRQ */
.start = IRQ_USB_INT0,
.end = IRQ_USB_INT0,
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHLEVEL,
.name = "mc"
},
[2] = { /* DMA IRQ */
.start = IRQ_USB_DMA,
.end = IRQ_USB_DMA,
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHLEVEL,
.name = "dma"
},
};
static struct musb_hdrc_config musb_config = {
.multipoint = 0,
.dyn_fifo = 0,
.soft_con = 1,
.dma = 1,
.num_eps = 8,
.dma_channels = 8,
.gpio_vrsel = GPIO_PF11,
/* Some custom boards need to be active low, just set it to "0"
* if it is the case.
*/
.gpio_vrsel_active = 1,
.clkin = 24, /* musb CLKIN in MHZ */
};
static struct musb_hdrc_platform_data musb_plat = {
#if defined(CONFIG_USB_MUSB_OTG)
.mode = MUSB_OTG,
#elif defined(CONFIG_USB_MUSB_HDRC_HCD)
.mode = MUSB_HOST,
#elif defined(CONFIG_USB_GADGET_MUSB_HDRC)
.mode = MUSB_PERIPHERAL,
#endif
.config = &musb_config,
};
static u64 musb_dmamask = ~(u32)0;
static struct platform_device musb_device = {
.name = "musb-blackfin",
.id = 0,
.dev = {
.dma_mask = &musb_dmamask,
.coherent_dma_mask = 0xffffffff,
.platform_data = &musb_plat,
},
.num_resources = ARRAY_SIZE(musb_resources),
.resource = musb_resources,
};
#endif
#if defined(CONFIG_MTD_NAND_BF5XX) || defined(CONFIG_MTD_NAND_BF5XX_MODULE)
static struct mtd_partition partition_info[] = {
{
.name = "linux kernel(nand)",
.offset = 0,
.size = 4 * 1024 * 1024,
},
{
.name = "file system(nand)",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
},
};
static struct bf5xx_nand_platform bf5xx_nand_platform = {
.data_width = NFC_NWIDTH_8,
.partitions = partition_info,
.nr_partitions = ARRAY_SIZE(partition_info),
.rd_dly = 3,
.wr_dly = 3,
};
static struct resource bf5xx_nand_resources[] = {
{
.start = NFC_CTL,
.end = NFC_DATA_RD + 2,
.flags = IORESOURCE_MEM,
},
{
.start = CH_NFC,
.end = CH_NFC,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device bf5xx_nand_device = {
.name = "bf5xx-nand",
.id = 0,
.num_resources = ARRAY_SIZE(bf5xx_nand_resources),
.resource = bf5xx_nand_resources,
.dev = {
.platform_data = &bf5xx_nand_platform,
},
};
#endif
#if defined(CONFIG_BFIN_CFPCMCIA) || defined(CONFIG_BFIN_CFPCMCIA_MODULE)
static struct resource bfin_pcmcia_cf_resources[] = {
{
.start = 0x20310000, /* IO PORT */
.end = 0x20312000,
.flags = IORESOURCE_MEM,
}, {
.start = 0x20311000, /* Attribute Memory */
.end = 0x20311FFF,
.flags = IORESOURCE_MEM,
}, {
.start = IRQ_PF4,
.end = IRQ_PF4,
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_LOWLEVEL,
}, {
.start = 6, /* Card Detect PF6 */
.end = 6,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device bfin_pcmcia_cf_device = {
.name = "bfin_cf_pcmcia",
.id = -1,
.num_resources = ARRAY_SIZE(bfin_pcmcia_cf_resources),
.resource = bfin_pcmcia_cf_resources,
};
#endif
#if defined(CONFIG_RTC_DRV_BFIN) || defined(CONFIG_RTC_DRV_BFIN_MODULE)
static struct platform_device rtc_device = {
.name = "rtc-bfin",
.id = -1,
};
#endif
#if defined(CONFIG_SMC91X) || defined(CONFIG_SMC91X_MODULE)
#include <linux/smc91x.h>
static struct smc91x_platdata smc91x_info = {
.flags = SMC91X_USE_16BIT | SMC91X_NOWAIT,
.leda = RPC_LED_100_10,
.ledb = RPC_LED_TX_RX,
};
static struct resource smc91x_resources[] = {
{
.name = "smc91x-regs",
.start = 0x20300300,
.end = 0x20300300 + 16,
.flags = IORESOURCE_MEM,
}, {
.start = IRQ_PF7,
.end = IRQ_PF7,
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHLEVEL,
},
};
static struct platform_device smc91x_device = {
.name = "smc91x",
.id = 0,
.num_resources = ARRAY_SIZE(smc91x_resources),
.resource = smc91x_resources,
.dev = {
.platform_data = &smc91x_info,
},
};
#endif
#if defined(CONFIG_DM9000) || defined(CONFIG_DM9000_MODULE)
static struct resource dm9000_resources[] = {
[0] = {
.start = 0x203FB800,
.end = 0x203FB800 + 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 0x203FB804,
.end = 0x203FB804 + 1,
.flags = IORESOURCE_MEM,
},
[2] = {
.start = IRQ_PF9,
.end = IRQ_PF9,
.flags = (IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHEDGE),
},
};
static struct platform_device dm9000_device = {
.name = "dm9000",
.id = -1,
.num_resources = ARRAY_SIZE(dm9000_resources),
.resource = dm9000_resources,
};
#endif
#if defined(CONFIG_BFIN_MAC) || defined(CONFIG_BFIN_MAC_MODULE)
#include <linux/bfin_mac.h>
static const unsigned short bfin_mac_peripherals[] = P_RMII0;
static struct bfin_phydev_platform_data bfin_phydev_data[] = {
{
.addr = 1,
.irq = IRQ_MAC_PHYINT,
},
};
static struct bfin_mii_bus_platform_data bfin_mii_bus_data = {
.phydev_number = 1,
.phydev_data = bfin_phydev_data,
.phy_mode = PHY_INTERFACE_MODE_RMII,
.mac_peripherals = bfin_mac_peripherals,
};
static struct platform_device bfin_mii_bus = {
.name = "bfin_mii_bus",
.dev = {
.platform_data = &bfin_mii_bus_data,
}
};
static struct platform_device bfin_mac_device = {
.name = "bfin_mac",
.dev = {
.platform_data = &bfin_mii_bus,
}
};
#endif
#if defined(CONFIG_USB_NET2272) || defined(CONFIG_USB_NET2272_MODULE)
static struct resource net2272_bfin_resources[] = {
{
.start = 0x20300000,
.end = 0x20300000 + 0x100,
.flags = IORESOURCE_MEM,
}, {
.start = IRQ_PF7,
.end = IRQ_PF7,
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHLEVEL,
},
};
static struct platform_device net2272_bfin_device = {
.name = "net2272",
.id = -1,
.num_resources = ARRAY_SIZE(net2272_bfin_resources),
.resource = net2272_bfin_resources,
};
#endif
#if defined(CONFIG_MTD_M25P80) \
|| defined(CONFIG_MTD_M25P80_MODULE)
static struct mtd_partition bfin_spi_flash_partitions[] = {
{
.name = "bootloader(spi)",
.size = 0x00040000,
.offset = 0,
.mask_flags = MTD_CAP_ROM
}, {
.name = "linux kernel(spi)",
.size = MTDPART_SIZ_FULL,
.offset = MTDPART_OFS_APPEND,
}
};
static struct flash_platform_data bfin_spi_flash_data = {
.name = "m25p80",
.parts = bfin_spi_flash_partitions,
.nr_parts = ARRAY_SIZE(bfin_spi_flash_partitions),
.type = "m25p16",
};
/* SPI flash chip (m25p64) */
static struct bfin5xx_spi_chip spi_flash_chip_info = {
.enable_dma = 0, /* use dma transfer with this chip*/
.bits_per_word = 8,
};
#endif
#if defined(CONFIG_BFIN_SPI_ADC) \
|| defined(CONFIG_BFIN_SPI_ADC_MODULE)
/* SPI ADC chip */
static struct bfin5xx_spi_chip spi_adc_chip_info = {
.enable_dma = 1, /* use dma transfer with this chip*/
.bits_per_word = 16,
};
#endif
#if defined(CONFIG_SND_BF5XX_SOC_AD183X) \
|| defined(CONFIG_SND_BF5XX_SOC_AD183X_MODULE)
static struct bfin5xx_spi_chip ad1836_spi_chip_info = {
.enable_dma = 0,
.bits_per_word = 16,
};
#endif
#if defined(CONFIG_MMC_SPI) || defined(CONFIG_MMC_SPI_MODULE)
static struct bfin5xx_spi_chip mmc_spi_chip_info = {
.enable_dma = 0,
.bits_per_word = 8,
};
#endif
#if defined(CONFIG_TOUCHSCREEN_AD7877) || defined(CONFIG_TOUCHSCREEN_AD7877_MODULE)
static struct bfin5xx_spi_chip spi_ad7877_chip_info = {
.enable_dma = 0,
.bits_per_word = 16,
};
static const struct ad7877_platform_data bfin_ad7877_ts_info = {
.model = 7877,
.vref_delay_usecs = 50, /* internal, no capacitor */
.x_plate_ohms = 419,
.y_plate_ohms = 486,
.pressure_max = 1000,
.pressure_min = 0,
.stopacq_polarity = 1,
.first_conversion_delay = 3,
.acquisition_time = 1,
.averaging = 1,
.pen_down_acc_interval = 1,
};
#endif
#if defined(CONFIG_SND_SOC_WM8731) || defined(CONFIG_SND_SOC_WM8731_MODULE) \
&& defined(CONFIG_SND_SOC_WM8731_SPI)
static struct bfin5xx_spi_chip spi_wm8731_chip_info = {
.enable_dma = 0,
.bits_per_word = 16,
};
#endif
#if defined(CONFIG_SPI_SPIDEV) || defined(CONFIG_SPI_SPIDEV_MODULE)
static struct bfin5xx_spi_chip spidev_chip_info = {
.enable_dma = 0,
.bits_per_word = 8,
};
#endif
static struct spi_board_info bfin_spi_board_info[] __initdata = {
#if defined(CONFIG_MTD_M25P80) \
|| defined(CONFIG_MTD_M25P80_MODULE)
{
/* the modalias must be the same as spi device driver name */
.modalias = "m25p80", /* Name of spi_driver for this device */
.max_speed_hz = 25000000, /* max spi clock (SCK) speed in HZ */
.bus_num = 0, /* Framework bus number */
.chip_select = 1, /* Framework chip select. On STAMP537 it is SPISSEL1*/
.platform_data = &bfin_spi_flash_data,
.controller_data = &spi_flash_chip_info,
.mode = SPI_MODE_3,
},
#endif
#if defined(CONFIG_BFIN_SPI_ADC) \
|| defined(CONFIG_BFIN_SPI_ADC_MODULE)
{
.modalias = "bfin_spi_adc", /* Name of spi_driver for this device */
.max_speed_hz = 6250000, /* max spi clock (SCK) speed in HZ */
.bus_num = 0, /* Framework bus number */
.chip_select = 1, /* Framework chip select. */
.platform_data = NULL, /* No spi_driver specific config */
.controller_data = &spi_adc_chip_info,
},
#endif
#if defined(CONFIG_SND_BF5XX_SOC_AD183X) \
|| defined(CONFIG_SND_BF5XX_SOC_AD183X_MODULE)
{
.modalias = "ad183x",
.max_speed_hz = 3125000, /* max spi clock (SCK) speed in HZ */
.bus_num = 0,
.chip_select = 4,
.controller_data = &ad1836_spi_chip_info,
},
#endif
#if defined(CONFIG_MMC_SPI) || defined(CONFIG_MMC_SPI_MODULE)
{
.modalias = "mmc_spi",
.max_speed_hz = 20000000, /* max spi clock (SCK) speed in HZ */
.bus_num = 0,
.chip_select = 5,
.controller_data = &mmc_spi_chip_info,
.mode = SPI_MODE_3,
},
#endif
#if defined(CONFIG_TOUCHSCREEN_AD7877) || defined(CONFIG_TOUCHSCREEN_AD7877_MODULE)
{
.modalias = "ad7877",
.platform_data = &bfin_ad7877_ts_info,
.irq = IRQ_PF8,
.max_speed_hz = 12500000, /* max spi clock (SCK) speed in HZ */
.bus_num = 0,
.chip_select = 2,
.controller_data = &spi_ad7877_chip_info,
},
#endif
#if defined(CONFIG_SND_SOC_WM8731) || defined(CONFIG_SND_SOC_WM8731_MODULE) \
&& defined(CONFIG_SND_SOC_WM8731_SPI)
{
.modalias = "wm8731",
.max_speed_hz = 3125000, /* max spi clock (SCK) speed in HZ */
.bus_num = 0,
.chip_select = 5,
.controller_data = &spi_wm8731_chip_info,
.mode = SPI_MODE_0,
},
#endif
#if defined(CONFIG_SPI_SPIDEV) || defined(CONFIG_SPI_SPIDEV_MODULE)
{
.modalias = "spidev",
.max_speed_hz = 3125000, /* max spi clock (SCK) speed in HZ */
.bus_num = 0,
.chip_select = 1,
.controller_data = &spidev_chip_info,
},
#endif
};
#if defined(CONFIG_SPI_BFIN) || defined(CONFIG_SPI_BFIN_MODULE)
/* SPI controller data */
static struct bfin5xx_spi_master bfin_spi0_info = {
.num_chipselect = 8,
.enable_dma = 1, /* master has the ability to do dma transfer */
.pin_req = {P_SPI0_SCK, P_SPI0_MISO, P_SPI0_MOSI, 0},
};
/* SPI (0) */
static struct resource bfin_spi0_resource[] = {
[0] = {
.start = SPI0_REGBASE,
.end = SPI0_REGBASE + 0xFF,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = CH_SPI,
.end = CH_SPI,
.flags = IORESOURCE_DMA,
},
[2] = {
.start = IRQ_SPI,
.end = IRQ_SPI,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device bfin_spi0_device = {
.name = "bfin-spi",
.id = 0, /* Bus number */
.num_resources = ARRAY_SIZE(bfin_spi0_resource),
.resource = bfin_spi0_resource,
.dev = {
.platform_data = &bfin_spi0_info, /* Passed to driver */
},
};
#endif /* spi master and devices */
#if defined(CONFIG_MTD_GPIO_ADDR) || defined(CONFIG_MTD_GPIO_ADDR_MODULE)
static struct mtd_partition cm_partitions[] = {
{
.name = "bootloader(nor)",
.size = 0x40000,
.offset = 0,
}, {
.name = "linux kernel(nor)",
.size = 0x100000,
.offset = MTDPART_OFS_APPEND,
}, {
.name = "file system(nor)",
.size = MTDPART_SIZ_FULL,
.offset = MTDPART_OFS_APPEND,
}
};
static struct physmap_flash_data cm_flash_data = {
.width = 2,
.parts = cm_partitions,
.nr_parts = ARRAY_SIZE(cm_partitions),
};
static unsigned cm_flash_gpios[] = { GPIO_PH9, GPIO_PG11 };
static struct resource cm_flash_resource[] = {
{
.name = "cfi_probe",
.start = 0x20000000,
.end = 0x201fffff,
.flags = IORESOURCE_MEM,
}, {
.start = (unsigned long)cm_flash_gpios,
.end = ARRAY_SIZE(cm_flash_gpios),
.flags = IORESOURCE_IRQ,
}
};
static struct platform_device cm_flash_device = {
.name = "gpio-addr-flash",
.id = 0,
.dev = {
.platform_data = &cm_flash_data,
},
.num_resources = ARRAY_SIZE(cm_flash_resource),
.resource = cm_flash_resource,
};
#endif
#if defined(CONFIG_SERIAL_BFIN) || defined(CONFIG_SERIAL_BFIN_MODULE)
#ifdef CONFIG_SERIAL_BFIN_UART0
static struct resource bfin_uart0_resources[] = {
{
.start = UART0_THR,
.end = UART0_GCTL+2,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_UART0_RX,
.end = IRQ_UART0_RX+1,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_UART0_ERROR,
.end = IRQ_UART0_ERROR,
.flags = IORESOURCE_IRQ,
},
{
.start = CH_UART0_TX,
.end = CH_UART0_TX,
.flags = IORESOURCE_DMA,
},
{
.start = CH_UART0_RX,
.end = CH_UART0_RX,
.flags = IORESOURCE_DMA,
},
};
static unsigned short bfin_uart0_peripherals[] = {
P_UART0_TX, P_UART0_RX, 0
};
static struct platform_device bfin_uart0_device = {
.name = "bfin-uart",
.id = 0,
.num_resources = ARRAY_SIZE(bfin_uart0_resources),
.resource = bfin_uart0_resources,
.dev = {
.platform_data = &bfin_uart0_peripherals, /* Passed to driver */
},
};
#endif
#ifdef CONFIG_SERIAL_BFIN_UART1
static struct resource bfin_uart1_resources[] = {
{
.start = UART1_THR,
.end = UART1_GCTL+2,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_UART1_RX,
.end = IRQ_UART1_RX+1,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_UART1_ERROR,
.end = IRQ_UART1_ERROR,
.flags = IORESOURCE_IRQ,
},
{
.start = CH_UART1_TX,
.end = CH_UART1_TX,
.flags = IORESOURCE_DMA,
},
{
.start = CH_UART1_RX,
.end = CH_UART1_RX,
.flags = IORESOURCE_DMA,
},
#ifdef CONFIG_BFIN_UART1_CTSRTS
{ /* CTS pin */
.start = GPIO_PF9,
.end = GPIO_PF9,
.flags = IORESOURCE_IO,
},
{ /* RTS pin */
.start = GPIO_PF10,
.end = GPIO_PF10,
.flags = IORESOURCE_IO,
},
#endif
};
static unsigned short bfin_uart1_peripherals[] = {
P_UART1_TX, P_UART1_RX, 0
};
static struct platform_device bfin_uart1_device = {
.name = "bfin-uart",
.id = 1,
.num_resources = ARRAY_SIZE(bfin_uart1_resources),
.resource = bfin_uart1_resources,
.dev = {
.platform_data = &bfin_uart1_peripherals, /* Passed to driver */
},
};
#endif
#endif
#if defined(CONFIG_BFIN_SIR) || defined(CONFIG_BFIN_SIR_MODULE)
#ifdef CONFIG_BFIN_SIR0
static struct resource bfin_sir0_resources[] = {
{
.start = 0xFFC00400,
.end = 0xFFC004FF,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_UART0_RX,
.end = IRQ_UART0_RX+1,
.flags = IORESOURCE_IRQ,
},
{
.start = CH_UART0_RX,
.end = CH_UART0_RX+1,
.flags = IORESOURCE_DMA,
},
};
static struct platform_device bfin_sir0_device = {
.name = "bfin_sir",
.id = 0,
.num_resources = ARRAY_SIZE(bfin_sir0_resources),
.resource = bfin_sir0_resources,
};
#endif
#ifdef CONFIG_BFIN_SIR1
static struct resource bfin_sir1_resources[] = {
{
.start = 0xFFC02000,
.end = 0xFFC020FF,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_UART1_RX,
.end = IRQ_UART1_RX+1,
.flags = IORESOURCE_IRQ,
},
{
.start = CH_UART1_RX,
.end = CH_UART1_RX+1,
.flags = IORESOURCE_DMA,
},
};
static struct platform_device bfin_sir1_device = {
.name = "bfin_sir",
.id = 1,
.num_resources = ARRAY_SIZE(bfin_sir1_resources),
.resource = bfin_sir1_resources,
};
#endif
#endif
#if defined(CONFIG_I2C_BLACKFIN_TWI) || defined(CONFIG_I2C_BLACKFIN_TWI_MODULE)
static struct resource bfin_twi0_resource[] = {
[0] = {
.start = TWI0_REGBASE,
.end = TWI0_REGBASE,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_TWI,
.end = IRQ_TWI,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device i2c_bfin_twi_device = {
.name = "i2c-bfin-twi",
.id = 0,
.num_resources = ARRAY_SIZE(bfin_twi0_resource),
.resource = bfin_twi0_resource,
};
#endif
static struct i2c_board_info __initdata bfin_i2c_board_info[] = {
#if defined(CONFIG_BFIN_TWI_LCD) || defined(CONFIG_BFIN_TWI_LCD_MODULE)
{
I2C_BOARD_INFO("pcf8574_lcd", 0x22),
},
#endif
#if defined(CONFIG_INPUT_PCF8574) || defined(CONFIG_INPUT_PCF8574_MODULE)
{
I2C_BOARD_INFO("pcf8574_keypad", 0x27),
.irq = IRQ_PF8,
},
#endif
#if defined(CONFIG_FB_BFIN_7393) || defined(CONFIG_FB_BFIN_7393_MODULE)
{
I2C_BOARD_INFO("bfin-adv7393", 0x2B),
},
#endif
};
#if defined(CONFIG_SERIAL_BFIN_SPORT) || defined(CONFIG_SERIAL_BFIN_SPORT_MODULE)
#ifdef CONFIG_SERIAL_BFIN_SPORT0_UART
static struct resource bfin_sport0_uart_resources[] = {
{
.start = SPORT0_TCR1,
.end = SPORT0_MRCS3+4,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_SPORT0_RX,
.end = IRQ_SPORT0_RX+1,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_SPORT0_ERROR,
.end = IRQ_SPORT0_ERROR,
.flags = IORESOURCE_IRQ,
},
};
static unsigned short bfin_sport0_peripherals[] = {
P_SPORT0_TFS, P_SPORT0_DTPRI, P_SPORT0_TSCLK, P_SPORT0_RFS,
P_SPORT0_DRPRI, P_SPORT0_RSCLK, 0
};
static struct platform_device bfin_sport0_uart_device = {
.name = "bfin-sport-uart",
.id = 0,
.num_resources = ARRAY_SIZE(bfin_sport0_uart_resources),
.resource = bfin_sport0_uart_resources,
.dev = {
.platform_data = &bfin_sport0_peripherals, /* Passed to driver */
},
};
#endif
#ifdef CONFIG_SERIAL_BFIN_SPORT1_UART
static struct resource bfin_sport1_uart_resources[] = {
{
.start = SPORT1_TCR1,
.end = SPORT1_MRCS3+4,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_SPORT1_RX,
.end = IRQ_SPORT1_RX+1,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_SPORT1_ERROR,
.end = IRQ_SPORT1_ERROR,
.flags = IORESOURCE_IRQ,
},
};
static unsigned short bfin_sport1_peripherals[] = {
P_SPORT1_TFS, P_SPORT1_DTPRI, P_SPORT1_TSCLK, P_SPORT1_RFS,
P_SPORT1_DRPRI, P_SPORT1_RSCLK, 0
};
static struct platform_device bfin_sport1_uart_device = {
.name = "bfin-sport-uart",
.id = 1,
.num_resources = ARRAY_SIZE(bfin_sport1_uart_resources),
.resource = bfin_sport1_uart_resources,
.dev = {
.platform_data = &bfin_sport1_peripherals, /* Passed to driver */
},
};
#endif
#endif
#if defined(CONFIG_KEYBOARD_GPIO) || defined(CONFIG_KEYBOARD_GPIO_MODULE)
#include <linux/input.h>
#include <linux/gpio_keys.h>
static struct gpio_keys_button bfin_gpio_keys_table[] = {
{BTN_0, GPIO_PF14, 1, "gpio-keys: BTN0"},
};
static struct gpio_keys_platform_data bfin_gpio_keys_data = {
.buttons = bfin_gpio_keys_table,
.nbuttons = ARRAY_SIZE(bfin_gpio_keys_table),
};
static struct platform_device bfin_device_gpiokeys = {
.name = "gpio-keys",
.dev = {
.platform_data = &bfin_gpio_keys_data,
},
};
#endif
static const unsigned int cclk_vlev_datasheet[] =
{
VRPAIR(VLEV_100, 400000000),
VRPAIR(VLEV_105, 426000000),
VRPAIR(VLEV_110, 500000000),
VRPAIR(VLEV_115, 533000000),
VRPAIR(VLEV_120, 600000000),
};
static struct bfin_dpmc_platform_data bfin_dmpc_vreg_data = {
.tuple_tab = cclk_vlev_datasheet,
.tabsize = ARRAY_SIZE(cclk_vlev_datasheet),
.vr_settling_time = 25 /* us */,
};
static struct platform_device bfin_dpmc = {
.name = "bfin dpmc",
.dev = {
.platform_data = &bfin_dmpc_vreg_data,
},
};
static struct platform_device *cmbf527_devices[] __initdata = {
&bfin_dpmc,
#if defined(CONFIG_MTD_NAND_BF5XX) || defined(CONFIG_MTD_NAND_BF5XX_MODULE)
&bf5xx_nand_device,
#endif
#if defined(CONFIG_BFIN_CFPCMCIA) || defined(CONFIG_BFIN_CFPCMCIA_MODULE)
&bfin_pcmcia_cf_device,
#endif
#if defined(CONFIG_RTC_DRV_BFIN) || defined(CONFIG_RTC_DRV_BFIN_MODULE)
&rtc_device,
#endif
#if defined(CONFIG_USB_ISP1760_HCD) || defined(CONFIG_USB_ISP1760_HCD_MODULE)
&bfin_isp1760_device,
#endif
#if defined(CONFIG_USB_MUSB_HDRC) || defined(CONFIG_USB_MUSB_HDRC_MODULE)
&musb_device,
#endif
#if defined(CONFIG_SMC91X) || defined(CONFIG_SMC91X_MODULE)
&smc91x_device,
#endif
#if defined(CONFIG_DM9000) || defined(CONFIG_DM9000_MODULE)
&dm9000_device,
#endif
#if defined(CONFIG_BFIN_MAC) || defined(CONFIG_BFIN_MAC_MODULE)
&bfin_mii_bus,
&bfin_mac_device,
#endif
#if defined(CONFIG_USB_NET2272) || defined(CONFIG_USB_NET2272_MODULE)
&net2272_bfin_device,
#endif
#if defined(CONFIG_SPI_BFIN) || defined(CONFIG_SPI_BFIN_MODULE)
&bfin_spi0_device,
#endif
#if defined(CONFIG_SERIAL_BFIN) || defined(CONFIG_SERIAL_BFIN_MODULE)
#ifdef CONFIG_SERIAL_BFIN_UART0
&bfin_uart0_device,
#endif
#ifdef CONFIG_SERIAL_BFIN_UART1
&bfin_uart1_device,
#endif
#endif
#if defined(CONFIG_BFIN_SIR) || defined(CONFIG_BFIN_SIR_MODULE)
#ifdef CONFIG_BFIN_SIR0
&bfin_sir0_device,
#endif
#ifdef CONFIG_BFIN_SIR1
&bfin_sir1_device,
#endif
#endif
#if defined(CONFIG_I2C_BLACKFIN_TWI) || defined(CONFIG_I2C_BLACKFIN_TWI_MODULE)
&i2c_bfin_twi_device,
#endif
#if defined(CONFIG_SERIAL_BFIN_SPORT) || defined(CONFIG_SERIAL_BFIN_SPORT_MODULE)
#ifdef CONFIG_SERIAL_BFIN_SPORT0_UART
&bfin_sport0_uart_device,
#endif
#ifdef CONFIG_SERIAL_BFIN_SPORT1_UART
&bfin_sport1_uart_device,
#endif
#endif
#if defined(CONFIG_KEYBOARD_GPIO) || defined(CONFIG_KEYBOARD_GPIO_MODULE)
&bfin_device_gpiokeys,
#endif
#if defined(CONFIG_MTD_GPIO_ADDR) || defined(CONFIG_MTD_GPIO_ADDR_MODULE)
&cm_flash_device,
#endif
};
static int __init cm_init(void)
{
printk(KERN_INFO "%s(): registering device resources\n", __func__);
i2c_register_board_info(0, bfin_i2c_board_info,
ARRAY_SIZE(bfin_i2c_board_info));
platform_add_devices(cmbf527_devices, ARRAY_SIZE(cmbf527_devices));
spi_register_board_info(bfin_spi_board_info, ARRAY_SIZE(bfin_spi_board_info));
return 0;
}
arch_initcall(cm_init);
static struct platform_device *cmbf527_early_devices[] __initdata = {
#if defined(CONFIG_SERIAL_BFIN_CONSOLE) || defined(CONFIG_EARLY_PRINTK)
#ifdef CONFIG_SERIAL_BFIN_UART0
&bfin_uart0_device,
#endif
#ifdef CONFIG_SERIAL_BFIN_UART1
&bfin_uart1_device,
#endif
#endif
#if defined(CONFIG_SERIAL_BFIN_SPORT_CONSOLE)
#ifdef CONFIG_SERIAL_BFIN_SPORT0_UART
&bfin_sport0_uart_device,
#endif
#ifdef CONFIG_SERIAL_BFIN_SPORT1_UART
&bfin_sport1_uart_device,
#endif
#endif
};
void __init native_machine_early_platform_add_devices(void)
{
printk(KERN_INFO "register early platform devices\n");
early_platform_add_devices(cmbf527_early_devices,
ARRAY_SIZE(cmbf527_early_devices));
}
void native_machine_restart(char *cmd)
{
/* workaround reboot hang when booting from SPI */
if ((bfin_read_SYSCR() & 0x7) == 0x3)
bfin_reset_boot_spi_cs(P_DEFAULT_BOOT_SPI_CS);
}
void bfin_get_ether_addr(char *addr)
{
random_ether_addr(addr);
printk(KERN_WARNING "%s:%s: Setting Ethernet MAC to a random one\n", __FILE__, __func__);
}
EXPORT_SYMBOL(bfin_get_ether_addr);
| gpl-2.0 |
skeller/linux | arch/arm/mach-omap2/clkt_clksel.c | 2440 | 13729 | /*
* clkt_clksel.c - OMAP2/3/4 clksel clock functions
*
* Copyright (C) 2005-2008 Texas Instruments, Inc.
* Copyright (C) 2004-2010 Nokia Corporation
*
* Contacts:
* Richard Woodruff <r-woodruff2@ti.com>
* Paul Walmsley
*
* 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.
*
*
* clksel clocks are clocks that do not have a fixed parent, or that
* can divide their parent's rate, or possibly both at the same time, based
* on the contents of a hardware register bitfield.
*
* All of the various mux and divider settings can be encoded into
* struct clksel* data structures, and then these can be autogenerated
* from some hardware database for each new chip generation. This
* should avoid the need to write, review, and validate a lot of new
* clock code for each new chip, since it can be exported from the SoC
* design flow. This is now done on OMAP4.
*
* The fusion of mux and divider clocks is a software creation. In
* hardware reality, the multiplexer (parent selection) and the
* divider exist separately. XXX At some point these clksel clocks
* should be split into "divider" clocks and "mux" clocks to better
* match the hardware.
*
* (The name "clksel" comes from the name of the corresponding
* register field in the OMAP2/3 family of SoCs.)
*
* XXX Currently these clocks are only used in the OMAP2/3/4 code, but
* many of the OMAP1 clocks should be convertible to use this
* mechanism.
*/
#undef DEBUG
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/clk-provider.h>
#include <linux/io.h>
#include <linux/bug.h>
#include "clock.h"
/* Private functions */
/**
* _get_clksel_by_parent() - return clksel struct for a given clk & parent
* @clk: OMAP struct clk ptr to inspect
* @src_clk: OMAP struct clk ptr of the parent clk to search for
*
* Scan the struct clksel array associated with the clock to find
* the element associated with the supplied parent clock address.
* Returns a pointer to the struct clksel on success or NULL on error.
*/
static const struct clksel *_get_clksel_by_parent(struct clk_hw_omap *clk,
struct clk *src_clk)
{
const struct clksel *clks;
if (!src_clk)
return NULL;
for (clks = clk->clksel; clks->parent; clks++)
if (clks->parent == src_clk)
break; /* Found the requested parent */
if (!clks->parent) {
/* This indicates a data problem */
WARN(1, "clock: %s: could not find parent clock %s in clksel array\n",
__clk_get_name(clk->hw.clk), __clk_get_name(src_clk));
return NULL;
}
return clks;
}
/**
* _write_clksel_reg() - program a clock's clksel register in hardware
* @clk: struct clk * to program
* @v: clksel bitfield value to program (with LSB at bit 0)
*
* Shift the clksel register bitfield value @v to its appropriate
* location in the clksel register and write it in. This function
* will ensure that the write to the clksel_reg reaches its
* destination before returning -- important since PRM and CM register
* accesses can be quite slow compared to ARM cycles -- but does not
* take into account any time the hardware might take to switch the
* clock source.
*/
static void _write_clksel_reg(struct clk_hw_omap *clk, u32 field_val)
{
u32 v;
v = __raw_readl(clk->clksel_reg);
v &= ~clk->clksel_mask;
v |= field_val << __ffs(clk->clksel_mask);
__raw_writel(v, clk->clksel_reg);
v = __raw_readl(clk->clksel_reg); /* OCP barrier */
}
/**
* _clksel_to_divisor() - turn clksel field value into integer divider
* @clk: OMAP struct clk to use
* @field_val: register field value to find
*
* Given a struct clk of a rate-selectable clksel clock, and a register field
* value to search for, find the corresponding clock divisor. The register
* field value should be pre-masked and shifted down so the LSB is at bit 0
* before calling. Returns 0 on error or returns the actual integer divisor
* upon success.
*/
static u32 _clksel_to_divisor(struct clk_hw_omap *clk, u32 field_val)
{
const struct clksel *clks;
const struct clksel_rate *clkr;
struct clk *parent;
parent = __clk_get_parent(clk->hw.clk);
clks = _get_clksel_by_parent(clk, parent);
if (!clks)
return 0;
for (clkr = clks->rates; clkr->div; clkr++) {
if (!(clkr->flags & cpu_mask))
continue;
if (clkr->val == field_val)
break;
}
if (!clkr->div) {
/* This indicates a data error */
WARN(1, "clock: %s: could not find fieldval %d for parent %s\n",
__clk_get_name(clk->hw.clk), field_val,
__clk_get_name(parent));
return 0;
}
return clkr->div;
}
/**
* _divisor_to_clksel() - turn clksel integer divisor into a field value
* @clk: OMAP struct clk to use
* @div: integer divisor to search for
*
* Given a struct clk of a rate-selectable clksel clock, and a clock
* divisor, find the corresponding register field value. Returns the
* register field value _before_ left-shifting (i.e., LSB is at bit
* 0); or returns 0xFFFFFFFF (~0) upon error.
*/
static u32 _divisor_to_clksel(struct clk_hw_omap *clk, u32 div)
{
const struct clksel *clks;
const struct clksel_rate *clkr;
struct clk *parent;
/* should never happen */
WARN_ON(div == 0);
parent = __clk_get_parent(clk->hw.clk);
clks = _get_clksel_by_parent(clk, parent);
if (!clks)
return ~0;
for (clkr = clks->rates; clkr->div; clkr++) {
if (!(clkr->flags & cpu_mask))
continue;
if (clkr->div == div)
break;
}
if (!clkr->div) {
pr_err("clock: %s: could not find divisor %d for parent %s\n",
__clk_get_name(clk->hw.clk), div,
__clk_get_name(parent));
return ~0;
}
return clkr->val;
}
/**
* _read_divisor() - get current divisor applied to parent clock (from hdwr)
* @clk: OMAP struct clk to use.
*
* Read the current divisor register value for @clk that is programmed
* into the hardware, convert it into the actual divisor value, and
* return it; or return 0 on error.
*/
static u32 _read_divisor(struct clk_hw_omap *clk)
{
u32 v;
if (!clk->clksel || !clk->clksel_mask)
return 0;
v = __raw_readl(clk->clksel_reg);
v &= clk->clksel_mask;
v >>= __ffs(clk->clksel_mask);
return _clksel_to_divisor(clk, v);
}
/* Public functions */
/**
* omap2_clksel_round_rate_div() - find divisor for the given clock and rate
* @clk: OMAP struct clk to use
* @target_rate: desired clock rate
* @new_div: ptr to where we should store the divisor
*
* Finds 'best' divider value in an array based on the source and target
* rates. The divider array must be sorted with smallest divider first.
* This function is also used by the DPLL3 M2 divider code.
*
* Returns the rounded clock rate or returns 0xffffffff on error.
*/
u32 omap2_clksel_round_rate_div(struct clk_hw_omap *clk,
unsigned long target_rate,
u32 *new_div)
{
unsigned long test_rate;
const struct clksel *clks;
const struct clksel_rate *clkr;
u32 last_div = 0;
struct clk *parent;
unsigned long parent_rate;
const char *clk_name;
parent = __clk_get_parent(clk->hw.clk);
clk_name = __clk_get_name(clk->hw.clk);
parent_rate = __clk_get_rate(parent);
if (!clk->clksel || !clk->clksel_mask)
return ~0;
pr_debug("clock: clksel_round_rate_div: %s target_rate %ld\n",
clk_name, target_rate);
*new_div = 1;
clks = _get_clksel_by_parent(clk, parent);
if (!clks)
return ~0;
for (clkr = clks->rates; clkr->div; clkr++) {
if (!(clkr->flags & cpu_mask))
continue;
/* Sanity check */
if (clkr->div <= last_div)
pr_err("clock: %s: clksel_rate table not sorted\n",
clk_name);
last_div = clkr->div;
test_rate = parent_rate / clkr->div;
if (test_rate <= target_rate)
break; /* found it */
}
if (!clkr->div) {
pr_err("clock: %s: could not find divisor for target rate %ld for parent %s\n",
clk_name, target_rate, __clk_get_name(parent));
return ~0;
}
*new_div = clkr->div;
pr_debug("clock: new_div = %d, new_rate = %ld\n", *new_div,
(parent_rate / clkr->div));
return parent_rate / clkr->div;
}
/*
* Clocktype interface functions to the OMAP clock code
* (i.e., those used in struct clk field function pointers, etc.)
*/
/**
* omap2_clksel_find_parent_index() - return the array index of the current
* hardware parent of @hw
* @hw: struct clk_hw * to find the current hardware parent of
*
* Given a struct clk_hw pointer @hw to the 'hw' member of a struct
* clk_hw_omap record representing a source-selectable hardware clock,
* read the hardware register and determine what its parent is
* currently set to. Intended to be called only by the common clock
* framework struct clk_hw_ops.get_parent function pointer. Return
* the array index of this parent clock upon success -- there is no
* way to return an error, so if we encounter an error, just WARN()
* and pretend that we know that we're doing.
*/
u8 omap2_clksel_find_parent_index(struct clk_hw *hw)
{
struct clk_hw_omap *clk = to_clk_hw_omap(hw);
const struct clksel *clks;
const struct clksel_rate *clkr;
u32 r, found = 0;
struct clk *parent;
const char *clk_name;
int ret = 0, f = 0;
parent = __clk_get_parent(hw->clk);
clk_name = __clk_get_name(hw->clk);
/* XXX should be able to return an error */
WARN((!clk->clksel || !clk->clksel_mask),
"clock: %s: attempt to call on a non-clksel clock", clk_name);
r = __raw_readl(clk->clksel_reg) & clk->clksel_mask;
r >>= __ffs(clk->clksel_mask);
for (clks = clk->clksel; clks->parent && !found; clks++) {
for (clkr = clks->rates; clkr->div && !found; clkr++) {
if (!(clkr->flags & cpu_mask))
continue;
if (clkr->val == r) {
found = 1;
ret = f;
}
}
f++;
}
/* This indicates a data error */
WARN(!found, "clock: %s: init parent: could not find regval %0x\n",
clk_name, r);
return ret;
}
/**
* omap2_clksel_recalc() - function ptr to pass via struct clk .recalc field
* @clk: struct clk *
*
* This function is intended to be called only by the clock framework.
* Each clksel clock should have its struct clk .recalc field set to this
* function. Returns the clock's current rate, based on its parent's rate
* and its current divisor setting in the hardware.
*/
unsigned long omap2_clksel_recalc(struct clk_hw *hw, unsigned long parent_rate)
{
unsigned long rate;
u32 div = 0;
struct clk_hw_omap *clk = to_clk_hw_omap(hw);
if (!parent_rate)
return 0;
div = _read_divisor(clk);
if (!div)
rate = parent_rate;
else
rate = parent_rate / div;
pr_debug("%s: recalc'd %s's rate to %lu (div %d)\n", __func__,
__clk_get_name(hw->clk), rate, div);
return rate;
}
/**
* omap2_clksel_round_rate() - find rounded rate for the given clock and rate
* @clk: OMAP struct clk to use
* @target_rate: desired clock rate
*
* This function is intended to be called only by the clock framework.
* Finds best target rate based on the source clock and possible dividers.
* rates. The divider array must be sorted with smallest divider first.
*
* Returns the rounded clock rate or returns 0xffffffff on error.
*/
long omap2_clksel_round_rate(struct clk_hw *hw, unsigned long target_rate,
unsigned long *parent_rate)
{
struct clk_hw_omap *clk = to_clk_hw_omap(hw);
u32 new_div;
return omap2_clksel_round_rate_div(clk, target_rate, &new_div);
}
/**
* omap2_clksel_set_rate() - program clock rate in hardware
* @clk: struct clk * to program rate
* @rate: target rate to program
*
* This function is intended to be called only by the clock framework.
* Program @clk's rate to @rate in the hardware. The clock can be
* either enabled or disabled when this happens, although if the clock
* is enabled, some downstream devices may glitch or behave
* unpredictably when the clock rate is changed - this depends on the
* hardware. This function does not currently check the usecount of
* the clock, so if multiple drivers are using the clock, and the rate
* is changed, they will all be affected without any notification.
* Returns -EINVAL upon error, or 0 upon success.
*/
int omap2_clksel_set_rate(struct clk_hw *hw, unsigned long rate,
unsigned long parent_rate)
{
struct clk_hw_omap *clk = to_clk_hw_omap(hw);
u32 field_val, validrate, new_div = 0;
if (!clk->clksel || !clk->clksel_mask)
return -EINVAL;
validrate = omap2_clksel_round_rate_div(clk, rate, &new_div);
if (validrate != rate)
return -EINVAL;
field_val = _divisor_to_clksel(clk, new_div);
if (field_val == ~0)
return -EINVAL;
_write_clksel_reg(clk, field_val);
pr_debug("clock: %s: set rate to %ld\n", __clk_get_name(hw->clk),
__clk_get_rate(hw->clk));
return 0;
}
/*
* Clksel parent setting function - not passed in struct clk function
* pointer - instead, the OMAP clock code currently assumes that any
* parent-setting clock is a clksel clock, and calls
* omap2_clksel_set_parent() by default
*/
/**
* omap2_clksel_set_parent() - change a clock's parent clock
* @clk: struct clk * of the child clock
* @new_parent: struct clk * of the new parent clock
*
* This function is intended to be called only by the clock framework.
* Change the parent clock of clock @clk to @new_parent. This is
* intended to be used while @clk is disabled. This function does not
* currently check the usecount of the clock, so if multiple drivers
* are using the clock, and the parent is changed, they will all be
* affected without any notification. Returns -EINVAL upon error, or
* 0 upon success.
*/
int omap2_clksel_set_parent(struct clk_hw *hw, u8 field_val)
{
struct clk_hw_omap *clk = to_clk_hw_omap(hw);
if (!clk->clksel || !clk->clksel_mask)
return -EINVAL;
_write_clksel_reg(clk, field_val);
return 0;
}
| gpl-2.0 |
ganjafuzz/PureKernel-v2-CAF | arch/sparc/mm/init_32.c | 2440 | 14208 | /*
* linux/arch/sparc/mm/init.c
*
* Copyright (C) 1995 David S. Miller (davem@caip.rutgers.edu)
* Copyright (C) 1995 Eddie C. Dost (ecd@skynet.be)
* Copyright (C) 1998 Jakub Jelinek (jj@sunsite.mff.cuni.cz)
* Copyright (C) 2000 Anton Blanchard (anton@samba.org)
*/
#include <linux/module.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/ptrace.h>
#include <linux/mman.h>
#include <linux/mm.h>
#include <linux/swap.h>
#include <linux/initrd.h>
#include <linux/init.h>
#include <linux/highmem.h>
#include <linux/bootmem.h>
#include <linux/pagemap.h>
#include <linux/poison.h>
#include <linux/gfp.h>
#include <asm/sections.h>
#include <asm/vac-ops.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/vaddrs.h>
#include <asm/pgalloc.h> /* bug in asm-generic/tlb.h: check_pgt_cache */
#include <asm/tlb.h>
#include <asm/prom.h>
#include <asm/leon.h>
unsigned long *sparc_valid_addr_bitmap;
EXPORT_SYMBOL(sparc_valid_addr_bitmap);
unsigned long phys_base;
EXPORT_SYMBOL(phys_base);
unsigned long pfn_base;
EXPORT_SYMBOL(pfn_base);
unsigned long page_kernel;
EXPORT_SYMBOL(page_kernel);
struct sparc_phys_banks sp_banks[SPARC_PHYS_BANKS+1];
unsigned long sparc_unmapped_base;
struct pgtable_cache_struct pgt_quicklists;
/* Initial ramdisk setup */
extern unsigned int sparc_ramdisk_image;
extern unsigned int sparc_ramdisk_size;
unsigned long highstart_pfn, highend_pfn;
pte_t *kmap_pte;
pgprot_t kmap_prot;
#define kmap_get_fixmap_pte(vaddr) \
pte_offset_kernel(pmd_offset(pgd_offset_k(vaddr), (vaddr)), (vaddr))
void __init kmap_init(void)
{
/* cache the first kmap pte */
kmap_pte = kmap_get_fixmap_pte(__fix_to_virt(FIX_KMAP_BEGIN));
kmap_prot = __pgprot(SRMMU_ET_PTE | SRMMU_PRIV | SRMMU_CACHE);
}
void show_mem(unsigned int filter)
{
printk("Mem-info:\n");
show_free_areas(filter);
printk("Free swap: %6ldkB\n",
get_nr_swap_pages() << (PAGE_SHIFT-10));
printk("%ld pages of RAM\n", totalram_pages);
printk("%ld free pages\n", nr_free_pages());
#if 0 /* undefined pgtable_cache_size, pgd_cache_size */
printk("%ld pages in page table cache\n",pgtable_cache_size);
#ifndef CONFIG_SMP
if (sparc_cpu_model == sun4m || sparc_cpu_model == sun4d)
printk("%ld entries in page dir cache\n",pgd_cache_size);
#endif
#endif
}
void __init sparc_context_init(int numctx)
{
int ctx;
ctx_list_pool = __alloc_bootmem(numctx * sizeof(struct ctx_list), SMP_CACHE_BYTES, 0UL);
for(ctx = 0; ctx < numctx; ctx++) {
struct ctx_list *clist;
clist = (ctx_list_pool + ctx);
clist->ctx_number = ctx;
clist->ctx_mm = NULL;
}
ctx_free.next = ctx_free.prev = &ctx_free;
ctx_used.next = ctx_used.prev = &ctx_used;
for(ctx = 0; ctx < numctx; ctx++)
add_to_free_ctxlist(ctx_list_pool + ctx);
}
extern unsigned long cmdline_memory_size;
unsigned long last_valid_pfn;
unsigned long calc_highpages(void)
{
int i;
int nr = 0;
for (i = 0; sp_banks[i].num_bytes != 0; i++) {
unsigned long start_pfn = sp_banks[i].base_addr >> PAGE_SHIFT;
unsigned long end_pfn = (sp_banks[i].base_addr + sp_banks[i].num_bytes) >> PAGE_SHIFT;
if (end_pfn <= max_low_pfn)
continue;
if (start_pfn < max_low_pfn)
start_pfn = max_low_pfn;
nr += end_pfn - start_pfn;
}
return nr;
}
static unsigned long calc_max_low_pfn(void)
{
int i;
unsigned long tmp = pfn_base + (SRMMU_MAXMEM >> PAGE_SHIFT);
unsigned long curr_pfn, last_pfn;
last_pfn = (sp_banks[0].base_addr + sp_banks[0].num_bytes) >> PAGE_SHIFT;
for (i = 1; sp_banks[i].num_bytes != 0; i++) {
curr_pfn = sp_banks[i].base_addr >> PAGE_SHIFT;
if (curr_pfn >= tmp) {
if (last_pfn < tmp)
tmp = last_pfn;
break;
}
last_pfn = (sp_banks[i].base_addr + sp_banks[i].num_bytes) >> PAGE_SHIFT;
}
return tmp;
}
unsigned long __init bootmem_init(unsigned long *pages_avail)
{
unsigned long bootmap_size, start_pfn;
unsigned long end_of_phys_memory = 0UL;
unsigned long bootmap_pfn, bytes_avail, size;
int i;
bytes_avail = 0UL;
for (i = 0; sp_banks[i].num_bytes != 0; i++) {
end_of_phys_memory = sp_banks[i].base_addr +
sp_banks[i].num_bytes;
bytes_avail += sp_banks[i].num_bytes;
if (cmdline_memory_size) {
if (bytes_avail > cmdline_memory_size) {
unsigned long slack = bytes_avail - cmdline_memory_size;
bytes_avail -= slack;
end_of_phys_memory -= slack;
sp_banks[i].num_bytes -= slack;
if (sp_banks[i].num_bytes == 0) {
sp_banks[i].base_addr = 0xdeadbeef;
} else {
sp_banks[i+1].num_bytes = 0;
sp_banks[i+1].base_addr = 0xdeadbeef;
}
break;
}
}
}
/* Start with page aligned address of last symbol in kernel
* image.
*/
start_pfn = (unsigned long)__pa(PAGE_ALIGN((unsigned long) &_end));
/* Now shift down to get the real physical page frame number. */
start_pfn >>= PAGE_SHIFT;
bootmap_pfn = start_pfn;
max_pfn = end_of_phys_memory >> PAGE_SHIFT;
max_low_pfn = max_pfn;
highstart_pfn = highend_pfn = max_pfn;
if (max_low_pfn > pfn_base + (SRMMU_MAXMEM >> PAGE_SHIFT)) {
highstart_pfn = pfn_base + (SRMMU_MAXMEM >> PAGE_SHIFT);
max_low_pfn = calc_max_low_pfn();
printk(KERN_NOTICE "%ldMB HIGHMEM available.\n",
calc_highpages() >> (20 - PAGE_SHIFT));
}
#ifdef CONFIG_BLK_DEV_INITRD
/* Now have to check initial ramdisk, so that bootmap does not overwrite it */
if (sparc_ramdisk_image) {
if (sparc_ramdisk_image >= (unsigned long)&_end - 2 * PAGE_SIZE)
sparc_ramdisk_image -= KERNBASE;
initrd_start = sparc_ramdisk_image + phys_base;
initrd_end = initrd_start + sparc_ramdisk_size;
if (initrd_end > end_of_phys_memory) {
printk(KERN_CRIT "initrd extends beyond end of memory "
"(0x%016lx > 0x%016lx)\ndisabling initrd\n",
initrd_end, end_of_phys_memory);
initrd_start = 0;
}
if (initrd_start) {
if (initrd_start >= (start_pfn << PAGE_SHIFT) &&
initrd_start < (start_pfn << PAGE_SHIFT) + 2 * PAGE_SIZE)
bootmap_pfn = PAGE_ALIGN (initrd_end) >> PAGE_SHIFT;
}
}
#endif
/* Initialize the boot-time allocator. */
bootmap_size = init_bootmem_node(NODE_DATA(0), bootmap_pfn, pfn_base,
max_low_pfn);
/* Now register the available physical memory with the
* allocator.
*/
*pages_avail = 0;
for (i = 0; sp_banks[i].num_bytes != 0; i++) {
unsigned long curr_pfn, last_pfn;
curr_pfn = sp_banks[i].base_addr >> PAGE_SHIFT;
if (curr_pfn >= max_low_pfn)
break;
last_pfn = (sp_banks[i].base_addr + sp_banks[i].num_bytes) >> PAGE_SHIFT;
if (last_pfn > max_low_pfn)
last_pfn = max_low_pfn;
/*
* .. finally, did all the rounding and playing
* around just make the area go away?
*/
if (last_pfn <= curr_pfn)
continue;
size = (last_pfn - curr_pfn) << PAGE_SHIFT;
*pages_avail += last_pfn - curr_pfn;
free_bootmem(sp_banks[i].base_addr, size);
}
#ifdef CONFIG_BLK_DEV_INITRD
if (initrd_start) {
/* Reserve the initrd image area. */
size = initrd_end - initrd_start;
reserve_bootmem(initrd_start, size, BOOTMEM_DEFAULT);
*pages_avail -= PAGE_ALIGN(size) >> PAGE_SHIFT;
initrd_start = (initrd_start - phys_base) + PAGE_OFFSET;
initrd_end = (initrd_end - phys_base) + PAGE_OFFSET;
}
#endif
/* Reserve the kernel text/data/bss. */
size = (start_pfn << PAGE_SHIFT) - phys_base;
reserve_bootmem(phys_base, size, BOOTMEM_DEFAULT);
*pages_avail -= PAGE_ALIGN(size) >> PAGE_SHIFT;
/* Reserve the bootmem map. We do not account for it
* in pages_avail because we will release that memory
* in free_all_bootmem.
*/
size = bootmap_size;
reserve_bootmem((bootmap_pfn << PAGE_SHIFT), size, BOOTMEM_DEFAULT);
*pages_avail -= PAGE_ALIGN(size) >> PAGE_SHIFT;
return max_pfn;
}
/*
* check_pgt_cache
*
* This is called at the end of unmapping of VMA (zap_page_range),
* to rescan the page cache for architecture specific things,
* presumably something like sun4/sun4c PMEGs. Most architectures
* define check_pgt_cache empty.
*
* We simply copy the 2.4 implementation for now.
*/
static int pgt_cache_water[2] = { 25, 50 };
void check_pgt_cache(void)
{
do_check_pgt_cache(pgt_cache_water[0], pgt_cache_water[1]);
}
/*
* paging_init() sets up the page tables: We call the MMU specific
* init routine based upon the Sun model type on the Sparc.
*
*/
extern void sun4c_paging_init(void);
extern void srmmu_paging_init(void);
extern void device_scan(void);
pgprot_t PAGE_SHARED __read_mostly;
EXPORT_SYMBOL(PAGE_SHARED);
void __init paging_init(void)
{
switch(sparc_cpu_model) {
case sun4c:
case sun4e:
case sun4:
sun4c_paging_init();
sparc_unmapped_base = 0xe0000000;
BTFIXUPSET_SETHI(sparc_unmapped_base, 0xe0000000);
break;
case sparc_leon:
leon_init();
/* fall through */
case sun4m:
case sun4d:
srmmu_paging_init();
sparc_unmapped_base = 0x50000000;
BTFIXUPSET_SETHI(sparc_unmapped_base, 0x50000000);
break;
default:
prom_printf("paging_init: Cannot init paging on this Sparc\n");
prom_printf("paging_init: sparc_cpu_model = %d\n", sparc_cpu_model);
prom_printf("paging_init: Halting...\n");
prom_halt();
}
/* Initialize the protection map with non-constant, MMU dependent values. */
protection_map[0] = PAGE_NONE;
protection_map[1] = PAGE_READONLY;
protection_map[2] = PAGE_COPY;
protection_map[3] = PAGE_COPY;
protection_map[4] = PAGE_READONLY;
protection_map[5] = PAGE_READONLY;
protection_map[6] = PAGE_COPY;
protection_map[7] = PAGE_COPY;
protection_map[8] = PAGE_NONE;
protection_map[9] = PAGE_READONLY;
protection_map[10] = PAGE_SHARED;
protection_map[11] = PAGE_SHARED;
protection_map[12] = PAGE_READONLY;
protection_map[13] = PAGE_READONLY;
protection_map[14] = PAGE_SHARED;
protection_map[15] = PAGE_SHARED;
btfixup();
prom_build_devicetree();
of_fill_in_cpu_data();
device_scan();
}
static void __init taint_real_pages(void)
{
int i;
for (i = 0; sp_banks[i].num_bytes; i++) {
unsigned long start, end;
start = sp_banks[i].base_addr;
end = start + sp_banks[i].num_bytes;
while (start < end) {
set_bit(start >> 20, sparc_valid_addr_bitmap);
start += PAGE_SIZE;
}
}
}
static void map_high_region(unsigned long start_pfn, unsigned long end_pfn)
{
unsigned long tmp;
#ifdef CONFIG_DEBUG_HIGHMEM
printk("mapping high region %08lx - %08lx\n", start_pfn, end_pfn);
#endif
for (tmp = start_pfn; tmp < end_pfn; tmp++) {
struct page *page = pfn_to_page(tmp);
ClearPageReserved(page);
init_page_count(page);
__free_page(page);
totalhigh_pages++;
}
}
void __init mem_init(void)
{
int codepages = 0;
int datapages = 0;
int initpages = 0;
int reservedpages = 0;
int i;
if (PKMAP_BASE+LAST_PKMAP*PAGE_SIZE >= FIXADDR_START) {
prom_printf("BUG: fixmap and pkmap areas overlap\n");
prom_printf("pkbase: 0x%lx pkend: 0x%lx fixstart 0x%lx\n",
PKMAP_BASE,
(unsigned long)PKMAP_BASE+LAST_PKMAP*PAGE_SIZE,
FIXADDR_START);
prom_printf("Please mail sparclinux@vger.kernel.org.\n");
prom_halt();
}
/* Saves us work later. */
memset((void *)&empty_zero_page, 0, PAGE_SIZE);
i = last_valid_pfn >> ((20 - PAGE_SHIFT) + 5);
i += 1;
sparc_valid_addr_bitmap = (unsigned long *)
__alloc_bootmem(i << 2, SMP_CACHE_BYTES, 0UL);
if (sparc_valid_addr_bitmap == NULL) {
prom_printf("mem_init: Cannot alloc valid_addr_bitmap.\n");
prom_halt();
}
memset(sparc_valid_addr_bitmap, 0, i << 2);
taint_real_pages();
max_mapnr = last_valid_pfn - pfn_base;
high_memory = __va(max_low_pfn << PAGE_SHIFT);
totalram_pages = free_all_bootmem();
for (i = 0; sp_banks[i].num_bytes != 0; i++) {
unsigned long start_pfn = sp_banks[i].base_addr >> PAGE_SHIFT;
unsigned long end_pfn = (sp_banks[i].base_addr + sp_banks[i].num_bytes) >> PAGE_SHIFT;
num_physpages += sp_banks[i].num_bytes >> PAGE_SHIFT;
if (end_pfn <= highstart_pfn)
continue;
if (start_pfn < highstart_pfn)
start_pfn = highstart_pfn;
map_high_region(start_pfn, end_pfn);
}
totalram_pages += totalhigh_pages;
codepages = (((unsigned long) &_etext) - ((unsigned long)&_start));
codepages = PAGE_ALIGN(codepages) >> PAGE_SHIFT;
datapages = (((unsigned long) &_edata) - ((unsigned long)&_etext));
datapages = PAGE_ALIGN(datapages) >> PAGE_SHIFT;
initpages = (((unsigned long) &__init_end) - ((unsigned long) &__init_begin));
initpages = PAGE_ALIGN(initpages) >> PAGE_SHIFT;
/* Ignore memory holes for the purpose of counting reserved pages */
for (i=0; i < max_low_pfn; i++)
if (test_bit(i >> (20 - PAGE_SHIFT), sparc_valid_addr_bitmap)
&& PageReserved(pfn_to_page(i)))
reservedpages++;
printk(KERN_INFO "Memory: %luk/%luk available (%dk kernel code, %dk reserved, %dk data, %dk init, %ldk highmem)\n",
nr_free_pages() << (PAGE_SHIFT-10),
num_physpages << (PAGE_SHIFT - 10),
codepages << (PAGE_SHIFT-10),
reservedpages << (PAGE_SHIFT - 10),
datapages << (PAGE_SHIFT-10),
initpages << (PAGE_SHIFT-10),
totalhigh_pages << (PAGE_SHIFT-10));
}
void free_initmem (void)
{
unsigned long addr;
unsigned long freed;
addr = (unsigned long)(&__init_begin);
freed = (unsigned long)(&__init_end) - addr;
for (; addr < (unsigned long)(&__init_end); addr += PAGE_SIZE) {
struct page *p;
memset((void *)addr, POISON_FREE_INITMEM, PAGE_SIZE);
p = virt_to_page(addr);
ClearPageReserved(p);
init_page_count(p);
__free_page(p);
totalram_pages++;
num_physpages++;
}
printk(KERN_INFO "Freeing unused kernel memory: %ldk freed\n",
freed >> 10);
}
#ifdef CONFIG_BLK_DEV_INITRD
void free_initrd_mem(unsigned long start, unsigned long end)
{
if (start < end)
printk(KERN_INFO "Freeing initrd memory: %ldk freed\n",
(end - start) >> 10);
for (; start < end; start += PAGE_SIZE) {
struct page *p;
memset((void *)start, POISON_FREE_INITMEM, PAGE_SIZE);
p = virt_to_page(start);
ClearPageReserved(p);
init_page_count(p);
__free_page(p);
totalram_pages++;
num_physpages++;
}
}
#endif
void sparc_flush_page_to_ram(struct page *page)
{
unsigned long vaddr = (unsigned long)page_address(page);
if (vaddr)
__flush_page_to_ram(vaddr);
}
EXPORT_SYMBOL(sparc_flush_page_to_ram);
| gpl-2.0 |
LeJay/android_kernel_samsung_jactivelte | net/sctp/input.c | 2952 | 31281 | /* SCTP kernel implementation
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001-2003 International Business Machines, Corp.
* Copyright (c) 2001 Intel Corp.
* Copyright (c) 2001 Nokia, Inc.
* Copyright (c) 2001 La Monte H.P. Yarroll
*
* This file is part of the SCTP kernel implementation
*
* These functions handle all input from the IP layer into SCTP.
*
* This SCTP implementation is free software;
* you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This SCTP implementation is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied
* ************************
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU CC; see the file COPYING. If not, write to
* the Free Software Foundation, 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <lksctp-developers@lists.sourceforge.net>
*
* Or submit a bug report through the following website:
* http://www.sf.net/projects/lksctp
*
* Written or modified by:
* La Monte H.P. Yarroll <piggy@acm.org>
* Karl Knutson <karl@athena.chicago.il.us>
* Xingang Guo <xingang.guo@intel.com>
* Jon Grimm <jgrimm@us.ibm.com>
* Hui Huang <hui.huang@nokia.com>
* Daisy Chang <daisyc@us.ibm.com>
* Sridhar Samudrala <sri@us.ibm.com>
* Ardelle Fan <ardelle.fan@intel.com>
*
* Any bugs reported given to us we will try to fix... any fixes shared will
* be incorporated into the next SCTP release.
*/
#include <linux/types.h>
#include <linux/list.h> /* For struct list_head */
#include <linux/socket.h>
#include <linux/ip.h>
#include <linux/time.h> /* For struct timeval */
#include <linux/slab.h>
#include <net/ip.h>
#include <net/icmp.h>
#include <net/snmp.h>
#include <net/sock.h>
#include <net/xfrm.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
#include <net/sctp/checksum.h>
#include <net/net_namespace.h>
/* Forward declarations for internal helpers. */
static int sctp_rcv_ootb(struct sk_buff *);
static struct sctp_association *__sctp_rcv_lookup(struct sk_buff *skb,
const union sctp_addr *laddr,
const union sctp_addr *paddr,
struct sctp_transport **transportp);
static struct sctp_endpoint *__sctp_rcv_lookup_endpoint(const union sctp_addr *laddr);
static struct sctp_association *__sctp_lookup_association(
const union sctp_addr *local,
const union sctp_addr *peer,
struct sctp_transport **pt);
static int sctp_add_backlog(struct sock *sk, struct sk_buff *skb);
/* Calculate the SCTP checksum of an SCTP packet. */
static inline int sctp_rcv_checksum(struct sk_buff *skb)
{
struct sctphdr *sh = sctp_hdr(skb);
__le32 cmp = sh->checksum;
struct sk_buff *list;
__le32 val;
__u32 tmp = sctp_start_cksum((__u8 *)sh, skb_headlen(skb));
skb_walk_frags(skb, list)
tmp = sctp_update_cksum((__u8 *)list->data, skb_headlen(list),
tmp);
val = sctp_end_cksum(tmp);
if (val != cmp) {
/* CRC failure, dump it. */
SCTP_INC_STATS_BH(SCTP_MIB_CHECKSUMERRORS);
return -1;
}
return 0;
}
struct sctp_input_cb {
union {
struct inet_skb_parm h4;
#if IS_ENABLED(CONFIG_IPV6)
struct inet6_skb_parm h6;
#endif
} header;
struct sctp_chunk *chunk;
};
#define SCTP_INPUT_CB(__skb) ((struct sctp_input_cb *)&((__skb)->cb[0]))
/*
* This is the routine which IP calls when receiving an SCTP packet.
*/
int sctp_rcv(struct sk_buff *skb)
{
struct sock *sk;
struct sctp_association *asoc;
struct sctp_endpoint *ep = NULL;
struct sctp_ep_common *rcvr;
struct sctp_transport *transport = NULL;
struct sctp_chunk *chunk;
struct sctphdr *sh;
union sctp_addr src;
union sctp_addr dest;
int family;
struct sctp_af *af;
if (skb->pkt_type!=PACKET_HOST)
goto discard_it;
SCTP_INC_STATS_BH(SCTP_MIB_INSCTPPACKS);
if (skb_linearize(skb))
goto discard_it;
sh = sctp_hdr(skb);
/* Pull up the IP and SCTP headers. */
__skb_pull(skb, skb_transport_offset(skb));
if (skb->len < sizeof(struct sctphdr))
goto discard_it;
if (!sctp_checksum_disable && !skb_csum_unnecessary(skb) &&
sctp_rcv_checksum(skb) < 0)
goto discard_it;
skb_pull(skb, sizeof(struct sctphdr));
/* Make sure we at least have chunk headers worth of data left. */
if (skb->len < sizeof(struct sctp_chunkhdr))
goto discard_it;
family = ipver2af(ip_hdr(skb)->version);
af = sctp_get_af_specific(family);
if (unlikely(!af))
goto discard_it;
/* Initialize local addresses for lookups. */
af->from_skb(&src, skb, 1);
af->from_skb(&dest, skb, 0);
/* If the packet is to or from a non-unicast address,
* silently discard the packet.
*
* This is not clearly defined in the RFC except in section
* 8.4 - OOTB handling. However, based on the book "Stream Control
* Transmission Protocol" 2.1, "It is important to note that the
* IP address of an SCTP transport address must be a routable
* unicast address. In other words, IP multicast addresses and
* IP broadcast addresses cannot be used in an SCTP transport
* address."
*/
if (!af->addr_valid(&src, NULL, skb) ||
!af->addr_valid(&dest, NULL, skb))
goto discard_it;
asoc = __sctp_rcv_lookup(skb, &src, &dest, &transport);
if (!asoc)
ep = __sctp_rcv_lookup_endpoint(&dest);
/* Retrieve the common input handling substructure. */
rcvr = asoc ? &asoc->base : &ep->base;
sk = rcvr->sk;
/*
* If a frame arrives on an interface and the receiving socket is
* bound to another interface, via SO_BINDTODEVICE, treat it as OOTB
*/
if (sk->sk_bound_dev_if && (sk->sk_bound_dev_if != af->skb_iif(skb)))
{
if (asoc) {
sctp_association_put(asoc);
asoc = NULL;
} else {
sctp_endpoint_put(ep);
ep = NULL;
}
sk = sctp_get_ctl_sock();
ep = sctp_sk(sk)->ep;
sctp_endpoint_hold(ep);
rcvr = &ep->base;
}
/*
* RFC 2960, 8.4 - Handle "Out of the blue" Packets.
* An SCTP packet is called an "out of the blue" (OOTB)
* packet if it is correctly formed, i.e., passed the
* receiver's checksum check, but the receiver is not
* able to identify the association to which this
* packet belongs.
*/
if (!asoc) {
if (sctp_rcv_ootb(skb)) {
SCTP_INC_STATS_BH(SCTP_MIB_OUTOFBLUES);
goto discard_release;
}
}
if (!xfrm_policy_check(sk, XFRM_POLICY_IN, skb, family))
goto discard_release;
nf_reset(skb);
if (sk_filter(sk, skb))
goto discard_release;
/* Create an SCTP packet structure. */
chunk = sctp_chunkify(skb, asoc, sk);
if (!chunk)
goto discard_release;
SCTP_INPUT_CB(skb)->chunk = chunk;
/* Remember what endpoint is to handle this packet. */
chunk->rcvr = rcvr;
/* Remember the SCTP header. */
chunk->sctp_hdr = sh;
/* Set the source and destination addresses of the incoming chunk. */
sctp_init_addrs(chunk, &src, &dest);
/* Remember where we came from. */
chunk->transport = transport;
/* Acquire access to the sock lock. Note: We are safe from other
* bottom halves on this lock, but a user may be in the lock too,
* so check if it is busy.
*/
sctp_bh_lock_sock(sk);
if (sk != rcvr->sk) {
/* Our cached sk is different from the rcvr->sk. This is
* because migrate()/accept() may have moved the association
* to a new socket and released all the sockets. So now we
* are holding a lock on the old socket while the user may
* be doing something with the new socket. Switch our veiw
* of the current sk.
*/
sctp_bh_unlock_sock(sk);
sk = rcvr->sk;
sctp_bh_lock_sock(sk);
}
if (sock_owned_by_user(sk)) {
if (sctp_add_backlog(sk, skb)) {
sctp_bh_unlock_sock(sk);
sctp_chunk_free(chunk);
skb = NULL; /* sctp_chunk_free already freed the skb */
goto discard_release;
}
SCTP_INC_STATS_BH(SCTP_MIB_IN_PKT_BACKLOG);
} else {
SCTP_INC_STATS_BH(SCTP_MIB_IN_PKT_SOFTIRQ);
sctp_inq_push(&chunk->rcvr->inqueue, chunk);
}
sctp_bh_unlock_sock(sk);
/* Release the asoc/ep ref we took in the lookup calls. */
if (asoc)
sctp_association_put(asoc);
else
sctp_endpoint_put(ep);
return 0;
discard_it:
SCTP_INC_STATS_BH(SCTP_MIB_IN_PKT_DISCARDS);
kfree_skb(skb);
return 0;
discard_release:
/* Release the asoc/ep ref we took in the lookup calls. */
if (asoc)
sctp_association_put(asoc);
else
sctp_endpoint_put(ep);
goto discard_it;
}
/* Process the backlog queue of the socket. Every skb on
* the backlog holds a ref on an association or endpoint.
* We hold this ref throughout the state machine to make
* sure that the structure we need is still around.
*/
int sctp_backlog_rcv(struct sock *sk, struct sk_buff *skb)
{
struct sctp_chunk *chunk = SCTP_INPUT_CB(skb)->chunk;
struct sctp_inq *inqueue = &chunk->rcvr->inqueue;
struct sctp_ep_common *rcvr = NULL;
int backloged = 0;
rcvr = chunk->rcvr;
/* If the rcvr is dead then the association or endpoint
* has been deleted and we can safely drop the chunk
* and refs that we are holding.
*/
if (rcvr->dead) {
sctp_chunk_free(chunk);
goto done;
}
if (unlikely(rcvr->sk != sk)) {
/* In this case, the association moved from one socket to
* another. We are currently sitting on the backlog of the
* old socket, so we need to move.
* However, since we are here in the process context we
* need to take make sure that the user doesn't own
* the new socket when we process the packet.
* If the new socket is user-owned, queue the chunk to the
* backlog of the new socket without dropping any refs.
* Otherwise, we can safely push the chunk on the inqueue.
*/
sk = rcvr->sk;
sctp_bh_lock_sock(sk);
if (sock_owned_by_user(sk)) {
if (sk_add_backlog(sk, skb))
sctp_chunk_free(chunk);
else
backloged = 1;
} else
sctp_inq_push(inqueue, chunk);
sctp_bh_unlock_sock(sk);
/* If the chunk was backloged again, don't drop refs */
if (backloged)
return 0;
} else {
sctp_inq_push(inqueue, chunk);
}
done:
/* Release the refs we took in sctp_add_backlog */
if (SCTP_EP_TYPE_ASSOCIATION == rcvr->type)
sctp_association_put(sctp_assoc(rcvr));
else if (SCTP_EP_TYPE_SOCKET == rcvr->type)
sctp_endpoint_put(sctp_ep(rcvr));
else
BUG();
return 0;
}
static int sctp_add_backlog(struct sock *sk, struct sk_buff *skb)
{
struct sctp_chunk *chunk = SCTP_INPUT_CB(skb)->chunk;
struct sctp_ep_common *rcvr = chunk->rcvr;
int ret;
ret = sk_add_backlog(sk, skb);
if (!ret) {
/* Hold the assoc/ep while hanging on the backlog queue.
* This way, we know structures we need will not disappear
* from us
*/
if (SCTP_EP_TYPE_ASSOCIATION == rcvr->type)
sctp_association_hold(sctp_assoc(rcvr));
else if (SCTP_EP_TYPE_SOCKET == rcvr->type)
sctp_endpoint_hold(sctp_ep(rcvr));
else
BUG();
}
return ret;
}
/* Handle icmp frag needed error. */
void sctp_icmp_frag_needed(struct sock *sk, struct sctp_association *asoc,
struct sctp_transport *t, __u32 pmtu)
{
if (!t || (t->pathmtu <= pmtu))
return;
if (sock_owned_by_user(sk)) {
asoc->pmtu_pending = 1;
t->pmtu_pending = 1;
return;
}
if (t->param_flags & SPP_PMTUD_ENABLE) {
/* Update transports view of the MTU */
sctp_transport_update_pmtu(t, pmtu);
/* Update association pmtu. */
sctp_assoc_sync_pmtu(asoc);
}
/* Retransmit with the new pmtu setting.
* Normally, if PMTU discovery is disabled, an ICMP Fragmentation
* Needed will never be sent, but if a message was sent before
* PMTU discovery was disabled that was larger than the PMTU, it
* would not be fragmented, so it must be re-transmitted fragmented.
*/
sctp_retransmit(&asoc->outqueue, t, SCTP_RTXR_PMTUD);
}
/*
* SCTP Implementer's Guide, 2.37 ICMP handling procedures
*
* ICMP8) If the ICMP code is a "Unrecognized next header type encountered"
* or a "Protocol Unreachable" treat this message as an abort
* with the T bit set.
*
* This function sends an event to the state machine, which will abort the
* association.
*
*/
void sctp_icmp_proto_unreachable(struct sock *sk,
struct sctp_association *asoc,
struct sctp_transport *t)
{
SCTP_DEBUG_PRINTK("%s\n", __func__);
if (sock_owned_by_user(sk)) {
if (timer_pending(&t->proto_unreach_timer))
return;
else {
if (!mod_timer(&t->proto_unreach_timer,
jiffies + (HZ/20)))
sctp_association_hold(asoc);
}
} else {
if (timer_pending(&t->proto_unreach_timer) &&
del_timer(&t->proto_unreach_timer))
sctp_association_put(asoc);
sctp_do_sm(SCTP_EVENT_T_OTHER,
SCTP_ST_OTHER(SCTP_EVENT_ICMP_PROTO_UNREACH),
asoc->state, asoc->ep, asoc, t,
GFP_ATOMIC);
}
}
/* Common lookup code for icmp/icmpv6 error handler. */
struct sock *sctp_err_lookup(int family, struct sk_buff *skb,
struct sctphdr *sctphdr,
struct sctp_association **app,
struct sctp_transport **tpp)
{
union sctp_addr saddr;
union sctp_addr daddr;
struct sctp_af *af;
struct sock *sk = NULL;
struct sctp_association *asoc;
struct sctp_transport *transport = NULL;
struct sctp_init_chunk *chunkhdr;
__u32 vtag = ntohl(sctphdr->vtag);
int len = skb->len - ((void *)sctphdr - (void *)skb->data);
*app = NULL; *tpp = NULL;
af = sctp_get_af_specific(family);
if (unlikely(!af)) {
return NULL;
}
/* Initialize local addresses for lookups. */
af->from_skb(&saddr, skb, 1);
af->from_skb(&daddr, skb, 0);
/* Look for an association that matches the incoming ICMP error
* packet.
*/
asoc = __sctp_lookup_association(&saddr, &daddr, &transport);
if (!asoc)
return NULL;
sk = asoc->base.sk;
/* RFC 4960, Appendix C. ICMP Handling
*
* ICMP6) An implementation MUST validate that the Verification Tag
* contained in the ICMP message matches the Verification Tag of
* the peer. If the Verification Tag is not 0 and does NOT
* match, discard the ICMP message. If it is 0 and the ICMP
* message contains enough bytes to verify that the chunk type is
* an INIT chunk and that the Initiate Tag matches the tag of the
* peer, continue with ICMP7. If the ICMP message is too short
* or the chunk type or the Initiate Tag does not match, silently
* discard the packet.
*/
if (vtag == 0) {
chunkhdr = (void *)sctphdr + sizeof(struct sctphdr);
if (len < sizeof(struct sctphdr) + sizeof(sctp_chunkhdr_t)
+ sizeof(__be32) ||
chunkhdr->chunk_hdr.type != SCTP_CID_INIT ||
ntohl(chunkhdr->init_hdr.init_tag) != asoc->c.my_vtag) {
goto out;
}
} else if (vtag != asoc->c.peer_vtag) {
goto out;
}
sctp_bh_lock_sock(sk);
/* If too many ICMPs get dropped on busy
* servers this needs to be solved differently.
*/
if (sock_owned_by_user(sk))
NET_INC_STATS_BH(&init_net, LINUX_MIB_LOCKDROPPEDICMPS);
*app = asoc;
*tpp = transport;
return sk;
out:
if (asoc)
sctp_association_put(asoc);
return NULL;
}
/* Common cleanup code for icmp/icmpv6 error handler. */
void sctp_err_finish(struct sock *sk, struct sctp_association *asoc)
{
sctp_bh_unlock_sock(sk);
if (asoc)
sctp_association_put(asoc);
}
/*
* This routine is called by the ICMP module when it gets some
* sort of error condition. If err < 0 then the socket should
* be closed and the error returned to the user. If err > 0
* it's just the icmp type << 8 | icmp code. After adjustment
* header points to the first 8 bytes of the sctp header. We need
* to find the appropriate port.
*
* The locking strategy used here is very "optimistic". When
* someone else accesses the socket the ICMP is just dropped
* and for some paths there is no check at all.
* A more general error queue to queue errors for later handling
* is probably better.
*
*/
void sctp_v4_err(struct sk_buff *skb, __u32 info)
{
const struct iphdr *iph = (const struct iphdr *)skb->data;
const int ihlen = iph->ihl * 4;
const int type = icmp_hdr(skb)->type;
const int code = icmp_hdr(skb)->code;
struct sock *sk;
struct sctp_association *asoc = NULL;
struct sctp_transport *transport;
struct inet_sock *inet;
sk_buff_data_t saveip, savesctp;
int err;
if (skb->len < ihlen + 8) {
ICMP_INC_STATS_BH(&init_net, ICMP_MIB_INERRORS);
return;
}
/* Fix up skb to look at the embedded net header. */
saveip = skb->network_header;
savesctp = skb->transport_header;
skb_reset_network_header(skb);
skb_set_transport_header(skb, ihlen);
sk = sctp_err_lookup(AF_INET, skb, sctp_hdr(skb), &asoc, &transport);
/* Put back, the original values. */
skb->network_header = saveip;
skb->transport_header = savesctp;
if (!sk) {
ICMP_INC_STATS_BH(&init_net, ICMP_MIB_INERRORS);
return;
}
/* Warning: The sock lock is held. Remember to call
* sctp_err_finish!
*/
switch (type) {
case ICMP_PARAMETERPROB:
err = EPROTO;
break;
case ICMP_DEST_UNREACH:
if (code > NR_ICMP_UNREACH)
goto out_unlock;
/* PMTU discovery (RFC1191) */
if (ICMP_FRAG_NEEDED == code) {
sctp_icmp_frag_needed(sk, asoc, transport, info);
goto out_unlock;
}
else {
if (ICMP_PROT_UNREACH == code) {
sctp_icmp_proto_unreachable(sk, asoc,
transport);
goto out_unlock;
}
}
err = icmp_err_convert[code].errno;
break;
case ICMP_TIME_EXCEEDED:
/* Ignore any time exceeded errors due to fragment reassembly
* timeouts.
*/
if (ICMP_EXC_FRAGTIME == code)
goto out_unlock;
err = EHOSTUNREACH;
break;
default:
goto out_unlock;
}
inet = inet_sk(sk);
if (!sock_owned_by_user(sk) && inet->recverr) {
sk->sk_err = err;
sk->sk_error_report(sk);
} else { /* Only an error on timeout */
sk->sk_err_soft = err;
}
out_unlock:
sctp_err_finish(sk, asoc);
}
/*
* RFC 2960, 8.4 - Handle "Out of the blue" Packets.
*
* This function scans all the chunks in the OOTB packet to determine if
* the packet should be discarded right away. If a response might be needed
* for this packet, or, if further processing is possible, the packet will
* be queued to a proper inqueue for the next phase of handling.
*
* Output:
* Return 0 - If further processing is needed.
* Return 1 - If the packet can be discarded right away.
*/
static int sctp_rcv_ootb(struct sk_buff *skb)
{
sctp_chunkhdr_t *ch;
__u8 *ch_end;
ch = (sctp_chunkhdr_t *) skb->data;
/* Scan through all the chunks in the packet. */
do {
/* Break out if chunk length is less then minimal. */
if (ntohs(ch->length) < sizeof(sctp_chunkhdr_t))
break;
ch_end = ((__u8 *)ch) + WORD_ROUND(ntohs(ch->length));
if (ch_end > skb_tail_pointer(skb))
break;
/* RFC 8.4, 2) If the OOTB packet contains an ABORT chunk, the
* receiver MUST silently discard the OOTB packet and take no
* further action.
*/
if (SCTP_CID_ABORT == ch->type)
goto discard;
/* RFC 8.4, 6) If the packet contains a SHUTDOWN COMPLETE
* chunk, the receiver should silently discard the packet
* and take no further action.
*/
if (SCTP_CID_SHUTDOWN_COMPLETE == ch->type)
goto discard;
/* RFC 4460, 2.11.2
* This will discard packets with INIT chunk bundled as
* subsequent chunks in the packet. When INIT is first,
* the normal INIT processing will discard the chunk.
*/
if (SCTP_CID_INIT == ch->type && (void *)ch != skb->data)
goto discard;
ch = (sctp_chunkhdr_t *) ch_end;
} while (ch_end < skb_tail_pointer(skb));
return 0;
discard:
return 1;
}
/* Insert endpoint into the hash table. */
static void __sctp_hash_endpoint(struct sctp_endpoint *ep)
{
struct sctp_ep_common *epb;
struct sctp_hashbucket *head;
epb = &ep->base;
epb->hashent = sctp_ep_hashfn(epb->bind_addr.port);
head = &sctp_ep_hashtable[epb->hashent];
sctp_write_lock(&head->lock);
hlist_add_head(&epb->node, &head->chain);
sctp_write_unlock(&head->lock);
}
/* Add an endpoint to the hash. Local BH-safe. */
void sctp_hash_endpoint(struct sctp_endpoint *ep)
{
sctp_local_bh_disable();
__sctp_hash_endpoint(ep);
sctp_local_bh_enable();
}
/* Remove endpoint from the hash table. */
static void __sctp_unhash_endpoint(struct sctp_endpoint *ep)
{
struct sctp_hashbucket *head;
struct sctp_ep_common *epb;
epb = &ep->base;
if (hlist_unhashed(&epb->node))
return;
epb->hashent = sctp_ep_hashfn(epb->bind_addr.port);
head = &sctp_ep_hashtable[epb->hashent];
sctp_write_lock(&head->lock);
__hlist_del(&epb->node);
sctp_write_unlock(&head->lock);
}
/* Remove endpoint from the hash. Local BH-safe. */
void sctp_unhash_endpoint(struct sctp_endpoint *ep)
{
sctp_local_bh_disable();
__sctp_unhash_endpoint(ep);
sctp_local_bh_enable();
}
/* Look up an endpoint. */
static struct sctp_endpoint *__sctp_rcv_lookup_endpoint(const union sctp_addr *laddr)
{
struct sctp_hashbucket *head;
struct sctp_ep_common *epb;
struct sctp_endpoint *ep;
struct hlist_node *node;
int hash;
hash = sctp_ep_hashfn(ntohs(laddr->v4.sin_port));
head = &sctp_ep_hashtable[hash];
read_lock(&head->lock);
sctp_for_each_hentry(epb, node, &head->chain) {
ep = sctp_ep(epb);
if (sctp_endpoint_is_match(ep, laddr))
goto hit;
}
ep = sctp_sk((sctp_get_ctl_sock()))->ep;
hit:
sctp_endpoint_hold(ep);
read_unlock(&head->lock);
return ep;
}
/* Insert association into the hash table. */
static void __sctp_hash_established(struct sctp_association *asoc)
{
struct sctp_ep_common *epb;
struct sctp_hashbucket *head;
epb = &asoc->base;
/* Calculate which chain this entry will belong to. */
epb->hashent = sctp_assoc_hashfn(epb->bind_addr.port, asoc->peer.port);
head = &sctp_assoc_hashtable[epb->hashent];
sctp_write_lock(&head->lock);
hlist_add_head(&epb->node, &head->chain);
sctp_write_unlock(&head->lock);
}
/* Add an association to the hash. Local BH-safe. */
void sctp_hash_established(struct sctp_association *asoc)
{
if (asoc->temp)
return;
sctp_local_bh_disable();
__sctp_hash_established(asoc);
sctp_local_bh_enable();
}
/* Remove association from the hash table. */
static void __sctp_unhash_established(struct sctp_association *asoc)
{
struct sctp_hashbucket *head;
struct sctp_ep_common *epb;
epb = &asoc->base;
epb->hashent = sctp_assoc_hashfn(epb->bind_addr.port,
asoc->peer.port);
head = &sctp_assoc_hashtable[epb->hashent];
sctp_write_lock(&head->lock);
__hlist_del(&epb->node);
sctp_write_unlock(&head->lock);
}
/* Remove association from the hash table. Local BH-safe. */
void sctp_unhash_established(struct sctp_association *asoc)
{
if (asoc->temp)
return;
sctp_local_bh_disable();
__sctp_unhash_established(asoc);
sctp_local_bh_enable();
}
/* Look up an association. */
static struct sctp_association *__sctp_lookup_association(
const union sctp_addr *local,
const union sctp_addr *peer,
struct sctp_transport **pt)
{
struct sctp_hashbucket *head;
struct sctp_ep_common *epb;
struct sctp_association *asoc;
struct sctp_transport *transport;
struct hlist_node *node;
int hash;
/* Optimize here for direct hit, only listening connections can
* have wildcards anyways.
*/
hash = sctp_assoc_hashfn(ntohs(local->v4.sin_port), ntohs(peer->v4.sin_port));
head = &sctp_assoc_hashtable[hash];
read_lock(&head->lock);
sctp_for_each_hentry(epb, node, &head->chain) {
asoc = sctp_assoc(epb);
transport = sctp_assoc_is_match(asoc, local, peer);
if (transport)
goto hit;
}
read_unlock(&head->lock);
return NULL;
hit:
*pt = transport;
sctp_association_hold(asoc);
read_unlock(&head->lock);
return asoc;
}
/* Look up an association. BH-safe. */
SCTP_STATIC
struct sctp_association *sctp_lookup_association(const union sctp_addr *laddr,
const union sctp_addr *paddr,
struct sctp_transport **transportp)
{
struct sctp_association *asoc;
sctp_local_bh_disable();
asoc = __sctp_lookup_association(laddr, paddr, transportp);
sctp_local_bh_enable();
return asoc;
}
/* Is there an association matching the given local and peer addresses? */
int sctp_has_association(const union sctp_addr *laddr,
const union sctp_addr *paddr)
{
struct sctp_association *asoc;
struct sctp_transport *transport;
if ((asoc = sctp_lookup_association(laddr, paddr, &transport))) {
sctp_association_put(asoc);
return 1;
}
return 0;
}
/*
* SCTP Implementors Guide, 2.18 Handling of address
* parameters within the INIT or INIT-ACK.
*
* D) When searching for a matching TCB upon reception of an INIT
* or INIT-ACK chunk the receiver SHOULD use not only the
* source address of the packet (containing the INIT or
* INIT-ACK) but the receiver SHOULD also use all valid
* address parameters contained within the chunk.
*
* 2.18.3 Solution description
*
* This new text clearly specifies to an implementor the need
* to look within the INIT or INIT-ACK. Any implementation that
* does not do this, may not be able to establish associations
* in certain circumstances.
*
*/
static struct sctp_association *__sctp_rcv_init_lookup(struct sk_buff *skb,
const union sctp_addr *laddr, struct sctp_transport **transportp)
{
struct sctp_association *asoc;
union sctp_addr addr;
union sctp_addr *paddr = &addr;
struct sctphdr *sh = sctp_hdr(skb);
union sctp_params params;
sctp_init_chunk_t *init;
struct sctp_transport *transport;
struct sctp_af *af;
/*
* This code will NOT touch anything inside the chunk--it is
* strictly READ-ONLY.
*
* RFC 2960 3 SCTP packet Format
*
* Multiple chunks can be bundled into one SCTP packet up to
* the MTU size, except for the INIT, INIT ACK, and SHUTDOWN
* COMPLETE chunks. These chunks MUST NOT be bundled with any
* other chunk in a packet. See Section 6.10 for more details
* on chunk bundling.
*/
/* Find the start of the TLVs and the end of the chunk. This is
* the region we search for address parameters.
*/
init = (sctp_init_chunk_t *)skb->data;
/* Walk the parameters looking for embedded addresses. */
sctp_walk_params(params, init, init_hdr.params) {
/* Note: Ignoring hostname addresses. */
af = sctp_get_af_specific(param_type2af(params.p->type));
if (!af)
continue;
af->from_addr_param(paddr, params.addr, sh->source, 0);
asoc = __sctp_lookup_association(laddr, paddr, &transport);
if (asoc)
return asoc;
}
return NULL;
}
/* ADD-IP, Section 5.2
* When an endpoint receives an ASCONF Chunk from the remote peer
* special procedures may be needed to identify the association the
* ASCONF Chunk is associated with. To properly find the association
* the following procedures SHOULD be followed:
*
* D2) If the association is not found, use the address found in the
* Address Parameter TLV combined with the port number found in the
* SCTP common header. If found proceed to rule D4.
*
* D2-ext) If more than one ASCONF Chunks are packed together, use the
* address found in the ASCONF Address Parameter TLV of each of the
* subsequent ASCONF Chunks. If found, proceed to rule D4.
*/
static struct sctp_association *__sctp_rcv_asconf_lookup(
sctp_chunkhdr_t *ch,
const union sctp_addr *laddr,
__be16 peer_port,
struct sctp_transport **transportp)
{
sctp_addip_chunk_t *asconf = (struct sctp_addip_chunk *)ch;
struct sctp_af *af;
union sctp_addr_param *param;
union sctp_addr paddr;
/* Skip over the ADDIP header and find the Address parameter */
param = (union sctp_addr_param *)(asconf + 1);
af = sctp_get_af_specific(param_type2af(param->p.type));
if (unlikely(!af))
return NULL;
af->from_addr_param(&paddr, param, peer_port, 0);
return __sctp_lookup_association(laddr, &paddr, transportp);
}
/* SCTP-AUTH, Section 6.3:
* If the receiver does not find a STCB for a packet containing an AUTH
* chunk as the first chunk and not a COOKIE-ECHO chunk as the second
* chunk, it MUST use the chunks after the AUTH chunk to look up an existing
* association.
*
* This means that any chunks that can help us identify the association need
* to be looked at to find this association.
*/
static struct sctp_association *__sctp_rcv_walk_lookup(struct sk_buff *skb,
const union sctp_addr *laddr,
struct sctp_transport **transportp)
{
struct sctp_association *asoc = NULL;
sctp_chunkhdr_t *ch;
int have_auth = 0;
unsigned int chunk_num = 1;
__u8 *ch_end;
/* Walk through the chunks looking for AUTH or ASCONF chunks
* to help us find the association.
*/
ch = (sctp_chunkhdr_t *) skb->data;
do {
/* Break out if chunk length is less then minimal. */
if (ntohs(ch->length) < sizeof(sctp_chunkhdr_t))
break;
ch_end = ((__u8 *)ch) + WORD_ROUND(ntohs(ch->length));
if (ch_end > skb_tail_pointer(skb))
break;
switch(ch->type) {
case SCTP_CID_AUTH:
have_auth = chunk_num;
break;
case SCTP_CID_COOKIE_ECHO:
/* If a packet arrives containing an AUTH chunk as
* a first chunk, a COOKIE-ECHO chunk as the second
* chunk, and possibly more chunks after them, and
* the receiver does not have an STCB for that
* packet, then authentication is based on
* the contents of the COOKIE- ECHO chunk.
*/
if (have_auth == 1 && chunk_num == 2)
return NULL;
break;
case SCTP_CID_ASCONF:
if (have_auth || sctp_addip_noauth)
asoc = __sctp_rcv_asconf_lookup(ch, laddr,
sctp_hdr(skb)->source,
transportp);
default:
break;
}
if (asoc)
break;
ch = (sctp_chunkhdr_t *) ch_end;
chunk_num++;
} while (ch_end < skb_tail_pointer(skb));
return asoc;
}
/*
* There are circumstances when we need to look inside the SCTP packet
* for information to help us find the association. Examples
* include looking inside of INIT/INIT-ACK chunks or after the AUTH
* chunks.
*/
static struct sctp_association *__sctp_rcv_lookup_harder(struct sk_buff *skb,
const union sctp_addr *laddr,
struct sctp_transport **transportp)
{
sctp_chunkhdr_t *ch;
ch = (sctp_chunkhdr_t *) skb->data;
/* The code below will attempt to walk the chunk and extract
* parameter information. Before we do that, we need to verify
* that the chunk length doesn't cause overflow. Otherwise, we'll
* walk off the end.
*/
if (WORD_ROUND(ntohs(ch->length)) > skb->len)
return NULL;
/* If this is INIT/INIT-ACK look inside the chunk too. */
switch (ch->type) {
case SCTP_CID_INIT:
case SCTP_CID_INIT_ACK:
return __sctp_rcv_init_lookup(skb, laddr, transportp);
break;
default:
return __sctp_rcv_walk_lookup(skb, laddr, transportp);
break;
}
return NULL;
}
/* Lookup an association for an inbound skb. */
static struct sctp_association *__sctp_rcv_lookup(struct sk_buff *skb,
const union sctp_addr *paddr,
const union sctp_addr *laddr,
struct sctp_transport **transportp)
{
struct sctp_association *asoc;
asoc = __sctp_lookup_association(laddr, paddr, transportp);
/* Further lookup for INIT/INIT-ACK packets.
* SCTP Implementors Guide, 2.18 Handling of address
* parameters within the INIT or INIT-ACK.
*/
if (!asoc)
asoc = __sctp_rcv_lookup_harder(skb, laddr, transportp);
return asoc;
}
| gpl-2.0 |
verygreen/green_kernel_omap | drivers/macintosh/mediabay.c | 4232 | 19355 | /*
* Driver for the media bay on the PowerBook 3400 and 2400.
*
* Copyright (C) 1998 Paul Mackerras.
*
* Various evolutions by Benjamin Herrenschmidt & Henry Worth
*
* 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/types.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include <linux/timer.h>
#include <linux/stddef.h>
#include <linux/init.h>
#include <linux/kthread.h>
#include <linux/mutex.h>
#include <asm/prom.h>
#include <asm/pgtable.h>
#include <asm/io.h>
#include <asm/machdep.h>
#include <asm/pmac_feature.h>
#include <asm/mediabay.h>
#include <asm/sections.h>
#include <asm/ohare.h>
#include <asm/heathrow.h>
#include <asm/keylargo.h>
#include <linux/adb.h>
#include <linux/pmu.h>
#define MB_FCR32(bay, r) ((bay)->base + ((r) >> 2))
#define MB_FCR8(bay, r) (((volatile u8 __iomem *)((bay)->base)) + (r))
#define MB_IN32(bay,r) (in_le32(MB_FCR32(bay,r)))
#define MB_OUT32(bay,r,v) (out_le32(MB_FCR32(bay,r), (v)))
#define MB_BIS(bay,r,v) (MB_OUT32((bay), (r), MB_IN32((bay), r) | (v)))
#define MB_BIC(bay,r,v) (MB_OUT32((bay), (r), MB_IN32((bay), r) & ~(v)))
#define MB_IN8(bay,r) (in_8(MB_FCR8(bay,r)))
#define MB_OUT8(bay,r,v) (out_8(MB_FCR8(bay,r), (v)))
struct media_bay_info;
struct mb_ops {
char* name;
void (*init)(struct media_bay_info *bay);
u8 (*content)(struct media_bay_info *bay);
void (*power)(struct media_bay_info *bay, int on_off);
int (*setup_bus)(struct media_bay_info *bay, u8 device_id);
void (*un_reset)(struct media_bay_info *bay);
void (*un_reset_ide)(struct media_bay_info *bay);
};
struct media_bay_info {
u32 __iomem *base;
int content_id;
int state;
int last_value;
int value_count;
int timer;
struct macio_dev *mdev;
struct mb_ops* ops;
int index;
int cached_gpio;
int sleeping;
int user_lock;
struct mutex lock;
};
#define MAX_BAYS 2
static struct media_bay_info media_bays[MAX_BAYS];
static int media_bay_count = 0;
/*
* Wait that number of ms between each step in normal polling mode
*/
#define MB_POLL_DELAY 25
/*
* Consider the media-bay ID value stable if it is the same for
* this number of milliseconds
*/
#define MB_STABLE_DELAY 100
/* Wait after powering up the media bay this delay in ms
* timeout bumped for some powerbooks
*/
#define MB_POWER_DELAY 200
/*
* Hold the media-bay reset signal true for this many ticks
* after a device is inserted before releasing it.
*/
#define MB_RESET_DELAY 50
/*
* Wait this long after the reset signal is released and before doing
* further operations. After this delay, the IDE reset signal is released
* too for an IDE device
*/
#define MB_SETUP_DELAY 100
/*
* Wait this many ticks after an IDE device (e.g. CD-ROM) is inserted
* (or until the device is ready) before calling into the driver
*/
#define MB_IDE_WAIT 1000
/*
* States of a media bay
*/
enum {
mb_empty = 0, /* Idle */
mb_powering_up, /* power bit set, waiting MB_POWER_DELAY */
mb_enabling_bay, /* enable bits set, waiting MB_RESET_DELAY */
mb_resetting, /* reset bit unset, waiting MB_SETUP_DELAY */
mb_ide_resetting, /* IDE reset bit unser, waiting MB_IDE_WAIT */
mb_up, /* Media bay full */
mb_powering_down /* Powering down (avoid too fast down/up) */
};
#define MB_POWER_SOUND 0x08
#define MB_POWER_FLOPPY 0x04
#define MB_POWER_ATA 0x02
#define MB_POWER_PCI 0x01
#define MB_POWER_OFF 0x00
/*
* Functions for polling content of media bay
*/
static u8
ohare_mb_content(struct media_bay_info *bay)
{
return (MB_IN32(bay, OHARE_MBCR) >> 12) & 7;
}
static u8
heathrow_mb_content(struct media_bay_info *bay)
{
return (MB_IN32(bay, HEATHROW_MBCR) >> 12) & 7;
}
static u8
keylargo_mb_content(struct media_bay_info *bay)
{
int new_gpio;
new_gpio = MB_IN8(bay, KL_GPIO_MEDIABAY_IRQ) & KEYLARGO_GPIO_INPUT_DATA;
if (new_gpio) {
bay->cached_gpio = new_gpio;
return MB_NO;
} else if (bay->cached_gpio != new_gpio) {
MB_BIS(bay, KEYLARGO_MBCR, KL_MBCR_MB0_ENABLE);
(void)MB_IN32(bay, KEYLARGO_MBCR);
udelay(5);
MB_BIC(bay, KEYLARGO_MBCR, 0x0000000F);
(void)MB_IN32(bay, KEYLARGO_MBCR);
udelay(5);
bay->cached_gpio = new_gpio;
}
return (MB_IN32(bay, KEYLARGO_MBCR) >> 4) & 7;
}
/*
* Functions for powering up/down the bay, puts the bay device
* into reset state as well
*/
static void
ohare_mb_power(struct media_bay_info* bay, int on_off)
{
if (on_off) {
/* Power up device, assert it's reset line */
MB_BIC(bay, OHARE_FCR, OH_BAY_RESET_N);
MB_BIC(bay, OHARE_FCR, OH_BAY_POWER_N);
} else {
/* Disable all devices */
MB_BIC(bay, OHARE_FCR, OH_BAY_DEV_MASK);
MB_BIC(bay, OHARE_FCR, OH_FLOPPY_ENABLE);
/* Cut power from bay, release reset line */
MB_BIS(bay, OHARE_FCR, OH_BAY_POWER_N);
MB_BIS(bay, OHARE_FCR, OH_BAY_RESET_N);
MB_BIS(bay, OHARE_FCR, OH_IDE1_RESET_N);
}
MB_BIC(bay, OHARE_MBCR, 0x00000F00);
}
static void
heathrow_mb_power(struct media_bay_info* bay, int on_off)
{
if (on_off) {
/* Power up device, assert it's reset line */
MB_BIC(bay, HEATHROW_FCR, HRW_BAY_RESET_N);
MB_BIC(bay, HEATHROW_FCR, HRW_BAY_POWER_N);
} else {
/* Disable all devices */
MB_BIC(bay, HEATHROW_FCR, HRW_BAY_DEV_MASK);
MB_BIC(bay, HEATHROW_FCR, HRW_SWIM_ENABLE);
/* Cut power from bay, release reset line */
MB_BIS(bay, HEATHROW_FCR, HRW_BAY_POWER_N);
MB_BIS(bay, HEATHROW_FCR, HRW_BAY_RESET_N);
MB_BIS(bay, HEATHROW_FCR, HRW_IDE1_RESET_N);
}
MB_BIC(bay, HEATHROW_MBCR, 0x00000F00);
}
static void
keylargo_mb_power(struct media_bay_info* bay, int on_off)
{
if (on_off) {
/* Power up device, assert it's reset line */
MB_BIC(bay, KEYLARGO_MBCR, KL_MBCR_MB0_DEV_RESET);
MB_BIC(bay, KEYLARGO_MBCR, KL_MBCR_MB0_DEV_POWER);
} else {
/* Disable all devices */
MB_BIC(bay, KEYLARGO_MBCR, KL_MBCR_MB0_DEV_MASK);
MB_BIC(bay, KEYLARGO_FCR1, KL1_EIDE0_ENABLE);
/* Cut power from bay, release reset line */
MB_BIS(bay, KEYLARGO_MBCR, KL_MBCR_MB0_DEV_POWER);
MB_BIS(bay, KEYLARGO_MBCR, KL_MBCR_MB0_DEV_RESET);
MB_BIS(bay, KEYLARGO_FCR1, KL1_EIDE0_RESET_N);
}
MB_BIC(bay, KEYLARGO_MBCR, 0x0000000F);
}
/*
* Functions for configuring the media bay for a given type of device,
* enable the related busses
*/
static int
ohare_mb_setup_bus(struct media_bay_info* bay, u8 device_id)
{
switch(device_id) {
case MB_FD:
case MB_FD1:
MB_BIS(bay, OHARE_FCR, OH_BAY_FLOPPY_ENABLE);
MB_BIS(bay, OHARE_FCR, OH_FLOPPY_ENABLE);
return 0;
case MB_CD:
MB_BIC(bay, OHARE_FCR, OH_IDE1_RESET_N);
MB_BIS(bay, OHARE_FCR, OH_BAY_IDE_ENABLE);
return 0;
case MB_PCI:
MB_BIS(bay, OHARE_FCR, OH_BAY_PCI_ENABLE);
return 0;
}
return -ENODEV;
}
static int
heathrow_mb_setup_bus(struct media_bay_info* bay, u8 device_id)
{
switch(device_id) {
case MB_FD:
case MB_FD1:
MB_BIS(bay, HEATHROW_FCR, HRW_BAY_FLOPPY_ENABLE);
MB_BIS(bay, HEATHROW_FCR, HRW_SWIM_ENABLE);
return 0;
case MB_CD:
MB_BIC(bay, HEATHROW_FCR, HRW_IDE1_RESET_N);
MB_BIS(bay, HEATHROW_FCR, HRW_BAY_IDE_ENABLE);
return 0;
case MB_PCI:
MB_BIS(bay, HEATHROW_FCR, HRW_BAY_PCI_ENABLE);
return 0;
}
return -ENODEV;
}
static int
keylargo_mb_setup_bus(struct media_bay_info* bay, u8 device_id)
{
switch(device_id) {
case MB_CD:
MB_BIS(bay, KEYLARGO_MBCR, KL_MBCR_MB0_IDE_ENABLE);
MB_BIC(bay, KEYLARGO_FCR1, KL1_EIDE0_RESET_N);
MB_BIS(bay, KEYLARGO_FCR1, KL1_EIDE0_ENABLE);
return 0;
case MB_PCI:
MB_BIS(bay, KEYLARGO_MBCR, KL_MBCR_MB0_PCI_ENABLE);
return 0;
case MB_SOUND:
MB_BIS(bay, KEYLARGO_MBCR, KL_MBCR_MB0_SOUND_ENABLE);
return 0;
}
return -ENODEV;
}
/*
* Functions for tweaking resets
*/
static void
ohare_mb_un_reset(struct media_bay_info* bay)
{
MB_BIS(bay, OHARE_FCR, OH_BAY_RESET_N);
}
static void keylargo_mb_init(struct media_bay_info *bay)
{
MB_BIS(bay, KEYLARGO_MBCR, KL_MBCR_MB0_ENABLE);
}
static void heathrow_mb_un_reset(struct media_bay_info* bay)
{
MB_BIS(bay, HEATHROW_FCR, HRW_BAY_RESET_N);
}
static void keylargo_mb_un_reset(struct media_bay_info* bay)
{
MB_BIS(bay, KEYLARGO_MBCR, KL_MBCR_MB0_DEV_RESET);
}
static void ohare_mb_un_reset_ide(struct media_bay_info* bay)
{
MB_BIS(bay, OHARE_FCR, OH_IDE1_RESET_N);
}
static void heathrow_mb_un_reset_ide(struct media_bay_info* bay)
{
MB_BIS(bay, HEATHROW_FCR, HRW_IDE1_RESET_N);
}
static void keylargo_mb_un_reset_ide(struct media_bay_info* bay)
{
MB_BIS(bay, KEYLARGO_FCR1, KL1_EIDE0_RESET_N);
}
static inline void set_mb_power(struct media_bay_info* bay, int onoff)
{
/* Power up up and assert the bay reset line */
if (onoff) {
bay->ops->power(bay, 1);
bay->state = mb_powering_up;
pr_debug("mediabay%d: powering up\n", bay->index);
} else {
/* Make sure everything is powered down & disabled */
bay->ops->power(bay, 0);
bay->state = mb_powering_down;
pr_debug("mediabay%d: powering down\n", bay->index);
}
bay->timer = msecs_to_jiffies(MB_POWER_DELAY);
}
static void poll_media_bay(struct media_bay_info* bay)
{
int id = bay->ops->content(bay);
static char *mb_content_types[] = {
"a floppy drive",
"a floppy drive",
"an unsuported audio device",
"an ATA device",
"an unsupported PCI device",
"an unknown device",
};
if (id != bay->last_value) {
bay->last_value = id;
bay->value_count = 0;
return;
}
if (id == bay->content_id)
return;
bay->value_count += msecs_to_jiffies(MB_POLL_DELAY);
if (bay->value_count >= msecs_to_jiffies(MB_STABLE_DELAY)) {
/* If the device type changes without going thru
* "MB_NO", we force a pass by "MB_NO" to make sure
* things are properly reset
*/
if ((id != MB_NO) && (bay->content_id != MB_NO)) {
id = MB_NO;
pr_debug("mediabay%d: forcing MB_NO\n", bay->index);
}
pr_debug("mediabay%d: switching to %d\n", bay->index, id);
set_mb_power(bay, id != MB_NO);
bay->content_id = id;
if (id >= MB_NO || id < 0)
printk(KERN_INFO "mediabay%d: Bay is now empty\n", bay->index);
else
printk(KERN_INFO "mediabay%d: Bay contains %s\n",
bay->index, mb_content_types[id]);
}
}
int check_media_bay(struct macio_dev *baydev)
{
struct media_bay_info* bay;
int id;
if (baydev == NULL)
return MB_NO;
/* This returns an instant snapshot, not locking, sine
* we may be called with the bay lock held. The resulting
* fuzzyness of the result if called at the wrong time is
* not actually a huge deal
*/
bay = macio_get_drvdata(baydev);
if (bay == NULL)
return MB_NO;
id = bay->content_id;
if (bay->state != mb_up)
return MB_NO;
if (id == MB_FD1)
return MB_FD;
return id;
}
EXPORT_SYMBOL_GPL(check_media_bay);
void lock_media_bay(struct macio_dev *baydev)
{
struct media_bay_info* bay;
if (baydev == NULL)
return;
bay = macio_get_drvdata(baydev);
if (bay == NULL)
return;
mutex_lock(&bay->lock);
bay->user_lock = 1;
}
EXPORT_SYMBOL_GPL(lock_media_bay);
void unlock_media_bay(struct macio_dev *baydev)
{
struct media_bay_info* bay;
if (baydev == NULL)
return;
bay = macio_get_drvdata(baydev);
if (bay == NULL)
return;
if (bay->user_lock) {
bay->user_lock = 0;
mutex_unlock(&bay->lock);
}
}
EXPORT_SYMBOL_GPL(unlock_media_bay);
static int mb_broadcast_hotplug(struct device *dev, void *data)
{
struct media_bay_info* bay = data;
struct macio_dev *mdev;
struct macio_driver *drv;
int state;
if (dev->bus != &macio_bus_type)
return 0;
state = bay->state == mb_up ? bay->content_id : MB_NO;
if (state == MB_FD1)
state = MB_FD;
mdev = to_macio_device(dev);
drv = to_macio_driver(dev->driver);
if (dev->driver && drv->mediabay_event)
drv->mediabay_event(mdev, state);
return 0;
}
static void media_bay_step(int i)
{
struct media_bay_info* bay = &media_bays[i];
/* We don't poll when powering down */
if (bay->state != mb_powering_down)
poll_media_bay(bay);
/* If timer expired run state machine */
if (bay->timer != 0) {
bay->timer -= msecs_to_jiffies(MB_POLL_DELAY);
if (bay->timer > 0)
return;
bay->timer = 0;
}
switch(bay->state) {
case mb_powering_up:
if (bay->ops->setup_bus(bay, bay->last_value) < 0) {
pr_debug("mediabay%d: device not supported (kind:%d)\n",
i, bay->content_id);
set_mb_power(bay, 0);
break;
}
bay->timer = msecs_to_jiffies(MB_RESET_DELAY);
bay->state = mb_enabling_bay;
pr_debug("mediabay%d: enabling (kind:%d)\n", i, bay->content_id);
break;
case mb_enabling_bay:
bay->ops->un_reset(bay);
bay->timer = msecs_to_jiffies(MB_SETUP_DELAY);
bay->state = mb_resetting;
pr_debug("mediabay%d: releasing bay reset (kind:%d)\n",
i, bay->content_id);
break;
case mb_resetting:
if (bay->content_id != MB_CD) {
pr_debug("mediabay%d: bay is up (kind:%d)\n", i,
bay->content_id);
bay->state = mb_up;
device_for_each_child(&bay->mdev->ofdev.dev,
bay, mb_broadcast_hotplug);
break;
}
pr_debug("mediabay%d: releasing ATA reset (kind:%d)\n",
i, bay->content_id);
bay->ops->un_reset_ide(bay);
bay->timer = msecs_to_jiffies(MB_IDE_WAIT);
bay->state = mb_ide_resetting;
break;
case mb_ide_resetting:
pr_debug("mediabay%d: bay is up (kind:%d)\n", i, bay->content_id);
bay->state = mb_up;
device_for_each_child(&bay->mdev->ofdev.dev,
bay, mb_broadcast_hotplug);
break;
case mb_powering_down:
bay->state = mb_empty;
device_for_each_child(&bay->mdev->ofdev.dev,
bay, mb_broadcast_hotplug);
pr_debug("mediabay%d: end of power down\n", i);
break;
}
}
/*
* This procedure runs as a kernel thread to poll the media bay
* once each tick and register and unregister the IDE interface
* with the IDE driver. It needs to be a thread because
* ide_register can't be called from interrupt context.
*/
static int media_bay_task(void *x)
{
int i;
while (!kthread_should_stop()) {
for (i = 0; i < media_bay_count; ++i) {
mutex_lock(&media_bays[i].lock);
if (!media_bays[i].sleeping)
media_bay_step(i);
mutex_unlock(&media_bays[i].lock);
}
msleep_interruptible(MB_POLL_DELAY);
}
return 0;
}
static int __devinit media_bay_attach(struct macio_dev *mdev, const struct of_device_id *match)
{
struct media_bay_info* bay;
u32 __iomem *regbase;
struct device_node *ofnode;
unsigned long base;
int i;
ofnode = mdev->ofdev.dev.of_node;
if (macio_resource_count(mdev) < 1)
return -ENODEV;
if (macio_request_resources(mdev, "media-bay"))
return -EBUSY;
/* Media bay registers are located at the beginning of the
* mac-io chip, for now, we trick and align down the first
* resource passed in
*/
base = macio_resource_start(mdev, 0) & 0xffff0000u;
regbase = (u32 __iomem *)ioremap(base, 0x100);
if (regbase == NULL) {
macio_release_resources(mdev);
return -ENOMEM;
}
i = media_bay_count++;
bay = &media_bays[i];
bay->mdev = mdev;
bay->base = regbase;
bay->index = i;
bay->ops = match->data;
bay->sleeping = 0;
mutex_init(&bay->lock);
/* Init HW probing */
if (bay->ops->init)
bay->ops->init(bay);
printk(KERN_INFO "mediabay%d: Registered %s media-bay\n", i, bay->ops->name);
/* Force an immediate detect */
set_mb_power(bay, 0);
msleep(MB_POWER_DELAY);
bay->content_id = MB_NO;
bay->last_value = bay->ops->content(bay);
bay->value_count = msecs_to_jiffies(MB_STABLE_DELAY);
bay->state = mb_empty;
/* Mark us ready by filling our mdev data */
macio_set_drvdata(mdev, bay);
/* Startup kernel thread */
if (i == 0)
kthread_run(media_bay_task, NULL, "media-bay");
return 0;
}
static int media_bay_suspend(struct macio_dev *mdev, pm_message_t state)
{
struct media_bay_info *bay = macio_get_drvdata(mdev);
if (state.event != mdev->ofdev.dev.power.power_state.event
&& (state.event & PM_EVENT_SLEEP)) {
mutex_lock(&bay->lock);
bay->sleeping = 1;
set_mb_power(bay, 0);
mutex_unlock(&bay->lock);
msleep(MB_POLL_DELAY);
mdev->ofdev.dev.power.power_state = state;
}
return 0;
}
static int media_bay_resume(struct macio_dev *mdev)
{
struct media_bay_info *bay = macio_get_drvdata(mdev);
if (mdev->ofdev.dev.power.power_state.event != PM_EVENT_ON) {
mdev->ofdev.dev.power.power_state = PMSG_ON;
/* We re-enable the bay using it's previous content
only if it did not change. Note those bozo timings,
they seem to help the 3400 get it right.
*/
/* Force MB power to 0 */
mutex_lock(&bay->lock);
set_mb_power(bay, 0);
msleep(MB_POWER_DELAY);
if (bay->ops->content(bay) != bay->content_id) {
printk("mediabay%d: Content changed during sleep...\n", bay->index);
mutex_unlock(&bay->lock);
return 0;
}
set_mb_power(bay, 1);
bay->last_value = bay->content_id;
bay->value_count = msecs_to_jiffies(MB_STABLE_DELAY);
bay->timer = msecs_to_jiffies(MB_POWER_DELAY);
do {
msleep(MB_POLL_DELAY);
media_bay_step(bay->index);
} while((bay->state != mb_empty) &&
(bay->state != mb_up));
bay->sleeping = 0;
mutex_unlock(&bay->lock);
}
return 0;
}
/* Definitions of "ops" structures.
*/
static struct mb_ops ohare_mb_ops = {
.name = "Ohare",
.content = ohare_mb_content,
.power = ohare_mb_power,
.setup_bus = ohare_mb_setup_bus,
.un_reset = ohare_mb_un_reset,
.un_reset_ide = ohare_mb_un_reset_ide,
};
static struct mb_ops heathrow_mb_ops = {
.name = "Heathrow",
.content = heathrow_mb_content,
.power = heathrow_mb_power,
.setup_bus = heathrow_mb_setup_bus,
.un_reset = heathrow_mb_un_reset,
.un_reset_ide = heathrow_mb_un_reset_ide,
};
static struct mb_ops keylargo_mb_ops = {
.name = "KeyLargo",
.init = keylargo_mb_init,
.content = keylargo_mb_content,
.power = keylargo_mb_power,
.setup_bus = keylargo_mb_setup_bus,
.un_reset = keylargo_mb_un_reset,
.un_reset_ide = keylargo_mb_un_reset_ide,
};
/*
* It seems that the bit for the media-bay interrupt in the IRQ_LEVEL
* register is always set when there is something in the media bay.
* This causes problems for the interrupt code if we attach an interrupt
* handler to the media-bay interrupt, because it tends to go into
* an infinite loop calling the media bay interrupt handler.
* Therefore we do it all by polling the media bay once each tick.
*/
static struct of_device_id media_bay_match[] =
{
{
.name = "media-bay",
.compatible = "keylargo-media-bay",
.data = &keylargo_mb_ops,
},
{
.name = "media-bay",
.compatible = "heathrow-media-bay",
.data = &heathrow_mb_ops,
},
{
.name = "media-bay",
.compatible = "ohare-media-bay",
.data = &ohare_mb_ops,
},
{},
};
static struct macio_driver media_bay_driver =
{
.driver = {
.name = "media-bay",
.of_match_table = media_bay_match,
},
.probe = media_bay_attach,
.suspend = media_bay_suspend,
.resume = media_bay_resume
};
static int __init media_bay_init(void)
{
int i;
for (i=0; i<MAX_BAYS; i++) {
memset((char *)&media_bays[i], 0, sizeof(struct media_bay_info));
media_bays[i].content_id = -1;
}
if (!machine_is(powermac))
return 0;
macio_register_driver(&media_bay_driver);
return 0;
}
device_initcall(media_bay_init);
| gpl-2.0 |
1nv4d3r5/linux-1 | sound/soc/codecs/wm8955.c | 4488 | 29307 | /*
* wm8955.c -- WM8955 ALSA SoC Audio driver
*
* Copyright 2009 Wolfson Microelectronics plc
*
* Author: Mark Brown <broonie@opensource.wolfsonmicro.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/pm.h>
#include <linux/i2c.h>
#include <linux/regmap.h>
#include <linux/regulator/consumer.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/initval.h>
#include <sound/tlv.h>
#include <sound/wm8955.h>
#include "wm8955.h"
#define WM8955_NUM_SUPPLIES 4
static const char *wm8955_supply_names[WM8955_NUM_SUPPLIES] = {
"DCVDD",
"DBVDD",
"HPVDD",
"AVDD",
};
/* codec private data */
struct wm8955_priv {
struct regmap *regmap;
unsigned int mclk_rate;
int deemph;
int fs;
struct regulator_bulk_data supplies[WM8955_NUM_SUPPLIES];
};
static const struct reg_default wm8955_reg_defaults[] = {
{ 2, 0x0079 }, /* R2 - LOUT1 volume */
{ 3, 0x0079 }, /* R3 - ROUT1 volume */
{ 5, 0x0008 }, /* R5 - DAC Control */
{ 7, 0x000A }, /* R7 - Audio Interface */
{ 8, 0x0000 }, /* R8 - Sample Rate */
{ 10, 0x00FF }, /* R10 - Left DAC volume */
{ 11, 0x00FF }, /* R11 - Right DAC volume */
{ 12, 0x000F }, /* R12 - Bass control */
{ 13, 0x000F }, /* R13 - Treble control */
{ 23, 0x00C1 }, /* R23 - Additional control (1) */
{ 24, 0x0000 }, /* R24 - Additional control (2) */
{ 25, 0x0000 }, /* R25 - Power Management (1) */
{ 26, 0x0000 }, /* R26 - Power Management (2) */
{ 27, 0x0000 }, /* R27 - Additional Control (3) */
{ 34, 0x0050 }, /* R34 - Left out Mix (1) */
{ 35, 0x0050 }, /* R35 - Left out Mix (2) */
{ 36, 0x0050 }, /* R36 - Right out Mix (1) */
{ 37, 0x0050 }, /* R37 - Right Out Mix (2) */
{ 38, 0x0050 }, /* R38 - Mono out Mix (1) */
{ 39, 0x0050 }, /* R39 - Mono out Mix (2) */
{ 40, 0x0079 }, /* R40 - LOUT2 volume */
{ 41, 0x0079 }, /* R41 - ROUT2 volume */
{ 42, 0x0079 }, /* R42 - MONOOUT volume */
{ 43, 0x0000 }, /* R43 - Clocking / PLL */
{ 44, 0x0103 }, /* R44 - PLL Control 1 */
{ 45, 0x0024 }, /* R45 - PLL Control 2 */
{ 46, 0x01BA }, /* R46 - PLL Control 3 */
{ 59, 0x0000 }, /* R59 - PLL Control 4 */
};
static bool wm8955_writeable(struct device *dev, unsigned int reg)
{
switch (reg) {
case WM8955_LOUT1_VOLUME:
case WM8955_ROUT1_VOLUME:
case WM8955_DAC_CONTROL:
case WM8955_AUDIO_INTERFACE:
case WM8955_SAMPLE_RATE:
case WM8955_LEFT_DAC_VOLUME:
case WM8955_RIGHT_DAC_VOLUME:
case WM8955_BASS_CONTROL:
case WM8955_TREBLE_CONTROL:
case WM8955_RESET:
case WM8955_ADDITIONAL_CONTROL_1:
case WM8955_ADDITIONAL_CONTROL_2:
case WM8955_POWER_MANAGEMENT_1:
case WM8955_POWER_MANAGEMENT_2:
case WM8955_ADDITIONAL_CONTROL_3:
case WM8955_LEFT_OUT_MIX_1:
case WM8955_LEFT_OUT_MIX_2:
case WM8955_RIGHT_OUT_MIX_1:
case WM8955_RIGHT_OUT_MIX_2:
case WM8955_MONO_OUT_MIX_1:
case WM8955_MONO_OUT_MIX_2:
case WM8955_LOUT2_VOLUME:
case WM8955_ROUT2_VOLUME:
case WM8955_MONOOUT_VOLUME:
case WM8955_CLOCKING_PLL:
case WM8955_PLL_CONTROL_1:
case WM8955_PLL_CONTROL_2:
case WM8955_PLL_CONTROL_3:
case WM8955_PLL_CONTROL_4:
return true;
default:
return false;
}
}
static bool wm8955_volatile(struct device *dev, unsigned int reg)
{
switch (reg) {
case WM8955_RESET:
return true;
default:
return false;
}
}
static int wm8955_reset(struct snd_soc_codec *codec)
{
return snd_soc_write(codec, WM8955_RESET, 0);
}
struct pll_factors {
int n;
int k;
int outdiv;
};
/* The size in bits of the FLL divide multiplied by 10
* to allow rounding later */
#define FIXED_FLL_SIZE ((1 << 22) * 10)
static int wm8995_pll_factors(struct device *dev,
int Fref, int Fout, struct pll_factors *pll)
{
u64 Kpart;
unsigned int K, Ndiv, Nmod, target;
dev_dbg(dev, "Fref=%u Fout=%u\n", Fref, Fout);
/* The oscilator should run at should be 90-100MHz, and
* there's a divide by 4 plus an optional divide by 2 in the
* output path to generate the system clock. The clock table
* is sortd so we should always generate a suitable target. */
target = Fout * 4;
if (target < 90000000) {
pll->outdiv = 1;
target *= 2;
} else {
pll->outdiv = 0;
}
WARN_ON(target < 90000000 || target > 100000000);
dev_dbg(dev, "Fvco=%dHz\n", target);
/* Now, calculate N.K */
Ndiv = target / Fref;
pll->n = Ndiv;
Nmod = target % Fref;
dev_dbg(dev, "Nmod=%d\n", Nmod);
/* Calculate fractional part - scale up so we can round. */
Kpart = FIXED_FLL_SIZE * (long long)Nmod;
do_div(Kpart, Fref);
K = Kpart & 0xFFFFFFFF;
if ((K % 10) >= 5)
K += 5;
/* Move down to proper range now rounding is done */
pll->k = K / 10;
dev_dbg(dev, "N=%x K=%x OUTDIV=%x\n", pll->n, pll->k, pll->outdiv);
return 0;
}
/* Lookup table specifying SRATE (table 25 in datasheet); some of the
* output frequencies have been rounded to the standard frequencies
* they are intended to match where the error is slight. */
static struct {
int mclk;
int fs;
int usb;
int sr;
} clock_cfgs[] = {
{ 18432000, 8000, 0, 3, },
{ 18432000, 12000, 0, 9, },
{ 18432000, 16000, 0, 11, },
{ 18432000, 24000, 0, 29, },
{ 18432000, 32000, 0, 13, },
{ 18432000, 48000, 0, 1, },
{ 18432000, 96000, 0, 15, },
{ 16934400, 8018, 0, 19, },
{ 16934400, 11025, 0, 25, },
{ 16934400, 22050, 0, 27, },
{ 16934400, 44100, 0, 17, },
{ 16934400, 88200, 0, 31, },
{ 12000000, 8000, 1, 2, },
{ 12000000, 11025, 1, 25, },
{ 12000000, 12000, 1, 8, },
{ 12000000, 16000, 1, 10, },
{ 12000000, 22050, 1, 27, },
{ 12000000, 24000, 1, 28, },
{ 12000000, 32000, 1, 12, },
{ 12000000, 44100, 1, 17, },
{ 12000000, 48000, 1, 0, },
{ 12000000, 88200, 1, 31, },
{ 12000000, 96000, 1, 14, },
{ 12288000, 8000, 0, 2, },
{ 12288000, 12000, 0, 8, },
{ 12288000, 16000, 0, 10, },
{ 12288000, 24000, 0, 28, },
{ 12288000, 32000, 0, 12, },
{ 12288000, 48000, 0, 0, },
{ 12288000, 96000, 0, 14, },
{ 12289600, 8018, 0, 18, },
{ 12289600, 11025, 0, 24, },
{ 12289600, 22050, 0, 26, },
{ 11289600, 44100, 0, 16, },
{ 11289600, 88200, 0, 31, },
};
static int wm8955_configure_clocking(struct snd_soc_codec *codec)
{
struct wm8955_priv *wm8955 = snd_soc_codec_get_drvdata(codec);
int i, ret, val;
int clocking = 0;
int srate = 0;
int sr = -1;
struct pll_factors pll;
/* If we're not running a sample rate currently just pick one */
if (wm8955->fs == 0)
wm8955->fs = 8000;
/* Can we generate an exact output? */
for (i = 0; i < ARRAY_SIZE(clock_cfgs); i++) {
if (wm8955->fs != clock_cfgs[i].fs)
continue;
sr = i;
if (wm8955->mclk_rate == clock_cfgs[i].mclk)
break;
}
/* We should never get here with an unsupported sample rate */
if (sr == -1) {
dev_err(codec->dev, "Sample rate %dHz unsupported\n",
wm8955->fs);
WARN_ON(sr == -1);
return -EINVAL;
}
if (i == ARRAY_SIZE(clock_cfgs)) {
/* If we can't generate the right clock from MCLK then
* we should configure the PLL to supply us with an
* appropriate clock.
*/
clocking |= WM8955_MCLKSEL;
/* Use the last divider configuration we saw for the
* sample rate. */
ret = wm8995_pll_factors(codec->dev, wm8955->mclk_rate,
clock_cfgs[sr].mclk, &pll);
if (ret != 0) {
dev_err(codec->dev,
"Unable to generate %dHz from %dHz MCLK\n",
wm8955->fs, wm8955->mclk_rate);
return -EINVAL;
}
snd_soc_update_bits(codec, WM8955_PLL_CONTROL_1,
WM8955_N_MASK | WM8955_K_21_18_MASK,
(pll.n << WM8955_N_SHIFT) |
pll.k >> 18);
snd_soc_update_bits(codec, WM8955_PLL_CONTROL_2,
WM8955_K_17_9_MASK,
(pll.k >> 9) & WM8955_K_17_9_MASK);
snd_soc_update_bits(codec, WM8955_PLL_CONTROL_2,
WM8955_K_8_0_MASK,
pll.k & WM8955_K_8_0_MASK);
if (pll.k)
snd_soc_update_bits(codec, WM8955_PLL_CONTROL_4,
WM8955_KEN, WM8955_KEN);
else
snd_soc_update_bits(codec, WM8955_PLL_CONTROL_4,
WM8955_KEN, 0);
if (pll.outdiv)
val = WM8955_PLL_RB | WM8955_PLLOUTDIV2;
else
val = WM8955_PLL_RB;
/* Now start the PLL running */
snd_soc_update_bits(codec, WM8955_CLOCKING_PLL,
WM8955_PLL_RB | WM8955_PLLOUTDIV2, val);
snd_soc_update_bits(codec, WM8955_CLOCKING_PLL,
WM8955_PLLEN, WM8955_PLLEN);
}
srate = clock_cfgs[sr].usb | (clock_cfgs[sr].sr << WM8955_SR_SHIFT);
snd_soc_update_bits(codec, WM8955_SAMPLE_RATE,
WM8955_USB | WM8955_SR_MASK, srate);
snd_soc_update_bits(codec, WM8955_CLOCKING_PLL,
WM8955_MCLKSEL, clocking);
return 0;
}
static int wm8955_sysclk(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
int ret = 0;
/* Always disable the clocks - if we're doing reconfiguration this
* avoids misclocking.
*/
snd_soc_update_bits(codec, WM8955_POWER_MANAGEMENT_1,
WM8955_DIGENB, 0);
snd_soc_update_bits(codec, WM8955_CLOCKING_PLL,
WM8955_PLL_RB | WM8955_PLLEN, 0);
switch (event) {
case SND_SOC_DAPM_POST_PMD:
break;
case SND_SOC_DAPM_PRE_PMU:
ret = wm8955_configure_clocking(codec);
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
static int deemph_settings[] = { 0, 32000, 44100, 48000 };
static int wm8955_set_deemph(struct snd_soc_codec *codec)
{
struct wm8955_priv *wm8955 = snd_soc_codec_get_drvdata(codec);
int val, i, best;
/* If we're using deemphasis select the nearest available sample
* rate.
*/
if (wm8955->deemph) {
best = 1;
for (i = 2; i < ARRAY_SIZE(deemph_settings); i++) {
if (abs(deemph_settings[i] - wm8955->fs) <
abs(deemph_settings[best] - wm8955->fs))
best = i;
}
val = best << WM8955_DEEMPH_SHIFT;
} else {
val = 0;
}
dev_dbg(codec->dev, "Set deemphasis %d\n", val);
return snd_soc_update_bits(codec, WM8955_DAC_CONTROL,
WM8955_DEEMPH_MASK, val);
}
static int wm8955_get_deemph(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct wm8955_priv *wm8955 = snd_soc_codec_get_drvdata(codec);
ucontrol->value.enumerated.item[0] = wm8955->deemph;
return 0;
}
static int wm8955_put_deemph(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct wm8955_priv *wm8955 = snd_soc_codec_get_drvdata(codec);
int deemph = ucontrol->value.enumerated.item[0];
if (deemph > 1)
return -EINVAL;
wm8955->deemph = deemph;
return wm8955_set_deemph(codec);
}
static const char *bass_mode_text[] = {
"Linear", "Adaptive",
};
static const struct soc_enum bass_mode =
SOC_ENUM_SINGLE(WM8955_BASS_CONTROL, 7, 2, bass_mode_text);
static const char *bass_cutoff_text[] = {
"Low", "High"
};
static const struct soc_enum bass_cutoff =
SOC_ENUM_SINGLE(WM8955_BASS_CONTROL, 6, 2, bass_cutoff_text);
static const char *treble_cutoff_text[] = {
"High", "Low"
};
static const struct soc_enum treble_cutoff =
SOC_ENUM_SINGLE(WM8955_TREBLE_CONTROL, 6, 2, treble_cutoff_text);
static const DECLARE_TLV_DB_SCALE(digital_tlv, -12750, 50, 1);
static const DECLARE_TLV_DB_SCALE(atten_tlv, -600, 600, 0);
static const DECLARE_TLV_DB_SCALE(bypass_tlv, -1500, 300, 0);
static const DECLARE_TLV_DB_SCALE(mono_tlv, -2100, 300, 0);
static const DECLARE_TLV_DB_SCALE(out_tlv, -12100, 100, 1);
static const DECLARE_TLV_DB_SCALE(treble_tlv, -1200, 150, 1);
static const struct snd_kcontrol_new wm8955_snd_controls[] = {
SOC_DOUBLE_R_TLV("Digital Playback Volume", WM8955_LEFT_DAC_VOLUME,
WM8955_RIGHT_DAC_VOLUME, 0, 255, 0, digital_tlv),
SOC_SINGLE_TLV("Playback Attenuation Volume", WM8955_DAC_CONTROL, 7, 1, 1,
atten_tlv),
SOC_SINGLE_BOOL_EXT("DAC Deemphasis Switch", 0,
wm8955_get_deemph, wm8955_put_deemph),
SOC_ENUM("Bass Mode", bass_mode),
SOC_ENUM("Bass Cutoff", bass_cutoff),
SOC_SINGLE("Bass Volume", WM8955_BASS_CONTROL, 0, 15, 1),
SOC_ENUM("Treble Cutoff", treble_cutoff),
SOC_SINGLE_TLV("Treble Volume", WM8955_TREBLE_CONTROL, 0, 14, 1, treble_tlv),
SOC_SINGLE_TLV("Left Bypass Volume", WM8955_LEFT_OUT_MIX_1, 4, 7, 1,
bypass_tlv),
SOC_SINGLE_TLV("Left Mono Volume", WM8955_LEFT_OUT_MIX_2, 4, 7, 1,
bypass_tlv),
SOC_SINGLE_TLV("Right Mono Volume", WM8955_RIGHT_OUT_MIX_1, 4, 7, 1,
bypass_tlv),
SOC_SINGLE_TLV("Right Bypass Volume", WM8955_RIGHT_OUT_MIX_2, 4, 7, 1,
bypass_tlv),
/* Not a stereo pair so they line up with the DAPM switches */
SOC_SINGLE_TLV("Mono Left Bypass Volume", WM8955_MONO_OUT_MIX_1, 4, 7, 1,
mono_tlv),
SOC_SINGLE_TLV("Mono Right Bypass Volume", WM8955_MONO_OUT_MIX_2, 4, 7, 1,
mono_tlv),
SOC_DOUBLE_R_TLV("Headphone Volume", WM8955_LOUT1_VOLUME,
WM8955_ROUT1_VOLUME, 0, 127, 0, out_tlv),
SOC_DOUBLE_R("Headphone ZC Switch", WM8955_LOUT1_VOLUME,
WM8955_ROUT1_VOLUME, 7, 1, 0),
SOC_DOUBLE_R_TLV("Speaker Volume", WM8955_LOUT2_VOLUME,
WM8955_ROUT2_VOLUME, 0, 127, 0, out_tlv),
SOC_DOUBLE_R("Speaker ZC Switch", WM8955_LOUT2_VOLUME,
WM8955_ROUT2_VOLUME, 7, 1, 0),
SOC_SINGLE_TLV("Mono Volume", WM8955_MONOOUT_VOLUME, 0, 127, 0, out_tlv),
SOC_SINGLE("Mono ZC Switch", WM8955_MONOOUT_VOLUME, 7, 1, 0),
};
static const struct snd_kcontrol_new lmixer[] = {
SOC_DAPM_SINGLE("Playback Switch", WM8955_LEFT_OUT_MIX_1, 8, 1, 0),
SOC_DAPM_SINGLE("Bypass Switch", WM8955_LEFT_OUT_MIX_1, 7, 1, 0),
SOC_DAPM_SINGLE("Right Playback Switch", WM8955_LEFT_OUT_MIX_2, 8, 1, 0),
SOC_DAPM_SINGLE("Mono Switch", WM8955_LEFT_OUT_MIX_2, 7, 1, 0),
};
static const struct snd_kcontrol_new rmixer[] = {
SOC_DAPM_SINGLE("Left Playback Switch", WM8955_RIGHT_OUT_MIX_1, 8, 1, 0),
SOC_DAPM_SINGLE("Mono Switch", WM8955_RIGHT_OUT_MIX_1, 7, 1, 0),
SOC_DAPM_SINGLE("Playback Switch", WM8955_RIGHT_OUT_MIX_2, 8, 1, 0),
SOC_DAPM_SINGLE("Bypass Switch", WM8955_RIGHT_OUT_MIX_2, 7, 1, 0),
};
static const struct snd_kcontrol_new mmixer[] = {
SOC_DAPM_SINGLE("Left Playback Switch", WM8955_MONO_OUT_MIX_1, 8, 1, 0),
SOC_DAPM_SINGLE("Left Bypass Switch", WM8955_MONO_OUT_MIX_1, 7, 1, 0),
SOC_DAPM_SINGLE("Right Playback Switch", WM8955_MONO_OUT_MIX_2, 8, 1, 0),
SOC_DAPM_SINGLE("Right Bypass Switch", WM8955_MONO_OUT_MIX_2, 7, 1, 0),
};
static const struct snd_soc_dapm_widget wm8955_dapm_widgets[] = {
SND_SOC_DAPM_INPUT("MONOIN-"),
SND_SOC_DAPM_INPUT("MONOIN+"),
SND_SOC_DAPM_INPUT("LINEINR"),
SND_SOC_DAPM_INPUT("LINEINL"),
SND_SOC_DAPM_PGA("Mono Input", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY("SYSCLK", WM8955_POWER_MANAGEMENT_1, 0, 1, wm8955_sysclk,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SUPPLY("TSDEN", WM8955_ADDITIONAL_CONTROL_1, 8, 0, NULL, 0),
SND_SOC_DAPM_DAC("DACL", "Playback", WM8955_POWER_MANAGEMENT_2, 8, 0),
SND_SOC_DAPM_DAC("DACR", "Playback", WM8955_POWER_MANAGEMENT_2, 7, 0),
SND_SOC_DAPM_PGA("LOUT1 PGA", WM8955_POWER_MANAGEMENT_2, 6, 0, NULL, 0),
SND_SOC_DAPM_PGA("ROUT1 PGA", WM8955_POWER_MANAGEMENT_2, 5, 0, NULL, 0),
SND_SOC_DAPM_PGA("LOUT2 PGA", WM8955_POWER_MANAGEMENT_2, 4, 0, NULL, 0),
SND_SOC_DAPM_PGA("ROUT2 PGA", WM8955_POWER_MANAGEMENT_2, 3, 0, NULL, 0),
SND_SOC_DAPM_PGA("MOUT PGA", WM8955_POWER_MANAGEMENT_2, 2, 0, NULL, 0),
SND_SOC_DAPM_PGA("OUT3 PGA", WM8955_POWER_MANAGEMENT_2, 1, 0, NULL, 0),
/* The names are chosen to make the control names nice */
SND_SOC_DAPM_MIXER("Left", SND_SOC_NOPM, 0, 0,
lmixer, ARRAY_SIZE(lmixer)),
SND_SOC_DAPM_MIXER("Right", SND_SOC_NOPM, 0, 0,
rmixer, ARRAY_SIZE(rmixer)),
SND_SOC_DAPM_MIXER("Mono", SND_SOC_NOPM, 0, 0,
mmixer, ARRAY_SIZE(mmixer)),
SND_SOC_DAPM_OUTPUT("LOUT1"),
SND_SOC_DAPM_OUTPUT("ROUT1"),
SND_SOC_DAPM_OUTPUT("LOUT2"),
SND_SOC_DAPM_OUTPUT("ROUT2"),
SND_SOC_DAPM_OUTPUT("MONOOUT"),
SND_SOC_DAPM_OUTPUT("OUT3"),
};
static const struct snd_soc_dapm_route wm8955_dapm_routes[] = {
{ "DACL", NULL, "SYSCLK" },
{ "DACR", NULL, "SYSCLK" },
{ "Mono Input", NULL, "MONOIN-" },
{ "Mono Input", NULL, "MONOIN+" },
{ "Left", "Playback Switch", "DACL" },
{ "Left", "Right Playback Switch", "DACR" },
{ "Left", "Bypass Switch", "LINEINL" },
{ "Left", "Mono Switch", "Mono Input" },
{ "Right", "Playback Switch", "DACR" },
{ "Right", "Left Playback Switch", "DACL" },
{ "Right", "Bypass Switch", "LINEINR" },
{ "Right", "Mono Switch", "Mono Input" },
{ "Mono", "Left Playback Switch", "DACL" },
{ "Mono", "Right Playback Switch", "DACR" },
{ "Mono", "Left Bypass Switch", "LINEINL" },
{ "Mono", "Right Bypass Switch", "LINEINR" },
{ "LOUT1 PGA", NULL, "Left" },
{ "LOUT1", NULL, "TSDEN" },
{ "LOUT1", NULL, "LOUT1 PGA" },
{ "ROUT1 PGA", NULL, "Right" },
{ "ROUT1", NULL, "TSDEN" },
{ "ROUT1", NULL, "ROUT1 PGA" },
{ "LOUT2 PGA", NULL, "Left" },
{ "LOUT2", NULL, "TSDEN" },
{ "LOUT2", NULL, "LOUT2 PGA" },
{ "ROUT2 PGA", NULL, "Right" },
{ "ROUT2", NULL, "TSDEN" },
{ "ROUT2", NULL, "ROUT2 PGA" },
{ "MOUT PGA", NULL, "Mono" },
{ "MONOOUT", NULL, "MOUT PGA" },
/* OUT3 not currently implemented */
{ "OUT3", NULL, "OUT3 PGA" },
};
static int wm8955_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct wm8955_priv *wm8955 = snd_soc_codec_get_drvdata(codec);
int ret;
int wl;
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
wl = 0;
break;
case SNDRV_PCM_FORMAT_S20_3LE:
wl = 0x4;
break;
case SNDRV_PCM_FORMAT_S24_LE:
wl = 0x8;
break;
case SNDRV_PCM_FORMAT_S32_LE:
wl = 0xc;
break;
default:
return -EINVAL;
}
snd_soc_update_bits(codec, WM8955_AUDIO_INTERFACE,
WM8955_WL_MASK, wl);
wm8955->fs = params_rate(params);
wm8955_set_deemph(codec);
/* If the chip is clocked then disable the clocks and force a
* reconfiguration, otherwise DAPM will power up the
* clocks for us later. */
ret = snd_soc_read(codec, WM8955_POWER_MANAGEMENT_1);
if (ret < 0)
return ret;
if (ret & WM8955_DIGENB) {
snd_soc_update_bits(codec, WM8955_POWER_MANAGEMENT_1,
WM8955_DIGENB, 0);
snd_soc_update_bits(codec, WM8955_CLOCKING_PLL,
WM8955_PLL_RB | WM8955_PLLEN, 0);
wm8955_configure_clocking(codec);
}
return 0;
}
static int wm8955_set_sysclk(struct snd_soc_dai *dai, int clk_id,
unsigned int freq, int dir)
{
struct snd_soc_codec *codec = dai->codec;
struct wm8955_priv *priv = snd_soc_codec_get_drvdata(codec);
int div;
switch (clk_id) {
case WM8955_CLK_MCLK:
if (freq > 15000000) {
priv->mclk_rate = freq /= 2;
div = WM8955_MCLKDIV2;
} else {
priv->mclk_rate = freq;
div = 0;
}
snd_soc_update_bits(codec, WM8955_SAMPLE_RATE,
WM8955_MCLKDIV2, div);
break;
default:
return -EINVAL;
}
dev_dbg(dai->dev, "Clock source is %d at %uHz\n", clk_id, freq);
return 0;
}
static int wm8955_set_fmt(struct snd_soc_dai *dai, unsigned int fmt)
{
struct snd_soc_codec *codec = dai->codec;
u16 aif = 0;
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBS_CFS:
break;
case SND_SOC_DAIFMT_CBM_CFM:
aif |= WM8955_MS;
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_DSP_B:
aif |= WM8955_LRP;
case SND_SOC_DAIFMT_DSP_A:
aif |= 0x3;
break;
case SND_SOC_DAIFMT_I2S:
aif |= 0x2;
break;
case SND_SOC_DAIFMT_RIGHT_J:
break;
case SND_SOC_DAIFMT_LEFT_J:
aif |= 0x1;
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_DSP_A:
case SND_SOC_DAIFMT_DSP_B:
/* frame inversion not valid for DSP modes */
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
break;
case SND_SOC_DAIFMT_IB_NF:
aif |= WM8955_BCLKINV;
break;
default:
return -EINVAL;
}
break;
case SND_SOC_DAIFMT_I2S:
case SND_SOC_DAIFMT_RIGHT_J:
case SND_SOC_DAIFMT_LEFT_J:
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
break;
case SND_SOC_DAIFMT_IB_IF:
aif |= WM8955_BCLKINV | WM8955_LRP;
break;
case SND_SOC_DAIFMT_IB_NF:
aif |= WM8955_BCLKINV;
break;
case SND_SOC_DAIFMT_NB_IF:
aif |= WM8955_LRP;
break;
default:
return -EINVAL;
}
break;
default:
return -EINVAL;
}
snd_soc_update_bits(codec, WM8955_AUDIO_INTERFACE,
WM8955_MS | WM8955_FORMAT_MASK | WM8955_BCLKINV |
WM8955_LRP, aif);
return 0;
}
static int wm8955_digital_mute(struct snd_soc_dai *codec_dai, int mute)
{
struct snd_soc_codec *codec = codec_dai->codec;
int val;
if (mute)
val = WM8955_DACMU;
else
val = 0;
snd_soc_update_bits(codec, WM8955_DAC_CONTROL, WM8955_DACMU, val);
return 0;
}
static int wm8955_set_bias_level(struct snd_soc_codec *codec,
enum snd_soc_bias_level level)
{
struct wm8955_priv *wm8955 = snd_soc_codec_get_drvdata(codec);
int ret;
switch (level) {
case SND_SOC_BIAS_ON:
break;
case SND_SOC_BIAS_PREPARE:
/* VMID resistance 2*50k */
snd_soc_update_bits(codec, WM8955_POWER_MANAGEMENT_1,
WM8955_VMIDSEL_MASK,
0x1 << WM8955_VMIDSEL_SHIFT);
/* Default bias current */
snd_soc_update_bits(codec, WM8955_ADDITIONAL_CONTROL_1,
WM8955_VSEL_MASK,
0x2 << WM8955_VSEL_SHIFT);
break;
case SND_SOC_BIAS_STANDBY:
if (codec->dapm.bias_level == SND_SOC_BIAS_OFF) {
ret = regulator_bulk_enable(ARRAY_SIZE(wm8955->supplies),
wm8955->supplies);
if (ret != 0) {
dev_err(codec->dev,
"Failed to enable supplies: %d\n",
ret);
return ret;
}
regcache_sync(wm8955->regmap);
/* Enable VREF and VMID */
snd_soc_update_bits(codec, WM8955_POWER_MANAGEMENT_1,
WM8955_VREF |
WM8955_VMIDSEL_MASK,
WM8955_VREF |
0x3 << WM8955_VREF_SHIFT);
/* Let VMID ramp */
msleep(500);
/* High resistance VROI to maintain outputs */
snd_soc_update_bits(codec,
WM8955_ADDITIONAL_CONTROL_3,
WM8955_VROI, WM8955_VROI);
}
/* Maintain VMID with 2*250k */
snd_soc_update_bits(codec, WM8955_POWER_MANAGEMENT_1,
WM8955_VMIDSEL_MASK,
0x2 << WM8955_VMIDSEL_SHIFT);
/* Minimum bias current */
snd_soc_update_bits(codec, WM8955_ADDITIONAL_CONTROL_1,
WM8955_VSEL_MASK, 0);
break;
case SND_SOC_BIAS_OFF:
/* Low resistance VROI to help discharge */
snd_soc_update_bits(codec,
WM8955_ADDITIONAL_CONTROL_3,
WM8955_VROI, 0);
/* Turn off VMID and VREF */
snd_soc_update_bits(codec, WM8955_POWER_MANAGEMENT_1,
WM8955_VREF |
WM8955_VMIDSEL_MASK, 0);
regulator_bulk_disable(ARRAY_SIZE(wm8955->supplies),
wm8955->supplies);
break;
}
codec->dapm.bias_level = level;
return 0;
}
#define WM8955_RATES SNDRV_PCM_RATE_8000_96000
#define WM8955_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE |\
SNDRV_PCM_FMTBIT_S24_LE | SNDRV_PCM_FMTBIT_S32_LE)
static const struct snd_soc_dai_ops wm8955_dai_ops = {
.set_sysclk = wm8955_set_sysclk,
.set_fmt = wm8955_set_fmt,
.hw_params = wm8955_hw_params,
.digital_mute = wm8955_digital_mute,
};
static struct snd_soc_dai_driver wm8955_dai = {
.name = "wm8955-hifi",
.playback = {
.stream_name = "Playback",
.channels_min = 2,
.channels_max = 2,
.rates = WM8955_RATES,
.formats = WM8955_FORMATS,
},
.ops = &wm8955_dai_ops,
};
#ifdef CONFIG_PM
static int wm8955_suspend(struct snd_soc_codec *codec)
{
struct wm8955_priv *wm8955 = snd_soc_codec_get_drvdata(codec);
wm8955_set_bias_level(codec, SND_SOC_BIAS_OFF);
regcache_mark_dirty(wm8955->regmap);
return 0;
}
static int wm8955_resume(struct snd_soc_codec *codec)
{
wm8955_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
return 0;
}
#else
#define wm8955_suspend NULL
#define wm8955_resume NULL
#endif
static int wm8955_probe(struct snd_soc_codec *codec)
{
struct wm8955_priv *wm8955 = snd_soc_codec_get_drvdata(codec);
struct wm8955_pdata *pdata = dev_get_platdata(codec->dev);
int ret, i;
codec->control_data = wm8955->regmap;
ret = snd_soc_codec_set_cache_io(codec, 7, 9, SND_SOC_REGMAP);
if (ret != 0) {
dev_err(codec->dev, "Failed to set cache I/O: %d\n", ret);
return ret;
}
for (i = 0; i < ARRAY_SIZE(wm8955->supplies); i++)
wm8955->supplies[i].supply = wm8955_supply_names[i];
ret = regulator_bulk_get(codec->dev, ARRAY_SIZE(wm8955->supplies),
wm8955->supplies);
if (ret != 0) {
dev_err(codec->dev, "Failed to request supplies: %d\n", ret);
return ret;
}
ret = regulator_bulk_enable(ARRAY_SIZE(wm8955->supplies),
wm8955->supplies);
if (ret != 0) {
dev_err(codec->dev, "Failed to enable supplies: %d\n", ret);
goto err_get;
}
ret = wm8955_reset(codec);
if (ret < 0) {
dev_err(codec->dev, "Failed to issue reset: %d\n", ret);
goto err_enable;
}
/* Change some default settings - latch VU and enable ZC */
snd_soc_update_bits(codec, WM8955_LEFT_DAC_VOLUME,
WM8955_LDVU, WM8955_LDVU);
snd_soc_update_bits(codec, WM8955_RIGHT_DAC_VOLUME,
WM8955_RDVU, WM8955_RDVU);
snd_soc_update_bits(codec, WM8955_LOUT1_VOLUME,
WM8955_LO1VU | WM8955_LO1ZC,
WM8955_LO1VU | WM8955_LO1ZC);
snd_soc_update_bits(codec, WM8955_ROUT1_VOLUME,
WM8955_RO1VU | WM8955_RO1ZC,
WM8955_RO1VU | WM8955_RO1ZC);
snd_soc_update_bits(codec, WM8955_LOUT2_VOLUME,
WM8955_LO2VU | WM8955_LO2ZC,
WM8955_LO2VU | WM8955_LO2ZC);
snd_soc_update_bits(codec, WM8955_ROUT2_VOLUME,
WM8955_RO2VU | WM8955_RO2ZC,
WM8955_RO2VU | WM8955_RO2ZC);
snd_soc_update_bits(codec, WM8955_MONOOUT_VOLUME,
WM8955_MOZC, WM8955_MOZC);
/* Also enable adaptive bass boost by default */
snd_soc_update_bits(codec, WM8955_BASS_CONTROL, WM8955_BB, WM8955_BB);
/* Set platform data values */
if (pdata) {
if (pdata->out2_speaker)
snd_soc_update_bits(codec, WM8955_ADDITIONAL_CONTROL_2,
WM8955_ROUT2INV, WM8955_ROUT2INV);
if (pdata->monoin_diff)
snd_soc_update_bits(codec, WM8955_MONO_OUT_MIX_1,
WM8955_DMEN, WM8955_DMEN);
}
wm8955_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
/* Bias level configuration will have done an extra enable */
regulator_bulk_disable(ARRAY_SIZE(wm8955->supplies), wm8955->supplies);
return 0;
err_enable:
regulator_bulk_disable(ARRAY_SIZE(wm8955->supplies), wm8955->supplies);
err_get:
regulator_bulk_free(ARRAY_SIZE(wm8955->supplies), wm8955->supplies);
return ret;
}
static int wm8955_remove(struct snd_soc_codec *codec)
{
struct wm8955_priv *wm8955 = snd_soc_codec_get_drvdata(codec);
wm8955_set_bias_level(codec, SND_SOC_BIAS_OFF);
regulator_bulk_free(ARRAY_SIZE(wm8955->supplies), wm8955->supplies);
return 0;
}
static struct snd_soc_codec_driver soc_codec_dev_wm8955 = {
.probe = wm8955_probe,
.remove = wm8955_remove,
.suspend = wm8955_suspend,
.resume = wm8955_resume,
.set_bias_level = wm8955_set_bias_level,
.controls = wm8955_snd_controls,
.num_controls = ARRAY_SIZE(wm8955_snd_controls),
.dapm_widgets = wm8955_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(wm8955_dapm_widgets),
.dapm_routes = wm8955_dapm_routes,
.num_dapm_routes = ARRAY_SIZE(wm8955_dapm_routes),
};
static const struct regmap_config wm8955_regmap = {
.reg_bits = 7,
.val_bits = 9,
.max_register = WM8955_MAX_REGISTER,
.volatile_reg = wm8955_volatile,
.writeable_reg = wm8955_writeable,
.cache_type = REGCACHE_RBTREE,
.reg_defaults = wm8955_reg_defaults,
.num_reg_defaults = ARRAY_SIZE(wm8955_reg_defaults),
};
static __devinit int wm8955_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct wm8955_priv *wm8955;
int ret;
wm8955 = devm_kzalloc(&i2c->dev, sizeof(struct wm8955_priv),
GFP_KERNEL);
if (wm8955 == NULL)
return -ENOMEM;
wm8955->regmap = regmap_init_i2c(i2c, &wm8955_regmap);
if (IS_ERR(wm8955->regmap)) {
ret = PTR_ERR(wm8955->regmap);
dev_err(&i2c->dev, "Failed to allocate register map: %d\n",
ret);
return ret;
}
i2c_set_clientdata(i2c, wm8955);
ret = snd_soc_register_codec(&i2c->dev,
&soc_codec_dev_wm8955, &wm8955_dai, 1);
if (ret != 0)
goto err;
return ret;
err:
regmap_exit(wm8955->regmap);
return ret;
}
static __devexit int wm8955_i2c_remove(struct i2c_client *client)
{
struct wm8955_priv *wm8955 = i2c_get_clientdata(client);
snd_soc_unregister_codec(&client->dev);
regmap_exit(wm8955->regmap);
return 0;
}
static const struct i2c_device_id wm8955_i2c_id[] = {
{ "wm8955", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, wm8955_i2c_id);
static struct i2c_driver wm8955_i2c_driver = {
.driver = {
.name = "wm8955",
.owner = THIS_MODULE,
},
.probe = wm8955_i2c_probe,
.remove = __devexit_p(wm8955_i2c_remove),
.id_table = wm8955_i2c_id,
};
static int __init wm8955_modinit(void)
{
int ret = 0;
ret = i2c_add_driver(&wm8955_i2c_driver);
if (ret != 0) {
printk(KERN_ERR "Failed to register WM8955 I2C driver: %d\n",
ret);
}
return ret;
}
module_init(wm8955_modinit);
static void __exit wm8955_exit(void)
{
i2c_del_driver(&wm8955_i2c_driver);
}
module_exit(wm8955_exit);
MODULE_DESCRIPTION("ASoC WM8955 driver");
MODULE_AUTHOR("Mark Brown <broonie@opensource.wolfsonmicro.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Silviumik/Silviu_Kernel_I9195_LTE_KitKat | fs/reiserfs/lock.c | 7304 | 2672 | #include "reiserfs.h"
#include <linux/mutex.h>
/*
* The previous reiserfs locking scheme was heavily based on
* the tricky properties of the Bkl:
*
* - it was acquired recursively by a same task
* - the performances relied on the release-while-schedule() property
*
* Now that we replace it by a mutex, we still want to keep the same
* recursive property to avoid big changes in the code structure.
* We use our own lock_owner here because the owner field on a mutex
* is only available in SMP or mutex debugging, also we only need this field
* for this mutex, no need for a system wide mutex facility.
*
* Also this lock is often released before a call that could block because
* reiserfs performances were partially based on the release while schedule()
* property of the Bkl.
*/
void reiserfs_write_lock(struct super_block *s)
{
struct reiserfs_sb_info *sb_i = REISERFS_SB(s);
if (sb_i->lock_owner != current) {
mutex_lock(&sb_i->lock);
sb_i->lock_owner = current;
}
/* No need to protect it, only the current task touches it */
sb_i->lock_depth++;
}
void reiserfs_write_unlock(struct super_block *s)
{
struct reiserfs_sb_info *sb_i = REISERFS_SB(s);
/*
* Are we unlocking without even holding the lock?
* Such a situation must raise a BUG() if we don't want
* to corrupt the data.
*/
BUG_ON(sb_i->lock_owner != current);
if (--sb_i->lock_depth == -1) {
sb_i->lock_owner = NULL;
mutex_unlock(&sb_i->lock);
}
}
/*
* If we already own the lock, just exit and don't increase the depth.
* Useful when we don't want to lock more than once.
*
* We always return the lock_depth we had before calling
* this function.
*/
int reiserfs_write_lock_once(struct super_block *s)
{
struct reiserfs_sb_info *sb_i = REISERFS_SB(s);
if (sb_i->lock_owner != current) {
mutex_lock(&sb_i->lock);
sb_i->lock_owner = current;
return sb_i->lock_depth++;
}
return sb_i->lock_depth;
}
void reiserfs_write_unlock_once(struct super_block *s, int lock_depth)
{
if (lock_depth == -1)
reiserfs_write_unlock(s);
}
/*
* Utility function to force a BUG if it is called without the superblock
* write lock held. caller is the string printed just before calling BUG()
*/
void reiserfs_check_lock_depth(struct super_block *sb, char *caller)
{
struct reiserfs_sb_info *sb_i = REISERFS_SB(sb);
if (sb_i->lock_depth < 0)
reiserfs_panic(sb, "%s called without kernel lock held %d",
caller);
}
#ifdef CONFIG_REISERFS_CHECK
void reiserfs_lock_check_recursive(struct super_block *sb)
{
struct reiserfs_sb_info *sb_i = REISERFS_SB(sb);
WARN_ONCE((sb_i->lock_depth > 0), "Unwanted recursive reiserfs lock!\n");
}
#endif
| gpl-2.0 |
rara7886/10.3.1.C.0.136 | fs/stack.c | 7560 | 2584 | #include <linux/export.h>
#include <linux/fs.h>
#include <linux/fs_stack.h>
/* does _NOT_ require i_mutex to be held.
*
* This function cannot be inlined since i_size_{read,write} is rather
* heavy-weight on 32-bit systems
*/
void fsstack_copy_inode_size(struct inode *dst, struct inode *src)
{
loff_t i_size;
blkcnt_t i_blocks;
/*
* i_size_read() includes its own seqlocking and protection from
* preemption (see include/linux/fs.h): we need nothing extra for
* that here, and prefer to avoid nesting locks than attempt to keep
* i_size and i_blocks in sync together.
*/
i_size = i_size_read(src);
/*
* But if CONFIG_LBDAF (on 32-bit), we ought to make an effort to
* keep the two halves of i_blocks in sync despite SMP or PREEMPT -
* though stat's generic_fillattr() doesn't bother, and we won't be
* applying quotas (where i_blocks does become important) at the
* upper level.
*
* We don't actually know what locking is used at the lower level;
* but if it's a filesystem that supports quotas, it will be using
* i_lock as in inode_add_bytes().
*/
if (sizeof(i_blocks) > sizeof(long))
spin_lock(&src->i_lock);
i_blocks = src->i_blocks;
if (sizeof(i_blocks) > sizeof(long))
spin_unlock(&src->i_lock);
/*
* If CONFIG_SMP or CONFIG_PREEMPT on 32-bit, it's vital for
* fsstack_copy_inode_size() to hold some lock around
* i_size_write(), otherwise i_size_read() may spin forever (see
* include/linux/fs.h). We don't necessarily hold i_mutex when this
* is called, so take i_lock for that case.
*
* And if CONFIG_LBADF (on 32-bit), continue our effort to keep the
* two halves of i_blocks in sync despite SMP or PREEMPT: use i_lock
* for that case too, and do both at once by combining the tests.
*
* There is none of this locking overhead in the 64-bit case.
*/
if (sizeof(i_size) > sizeof(long) || sizeof(i_blocks) > sizeof(long))
spin_lock(&dst->i_lock);
i_size_write(dst, i_size);
dst->i_blocks = i_blocks;
if (sizeof(i_size) > sizeof(long) || sizeof(i_blocks) > sizeof(long))
spin_unlock(&dst->i_lock);
}
EXPORT_SYMBOL_GPL(fsstack_copy_inode_size);
/* copy all attributes */
void fsstack_copy_attr_all(struct inode *dest, const struct inode *src)
{
dest->i_mode = src->i_mode;
dest->i_uid = src->i_uid;
dest->i_gid = src->i_gid;
dest->i_rdev = src->i_rdev;
dest->i_atime = src->i_atime;
dest->i_mtime = src->i_mtime;
dest->i_ctime = src->i_ctime;
dest->i_blkbits = src->i_blkbits;
dest->i_flags = src->i_flags;
set_nlink(dest, src->i_nlink);
}
EXPORT_SYMBOL_GPL(fsstack_copy_attr_all);
| gpl-2.0 |
keecker/kernel_msm-3.10 | drivers/net/wireless/rtlwifi/rtl8192ce/table.c | 9608 | 25797 | /******************************************************************************
*
* Copyright(c) 2009-2012 Realtek Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <wlanfae@realtek.com>
* Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park,
* Hsinchu 300, Taiwan.
*
* Created on 2010/ 5/18, 1:41
*
* Larry Finger <Larry.Finger@lwfinger.net>
*
*****************************************************************************/
#include "table.h"
u32 RTL8192CEPHY_REG_2TARRAY[PHY_REG_2TARRAY_LENGTH] = {
0x024, 0x0011800f,
0x028, 0x00ffdb83,
0x800, 0x80040002,
0x804, 0x00000003,
0x808, 0x0000fc00,
0x80c, 0x0000000a,
0x810, 0x10005388,
0x814, 0x020c3d10,
0x818, 0x02200385,
0x81c, 0x00000000,
0x820, 0x01000100,
0x824, 0x00390004,
0x828, 0x01000100,
0x82c, 0x00390004,
0x830, 0x27272727,
0x834, 0x27272727,
0x838, 0x27272727,
0x83c, 0x27272727,
0x840, 0x00010000,
0x844, 0x00010000,
0x848, 0x27272727,
0x84c, 0x27272727,
0x850, 0x00000000,
0x854, 0x00000000,
0x858, 0x569a569a,
0x85c, 0x0c1b25a4,
0x860, 0x66e60230,
0x864, 0x061f0130,
0x868, 0x27272727,
0x86c, 0x2b2b2b27,
0x870, 0x07000700,
0x874, 0x22184000,
0x878, 0x08080808,
0x87c, 0x00000000,
0x880, 0xc0083070,
0x884, 0x000004d5,
0x888, 0x00000000,
0x88c, 0xcc0000c0,
0x890, 0x00000800,
0x894, 0xfffffffe,
0x898, 0x40302010,
0x89c, 0x00706050,
0x900, 0x00000000,
0x904, 0x00000023,
0x908, 0x00000000,
0x90c, 0x81121313,
0xa00, 0x00d047c8,
0xa04, 0x80ff000c,
0xa08, 0x8c838300,
0xa0c, 0x2e68120f,
0xa10, 0x9500bb78,
0xa14, 0x11144028,
0xa18, 0x00881117,
0xa1c, 0x89140f00,
0xa20, 0x1a1b0000,
0xa24, 0x090e1317,
0xa28, 0x00000204,
0xa2c, 0x00d30000,
0xa70, 0x101fbf00,
0xa74, 0x00000007,
0xc00, 0x48071d40,
0xc04, 0x03a05633,
0xc08, 0x000000e4,
0xc0c, 0x6c6c6c6c,
0xc10, 0x08800000,
0xc14, 0x40000100,
0xc18, 0x08800000,
0xc1c, 0x40000100,
0xc20, 0x00000000,
0xc24, 0x00000000,
0xc28, 0x00000000,
0xc2c, 0x00000000,
0xc30, 0x69e9ac44,
0xc34, 0x469652cf,
0xc38, 0x49795994,
0xc3c, 0x0a97971c,
0xc40, 0x1f7c403f,
0xc44, 0x000100b7,
0xc48, 0xec020107,
0xc4c, 0x007f037f,
0xc50, 0x69543420,
0xc54, 0x43bc0094,
0xc58, 0x69543420,
0xc5c, 0x433c0094,
0xc60, 0x00000000,
0xc64, 0x5116848b,
0xc68, 0x47c00bff,
0xc6c, 0x00000036,
0xc70, 0x2c7f000d,
0xc74, 0x018610db,
0xc78, 0x0000001f,
0xc7c, 0x00b91612,
0xc80, 0x40000100,
0xc84, 0x20f60000,
0xc88, 0x40000100,
0xc8c, 0x20200000,
0xc90, 0x00121820,
0xc94, 0x00000000,
0xc98, 0x00121820,
0xc9c, 0x00007f7f,
0xca0, 0x00000000,
0xca4, 0x00000080,
0xca8, 0x00000000,
0xcac, 0x00000000,
0xcb0, 0x00000000,
0xcb4, 0x00000000,
0xcb8, 0x00000000,
0xcbc, 0x28000000,
0xcc0, 0x00000000,
0xcc4, 0x00000000,
0xcc8, 0x00000000,
0xccc, 0x00000000,
0xcd0, 0x00000000,
0xcd4, 0x00000000,
0xcd8, 0x64b22427,
0xcdc, 0x00766932,
0xce0, 0x00222222,
0xce4, 0x00000000,
0xce8, 0x37644302,
0xcec, 0x2f97d40c,
0xd00, 0x00080740,
0xd04, 0x00020403,
0xd08, 0x0000907f,
0xd0c, 0x20010201,
0xd10, 0xa0633333,
0xd14, 0x3333bc43,
0xd18, 0x7a8f5b6b,
0xd2c, 0xcc979975,
0xd30, 0x00000000,
0xd34, 0x80608000,
0xd38, 0x00000000,
0xd3c, 0x00027293,
0xd40, 0x00000000,
0xd44, 0x00000000,
0xd48, 0x00000000,
0xd4c, 0x00000000,
0xd50, 0x6437140a,
0xd54, 0x00000000,
0xd58, 0x00000000,
0xd5c, 0x30032064,
0xd60, 0x4653de68,
0xd64, 0x04518a3c,
0xd68, 0x00002101,
0xd6c, 0x2a201c16,
0xd70, 0x1812362e,
0xd74, 0x322c2220,
0xd78, 0x000e3c24,
0xe00, 0x2a2a2a2a,
0xe04, 0x2a2a2a2a,
0xe08, 0x03902a2a,
0xe10, 0x2a2a2a2a,
0xe14, 0x2a2a2a2a,
0xe18, 0x2a2a2a2a,
0xe1c, 0x2a2a2a2a,
0xe28, 0x00000000,
0xe30, 0x1000dc1f,
0xe34, 0x10008c1f,
0xe38, 0x02140102,
0xe3c, 0x681604c2,
0xe40, 0x01007c00,
0xe44, 0x01004800,
0xe48, 0xfb000000,
0xe4c, 0x000028d1,
0xe50, 0x1000dc1f,
0xe54, 0x10008c1f,
0xe58, 0x02140102,
0xe5c, 0x28160d05,
0xe60, 0x00000010,
0xe68, 0x001b25a4,
0xe6c, 0x63db25a4,
0xe70, 0x63db25a4,
0xe74, 0x0c1b25a4,
0xe78, 0x0c1b25a4,
0xe7c, 0x0c1b25a4,
0xe80, 0x0c1b25a4,
0xe84, 0x63db25a4,
0xe88, 0x0c1b25a4,
0xe8c, 0x63db25a4,
0xed0, 0x63db25a4,
0xed4, 0x63db25a4,
0xed8, 0x63db25a4,
0xedc, 0x001b25a4,
0xee0, 0x001b25a4,
0xeec, 0x6fdb25a4,
0xf14, 0x00000003,
0xf4c, 0x00000000,
0xf00, 0x00000300,
};
u32 RTL8192CEPHY_REG_1TARRAY[PHY_REG_1TARRAY_LENGTH] = {
0x024, 0x0011800f,
0x028, 0x00ffdb83,
0x800, 0x80040000,
0x804, 0x00000001,
0x808, 0x0000fc00,
0x80c, 0x0000000a,
0x810, 0x10005388,
0x814, 0x020c3d10,
0x818, 0x02200385,
0x81c, 0x00000000,
0x820, 0x01000100,
0x824, 0x00390004,
0x828, 0x00000000,
0x82c, 0x00000000,
0x830, 0x00000000,
0x834, 0x00000000,
0x838, 0x00000000,
0x83c, 0x00000000,
0x840, 0x00010000,
0x844, 0x00000000,
0x848, 0x00000000,
0x84c, 0x00000000,
0x850, 0x00000000,
0x854, 0x00000000,
0x858, 0x569a569a,
0x85c, 0x001b25a4,
0x860, 0x66e60230,
0x864, 0x061f0130,
0x868, 0x00000000,
0x86c, 0x32323200,
0x870, 0x07000700,
0x874, 0x22004000,
0x878, 0x00000808,
0x87c, 0x00000000,
0x880, 0xc0083070,
0x884, 0x000004d5,
0x888, 0x00000000,
0x88c, 0xccc000c0,
0x890, 0x00000800,
0x894, 0xfffffffe,
0x898, 0x40302010,
0x89c, 0x00706050,
0x900, 0x00000000,
0x904, 0x00000023,
0x908, 0x00000000,
0x90c, 0x81121111,
0xa00, 0x00d047c8,
0xa04, 0x80ff000c,
0xa08, 0x8c838300,
0xa0c, 0x2e68120f,
0xa10, 0x9500bb78,
0xa14, 0x11144028,
0xa18, 0x00881117,
0xa1c, 0x89140f00,
0xa20, 0x1a1b0000,
0xa24, 0x090e1317,
0xa28, 0x00000204,
0xa2c, 0x00d30000,
0xa70, 0x101fbf00,
0xa74, 0x00000007,
0xc00, 0x48071d40,
0xc04, 0x03a05611,
0xc08, 0x000000e4,
0xc0c, 0x6c6c6c6c,
0xc10, 0x08800000,
0xc14, 0x40000100,
0xc18, 0x08800000,
0xc1c, 0x40000100,
0xc20, 0x00000000,
0xc24, 0x00000000,
0xc28, 0x00000000,
0xc2c, 0x00000000,
0xc30, 0x69e9ac44,
0xc34, 0x469652cf,
0xc38, 0x49795994,
0xc3c, 0x0a97971c,
0xc40, 0x1f7c403f,
0xc44, 0x000100b7,
0xc48, 0xec020107,
0xc4c, 0x007f037f,
0xc50, 0x69543420,
0xc54, 0x43bc0094,
0xc58, 0x69543420,
0xc5c, 0x433c0094,
0xc60, 0x00000000,
0xc64, 0x5116848b,
0xc68, 0x47c00bff,
0xc6c, 0x00000036,
0xc70, 0x2c7f000d,
0xc74, 0x018610db,
0xc78, 0x0000001f,
0xc7c, 0x00b91612,
0xc80, 0x40000100,
0xc84, 0x20f60000,
0xc88, 0x40000100,
0xc8c, 0x20200000,
0xc90, 0x00121820,
0xc94, 0x00000000,
0xc98, 0x00121820,
0xc9c, 0x00007f7f,
0xca0, 0x00000000,
0xca4, 0x00000080,
0xca8, 0x00000000,
0xcac, 0x00000000,
0xcb0, 0x00000000,
0xcb4, 0x00000000,
0xcb8, 0x00000000,
0xcbc, 0x28000000,
0xcc0, 0x00000000,
0xcc4, 0x00000000,
0xcc8, 0x00000000,
0xccc, 0x00000000,
0xcd0, 0x00000000,
0xcd4, 0x00000000,
0xcd8, 0x64b22427,
0xcdc, 0x00766932,
0xce0, 0x00222222,
0xce4, 0x00000000,
0xce8, 0x37644302,
0xcec, 0x2f97d40c,
0xd00, 0x00080740,
0xd04, 0x00020401,
0xd08, 0x0000907f,
0xd0c, 0x20010201,
0xd10, 0xa0633333,
0xd14, 0x3333bc43,
0xd18, 0x7a8f5b6b,
0xd2c, 0xcc979975,
0xd30, 0x00000000,
0xd34, 0x80608000,
0xd38, 0x00000000,
0xd3c, 0x00027293,
0xd40, 0x00000000,
0xd44, 0x00000000,
0xd48, 0x00000000,
0xd4c, 0x00000000,
0xd50, 0x6437140a,
0xd54, 0x00000000,
0xd58, 0x00000000,
0xd5c, 0x30032064,
0xd60, 0x4653de68,
0xd64, 0x04518a3c,
0xd68, 0x00002101,
0xd6c, 0x2a201c16,
0xd70, 0x1812362e,
0xd74, 0x322c2220,
0xd78, 0x000e3c24,
0xe00, 0x2a2a2a2a,
0xe04, 0x2a2a2a2a,
0xe08, 0x03902a2a,
0xe10, 0x2a2a2a2a,
0xe14, 0x2a2a2a2a,
0xe18, 0x2a2a2a2a,
0xe1c, 0x2a2a2a2a,
0xe28, 0x00000000,
0xe30, 0x1000dc1f,
0xe34, 0x10008c1f,
0xe38, 0x02140102,
0xe3c, 0x681604c2,
0xe40, 0x01007c00,
0xe44, 0x01004800,
0xe48, 0xfb000000,
0xe4c, 0x000028d1,
0xe50, 0x1000dc1f,
0xe54, 0x10008c1f,
0xe58, 0x02140102,
0xe5c, 0x28160d05,
0xe60, 0x00000010,
0xe68, 0x001b25a4,
0xe6c, 0x631b25a0,
0xe70, 0x631b25a0,
0xe74, 0x081b25a0,
0xe78, 0x081b25a0,
0xe7c, 0x081b25a0,
0xe80, 0x081b25a0,
0xe84, 0x631b25a0,
0xe88, 0x081b25a0,
0xe8c, 0x631b25a0,
0xed0, 0x631b25a0,
0xed4, 0x631b25a0,
0xed8, 0x631b25a0,
0xedc, 0x001b25a0,
0xee0, 0x001b25a0,
0xeec, 0x6b1b25a0,
0xf14, 0x00000003,
0xf4c, 0x00000000,
0xf00, 0x00000300,
};
u32 RTL8192CEPHY_REG_ARRAY_PG[PHY_REG_ARRAY_PGLENGTH] = {
0xe00, 0xffffffff, 0x0a0c0c0c,
0xe04, 0xffffffff, 0x02040608,
0xe08, 0x0000ff00, 0x00000000,
0x86c, 0xffffff00, 0x00000000,
0xe10, 0xffffffff, 0x0a0c0d0e,
0xe14, 0xffffffff, 0x02040608,
0xe18, 0xffffffff, 0x0a0c0d0e,
0xe1c, 0xffffffff, 0x02040608,
0x830, 0xffffffff, 0x0a0c0c0c,
0x834, 0xffffffff, 0x02040608,
0x838, 0xffffff00, 0x00000000,
0x86c, 0x000000ff, 0x00000000,
0x83c, 0xffffffff, 0x0a0c0d0e,
0x848, 0xffffffff, 0x02040608,
0x84c, 0xffffffff, 0x0a0c0d0e,
0x868, 0xffffffff, 0x02040608,
0xe00, 0xffffffff, 0x00000000,
0xe04, 0xffffffff, 0x00000000,
0xe08, 0x0000ff00, 0x00000000,
0x86c, 0xffffff00, 0x00000000,
0xe10, 0xffffffff, 0x00000000,
0xe14, 0xffffffff, 0x00000000,
0xe18, 0xffffffff, 0x00000000,
0xe1c, 0xffffffff, 0x00000000,
0x830, 0xffffffff, 0x00000000,
0x834, 0xffffffff, 0x00000000,
0x838, 0xffffff00, 0x00000000,
0x86c, 0x000000ff, 0x00000000,
0x83c, 0xffffffff, 0x00000000,
0x848, 0xffffffff, 0x00000000,
0x84c, 0xffffffff, 0x00000000,
0x868, 0xffffffff, 0x00000000,
0xe00, 0xffffffff, 0x04040404,
0xe04, 0xffffffff, 0x00020204,
0xe08, 0x0000ff00, 0x00000000,
0x86c, 0xffffff00, 0x00000000,
0xe10, 0xffffffff, 0x06060606,
0xe14, 0xffffffff, 0x00020406,
0xe18, 0xffffffff, 0x06060606,
0xe1c, 0xffffffff, 0x00020406,
0x830, 0xffffffff, 0x04040404,
0x834, 0xffffffff, 0x00020204,
0x838, 0xffffff00, 0x00000000,
0x86c, 0x000000ff, 0x00000000,
0x83c, 0xffffffff, 0x06060606,
0x848, 0xffffffff, 0x00020406,
0x84c, 0xffffffff, 0x06060606,
0x868, 0xffffffff, 0x00020406,
0xe00, 0xffffffff, 0x00000000,
0xe04, 0xffffffff, 0x00000000,
0xe08, 0x0000ff00, 0x00000000,
0x86c, 0xffffff00, 0x00000000,
0xe10, 0xffffffff, 0x00000000,
0xe14, 0xffffffff, 0x00000000,
0xe18, 0xffffffff, 0x00000000,
0xe1c, 0xffffffff, 0x00000000,
0x830, 0xffffffff, 0x00000000,
0x834, 0xffffffff, 0x00000000,
0x838, 0xffffff00, 0x00000000,
0x86c, 0x000000ff, 0x00000000,
0x83c, 0xffffffff, 0x00000000,
0x848, 0xffffffff, 0x00000000,
0x84c, 0xffffffff, 0x00000000,
0x868, 0xffffffff, 0x00000000,
};
u32 RTL8192CERADIOA_2TARRAY[RADIOA_2TARRAYLENGTH] = {
0x000, 0x00030159,
0x001, 0x00031284,
0x002, 0x00098000,
0x003, 0x00018c63,
0x004, 0x000210e7,
0x009, 0x0002044f,
0x00a, 0x0001adb0,
0x00b, 0x00054867,
0x00c, 0x0008992e,
0x00d, 0x0000e52c,
0x00e, 0x00039ce7,
0x00f, 0x00000451,
0x019, 0x00000000,
0x01a, 0x00010255,
0x01b, 0x00060a00,
0x01c, 0x000fc378,
0x01d, 0x000a1250,
0x01e, 0x0004445f,
0x01f, 0x00080001,
0x020, 0x0000b614,
0x021, 0x0006c000,
0x022, 0x00000000,
0x023, 0x00001558,
0x024, 0x00000060,
0x025, 0x00000483,
0x026, 0x0004f000,
0x027, 0x000ec7d9,
0x028, 0x000977c0,
0x029, 0x00004783,
0x02a, 0x00000001,
0x02b, 0x00021334,
0x02a, 0x00000000,
0x02b, 0x00000054,
0x02a, 0x00000001,
0x02b, 0x00000808,
0x02b, 0x00053333,
0x02c, 0x0000000c,
0x02a, 0x00000002,
0x02b, 0x00000808,
0x02b, 0x0005b333,
0x02c, 0x0000000d,
0x02a, 0x00000003,
0x02b, 0x00000808,
0x02b, 0x00063333,
0x02c, 0x0000000d,
0x02a, 0x00000004,
0x02b, 0x00000808,
0x02b, 0x0006b333,
0x02c, 0x0000000d,
0x02a, 0x00000005,
0x02b, 0x00000808,
0x02b, 0x00073333,
0x02c, 0x0000000d,
0x02a, 0x00000006,
0x02b, 0x00000709,
0x02b, 0x0005b333,
0x02c, 0x0000000d,
0x02a, 0x00000007,
0x02b, 0x00000709,
0x02b, 0x00063333,
0x02c, 0x0000000d,
0x02a, 0x00000008,
0x02b, 0x0000060a,
0x02b, 0x0004b333,
0x02c, 0x0000000d,
0x02a, 0x00000009,
0x02b, 0x0000060a,
0x02b, 0x00053333,
0x02c, 0x0000000d,
0x02a, 0x0000000a,
0x02b, 0x0000060a,
0x02b, 0x0005b333,
0x02c, 0x0000000d,
0x02a, 0x0000000b,
0x02b, 0x0000060a,
0x02b, 0x00063333,
0x02c, 0x0000000d,
0x02a, 0x0000000c,
0x02b, 0x0000060a,
0x02b, 0x0006b333,
0x02c, 0x0000000d,
0x02a, 0x0000000d,
0x02b, 0x0000060a,
0x02b, 0x00073333,
0x02c, 0x0000000d,
0x02a, 0x0000000e,
0x02b, 0x0000050b,
0x02b, 0x00066666,
0x02c, 0x0000001a,
0x02a, 0x000e0000,
0x010, 0x0004000f,
0x011, 0x000e31fc,
0x010, 0x0006000f,
0x011, 0x000ff9f8,
0x010, 0x0002000f,
0x011, 0x000203f9,
0x010, 0x0003000f,
0x011, 0x000ff500,
0x010, 0x00000000,
0x011, 0x00000000,
0x010, 0x0008000f,
0x011, 0x0003f100,
0x010, 0x0009000f,
0x011, 0x00023100,
0x012, 0x00032000,
0x012, 0x00071000,
0x012, 0x000b0000,
0x012, 0x000fc000,
0x013, 0x000287af,
0x013, 0x000244b7,
0x013, 0x000204ab,
0x013, 0x0001c49f,
0x013, 0x00018493,
0x013, 0x00014297,
0x013, 0x00010295,
0x013, 0x0000c298,
0x013, 0x0000819c,
0x013, 0x000040a8,
0x013, 0x0000001c,
0x014, 0x0001944c,
0x014, 0x00059444,
0x014, 0x0009944c,
0x014, 0x000d9444,
0x015, 0x0000f424,
0x015, 0x0004f424,
0x015, 0x0008f424,
0x015, 0x000cf424,
0x016, 0x000e0330,
0x016, 0x000a0330,
0x016, 0x00060330,
0x016, 0x00020330,
0x000, 0x00010159,
0x018, 0x0000f401,
0x0fe, 0x00000000,
0x0fe, 0x00000000,
0x01f, 0x00080003,
0x0fe, 0x00000000,
0x0fe, 0x00000000,
0x01e, 0x00044457,
0x01f, 0x00080000,
0x000, 0x00030159,
};
u32 RTL8192CE_RADIOB_2TARRAY[RADIOB_2TARRAYLENGTH] = {
0x000, 0x00030159,
0x001, 0x00031284,
0x002, 0x00098000,
0x003, 0x00018c63,
0x004, 0x000210e7,
0x009, 0x0002044f,
0x00a, 0x0001adb0,
0x00b, 0x00054867,
0x00c, 0x0008992e,
0x00d, 0x0000e52c,
0x00e, 0x00039ce7,
0x00f, 0x00000451,
0x012, 0x00032000,
0x012, 0x00071000,
0x012, 0x000b0000,
0x012, 0x000fc000,
0x013, 0x000287af,
0x013, 0x000244b7,
0x013, 0x000204ab,
0x013, 0x0001c49f,
0x013, 0x00018493,
0x013, 0x00014297,
0x013, 0x00010295,
0x013, 0x0000c298,
0x013, 0x0000819c,
0x013, 0x000040a8,
0x013, 0x0000001c,
0x014, 0x0001944c,
0x014, 0x00059444,
0x014, 0x0009944c,
0x014, 0x000d9444,
0x015, 0x0000f424,
0x015, 0x0004f424,
0x015, 0x0008f424,
0x015, 0x000cf424,
0x016, 0x000e0330,
0x016, 0x000a0330,
0x016, 0x00060330,
0x016, 0x00020330,
};
u32 RTL8192CE_RADIOA_1TARRAY[RADIOA_1TARRAYLENGTH] = {
0x000, 0x00030159,
0x001, 0x00031284,
0x002, 0x00098000,
0x003, 0x00018c63,
0x004, 0x000210e7,
0x009, 0x0002044f,
0x00a, 0x0001adb0,
0x00b, 0x00054867,
0x00c, 0x0008992e,
0x00d, 0x0000e52c,
0x00e, 0x00039ce7,
0x00f, 0x00000451,
0x019, 0x00000000,
0x01a, 0x00010255,
0x01b, 0x00060a00,
0x01c, 0x000fc378,
0x01d, 0x000a1250,
0x01e, 0x0004445f,
0x01f, 0x00080001,
0x020, 0x0000b614,
0x021, 0x0006c000,
0x022, 0x00000000,
0x023, 0x00001558,
0x024, 0x00000060,
0x025, 0x00000483,
0x026, 0x0004f000,
0x027, 0x000ec7d9,
0x028, 0x000977c0,
0x029, 0x00004783,
0x02a, 0x00000001,
0x02b, 0x00021334,
0x02a, 0x00000000,
0x02b, 0x00000054,
0x02a, 0x00000001,
0x02b, 0x00000808,
0x02b, 0x00053333,
0x02c, 0x0000000c,
0x02a, 0x00000002,
0x02b, 0x00000808,
0x02b, 0x0005b333,
0x02c, 0x0000000d,
0x02a, 0x00000003,
0x02b, 0x00000808,
0x02b, 0x00063333,
0x02c, 0x0000000d,
0x02a, 0x00000004,
0x02b, 0x00000808,
0x02b, 0x0006b333,
0x02c, 0x0000000d,
0x02a, 0x00000005,
0x02b, 0x00000808,
0x02b, 0x00073333,
0x02c, 0x0000000d,
0x02a, 0x00000006,
0x02b, 0x00000709,
0x02b, 0x0005b333,
0x02c, 0x0000000d,
0x02a, 0x00000007,
0x02b, 0x00000709,
0x02b, 0x00063333,
0x02c, 0x0000000d,
0x02a, 0x00000008,
0x02b, 0x0000060a,
0x02b, 0x0004b333,
0x02c, 0x0000000d,
0x02a, 0x00000009,
0x02b, 0x0000060a,
0x02b, 0x00053333,
0x02c, 0x0000000d,
0x02a, 0x0000000a,
0x02b, 0x0000060a,
0x02b, 0x0005b333,
0x02c, 0x0000000d,
0x02a, 0x0000000b,
0x02b, 0x0000060a,
0x02b, 0x00063333,
0x02c, 0x0000000d,
0x02a, 0x0000000c,
0x02b, 0x0000060a,
0x02b, 0x0006b333,
0x02c, 0x0000000d,
0x02a, 0x0000000d,
0x02b, 0x0000060a,
0x02b, 0x00073333,
0x02c, 0x0000000d,
0x02a, 0x0000000e,
0x02b, 0x0000050b,
0x02b, 0x00066666,
0x02c, 0x0000001a,
0x02a, 0x000e0000,
0x010, 0x0004000f,
0x011, 0x000e31fc,
0x010, 0x0006000f,
0x011, 0x000ff9f8,
0x010, 0x0002000f,
0x011, 0x000203f9,
0x010, 0x0003000f,
0x011, 0x000ff500,
0x010, 0x00000000,
0x011, 0x00000000,
0x010, 0x0008000f,
0x011, 0x0003f100,
0x010, 0x0009000f,
0x011, 0x00023100,
0x012, 0x00032000,
0x012, 0x00071000,
0x012, 0x000b0000,
0x012, 0x000fc000,
0x013, 0x000287af,
0x013, 0x000244b7,
0x013, 0x000204ab,
0x013, 0x0001c49f,
0x013, 0x00018493,
0x013, 0x00014297,
0x013, 0x00010295,
0x013, 0x0000c298,
0x013, 0x0000819c,
0x013, 0x000040a8,
0x013, 0x0000001c,
0x014, 0x0001944c,
0x014, 0x00059444,
0x014, 0x0009944c,
0x014, 0x000d9444,
0x015, 0x0000f424,
0x015, 0x0004f424,
0x015, 0x0008f424,
0x015, 0x000cf424,
0x016, 0x000e0330,
0x016, 0x000a0330,
0x016, 0x00060330,
0x016, 0x00020330,
0x000, 0x00010159,
0x018, 0x0000f401,
0x0fe, 0x00000000,
0x0fe, 0x00000000,
0x01f, 0x00080003,
0x0fe, 0x00000000,
0x0fe, 0x00000000,
0x01e, 0x00044457,
0x01f, 0x00080000,
0x000, 0x00030159,
};
u32 RTL8192CE_RADIOB_1TARRAY[RADIOB_1TARRAYLENGTH] = {
0x0,
};
u32 RTL8192CEMAC_2T_ARRAY[MAC_2T_ARRAYLENGTH] = {
0x420, 0x00000080,
0x423, 0x00000000,
0x430, 0x00000000,
0x431, 0x00000000,
0x432, 0x00000000,
0x433, 0x00000001,
0x434, 0x00000004,
0x435, 0x00000005,
0x436, 0x00000006,
0x437, 0x00000007,
0x438, 0x00000000,
0x439, 0x00000000,
0x43a, 0x00000000,
0x43b, 0x00000001,
0x43c, 0x00000004,
0x43d, 0x00000005,
0x43e, 0x00000006,
0x43f, 0x00000007,
0x440, 0x0000005d,
0x441, 0x00000001,
0x442, 0x00000000,
0x444, 0x00000015,
0x445, 0x000000f0,
0x446, 0x0000000f,
0x447, 0x00000000,
0x458, 0x00000041,
0x459, 0x000000a8,
0x45a, 0x00000072,
0x45b, 0x000000b9,
0x460, 0x00000088,
0x461, 0x00000088,
0x462, 0x00000006,
0x463, 0x00000003,
0x4c8, 0x00000004,
0x4c9, 0x00000008,
0x4cc, 0x00000002,
0x4cd, 0x00000028,
0x4ce, 0x00000001,
0x500, 0x00000026,
0x501, 0x000000a2,
0x502, 0x0000002f,
0x503, 0x00000000,
0x504, 0x00000028,
0x505, 0x000000a3,
0x506, 0x0000005e,
0x507, 0x00000000,
0x508, 0x0000002b,
0x509, 0x000000a4,
0x50a, 0x0000005e,
0x50b, 0x00000000,
0x50c, 0x0000004f,
0x50d, 0x000000a4,
0x50e, 0x00000000,
0x50f, 0x00000000,
0x512, 0x0000001c,
0x514, 0x0000000a,
0x515, 0x00000010,
0x516, 0x0000000a,
0x517, 0x00000010,
0x51a, 0x00000016,
0x524, 0x0000000f,
0x525, 0x0000004f,
0x546, 0x00000020,
0x547, 0x00000000,
0x559, 0x00000002,
0x55a, 0x00000002,
0x55d, 0x000000ff,
0x605, 0x00000030,
0x608, 0x0000000e,
0x609, 0x0000002a,
0x652, 0x00000020,
0x63c, 0x0000000a,
0x63d, 0x0000000a,
0x700, 0x00000021,
0x701, 0x00000043,
0x702, 0x00000065,
0x703, 0x00000087,
0x708, 0x00000021,
0x709, 0x00000043,
0x70a, 0x00000065,
0x70b, 0x00000087,
};
u32 RTL8192CEAGCTAB_2TARRAY[AGCTAB_2TARRAYLENGTH] = {
0xc78, 0x7b000001,
0xc78, 0x7b010001,
0xc78, 0x7b020001,
0xc78, 0x7b030001,
0xc78, 0x7b040001,
0xc78, 0x7b050001,
0xc78, 0x7a060001,
0xc78, 0x79070001,
0xc78, 0x78080001,
0xc78, 0x77090001,
0xc78, 0x760a0001,
0xc78, 0x750b0001,
0xc78, 0x740c0001,
0xc78, 0x730d0001,
0xc78, 0x720e0001,
0xc78, 0x710f0001,
0xc78, 0x70100001,
0xc78, 0x6f110001,
0xc78, 0x6e120001,
0xc78, 0x6d130001,
0xc78, 0x6c140001,
0xc78, 0x6b150001,
0xc78, 0x6a160001,
0xc78, 0x69170001,
0xc78, 0x68180001,
0xc78, 0x67190001,
0xc78, 0x661a0001,
0xc78, 0x651b0001,
0xc78, 0x641c0001,
0xc78, 0x631d0001,
0xc78, 0x621e0001,
0xc78, 0x611f0001,
0xc78, 0x60200001,
0xc78, 0x49210001,
0xc78, 0x48220001,
0xc78, 0x47230001,
0xc78, 0x46240001,
0xc78, 0x45250001,
0xc78, 0x44260001,
0xc78, 0x43270001,
0xc78, 0x42280001,
0xc78, 0x41290001,
0xc78, 0x402a0001,
0xc78, 0x262b0001,
0xc78, 0x252c0001,
0xc78, 0x242d0001,
0xc78, 0x232e0001,
0xc78, 0x222f0001,
0xc78, 0x21300001,
0xc78, 0x20310001,
0xc78, 0x06320001,
0xc78, 0x05330001,
0xc78, 0x04340001,
0xc78, 0x03350001,
0xc78, 0x02360001,
0xc78, 0x01370001,
0xc78, 0x00380001,
0xc78, 0x00390001,
0xc78, 0x003a0001,
0xc78, 0x003b0001,
0xc78, 0x003c0001,
0xc78, 0x003d0001,
0xc78, 0x003e0001,
0xc78, 0x003f0001,
0xc78, 0x7b400001,
0xc78, 0x7b410001,
0xc78, 0x7b420001,
0xc78, 0x7b430001,
0xc78, 0x7b440001,
0xc78, 0x7b450001,
0xc78, 0x7a460001,
0xc78, 0x79470001,
0xc78, 0x78480001,
0xc78, 0x77490001,
0xc78, 0x764a0001,
0xc78, 0x754b0001,
0xc78, 0x744c0001,
0xc78, 0x734d0001,
0xc78, 0x724e0001,
0xc78, 0x714f0001,
0xc78, 0x70500001,
0xc78, 0x6f510001,
0xc78, 0x6e520001,
0xc78, 0x6d530001,
0xc78, 0x6c540001,
0xc78, 0x6b550001,
0xc78, 0x6a560001,
0xc78, 0x69570001,
0xc78, 0x68580001,
0xc78, 0x67590001,
0xc78, 0x665a0001,
0xc78, 0x655b0001,
0xc78, 0x645c0001,
0xc78, 0x635d0001,
0xc78, 0x625e0001,
0xc78, 0x615f0001,
0xc78, 0x60600001,
0xc78, 0x49610001,
0xc78, 0x48620001,
0xc78, 0x47630001,
0xc78, 0x46640001,
0xc78, 0x45650001,
0xc78, 0x44660001,
0xc78, 0x43670001,
0xc78, 0x42680001,
0xc78, 0x41690001,
0xc78, 0x406a0001,
0xc78, 0x266b0001,
0xc78, 0x256c0001,
0xc78, 0x246d0001,
0xc78, 0x236e0001,
0xc78, 0x226f0001,
0xc78, 0x21700001,
0xc78, 0x20710001,
0xc78, 0x06720001,
0xc78, 0x05730001,
0xc78, 0x04740001,
0xc78, 0x03750001,
0xc78, 0x02760001,
0xc78, 0x01770001,
0xc78, 0x00780001,
0xc78, 0x00790001,
0xc78, 0x007a0001,
0xc78, 0x007b0001,
0xc78, 0x007c0001,
0xc78, 0x007d0001,
0xc78, 0x007e0001,
0xc78, 0x007f0001,
0xc78, 0x3800001e,
0xc78, 0x3801001e,
0xc78, 0x3802001e,
0xc78, 0x3803001e,
0xc78, 0x3804001e,
0xc78, 0x3805001e,
0xc78, 0x3806001e,
0xc78, 0x3807001e,
0xc78, 0x3808001e,
0xc78, 0x3c09001e,
0xc78, 0x3e0a001e,
0xc78, 0x400b001e,
0xc78, 0x440c001e,
0xc78, 0x480d001e,
0xc78, 0x4c0e001e,
0xc78, 0x500f001e,
0xc78, 0x5210001e,
0xc78, 0x5611001e,
0xc78, 0x5a12001e,
0xc78, 0x5e13001e,
0xc78, 0x6014001e,
0xc78, 0x6015001e,
0xc78, 0x6016001e,
0xc78, 0x6217001e,
0xc78, 0x6218001e,
0xc78, 0x6219001e,
0xc78, 0x621a001e,
0xc78, 0x621b001e,
0xc78, 0x621c001e,
0xc78, 0x621d001e,
0xc78, 0x621e001e,
0xc78, 0x621f001e,
};
u32 RTL8192CEAGCTAB_1TARRAY[AGCTAB_1TARRAYLENGTH] = {
0xc78, 0x7b000001,
0xc78, 0x7b010001,
0xc78, 0x7b020001,
0xc78, 0x7b030001,
0xc78, 0x7b040001,
0xc78, 0x7b050001,
0xc78, 0x7a060001,
0xc78, 0x79070001,
0xc78, 0x78080001,
0xc78, 0x77090001,
0xc78, 0x760a0001,
0xc78, 0x750b0001,
0xc78, 0x740c0001,
0xc78, 0x730d0001,
0xc78, 0x720e0001,
0xc78, 0x710f0001,
0xc78, 0x70100001,
0xc78, 0x6f110001,
0xc78, 0x6e120001,
0xc78, 0x6d130001,
0xc78, 0x6c140001,
0xc78, 0x6b150001,
0xc78, 0x6a160001,
0xc78, 0x69170001,
0xc78, 0x68180001,
0xc78, 0x67190001,
0xc78, 0x661a0001,
0xc78, 0x651b0001,
0xc78, 0x641c0001,
0xc78, 0x631d0001,
0xc78, 0x621e0001,
0xc78, 0x611f0001,
0xc78, 0x60200001,
0xc78, 0x49210001,
0xc78, 0x48220001,
0xc78, 0x47230001,
0xc78, 0x46240001,
0xc78, 0x45250001,
0xc78, 0x44260001,
0xc78, 0x43270001,
0xc78, 0x42280001,
0xc78, 0x41290001,
0xc78, 0x402a0001,
0xc78, 0x262b0001,
0xc78, 0x252c0001,
0xc78, 0x242d0001,
0xc78, 0x232e0001,
0xc78, 0x222f0001,
0xc78, 0x21300001,
0xc78, 0x20310001,
0xc78, 0x06320001,
0xc78, 0x05330001,
0xc78, 0x04340001,
0xc78, 0x03350001,
0xc78, 0x02360001,
0xc78, 0x01370001,
0xc78, 0x00380001,
0xc78, 0x00390001,
0xc78, 0x003a0001,
0xc78, 0x003b0001,
0xc78, 0x003c0001,
0xc78, 0x003d0001,
0xc78, 0x003e0001,
0xc78, 0x003f0001,
0xc78, 0x7b400001,
0xc78, 0x7b410001,
0xc78, 0x7b420001,
0xc78, 0x7b430001,
0xc78, 0x7b440001,
0xc78, 0x7b450001,
0xc78, 0x7a460001,
0xc78, 0x79470001,
0xc78, 0x78480001,
0xc78, 0x77490001,
0xc78, 0x764a0001,
0xc78, 0x754b0001,
0xc78, 0x744c0001,
0xc78, 0x734d0001,
0xc78, 0x724e0001,
0xc78, 0x714f0001,
0xc78, 0x70500001,
0xc78, 0x6f510001,
0xc78, 0x6e520001,
0xc78, 0x6d530001,
0xc78, 0x6c540001,
0xc78, 0x6b550001,
0xc78, 0x6a560001,
0xc78, 0x69570001,
0xc78, 0x68580001,
0xc78, 0x67590001,
0xc78, 0x665a0001,
0xc78, 0x655b0001,
0xc78, 0x645c0001,
0xc78, 0x635d0001,
0xc78, 0x625e0001,
0xc78, 0x615f0001,
0xc78, 0x60600001,
0xc78, 0x49610001,
0xc78, 0x48620001,
0xc78, 0x47630001,
0xc78, 0x46640001,
0xc78, 0x45650001,
0xc78, 0x44660001,
0xc78, 0x43670001,
0xc78, 0x42680001,
0xc78, 0x41690001,
0xc78, 0x406a0001,
0xc78, 0x266b0001,
0xc78, 0x256c0001,
0xc78, 0x246d0001,
0xc78, 0x236e0001,
0xc78, 0x226f0001,
0xc78, 0x21700001,
0xc78, 0x20710001,
0xc78, 0x06720001,
0xc78, 0x05730001,
0xc78, 0x04740001,
0xc78, 0x03750001,
0xc78, 0x02760001,
0xc78, 0x01770001,
0xc78, 0x00780001,
0xc78, 0x00790001,
0xc78, 0x007a0001,
0xc78, 0x007b0001,
0xc78, 0x007c0001,
0xc78, 0x007d0001,
0xc78, 0x007e0001,
0xc78, 0x007f0001,
0xc78, 0x3800001e,
0xc78, 0x3801001e,
0xc78, 0x3802001e,
0xc78, 0x3803001e,
0xc78, 0x3804001e,
0xc78, 0x3805001e,
0xc78, 0x3806001e,
0xc78, 0x3807001e,
0xc78, 0x3808001e,
0xc78, 0x3c09001e,
0xc78, 0x3e0a001e,
0xc78, 0x400b001e,
0xc78, 0x440c001e,
0xc78, 0x480d001e,
0xc78, 0x4c0e001e,
0xc78, 0x500f001e,
0xc78, 0x5210001e,
0xc78, 0x5611001e,
0xc78, 0x5a12001e,
0xc78, 0x5e13001e,
0xc78, 0x6014001e,
0xc78, 0x6015001e,
0xc78, 0x6016001e,
0xc78, 0x6217001e,
0xc78, 0x6218001e,
0xc78, 0x6219001e,
0xc78, 0x621a001e,
0xc78, 0x621b001e,
0xc78, 0x621c001e,
0xc78, 0x621d001e,
0xc78, 0x621e001e,
0xc78, 0x621f001e,
};
| gpl-2.0 |
Octo-Kat/platform_kernel_asus_flo | drivers/net/wimax/i2400m/tx.c | 9864 | 38202 | /*
* Intel Wireless WiMAX Connection 2400m
* Generic (non-bus specific) TX handling
*
*
* Copyright (C) 2007-2008 Intel Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE 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.
*
*
* Intel Corporation <linux-wimax@intel.com>
* Yanir Lubetkin <yanirx.lubetkin@intel.com>
* - Initial implementation
*
* Intel Corporation <linux-wimax@intel.com>
* Inaky Perez-Gonzalez <inaky.perez-gonzalez@intel.com>
* - Rewritten to use a single FIFO to lower the memory allocation
* pressure and optimize cache hits when copying to the queue, as
* well as splitting out bus-specific code.
*
*
* Implements data transmission to the device; this is done through a
* software FIFO, as data/control frames can be coalesced (while the
* device is reading the previous tx transaction, others accumulate).
*
* A FIFO is used because at the end it is resource-cheaper that trying
* to implement scatter/gather over USB. As well, most traffic is going
* to be download (vs upload).
*
* The format for sending/receiving data to/from the i2400m is
* described in detail in rx.c:PROTOCOL FORMAT. In here we implement
* the transmission of that. This is split between a bus-independent
* part that just prepares everything and a bus-specific part that
* does the actual transmission over the bus to the device (in the
* bus-specific driver).
*
*
* The general format of a device-host transaction is MSG-HDR, PLD1,
* PLD2...PLDN, PL1, PL2,...PLN, PADDING.
*
* Because we need the send payload descriptors and then payloads and
* because it is kind of expensive to do scatterlists in USB (one URB
* per node), it becomes cheaper to append all the data to a FIFO
* (copying to a FIFO potentially in cache is cheaper).
*
* Then the bus-specific code takes the parts of that FIFO that are
* written and passes them to the device.
*
* So the concepts to keep in mind there are:
*
* We use a FIFO to queue the data in a linear buffer. We first append
* a MSG-HDR, space for I2400M_TX_PLD_MAX payload descriptors and then
* go appending payloads until we run out of space or of payload
* descriptors. Then we append padding to make the whole transaction a
* multiple of i2400m->bus_tx_block_size (as defined by the bus layer).
*
* - A TX message: a combination of a message header, payload
* descriptors and payloads.
*
* Open: it is marked as active (i2400m->tx_msg is valid) and we
* can keep adding payloads to it.
*
* Closed: we are not appending more payloads to this TX message
* (exahusted space in the queue, too many payloads or
* whichever). We have appended padding so the whole message
* length is aligned to i2400m->bus_tx_block_size (as set by the
* bus/transport layer).
*
* - Most of the time we keep a TX message open to which we append
* payloads.
*
* - If we are going to append and there is no more space (we are at
* the end of the FIFO), we close the message, mark the rest of the
* FIFO space unusable (skip_tail), create a new message at the
* beginning of the FIFO (if there is space) and append the message
* there.
*
* This is because we need to give linear TX messages to the bus
* engine. So we don't write a message to the remaining FIFO space
* until the tail and continue at the head of it.
*
* - We overload one of the fields in the message header to use it as
* 'size' of the TX message, so we can iterate over them. It also
* contains a flag that indicates if we have to skip it or not.
* When we send the buffer, we update that to its real on-the-wire
* value.
*
* - The MSG-HDR PLD1...PLD2 stuff has to be a size multiple of 16.
*
* It follows that if MSG-HDR says we have N messages, the whole
* header + descriptors is 16 + 4*N; for those to be a multiple of
* 16, it follows that N can be 4, 8, 12, ... (32, 48, 64, 80...
* bytes).
*
* So if we have only 1 payload, we have to submit a header that in
* all truth has space for 4.
*
* The implication is that we reserve space for 12 (64 bytes); but
* if we fill up only (eg) 2, our header becomes 32 bytes only. So
* the TX engine has to shift those 32 bytes of msg header and 2
* payloads and padding so that right after it the payloads start
* and the TX engine has to know about that.
*
* It is cheaper to move the header up than the whole payloads down.
*
* We do this in i2400m_tx_close(). See 'i2400m_msg_hdr->offset'.
*
* - Each payload has to be size-padded to 16 bytes; before appending
* it, we just do it.
*
* - The whole message has to be padded to i2400m->bus_tx_block_size;
* we do this at close time. Thus, when reserving space for the
* payload, we always make sure there is also free space for this
* padding that sooner or later will happen.
*
* When we append a message, we tell the bus specific code to kick in
* TXs. It will TX (in parallel) until the buffer is exhausted--hence
* the lockin we do. The TX code will only send a TX message at the
* time (which remember, might contain more than one payload). Of
* course, when the bus-specific driver attempts to TX a message that
* is still open, it gets closed first.
*
* Gee, this is messy; well a picture. In the example below we have a
* partially full FIFO, with a closed message ready to be delivered
* (with a moved message header to make sure it is size-aligned to
* 16), TAIL room that was unusable (and thus is marked with a message
* header that says 'skip this') and at the head of the buffer, an
* incomplete message with a couple of payloads.
*
* N ___________________________________________________
* | |
* | TAIL room |
* | |
* | msg_hdr to skip (size |= 0x80000) |
* |---------------------------------------------------|-------
* | | /|\
* | | |
* | TX message padding | |
* | | |
* | | |
* |- - - - - - - - - - - - - - - - - - - - - - - - - -| |
* | | |
* | payload 1 | |
* | | N * tx_block_size
* | | |
* |- - - - - - - - - - - - - - - - - - - - - - - - - -| |
* | | |
* | payload 1 | |
* | | |
* | | |
* |- - - - - - - - - - - - - - - - - - - - - - - - - -|- -|- - - -
* | padding 3 /|\ | | /|\
* | padding 2 | | | |
* | pld 1 32 bytes (2 * 16) | | |
* | pld 0 | | | |
* | moved msg_hdr \|/ | \|/ |
* |- - - - - - - - - - - - - - - - - - - - - - - - - -|- - - |
* | | _PLD_SIZE
* | unused | |
* | | |
* |- - - - - - - - - - - - - - - - - - - - - - - - - -| |
* | msg_hdr (size X) [this message is closed] | \|/
* |===================================================|========== <=== OUT
* | |
* | |
* | |
* | Free rooom |
* | |
* | |
* | |
* | |
* | |
* | |
* | |
* | |
* | |
* |===================================================|========== <=== IN
* | |
* | |
* | |
* | |
* | payload 1 |
* | |
* | |
* |- - - - - - - - - - - - - - - - - - - - - - - - - -|
* | |
* | payload 0 |
* | |
* | |
* |- - - - - - - - - - - - - - - - - - - - - - - - - -|
* | pld 11 /|\ |
* | ... | |
* | pld 1 64 bytes (2 * 16) |
* | pld 0 | |
* | msg_hdr (size X) \|/ [message is open] |
* 0 ---------------------------------------------------
*
*
* ROADMAP
*
* i2400m_tx_setup() Called by i2400m_setup
* i2400m_tx_release() Called by i2400m_release()
*
* i2400m_tx() Called to send data or control frames
* i2400m_tx_fifo_push() Allocates append-space in the FIFO
* i2400m_tx_new() Opens a new message in the FIFO
* i2400m_tx_fits() Checks if a new payload fits in the message
* i2400m_tx_close() Closes an open message in the FIFO
* i2400m_tx_skip_tail() Marks unusable FIFO tail space
* i2400m->bus_tx_kick()
*
* Now i2400m->bus_tx_kick() is the the bus-specific driver backend
* implementation; that would do:
*
* i2400m->bus_tx_kick()
* i2400m_tx_msg_get() Gets first message ready to go
* ...sends it...
* i2400m_tx_msg_sent() Ack the message is sent; repeat from
* _tx_msg_get() until it returns NULL
* (FIFO empty).
*/
#include <linux/netdevice.h>
#include <linux/slab.h>
#include <linux/export.h>
#include "i2400m.h"
#define D_SUBMODULE tx
#include "debug-levels.h"
enum {
/**
* TX Buffer size
*
* Doc says maximum transaction is 16KiB. If we had 16KiB en
* route and 16KiB being queued, it boils down to needing
* 32KiB.
* 32KiB is insufficient for 1400 MTU, hence increasing
* tx buffer size to 64KiB.
*/
I2400M_TX_BUF_SIZE = 65536,
/**
* Message header and payload descriptors have to be 16
* aligned (16 + 4 * N = 16 * M). If we take that average sent
* packets are MTU size (~1400-~1500) it follows that we could
* fit at most 10-11 payloads in one transaction. To meet the
* alignment requirement, that means we need to leave space
* for 12 (64 bytes). To simplify, we leave space for that. If
* at the end there are less, we pad up to the nearest
* multiple of 16.
*/
/*
* According to Intel Wimax i3200, i5x50 and i6x50 specification
* documents, the maximum number of payloads per message can be
* up to 60. Increasing the number of payloads to 60 per message
* helps to accommodate smaller payloads in a single transaction.
*/
I2400M_TX_PLD_MAX = 60,
I2400M_TX_PLD_SIZE = sizeof(struct i2400m_msg_hdr)
+ I2400M_TX_PLD_MAX * sizeof(struct i2400m_pld),
I2400M_TX_SKIP = 0x80000000,
/*
* According to Intel Wimax i3200, i5x50 and i6x50 specification
* documents, the maximum size of each message can be up to 16KiB.
*/
I2400M_TX_MSG_SIZE = 16384,
};
#define TAIL_FULL ((void *)~(unsigned long)NULL)
/*
* Calculate how much tail room is available
*
* Note the trick here. This path is ONLY caleed for Case A (see
* i2400m_tx_fifo_push() below), where we have:
*
* Case A
* N ___________
* | tail room |
* | |
* |<- IN ->|
* | |
* | data |
* | |
* |<- OUT ->|
* | |
* | head room |
* 0 -----------
*
* When calculating the tail_room, tx_in might get to be zero if
* i2400m->tx_in is right at the end of the buffer (really full
* buffer) if there is no head room. In this case, tail_room would be
* I2400M_TX_BUF_SIZE, although it is actually zero. Hence the final
* mod (%) operation. However, when doing this kind of optimization,
* i2400m->tx_in being zero would fail, so we treat is an a special
* case.
*/
static inline
size_t __i2400m_tx_tail_room(struct i2400m *i2400m)
{
size_t tail_room;
size_t tx_in;
if (unlikely(i2400m->tx_in == 0))
return I2400M_TX_BUF_SIZE;
tx_in = i2400m->tx_in % I2400M_TX_BUF_SIZE;
tail_room = I2400M_TX_BUF_SIZE - tx_in;
tail_room %= I2400M_TX_BUF_SIZE;
return tail_room;
}
/*
* Allocate @size bytes in the TX fifo, return a pointer to it
*
* @i2400m: device descriptor
* @size: size of the buffer we need to allocate
* @padding: ensure that there is at least this many bytes of free
* contiguous space in the fifo. This is needed because later on
* we might need to add padding.
* @try_head: specify either to allocate head room or tail room space
* in the TX FIFO. This boolean is required to avoids a system hang
* due to an infinite loop caused by i2400m_tx_fifo_push().
* The caller must always try to allocate tail room space first by
* calling this routine with try_head = 0. In case if there
* is not enough tail room space but there is enough head room space,
* (i2400m_tx_fifo_push() returns TAIL_FULL) try to allocate head
* room space, by calling this routine again with try_head = 1.
*
* Returns:
*
* Pointer to the allocated space. NULL if there is no
* space. TAIL_FULL if there is no space at the tail but there is at
* the head (Case B below).
*
* These are the two basic cases we need to keep an eye for -- it is
* much better explained in linux/kernel/kfifo.c, but this code
* basically does the same. No rocket science here.
*
* Case A Case B
* N ___________ ___________
* | tail room | | data |
* | | | |
* |<- IN ->| |<- OUT ->|
* | | | |
* | data | | room |
* | | | |
* |<- OUT ->| |<- IN ->|
* | | | |
* | head room | | data |
* 0 ----------- -----------
*
* We allocate only *contiguous* space.
*
* We can allocate only from 'room'. In Case B, it is simple; in case
* A, we only try from the tail room; if it is not enough, we just
* fail and return TAIL_FULL and let the caller figure out if we wants to
* skip the tail room and try to allocate from the head.
*
* There is a corner case, wherein i2400m_tx_new() can get into
* an infinite loop calling i2400m_tx_fifo_push().
* In certain situations, tx_in would have reached on the top of TX FIFO
* and i2400m_tx_tail_room() returns 0, as described below:
*
* N ___________ tail room is zero
* |<- IN ->|
* | |
* | |
* | |
* | data |
* |<- OUT ->|
* | |
* | |
* | head room |
* 0 -----------
* During such a time, where tail room is zero in the TX FIFO and if there
* is a request to add a payload to TX FIFO, which calls:
* i2400m_tx()
* ->calls i2400m_tx_close()
* ->calls i2400m_tx_skip_tail()
* goto try_new;
* ->calls i2400m_tx_new()
* |----> [try_head:]
* infinite loop | ->calls i2400m_tx_fifo_push()
* | if (tail_room < needed)
* | if (head_room => needed)
* | return TAIL_FULL;
* |<---- goto try_head;
*
* i2400m_tx() calls i2400m_tx_close() to close the message, since there
* is no tail room to accommodate the payload and calls
* i2400m_tx_skip_tail() to skip the tail space. Now i2400m_tx() calls
* i2400m_tx_new() to allocate space for new message header calling
* i2400m_tx_fifo_push() that returns TAIL_FULL, since there is no tail space
* to accommodate the message header, but there is enough head space.
* The i2400m_tx_new() keeps re-retrying by calling i2400m_tx_fifo_push()
* ending up in a loop causing system freeze.
*
* This corner case is avoided by using a try_head boolean,
* as an argument to i2400m_tx_fifo_push().
*
* Note:
*
* Assumes i2400m->tx_lock is taken, and we use that as a barrier
*
* The indexes keep increasing and we reset them to zero when we
* pop data off the queue
*/
static
void *i2400m_tx_fifo_push(struct i2400m *i2400m, size_t size,
size_t padding, bool try_head)
{
struct device *dev = i2400m_dev(i2400m);
size_t room, tail_room, needed_size;
void *ptr;
needed_size = size + padding;
room = I2400M_TX_BUF_SIZE - (i2400m->tx_in - i2400m->tx_out);
if (room < needed_size) { /* this takes care of Case B */
d_printf(2, dev, "fifo push %zu/%zu: no space\n",
size, padding);
return NULL;
}
/* Is there space at the tail? */
tail_room = __i2400m_tx_tail_room(i2400m);
if (!try_head && tail_room < needed_size) {
/*
* If the tail room space is not enough to push the message
* in the TX FIFO, then there are two possibilities:
* 1. There is enough head room space to accommodate
* this message in the TX FIFO.
* 2. There is not enough space in the head room and
* in tail room of the TX FIFO to accommodate the message.
* In the case (1), return TAIL_FULL so that the caller
* can figure out, if the caller wants to push the message
* into the head room space.
* In the case (2), return NULL, indicating that the TX FIFO
* cannot accommodate the message.
*/
if (room - tail_room >= needed_size) {
d_printf(2, dev, "fifo push %zu/%zu: tail full\n",
size, padding);
return TAIL_FULL; /* There might be head space */
} else {
d_printf(2, dev, "fifo push %zu/%zu: no head space\n",
size, padding);
return NULL; /* There is no space */
}
}
ptr = i2400m->tx_buf + i2400m->tx_in % I2400M_TX_BUF_SIZE;
d_printf(2, dev, "fifo push %zu/%zu: at @%zu\n", size, padding,
i2400m->tx_in % I2400M_TX_BUF_SIZE);
i2400m->tx_in += size;
return ptr;
}
/*
* Mark the tail of the FIFO buffer as 'to-skip'
*
* We should never hit the BUG_ON() because all the sizes we push to
* the FIFO are padded to be a multiple of 16 -- the size of *msg
* (I2400M_PL_PAD for the payloads, I2400M_TX_PLD_SIZE for the
* header).
*
* Tail room can get to be zero if a message was opened when there was
* space only for a header. _tx_close() will mark it as to-skip (as it
* will have no payloads) and there will be no more space to flush, so
* nothing has to be done here. This is probably cheaper than ensuring
* in _tx_new() that there is some space for payloads...as we could
* always possibly hit the same problem if the payload wouldn't fit.
*
* Note:
*
* Assumes i2400m->tx_lock is taken, and we use that as a barrier
*
* This path is only taken for Case A FIFO situations [see
* i2400m_tx_fifo_push()]
*/
static
void i2400m_tx_skip_tail(struct i2400m *i2400m)
{
struct device *dev = i2400m_dev(i2400m);
size_t tx_in = i2400m->tx_in % I2400M_TX_BUF_SIZE;
size_t tail_room = __i2400m_tx_tail_room(i2400m);
struct i2400m_msg_hdr *msg = i2400m->tx_buf + tx_in;
if (unlikely(tail_room == 0))
return;
BUG_ON(tail_room < sizeof(*msg));
msg->size = tail_room | I2400M_TX_SKIP;
d_printf(2, dev, "skip tail: skipping %zu bytes @%zu\n",
tail_room, tx_in);
i2400m->tx_in += tail_room;
}
/*
* Check if a skb will fit in the TX queue's current active TX
* message (if there are still descriptors left unused).
*
* Returns:
* 0 if the message won't fit, 1 if it will.
*
* Note:
*
* Assumes a TX message is active (i2400m->tx_msg).
*
* Assumes i2400m->tx_lock is taken, and we use that as a barrier
*/
static
unsigned i2400m_tx_fits(struct i2400m *i2400m)
{
struct i2400m_msg_hdr *msg_hdr = i2400m->tx_msg;
return le16_to_cpu(msg_hdr->num_pls) < I2400M_TX_PLD_MAX;
}
/*
* Start a new TX message header in the queue.
*
* Reserve memory from the base FIFO engine and then just initialize
* the message header.
*
* We allocate the biggest TX message header we might need (one that'd
* fit I2400M_TX_PLD_MAX payloads) -- when it is closed it will be
* 'ironed it out' and the unneeded parts removed.
*
* NOTE:
*
* Assumes that the previous message is CLOSED (eg: either
* there was none or 'i2400m_tx_close()' was called on it).
*
* Assumes i2400m->tx_lock is taken, and we use that as a barrier
*/
static
void i2400m_tx_new(struct i2400m *i2400m)
{
struct device *dev = i2400m_dev(i2400m);
struct i2400m_msg_hdr *tx_msg;
bool try_head = false;
BUG_ON(i2400m->tx_msg != NULL);
/*
* In certain situations, TX queue might have enough space to
* accommodate the new message header I2400M_TX_PLD_SIZE, but
* might not have enough space to accommodate the payloads.
* Adding bus_tx_room_min padding while allocating a new TX message
* increases the possibilities of including at least one payload of the
* size <= bus_tx_room_min.
*/
try_head:
tx_msg = i2400m_tx_fifo_push(i2400m, I2400M_TX_PLD_SIZE,
i2400m->bus_tx_room_min, try_head);
if (tx_msg == NULL)
goto out;
else if (tx_msg == TAIL_FULL) {
i2400m_tx_skip_tail(i2400m);
d_printf(2, dev, "new TX message: tail full, trying head\n");
try_head = true;
goto try_head;
}
memset(tx_msg, 0, I2400M_TX_PLD_SIZE);
tx_msg->size = I2400M_TX_PLD_SIZE;
out:
i2400m->tx_msg = tx_msg;
d_printf(2, dev, "new TX message: %p @%zu\n",
tx_msg, (void *) tx_msg - i2400m->tx_buf);
}
/*
* Finalize the current TX message header
*
* Sets the message header to be at the proper location depending on
* how many descriptors we have (check documentation at the file's
* header for more info on that).
*
* Appends padding bytes to make sure the whole TX message (counting
* from the 'relocated' message header) is aligned to
* tx_block_size. We assume the _append() code has left enough space
* in the FIFO for that. If there are no payloads, just pass, as it
* won't be transferred.
*
* The amount of padding bytes depends on how many payloads are in the
* TX message, as the "msg header and payload descriptors" will be
* shifted up in the buffer.
*/
static
void i2400m_tx_close(struct i2400m *i2400m)
{
struct device *dev = i2400m_dev(i2400m);
struct i2400m_msg_hdr *tx_msg = i2400m->tx_msg;
struct i2400m_msg_hdr *tx_msg_moved;
size_t aligned_size, padding, hdr_size;
void *pad_buf;
unsigned num_pls;
if (tx_msg->size & I2400M_TX_SKIP) /* a skipper? nothing to do */
goto out;
num_pls = le16_to_cpu(tx_msg->num_pls);
/* We can get this situation when a new message was started
* and there was no space to add payloads before hitting the
tail (and taking padding into consideration). */
if (num_pls == 0) {
tx_msg->size |= I2400M_TX_SKIP;
goto out;
}
/* Relocate the message header
*
* Find the current header size, align it to 16 and if we need
* to move it so the tail is next to the payloads, move it and
* set the offset.
*
* If it moved, this header is good only for transmission; the
* original one (it is kept if we moved) is still used to
* figure out where the next TX message starts (and where the
* offset to the moved header is).
*/
hdr_size = sizeof(*tx_msg)
+ le16_to_cpu(tx_msg->num_pls) * sizeof(tx_msg->pld[0]);
hdr_size = ALIGN(hdr_size, I2400M_PL_ALIGN);
tx_msg->offset = I2400M_TX_PLD_SIZE - hdr_size;
tx_msg_moved = (void *) tx_msg + tx_msg->offset;
memmove(tx_msg_moved, tx_msg, hdr_size);
tx_msg_moved->size -= tx_msg->offset;
/*
* Now figure out how much we have to add to the (moved!)
* message so the size is a multiple of i2400m->bus_tx_block_size.
*/
aligned_size = ALIGN(tx_msg_moved->size, i2400m->bus_tx_block_size);
padding = aligned_size - tx_msg_moved->size;
if (padding > 0) {
pad_buf = i2400m_tx_fifo_push(i2400m, padding, 0, 0);
if (unlikely(WARN_ON(pad_buf == NULL
|| pad_buf == TAIL_FULL))) {
/* This should not happen -- append should verify
* there is always space left at least to append
* tx_block_size */
dev_err(dev,
"SW BUG! Possible data leakage from memory the "
"device should not read for padding - "
"size %lu aligned_size %zu tx_buf %p in "
"%zu out %zu\n",
(unsigned long) tx_msg_moved->size,
aligned_size, i2400m->tx_buf, i2400m->tx_in,
i2400m->tx_out);
} else
memset(pad_buf, 0xad, padding);
}
tx_msg_moved->padding = cpu_to_le16(padding);
tx_msg_moved->size += padding;
if (tx_msg != tx_msg_moved)
tx_msg->size += padding;
out:
i2400m->tx_msg = NULL;
}
/**
* i2400m_tx - send the data in a buffer to the device
*
* @buf: pointer to the buffer to transmit
*
* @buf_len: buffer size
*
* @pl_type: type of the payload we are sending.
*
* Returns:
* 0 if ok, < 0 errno code on error (-ENOSPC, if there is no more
* room for the message in the queue).
*
* Appends the buffer to the TX FIFO and notifies the bus-specific
* part of the driver that there is new data ready to transmit.
* Once this function returns, the buffer has been copied, so it can
* be reused.
*
* The steps followed to append are explained in detail in the file
* header.
*
* Whenever we write to a message, we increase msg->size, so it
* reflects exactly how big the message is. This is needed so that if
* we concatenate two messages before they can be sent, the code that
* sends the messages can find the boundaries (and it will replace the
* size with the real barker before sending).
*
* Note:
*
* Cold and warm reset payloads need to be sent as a single
* payload, so we handle that.
*/
int i2400m_tx(struct i2400m *i2400m, const void *buf, size_t buf_len,
enum i2400m_pt pl_type)
{
int result = -ENOSPC;
struct device *dev = i2400m_dev(i2400m);
unsigned long flags;
size_t padded_len;
void *ptr;
bool try_head = false;
unsigned is_singleton = pl_type == I2400M_PT_RESET_WARM
|| pl_type == I2400M_PT_RESET_COLD;
d_fnstart(3, dev, "(i2400m %p skb %p [%zu bytes] pt %u)\n",
i2400m, buf, buf_len, pl_type);
padded_len = ALIGN(buf_len, I2400M_PL_ALIGN);
d_printf(5, dev, "padded_len %zd buf_len %zd\n", padded_len, buf_len);
/* If there is no current TX message, create one; if the
* current one is out of payload slots or we have a singleton,
* close it and start a new one */
spin_lock_irqsave(&i2400m->tx_lock, flags);
/* If tx_buf is NULL, device is shutdown */
if (i2400m->tx_buf == NULL) {
result = -ESHUTDOWN;
goto error_tx_new;
}
try_new:
if (unlikely(i2400m->tx_msg == NULL))
i2400m_tx_new(i2400m);
else if (unlikely(!i2400m_tx_fits(i2400m)
|| (is_singleton && i2400m->tx_msg->num_pls != 0))) {
d_printf(2, dev, "closing TX message (fits %u singleton "
"%u num_pls %u)\n", i2400m_tx_fits(i2400m),
is_singleton, i2400m->tx_msg->num_pls);
i2400m_tx_close(i2400m);
i2400m_tx_new(i2400m);
}
if (i2400m->tx_msg == NULL)
goto error_tx_new;
/*
* Check if this skb will fit in the TX queue's current active
* TX message. The total message size must not exceed the maximum
* size of each message I2400M_TX_MSG_SIZE. If it exceeds,
* close the current message and push this skb into the new message.
*/
if (i2400m->tx_msg->size + padded_len > I2400M_TX_MSG_SIZE) {
d_printf(2, dev, "TX: message too big, going new\n");
i2400m_tx_close(i2400m);
i2400m_tx_new(i2400m);
}
if (i2400m->tx_msg == NULL)
goto error_tx_new;
/* So we have a current message header; now append space for
* the message -- if there is not enough, try the head */
ptr = i2400m_tx_fifo_push(i2400m, padded_len,
i2400m->bus_tx_block_size, try_head);
if (ptr == TAIL_FULL) { /* Tail is full, try head */
d_printf(2, dev, "pl append: tail full\n");
i2400m_tx_close(i2400m);
i2400m_tx_skip_tail(i2400m);
try_head = true;
goto try_new;
} else if (ptr == NULL) { /* All full */
result = -ENOSPC;
d_printf(2, dev, "pl append: all full\n");
} else { /* Got space, copy it, set padding */
struct i2400m_msg_hdr *tx_msg = i2400m->tx_msg;
unsigned num_pls = le16_to_cpu(tx_msg->num_pls);
memcpy(ptr, buf, buf_len);
memset(ptr + buf_len, 0xad, padded_len - buf_len);
i2400m_pld_set(&tx_msg->pld[num_pls], buf_len, pl_type);
d_printf(3, dev, "pld 0x%08x (type 0x%1x len 0x%04zx\n",
le32_to_cpu(tx_msg->pld[num_pls].val),
pl_type, buf_len);
tx_msg->num_pls = le16_to_cpu(num_pls+1);
tx_msg->size += padded_len;
d_printf(2, dev, "TX: appended %zu b (up to %u b) pl #%u\n",
padded_len, tx_msg->size, num_pls+1);
d_printf(2, dev,
"TX: appended hdr @%zu %zu b pl #%u @%zu %zu/%zu b\n",
(void *)tx_msg - i2400m->tx_buf, (size_t)tx_msg->size,
num_pls+1, ptr - i2400m->tx_buf, buf_len, padded_len);
result = 0;
if (is_singleton)
i2400m_tx_close(i2400m);
}
error_tx_new:
spin_unlock_irqrestore(&i2400m->tx_lock, flags);
/* kick in most cases, except when the TX subsys is down, as
* it might free space */
if (likely(result != -ESHUTDOWN))
i2400m->bus_tx_kick(i2400m);
d_fnend(3, dev, "(i2400m %p skb %p [%zu bytes] pt %u) = %d\n",
i2400m, buf, buf_len, pl_type, result);
return result;
}
EXPORT_SYMBOL_GPL(i2400m_tx);
/**
* i2400m_tx_msg_get - Get the first TX message in the FIFO to start sending it
*
* @i2400m: device descriptors
* @bus_size: where to place the size of the TX message
*
* Called by the bus-specific driver to get the first TX message at
* the FIF that is ready for transmission.
*
* It sets the state in @i2400m to indicate the bus-specific driver is
* transferring that message (i2400m->tx_msg_size).
*
* Once the transfer is completed, call i2400m_tx_msg_sent().
*
* Notes:
*
* The size of the TX message to be transmitted might be smaller than
* that of the TX message in the FIFO (in case the header was
* shorter). Hence, we copy it in @bus_size, for the bus layer to
* use. We keep the message's size in i2400m->tx_msg_size so that
* when the bus later is done transferring we know how much to
* advance the fifo.
*
* We collect statistics here as all the data is available and we
* assume it is going to work [see i2400m_tx_msg_sent()].
*/
struct i2400m_msg_hdr *i2400m_tx_msg_get(struct i2400m *i2400m,
size_t *bus_size)
{
struct device *dev = i2400m_dev(i2400m);
struct i2400m_msg_hdr *tx_msg, *tx_msg_moved;
unsigned long flags, pls;
d_fnstart(3, dev, "(i2400m %p bus_size %p)\n", i2400m, bus_size);
spin_lock_irqsave(&i2400m->tx_lock, flags);
tx_msg_moved = NULL;
if (i2400m->tx_buf == NULL)
goto out_unlock;
skip:
tx_msg_moved = NULL;
if (i2400m->tx_in == i2400m->tx_out) { /* Empty FIFO? */
i2400m->tx_in = 0;
i2400m->tx_out = 0;
d_printf(2, dev, "TX: FIFO empty: resetting\n");
goto out_unlock;
}
tx_msg = i2400m->tx_buf + i2400m->tx_out % I2400M_TX_BUF_SIZE;
if (tx_msg->size & I2400M_TX_SKIP) { /* skip? */
d_printf(2, dev, "TX: skip: msg @%zu (%zu b)\n",
i2400m->tx_out % I2400M_TX_BUF_SIZE,
(size_t) tx_msg->size & ~I2400M_TX_SKIP);
i2400m->tx_out += tx_msg->size & ~I2400M_TX_SKIP;
goto skip;
}
if (tx_msg->num_pls == 0) { /* No payloads? */
if (tx_msg == i2400m->tx_msg) { /* open, we are done */
d_printf(2, dev,
"TX: FIFO empty: open msg w/o payloads @%zu\n",
(void *) tx_msg - i2400m->tx_buf);
tx_msg = NULL;
goto out_unlock;
} else { /* closed, skip it */
d_printf(2, dev,
"TX: skip msg w/o payloads @%zu (%zu b)\n",
(void *) tx_msg - i2400m->tx_buf,
(size_t) tx_msg->size);
i2400m->tx_out += tx_msg->size & ~I2400M_TX_SKIP;
goto skip;
}
}
if (tx_msg == i2400m->tx_msg) /* open msg? */
i2400m_tx_close(i2400m);
/* Now we have a valid TX message (with payloads) to TX */
tx_msg_moved = (void *) tx_msg + tx_msg->offset;
i2400m->tx_msg_size = tx_msg->size;
*bus_size = tx_msg_moved->size;
d_printf(2, dev, "TX: pid %d msg hdr at @%zu offset +@%zu "
"size %zu bus_size %zu\n",
current->pid, (void *) tx_msg - i2400m->tx_buf,
(size_t) tx_msg->offset, (size_t) tx_msg->size,
(size_t) tx_msg_moved->size);
tx_msg_moved->barker = le32_to_cpu(I2400M_H2D_PREVIEW_BARKER);
tx_msg_moved->sequence = le32_to_cpu(i2400m->tx_sequence++);
pls = le32_to_cpu(tx_msg_moved->num_pls);
i2400m->tx_pl_num += pls; /* Update stats */
if (pls > i2400m->tx_pl_max)
i2400m->tx_pl_max = pls;
if (pls < i2400m->tx_pl_min)
i2400m->tx_pl_min = pls;
i2400m->tx_num++;
i2400m->tx_size_acc += *bus_size;
if (*bus_size < i2400m->tx_size_min)
i2400m->tx_size_min = *bus_size;
if (*bus_size > i2400m->tx_size_max)
i2400m->tx_size_max = *bus_size;
out_unlock:
spin_unlock_irqrestore(&i2400m->tx_lock, flags);
d_fnstart(3, dev, "(i2400m %p bus_size %p [%zu]) = %p\n",
i2400m, bus_size, *bus_size, tx_msg_moved);
return tx_msg_moved;
}
EXPORT_SYMBOL_GPL(i2400m_tx_msg_get);
/**
* i2400m_tx_msg_sent - indicate the transmission of a TX message
*
* @i2400m: device descriptor
*
* Called by the bus-specific driver when a message has been sent;
* this pops it from the FIFO; and as there is space, start the queue
* in case it was stopped.
*
* Should be called even if the message send failed and we are
* dropping this TX message.
*/
void i2400m_tx_msg_sent(struct i2400m *i2400m)
{
unsigned n;
unsigned long flags;
struct device *dev = i2400m_dev(i2400m);
d_fnstart(3, dev, "(i2400m %p)\n", i2400m);
spin_lock_irqsave(&i2400m->tx_lock, flags);
if (i2400m->tx_buf == NULL)
goto out_unlock;
i2400m->tx_out += i2400m->tx_msg_size;
d_printf(2, dev, "TX: sent %zu b\n", (size_t) i2400m->tx_msg_size);
i2400m->tx_msg_size = 0;
BUG_ON(i2400m->tx_out > i2400m->tx_in);
/* level them FIFO markers off */
n = i2400m->tx_out / I2400M_TX_BUF_SIZE;
i2400m->tx_out %= I2400M_TX_BUF_SIZE;
i2400m->tx_in -= n * I2400M_TX_BUF_SIZE;
out_unlock:
spin_unlock_irqrestore(&i2400m->tx_lock, flags);
d_fnend(3, dev, "(i2400m %p) = void\n", i2400m);
}
EXPORT_SYMBOL_GPL(i2400m_tx_msg_sent);
/**
* i2400m_tx_setup - Initialize the TX queue and infrastructure
*
* Make sure we reset the TX sequence to zero, as when this function
* is called, the firmware has been just restarted. Same rational
* for tx_in, tx_out, tx_msg_size and tx_msg. We reset them since
* the memory for TX queue is reallocated.
*/
int i2400m_tx_setup(struct i2400m *i2400m)
{
int result = 0;
void *tx_buf;
unsigned long flags;
/* Do this here only once -- can't do on
* i2400m_hard_start_xmit() as we'll cause race conditions if
* the WS was scheduled on another CPU */
INIT_WORK(&i2400m->wake_tx_ws, i2400m_wake_tx_work);
tx_buf = kmalloc(I2400M_TX_BUF_SIZE, GFP_ATOMIC);
if (tx_buf == NULL) {
result = -ENOMEM;
goto error_kmalloc;
}
/*
* Fail the build if we can't fit at least two maximum size messages
* on the TX FIFO [one being delivered while one is constructed].
*/
BUILD_BUG_ON(2 * I2400M_TX_MSG_SIZE > I2400M_TX_BUF_SIZE);
spin_lock_irqsave(&i2400m->tx_lock, flags);
i2400m->tx_sequence = 0;
i2400m->tx_in = 0;
i2400m->tx_out = 0;
i2400m->tx_msg_size = 0;
i2400m->tx_msg = NULL;
i2400m->tx_buf = tx_buf;
spin_unlock_irqrestore(&i2400m->tx_lock, flags);
/* Huh? the bus layer has to define this... */
BUG_ON(i2400m->bus_tx_block_size == 0);
error_kmalloc:
return result;
}
/**
* i2400m_tx_release - Tear down the TX queue and infrastructure
*/
void i2400m_tx_release(struct i2400m *i2400m)
{
unsigned long flags;
spin_lock_irqsave(&i2400m->tx_lock, flags);
kfree(i2400m->tx_buf);
i2400m->tx_buf = NULL;
spin_unlock_irqrestore(&i2400m->tx_lock, flags);
}
| gpl-2.0 |
RR-msm7x30/samsung-kernel-msm7x30-common | drivers/net/wireless/ath/ath5k/caps.c | 10632 | 4390 | /*
* Copyright (c) 2004-2008 Reyk Floeter <reyk@openbsd.org>
* Copyright (c) 2006-2008 Nick Kossifidis <mickflemm@gmail.com>
* Copyright (c) 2007-2008 Jiri Slaby <jirislaby@gmail.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
/**************\
* Capabilities *
\**************/
#include "ath5k.h"
#include "reg.h"
#include "debug.h"
#include "../regd.h"
/*
* Fill the capabilities struct
* TODO: Merge this with EEPROM code when we are done with it
*/
int ath5k_hw_set_capabilities(struct ath5k_hw *ah)
{
struct ath5k_capabilities *caps = &ah->ah_capabilities;
u16 ee_header;
/* Capabilities stored in the EEPROM */
ee_header = caps->cap_eeprom.ee_header;
if (ah->ah_version == AR5K_AR5210) {
/*
* Set radio capabilities
* (The AR5110 only supports the middle 5GHz band)
*/
caps->cap_range.range_5ghz_min = 5120;
caps->cap_range.range_5ghz_max = 5430;
caps->cap_range.range_2ghz_min = 0;
caps->cap_range.range_2ghz_max = 0;
/* Set supported modes */
__set_bit(AR5K_MODE_11A, caps->cap_mode);
} else {
/*
* XXX The transceiver supports frequencies from 4920 to 6100MHz
* XXX and from 2312 to 2732MHz. There are problems with the
* XXX current ieee80211 implementation because the IEEE
* XXX channel mapping does not support negative channel
* XXX numbers (2312MHz is channel -19). Of course, this
* XXX doesn't matter because these channels are out of the
* XXX legal range.
*/
/*
* Set radio capabilities
*/
if (AR5K_EEPROM_HDR_11A(ee_header)) {
if (ath_is_49ghz_allowed(caps->cap_eeprom.ee_regdomain))
caps->cap_range.range_5ghz_min = 4920;
else
caps->cap_range.range_5ghz_min = 5005;
caps->cap_range.range_5ghz_max = 6100;
/* Set supported modes */
__set_bit(AR5K_MODE_11A, caps->cap_mode);
}
/* Enable 802.11b if a 2GHz capable radio (2111/5112) is
* connected */
if (AR5K_EEPROM_HDR_11B(ee_header) ||
(AR5K_EEPROM_HDR_11G(ee_header) &&
ah->ah_version != AR5K_AR5211)) {
/* 2312 */
caps->cap_range.range_2ghz_min = 2412;
caps->cap_range.range_2ghz_max = 2732;
/* Override 2GHz modes on SoCs that need it
* NOTE: cap_needs_2GHz_ovr gets set from
* ath_ahb_probe */
if (!caps->cap_needs_2GHz_ovr) {
if (AR5K_EEPROM_HDR_11B(ee_header))
__set_bit(AR5K_MODE_11B,
caps->cap_mode);
if (AR5K_EEPROM_HDR_11G(ee_header) &&
ah->ah_version != AR5K_AR5211)
__set_bit(AR5K_MODE_11G,
caps->cap_mode);
}
}
}
if ((ah->ah_radio_5ghz_revision & 0xf0) == AR5K_SREV_RAD_2112)
__clear_bit(AR5K_MODE_11A, caps->cap_mode);
/* Set number of supported TX queues */
if (ah->ah_version == AR5K_AR5210)
caps->cap_queues.q_tx_num = AR5K_NUM_TX_QUEUES_NOQCU;
else
caps->cap_queues.q_tx_num = AR5K_NUM_TX_QUEUES;
/* Newer hardware has PHY error counters */
if (ah->ah_mac_srev >= AR5K_SREV_AR5213A)
caps->cap_has_phyerr_counters = true;
else
caps->cap_has_phyerr_counters = false;
/* MACs since AR5212 have MRR support */
if (ah->ah_version == AR5K_AR5212)
caps->cap_has_mrr_support = true;
else
caps->cap_has_mrr_support = false;
return 0;
}
/*
* TODO: Following functions should be part of a new function
* set_capability
*/
int ath5k_hw_enable_pspoll(struct ath5k_hw *ah, u8 *bssid,
u16 assoc_id)
{
if (ah->ah_version == AR5K_AR5210) {
AR5K_REG_DISABLE_BITS(ah, AR5K_STA_ID1,
AR5K_STA_ID1_NO_PSPOLL | AR5K_STA_ID1_DEFAULT_ANTENNA);
return 0;
}
return -EIO;
}
int ath5k_hw_disable_pspoll(struct ath5k_hw *ah)
{
if (ah->ah_version == AR5K_AR5210) {
AR5K_REG_ENABLE_BITS(ah, AR5K_STA_ID1,
AR5K_STA_ID1_NO_PSPOLL | AR5K_STA_ID1_DEFAULT_ANTENNA);
return 0;
}
return -EIO;
}
| gpl-2.0 |
dh-electronics/linux-am35x | arch/arm/mach-pxa/vpac270.c | 137 | 17778 | /*
* Hardware definitions for Voipac PXA270
*
* Copyright (C) 2010
* Marek Vasut <marek.vasut@gmail.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/platform_device.h>
#include <linux/delay.h>
#include <linux/irq.h>
#include <linux/gpio_keys.h>
#include <linux/input.h>
#include <linux/gpio.h>
#include <linux/usb/gpio_vbus.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/physmap.h>
#include <linux/mtd/onenand.h>
#include <linux/dm9000.h>
#include <linux/ucb1400.h>
#include <linux/ata_platform.h>
#include <linux/regulator/max1586.h>
#include <linux/i2c/pxa-i2c.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <mach/pxa27x.h>
#include <mach/audio.h>
#include <mach/vpac270.h>
#include <mach/mmc.h>
#include <mach/pxafb.h>
#include <mach/ohci.h>
#include <mach/pxa27x-udc.h>
#include <mach/udc.h>
#include <mach/pata_pxa.h>
#include "generic.h"
#include "devices.h"
/******************************************************************************
* Pin configuration
******************************************************************************/
static unsigned long vpac270_pin_config[] __initdata = {
/* MMC */
GPIO32_MMC_CLK,
GPIO92_MMC_DAT_0,
GPIO109_MMC_DAT_1,
GPIO110_MMC_DAT_2,
GPIO111_MMC_DAT_3,
GPIO112_MMC_CMD,
GPIO53_GPIO, /* SD detect */
GPIO52_GPIO, /* SD r/o switch */
/* GPIO KEYS */
GPIO1_GPIO, /* USER BTN */
/* LEDs */
GPIO15_GPIO, /* orange led */
/* FFUART */
GPIO34_FFUART_RXD,
GPIO39_FFUART_TXD,
GPIO27_FFUART_RTS,
GPIO100_FFUART_CTS,
GPIO33_FFUART_DSR,
GPIO40_FFUART_DTR,
GPIO10_FFUART_DCD,
GPIO38_FFUART_RI,
/* LCD */
GPIO58_LCD_LDD_0,
GPIO59_LCD_LDD_1,
GPIO60_LCD_LDD_2,
GPIO61_LCD_LDD_3,
GPIO62_LCD_LDD_4,
GPIO63_LCD_LDD_5,
GPIO64_LCD_LDD_6,
GPIO65_LCD_LDD_7,
GPIO66_LCD_LDD_8,
GPIO67_LCD_LDD_9,
GPIO68_LCD_LDD_10,
GPIO69_LCD_LDD_11,
GPIO70_LCD_LDD_12,
GPIO71_LCD_LDD_13,
GPIO72_LCD_LDD_14,
GPIO73_LCD_LDD_15,
GPIO86_LCD_LDD_16,
GPIO87_LCD_LDD_17,
GPIO74_LCD_FCLK,
GPIO75_LCD_LCLK,
GPIO76_LCD_PCLK,
GPIO77_LCD_BIAS,
/* PCMCIA */
GPIO48_nPOE,
GPIO49_nPWE,
GPIO50_nPIOR,
GPIO51_nPIOW,
GPIO85_nPCE_1,
GPIO54_nPCE_2,
GPIO55_nPREG,
GPIO57_nIOIS16,
GPIO56_nPWAIT,
GPIO104_PSKTSEL,
GPIO84_GPIO, /* PCMCIA CD */
GPIO35_GPIO, /* PCMCIA RDY */
GPIO107_GPIO, /* PCMCIA PPEN */
GPIO11_GPIO, /* PCMCIA RESET */
GPIO17_GPIO, /* CF CD */
GPIO12_GPIO, /* CF RDY */
GPIO16_GPIO, /* CF RESET */
/* UHC */
GPIO88_USBH1_PWR,
GPIO89_USBH1_PEN,
GPIO119_USBH2_PWR,
GPIO120_USBH2_PEN,
/* UDC */
GPIO41_GPIO,
/* Ethernet */
GPIO114_GPIO, /* IRQ */
/* AC97 */
GPIO28_AC97_BITCLK,
GPIO29_AC97_SDATA_IN_0,
GPIO30_AC97_SDATA_OUT,
GPIO31_AC97_SYNC,
GPIO95_AC97_nRESET,
GPIO98_AC97_SYSCLK,
GPIO113_GPIO, /* TS IRQ */
/* I2C */
GPIO117_I2C_SCL,
GPIO118_I2C_SDA,
/* IDE */
GPIO36_GPIO, /* IDE IRQ */
GPIO80_DREQ_1,
};
/******************************************************************************
* NOR Flash
******************************************************************************/
#if defined(CONFIG_MTD_PHYSMAP) || defined(CONFIG_MTD_PHYSMAP_MODULE)
static struct mtd_partition vpac270_nor_partitions[] = {
{
.name = "Flash",
.offset = 0x00000000,
.size = MTDPART_SIZ_FULL,
}
};
static struct physmap_flash_data vpac270_flash_data[] = {
{
.width = 2, /* bankwidth in bytes */
.parts = vpac270_nor_partitions,
.nr_parts = ARRAY_SIZE(vpac270_nor_partitions)
}
};
static struct resource vpac270_flash_resource = {
.start = PXA_CS0_PHYS,
.end = PXA_CS0_PHYS + SZ_64M - 1,
.flags = IORESOURCE_MEM,
};
static struct platform_device vpac270_flash = {
.name = "physmap-flash",
.id = 0,
.resource = &vpac270_flash_resource,
.num_resources = 1,
.dev = {
.platform_data = vpac270_flash_data,
},
};
static void __init vpac270_nor_init(void)
{
platform_device_register(&vpac270_flash);
}
#else
static inline void vpac270_nor_init(void) {}
#endif
/******************************************************************************
* OneNAND Flash
******************************************************************************/
#if defined(CONFIG_MTD_ONENAND) || defined(CONFIG_MTD_ONENAND_MODULE)
static struct mtd_partition vpac270_onenand_partitions[] = {
{
.name = "Flash",
.offset = 0x00000000,
.size = MTDPART_SIZ_FULL,
}
};
static struct onenand_platform_data vpac270_onenand_info = {
.parts = vpac270_onenand_partitions,
.nr_parts = ARRAY_SIZE(vpac270_onenand_partitions),
};
static struct resource vpac270_onenand_resources[] = {
[0] = {
.start = PXA_CS0_PHYS,
.end = PXA_CS0_PHYS + SZ_1M,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device vpac270_onenand = {
.name = "onenand-flash",
.id = -1,
.resource = vpac270_onenand_resources,
.num_resources = ARRAY_SIZE(vpac270_onenand_resources),
.dev = {
.platform_data = &vpac270_onenand_info,
},
};
static void __init vpac270_onenand_init(void)
{
platform_device_register(&vpac270_onenand);
}
#else
static void __init vpac270_onenand_init(void) {}
#endif
/******************************************************************************
* SD/MMC card controller
******************************************************************************/
#if defined(CONFIG_MMC_PXA) || defined(CONFIG_MMC_PXA_MODULE)
static struct pxamci_platform_data vpac270_mci_platform_data = {
.ocr_mask = MMC_VDD_32_33 | MMC_VDD_33_34,
.gpio_power = -1,
.gpio_card_detect = GPIO53_VPAC270_SD_DETECT_N,
.gpio_card_ro = GPIO52_VPAC270_SD_READONLY,
.detect_delay_ms = 200,
};
static void __init vpac270_mmc_init(void)
{
pxa_set_mci_info(&vpac270_mci_platform_data);
}
#else
static inline void vpac270_mmc_init(void) {}
#endif
/******************************************************************************
* GPIO keys
******************************************************************************/
#if defined(CONFIG_KEYBOARD_GPIO) || defined(CONFIG_KEYBOARD_GPIO_MODULE)
static struct gpio_keys_button vpac270_pxa_buttons[] = {
{KEY_POWER, GPIO1_VPAC270_USER_BTN, 0, "USER BTN"},
};
static struct gpio_keys_platform_data vpac270_pxa_keys_data = {
.buttons = vpac270_pxa_buttons,
.nbuttons = ARRAY_SIZE(vpac270_pxa_buttons),
};
static struct platform_device vpac270_pxa_keys = {
.name = "gpio-keys",
.id = -1,
.dev = {
.platform_data = &vpac270_pxa_keys_data,
},
};
static void __init vpac270_keys_init(void)
{
platform_device_register(&vpac270_pxa_keys);
}
#else
static inline void vpac270_keys_init(void) {}
#endif
/******************************************************************************
* LED
******************************************************************************/
#if defined(CONFIG_LEDS_GPIO) || defined(CONFIG_LEDS_GPIO_MODULE)
struct gpio_led vpac270_gpio_leds[] = {
{
.name = "vpac270:orange:user",
.default_trigger = "none",
.gpio = GPIO15_VPAC270_LED_ORANGE,
.active_low = 1,
}
};
static struct gpio_led_platform_data vpac270_gpio_led_info = {
.leds = vpac270_gpio_leds,
.num_leds = ARRAY_SIZE(vpac270_gpio_leds),
};
static struct platform_device vpac270_leds = {
.name = "leds-gpio",
.id = -1,
.dev = {
.platform_data = &vpac270_gpio_led_info,
}
};
static void __init vpac270_leds_init(void)
{
platform_device_register(&vpac270_leds);
}
#else
static inline void vpac270_leds_init(void) {}
#endif
/******************************************************************************
* USB Host
******************************************************************************/
#if defined(CONFIG_USB_OHCI_HCD) || defined(CONFIG_USB_OHCI_HCD_MODULE)
static int vpac270_ohci_init(struct device *dev)
{
UP2OCR = UP2OCR_HXS | UP2OCR_HXOE | UP2OCR_DPPDE | UP2OCR_DMPDE;
return 0;
}
static struct pxaohci_platform_data vpac270_ohci_info = {
.port_mode = PMM_PERPORT_MODE,
.flags = ENABLE_PORT1 | ENABLE_PORT2 |
POWER_CONTROL_LOW | POWER_SENSE_LOW,
.init = vpac270_ohci_init,
};
static void __init vpac270_uhc_init(void)
{
pxa_set_ohci_info(&vpac270_ohci_info);
}
#else
static inline void vpac270_uhc_init(void) {}
#endif
/******************************************************************************
* USB Gadget
******************************************************************************/
#if defined(CONFIG_USB_PXA27X)||defined(CONFIG_USB_PXA27X_MODULE)
static struct gpio_vbus_mach_info vpac270_gpio_vbus_info = {
.gpio_vbus = GPIO41_VPAC270_UDC_DETECT,
.gpio_pullup = -1,
};
static struct platform_device vpac270_gpio_vbus = {
.name = "gpio-vbus",
.id = -1,
.dev = {
.platform_data = &vpac270_gpio_vbus_info,
},
};
static void vpac270_udc_command(int cmd)
{
if (cmd == PXA2XX_UDC_CMD_CONNECT)
UP2OCR = UP2OCR_HXOE | UP2OCR_DPPUE;
else if (cmd == PXA2XX_UDC_CMD_DISCONNECT)
UP2OCR = UP2OCR_HXOE;
}
static struct pxa2xx_udc_mach_info vpac270_udc_info __initdata = {
.udc_command = vpac270_udc_command,
.gpio_pullup = -1,
};
static void __init vpac270_udc_init(void)
{
pxa_set_udc_info(&vpac270_udc_info);
platform_device_register(&vpac270_gpio_vbus);
}
#else
static inline void vpac270_udc_init(void) {}
#endif
/******************************************************************************
* Ethernet
******************************************************************************/
#if defined(CONFIG_DM9000) || defined(CONFIG_DM9000_MODULE)
static struct resource vpac270_dm9000_resources[] = {
[0] = {
.start = PXA_CS2_PHYS + 0x300,
.end = PXA_CS2_PHYS + 0x303,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = PXA_CS2_PHYS + 0x304,
.end = PXA_CS2_PHYS + 0x343,
.flags = IORESOURCE_MEM,
},
[2] = {
.start = IRQ_GPIO(GPIO114_VPAC270_ETH_IRQ),
.end = IRQ_GPIO(GPIO114_VPAC270_ETH_IRQ),
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHEDGE,
},
};
static struct dm9000_plat_data vpac270_dm9000_platdata = {
.flags = DM9000_PLATF_32BITONLY,
};
static struct platform_device vpac270_dm9000_device = {
.name = "dm9000",
.id = -1,
.num_resources = ARRAY_SIZE(vpac270_dm9000_resources),
.resource = vpac270_dm9000_resources,
.dev = {
.platform_data = &vpac270_dm9000_platdata,
}
};
static void __init vpac270_eth_init(void)
{
platform_device_register(&vpac270_dm9000_device);
}
#else
static inline void vpac270_eth_init(void) {}
#endif
/******************************************************************************
* Audio and Touchscreen
******************************************************************************/
#if defined(CONFIG_TOUCHSCREEN_UCB1400) || \
defined(CONFIG_TOUCHSCREEN_UCB1400_MODULE)
static pxa2xx_audio_ops_t vpac270_ac97_pdata = {
.reset_gpio = 95,
};
static struct ucb1400_pdata vpac270_ucb1400_pdata = {
.irq = IRQ_GPIO(GPIO113_VPAC270_TS_IRQ),
};
static struct platform_device vpac270_ucb1400_device = {
.name = "ucb1400_core",
.id = -1,
.dev = {
.platform_data = &vpac270_ucb1400_pdata,
},
};
static void __init vpac270_ts_init(void)
{
pxa_set_ac97_info(&vpac270_ac97_pdata);
platform_device_register(&vpac270_ucb1400_device);
}
#else
static inline void vpac270_ts_init(void) {}
#endif
/******************************************************************************
* RTC
******************************************************************************/
#if defined(CONFIG_RTC_DRV_DS1307) || defined(CONFIG_RTC_DRV_DS1307_MODULE)
static struct i2c_board_info __initdata vpac270_i2c_devs[] = {
{
I2C_BOARD_INFO("ds1339", 0x68),
},
};
static void __init vpac270_rtc_init(void)
{
i2c_register_board_info(0, ARRAY_AND_SIZE(vpac270_i2c_devs));
}
#else
static inline void vpac270_rtc_init(void) {}
#endif
/******************************************************************************
* Framebuffer
******************************************************************************/
#if defined(CONFIG_FB_PXA) || defined(CONFIG_FB_PXA_MODULE)
static struct pxafb_mode_info vpac270_lcd_modes[] = {
{
.pixclock = 57692,
.xres = 640,
.yres = 480,
.bpp = 32,
.depth = 18,
.left_margin = 144,
.right_margin = 32,
.upper_margin = 13,
.lower_margin = 30,
.hsync_len = 32,
.vsync_len = 2,
.sync = FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
}, { /* CRT 640x480 */
.pixclock = 35000,
.xres = 640,
.yres = 480,
.bpp = 16,
.depth = 16,
.left_margin = 96,
.right_margin = 48,
.upper_margin = 33,
.lower_margin = 10,
.hsync_len = 48,
.vsync_len = 1,
.sync = FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
}, { /* CRT 800x600 H=30kHz V=48HZ */
.pixclock = 25000,
.xres = 800,
.yres = 600,
.bpp = 16,
.depth = 16,
.left_margin = 50,
.right_margin = 1,
.upper_margin = 21,
.lower_margin = 12,
.hsync_len = 8,
.vsync_len = 1,
.sync = FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
}, { /* CRT 1024x768 H=40kHz V=50Hz */
.pixclock = 15000,
.xres = 1024,
.yres = 768,
.bpp = 16,
.depth = 16,
.left_margin = 220,
.right_margin = 8,
.upper_margin = 33,
.lower_margin = 2,
.hsync_len = 48,
.vsync_len = 1,
.sync = FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
}
};
static struct pxafb_mach_info vpac270_lcd_screen = {
.modes = vpac270_lcd_modes,
.num_modes = ARRAY_SIZE(vpac270_lcd_modes),
.lcd_conn = LCD_COLOR_TFT_18BPP,
};
static void vpac270_lcd_power(int on, struct fb_var_screeninfo *info)
{
gpio_set_value(GPIO81_VPAC270_BKL_ON, on);
}
static void __init vpac270_lcd_init(void)
{
int ret;
ret = gpio_request(GPIO81_VPAC270_BKL_ON, "BKL-ON");
if (ret) {
pr_err("Requesting BKL-ON GPIO failed!\n");
goto err;
}
ret = gpio_direction_output(GPIO81_VPAC270_BKL_ON, 1);
if (ret) {
pr_err("Setting BKL-ON GPIO direction failed!\n");
goto err2;
}
vpac270_lcd_screen.pxafb_lcd_power = vpac270_lcd_power;
pxa_set_fb_info(NULL, &vpac270_lcd_screen);
return;
err2:
gpio_free(GPIO81_VPAC270_BKL_ON);
err:
return;
}
#else
static inline void vpac270_lcd_init(void) {}
#endif
/******************************************************************************
* PATA IDE
******************************************************************************/
#if defined(CONFIG_PATA_PXA) || defined(CONFIG_PATA_PXA_MODULE)
static struct pata_pxa_pdata vpac270_pata_pdata = {
.reg_shift = 1,
.dma_dreq = 1,
.irq_flags = IRQF_TRIGGER_RISING,
};
static struct resource vpac270_ide_resources[] = {
[0] = { /* I/O Base address */
.start = PXA_CS3_PHYS + 0x120,
.end = PXA_CS3_PHYS + 0x13f,
.flags = IORESOURCE_MEM
},
[1] = { /* CTL Base address */
.start = PXA_CS3_PHYS + 0x15c,
.end = PXA_CS3_PHYS + 0x15f,
.flags = IORESOURCE_MEM
},
[2] = { /* DMA Base address */
.start = PXA_CS3_PHYS + 0x20,
.end = PXA_CS3_PHYS + 0x2f,
.flags = IORESOURCE_DMA
},
[3] = { /* IDE IRQ pin */
.start = gpio_to_irq(GPIO36_VPAC270_IDE_IRQ),
.end = gpio_to_irq(GPIO36_VPAC270_IDE_IRQ),
.flags = IORESOURCE_IRQ
}
};
static struct platform_device vpac270_ide_device = {
.name = "pata_pxa",
.num_resources = ARRAY_SIZE(vpac270_ide_resources),
.resource = vpac270_ide_resources,
.dev = {
.platform_data = &vpac270_pata_pdata,
.coherent_dma_mask = 0xffffffff,
}
};
static void __init vpac270_ide_init(void)
{
platform_device_register(&vpac270_ide_device);
}
#else
static inline void vpac270_ide_init(void) {}
#endif
/******************************************************************************
* Core power regulator
******************************************************************************/
#if defined(CONFIG_REGULATOR_MAX1586) || \
defined(CONFIG_REGULATOR_MAX1586_MODULE)
static struct regulator_consumer_supply vpac270_max1587a_consumers[] = {
{
.supply = "vcc_core",
}
};
static struct regulator_init_data vpac270_max1587a_v3_info = {
.constraints = {
.name = "vcc_core range",
.min_uV = 900000,
.max_uV = 1705000,
.always_on = 1,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE,
},
.consumer_supplies = vpac270_max1587a_consumers,
.num_consumer_supplies = ARRAY_SIZE(vpac270_max1587a_consumers),
};
static struct max1586_subdev_data vpac270_max1587a_subdevs[] = {
{
.name = "vcc_core",
.id = MAX1586_V3,
.platform_data = &vpac270_max1587a_v3_info,
}
};
static struct max1586_platform_data vpac270_max1587a_info = {
.subdevs = vpac270_max1587a_subdevs,
.num_subdevs = ARRAY_SIZE(vpac270_max1587a_subdevs),
.v3_gain = MAX1586_GAIN_R24_3k32, /* 730..1550 mV */
};
static struct i2c_board_info __initdata vpac270_pi2c_board_info[] = {
{
I2C_BOARD_INFO("max1586", 0x14),
.platform_data = &vpac270_max1587a_info,
},
};
static void __init vpac270_pmic_init(void)
{
i2c_register_board_info(1, ARRAY_AND_SIZE(vpac270_pi2c_board_info));
}
#else
static inline void vpac270_pmic_init(void) {}
#endif
/******************************************************************************
* Machine init
******************************************************************************/
static void __init vpac270_init(void)
{
pxa2xx_mfp_config(ARRAY_AND_SIZE(vpac270_pin_config));
pxa_set_ffuart_info(NULL);
pxa_set_btuart_info(NULL);
pxa_set_stuart_info(NULL);
pxa_set_i2c_info(NULL);
pxa27x_set_i2c_power_info(NULL);
vpac270_pmic_init();
vpac270_lcd_init();
vpac270_mmc_init();
vpac270_nor_init();
vpac270_onenand_init();
vpac270_leds_init();
vpac270_keys_init();
vpac270_uhc_init();
vpac270_udc_init();
vpac270_eth_init();
vpac270_ts_init();
vpac270_rtc_init();
vpac270_ide_init();
}
MACHINE_START(VPAC270, "Voipac PXA270")
.atag_offset = 0x100,
.map_io = pxa27x_map_io,
.init_irq = pxa27x_init_irq,
.handle_irq = pxa27x_handle_irq,
.timer = &pxa_timer,
.init_machine = vpac270_init
MACHINE_END
| gpl-2.0 |
daniel666/oshw2 | arch/powerpc/mm/mem.c | 137 | 14846 | /*
* PowerPC version
* Copyright (C) 1995-1996 Gary Thomas (gdt@linuxppc.org)
*
* Modifications by Paul Mackerras (PowerMac) (paulus@cs.anu.edu.au)
* and Cort Dougan (PReP) (cort@cs.nmt.edu)
* Copyright (C) 1996 Paul Mackerras
* PPC44x/36-bit changes by Matt Porter (mporter@mvista.com)
*
* Derived from "arch/i386/mm/init.c"
* Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
*
* 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/sched.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/stddef.h>
#include <linux/init.h>
#include <linux/bootmem.h>
#include <linux/highmem.h>
#include <linux/initrd.h>
#include <linux/pagemap.h>
#include <linux/suspend.h>
#include <linux/lmb.h>
#include <asm/pgalloc.h>
#include <asm/prom.h>
#include <asm/io.h>
#include <asm/mmu_context.h>
#include <asm/pgtable.h>
#include <asm/mmu.h>
#include <asm/smp.h>
#include <asm/machdep.h>
#include <asm/btext.h>
#include <asm/tlb.h>
#include <asm/sections.h>
#include <asm/sparsemem.h>
#include <asm/vdso.h>
#include <asm/fixmap.h>
#include "mmu_decl.h"
#ifndef CPU_FTR_COHERENT_ICACHE
#define CPU_FTR_COHERENT_ICACHE 0 /* XXX for now */
#define CPU_FTR_NOEXECUTE 0
#endif
int init_bootmem_done;
int mem_init_done;
unsigned long memory_limit;
#ifdef CONFIG_HIGHMEM
pte_t *kmap_pte;
pgprot_t kmap_prot;
EXPORT_SYMBOL(kmap_prot);
EXPORT_SYMBOL(kmap_pte);
static inline pte_t *virt_to_kpte(unsigned long vaddr)
{
return pte_offset_kernel(pmd_offset(pud_offset(pgd_offset_k(vaddr),
vaddr), vaddr), vaddr);
}
#endif
int page_is_ram(unsigned long pfn)
{
#ifndef CONFIG_PPC64 /* XXX for now */
return pfn < max_pfn;
#else
unsigned long paddr = (pfn << PAGE_SHIFT);
int i;
for (i=0; i < lmb.memory.cnt; i++) {
unsigned long base;
base = lmb.memory.region[i].base;
if ((paddr >= base) &&
(paddr < (base + lmb.memory.region[i].size))) {
return 1;
}
}
return 0;
#endif
}
pgprot_t phys_mem_access_prot(struct file *file, unsigned long pfn,
unsigned long size, pgprot_t vma_prot)
{
if (ppc_md.phys_mem_access_prot)
return ppc_md.phys_mem_access_prot(file, pfn, size, vma_prot);
if (!page_is_ram(pfn))
vma_prot = pgprot_noncached(vma_prot);
return vma_prot;
}
EXPORT_SYMBOL(phys_mem_access_prot);
#ifdef CONFIG_MEMORY_HOTPLUG
#ifdef CONFIG_NUMA
int memory_add_physaddr_to_nid(u64 start)
{
return hot_add_scn_to_nid(start);
}
#endif
int arch_add_memory(int nid, u64 start, u64 size)
{
struct pglist_data *pgdata;
struct zone *zone;
unsigned long start_pfn = start >> PAGE_SHIFT;
unsigned long nr_pages = size >> PAGE_SHIFT;
pgdata = NODE_DATA(nid);
start = (unsigned long)__va(start);
create_section_mapping(start, start + size);
/* this should work for most non-highmem platforms */
zone = pgdata->node_zones;
return __add_pages(nid, zone, start_pfn, nr_pages);
}
#endif /* CONFIG_MEMORY_HOTPLUG */
/*
* walk_memory_resource() needs to make sure there is no holes in a given
* memory range. PPC64 does not maintain the memory layout in /proc/iomem.
* Instead it maintains it in lmb.memory structures. Walk through the
* memory regions, find holes and callback for contiguous regions.
*/
int
walk_memory_resource(unsigned long start_pfn, unsigned long nr_pages, void *arg,
int (*func)(unsigned long, unsigned long, void *))
{
struct lmb_property res;
unsigned long pfn, len;
u64 end;
int ret = -1;
res.base = (u64) start_pfn << PAGE_SHIFT;
res.size = (u64) nr_pages << PAGE_SHIFT;
end = res.base + res.size - 1;
while ((res.base < end) && (lmb_find(&res) >= 0)) {
pfn = (unsigned long)(res.base >> PAGE_SHIFT);
len = (unsigned long)(res.size >> PAGE_SHIFT);
ret = (*func)(pfn, len, arg);
if (ret)
break;
res.base += (res.size + 1);
res.size = (end - res.base + 1);
}
return ret;
}
EXPORT_SYMBOL_GPL(walk_memory_resource);
/*
* Initialize the bootmem system and give it all the memory we
* have available. If we are using highmem, we only put the
* lowmem into the bootmem system.
*/
#ifndef CONFIG_NEED_MULTIPLE_NODES
void __init do_init_bootmem(void)
{
unsigned long i;
unsigned long start, bootmap_pages;
unsigned long total_pages;
int boot_mapsize;
max_low_pfn = max_pfn = lmb_end_of_DRAM() >> PAGE_SHIFT;
total_pages = (lmb_end_of_DRAM() - memstart_addr) >> PAGE_SHIFT;
#ifdef CONFIG_HIGHMEM
total_pages = total_lowmem >> PAGE_SHIFT;
max_low_pfn = lowmem_end_addr >> PAGE_SHIFT;
#endif
/*
* Find an area to use for the bootmem bitmap. Calculate the size of
* bitmap required as (Total Memory) / PAGE_SIZE / BITS_PER_BYTE.
* Add 1 additional page in case the address isn't page-aligned.
*/
bootmap_pages = bootmem_bootmap_pages(total_pages);
start = lmb_alloc(bootmap_pages << PAGE_SHIFT, PAGE_SIZE);
min_low_pfn = MEMORY_START >> PAGE_SHIFT;
boot_mapsize = init_bootmem_node(NODE_DATA(0), start >> PAGE_SHIFT, min_low_pfn, max_low_pfn);
/* Add active regions with valid PFNs */
for (i = 0; i < lmb.memory.cnt; i++) {
unsigned long start_pfn, end_pfn;
start_pfn = lmb.memory.region[i].base >> PAGE_SHIFT;
end_pfn = start_pfn + lmb_size_pages(&lmb.memory, i);
add_active_range(0, start_pfn, end_pfn);
}
/* Add all physical memory to the bootmem map, mark each area
* present.
*/
#ifdef CONFIG_HIGHMEM
free_bootmem_with_active_regions(0, lowmem_end_addr >> PAGE_SHIFT);
/* reserve the sections we're already using */
for (i = 0; i < lmb.reserved.cnt; i++) {
unsigned long addr = lmb.reserved.region[i].base +
lmb_size_bytes(&lmb.reserved, i) - 1;
if (addr < lowmem_end_addr)
reserve_bootmem(lmb.reserved.region[i].base,
lmb_size_bytes(&lmb.reserved, i),
BOOTMEM_DEFAULT);
else if (lmb.reserved.region[i].base < lowmem_end_addr) {
unsigned long adjusted_size = lowmem_end_addr -
lmb.reserved.region[i].base;
reserve_bootmem(lmb.reserved.region[i].base,
adjusted_size, BOOTMEM_DEFAULT);
}
}
#else
free_bootmem_with_active_regions(0, max_pfn);
/* reserve the sections we're already using */
for (i = 0; i < lmb.reserved.cnt; i++)
reserve_bootmem(lmb.reserved.region[i].base,
lmb_size_bytes(&lmb.reserved, i),
BOOTMEM_DEFAULT);
#endif
/* XXX need to clip this if using highmem? */
sparse_memory_present_with_active_regions(0);
init_bootmem_done = 1;
}
/* mark pages that don't exist as nosave */
static int __init mark_nonram_nosave(void)
{
unsigned long lmb_next_region_start_pfn,
lmb_region_max_pfn;
int i;
for (i = 0; i < lmb.memory.cnt - 1; i++) {
lmb_region_max_pfn =
(lmb.memory.region[i].base >> PAGE_SHIFT) +
(lmb.memory.region[i].size >> PAGE_SHIFT);
lmb_next_region_start_pfn =
lmb.memory.region[i+1].base >> PAGE_SHIFT;
if (lmb_region_max_pfn < lmb_next_region_start_pfn)
register_nosave_region(lmb_region_max_pfn,
lmb_next_region_start_pfn);
}
return 0;
}
/*
* paging_init() sets up the page tables - in fact we've already done this.
*/
void __init paging_init(void)
{
unsigned long total_ram = lmb_phys_mem_size();
phys_addr_t top_of_ram = lmb_end_of_DRAM();
unsigned long max_zone_pfns[MAX_NR_ZONES];
#ifdef CONFIG_PPC32
unsigned long v = __fix_to_virt(__end_of_fixed_addresses - 1);
unsigned long end = __fix_to_virt(FIX_HOLE);
for (; v < end; v += PAGE_SIZE)
map_page(v, 0, 0); /* XXX gross */
#endif
#ifdef CONFIG_HIGHMEM
map_page(PKMAP_BASE, 0, 0); /* XXX gross */
pkmap_page_table = virt_to_kpte(PKMAP_BASE);
kmap_pte = virt_to_kpte(__fix_to_virt(FIX_KMAP_BEGIN));
kmap_prot = PAGE_KERNEL;
#endif /* CONFIG_HIGHMEM */
printk(KERN_DEBUG "Top of RAM: 0x%llx, Total RAM: 0x%lx\n",
(unsigned long long)top_of_ram, total_ram);
printk(KERN_DEBUG "Memory hole size: %ldMB\n",
(long int)((top_of_ram - total_ram) >> 20));
memset(max_zone_pfns, 0, sizeof(max_zone_pfns));
#ifdef CONFIG_HIGHMEM
max_zone_pfns[ZONE_DMA] = lowmem_end_addr >> PAGE_SHIFT;
max_zone_pfns[ZONE_HIGHMEM] = top_of_ram >> PAGE_SHIFT;
#else
max_zone_pfns[ZONE_DMA] = top_of_ram >> PAGE_SHIFT;
#endif
free_area_init_nodes(max_zone_pfns);
mark_nonram_nosave();
}
#endif /* ! CONFIG_NEED_MULTIPLE_NODES */
void __init mem_init(void)
{
#ifdef CONFIG_NEED_MULTIPLE_NODES
int nid;
#endif
pg_data_t *pgdat;
unsigned long i;
struct page *page;
unsigned long reservedpages = 0, codesize, initsize, datasize, bsssize;
num_physpages = lmb.memory.size >> PAGE_SHIFT;
high_memory = (void *) __va(max_low_pfn * PAGE_SIZE);
#ifdef CONFIG_NEED_MULTIPLE_NODES
for_each_online_node(nid) {
if (NODE_DATA(nid)->node_spanned_pages != 0) {
printk("freeing bootmem node %d\n", nid);
totalram_pages +=
free_all_bootmem_node(NODE_DATA(nid));
}
}
#else
max_mapnr = max_pfn;
totalram_pages += free_all_bootmem();
#endif
for_each_online_pgdat(pgdat) {
for (i = 0; i < pgdat->node_spanned_pages; i++) {
if (!pfn_valid(pgdat->node_start_pfn + i))
continue;
page = pgdat_page_nr(pgdat, i);
if (PageReserved(page))
reservedpages++;
}
}
codesize = (unsigned long)&_sdata - (unsigned long)&_stext;
datasize = (unsigned long)&_edata - (unsigned long)&_sdata;
initsize = (unsigned long)&__init_end - (unsigned long)&__init_begin;
bsssize = (unsigned long)&__bss_stop - (unsigned long)&__bss_start;
#ifdef CONFIG_HIGHMEM
{
unsigned long pfn, highmem_mapnr;
highmem_mapnr = lowmem_end_addr >> PAGE_SHIFT;
for (pfn = highmem_mapnr; pfn < max_mapnr; ++pfn) {
struct page *page = pfn_to_page(pfn);
if (lmb_is_reserved(pfn << PAGE_SHIFT))
continue;
ClearPageReserved(page);
init_page_count(page);
__free_page(page);
totalhigh_pages++;
reservedpages--;
}
totalram_pages += totalhigh_pages;
printk(KERN_DEBUG "High memory: %luk\n",
totalhigh_pages << (PAGE_SHIFT-10));
}
#endif /* CONFIG_HIGHMEM */
printk(KERN_INFO "Memory: %luk/%luk available (%luk kernel code, "
"%luk reserved, %luk data, %luk bss, %luk init)\n",
(unsigned long)nr_free_pages() << (PAGE_SHIFT-10),
num_physpages << (PAGE_SHIFT-10),
codesize >> 10,
reservedpages << (PAGE_SHIFT-10),
datasize >> 10,
bsssize >> 10,
initsize >> 10);
mem_init_done = 1;
}
/*
* This is called when a page has been modified by the kernel.
* It just marks the page as not i-cache clean. We do the i-cache
* flush later when the page is given to a user process, if necessary.
*/
void flush_dcache_page(struct page *page)
{
if (cpu_has_feature(CPU_FTR_COHERENT_ICACHE))
return;
/* avoid an atomic op if possible */
if (test_bit(PG_arch_1, &page->flags))
clear_bit(PG_arch_1, &page->flags);
}
EXPORT_SYMBOL(flush_dcache_page);
void flush_dcache_icache_page(struct page *page)
{
#ifdef CONFIG_BOOKE
void *start = kmap_atomic(page, KM_PPC_SYNC_ICACHE);
__flush_dcache_icache(start);
kunmap_atomic(start, KM_PPC_SYNC_ICACHE);
#elif defined(CONFIG_8xx) || defined(CONFIG_PPC64)
/* On 8xx there is no need to kmap since highmem is not supported */
__flush_dcache_icache(page_address(page));
#else
__flush_dcache_icache_phys(page_to_pfn(page) << PAGE_SHIFT);
#endif
}
void clear_user_page(void *page, unsigned long vaddr, struct page *pg)
{
clear_page(page);
/*
* We shouldnt have to do this, but some versions of glibc
* require it (ld.so assumes zero filled pages are icache clean)
* - Anton
*/
flush_dcache_page(pg);
}
EXPORT_SYMBOL(clear_user_page);
void copy_user_page(void *vto, void *vfrom, unsigned long vaddr,
struct page *pg)
{
copy_page(vto, vfrom);
/*
* We should be able to use the following optimisation, however
* there are two problems.
* Firstly a bug in some versions of binutils meant PLT sections
* were not marked executable.
* Secondly the first word in the GOT section is blrl, used
* to establish the GOT address. Until recently the GOT was
* not marked executable.
* - Anton
*/
#if 0
if (!vma->vm_file && ((vma->vm_flags & VM_EXEC) == 0))
return;
#endif
flush_dcache_page(pg);
}
void flush_icache_user_range(struct vm_area_struct *vma, struct page *page,
unsigned long addr, int len)
{
unsigned long maddr;
maddr = (unsigned long) kmap(page) + (addr & ~PAGE_MASK);
flush_icache_range(maddr, maddr + len);
kunmap(page);
}
EXPORT_SYMBOL(flush_icache_user_range);
/*
* This is called at the end of handling a user page fault, when the
* fault has been handled by updating a PTE in the linux page tables.
* We use it to preload an HPTE into the hash table corresponding to
* the updated linux PTE.
*
* This must always be called with the pte lock held.
*/
void update_mmu_cache(struct vm_area_struct *vma, unsigned long address,
pte_t pte)
{
#ifdef CONFIG_PPC_STD_MMU
unsigned long access = 0, trap;
#endif
unsigned long pfn = pte_pfn(pte);
/* handle i-cache coherency */
if (!cpu_has_feature(CPU_FTR_COHERENT_ICACHE) &&
!cpu_has_feature(CPU_FTR_NOEXECUTE) &&
pfn_valid(pfn)) {
struct page *page = pfn_to_page(pfn);
#ifdef CONFIG_8xx
/* On 8xx, cache control instructions (particularly
* "dcbst" from flush_dcache_icache) fault as write
* operation if there is an unpopulated TLB entry
* for the address in question. To workaround that,
* we invalidate the TLB here, thus avoiding dcbst
* misbehaviour.
*/
_tlbil_va(address, 0 /* 8xx doesn't care about PID */);
#endif
/* The _PAGE_USER test should really be _PAGE_EXEC, but
* older glibc versions execute some code from no-exec
* pages, which for now we are supporting. If exec-only
* pages are ever implemented, this will have to change.
*/
if (!PageReserved(page) && (pte_val(pte) & _PAGE_USER)
&& !test_bit(PG_arch_1, &page->flags)) {
if (vma->vm_mm == current->active_mm) {
__flush_dcache_icache((void *) address);
} else
flush_dcache_icache_page(page);
set_bit(PG_arch_1, &page->flags);
}
}
#ifdef CONFIG_PPC_STD_MMU
/* We only want HPTEs for linux PTEs that have _PAGE_ACCESSED set */
if (!pte_young(pte) || address >= TASK_SIZE)
return;
/* We try to figure out if we are coming from an instruction
* access fault and pass that down to __hash_page so we avoid
* double-faulting on execution of fresh text. We have to test
* for regs NULL since init will get here first thing at boot
*
* We also avoid filling the hash if not coming from a fault
*/
if (current->thread.regs == NULL)
return;
trap = TRAP(current->thread.regs);
if (trap == 0x400)
access |= _PAGE_EXEC;
else if (trap != 0x300)
return;
hash_preload(vma->vm_mm, address, access, trap);
#endif /* CONFIG_PPC_STD_MMU */
}
| gpl-2.0 |
pscholl/jennic-usb-zigbee-linux-driver | arch/arm/mach-omap2/omap3-iommu.c | 137 | 2196 | /*
* omap iommu: omap3 device registration
*
* Copyright (C) 2008-2009 Nokia Corporation
*
* Written by Hiroshi DOYU <Hiroshi.DOYU@nokia.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/platform_device.h>
#include <plat/iommu.h>
struct iommu_device {
resource_size_t base;
int irq;
struct iommu_platform_data pdata;
struct resource res[2];
};
static struct iommu_device devices[] = {
{
.base = 0x480bd400,
.irq = 24,
.pdata = {
.name = "isp",
.nr_tlb_entries = 8,
.clk_name = "cam_ick",
},
},
#if defined(CONFIG_MPU_BRIDGE_IOMMU)
{
.base = 0x5d000000,
.irq = 28,
.pdata = {
.name = "iva2",
.nr_tlb_entries = 32,
.clk_name = "iva2_ck",
},
},
#endif
};
#define NR_IOMMU_DEVICES ARRAY_SIZE(devices)
static struct platform_device *omap3_iommu_pdev[NR_IOMMU_DEVICES];
static int __init omap3_iommu_init(void)
{
int i, err;
struct resource res[] = {
{ .flags = IORESOURCE_MEM },
{ .flags = IORESOURCE_IRQ },
};
for (i = 0; i < NR_IOMMU_DEVICES; i++) {
struct platform_device *pdev;
const struct iommu_device *d = &devices[i];
pdev = platform_device_alloc("omap-iommu", i);
if (!pdev) {
err = -ENOMEM;
goto err_out;
}
res[0].start = d->base;
res[0].end = d->base + MMU_REG_SIZE - 1;
res[1].start = res[1].end = d->irq;
err = platform_device_add_resources(pdev, res,
ARRAY_SIZE(res));
if (err)
goto err_out;
err = platform_device_add_data(pdev, &d->pdata,
sizeof(d->pdata));
if (err)
goto err_out;
err = platform_device_add(pdev);
if (err)
goto err_out;
omap3_iommu_pdev[i] = pdev;
}
return 0;
err_out:
while (i--)
platform_device_put(omap3_iommu_pdev[i]);
return err;
}
module_init(omap3_iommu_init);
static void __exit omap3_iommu_exit(void)
{
int i;
for (i = 0; i < NR_IOMMU_DEVICES; i++)
platform_device_unregister(omap3_iommu_pdev[i]);
}
module_exit(omap3_iommu_exit);
MODULE_AUTHOR("Hiroshi DOYU");
MODULE_DESCRIPTION("omap iommu: omap3 device registration");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
sky7sea/linux | drivers/usb/storage/isd200.c | 393 | 46380 | /* Transport & Protocol Driver for In-System Design, Inc. ISD200 ASIC
*
* Current development and maintenance:
* (C) 2001-2002 Björn Stenberg (bjorn@haxx.se)
*
* Developed with the assistance of:
* (C) 2002 Alan Stern <stern@rowland.org>
*
* Initial work:
* (C) 2000 In-System Design, Inc. (support@in-system.com)
*
* The ISD200 ASIC does not natively support ATA devices. The chip
* does implement an interface, the ATA Command Block (ATACB) which provides
* a means of passing ATA commands and ATA register accesses to a device.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*
* History:
*
* 2002-10-19: Removed the specialized transfer routines.
* (Alan Stern <stern@rowland.harvard.edu>)
* 2001-02-24: Removed lots of duplicate code and simplified the structure.
* (bjorn@haxx.se)
* 2002-01-16: Fixed endianness bug so it works on the ppc arch.
* (Luc Saillard <luc@saillard.org>)
* 2002-01-17: All bitfields removed.
* (bjorn@haxx.se)
*/
/* Include files */
#include <linux/jiffies.h>
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/ata.h>
#include <linux/hdreg.h>
#include <linux/scatterlist.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include "usb.h"
#include "transport.h"
#include "protocol.h"
#include "debug.h"
#include "scsiglue.h"
#define DRV_NAME "ums-isd200"
MODULE_DESCRIPTION("Driver for In-System Design, Inc. ISD200 ASIC");
MODULE_AUTHOR("Björn Stenberg <bjorn@haxx.se>");
MODULE_LICENSE("GPL");
static int isd200_Initialization(struct us_data *us);
/*
* The table of devices
*/
#define UNUSUAL_DEV(id_vendor, id_product, bcdDeviceMin, bcdDeviceMax, \
vendorName, productName, useProtocol, useTransport, \
initFunction, flags) \
{ USB_DEVICE_VER(id_vendor, id_product, bcdDeviceMin, bcdDeviceMax), \
.driver_info = (flags) }
static struct usb_device_id isd200_usb_ids[] = {
# include "unusual_isd200.h"
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, isd200_usb_ids);
#undef UNUSUAL_DEV
/*
* The flags table
*/
#define UNUSUAL_DEV(idVendor, idProduct, bcdDeviceMin, bcdDeviceMax, \
vendor_name, product_name, use_protocol, use_transport, \
init_function, Flags) \
{ \
.vendorName = vendor_name, \
.productName = product_name, \
.useProtocol = use_protocol, \
.useTransport = use_transport, \
.initFunction = init_function, \
}
static struct us_unusual_dev isd200_unusual_dev_list[] = {
# include "unusual_isd200.h"
{ } /* Terminating entry */
};
#undef UNUSUAL_DEV
/* Timeout defines (in Seconds) */
#define ISD200_ENUM_BSY_TIMEOUT 35
#define ISD200_ENUM_DETECT_TIMEOUT 30
#define ISD200_DEFAULT_TIMEOUT 30
/* device flags */
#define DF_ATA_DEVICE 0x0001
#define DF_MEDIA_STATUS_ENABLED 0x0002
#define DF_REMOVABLE_MEDIA 0x0004
/* capability bit definitions */
#define CAPABILITY_DMA 0x01
#define CAPABILITY_LBA 0x02
/* command_setX bit definitions */
#define COMMANDSET_REMOVABLE 0x02
#define COMMANDSET_MEDIA_STATUS 0x10
/* ATA Vendor Specific defines */
#define ATA_ADDRESS_DEVHEAD_STD 0xa0
#define ATA_ADDRESS_DEVHEAD_LBA_MODE 0x40
#define ATA_ADDRESS_DEVHEAD_SLAVE 0x10
/* Action Select bits */
#define ACTION_SELECT_0 0x01
#define ACTION_SELECT_1 0x02
#define ACTION_SELECT_2 0x04
#define ACTION_SELECT_3 0x08
#define ACTION_SELECT_4 0x10
#define ACTION_SELECT_5 0x20
#define ACTION_SELECT_6 0x40
#define ACTION_SELECT_7 0x80
/* Register Select bits */
#define REG_ALTERNATE_STATUS 0x01
#define REG_DEVICE_CONTROL 0x01
#define REG_ERROR 0x02
#define REG_FEATURES 0x02
#define REG_SECTOR_COUNT 0x04
#define REG_SECTOR_NUMBER 0x08
#define REG_CYLINDER_LOW 0x10
#define REG_CYLINDER_HIGH 0x20
#define REG_DEVICE_HEAD 0x40
#define REG_STATUS 0x80
#define REG_COMMAND 0x80
/* ATA registers offset definitions */
#define ATA_REG_ERROR_OFFSET 1
#define ATA_REG_LCYL_OFFSET 4
#define ATA_REG_HCYL_OFFSET 5
#define ATA_REG_STATUS_OFFSET 7
/* ATA error definitions not in <linux/hdreg.h> */
#define ATA_ERROR_MEDIA_CHANGE 0x20
/* ATA command definitions not in <linux/hdreg.h> */
#define ATA_COMMAND_GET_MEDIA_STATUS 0xDA
#define ATA_COMMAND_MEDIA_EJECT 0xED
/* ATA drive control definitions */
#define ATA_DC_DISABLE_INTERRUPTS 0x02
#define ATA_DC_RESET_CONTROLLER 0x04
#define ATA_DC_REENABLE_CONTROLLER 0x00
/*
* General purpose return codes
*/
#define ISD200_ERROR -1
#define ISD200_GOOD 0
/*
* Transport return codes
*/
#define ISD200_TRANSPORT_GOOD 0 /* Transport good, command good */
#define ISD200_TRANSPORT_FAILED 1 /* Transport good, command failed */
#define ISD200_TRANSPORT_ERROR 2 /* Transport bad (i.e. device dead) */
/* driver action codes */
#define ACTION_READ_STATUS 0
#define ACTION_RESET 1
#define ACTION_REENABLE 2
#define ACTION_SOFT_RESET 3
#define ACTION_ENUM 4
#define ACTION_IDENTIFY 5
/*
* ata_cdb struct
*/
union ata_cdb {
struct {
unsigned char SignatureByte0;
unsigned char SignatureByte1;
unsigned char ActionSelect;
unsigned char RegisterSelect;
unsigned char TransferBlockSize;
unsigned char WriteData3F6;
unsigned char WriteData1F1;
unsigned char WriteData1F2;
unsigned char WriteData1F3;
unsigned char WriteData1F4;
unsigned char WriteData1F5;
unsigned char WriteData1F6;
unsigned char WriteData1F7;
unsigned char Reserved[3];
} generic;
struct {
unsigned char SignatureByte0;
unsigned char SignatureByte1;
unsigned char ActionSelect;
unsigned char RegisterSelect;
unsigned char TransferBlockSize;
unsigned char AlternateStatusByte;
unsigned char ErrorByte;
unsigned char SectorCountByte;
unsigned char SectorNumberByte;
unsigned char CylinderLowByte;
unsigned char CylinderHighByte;
unsigned char DeviceHeadByte;
unsigned char StatusByte;
unsigned char Reserved[3];
} read;
struct {
unsigned char SignatureByte0;
unsigned char SignatureByte1;
unsigned char ActionSelect;
unsigned char RegisterSelect;
unsigned char TransferBlockSize;
unsigned char DeviceControlByte;
unsigned char FeaturesByte;
unsigned char SectorCountByte;
unsigned char SectorNumberByte;
unsigned char CylinderLowByte;
unsigned char CylinderHighByte;
unsigned char DeviceHeadByte;
unsigned char CommandByte;
unsigned char Reserved[3];
} write;
};
/*
* Inquiry data structure. This is the data returned from the target
* after it receives an inquiry.
*
* This structure may be extended by the number of bytes specified
* in the field AdditionalLength. The defined size constant only
* includes fields through ProductRevisionLevel.
*/
/*
* DeviceType field
*/
#define DIRECT_ACCESS_DEVICE 0x00 /* disks */
#define DEVICE_REMOVABLE 0x80
struct inquiry_data {
unsigned char DeviceType;
unsigned char DeviceTypeModifier;
unsigned char Versions;
unsigned char Format;
unsigned char AdditionalLength;
unsigned char Reserved[2];
unsigned char Capability;
unsigned char VendorId[8];
unsigned char ProductId[16];
unsigned char ProductRevisionLevel[4];
unsigned char VendorSpecific[20];
unsigned char Reserved3[40];
} __attribute__ ((packed));
/*
* INQUIRY data buffer size
*/
#define INQUIRYDATABUFFERSIZE 36
/*
* ISD200 CONFIG data struct
*/
#define ATACFG_TIMING 0x0f
#define ATACFG_ATAPI_RESET 0x10
#define ATACFG_MASTER 0x20
#define ATACFG_BLOCKSIZE 0xa0
#define ATACFGE_LAST_LUN 0x07
#define ATACFGE_DESC_OVERRIDE 0x08
#define ATACFGE_STATE_SUSPEND 0x10
#define ATACFGE_SKIP_BOOT 0x20
#define ATACFGE_CONF_DESC2 0x40
#define ATACFGE_INIT_STATUS 0x80
#define CFG_CAPABILITY_SRST 0x01
struct isd200_config {
unsigned char EventNotification;
unsigned char ExternalClock;
unsigned char ATAInitTimeout;
unsigned char ATAConfig;
unsigned char ATAMajorCommand;
unsigned char ATAMinorCommand;
unsigned char ATAExtraConfig;
unsigned char Capability;
}__attribute__ ((packed));
/*
* ISD200 driver information struct
*/
struct isd200_info {
struct inquiry_data InquiryData;
u16 *id;
struct isd200_config ConfigData;
unsigned char *RegsBuf;
unsigned char ATARegs[8];
unsigned char DeviceHead;
unsigned char DeviceFlags;
/* maximum number of LUNs supported */
unsigned char MaxLUNs;
unsigned char cmnd[BLK_MAX_CDB];
struct scsi_cmnd srb;
struct scatterlist sg;
};
/*
* Read Capacity Data - returned in Big Endian format
*/
struct read_capacity_data {
__be32 LogicalBlockAddress;
__be32 BytesPerBlock;
};
/*
* Read Block Limits Data - returned in Big Endian format
* This structure returns the maximum and minimum block
* size for a TAPE device.
*/
struct read_block_limits {
unsigned char Reserved;
unsigned char BlockMaximumSize[3];
unsigned char BlockMinimumSize[2];
};
/*
* Sense Data Format
*/
#define SENSE_ERRCODE 0x7f
#define SENSE_ERRCODE_VALID 0x80
#define SENSE_FLAG_SENSE_KEY 0x0f
#define SENSE_FLAG_BAD_LENGTH 0x20
#define SENSE_FLAG_END_OF_MEDIA 0x40
#define SENSE_FLAG_FILE_MARK 0x80
struct sense_data {
unsigned char ErrorCode;
unsigned char SegmentNumber;
unsigned char Flags;
unsigned char Information[4];
unsigned char AdditionalSenseLength;
unsigned char CommandSpecificInformation[4];
unsigned char AdditionalSenseCode;
unsigned char AdditionalSenseCodeQualifier;
unsigned char FieldReplaceableUnitCode;
unsigned char SenseKeySpecific[3];
} __attribute__ ((packed));
/*
* Default request sense buffer size
*/
#define SENSE_BUFFER_SIZE 18
/***********************************************************************
* Helper routines
***********************************************************************/
/**************************************************************************
* isd200_build_sense
*
* Builds an artificial sense buffer to report the results of a
* failed command.
*
* RETURNS:
* void
*/
static void isd200_build_sense(struct us_data *us, struct scsi_cmnd *srb)
{
struct isd200_info *info = (struct isd200_info *)us->extra;
struct sense_data *buf = (struct sense_data *) &srb->sense_buffer[0];
unsigned char error = info->ATARegs[ATA_REG_ERROR_OFFSET];
if(error & ATA_ERROR_MEDIA_CHANGE) {
buf->ErrorCode = 0x70 | SENSE_ERRCODE_VALID;
buf->AdditionalSenseLength = 0xb;
buf->Flags = UNIT_ATTENTION;
buf->AdditionalSenseCode = 0;
buf->AdditionalSenseCodeQualifier = 0;
} else if (error & ATA_MCR) {
buf->ErrorCode = 0x70 | SENSE_ERRCODE_VALID;
buf->AdditionalSenseLength = 0xb;
buf->Flags = UNIT_ATTENTION;
buf->AdditionalSenseCode = 0;
buf->AdditionalSenseCodeQualifier = 0;
} else if (error & ATA_TRK0NF) {
buf->ErrorCode = 0x70 | SENSE_ERRCODE_VALID;
buf->AdditionalSenseLength = 0xb;
buf->Flags = NOT_READY;
buf->AdditionalSenseCode = 0;
buf->AdditionalSenseCodeQualifier = 0;
} else if (error & ATA_UNC) {
buf->ErrorCode = 0x70 | SENSE_ERRCODE_VALID;
buf->AdditionalSenseLength = 0xb;
buf->Flags = DATA_PROTECT;
buf->AdditionalSenseCode = 0;
buf->AdditionalSenseCodeQualifier = 0;
} else {
buf->ErrorCode = 0;
buf->AdditionalSenseLength = 0;
buf->Flags = 0;
buf->AdditionalSenseCode = 0;
buf->AdditionalSenseCodeQualifier = 0;
}
}
/***********************************************************************
* Transport routines
***********************************************************************/
/**************************************************************************
* isd200_set_srb(), isd200_srb_set_bufflen()
*
* Two helpers to facilitate in initialization of scsi_cmnd structure
* Will need to change when struct scsi_cmnd changes
*/
static void isd200_set_srb(struct isd200_info *info,
enum dma_data_direction dir, void* buff, unsigned bufflen)
{
struct scsi_cmnd *srb = &info->srb;
if (buff)
sg_init_one(&info->sg, buff, bufflen);
srb->sc_data_direction = dir;
srb->sdb.table.sgl = buff ? &info->sg : NULL;
srb->sdb.length = bufflen;
srb->sdb.table.nents = buff ? 1 : 0;
}
static void isd200_srb_set_bufflen(struct scsi_cmnd *srb, unsigned bufflen)
{
srb->sdb.length = bufflen;
}
/**************************************************************************
* isd200_action
*
* Routine for sending commands to the isd200
*
* RETURNS:
* ISD status code
*/
static int isd200_action( struct us_data *us, int action,
void* pointer, int value )
{
union ata_cdb ata;
/* static to prevent this large struct being placed on the valuable stack */
static struct scsi_device srb_dev;
struct isd200_info *info = (struct isd200_info *)us->extra;
struct scsi_cmnd *srb = &info->srb;
int status;
memset(&ata, 0, sizeof(ata));
srb->cmnd = info->cmnd;
srb->device = &srb_dev;
ata.generic.SignatureByte0 = info->ConfigData.ATAMajorCommand;
ata.generic.SignatureByte1 = info->ConfigData.ATAMinorCommand;
ata.generic.TransferBlockSize = 1;
switch ( action ) {
case ACTION_READ_STATUS:
usb_stor_dbg(us, " isd200_action(READ_STATUS)\n");
ata.generic.ActionSelect = ACTION_SELECT_0|ACTION_SELECT_2;
ata.generic.RegisterSelect =
REG_CYLINDER_LOW | REG_CYLINDER_HIGH |
REG_STATUS | REG_ERROR;
isd200_set_srb(info, DMA_FROM_DEVICE, pointer, value);
break;
case ACTION_ENUM:
usb_stor_dbg(us, " isd200_action(ENUM,0x%02x)\n", value);
ata.generic.ActionSelect = ACTION_SELECT_1|ACTION_SELECT_2|
ACTION_SELECT_3|ACTION_SELECT_4|
ACTION_SELECT_5;
ata.generic.RegisterSelect = REG_DEVICE_HEAD;
ata.write.DeviceHeadByte = value;
isd200_set_srb(info, DMA_NONE, NULL, 0);
break;
case ACTION_RESET:
usb_stor_dbg(us, " isd200_action(RESET)\n");
ata.generic.ActionSelect = ACTION_SELECT_1|ACTION_SELECT_2|
ACTION_SELECT_3|ACTION_SELECT_4;
ata.generic.RegisterSelect = REG_DEVICE_CONTROL;
ata.write.DeviceControlByte = ATA_DC_RESET_CONTROLLER;
isd200_set_srb(info, DMA_NONE, NULL, 0);
break;
case ACTION_REENABLE:
usb_stor_dbg(us, " isd200_action(REENABLE)\n");
ata.generic.ActionSelect = ACTION_SELECT_1|ACTION_SELECT_2|
ACTION_SELECT_3|ACTION_SELECT_4;
ata.generic.RegisterSelect = REG_DEVICE_CONTROL;
ata.write.DeviceControlByte = ATA_DC_REENABLE_CONTROLLER;
isd200_set_srb(info, DMA_NONE, NULL, 0);
break;
case ACTION_SOFT_RESET:
usb_stor_dbg(us, " isd200_action(SOFT_RESET)\n");
ata.generic.ActionSelect = ACTION_SELECT_1|ACTION_SELECT_5;
ata.generic.RegisterSelect = REG_DEVICE_HEAD | REG_COMMAND;
ata.write.DeviceHeadByte = info->DeviceHead;
ata.write.CommandByte = ATA_CMD_DEV_RESET;
isd200_set_srb(info, DMA_NONE, NULL, 0);
break;
case ACTION_IDENTIFY:
usb_stor_dbg(us, " isd200_action(IDENTIFY)\n");
ata.generic.RegisterSelect = REG_COMMAND;
ata.write.CommandByte = ATA_CMD_ID_ATA;
isd200_set_srb(info, DMA_FROM_DEVICE, info->id,
ATA_ID_WORDS * 2);
break;
default:
usb_stor_dbg(us, "Error: Undefined action %d\n", action);
return ISD200_ERROR;
}
memcpy(srb->cmnd, &ata, sizeof(ata.generic));
srb->cmd_len = sizeof(ata.generic);
status = usb_stor_Bulk_transport(srb, us);
if (status == USB_STOR_TRANSPORT_GOOD)
status = ISD200_GOOD;
else {
usb_stor_dbg(us, " isd200_action(0x%02x) error: %d\n",
action, status);
status = ISD200_ERROR;
/* need to reset device here */
}
return status;
}
/**************************************************************************
* isd200_read_regs
*
* Read ATA Registers
*
* RETURNS:
* ISD status code
*/
static int isd200_read_regs( struct us_data *us )
{
struct isd200_info *info = (struct isd200_info *)us->extra;
int retStatus = ISD200_GOOD;
int transferStatus;
usb_stor_dbg(us, "Entering isd200_IssueATAReadRegs\n");
transferStatus = isd200_action( us, ACTION_READ_STATUS,
info->RegsBuf, sizeof(info->ATARegs) );
if (transferStatus != ISD200_TRANSPORT_GOOD) {
usb_stor_dbg(us, " Error reading ATA registers\n");
retStatus = ISD200_ERROR;
} else {
memcpy(info->ATARegs, info->RegsBuf, sizeof(info->ATARegs));
usb_stor_dbg(us, " Got ATA Register[ATA_REG_ERROR_OFFSET] = 0x%x\n",
info->ATARegs[ATA_REG_ERROR_OFFSET]);
}
return retStatus;
}
/**************************************************************************
* Invoke the transport and basic error-handling/recovery methods
*
* This is used by the protocol layers to actually send the message to
* the device and receive the response.
*/
static void isd200_invoke_transport( struct us_data *us,
struct scsi_cmnd *srb,
union ata_cdb *ataCdb )
{
int need_auto_sense = 0;
int transferStatus;
int result;
/* send the command to the transport layer */
memcpy(srb->cmnd, ataCdb, sizeof(ataCdb->generic));
srb->cmd_len = sizeof(ataCdb->generic);
transferStatus = usb_stor_Bulk_transport(srb, us);
/* if the command gets aborted by the higher layers, we need to
* short-circuit all other processing
*/
if (test_bit(US_FLIDX_TIMED_OUT, &us->dflags)) {
usb_stor_dbg(us, "-- command was aborted\n");
goto Handle_Abort;
}
switch (transferStatus) {
case USB_STOR_TRANSPORT_GOOD:
/* Indicate a good result */
srb->result = SAM_STAT_GOOD;
break;
case USB_STOR_TRANSPORT_NO_SENSE:
usb_stor_dbg(us, "-- transport indicates protocol failure\n");
srb->result = SAM_STAT_CHECK_CONDITION;
return;
case USB_STOR_TRANSPORT_FAILED:
usb_stor_dbg(us, "-- transport indicates command failure\n");
need_auto_sense = 1;
break;
case USB_STOR_TRANSPORT_ERROR:
usb_stor_dbg(us, "-- transport indicates transport error\n");
srb->result = DID_ERROR << 16;
/* Need reset here */
return;
default:
usb_stor_dbg(us, "-- transport indicates unknown error\n");
srb->result = DID_ERROR << 16;
/* Need reset here */
return;
}
if ((scsi_get_resid(srb) > 0) &&
!((srb->cmnd[0] == REQUEST_SENSE) ||
(srb->cmnd[0] == INQUIRY) ||
(srb->cmnd[0] == MODE_SENSE) ||
(srb->cmnd[0] == LOG_SENSE) ||
(srb->cmnd[0] == MODE_SENSE_10))) {
usb_stor_dbg(us, "-- unexpectedly short transfer\n");
need_auto_sense = 1;
}
if (need_auto_sense) {
result = isd200_read_regs(us);
if (test_bit(US_FLIDX_TIMED_OUT, &us->dflags)) {
usb_stor_dbg(us, "-- auto-sense aborted\n");
goto Handle_Abort;
}
if (result == ISD200_GOOD) {
isd200_build_sense(us, srb);
srb->result = SAM_STAT_CHECK_CONDITION;
/* If things are really okay, then let's show that */
if ((srb->sense_buffer[2] & 0xf) == 0x0)
srb->result = SAM_STAT_GOOD;
} else {
srb->result = DID_ERROR << 16;
/* Need reset here */
}
}
/* Regardless of auto-sense, if we _know_ we have an error
* condition, show that in the result code
*/
if (transferStatus == USB_STOR_TRANSPORT_FAILED)
srb->result = SAM_STAT_CHECK_CONDITION;
return;
/* abort processing: the bulk-only transport requires a reset
* following an abort */
Handle_Abort:
srb->result = DID_ABORT << 16;
/* permit the reset transfer to take place */
clear_bit(US_FLIDX_ABORTING, &us->dflags);
/* Need reset here */
}
#ifdef CONFIG_USB_STORAGE_DEBUG
static void isd200_log_config(struct us_data *us, struct isd200_info *info)
{
usb_stor_dbg(us, " Event Notification: 0x%x\n",
info->ConfigData.EventNotification);
usb_stor_dbg(us, " External Clock: 0x%x\n",
info->ConfigData.ExternalClock);
usb_stor_dbg(us, " ATA Init Timeout: 0x%x\n",
info->ConfigData.ATAInitTimeout);
usb_stor_dbg(us, " ATAPI Command Block Size: 0x%x\n",
(info->ConfigData.ATAConfig & ATACFG_BLOCKSIZE) >> 6);
usb_stor_dbg(us, " Master/Slave Selection: 0x%x\n",
info->ConfigData.ATAConfig & ATACFG_MASTER);
usb_stor_dbg(us, " ATAPI Reset: 0x%x\n",
info->ConfigData.ATAConfig & ATACFG_ATAPI_RESET);
usb_stor_dbg(us, " ATA Timing: 0x%x\n",
info->ConfigData.ATAConfig & ATACFG_TIMING);
usb_stor_dbg(us, " ATA Major Command: 0x%x\n",
info->ConfigData.ATAMajorCommand);
usb_stor_dbg(us, " ATA Minor Command: 0x%x\n",
info->ConfigData.ATAMinorCommand);
usb_stor_dbg(us, " Init Status: 0x%x\n",
info->ConfigData.ATAExtraConfig & ATACFGE_INIT_STATUS);
usb_stor_dbg(us, " Config Descriptor 2: 0x%x\n",
info->ConfigData.ATAExtraConfig & ATACFGE_CONF_DESC2);
usb_stor_dbg(us, " Skip Device Boot: 0x%x\n",
info->ConfigData.ATAExtraConfig & ATACFGE_SKIP_BOOT);
usb_stor_dbg(us, " ATA 3 State Suspend: 0x%x\n",
info->ConfigData.ATAExtraConfig & ATACFGE_STATE_SUSPEND);
usb_stor_dbg(us, " Descriptor Override: 0x%x\n",
info->ConfigData.ATAExtraConfig & ATACFGE_DESC_OVERRIDE);
usb_stor_dbg(us, " Last LUN Identifier: 0x%x\n",
info->ConfigData.ATAExtraConfig & ATACFGE_LAST_LUN);
usb_stor_dbg(us, " SRST Enable: 0x%x\n",
info->ConfigData.ATAExtraConfig & CFG_CAPABILITY_SRST);
}
#endif
/**************************************************************************
* isd200_write_config
*
* Write the ISD200 Configuration data
*
* RETURNS:
* ISD status code
*/
static int isd200_write_config( struct us_data *us )
{
struct isd200_info *info = (struct isd200_info *)us->extra;
int retStatus = ISD200_GOOD;
int result;
#ifdef CONFIG_USB_STORAGE_DEBUG
usb_stor_dbg(us, "Entering isd200_write_config\n");
usb_stor_dbg(us, " Writing the following ISD200 Config Data:\n");
isd200_log_config(us, info);
#endif
/* let's send the command via the control pipe */
result = usb_stor_ctrl_transfer(
us,
us->send_ctrl_pipe,
0x01,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT,
0x0000,
0x0002,
(void *) &info->ConfigData,
sizeof(info->ConfigData));
if (result >= 0) {
usb_stor_dbg(us, " ISD200 Config Data was written successfully\n");
} else {
usb_stor_dbg(us, " Request to write ISD200 Config Data failed!\n");
retStatus = ISD200_ERROR;
}
usb_stor_dbg(us, "Leaving isd200_write_config %08X\n", retStatus);
return retStatus;
}
/**************************************************************************
* isd200_read_config
*
* Reads the ISD200 Configuration data
*
* RETURNS:
* ISD status code
*/
static int isd200_read_config( struct us_data *us )
{
struct isd200_info *info = (struct isd200_info *)us->extra;
int retStatus = ISD200_GOOD;
int result;
usb_stor_dbg(us, "Entering isd200_read_config\n");
/* read the configuration information from ISD200. Use this to */
/* determine what the special ATA CDB bytes are. */
result = usb_stor_ctrl_transfer(
us,
us->recv_ctrl_pipe,
0x02,
USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
0x0000,
0x0002,
(void *) &info->ConfigData,
sizeof(info->ConfigData));
if (result >= 0) {
usb_stor_dbg(us, " Retrieved the following ISD200 Config Data:\n");
#ifdef CONFIG_USB_STORAGE_DEBUG
isd200_log_config(us, info);
#endif
} else {
usb_stor_dbg(us, " Request to get ISD200 Config Data failed!\n");
retStatus = ISD200_ERROR;
}
usb_stor_dbg(us, "Leaving isd200_read_config %08X\n", retStatus);
return retStatus;
}
/**************************************************************************
* isd200_atapi_soft_reset
*
* Perform an Atapi Soft Reset on the device
*
* RETURNS:
* NT status code
*/
static int isd200_atapi_soft_reset( struct us_data *us )
{
int retStatus = ISD200_GOOD;
int transferStatus;
usb_stor_dbg(us, "Entering isd200_atapi_soft_reset\n");
transferStatus = isd200_action( us, ACTION_SOFT_RESET, NULL, 0 );
if (transferStatus != ISD200_TRANSPORT_GOOD) {
usb_stor_dbg(us, " Error issuing Atapi Soft Reset\n");
retStatus = ISD200_ERROR;
}
usb_stor_dbg(us, "Leaving isd200_atapi_soft_reset %08X\n", retStatus);
return retStatus;
}
/**************************************************************************
* isd200_srst
*
* Perform an SRST on the device
*
* RETURNS:
* ISD status code
*/
static int isd200_srst( struct us_data *us )
{
int retStatus = ISD200_GOOD;
int transferStatus;
usb_stor_dbg(us, "Entering isd200_SRST\n");
transferStatus = isd200_action( us, ACTION_RESET, NULL, 0 );
/* check to see if this request failed */
if (transferStatus != ISD200_TRANSPORT_GOOD) {
usb_stor_dbg(us, " Error issuing SRST\n");
retStatus = ISD200_ERROR;
} else {
/* delay 10ms to give the drive a chance to see it */
msleep(10);
transferStatus = isd200_action( us, ACTION_REENABLE, NULL, 0 );
if (transferStatus != ISD200_TRANSPORT_GOOD) {
usb_stor_dbg(us, " Error taking drive out of reset\n");
retStatus = ISD200_ERROR;
} else {
/* delay 50ms to give the drive a chance to recover after SRST */
msleep(50);
}
}
usb_stor_dbg(us, "Leaving isd200_srst %08X\n", retStatus);
return retStatus;
}
/**************************************************************************
* isd200_try_enum
*
* Helper function for isd200_manual_enum(). Does ENUM and READ_STATUS
* and tries to analyze the status registers
*
* RETURNS:
* ISD status code
*/
static int isd200_try_enum(struct us_data *us, unsigned char master_slave,
int detect )
{
int status = ISD200_GOOD;
unsigned long endTime;
struct isd200_info *info = (struct isd200_info *)us->extra;
unsigned char *regs = info->RegsBuf;
int recheckAsMaster = 0;
if ( detect )
endTime = jiffies + ISD200_ENUM_DETECT_TIMEOUT * HZ;
else
endTime = jiffies + ISD200_ENUM_BSY_TIMEOUT * HZ;
/* loop until we detect !BSY or timeout */
while(1) {
status = isd200_action( us, ACTION_ENUM, NULL, master_slave );
if ( status != ISD200_GOOD )
break;
status = isd200_action( us, ACTION_READ_STATUS,
regs, 8 );
if ( status != ISD200_GOOD )
break;
if (!detect) {
if (regs[ATA_REG_STATUS_OFFSET] & ATA_BUSY) {
usb_stor_dbg(us, " %s status is still BSY, try again...\n",
master_slave == ATA_ADDRESS_DEVHEAD_STD ?
"Master" : "Slave");
} else {
usb_stor_dbg(us, " %s status !BSY, continue with next operation\n",
master_slave == ATA_ADDRESS_DEVHEAD_STD ?
"Master" : "Slave");
break;
}
}
/* check for ATA_BUSY and */
/* ATA_DF (workaround ATA Zip drive) and */
/* ATA_ERR (workaround for Archos CD-ROM) */
else if (regs[ATA_REG_STATUS_OFFSET] &
(ATA_BUSY | ATA_DF | ATA_ERR)) {
usb_stor_dbg(us, " Status indicates it is not ready, try again...\n");
}
/* check for DRDY, ATA devices set DRDY after SRST */
else if (regs[ATA_REG_STATUS_OFFSET] & ATA_DRDY) {
usb_stor_dbg(us, " Identified ATA device\n");
info->DeviceFlags |= DF_ATA_DEVICE;
info->DeviceHead = master_slave;
break;
}
/* check Cylinder High/Low to
determine if it is an ATAPI device
*/
else if (regs[ATA_REG_HCYL_OFFSET] == 0xEB &&
regs[ATA_REG_LCYL_OFFSET] == 0x14) {
/* It seems that the RICOH
MP6200A CD/RW drive will
report itself okay as a
slave when it is really a
master. So this check again
as a master device just to
make sure it doesn't report
itself okay as a master also
*/
if ((master_slave & ATA_ADDRESS_DEVHEAD_SLAVE) &&
!recheckAsMaster) {
usb_stor_dbg(us, " Identified ATAPI device as slave. Rechecking again as master\n");
recheckAsMaster = 1;
master_slave = ATA_ADDRESS_DEVHEAD_STD;
} else {
usb_stor_dbg(us, " Identified ATAPI device\n");
info->DeviceHead = master_slave;
status = isd200_atapi_soft_reset(us);
break;
}
} else {
usb_stor_dbg(us, " Not ATA, not ATAPI - Weird\n");
break;
}
/* check for timeout on this request */
if (time_after_eq(jiffies, endTime)) {
if (!detect)
usb_stor_dbg(us, " BSY check timeout, just continue with next operation...\n");
else
usb_stor_dbg(us, " Device detect timeout!\n");
break;
}
}
return status;
}
/**************************************************************************
* isd200_manual_enum
*
* Determines if the drive attached is an ATA or ATAPI and if it is a
* master or slave.
*
* RETURNS:
* ISD status code
*/
static int isd200_manual_enum(struct us_data *us)
{
struct isd200_info *info = (struct isd200_info *)us->extra;
int retStatus = ISD200_GOOD;
usb_stor_dbg(us, "Entering isd200_manual_enum\n");
retStatus = isd200_read_config(us);
if (retStatus == ISD200_GOOD) {
int isslave;
/* master or slave? */
retStatus = isd200_try_enum( us, ATA_ADDRESS_DEVHEAD_STD, 0);
if (retStatus == ISD200_GOOD)
retStatus = isd200_try_enum( us, ATA_ADDRESS_DEVHEAD_SLAVE, 0);
if (retStatus == ISD200_GOOD) {
retStatus = isd200_srst(us);
if (retStatus == ISD200_GOOD)
/* ata or atapi? */
retStatus = isd200_try_enum( us, ATA_ADDRESS_DEVHEAD_STD, 1);
}
isslave = (info->DeviceHead & ATA_ADDRESS_DEVHEAD_SLAVE) ? 1 : 0;
if (!(info->ConfigData.ATAConfig & ATACFG_MASTER)) {
usb_stor_dbg(us, " Setting Master/Slave selection to %d\n",
isslave);
info->ConfigData.ATAConfig &= 0x3f;
info->ConfigData.ATAConfig |= (isslave<<6);
retStatus = isd200_write_config(us);
}
}
usb_stor_dbg(us, "Leaving isd200_manual_enum %08X\n", retStatus);
return(retStatus);
}
static void isd200_fix_driveid(u16 *id)
{
#ifndef __LITTLE_ENDIAN
# ifdef __BIG_ENDIAN
int i;
for (i = 0; i < ATA_ID_WORDS; i++)
id[i] = __le16_to_cpu(id[i]);
# else
# error "Please fix <asm/byteorder.h>"
# endif
#endif
}
static void isd200_dump_driveid(struct us_data *us, u16 *id)
{
usb_stor_dbg(us, " Identify Data Structure:\n");
usb_stor_dbg(us, " config = 0x%x\n", id[ATA_ID_CONFIG]);
usb_stor_dbg(us, " cyls = 0x%x\n", id[ATA_ID_CYLS]);
usb_stor_dbg(us, " heads = 0x%x\n", id[ATA_ID_HEADS]);
usb_stor_dbg(us, " track_bytes = 0x%x\n", id[4]);
usb_stor_dbg(us, " sector_bytes = 0x%x\n", id[5]);
usb_stor_dbg(us, " sectors = 0x%x\n", id[ATA_ID_SECTORS]);
usb_stor_dbg(us, " serial_no[0] = 0x%x\n", *(char *)&id[ATA_ID_SERNO]);
usb_stor_dbg(us, " buf_type = 0x%x\n", id[20]);
usb_stor_dbg(us, " buf_size = 0x%x\n", id[ATA_ID_BUF_SIZE]);
usb_stor_dbg(us, " ecc_bytes = 0x%x\n", id[22]);
usb_stor_dbg(us, " fw_rev[0] = 0x%x\n", *(char *)&id[ATA_ID_FW_REV]);
usb_stor_dbg(us, " model[0] = 0x%x\n", *(char *)&id[ATA_ID_PROD]);
usb_stor_dbg(us, " max_multsect = 0x%x\n", id[ATA_ID_MAX_MULTSECT] & 0xff);
usb_stor_dbg(us, " dword_io = 0x%x\n", id[ATA_ID_DWORD_IO]);
usb_stor_dbg(us, " capability = 0x%x\n", id[ATA_ID_CAPABILITY] >> 8);
usb_stor_dbg(us, " tPIO = 0x%x\n", id[ATA_ID_OLD_PIO_MODES] >> 8);
usb_stor_dbg(us, " tDMA = 0x%x\n", id[ATA_ID_OLD_DMA_MODES] >> 8);
usb_stor_dbg(us, " field_valid = 0x%x\n", id[ATA_ID_FIELD_VALID]);
usb_stor_dbg(us, " cur_cyls = 0x%x\n", id[ATA_ID_CUR_CYLS]);
usb_stor_dbg(us, " cur_heads = 0x%x\n", id[ATA_ID_CUR_HEADS]);
usb_stor_dbg(us, " cur_sectors = 0x%x\n", id[ATA_ID_CUR_SECTORS]);
usb_stor_dbg(us, " cur_capacity = 0x%x\n", ata_id_u32(id, 57));
usb_stor_dbg(us, " multsect = 0x%x\n", id[ATA_ID_MULTSECT] & 0xff);
usb_stor_dbg(us, " lba_capacity = 0x%x\n", ata_id_u32(id, ATA_ID_LBA_CAPACITY));
usb_stor_dbg(us, " command_set_1 = 0x%x\n", id[ATA_ID_COMMAND_SET_1]);
usb_stor_dbg(us, " command_set_2 = 0x%x\n", id[ATA_ID_COMMAND_SET_2]);
}
/**************************************************************************
* isd200_get_inquiry_data
*
* Get inquiry data
*
* RETURNS:
* ISD status code
*/
static int isd200_get_inquiry_data( struct us_data *us )
{
struct isd200_info *info = (struct isd200_info *)us->extra;
int retStatus = ISD200_GOOD;
u16 *id = info->id;
usb_stor_dbg(us, "Entering isd200_get_inquiry_data\n");
/* set default to Master */
info->DeviceHead = ATA_ADDRESS_DEVHEAD_STD;
/* attempt to manually enumerate this device */
retStatus = isd200_manual_enum(us);
if (retStatus == ISD200_GOOD) {
int transferStatus;
/* check for an ATA device */
if (info->DeviceFlags & DF_ATA_DEVICE) {
/* this must be an ATA device */
/* perform an ATA Command Identify */
transferStatus = isd200_action( us, ACTION_IDENTIFY,
id, ATA_ID_WORDS * 2);
if (transferStatus != ISD200_TRANSPORT_GOOD) {
/* Error issuing ATA Command Identify */
usb_stor_dbg(us, " Error issuing ATA Command Identify\n");
retStatus = ISD200_ERROR;
} else {
/* ATA Command Identify successful */
int i;
__be16 *src;
__u16 *dest;
isd200_fix_driveid(id);
isd200_dump_driveid(us, id);
memset(&info->InquiryData, 0, sizeof(info->InquiryData));
/* Standard IDE interface only supports disks */
info->InquiryData.DeviceType = DIRECT_ACCESS_DEVICE;
/* The length must be at least 36 (5 + 31) */
info->InquiryData.AdditionalLength = 0x1F;
if (id[ATA_ID_COMMAND_SET_1] & COMMANDSET_MEDIA_STATUS) {
/* set the removable bit */
info->InquiryData.DeviceTypeModifier = DEVICE_REMOVABLE;
info->DeviceFlags |= DF_REMOVABLE_MEDIA;
}
/* Fill in vendor identification fields */
src = (__be16 *)&id[ATA_ID_PROD];
dest = (__u16*)info->InquiryData.VendorId;
for (i=0;i<4;i++)
dest[i] = be16_to_cpu(src[i]);
src = (__be16 *)&id[ATA_ID_PROD + 8/2];
dest = (__u16*)info->InquiryData.ProductId;
for (i=0;i<8;i++)
dest[i] = be16_to_cpu(src[i]);
src = (__be16 *)&id[ATA_ID_FW_REV];
dest = (__u16*)info->InquiryData.ProductRevisionLevel;
for (i=0;i<2;i++)
dest[i] = be16_to_cpu(src[i]);
/* determine if it supports Media Status Notification */
if (id[ATA_ID_COMMAND_SET_2] & COMMANDSET_MEDIA_STATUS) {
usb_stor_dbg(us, " Device supports Media Status Notification\n");
/* Indicate that it is enabled, even though it is not
* This allows the lock/unlock of the media to work
* correctly.
*/
info->DeviceFlags |= DF_MEDIA_STATUS_ENABLED;
}
else
info->DeviceFlags &= ~DF_MEDIA_STATUS_ENABLED;
}
} else {
/*
* this must be an ATAPI device
* use an ATAPI protocol (Transparent SCSI)
*/
us->protocol_name = "Transparent SCSI";
us->proto_handler = usb_stor_transparent_scsi_command;
usb_stor_dbg(us, "Protocol changed to: %s\n",
us->protocol_name);
/* Free driver structure */
us->extra_destructor(info);
kfree(info);
us->extra = NULL;
us->extra_destructor = NULL;
}
}
usb_stor_dbg(us, "Leaving isd200_get_inquiry_data %08X\n", retStatus);
return(retStatus);
}
/**************************************************************************
* isd200_scsi_to_ata
*
* Translate SCSI commands to ATA commands.
*
* RETURNS:
* 1 if the command needs to be sent to the transport layer
* 0 otherwise
*/
static int isd200_scsi_to_ata(struct scsi_cmnd *srb, struct us_data *us,
union ata_cdb * ataCdb)
{
struct isd200_info *info = (struct isd200_info *)us->extra;
u16 *id = info->id;
int sendToTransport = 1;
unsigned char sectnum, head;
unsigned short cylinder;
unsigned long lba;
unsigned long blockCount;
unsigned char senseData[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
memset(ataCdb, 0, sizeof(union ata_cdb));
/* SCSI Command */
switch (srb->cmnd[0]) {
case INQUIRY:
usb_stor_dbg(us, " ATA OUT - INQUIRY\n");
/* copy InquiryData */
usb_stor_set_xfer_buf((unsigned char *) &info->InquiryData,
sizeof(info->InquiryData), srb);
srb->result = SAM_STAT_GOOD;
sendToTransport = 0;
break;
case MODE_SENSE:
usb_stor_dbg(us, " ATA OUT - SCSIOP_MODE_SENSE\n");
/* Initialize the return buffer */
usb_stor_set_xfer_buf(senseData, sizeof(senseData), srb);
if (info->DeviceFlags & DF_MEDIA_STATUS_ENABLED)
{
ataCdb->generic.SignatureByte0 = info->ConfigData.ATAMajorCommand;
ataCdb->generic.SignatureByte1 = info->ConfigData.ATAMinorCommand;
ataCdb->generic.TransferBlockSize = 1;
ataCdb->generic.RegisterSelect = REG_COMMAND;
ataCdb->write.CommandByte = ATA_COMMAND_GET_MEDIA_STATUS;
isd200_srb_set_bufflen(srb, 0);
} else {
usb_stor_dbg(us, " Media Status not supported, just report okay\n");
srb->result = SAM_STAT_GOOD;
sendToTransport = 0;
}
break;
case TEST_UNIT_READY:
usb_stor_dbg(us, " ATA OUT - SCSIOP_TEST_UNIT_READY\n");
if (info->DeviceFlags & DF_MEDIA_STATUS_ENABLED)
{
ataCdb->generic.SignatureByte0 = info->ConfigData.ATAMajorCommand;
ataCdb->generic.SignatureByte1 = info->ConfigData.ATAMinorCommand;
ataCdb->generic.TransferBlockSize = 1;
ataCdb->generic.RegisterSelect = REG_COMMAND;
ataCdb->write.CommandByte = ATA_COMMAND_GET_MEDIA_STATUS;
isd200_srb_set_bufflen(srb, 0);
} else {
usb_stor_dbg(us, " Media Status not supported, just report okay\n");
srb->result = SAM_STAT_GOOD;
sendToTransport = 0;
}
break;
case READ_CAPACITY:
{
unsigned long capacity;
struct read_capacity_data readCapacityData;
usb_stor_dbg(us, " ATA OUT - SCSIOP_READ_CAPACITY\n");
if (ata_id_has_lba(id))
capacity = ata_id_u32(id, ATA_ID_LBA_CAPACITY) - 1;
else
capacity = (id[ATA_ID_HEADS] * id[ATA_ID_CYLS] *
id[ATA_ID_SECTORS]) - 1;
readCapacityData.LogicalBlockAddress = cpu_to_be32(capacity);
readCapacityData.BytesPerBlock = cpu_to_be32(0x200);
usb_stor_set_xfer_buf((unsigned char *) &readCapacityData,
sizeof(readCapacityData), srb);
srb->result = SAM_STAT_GOOD;
sendToTransport = 0;
}
break;
case READ_10:
usb_stor_dbg(us, " ATA OUT - SCSIOP_READ\n");
lba = be32_to_cpu(*(__be32 *)&srb->cmnd[2]);
blockCount = (unsigned long)srb->cmnd[7]<<8 | (unsigned long)srb->cmnd[8];
if (ata_id_has_lba(id)) {
sectnum = (unsigned char)(lba);
cylinder = (unsigned short)(lba>>8);
head = ATA_ADDRESS_DEVHEAD_LBA_MODE | (unsigned char)(lba>>24 & 0x0F);
} else {
sectnum = (u8)((lba % id[ATA_ID_SECTORS]) + 1);
cylinder = (u16)(lba / (id[ATA_ID_SECTORS] *
id[ATA_ID_HEADS]));
head = (u8)((lba / id[ATA_ID_SECTORS]) %
id[ATA_ID_HEADS]);
}
ataCdb->generic.SignatureByte0 = info->ConfigData.ATAMajorCommand;
ataCdb->generic.SignatureByte1 = info->ConfigData.ATAMinorCommand;
ataCdb->generic.TransferBlockSize = 1;
ataCdb->generic.RegisterSelect =
REG_SECTOR_COUNT | REG_SECTOR_NUMBER |
REG_CYLINDER_LOW | REG_CYLINDER_HIGH |
REG_DEVICE_HEAD | REG_COMMAND;
ataCdb->write.SectorCountByte = (unsigned char)blockCount;
ataCdb->write.SectorNumberByte = sectnum;
ataCdb->write.CylinderHighByte = (unsigned char)(cylinder>>8);
ataCdb->write.CylinderLowByte = (unsigned char)cylinder;
ataCdb->write.DeviceHeadByte = (head | ATA_ADDRESS_DEVHEAD_STD);
ataCdb->write.CommandByte = ATA_CMD_PIO_READ;
break;
case WRITE_10:
usb_stor_dbg(us, " ATA OUT - SCSIOP_WRITE\n");
lba = be32_to_cpu(*(__be32 *)&srb->cmnd[2]);
blockCount = (unsigned long)srb->cmnd[7]<<8 | (unsigned long)srb->cmnd[8];
if (ata_id_has_lba(id)) {
sectnum = (unsigned char)(lba);
cylinder = (unsigned short)(lba>>8);
head = ATA_ADDRESS_DEVHEAD_LBA_MODE | (unsigned char)(lba>>24 & 0x0F);
} else {
sectnum = (u8)((lba % id[ATA_ID_SECTORS]) + 1);
cylinder = (u16)(lba / (id[ATA_ID_SECTORS] *
id[ATA_ID_HEADS]));
head = (u8)((lba / id[ATA_ID_SECTORS]) %
id[ATA_ID_HEADS]);
}
ataCdb->generic.SignatureByte0 = info->ConfigData.ATAMajorCommand;
ataCdb->generic.SignatureByte1 = info->ConfigData.ATAMinorCommand;
ataCdb->generic.TransferBlockSize = 1;
ataCdb->generic.RegisterSelect =
REG_SECTOR_COUNT | REG_SECTOR_NUMBER |
REG_CYLINDER_LOW | REG_CYLINDER_HIGH |
REG_DEVICE_HEAD | REG_COMMAND;
ataCdb->write.SectorCountByte = (unsigned char)blockCount;
ataCdb->write.SectorNumberByte = sectnum;
ataCdb->write.CylinderHighByte = (unsigned char)(cylinder>>8);
ataCdb->write.CylinderLowByte = (unsigned char)cylinder;
ataCdb->write.DeviceHeadByte = (head | ATA_ADDRESS_DEVHEAD_STD);
ataCdb->write.CommandByte = ATA_CMD_PIO_WRITE;
break;
case ALLOW_MEDIUM_REMOVAL:
usb_stor_dbg(us, " ATA OUT - SCSIOP_MEDIUM_REMOVAL\n");
if (info->DeviceFlags & DF_REMOVABLE_MEDIA) {
usb_stor_dbg(us, " srb->cmnd[4] = 0x%X\n",
srb->cmnd[4]);
ataCdb->generic.SignatureByte0 = info->ConfigData.ATAMajorCommand;
ataCdb->generic.SignatureByte1 = info->ConfigData.ATAMinorCommand;
ataCdb->generic.TransferBlockSize = 1;
ataCdb->generic.RegisterSelect = REG_COMMAND;
ataCdb->write.CommandByte = (srb->cmnd[4] & 0x1) ?
ATA_CMD_MEDIA_LOCK : ATA_CMD_MEDIA_UNLOCK;
isd200_srb_set_bufflen(srb, 0);
} else {
usb_stor_dbg(us, " Not removeable media, just report okay\n");
srb->result = SAM_STAT_GOOD;
sendToTransport = 0;
}
break;
case START_STOP:
usb_stor_dbg(us, " ATA OUT - SCSIOP_START_STOP_UNIT\n");
usb_stor_dbg(us, " srb->cmnd[4] = 0x%X\n", srb->cmnd[4]);
if ((srb->cmnd[4] & 0x3) == 0x2) {
usb_stor_dbg(us, " Media Eject\n");
ataCdb->generic.SignatureByte0 = info->ConfigData.ATAMajorCommand;
ataCdb->generic.SignatureByte1 = info->ConfigData.ATAMinorCommand;
ataCdb->generic.TransferBlockSize = 0;
ataCdb->generic.RegisterSelect = REG_COMMAND;
ataCdb->write.CommandByte = ATA_COMMAND_MEDIA_EJECT;
} else if ((srb->cmnd[4] & 0x3) == 0x1) {
usb_stor_dbg(us, " Get Media Status\n");
ataCdb->generic.SignatureByte0 = info->ConfigData.ATAMajorCommand;
ataCdb->generic.SignatureByte1 = info->ConfigData.ATAMinorCommand;
ataCdb->generic.TransferBlockSize = 1;
ataCdb->generic.RegisterSelect = REG_COMMAND;
ataCdb->write.CommandByte = ATA_COMMAND_GET_MEDIA_STATUS;
isd200_srb_set_bufflen(srb, 0);
} else {
usb_stor_dbg(us, " Nothing to do, just report okay\n");
srb->result = SAM_STAT_GOOD;
sendToTransport = 0;
}
break;
default:
usb_stor_dbg(us, "Unsupported SCSI command - 0x%X\n",
srb->cmnd[0]);
srb->result = DID_ERROR << 16;
sendToTransport = 0;
break;
}
return(sendToTransport);
}
/**************************************************************************
* isd200_free_info
*
* Frees the driver structure.
*/
static void isd200_free_info_ptrs(void *info_)
{
struct isd200_info *info = (struct isd200_info *) info_;
if (info) {
kfree(info->id);
kfree(info->RegsBuf);
kfree(info->srb.sense_buffer);
}
}
/**************************************************************************
* isd200_init_info
*
* Allocates (if necessary) and initializes the driver structure.
*
* RETURNS:
* ISD status code
*/
static int isd200_init_info(struct us_data *us)
{
int retStatus = ISD200_GOOD;
struct isd200_info *info;
info = kzalloc(sizeof(struct isd200_info), GFP_KERNEL);
if (!info)
retStatus = ISD200_ERROR;
else {
info->id = kzalloc(ATA_ID_WORDS * 2, GFP_KERNEL);
info->RegsBuf = kmalloc(sizeof(info->ATARegs), GFP_KERNEL);
info->srb.sense_buffer =
kmalloc(SCSI_SENSE_BUFFERSIZE, GFP_KERNEL);
if (!info->id || !info->RegsBuf || !info->srb.sense_buffer) {
isd200_free_info_ptrs(info);
kfree(info);
retStatus = ISD200_ERROR;
}
}
if (retStatus == ISD200_GOOD) {
us->extra = info;
us->extra_destructor = isd200_free_info_ptrs;
}
return retStatus;
}
/**************************************************************************
* Initialization for the ISD200
*/
static int isd200_Initialization(struct us_data *us)
{
usb_stor_dbg(us, "ISD200 Initialization...\n");
/* Initialize ISD200 info struct */
if (isd200_init_info(us) == ISD200_ERROR) {
usb_stor_dbg(us, "ERROR Initializing ISD200 Info struct\n");
} else {
/* Get device specific data */
if (isd200_get_inquiry_data(us) != ISD200_GOOD)
usb_stor_dbg(us, "ISD200 Initialization Failure\n");
else
usb_stor_dbg(us, "ISD200 Initialization complete\n");
}
return 0;
}
/**************************************************************************
* Protocol and Transport for the ISD200 ASIC
*
* This protocol and transport are for ATA devices connected to an ISD200
* ASIC. An ATAPI device that is connected as a slave device will be
* detected in the driver initialization function and the protocol will
* be changed to an ATAPI protocol (Transparent SCSI).
*
*/
static void isd200_ata_command(struct scsi_cmnd *srb, struct us_data *us)
{
int sendToTransport = 1, orig_bufflen;
union ata_cdb ataCdb;
/* Make sure driver was initialized */
if (us->extra == NULL)
usb_stor_dbg(us, "ERROR Driver not initialized\n");
scsi_set_resid(srb, 0);
/* scsi_bufflen might change in protocol translation to ata */
orig_bufflen = scsi_bufflen(srb);
sendToTransport = isd200_scsi_to_ata(srb, us, &ataCdb);
/* send the command to the transport layer */
if (sendToTransport)
isd200_invoke_transport(us, srb, &ataCdb);
isd200_srb_set_bufflen(srb, orig_bufflen);
}
static struct scsi_host_template isd200_host_template;
static int isd200_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct us_data *us;
int result;
result = usb_stor_probe1(&us, intf, id,
(id - isd200_usb_ids) + isd200_unusual_dev_list,
&isd200_host_template);
if (result)
return result;
us->protocol_name = "ISD200 ATA/ATAPI";
us->proto_handler = isd200_ata_command;
result = usb_stor_probe2(us);
return result;
}
static struct usb_driver isd200_driver = {
.name = DRV_NAME,
.probe = isd200_probe,
.disconnect = usb_stor_disconnect,
.suspend = usb_stor_suspend,
.resume = usb_stor_resume,
.reset_resume = usb_stor_reset_resume,
.pre_reset = usb_stor_pre_reset,
.post_reset = usb_stor_post_reset,
.id_table = isd200_usb_ids,
.soft_unbind = 1,
.no_dynamic_id = 1,
};
module_usb_stor_driver(isd200_driver, isd200_host_template, DRV_NAME);
| gpl-2.0 |
gilelad/linux | drivers/gpu/drm/nouveau/nv50_fbcon.c | 393 | 7022 | /*
* Copyright 2010 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Ben Skeggs
*/
#include "nouveau_drm.h"
#include "nouveau_dma.h"
#include "nouveau_fbcon.h"
int
nv50_fbcon_fillrect(struct fb_info *info, const struct fb_fillrect *rect)
{
struct nouveau_fbdev *nfbdev = info->par;
struct nouveau_drm *drm = nouveau_drm(nfbdev->dev);
struct nouveau_channel *chan = drm->channel;
int ret;
ret = RING_SPACE(chan, rect->rop == ROP_COPY ? 7 : 11);
if (ret)
return ret;
if (rect->rop != ROP_COPY) {
BEGIN_NV04(chan, NvSub2D, 0x02ac, 1);
OUT_RING(chan, 1);
}
BEGIN_NV04(chan, NvSub2D, 0x0588, 1);
if (info->fix.visual == FB_VISUAL_TRUECOLOR ||
info->fix.visual == FB_VISUAL_DIRECTCOLOR)
OUT_RING(chan, ((uint32_t *)info->pseudo_palette)[rect->color]);
else
OUT_RING(chan, rect->color);
BEGIN_NV04(chan, NvSub2D, 0x0600, 4);
OUT_RING(chan, rect->dx);
OUT_RING(chan, rect->dy);
OUT_RING(chan, rect->dx + rect->width);
OUT_RING(chan, rect->dy + rect->height);
if (rect->rop != ROP_COPY) {
BEGIN_NV04(chan, NvSub2D, 0x02ac, 1);
OUT_RING(chan, 3);
}
FIRE_RING(chan);
return 0;
}
int
nv50_fbcon_copyarea(struct fb_info *info, const struct fb_copyarea *region)
{
struct nouveau_fbdev *nfbdev = info->par;
struct nouveau_drm *drm = nouveau_drm(nfbdev->dev);
struct nouveau_channel *chan = drm->channel;
int ret;
ret = RING_SPACE(chan, 12);
if (ret)
return ret;
BEGIN_NV04(chan, NvSub2D, 0x0110, 1);
OUT_RING(chan, 0);
BEGIN_NV04(chan, NvSub2D, 0x08b0, 4);
OUT_RING(chan, region->dx);
OUT_RING(chan, region->dy);
OUT_RING(chan, region->width);
OUT_RING(chan, region->height);
BEGIN_NV04(chan, NvSub2D, 0x08d0, 4);
OUT_RING(chan, 0);
OUT_RING(chan, region->sx);
OUT_RING(chan, 0);
OUT_RING(chan, region->sy);
FIRE_RING(chan);
return 0;
}
int
nv50_fbcon_imageblit(struct fb_info *info, const struct fb_image *image)
{
struct nouveau_fbdev *nfbdev = info->par;
struct nouveau_drm *drm = nouveau_drm(nfbdev->dev);
struct nouveau_channel *chan = drm->channel;
uint32_t width, dwords, *data = (uint32_t *)image->data;
uint32_t mask = ~(~0 >> (32 - info->var.bits_per_pixel));
uint32_t *palette = info->pseudo_palette;
int ret;
if (image->depth != 1)
return -ENODEV;
ret = RING_SPACE(chan, 11);
if (ret)
return ret;
width = ALIGN(image->width, 32);
dwords = (width * image->height) >> 5;
BEGIN_NV04(chan, NvSub2D, 0x0814, 2);
if (info->fix.visual == FB_VISUAL_TRUECOLOR ||
info->fix.visual == FB_VISUAL_DIRECTCOLOR) {
OUT_RING(chan, palette[image->bg_color] | mask);
OUT_RING(chan, palette[image->fg_color] | mask);
} else {
OUT_RING(chan, image->bg_color);
OUT_RING(chan, image->fg_color);
}
BEGIN_NV04(chan, NvSub2D, 0x0838, 2);
OUT_RING(chan, image->width);
OUT_RING(chan, image->height);
BEGIN_NV04(chan, NvSub2D, 0x0850, 4);
OUT_RING(chan, 0);
OUT_RING(chan, image->dx);
OUT_RING(chan, 0);
OUT_RING(chan, image->dy);
while (dwords) {
int push = dwords > 2047 ? 2047 : dwords;
ret = RING_SPACE(chan, push + 1);
if (ret)
return ret;
dwords -= push;
BEGIN_NI04(chan, NvSub2D, 0x0860, push);
OUT_RINGp(chan, data, push);
data += push;
}
FIRE_RING(chan);
return 0;
}
int
nv50_fbcon_accel_init(struct fb_info *info)
{
struct nouveau_fbdev *nfbdev = info->par;
struct nouveau_framebuffer *fb = &nfbdev->nouveau_fb;
struct drm_device *dev = nfbdev->dev;
struct nouveau_drm *drm = nouveau_drm(dev);
struct nouveau_channel *chan = drm->channel;
int ret, format;
switch (info->var.bits_per_pixel) {
case 8:
format = 0xf3;
break;
case 15:
format = 0xf8;
break;
case 16:
format = 0xe8;
break;
case 32:
switch (info->var.transp.length) {
case 0: /* depth 24 */
case 8: /* depth 32, just use 24.. */
format = 0xe6;
break;
case 2: /* depth 30 */
format = 0xd1;
break;
default:
return -EINVAL;
}
break;
default:
return -EINVAL;
}
ret = nvif_object_init(&chan->user, 0x502d, 0x502d, NULL, 0,
&nfbdev->twod);
if (ret)
return ret;
ret = RING_SPACE(chan, 58);
if (ret) {
nouveau_fbcon_gpu_lockup(info);
return ret;
}
BEGIN_NV04(chan, NvSub2D, 0x0000, 1);
OUT_RING(chan, nfbdev->twod.handle);
BEGIN_NV04(chan, NvSub2D, 0x0184, 3);
OUT_RING(chan, chan->vram.handle);
OUT_RING(chan, chan->vram.handle);
OUT_RING(chan, chan->vram.handle);
BEGIN_NV04(chan, NvSub2D, 0x0290, 1);
OUT_RING(chan, 0);
BEGIN_NV04(chan, NvSub2D, 0x0888, 1);
OUT_RING(chan, 1);
BEGIN_NV04(chan, NvSub2D, 0x02ac, 1);
OUT_RING(chan, 3);
BEGIN_NV04(chan, NvSub2D, 0x02a0, 1);
OUT_RING(chan, 0x55);
BEGIN_NV04(chan, NvSub2D, 0x08c0, 4);
OUT_RING(chan, 0);
OUT_RING(chan, 1);
OUT_RING(chan, 0);
OUT_RING(chan, 1);
BEGIN_NV04(chan, NvSub2D, 0x0580, 2);
OUT_RING(chan, 4);
OUT_RING(chan, format);
BEGIN_NV04(chan, NvSub2D, 0x02e8, 2);
OUT_RING(chan, 2);
OUT_RING(chan, 1);
BEGIN_NV04(chan, NvSub2D, 0x0804, 1);
OUT_RING(chan, format);
BEGIN_NV04(chan, NvSub2D, 0x0800, 1);
OUT_RING(chan, 1);
BEGIN_NV04(chan, NvSub2D, 0x0808, 3);
OUT_RING(chan, 0);
OUT_RING(chan, 0);
OUT_RING(chan, 1);
BEGIN_NV04(chan, NvSub2D, 0x081c, 1);
OUT_RING(chan, 1);
BEGIN_NV04(chan, NvSub2D, 0x0840, 4);
OUT_RING(chan, 0);
OUT_RING(chan, 1);
OUT_RING(chan, 0);
OUT_RING(chan, 1);
BEGIN_NV04(chan, NvSub2D, 0x0200, 2);
OUT_RING(chan, format);
OUT_RING(chan, 1);
BEGIN_NV04(chan, NvSub2D, 0x0214, 5);
OUT_RING(chan, info->fix.line_length);
OUT_RING(chan, info->var.xres_virtual);
OUT_RING(chan, info->var.yres_virtual);
OUT_RING(chan, upper_32_bits(fb->vma.offset));
OUT_RING(chan, lower_32_bits(fb->vma.offset));
BEGIN_NV04(chan, NvSub2D, 0x0230, 2);
OUT_RING(chan, format);
OUT_RING(chan, 1);
BEGIN_NV04(chan, NvSub2D, 0x0244, 5);
OUT_RING(chan, info->fix.line_length);
OUT_RING(chan, info->var.xres_virtual);
OUT_RING(chan, info->var.yres_virtual);
OUT_RING(chan, upper_32_bits(fb->vma.offset));
OUT_RING(chan, lower_32_bits(fb->vma.offset));
FIRE_RING(chan);
return 0;
}
| gpl-2.0 |
The-Covenant/android_kernel_samsung_i927 | drivers/s390/char/sclp_cmd.c | 393 | 17500 | /*
* Copyright IBM Corp. 2007, 2009
*
* Author(s): Heiko Carstens <heiko.carstens@de.ibm.com>,
* Peter Oberparleiter <peter.oberparleiter@de.ibm.com>
*/
#define KMSG_COMPONENT "sclp_cmd"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/completion.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/mmzone.h>
#include <linux/memory.h>
#include <linux/platform_device.h>
#include <asm/chpid.h>
#include <asm/sclp.h>
#include <asm/setup.h>
#include "sclp.h"
#define SCLP_CMDW_READ_SCP_INFO 0x00020001
#define SCLP_CMDW_READ_SCP_INFO_FORCED 0x00120001
struct read_info_sccb {
struct sccb_header header; /* 0-7 */
u16 rnmax; /* 8-9 */
u8 rnsize; /* 10 */
u8 _reserved0[24 - 11]; /* 11-15 */
u8 loadparm[8]; /* 24-31 */
u8 _reserved1[48 - 32]; /* 32-47 */
u64 facilities; /* 48-55 */
u8 _reserved2[84 - 56]; /* 56-83 */
u8 fac84; /* 84 */
u8 _reserved3[91 - 85]; /* 85-90 */
u8 flags; /* 91 */
u8 _reserved4[100 - 92]; /* 92-99 */
u32 rnsize2; /* 100-103 */
u64 rnmax2; /* 104-111 */
u8 _reserved5[4096 - 112]; /* 112-4095 */
} __attribute__((packed, aligned(PAGE_SIZE)));
static struct read_info_sccb __initdata early_read_info_sccb;
static int __initdata early_read_info_sccb_valid;
u64 sclp_facilities;
static u8 sclp_fac84;
static unsigned long long rzm;
static unsigned long long rnmax;
static int __init sclp_cmd_sync_early(sclp_cmdw_t cmd, void *sccb)
{
int rc;
__ctl_set_bit(0, 9);
rc = sclp_service_call(cmd, sccb);
if (rc)
goto out;
__load_psw_mask(PSW_BASE_BITS | PSW_MASK_EXT |
PSW_MASK_WAIT | PSW_DEFAULT_KEY);
local_irq_disable();
out:
/* Contents of the sccb might have changed. */
barrier();
__ctl_clear_bit(0, 9);
return rc;
}
static void __init sclp_read_info_early(void)
{
int rc;
int i;
struct read_info_sccb *sccb;
sclp_cmdw_t commands[] = {SCLP_CMDW_READ_SCP_INFO_FORCED,
SCLP_CMDW_READ_SCP_INFO};
sccb = &early_read_info_sccb;
for (i = 0; i < ARRAY_SIZE(commands); i++) {
do {
memset(sccb, 0, sizeof(*sccb));
sccb->header.length = sizeof(*sccb);
sccb->header.function_code = 0x80;
sccb->header.control_mask[2] = 0x80;
rc = sclp_cmd_sync_early(commands[i], sccb);
} while (rc == -EBUSY);
if (rc)
break;
if (sccb->header.response_code == 0x10) {
early_read_info_sccb_valid = 1;
break;
}
if (sccb->header.response_code != 0x1f0)
break;
}
}
void __init sclp_facilities_detect(void)
{
struct read_info_sccb *sccb;
sclp_read_info_early();
if (!early_read_info_sccb_valid)
return;
sccb = &early_read_info_sccb;
sclp_facilities = sccb->facilities;
sclp_fac84 = sccb->fac84;
rnmax = sccb->rnmax ? sccb->rnmax : sccb->rnmax2;
rzm = sccb->rnsize ? sccb->rnsize : sccb->rnsize2;
rzm <<= 20;
}
unsigned long long sclp_get_rnmax(void)
{
return rnmax;
}
unsigned long long sclp_get_rzm(void)
{
return rzm;
}
/*
* This function will be called after sclp_facilities_detect(), which gets
* called from early.c code. Therefore the sccb should have valid contents.
*/
void __init sclp_get_ipl_info(struct sclp_ipl_info *info)
{
struct read_info_sccb *sccb;
if (!early_read_info_sccb_valid)
return;
sccb = &early_read_info_sccb;
info->is_valid = 1;
if (sccb->flags & 0x2)
info->has_dump = 1;
memcpy(&info->loadparm, &sccb->loadparm, LOADPARM_LEN);
}
static void sclp_sync_callback(struct sclp_req *req, void *data)
{
struct completion *completion = data;
complete(completion);
}
static int do_sync_request(sclp_cmdw_t cmd, void *sccb)
{
struct completion completion;
struct sclp_req *request;
int rc;
request = kzalloc(sizeof(*request), GFP_KERNEL);
if (!request)
return -ENOMEM;
request->command = cmd;
request->sccb = sccb;
request->status = SCLP_REQ_FILLED;
request->callback = sclp_sync_callback;
request->callback_data = &completion;
init_completion(&completion);
/* Perform sclp request. */
rc = sclp_add_request(request);
if (rc)
goto out;
wait_for_completion(&completion);
/* Check response. */
if (request->status != SCLP_REQ_DONE) {
pr_warning("sync request failed (cmd=0x%08x, "
"status=0x%02x)\n", cmd, request->status);
rc = -EIO;
}
out:
kfree(request);
return rc;
}
/*
* CPU configuration related functions.
*/
#define SCLP_CMDW_READ_CPU_INFO 0x00010001
#define SCLP_CMDW_CONFIGURE_CPU 0x00110001
#define SCLP_CMDW_DECONFIGURE_CPU 0x00100001
struct read_cpu_info_sccb {
struct sccb_header header;
u16 nr_configured;
u16 offset_configured;
u16 nr_standby;
u16 offset_standby;
u8 reserved[4096 - 16];
} __attribute__((packed, aligned(PAGE_SIZE)));
static void sclp_fill_cpu_info(struct sclp_cpu_info *info,
struct read_cpu_info_sccb *sccb)
{
char *page = (char *) sccb;
memset(info, 0, sizeof(*info));
info->configured = sccb->nr_configured;
info->standby = sccb->nr_standby;
info->combined = sccb->nr_configured + sccb->nr_standby;
info->has_cpu_type = sclp_fac84 & 0x1;
memcpy(&info->cpu, page + sccb->offset_configured,
info->combined * sizeof(struct sclp_cpu_entry));
}
int sclp_get_cpu_info(struct sclp_cpu_info *info)
{
int rc;
struct read_cpu_info_sccb *sccb;
if (!SCLP_HAS_CPU_INFO)
return -EOPNOTSUPP;
sccb = (void *) get_zeroed_page(GFP_KERNEL | GFP_DMA);
if (!sccb)
return -ENOMEM;
sccb->header.length = sizeof(*sccb);
rc = do_sync_request(SCLP_CMDW_READ_CPU_INFO, sccb);
if (rc)
goto out;
if (sccb->header.response_code != 0x0010) {
pr_warning("readcpuinfo failed (response=0x%04x)\n",
sccb->header.response_code);
rc = -EIO;
goto out;
}
sclp_fill_cpu_info(info, sccb);
out:
free_page((unsigned long) sccb);
return rc;
}
struct cpu_configure_sccb {
struct sccb_header header;
} __attribute__((packed, aligned(8)));
static int do_cpu_configure(sclp_cmdw_t cmd)
{
struct cpu_configure_sccb *sccb;
int rc;
if (!SCLP_HAS_CPU_RECONFIG)
return -EOPNOTSUPP;
/*
* This is not going to cross a page boundary since we force
* kmalloc to have a minimum alignment of 8 bytes on s390.
*/
sccb = kzalloc(sizeof(*sccb), GFP_KERNEL | GFP_DMA);
if (!sccb)
return -ENOMEM;
sccb->header.length = sizeof(*sccb);
rc = do_sync_request(cmd, sccb);
if (rc)
goto out;
switch (sccb->header.response_code) {
case 0x0020:
case 0x0120:
break;
default:
pr_warning("configure cpu failed (cmd=0x%08x, "
"response=0x%04x)\n", cmd,
sccb->header.response_code);
rc = -EIO;
break;
}
out:
kfree(sccb);
return rc;
}
int sclp_cpu_configure(u8 cpu)
{
return do_cpu_configure(SCLP_CMDW_CONFIGURE_CPU | cpu << 8);
}
int sclp_cpu_deconfigure(u8 cpu)
{
return do_cpu_configure(SCLP_CMDW_DECONFIGURE_CPU | cpu << 8);
}
#ifdef CONFIG_MEMORY_HOTPLUG
static DEFINE_MUTEX(sclp_mem_mutex);
static LIST_HEAD(sclp_mem_list);
static u8 sclp_max_storage_id;
static unsigned long sclp_storage_ids[256 / BITS_PER_LONG];
static int sclp_mem_state_changed;
struct memory_increment {
struct list_head list;
u16 rn;
int standby;
int usecount;
};
struct assign_storage_sccb {
struct sccb_header header;
u16 rn;
} __packed;
int arch_get_memory_phys_device(unsigned long start_pfn)
{
if (!rzm)
return 0;
return PFN_PHYS(start_pfn) >> ilog2(rzm);
}
static unsigned long long rn2addr(u16 rn)
{
return (unsigned long long) (rn - 1) * rzm;
}
static int do_assign_storage(sclp_cmdw_t cmd, u16 rn)
{
struct assign_storage_sccb *sccb;
int rc;
sccb = (void *) get_zeroed_page(GFP_KERNEL | GFP_DMA);
if (!sccb)
return -ENOMEM;
sccb->header.length = PAGE_SIZE;
sccb->rn = rn;
rc = do_sync_request(cmd, sccb);
if (rc)
goto out;
switch (sccb->header.response_code) {
case 0x0020:
case 0x0120:
break;
default:
pr_warning("assign storage failed (cmd=0x%08x, "
"response=0x%04x, rn=0x%04x)\n", cmd,
sccb->header.response_code, rn);
rc = -EIO;
break;
}
out:
free_page((unsigned long) sccb);
return rc;
}
static int sclp_assign_storage(u16 rn)
{
return do_assign_storage(0x000d0001, rn);
}
static int sclp_unassign_storage(u16 rn)
{
return do_assign_storage(0x000c0001, rn);
}
struct attach_storage_sccb {
struct sccb_header header;
u16 :16;
u16 assigned;
u32 :32;
u32 entries[0];
} __packed;
static int sclp_attach_storage(u8 id)
{
struct attach_storage_sccb *sccb;
int rc;
int i;
sccb = (void *) get_zeroed_page(GFP_KERNEL | GFP_DMA);
if (!sccb)
return -ENOMEM;
sccb->header.length = PAGE_SIZE;
rc = do_sync_request(0x00080001 | id << 8, sccb);
if (rc)
goto out;
switch (sccb->header.response_code) {
case 0x0020:
set_bit(id, sclp_storage_ids);
for (i = 0; i < sccb->assigned; i++) {
if (sccb->entries[i])
sclp_unassign_storage(sccb->entries[i] >> 16);
}
break;
default:
rc = -EIO;
break;
}
out:
free_page((unsigned long) sccb);
return rc;
}
static int sclp_mem_change_state(unsigned long start, unsigned long size,
int online)
{
struct memory_increment *incr;
unsigned long long istart;
int rc = 0;
list_for_each_entry(incr, &sclp_mem_list, list) {
istart = rn2addr(incr->rn);
if (start + size - 1 < istart)
break;
if (start > istart + rzm - 1)
continue;
if (online) {
if (incr->usecount++)
continue;
/*
* Don't break the loop if one assign fails. Loop may
* be walked again on CANCEL and we can't save
* information if state changed before or not.
* So continue and increase usecount for all increments.
*/
rc |= sclp_assign_storage(incr->rn);
} else {
if (--incr->usecount)
continue;
sclp_unassign_storage(incr->rn);
}
}
return rc ? -EIO : 0;
}
static int sclp_mem_notifier(struct notifier_block *nb,
unsigned long action, void *data)
{
unsigned long start, size;
struct memory_notify *arg;
unsigned char id;
int rc = 0;
arg = data;
start = arg->start_pfn << PAGE_SHIFT;
size = arg->nr_pages << PAGE_SHIFT;
mutex_lock(&sclp_mem_mutex);
for (id = 0; id <= sclp_max_storage_id; id++)
if (!test_bit(id, sclp_storage_ids))
sclp_attach_storage(id);
switch (action) {
case MEM_ONLINE:
case MEM_GOING_OFFLINE:
case MEM_CANCEL_OFFLINE:
break;
case MEM_GOING_ONLINE:
rc = sclp_mem_change_state(start, size, 1);
break;
case MEM_CANCEL_ONLINE:
sclp_mem_change_state(start, size, 0);
break;
case MEM_OFFLINE:
sclp_mem_change_state(start, size, 0);
break;
default:
rc = -EINVAL;
break;
}
if (!rc)
sclp_mem_state_changed = 1;
mutex_unlock(&sclp_mem_mutex);
return rc ? NOTIFY_BAD : NOTIFY_OK;
}
static struct notifier_block sclp_mem_nb = {
.notifier_call = sclp_mem_notifier,
};
static void __init add_memory_merged(u16 rn)
{
static u16 first_rn, num;
unsigned long long start, size;
if (rn && first_rn && (first_rn + num == rn)) {
num++;
return;
}
if (!first_rn)
goto skip_add;
start = rn2addr(first_rn);
size = (unsigned long long ) num * rzm;
if (start >= VMEM_MAX_PHYS)
goto skip_add;
if (start + size > VMEM_MAX_PHYS)
size = VMEM_MAX_PHYS - start;
if (memory_end_set && (start >= memory_end))
goto skip_add;
if (memory_end_set && (start + size > memory_end))
size = memory_end - start;
add_memory(0, start, size);
skip_add:
first_rn = rn;
num = 1;
}
static void __init sclp_add_standby_memory(void)
{
struct memory_increment *incr;
list_for_each_entry(incr, &sclp_mem_list, list)
if (incr->standby)
add_memory_merged(incr->rn);
add_memory_merged(0);
}
static void __init insert_increment(u16 rn, int standby, int assigned)
{
struct memory_increment *incr, *new_incr;
struct list_head *prev;
u16 last_rn;
new_incr = kzalloc(sizeof(*new_incr), GFP_KERNEL);
if (!new_incr)
return;
new_incr->rn = rn;
new_incr->standby = standby;
if (!standby)
new_incr->usecount = 1;
last_rn = 0;
prev = &sclp_mem_list;
list_for_each_entry(incr, &sclp_mem_list, list) {
if (assigned && incr->rn > rn)
break;
if (!assigned && incr->rn - last_rn > 1)
break;
last_rn = incr->rn;
prev = &incr->list;
}
if (!assigned)
new_incr->rn = last_rn + 1;
if (new_incr->rn > rnmax) {
kfree(new_incr);
return;
}
list_add(&new_incr->list, prev);
}
static int sclp_mem_freeze(struct device *dev)
{
if (!sclp_mem_state_changed)
return 0;
pr_err("Memory hotplug state changed, suspend refused.\n");
return -EPERM;
}
struct read_storage_sccb {
struct sccb_header header;
u16 max_id;
u16 assigned;
u16 standby;
u16 :16;
u32 entries[0];
} __packed;
static const struct dev_pm_ops sclp_mem_pm_ops = {
.freeze = sclp_mem_freeze,
};
static struct platform_driver sclp_mem_pdrv = {
.driver = {
.name = "sclp_mem",
.pm = &sclp_mem_pm_ops,
},
};
static int __init sclp_detect_standby_memory(void)
{
struct platform_device *sclp_pdev;
struct read_storage_sccb *sccb;
int i, id, assigned, rc;
if (!early_read_info_sccb_valid)
return 0;
if ((sclp_facilities & 0xe00000000000ULL) != 0xe00000000000ULL)
return 0;
rc = -ENOMEM;
sccb = (void *) __get_free_page(GFP_KERNEL | GFP_DMA);
if (!sccb)
goto out;
assigned = 0;
for (id = 0; id <= sclp_max_storage_id; id++) {
memset(sccb, 0, PAGE_SIZE);
sccb->header.length = PAGE_SIZE;
rc = do_sync_request(0x00040001 | id << 8, sccb);
if (rc)
goto out;
switch (sccb->header.response_code) {
case 0x0010:
set_bit(id, sclp_storage_ids);
for (i = 0; i < sccb->assigned; i++) {
if (!sccb->entries[i])
continue;
assigned++;
insert_increment(sccb->entries[i] >> 16, 0, 1);
}
break;
case 0x0310:
break;
case 0x0410:
for (i = 0; i < sccb->assigned; i++) {
if (!sccb->entries[i])
continue;
assigned++;
insert_increment(sccb->entries[i] >> 16, 1, 1);
}
break;
default:
rc = -EIO;
break;
}
if (!rc)
sclp_max_storage_id = sccb->max_id;
}
if (rc || list_empty(&sclp_mem_list))
goto out;
for (i = 1; i <= rnmax - assigned; i++)
insert_increment(0, 1, 0);
rc = register_memory_notifier(&sclp_mem_nb);
if (rc)
goto out;
rc = platform_driver_register(&sclp_mem_pdrv);
if (rc)
goto out;
sclp_pdev = platform_device_register_simple("sclp_mem", -1, NULL, 0);
rc = IS_ERR(sclp_pdev) ? PTR_ERR(sclp_pdev) : 0;
if (rc)
goto out_driver;
sclp_add_standby_memory();
goto out;
out_driver:
platform_driver_unregister(&sclp_mem_pdrv);
out:
free_page((unsigned long) sccb);
return rc;
}
__initcall(sclp_detect_standby_memory);
#endif /* CONFIG_MEMORY_HOTPLUG */
/*
* Channel path configuration related functions.
*/
#define SCLP_CMDW_CONFIGURE_CHPATH 0x000f0001
#define SCLP_CMDW_DECONFIGURE_CHPATH 0x000e0001
#define SCLP_CMDW_READ_CHPATH_INFORMATION 0x00030001
struct chp_cfg_sccb {
struct sccb_header header;
u8 ccm;
u8 reserved[6];
u8 cssid;
} __attribute__((packed));
static int do_chp_configure(sclp_cmdw_t cmd)
{
struct chp_cfg_sccb *sccb;
int rc;
if (!SCLP_HAS_CHP_RECONFIG)
return -EOPNOTSUPP;
/* Prepare sccb. */
sccb = (struct chp_cfg_sccb *) get_zeroed_page(GFP_KERNEL | GFP_DMA);
if (!sccb)
return -ENOMEM;
sccb->header.length = sizeof(*sccb);
rc = do_sync_request(cmd, sccb);
if (rc)
goto out;
switch (sccb->header.response_code) {
case 0x0020:
case 0x0120:
case 0x0440:
case 0x0450:
break;
default:
pr_warning("configure channel-path failed "
"(cmd=0x%08x, response=0x%04x)\n", cmd,
sccb->header.response_code);
rc = -EIO;
break;
}
out:
free_page((unsigned long) sccb);
return rc;
}
/**
* sclp_chp_configure - perform configure channel-path sclp command
* @chpid: channel-path ID
*
* Perform configure channel-path command sclp command for specified chpid.
* Return 0 after command successfully finished, non-zero otherwise.
*/
int sclp_chp_configure(struct chp_id chpid)
{
return do_chp_configure(SCLP_CMDW_CONFIGURE_CHPATH | chpid.id << 8);
}
/**
* sclp_chp_deconfigure - perform deconfigure channel-path sclp command
* @chpid: channel-path ID
*
* Perform deconfigure channel-path command sclp command for specified chpid
* and wait for completion. On success return 0. Return non-zero otherwise.
*/
int sclp_chp_deconfigure(struct chp_id chpid)
{
return do_chp_configure(SCLP_CMDW_DECONFIGURE_CHPATH | chpid.id << 8);
}
struct chp_info_sccb {
struct sccb_header header;
u8 recognized[SCLP_CHP_INFO_MASK_SIZE];
u8 standby[SCLP_CHP_INFO_MASK_SIZE];
u8 configured[SCLP_CHP_INFO_MASK_SIZE];
u8 ccm;
u8 reserved[6];
u8 cssid;
} __attribute__((packed));
/**
* sclp_chp_read_info - perform read channel-path information sclp command
* @info: resulting channel-path information data
*
* Perform read channel-path information sclp command and wait for completion.
* On success, store channel-path information in @info and return 0. Return
* non-zero otherwise.
*/
int sclp_chp_read_info(struct sclp_chp_info *info)
{
struct chp_info_sccb *sccb;
int rc;
if (!SCLP_HAS_CHP_INFO)
return -EOPNOTSUPP;
/* Prepare sccb. */
sccb = (struct chp_info_sccb *) get_zeroed_page(GFP_KERNEL | GFP_DMA);
if (!sccb)
return -ENOMEM;
sccb->header.length = sizeof(*sccb);
rc = do_sync_request(SCLP_CMDW_READ_CHPATH_INFORMATION, sccb);
if (rc)
goto out;
if (sccb->header.response_code != 0x0010) {
pr_warning("read channel-path info failed "
"(response=0x%04x)\n", sccb->header.response_code);
rc = -EIO;
goto out;
}
memcpy(info->recognized, sccb->recognized, SCLP_CHP_INFO_MASK_SIZE);
memcpy(info->standby, sccb->standby, SCLP_CHP_INFO_MASK_SIZE);
memcpy(info->configured, sccb->configured, SCLP_CHP_INFO_MASK_SIZE);
out:
free_page((unsigned long) sccb);
return rc;
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.