repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
Rashed97/caf-kernel-msm-3.14 | arch/mips/sgi-ip27/ip27-nmi.c | 4045 | 5574 | #include <linux/kernel.h>
#include <linux/mmzone.h>
#include <linux/nodemask.h>
#include <linux/spinlock.h>
#include <linux/smp.h>
#include <linux/atomic.h>
#include <asm/sn/types.h>
#include <asm/sn/addrs.h>
#include <asm/sn/nmi.h>
#include <asm/sn/arch.h>
#include <asm/sn/sn0/hub.h>
#if 0
#define NODE_NUM_CPUS(n) CNODE_NUM_CPUS(n)
#else
#define NODE_NUM_CPUS(n) CPUS_PER_NODE
#endif
#define CNODEID_NONE (cnodeid_t)-1
typedef unsigned long machreg_t;
static arch_spinlock_t nmi_lock = __ARCH_SPIN_LOCK_UNLOCKED;
/*
* Lets see what else we need to do here. Set up sp, gp?
*/
void nmi_dump(void)
{
void cont_nmi_dump(void);
cont_nmi_dump();
}
void install_cpu_nmi_handler(int slice)
{
nmi_t *nmi_addr;
nmi_addr = (nmi_t *)NMI_ADDR(get_nasid(), slice);
if (nmi_addr->call_addr)
return;
nmi_addr->magic = NMI_MAGIC;
nmi_addr->call_addr = (void *)nmi_dump;
nmi_addr->call_addr_c =
(void *)(~((unsigned long)(nmi_addr->call_addr)));
nmi_addr->call_parm = 0;
}
/*
* Copy the cpu registers which have been saved in the IP27prom format
* into the eframe format for the node under consideration.
*/
void nmi_cpu_eframe_save(nasid_t nasid, int slice)
{
struct reg_struct *nr;
int i;
/* Get the pointer to the current cpu's register set. */
nr = (struct reg_struct *)
(TO_UNCAC(TO_NODE(nasid, IP27_NMI_KREGS_OFFSET)) +
slice * IP27_NMI_KREGS_CPU_SIZE);
printk("NMI nasid %d: slice %d\n", nasid, slice);
/*
* Saved main processor registers
*/
for (i = 0; i < 32; ) {
if ((i % 4) == 0)
printk("$%2d :", i);
printk(" %016lx", nr->gpr[i]);
i++;
if ((i % 4) == 0)
printk("\n");
}
printk("Hi : (value lost)\n");
printk("Lo : (value lost)\n");
/*
* Saved cp0 registers
*/
printk("epc : %016lx %pS\n", nr->epc, (void *) nr->epc);
printk("%s\n", print_tainted());
printk("ErrEPC: %016lx %pS\n", nr->error_epc, (void *) nr->error_epc);
printk("ra : %016lx %pS\n", nr->gpr[31], (void *) nr->gpr[31]);
printk("Status: %08lx ", nr->sr);
if (nr->sr & ST0_KX)
printk("KX ");
if (nr->sr & ST0_SX)
printk("SX ");
if (nr->sr & ST0_UX)
printk("UX ");
switch (nr->sr & ST0_KSU) {
case KSU_USER:
printk("USER ");
break;
case KSU_SUPERVISOR:
printk("SUPERVISOR ");
break;
case KSU_KERNEL:
printk("KERNEL ");
break;
default:
printk("BAD_MODE ");
break;
}
if (nr->sr & ST0_ERL)
printk("ERL ");
if (nr->sr & ST0_EXL)
printk("EXL ");
if (nr->sr & ST0_IE)
printk("IE ");
printk("\n");
printk("Cause : %08lx\n", nr->cause);
printk("PrId : %08x\n", read_c0_prid());
printk("BadVA : %016lx\n", nr->badva);
printk("CErr : %016lx\n", nr->cache_err);
printk("NMI_SR: %016lx\n", nr->nmi_sr);
printk("\n");
}
void nmi_dump_hub_irq(nasid_t nasid, int slice)
{
hubreg_t mask0, mask1, pend0, pend1;
if (slice == 0) { /* Slice A */
mask0 = REMOTE_HUB_L(nasid, PI_INT_MASK0_A);
mask1 = REMOTE_HUB_L(nasid, PI_INT_MASK1_A);
} else { /* Slice B */
mask0 = REMOTE_HUB_L(nasid, PI_INT_MASK0_B);
mask1 = REMOTE_HUB_L(nasid, PI_INT_MASK1_B);
}
pend0 = REMOTE_HUB_L(nasid, PI_INT_PEND0);
pend1 = REMOTE_HUB_L(nasid, PI_INT_PEND1);
printk("PI_INT_MASK0: %16Lx PI_INT_MASK1: %16Lx\n", mask0, mask1);
printk("PI_INT_PEND0: %16Lx PI_INT_PEND1: %16Lx\n", pend0, pend1);
printk("\n\n");
}
/*
* Copy the cpu registers which have been saved in the IP27prom format
* into the eframe format for the node under consideration.
*/
void nmi_node_eframe_save(cnodeid_t cnode)
{
nasid_t nasid;
int slice;
/* Make sure that we have a valid node */
if (cnode == CNODEID_NONE)
return;
nasid = COMPACT_TO_NASID_NODEID(cnode);
if (nasid == INVALID_NASID)
return;
/* Save the registers into eframe for each cpu */
for (slice = 0; slice < NODE_NUM_CPUS(slice); slice++) {
nmi_cpu_eframe_save(nasid, slice);
nmi_dump_hub_irq(nasid, slice);
}
}
/*
* Save the nmi cpu registers for all cpus in the system.
*/
void
nmi_eframes_save(void)
{
cnodeid_t cnode;
for_each_online_node(cnode)
nmi_node_eframe_save(cnode);
}
void
cont_nmi_dump(void)
{
#ifndef REAL_NMI_SIGNAL
static atomic_t nmied_cpus = ATOMIC_INIT(0);
atomic_inc(&nmied_cpus);
#endif
/*
* Only allow 1 cpu to proceed
*/
arch_spin_lock(&nmi_lock);
#ifdef REAL_NMI_SIGNAL
/*
* Wait up to 15 seconds for the other cpus to respond to the NMI.
* If a cpu has not responded after 10 sec, send it 1 additional NMI.
* This is for 2 reasons:
* - sometimes a MMSC fail to NMI all cpus.
* - on 512p SN0 system, the MMSC will only send NMIs to
* half the cpus. Unfortunately, we don't know which cpus may be
* NMIed - it depends on how the site chooses to configure.
*
* Note: it has been measure that it takes the MMSC up to 2.3 secs to
* send NMIs to all cpus on a 256p system.
*/
for (i=0; i < 1500; i++) {
for_each_online_node(node)
if (NODEPDA(node)->dump_count == 0)
break;
if (node == MAX_NUMNODES)
break;
if (i == 1000) {
for_each_online_node(node)
if (NODEPDA(node)->dump_count == 0) {
cpu = cpumask_first(cpumask_of_node(node));
for (n=0; n < CNODE_NUM_CPUS(node); cpu++, n++) {
CPUMASK_SETB(nmied_cpus, cpu);
/*
* cputonasid, cputoslice
* needs kernel cpuid
*/
SEND_NMI((cputonasid(cpu)), (cputoslice(cpu)));
}
}
}
udelay(10000);
}
#else
while (atomic_read(&nmied_cpus) != num_online_cpus());
#endif
/*
* Save the nmi cpu registers for all cpu in the eframe format.
*/
nmi_eframes_save();
LOCAL_HUB_S(NI_PORT_RESET, NPR_PORTRESET | NPR_LOCALRESET);
}
| gpl-2.0 |
zephiK/android_kernel_moto_shamu_fk | arch/mips/sgi-ip27/ip27-nmi.c | 4045 | 5574 | #include <linux/kernel.h>
#include <linux/mmzone.h>
#include <linux/nodemask.h>
#include <linux/spinlock.h>
#include <linux/smp.h>
#include <linux/atomic.h>
#include <asm/sn/types.h>
#include <asm/sn/addrs.h>
#include <asm/sn/nmi.h>
#include <asm/sn/arch.h>
#include <asm/sn/sn0/hub.h>
#if 0
#define NODE_NUM_CPUS(n) CNODE_NUM_CPUS(n)
#else
#define NODE_NUM_CPUS(n) CPUS_PER_NODE
#endif
#define CNODEID_NONE (cnodeid_t)-1
typedef unsigned long machreg_t;
static arch_spinlock_t nmi_lock = __ARCH_SPIN_LOCK_UNLOCKED;
/*
* Lets see what else we need to do here. Set up sp, gp?
*/
void nmi_dump(void)
{
void cont_nmi_dump(void);
cont_nmi_dump();
}
void install_cpu_nmi_handler(int slice)
{
nmi_t *nmi_addr;
nmi_addr = (nmi_t *)NMI_ADDR(get_nasid(), slice);
if (nmi_addr->call_addr)
return;
nmi_addr->magic = NMI_MAGIC;
nmi_addr->call_addr = (void *)nmi_dump;
nmi_addr->call_addr_c =
(void *)(~((unsigned long)(nmi_addr->call_addr)));
nmi_addr->call_parm = 0;
}
/*
* Copy the cpu registers which have been saved in the IP27prom format
* into the eframe format for the node under consideration.
*/
void nmi_cpu_eframe_save(nasid_t nasid, int slice)
{
struct reg_struct *nr;
int i;
/* Get the pointer to the current cpu's register set. */
nr = (struct reg_struct *)
(TO_UNCAC(TO_NODE(nasid, IP27_NMI_KREGS_OFFSET)) +
slice * IP27_NMI_KREGS_CPU_SIZE);
printk("NMI nasid %d: slice %d\n", nasid, slice);
/*
* Saved main processor registers
*/
for (i = 0; i < 32; ) {
if ((i % 4) == 0)
printk("$%2d :", i);
printk(" %016lx", nr->gpr[i]);
i++;
if ((i % 4) == 0)
printk("\n");
}
printk("Hi : (value lost)\n");
printk("Lo : (value lost)\n");
/*
* Saved cp0 registers
*/
printk("epc : %016lx %pS\n", nr->epc, (void *) nr->epc);
printk("%s\n", print_tainted());
printk("ErrEPC: %016lx %pS\n", nr->error_epc, (void *) nr->error_epc);
printk("ra : %016lx %pS\n", nr->gpr[31], (void *) nr->gpr[31]);
printk("Status: %08lx ", nr->sr);
if (nr->sr & ST0_KX)
printk("KX ");
if (nr->sr & ST0_SX)
printk("SX ");
if (nr->sr & ST0_UX)
printk("UX ");
switch (nr->sr & ST0_KSU) {
case KSU_USER:
printk("USER ");
break;
case KSU_SUPERVISOR:
printk("SUPERVISOR ");
break;
case KSU_KERNEL:
printk("KERNEL ");
break;
default:
printk("BAD_MODE ");
break;
}
if (nr->sr & ST0_ERL)
printk("ERL ");
if (nr->sr & ST0_EXL)
printk("EXL ");
if (nr->sr & ST0_IE)
printk("IE ");
printk("\n");
printk("Cause : %08lx\n", nr->cause);
printk("PrId : %08x\n", read_c0_prid());
printk("BadVA : %016lx\n", nr->badva);
printk("CErr : %016lx\n", nr->cache_err);
printk("NMI_SR: %016lx\n", nr->nmi_sr);
printk("\n");
}
void nmi_dump_hub_irq(nasid_t nasid, int slice)
{
hubreg_t mask0, mask1, pend0, pend1;
if (slice == 0) { /* Slice A */
mask0 = REMOTE_HUB_L(nasid, PI_INT_MASK0_A);
mask1 = REMOTE_HUB_L(nasid, PI_INT_MASK1_A);
} else { /* Slice B */
mask0 = REMOTE_HUB_L(nasid, PI_INT_MASK0_B);
mask1 = REMOTE_HUB_L(nasid, PI_INT_MASK1_B);
}
pend0 = REMOTE_HUB_L(nasid, PI_INT_PEND0);
pend1 = REMOTE_HUB_L(nasid, PI_INT_PEND1);
printk("PI_INT_MASK0: %16Lx PI_INT_MASK1: %16Lx\n", mask0, mask1);
printk("PI_INT_PEND0: %16Lx PI_INT_PEND1: %16Lx\n", pend0, pend1);
printk("\n\n");
}
/*
* Copy the cpu registers which have been saved in the IP27prom format
* into the eframe format for the node under consideration.
*/
void nmi_node_eframe_save(cnodeid_t cnode)
{
nasid_t nasid;
int slice;
/* Make sure that we have a valid node */
if (cnode == CNODEID_NONE)
return;
nasid = COMPACT_TO_NASID_NODEID(cnode);
if (nasid == INVALID_NASID)
return;
/* Save the registers into eframe for each cpu */
for (slice = 0; slice < NODE_NUM_CPUS(slice); slice++) {
nmi_cpu_eframe_save(nasid, slice);
nmi_dump_hub_irq(nasid, slice);
}
}
/*
* Save the nmi cpu registers for all cpus in the system.
*/
void
nmi_eframes_save(void)
{
cnodeid_t cnode;
for_each_online_node(cnode)
nmi_node_eframe_save(cnode);
}
void
cont_nmi_dump(void)
{
#ifndef REAL_NMI_SIGNAL
static atomic_t nmied_cpus = ATOMIC_INIT(0);
atomic_inc(&nmied_cpus);
#endif
/*
* Only allow 1 cpu to proceed
*/
arch_spin_lock(&nmi_lock);
#ifdef REAL_NMI_SIGNAL
/*
* Wait up to 15 seconds for the other cpus to respond to the NMI.
* If a cpu has not responded after 10 sec, send it 1 additional NMI.
* This is for 2 reasons:
* - sometimes a MMSC fail to NMI all cpus.
* - on 512p SN0 system, the MMSC will only send NMIs to
* half the cpus. Unfortunately, we don't know which cpus may be
* NMIed - it depends on how the site chooses to configure.
*
* Note: it has been measure that it takes the MMSC up to 2.3 secs to
* send NMIs to all cpus on a 256p system.
*/
for (i=0; i < 1500; i++) {
for_each_online_node(node)
if (NODEPDA(node)->dump_count == 0)
break;
if (node == MAX_NUMNODES)
break;
if (i == 1000) {
for_each_online_node(node)
if (NODEPDA(node)->dump_count == 0) {
cpu = cpumask_first(cpumask_of_node(node));
for (n=0; n < CNODE_NUM_CPUS(node); cpu++, n++) {
CPUMASK_SETB(nmied_cpus, cpu);
/*
* cputonasid, cputoslice
* needs kernel cpuid
*/
SEND_NMI((cputonasid(cpu)), (cputoslice(cpu)));
}
}
}
udelay(10000);
}
#else
while (atomic_read(&nmied_cpus) != num_online_cpus());
#endif
/*
* Save the nmi cpu registers for all cpu in the eframe format.
*/
nmi_eframes_save();
LOCAL_HUB_S(NI_PORT_RESET, NPR_PORTRESET | NPR_LOCALRESET);
}
| gpl-2.0 |
coolshou/htc_dlxub1_kernel-3.4.10 | arch/s390/kernel/sys_s390.c | 4557 | 4238 | /*
* arch/s390/kernel/sys_s390.c
*
* S390 version
* Copyright (C) 1999,2000 IBM Deutschland Entwicklung GmbH, IBM Corporation
* Author(s): Martin Schwidefsky (schwidefsky@de.ibm.com),
* Thomas Spatzier (tspat@de.ibm.com)
*
* Derived from "arch/i386/kernel/sys_i386.c"
*
* This file contains various random system calls that
* have a non-standard calling sequence on the Linux/s390
* platform.
*/
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/fs.h>
#include <linux/smp.h>
#include <linux/sem.h>
#include <linux/msg.h>
#include <linux/shm.h>
#include <linux/stat.h>
#include <linux/syscalls.h>
#include <linux/mman.h>
#include <linux/file.h>
#include <linux/utsname.h>
#include <linux/personality.h>
#include <linux/unistd.h>
#include <linux/ipc.h>
#include <asm/uaccess.h>
#include "entry.h"
/*
* Perform the mmap() system call. Linux for S/390 isn't able to handle more
* than 5 system call parameters, so this system call uses a memory block
* for parameter passing.
*/
struct s390_mmap_arg_struct {
unsigned long addr;
unsigned long len;
unsigned long prot;
unsigned long flags;
unsigned long fd;
unsigned long offset;
};
SYSCALL_DEFINE1(mmap2, struct s390_mmap_arg_struct __user *, arg)
{
struct s390_mmap_arg_struct a;
int error = -EFAULT;
if (copy_from_user(&a, arg, sizeof(a)))
goto out;
error = sys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd, a.offset);
out:
return error;
}
/*
* sys_ipc() is the de-multiplexer for the SysV IPC calls.
*/
SYSCALL_DEFINE5(s390_ipc, uint, call, int, first, unsigned long, second,
unsigned long, third, void __user *, ptr)
{
if (call >> 16)
return -EINVAL;
/* The s390 sys_ipc variant has only five parameters instead of six
* like the generic variant. The only difference is the handling of
* the SEMTIMEDOP subcall where on s390 the third parameter is used
* as a pointer to a struct timespec where the generic variant uses
* the fifth parameter.
* Therefore we can call the generic variant by simply passing the
* third parameter also as fifth parameter.
*/
return sys_ipc(call, first, second, third, ptr, third);
}
#ifdef CONFIG_64BIT
SYSCALL_DEFINE1(s390_personality, unsigned int, personality)
{
unsigned int ret;
if (current->personality == PER_LINUX32 && personality == PER_LINUX)
personality = PER_LINUX32;
ret = sys_personality(personality);
if (ret == PER_LINUX32)
ret = PER_LINUX;
return ret;
}
#endif /* CONFIG_64BIT */
/*
* Wrapper function for sys_fadvise64/fadvise64_64
*/
#ifndef CONFIG_64BIT
SYSCALL_DEFINE5(s390_fadvise64, int, fd, u32, offset_high, u32, offset_low,
size_t, len, int, advice)
{
return sys_fadvise64(fd, (u64) offset_high << 32 | offset_low,
len, advice);
}
struct fadvise64_64_args {
int fd;
long long offset;
long long len;
int advice;
};
SYSCALL_DEFINE1(s390_fadvise64_64, struct fadvise64_64_args __user *, args)
{
struct fadvise64_64_args a;
if ( copy_from_user(&a, args, sizeof(a)) )
return -EFAULT;
return sys_fadvise64_64(a.fd, a.offset, a.len, a.advice);
}
/*
* This is a wrapper to call sys_fallocate(). For 31 bit s390 the last
* 64 bit argument "len" is split into the upper and lower 32 bits. The
* system call wrapper in the user space loads the value to %r6/%r7.
* The code in entry.S keeps the values in %r2 - %r6 where they are and
* stores %r7 to 96(%r15). But the standard C linkage requires that
* the whole 64 bit value for len is stored on the stack and doesn't
* use %r6 at all. So s390_fallocate has to convert the arguments from
* %r2: fd, %r3: mode, %r4/%r5: offset, %r6/96(%r15)-99(%r15): len
* to
* %r2: fd, %r3: mode, %r4/%r5: offset, 96(%r15)-103(%r15): len
*/
SYSCALL_DEFINE(s390_fallocate)(int fd, int mode, loff_t offset,
u32 len_high, u32 len_low)
{
return sys_fallocate(fd, mode, offset, ((u64)len_high << 32) | len_low);
}
#ifdef CONFIG_HAVE_SYSCALL_WRAPPERS
asmlinkage long SyS_s390_fallocate(long fd, long mode, loff_t offset,
long len_high, long len_low)
{
return SYSC_s390_fallocate((int) fd, (int) mode, offset,
(u32) len_high, (u32) len_low);
}
SYSCALL_ALIAS(sys_s390_fallocate, SyS_s390_fallocate);
#endif
#endif
| gpl-2.0 |
MattCrystal/tripping-hipster | drivers/media/dvb/frontends/it913x-fe.c | 4813 | 24913 | /*
* Driver for it913x-fe Frontend
*
* with support for on chip it9137 integral tuner
*
* Copyright (C) 2011 Malcolm Priestley (tvboxspy@gmail.com)
* IT9137 Copyright (C) ITE Tech 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.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.=
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/types.h>
#include "dvb_frontend.h"
#include "it913x-fe.h"
#include "it913x-fe-priv.h"
static int it913x_debug;
module_param_named(debug, it913x_debug, int, 0644);
MODULE_PARM_DESC(debug, "set debugging level (1=info (or-able)).");
#define dprintk(level, args...) do { \
if (level & it913x_debug) \
printk(KERN_DEBUG "it913x-fe: " args); \
} while (0)
#define deb_info(args...) dprintk(0x01, args)
#define debug_data_snipet(level, name, p) \
dprintk(level, name" (%02x%02x%02x%02x%02x%02x%02x%02x)", \
*p, *(p+1), *(p+2), *(p+3), *(p+4), \
*(p+5), *(p+6), *(p+7));
#define info(format, arg...) \
printk(KERN_INFO "it913x-fe: " format "\n" , ## arg)
struct it913x_fe_state {
struct dvb_frontend frontend;
struct i2c_adapter *i2c_adap;
struct ite_config *config;
u8 i2c_addr;
u32 frequency;
fe_modulation_t constellation;
fe_transmit_mode_t transmission_mode;
u8 priority;
u32 crystalFrequency;
u32 adcFrequency;
u8 tuner_type;
struct adctable *table;
fe_status_t it913x_status;
u16 tun_xtal;
u8 tun_fdiv;
u8 tun_clk_mode;
u32 tun_fn_min;
u32 ucblocks;
};
static int it913x_read_reg(struct it913x_fe_state *state,
u32 reg, u8 *data, u8 count)
{
int ret;
u8 pro = PRO_DMOD; /* All reads from demodulator */
u8 b[4];
struct i2c_msg msg[2] = {
{ .addr = state->i2c_addr + (pro << 1), .flags = 0,
.buf = b, .len = sizeof(b) },
{ .addr = state->i2c_addr + (pro << 1), .flags = I2C_M_RD,
.buf = data, .len = count }
};
b[0] = (u8) reg >> 24;
b[1] = (u8)(reg >> 16) & 0xff;
b[2] = (u8)(reg >> 8) & 0xff;
b[3] = (u8) reg & 0xff;
ret = i2c_transfer(state->i2c_adap, msg, 2);
return ret;
}
static int it913x_read_reg_u8(struct it913x_fe_state *state, u32 reg)
{
int ret;
u8 b[1];
ret = it913x_read_reg(state, reg, &b[0], sizeof(b));
return (ret < 0) ? -ENODEV : b[0];
}
static int it913x_write(struct it913x_fe_state *state,
u8 pro, u32 reg, u8 buf[], u8 count)
{
u8 b[256];
struct i2c_msg msg[1] = {
{ .addr = state->i2c_addr + (pro << 1), .flags = 0,
.buf = b, .len = count + 4 }
};
int ret;
b[0] = (u8) reg >> 24;
b[1] = (u8)(reg >> 16) & 0xff;
b[2] = (u8)(reg >> 8) & 0xff;
b[3] = (u8) reg & 0xff;
memcpy(&b[4], buf, count);
ret = i2c_transfer(state->i2c_adap, msg, 1);
if (ret < 0)
return -EIO;
return 0;
}
static int it913x_write_reg(struct it913x_fe_state *state,
u8 pro, u32 reg, u32 data)
{
int ret;
u8 b[4];
u8 s;
b[0] = data >> 24;
b[1] = (data >> 16) & 0xff;
b[2] = (data >> 8) & 0xff;
b[3] = data & 0xff;
/* expand write as needed */
if (data < 0x100)
s = 3;
else if (data < 0x1000)
s = 2;
else if (data < 0x100000)
s = 1;
else
s = 0;
ret = it913x_write(state, pro, reg, &b[s], sizeof(b) - s);
return ret;
}
static int it913x_fe_script_loader(struct it913x_fe_state *state,
struct it913xset *loadscript)
{
int ret, i;
if (loadscript == NULL)
return -EINVAL;
for (i = 0; i < 1000; ++i) {
if (loadscript[i].pro == 0xff)
break;
ret = it913x_write(state, loadscript[i].pro,
loadscript[i].address,
loadscript[i].reg, loadscript[i].count);
if (ret < 0)
return -ENODEV;
}
return 0;
}
static int it913x_init_tuner(struct it913x_fe_state *state)
{
int ret, i, reg;
u8 val, nv_val;
u8 nv[] = {48, 32, 24, 16, 12, 8, 6, 4, 2};
u8 b[2];
reg = it913x_read_reg_u8(state, 0xec86);
switch (reg) {
case 0:
state->tun_clk_mode = reg;
state->tun_xtal = 2000;
state->tun_fdiv = 3;
val = 16;
break;
case -ENODEV:
return -ENODEV;
case 1:
default:
state->tun_clk_mode = reg;
state->tun_xtal = 640;
state->tun_fdiv = 1;
val = 6;
break;
}
reg = it913x_read_reg_u8(state, 0xed03);
if (reg < 0)
return -ENODEV;
else if (reg < sizeof(nv))
nv_val = nv[reg];
else
nv_val = 2;
for (i = 0; i < 50; i++) {
ret = it913x_read_reg(state, 0xed23, &b[0], sizeof(b));
reg = (b[1] << 8) + b[0];
if (reg > 0)
break;
if (ret < 0)
return -ENODEV;
udelay(2000);
}
state->tun_fn_min = state->tun_xtal * reg;
state->tun_fn_min /= (state->tun_fdiv * nv_val);
deb_info("Tuner fn_min %d", state->tun_fn_min);
if (state->config->chip_ver > 1)
msleep(50);
else {
for (i = 0; i < 50; i++) {
reg = it913x_read_reg_u8(state, 0xec82);
if (reg > 0)
break;
if (reg < 0)
return -ENODEV;
udelay(2000);
}
}
return it913x_write_reg(state, PRO_DMOD, 0xed81, val);
}
static int it9137_set_tuner(struct it913x_fe_state *state,
u32 bandwidth, u32 frequency_m)
{
struct it913xset *set_tuner = set_it9137_template;
int ret, reg;
u32 frequency = frequency_m / 1000;
u32 freq, temp_f, tmp;
u16 iqik_m_cal;
u16 n_div;
u8 n;
u8 l_band;
u8 lna_band;
u8 bw;
if (state->config->firmware_ver == 1)
set_tuner = set_it9135_template;
else
set_tuner = set_it9137_template;
deb_info("Tuner Frequency %d Bandwidth %d", frequency, bandwidth);
if (frequency >= 51000 && frequency <= 440000) {
l_band = 0;
lna_band = 0;
} else if (frequency > 440000 && frequency <= 484000) {
l_band = 1;
lna_band = 1;
} else if (frequency > 484000 && frequency <= 533000) {
l_band = 1;
lna_band = 2;
} else if (frequency > 533000 && frequency <= 587000) {
l_band = 1;
lna_band = 3;
} else if (frequency > 587000 && frequency <= 645000) {
l_band = 1;
lna_band = 4;
} else if (frequency > 645000 && frequency <= 710000) {
l_band = 1;
lna_band = 5;
} else if (frequency > 710000 && frequency <= 782000) {
l_band = 1;
lna_band = 6;
} else if (frequency > 782000 && frequency <= 860000) {
l_band = 1;
lna_band = 7;
} else if (frequency > 1450000 && frequency <= 1492000) {
l_band = 1;
lna_band = 0;
} else if (frequency > 1660000 && frequency <= 1685000) {
l_band = 1;
lna_band = 1;
} else
return -EINVAL;
set_tuner[0].reg[0] = lna_band;
switch (bandwidth) {
case 5000000:
bw = 0;
break;
case 6000000:
bw = 2;
break;
case 7000000:
bw = 4;
break;
default:
case 8000000:
bw = 6;
break;
}
set_tuner[1].reg[0] = bw;
set_tuner[2].reg[0] = 0xa0 | (l_band << 3);
if (frequency > 53000 && frequency <= 74000) {
n_div = 48;
n = 0;
} else if (frequency > 74000 && frequency <= 111000) {
n_div = 32;
n = 1;
} else if (frequency > 111000 && frequency <= 148000) {
n_div = 24;
n = 2;
} else if (frequency > 148000 && frequency <= 222000) {
n_div = 16;
n = 3;
} else if (frequency > 222000 && frequency <= 296000) {
n_div = 12;
n = 4;
} else if (frequency > 296000 && frequency <= 445000) {
n_div = 8;
n = 5;
} else if (frequency > 445000 && frequency <= state->tun_fn_min) {
n_div = 6;
n = 6;
} else if (frequency > state->tun_fn_min && frequency <= 950000) {
n_div = 4;
n = 7;
} else if (frequency > 1450000 && frequency <= 1680000) {
n_div = 2;
n = 0;
} else
return -EINVAL;
reg = it913x_read_reg_u8(state, 0xed81);
iqik_m_cal = (u16)reg * n_div;
if (reg < 0x20) {
if (state->tun_clk_mode == 0)
iqik_m_cal = (iqik_m_cal * 9) >> 5;
else
iqik_m_cal >>= 1;
} else {
iqik_m_cal = 0x40 - iqik_m_cal;
if (state->tun_clk_mode == 0)
iqik_m_cal = ~((iqik_m_cal * 9) >> 5);
else
iqik_m_cal = ~(iqik_m_cal >> 1);
}
temp_f = frequency * (u32)n_div * (u32)state->tun_fdiv;
freq = temp_f / state->tun_xtal;
tmp = freq * state->tun_xtal;
if ((temp_f - tmp) >= (state->tun_xtal >> 1))
freq++;
freq += (u32) n << 13;
/* Frequency OMEGA_IQIK_M_CAL_MID*/
temp_f = freq + (u32)iqik_m_cal;
set_tuner[3].reg[0] = temp_f & 0xff;
set_tuner[4].reg[0] = (temp_f >> 8) & 0xff;
deb_info("High Frequency = %04x", temp_f);
/* Lower frequency */
set_tuner[5].reg[0] = freq & 0xff;
set_tuner[6].reg[0] = (freq >> 8) & 0xff;
deb_info("low Frequency = %04x", freq);
ret = it913x_fe_script_loader(state, set_tuner);
return (ret < 0) ? -ENODEV : 0;
}
static int it913x_fe_select_bw(struct it913x_fe_state *state,
u32 bandwidth, u32 adcFrequency)
{
int ret, i;
u8 buffer[256];
u32 coeff[8];
u16 bfsfcw_fftinx_ratio;
u16 fftinx_bfsfcw_ratio;
u8 count;
u8 bw;
u8 adcmultiplier;
deb_info("Bandwidth %d Adc %d", bandwidth, adcFrequency);
switch (bandwidth) {
case 5000000:
bw = 3;
break;
case 6000000:
bw = 0;
break;
case 7000000:
bw = 1;
break;
default:
case 8000000:
bw = 2;
break;
}
ret = it913x_write_reg(state, PRO_DMOD, REG_BW, bw);
if (state->table == NULL)
return -EINVAL;
/* In write order */
coeff[0] = state->table[bw].coeff_1_2048;
coeff[1] = state->table[bw].coeff_2_2k;
coeff[2] = state->table[bw].coeff_1_8191;
coeff[3] = state->table[bw].coeff_1_8192;
coeff[4] = state->table[bw].coeff_1_8193;
coeff[5] = state->table[bw].coeff_2_8k;
coeff[6] = state->table[bw].coeff_1_4096;
coeff[7] = state->table[bw].coeff_2_4k;
bfsfcw_fftinx_ratio = state->table[bw].bfsfcw_fftinx_ratio;
fftinx_bfsfcw_ratio = state->table[bw].fftinx_bfsfcw_ratio;
/* ADC multiplier */
ret = it913x_read_reg_u8(state, ADC_X_2);
if (ret < 0)
return -EINVAL;
adcmultiplier = ret;
count = 0;
/* Build Buffer for COEFF Registers */
for (i = 0; i < 8; i++) {
if (adcmultiplier == 1)
coeff[i] /= 2;
buffer[count++] = (coeff[i] >> 24) & 0x3;
buffer[count++] = (coeff[i] >> 16) & 0xff;
buffer[count++] = (coeff[i] >> 8) & 0xff;
buffer[count++] = coeff[i] & 0xff;
}
/* bfsfcw_fftinx_ratio register 0x21-0x22 */
buffer[count++] = bfsfcw_fftinx_ratio & 0xff;
buffer[count++] = (bfsfcw_fftinx_ratio >> 8) & 0xff;
/* fftinx_bfsfcw_ratio register 0x23-0x24 */
buffer[count++] = fftinx_bfsfcw_ratio & 0xff;
buffer[count++] = (fftinx_bfsfcw_ratio >> 8) & 0xff;
/* start at COEFF_1_2048 and write through to fftinx_bfsfcw_ratio*/
ret = it913x_write(state, PRO_DMOD, COEFF_1_2048, buffer, count);
for (i = 0; i < 42; i += 8)
debug_data_snipet(0x1, "Buffer", &buffer[i]);
return ret;
}
static int it913x_fe_read_status(struct dvb_frontend *fe, fe_status_t *status)
{
struct it913x_fe_state *state = fe->demodulator_priv;
int ret, i;
fe_status_t old_status = state->it913x_status;
*status = 0;
if (state->it913x_status == 0) {
ret = it913x_read_reg_u8(state, EMPTY_CHANNEL_STATUS);
if (ret == 0x1) {
*status |= FE_HAS_SIGNAL;
for (i = 0; i < 40; i++) {
ret = it913x_read_reg_u8(state, MP2IF_SYNC_LK);
if (ret == 0x1)
break;
msleep(25);
}
if (ret == 0x1)
*status |= FE_HAS_CARRIER
| FE_HAS_VITERBI
| FE_HAS_SYNC;
state->it913x_status = *status;
}
}
if (state->it913x_status & FE_HAS_SYNC) {
ret = it913x_read_reg_u8(state, TPSD_LOCK);
if (ret == 0x1)
*status |= FE_HAS_LOCK
| state->it913x_status;
else
state->it913x_status = 0;
if (old_status != state->it913x_status)
ret = it913x_write_reg(state, PRO_LINK, GPIOH3_O, ret);
}
return 0;
}
/* FEC values based on fe_code_rate_t non supported values 0*/
int it913x_qpsk_pval[] = {0, -93, -91, -90, 0, -89, -88};
int it913x_16qam_pval[] = {0, -87, -85, -84, 0, -83, -82};
int it913x_64qam_pval[] = {0, -82, -80, -78, 0, -77, -76};
static int it913x_get_signal_strength(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *p = &fe->dtv_property_cache;
struct it913x_fe_state *state = fe->demodulator_priv;
u8 code_rate;
int ret, temp;
u8 lna_gain_os;
ret = it913x_read_reg_u8(state, VAR_P_INBAND);
if (ret < 0)
return ret;
/* VHF/UHF gain offset */
if (state->frequency < 300000000)
lna_gain_os = 7;
else
lna_gain_os = 14;
temp = (ret - 100) - lna_gain_os;
if (state->priority == PRIORITY_HIGH)
code_rate = p->code_rate_HP;
else
code_rate = p->code_rate_LP;
if (code_rate >= ARRAY_SIZE(it913x_qpsk_pval))
return -EINVAL;
deb_info("Reg VAR_P_INBAND:%d Calc Offset Value:%d", ret, temp);
/* Apply FEC offset values*/
switch (p->modulation) {
case QPSK:
temp -= it913x_qpsk_pval[code_rate];
break;
case QAM_16:
temp -= it913x_16qam_pval[code_rate];
break;
case QAM_64:
temp -= it913x_64qam_pval[code_rate];
break;
default:
return -EINVAL;
}
if (temp < -15)
ret = 0;
else if ((-15 <= temp) && (temp < 0))
ret = (2 * (temp + 15)) / 3;
else if ((0 <= temp) && (temp < 20))
ret = 4 * temp + 10;
else if ((20 <= temp) && (temp < 35))
ret = (2 * (temp - 20)) / 3 + 90;
else if (temp >= 35)
ret = 100;
deb_info("Signal Strength :%d", ret);
return ret;
}
static int it913x_fe_read_signal_strength(struct dvb_frontend *fe,
u16 *strength)
{
struct it913x_fe_state *state = fe->demodulator_priv;
int ret = 0;
if (state->config->read_slevel) {
if (state->it913x_status & FE_HAS_SIGNAL)
ret = it913x_read_reg_u8(state, SIGNAL_LEVEL);
} else
ret = it913x_get_signal_strength(fe);
if (ret >= 0)
*strength = (u16)((u32)ret * 0xffff / 0x64);
return (ret < 0) ? -ENODEV : 0;
}
static int it913x_fe_read_snr(struct dvb_frontend *fe, u16 *snr)
{
struct it913x_fe_state *state = fe->demodulator_priv;
int ret;
u8 reg[3];
u32 snr_val, snr_min, snr_max;
u32 temp;
ret = it913x_read_reg(state, 0x2c, reg, sizeof(reg));
snr_val = (u32)(reg[2] << 16) | (reg[1] << 8) | reg[0];
ret |= it913x_read_reg(state, 0xf78b, reg, 1);
if (reg[0])
snr_val /= reg[0];
if (state->transmission_mode == TRANSMISSION_MODE_2K)
snr_val *= 4;
else if (state->transmission_mode == TRANSMISSION_MODE_4K)
snr_val *= 2;
if (state->constellation == QPSK) {
snr_min = 0xb4711;
snr_max = 0x191451;
} else if (state->constellation == QAM_16) {
snr_min = 0x4f0d5;
snr_max = 0xc7925;
} else if (state->constellation == QAM_64) {
snr_min = 0x256d0;
snr_max = 0x626be;
} else
return -EINVAL;
if (snr_val < snr_min)
*snr = 0;
else if (snr_val < snr_max) {
temp = (snr_val - snr_min) >> 5;
temp *= 0xffff;
temp /= (snr_max - snr_min) >> 5;
*snr = (u16)temp;
} else
*snr = 0xffff;
return (ret < 0) ? -ENODEV : 0;
}
static int it913x_fe_read_ber(struct dvb_frontend *fe, u32 *ber)
{
struct it913x_fe_state *state = fe->demodulator_priv;
int ret;
u8 reg[5];
/* Read Aborted Packets and Pre-Viterbi error rate 5 bytes */
ret = it913x_read_reg(state, RSD_ABORT_PKT_LSB, reg, sizeof(reg));
state->ucblocks += (u32)(reg[1] << 8) | reg[0];
*ber = (u32)(reg[4] << 16) | (reg[3] << 8) | reg[2];
return 0;
}
static int it913x_fe_read_ucblocks(struct dvb_frontend *fe, u32 *ucblocks)
{
struct it913x_fe_state *state = fe->demodulator_priv;
int ret;
u8 reg[2];
/* Aborted Packets */
ret = it913x_read_reg(state, RSD_ABORT_PKT_LSB, reg, sizeof(reg));
state->ucblocks += (u32)(reg[1] << 8) | reg[0];
*ucblocks = state->ucblocks;
return ret;
}
static int it913x_fe_get_frontend(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *p = &fe->dtv_property_cache;
struct it913x_fe_state *state = fe->demodulator_priv;
int ret;
u8 reg[8];
ret = it913x_read_reg(state, REG_TPSD_TX_MODE, reg, sizeof(reg));
if (reg[3] < 3)
p->modulation = fe_con[reg[3]];
if (reg[0] < 3)
p->transmission_mode = fe_mode[reg[0]];
if (reg[1] < 4)
p->guard_interval = fe_gi[reg[1]];
if (reg[2] < 4)
p->hierarchy = fe_hi[reg[2]];
state->priority = reg[5];
p->code_rate_HP = (reg[6] < 6) ? fe_code[reg[6]] : FEC_NONE;
p->code_rate_LP = (reg[7] < 6) ? fe_code[reg[7]] : FEC_NONE;
/* Update internal state to reflect the autodetected props */
state->constellation = p->modulation;
state->transmission_mode = p->transmission_mode;
return 0;
}
static int it913x_fe_set_frontend(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *p = &fe->dtv_property_cache;
struct it913x_fe_state *state = fe->demodulator_priv;
int ret, i;
u8 empty_ch, last_ch;
state->it913x_status = 0;
/* Set bw*/
ret = it913x_fe_select_bw(state, p->bandwidth_hz,
state->adcFrequency);
/* Training Mode Off */
ret = it913x_write_reg(state, PRO_LINK, TRAINING_MODE, 0x0);
/* Clear Empty Channel */
ret = it913x_write_reg(state, PRO_DMOD, EMPTY_CHANNEL_STATUS, 0x0);
/* Clear bits */
ret = it913x_write_reg(state, PRO_DMOD, MP2IF_SYNC_LK, 0x0);
/* LED on */
ret = it913x_write_reg(state, PRO_LINK, GPIOH3_O, 0x1);
/* Select Band*/
if ((p->frequency >= 51000000) && (p->frequency <= 230000000))
i = 0;
else if ((p->frequency >= 350000000) && (p->frequency <= 900000000))
i = 1;
else if ((p->frequency >= 1450000000) && (p->frequency <= 1680000000))
i = 2;
else
return -EOPNOTSUPP;
ret = it913x_write_reg(state, PRO_DMOD, FREE_BAND, i);
deb_info("Frontend Set Tuner Type %02x", state->tuner_type);
switch (state->tuner_type) {
case IT9135_38:
case IT9135_51:
case IT9135_52:
case IT9135_60:
case IT9135_61:
case IT9135_62:
ret = it9137_set_tuner(state,
p->bandwidth_hz, p->frequency);
break;
default:
if (fe->ops.tuner_ops.set_params) {
fe->ops.tuner_ops.set_params(fe);
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 0);
}
break;
}
/* LED off */
ret = it913x_write_reg(state, PRO_LINK, GPIOH3_O, 0x0);
/* Trigger ofsm */
ret = it913x_write_reg(state, PRO_DMOD, TRIGGER_OFSM, 0x0);
last_ch = 2;
for (i = 0; i < 40; ++i) {
empty_ch = it913x_read_reg_u8(state, EMPTY_CHANNEL_STATUS);
if (last_ch == 1 && empty_ch == 1)
break;
if (last_ch == 2 && empty_ch == 2)
return 0;
last_ch = empty_ch;
msleep(25);
}
for (i = 0; i < 40; ++i) {
if (it913x_read_reg_u8(state, D_TPSD_LOCK) == 1)
break;
msleep(25);
}
state->frequency = p->frequency;
return 0;
}
static int it913x_fe_suspend(struct it913x_fe_state *state)
{
int ret, i;
u8 b;
ret = it913x_write_reg(state, PRO_DMOD, SUSPEND_FLAG, 0x1);
ret |= it913x_write_reg(state, PRO_DMOD, TRIGGER_OFSM, 0x0);
for (i = 0; i < 128; i++) {
ret = it913x_read_reg(state, SUSPEND_FLAG, &b, 1);
if (ret < 0)
return -ENODEV;
if (b == 0)
break;
}
ret |= it913x_write_reg(state, PRO_DMOD, AFE_MEM0, 0x8);
/* Turn LED off */
ret |= it913x_write_reg(state, PRO_LINK, GPIOH3_O, 0x0);
ret |= it913x_fe_script_loader(state, it9137_tuner_off);
return (ret < 0) ? -ENODEV : 0;
}
/* Power sequence */
/* Power Up Tuner on -> Frontend suspend off -> Tuner clk on */
/* Power Down Frontend suspend on -> Tuner clk off -> Tuner off */
static int it913x_fe_sleep(struct dvb_frontend *fe)
{
struct it913x_fe_state *state = fe->demodulator_priv;
return it913x_fe_suspend(state);
}
static u32 compute_div(u32 a, u32 b, u32 x)
{
u32 res = 0;
u32 c = 0;
u32 i = 0;
if (a > b) {
c = a / b;
a = a - c * b;
}
for (i = 0; i < x; i++) {
if (a >= b) {
res += 1;
a -= b;
}
a <<= 1;
res <<= 1;
}
res = (c << x) + res;
return res;
}
static int it913x_fe_start(struct it913x_fe_state *state)
{
struct it913xset *set_lna;
struct it913xset *set_mode;
int ret;
u8 adf = (state->config->adf & 0xf);
u32 adc, xtal;
u8 b[4];
if (state->config->chip_ver == 1)
ret = it913x_init_tuner(state);
info("ADF table value :%02x", adf);
if (adf < 10) {
state->crystalFrequency = fe_clockTable[adf].xtal ;
state->table = fe_clockTable[adf].table;
state->adcFrequency = state->table->adcFrequency;
adc = compute_div(state->adcFrequency, 1000000ul, 19ul);
xtal = compute_div(state->crystalFrequency, 1000000ul, 19ul);
} else
return -EINVAL;
/* Set LED indicator on GPIOH3 */
ret = it913x_write_reg(state, PRO_LINK, GPIOH3_EN, 0x1);
ret |= it913x_write_reg(state, PRO_LINK, GPIOH3_ON, 0x1);
ret |= it913x_write_reg(state, PRO_LINK, GPIOH3_O, 0x1);
ret |= it913x_write_reg(state, PRO_LINK, 0xf641, state->tuner_type);
ret |= it913x_write_reg(state, PRO_DMOD, 0xf5ca, 0x01);
ret |= it913x_write_reg(state, PRO_DMOD, 0xf715, 0x01);
b[0] = xtal & 0xff;
b[1] = (xtal >> 8) & 0xff;
b[2] = (xtal >> 16) & 0xff;
b[3] = (xtal >> 24);
ret |= it913x_write(state, PRO_DMOD, XTAL_CLK, b , 4);
b[0] = adc & 0xff;
b[1] = (adc >> 8) & 0xff;
b[2] = (adc >> 16) & 0xff;
ret |= it913x_write(state, PRO_DMOD, ADC_FREQ, b, 3);
if (state->config->adc_x2)
ret |= it913x_write_reg(state, PRO_DMOD, ADC_X_2, 0x01);
b[0] = 0;
b[1] = 0;
b[2] = 0;
ret |= it913x_write(state, PRO_DMOD, 0x0029, b, 3);
info("Crystal Frequency :%d Adc Frequency :%d ADC X2: %02x",
state->crystalFrequency, state->adcFrequency,
state->config->adc_x2);
deb_info("Xtal value :%04x Adc value :%04x", xtal, adc);
if (ret < 0)
return -ENODEV;
/* v1 or v2 tuner script */
if (state->config->chip_ver > 1)
ret = it913x_fe_script_loader(state, it9135_v2);
else
ret = it913x_fe_script_loader(state, it9135_v1);
if (ret < 0)
return ret;
/* LNA Scripts */
switch (state->tuner_type) {
case IT9135_51:
set_lna = it9135_51;
break;
case IT9135_52:
set_lna = it9135_52;
break;
case IT9135_60:
set_lna = it9135_60;
break;
case IT9135_61:
set_lna = it9135_61;
break;
case IT9135_62:
set_lna = it9135_62;
break;
case IT9135_38:
default:
set_lna = it9135_38;
}
info("Tuner LNA type :%02x", state->tuner_type);
ret = it913x_fe_script_loader(state, set_lna);
if (ret < 0)
return ret;
if (state->config->chip_ver == 2) {
ret = it913x_write_reg(state, PRO_DMOD, TRIGGER_OFSM, 0x1);
ret |= it913x_write_reg(state, PRO_LINK, PADODPU, 0x0);
ret |= it913x_write_reg(state, PRO_LINK, AGC_O_D, 0x0);
ret |= it913x_init_tuner(state);
}
if (ret < 0)
return -ENODEV;
/* Always solo frontend */
set_mode = set_solo_fe;
ret |= it913x_fe_script_loader(state, set_mode);
ret |= it913x_fe_suspend(state);
return (ret < 0) ? -ENODEV : 0;
}
static int it913x_fe_init(struct dvb_frontend *fe)
{
struct it913x_fe_state *state = fe->demodulator_priv;
int ret = 0;
/* Power Up Tuner - common all versions */
ret = it913x_write_reg(state, PRO_DMOD, 0xec40, 0x1);
ret |= it913x_fe_script_loader(state, init_1);
ret |= it913x_write_reg(state, PRO_DMOD, AFE_MEM0, 0x0);
ret |= it913x_write_reg(state, PRO_DMOD, 0xfba8, 0x0);
return (ret < 0) ? -ENODEV : 0;
}
static void it913x_fe_release(struct dvb_frontend *fe)
{
struct it913x_fe_state *state = fe->demodulator_priv;
kfree(state);
}
static struct dvb_frontend_ops it913x_fe_ofdm_ops;
struct dvb_frontend *it913x_fe_attach(struct i2c_adapter *i2c_adap,
u8 i2c_addr, struct ite_config *config)
{
struct it913x_fe_state *state = NULL;
int ret;
/* allocate memory for the internal state */
state = kzalloc(sizeof(struct it913x_fe_state), GFP_KERNEL);
if (state == NULL)
return NULL;
if (config == NULL)
goto error;
state->i2c_adap = i2c_adap;
state->i2c_addr = i2c_addr;
state->config = config;
switch (state->config->tuner_id_0) {
case IT9135_51:
case IT9135_52:
case IT9135_60:
case IT9135_61:
case IT9135_62:
state->tuner_type = state->config->tuner_id_0;
break;
default:
case IT9135_38:
state->tuner_type = IT9135_38;
}
ret = it913x_fe_start(state);
if (ret < 0)
goto error;
/* create dvb_frontend */
memcpy(&state->frontend.ops, &it913x_fe_ofdm_ops,
sizeof(struct dvb_frontend_ops));
state->frontend.demodulator_priv = state;
return &state->frontend;
error:
kfree(state);
return NULL;
}
EXPORT_SYMBOL(it913x_fe_attach);
static struct dvb_frontend_ops it913x_fe_ofdm_ops = {
.delsys = { SYS_DVBT },
.info = {
.name = "it913x-fe DVB-T",
.frequency_min = 51000000,
.frequency_max = 1680000000,
.frequency_stepsize = 62500,
.caps = FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 |
FE_CAN_FEC_4_5 | FE_CAN_FEC_5_6 | FE_CAN_FEC_6_7 |
FE_CAN_FEC_7_8 | FE_CAN_FEC_8_9 | FE_CAN_FEC_AUTO |
FE_CAN_QAM_16 | FE_CAN_QAM_64 | FE_CAN_QAM_AUTO |
FE_CAN_TRANSMISSION_MODE_AUTO |
FE_CAN_GUARD_INTERVAL_AUTO |
FE_CAN_HIERARCHY_AUTO,
},
.release = it913x_fe_release,
.init = it913x_fe_init,
.sleep = it913x_fe_sleep,
.set_frontend = it913x_fe_set_frontend,
.get_frontend = it913x_fe_get_frontend,
.read_status = it913x_fe_read_status,
.read_signal_strength = it913x_fe_read_signal_strength,
.read_snr = it913x_fe_read_snr,
.read_ber = it913x_fe_read_ber,
.read_ucblocks = it913x_fe_read_ucblocks,
};
MODULE_DESCRIPTION("it913x Frontend and it9137 tuner");
MODULE_AUTHOR("Malcolm Priestley tvboxspy@gmail.com");
MODULE_VERSION("1.15");
MODULE_LICENSE("GPL");
| gpl-2.0 |
kostoulhs/android_kernel_samsung_expressltexx | sound/soc/au1x/psc-ac97.c | 5069 | 12576 | /*
* Au12x0/Au1550 PSC ALSA ASoC audio support.
*
* (c) 2007-2009 MSC Vertriebsges.m.b.H.,
* Manuel Lauss <manuel.lauss@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.
*
* Au1xxx-PSC AC97 glue.
*
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/mutex.h>
#include <linux/suspend.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/initval.h>
#include <sound/soc.h>
#include <asm/mach-au1x00/au1000.h>
#include <asm/mach-au1x00/au1xxx_psc.h>
#include "psc.h"
/* how often to retry failed codec register reads/writes */
#define AC97_RW_RETRIES 5
#define AC97_DIR \
(SND_SOC_DAIDIR_PLAYBACK | SND_SOC_DAIDIR_CAPTURE)
#define AC97_RATES \
SNDRV_PCM_RATE_8000_48000
#define AC97_FMTS \
(SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3BE)
#define AC97PCR_START(stype) \
((stype) == SNDRV_PCM_STREAM_PLAYBACK ? PSC_AC97PCR_TS : PSC_AC97PCR_RS)
#define AC97PCR_STOP(stype) \
((stype) == SNDRV_PCM_STREAM_PLAYBACK ? PSC_AC97PCR_TP : PSC_AC97PCR_RP)
#define AC97PCR_CLRFIFO(stype) \
((stype) == SNDRV_PCM_STREAM_PLAYBACK ? PSC_AC97PCR_TC : PSC_AC97PCR_RC)
#define AC97STAT_BUSY(stype) \
((stype) == SNDRV_PCM_STREAM_PLAYBACK ? PSC_AC97STAT_TB : PSC_AC97STAT_RB)
/* instance data. There can be only one, MacLeod!!!! */
static struct au1xpsc_audio_data *au1xpsc_ac97_workdata;
#if 0
/* this could theoretically work, but ac97->bus->card->private_data can be NULL
* when snd_ac97_mixer() is called; I don't know if the rest further down the
* chain are always valid either.
*/
static inline struct au1xpsc_audio_data *ac97_to_pscdata(struct snd_ac97 *x)
{
struct snd_soc_card *c = x->bus->card->private_data;
return snd_soc_dai_get_drvdata(c->rtd->cpu_dai);
}
#else
#define ac97_to_pscdata(x) au1xpsc_ac97_workdata
#endif
/* AC97 controller reads codec register */
static unsigned short au1xpsc_ac97_read(struct snd_ac97 *ac97,
unsigned short reg)
{
struct au1xpsc_audio_data *pscdata = ac97_to_pscdata(ac97);
unsigned short retry, tmo;
unsigned long data;
au_writel(PSC_AC97EVNT_CD, AC97_EVNT(pscdata));
au_sync();
retry = AC97_RW_RETRIES;
do {
mutex_lock(&pscdata->lock);
au_writel(PSC_AC97CDC_RD | PSC_AC97CDC_INDX(reg),
AC97_CDC(pscdata));
au_sync();
tmo = 20;
do {
udelay(21);
if (au_readl(AC97_EVNT(pscdata)) & PSC_AC97EVNT_CD)
break;
} while (--tmo);
data = au_readl(AC97_CDC(pscdata));
au_writel(PSC_AC97EVNT_CD, AC97_EVNT(pscdata));
au_sync();
mutex_unlock(&pscdata->lock);
if (reg != ((data >> 16) & 0x7f))
tmo = 1; /* wrong register, try again */
} while (--retry && !tmo);
return retry ? data & 0xffff : 0xffff;
}
/* AC97 controller writes to codec register */
static void au1xpsc_ac97_write(struct snd_ac97 *ac97, unsigned short reg,
unsigned short val)
{
struct au1xpsc_audio_data *pscdata = ac97_to_pscdata(ac97);
unsigned int tmo, retry;
au_writel(PSC_AC97EVNT_CD, AC97_EVNT(pscdata));
au_sync();
retry = AC97_RW_RETRIES;
do {
mutex_lock(&pscdata->lock);
au_writel(PSC_AC97CDC_INDX(reg) | (val & 0xffff),
AC97_CDC(pscdata));
au_sync();
tmo = 20;
do {
udelay(21);
if (au_readl(AC97_EVNT(pscdata)) & PSC_AC97EVNT_CD)
break;
} while (--tmo);
au_writel(PSC_AC97EVNT_CD, AC97_EVNT(pscdata));
au_sync();
mutex_unlock(&pscdata->lock);
} while (--retry && !tmo);
}
/* AC97 controller asserts a warm reset */
static void au1xpsc_ac97_warm_reset(struct snd_ac97 *ac97)
{
struct au1xpsc_audio_data *pscdata = ac97_to_pscdata(ac97);
au_writel(PSC_AC97RST_SNC, AC97_RST(pscdata));
au_sync();
msleep(10);
au_writel(0, AC97_RST(pscdata));
au_sync();
}
static void au1xpsc_ac97_cold_reset(struct snd_ac97 *ac97)
{
struct au1xpsc_audio_data *pscdata = ac97_to_pscdata(ac97);
int i;
/* disable PSC during cold reset */
au_writel(0, AC97_CFG(au1xpsc_ac97_workdata));
au_sync();
au_writel(PSC_CTRL_DISABLE, PSC_CTRL(pscdata));
au_sync();
/* issue cold reset */
au_writel(PSC_AC97RST_RST, AC97_RST(pscdata));
au_sync();
msleep(500);
au_writel(0, AC97_RST(pscdata));
au_sync();
/* enable PSC */
au_writel(PSC_CTRL_ENABLE, PSC_CTRL(pscdata));
au_sync();
/* wait for PSC to indicate it's ready */
i = 1000;
while (!((au_readl(AC97_STAT(pscdata)) & PSC_AC97STAT_SR)) && (--i))
msleep(1);
if (i == 0) {
printk(KERN_ERR "au1xpsc-ac97: PSC not ready!\n");
return;
}
/* enable the ac97 function */
au_writel(pscdata->cfg | PSC_AC97CFG_DE_ENABLE, AC97_CFG(pscdata));
au_sync();
/* wait for AC97 core to become ready */
i = 1000;
while (!((au_readl(AC97_STAT(pscdata)) & PSC_AC97STAT_DR)) && (--i))
msleep(1);
if (i == 0)
printk(KERN_ERR "au1xpsc-ac97: AC97 ctrl not ready\n");
}
/* AC97 controller operations */
struct snd_ac97_bus_ops soc_ac97_ops = {
.read = au1xpsc_ac97_read,
.write = au1xpsc_ac97_write,
.reset = au1xpsc_ac97_cold_reset,
.warm_reset = au1xpsc_ac97_warm_reset,
};
EXPORT_SYMBOL_GPL(soc_ac97_ops);
static int au1xpsc_ac97_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct au1xpsc_audio_data *pscdata = snd_soc_dai_get_drvdata(dai);
unsigned long r, ro, stat;
int chans, t, stype = substream->stream;
chans = params_channels(params);
r = ro = au_readl(AC97_CFG(pscdata));
stat = au_readl(AC97_STAT(pscdata));
/* already active? */
if (stat & (PSC_AC97STAT_TB | PSC_AC97STAT_RB)) {
/* reject parameters not currently set up */
if ((PSC_AC97CFG_GET_LEN(r) != params->msbits) ||
(pscdata->rate != params_rate(params)))
return -EINVAL;
} else {
/* set sample bitdepth: REG[24:21]=(BITS-2)/2 */
r &= ~PSC_AC97CFG_LEN_MASK;
r |= PSC_AC97CFG_SET_LEN(params->msbits);
/* channels: enable slots for front L/R channel */
if (stype == SNDRV_PCM_STREAM_PLAYBACK) {
r &= ~PSC_AC97CFG_TXSLOT_MASK;
r |= PSC_AC97CFG_TXSLOT_ENA(3);
r |= PSC_AC97CFG_TXSLOT_ENA(4);
} else {
r &= ~PSC_AC97CFG_RXSLOT_MASK;
r |= PSC_AC97CFG_RXSLOT_ENA(3);
r |= PSC_AC97CFG_RXSLOT_ENA(4);
}
/* do we need to poke the hardware? */
if (!(r ^ ro))
goto out;
/* ac97 engine is about to be disabled */
mutex_lock(&pscdata->lock);
/* disable AC97 device controller first... */
au_writel(r & ~PSC_AC97CFG_DE_ENABLE, AC97_CFG(pscdata));
au_sync();
/* ...wait for it... */
t = 100;
while ((au_readl(AC97_STAT(pscdata)) & PSC_AC97STAT_DR) && --t)
msleep(1);
if (!t)
printk(KERN_ERR "PSC-AC97: can't disable!\n");
/* ...write config... */
au_writel(r, AC97_CFG(pscdata));
au_sync();
/* ...enable the AC97 controller again... */
au_writel(r | PSC_AC97CFG_DE_ENABLE, AC97_CFG(pscdata));
au_sync();
/* ...and wait for ready bit */
t = 100;
while ((!(au_readl(AC97_STAT(pscdata)) & PSC_AC97STAT_DR)) && --t)
msleep(1);
if (!t)
printk(KERN_ERR "PSC-AC97: can't enable!\n");
mutex_unlock(&pscdata->lock);
pscdata->cfg = r;
pscdata->rate = params_rate(params);
}
out:
return 0;
}
static int au1xpsc_ac97_trigger(struct snd_pcm_substream *substream,
int cmd, struct snd_soc_dai *dai)
{
struct au1xpsc_audio_data *pscdata = snd_soc_dai_get_drvdata(dai);
int ret, stype = substream->stream;
ret = 0;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
au_writel(AC97PCR_CLRFIFO(stype), AC97_PCR(pscdata));
au_sync();
au_writel(AC97PCR_START(stype), AC97_PCR(pscdata));
au_sync();
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
au_writel(AC97PCR_STOP(stype), AC97_PCR(pscdata));
au_sync();
while (au_readl(AC97_STAT(pscdata)) & AC97STAT_BUSY(stype))
asm volatile ("nop");
au_writel(AC97PCR_CLRFIFO(stype), AC97_PCR(pscdata));
au_sync();
break;
default:
ret = -EINVAL;
}
return ret;
}
static int au1xpsc_ac97_startup(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct au1xpsc_audio_data *pscdata = snd_soc_dai_get_drvdata(dai);
snd_soc_dai_set_dma_data(dai, substream, &pscdata->dmaids[0]);
return 0;
}
static int au1xpsc_ac97_probe(struct snd_soc_dai *dai)
{
return au1xpsc_ac97_workdata ? 0 : -ENODEV;
}
static const struct snd_soc_dai_ops au1xpsc_ac97_dai_ops = {
.startup = au1xpsc_ac97_startup,
.trigger = au1xpsc_ac97_trigger,
.hw_params = au1xpsc_ac97_hw_params,
};
static const struct snd_soc_dai_driver au1xpsc_ac97_dai_template = {
.ac97_control = 1,
.probe = au1xpsc_ac97_probe,
.playback = {
.rates = AC97_RATES,
.formats = AC97_FMTS,
.channels_min = 2,
.channels_max = 2,
},
.capture = {
.rates = AC97_RATES,
.formats = AC97_FMTS,
.channels_min = 2,
.channels_max = 2,
},
.ops = &au1xpsc_ac97_dai_ops,
};
static int __devinit au1xpsc_ac97_drvprobe(struct platform_device *pdev)
{
int ret;
struct resource *iores, *dmares;
unsigned long sel;
struct au1xpsc_audio_data *wd;
wd = devm_kzalloc(&pdev->dev, sizeof(struct au1xpsc_audio_data),
GFP_KERNEL);
if (!wd)
return -ENOMEM;
mutex_init(&wd->lock);
iores = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!iores)
return -ENODEV;
if (!devm_request_mem_region(&pdev->dev, iores->start,
resource_size(iores),
pdev->name))
return -EBUSY;
wd->mmio = devm_ioremap(&pdev->dev, iores->start,
resource_size(iores));
if (!wd->mmio)
return -EBUSY;
dmares = platform_get_resource(pdev, IORESOURCE_DMA, 0);
if (!dmares)
return -EBUSY;
wd->dmaids[SNDRV_PCM_STREAM_PLAYBACK] = dmares->start;
dmares = platform_get_resource(pdev, IORESOURCE_DMA, 1);
if (!dmares)
return -EBUSY;
wd->dmaids[SNDRV_PCM_STREAM_CAPTURE] = dmares->start;
/* configuration: max dma trigger threshold, enable ac97 */
wd->cfg = PSC_AC97CFG_RT_FIFO8 | PSC_AC97CFG_TT_FIFO8 |
PSC_AC97CFG_DE_ENABLE;
/* preserve PSC clock source set up by platform */
sel = au_readl(PSC_SEL(wd)) & PSC_SEL_CLK_MASK;
au_writel(PSC_CTRL_DISABLE, PSC_CTRL(wd));
au_sync();
au_writel(0, PSC_SEL(wd));
au_sync();
au_writel(PSC_SEL_PS_AC97MODE | sel, PSC_SEL(wd));
au_sync();
/* name the DAI like this device instance ("au1xpsc-ac97.PSCINDEX") */
memcpy(&wd->dai_drv, &au1xpsc_ac97_dai_template,
sizeof(struct snd_soc_dai_driver));
wd->dai_drv.name = dev_name(&pdev->dev);
platform_set_drvdata(pdev, wd);
ret = snd_soc_register_dai(&pdev->dev, &wd->dai_drv);
if (ret)
return ret;
au1xpsc_ac97_workdata = wd;
return 0;
}
static int __devexit au1xpsc_ac97_drvremove(struct platform_device *pdev)
{
struct au1xpsc_audio_data *wd = platform_get_drvdata(pdev);
snd_soc_unregister_dai(&pdev->dev);
/* disable PSC completely */
au_writel(0, AC97_CFG(wd));
au_sync();
au_writel(PSC_CTRL_DISABLE, PSC_CTRL(wd));
au_sync();
au1xpsc_ac97_workdata = NULL; /* MDEV */
return 0;
}
#ifdef CONFIG_PM
static int au1xpsc_ac97_drvsuspend(struct device *dev)
{
struct au1xpsc_audio_data *wd = dev_get_drvdata(dev);
/* save interesting registers and disable PSC */
wd->pm[0] = au_readl(PSC_SEL(wd));
au_writel(0, AC97_CFG(wd));
au_sync();
au_writel(PSC_CTRL_DISABLE, PSC_CTRL(wd));
au_sync();
return 0;
}
static int au1xpsc_ac97_drvresume(struct device *dev)
{
struct au1xpsc_audio_data *wd = dev_get_drvdata(dev);
/* restore PSC clock config */
au_writel(wd->pm[0] | PSC_SEL_PS_AC97MODE, PSC_SEL(wd));
au_sync();
/* after this point the ac97 core will cold-reset the codec.
* During cold-reset the PSC is reinitialized and the last
* configuration set up in hw_params() is restored.
*/
return 0;
}
static struct dev_pm_ops au1xpscac97_pmops = {
.suspend = au1xpsc_ac97_drvsuspend,
.resume = au1xpsc_ac97_drvresume,
};
#define AU1XPSCAC97_PMOPS &au1xpscac97_pmops
#else
#define AU1XPSCAC97_PMOPS NULL
#endif
static struct platform_driver au1xpsc_ac97_driver = {
.driver = {
.name = "au1xpsc_ac97",
.owner = THIS_MODULE,
.pm = AU1XPSCAC97_PMOPS,
},
.probe = au1xpsc_ac97_drvprobe,
.remove = __devexit_p(au1xpsc_ac97_drvremove),
};
static int __init au1xpsc_ac97_load(void)
{
au1xpsc_ac97_workdata = NULL;
return platform_driver_register(&au1xpsc_ac97_driver);
}
static void __exit au1xpsc_ac97_unload(void)
{
platform_driver_unregister(&au1xpsc_ac97_driver);
}
module_init(au1xpsc_ac97_load);
module_exit(au1xpsc_ac97_unload);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Au12x0/Au1550 PSC AC97 ALSA ASoC audio driver");
MODULE_AUTHOR("Manuel Lauss");
| gpl-2.0 |
NamanArora/flamingo_kernel | drivers/rtc/rtc-m48t86.c | 5069 | 5614 | /*
* ST M48T86 / Dallas DS12887 RTC driver
* Copyright (c) 2006 Tower Technologies
*
* Author: Alessandro Zummo <a.zummo@towertech.it>
*
* 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 drivers only supports the clock running in BCD and 24H mode.
* If it will be ever adapted to binary and 12H mode, care must be taken
* to not introduce bugs.
*/
#include <linux/module.h>
#include <linux/rtc.h>
#include <linux/platform_device.h>
#include <linux/m48t86.h>
#include <linux/bcd.h>
#define M48T86_REG_SEC 0x00
#define M48T86_REG_SECALRM 0x01
#define M48T86_REG_MIN 0x02
#define M48T86_REG_MINALRM 0x03
#define M48T86_REG_HOUR 0x04
#define M48T86_REG_HOURALRM 0x05
#define M48T86_REG_DOW 0x06 /* 1 = sunday */
#define M48T86_REG_DOM 0x07
#define M48T86_REG_MONTH 0x08 /* 1 - 12 */
#define M48T86_REG_YEAR 0x09 /* 0 - 99 */
#define M48T86_REG_A 0x0A
#define M48T86_REG_B 0x0B
#define M48T86_REG_C 0x0C
#define M48T86_REG_D 0x0D
#define M48T86_REG_B_H24 (1 << 1)
#define M48T86_REG_B_DM (1 << 2)
#define M48T86_REG_B_SET (1 << 7)
#define M48T86_REG_D_VRT (1 << 7)
#define DRV_VERSION "0.1"
static int m48t86_rtc_read_time(struct device *dev, struct rtc_time *tm)
{
unsigned char reg;
struct platform_device *pdev = to_platform_device(dev);
struct m48t86_ops *ops = pdev->dev.platform_data;
reg = ops->readbyte(M48T86_REG_B);
if (reg & M48T86_REG_B_DM) {
/* data (binary) mode */
tm->tm_sec = ops->readbyte(M48T86_REG_SEC);
tm->tm_min = ops->readbyte(M48T86_REG_MIN);
tm->tm_hour = ops->readbyte(M48T86_REG_HOUR) & 0x3F;
tm->tm_mday = ops->readbyte(M48T86_REG_DOM);
/* tm_mon is 0-11 */
tm->tm_mon = ops->readbyte(M48T86_REG_MONTH) - 1;
tm->tm_year = ops->readbyte(M48T86_REG_YEAR) + 100;
tm->tm_wday = ops->readbyte(M48T86_REG_DOW);
} else {
/* bcd mode */
tm->tm_sec = bcd2bin(ops->readbyte(M48T86_REG_SEC));
tm->tm_min = bcd2bin(ops->readbyte(M48T86_REG_MIN));
tm->tm_hour = bcd2bin(ops->readbyte(M48T86_REG_HOUR) & 0x3F);
tm->tm_mday = bcd2bin(ops->readbyte(M48T86_REG_DOM));
/* tm_mon is 0-11 */
tm->tm_mon = bcd2bin(ops->readbyte(M48T86_REG_MONTH)) - 1;
tm->tm_year = bcd2bin(ops->readbyte(M48T86_REG_YEAR)) + 100;
tm->tm_wday = bcd2bin(ops->readbyte(M48T86_REG_DOW));
}
/* correct the hour if the clock is in 12h mode */
if (!(reg & M48T86_REG_B_H24))
if (ops->readbyte(M48T86_REG_HOUR) & 0x80)
tm->tm_hour += 12;
return rtc_valid_tm(tm);
}
static int m48t86_rtc_set_time(struct device *dev, struct rtc_time *tm)
{
unsigned char reg;
struct platform_device *pdev = to_platform_device(dev);
struct m48t86_ops *ops = pdev->dev.platform_data;
reg = ops->readbyte(M48T86_REG_B);
/* update flag and 24h mode */
reg |= M48T86_REG_B_SET | M48T86_REG_B_H24;
ops->writebyte(reg, M48T86_REG_B);
if (reg & M48T86_REG_B_DM) {
/* data (binary) mode */
ops->writebyte(tm->tm_sec, M48T86_REG_SEC);
ops->writebyte(tm->tm_min, M48T86_REG_MIN);
ops->writebyte(tm->tm_hour, M48T86_REG_HOUR);
ops->writebyte(tm->tm_mday, M48T86_REG_DOM);
ops->writebyte(tm->tm_mon + 1, M48T86_REG_MONTH);
ops->writebyte(tm->tm_year % 100, M48T86_REG_YEAR);
ops->writebyte(tm->tm_wday, M48T86_REG_DOW);
} else {
/* bcd mode */
ops->writebyte(bin2bcd(tm->tm_sec), M48T86_REG_SEC);
ops->writebyte(bin2bcd(tm->tm_min), M48T86_REG_MIN);
ops->writebyte(bin2bcd(tm->tm_hour), M48T86_REG_HOUR);
ops->writebyte(bin2bcd(tm->tm_mday), M48T86_REG_DOM);
ops->writebyte(bin2bcd(tm->tm_mon + 1), M48T86_REG_MONTH);
ops->writebyte(bin2bcd(tm->tm_year % 100), M48T86_REG_YEAR);
ops->writebyte(bin2bcd(tm->tm_wday), M48T86_REG_DOW);
}
/* update ended */
reg &= ~M48T86_REG_B_SET;
ops->writebyte(reg, M48T86_REG_B);
return 0;
}
static int m48t86_rtc_proc(struct device *dev, struct seq_file *seq)
{
unsigned char reg;
struct platform_device *pdev = to_platform_device(dev);
struct m48t86_ops *ops = pdev->dev.platform_data;
reg = ops->readbyte(M48T86_REG_B);
seq_printf(seq, "mode\t\t: %s\n",
(reg & M48T86_REG_B_DM) ? "binary" : "bcd");
reg = ops->readbyte(M48T86_REG_D);
seq_printf(seq, "battery\t\t: %s\n",
(reg & M48T86_REG_D_VRT) ? "ok" : "exhausted");
return 0;
}
static const struct rtc_class_ops m48t86_rtc_ops = {
.read_time = m48t86_rtc_read_time,
.set_time = m48t86_rtc_set_time,
.proc = m48t86_rtc_proc,
};
static int __devinit m48t86_rtc_probe(struct platform_device *dev)
{
unsigned char reg;
struct m48t86_ops *ops = dev->dev.platform_data;
struct rtc_device *rtc = rtc_device_register("m48t86",
&dev->dev, &m48t86_rtc_ops, THIS_MODULE);
if (IS_ERR(rtc))
return PTR_ERR(rtc);
platform_set_drvdata(dev, rtc);
/* read battery status */
reg = ops->readbyte(M48T86_REG_D);
dev_info(&dev->dev, "battery %s\n",
(reg & M48T86_REG_D_VRT) ? "ok" : "exhausted");
return 0;
}
static int __devexit m48t86_rtc_remove(struct platform_device *dev)
{
struct rtc_device *rtc = platform_get_drvdata(dev);
if (rtc)
rtc_device_unregister(rtc);
platform_set_drvdata(dev, NULL);
return 0;
}
static struct platform_driver m48t86_rtc_platform_driver = {
.driver = {
.name = "rtc-m48t86",
.owner = THIS_MODULE,
},
.probe = m48t86_rtc_probe,
.remove = __devexit_p(m48t86_rtc_remove),
};
module_platform_driver(m48t86_rtc_platform_driver);
MODULE_AUTHOR("Alessandro Zummo <a.zummo@towertech.it>");
MODULE_DESCRIPTION("M48T86 RTC driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
MODULE_ALIAS("platform:rtc-m48t86");
| gpl-2.0 |
JASON-RR/Imperium_Kernel_TW_5.0.1 | drivers/staging/usbip/userspace/libsrc/usbip_common.c | 5837 | 6539 | /*
* Copyright (C) 2005-2007 Takahiro Hirofuchi
*/
#include "usbip_common.h"
#include "names.h"
#undef PROGNAME
#define PROGNAME "libusbip"
int usbip_use_syslog = 0;
int usbip_use_stderr = 0;
int usbip_use_debug = 0;
struct speed_string {
int num;
char *speed;
char *desc;
};
static const struct speed_string speed_strings[] = {
{ USB_SPEED_UNKNOWN, "unknown", "Unknown Speed"},
{ USB_SPEED_LOW, "1.5", "Low Speed(1.5Mbps)" },
{ USB_SPEED_FULL, "12", "Full Speed(12Mbps)" },
{ USB_SPEED_HIGH, "480", "High Speed(480Mbps)" },
{ 0, NULL, NULL }
};
struct portst_string {
int num;
char *desc;
};
static struct portst_string portst_strings[] = {
{ SDEV_ST_AVAILABLE, "Device Available" },
{ SDEV_ST_USED, "Device in Use" },
{ SDEV_ST_ERROR, "Device Error"},
{ VDEV_ST_NULL, "Port Available"},
{ VDEV_ST_NOTASSIGNED, "Port Initializing"},
{ VDEV_ST_USED, "Port in Use"},
{ VDEV_ST_ERROR, "Port Error"},
{ 0, NULL}
};
const char *usbip_status_string(int32_t status)
{
for (int i=0; portst_strings[i].desc != NULL; i++)
if (portst_strings[i].num == status)
return portst_strings[i].desc;
return "Unknown Status";
}
const char *usbip_speed_string(int num)
{
for (int i=0; speed_strings[i].speed != NULL; i++)
if (speed_strings[i].num == num)
return speed_strings[i].desc;
return "Unknown Speed";
}
#define DBG_UDEV_INTEGER(name)\
dbg("%-20s = %x", to_string(name), (int) udev->name)
#define DBG_UINF_INTEGER(name)\
dbg("%-20s = %x", to_string(name), (int) uinf->name)
void dump_usb_interface(struct usbip_usb_interface *uinf)
{
char buff[100];
usbip_names_get_class(buff, sizeof(buff),
uinf->bInterfaceClass,
uinf->bInterfaceSubClass,
uinf->bInterfaceProtocol);
dbg("%-20s = %s", "Interface(C/SC/P)", buff);
}
void dump_usb_device(struct usbip_usb_device *udev)
{
char buff[100];
dbg("%-20s = %s", "path", udev->path);
dbg("%-20s = %s", "busid", udev->busid);
usbip_names_get_class(buff, sizeof(buff),
udev->bDeviceClass,
udev->bDeviceSubClass,
udev->bDeviceProtocol);
dbg("%-20s = %s", "Device(C/SC/P)", buff);
DBG_UDEV_INTEGER(bcdDevice);
usbip_names_get_product(buff, sizeof(buff),
udev->idVendor,
udev->idProduct);
dbg("%-20s = %s", "Vendor/Product", buff);
DBG_UDEV_INTEGER(bNumConfigurations);
DBG_UDEV_INTEGER(bNumInterfaces);
dbg("%-20s = %s", "speed",
usbip_speed_string(udev->speed));
DBG_UDEV_INTEGER(busnum);
DBG_UDEV_INTEGER(devnum);
}
int read_attr_value(struct sysfs_device *dev, const char *name, const char *format)
{
char attrpath[SYSFS_PATH_MAX];
struct sysfs_attribute *attr;
int num = 0;
int ret;
snprintf(attrpath, sizeof(attrpath), "%s/%s", dev->path, name);
attr = sysfs_open_attribute(attrpath);
if (!attr) {
dbg("sysfs_open_attribute failed: %s", attrpath);
return 0;
}
ret = sysfs_read_attribute(attr);
if (ret < 0) {
dbg("sysfs_read_attribute failed");
goto err;
}
ret = sscanf(attr->value, format, &num);
if (ret < 1) {
dbg("sscanf failed");
goto err;
}
err:
sysfs_close_attribute(attr);
return num;
}
int read_attr_speed(struct sysfs_device *dev)
{
char attrpath[SYSFS_PATH_MAX];
struct sysfs_attribute *attr;
char speed[100];
int ret;
snprintf(attrpath, sizeof(attrpath), "%s/%s", dev->path, "speed");
attr = sysfs_open_attribute(attrpath);
if (!attr) {
dbg("sysfs_open_attribute failed: %s", attrpath);
return 0;
}
ret = sysfs_read_attribute(attr);
if (ret < 0) {
dbg("sysfs_read_attribute failed");
goto err;
}
ret = sscanf(attr->value, "%s\n", speed);
if (ret < 1) {
dbg("sscanf failed");
goto err;
}
err:
sysfs_close_attribute(attr);
for (int i=0; speed_strings[i].speed != NULL; i++) {
if (!strcmp(speed, speed_strings[i].speed))
return speed_strings[i].num;
}
return USB_SPEED_UNKNOWN;
}
#define READ_ATTR(object, type, dev, name, format)\
do { (object)->name = (type) read_attr_value(dev, to_string(name), format); } while (0)
int read_usb_device(struct sysfs_device *sdev, struct usbip_usb_device *udev)
{
uint32_t busnum, devnum;
READ_ATTR(udev, uint8_t, sdev, bDeviceClass, "%02x\n");
READ_ATTR(udev, uint8_t, sdev, bDeviceSubClass, "%02x\n");
READ_ATTR(udev, uint8_t, sdev, bDeviceProtocol, "%02x\n");
READ_ATTR(udev, uint16_t, sdev, idVendor, "%04x\n");
READ_ATTR(udev, uint16_t, sdev, idProduct, "%04x\n");
READ_ATTR(udev, uint16_t, sdev, bcdDevice, "%04x\n");
READ_ATTR(udev, uint8_t, sdev, bConfigurationValue, "%02x\n");
READ_ATTR(udev, uint8_t, sdev, bNumConfigurations, "%02x\n");
READ_ATTR(udev, uint8_t, sdev, bNumInterfaces, "%02x\n");
READ_ATTR(udev, uint8_t, sdev, devnum, "%d\n");
udev->speed = read_attr_speed(sdev);
strncpy(udev->path, sdev->path, SYSFS_PATH_MAX);
strncpy(udev->busid, sdev->name, SYSFS_BUS_ID_SIZE);
sscanf(sdev->name, "%u-%u", &busnum, &devnum);
udev->busnum = busnum;
return 0;
}
int read_usb_interface(struct usbip_usb_device *udev, int i,
struct usbip_usb_interface *uinf)
{
char busid[SYSFS_BUS_ID_SIZE];
struct sysfs_device *sif;
sprintf(busid, "%s:%d.%d", udev->busid, udev->bConfigurationValue, i);
sif = sysfs_open_device("usb", busid);
if (!sif) {
dbg("sysfs_open_device(\"usb\", \"%s\") failed", busid);
return -1;
}
READ_ATTR(uinf, uint8_t, sif, bInterfaceClass, "%02x\n");
READ_ATTR(uinf, uint8_t, sif, bInterfaceSubClass, "%02x\n");
READ_ATTR(uinf, uint8_t, sif, bInterfaceProtocol, "%02x\n");
sysfs_close_device(sif);
return 0;
}
int usbip_names_init(char *f)
{
return names_init(f);
}
void usbip_names_free()
{
names_free();
}
void usbip_names_get_product(char *buff, size_t size, uint16_t vendor, uint16_t product)
{
const char *prod, *vend;
prod = names_product(vendor, product);
if (!prod)
prod = "unknown product";
vend = names_vendor(vendor);
if (!vend)
vend = "unknown vendor";
snprintf(buff, size, "%s : %s (%04x:%04x)", vend, prod, vendor, product);
}
void usbip_names_get_class(char *buff, size_t size, uint8_t class, uint8_t subclass, uint8_t protocol)
{
const char *c, *s, *p;
if (class == 0 && subclass == 0 && protocol == 0) {
snprintf(buff, size, "(Defined at Interface level) (%02x/%02x/%02x)", class, subclass, protocol);
return;
}
p = names_protocol(class, subclass, protocol);
if (!p)
p = "unknown protocol";
s = names_subclass(class, subclass);
if (!s)
s = "unknown subclass";
c = names_class(class);
if (!c)
c = "unknown class";
snprintf(buff, size, "%s / %s / %s (%02x/%02x/%02x)", c, s, p, class, subclass, protocol);
}
| gpl-2.0 |
raja161287/kernel_samsung_msm8930-common | drivers/pci/hotplug/acpiphp_ibm.c | 7373 | 14670 | /*
* ACPI PCI Hot Plug IBM Extension
*
* Copyright (C) 2004 Vernon Mauery <vernux@us.ibm.com>
* Copyright (C) 2004 IBM Corp.
*
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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 <vernux@us.ibm.com>
*
*/
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <acpi/acpi_bus.h>
#include <linux/sysfs.h>
#include <linux/kobject.h>
#include <asm/uaccess.h>
#include <linux/moduleparam.h>
#include <linux/pci.h>
#include "acpiphp.h"
#include "../pci.h"
#define DRIVER_VERSION "1.0.1"
#define DRIVER_AUTHOR "Irene Zubarev <zubarev@us.ibm.com>, Vernon Mauery <vernux@us.ibm.com>"
#define DRIVER_DESC "ACPI Hot Plug PCI Controller Driver IBM extension"
static bool debug;
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
MODULE_VERSION(DRIVER_VERSION);
module_param(debug, bool, 0644);
MODULE_PARM_DESC(debug, " Debugging mode enabled or not");
#define MY_NAME "acpiphp_ibm"
#undef dbg
#define dbg(format, arg...) \
do { \
if (debug) \
printk(KERN_DEBUG "%s: " format, \
MY_NAME , ## arg); \
} while (0)
#define FOUND_APCI 0x61504349
/* these are the names for the IBM ACPI pseudo-device */
#define IBM_HARDWARE_ID1 "IBM37D0"
#define IBM_HARDWARE_ID2 "IBM37D4"
#define hpslot_to_sun(A) (((struct slot *)((A)->private))->acpi_slot->sun)
/* union apci_descriptor - allows access to the
* various device descriptors that are embedded in the
* aPCI table
*/
union apci_descriptor {
struct {
char sig[4];
u8 len;
} header;
struct {
u8 type;
u8 len;
u16 slot_id;
u8 bus_id;
u8 dev_num;
u8 slot_num;
u8 slot_attr[2];
u8 attn;
u8 status[2];
u8 sun;
u8 res[3];
} slot;
struct {
u8 type;
u8 len;
} generic;
};
/* struct notification - keeps info about the device
* that cause the ACPI notification event
*/
struct notification {
struct acpi_device *device;
u8 event;
};
static int ibm_set_attention_status(struct hotplug_slot *slot, u8 status);
static int ibm_get_attention_status(struct hotplug_slot *slot, u8 *status);
static void ibm_handle_events(acpi_handle handle, u32 event, void *context);
static int ibm_get_table_from_acpi(char **bufp);
static ssize_t ibm_read_apci_table(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buffer, loff_t pos, size_t size);
static acpi_status __init ibm_find_acpi_device(acpi_handle handle,
u32 lvl, void *context, void **rv);
static int __init ibm_acpiphp_init(void);
static void __exit ibm_acpiphp_exit(void);
static acpi_handle ibm_acpi_handle;
static struct notification ibm_note;
static struct bin_attribute ibm_apci_table_attr = {
.attr = {
.name = "apci_table",
.mode = S_IRUGO,
},
.read = ibm_read_apci_table,
.write = NULL,
};
static struct acpiphp_attention_info ibm_attention_info =
{
.set_attn = ibm_set_attention_status,
.get_attn = ibm_get_attention_status,
.owner = THIS_MODULE,
};
/**
* ibm_slot_from_id - workaround for bad ibm hardware
* @id: the slot number that linux refers to the slot by
*
* Description: This method returns the aCPI slot descriptor
* corresponding to the Linux slot number. This descriptor
* has info about the aPCI slot id and attention status.
* This descriptor must be freed using kfree when done.
*/
static union apci_descriptor *ibm_slot_from_id(int id)
{
int ind = 0, size;
union apci_descriptor *ret = NULL, *des;
char *table;
size = ibm_get_table_from_acpi(&table);
des = (union apci_descriptor *)table;
if (memcmp(des->header.sig, "aPCI", 4) != 0)
goto ibm_slot_done;
des = (union apci_descriptor *)&table[ind += des->header.len];
while (ind < size && (des->generic.type != 0x82 ||
des->slot.slot_num != id)) {
des = (union apci_descriptor *)&table[ind += des->generic.len];
}
if (ind < size && des->slot.slot_num == id)
ret = des;
ibm_slot_done:
if (ret) {
ret = kmalloc(sizeof(union apci_descriptor), GFP_KERNEL);
memcpy(ret, des, sizeof(union apci_descriptor));
}
kfree(table);
return ret;
}
/**
* ibm_set_attention_status - callback method to set the attention LED
* @slot: the hotplug_slot to work with
* @status: what to set the LED to (0 or 1)
*
* Description: This method is registered with the acpiphp module as a
* callback to do the device specific task of setting the LED status.
*/
static int ibm_set_attention_status(struct hotplug_slot *slot, u8 status)
{
union acpi_object args[2];
struct acpi_object_list params = { .pointer = args, .count = 2 };
acpi_status stat;
unsigned long long rc;
union apci_descriptor *ibm_slot;
ibm_slot = ibm_slot_from_id(hpslot_to_sun(slot));
dbg("%s: set slot %d (%d) attention status to %d\n", __func__,
ibm_slot->slot.slot_num, ibm_slot->slot.slot_id,
(status ? 1 : 0));
args[0].type = ACPI_TYPE_INTEGER;
args[0].integer.value = ibm_slot->slot.slot_id;
args[1].type = ACPI_TYPE_INTEGER;
args[1].integer.value = (status) ? 1 : 0;
kfree(ibm_slot);
stat = acpi_evaluate_integer(ibm_acpi_handle, "APLS", ¶ms, &rc);
if (ACPI_FAILURE(stat)) {
err("APLS evaluation failed: 0x%08x\n", stat);
return -ENODEV;
} else if (!rc) {
err("APLS method failed: 0x%08llx\n", rc);
return -ERANGE;
}
return 0;
}
/**
* ibm_get_attention_status - callback method to get attention LED status
* @slot: the hotplug_slot to work with
* @status: returns what the LED is set to (0 or 1)
*
* Description: This method is registered with the acpiphp module as a
* callback to do the device specific task of getting the LED status.
*
* Because there is no direct method of getting the LED status directly
* from an ACPI call, we read the aPCI table and parse out our
* slot descriptor to read the status from that.
*/
static int ibm_get_attention_status(struct hotplug_slot *slot, u8 *status)
{
union apci_descriptor *ibm_slot;
ibm_slot = ibm_slot_from_id(hpslot_to_sun(slot));
if (ibm_slot->slot.attn & 0xa0 || ibm_slot->slot.status[1] & 0x08)
*status = 1;
else
*status = 0;
dbg("%s: get slot %d (%d) attention status is %d\n", __func__,
ibm_slot->slot.slot_num, ibm_slot->slot.slot_id,
*status);
kfree(ibm_slot);
return 0;
}
/**
* ibm_handle_events - listens for ACPI events for the IBM37D0 device
* @handle: an ACPI handle to the device that caused the event
* @event: the event info (device specific)
* @context: passed context (our notification struct)
*
* Description: This method is registered as a callback with the ACPI
* subsystem it is called when this device has an event to notify the OS of.
*
* The events actually come from the device as two events that get
* synthesized into one event with data by this function. The event
* ID comes first and then the slot number that caused it. We report
* this as one event to the OS.
*
* From section 5.6.2.2 of the ACPI 2.0 spec, I understand that the OSPM will
* only re-enable the interrupt that causes this event AFTER this method
* has returned, thereby enforcing serial access for the notification struct.
*/
static void ibm_handle_events(acpi_handle handle, u32 event, void *context)
{
u8 detail = event & 0x0f;
u8 subevent = event & 0xf0;
struct notification *note = context;
dbg("%s: Received notification %02x\n", __func__, event);
if (subevent == 0x80) {
dbg("%s: generationg bus event\n", __func__);
acpi_bus_generate_proc_event(note->device, note->event, detail);
acpi_bus_generate_netlink_event(note->device->pnp.device_class,
dev_name(¬e->device->dev),
note->event, detail);
} else
note->event = event;
}
/**
* ibm_get_table_from_acpi - reads the APLS buffer from ACPI
* @bufp: address to pointer to allocate for the table
*
* Description: This method reads the APLS buffer in from ACPI and
* stores the "stripped" table into a single buffer
* it allocates and passes the address back in bufp.
*
* If NULL is passed in as buffer, this method only calculates
* the size of the table and returns that without filling
* in the buffer.
*
* Returns < 0 on error or the size of the table on success.
*/
static int ibm_get_table_from_acpi(char **bufp)
{
union acpi_object *package;
struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
acpi_status status;
char *lbuf = NULL;
int i, size = -EIO;
status = acpi_evaluate_object(ibm_acpi_handle, "APCI", NULL, &buffer);
if (ACPI_FAILURE(status)) {
err("%s: APCI evaluation failed\n", __func__);
return -ENODEV;
}
package = (union acpi_object *) buffer.pointer;
if (!(package) ||
(package->type != ACPI_TYPE_PACKAGE) ||
!(package->package.elements)) {
err("%s: Invalid APCI object\n", __func__);
goto read_table_done;
}
for(size = 0, i = 0; i < package->package.count; i++) {
if (package->package.elements[i].type != ACPI_TYPE_BUFFER) {
err("%s: Invalid APCI element %d\n", __func__, i);
goto read_table_done;
}
size += package->package.elements[i].buffer.length;
}
if (bufp == NULL)
goto read_table_done;
lbuf = kzalloc(size, GFP_KERNEL);
dbg("%s: element count: %i, ASL table size: %i, &table = 0x%p\n",
__func__, package->package.count, size, lbuf);
if (lbuf) {
*bufp = lbuf;
} else {
size = -ENOMEM;
goto read_table_done;
}
size = 0;
for (i=0; i<package->package.count; i++) {
memcpy(&lbuf[size],
package->package.elements[i].buffer.pointer,
package->package.elements[i].buffer.length);
size += package->package.elements[i].buffer.length;
}
read_table_done:
kfree(buffer.pointer);
return size;
}
/**
* ibm_read_apci_table - callback for the sysfs apci_table file
* @filp: the open sysfs file
* @kobj: the kobject this binary attribute is a part of
* @bin_attr: struct bin_attribute for this file
* @buffer: the kernel space buffer to fill
* @pos: the offset into the file
* @size: the number of bytes requested
*
* Description: Gets registered with sysfs as the reader callback
* to be executed when /sys/bus/pci/slots/apci_table gets read.
*
* Since we don't get notified on open and close for this file,
* things get really tricky here...
* our solution is to only allow reading the table in all at once.
*/
static ssize_t ibm_read_apci_table(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buffer, loff_t pos, size_t size)
{
int bytes_read = -EINVAL;
char *table = NULL;
dbg("%s: pos = %d, size = %zd\n", __func__, (int)pos, size);
if (pos == 0) {
bytes_read = ibm_get_table_from_acpi(&table);
if (bytes_read > 0 && bytes_read <= size)
memcpy(buffer, table, bytes_read);
kfree(table);
}
return bytes_read;
}
/**
* ibm_find_acpi_device - callback to find our ACPI device
* @handle: the ACPI handle of the device we are inspecting
* @lvl: depth into the namespace tree
* @context: a pointer to our handle to fill when we find the device
* @rv: a return value to fill if desired
*
* Description: Used as a callback when calling acpi_walk_namespace
* to find our device. When this method returns non-zero
* acpi_walk_namespace quits its search and returns our value.
*/
static acpi_status __init ibm_find_acpi_device(acpi_handle handle,
u32 lvl, void *context, void **rv)
{
acpi_handle *phandle = (acpi_handle *)context;
acpi_status status;
struct acpi_device_info *info;
int retval = 0;
status = acpi_get_object_info(handle, &info);
if (ACPI_FAILURE(status)) {
err("%s: Failed to get device information status=0x%x\n",
__func__, status);
return retval;
}
if (info->current_status && (info->valid & ACPI_VALID_HID) &&
(!strcmp(info->hardware_id.string, IBM_HARDWARE_ID1) ||
!strcmp(info->hardware_id.string, IBM_HARDWARE_ID2))) {
dbg("found hardware: %s, handle: %p\n",
info->hardware_id.string, handle);
*phandle = handle;
/* returning non-zero causes the search to stop
* and returns this value to the caller of
* acpi_walk_namespace, but it also causes some warnings
* in the acpi debug code to print...
*/
retval = FOUND_APCI;
}
kfree(info);
return retval;
}
static int __init ibm_acpiphp_init(void)
{
int retval = 0;
acpi_status status;
struct acpi_device *device;
struct kobject *sysdir = &pci_slots_kset->kobj;
dbg("%s\n", __func__);
if (acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
ACPI_UINT32_MAX, ibm_find_acpi_device, NULL,
&ibm_acpi_handle, NULL) != FOUND_APCI) {
err("%s: acpi_walk_namespace failed\n", __func__);
retval = -ENODEV;
goto init_return;
}
dbg("%s: found IBM aPCI device\n", __func__);
if (acpi_bus_get_device(ibm_acpi_handle, &device)) {
err("%s: acpi_bus_get_device failed\n", __func__);
retval = -ENODEV;
goto init_return;
}
if (acpiphp_register_attention(&ibm_attention_info)) {
retval = -ENODEV;
goto init_return;
}
ibm_note.device = device;
status = acpi_install_notify_handler(ibm_acpi_handle,
ACPI_DEVICE_NOTIFY, ibm_handle_events,
&ibm_note);
if (ACPI_FAILURE(status)) {
err("%s: Failed to register notification handler\n",
__func__);
retval = -EBUSY;
goto init_cleanup;
}
ibm_apci_table_attr.size = ibm_get_table_from_acpi(NULL);
retval = sysfs_create_bin_file(sysdir, &ibm_apci_table_attr);
return retval;
init_cleanup:
acpiphp_unregister_attention(&ibm_attention_info);
init_return:
return retval;
}
static void __exit ibm_acpiphp_exit(void)
{
acpi_status status;
struct kobject *sysdir = &pci_slots_kset->kobj;
dbg("%s\n", __func__);
if (acpiphp_unregister_attention(&ibm_attention_info))
err("%s: attention info deregistration failed", __func__);
status = acpi_remove_notify_handler(
ibm_acpi_handle,
ACPI_DEVICE_NOTIFY,
ibm_handle_events);
if (ACPI_FAILURE(status))
err("%s: Notification handler removal failed\n", __func__);
/* remove the /sys entries */
sysfs_remove_bin_file(sysdir, &ibm_apci_table_attr);
}
module_init(ibm_acpiphp_init);
module_exit(ibm_acpiphp_exit);
| gpl-2.0 |
pvanhoof/kernel | drivers/isdn/capi/kcapi_proc.c | 9677 | 7547 | /*
* Kernel CAPI 2.0 Module - /proc/capi handling
*
* Copyright 1999 by Carsten Paeth <calle@calle.de>
* Copyright 2002 by Kai Germaschewski <kai@germaschewski.name>
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
*/
#include "kcapi.h"
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/init.h>
#include <linux/export.h>
static char *state2str(unsigned short state)
{
switch (state) {
case CAPI_CTR_DETECTED: return "detected";
case CAPI_CTR_LOADING: return "loading";
case CAPI_CTR_RUNNING: return "running";
default: return "???";
}
}
// /proc/capi
// ===========================================================================
// /proc/capi/controller:
// cnr driver cardstate name driverinfo
// /proc/capi/contrstats:
// cnr nrecvctlpkt nrecvdatapkt nsentctlpkt nsentdatapkt
// ---------------------------------------------------------------------------
static void *controller_start(struct seq_file *seq, loff_t *pos)
__acquires(capi_controller_lock)
{
mutex_lock(&capi_controller_lock);
if (*pos < CAPI_MAXCONTR)
return &capi_controller[*pos];
return NULL;
}
static void *controller_next(struct seq_file *seq, void *v, loff_t *pos)
{
++*pos;
if (*pos < CAPI_MAXCONTR)
return &capi_controller[*pos];
return NULL;
}
static void controller_stop(struct seq_file *seq, void *v)
__releases(capi_controller_lock)
{
mutex_unlock(&capi_controller_lock);
}
static int controller_show(struct seq_file *seq, void *v)
{
struct capi_ctr *ctr = *(struct capi_ctr **) v;
if (!ctr)
return 0;
seq_printf(seq, "%d %-10s %-8s %-16s %s\n",
ctr->cnr, ctr->driver_name,
state2str(ctr->state),
ctr->name,
ctr->procinfo ? ctr->procinfo(ctr) : "");
return 0;
}
static int contrstats_show(struct seq_file *seq, void *v)
{
struct capi_ctr *ctr = *(struct capi_ctr **) v;
if (!ctr)
return 0;
seq_printf(seq, "%d %lu %lu %lu %lu\n",
ctr->cnr,
ctr->nrecvctlpkt,
ctr->nrecvdatapkt,
ctr->nsentctlpkt,
ctr->nsentdatapkt);
return 0;
}
static const struct seq_operations seq_controller_ops = {
.start = controller_start,
.next = controller_next,
.stop = controller_stop,
.show = controller_show,
};
static const struct seq_operations seq_contrstats_ops = {
.start = controller_start,
.next = controller_next,
.stop = controller_stop,
.show = contrstats_show,
};
static int seq_controller_open(struct inode *inode, struct file *file)
{
return seq_open(file, &seq_controller_ops);
}
static int seq_contrstats_open(struct inode *inode, struct file *file)
{
return seq_open(file, &seq_contrstats_ops);
}
static const struct file_operations proc_controller_ops = {
.owner = THIS_MODULE,
.open = seq_controller_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
static const struct file_operations proc_contrstats_ops = {
.owner = THIS_MODULE,
.open = seq_contrstats_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
// /proc/capi/applications:
// applid l3cnt dblkcnt dblklen #ncci recvqueuelen
// /proc/capi/applstats:
// applid nrecvctlpkt nrecvdatapkt nsentctlpkt nsentdatapkt
// ---------------------------------------------------------------------------
static void *applications_start(struct seq_file *seq, loff_t *pos)
__acquires(capi_controller_lock)
{
mutex_lock(&capi_controller_lock);
if (*pos < CAPI_MAXAPPL)
return &capi_applications[*pos];
return NULL;
}
static void *
applications_next(struct seq_file *seq, void *v, loff_t *pos)
{
++*pos;
if (*pos < CAPI_MAXAPPL)
return &capi_applications[*pos];
return NULL;
}
static void applications_stop(struct seq_file *seq, void *v)
__releases(capi_controller_lock)
{
mutex_unlock(&capi_controller_lock);
}
static int
applications_show(struct seq_file *seq, void *v)
{
struct capi20_appl *ap = *(struct capi20_appl **) v;
if (!ap)
return 0;
seq_printf(seq, "%u %d %d %d\n",
ap->applid,
ap->rparam.level3cnt,
ap->rparam.datablkcnt,
ap->rparam.datablklen);
return 0;
}
static int
applstats_show(struct seq_file *seq, void *v)
{
struct capi20_appl *ap = *(struct capi20_appl **) v;
if (!ap)
return 0;
seq_printf(seq, "%u %lu %lu %lu %lu\n",
ap->applid,
ap->nrecvctlpkt,
ap->nrecvdatapkt,
ap->nsentctlpkt,
ap->nsentdatapkt);
return 0;
}
static const struct seq_operations seq_applications_ops = {
.start = applications_start,
.next = applications_next,
.stop = applications_stop,
.show = applications_show,
};
static const struct seq_operations seq_applstats_ops = {
.start = applications_start,
.next = applications_next,
.stop = applications_stop,
.show = applstats_show,
};
static int
seq_applications_open(struct inode *inode, struct file *file)
{
return seq_open(file, &seq_applications_ops);
}
static int
seq_applstats_open(struct inode *inode, struct file *file)
{
return seq_open(file, &seq_applstats_ops);
}
static const struct file_operations proc_applications_ops = {
.owner = THIS_MODULE,
.open = seq_applications_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
static const struct file_operations proc_applstats_ops = {
.owner = THIS_MODULE,
.open = seq_applstats_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
// ---------------------------------------------------------------------------
static void *capi_driver_start(struct seq_file *seq, loff_t *pos)
__acquires(&capi_drivers_lock)
{
mutex_lock(&capi_drivers_lock);
return seq_list_start(&capi_drivers, *pos);
}
static void *capi_driver_next(struct seq_file *seq, void *v, loff_t *pos)
{
return seq_list_next(v, &capi_drivers, pos);
}
static void capi_driver_stop(struct seq_file *seq, void *v)
__releases(&capi_drivers_lock)
{
mutex_unlock(&capi_drivers_lock);
}
static int capi_driver_show(struct seq_file *seq, void *v)
{
struct capi_driver *drv = list_entry(v, struct capi_driver, list);
seq_printf(seq, "%-32s %s\n", drv->name, drv->revision);
return 0;
}
static const struct seq_operations seq_capi_driver_ops = {
.start = capi_driver_start,
.next = capi_driver_next,
.stop = capi_driver_stop,
.show = capi_driver_show,
};
static int
seq_capi_driver_open(struct inode *inode, struct file *file)
{
int err;
err = seq_open(file, &seq_capi_driver_ops);
return err;
}
static const struct file_operations proc_driver_ops = {
.owner = THIS_MODULE,
.open = seq_capi_driver_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
// ---------------------------------------------------------------------------
void __init
kcapi_proc_init(void)
{
proc_mkdir("capi", NULL);
proc_mkdir("capi/controllers", NULL);
proc_create("capi/controller", 0, NULL, &proc_controller_ops);
proc_create("capi/contrstats", 0, NULL, &proc_contrstats_ops);
proc_create("capi/applications", 0, NULL, &proc_applications_ops);
proc_create("capi/applstats", 0, NULL, &proc_applstats_ops);
proc_create("capi/driver", 0, NULL, &proc_driver_ops);
}
void __exit
kcapi_proc_exit(void)
{
remove_proc_entry("capi/driver", NULL);
remove_proc_entry("capi/controller", NULL);
remove_proc_entry("capi/contrstats", NULL);
remove_proc_entry("capi/applications", NULL);
remove_proc_entry("capi/applstats", NULL);
remove_proc_entry("capi/controllers", NULL);
remove_proc_entry("capi", NULL);
}
| gpl-2.0 |
Hellybean/android_kernel_lge_hammerhead | drivers/net/ethernet/intel/ixgb/ixgb_ee.c | 9677 | 17466 | /*******************************************************************************
Intel PRO/10GbE Linux driver
Copyright(c) 1999 - 2008 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
Linux NICS <linux.nics@intel.com>
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include "ixgb_hw.h"
#include "ixgb_ee.h"
/* Local prototypes */
static u16 ixgb_shift_in_bits(struct ixgb_hw *hw);
static void ixgb_shift_out_bits(struct ixgb_hw *hw,
u16 data,
u16 count);
static void ixgb_standby_eeprom(struct ixgb_hw *hw);
static bool ixgb_wait_eeprom_command(struct ixgb_hw *hw);
static void ixgb_cleanup_eeprom(struct ixgb_hw *hw);
/******************************************************************************
* Raises the EEPROM's clock input.
*
* hw - Struct containing variables accessed by shared code
* eecd_reg - EECD's current value
*****************************************************************************/
static void
ixgb_raise_clock(struct ixgb_hw *hw,
u32 *eecd_reg)
{
/* Raise the clock input to the EEPROM (by setting the SK bit), and then
* wait 50 microseconds.
*/
*eecd_reg = *eecd_reg | IXGB_EECD_SK;
IXGB_WRITE_REG(hw, EECD, *eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
}
/******************************************************************************
* Lowers the EEPROM's clock input.
*
* hw - Struct containing variables accessed by shared code
* eecd_reg - EECD's current value
*****************************************************************************/
static void
ixgb_lower_clock(struct ixgb_hw *hw,
u32 *eecd_reg)
{
/* Lower the clock input to the EEPROM (by clearing the SK bit), and then
* wait 50 microseconds.
*/
*eecd_reg = *eecd_reg & ~IXGB_EECD_SK;
IXGB_WRITE_REG(hw, EECD, *eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
}
/******************************************************************************
* Shift data bits out to the EEPROM.
*
* hw - Struct containing variables accessed by shared code
* data - data to send to the EEPROM
* count - number of bits to shift out
*****************************************************************************/
static void
ixgb_shift_out_bits(struct ixgb_hw *hw,
u16 data,
u16 count)
{
u32 eecd_reg;
u32 mask;
/* We need to shift "count" bits out to the EEPROM. So, value in the
* "data" parameter will be shifted out to the EEPROM one bit at a time.
* In order to do this, "data" must be broken down into bits.
*/
mask = 0x01 << (count - 1);
eecd_reg = IXGB_READ_REG(hw, EECD);
eecd_reg &= ~(IXGB_EECD_DO | IXGB_EECD_DI);
do {
/* A "1" is shifted out to the EEPROM by setting bit "DI" to a "1",
* and then raising and then lowering the clock (the SK bit controls
* the clock input to the EEPROM). A "0" is shifted out to the EEPROM
* by setting "DI" to "0" and then raising and then lowering the clock.
*/
eecd_reg &= ~IXGB_EECD_DI;
if (data & mask)
eecd_reg |= IXGB_EECD_DI;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
ixgb_raise_clock(hw, &eecd_reg);
ixgb_lower_clock(hw, &eecd_reg);
mask = mask >> 1;
} while (mask);
/* We leave the "DI" bit set to "0" when we leave this routine. */
eecd_reg &= ~IXGB_EECD_DI;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
}
/******************************************************************************
* Shift data bits in from the EEPROM
*
* hw - Struct containing variables accessed by shared code
*****************************************************************************/
static u16
ixgb_shift_in_bits(struct ixgb_hw *hw)
{
u32 eecd_reg;
u32 i;
u16 data;
/* In order to read a register from the EEPROM, we need to shift 16 bits
* in from the EEPROM. Bits are "shifted in" by raising the clock input to
* the EEPROM (setting the SK bit), and then reading the value of the "DO"
* bit. During this "shifting in" process the "DI" bit should always be
* clear..
*/
eecd_reg = IXGB_READ_REG(hw, EECD);
eecd_reg &= ~(IXGB_EECD_DO | IXGB_EECD_DI);
data = 0;
for (i = 0; i < 16; i++) {
data = data << 1;
ixgb_raise_clock(hw, &eecd_reg);
eecd_reg = IXGB_READ_REG(hw, EECD);
eecd_reg &= ~(IXGB_EECD_DI);
if (eecd_reg & IXGB_EECD_DO)
data |= 1;
ixgb_lower_clock(hw, &eecd_reg);
}
return data;
}
/******************************************************************************
* Prepares EEPROM for access
*
* hw - Struct containing variables accessed by shared code
*
* Lowers EEPROM clock. Clears input pin. Sets the chip select pin. This
* function should be called before issuing a command to the EEPROM.
*****************************************************************************/
static void
ixgb_setup_eeprom(struct ixgb_hw *hw)
{
u32 eecd_reg;
eecd_reg = IXGB_READ_REG(hw, EECD);
/* Clear SK and DI */
eecd_reg &= ~(IXGB_EECD_SK | IXGB_EECD_DI);
IXGB_WRITE_REG(hw, EECD, eecd_reg);
/* Set CS */
eecd_reg |= IXGB_EECD_CS;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
}
/******************************************************************************
* Returns EEPROM to a "standby" state
*
* hw - Struct containing variables accessed by shared code
*****************************************************************************/
static void
ixgb_standby_eeprom(struct ixgb_hw *hw)
{
u32 eecd_reg;
eecd_reg = IXGB_READ_REG(hw, EECD);
/* Deselect EEPROM */
eecd_reg &= ~(IXGB_EECD_CS | IXGB_EECD_SK);
IXGB_WRITE_REG(hw, EECD, eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
/* Clock high */
eecd_reg |= IXGB_EECD_SK;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
/* Select EEPROM */
eecd_reg |= IXGB_EECD_CS;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
/* Clock low */
eecd_reg &= ~IXGB_EECD_SK;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
}
/******************************************************************************
* Raises then lowers the EEPROM's clock pin
*
* hw - Struct containing variables accessed by shared code
*****************************************************************************/
static void
ixgb_clock_eeprom(struct ixgb_hw *hw)
{
u32 eecd_reg;
eecd_reg = IXGB_READ_REG(hw, EECD);
/* Rising edge of clock */
eecd_reg |= IXGB_EECD_SK;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
/* Falling edge of clock */
eecd_reg &= ~IXGB_EECD_SK;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
}
/******************************************************************************
* Terminates a command by lowering the EEPROM's chip select pin
*
* hw - Struct containing variables accessed by shared code
*****************************************************************************/
static void
ixgb_cleanup_eeprom(struct ixgb_hw *hw)
{
u32 eecd_reg;
eecd_reg = IXGB_READ_REG(hw, EECD);
eecd_reg &= ~(IXGB_EECD_CS | IXGB_EECD_DI);
IXGB_WRITE_REG(hw, EECD, eecd_reg);
ixgb_clock_eeprom(hw);
}
/******************************************************************************
* Waits for the EEPROM to finish the current command.
*
* hw - Struct containing variables accessed by shared code
*
* The command is done when the EEPROM's data out pin goes high.
*
* Returns:
* true: EEPROM data pin is high before timeout.
* false: Time expired.
*****************************************************************************/
static bool
ixgb_wait_eeprom_command(struct ixgb_hw *hw)
{
u32 eecd_reg;
u32 i;
/* Toggle the CS line. This in effect tells to EEPROM to actually execute
* the command in question.
*/
ixgb_standby_eeprom(hw);
/* Now read DO repeatedly until is high (equal to '1'). The EEPROM will
* signal that the command has been completed by raising the DO signal.
* If DO does not go high in 10 milliseconds, then error out.
*/
for (i = 0; i < 200; i++) {
eecd_reg = IXGB_READ_REG(hw, EECD);
if (eecd_reg & IXGB_EECD_DO)
return true;
udelay(50);
}
ASSERT(0);
return false;
}
/******************************************************************************
* Verifies that the EEPROM has a valid checksum
*
* hw - Struct containing variables accessed by shared code
*
* Reads the first 64 16 bit words of the EEPROM and sums the values read.
* If the sum of the 64 16 bit words is 0xBABA, the EEPROM's checksum is
* valid.
*
* Returns:
* true: Checksum is valid
* false: Checksum is not valid.
*****************************************************************************/
bool
ixgb_validate_eeprom_checksum(struct ixgb_hw *hw)
{
u16 checksum = 0;
u16 i;
for (i = 0; i < (EEPROM_CHECKSUM_REG + 1); i++)
checksum += ixgb_read_eeprom(hw, i);
if (checksum == (u16) EEPROM_SUM)
return true;
else
return false;
}
/******************************************************************************
* Calculates the EEPROM checksum and writes it to the EEPROM
*
* hw - Struct containing variables accessed by shared code
*
* Sums the first 63 16 bit words of the EEPROM. Subtracts the sum from 0xBABA.
* Writes the difference to word offset 63 of the EEPROM.
*****************************************************************************/
void
ixgb_update_eeprom_checksum(struct ixgb_hw *hw)
{
u16 checksum = 0;
u16 i;
for (i = 0; i < EEPROM_CHECKSUM_REG; i++)
checksum += ixgb_read_eeprom(hw, i);
checksum = (u16) EEPROM_SUM - checksum;
ixgb_write_eeprom(hw, EEPROM_CHECKSUM_REG, checksum);
}
/******************************************************************************
* Writes a 16 bit word to a given offset in the EEPROM.
*
* hw - Struct containing variables accessed by shared code
* reg - offset within the EEPROM to be written to
* data - 16 bit word to be written to the EEPROM
*
* If ixgb_update_eeprom_checksum is not called after this function, the
* EEPROM will most likely contain an invalid checksum.
*
*****************************************************************************/
void
ixgb_write_eeprom(struct ixgb_hw *hw, u16 offset, u16 data)
{
struct ixgb_ee_map_type *ee_map = (struct ixgb_ee_map_type *)hw->eeprom;
/* Prepare the EEPROM for writing */
ixgb_setup_eeprom(hw);
/* Send the 9-bit EWEN (write enable) command to the EEPROM (5-bit opcode
* plus 4-bit dummy). This puts the EEPROM into write/erase mode.
*/
ixgb_shift_out_bits(hw, EEPROM_EWEN_OPCODE, 5);
ixgb_shift_out_bits(hw, 0, 4);
/* Prepare the EEPROM */
ixgb_standby_eeprom(hw);
/* Send the Write command (3-bit opcode + 6-bit addr) */
ixgb_shift_out_bits(hw, EEPROM_WRITE_OPCODE, 3);
ixgb_shift_out_bits(hw, offset, 6);
/* Send the data */
ixgb_shift_out_bits(hw, data, 16);
ixgb_wait_eeprom_command(hw);
/* Recover from write */
ixgb_standby_eeprom(hw);
/* Send the 9-bit EWDS (write disable) command to the EEPROM (5-bit
* opcode plus 4-bit dummy). This takes the EEPROM out of write/erase
* mode.
*/
ixgb_shift_out_bits(hw, EEPROM_EWDS_OPCODE, 5);
ixgb_shift_out_bits(hw, 0, 4);
/* Done with writing */
ixgb_cleanup_eeprom(hw);
/* clear the init_ctrl_reg_1 to signify that the cache is invalidated */
ee_map->init_ctrl_reg_1 = cpu_to_le16(EEPROM_ICW1_SIGNATURE_CLEAR);
}
/******************************************************************************
* Reads a 16 bit word from the EEPROM.
*
* hw - Struct containing variables accessed by shared code
* offset - offset of 16 bit word in the EEPROM to read
*
* Returns:
* The 16-bit value read from the eeprom
*****************************************************************************/
u16
ixgb_read_eeprom(struct ixgb_hw *hw,
u16 offset)
{
u16 data;
/* Prepare the EEPROM for reading */
ixgb_setup_eeprom(hw);
/* Send the READ command (opcode + addr) */
ixgb_shift_out_bits(hw, EEPROM_READ_OPCODE, 3);
/*
* We have a 64 word EEPROM, there are 6 address bits
*/
ixgb_shift_out_bits(hw, offset, 6);
/* Read the data */
data = ixgb_shift_in_bits(hw);
/* End this read operation */
ixgb_standby_eeprom(hw);
return data;
}
/******************************************************************************
* Reads eeprom and stores data in shared structure.
* Validates eeprom checksum and eeprom signature.
*
* hw - Struct containing variables accessed by shared code
*
* Returns:
* true: if eeprom read is successful
* false: otherwise.
*****************************************************************************/
bool
ixgb_get_eeprom_data(struct ixgb_hw *hw)
{
u16 i;
u16 checksum = 0;
struct ixgb_ee_map_type *ee_map;
ENTER();
ee_map = (struct ixgb_ee_map_type *)hw->eeprom;
pr_debug("Reading eeprom data\n");
for (i = 0; i < IXGB_EEPROM_SIZE ; i++) {
u16 ee_data;
ee_data = ixgb_read_eeprom(hw, i);
checksum += ee_data;
hw->eeprom[i] = cpu_to_le16(ee_data);
}
if (checksum != (u16) EEPROM_SUM) {
pr_debug("Checksum invalid\n");
/* clear the init_ctrl_reg_1 to signify that the cache is
* invalidated */
ee_map->init_ctrl_reg_1 = cpu_to_le16(EEPROM_ICW1_SIGNATURE_CLEAR);
return false;
}
if ((ee_map->init_ctrl_reg_1 & cpu_to_le16(EEPROM_ICW1_SIGNATURE_MASK))
!= cpu_to_le16(EEPROM_ICW1_SIGNATURE_VALID)) {
pr_debug("Signature invalid\n");
return false;
}
return true;
}
/******************************************************************************
* Local function to check if the eeprom signature is good
* If the eeprom signature is good, calls ixgb)get_eeprom_data.
*
* hw - Struct containing variables accessed by shared code
*
* Returns:
* true: eeprom signature was good and the eeprom read was successful
* false: otherwise.
******************************************************************************/
static bool
ixgb_check_and_get_eeprom_data (struct ixgb_hw* hw)
{
struct ixgb_ee_map_type *ee_map = (struct ixgb_ee_map_type *)hw->eeprom;
if ((ee_map->init_ctrl_reg_1 & cpu_to_le16(EEPROM_ICW1_SIGNATURE_MASK))
== cpu_to_le16(EEPROM_ICW1_SIGNATURE_VALID)) {
return true;
} else {
return ixgb_get_eeprom_data(hw);
}
}
/******************************************************************************
* return a word from the eeprom
*
* hw - Struct containing variables accessed by shared code
* index - Offset of eeprom word
*
* Returns:
* Word at indexed offset in eeprom, if valid, 0 otherwise.
******************************************************************************/
__le16
ixgb_get_eeprom_word(struct ixgb_hw *hw, u16 index)
{
if (index < IXGB_EEPROM_SIZE && ixgb_check_and_get_eeprom_data(hw))
return hw->eeprom[index];
return 0;
}
/******************************************************************************
* return the mac address from EEPROM
*
* hw - Struct containing variables accessed by shared code
* mac_addr - Ethernet Address if EEPROM contents are valid, 0 otherwise
*
* Returns: None.
******************************************************************************/
void
ixgb_get_ee_mac_addr(struct ixgb_hw *hw,
u8 *mac_addr)
{
int i;
struct ixgb_ee_map_type *ee_map = (struct ixgb_ee_map_type *)hw->eeprom;
ENTER();
if (ixgb_check_and_get_eeprom_data(hw)) {
for (i = 0; i < ETH_ALEN; i++) {
mac_addr[i] = ee_map->mac_addr[i];
}
pr_debug("eeprom mac address = %pM\n", mac_addr);
}
}
/******************************************************************************
* return the Printed Board Assembly number from EEPROM
*
* hw - Struct containing variables accessed by shared code
*
* Returns:
* PBA number if EEPROM contents are valid, 0 otherwise
******************************************************************************/
u32
ixgb_get_ee_pba_number(struct ixgb_hw *hw)
{
if (ixgb_check_and_get_eeprom_data(hw))
return le16_to_cpu(hw->eeprom[EEPROM_PBA_1_2_REG])
| (le16_to_cpu(hw->eeprom[EEPROM_PBA_3_4_REG])<<16);
return 0;
}
/******************************************************************************
* return the Device Id from EEPROM
*
* hw - Struct containing variables accessed by shared code
*
* Returns:
* Device Id if EEPROM contents are valid, 0 otherwise
******************************************************************************/
u16
ixgb_get_ee_device_id(struct ixgb_hw *hw)
{
struct ixgb_ee_map_type *ee_map = (struct ixgb_ee_map_type *)hw->eeprom;
if (ixgb_check_and_get_eeprom_data(hw))
return le16_to_cpu(ee_map->device_id);
return 0;
}
| gpl-2.0 |
GranPC/linux-asus-flo | drivers/net/ethernet/intel/ixgb/ixgb_ee.c | 9677 | 17466 | /*******************************************************************************
Intel PRO/10GbE Linux driver
Copyright(c) 1999 - 2008 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
Linux NICS <linux.nics@intel.com>
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include "ixgb_hw.h"
#include "ixgb_ee.h"
/* Local prototypes */
static u16 ixgb_shift_in_bits(struct ixgb_hw *hw);
static void ixgb_shift_out_bits(struct ixgb_hw *hw,
u16 data,
u16 count);
static void ixgb_standby_eeprom(struct ixgb_hw *hw);
static bool ixgb_wait_eeprom_command(struct ixgb_hw *hw);
static void ixgb_cleanup_eeprom(struct ixgb_hw *hw);
/******************************************************************************
* Raises the EEPROM's clock input.
*
* hw - Struct containing variables accessed by shared code
* eecd_reg - EECD's current value
*****************************************************************************/
static void
ixgb_raise_clock(struct ixgb_hw *hw,
u32 *eecd_reg)
{
/* Raise the clock input to the EEPROM (by setting the SK bit), and then
* wait 50 microseconds.
*/
*eecd_reg = *eecd_reg | IXGB_EECD_SK;
IXGB_WRITE_REG(hw, EECD, *eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
}
/******************************************************************************
* Lowers the EEPROM's clock input.
*
* hw - Struct containing variables accessed by shared code
* eecd_reg - EECD's current value
*****************************************************************************/
static void
ixgb_lower_clock(struct ixgb_hw *hw,
u32 *eecd_reg)
{
/* Lower the clock input to the EEPROM (by clearing the SK bit), and then
* wait 50 microseconds.
*/
*eecd_reg = *eecd_reg & ~IXGB_EECD_SK;
IXGB_WRITE_REG(hw, EECD, *eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
}
/******************************************************************************
* Shift data bits out to the EEPROM.
*
* hw - Struct containing variables accessed by shared code
* data - data to send to the EEPROM
* count - number of bits to shift out
*****************************************************************************/
static void
ixgb_shift_out_bits(struct ixgb_hw *hw,
u16 data,
u16 count)
{
u32 eecd_reg;
u32 mask;
/* We need to shift "count" bits out to the EEPROM. So, value in the
* "data" parameter will be shifted out to the EEPROM one bit at a time.
* In order to do this, "data" must be broken down into bits.
*/
mask = 0x01 << (count - 1);
eecd_reg = IXGB_READ_REG(hw, EECD);
eecd_reg &= ~(IXGB_EECD_DO | IXGB_EECD_DI);
do {
/* A "1" is shifted out to the EEPROM by setting bit "DI" to a "1",
* and then raising and then lowering the clock (the SK bit controls
* the clock input to the EEPROM). A "0" is shifted out to the EEPROM
* by setting "DI" to "0" and then raising and then lowering the clock.
*/
eecd_reg &= ~IXGB_EECD_DI;
if (data & mask)
eecd_reg |= IXGB_EECD_DI;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
ixgb_raise_clock(hw, &eecd_reg);
ixgb_lower_clock(hw, &eecd_reg);
mask = mask >> 1;
} while (mask);
/* We leave the "DI" bit set to "0" when we leave this routine. */
eecd_reg &= ~IXGB_EECD_DI;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
}
/******************************************************************************
* Shift data bits in from the EEPROM
*
* hw - Struct containing variables accessed by shared code
*****************************************************************************/
static u16
ixgb_shift_in_bits(struct ixgb_hw *hw)
{
u32 eecd_reg;
u32 i;
u16 data;
/* In order to read a register from the EEPROM, we need to shift 16 bits
* in from the EEPROM. Bits are "shifted in" by raising the clock input to
* the EEPROM (setting the SK bit), and then reading the value of the "DO"
* bit. During this "shifting in" process the "DI" bit should always be
* clear..
*/
eecd_reg = IXGB_READ_REG(hw, EECD);
eecd_reg &= ~(IXGB_EECD_DO | IXGB_EECD_DI);
data = 0;
for (i = 0; i < 16; i++) {
data = data << 1;
ixgb_raise_clock(hw, &eecd_reg);
eecd_reg = IXGB_READ_REG(hw, EECD);
eecd_reg &= ~(IXGB_EECD_DI);
if (eecd_reg & IXGB_EECD_DO)
data |= 1;
ixgb_lower_clock(hw, &eecd_reg);
}
return data;
}
/******************************************************************************
* Prepares EEPROM for access
*
* hw - Struct containing variables accessed by shared code
*
* Lowers EEPROM clock. Clears input pin. Sets the chip select pin. This
* function should be called before issuing a command to the EEPROM.
*****************************************************************************/
static void
ixgb_setup_eeprom(struct ixgb_hw *hw)
{
u32 eecd_reg;
eecd_reg = IXGB_READ_REG(hw, EECD);
/* Clear SK and DI */
eecd_reg &= ~(IXGB_EECD_SK | IXGB_EECD_DI);
IXGB_WRITE_REG(hw, EECD, eecd_reg);
/* Set CS */
eecd_reg |= IXGB_EECD_CS;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
}
/******************************************************************************
* Returns EEPROM to a "standby" state
*
* hw - Struct containing variables accessed by shared code
*****************************************************************************/
static void
ixgb_standby_eeprom(struct ixgb_hw *hw)
{
u32 eecd_reg;
eecd_reg = IXGB_READ_REG(hw, EECD);
/* Deselect EEPROM */
eecd_reg &= ~(IXGB_EECD_CS | IXGB_EECD_SK);
IXGB_WRITE_REG(hw, EECD, eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
/* Clock high */
eecd_reg |= IXGB_EECD_SK;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
/* Select EEPROM */
eecd_reg |= IXGB_EECD_CS;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
/* Clock low */
eecd_reg &= ~IXGB_EECD_SK;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
}
/******************************************************************************
* Raises then lowers the EEPROM's clock pin
*
* hw - Struct containing variables accessed by shared code
*****************************************************************************/
static void
ixgb_clock_eeprom(struct ixgb_hw *hw)
{
u32 eecd_reg;
eecd_reg = IXGB_READ_REG(hw, EECD);
/* Rising edge of clock */
eecd_reg |= IXGB_EECD_SK;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
/* Falling edge of clock */
eecd_reg &= ~IXGB_EECD_SK;
IXGB_WRITE_REG(hw, EECD, eecd_reg);
IXGB_WRITE_FLUSH(hw);
udelay(50);
}
/******************************************************************************
* Terminates a command by lowering the EEPROM's chip select pin
*
* hw - Struct containing variables accessed by shared code
*****************************************************************************/
static void
ixgb_cleanup_eeprom(struct ixgb_hw *hw)
{
u32 eecd_reg;
eecd_reg = IXGB_READ_REG(hw, EECD);
eecd_reg &= ~(IXGB_EECD_CS | IXGB_EECD_DI);
IXGB_WRITE_REG(hw, EECD, eecd_reg);
ixgb_clock_eeprom(hw);
}
/******************************************************************************
* Waits for the EEPROM to finish the current command.
*
* hw - Struct containing variables accessed by shared code
*
* The command is done when the EEPROM's data out pin goes high.
*
* Returns:
* true: EEPROM data pin is high before timeout.
* false: Time expired.
*****************************************************************************/
static bool
ixgb_wait_eeprom_command(struct ixgb_hw *hw)
{
u32 eecd_reg;
u32 i;
/* Toggle the CS line. This in effect tells to EEPROM to actually execute
* the command in question.
*/
ixgb_standby_eeprom(hw);
/* Now read DO repeatedly until is high (equal to '1'). The EEPROM will
* signal that the command has been completed by raising the DO signal.
* If DO does not go high in 10 milliseconds, then error out.
*/
for (i = 0; i < 200; i++) {
eecd_reg = IXGB_READ_REG(hw, EECD);
if (eecd_reg & IXGB_EECD_DO)
return true;
udelay(50);
}
ASSERT(0);
return false;
}
/******************************************************************************
* Verifies that the EEPROM has a valid checksum
*
* hw - Struct containing variables accessed by shared code
*
* Reads the first 64 16 bit words of the EEPROM and sums the values read.
* If the sum of the 64 16 bit words is 0xBABA, the EEPROM's checksum is
* valid.
*
* Returns:
* true: Checksum is valid
* false: Checksum is not valid.
*****************************************************************************/
bool
ixgb_validate_eeprom_checksum(struct ixgb_hw *hw)
{
u16 checksum = 0;
u16 i;
for (i = 0; i < (EEPROM_CHECKSUM_REG + 1); i++)
checksum += ixgb_read_eeprom(hw, i);
if (checksum == (u16) EEPROM_SUM)
return true;
else
return false;
}
/******************************************************************************
* Calculates the EEPROM checksum and writes it to the EEPROM
*
* hw - Struct containing variables accessed by shared code
*
* Sums the first 63 16 bit words of the EEPROM. Subtracts the sum from 0xBABA.
* Writes the difference to word offset 63 of the EEPROM.
*****************************************************************************/
void
ixgb_update_eeprom_checksum(struct ixgb_hw *hw)
{
u16 checksum = 0;
u16 i;
for (i = 0; i < EEPROM_CHECKSUM_REG; i++)
checksum += ixgb_read_eeprom(hw, i);
checksum = (u16) EEPROM_SUM - checksum;
ixgb_write_eeprom(hw, EEPROM_CHECKSUM_REG, checksum);
}
/******************************************************************************
* Writes a 16 bit word to a given offset in the EEPROM.
*
* hw - Struct containing variables accessed by shared code
* reg - offset within the EEPROM to be written to
* data - 16 bit word to be written to the EEPROM
*
* If ixgb_update_eeprom_checksum is not called after this function, the
* EEPROM will most likely contain an invalid checksum.
*
*****************************************************************************/
void
ixgb_write_eeprom(struct ixgb_hw *hw, u16 offset, u16 data)
{
struct ixgb_ee_map_type *ee_map = (struct ixgb_ee_map_type *)hw->eeprom;
/* Prepare the EEPROM for writing */
ixgb_setup_eeprom(hw);
/* Send the 9-bit EWEN (write enable) command to the EEPROM (5-bit opcode
* plus 4-bit dummy). This puts the EEPROM into write/erase mode.
*/
ixgb_shift_out_bits(hw, EEPROM_EWEN_OPCODE, 5);
ixgb_shift_out_bits(hw, 0, 4);
/* Prepare the EEPROM */
ixgb_standby_eeprom(hw);
/* Send the Write command (3-bit opcode + 6-bit addr) */
ixgb_shift_out_bits(hw, EEPROM_WRITE_OPCODE, 3);
ixgb_shift_out_bits(hw, offset, 6);
/* Send the data */
ixgb_shift_out_bits(hw, data, 16);
ixgb_wait_eeprom_command(hw);
/* Recover from write */
ixgb_standby_eeprom(hw);
/* Send the 9-bit EWDS (write disable) command to the EEPROM (5-bit
* opcode plus 4-bit dummy). This takes the EEPROM out of write/erase
* mode.
*/
ixgb_shift_out_bits(hw, EEPROM_EWDS_OPCODE, 5);
ixgb_shift_out_bits(hw, 0, 4);
/* Done with writing */
ixgb_cleanup_eeprom(hw);
/* clear the init_ctrl_reg_1 to signify that the cache is invalidated */
ee_map->init_ctrl_reg_1 = cpu_to_le16(EEPROM_ICW1_SIGNATURE_CLEAR);
}
/******************************************************************************
* Reads a 16 bit word from the EEPROM.
*
* hw - Struct containing variables accessed by shared code
* offset - offset of 16 bit word in the EEPROM to read
*
* Returns:
* The 16-bit value read from the eeprom
*****************************************************************************/
u16
ixgb_read_eeprom(struct ixgb_hw *hw,
u16 offset)
{
u16 data;
/* Prepare the EEPROM for reading */
ixgb_setup_eeprom(hw);
/* Send the READ command (opcode + addr) */
ixgb_shift_out_bits(hw, EEPROM_READ_OPCODE, 3);
/*
* We have a 64 word EEPROM, there are 6 address bits
*/
ixgb_shift_out_bits(hw, offset, 6);
/* Read the data */
data = ixgb_shift_in_bits(hw);
/* End this read operation */
ixgb_standby_eeprom(hw);
return data;
}
/******************************************************************************
* Reads eeprom and stores data in shared structure.
* Validates eeprom checksum and eeprom signature.
*
* hw - Struct containing variables accessed by shared code
*
* Returns:
* true: if eeprom read is successful
* false: otherwise.
*****************************************************************************/
bool
ixgb_get_eeprom_data(struct ixgb_hw *hw)
{
u16 i;
u16 checksum = 0;
struct ixgb_ee_map_type *ee_map;
ENTER();
ee_map = (struct ixgb_ee_map_type *)hw->eeprom;
pr_debug("Reading eeprom data\n");
for (i = 0; i < IXGB_EEPROM_SIZE ; i++) {
u16 ee_data;
ee_data = ixgb_read_eeprom(hw, i);
checksum += ee_data;
hw->eeprom[i] = cpu_to_le16(ee_data);
}
if (checksum != (u16) EEPROM_SUM) {
pr_debug("Checksum invalid\n");
/* clear the init_ctrl_reg_1 to signify that the cache is
* invalidated */
ee_map->init_ctrl_reg_1 = cpu_to_le16(EEPROM_ICW1_SIGNATURE_CLEAR);
return false;
}
if ((ee_map->init_ctrl_reg_1 & cpu_to_le16(EEPROM_ICW1_SIGNATURE_MASK))
!= cpu_to_le16(EEPROM_ICW1_SIGNATURE_VALID)) {
pr_debug("Signature invalid\n");
return false;
}
return true;
}
/******************************************************************************
* Local function to check if the eeprom signature is good
* If the eeprom signature is good, calls ixgb)get_eeprom_data.
*
* hw - Struct containing variables accessed by shared code
*
* Returns:
* true: eeprom signature was good and the eeprom read was successful
* false: otherwise.
******************************************************************************/
static bool
ixgb_check_and_get_eeprom_data (struct ixgb_hw* hw)
{
struct ixgb_ee_map_type *ee_map = (struct ixgb_ee_map_type *)hw->eeprom;
if ((ee_map->init_ctrl_reg_1 & cpu_to_le16(EEPROM_ICW1_SIGNATURE_MASK))
== cpu_to_le16(EEPROM_ICW1_SIGNATURE_VALID)) {
return true;
} else {
return ixgb_get_eeprom_data(hw);
}
}
/******************************************************************************
* return a word from the eeprom
*
* hw - Struct containing variables accessed by shared code
* index - Offset of eeprom word
*
* Returns:
* Word at indexed offset in eeprom, if valid, 0 otherwise.
******************************************************************************/
__le16
ixgb_get_eeprom_word(struct ixgb_hw *hw, u16 index)
{
if (index < IXGB_EEPROM_SIZE && ixgb_check_and_get_eeprom_data(hw))
return hw->eeprom[index];
return 0;
}
/******************************************************************************
* return the mac address from EEPROM
*
* hw - Struct containing variables accessed by shared code
* mac_addr - Ethernet Address if EEPROM contents are valid, 0 otherwise
*
* Returns: None.
******************************************************************************/
void
ixgb_get_ee_mac_addr(struct ixgb_hw *hw,
u8 *mac_addr)
{
int i;
struct ixgb_ee_map_type *ee_map = (struct ixgb_ee_map_type *)hw->eeprom;
ENTER();
if (ixgb_check_and_get_eeprom_data(hw)) {
for (i = 0; i < ETH_ALEN; i++) {
mac_addr[i] = ee_map->mac_addr[i];
}
pr_debug("eeprom mac address = %pM\n", mac_addr);
}
}
/******************************************************************************
* return the Printed Board Assembly number from EEPROM
*
* hw - Struct containing variables accessed by shared code
*
* Returns:
* PBA number if EEPROM contents are valid, 0 otherwise
******************************************************************************/
u32
ixgb_get_ee_pba_number(struct ixgb_hw *hw)
{
if (ixgb_check_and_get_eeprom_data(hw))
return le16_to_cpu(hw->eeprom[EEPROM_PBA_1_2_REG])
| (le16_to_cpu(hw->eeprom[EEPROM_PBA_3_4_REG])<<16);
return 0;
}
/******************************************************************************
* return the Device Id from EEPROM
*
* hw - Struct containing variables accessed by shared code
*
* Returns:
* Device Id if EEPROM contents are valid, 0 otherwise
******************************************************************************/
u16
ixgb_get_ee_device_id(struct ixgb_hw *hw)
{
struct ixgb_ee_map_type *ee_map = (struct ixgb_ee_map_type *)hw->eeprom;
if (ixgb_check_and_get_eeprom_data(hw))
return le16_to_cpu(ee_map->device_id);
return 0;
}
| gpl-2.0 |
RealVNC/Android-kernel-hammerhead | drivers/rtc/rtc-sun4v.c | 10189 | 2536 | /* rtc-sun4v.c: Hypervisor based RTC for SUN4V systems.
*
* Copyright (C) 2008 David S. Miller <davem@davemloft.net>
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/rtc.h>
#include <linux/platform_device.h>
#include <asm/hypervisor.h>
static unsigned long hypervisor_get_time(void)
{
unsigned long ret, time;
int retries = 10000;
retry:
ret = sun4v_tod_get(&time);
if (ret == HV_EOK)
return time;
if (ret == HV_EWOULDBLOCK) {
if (--retries > 0) {
udelay(100);
goto retry;
}
printk(KERN_WARNING "SUN4V: tod_get() timed out.\n");
return 0;
}
printk(KERN_WARNING "SUN4V: tod_get() not supported.\n");
return 0;
}
static int sun4v_read_time(struct device *dev, struct rtc_time *tm)
{
rtc_time_to_tm(hypervisor_get_time(), tm);
return 0;
}
static int hypervisor_set_time(unsigned long secs)
{
unsigned long ret;
int retries = 10000;
retry:
ret = sun4v_tod_set(secs);
if (ret == HV_EOK)
return 0;
if (ret == HV_EWOULDBLOCK) {
if (--retries > 0) {
udelay(100);
goto retry;
}
printk(KERN_WARNING "SUN4V: tod_set() timed out.\n");
return -EAGAIN;
}
printk(KERN_WARNING "SUN4V: tod_set() not supported.\n");
return -EOPNOTSUPP;
}
static int sun4v_set_time(struct device *dev, struct rtc_time *tm)
{
unsigned long secs;
int err;
err = rtc_tm_to_time(tm, &secs);
if (err)
return err;
return hypervisor_set_time(secs);
}
static const struct rtc_class_ops sun4v_rtc_ops = {
.read_time = sun4v_read_time,
.set_time = sun4v_set_time,
};
static int __init sun4v_rtc_probe(struct platform_device *pdev)
{
struct rtc_device *rtc = rtc_device_register("sun4v", &pdev->dev,
&sun4v_rtc_ops, THIS_MODULE);
if (IS_ERR(rtc))
return PTR_ERR(rtc);
platform_set_drvdata(pdev, rtc);
return 0;
}
static int __exit sun4v_rtc_remove(struct platform_device *pdev)
{
struct rtc_device *rtc = platform_get_drvdata(pdev);
rtc_device_unregister(rtc);
return 0;
}
static struct platform_driver sun4v_rtc_driver = {
.driver = {
.name = "rtc-sun4v",
.owner = THIS_MODULE,
},
.remove = __exit_p(sun4v_rtc_remove),
};
static int __init sun4v_rtc_init(void)
{
return platform_driver_probe(&sun4v_rtc_driver, sun4v_rtc_probe);
}
static void __exit sun4v_rtc_exit(void)
{
platform_driver_unregister(&sun4v_rtc_driver);
}
module_init(sun4v_rtc_init);
module_exit(sun4v_rtc_exit);
MODULE_AUTHOR("David S. Miller <davem@davemloft.net>");
MODULE_DESCRIPTION("SUN4V RTC driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
adityak74/android_kernel_mediatek_sprout | arch/powerpc/platforms/embedded6xx/gamecube.c | 10445 | 2145 | /*
* arch/powerpc/platforms/embedded6xx/gamecube.c
*
* Nintendo GameCube board-specific support
* Copyright (C) 2004-2009 The GameCube Linux Team
* Copyright (C) 2007,2008,2009 Albert Herranz
*
* 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/irq.h>
#include <linux/kexec.h>
#include <linux/seq_file.h>
#include <linux/of_platform.h>
#include <asm/io.h>
#include <asm/machdep.h>
#include <asm/prom.h>
#include <asm/time.h>
#include <asm/udbg.h>
#include "flipper-pic.h"
#include "usbgecko_udbg.h"
static void gamecube_spin(void)
{
/* spin until power button pressed */
for (;;)
cpu_relax();
}
static void gamecube_restart(char *cmd)
{
local_irq_disable();
flipper_platform_reset();
gamecube_spin();
}
static void gamecube_power_off(void)
{
local_irq_disable();
gamecube_spin();
}
static void gamecube_halt(void)
{
gamecube_restart(NULL);
}
static void __init gamecube_init_early(void)
{
ug_udbg_init();
}
static int __init gamecube_probe(void)
{
unsigned long dt_root;
dt_root = of_get_flat_dt_root();
if (!of_flat_dt_is_compatible(dt_root, "nintendo,gamecube"))
return 0;
return 1;
}
static void gamecube_shutdown(void)
{
flipper_quiesce();
}
define_machine(gamecube) {
.name = "gamecube",
.probe = gamecube_probe,
.init_early = gamecube_init_early,
.restart = gamecube_restart,
.power_off = gamecube_power_off,
.halt = gamecube_halt,
.init_IRQ = flipper_pic_probe,
.get_irq = flipper_pic_get_irq,
.calibrate_decr = generic_calibrate_decr,
.progress = udbg_progress,
.machine_shutdown = gamecube_shutdown,
};
static struct of_device_id gamecube_of_bus[] = {
{ .compatible = "nintendo,flipper", },
{ },
};
static int __init gamecube_device_probe(void)
{
if (!machine_is(gamecube))
return 0;
of_platform_bus_probe(NULL, gamecube_of_bus, NULL);
return 0;
}
device_initcall(gamecube_device_probe);
| gpl-2.0 |
poondog/m7-stock | arch/powerpc/platforms/embedded6xx/gamecube.c | 10445 | 2145 | /*
* arch/powerpc/platforms/embedded6xx/gamecube.c
*
* Nintendo GameCube board-specific support
* Copyright (C) 2004-2009 The GameCube Linux Team
* Copyright (C) 2007,2008,2009 Albert Herranz
*
* 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/irq.h>
#include <linux/kexec.h>
#include <linux/seq_file.h>
#include <linux/of_platform.h>
#include <asm/io.h>
#include <asm/machdep.h>
#include <asm/prom.h>
#include <asm/time.h>
#include <asm/udbg.h>
#include "flipper-pic.h"
#include "usbgecko_udbg.h"
static void gamecube_spin(void)
{
/* spin until power button pressed */
for (;;)
cpu_relax();
}
static void gamecube_restart(char *cmd)
{
local_irq_disable();
flipper_platform_reset();
gamecube_spin();
}
static void gamecube_power_off(void)
{
local_irq_disable();
gamecube_spin();
}
static void gamecube_halt(void)
{
gamecube_restart(NULL);
}
static void __init gamecube_init_early(void)
{
ug_udbg_init();
}
static int __init gamecube_probe(void)
{
unsigned long dt_root;
dt_root = of_get_flat_dt_root();
if (!of_flat_dt_is_compatible(dt_root, "nintendo,gamecube"))
return 0;
return 1;
}
static void gamecube_shutdown(void)
{
flipper_quiesce();
}
define_machine(gamecube) {
.name = "gamecube",
.probe = gamecube_probe,
.init_early = gamecube_init_early,
.restart = gamecube_restart,
.power_off = gamecube_power_off,
.halt = gamecube_halt,
.init_IRQ = flipper_pic_probe,
.get_irq = flipper_pic_get_irq,
.calibrate_decr = generic_calibrate_decr,
.progress = udbg_progress,
.machine_shutdown = gamecube_shutdown,
};
static struct of_device_id gamecube_of_bus[] = {
{ .compatible = "nintendo,flipper", },
{ },
};
static int __init gamecube_device_probe(void)
{
if (!machine_is(gamecube))
return 0;
of_platform_bus_probe(NULL, gamecube_of_bus, NULL);
return 0;
}
device_initcall(gamecube_device_probe);
| gpl-2.0 |
1nv4d3r5/android_kernel_oppo_find5 | arch/powerpc/platforms/embedded6xx/gamecube.c | 10445 | 2145 | /*
* arch/powerpc/platforms/embedded6xx/gamecube.c
*
* Nintendo GameCube board-specific support
* Copyright (C) 2004-2009 The GameCube Linux Team
* Copyright (C) 2007,2008,2009 Albert Herranz
*
* 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/irq.h>
#include <linux/kexec.h>
#include <linux/seq_file.h>
#include <linux/of_platform.h>
#include <asm/io.h>
#include <asm/machdep.h>
#include <asm/prom.h>
#include <asm/time.h>
#include <asm/udbg.h>
#include "flipper-pic.h"
#include "usbgecko_udbg.h"
static void gamecube_spin(void)
{
/* spin until power button pressed */
for (;;)
cpu_relax();
}
static void gamecube_restart(char *cmd)
{
local_irq_disable();
flipper_platform_reset();
gamecube_spin();
}
static void gamecube_power_off(void)
{
local_irq_disable();
gamecube_spin();
}
static void gamecube_halt(void)
{
gamecube_restart(NULL);
}
static void __init gamecube_init_early(void)
{
ug_udbg_init();
}
static int __init gamecube_probe(void)
{
unsigned long dt_root;
dt_root = of_get_flat_dt_root();
if (!of_flat_dt_is_compatible(dt_root, "nintendo,gamecube"))
return 0;
return 1;
}
static void gamecube_shutdown(void)
{
flipper_quiesce();
}
define_machine(gamecube) {
.name = "gamecube",
.probe = gamecube_probe,
.init_early = gamecube_init_early,
.restart = gamecube_restart,
.power_off = gamecube_power_off,
.halt = gamecube_halt,
.init_IRQ = flipper_pic_probe,
.get_irq = flipper_pic_get_irq,
.calibrate_decr = generic_calibrate_decr,
.progress = udbg_progress,
.machine_shutdown = gamecube_shutdown,
};
static struct of_device_id gamecube_of_bus[] = {
{ .compatible = "nintendo,flipper", },
{ },
};
static int __init gamecube_device_probe(void)
{
if (!machine_is(gamecube))
return 0;
of_platform_bus_probe(NULL, gamecube_of_bus, NULL);
return 0;
}
device_initcall(gamecube_device_probe);
| gpl-2.0 |
smksyj/linux_modified_mlock | drivers/scsi/fnic/fnic_res.c | 14541 | 12229 | /*
* Copyright 2008 Cisco Systems, Inc. All rights reserved.
* Copyright 2007 Nuova Systems, Inc. All rights reserved.
*
* This program is free software; you may redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/pci.h>
#include "wq_enet_desc.h"
#include "rq_enet_desc.h"
#include "cq_enet_desc.h"
#include "vnic_resource.h"
#include "vnic_dev.h"
#include "vnic_wq.h"
#include "vnic_rq.h"
#include "vnic_cq.h"
#include "vnic_intr.h"
#include "vnic_stats.h"
#include "vnic_nic.h"
#include "fnic.h"
int fnic_get_vnic_config(struct fnic *fnic)
{
struct vnic_fc_config *c = &fnic->config;
int err;
#define GET_CONFIG(m) \
do { \
err = vnic_dev_spec(fnic->vdev, \
offsetof(struct vnic_fc_config, m), \
sizeof(c->m), &c->m); \
if (err) { \
shost_printk(KERN_ERR, fnic->lport->host, \
"Error getting %s, %d\n", #m, \
err); \
return err; \
} \
} while (0);
GET_CONFIG(node_wwn);
GET_CONFIG(port_wwn);
GET_CONFIG(wq_enet_desc_count);
GET_CONFIG(wq_copy_desc_count);
GET_CONFIG(rq_desc_count);
GET_CONFIG(maxdatafieldsize);
GET_CONFIG(ed_tov);
GET_CONFIG(ra_tov);
GET_CONFIG(intr_timer);
GET_CONFIG(intr_timer_type);
GET_CONFIG(flags);
GET_CONFIG(flogi_retries);
GET_CONFIG(flogi_timeout);
GET_CONFIG(plogi_retries);
GET_CONFIG(plogi_timeout);
GET_CONFIG(io_throttle_count);
GET_CONFIG(link_down_timeout);
GET_CONFIG(port_down_timeout);
GET_CONFIG(port_down_io_retries);
GET_CONFIG(luns_per_tgt);
c->wq_enet_desc_count =
min_t(u32, VNIC_FNIC_WQ_DESCS_MAX,
max_t(u32, VNIC_FNIC_WQ_DESCS_MIN,
c->wq_enet_desc_count));
c->wq_enet_desc_count = ALIGN(c->wq_enet_desc_count, 16);
c->wq_copy_desc_count =
min_t(u32, VNIC_FNIC_WQ_COPY_DESCS_MAX,
max_t(u32, VNIC_FNIC_WQ_COPY_DESCS_MIN,
c->wq_copy_desc_count));
c->wq_copy_desc_count = ALIGN(c->wq_copy_desc_count, 16);
c->rq_desc_count =
min_t(u32, VNIC_FNIC_RQ_DESCS_MAX,
max_t(u32, VNIC_FNIC_RQ_DESCS_MIN,
c->rq_desc_count));
c->rq_desc_count = ALIGN(c->rq_desc_count, 16);
c->maxdatafieldsize =
min_t(u16, VNIC_FNIC_MAXDATAFIELDSIZE_MAX,
max_t(u16, VNIC_FNIC_MAXDATAFIELDSIZE_MIN,
c->maxdatafieldsize));
c->ed_tov =
min_t(u32, VNIC_FNIC_EDTOV_MAX,
max_t(u32, VNIC_FNIC_EDTOV_MIN,
c->ed_tov));
c->ra_tov =
min_t(u32, VNIC_FNIC_RATOV_MAX,
max_t(u32, VNIC_FNIC_RATOV_MIN,
c->ra_tov));
c->flogi_retries =
min_t(u32, VNIC_FNIC_FLOGI_RETRIES_MAX, c->flogi_retries);
c->flogi_timeout =
min_t(u32, VNIC_FNIC_FLOGI_TIMEOUT_MAX,
max_t(u32, VNIC_FNIC_FLOGI_TIMEOUT_MIN,
c->flogi_timeout));
c->plogi_retries =
min_t(u32, VNIC_FNIC_PLOGI_RETRIES_MAX, c->plogi_retries);
c->plogi_timeout =
min_t(u32, VNIC_FNIC_PLOGI_TIMEOUT_MAX,
max_t(u32, VNIC_FNIC_PLOGI_TIMEOUT_MIN,
c->plogi_timeout));
c->io_throttle_count =
min_t(u32, VNIC_FNIC_IO_THROTTLE_COUNT_MAX,
max_t(u32, VNIC_FNIC_IO_THROTTLE_COUNT_MIN,
c->io_throttle_count));
c->link_down_timeout =
min_t(u32, VNIC_FNIC_LINK_DOWN_TIMEOUT_MAX,
c->link_down_timeout);
c->port_down_timeout =
min_t(u32, VNIC_FNIC_PORT_DOWN_TIMEOUT_MAX,
c->port_down_timeout);
c->port_down_io_retries =
min_t(u32, VNIC_FNIC_PORT_DOWN_IO_RETRIES_MAX,
c->port_down_io_retries);
c->luns_per_tgt =
min_t(u32, VNIC_FNIC_LUNS_PER_TARGET_MAX,
max_t(u32, VNIC_FNIC_LUNS_PER_TARGET_MIN,
c->luns_per_tgt));
c->intr_timer = min_t(u16, VNIC_INTR_TIMER_MAX, c->intr_timer);
c->intr_timer_type = c->intr_timer_type;
shost_printk(KERN_INFO, fnic->lport->host,
"vNIC MAC addr %pM "
"wq/wq_copy/rq %d/%d/%d\n",
fnic->ctlr.ctl_src_addr,
c->wq_enet_desc_count, c->wq_copy_desc_count,
c->rq_desc_count);
shost_printk(KERN_INFO, fnic->lport->host,
"vNIC node wwn %llx port wwn %llx\n",
c->node_wwn, c->port_wwn);
shost_printk(KERN_INFO, fnic->lport->host,
"vNIC ed_tov %d ra_tov %d\n",
c->ed_tov, c->ra_tov);
shost_printk(KERN_INFO, fnic->lport->host,
"vNIC mtu %d intr timer %d\n",
c->maxdatafieldsize, c->intr_timer);
shost_printk(KERN_INFO, fnic->lport->host,
"vNIC flags 0x%x luns per tgt %d\n",
c->flags, c->luns_per_tgt);
shost_printk(KERN_INFO, fnic->lport->host,
"vNIC flogi_retries %d flogi timeout %d\n",
c->flogi_retries, c->flogi_timeout);
shost_printk(KERN_INFO, fnic->lport->host,
"vNIC plogi retries %d plogi timeout %d\n",
c->plogi_retries, c->plogi_timeout);
shost_printk(KERN_INFO, fnic->lport->host,
"vNIC io throttle count %d link dn timeout %d\n",
c->io_throttle_count, c->link_down_timeout);
shost_printk(KERN_INFO, fnic->lport->host,
"vNIC port dn io retries %d port dn timeout %d\n",
c->port_down_io_retries, c->port_down_timeout);
return 0;
}
int fnic_set_nic_config(struct fnic *fnic, u8 rss_default_cpu,
u8 rss_hash_type,
u8 rss_hash_bits, u8 rss_base_cpu, u8 rss_enable,
u8 tso_ipid_split_en, u8 ig_vlan_strip_en)
{
u64 a0, a1;
u32 nic_cfg;
int wait = 1000;
vnic_set_nic_cfg(&nic_cfg, rss_default_cpu,
rss_hash_type, rss_hash_bits, rss_base_cpu,
rss_enable, tso_ipid_split_en, ig_vlan_strip_en);
a0 = nic_cfg;
a1 = 0;
return vnic_dev_cmd(fnic->vdev, CMD_NIC_CFG, &a0, &a1, wait);
}
void fnic_get_res_counts(struct fnic *fnic)
{
fnic->wq_count = vnic_dev_get_res_count(fnic->vdev, RES_TYPE_WQ);
fnic->raw_wq_count = fnic->wq_count - 1;
fnic->wq_copy_count = fnic->wq_count - fnic->raw_wq_count;
fnic->rq_count = vnic_dev_get_res_count(fnic->vdev, RES_TYPE_RQ);
fnic->cq_count = vnic_dev_get_res_count(fnic->vdev, RES_TYPE_CQ);
fnic->intr_count = vnic_dev_get_res_count(fnic->vdev,
RES_TYPE_INTR_CTRL);
}
void fnic_free_vnic_resources(struct fnic *fnic)
{
unsigned int i;
for (i = 0; i < fnic->raw_wq_count; i++)
vnic_wq_free(&fnic->wq[i]);
for (i = 0; i < fnic->wq_copy_count; i++)
vnic_wq_copy_free(&fnic->wq_copy[i]);
for (i = 0; i < fnic->rq_count; i++)
vnic_rq_free(&fnic->rq[i]);
for (i = 0; i < fnic->cq_count; i++)
vnic_cq_free(&fnic->cq[i]);
for (i = 0; i < fnic->intr_count; i++)
vnic_intr_free(&fnic->intr[i]);
}
int fnic_alloc_vnic_resources(struct fnic *fnic)
{
enum vnic_dev_intr_mode intr_mode;
unsigned int mask_on_assertion;
unsigned int interrupt_offset;
unsigned int error_interrupt_enable;
unsigned int error_interrupt_offset;
unsigned int i, cq_index;
unsigned int wq_copy_cq_desc_count;
int err;
intr_mode = vnic_dev_get_intr_mode(fnic->vdev);
shost_printk(KERN_INFO, fnic->lport->host, "vNIC interrupt mode: %s\n",
intr_mode == VNIC_DEV_INTR_MODE_INTX ? "legacy PCI INTx" :
intr_mode == VNIC_DEV_INTR_MODE_MSI ? "MSI" :
intr_mode == VNIC_DEV_INTR_MODE_MSIX ?
"MSI-X" : "unknown");
shost_printk(KERN_INFO, fnic->lport->host, "vNIC resources avail: "
"wq %d cp_wq %d raw_wq %d rq %d cq %d intr %d\n",
fnic->wq_count, fnic->wq_copy_count, fnic->raw_wq_count,
fnic->rq_count, fnic->cq_count, fnic->intr_count);
/* Allocate Raw WQ used for FCS frames */
for (i = 0; i < fnic->raw_wq_count; i++) {
err = vnic_wq_alloc(fnic->vdev, &fnic->wq[i], i,
fnic->config.wq_enet_desc_count,
sizeof(struct wq_enet_desc));
if (err)
goto err_out_cleanup;
}
/* Allocate Copy WQs used for SCSI IOs */
for (i = 0; i < fnic->wq_copy_count; i++) {
err = vnic_wq_copy_alloc(fnic->vdev, &fnic->wq_copy[i],
(fnic->raw_wq_count + i),
fnic->config.wq_copy_desc_count,
sizeof(struct fcpio_host_req));
if (err)
goto err_out_cleanup;
}
/* RQ for receiving FCS frames */
for (i = 0; i < fnic->rq_count; i++) {
err = vnic_rq_alloc(fnic->vdev, &fnic->rq[i], i,
fnic->config.rq_desc_count,
sizeof(struct rq_enet_desc));
if (err)
goto err_out_cleanup;
}
/* CQ for each RQ */
for (i = 0; i < fnic->rq_count; i++) {
cq_index = i;
err = vnic_cq_alloc(fnic->vdev,
&fnic->cq[cq_index], cq_index,
fnic->config.rq_desc_count,
sizeof(struct cq_enet_rq_desc));
if (err)
goto err_out_cleanup;
}
/* CQ for each WQ */
for (i = 0; i < fnic->raw_wq_count; i++) {
cq_index = fnic->rq_count + i;
err = vnic_cq_alloc(fnic->vdev, &fnic->cq[cq_index], cq_index,
fnic->config.wq_enet_desc_count,
sizeof(struct cq_enet_wq_desc));
if (err)
goto err_out_cleanup;
}
/* CQ for each COPY WQ */
wq_copy_cq_desc_count = (fnic->config.wq_copy_desc_count * 3);
for (i = 0; i < fnic->wq_copy_count; i++) {
cq_index = fnic->raw_wq_count + fnic->rq_count + i;
err = vnic_cq_alloc(fnic->vdev, &fnic->cq[cq_index],
cq_index,
wq_copy_cq_desc_count,
sizeof(struct fcpio_fw_req));
if (err)
goto err_out_cleanup;
}
for (i = 0; i < fnic->intr_count; i++) {
err = vnic_intr_alloc(fnic->vdev, &fnic->intr[i], i);
if (err)
goto err_out_cleanup;
}
fnic->legacy_pba = vnic_dev_get_res(fnic->vdev,
RES_TYPE_INTR_PBA_LEGACY, 0);
if (!fnic->legacy_pba && intr_mode == VNIC_DEV_INTR_MODE_INTX) {
shost_printk(KERN_ERR, fnic->lport->host,
"Failed to hook legacy pba resource\n");
err = -ENODEV;
goto err_out_cleanup;
}
/*
* Init RQ/WQ resources.
*
* RQ[0 to n-1] point to CQ[0 to n-1]
* WQ[0 to m-1] point to CQ[n to n+m-1]
* WQ_COPY[0 to k-1] points to CQ[n+m to n+m+k-1]
*
* Note for copy wq we always initialize with cq_index = 0
*
* Error interrupt is not enabled for MSI.
*/
switch (intr_mode) {
case VNIC_DEV_INTR_MODE_INTX:
case VNIC_DEV_INTR_MODE_MSIX:
error_interrupt_enable = 1;
error_interrupt_offset = fnic->err_intr_offset;
break;
default:
error_interrupt_enable = 0;
error_interrupt_offset = 0;
break;
}
for (i = 0; i < fnic->rq_count; i++) {
cq_index = i;
vnic_rq_init(&fnic->rq[i],
cq_index,
error_interrupt_enable,
error_interrupt_offset);
}
for (i = 0; i < fnic->raw_wq_count; i++) {
cq_index = i + fnic->rq_count;
vnic_wq_init(&fnic->wq[i],
cq_index,
error_interrupt_enable,
error_interrupt_offset);
}
for (i = 0; i < fnic->wq_copy_count; i++) {
vnic_wq_copy_init(&fnic->wq_copy[i],
0 /* cq_index 0 - always */,
error_interrupt_enable,
error_interrupt_offset);
}
for (i = 0; i < fnic->cq_count; i++) {
switch (intr_mode) {
case VNIC_DEV_INTR_MODE_MSIX:
interrupt_offset = i;
break;
default:
interrupt_offset = 0;
break;
}
vnic_cq_init(&fnic->cq[i],
0 /* flow_control_enable */,
1 /* color_enable */,
0 /* cq_head */,
0 /* cq_tail */,
1 /* cq_tail_color */,
1 /* interrupt_enable */,
1 /* cq_entry_enable */,
0 /* cq_message_enable */,
interrupt_offset,
0 /* cq_message_addr */);
}
/*
* Init INTR resources
*
* mask_on_assertion is not used for INTx due to the level-
* triggered nature of INTx
*/
switch (intr_mode) {
case VNIC_DEV_INTR_MODE_MSI:
case VNIC_DEV_INTR_MODE_MSIX:
mask_on_assertion = 1;
break;
default:
mask_on_assertion = 0;
break;
}
for (i = 0; i < fnic->intr_count; i++) {
vnic_intr_init(&fnic->intr[i],
fnic->config.intr_timer,
fnic->config.intr_timer_type,
mask_on_assertion);
}
/* init the stats memory by making the first call here */
err = vnic_dev_stats_dump(fnic->vdev, &fnic->stats);
if (err) {
shost_printk(KERN_ERR, fnic->lport->host,
"vnic_dev_stats_dump failed - x%x\n", err);
goto err_out_cleanup;
}
/* Clear LIF stats */
vnic_dev_stats_clear(fnic->vdev);
return 0;
err_out_cleanup:
fnic_free_vnic_resources(fnic);
return err;
}
| gpl-2.0 |
Silviumik/Silviu_Kernel_I9195_LTE_KitKat | net/llc/llc_c_ev.c | 15053 | 21776 | /*
* llc_c_ev.c - Connection component state transition event qualifiers
*
* A 'state' consists of a number of possible event matching functions,
* the actions associated with each being executed when that event is
* matched; a 'state machine' accepts events in a serial fashion from an
* event queue. Each event is passed to each successive event matching
* function until a match is made (the event matching function returns
* success, or '0') or the list of event matching functions is exhausted.
* If a match is made, the actions associated with the event are executed
* and the state is changed to that event's transition state. Before some
* events are recognized, even after a match has been made, a certain
* number of 'event qualifier' functions must also be executed. If these
* all execute successfully, then the event is finally executed.
*
* These event functions must return 0 for success, to show a matched
* event, of 1 if the event does not match. Event qualifier functions
* must return a 0 for success or a non-zero for failure. Each function
* is simply responsible for verifying one single thing and returning
* either a success or failure.
*
* All of followed event functions are described in 802.2 LLC Protocol
* standard document except two functions that we added that will explain
* in their comments, at below.
*
* Copyright (c) 1997 by Procom Technology, Inc.
* 2001-2003 by Arnaldo Carvalho de Melo <acme@conectiva.com.br>
*
* This program can be redistributed or modified under the terms of the
* GNU General Public License as published by the Free Software Foundation.
* This program is distributed without any warranty or implied warranty
* of merchantability or fitness for a particular purpose.
*
* See the GNU General Public License for more details.
*/
#include <linux/netdevice.h>
#include <net/llc_conn.h>
#include <net/llc_sap.h>
#include <net/sock.h>
#include <net/llc_c_ac.h>
#include <net/llc_c_ev.h>
#include <net/llc_pdu.h>
#if 1
#define dprintk(args...) printk(KERN_DEBUG args)
#else
#define dprintk(args...)
#endif
/**
* llc_util_ns_inside_rx_window - check if sequence number is in rx window
* @ns: sequence number of received pdu.
* @vr: sequence number which receiver expects to receive.
* @rw: receive window size of receiver.
*
* Checks if sequence number of received PDU is in range of receive
* window. Returns 0 for success, 1 otherwise
*/
static u16 llc_util_ns_inside_rx_window(u8 ns, u8 vr, u8 rw)
{
return !llc_circular_between(vr, ns,
(vr + rw - 1) % LLC_2_SEQ_NBR_MODULO);
}
/**
* llc_util_nr_inside_tx_window - check if sequence number is in tx window
* @sk: current connection.
* @nr: N(R) of received PDU.
*
* This routine checks if N(R) of received PDU is in range of transmit
* window; on the other hand checks if received PDU acknowledges some
* outstanding PDUs that are in transmit window. Returns 0 for success, 1
* otherwise.
*/
static u16 llc_util_nr_inside_tx_window(struct sock *sk, u8 nr)
{
u8 nr1, nr2;
struct sk_buff *skb;
struct llc_pdu_sn *pdu;
struct llc_sock *llc = llc_sk(sk);
int rc = 0;
if (llc->dev->flags & IFF_LOOPBACK)
goto out;
rc = 1;
if (skb_queue_empty(&llc->pdu_unack_q))
goto out;
skb = skb_peek(&llc->pdu_unack_q);
pdu = llc_pdu_sn_hdr(skb);
nr1 = LLC_I_GET_NS(pdu);
skb = skb_peek_tail(&llc->pdu_unack_q);
pdu = llc_pdu_sn_hdr(skb);
nr2 = LLC_I_GET_NS(pdu);
rc = !llc_circular_between(nr1, nr, (nr2 + 1) % LLC_2_SEQ_NBR_MODULO);
out:
return rc;
}
int llc_conn_ev_conn_req(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->prim == LLC_CONN_PRIM &&
ev->prim_type == LLC_PRIM_TYPE_REQ ? 0 : 1;
}
int llc_conn_ev_data_req(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->prim == LLC_DATA_PRIM &&
ev->prim_type == LLC_PRIM_TYPE_REQ ? 0 : 1;
}
int llc_conn_ev_disc_req(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->prim == LLC_DISC_PRIM &&
ev->prim_type == LLC_PRIM_TYPE_REQ ? 0 : 1;
}
int llc_conn_ev_rst_req(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->prim == LLC_RESET_PRIM &&
ev->prim_type == LLC_PRIM_TYPE_REQ ? 0 : 1;
}
int llc_conn_ev_local_busy_detected(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->type == LLC_CONN_EV_TYPE_SIMPLE &&
ev->prim_type == LLC_CONN_EV_LOCAL_BUSY_DETECTED ? 0 : 1;
}
int llc_conn_ev_local_busy_cleared(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->type == LLC_CONN_EV_TYPE_SIMPLE &&
ev->prim_type == LLC_CONN_EV_LOCAL_BUSY_CLEARED ? 0 : 1;
}
int llc_conn_ev_rx_bad_pdu(struct sock *sk, struct sk_buff *skb)
{
return 1;
}
int llc_conn_ev_rx_disc_cmd_pbit_set_x(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_U(pdu) &&
LLC_U_PDU_CMD(pdu) == LLC_2_PDU_CMD_DISC ? 0 : 1;
}
int llc_conn_ev_rx_dm_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_U(pdu) &&
LLC_U_PDU_RSP(pdu) == LLC_2_PDU_RSP_DM ? 0 : 1;
}
int llc_conn_ev_rx_frmr_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_U(pdu) &&
LLC_U_PDU_RSP(pdu) == LLC_2_PDU_RSP_FRMR ? 0 : 1;
}
int llc_conn_ev_rx_i_cmd_pbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return llc_conn_space(sk, skb) &&
LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_0(pdu) &&
LLC_I_GET_NS(pdu) == llc_sk(sk)->vR ? 0 : 1;
}
int llc_conn_ev_rx_i_cmd_pbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return llc_conn_space(sk, skb) &&
LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_1(pdu) &&
LLC_I_GET_NS(pdu) == llc_sk(sk)->vR ? 0 : 1;
}
int llc_conn_ev_rx_i_cmd_pbit_set_0_unexpd_ns(struct sock *sk,
struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vr = llc_sk(sk)->vR;
const u8 ns = LLC_I_GET_NS(pdu);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_0(pdu) && ns != vr &&
!llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1;
}
int llc_conn_ev_rx_i_cmd_pbit_set_1_unexpd_ns(struct sock *sk,
struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vr = llc_sk(sk)->vR;
const u8 ns = LLC_I_GET_NS(pdu);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_1(pdu) && ns != vr &&
!llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1;
}
int llc_conn_ev_rx_i_cmd_pbit_set_x_inval_ns(struct sock *sk,
struct sk_buff *skb)
{
const struct llc_pdu_sn * pdu = llc_pdu_sn_hdr(skb);
const u8 vr = llc_sk(sk)->vR;
const u8 ns = LLC_I_GET_NS(pdu);
const u16 rc = LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
ns != vr &&
llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1;
if (!rc)
dprintk("%s: matched, state=%d, ns=%d, vr=%d\n",
__func__, llc_sk(sk)->state, ns, vr);
return rc;
}
int llc_conn_ev_rx_i_rsp_fbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return llc_conn_space(sk, skb) &&
LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_0(pdu) &&
LLC_I_GET_NS(pdu) == llc_sk(sk)->vR ? 0 : 1;
}
int llc_conn_ev_rx_i_rsp_fbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_1(pdu) &&
LLC_I_GET_NS(pdu) == llc_sk(sk)->vR ? 0 : 1;
}
int llc_conn_ev_rx_i_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return llc_conn_space(sk, skb) &&
LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_GET_NS(pdu) == llc_sk(sk)->vR ? 0 : 1;
}
int llc_conn_ev_rx_i_rsp_fbit_set_0_unexpd_ns(struct sock *sk,
struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vr = llc_sk(sk)->vR;
const u8 ns = LLC_I_GET_NS(pdu);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_0(pdu) && ns != vr &&
!llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1;
}
int llc_conn_ev_rx_i_rsp_fbit_set_1_unexpd_ns(struct sock *sk,
struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vr = llc_sk(sk)->vR;
const u8 ns = LLC_I_GET_NS(pdu);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_1(pdu) && ns != vr &&
!llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1;
}
int llc_conn_ev_rx_i_rsp_fbit_set_x_unexpd_ns(struct sock *sk,
struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vr = llc_sk(sk)->vR;
const u8 ns = LLC_I_GET_NS(pdu);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) && ns != vr &&
!llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1;
}
int llc_conn_ev_rx_i_rsp_fbit_set_x_inval_ns(struct sock *sk,
struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vr = llc_sk(sk)->vR;
const u8 ns = LLC_I_GET_NS(pdu);
const u16 rc = LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
ns != vr &&
llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1;
if (!rc)
dprintk("%s: matched, state=%d, ns=%d, vr=%d\n",
__func__, llc_sk(sk)->state, ns, vr);
return rc;
}
int llc_conn_ev_rx_rej_cmd_pbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_0(pdu) &&
LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_REJ ? 0 : 1;
}
int llc_conn_ev_rx_rej_cmd_pbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_1(pdu) &&
LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_REJ ? 0 : 1;
}
int llc_conn_ev_rx_rej_rsp_fbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_0(pdu) &&
LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_REJ ? 0 : 1;
}
int llc_conn_ev_rx_rej_rsp_fbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_1(pdu) &&
LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_REJ ? 0 : 1;
}
int llc_conn_ev_rx_rej_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_REJ ? 0 : 1;
}
int llc_conn_ev_rx_rnr_cmd_pbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_0(pdu) &&
LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_RNR ? 0 : 1;
}
int llc_conn_ev_rx_rnr_cmd_pbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_1(pdu) &&
LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_RNR ? 0 : 1;
}
int llc_conn_ev_rx_rnr_rsp_fbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_0(pdu) &&
LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_RNR ? 0 : 1;
}
int llc_conn_ev_rx_rnr_rsp_fbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_1(pdu) &&
LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_RNR ? 0 : 1;
}
int llc_conn_ev_rx_rr_cmd_pbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_0(pdu) &&
LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_RR ? 0 : 1;
}
int llc_conn_ev_rx_rr_cmd_pbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_1(pdu) &&
LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_RR ? 0 : 1;
}
int llc_conn_ev_rx_rr_rsp_fbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return llc_conn_space(sk, skb) &&
LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_0(pdu) &&
LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_RR ? 0 : 1;
}
int llc_conn_ev_rx_rr_rsp_fbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return llc_conn_space(sk, skb) &&
LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_1(pdu) &&
LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_RR ? 0 : 1;
}
int llc_conn_ev_rx_sabme_cmd_pbit_set_x(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_U(pdu) &&
LLC_U_PDU_CMD(pdu) == LLC_2_PDU_CMD_SABME ? 0 : 1;
}
int llc_conn_ev_rx_ua_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb)
{
struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_U(pdu) &&
LLC_U_PDU_RSP(pdu) == LLC_2_PDU_RSP_UA ? 0 : 1;
}
int llc_conn_ev_rx_xxx_cmd_pbit_set_1(struct sock *sk, struct sk_buff *skb)
{
u16 rc = 1;
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
if (LLC_PDU_IS_CMD(pdu)) {
if (LLC_PDU_TYPE_IS_I(pdu) || LLC_PDU_TYPE_IS_S(pdu)) {
if (LLC_I_PF_IS_1(pdu))
rc = 0;
} else if (LLC_PDU_TYPE_IS_U(pdu) && LLC_U_PF_IS_1(pdu))
rc = 0;
}
return rc;
}
int llc_conn_ev_rx_xxx_cmd_pbit_set_x(struct sock *sk, struct sk_buff *skb)
{
u16 rc = 1;
const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
if (LLC_PDU_IS_CMD(pdu)) {
if (LLC_PDU_TYPE_IS_I(pdu) || LLC_PDU_TYPE_IS_S(pdu))
rc = 0;
else if (LLC_PDU_TYPE_IS_U(pdu))
switch (LLC_U_PDU_CMD(pdu)) {
case LLC_2_PDU_CMD_SABME:
case LLC_2_PDU_CMD_DISC:
rc = 0;
break;
}
}
return rc;
}
int llc_conn_ev_rx_xxx_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb)
{
u16 rc = 1;
const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
if (LLC_PDU_IS_RSP(pdu)) {
if (LLC_PDU_TYPE_IS_I(pdu) || LLC_PDU_TYPE_IS_S(pdu))
rc = 0;
else if (LLC_PDU_TYPE_IS_U(pdu))
switch (LLC_U_PDU_RSP(pdu)) {
case LLC_2_PDU_RSP_UA:
case LLC_2_PDU_RSP_DM:
case LLC_2_PDU_RSP_FRMR:
rc = 0;
break;
}
}
return rc;
}
int llc_conn_ev_rx_zzz_cmd_pbit_set_x_inval_nr(struct sock *sk,
struct sk_buff *skb)
{
u16 rc = 1;
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vs = llc_sk(sk)->vS;
const u8 nr = LLC_I_GET_NR(pdu);
if (LLC_PDU_IS_CMD(pdu) &&
(LLC_PDU_TYPE_IS_I(pdu) || LLC_PDU_TYPE_IS_S(pdu)) &&
nr != vs && llc_util_nr_inside_tx_window(sk, nr)) {
dprintk("%s: matched, state=%d, vs=%d, nr=%d\n",
__func__, llc_sk(sk)->state, vs, nr);
rc = 0;
}
return rc;
}
int llc_conn_ev_rx_zzz_rsp_fbit_set_x_inval_nr(struct sock *sk,
struct sk_buff *skb)
{
u16 rc = 1;
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vs = llc_sk(sk)->vS;
const u8 nr = LLC_I_GET_NR(pdu);
if (LLC_PDU_IS_RSP(pdu) &&
(LLC_PDU_TYPE_IS_I(pdu) || LLC_PDU_TYPE_IS_S(pdu)) &&
nr != vs && llc_util_nr_inside_tx_window(sk, nr)) {
rc = 0;
dprintk("%s: matched, state=%d, vs=%d, nr=%d\n",
__func__, llc_sk(sk)->state, vs, nr);
}
return rc;
}
int llc_conn_ev_rx_any_frame(struct sock *sk, struct sk_buff *skb)
{
return 0;
}
int llc_conn_ev_p_tmr_exp(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->type != LLC_CONN_EV_TYPE_P_TMR;
}
int llc_conn_ev_ack_tmr_exp(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->type != LLC_CONN_EV_TYPE_ACK_TMR;
}
int llc_conn_ev_rej_tmr_exp(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->type != LLC_CONN_EV_TYPE_REJ_TMR;
}
int llc_conn_ev_busy_tmr_exp(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->type != LLC_CONN_EV_TYPE_BUSY_TMR;
}
int llc_conn_ev_init_p_f_cycle(struct sock *sk, struct sk_buff *skb)
{
return 1;
}
int llc_conn_ev_tx_buffer_full(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->type == LLC_CONN_EV_TYPE_SIMPLE &&
ev->prim_type == LLC_CONN_EV_TX_BUFF_FULL ? 0 : 1;
}
/* Event qualifier functions
*
* these functions simply verify the value of a state flag associated with
* the connection and return either a 0 for success or a non-zero value
* for not-success; verify the event is the type we expect
*/
int llc_conn_ev_qlfy_data_flag_eq_1(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->data_flag != 1;
}
int llc_conn_ev_qlfy_data_flag_eq_0(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->data_flag;
}
int llc_conn_ev_qlfy_data_flag_eq_2(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->data_flag != 2;
}
int llc_conn_ev_qlfy_p_flag_eq_1(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->p_flag != 1;
}
/**
* conn_ev_qlfy_last_frame_eq_1 - checks if frame is last in tx window
* @sk: current connection structure.
* @skb: current event.
*
* This function determines when frame which is sent, is last frame of
* transmit window, if it is then this function return zero else return
* one. This function is used for sending last frame of transmit window
* as I-format command with p-bit set to one. Returns 0 if frame is last
* frame, 1 otherwise.
*/
int llc_conn_ev_qlfy_last_frame_eq_1(struct sock *sk, struct sk_buff *skb)
{
return !(skb_queue_len(&llc_sk(sk)->pdu_unack_q) + 1 == llc_sk(sk)->k);
}
/**
* conn_ev_qlfy_last_frame_eq_0 - checks if frame isn't last in tx window
* @sk: current connection structure.
* @skb: current event.
*
* This function determines when frame which is sent, isn't last frame of
* transmit window, if it isn't then this function return zero else return
* one. Returns 0 if frame isn't last frame, 1 otherwise.
*/
int llc_conn_ev_qlfy_last_frame_eq_0(struct sock *sk, struct sk_buff *skb)
{
return skb_queue_len(&llc_sk(sk)->pdu_unack_q) + 1 == llc_sk(sk)->k;
}
int llc_conn_ev_qlfy_p_flag_eq_0(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->p_flag;
}
int llc_conn_ev_qlfy_p_flag_eq_f(struct sock *sk, struct sk_buff *skb)
{
u8 f_bit;
llc_pdu_decode_pf_bit(skb, &f_bit);
return llc_sk(sk)->p_flag == f_bit ? 0 : 1;
}
int llc_conn_ev_qlfy_remote_busy_eq_0(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->remote_busy_flag;
}
int llc_conn_ev_qlfy_remote_busy_eq_1(struct sock *sk, struct sk_buff *skb)
{
return !llc_sk(sk)->remote_busy_flag;
}
int llc_conn_ev_qlfy_retry_cnt_lt_n2(struct sock *sk, struct sk_buff *skb)
{
return !(llc_sk(sk)->retry_count < llc_sk(sk)->n2);
}
int llc_conn_ev_qlfy_retry_cnt_gte_n2(struct sock *sk, struct sk_buff *skb)
{
return !(llc_sk(sk)->retry_count >= llc_sk(sk)->n2);
}
int llc_conn_ev_qlfy_s_flag_eq_1(struct sock *sk, struct sk_buff *skb)
{
return !llc_sk(sk)->s_flag;
}
int llc_conn_ev_qlfy_s_flag_eq_0(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->s_flag;
}
int llc_conn_ev_qlfy_cause_flag_eq_1(struct sock *sk, struct sk_buff *skb)
{
return !llc_sk(sk)->cause_flag;
}
int llc_conn_ev_qlfy_cause_flag_eq_0(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->cause_flag;
}
int llc_conn_ev_qlfy_set_status_conn(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->status = LLC_STATUS_CONN;
return 0;
}
int llc_conn_ev_qlfy_set_status_disc(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->status = LLC_STATUS_DISC;
return 0;
}
int llc_conn_ev_qlfy_set_status_failed(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->status = LLC_STATUS_FAILED;
return 0;
}
int llc_conn_ev_qlfy_set_status_remote_busy(struct sock *sk,
struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->status = LLC_STATUS_REMOTE_BUSY;
return 0;
}
int llc_conn_ev_qlfy_set_status_refuse(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->status = LLC_STATUS_REFUSE;
return 0;
}
int llc_conn_ev_qlfy_set_status_conflict(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->status = LLC_STATUS_CONFLICT;
return 0;
}
int llc_conn_ev_qlfy_set_status_rst_done(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->status = LLC_STATUS_RESET_DONE;
return 0;
}
| gpl-2.0 |
NAM-IL/ARM_Linux_Kernel_12b | drivers/staging/rtl8723au/core/rtw_security.c | 206 | 49843 | /******************************************************************************
*
* Copyright(c) 2007 - 2011 Realtek Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
******************************************************************************/
#define _RTW_SECURITY_C_
#include <osdep_service.h>
#include <drv_types.h>
#include <wifi.h>
#include <osdep_intf.h>
/* WEP related ===== */
#define CRC32_POLY 0x04c11db7
struct arc4context {
u32 x;
u32 y;
u8 state[256];
};
static void arcfour_init(struct arc4context *parc4ctx, u8 *key, u32 key_len)
{
u32 t, u;
u32 keyindex;
u32 stateindex;
u8 *state;
u32 counter;
state = parc4ctx->state;
parc4ctx->x = 0;
parc4ctx->y = 0;
for (counter = 0; counter < 256; counter++)
state[counter] = (u8)counter;
keyindex = 0;
stateindex = 0;
for (counter = 0; counter < 256; counter++) {
t = state[counter];
stateindex = (stateindex + key[keyindex] + t) & 0xff;
u = state[stateindex];
state[stateindex] = (u8)t;
state[counter] = (u8)u;
if (++keyindex >= key_len)
keyindex = 0;
}
}
static u32 arcfour_byte( struct arc4context *parc4ctx)
{
u32 x;
u32 y;
u32 sx, sy;
u8 *state;
state = parc4ctx->state;
x = (parc4ctx->x + 1) & 0xff;
sx = state[x];
y = (sx + parc4ctx->y) & 0xff;
sy = state[y];
parc4ctx->x = x;
parc4ctx->y = y;
state[y] = (u8)sx;
state[x] = (u8)sy;
return state[(sx + sy) & 0xff];
}
static void arcfour_encrypt( struct arc4context *parc4ctx,
u8 *dest,
u8 *src,
u32 len)
{
u32 i;
for (i = 0; i < len; i++)
dest[i] = src[i] ^ (unsigned char)arcfour_byte(parc4ctx);
}
static int bcrc32initialized = 0;
static u32 crc32_table[256];
static u8 crc32_reverseBit(u8 data)
{
u8 retval = ((data << 7) & 0x80) | ((data << 5) & 0x40) |
((data << 3) & 0x20) | ((data << 1) & 0x10) |
((data >> 1) & 0x08) | ((data >> 3) & 0x04) |
((data >> 5) & 0x02) | ((data >> 7) & 0x01);
return retval;
}
static void crc32_init(void)
{
if (bcrc32initialized == 1)
return;
else{
int i, j;
u32 c;
u8 *p = (u8 *)&c, *p1;
u8 k;
c = 0x12340000;
for (i = 0; i < 256; ++i) {
k = crc32_reverseBit((u8)i);
for (c = ((u32)k) << 24, j = 8; j > 0; --j) {
c = c & 0x80000000 ? (c << 1) ^ CRC32_POLY : (c << 1);
}
p1 = (u8 *)&crc32_table[i];
p1[0] = crc32_reverseBit(p[3]);
p1[1] = crc32_reverseBit(p[2]);
p1[2] = crc32_reverseBit(p[1]);
p1[3] = crc32_reverseBit(p[0]);
}
bcrc32initialized = 1;
}
}
static u32 getcrc32(u8 *buf, int len)
{
u8 *p;
u32 crc;
if (bcrc32initialized == 0) crc32_init();
crc = 0xffffffff; /* preload shift register, per CRC-32 spec */
for (p = buf; len > 0; ++p, --len)
crc = crc32_table[ (crc ^ *p) & 0xff] ^ (crc >> 8);
return ~crc; /* transmit complement, per CRC-32 spec */
}
/* Need to consider the fragment situation */
void rtw_wep_encrypt23a(struct rtw_adapter *padapter,
struct xmit_frame *pxmitframe)
{
/* exclude ICV */
unsigned char crc[4];
struct arc4context mycontext;
int curfragnum, length, index;
u32 keylength;
u8 *pframe, *payload, *iv; /* wepkey */
u8 wepkey[16];
u8 hw_hdr_offset = 0;
struct pkt_attrib *pattrib = &pxmitframe->attrib;
struct security_priv *psecuritypriv = &padapter->securitypriv;
struct xmit_priv *pxmitpriv = &padapter->xmitpriv;
if (!pxmitframe->buf_addr)
return;
hw_hdr_offset = TXDESC_OFFSET;
pframe = pxmitframe->buf_addr + hw_hdr_offset;
/* start to encrypt each fragment */
if (pattrib->encrypt != WLAN_CIPHER_SUITE_WEP40 &&
pattrib->encrypt != WLAN_CIPHER_SUITE_WEP104)
return;
index = psecuritypriv->dot11PrivacyKeyIndex;
keylength = psecuritypriv->wep_key[index].keylen;
for (curfragnum = 0; curfragnum < pattrib->nr_frags ; curfragnum++) {
iv = pframe + pattrib->hdrlen;
memcpy(&wepkey[0], iv, 3);
memcpy(&wepkey[3], &psecuritypriv->wep_key[index].key,
keylength);
payload = pframe + pattrib->iv_len + pattrib->hdrlen;
if ((curfragnum + 1) == pattrib->nr_frags) {
/* the last fragment */
length = pattrib->last_txcmdsz - pattrib->hdrlen -
pattrib->iv_len- pattrib->icv_len;
*((u32 *)crc) = cpu_to_le32(getcrc32(payload, length));
arcfour_init(&mycontext, wepkey, 3 + keylength);
arcfour_encrypt(&mycontext, payload, payload, length);
arcfour_encrypt(&mycontext, payload + length, crc, 4);
} else {
length = pxmitpriv->frag_len - pattrib->hdrlen -
pattrib->iv_len - pattrib->icv_len;
*((u32 *)crc) = cpu_to_le32(getcrc32(payload, length));
arcfour_init(&mycontext, wepkey, 3 + keylength);
arcfour_encrypt(&mycontext, payload, payload, length);
arcfour_encrypt(&mycontext, payload + length, crc, 4);
pframe += pxmitpriv->frag_len;
pframe = PTR_ALIGN(pframe, 4);
}
}
}
void rtw_wep_decrypt23a(struct rtw_adapter *padapter,
struct recv_frame *precvframe)
{
/* exclude ICV */
u8 crc[4];
struct arc4context mycontext;
int length;
u32 keylength;
u8 *pframe, *payload, *iv, wepkey[16];
u8 keyindex;
struct rx_pkt_attrib *prxattrib = &precvframe->attrib;
struct security_priv *psecuritypriv = &padapter->securitypriv;
struct sk_buff *skb = precvframe->pkt;
pframe = skb->data;
/* start to decrypt recvframe */
if (prxattrib->encrypt != WLAN_CIPHER_SUITE_WEP40 &&
prxattrib->encrypt != WLAN_CIPHER_SUITE_WEP104)
return;
iv = pframe + prxattrib->hdrlen;
/* keyindex = (iv[3]&0x3); */
keyindex = prxattrib->key_index;
keylength = psecuritypriv->wep_key[keyindex].keylen;
memcpy(&wepkey[0], iv, 3);
/* memcpy(&wepkey[3], &psecuritypriv->dot11DefKey[psecuritypriv->dot11PrivacyKeyIndex].skey[0], keylength); */
memcpy(&wepkey[3], &psecuritypriv->wep_key[keyindex].key, keylength);
length = skb->len - prxattrib->hdrlen - prxattrib->iv_len;
payload = pframe + prxattrib->iv_len + prxattrib->hdrlen;
/* decrypt payload include icv */
arcfour_init(&mycontext, wepkey, 3 + keylength);
arcfour_encrypt(&mycontext, payload, payload, length);
/* calculate icv and compare the icv */
*((u32 *)crc) = le32_to_cpu(getcrc32(payload, length - 4));
if (crc[3] != payload[length - 1] || crc[2] != payload[length - 2] ||
crc[1] != payload[length - 3] || crc[0] != payload[length - 4]) {
RT_TRACE(_module_rtl871x_security_c_, _drv_err_,
("rtw_wep_decrypt23a:icv error crc[3](%x)!= payload"
"[length-1](%x) || crc[2](%x)!= payload[length-2](%x)"
" || crc[1](%x)!= payload[length-3](%x) || crc[0](%x)"
"!= payload[length-4](%x)\n",
crc[3], payload[length - 1],
crc[2], payload[length - 2],
crc[1], payload[length - 3],
crc[0], payload[length - 4]));
}
}
/* 3 ===== TKIP related ===== */
static u32 secmicgetuint32(u8 *p)
/* Convert from Byte[] to u32 in a portable way */
{
s32 i;
u32 res = 0;
for (i = 0; i<4; i++) {
res |= ((u32)(*p++)) << (8*i);
}
return res;
}
static void secmicputuint32(u8 *p, u32 val)
/* Convert from long to Byte[] in a portable way */
{
long i;
for (i = 0; i<4; i++) {
*p++ = (u8) (val & 0xff);
val >>= 8;
}
}
static void secmicclear(struct mic_data *pmicdata)
{
/* Reset the state to the empty message. */
pmicdata->L = pmicdata->K0;
pmicdata->R = pmicdata->K1;
pmicdata->nBytesInM = 0;
pmicdata->M = 0;
}
void rtw_secmicsetkey23a(struct mic_data *pmicdata, u8 *key)
{
/* Set the key */
pmicdata->K0 = secmicgetuint32(key);
pmicdata->K1 = secmicgetuint32(key + 4);
/* and reset the message */
secmicclear(pmicdata);
}
void rtw_secmicappend23abyte23a(struct mic_data *pmicdata, u8 b)
{
/* Append the byte to our word-sized buffer */
pmicdata->M |= ((unsigned long)b) << (8*pmicdata->nBytesInM);
pmicdata->nBytesInM++;
/* Process the word if it is full. */
if (pmicdata->nBytesInM >= 4) {
pmicdata->L ^= pmicdata->M;
pmicdata->R ^= ROL32(pmicdata->L, 17);
pmicdata->L += pmicdata->R;
pmicdata->R ^= ((pmicdata->L & 0xff00ff00) >> 8) | ((pmicdata->L & 0x00ff00ff) << 8);
pmicdata->L += pmicdata->R;
pmicdata->R ^= ROL32(pmicdata->L, 3);
pmicdata->L += pmicdata->R;
pmicdata->R ^= ROR32(pmicdata->L, 2);
pmicdata->L += pmicdata->R;
/* Clear the buffer */
pmicdata->M = 0;
pmicdata->nBytesInM = 0;
}
}
void rtw_secmicappend23a(struct mic_data *pmicdata, u8 *src, u32 nbytes)
{
/* This is simple */
while(nbytes > 0) {
rtw_secmicappend23abyte23a(pmicdata, *src++);
nbytes--;
}
}
void rtw_secgetmic23a(struct mic_data *pmicdata, u8 *dst)
{
/* Append the minimum padding */
rtw_secmicappend23abyte23a(pmicdata, 0x5a);
rtw_secmicappend23abyte23a(pmicdata, 0);
rtw_secmicappend23abyte23a(pmicdata, 0);
rtw_secmicappend23abyte23a(pmicdata, 0);
rtw_secmicappend23abyte23a(pmicdata, 0);
/* and then zeroes until the length is a multiple of 4 */
while(pmicdata->nBytesInM != 0) {
rtw_secmicappend23abyte23a(pmicdata, 0);
}
/* The appendByte function has already computed the result. */
secmicputuint32(dst, pmicdata->L);
secmicputuint32(dst+4, pmicdata->R);
/* Reset to the empty message. */
secmicclear(pmicdata);
}
void rtw_seccalctkipmic23a(u8 *key, u8 *header, u8 *data, u32 data_len,
u8 *mic_code, u8 pri)
{
struct mic_data micdata;
u8 priority[4]={0x0, 0x0, 0x0, 0x0};
rtw_secmicsetkey23a(&micdata, key);
priority[0]= pri;
/* Michael MIC pseudo header: DA, SA, 3 x 0, Priority */
if (header[1]&1) { /* ToDS == 1 */
rtw_secmicappend23a(&micdata, &header[16], 6); /* DA */
if (header[1]&2) /* From Ds == 1 */
rtw_secmicappend23a(&micdata, &header[24], 6);
else
rtw_secmicappend23a(&micdata, &header[10], 6);
}
else{ /* ToDS == 0 */
rtw_secmicappend23a(&micdata, &header[4], 6); /* DA */
if (header[1]&2) /* From Ds == 1 */
rtw_secmicappend23a(&micdata, &header[16], 6);
else
rtw_secmicappend23a(&micdata, &header[10], 6);
}
rtw_secmicappend23a(&micdata, &priority[0], 4);
rtw_secmicappend23a(&micdata, data, data_len);
rtw_secgetmic23a(&micdata, mic_code);
}
/* macros for extraction/creation of unsigned char/unsigned short values */
#define RotR1(v16) ((((v16) >> 1) & 0x7FFF) ^ (((v16) & 1) << 15))
#define Lo8(v16) ((u8)((v16) & 0x00FF))
#define Hi8(v16) ((u8)(((v16) >> 8) & 0x00FF))
#define Lo16(v32) ((u16)((v32) & 0xFFFF))
#define Hi16(v32) ((u16)(((v32) >>16) & 0xFFFF))
#define Mk16(hi, lo) ((lo) ^ (((u16)(hi)) << 8))
/* select the Nth 16-bit word of the temporal key unsigned char array TK[] */
#define TK16(N) Mk16(tk[2*(N)+1], tk[2*(N)])
/* S-box lookup: 16 bits --> 16 bits */
#define _S_(v16) (Sbox1[0][Lo8(v16)] ^ Sbox1[1][Hi8(v16)])
/* fixed algorithm "parameters" */
#define PHASE1_LOOP_CNT 8 /* this needs to be "big enough" */
#define TA_SIZE 6 /* 48-bit transmitter address */
#define TK_SIZE 16 /* 128-bit temporal key */
#define P1K_SIZE 10 /* 80-bit Phase1 key */
#define RC4_KEY_SIZE 16 /* 128-bit RC4KEY (104 bits unknown) */
/* 2-unsigned char by 2-unsigned char subset of the full AES S-box table */
static const unsigned short Sbox1[2][256]= /* Sbox for hash (can be in ROM) */
{ {
0xC6A5, 0xF884, 0xEE99, 0xF68D, 0xFF0D, 0xD6BD, 0xDEB1, 0x9154,
0x6050, 0x0203, 0xCEA9, 0x567D, 0xE719, 0xB562, 0x4DE6, 0xEC9A,
0x8F45, 0x1F9D, 0x8940, 0xFA87, 0xEF15, 0xB2EB, 0x8EC9, 0xFB0B,
0x41EC, 0xB367, 0x5FFD, 0x45EA, 0x23BF, 0x53F7, 0xE496, 0x9B5B,
0x75C2, 0xE11C, 0x3DAE, 0x4C6A, 0x6C5A, 0x7E41, 0xF502, 0x834F,
0x685C, 0x51F4, 0xD134, 0xF908, 0xE293, 0xAB73, 0x6253, 0x2A3F,
0x080C, 0x9552, 0x4665, 0x9D5E, 0x3028, 0x37A1, 0x0A0F, 0x2FB5,
0x0E09, 0x2436, 0x1B9B, 0xDF3D, 0xCD26, 0x4E69, 0x7FCD, 0xEA9F,
0x121B, 0x1D9E, 0x5874, 0x342E, 0x362D, 0xDCB2, 0xB4EE, 0x5BFB,
0xA4F6, 0x764D, 0xB761, 0x7DCE, 0x527B, 0xDD3E, 0x5E71, 0x1397,
0xA6F5, 0xB968, 0x0000, 0xC12C, 0x4060, 0xE31F, 0x79C8, 0xB6ED,
0xD4BE, 0x8D46, 0x67D9, 0x724B, 0x94DE, 0x98D4, 0xB0E8, 0x854A,
0xBB6B, 0xC52A, 0x4FE5, 0xED16, 0x86C5, 0x9AD7, 0x6655, 0x1194,
0x8ACF, 0xE910, 0x0406, 0xFE81, 0xA0F0, 0x7844, 0x25BA, 0x4BE3,
0xA2F3, 0x5DFE, 0x80C0, 0x058A, 0x3FAD, 0x21BC, 0x7048, 0xF104,
0x63DF, 0x77C1, 0xAF75, 0x4263, 0x2030, 0xE51A, 0xFD0E, 0xBF6D,
0x814C, 0x1814, 0x2635, 0xC32F, 0xBEE1, 0x35A2, 0x88CC, 0x2E39,
0x9357, 0x55F2, 0xFC82, 0x7A47, 0xC8AC, 0xBAE7, 0x322B, 0xE695,
0xC0A0, 0x1998, 0x9ED1, 0xA37F, 0x4466, 0x547E, 0x3BAB, 0x0B83,
0x8CCA, 0xC729, 0x6BD3, 0x283C, 0xA779, 0xBCE2, 0x161D, 0xAD76,
0xDB3B, 0x6456, 0x744E, 0x141E, 0x92DB, 0x0C0A, 0x486C, 0xB8E4,
0x9F5D, 0xBD6E, 0x43EF, 0xC4A6, 0x39A8, 0x31A4, 0xD337, 0xF28B,
0xD532, 0x8B43, 0x6E59, 0xDAB7, 0x018C, 0xB164, 0x9CD2, 0x49E0,
0xD8B4, 0xACFA, 0xF307, 0xCF25, 0xCAAF, 0xF48E, 0x47E9, 0x1018,
0x6FD5, 0xF088, 0x4A6F, 0x5C72, 0x3824, 0x57F1, 0x73C7, 0x9751,
0xCB23, 0xA17C, 0xE89C, 0x3E21, 0x96DD, 0x61DC, 0x0D86, 0x0F85,
0xE090, 0x7C42, 0x71C4, 0xCCAA, 0x90D8, 0x0605, 0xF701, 0x1C12,
0xC2A3, 0x6A5F, 0xAEF9, 0x69D0, 0x1791, 0x9958, 0x3A27, 0x27B9,
0xD938, 0xEB13, 0x2BB3, 0x2233, 0xD2BB, 0xA970, 0x0789, 0x33A7,
0x2DB6, 0x3C22, 0x1592, 0xC920, 0x8749, 0xAAFF, 0x5078, 0xA57A,
0x038F, 0x59F8, 0x0980, 0x1A17, 0x65DA, 0xD731, 0x84C6, 0xD0B8,
0x82C3, 0x29B0, 0x5A77, 0x1E11, 0x7BCB, 0xA8FC, 0x6DD6, 0x2C3A,
},
{ /* second half of table is unsigned char-reversed version of first! */
0xA5C6, 0x84F8, 0x99EE, 0x8DF6, 0x0DFF, 0xBDD6, 0xB1DE, 0x5491,
0x5060, 0x0302, 0xA9CE, 0x7D56, 0x19E7, 0x62B5, 0xE64D, 0x9AEC,
0x458F, 0x9D1F, 0x4089, 0x87FA, 0x15EF, 0xEBB2, 0xC98E, 0x0BFB,
0xEC41, 0x67B3, 0xFD5F, 0xEA45, 0xBF23, 0xF753, 0x96E4, 0x5B9B,
0xC275, 0x1CE1, 0xAE3D, 0x6A4C, 0x5A6C, 0x417E, 0x02F5, 0x4F83,
0x5C68, 0xF451, 0x34D1, 0x08F9, 0x93E2, 0x73AB, 0x5362, 0x3F2A,
0x0C08, 0x5295, 0x6546, 0x5E9D, 0x2830, 0xA137, 0x0F0A, 0xB52F,
0x090E, 0x3624, 0x9B1B, 0x3DDF, 0x26CD, 0x694E, 0xCD7F, 0x9FEA,
0x1B12, 0x9E1D, 0x7458, 0x2E34, 0x2D36, 0xB2DC, 0xEEB4, 0xFB5B,
0xF6A4, 0x4D76, 0x61B7, 0xCE7D, 0x7B52, 0x3EDD, 0x715E, 0x9713,
0xF5A6, 0x68B9, 0x0000, 0x2CC1, 0x6040, 0x1FE3, 0xC879, 0xEDB6,
0xBED4, 0x468D, 0xD967, 0x4B72, 0xDE94, 0xD498, 0xE8B0, 0x4A85,
0x6BBB, 0x2AC5, 0xE54F, 0x16ED, 0xC586, 0xD79A, 0x5566, 0x9411,
0xCF8A, 0x10E9, 0x0604, 0x81FE, 0xF0A0, 0x4478, 0xBA25, 0xE34B,
0xF3A2, 0xFE5D, 0xC080, 0x8A05, 0xAD3F, 0xBC21, 0x4870, 0x04F1,
0xDF63, 0xC177, 0x75AF, 0x6342, 0x3020, 0x1AE5, 0x0EFD, 0x6DBF,
0x4C81, 0x1418, 0x3526, 0x2FC3, 0xE1BE, 0xA235, 0xCC88, 0x392E,
0x5793, 0xF255, 0x82FC, 0x477A, 0xACC8, 0xE7BA, 0x2B32, 0x95E6,
0xA0C0, 0x9819, 0xD19E, 0x7FA3, 0x6644, 0x7E54, 0xAB3B, 0x830B,
0xCA8C, 0x29C7, 0xD36B, 0x3C28, 0x79A7, 0xE2BC, 0x1D16, 0x76AD,
0x3BDB, 0x5664, 0x4E74, 0x1E14, 0xDB92, 0x0A0C, 0x6C48, 0xE4B8,
0x5D9F, 0x6EBD, 0xEF43, 0xA6C4, 0xA839, 0xA431, 0x37D3, 0x8BF2,
0x32D5, 0x438B, 0x596E, 0xB7DA, 0x8C01, 0x64B1, 0xD29C, 0xE049,
0xB4D8, 0xFAAC, 0x07F3, 0x25CF, 0xAFCA, 0x8EF4, 0xE947, 0x1810,
0xD56F, 0x88F0, 0x6F4A, 0x725C, 0x2438, 0xF157, 0xC773, 0x5197,
0x23CB, 0x7CA1, 0x9CE8, 0x213E, 0xDD96, 0xDC61, 0x860D, 0x850F,
0x90E0, 0x427C, 0xC471, 0xAACC, 0xD890, 0x0506, 0x01F7, 0x121C,
0xA3C2, 0x5F6A, 0xF9AE, 0xD069, 0x9117, 0x5899, 0x273A, 0xB927,
0x38D9, 0x13EB, 0xB32B, 0x3322, 0xBBD2, 0x70A9, 0x8907, 0xA733,
0xB62D, 0x223C, 0x9215, 0x20C9, 0x4987, 0xFFAA, 0x7850, 0x7AA5,
0x8F03, 0xF859, 0x8009, 0x171A, 0xDA65, 0x31D7, 0xC684, 0xB8D0,
0xC382, 0xB029, 0x775A, 0x111E, 0xCB7B, 0xFCA8, 0xD66D, 0x3A2C,
}
};
/*
**********************************************************************
* Routine: Phase 1 -- generate P1K, given TA, TK, IV32
*
* Inputs:
* tk[] = temporal key [128 bits]
* ta[] = transmitter's MAC address [ 48 bits]
* iv32 = upper 32 bits of IV [ 32 bits]
* Output:
* p1k[] = Phase 1 key [ 80 bits]
*
* Note:
* This function only needs to be called every 2**16 packets,
* although in theory it could be called every packet.
*
**********************************************************************
*/
static void phase1(u16 *p1k, const u8 *tk, const u8 *ta, u32 iv32)
{
int i;
/* Initialize the 80 bits of P1K[] from IV32 and TA[0..5] */
p1k[0] = Lo16(iv32);
p1k[1] = Hi16(iv32);
p1k[2] = Mk16(ta[1], ta[0]); /* use TA[] as little-endian */
p1k[3] = Mk16(ta[3], ta[2]);
p1k[4] = Mk16(ta[5], ta[4]);
/* Now compute an unbalanced Feistel cipher with 80-bit block */
/* size on the 80-bit block P1K[], using the 128-bit key TK[] */
for (i = 0; i < PHASE1_LOOP_CNT ;i++) {
/* Each add operation here is mod 2**16 */
p1k[0] += _S_(p1k[4] ^ TK16((i&1)+0));
p1k[1] += _S_(p1k[0] ^ TK16((i&1)+2));
p1k[2] += _S_(p1k[1] ^ TK16((i&1)+4));
p1k[3] += _S_(p1k[2] ^ TK16((i&1)+6));
p1k[4] += _S_(p1k[3] ^ TK16((i&1)+0));
p1k[4] += (unsigned short)i; /* avoid "slide attacks" */
}
}
/*
**********************************************************************
* Routine: Phase 2 -- generate RC4KEY, given TK, P1K, IV16
*
* Inputs:
* tk[] = Temporal key [128 bits]
* p1k[] = Phase 1 output key [ 80 bits]
* iv16 = low 16 bits of IV counter [ 16 bits]
* Output:
* rc4key[] = the key used to encrypt the packet [128 bits]
*
* Note:
* The value {TA, IV32, IV16} for Phase1/Phase2 must be unique
* across all packets using the same key TK value. Then, for a
* given value of TK[], this TKIP48 construction guarantees that
* the final RC4KEY value is unique across all packets.
*
* Suggested implementation optimization: if PPK[] is "overlaid"
* appropriately on RC4KEY[], there is no need for the final
* for loop below that copies the PPK[] result into RC4KEY[].
*
**********************************************************************
*/
static void phase2(u8 *rc4key, const u8 *tk, const u16 *p1k, u16 iv16)
{
int i;
u16 PPK[6]; /* temporary key for mixing */
/* Note: all adds in the PPK[] equations below are mod 2**16 */
for (i = 0;i<5;i++) PPK[i]= p1k[i]; /* first, copy P1K to PPK */
PPK[5] = p1k[4] +iv16; /* next, add in IV16 */
/* Bijective non-linear mixing of the 96 bits of PPK[0..5] */
PPK[0] += _S_(PPK[5] ^ TK16(0)); /* Mix key in each "round" */
PPK[1] += _S_(PPK[0] ^ TK16(1));
PPK[2] += _S_(PPK[1] ^ TK16(2));
PPK[3] += _S_(PPK[2] ^ TK16(3));
PPK[4] += _S_(PPK[3] ^ TK16(4));
PPK[5] += _S_(PPK[4] ^ TK16(5)); /* Total # S-box lookups == 6 */
/* Final sweep: bijective, "linear". Rotates kill LSB correlations */
PPK[0] += RotR1(PPK[5] ^ TK16(6));
PPK[1] += RotR1(PPK[0] ^ TK16(7)); /* Use all of TK[] in Phase2 */
PPK[2] += RotR1(PPK[1]);
PPK[3] += RotR1(PPK[2]);
PPK[4] += RotR1(PPK[3]);
PPK[5] += RotR1(PPK[4]);
/* Note: At this point, for a given key TK[0..15], the 96-bit output */
/* value PPK[0..5] is guaranteed to be unique, as a function */
/* of the 96-bit "input" value {TA, IV32, IV16}. That is, P1K */
/* is now a keyed permutation of {TA, IV32, IV16}. */
/* Set RC4KEY[0..3], which includes "cleartext" portion of RC4 key */
rc4key[0] = Hi8(iv16); /* RC4KEY[0..2] is the WEP IV */
rc4key[1] = (Hi8(iv16) | 0x20) & 0x7F; /* Help avoid weak (FMS) keys */
rc4key[2] = Lo8(iv16);
rc4key[3] = Lo8((PPK[5] ^ TK16(0)) >> 1);
/* Copy 96 bits of PPK[0..5] to RC4KEY[4..15] (little-endian) */
for (i = 0;i<6;i++) {
rc4key[4+2*i] = Lo8(PPK[i]);
rc4key[5+2*i] = Hi8(PPK[i]);
}
}
/* The hlen isn't include the IV */
int rtw_tkip_encrypt23a(struct rtw_adapter *padapter,
struct xmit_frame *pxmitframe)
{
u16 pnl;
u32 pnh;
u8 rc4key[16];
u8 ttkey[16];
u8 crc[4];
u8 hw_hdr_offset = 0;
struct arc4context mycontext;
int curfragnum, length;
u32 prwskeylen;
u8 *pframe, *payload, *iv, *prwskey;
union pn48 dot11txpn;
struct sta_info *stainfo;
struct pkt_attrib *pattrib = &pxmitframe->attrib;
struct security_priv *psecuritypriv = &padapter->securitypriv;
struct xmit_priv *pxmitpriv = &padapter->xmitpriv;
int res = _SUCCESS;
if (!pxmitframe->buf_addr)
return _FAIL;
hw_hdr_offset = TXDESC_OFFSET;
pframe = pxmitframe->buf_addr + hw_hdr_offset;
/* 4 start to encrypt each fragment */
if (pattrib->encrypt == WLAN_CIPHER_SUITE_TKIP) {
if (pattrib->psta)
stainfo = pattrib->psta;
else {
DBG_8723A("%s, call rtw_get_stainfo()\n", __func__);
stainfo = rtw_get_stainfo23a(&padapter->stapriv,
&pattrib->ra[0]);
}
if (stainfo!= NULL) {
if (!(stainfo->state &_FW_LINKED)) {
DBG_8723A("%s, psta->state(0x%x) != _FW_LINKED\n", __func__, stainfo->state);
return _FAIL;
}
RT_TRACE(_module_rtl871x_security_c_, _drv_err_, ("rtw_tkip_encrypt23a: stainfo!= NULL!!!\n"));
if (is_multicast_ether_addr(pattrib->ra))
prwskey = psecuritypriv->dot118021XGrpKey[psecuritypriv->dot118021XGrpKeyid].skey;
else
prwskey = &stainfo->dot118021x_UncstKey.skey[0];
prwskeylen = 16;
for (curfragnum = 0;curfragnum<pattrib->nr_frags;curfragnum++) {
iv = pframe+pattrib->hdrlen;
payload = pframe+pattrib->iv_len+pattrib->hdrlen;
GET_TKIP_PN(iv, dot11txpn);
pnl = (u16)(dot11txpn.val);
pnh = (u32)(dot11txpn.val>>16);
phase1((u16 *)&ttkey[0], prwskey,&pattrib->ta[0], pnh);
phase2(&rc4key[0], prwskey, (u16 *)&ttkey[0], pnl);
if ((curfragnum+1) == pattrib->nr_frags) { /* 4 the last fragment */
length = pattrib->last_txcmdsz-pattrib->hdrlen-pattrib->iv_len- pattrib->icv_len;
RT_TRACE(_module_rtl871x_security_c_, _drv_info_, ("pattrib->iv_len =%x, pattrib->icv_len =%x\n", pattrib->iv_len, pattrib->icv_len));
*((u32 *)crc) = cpu_to_le32(getcrc32(payload, length));/* modified by Amy*/
arcfour_init(&mycontext, rc4key, 16);
arcfour_encrypt(&mycontext, payload, payload, length);
arcfour_encrypt(&mycontext, payload+length, crc, 4);
}
else{
length = pxmitpriv->frag_len-pattrib->hdrlen-pattrib->iv_len-pattrib->icv_len ;
*((u32 *)crc) = cpu_to_le32(getcrc32(payload, length));/* modified by Amy*/
arcfour_init(&mycontext, rc4key, 16);
arcfour_encrypt(&mycontext, payload, payload, length);
arcfour_encrypt(&mycontext, payload+length, crc, 4);
pframe+= pxmitpriv->frag_len;
pframe = PTR_ALIGN(pframe, 4);
}
}
}
else{
RT_TRACE(_module_rtl871x_security_c_, _drv_err_, ("rtw_tkip_encrypt23a: stainfo == NULL!!!\n"));
DBG_8723A("%s, psta == NUL\n", __func__);
res = _FAIL;
}
}
return res;
}
/* The hlen isn't include the IV */
int rtw_tkip_decrypt23a(struct rtw_adapter *padapter,
struct recv_frame *precvframe)
{
u16 pnl;
u32 pnh;
u8 rc4key[16];
u8 ttkey[16];
u8 crc[4];
struct arc4context mycontext;
int length;
u32 prwskeylen;
u8 *pframe, *payload, *iv, *prwskey;
union pn48 dot11txpn;
struct sta_info *stainfo;
struct rx_pkt_attrib *prxattrib = &precvframe->attrib;
struct security_priv *psecuritypriv = &padapter->securitypriv;
struct sk_buff *skb = precvframe->pkt;
int res = _SUCCESS;
pframe = skb->data;
/* 4 start to decrypt recvframe */
if (prxattrib->encrypt == WLAN_CIPHER_SUITE_TKIP) {
stainfo = rtw_get_stainfo23a(&padapter->stapriv,
&prxattrib->ta[0]);
if (stainfo!= NULL) {
if (is_multicast_ether_addr(prxattrib->ra)) {
if (psecuritypriv->binstallGrpkey == 0) {
res = _FAIL;
DBG_8723A("%s:rx bc/mc packets, but didn't install group key!!!!!!!!!!\n", __func__);
goto exit;
}
prwskey = psecuritypriv->dot118021XGrpKey[prxattrib->key_index].skey;
prwskeylen = 16;
} else {
RT_TRACE(_module_rtl871x_security_c_, _drv_err_, ("rtw_tkip_decrypt23a: stainfo!= NULL!!!\n"));
prwskey = &stainfo->dot118021x_UncstKey.skey[0];
prwskeylen = 16;
}
iv = pframe+prxattrib->hdrlen;
payload = pframe+prxattrib->iv_len+prxattrib->hdrlen;
length = skb->len - prxattrib->hdrlen-prxattrib->iv_len;
GET_TKIP_PN(iv, dot11txpn);
pnl = (u16)(dot11txpn.val);
pnh = (u32)(dot11txpn.val>>16);
phase1((u16 *)&ttkey[0], prwskey,&prxattrib->ta[0], pnh);
phase2(&rc4key[0], prwskey, (unsigned short *)&ttkey[0], pnl);
/* 4 decrypt payload include icv */
arcfour_init(&mycontext, rc4key, 16);
arcfour_encrypt(&mycontext, payload, payload, length);
*((u32 *)crc) = le32_to_cpu(getcrc32(payload, length-4));
if (crc[3]!= payload[length-1] || crc[2]!= payload[length-2] || crc[1]!= payload[length-3] || crc[0]!= payload[length-4])
{
RT_TRACE(_module_rtl871x_security_c_, _drv_err_, ("rtw_wep_decrypt23a:icv error crc[3](%x)!= payload[length-1](%x) || crc[2](%x)!= payload[length-2](%x) || crc[1](%x)!= payload[length-3](%x) || crc[0](%x)!= payload[length-4](%x)\n",
crc[3], payload[length-1], crc[2], payload[length-2], crc[1], payload[length-3], crc[0], payload[length-4]));
res = _FAIL;
}
} else {
RT_TRACE(_module_rtl871x_security_c_, _drv_err_, ("rtw_tkip_decrypt23a: stainfo == NULL!!!\n"));
res = _FAIL;
}
}
exit:
return res;
}
/* 3 ===== AES related ===== */
#define MAX_MSG_SIZE 2048
/*****************************/
/******** SBOX Table *********/
/*****************************/
static u8 sbox_table[256] = {
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5,
0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc,
0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a,
0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b,
0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85,
0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17,
0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88,
0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9,
0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6,
0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94,
0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68,
0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16
};
/*****************************/
/**** Function Prototypes ****/
/*****************************/
static void construct_mic_header2(u8 *mic_header2, u8 *mpdu, int a4_exists,
int qc_exists);
static void xor_128(u8 *a, u8 *b, u8 *out)
{
int i;
for (i = 0;i<16; i++)
out[i] = a[i] ^ b[i];
}
static void xor_32(u8 *a, u8 *b, u8 *out)
{
int i;
for (i = 0; i < 4; i++)
out[i] = a[i] ^ b[i];
}
static u8 sbox(u8 a)
{
return sbox_table[(int)a];
}
static void next_key(u8 *key, int round)
{
u8 rcon;
u8 sbox_key[4];
u8 rcon_table[12] =
{
0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80,
0x1b, 0x36, 0x36, 0x36
};
sbox_key[0] = sbox(key[13]);
sbox_key[1] = sbox(key[14]);
sbox_key[2] = sbox(key[15]);
sbox_key[3] = sbox(key[12]);
rcon = rcon_table[round];
xor_32(&key[0], sbox_key, &key[0]);
key[0] = key[0] ^ rcon;
xor_32(&key[4], &key[0], &key[4]);
xor_32(&key[8], &key[4], &key[8]);
xor_32(&key[12], &key[8], &key[12]);
}
static void byte_sub(u8 *in, u8 *out)
{
int i;
for (i = 0; i< 16; i++) {
out[i] = sbox(in[i]);
}
}
static void shift_row(u8 *in, u8 *out)
{
out[0] = in[0];
out[1] = in[5];
out[2] = in[10];
out[3] = in[15];
out[4] = in[4];
out[5] = in[9];
out[6] = in[14];
out[7] = in[3];
out[8] = in[8];
out[9] = in[13];
out[10] = in[2];
out[11] = in[7];
out[12] = in[12];
out[13] = in[1];
out[14] = in[6];
out[15] = in[11];
}
static void mix_column(u8 *in, u8 *out)
{
int i;
u8 add1b[4];
u8 add1bf7[4];
u8 rotl[4];
u8 swap_halfs[4];
u8 andf7[4];
u8 rotr[4];
u8 temp[4];
u8 tempb[4];
for (i = 0 ; i<4; i++) {
if ((in[i] & 0x80) == 0x80)
add1b[i] = 0x1b;
else
add1b[i] = 0x00;
}
swap_halfs[0] = in[2]; /* Swap halfs */
swap_halfs[1] = in[3];
swap_halfs[2] = in[0];
swap_halfs[3] = in[1];
rotl[0] = in[3]; /* Rotate left 8 bits */
rotl[1] = in[0];
rotl[2] = in[1];
rotl[3] = in[2];
andf7[0] = in[0] & 0x7f;
andf7[1] = in[1] & 0x7f;
andf7[2] = in[2] & 0x7f;
andf7[3] = in[3] & 0x7f;
for (i = 3; i>0; i--) { /* logical shift left 1 bit */
andf7[i] = andf7[i] << 1;
if ((andf7[i-1] & 0x80) == 0x80) {
andf7[i] = (andf7[i] | 0x01);
}
}
andf7[0] = andf7[0] << 1;
andf7[0] = andf7[0] & 0xfe;
xor_32(add1b, andf7, add1bf7);
xor_32(in, add1bf7, rotr);
temp[0] = rotr[0]; /* Rotate right 8 bits */
rotr[0] = rotr[1];
rotr[1] = rotr[2];
rotr[2] = rotr[3];
rotr[3] = temp[0];
xor_32(add1bf7, rotr, temp);
xor_32(swap_halfs, rotl, tempb);
xor_32(temp, tempb, out);
}
static void aes128k128d(u8 *key, u8 *data, u8 *ciphertext)
{
int round;
int i;
u8 intermediatea[16];
u8 intermediateb[16];
u8 round_key[16];
for (i = 0; i<16; i++) round_key[i] = key[i];
for (round = 0; round < 11; round++) {
if (round == 0) {
xor_128(round_key, data, ciphertext);
next_key(round_key, round);
} else if (round == 10) {
byte_sub(ciphertext, intermediatea);
shift_row(intermediatea, intermediateb);
xor_128(intermediateb, round_key, ciphertext);
} else { /* 1 - 9 */
byte_sub(ciphertext, intermediatea);
shift_row(intermediatea, intermediateb);
mix_column(&intermediateb[0], &intermediatea[0]);
mix_column(&intermediateb[4], &intermediatea[4]);
mix_column(&intermediateb[8], &intermediatea[8]);
mix_column(&intermediateb[12], &intermediatea[12]);
xor_128(intermediatea, round_key, ciphertext);
next_key(round_key, round);
}
}
}
/************************************************/
/* construct_mic_iv() */
/* Builds the MIC IV from header fields and PN */
/************************************************/
static void construct_mic_iv(u8 *mic_iv, int qc_exists, int a4_exists, u8 *mpdu,
uint payload_length, u8 *pn_vector)
{
int i;
mic_iv[0] = 0x59;
if (qc_exists && a4_exists)
mic_iv[1] = mpdu[30] & 0x0f; /* QoS_TC */
if (qc_exists && !a4_exists)
mic_iv[1] = mpdu[24] & 0x0f; /* mute bits 7-4 */
if (!qc_exists)
mic_iv[1] = 0x00;
for (i = 2; i < 8; i++)
mic_iv[i] = mpdu[i + 8]; /* mic_iv[2:7] = A2[0:5] = mpdu[10:15] */
for (i = 8; i < 14; i++)
mic_iv[i] = pn_vector[13 - i]; /* mic_iv[8:13] = PN[5:0] */
mic_iv[14] = (unsigned char)(payload_length / 256);
mic_iv[15] = (unsigned char)(payload_length % 256);
}
/************************************************/
/* construct_mic_header1() */
/* Builds the first MIC header block from */
/* header fields. */
/************************************************/
static void construct_mic_header1(u8 *mic_header1, int header_length, u8 *mpdu)
{
mic_header1[0] = (u8)((header_length - 2) / 256);
mic_header1[1] = (u8)((header_length - 2) % 256);
mic_header1[2] = mpdu[0] & 0xcf; /* Mute CF poll & CF ack bits */
mic_header1[3] = mpdu[1] & 0xc7; /* Mute retry, more data and pwr mgt bits */
mic_header1[4] = mpdu[4]; /* A1 */
mic_header1[5] = mpdu[5];
mic_header1[6] = mpdu[6];
mic_header1[7] = mpdu[7];
mic_header1[8] = mpdu[8];
mic_header1[9] = mpdu[9];
mic_header1[10] = mpdu[10]; /* A2 */
mic_header1[11] = mpdu[11];
mic_header1[12] = mpdu[12];
mic_header1[13] = mpdu[13];
mic_header1[14] = mpdu[14];
mic_header1[15] = mpdu[15];
}
/************************************************/
/* construct_mic_header2() */
/* Builds the last MIC header block from */
/* header fields. */
/************************************************/
static void construct_mic_header2(u8 *mic_header2, u8 *mpdu, int a4_exists,
int qc_exists)
{
int i;
for (i = 0; i<16; i++) mic_header2[i]= 0x00;
mic_header2[0] = mpdu[16]; /* A3 */
mic_header2[1] = mpdu[17];
mic_header2[2] = mpdu[18];
mic_header2[3] = mpdu[19];
mic_header2[4] = mpdu[20];
mic_header2[5] = mpdu[21];
mic_header2[6] = 0x00;
mic_header2[7] = 0x00; /* mpdu[23]; */
if (!qc_exists && a4_exists) {
for (i = 0;i<6;i++) mic_header2[8+i] = mpdu[24+i]; /* A4 */
}
if (qc_exists && !a4_exists) {
mic_header2[8] = mpdu[24] & 0x0f; /* mute bits 15 - 4 */
mic_header2[9] = mpdu[25] & 0x00;
}
if (qc_exists && a4_exists) {
for (i = 0;i<6;i++) mic_header2[8+i] = mpdu[24+i]; /* A4 */
mic_header2[14] = mpdu[30] & 0x0f;
mic_header2[15] = mpdu[31] & 0x00;
}
}
/************************************************/
/* construct_mic_header2() */
/* Builds the last MIC header block from */
/* header fields. */
/************************************************/
static void construct_ctr_preload(u8 *ctr_preload, int a4_exists, int qc_exists,
u8 *mpdu, u8 *pn_vector, int c)
{
int i = 0;
for (i = 0; i<16; i++) ctr_preload[i] = 0x00;
i = 0;
ctr_preload[0] = 0x01; /* flag */
if (qc_exists && a4_exists)
ctr_preload[1] = mpdu[30] & 0x0f; /* QoC_Control */
if (qc_exists && !a4_exists)
ctr_preload[1] = mpdu[24] & 0x0f;
for (i = 2; i < 8; i++)
ctr_preload[i] = mpdu[i + 8]; /* ctr_preload[2:7] = A2[0:5] = mpdu[10:15] */
for (i = 8; i < 14; i++)
ctr_preload[i] = pn_vector[13 - i]; /* ctr_preload[8:13] = PN[5:0] */
ctr_preload[14] = (unsigned char) (c / 256); /* Ctr */
ctr_preload[15] = (unsigned char) (c % 256);
}
/************************************/
/* bitwise_xor() */
/* A 128 bit, bitwise exclusive or */
/************************************/
static void bitwise_xor(u8 *ina, u8 *inb, u8 *out)
{
int i;
for (i = 0; i < 16; i++)
out[i] = ina[i] ^ inb[i];
}
static int aes_cipher(u8 *key, uint hdrlen, u8 *pframe, uint plen)
{
uint qc_exists, a4_exists, i, j, payload_remainder,
num_blocks, payload_index;
u8 pn_vector[6];
u8 mic_iv[16];
u8 mic_header1[16];
u8 mic_header2[16];
u8 ctr_preload[16];
/* Intermediate Buffers */
u8 chain_buffer[16];
u8 aes_out[16];
u8 padded_buffer[16];
u8 mic[8];
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)pframe;
u16 frsubtype = le16_to_cpu(hdr->frame_control) & IEEE80211_FCTL_STYPE;
memset((void *)mic_iv, 0, 16);
memset((void *)mic_header1, 0, 16);
memset((void *)mic_header2, 0, 16);
memset((void *)ctr_preload, 0, 16);
memset((void *)chain_buffer, 0, 16);
memset((void *)aes_out, 0, 16);
memset((void *)padded_buffer, 0, 16);
if ((hdrlen == sizeof(struct ieee80211_hdr_3addr) ||
(hdrlen == sizeof(struct ieee80211_qos_hdr))))
a4_exists = 0;
else
a4_exists = 1;
if (ieee80211_is_data(hdr->frame_control)) {
if ((frsubtype == IEEE80211_STYPE_DATA_CFACK) ||
(frsubtype == IEEE80211_STYPE_DATA_CFPOLL) ||
(frsubtype == IEEE80211_STYPE_DATA_CFACKPOLL)) {
qc_exists = 1;
if (hdrlen != sizeof(struct ieee80211_qos_hdr))
hdrlen += 2;
} else if ((frsubtype == IEEE80211_STYPE_QOS_DATA) ||
(frsubtype == IEEE80211_STYPE_QOS_DATA_CFACK) ||
(frsubtype == IEEE80211_STYPE_QOS_DATA_CFPOLL) ||
(frsubtype == IEEE80211_STYPE_QOS_DATA_CFACKPOLL)) {
if (hdrlen != sizeof(struct ieee80211_qos_hdr))
hdrlen += 2;
qc_exists = 1;
} else {
qc_exists = 0;
}
} else {
qc_exists = 0;
}
pn_vector[0]= pframe[hdrlen];
pn_vector[1]= pframe[hdrlen+1];
pn_vector[2]= pframe[hdrlen+4];
pn_vector[3]= pframe[hdrlen+5];
pn_vector[4]= pframe[hdrlen+6];
pn_vector[5]= pframe[hdrlen+7];
construct_mic_iv(mic_iv, qc_exists, a4_exists, pframe, plen, pn_vector);
construct_mic_header1(mic_header1, hdrlen, pframe);
construct_mic_header2(mic_header2, pframe, a4_exists, qc_exists);
payload_remainder = plen % 16;
num_blocks = plen / 16;
/* Find start of payload */
payload_index = (hdrlen + 8);
/* Calculate MIC */
aes128k128d(key, mic_iv, aes_out);
bitwise_xor(aes_out, mic_header1, chain_buffer);
aes128k128d(key, chain_buffer, aes_out);
bitwise_xor(aes_out, mic_header2, chain_buffer);
aes128k128d(key, chain_buffer, aes_out);
for (i = 0; i < num_blocks; i++) {
bitwise_xor(aes_out, &pframe[payload_index], chain_buffer);
payload_index += 16;
aes128k128d(key, chain_buffer, aes_out);
}
/* Add on the final payload block if it needs padding */
if (payload_remainder > 0) {
for (j = 0; j < 16; j++)
padded_buffer[j] = 0x00;
for (j = 0; j < payload_remainder; j++)
padded_buffer[j] = pframe[payload_index++];
bitwise_xor(aes_out, padded_buffer, chain_buffer);
aes128k128d(key, chain_buffer, aes_out);
}
for (j = 0; j < 8; j++)
mic[j] = aes_out[j];
/* Insert MIC into payload */
for (j = 0; j < 8; j++)
pframe[payload_index+j] = mic[j];
payload_index = hdrlen + 8;
for (i = 0; i < num_blocks; i++) {
construct_ctr_preload(ctr_preload, a4_exists, qc_exists,
pframe, pn_vector, i+1);
aes128k128d(key, ctr_preload, aes_out);
bitwise_xor(aes_out, &pframe[payload_index], chain_buffer);
for (j = 0; j < 16; j++)
pframe[payload_index++] = chain_buffer[j];
}
if (payload_remainder > 0) {
/* If there is a short final block, then pad it,
* encrypt it and copy the unpadded part back
*/
construct_ctr_preload(ctr_preload, a4_exists, qc_exists, pframe,
pn_vector, num_blocks+1);
for (j = 0; j < 16; j++)
padded_buffer[j] = 0x00;
for (j = 0; j < payload_remainder; j++)
padded_buffer[j] = pframe[payload_index+j];
aes128k128d(key, ctr_preload, aes_out);
bitwise_xor(aes_out, padded_buffer, chain_buffer);
for (j = 0; j < payload_remainder;j++)
pframe[payload_index++] = chain_buffer[j];
}
/* Encrypt the MIC */
construct_ctr_preload(ctr_preload, a4_exists, qc_exists, pframe,
pn_vector, 0);
for (j = 0; j < 16; j++)
padded_buffer[j] = 0x00;
for (j = 0; j < 8; j++)
padded_buffer[j] = pframe[j+hdrlen+8+plen];
aes128k128d(key, ctr_preload, aes_out);
bitwise_xor(aes_out, padded_buffer, chain_buffer);
for (j = 0; j < 8;j++)
pframe[payload_index++] = chain_buffer[j];
return _SUCCESS;
}
int rtw_aes_encrypt23a(struct rtw_adapter *padapter,
struct xmit_frame *pxmitframe)
{ /* exclude ICV */
/* Intermediate Buffers */
int curfragnum, length;
u32 prwskeylen;
u8 *pframe, *prwskey; /* *payload,*iv */
u8 hw_hdr_offset = 0;
struct sta_info *stainfo;
struct pkt_attrib *pattrib = &pxmitframe->attrib;
struct security_priv *psecuritypriv = &padapter->securitypriv;
struct xmit_priv *pxmitpriv = &padapter->xmitpriv;
int res = _SUCCESS;
if (!pxmitframe->buf_addr)
return _FAIL;
hw_hdr_offset = TXDESC_OFFSET;
pframe = pxmitframe->buf_addr + hw_hdr_offset;
/* 4 start to encrypt each fragment */
if (pattrib->encrypt != WLAN_CIPHER_SUITE_CCMP)
return _FAIL;
if (pattrib->psta) {
stainfo = pattrib->psta;
} else {
DBG_8723A("%s, call rtw_get_stainfo23a()\n", __func__);
stainfo = rtw_get_stainfo23a(&padapter->stapriv, &pattrib->ra[0]);
}
if (!stainfo) {
RT_TRACE(_module_rtl871x_security_c_, _drv_err_,
("rtw_aes_encrypt23a: stainfo == NULL!!!\n"));
DBG_8723A("%s, psta == NUL\n", __func__);
res = _FAIL;
goto out;
}
if (!(stainfo->state &_FW_LINKED)) {
DBG_8723A("%s, psta->state(0x%x) != _FW_LINKED\n",
__func__, stainfo->state);
return _FAIL;
}
RT_TRACE(_module_rtl871x_security_c_, _drv_err_,
("rtw_aes_encrypt23a: stainfo!= NULL!!!\n"));
if (is_multicast_ether_addr(pattrib->ra))
prwskey = psecuritypriv->dot118021XGrpKey[psecuritypriv->dot118021XGrpKeyid].skey;
else
prwskey = &stainfo->dot118021x_UncstKey.skey[0];
prwskeylen = 16;
for (curfragnum = 0; curfragnum < pattrib->nr_frags; curfragnum++) {
/* 4 the last fragment */
if ((curfragnum + 1) == pattrib->nr_frags) {
length = pattrib->last_txcmdsz -
pattrib->hdrlen-pattrib->iv_len -
pattrib->icv_len;
aes_cipher(prwskey, pattrib->hdrlen, pframe, length);
} else {
length = pxmitpriv->frag_len-pattrib->hdrlen -
pattrib->iv_len - pattrib->icv_len;
aes_cipher(prwskey, pattrib->hdrlen, pframe, length);
pframe += pxmitpriv->frag_len;
pframe = PTR_ALIGN(pframe, 4);
}
}
out:
return res;
}
static int aes_decipher(u8 *key, uint hdrlen,
u8 *pframe, uint plen)
{
static u8 message[MAX_MSG_SIZE];
uint qc_exists, a4_exists, i, j, payload_remainder,
num_blocks, payload_index;
int res = _SUCCESS;
u8 pn_vector[6];
u8 mic_iv[16];
u8 mic_header1[16];
u8 mic_header2[16];
u8 ctr_preload[16];
/* Intermediate Buffers */
u8 chain_buffer[16];
u8 aes_out[16];
u8 padded_buffer[16];
u8 mic[8];
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)pframe;
u16 frsubtype = le16_to_cpu(hdr->frame_control) & IEEE80211_FCTL_STYPE;
memset((void *)mic_iv, 0, 16);
memset((void *)mic_header1, 0, 16);
memset((void *)mic_header2, 0, 16);
memset((void *)ctr_preload, 0, 16);
memset((void *)chain_buffer, 0, 16);
memset((void *)aes_out, 0, 16);
memset((void *)padded_buffer, 0, 16);
/* start to decrypt the payload */
num_blocks = (plen-8) / 16; /* plen including llc, payload_length and mic) */
payload_remainder = (plen-8) % 16;
pn_vector[0] = pframe[hdrlen];
pn_vector[1] = pframe[hdrlen+1];
pn_vector[2] = pframe[hdrlen+4];
pn_vector[3] = pframe[hdrlen+5];
pn_vector[4] = pframe[hdrlen+6];
pn_vector[5] = pframe[hdrlen+7];
if ((hdrlen == sizeof(struct ieee80211_hdr_3addr) ||
(hdrlen == sizeof(struct ieee80211_qos_hdr))))
a4_exists = 0;
else
a4_exists = 1;
if (ieee80211_is_data(hdr->frame_control)) {
if ((frsubtype == IEEE80211_STYPE_DATA_CFACK) ||
(frsubtype == IEEE80211_STYPE_DATA_CFPOLL) ||
(frsubtype == IEEE80211_STYPE_DATA_CFACKPOLL)) {
qc_exists = 1;
if (hdrlen != sizeof(struct ieee80211_hdr_3addr))
hdrlen += 2;
} else if ((frsubtype == IEEE80211_STYPE_QOS_DATA) ||
(frsubtype == IEEE80211_STYPE_QOS_DATA_CFACK) ||
(frsubtype == IEEE80211_STYPE_QOS_DATA_CFPOLL) ||
(frsubtype == IEEE80211_STYPE_QOS_DATA_CFACKPOLL)) {
if (hdrlen != sizeof(struct ieee80211_hdr_3addr))
hdrlen += 2;
qc_exists = 1;
} else {
qc_exists = 0;
}
} else {
qc_exists = 0;
}
/* now, decrypt pframe with hdrlen offset and plen long */
payload_index = hdrlen + 8; /* 8 is for extiv */
for (i = 0; i < num_blocks; i++) {
construct_ctr_preload(ctr_preload, a4_exists, qc_exists,
pframe, pn_vector, i+1);
aes128k128d(key, ctr_preload, aes_out);
bitwise_xor(aes_out, &pframe[payload_index], chain_buffer);
for (j = 0; j < 16; j++)
pframe[payload_index++] = chain_buffer[j];
}
if (payload_remainder > 0) {
/* If there is a short final block, then pad it,
* encrypt it and copy the unpadded part back
*/
construct_ctr_preload(ctr_preload, a4_exists, qc_exists, pframe,
pn_vector, num_blocks+1);
for (j = 0; j < 16; j++)
padded_buffer[j] = 0x00;
for (j = 0; j < payload_remainder; j++)
padded_buffer[j] = pframe[payload_index+j];
aes128k128d(key, ctr_preload, aes_out);
bitwise_xor(aes_out, padded_buffer, chain_buffer);
for (j = 0; j < payload_remainder; j++)
pframe[payload_index++] = chain_buffer[j];
}
/* start to calculate the mic */
if ((hdrlen +plen+8) <= MAX_MSG_SIZE)
memcpy(message, pframe, (hdrlen+plen+8)); /* 8 is for ext iv len */
pn_vector[0] = pframe[hdrlen];
pn_vector[1] = pframe[hdrlen+1];
pn_vector[2] = pframe[hdrlen+4];
pn_vector[3] = pframe[hdrlen+5];
pn_vector[4] = pframe[hdrlen+6];
pn_vector[5] = pframe[hdrlen+7];
construct_mic_iv(mic_iv, qc_exists, a4_exists, message,
plen-8, pn_vector);
construct_mic_header1(mic_header1, hdrlen, message);
construct_mic_header2(mic_header2, message, a4_exists, qc_exists);
payload_remainder = (plen-8) % 16;
num_blocks = (plen-8) / 16;
/* Find start of payload */
payload_index = (hdrlen + 8);
/* Calculate MIC */
aes128k128d(key, mic_iv, aes_out);
bitwise_xor(aes_out, mic_header1, chain_buffer);
aes128k128d(key, chain_buffer, aes_out);
bitwise_xor(aes_out, mic_header2, chain_buffer);
aes128k128d(key, chain_buffer, aes_out);
for (i = 0; i < num_blocks; i++) {
bitwise_xor(aes_out, &message[payload_index], chain_buffer);
payload_index += 16;
aes128k128d(key, chain_buffer, aes_out);
}
/* Add on the final payload block if it needs padding */
if (payload_remainder > 0) {
for (j = 0; j < 16; j++)
padded_buffer[j] = 0x00;
for (j = 0; j < payload_remainder; j++)
padded_buffer[j] = message[payload_index++];
bitwise_xor(aes_out, padded_buffer, chain_buffer);
aes128k128d(key, chain_buffer, aes_out);
}
for (j = 0 ; j < 8; j++)
mic[j] = aes_out[j];
/* Insert MIC into payload */
for (j = 0; j < 8; j++)
message[payload_index+j] = mic[j];
payload_index = hdrlen + 8;
for (i = 0; i< num_blocks; i++) {
construct_ctr_preload(ctr_preload, a4_exists, qc_exists,
message, pn_vector, i+1);
aes128k128d(key, ctr_preload, aes_out);
bitwise_xor(aes_out, &message[payload_index], chain_buffer);
for (j = 0; j < 16; j++)
message[payload_index++] = chain_buffer[j];
}
if (payload_remainder > 0) {
/* If there is a short final block, then pad it,
* encrypt it and copy the unpadded part back
*/
construct_ctr_preload(ctr_preload, a4_exists, qc_exists,
message, pn_vector, num_blocks+1);
for (j = 0; j < 16; j++)
padded_buffer[j] = 0x00;
for (j = 0; j < payload_remainder; j++)
padded_buffer[j] = message[payload_index+j];
aes128k128d(key, ctr_preload, aes_out);
bitwise_xor(aes_out, padded_buffer, chain_buffer);
for (j = 0; j < payload_remainder; j++)
message[payload_index++] = chain_buffer[j];
}
/* Encrypt the MIC */
construct_ctr_preload(ctr_preload, a4_exists, qc_exists, message,
pn_vector, 0);
for (j = 0; j < 16; j++)
padded_buffer[j] = 0x00;
for (j = 0; j < 8; j++)
padded_buffer[j] = message[j+hdrlen+8+plen-8];
aes128k128d(key, ctr_preload, aes_out);
bitwise_xor(aes_out, padded_buffer, chain_buffer);
for (j = 0; j < 8; j++)
message[payload_index++] = chain_buffer[j];
/* compare the mic */
for (i = 0; i < 8; i++) {
if (pframe[hdrlen+8+plen-8+i] != message[hdrlen+8+plen-8+i]) {
RT_TRACE(_module_rtl871x_security_c_, _drv_err_,
("aes_decipher:mic check error mic[%d]: pframe(%x) != message(%x)\n",
i, pframe[hdrlen+8+plen-8+i], message[hdrlen+8+plen-8+i]));
DBG_8723A("aes_decipher:mic check error mic[%d]: pframe(%x) != message(%x)\n",
i, pframe[hdrlen+8+plen-8+i], message[hdrlen+8+plen-8+i]);
res = _FAIL;
}
}
return res;
}
int rtw_aes_decrypt23a(struct rtw_adapter *padapter,
struct recv_frame *precvframe)
{ /* exclude ICV */
struct sta_info *stainfo;
struct rx_pkt_attrib *prxattrib = &precvframe->attrib;
struct security_priv *psecuritypriv = &padapter->securitypriv;
struct sk_buff *skb = precvframe->pkt;
int length;
u8 *pframe, *prwskey; /* *payload,*iv */
int res = _SUCCESS;
pframe = skb->data;
/* 4 start to encrypt each fragment */
if (prxattrib->encrypt != WLAN_CIPHER_SUITE_CCMP)
return _FAIL;
stainfo = rtw_get_stainfo23a(&padapter->stapriv, &prxattrib->ta[0]);
if (!stainfo) {
RT_TRACE(_module_rtl871x_security_c_, _drv_err_,
("rtw_aes_encrypt23a: stainfo == NULL!!!\n"));
res = _FAIL;
goto exit;
}
RT_TRACE(_module_rtl871x_security_c_, _drv_err_,
("rtw_aes_decrypt23a: stainfo!= NULL!!!\n"));
if (is_multicast_ether_addr(prxattrib->ra)) {
/* in concurrent we should use sw decrypt in group key,
so we remove this message */
if (!psecuritypriv->binstallGrpkey) {
res = _FAIL;
DBG_8723A("%s:rx bc/mc packets, but didn't install "
"group key!!!!!!!!!!\n", __func__);
goto exit;
}
prwskey = psecuritypriv->dot118021XGrpKey[prxattrib->key_index].skey;
if (psecuritypriv->dot118021XGrpKeyid != prxattrib->key_index) {
DBG_8723A("not match packet_index =%d, install_index ="
"%d\n", prxattrib->key_index,
psecuritypriv->dot118021XGrpKeyid);
res = _FAIL;
goto exit;
}
} else {
prwskey = &stainfo->dot118021x_UncstKey.skey[0];
}
length = skb->len - prxattrib->hdrlen - prxattrib->iv_len;
res = aes_decipher(prwskey, prxattrib->hdrlen, pframe, length);
exit:
return res;
}
void rtw_use_tkipkey_handler23a(void *FunctionContext)
{
struct rtw_adapter *padapter = (struct rtw_adapter *)FunctionContext;
RT_TRACE(_module_rtl871x_security_c_, _drv_err_, ("^^^rtw_use_tkipkey_handler23a ^^^\n"));
padapter->securitypriv.busetkipkey = 1;
RT_TRACE(_module_rtl871x_security_c_, _drv_err_,
("^^^rtw_use_tkipkey_handler23a padapter->securitypriv.busetkipkey =%d^^^\n",
padapter->securitypriv.busetkipkey));
}
| gpl-2.0 |
ma34s/so03c_kernel | tools/perf/util/symbol.c | 462 | 21795 | #include "util.h"
#include "../perf.h"
#include "string.h"
#include "symbol.h"
#include "debug.h"
#include <libelf.h>
#include <gelf.h>
#include <elf.h>
const char *sym_hist_filter;
enum dso_origin {
DSO__ORIG_KERNEL = 0,
DSO__ORIG_JAVA_JIT,
DSO__ORIG_FEDORA,
DSO__ORIG_UBUNTU,
DSO__ORIG_BUILDID,
DSO__ORIG_DSO,
DSO__ORIG_NOT_FOUND,
};
static struct symbol *symbol__new(u64 start, u64 len,
const char *name, unsigned int priv_size,
u64 obj_start, int v)
{
size_t namelen = strlen(name) + 1;
struct symbol *self = calloc(1, priv_size + sizeof(*self) + namelen);
if (!self)
return NULL;
if (v >= 2)
printf("new symbol: %016Lx [%08lx]: %s, hist: %p, obj_start: %p\n",
(u64)start, (unsigned long)len, name, self->hist, (void *)(unsigned long)obj_start);
self->obj_start= obj_start;
self->hist = NULL;
self->hist_sum = 0;
if (sym_hist_filter && !strcmp(name, sym_hist_filter))
self->hist = calloc(sizeof(u64), len);
if (priv_size) {
memset(self, 0, priv_size);
self = ((void *)self) + priv_size;
}
self->start = start;
self->end = len ? start + len - 1 : start;
memcpy(self->name, name, namelen);
return self;
}
static void symbol__delete(struct symbol *self, unsigned int priv_size)
{
free(((void *)self) - priv_size);
}
static size_t symbol__fprintf(struct symbol *self, FILE *fp)
{
if (!self->module)
return fprintf(fp, " %llx-%llx %s\n",
self->start, self->end, self->name);
else
return fprintf(fp, " %llx-%llx %s \t[%s]\n",
self->start, self->end, self->name, self->module->name);
}
struct dso *dso__new(const char *name, unsigned int sym_priv_size)
{
struct dso *self = malloc(sizeof(*self) + strlen(name) + 1);
if (self != NULL) {
strcpy(self->name, name);
self->syms = RB_ROOT;
self->sym_priv_size = sym_priv_size;
self->find_symbol = dso__find_symbol;
self->slen_calculated = 0;
self->origin = DSO__ORIG_NOT_FOUND;
}
return self;
}
static void dso__delete_symbols(struct dso *self)
{
struct symbol *pos;
struct rb_node *next = rb_first(&self->syms);
while (next) {
pos = rb_entry(next, struct symbol, rb_node);
next = rb_next(&pos->rb_node);
rb_erase(&pos->rb_node, &self->syms);
symbol__delete(pos, self->sym_priv_size);
}
}
void dso__delete(struct dso *self)
{
dso__delete_symbols(self);
free(self);
}
static void dso__insert_symbol(struct dso *self, struct symbol *sym)
{
struct rb_node **p = &self->syms.rb_node;
struct rb_node *parent = NULL;
const u64 ip = sym->start;
struct symbol *s;
while (*p != NULL) {
parent = *p;
s = rb_entry(parent, struct symbol, rb_node);
if (ip < s->start)
p = &(*p)->rb_left;
else
p = &(*p)->rb_right;
}
rb_link_node(&sym->rb_node, parent, p);
rb_insert_color(&sym->rb_node, &self->syms);
}
struct symbol *dso__find_symbol(struct dso *self, u64 ip)
{
struct rb_node *n;
if (self == NULL)
return NULL;
n = self->syms.rb_node;
while (n) {
struct symbol *s = rb_entry(n, struct symbol, rb_node);
if (ip < s->start)
n = n->rb_left;
else if (ip > s->end)
n = n->rb_right;
else
return s;
}
return NULL;
}
size_t dso__fprintf(struct dso *self, FILE *fp)
{
size_t ret = fprintf(fp, "dso: %s\n", self->name);
struct rb_node *nd;
for (nd = rb_first(&self->syms); nd; nd = rb_next(nd)) {
struct symbol *pos = rb_entry(nd, struct symbol, rb_node);
ret += symbol__fprintf(pos, fp);
}
return ret;
}
static int dso__load_kallsyms(struct dso *self, symbol_filter_t filter, int v)
{
struct rb_node *nd, *prevnd;
char *line = NULL;
size_t n;
FILE *file = fopen("/proc/kallsyms", "r");
int count = 0;
if (file == NULL)
goto out_failure;
while (!feof(file)) {
u64 start;
struct symbol *sym;
int line_len, len;
char symbol_type;
line_len = getline(&line, &n, file);
if (line_len < 0)
break;
if (!line)
goto out_failure;
line[--line_len] = '\0'; /* \n */
len = hex2u64(line, &start);
len++;
if (len + 2 >= line_len)
continue;
symbol_type = toupper(line[len]);
/*
* We're interested only in code ('T'ext)
*/
if (symbol_type != 'T' && symbol_type != 'W')
continue;
/*
* Well fix up the end later, when we have all sorted.
*/
sym = symbol__new(start, 0xdead, line + len + 2,
self->sym_priv_size, 0, v);
if (sym == NULL)
goto out_delete_line;
if (filter && filter(self, sym))
symbol__delete(sym, self->sym_priv_size);
else {
dso__insert_symbol(self, sym);
count++;
}
}
/*
* Now that we have all sorted out, just set the ->end of all
* symbols
*/
prevnd = rb_first(&self->syms);
if (prevnd == NULL)
goto out_delete_line;
for (nd = rb_next(prevnd); nd; nd = rb_next(nd)) {
struct symbol *prev = rb_entry(prevnd, struct symbol, rb_node),
*curr = rb_entry(nd, struct symbol, rb_node);
prev->end = curr->start - 1;
prevnd = nd;
}
free(line);
fclose(file);
return count;
out_delete_line:
free(line);
out_failure:
return -1;
}
static int dso__load_perf_map(struct dso *self, symbol_filter_t filter, int v)
{
char *line = NULL;
size_t n;
FILE *file;
int nr_syms = 0;
file = fopen(self->name, "r");
if (file == NULL)
goto out_failure;
while (!feof(file)) {
u64 start, size;
struct symbol *sym;
int line_len, len;
line_len = getline(&line, &n, file);
if (line_len < 0)
break;
if (!line)
goto out_failure;
line[--line_len] = '\0'; /* \n */
len = hex2u64(line, &start);
len++;
if (len + 2 >= line_len)
continue;
len += hex2u64(line + len, &size);
len++;
if (len + 2 >= line_len)
continue;
sym = symbol__new(start, size, line + len,
self->sym_priv_size, start, v);
if (sym == NULL)
goto out_delete_line;
if (filter && filter(self, sym))
symbol__delete(sym, self->sym_priv_size);
else {
dso__insert_symbol(self, sym);
nr_syms++;
}
}
free(line);
fclose(file);
return nr_syms;
out_delete_line:
free(line);
out_failure:
return -1;
}
/**
* elf_symtab__for_each_symbol - iterate thru all the symbols
*
* @self: struct elf_symtab instance to iterate
* @idx: uint32_t idx
* @sym: GElf_Sym iterator
*/
#define elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) \
for (idx = 0, gelf_getsym(syms, idx, &sym);\
idx < nr_syms; \
idx++, gelf_getsym(syms, idx, &sym))
static inline uint8_t elf_sym__type(const GElf_Sym *sym)
{
return GELF_ST_TYPE(sym->st_info);
}
static inline int elf_sym__is_function(const GElf_Sym *sym)
{
return elf_sym__type(sym) == STT_FUNC &&
sym->st_name != 0 &&
sym->st_shndx != SHN_UNDEF;
}
static inline int elf_sym__is_label(const GElf_Sym *sym)
{
return elf_sym__type(sym) == STT_NOTYPE &&
sym->st_name != 0 &&
sym->st_shndx != SHN_UNDEF &&
sym->st_shndx != SHN_ABS;
}
static inline const char *elf_sec__name(const GElf_Shdr *shdr,
const Elf_Data *secstrs)
{
return secstrs->d_buf + shdr->sh_name;
}
static inline int elf_sec__is_text(const GElf_Shdr *shdr,
const Elf_Data *secstrs)
{
return strstr(elf_sec__name(shdr, secstrs), "text") != NULL;
}
static inline const char *elf_sym__name(const GElf_Sym *sym,
const Elf_Data *symstrs)
{
return symstrs->d_buf + sym->st_name;
}
static Elf_Scn *elf_section_by_name(Elf *elf, GElf_Ehdr *ep,
GElf_Shdr *shp, const char *name,
size_t *idx)
{
Elf_Scn *sec = NULL;
size_t cnt = 1;
while ((sec = elf_nextscn(elf, sec)) != NULL) {
char *str;
gelf_getshdr(sec, shp);
str = elf_strptr(elf, ep->e_shstrndx, shp->sh_name);
if (!strcmp(name, str)) {
if (idx)
*idx = cnt;
break;
}
++cnt;
}
return sec;
}
#define elf_section__for_each_rel(reldata, pos, pos_mem, idx, nr_entries) \
for (idx = 0, pos = gelf_getrel(reldata, 0, &pos_mem); \
idx < nr_entries; \
++idx, pos = gelf_getrel(reldata, idx, &pos_mem))
#define elf_section__for_each_rela(reldata, pos, pos_mem, idx, nr_entries) \
for (idx = 0, pos = gelf_getrela(reldata, 0, &pos_mem); \
idx < nr_entries; \
++idx, pos = gelf_getrela(reldata, idx, &pos_mem))
/*
* We need to check if we have a .dynsym, so that we can handle the
* .plt, synthesizing its symbols, that aren't on the symtabs (be it
* .dynsym or .symtab).
* And always look at the original dso, not at debuginfo packages, that
* have the PLT data stripped out (shdr_rel_plt.sh_type == SHT_NOBITS).
*/
static int dso__synthesize_plt_symbols(struct dso *self, int v)
{
uint32_t nr_rel_entries, idx;
GElf_Sym sym;
u64 plt_offset;
GElf_Shdr shdr_plt;
struct symbol *f;
GElf_Shdr shdr_rel_plt, shdr_dynsym;
Elf_Data *reldata, *syms, *symstrs;
Elf_Scn *scn_plt_rel, *scn_symstrs, *scn_dynsym;
size_t dynsym_idx;
GElf_Ehdr ehdr;
char sympltname[1024];
Elf *elf;
int nr = 0, symidx, fd, err = 0;
fd = open(self->name, O_RDONLY);
if (fd < 0)
goto out;
elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
if (elf == NULL)
goto out_close;
if (gelf_getehdr(elf, &ehdr) == NULL)
goto out_elf_end;
scn_dynsym = elf_section_by_name(elf, &ehdr, &shdr_dynsym,
".dynsym", &dynsym_idx);
if (scn_dynsym == NULL)
goto out_elf_end;
scn_plt_rel = elf_section_by_name(elf, &ehdr, &shdr_rel_plt,
".rela.plt", NULL);
if (scn_plt_rel == NULL) {
scn_plt_rel = elf_section_by_name(elf, &ehdr, &shdr_rel_plt,
".rel.plt", NULL);
if (scn_plt_rel == NULL)
goto out_elf_end;
}
err = -1;
if (shdr_rel_plt.sh_link != dynsym_idx)
goto out_elf_end;
if (elf_section_by_name(elf, &ehdr, &shdr_plt, ".plt", NULL) == NULL)
goto out_elf_end;
/*
* Fetch the relocation section to find the idxes to the GOT
* and the symbols in the .dynsym they refer to.
*/
reldata = elf_getdata(scn_plt_rel, NULL);
if (reldata == NULL)
goto out_elf_end;
syms = elf_getdata(scn_dynsym, NULL);
if (syms == NULL)
goto out_elf_end;
scn_symstrs = elf_getscn(elf, shdr_dynsym.sh_link);
if (scn_symstrs == NULL)
goto out_elf_end;
symstrs = elf_getdata(scn_symstrs, NULL);
if (symstrs == NULL)
goto out_elf_end;
nr_rel_entries = shdr_rel_plt.sh_size / shdr_rel_plt.sh_entsize;
plt_offset = shdr_plt.sh_offset;
if (shdr_rel_plt.sh_type == SHT_RELA) {
GElf_Rela pos_mem, *pos;
elf_section__for_each_rela(reldata, pos, pos_mem, idx,
nr_rel_entries) {
symidx = GELF_R_SYM(pos->r_info);
plt_offset += shdr_plt.sh_entsize;
gelf_getsym(syms, symidx, &sym);
snprintf(sympltname, sizeof(sympltname),
"%s@plt", elf_sym__name(&sym, symstrs));
f = symbol__new(plt_offset, shdr_plt.sh_entsize,
sympltname, self->sym_priv_size, 0, v);
if (!f)
goto out_elf_end;
dso__insert_symbol(self, f);
++nr;
}
} else if (shdr_rel_plt.sh_type == SHT_REL) {
GElf_Rel pos_mem, *pos;
elf_section__for_each_rel(reldata, pos, pos_mem, idx,
nr_rel_entries) {
symidx = GELF_R_SYM(pos->r_info);
plt_offset += shdr_plt.sh_entsize;
gelf_getsym(syms, symidx, &sym);
snprintf(sympltname, sizeof(sympltname),
"%s@plt", elf_sym__name(&sym, symstrs));
f = symbol__new(plt_offset, shdr_plt.sh_entsize,
sympltname, self->sym_priv_size, 0, v);
if (!f)
goto out_elf_end;
dso__insert_symbol(self, f);
++nr;
}
}
err = 0;
out_elf_end:
elf_end(elf);
out_close:
close(fd);
if (err == 0)
return nr;
out:
fprintf(stderr, "%s: problems reading %s PLT info.\n",
__func__, self->name);
return 0;
}
static int dso__load_sym(struct dso *self, int fd, const char *name,
symbol_filter_t filter, int v, struct module *mod)
{
Elf_Data *symstrs, *secstrs;
uint32_t nr_syms;
int err = -1;
uint32_t idx;
GElf_Ehdr ehdr;
GElf_Shdr shdr;
Elf_Data *syms;
GElf_Sym sym;
Elf_Scn *sec, *sec_strndx;
Elf *elf;
int nr = 0, kernel = !strcmp("[kernel]", self->name);
elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
if (elf == NULL) {
if (v)
fprintf(stderr, "%s: cannot read %s ELF file.\n",
__func__, name);
goto out_close;
}
if (gelf_getehdr(elf, &ehdr) == NULL) {
if (v)
fprintf(stderr, "%s: cannot get elf header.\n", __func__);
goto out_elf_end;
}
sec = elf_section_by_name(elf, &ehdr, &shdr, ".symtab", NULL);
if (sec == NULL) {
sec = elf_section_by_name(elf, &ehdr, &shdr, ".dynsym", NULL);
if (sec == NULL)
goto out_elf_end;
}
syms = elf_getdata(sec, NULL);
if (syms == NULL)
goto out_elf_end;
sec = elf_getscn(elf, shdr.sh_link);
if (sec == NULL)
goto out_elf_end;
symstrs = elf_getdata(sec, NULL);
if (symstrs == NULL)
goto out_elf_end;
sec_strndx = elf_getscn(elf, ehdr.e_shstrndx);
if (sec_strndx == NULL)
goto out_elf_end;
secstrs = elf_getdata(sec_strndx, NULL);
if (secstrs == NULL)
goto out_elf_end;
nr_syms = shdr.sh_size / shdr.sh_entsize;
memset(&sym, 0, sizeof(sym));
if (!kernel) {
self->adjust_symbols = (ehdr.e_type == ET_EXEC ||
elf_section_by_name(elf, &ehdr, &shdr,
".gnu.prelink_undo",
NULL) != NULL);
} else self->adjust_symbols = 0;
elf_symtab__for_each_symbol(syms, nr_syms, idx, sym) {
struct symbol *f;
const char *elf_name;
char *demangled;
u64 obj_start;
struct section *section = NULL;
int is_label = elf_sym__is_label(&sym);
const char *section_name;
if (!is_label && !elf_sym__is_function(&sym))
continue;
sec = elf_getscn(elf, sym.st_shndx);
if (!sec)
goto out_elf_end;
gelf_getshdr(sec, &shdr);
if (is_label && !elf_sec__is_text(&shdr, secstrs))
continue;
section_name = elf_sec__name(&shdr, secstrs);
obj_start = sym.st_value;
if (self->adjust_symbols) {
if (v >= 2)
printf("adjusting symbol: st_value: %Lx sh_addr: %Lx sh_offset: %Lx\n",
(u64)sym.st_value, (u64)shdr.sh_addr, (u64)shdr.sh_offset);
sym.st_value -= shdr.sh_addr - shdr.sh_offset;
}
if (mod) {
section = mod->sections->find_section(mod->sections, section_name);
if (section)
sym.st_value += section->vma;
else {
fprintf(stderr, "dso__load_sym() module %s lookup of %s failed\n",
mod->name, section_name);
goto out_elf_end;
}
}
/*
* We need to figure out if the object was created from C++ sources
* DWARF DW_compile_unit has this, but we don't always have access
* to it...
*/
elf_name = elf_sym__name(&sym, symstrs);
demangled = bfd_demangle(NULL, elf_name, DMGL_PARAMS | DMGL_ANSI);
if (demangled != NULL)
elf_name = demangled;
f = symbol__new(sym.st_value, sym.st_size, elf_name,
self->sym_priv_size, obj_start, v);
free(demangled);
if (!f)
goto out_elf_end;
if (filter && filter(self, f))
symbol__delete(f, self->sym_priv_size);
else {
f->module = mod;
dso__insert_symbol(self, f);
nr++;
}
}
err = nr;
out_elf_end:
elf_end(elf);
out_close:
return err;
}
#define BUILD_ID_SIZE 128
static char *dso__read_build_id(struct dso *self, int v)
{
int i;
GElf_Ehdr ehdr;
GElf_Shdr shdr;
Elf_Data *build_id_data;
Elf_Scn *sec;
char *build_id = NULL, *bid;
unsigned char *raw;
Elf *elf;
int fd = open(self->name, O_RDONLY);
if (fd < 0)
goto out;
elf = elf_begin(fd, PERF_ELF_C_READ_MMAP, NULL);
if (elf == NULL) {
if (v)
fprintf(stderr, "%s: cannot read %s ELF file.\n",
__func__, self->name);
goto out_close;
}
if (gelf_getehdr(elf, &ehdr) == NULL) {
if (v)
fprintf(stderr, "%s: cannot get elf header.\n", __func__);
goto out_elf_end;
}
sec = elf_section_by_name(elf, &ehdr, &shdr, ".note.gnu.build-id", NULL);
if (sec == NULL)
goto out_elf_end;
build_id_data = elf_getdata(sec, NULL);
if (build_id_data == NULL)
goto out_elf_end;
build_id = malloc(BUILD_ID_SIZE);
if (build_id == NULL)
goto out_elf_end;
raw = build_id_data->d_buf + 16;
bid = build_id;
for (i = 0; i < 20; ++i) {
sprintf(bid, "%02x", *raw);
++raw;
bid += 2;
}
if (v >= 2)
printf("%s(%s): %s\n", __func__, self->name, build_id);
out_elf_end:
elf_end(elf);
out_close:
close(fd);
out:
return build_id;
}
char dso__symtab_origin(const struct dso *self)
{
static const char origin[] = {
[DSO__ORIG_KERNEL] = 'k',
[DSO__ORIG_JAVA_JIT] = 'j',
[DSO__ORIG_FEDORA] = 'f',
[DSO__ORIG_UBUNTU] = 'u',
[DSO__ORIG_BUILDID] = 'b',
[DSO__ORIG_DSO] = 'd',
};
if (self == NULL || self->origin == DSO__ORIG_NOT_FOUND)
return '!';
return origin[self->origin];
}
int dso__load(struct dso *self, symbol_filter_t filter, int v)
{
int size = PATH_MAX;
char *name = malloc(size), *build_id = NULL;
int ret = -1;
int fd;
if (!name)
return -1;
self->adjust_symbols = 0;
if (strncmp(self->name, "/tmp/perf-", 10) == 0) {
ret = dso__load_perf_map(self, filter, v);
self->origin = ret > 0 ? DSO__ORIG_JAVA_JIT :
DSO__ORIG_NOT_FOUND;
return ret;
}
self->origin = DSO__ORIG_FEDORA - 1;
more:
do {
self->origin++;
switch (self->origin) {
case DSO__ORIG_FEDORA:
snprintf(name, size, "/usr/lib/debug%s.debug", self->name);
break;
case DSO__ORIG_UBUNTU:
snprintf(name, size, "/usr/lib/debug%s", self->name);
break;
case DSO__ORIG_BUILDID:
build_id = dso__read_build_id(self, v);
if (build_id != NULL) {
snprintf(name, size,
"/usr/lib/debug/.build-id/%.2s/%s.debug",
build_id, build_id + 2);
free(build_id);
break;
}
self->origin++;
/* Fall thru */
case DSO__ORIG_DSO:
snprintf(name, size, "%s", self->name);
break;
default:
goto out;
}
fd = open(name, O_RDONLY);
} while (fd < 0);
ret = dso__load_sym(self, fd, name, filter, v, NULL);
close(fd);
/*
* Some people seem to have debuginfo files _WITHOUT_ debug info!?!?
*/
if (!ret)
goto more;
if (ret > 0) {
int nr_plt = dso__synthesize_plt_symbols(self, v);
if (nr_plt > 0)
ret += nr_plt;
}
out:
free(name);
if (ret < 0 && strstr(self->name, " (deleted)") != NULL)
return 0;
return ret;
}
static int dso__load_module(struct dso *self, struct mod_dso *mods, const char *name,
symbol_filter_t filter, int v)
{
struct module *mod = mod_dso__find_module(mods, name);
int err = 0, fd;
if (mod == NULL || !mod->active)
return err;
fd = open(mod->path, O_RDONLY);
if (fd < 0)
return err;
err = dso__load_sym(self, fd, name, filter, v, mod);
close(fd);
return err;
}
int dso__load_modules(struct dso *self, symbol_filter_t filter, int v)
{
struct mod_dso *mods = mod_dso__new_dso("modules");
struct module *pos;
struct rb_node *next;
int err, count = 0;
err = mod_dso__load_modules(mods);
if (err <= 0)
return err;
/*
* Iterate over modules, and load active symbols.
*/
next = rb_first(&mods->mods);
while (next) {
pos = rb_entry(next, struct module, rb_node);
err = dso__load_module(self, mods, pos->name, filter, v);
if (err < 0)
break;
next = rb_next(&pos->rb_node);
count += err;
}
if (err < 0) {
mod_dso__delete_modules(mods);
mod_dso__delete_self(mods);
return err;
}
return count;
}
static inline void dso__fill_symbol_holes(struct dso *self)
{
struct symbol *prev = NULL;
struct rb_node *nd;
for (nd = rb_last(&self->syms); nd; nd = rb_prev(nd)) {
struct symbol *pos = rb_entry(nd, struct symbol, rb_node);
if (prev) {
u64 hole = 0;
int alias = pos->start == prev->start;
if (!alias)
hole = prev->start - pos->end - 1;
if (hole || alias) {
if (alias)
pos->end = prev->end;
else if (hole)
pos->end = prev->start - 1;
}
}
prev = pos;
}
}
static int dso__load_vmlinux(struct dso *self, const char *vmlinux,
symbol_filter_t filter, int v)
{
int err, fd = open(vmlinux, O_RDONLY);
if (fd < 0)
return -1;
err = dso__load_sym(self, fd, vmlinux, filter, v, NULL);
if (err > 0)
dso__fill_symbol_holes(self);
close(fd);
return err;
}
int dso__load_kernel(struct dso *self, const char *vmlinux,
symbol_filter_t filter, int v, int use_modules)
{
int err = -1;
if (vmlinux) {
err = dso__load_vmlinux(self, vmlinux, filter, v);
if (err > 0 && use_modules) {
int syms = dso__load_modules(self, filter, v);
if (syms < 0) {
fprintf(stderr, "dso__load_modules failed!\n");
return syms;
}
err += syms;
}
}
if (err <= 0)
err = dso__load_kallsyms(self, filter, v);
if (err > 0)
self->origin = DSO__ORIG_KERNEL;
return err;
}
LIST_HEAD(dsos);
struct dso *kernel_dso;
struct dso *vdso;
struct dso *hypervisor_dso;
const char *vmlinux_name = "vmlinux";
int modules;
static void dsos__add(struct dso *dso)
{
list_add_tail(&dso->node, &dsos);
}
static struct dso *dsos__find(const char *name)
{
struct dso *pos;
list_for_each_entry(pos, &dsos, node)
if (strcmp(pos->name, name) == 0)
return pos;
return NULL;
}
struct dso *dsos__findnew(const char *name)
{
struct dso *dso = dsos__find(name);
int nr;
if (dso)
return dso;
dso = dso__new(name, 0);
if (!dso)
goto out_delete_dso;
nr = dso__load(dso, NULL, verbose);
if (nr < 0) {
eprintf("Failed to open: %s\n", name);
goto out_delete_dso;
}
if (!nr)
eprintf("No symbols found in: %s, maybe install a debug package?\n", name);
dsos__add(dso);
return dso;
out_delete_dso:
dso__delete(dso);
return NULL;
}
void dsos__fprintf(FILE *fp)
{
struct dso *pos;
list_for_each_entry(pos, &dsos, node)
dso__fprintf(pos, fp);
}
static struct symbol *vdso__find_symbol(struct dso *dso, u64 ip)
{
return dso__find_symbol(dso, ip);
}
int load_kernel(void)
{
int err;
kernel_dso = dso__new("[kernel]", 0);
if (!kernel_dso)
return -1;
err = dso__load_kernel(kernel_dso, vmlinux_name, NULL, verbose, modules);
if (err <= 0) {
dso__delete(kernel_dso);
kernel_dso = NULL;
} else
dsos__add(kernel_dso);
vdso = dso__new("[vdso]", 0);
if (!vdso)
return -1;
vdso->find_symbol = vdso__find_symbol;
dsos__add(vdso);
hypervisor_dso = dso__new("[hypervisor]", 0);
if (!hypervisor_dso)
return -1;
dsos__add(hypervisor_dso);
return err;
}
void symbol__init(void)
{
elf_version(EV_CURRENT);
}
| gpl-2.0 |
heicrd/android_kernel_motorola_omap4-common | net/ipv4/inetpeer.c | 462 | 19985 | /*
* INETPEER - A storage for permanent information about peers
*
* This source is covered by the GNU GPL, the same as all kernel sources.
*
* Authors: Andrey V. Savochkin <saw@msu.ru>
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/random.h>
#include <linux/timer.h>
#include <linux/time.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/net.h>
#include <net/ip.h>
#include <net/inetpeer.h>
#include <net/secure_seq.h>
/*
* Theory of operations.
* We keep one entry for each peer IP address. The nodes contains long-living
* information about the peer which doesn't depend on routes.
* At this moment this information consists only of ID field for the next
* outgoing IP packet. This field is incremented with each packet as encoded
* in inet_getid() function (include/net/inetpeer.h).
* At the moment of writing this notes identifier of IP packets is generated
* to be unpredictable using this code only for packets subjected
* (actually or potentially) to defragmentation. I.e. DF packets less than
* PMTU in size when local fragmentation is disabled use a constant ID and do
* not use this code (see ip_select_ident() in include/net/ip.h).
*
* Route cache entries hold references to our nodes.
* New cache entries get references via lookup by destination IP address in
* the avl tree. The reference is grabbed only when it's needed i.e. only
* when we try to output IP packet which needs an unpredictable ID (see
* __ip_select_ident() in net/ipv4/route.c).
* Nodes are removed only when reference counter goes to 0.
* When it's happened the node may be removed when a sufficient amount of
* time has been passed since its last use. The less-recently-used entry can
* also be removed if the pool is overloaded i.e. if the total amount of
* entries is greater-or-equal than the threshold.
*
* Node pool is organised as an AVL tree.
* Such an implementation has been chosen not just for fun. It's a way to
* prevent easy and efficient DoS attacks by creating hash collisions. A huge
* amount of long living nodes in a single hash slot would significantly delay
* lookups performed with disabled BHs.
*
* Serialisation issues.
* 1. Nodes may appear in the tree only with the pool lock held.
* 2. Nodes may disappear from the tree only with the pool lock held
* AND reference count being 0.
* 3. Nodes appears and disappears from unused node list only under
* "inet_peer_unused_lock".
* 4. Global variable peer_total is modified under the pool lock.
* 5. struct inet_peer fields modification:
* avl_left, avl_right, avl_parent, avl_height: pool lock
* unused: unused node list lock
* refcnt: atomically against modifications on other CPU;
* usually under some other lock to prevent node disappearing
* dtime: unused node list lock
* daddr: unchangeable
* ip_id_count: atomic value (no lock needed)
*/
static struct kmem_cache *peer_cachep __read_mostly;
#define node_height(x) x->avl_height
#define peer_avl_empty ((struct inet_peer *)&peer_fake_node)
#define peer_avl_empty_rcu ((struct inet_peer __rcu __force *)&peer_fake_node)
static const struct inet_peer peer_fake_node = {
.avl_left = peer_avl_empty_rcu,
.avl_right = peer_avl_empty_rcu,
.avl_height = 0
};
struct inet_peer_base {
struct inet_peer __rcu *root;
seqlock_t lock;
int total;
};
static struct inet_peer_base v4_peers = {
.root = peer_avl_empty_rcu,
.lock = __SEQLOCK_UNLOCKED(v4_peers.lock),
.total = 0,
};
static struct inet_peer_base v6_peers = {
.root = peer_avl_empty_rcu,
.lock = __SEQLOCK_UNLOCKED(v6_peers.lock),
.total = 0,
};
#define PEER_MAXDEPTH 40 /* sufficient for about 2^27 nodes */
/* Exported for sysctl_net_ipv4. */
int inet_peer_threshold __read_mostly = 65536 + 128; /* start to throw entries more
* aggressively at this stage */
int inet_peer_minttl __read_mostly = 120 * HZ; /* TTL under high load: 120 sec */
int inet_peer_maxttl __read_mostly = 10 * 60 * HZ; /* usual time to live: 10 min */
int inet_peer_gc_mintime __read_mostly = 10 * HZ;
int inet_peer_gc_maxtime __read_mostly = 120 * HZ;
static struct {
struct list_head list;
spinlock_t lock;
} unused_peers = {
.list = LIST_HEAD_INIT(unused_peers.list),
.lock = __SPIN_LOCK_UNLOCKED(unused_peers.lock),
};
static void peer_check_expire(unsigned long dummy);
static DEFINE_TIMER(peer_periodic_timer, peer_check_expire, 0, 0);
/* Called from ip_output.c:ip_init */
void __init inet_initpeers(void)
{
struct sysinfo si;
/* Use the straight interface to information about memory. */
si_meminfo(&si);
/* The values below were suggested by Alexey Kuznetsov
* <kuznet@ms2.inr.ac.ru>. I don't have any opinion about the values
* myself. --SAW
*/
if (si.totalram <= (32768*1024)/PAGE_SIZE)
inet_peer_threshold >>= 1; /* max pool size about 1MB on IA32 */
if (si.totalram <= (16384*1024)/PAGE_SIZE)
inet_peer_threshold >>= 1; /* about 512KB */
if (si.totalram <= (8192*1024)/PAGE_SIZE)
inet_peer_threshold >>= 2; /* about 128KB */
peer_cachep = kmem_cache_create("inet_peer_cache",
sizeof(struct inet_peer),
0, SLAB_HWCACHE_ALIGN | SLAB_PANIC,
NULL);
/* All the timers, started at system startup tend
to synchronize. Perturb it a bit.
*/
peer_periodic_timer.expires = jiffies
+ net_random() % inet_peer_gc_maxtime
+ inet_peer_gc_maxtime;
add_timer(&peer_periodic_timer);
}
/* Called with or without local BH being disabled. */
static void unlink_from_unused(struct inet_peer *p)
{
spin_lock_bh(&unused_peers.lock);
list_del_init(&p->unused);
spin_unlock_bh(&unused_peers.lock);
}
static int addr_compare(const struct inetpeer_addr *a,
const struct inetpeer_addr *b)
{
int i, n = (a->family == AF_INET ? 1 : 4);
for (i = 0; i < n; i++) {
if (a->addr.a6[i] == b->addr.a6[i])
continue;
if (a->addr.a6[i] < b->addr.a6[i])
return -1;
return 1;
}
return 0;
}
#define rcu_deref_locked(X, BASE) \
rcu_dereference_protected(X, lockdep_is_held(&(BASE)->lock.lock))
/*
* Called with local BH disabled and the pool lock held.
*/
#define lookup(_daddr, _stack, _base) \
({ \
struct inet_peer *u; \
struct inet_peer __rcu **v; \
\
stackptr = _stack; \
*stackptr++ = &_base->root; \
for (u = rcu_deref_locked(_base->root, _base); \
u != peer_avl_empty; ) { \
int cmp = addr_compare(_daddr, &u->daddr); \
if (cmp == 0) \
break; \
if (cmp == -1) \
v = &u->avl_left; \
else \
v = &u->avl_right; \
*stackptr++ = v; \
u = rcu_deref_locked(*v, _base); \
} \
u; \
})
static bool atomic_add_unless_return(atomic_t *ptr, int a, int u, int *newv)
{
int cur, old = atomic_read(ptr);
while (old != u) {
*newv = old + a;
cur = atomic_cmpxchg(ptr, old, *newv);
if (cur == old)
return true;
old = cur;
}
return false;
}
/*
* Called with rcu_read_lock()
* Because we hold no lock against a writer, its quite possible we fall
* in an endless loop.
* But every pointer we follow is guaranteed to be valid thanks to RCU.
* We exit from this function if number of links exceeds PEER_MAXDEPTH
*/
static struct inet_peer *lookup_rcu(const struct inetpeer_addr *daddr,
struct inet_peer_base *base,
int *newrefcnt)
{
struct inet_peer *u = rcu_dereference(base->root);
int count = 0;
while (u != peer_avl_empty) {
int cmp = addr_compare(daddr, &u->daddr);
if (cmp == 0) {
/* Before taking a reference, check if this entry was
* deleted, unlink_from_pool() sets refcnt=-1 to make
* distinction between an unused entry (refcnt=0) and
* a freed one.
*/
if (!atomic_add_unless_return(&u->refcnt, 1, -1, newrefcnt))
u = NULL;
return u;
}
if (cmp == -1)
u = rcu_dereference(u->avl_left);
else
u = rcu_dereference(u->avl_right);
if (unlikely(++count == PEER_MAXDEPTH))
break;
}
return NULL;
}
/* Called with local BH disabled and the pool lock held. */
#define lookup_rightempty(start, base) \
({ \
struct inet_peer *u; \
struct inet_peer __rcu **v; \
*stackptr++ = &start->avl_left; \
v = &start->avl_left; \
for (u = rcu_deref_locked(*v, base); \
u->avl_right != peer_avl_empty_rcu; ) { \
v = &u->avl_right; \
*stackptr++ = v; \
u = rcu_deref_locked(*v, base); \
} \
u; \
})
/* Called with local BH disabled and the pool lock held.
* Variable names are the proof of operation correctness.
* Look into mm/map_avl.c for more detail description of the ideas.
*/
static void peer_avl_rebalance(struct inet_peer __rcu **stack[],
struct inet_peer __rcu ***stackend,
struct inet_peer_base *base)
{
struct inet_peer __rcu **nodep;
struct inet_peer *node, *l, *r;
int lh, rh;
while (stackend > stack) {
nodep = *--stackend;
node = rcu_deref_locked(*nodep, base);
l = rcu_deref_locked(node->avl_left, base);
r = rcu_deref_locked(node->avl_right, base);
lh = node_height(l);
rh = node_height(r);
if (lh > rh + 1) { /* l: RH+2 */
struct inet_peer *ll, *lr, *lrl, *lrr;
int lrh;
ll = rcu_deref_locked(l->avl_left, base);
lr = rcu_deref_locked(l->avl_right, base);
lrh = node_height(lr);
if (lrh <= node_height(ll)) { /* ll: RH+1 */
RCU_INIT_POINTER(node->avl_left, lr); /* lr: RH or RH+1 */
RCU_INIT_POINTER(node->avl_right, r); /* r: RH */
node->avl_height = lrh + 1; /* RH+1 or RH+2 */
RCU_INIT_POINTER(l->avl_left, ll); /* ll: RH+1 */
RCU_INIT_POINTER(l->avl_right, node); /* node: RH+1 or RH+2 */
l->avl_height = node->avl_height + 1;
RCU_INIT_POINTER(*nodep, l);
} else { /* ll: RH, lr: RH+1 */
lrl = rcu_deref_locked(lr->avl_left, base);/* lrl: RH or RH-1 */
lrr = rcu_deref_locked(lr->avl_right, base);/* lrr: RH or RH-1 */
RCU_INIT_POINTER(node->avl_left, lrr); /* lrr: RH or RH-1 */
RCU_INIT_POINTER(node->avl_right, r); /* r: RH */
node->avl_height = rh + 1; /* node: RH+1 */
RCU_INIT_POINTER(l->avl_left, ll); /* ll: RH */
RCU_INIT_POINTER(l->avl_right, lrl); /* lrl: RH or RH-1 */
l->avl_height = rh + 1; /* l: RH+1 */
RCU_INIT_POINTER(lr->avl_left, l); /* l: RH+1 */
RCU_INIT_POINTER(lr->avl_right, node); /* node: RH+1 */
lr->avl_height = rh + 2;
RCU_INIT_POINTER(*nodep, lr);
}
} else if (rh > lh + 1) { /* r: LH+2 */
struct inet_peer *rr, *rl, *rlr, *rll;
int rlh;
rr = rcu_deref_locked(r->avl_right, base);
rl = rcu_deref_locked(r->avl_left, base);
rlh = node_height(rl);
if (rlh <= node_height(rr)) { /* rr: LH+1 */
RCU_INIT_POINTER(node->avl_right, rl); /* rl: LH or LH+1 */
RCU_INIT_POINTER(node->avl_left, l); /* l: LH */
node->avl_height = rlh + 1; /* LH+1 or LH+2 */
RCU_INIT_POINTER(r->avl_right, rr); /* rr: LH+1 */
RCU_INIT_POINTER(r->avl_left, node); /* node: LH+1 or LH+2 */
r->avl_height = node->avl_height + 1;
RCU_INIT_POINTER(*nodep, r);
} else { /* rr: RH, rl: RH+1 */
rlr = rcu_deref_locked(rl->avl_right, base);/* rlr: LH or LH-1 */
rll = rcu_deref_locked(rl->avl_left, base);/* rll: LH or LH-1 */
RCU_INIT_POINTER(node->avl_right, rll); /* rll: LH or LH-1 */
RCU_INIT_POINTER(node->avl_left, l); /* l: LH */
node->avl_height = lh + 1; /* node: LH+1 */
RCU_INIT_POINTER(r->avl_right, rr); /* rr: LH */
RCU_INIT_POINTER(r->avl_left, rlr); /* rlr: LH or LH-1 */
r->avl_height = lh + 1; /* r: LH+1 */
RCU_INIT_POINTER(rl->avl_right, r); /* r: LH+1 */
RCU_INIT_POINTER(rl->avl_left, node); /* node: LH+1 */
rl->avl_height = lh + 2;
RCU_INIT_POINTER(*nodep, rl);
}
} else {
node->avl_height = (lh > rh ? lh : rh) + 1;
}
}
}
/* Called with local BH disabled and the pool lock held. */
#define link_to_pool(n, base) \
do { \
n->avl_height = 1; \
n->avl_left = peer_avl_empty_rcu; \
n->avl_right = peer_avl_empty_rcu; \
/* lockless readers can catch us now */ \
rcu_assign_pointer(**--stackptr, n); \
peer_avl_rebalance(stack, stackptr, base); \
} while (0)
static void inetpeer_free_rcu(struct rcu_head *head)
{
kmem_cache_free(peer_cachep, container_of(head, struct inet_peer, rcu));
}
/* May be called with local BH enabled. */
static void unlink_from_pool(struct inet_peer *p, struct inet_peer_base *base,
struct inet_peer __rcu **stack[PEER_MAXDEPTH])
{
int do_free;
do_free = 0;
write_seqlock_bh(&base->lock);
/* Check the reference counter. It was artificially incremented by 1
* in cleanup() function to prevent sudden disappearing. If we can
* atomically (because of lockless readers) take this last reference,
* it's safe to remove the node and free it later.
* We use refcnt=-1 to alert lockless readers this entry is deleted.
*/
if (atomic_cmpxchg(&p->refcnt, 1, -1) == 1) {
struct inet_peer __rcu ***stackptr, ***delp;
if (lookup(&p->daddr, stack, base) != p)
BUG();
delp = stackptr - 1; /* *delp[0] == p */
if (p->avl_left == peer_avl_empty_rcu) {
*delp[0] = p->avl_right;
--stackptr;
} else {
/* look for a node to insert instead of p */
struct inet_peer *t;
t = lookup_rightempty(p, base);
BUG_ON(rcu_deref_locked(*stackptr[-1], base) != t);
**--stackptr = t->avl_left;
/* t is removed, t->daddr > x->daddr for any
* x in p->avl_left subtree.
* Put t in the old place of p. */
RCU_INIT_POINTER(*delp[0], t);
t->avl_left = p->avl_left;
t->avl_right = p->avl_right;
t->avl_height = p->avl_height;
BUG_ON(delp[1] != &p->avl_left);
delp[1] = &t->avl_left; /* was &p->avl_left */
}
peer_avl_rebalance(stack, stackptr, base);
base->total--;
do_free = 1;
}
write_sequnlock_bh(&base->lock);
if (do_free)
call_rcu(&p->rcu, inetpeer_free_rcu);
else
/* The node is used again. Decrease the reference counter
* back. The loop "cleanup -> unlink_from_unused
* -> unlink_from_pool -> putpeer -> link_to_unused
* -> cleanup (for the same node)"
* doesn't really exist because the entry will have a
* recent deletion time and will not be cleaned again soon.
*/
inet_putpeer(p);
}
static struct inet_peer_base *family_to_base(int family)
{
return (family == AF_INET ? &v4_peers : &v6_peers);
}
static struct inet_peer_base *peer_to_base(struct inet_peer *p)
{
return family_to_base(p->daddr.family);
}
/* May be called with local BH enabled. */
static int cleanup_once(unsigned long ttl, struct inet_peer __rcu **stack[PEER_MAXDEPTH])
{
struct inet_peer *p = NULL;
/* Remove the first entry from the list of unused nodes. */
spin_lock_bh(&unused_peers.lock);
if (!list_empty(&unused_peers.list)) {
__u32 delta;
p = list_first_entry(&unused_peers.list, struct inet_peer, unused);
delta = (__u32)jiffies - p->dtime;
if (delta < ttl) {
/* Do not prune fresh entries. */
spin_unlock_bh(&unused_peers.lock);
return -1;
}
list_del_init(&p->unused);
/* Grab an extra reference to prevent node disappearing
* before unlink_from_pool() call. */
atomic_inc(&p->refcnt);
}
spin_unlock_bh(&unused_peers.lock);
if (p == NULL)
/* It means that the total number of USED entries has
* grown over inet_peer_threshold. It shouldn't really
* happen because of entry limits in route cache. */
return -1;
unlink_from_pool(p, peer_to_base(p), stack);
return 0;
}
/* Called with or without local BH being disabled. */
struct inet_peer *inet_getpeer(struct inetpeer_addr *daddr, int create)
{
struct inet_peer __rcu **stack[PEER_MAXDEPTH], ***stackptr;
struct inet_peer_base *base = family_to_base(daddr->family);
struct inet_peer *p;
unsigned int sequence;
int invalidated, newrefcnt = 0;
/* Look up for the address quickly, lockless.
* Because of a concurrent writer, we might not find an existing entry.
*/
rcu_read_lock();
sequence = read_seqbegin(&base->lock);
p = lookup_rcu(daddr, base, &newrefcnt);
invalidated = read_seqretry(&base->lock, sequence);
rcu_read_unlock();
if (p) {
found: /* The existing node has been found.
* Remove the entry from unused list if it was there.
*/
if (newrefcnt == 1)
unlink_from_unused(p);
return p;
}
/* If no writer did a change during our lookup, we can return early. */
if (!create && !invalidated)
return NULL;
/* retry an exact lookup, taking the lock before.
* At least, nodes should be hot in our cache.
*/
write_seqlock_bh(&base->lock);
p = lookup(daddr, stack, base);
if (p != peer_avl_empty) {
newrefcnt = atomic_inc_return(&p->refcnt);
write_sequnlock_bh(&base->lock);
goto found;
}
p = create ? kmem_cache_alloc(peer_cachep, GFP_ATOMIC) : NULL;
if (p) {
p->daddr = *daddr;
atomic_set(&p->refcnt, 1);
atomic_set(&p->rid, 0);
atomic_set(&p->ip_id_count, secure_ip_id(daddr->addr.a4));
p->tcp_ts_stamp = 0;
p->metrics[RTAX_LOCK-1] = INETPEER_METRICS_NEW;
p->rate_tokens = 0;
p->rate_last = 0;
p->pmtu_expires = 0;
p->pmtu_orig = 0;
memset(&p->redirect_learned, 0, sizeof(p->redirect_learned));
INIT_LIST_HEAD(&p->unused);
/* Link the node. */
link_to_pool(p, base);
base->total++;
}
write_sequnlock_bh(&base->lock);
if (base->total >= inet_peer_threshold)
/* Remove one less-recently-used entry. */
cleanup_once(0, stack);
return p;
}
static int compute_total(void)
{
return v4_peers.total + v6_peers.total;
}
EXPORT_SYMBOL_GPL(inet_getpeer);
/* Called with local BH disabled. */
static void peer_check_expire(unsigned long dummy)
{
unsigned long now = jiffies;
int ttl, total;
struct inet_peer __rcu **stack[PEER_MAXDEPTH];
total = compute_total();
if (total >= inet_peer_threshold)
ttl = inet_peer_minttl;
else
ttl = inet_peer_maxttl
- (inet_peer_maxttl - inet_peer_minttl) / HZ *
total / inet_peer_threshold * HZ;
while (!cleanup_once(ttl, stack)) {
if (jiffies != now)
break;
}
/* Trigger the timer after inet_peer_gc_mintime .. inet_peer_gc_maxtime
* interval depending on the total number of entries (more entries,
* less interval). */
total = compute_total();
if (total >= inet_peer_threshold)
peer_periodic_timer.expires = jiffies + inet_peer_gc_mintime;
else
peer_periodic_timer.expires = jiffies
+ inet_peer_gc_maxtime
- (inet_peer_gc_maxtime - inet_peer_gc_mintime) / HZ *
total / inet_peer_threshold * HZ;
add_timer(&peer_periodic_timer);
}
void inet_putpeer(struct inet_peer *p)
{
local_bh_disable();
if (atomic_dec_and_lock(&p->refcnt, &unused_peers.lock)) {
list_add_tail(&p->unused, &unused_peers.list);
p->dtime = (__u32)jiffies;
spin_unlock(&unused_peers.lock);
}
local_bh_enable();
}
EXPORT_SYMBOL_GPL(inet_putpeer);
/*
* Check transmit rate limitation for given message.
* The rate information is held in the inet_peer entries now.
* This function is generic and could be used for other purposes
* too. It uses a Token bucket filter as suggested by Alexey Kuznetsov.
*
* Note that the same inet_peer fields are modified by functions in
* route.c too, but these work for packet destinations while xrlim_allow
* works for icmp destinations. This means the rate limiting information
* for one "ip object" is shared - and these ICMPs are twice limited:
* by source and by destination.
*
* RFC 1812: 4.3.2.8 SHOULD be able to limit error message rate
* SHOULD allow setting of rate limits
*
* Shared between ICMPv4 and ICMPv6.
*/
#define XRLIM_BURST_FACTOR 6
bool inet_peer_xrlim_allow(struct inet_peer *peer, int timeout)
{
unsigned long now, token;
bool rc = false;
if (!peer)
return true;
token = peer->rate_tokens;
now = jiffies;
token += now - peer->rate_last;
peer->rate_last = now;
if (token > XRLIM_BURST_FACTOR * timeout)
token = XRLIM_BURST_FACTOR * timeout;
if (token >= timeout) {
token -= timeout;
rc = true;
}
peer->rate_tokens = token;
return rc;
}
EXPORT_SYMBOL(inet_peer_xrlim_allow);
| gpl-2.0 |
varigit/VAR-SOM-AMx3-Kernel-4-1 | drivers/net/wireless/rtlwifi/rtl8188ee/trx.c | 974 | 24493 | /******************************************************************************
*
* Copyright(c) 2009-2013 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.
*
* 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 "../base.h"
#include "../stats.h"
#include "reg.h"
#include "def.h"
#include "phy.h"
#include "trx.h"
#include "led.h"
#include "dm.h"
#include "phy.h"
static u8 _rtl88ee_map_hwqueue_to_fwqueue(struct sk_buff *skb, u8 hw_queue)
{
__le16 fc = rtl_get_fc(skb);
if (unlikely(ieee80211_is_beacon(fc)))
return QSLT_BEACON;
if (ieee80211_is_mgmt(fc) || ieee80211_is_ctl(fc))
return QSLT_MGNT;
return skb->priority;
}
static void _rtl88ee_query_rxphystatus(struct ieee80211_hw *hw,
struct rtl_stats *pstatus, u8 *pdesc,
struct rx_fwinfo_88e *p_drvinfo,
bool bpacket_match_bssid,
bool bpacket_toself, bool packet_beacon)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_ps_ctl *ppsc = rtl_psc(rtlpriv);
struct phy_sts_cck_8192s_t *cck_buf;
struct phy_status_rpt *phystrpt =
(struct phy_status_rpt *)p_drvinfo;
struct rtl_dm *rtldm = rtl_dm(rtl_priv(hw));
char rx_pwr_all = 0, rx_pwr[4];
u8 rf_rx_num = 0, evm, pwdb_all;
u8 i, max_spatial_stream;
u32 rssi, total_rssi = 0;
bool is_cck = pstatus->is_cck;
u8 lan_idx, vga_idx;
/* Record it for next packet processing */
pstatus->packet_matchbssid = bpacket_match_bssid;
pstatus->packet_toself = bpacket_toself;
pstatus->packet_beacon = packet_beacon;
pstatus->rx_mimo_signalquality[0] = -1;
pstatus->rx_mimo_signalquality[1] = -1;
if (is_cck) {
u8 cck_highpwr;
u8 cck_agc_rpt;
/* CCK Driver info Structure is not the same as OFDM packet. */
cck_buf = (struct phy_sts_cck_8192s_t *)p_drvinfo;
cck_agc_rpt = cck_buf->cck_agc_rpt;
/* (1)Hardware does not provide RSSI for CCK
* (2)PWDB, Average PWDB cacluated by
* hardware (for rate adaptive)
*/
if (ppsc->rfpwr_state == ERFON)
cck_highpwr =
(u8)rtl_get_bbreg(hw, RFPGA0_XA_HSSIPARAMETER2,
BIT(9));
else
cck_highpwr = false;
lan_idx = ((cck_agc_rpt & 0xE0) >> 5);
vga_idx = (cck_agc_rpt & 0x1f);
switch (lan_idx) {
case 7:
if (vga_idx <= 27)
/*VGA_idx = 27~2*/
rx_pwr_all = -100 + 2*(27-vga_idx);
else
rx_pwr_all = -100;
break;
case 6:
/*VGA_idx = 2~0*/
rx_pwr_all = -48 + 2*(2-vga_idx);
break;
case 5:
/*VGA_idx = 7~5*/
rx_pwr_all = -42 + 2*(7-vga_idx);
break;
case 4:
/*VGA_idx = 7~4*/
rx_pwr_all = -36 + 2*(7-vga_idx);
break;
case 3:
/*VGA_idx = 7~0*/
rx_pwr_all = -24 + 2*(7-vga_idx);
break;
case 2:
if (cck_highpwr)
/*VGA_idx = 5~0*/
rx_pwr_all = -12 + 2*(5-vga_idx);
else
rx_pwr_all = -6 + 2*(5-vga_idx);
break;
case 1:
rx_pwr_all = 8-2*vga_idx;
break;
case 0:
rx_pwr_all = 14-2*vga_idx;
break;
default:
break;
}
rx_pwr_all += 6;
pwdb_all = rtl_query_rxpwrpercentage(rx_pwr_all);
/* CCK gain is smaller than OFDM/MCS gain, */
/* so we add gain diff by experiences, the val is 6 */
pwdb_all += 6;
if (pwdb_all > 100)
pwdb_all = 100;
/* modify the offset to make the same
* gain index with OFDM.
*/
if (pwdb_all > 34 && pwdb_all <= 42)
pwdb_all -= 2;
else if (pwdb_all > 26 && pwdb_all <= 34)
pwdb_all -= 6;
else if (pwdb_all > 14 && pwdb_all <= 26)
pwdb_all -= 8;
else if (pwdb_all > 4 && pwdb_all <= 14)
pwdb_all -= 4;
if (!cck_highpwr) {
if (pwdb_all >= 80)
pwdb_all = ((pwdb_all-80)<<1) +
((pwdb_all-80)>>1) + 80;
else if ((pwdb_all <= 78) && (pwdb_all >= 20))
pwdb_all += 3;
if (pwdb_all > 100)
pwdb_all = 100;
}
pstatus->rx_pwdb_all = pwdb_all;
pstatus->recvsignalpower = rx_pwr_all;
/* (3) Get Signal Quality (EVM) */
if (bpacket_match_bssid) {
u8 sq;
if (pstatus->rx_pwdb_all > 40)
sq = 100;
else {
sq = cck_buf->sq_rpt;
if (sq > 64)
sq = 0;
else if (sq < 20)
sq = 100;
else
sq = ((64 - sq) * 100) / 44;
}
pstatus->signalquality = sq;
pstatus->rx_mimo_signalquality[0] = sq;
pstatus->rx_mimo_signalquality[1] = -1;
}
} else {
rtlpriv->dm.rfpath_rxenable[0] =
rtlpriv->dm.rfpath_rxenable[1] = true;
/* (1)Get RSSI for HT rate */
for (i = RF90_PATH_A; i < RF6052_MAX_PATH; i++) {
/* we will judge RF RX path now. */
if (rtlpriv->dm.rfpath_rxenable[i])
rf_rx_num++;
rx_pwr[i] = ((p_drvinfo->gain_trsw[i] &
0x3f) * 2) - 110;
/* Translate DBM to percentage. */
rssi = rtl_query_rxpwrpercentage(rx_pwr[i]);
total_rssi += rssi;
/* Get Rx snr value in DB */
rtlpriv->stats.rx_snr_db[i] =
(long)(p_drvinfo->rxsnr[i] / 2);
/* Record Signal Strength for next packet */
if (bpacket_match_bssid)
pstatus->rx_mimo_signalstrength[i] = (u8)rssi;
}
/* (2)PWDB, Average PWDB cacluated by
* hardware (for rate adaptive)
*/
rx_pwr_all = ((p_drvinfo->pwdb_all >> 1) & 0x7f) - 110;
pwdb_all = rtl_query_rxpwrpercentage(rx_pwr_all);
pstatus->rx_pwdb_all = pwdb_all;
pstatus->rxpower = rx_pwr_all;
pstatus->recvsignalpower = rx_pwr_all;
/* (3)EVM of HT rate */
if (pstatus->is_ht && pstatus->rate >= DESC92C_RATEMCS8 &&
pstatus->rate <= DESC92C_RATEMCS15)
max_spatial_stream = 2;
else
max_spatial_stream = 1;
for (i = 0; i < max_spatial_stream; i++) {
evm = rtl_evm_db_to_percentage(p_drvinfo->rxevm[i]);
if (bpacket_match_bssid) {
/* Fill value in RFD, Get the first
* spatial stream onlyi
*/
if (i == 0)
pstatus->signalquality =
(u8)(evm & 0xff);
pstatus->rx_mimo_signalquality[i] =
(u8)(evm & 0xff);
}
}
}
/* UI BSS List signal strength(in percentage),
* make it good looking, from 0~100.
*/
if (is_cck)
pstatus->signalstrength = (u8)(rtl_signal_scale_mapping(hw,
pwdb_all));
else if (rf_rx_num != 0)
pstatus->signalstrength = (u8)(rtl_signal_scale_mapping(hw,
total_rssi /= rf_rx_num));
/*HW antenna diversity*/
rtldm->fat_table.antsel_rx_keep_0 = phystrpt->ant_sel;
rtldm->fat_table.antsel_rx_keep_1 = phystrpt->ant_sel_b;
rtldm->fat_table.antsel_rx_keep_2 = phystrpt->antsel_rx_keep_2;
}
static void _rtl88ee_smart_antenna(struct ieee80211_hw *hw,
struct rtl_stats *pstatus)
{
struct rtl_dm *rtldm = rtl_dm(rtl_priv(hw));
struct rtl_efuse *rtlefuse = rtl_efuse(rtl_priv(hw));
u8 antsel_tr_mux;
struct fast_ant_training *pfat_table = &rtldm->fat_table;
if (rtlefuse->antenna_div_type == CG_TRX_SMART_ANTDIV) {
if (pfat_table->fat_state == FAT_TRAINING_STATE) {
if (pstatus->packet_toself) {
antsel_tr_mux =
(pfat_table->antsel_rx_keep_2 << 2) |
(pfat_table->antsel_rx_keep_1 << 1) |
pfat_table->antsel_rx_keep_0;
pfat_table->ant_sum[antsel_tr_mux] +=
pstatus->rx_pwdb_all;
pfat_table->ant_cnt[antsel_tr_mux]++;
}
}
} else if ((rtlefuse->antenna_div_type == CG_TRX_HW_ANTDIV) ||
(rtlefuse->antenna_div_type == CGCS_RX_HW_ANTDIV)) {
if (pstatus->packet_toself || pstatus->packet_matchbssid) {
antsel_tr_mux = (pfat_table->antsel_rx_keep_2 << 2) |
(pfat_table->antsel_rx_keep_1 << 1) |
pfat_table->antsel_rx_keep_0;
rtl88e_dm_ant_sel_statistics(hw, antsel_tr_mux, 0,
pstatus->rx_pwdb_all);
}
}
}
static void _rtl88ee_translate_rx_signal_stuff(struct ieee80211_hw *hw,
struct sk_buff *skb,
struct rtl_stats *pstatus,
u8 *pdesc,
struct rx_fwinfo_88e *p_drvinfo)
{
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_efuse *rtlefuse = rtl_efuse(rtl_priv(hw));
struct ieee80211_hdr *hdr;
u8 *tmp_buf;
u8 *praddr;
u8 *psaddr;
__le16 fc;
bool packet_matchbssid, packet_toself, packet_beacon;
tmp_buf = skb->data + pstatus->rx_drvinfo_size + pstatus->rx_bufshift;
hdr = (struct ieee80211_hdr *)tmp_buf;
fc = hdr->frame_control;
praddr = hdr->addr1;
psaddr = ieee80211_get_SA(hdr);
memcpy(pstatus->psaddr, psaddr, ETH_ALEN);
packet_matchbssid = ((!ieee80211_is_ctl(fc)) &&
(ether_addr_equal(mac->bssid, ieee80211_has_tods(fc) ?
hdr->addr1 : ieee80211_has_fromds(fc) ?
hdr->addr2 : hdr->addr3)) &&
(!pstatus->hwerror) &&
(!pstatus->crc) && (!pstatus->icv));
packet_toself = packet_matchbssid &&
(ether_addr_equal(praddr, rtlefuse->dev_addr));
if (ieee80211_is_beacon(hdr->frame_control))
packet_beacon = true;
else
packet_beacon = false;
_rtl88ee_query_rxphystatus(hw, pstatus, pdesc, p_drvinfo,
packet_matchbssid, packet_toself,
packet_beacon);
_rtl88ee_smart_antenna(hw, pstatus);
rtl_process_phyinfo(hw, tmp_buf, pstatus);
}
static void _rtl88ee_insert_emcontent(struct rtl_tcb_desc *ptcb_desc,
u8 *virtualaddress)
{
u32 dwtmp = 0;
memset(virtualaddress, 0, 8);
SET_EARLYMODE_PKTNUM(virtualaddress, ptcb_desc->empkt_num);
if (ptcb_desc->empkt_num == 1) {
dwtmp = ptcb_desc->empkt_len[0];
} else {
dwtmp = ptcb_desc->empkt_len[0];
dwtmp += ((dwtmp%4) ? (4-dwtmp%4) : 0)+4;
dwtmp += ptcb_desc->empkt_len[1];
}
SET_EARLYMODE_LEN0(virtualaddress, dwtmp);
if (ptcb_desc->empkt_num <= 3) {
dwtmp = ptcb_desc->empkt_len[2];
} else {
dwtmp = ptcb_desc->empkt_len[2];
dwtmp += ((dwtmp%4) ? (4-dwtmp%4) : 0)+4;
dwtmp += ptcb_desc->empkt_len[3];
}
SET_EARLYMODE_LEN1(virtualaddress, dwtmp);
if (ptcb_desc->empkt_num <= 5) {
dwtmp = ptcb_desc->empkt_len[4];
} else {
dwtmp = ptcb_desc->empkt_len[4];
dwtmp += ((dwtmp%4) ? (4-dwtmp%4) : 0)+4;
dwtmp += ptcb_desc->empkt_len[5];
}
SET_EARLYMODE_LEN2_1(virtualaddress, dwtmp & 0xF);
SET_EARLYMODE_LEN2_2(virtualaddress, dwtmp >> 4);
if (ptcb_desc->empkt_num <= 7) {
dwtmp = ptcb_desc->empkt_len[6];
} else {
dwtmp = ptcb_desc->empkt_len[6];
dwtmp += ((dwtmp%4) ? (4-dwtmp%4) : 0)+4;
dwtmp += ptcb_desc->empkt_len[7];
}
SET_EARLYMODE_LEN3(virtualaddress, dwtmp);
if (ptcb_desc->empkt_num <= 9) {
dwtmp = ptcb_desc->empkt_len[8];
} else {
dwtmp = ptcb_desc->empkt_len[8];
dwtmp += ((dwtmp%4) ? (4-dwtmp%4) : 0)+4;
dwtmp += ptcb_desc->empkt_len[9];
}
SET_EARLYMODE_LEN4(virtualaddress, dwtmp);
}
bool rtl88ee_rx_query_desc(struct ieee80211_hw *hw,
struct rtl_stats *status,
struct ieee80211_rx_status *rx_status,
u8 *pdesc, struct sk_buff *skb)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rx_fwinfo_88e *p_drvinfo;
struct ieee80211_hdr *hdr;
u32 phystatus = GET_RX_DESC_PHYST(pdesc);
status->packet_report_type = (u8)GET_RX_STATUS_DESC_RPT_SEL(pdesc);
if (status->packet_report_type == TX_REPORT2)
status->length = (u16)GET_RX_RPT2_DESC_PKT_LEN(pdesc);
else
status->length = (u16)GET_RX_DESC_PKT_LEN(pdesc);
status->rx_drvinfo_size = (u8)GET_RX_DESC_DRV_INFO_SIZE(pdesc) *
RX_DRV_INFO_SIZE_UNIT;
status->rx_bufshift = (u8)(GET_RX_DESC_SHIFT(pdesc) & 0x03);
status->icv = (u16)GET_RX_DESC_ICV(pdesc);
status->crc = (u16)GET_RX_DESC_CRC32(pdesc);
status->hwerror = (status->crc | status->icv);
status->decrypted = !GET_RX_DESC_SWDEC(pdesc);
status->rate = (u8)GET_RX_DESC_RXMCS(pdesc);
status->shortpreamble = (u16)GET_RX_DESC_SPLCP(pdesc);
status->isampdu = (bool) (GET_RX_DESC_PAGGR(pdesc) == 1);
status->isfirst_ampdu = (bool)((GET_RX_DESC_PAGGR(pdesc) == 1) &&
(GET_RX_DESC_FAGGR(pdesc) == 1));
if (status->packet_report_type == NORMAL_RX)
status->timestamp_low = GET_RX_DESC_TSFL(pdesc);
status->rx_is40Mhzpacket = (bool) GET_RX_DESC_BW(pdesc);
status->is_ht = (bool)GET_RX_DESC_RXHT(pdesc);
status->is_cck = RTL8188_RX_HAL_IS_CCK_RATE(status->rate);
status->macid = GET_RX_DESC_MACID(pdesc);
if (GET_RX_STATUS_DESC_MAGIC_MATCH(pdesc))
status->wake_match = BIT(2);
else if (GET_RX_STATUS_DESC_MAGIC_MATCH(pdesc))
status->wake_match = BIT(1);
else if (GET_RX_STATUS_DESC_UNICAST_MATCH(pdesc))
status->wake_match = BIT(0);
else
status->wake_match = 0;
if (status->wake_match)
RT_TRACE(rtlpriv, COMP_RXDESC, DBG_LOUD,
"GGGGGGGGGGGGGet Wakeup Packet!! WakeMatch=%d\n",
status->wake_match);
rx_status->freq = hw->conf.chandef.chan->center_freq;
rx_status->band = hw->conf.chandef.chan->band;
hdr = (struct ieee80211_hdr *)(skb->data + status->rx_drvinfo_size
+ status->rx_bufshift);
if (status->crc)
rx_status->flag |= RX_FLAG_FAILED_FCS_CRC;
if (status->rx_is40Mhzpacket)
rx_status->flag |= RX_FLAG_40MHZ;
if (status->is_ht)
rx_status->flag |= RX_FLAG_HT;
rx_status->flag |= RX_FLAG_MACTIME_START;
/* hw will set status->decrypted true, if it finds the
* frame is open data frame or mgmt frame.
* So hw will not decryption robust managment frame
* for IEEE80211w but still set status->decrypted
* true, so here we should set it back to undecrypted
* for IEEE80211w frame, and mac80211 sw will help
* to decrypt it
*/
if (status->decrypted) {
if ((!_ieee80211_is_robust_mgmt_frame(hdr)) &&
(ieee80211_has_protected(hdr->frame_control)))
rx_status->flag |= RX_FLAG_DECRYPTED;
else
rx_status->flag &= ~RX_FLAG_DECRYPTED;
}
/* rate_idx: index of data rate into band's
* supported rates or MCS index if HT rates
* are use (RX_FLAG_HT)
* Notice: this is diff with windows define
*/
rx_status->rate_idx = rtlwifi_rate_mapping(hw, status->is_ht,
false, status->rate);
rx_status->mactime = status->timestamp_low;
if (phystatus == true) {
p_drvinfo = (struct rx_fwinfo_88e *)(skb->data +
status->rx_bufshift);
_rtl88ee_translate_rx_signal_stuff(hw,
skb, status, pdesc,
p_drvinfo);
}
rx_status->signal = status->recvsignalpower + 10;
if (status->packet_report_type == TX_REPORT2) {
status->macid_valid_entry[0] =
GET_RX_RPT2_DESC_MACID_VALID_1(pdesc);
status->macid_valid_entry[1] =
GET_RX_RPT2_DESC_MACID_VALID_2(pdesc);
}
return true;
}
void rtl88ee_tx_fill_desc(struct ieee80211_hw *hw,
struct ieee80211_hdr *hdr, u8 *pdesc_tx,
u8 *txbd, struct ieee80211_tx_info *info,
struct ieee80211_sta *sta,
struct sk_buff *skb,
u8 hw_queue, struct rtl_tcb_desc *ptcb_desc)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
struct rtl_hal *rtlhal = rtl_hal(rtlpriv);
u8 *pdesc = (u8 *)pdesc_tx;
u16 seq_number;
__le16 fc = hdr->frame_control;
unsigned int buf_len = 0;
unsigned int skb_len = skb->len;
u8 fw_qsel = _rtl88ee_map_hwqueue_to_fwqueue(skb, hw_queue);
bool firstseg = ((hdr->seq_ctrl &
cpu_to_le16(IEEE80211_SCTL_FRAG)) == 0);
bool lastseg = ((hdr->frame_control &
cpu_to_le16(IEEE80211_FCTL_MOREFRAGS)) == 0);
dma_addr_t mapping;
u8 bw_40 = 0;
u8 short_gi = 0;
if (mac->opmode == NL80211_IFTYPE_STATION) {
bw_40 = mac->bw_40;
} else if (mac->opmode == NL80211_IFTYPE_AP ||
mac->opmode == NL80211_IFTYPE_ADHOC) {
if (sta)
bw_40 = sta->ht_cap.cap &
IEEE80211_HT_CAP_SUP_WIDTH_20_40;
}
seq_number = (le16_to_cpu(hdr->seq_ctrl) & IEEE80211_SCTL_SEQ) >> 4;
rtl_get_tcb_desc(hw, info, sta, skb, ptcb_desc);
/* reserve 8 byte for AMPDU early mode */
if (rtlhal->earlymode_enable) {
skb_push(skb, EM_HDR_LEN);
memset(skb->data, 0, EM_HDR_LEN);
}
buf_len = skb->len;
mapping = pci_map_single(rtlpci->pdev, skb->data, skb->len,
PCI_DMA_TODEVICE);
if (pci_dma_mapping_error(rtlpci->pdev, mapping)) {
RT_TRACE(rtlpriv, COMP_SEND, DBG_TRACE,
"DMA mapping error");
return;
}
CLEAR_PCI_TX_DESC_CONTENT(pdesc, sizeof(struct tx_desc_88e));
if (ieee80211_is_nullfunc(fc) || ieee80211_is_ctl(fc)) {
firstseg = true;
lastseg = true;
}
if (firstseg) {
if (rtlhal->earlymode_enable) {
SET_TX_DESC_PKT_OFFSET(pdesc, 1);
SET_TX_DESC_OFFSET(pdesc, USB_HWDESC_HEADER_LEN +
EM_HDR_LEN);
if (ptcb_desc->empkt_num) {
RT_TRACE(rtlpriv, COMP_SEND, DBG_TRACE,
"Insert 8 byte.pTcb->EMPktNum:%d\n",
ptcb_desc->empkt_num);
_rtl88ee_insert_emcontent(ptcb_desc,
(u8 *)(skb->data));
}
} else {
SET_TX_DESC_OFFSET(pdesc, USB_HWDESC_HEADER_LEN);
}
ptcb_desc->use_driver_rate = true;
SET_TX_DESC_TX_RATE(pdesc, ptcb_desc->hw_rate);
if (ptcb_desc->hw_rate > DESC92C_RATEMCS0)
short_gi = (ptcb_desc->use_shortgi) ? 1 : 0;
else
short_gi = (ptcb_desc->use_shortpreamble) ? 1 : 0;
SET_TX_DESC_DATA_SHORTGI(pdesc, short_gi);
if (info->flags & IEEE80211_TX_CTL_AMPDU) {
SET_TX_DESC_AGG_ENABLE(pdesc, 1);
SET_TX_DESC_MAX_AGG_NUM(pdesc, 0x14);
}
SET_TX_DESC_SEQ(pdesc, seq_number);
SET_TX_DESC_RTS_ENABLE(pdesc, ((ptcb_desc->rts_enable &&
!ptcb_desc->cts_enable) ? 1 : 0));
SET_TX_DESC_HW_RTS_ENABLE(pdesc, 0);
SET_TX_DESC_CTS2SELF(pdesc, ((ptcb_desc->cts_enable) ? 1 : 0));
SET_TX_DESC_RTS_STBC(pdesc, ((ptcb_desc->rts_stbc) ? 1 : 0));
SET_TX_DESC_RTS_RATE(pdesc, ptcb_desc->rts_rate);
SET_TX_DESC_RTS_BW(pdesc, 0);
SET_TX_DESC_RTS_SC(pdesc, ptcb_desc->rts_sc);
SET_TX_DESC_RTS_SHORT(pdesc,
((ptcb_desc->rts_rate <= DESC92C_RATE54M) ?
(ptcb_desc->rts_use_shortpreamble ? 1 : 0) :
(ptcb_desc->rts_use_shortgi ? 1 : 0)));
if (ptcb_desc->tx_enable_sw_calc_duration)
SET_TX_DESC_NAV_USE_HDR(pdesc, 1);
if (bw_40) {
if (ptcb_desc->packet_bw == HT_CHANNEL_WIDTH_20_40) {
SET_TX_DESC_DATA_BW(pdesc, 1);
SET_TX_DESC_TX_SUB_CARRIER(pdesc, 3);
} else {
SET_TX_DESC_DATA_BW(pdesc, 0);
SET_TX_DESC_TX_SUB_CARRIER(pdesc,
mac->cur_40_prime_sc);
}
} else {
SET_TX_DESC_DATA_BW(pdesc, 0);
SET_TX_DESC_TX_SUB_CARRIER(pdesc, 0);
}
SET_TX_DESC_LINIP(pdesc, 0);
SET_TX_DESC_PKT_SIZE(pdesc, (u16)skb_len);
if (sta) {
u8 ampdu_density = sta->ht_cap.ampdu_density;
SET_TX_DESC_AMPDU_DENSITY(pdesc, ampdu_density);
}
if (info->control.hw_key) {
struct ieee80211_key_conf *keyconf;
keyconf = info->control.hw_key;
switch (keyconf->cipher) {
case WLAN_CIPHER_SUITE_WEP40:
case WLAN_CIPHER_SUITE_WEP104:
case WLAN_CIPHER_SUITE_TKIP:
SET_TX_DESC_SEC_TYPE(pdesc, 0x1);
break;
case WLAN_CIPHER_SUITE_CCMP:
SET_TX_DESC_SEC_TYPE(pdesc, 0x3);
break;
default:
SET_TX_DESC_SEC_TYPE(pdesc, 0x0);
break;
}
}
SET_TX_DESC_QUEUE_SEL(pdesc, fw_qsel);
SET_TX_DESC_DATA_RATE_FB_LIMIT(pdesc, 0x1F);
SET_TX_DESC_RTS_RATE_FB_LIMIT(pdesc, 0xF);
SET_TX_DESC_DISABLE_FB(pdesc, ptcb_desc->disable_ratefallback ?
1 : 0);
SET_TX_DESC_USE_RATE(pdesc, ptcb_desc->use_driver_rate ? 1 : 0);
/*SET_TX_DESC_PWR_STATUS(pdesc, pwr_status);*/
/* Set TxRate and RTSRate in TxDesc */
/* This prevent Tx initial rate of new-coming packets */
/* from being overwritten by retried packet rate.*/
if (!ptcb_desc->use_driver_rate) {
/*SET_TX_DESC_RTS_RATE(pdesc, 0x08); */
/* SET_TX_DESC_TX_RATE(pdesc, 0x0b); */
}
if (ieee80211_is_data_qos(fc)) {
if (mac->rdg_en) {
RT_TRACE(rtlpriv, COMP_SEND, DBG_TRACE,
"Enable RDG function.\n");
SET_TX_DESC_RDG_ENABLE(pdesc, 1);
SET_TX_DESC_HTC(pdesc, 1);
}
}
}
SET_TX_DESC_FIRST_SEG(pdesc, (firstseg ? 1 : 0));
SET_TX_DESC_LAST_SEG(pdesc, (lastseg ? 1 : 0));
SET_TX_DESC_TX_BUFFER_SIZE(pdesc, (u16)buf_len);
SET_TX_DESC_TX_BUFFER_ADDRESS(pdesc, mapping);
if (rtlpriv->dm.useramask) {
SET_TX_DESC_RATE_ID(pdesc, ptcb_desc->ratr_index);
SET_TX_DESC_MACID(pdesc, ptcb_desc->mac_id);
} else {
SET_TX_DESC_RATE_ID(pdesc, 0xC + ptcb_desc->ratr_index);
SET_TX_DESC_MACID(pdesc, ptcb_desc->ratr_index);
}
if (ieee80211_is_data_qos(fc))
SET_TX_DESC_QOS(pdesc, 1);
if (!ieee80211_is_data_qos(fc))
SET_TX_DESC_HWSEQ_EN(pdesc, 1);
SET_TX_DESC_MORE_FRAG(pdesc, (lastseg ? 0 : 1));
if (is_multicast_ether_addr(ieee80211_get_DA(hdr)) ||
is_broadcast_ether_addr(ieee80211_get_DA(hdr))) {
SET_TX_DESC_BMC(pdesc, 1);
}
rtl88e_dm_set_tx_ant_by_tx_info(hw, pdesc, ptcb_desc->mac_id);
RT_TRACE(rtlpriv, COMP_SEND, DBG_TRACE, "\n");
}
void rtl88ee_tx_fill_cmddesc(struct ieee80211_hw *hw,
u8 *pdesc, bool firstseg,
bool lastseg, struct sk_buff *skb)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
u8 fw_queue = QSLT_BEACON;
dma_addr_t mapping = pci_map_single(rtlpci->pdev,
skb->data, skb->len,
PCI_DMA_TODEVICE);
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)(skb->data);
__le16 fc = hdr->frame_control;
if (pci_dma_mapping_error(rtlpci->pdev, mapping)) {
RT_TRACE(rtlpriv, COMP_SEND, DBG_TRACE,
"DMA mapping error");
return;
}
CLEAR_PCI_TX_DESC_CONTENT(pdesc, TX_DESC_SIZE);
if (firstseg)
SET_TX_DESC_OFFSET(pdesc, USB_HWDESC_HEADER_LEN);
SET_TX_DESC_TX_RATE(pdesc, DESC92C_RATE1M);
SET_TX_DESC_SEQ(pdesc, 0);
SET_TX_DESC_LINIP(pdesc, 0);
SET_TX_DESC_QUEUE_SEL(pdesc, fw_queue);
SET_TX_DESC_FIRST_SEG(pdesc, 1);
SET_TX_DESC_LAST_SEG(pdesc, 1);
SET_TX_DESC_TX_BUFFER_SIZE(pdesc, (u16)(skb->len));
SET_TX_DESC_TX_BUFFER_ADDRESS(pdesc, mapping);
SET_TX_DESC_RATE_ID(pdesc, 7);
SET_TX_DESC_MACID(pdesc, 0);
SET_TX_DESC_OWN(pdesc, 1);
SET_TX_DESC_PKT_SIZE(pdesc, (u16)(skb->len));
SET_TX_DESC_FIRST_SEG(pdesc, 1);
SET_TX_DESC_LAST_SEG(pdesc, 1);
SET_TX_DESC_OFFSET(pdesc, 0x20);
SET_TX_DESC_USE_RATE(pdesc, 1);
if (!ieee80211_is_data_qos(fc))
SET_TX_DESC_HWSEQ_EN(pdesc, 1);
RT_PRINT_DATA(rtlpriv, COMP_CMD, DBG_LOUD,
"H2C Tx Cmd Content\n",
pdesc, TX_DESC_SIZE);
}
void rtl88ee_set_desc(struct ieee80211_hw *hw, u8 *pdesc,
bool istx, u8 desc_name, u8 *val)
{
if (istx == true) {
switch (desc_name) {
case HW_DESC_OWN:
SET_TX_DESC_OWN(pdesc, 1);
break;
case HW_DESC_TX_NEXTDESC_ADDR:
SET_TX_DESC_NEXT_DESC_ADDRESS(pdesc, *(u32 *)val);
break;
default:
RT_ASSERT(false, "ERR txdesc :%d not process\n",
desc_name);
break;
}
} else {
switch (desc_name) {
case HW_DESC_RXOWN:
SET_RX_DESC_OWN(pdesc, 1);
break;
case HW_DESC_RXBUFF_ADDR:
SET_RX_DESC_BUFF_ADDR(pdesc, *(u32 *)val);
break;
case HW_DESC_RXPKT_LEN:
SET_RX_DESC_PKT_LEN(pdesc, *(u32 *)val);
break;
case HW_DESC_RXERO:
SET_RX_DESC_EOR(pdesc, 1);
break;
default:
RT_ASSERT(false, "ERR rxdesc :%d not process\n",
desc_name);
break;
}
}
}
u32 rtl88ee_get_desc(u8 *pdesc, bool istx, u8 desc_name)
{
u32 ret = 0;
if (istx == true) {
switch (desc_name) {
case HW_DESC_OWN:
ret = GET_TX_DESC_OWN(pdesc);
break;
case HW_DESC_TXBUFF_ADDR:
ret = GET_TX_DESC_TX_BUFFER_ADDRESS(pdesc);
break;
default:
RT_ASSERT(false, "ERR txdesc :%d not process\n",
desc_name);
break;
}
} else {
switch (desc_name) {
case HW_DESC_OWN:
ret = GET_RX_DESC_OWN(pdesc);
break;
case HW_DESC_RXPKT_LEN:
ret = GET_RX_DESC_PKT_LEN(pdesc);
break;
case HW_DESC_RXBUFF_ADDR:
ret = GET_RX_DESC_BUFF_ADDR(pdesc);
break;
default:
RT_ASSERT(false, "ERR rxdesc :%d not process\n",
desc_name);
break;
}
}
return ret;
}
bool rtl88ee_is_tx_desc_closed(struct ieee80211_hw *hw, u8 hw_queue, u16 index)
{
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
struct rtl8192_tx_ring *ring = &rtlpci->tx_ring[hw_queue];
u8 *entry = (u8 *)(&ring->desc[ring->idx]);
u8 own = (u8)rtl88ee_get_desc(entry, true, HW_DESC_OWN);
/*beacon packet will only use the first
*descriptor defautly,and the own may not
*be cleared by the hardware
*/
if (own)
return false;
return true;
}
void rtl88ee_tx_polling(struct ieee80211_hw *hw, u8 hw_queue)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
if (hw_queue == BEACON_QUEUE) {
rtl_write_word(rtlpriv, REG_PCIE_CTRL_REG, BIT(4));
} else {
rtl_write_word(rtlpriv, REG_PCIE_CTRL_REG,
BIT(0) << (hw_queue));
}
}
u32 rtl88ee_rx_command_packet(struct ieee80211_hw *hw,
struct rtl_stats status,
struct sk_buff *skb)
{
return 0;
}
| gpl-2.0 |
sandy-harris/random.gcm | drivers/net/ethernet/oki-semi/pch_gbe/pch_gbe_param.c | 1742 | 15501 | /*
* Copyright (C) 1999 - 2010 Intel Corporation.
* Copyright (C) 2010 OKI SEMICONDUCTOR Co., LTD.
*
* This code was derived from the Intel e1000e Linux driver.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include "pch_gbe.h"
#include <linux/module.h> /* for __MODULE_STRING */
#define OPTION_UNSET -1
#define OPTION_DISABLED 0
#define OPTION_ENABLED 1
/**
* TxDescriptors - Transmit Descriptor Count
* @Valid Range: PCH_GBE_MIN_TXD - PCH_GBE_MAX_TXD
* @Default Value: PCH_GBE_DEFAULT_TXD
*/
static int TxDescriptors = OPTION_UNSET;
module_param(TxDescriptors, int, 0);
MODULE_PARM_DESC(TxDescriptors, "Number of transmit descriptors");
/**
* RxDescriptors -Receive Descriptor Count
* @Valid Range: PCH_GBE_MIN_RXD - PCH_GBE_MAX_RXD
* @Default Value: PCH_GBE_DEFAULT_RXD
*/
static int RxDescriptors = OPTION_UNSET;
module_param(RxDescriptors, int, 0);
MODULE_PARM_DESC(RxDescriptors, "Number of receive descriptors");
/**
* Speed - User Specified Speed Override
* @Valid Range: 0, 10, 100, 1000
* - 0: auto-negotiate at all supported speeds
* - 10: only link at 10 Mbps
* - 100: only link at 100 Mbps
* - 1000: only link at 1000 Mbps
* @Default Value: 0
*/
static int Speed = OPTION_UNSET;
module_param(Speed, int, 0);
MODULE_PARM_DESC(Speed, "Speed setting");
/**
* Duplex - User Specified Duplex Override
* @Valid Range: 0-2
* - 0: auto-negotiate for duplex
* - 1: only link at half duplex
* - 2: only link at full duplex
* @Default Value: 0
*/
static int Duplex = OPTION_UNSET;
module_param(Duplex, int, 0);
MODULE_PARM_DESC(Duplex, "Duplex setting");
#define HALF_DUPLEX 1
#define FULL_DUPLEX 2
/**
* AutoNeg - Auto-negotiation Advertisement Override
* @Valid Range: 0x01-0x0F, 0x20-0x2F
*
* The AutoNeg value is a bit mask describing which speed and duplex
* combinations should be advertised during auto-negotiation.
* The supported speed and duplex modes are listed below
*
* Bit 7 6 5 4 3 2 1 0
* Speed (Mbps) N/A N/A 1000 N/A 100 100 10 10
* Duplex Full Full Half Full Half
*
* @Default Value: 0x2F (copper)
*/
static int AutoNeg = OPTION_UNSET;
module_param(AutoNeg, int, 0);
MODULE_PARM_DESC(AutoNeg, "Advertised auto-negotiation setting");
#define PHY_ADVERTISE_10_HALF 0x0001
#define PHY_ADVERTISE_10_FULL 0x0002
#define PHY_ADVERTISE_100_HALF 0x0004
#define PHY_ADVERTISE_100_FULL 0x0008
#define PHY_ADVERTISE_1000_HALF 0x0010 /* Not used, just FYI */
#define PHY_ADVERTISE_1000_FULL 0x0020
#define PCH_AUTONEG_ADVERTISE_DEFAULT 0x2F
/**
* FlowControl - User Specified Flow Control Override
* @Valid Range: 0-3
* - 0: No Flow Control
* - 1: Rx only, respond to PAUSE frames but do not generate them
* - 2: Tx only, generate PAUSE frames but ignore them on receive
* - 3: Full Flow Control Support
* @Default Value: Read flow control settings from the EEPROM
*/
static int FlowControl = OPTION_UNSET;
module_param(FlowControl, int, 0);
MODULE_PARM_DESC(FlowControl, "Flow Control setting");
/*
* XsumRX - Receive Checksum Offload Enable/Disable
* @Valid Range: 0, 1
* - 0: disables all checksum offload
* - 1: enables receive IP/TCP/UDP checksum offload
* @Default Value: PCH_GBE_DEFAULT_RX_CSUM
*/
static int XsumRX = OPTION_UNSET;
module_param(XsumRX, int, 0);
MODULE_PARM_DESC(XsumRX, "Disable or enable Receive Checksum offload");
#define PCH_GBE_DEFAULT_RX_CSUM true /* trueorfalse */
/*
* XsumTX - Transmit Checksum Offload Enable/Disable
* @Valid Range: 0, 1
* - 0: disables all checksum offload
* - 1: enables transmit IP/TCP/UDP checksum offload
* @Default Value: PCH_GBE_DEFAULT_TX_CSUM
*/
static int XsumTX = OPTION_UNSET;
module_param(XsumTX, int, 0);
MODULE_PARM_DESC(XsumTX, "Disable or enable Transmit Checksum offload");
#define PCH_GBE_DEFAULT_TX_CSUM true /* trueorfalse */
/**
* pch_gbe_option - Force the MAC's flow control settings
* @hw: Pointer to the HW structure
* Returns:
* 0: Successful.
* Negative value: Failed.
*/
struct pch_gbe_option {
enum { enable_option, range_option, list_option } type;
char *name;
char *err;
int def;
union {
struct { /* range_option info */
int min;
int max;
} r;
struct { /* list_option info */
int nr;
const struct pch_gbe_opt_list { int i; char *str; } *p;
} l;
} arg;
};
static const struct pch_gbe_opt_list speed_list[] = {
{ 0, "" },
{ SPEED_10, "" },
{ SPEED_100, "" },
{ SPEED_1000, "" }
};
static const struct pch_gbe_opt_list dplx_list[] = {
{ 0, "" },
{ HALF_DUPLEX, "" },
{ FULL_DUPLEX, "" }
};
static const struct pch_gbe_opt_list an_list[] =
#define AA "AutoNeg advertising "
{{ 0x01, AA "10/HD" },
{ 0x02, AA "10/FD" },
{ 0x03, AA "10/FD, 10/HD" },
{ 0x04, AA "100/HD" },
{ 0x05, AA "100/HD, 10/HD" },
{ 0x06, AA "100/HD, 10/FD" },
{ 0x07, AA "100/HD, 10/FD, 10/HD" },
{ 0x08, AA "100/FD" },
{ 0x09, AA "100/FD, 10/HD" },
{ 0x0a, AA "100/FD, 10/FD" },
{ 0x0b, AA "100/FD, 10/FD, 10/HD" },
{ 0x0c, AA "100/FD, 100/HD" },
{ 0x0d, AA "100/FD, 100/HD, 10/HD" },
{ 0x0e, AA "100/FD, 100/HD, 10/FD" },
{ 0x0f, AA "100/FD, 100/HD, 10/FD, 10/HD" },
{ 0x20, AA "1000/FD" },
{ 0x21, AA "1000/FD, 10/HD" },
{ 0x22, AA "1000/FD, 10/FD" },
{ 0x23, AA "1000/FD, 10/FD, 10/HD" },
{ 0x24, AA "1000/FD, 100/HD" },
{ 0x25, AA "1000/FD, 100/HD, 10/HD" },
{ 0x26, AA "1000/FD, 100/HD, 10/FD" },
{ 0x27, AA "1000/FD, 100/HD, 10/FD, 10/HD" },
{ 0x28, AA "1000/FD, 100/FD" },
{ 0x29, AA "1000/FD, 100/FD, 10/HD" },
{ 0x2a, AA "1000/FD, 100/FD, 10/FD" },
{ 0x2b, AA "1000/FD, 100/FD, 10/FD, 10/HD" },
{ 0x2c, AA "1000/FD, 100/FD, 100/HD" },
{ 0x2d, AA "1000/FD, 100/FD, 100/HD, 10/HD" },
{ 0x2e, AA "1000/FD, 100/FD, 100/HD, 10/FD" },
{ 0x2f, AA "1000/FD, 100/FD, 100/HD, 10/FD, 10/HD" }
};
static const struct pch_gbe_opt_list fc_list[] = {
{ PCH_GBE_FC_NONE, "Flow Control Disabled" },
{ PCH_GBE_FC_RX_PAUSE, "Flow Control Receive Only" },
{ PCH_GBE_FC_TX_PAUSE, "Flow Control Transmit Only" },
{ PCH_GBE_FC_FULL, "Flow Control Enabled" }
};
/**
* pch_gbe_validate_option - Validate option
* @value: value
* @opt: option
* @adapter: Board private structure
* Returns:
* 0: Successful.
* Negative value: Failed.
*/
static int pch_gbe_validate_option(int *value,
const struct pch_gbe_option *opt,
struct pch_gbe_adapter *adapter)
{
if (*value == OPTION_UNSET) {
*value = opt->def;
return 0;
}
switch (opt->type) {
case enable_option:
switch (*value) {
case OPTION_ENABLED:
netdev_dbg(adapter->netdev, "%s Enabled\n", opt->name);
return 0;
case OPTION_DISABLED:
netdev_dbg(adapter->netdev, "%s Disabled\n", opt->name);
return 0;
}
break;
case range_option:
if (*value >= opt->arg.r.min && *value <= opt->arg.r.max) {
netdev_dbg(adapter->netdev, "%s set to %i\n",
opt->name, *value);
return 0;
}
break;
case list_option: {
int i;
const struct pch_gbe_opt_list *ent;
for (i = 0; i < opt->arg.l.nr; i++) {
ent = &opt->arg.l.p[i];
if (*value == ent->i) {
if (ent->str[0] != '\0')
netdev_dbg(adapter->netdev, "%s\n",
ent->str);
return 0;
}
}
}
break;
default:
BUG();
}
netdev_dbg(adapter->netdev, "Invalid %s value specified (%i) %s\n",
opt->name, *value, opt->err);
*value = opt->def;
return -1;
}
/**
* pch_gbe_check_copper_options - Range Checking for Link Options, Copper Version
* @adapter: Board private structure
*/
static void pch_gbe_check_copper_options(struct pch_gbe_adapter *adapter)
{
struct pch_gbe_hw *hw = &adapter->hw;
int speed, dplx;
{ /* Speed */
static const struct pch_gbe_option opt = {
.type = list_option,
.name = "Speed",
.err = "parameter ignored",
.def = 0,
.arg = { .l = { .nr = (int)ARRAY_SIZE(speed_list),
.p = speed_list } }
};
speed = Speed;
pch_gbe_validate_option(&speed, &opt, adapter);
}
{ /* Duplex */
static const struct pch_gbe_option opt = {
.type = list_option,
.name = "Duplex",
.err = "parameter ignored",
.def = 0,
.arg = { .l = { .nr = (int)ARRAY_SIZE(dplx_list),
.p = dplx_list } }
};
dplx = Duplex;
pch_gbe_validate_option(&dplx, &opt, adapter);
}
{ /* Autoneg */
static const struct pch_gbe_option opt = {
.type = list_option,
.name = "AutoNeg",
.err = "parameter ignored",
.def = PCH_AUTONEG_ADVERTISE_DEFAULT,
.arg = { .l = { .nr = (int)ARRAY_SIZE(an_list),
.p = an_list} }
};
if (speed || dplx) {
netdev_dbg(adapter->netdev,
"AutoNeg specified along with Speed or Duplex, AutoNeg parameter ignored\n");
hw->phy.autoneg_advertised = opt.def;
} else {
int tmp = AutoNeg;
pch_gbe_validate_option(&tmp, &opt, adapter);
hw->phy.autoneg_advertised = tmp;
}
}
switch (speed + dplx) {
case 0:
hw->mac.autoneg = hw->mac.fc_autoneg = 1;
if ((speed || dplx))
netdev_dbg(adapter->netdev,
"Speed and duplex autonegotiation enabled\n");
hw->mac.link_speed = SPEED_10;
hw->mac.link_duplex = DUPLEX_HALF;
break;
case HALF_DUPLEX:
netdev_dbg(adapter->netdev,
"Half Duplex specified without Speed\n");
netdev_dbg(adapter->netdev,
"Using Autonegotiation at Half Duplex only\n");
hw->mac.autoneg = hw->mac.fc_autoneg = 1;
hw->phy.autoneg_advertised = PHY_ADVERTISE_10_HALF |
PHY_ADVERTISE_100_HALF;
hw->mac.link_speed = SPEED_10;
hw->mac.link_duplex = DUPLEX_HALF;
break;
case FULL_DUPLEX:
netdev_dbg(adapter->netdev,
"Full Duplex specified without Speed\n");
netdev_dbg(adapter->netdev,
"Using Autonegotiation at Full Duplex only\n");
hw->mac.autoneg = hw->mac.fc_autoneg = 1;
hw->phy.autoneg_advertised = PHY_ADVERTISE_10_FULL |
PHY_ADVERTISE_100_FULL |
PHY_ADVERTISE_1000_FULL;
hw->mac.link_speed = SPEED_10;
hw->mac.link_duplex = DUPLEX_FULL;
break;
case SPEED_10:
netdev_dbg(adapter->netdev,
"10 Mbps Speed specified without Duplex\n");
netdev_dbg(adapter->netdev,
"Using Autonegotiation at 10 Mbps only\n");
hw->mac.autoneg = hw->mac.fc_autoneg = 1;
hw->phy.autoneg_advertised = PHY_ADVERTISE_10_HALF |
PHY_ADVERTISE_10_FULL;
hw->mac.link_speed = SPEED_10;
hw->mac.link_duplex = DUPLEX_HALF;
break;
case SPEED_10 + HALF_DUPLEX:
netdev_dbg(adapter->netdev, "Forcing to 10 Mbps Half Duplex\n");
hw->mac.autoneg = hw->mac.fc_autoneg = 0;
hw->phy.autoneg_advertised = 0;
hw->mac.link_speed = SPEED_10;
hw->mac.link_duplex = DUPLEX_HALF;
break;
case SPEED_10 + FULL_DUPLEX:
netdev_dbg(adapter->netdev, "Forcing to 10 Mbps Full Duplex\n");
hw->mac.autoneg = hw->mac.fc_autoneg = 0;
hw->phy.autoneg_advertised = 0;
hw->mac.link_speed = SPEED_10;
hw->mac.link_duplex = DUPLEX_FULL;
break;
case SPEED_100:
netdev_dbg(adapter->netdev,
"100 Mbps Speed specified without Duplex\n");
netdev_dbg(adapter->netdev,
"Using Autonegotiation at 100 Mbps only\n");
hw->mac.autoneg = hw->mac.fc_autoneg = 1;
hw->phy.autoneg_advertised = PHY_ADVERTISE_100_HALF |
PHY_ADVERTISE_100_FULL;
hw->mac.link_speed = SPEED_100;
hw->mac.link_duplex = DUPLEX_HALF;
break;
case SPEED_100 + HALF_DUPLEX:
netdev_dbg(adapter->netdev,
"Forcing to 100 Mbps Half Duplex\n");
hw->mac.autoneg = hw->mac.fc_autoneg = 0;
hw->phy.autoneg_advertised = 0;
hw->mac.link_speed = SPEED_100;
hw->mac.link_duplex = DUPLEX_HALF;
break;
case SPEED_100 + FULL_DUPLEX:
netdev_dbg(adapter->netdev,
"Forcing to 100 Mbps Full Duplex\n");
hw->mac.autoneg = hw->mac.fc_autoneg = 0;
hw->phy.autoneg_advertised = 0;
hw->mac.link_speed = SPEED_100;
hw->mac.link_duplex = DUPLEX_FULL;
break;
case SPEED_1000:
netdev_dbg(adapter->netdev,
"1000 Mbps Speed specified without Duplex\n");
goto full_duplex_only;
case SPEED_1000 + HALF_DUPLEX:
netdev_dbg(adapter->netdev,
"Half Duplex is not supported at 1000 Mbps\n");
/* fall through */
case SPEED_1000 + FULL_DUPLEX:
full_duplex_only:
netdev_dbg(adapter->netdev,
"Using Autonegotiation at 1000 Mbps Full Duplex only\n");
hw->mac.autoneg = hw->mac.fc_autoneg = 1;
hw->phy.autoneg_advertised = PHY_ADVERTISE_1000_FULL;
hw->mac.link_speed = SPEED_1000;
hw->mac.link_duplex = DUPLEX_FULL;
break;
default:
BUG();
}
}
/**
* pch_gbe_check_options - Range Checking for Command Line Parameters
* @adapter: Board private structure
*/
void pch_gbe_check_options(struct pch_gbe_adapter *adapter)
{
struct pch_gbe_hw *hw = &adapter->hw;
struct net_device *dev = adapter->netdev;
int val;
{ /* Transmit Descriptor Count */
static const struct pch_gbe_option opt = {
.type = range_option,
.name = "Transmit Descriptors",
.err = "using default of "
__MODULE_STRING(PCH_GBE_DEFAULT_TXD),
.def = PCH_GBE_DEFAULT_TXD,
.arg = { .r = { .min = PCH_GBE_MIN_TXD,
.max = PCH_GBE_MAX_TXD } }
};
struct pch_gbe_tx_ring *tx_ring = adapter->tx_ring;
tx_ring->count = TxDescriptors;
pch_gbe_validate_option(&tx_ring->count, &opt, adapter);
tx_ring->count = roundup(tx_ring->count,
PCH_GBE_TX_DESC_MULTIPLE);
}
{ /* Receive Descriptor Count */
static const struct pch_gbe_option opt = {
.type = range_option,
.name = "Receive Descriptors",
.err = "using default of "
__MODULE_STRING(PCH_GBE_DEFAULT_RXD),
.def = PCH_GBE_DEFAULT_RXD,
.arg = { .r = { .min = PCH_GBE_MIN_RXD,
.max = PCH_GBE_MAX_RXD } }
};
struct pch_gbe_rx_ring *rx_ring = adapter->rx_ring;
rx_ring->count = RxDescriptors;
pch_gbe_validate_option(&rx_ring->count, &opt, adapter);
rx_ring->count = roundup(rx_ring->count,
PCH_GBE_RX_DESC_MULTIPLE);
}
{ /* Checksum Offload Enable/Disable */
static const struct pch_gbe_option opt = {
.type = enable_option,
.name = "Checksum Offload",
.err = "defaulting to Enabled",
.def = PCH_GBE_DEFAULT_RX_CSUM
};
val = XsumRX;
pch_gbe_validate_option(&val, &opt, adapter);
if (!val)
dev->features &= ~NETIF_F_RXCSUM;
}
{ /* Checksum Offload Enable/Disable */
static const struct pch_gbe_option opt = {
.type = enable_option,
.name = "Checksum Offload",
.err = "defaulting to Enabled",
.def = PCH_GBE_DEFAULT_TX_CSUM
};
val = XsumTX;
pch_gbe_validate_option(&val, &opt, adapter);
if (!val)
dev->features &= ~NETIF_F_ALL_CSUM;
}
{ /* Flow Control */
static const struct pch_gbe_option opt = {
.type = list_option,
.name = "Flow Control",
.err = "reading default settings from EEPROM",
.def = PCH_GBE_FC_DEFAULT,
.arg = { .l = { .nr = (int)ARRAY_SIZE(fc_list),
.p = fc_list } }
};
int tmp = FlowControl;
pch_gbe_validate_option(&tmp, &opt, adapter);
hw->mac.fc = tmp;
}
pch_gbe_check_copper_options(adapter);
}
| gpl-2.0 |
RezaSR/android_kernel_asus_tf303cl | net/sched/act_csum.c | 2254 | 13778 | /*
* Checksum updating actions
*
* Copyright (c) 2010 Gregoire Baron <baronchon@n7mm.org>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
*/
#include <linux/types.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/netlink.h>
#include <net/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/skbuff.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <net/icmp.h>
#include <linux/icmpv6.h>
#include <linux/igmp.h>
#include <net/tcp.h>
#include <net/udp.h>
#include <net/ip6_checksum.h>
#include <net/act_api.h>
#include <linux/tc_act/tc_csum.h>
#include <net/tc_act/tc_csum.h>
#define CSUM_TAB_MASK 15
static struct tcf_common *tcf_csum_ht[CSUM_TAB_MASK + 1];
static u32 csum_idx_gen;
static DEFINE_RWLOCK(csum_lock);
static struct tcf_hashinfo csum_hash_info = {
.htab = tcf_csum_ht,
.hmask = CSUM_TAB_MASK,
.lock = &csum_lock,
};
static const struct nla_policy csum_policy[TCA_CSUM_MAX + 1] = {
[TCA_CSUM_PARMS] = { .len = sizeof(struct tc_csum), },
};
static int tcf_csum_init(struct net *n, struct nlattr *nla, struct nlattr *est,
struct tc_action *a, int ovr, int bind)
{
struct nlattr *tb[TCA_CSUM_MAX + 1];
struct tc_csum *parm;
struct tcf_common *pc;
struct tcf_csum *p;
int ret = 0, err;
if (nla == NULL)
return -EINVAL;
err = nla_parse_nested(tb, TCA_CSUM_MAX, nla, csum_policy);
if (err < 0)
return err;
if (tb[TCA_CSUM_PARMS] == NULL)
return -EINVAL;
parm = nla_data(tb[TCA_CSUM_PARMS]);
pc = tcf_hash_check(parm->index, a, bind, &csum_hash_info);
if (!pc) {
pc = tcf_hash_create(parm->index, est, a, sizeof(*p), bind,
&csum_idx_gen, &csum_hash_info);
if (IS_ERR(pc))
return PTR_ERR(pc);
p = to_tcf_csum(pc);
ret = ACT_P_CREATED;
} else {
p = to_tcf_csum(pc);
if (!ovr) {
tcf_hash_release(pc, bind, &csum_hash_info);
return -EEXIST;
}
}
spin_lock_bh(&p->tcf_lock);
p->tcf_action = parm->action;
p->update_flags = parm->update_flags;
spin_unlock_bh(&p->tcf_lock);
if (ret == ACT_P_CREATED)
tcf_hash_insert(pc, &csum_hash_info);
return ret;
}
static int tcf_csum_cleanup(struct tc_action *a, int bind)
{
struct tcf_csum *p = a->priv;
return tcf_hash_release(&p->common, bind, &csum_hash_info);
}
/**
* tcf_csum_skb_nextlayer - Get next layer pointer
* @skb: sk_buff to use
* @ihl: previous summed headers length
* @ipl: complete packet length
* @jhl: next header length
*
* Check the expected next layer availability in the specified sk_buff.
* Return the next layer pointer if pass, NULL otherwise.
*/
static void *tcf_csum_skb_nextlayer(struct sk_buff *skb,
unsigned int ihl, unsigned int ipl,
unsigned int jhl)
{
int ntkoff = skb_network_offset(skb);
int hl = ihl + jhl;
if (!pskb_may_pull(skb, ipl + ntkoff) || (ipl < hl) ||
(skb_cloned(skb) &&
!skb_clone_writable(skb, hl + ntkoff) &&
pskb_expand_head(skb, 0, 0, GFP_ATOMIC)))
return NULL;
else
return (void *)(skb_network_header(skb) + ihl);
}
static int tcf_csum_ipv4_icmp(struct sk_buff *skb,
unsigned int ihl, unsigned int ipl)
{
struct icmphdr *icmph;
icmph = tcf_csum_skb_nextlayer(skb, ihl, ipl, sizeof(*icmph));
if (icmph == NULL)
return 0;
icmph->checksum = 0;
skb->csum = csum_partial(icmph, ipl - ihl, 0);
icmph->checksum = csum_fold(skb->csum);
skb->ip_summed = CHECKSUM_NONE;
return 1;
}
static int tcf_csum_ipv4_igmp(struct sk_buff *skb,
unsigned int ihl, unsigned int ipl)
{
struct igmphdr *igmph;
igmph = tcf_csum_skb_nextlayer(skb, ihl, ipl, sizeof(*igmph));
if (igmph == NULL)
return 0;
igmph->csum = 0;
skb->csum = csum_partial(igmph, ipl - ihl, 0);
igmph->csum = csum_fold(skb->csum);
skb->ip_summed = CHECKSUM_NONE;
return 1;
}
static int tcf_csum_ipv6_icmp(struct sk_buff *skb,
unsigned int ihl, unsigned int ipl)
{
struct icmp6hdr *icmp6h;
const struct ipv6hdr *ip6h;
icmp6h = tcf_csum_skb_nextlayer(skb, ihl, ipl, sizeof(*icmp6h));
if (icmp6h == NULL)
return 0;
ip6h = ipv6_hdr(skb);
icmp6h->icmp6_cksum = 0;
skb->csum = csum_partial(icmp6h, ipl - ihl, 0);
icmp6h->icmp6_cksum = csum_ipv6_magic(&ip6h->saddr, &ip6h->daddr,
ipl - ihl, IPPROTO_ICMPV6,
skb->csum);
skb->ip_summed = CHECKSUM_NONE;
return 1;
}
static int tcf_csum_ipv4_tcp(struct sk_buff *skb,
unsigned int ihl, unsigned int ipl)
{
struct tcphdr *tcph;
const struct iphdr *iph;
tcph = tcf_csum_skb_nextlayer(skb, ihl, ipl, sizeof(*tcph));
if (tcph == NULL)
return 0;
iph = ip_hdr(skb);
tcph->check = 0;
skb->csum = csum_partial(tcph, ipl - ihl, 0);
tcph->check = tcp_v4_check(ipl - ihl,
iph->saddr, iph->daddr, skb->csum);
skb->ip_summed = CHECKSUM_NONE;
return 1;
}
static int tcf_csum_ipv6_tcp(struct sk_buff *skb,
unsigned int ihl, unsigned int ipl)
{
struct tcphdr *tcph;
const struct ipv6hdr *ip6h;
tcph = tcf_csum_skb_nextlayer(skb, ihl, ipl, sizeof(*tcph));
if (tcph == NULL)
return 0;
ip6h = ipv6_hdr(skb);
tcph->check = 0;
skb->csum = csum_partial(tcph, ipl - ihl, 0);
tcph->check = csum_ipv6_magic(&ip6h->saddr, &ip6h->daddr,
ipl - ihl, IPPROTO_TCP,
skb->csum);
skb->ip_summed = CHECKSUM_NONE;
return 1;
}
static int tcf_csum_ipv4_udp(struct sk_buff *skb,
unsigned int ihl, unsigned int ipl, int udplite)
{
struct udphdr *udph;
const struct iphdr *iph;
u16 ul;
/*
* Support both UDP and UDPLITE checksum algorithms, Don't use
* udph->len to get the real length without any protocol check,
* UDPLITE uses udph->len for another thing,
* Use iph->tot_len, or just ipl.
*/
udph = tcf_csum_skb_nextlayer(skb, ihl, ipl, sizeof(*udph));
if (udph == NULL)
return 0;
iph = ip_hdr(skb);
ul = ntohs(udph->len);
if (udplite || udph->check) {
udph->check = 0;
if (udplite) {
if (ul == 0)
skb->csum = csum_partial(udph, ipl - ihl, 0);
else if ((ul >= sizeof(*udph)) && (ul <= ipl - ihl))
skb->csum = csum_partial(udph, ul, 0);
else
goto ignore_obscure_skb;
} else {
if (ul != ipl - ihl)
goto ignore_obscure_skb;
skb->csum = csum_partial(udph, ul, 0);
}
udph->check = csum_tcpudp_magic(iph->saddr, iph->daddr,
ul, iph->protocol,
skb->csum);
if (!udph->check)
udph->check = CSUM_MANGLED_0;
}
skb->ip_summed = CHECKSUM_NONE;
ignore_obscure_skb:
return 1;
}
static int tcf_csum_ipv6_udp(struct sk_buff *skb,
unsigned int ihl, unsigned int ipl, int udplite)
{
struct udphdr *udph;
const struct ipv6hdr *ip6h;
u16 ul;
/*
* Support both UDP and UDPLITE checksum algorithms, Don't use
* udph->len to get the real length without any protocol check,
* UDPLITE uses udph->len for another thing,
* Use ip6h->payload_len + sizeof(*ip6h) ... , or just ipl.
*/
udph = tcf_csum_skb_nextlayer(skb, ihl, ipl, sizeof(*udph));
if (udph == NULL)
return 0;
ip6h = ipv6_hdr(skb);
ul = ntohs(udph->len);
udph->check = 0;
if (udplite) {
if (ul == 0)
skb->csum = csum_partial(udph, ipl - ihl, 0);
else if ((ul >= sizeof(*udph)) && (ul <= ipl - ihl))
skb->csum = csum_partial(udph, ul, 0);
else
goto ignore_obscure_skb;
} else {
if (ul != ipl - ihl)
goto ignore_obscure_skb;
skb->csum = csum_partial(udph, ul, 0);
}
udph->check = csum_ipv6_magic(&ip6h->saddr, &ip6h->daddr, ul,
udplite ? IPPROTO_UDPLITE : IPPROTO_UDP,
skb->csum);
if (!udph->check)
udph->check = CSUM_MANGLED_0;
skb->ip_summed = CHECKSUM_NONE;
ignore_obscure_skb:
return 1;
}
static int tcf_csum_ipv4(struct sk_buff *skb, u32 update_flags)
{
const struct iphdr *iph;
int ntkoff;
ntkoff = skb_network_offset(skb);
if (!pskb_may_pull(skb, sizeof(*iph) + ntkoff))
goto fail;
iph = ip_hdr(skb);
switch (iph->frag_off & htons(IP_OFFSET) ? 0 : iph->protocol) {
case IPPROTO_ICMP:
if (update_flags & TCA_CSUM_UPDATE_FLAG_ICMP)
if (!tcf_csum_ipv4_icmp(skb, iph->ihl * 4,
ntohs(iph->tot_len)))
goto fail;
break;
case IPPROTO_IGMP:
if (update_flags & TCA_CSUM_UPDATE_FLAG_IGMP)
if (!tcf_csum_ipv4_igmp(skb, iph->ihl * 4,
ntohs(iph->tot_len)))
goto fail;
break;
case IPPROTO_TCP:
if (update_flags & TCA_CSUM_UPDATE_FLAG_TCP)
if (!tcf_csum_ipv4_tcp(skb, iph->ihl * 4,
ntohs(iph->tot_len)))
goto fail;
break;
case IPPROTO_UDP:
if (update_flags & TCA_CSUM_UPDATE_FLAG_UDP)
if (!tcf_csum_ipv4_udp(skb, iph->ihl * 4,
ntohs(iph->tot_len), 0))
goto fail;
break;
case IPPROTO_UDPLITE:
if (update_flags & TCA_CSUM_UPDATE_FLAG_UDPLITE)
if (!tcf_csum_ipv4_udp(skb, iph->ihl * 4,
ntohs(iph->tot_len), 1))
goto fail;
break;
}
if (update_flags & TCA_CSUM_UPDATE_FLAG_IPV4HDR) {
if (skb_cloned(skb) &&
!skb_clone_writable(skb, sizeof(*iph) + ntkoff) &&
pskb_expand_head(skb, 0, 0, GFP_ATOMIC))
goto fail;
ip_send_check(ip_hdr(skb));
}
return 1;
fail:
return 0;
}
static int tcf_csum_ipv6_hopopts(struct ipv6_opt_hdr *ip6xh,
unsigned int ixhl, unsigned int *pl)
{
int off, len, optlen;
unsigned char *xh = (void *)ip6xh;
off = sizeof(*ip6xh);
len = ixhl - off;
while (len > 1) {
switch (xh[off]) {
case IPV6_TLV_PAD1:
optlen = 1;
break;
case IPV6_TLV_JUMBO:
optlen = xh[off + 1] + 2;
if (optlen != 6 || len < 6 || (off & 3) != 2)
/* wrong jumbo option length/alignment */
return 0;
*pl = ntohl(*(__be32 *)(xh + off + 2));
goto done;
default:
optlen = xh[off + 1] + 2;
if (optlen > len)
/* ignore obscure options */
goto done;
break;
}
off += optlen;
len -= optlen;
}
done:
return 1;
}
static int tcf_csum_ipv6(struct sk_buff *skb, u32 update_flags)
{
struct ipv6hdr *ip6h;
struct ipv6_opt_hdr *ip6xh;
unsigned int hl, ixhl;
unsigned int pl;
int ntkoff;
u8 nexthdr;
ntkoff = skb_network_offset(skb);
hl = sizeof(*ip6h);
if (!pskb_may_pull(skb, hl + ntkoff))
goto fail;
ip6h = ipv6_hdr(skb);
pl = ntohs(ip6h->payload_len);
nexthdr = ip6h->nexthdr;
do {
switch (nexthdr) {
case NEXTHDR_FRAGMENT:
goto ignore_skb;
case NEXTHDR_ROUTING:
case NEXTHDR_HOP:
case NEXTHDR_DEST:
if (!pskb_may_pull(skb, hl + sizeof(*ip6xh) + ntkoff))
goto fail;
ip6xh = (void *)(skb_network_header(skb) + hl);
ixhl = ipv6_optlen(ip6xh);
if (!pskb_may_pull(skb, hl + ixhl + ntkoff))
goto fail;
ip6xh = (void *)(skb_network_header(skb) + hl);
if ((nexthdr == NEXTHDR_HOP) &&
!(tcf_csum_ipv6_hopopts(ip6xh, ixhl, &pl)))
goto fail;
nexthdr = ip6xh->nexthdr;
hl += ixhl;
break;
case IPPROTO_ICMPV6:
if (update_flags & TCA_CSUM_UPDATE_FLAG_ICMP)
if (!tcf_csum_ipv6_icmp(skb,
hl, pl + sizeof(*ip6h)))
goto fail;
goto done;
case IPPROTO_TCP:
if (update_flags & TCA_CSUM_UPDATE_FLAG_TCP)
if (!tcf_csum_ipv6_tcp(skb,
hl, pl + sizeof(*ip6h)))
goto fail;
goto done;
case IPPROTO_UDP:
if (update_flags & TCA_CSUM_UPDATE_FLAG_UDP)
if (!tcf_csum_ipv6_udp(skb, hl,
pl + sizeof(*ip6h), 0))
goto fail;
goto done;
case IPPROTO_UDPLITE:
if (update_flags & TCA_CSUM_UPDATE_FLAG_UDPLITE)
if (!tcf_csum_ipv6_udp(skb, hl,
pl + sizeof(*ip6h), 1))
goto fail;
goto done;
default:
goto ignore_skb;
}
} while (pskb_may_pull(skb, hl + 1 + ntkoff));
done:
ignore_skb:
return 1;
fail:
return 0;
}
static int tcf_csum(struct sk_buff *skb,
const struct tc_action *a, struct tcf_result *res)
{
struct tcf_csum *p = a->priv;
int action;
u32 update_flags;
spin_lock(&p->tcf_lock);
p->tcf_tm.lastuse = jiffies;
bstats_update(&p->tcf_bstats, skb);
action = p->tcf_action;
update_flags = p->update_flags;
spin_unlock(&p->tcf_lock);
if (unlikely(action == TC_ACT_SHOT))
goto drop;
switch (skb->protocol) {
case cpu_to_be16(ETH_P_IP):
if (!tcf_csum_ipv4(skb, update_flags))
goto drop;
break;
case cpu_to_be16(ETH_P_IPV6):
if (!tcf_csum_ipv6(skb, update_flags))
goto drop;
break;
}
return action;
drop:
spin_lock(&p->tcf_lock);
p->tcf_qstats.drops++;
spin_unlock(&p->tcf_lock);
return TC_ACT_SHOT;
}
static int tcf_csum_dump(struct sk_buff *skb,
struct tc_action *a, int bind, int ref)
{
unsigned char *b = skb_tail_pointer(skb);
struct tcf_csum *p = a->priv;
struct tc_csum opt = {
.update_flags = p->update_flags,
.index = p->tcf_index,
.action = p->tcf_action,
.refcnt = p->tcf_refcnt - ref,
.bindcnt = p->tcf_bindcnt - bind,
};
struct tcf_t t;
if (nla_put(skb, TCA_CSUM_PARMS, sizeof(opt), &opt))
goto nla_put_failure;
t.install = jiffies_to_clock_t(jiffies - p->tcf_tm.install);
t.lastuse = jiffies_to_clock_t(jiffies - p->tcf_tm.lastuse);
t.expires = jiffies_to_clock_t(p->tcf_tm.expires);
if (nla_put(skb, TCA_CSUM_TM, sizeof(t), &t))
goto nla_put_failure;
return skb->len;
nla_put_failure:
nlmsg_trim(skb, b);
return -1;
}
static struct tc_action_ops act_csum_ops = {
.kind = "csum",
.hinfo = &csum_hash_info,
.type = TCA_ACT_CSUM,
.capab = TCA_CAP_NONE,
.owner = THIS_MODULE,
.act = tcf_csum,
.dump = tcf_csum_dump,
.cleanup = tcf_csum_cleanup,
.lookup = tcf_hash_search,
.init = tcf_csum_init,
.walk = tcf_generic_walker
};
MODULE_DESCRIPTION("Checksum updating actions");
MODULE_LICENSE("GPL");
static int __init csum_init_module(void)
{
return tcf_register_action(&act_csum_ops);
}
static void __exit csum_cleanup_module(void)
{
tcf_unregister_action(&act_csum_ops);
}
module_init(csum_init_module);
module_exit(csum_cleanup_module);
| gpl-2.0 |
shark147/m7-kernel | arch/m68k/kernel/sys_m68k.c | 3022 | 13827 | /*
* linux/arch/m68k/kernel/sys_m68k.c
*
* This file contains various random system calls that
* have a non-standard calling sequence on the Linux/m68k
* platform.
*/
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/fs.h>
#include <linux/smp.h>
#include <linux/sem.h>
#include <linux/msg.h>
#include <linux/shm.h>
#include <linux/stat.h>
#include <linux/syscalls.h>
#include <linux/mman.h>
#include <linux/file.h>
#include <linux/ipc.h>
#include <asm/setup.h>
#include <asm/uaccess.h>
#include <asm/cachectl.h>
#include <asm/traps.h>
#include <asm/page.h>
#include <asm/unistd.h>
#include <asm/cacheflush.h>
#ifdef CONFIG_MMU
#include <asm/tlb.h>
asmlinkage int do_page_fault(struct pt_regs *regs, unsigned long address,
unsigned long error_code);
asmlinkage long sys_mmap2(unsigned long addr, unsigned long len,
unsigned long prot, unsigned long flags,
unsigned long fd, unsigned long pgoff)
{
/*
* This is wrong for sun3 - there PAGE_SIZE is 8Kb,
* so we need to shift the argument down by 1; m68k mmap64(3)
* (in libc) expects the last argument of mmap2 in 4Kb units.
*/
return sys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);
}
/* Convert virtual (user) address VADDR to physical address PADDR */
#define virt_to_phys_040(vaddr) \
({ \
unsigned long _mmusr, _paddr; \
\
__asm__ __volatile__ (".chip 68040\n\t" \
"ptestr (%1)\n\t" \
"movec %%mmusr,%0\n\t" \
".chip 68k" \
: "=r" (_mmusr) \
: "a" (vaddr)); \
_paddr = (_mmusr & MMU_R_040) ? (_mmusr & PAGE_MASK) : 0; \
_paddr; \
})
static inline int
cache_flush_040 (unsigned long addr, int scope, int cache, unsigned long len)
{
unsigned long paddr, i;
switch (scope)
{
case FLUSH_SCOPE_ALL:
switch (cache)
{
case FLUSH_CACHE_DATA:
/* This nop is needed for some broken versions of the 68040. */
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpusha %dc\n\t"
".chip 68k");
break;
case FLUSH_CACHE_INSN:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpusha %ic\n\t"
".chip 68k");
break;
default:
case FLUSH_CACHE_BOTH:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpusha %bc\n\t"
".chip 68k");
break;
}
break;
case FLUSH_SCOPE_LINE:
/* Find the physical address of the first mapped page in the
address range. */
if ((paddr = virt_to_phys_040(addr))) {
paddr += addr & ~(PAGE_MASK | 15);
len = (len + (addr & 15) + 15) >> 4;
} else {
unsigned long tmp = PAGE_SIZE - (addr & ~PAGE_MASK);
if (len <= tmp)
return 0;
addr += tmp;
len -= tmp;
tmp = PAGE_SIZE;
for (;;)
{
if ((paddr = virt_to_phys_040(addr)))
break;
if (len <= tmp)
return 0;
addr += tmp;
len -= tmp;
}
len = (len + 15) >> 4;
}
i = (PAGE_SIZE - (paddr & ~PAGE_MASK)) >> 4;
while (len--)
{
switch (cache)
{
case FLUSH_CACHE_DATA:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpushl %%dc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
case FLUSH_CACHE_INSN:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpushl %%ic,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
default:
case FLUSH_CACHE_BOTH:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpushl %%bc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
}
if (!--i && len)
{
/*
* No need to page align here since it is done by
* virt_to_phys_040().
*/
addr += PAGE_SIZE;
i = PAGE_SIZE / 16;
/* Recompute physical address when crossing a page
boundary. */
for (;;)
{
if ((paddr = virt_to_phys_040(addr)))
break;
if (len <= i)
return 0;
len -= i;
addr += PAGE_SIZE;
}
}
else
paddr += 16;
}
break;
default:
case FLUSH_SCOPE_PAGE:
len += (addr & ~PAGE_MASK) + (PAGE_SIZE - 1);
for (len >>= PAGE_SHIFT; len--; addr += PAGE_SIZE)
{
if (!(paddr = virt_to_phys_040(addr)))
continue;
switch (cache)
{
case FLUSH_CACHE_DATA:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpushp %%dc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
case FLUSH_CACHE_INSN:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpushp %%ic,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
default:
case FLUSH_CACHE_BOTH:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpushp %%bc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
}
}
break;
}
return 0;
}
#define virt_to_phys_060(vaddr) \
({ \
unsigned long paddr; \
__asm__ __volatile__ (".chip 68060\n\t" \
"plpar (%0)\n\t" \
".chip 68k" \
: "=a" (paddr) \
: "0" (vaddr)); \
(paddr); /* XXX */ \
})
static inline int
cache_flush_060 (unsigned long addr, int scope, int cache, unsigned long len)
{
unsigned long paddr, i;
/*
* 68060 manual says:
* cpush %dc : flush DC, remains valid (with our %cacr setup)
* cpush %ic : invalidate IC
* cpush %bc : flush DC + invalidate IC
*/
switch (scope)
{
case FLUSH_SCOPE_ALL:
switch (cache)
{
case FLUSH_CACHE_DATA:
__asm__ __volatile__ (".chip 68060\n\t"
"cpusha %dc\n\t"
".chip 68k");
break;
case FLUSH_CACHE_INSN:
__asm__ __volatile__ (".chip 68060\n\t"
"cpusha %ic\n\t"
".chip 68k");
break;
default:
case FLUSH_CACHE_BOTH:
__asm__ __volatile__ (".chip 68060\n\t"
"cpusha %bc\n\t"
".chip 68k");
break;
}
break;
case FLUSH_SCOPE_LINE:
/* Find the physical address of the first mapped page in the
address range. */
len += addr & 15;
addr &= -16;
if (!(paddr = virt_to_phys_060(addr))) {
unsigned long tmp = PAGE_SIZE - (addr & ~PAGE_MASK);
if (len <= tmp)
return 0;
addr += tmp;
len -= tmp;
tmp = PAGE_SIZE;
for (;;)
{
if ((paddr = virt_to_phys_060(addr)))
break;
if (len <= tmp)
return 0;
addr += tmp;
len -= tmp;
}
}
len = (len + 15) >> 4;
i = (PAGE_SIZE - (paddr & ~PAGE_MASK)) >> 4;
while (len--)
{
switch (cache)
{
case FLUSH_CACHE_DATA:
__asm__ __volatile__ (".chip 68060\n\t"
"cpushl %%dc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
case FLUSH_CACHE_INSN:
__asm__ __volatile__ (".chip 68060\n\t"
"cpushl %%ic,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
default:
case FLUSH_CACHE_BOTH:
__asm__ __volatile__ (".chip 68060\n\t"
"cpushl %%bc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
}
if (!--i && len)
{
/*
* We just want to jump to the first cache line
* in the next page.
*/
addr += PAGE_SIZE;
addr &= PAGE_MASK;
i = PAGE_SIZE / 16;
/* Recompute physical address when crossing a page
boundary. */
for (;;)
{
if ((paddr = virt_to_phys_060(addr)))
break;
if (len <= i)
return 0;
len -= i;
addr += PAGE_SIZE;
}
}
else
paddr += 16;
}
break;
default:
case FLUSH_SCOPE_PAGE:
len += (addr & ~PAGE_MASK) + (PAGE_SIZE - 1);
addr &= PAGE_MASK; /* Workaround for bug in some
revisions of the 68060 */
for (len >>= PAGE_SHIFT; len--; addr += PAGE_SIZE)
{
if (!(paddr = virt_to_phys_060(addr)))
continue;
switch (cache)
{
case FLUSH_CACHE_DATA:
__asm__ __volatile__ (".chip 68060\n\t"
"cpushp %%dc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
case FLUSH_CACHE_INSN:
__asm__ __volatile__ (".chip 68060\n\t"
"cpushp %%ic,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
default:
case FLUSH_CACHE_BOTH:
__asm__ __volatile__ (".chip 68060\n\t"
"cpushp %%bc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
}
}
break;
}
return 0;
}
/* sys_cacheflush -- flush (part of) the processor cache. */
asmlinkage int
sys_cacheflush (unsigned long addr, int scope, int cache, unsigned long len)
{
struct vm_area_struct *vma;
int ret = -EINVAL;
if (scope < FLUSH_SCOPE_LINE || scope > FLUSH_SCOPE_ALL ||
cache & ~FLUSH_CACHE_BOTH)
goto out;
if (scope == FLUSH_SCOPE_ALL) {
/* Only the superuser may explicitly flush the whole cache. */
ret = -EPERM;
if (!capable(CAP_SYS_ADMIN))
goto out;
} else {
/*
* Verify that the specified address region actually belongs
* to this process.
*/
vma = find_vma (current->mm, addr);
ret = -EINVAL;
/* Check for overflow. */
if (addr + len < addr)
goto out;
if (vma == NULL || addr < vma->vm_start || addr + len > vma->vm_end)
goto out;
}
if (CPU_IS_020_OR_030) {
if (scope == FLUSH_SCOPE_LINE && len < 256) {
unsigned long cacr;
__asm__ ("movec %%cacr, %0" : "=r" (cacr));
if (cache & FLUSH_CACHE_INSN)
cacr |= 4;
if (cache & FLUSH_CACHE_DATA)
cacr |= 0x400;
len >>= 2;
while (len--) {
__asm__ __volatile__ ("movec %1, %%caar\n\t"
"movec %0, %%cacr"
: /* no outputs */
: "r" (cacr), "r" (addr));
addr += 4;
}
} else {
/* Flush the whole cache, even if page granularity requested. */
unsigned long cacr;
__asm__ ("movec %%cacr, %0" : "=r" (cacr));
if (cache & FLUSH_CACHE_INSN)
cacr |= 8;
if (cache & FLUSH_CACHE_DATA)
cacr |= 0x800;
__asm__ __volatile__ ("movec %0, %%cacr" : : "r" (cacr));
}
ret = 0;
goto out;
} else {
/*
* 040 or 060: don't blindly trust 'scope', someone could
* try to flush a few megs of memory.
*/
if (len>=3*PAGE_SIZE && scope<FLUSH_SCOPE_PAGE)
scope=FLUSH_SCOPE_PAGE;
if (len>=10*PAGE_SIZE && scope<FLUSH_SCOPE_ALL)
scope=FLUSH_SCOPE_ALL;
if (CPU_IS_040) {
ret = cache_flush_040 (addr, scope, cache, len);
} else if (CPU_IS_060) {
ret = cache_flush_060 (addr, scope, cache, len);
}
}
out:
return ret;
}
/* This syscall gets its arguments in A0 (mem), D2 (oldval) and
D1 (newval). */
asmlinkage int
sys_atomic_cmpxchg_32(unsigned long newval, int oldval, int d3, int d4, int d5,
unsigned long __user * mem)
{
/* This was borrowed from ARM's implementation. */
for (;;) {
struct mm_struct *mm = current->mm;
pgd_t *pgd;
pmd_t *pmd;
pte_t *pte;
spinlock_t *ptl;
unsigned long mem_value;
down_read(&mm->mmap_sem);
pgd = pgd_offset(mm, (unsigned long)mem);
if (!pgd_present(*pgd))
goto bad_access;
pmd = pmd_offset(pgd, (unsigned long)mem);
if (!pmd_present(*pmd))
goto bad_access;
pte = pte_offset_map_lock(mm, pmd, (unsigned long)mem, &ptl);
if (!pte_present(*pte) || !pte_dirty(*pte)
|| !pte_write(*pte)) {
pte_unmap_unlock(pte, ptl);
goto bad_access;
}
/*
* No need to check for EFAULT; we know that the page is
* present and writable.
*/
__get_user(mem_value, mem);
if (mem_value == oldval)
__put_user(newval, mem);
pte_unmap_unlock(pte, ptl);
up_read(&mm->mmap_sem);
return mem_value;
bad_access:
up_read(&mm->mmap_sem);
/* This is not necessarily a bad access, we can get here if
a memory we're trying to write to should be copied-on-write.
Make the kernel do the necessary page stuff, then re-iterate.
Simulate a write access fault to do that. */
{
/* The first argument of the function corresponds to
D1, which is the first field of struct pt_regs. */
struct pt_regs *fp = (struct pt_regs *)&newval;
/* '3' is an RMW flag. */
if (do_page_fault(fp, (unsigned long)mem, 3))
/* If the do_page_fault() failed, we don't
have anything meaningful to return.
There should be a SIGSEGV pending for
the process. */
return 0xdeadbeef;
}
}
}
#else
/* sys_cacheflush -- flush (part of) the processor cache. */
asmlinkage int
sys_cacheflush (unsigned long addr, int scope, int cache, unsigned long len)
{
flush_cache_all();
return 0;
}
/* This syscall gets its arguments in A0 (mem), D2 (oldval) and
D1 (newval). */
asmlinkage int
sys_atomic_cmpxchg_32(unsigned long newval, int oldval, int d3, int d4, int d5,
unsigned long __user * mem)
{
struct mm_struct *mm = current->mm;
unsigned long mem_value;
down_read(&mm->mmap_sem);
mem_value = *mem;
if (mem_value == oldval)
*mem = newval;
up_read(&mm->mmap_sem);
return mem_value;
}
#endif /* CONFIG_MMU */
asmlinkage int sys_getpagesize(void)
{
return PAGE_SIZE;
}
/*
* Do a system call from kernel instead of calling sys_execve so we
* end up with proper pt_regs.
*/
int kernel_execve(const char *filename,
const char *const argv[],
const char *const envp[])
{
register long __res asm ("%d0") = __NR_execve;
register long __a asm ("%d1") = (long)(filename);
register long __b asm ("%d2") = (long)(argv);
register long __c asm ("%d3") = (long)(envp);
asm volatile ("trap #0" : "+d" (__res)
: "d" (__a), "d" (__b), "d" (__c));
return __res;
}
asmlinkage unsigned long sys_get_thread_area(void)
{
return current_thread_info()->tp_value;
}
asmlinkage int sys_set_thread_area(unsigned long tp)
{
current_thread_info()->tp_value = tp;
return 0;
}
asmlinkage int sys_atomic_barrier(void)
{
/* no code needed for uniprocs */
return 0;
}
| gpl-2.0 |
S4WRXTTCS/BeagleXM-Test | drivers/scsi/bnx2fc/bnx2fc_fcoe.c | 4302 | 65725 | /* bnx2fc_fcoe.c: Broadcom NetXtreme II Linux FCoE offload driver.
* This file contains the code that interacts with libfc, libfcoe,
* cnic modules to create FCoE instances, send/receive non-offloaded
* FIP/FCoE packets, listen to link events etc.
*
* Copyright (c) 2008 - 2011 Broadcom 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.
*
* Written by: Bhanu Prakash Gollapudi (bprakash@broadcom.com)
*/
#include "bnx2fc.h"
static struct list_head adapter_list;
static struct list_head if_list;
static u32 adapter_count;
static DEFINE_MUTEX(bnx2fc_dev_lock);
DEFINE_PER_CPU(struct bnx2fc_percpu_s, bnx2fc_percpu);
#define DRV_MODULE_NAME "bnx2fc"
#define DRV_MODULE_VERSION BNX2FC_VERSION
#define DRV_MODULE_RELDATE "Jan 22, 2011"
static char version[] __devinitdata =
"Broadcom NetXtreme II FCoE Driver " DRV_MODULE_NAME \
" v" DRV_MODULE_VERSION " (" DRV_MODULE_RELDATE ")\n";
MODULE_AUTHOR("Bhanu Prakash Gollapudi <bprakash@broadcom.com>");
MODULE_DESCRIPTION("Broadcom NetXtreme II BCM57710 FCoE Driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_MODULE_VERSION);
#define BNX2FC_MAX_QUEUE_DEPTH 256
#define BNX2FC_MIN_QUEUE_DEPTH 32
#define FCOE_WORD_TO_BYTE 4
static struct scsi_transport_template *bnx2fc_transport_template;
static struct scsi_transport_template *bnx2fc_vport_xport_template;
struct workqueue_struct *bnx2fc_wq;
/* bnx2fc structure needs only one instance of the fcoe_percpu_s structure.
* Here the io threads are per cpu but the l2 thread is just one
*/
struct fcoe_percpu_s bnx2fc_global;
DEFINE_SPINLOCK(bnx2fc_global_lock);
static struct cnic_ulp_ops bnx2fc_cnic_cb;
static struct libfc_function_template bnx2fc_libfc_fcn_templ;
static struct scsi_host_template bnx2fc_shost_template;
static struct fc_function_template bnx2fc_transport_function;
static struct fc_function_template bnx2fc_vport_xport_function;
static int bnx2fc_create(struct net_device *netdev, enum fip_state fip_mode);
static void __bnx2fc_destroy(struct bnx2fc_interface *interface);
static int bnx2fc_destroy(struct net_device *net_device);
static int bnx2fc_enable(struct net_device *netdev);
static int bnx2fc_disable(struct net_device *netdev);
static void bnx2fc_recv_frame(struct sk_buff *skb);
static void bnx2fc_start_disc(struct bnx2fc_interface *interface);
static int bnx2fc_shost_config(struct fc_lport *lport, struct device *dev);
static int bnx2fc_lport_config(struct fc_lport *lport);
static int bnx2fc_em_config(struct fc_lport *lport);
static int bnx2fc_bind_adapter_devices(struct bnx2fc_hba *hba);
static void bnx2fc_unbind_adapter_devices(struct bnx2fc_hba *hba);
static int bnx2fc_bind_pcidev(struct bnx2fc_hba *hba);
static void bnx2fc_unbind_pcidev(struct bnx2fc_hba *hba);
static struct fc_lport *bnx2fc_if_create(struct bnx2fc_interface *interface,
struct device *parent, int npiv);
static void bnx2fc_destroy_work(struct work_struct *work);
static struct bnx2fc_hba *bnx2fc_hba_lookup(struct net_device *phys_dev);
static struct bnx2fc_interface *bnx2fc_interface_lookup(struct net_device
*phys_dev);
static inline void bnx2fc_interface_put(struct bnx2fc_interface *interface);
static struct bnx2fc_hba *bnx2fc_find_hba_for_cnic(struct cnic_dev *cnic);
static int bnx2fc_fw_init(struct bnx2fc_hba *hba);
static void bnx2fc_fw_destroy(struct bnx2fc_hba *hba);
static void bnx2fc_port_shutdown(struct fc_lport *lport);
static void bnx2fc_stop(struct bnx2fc_interface *interface);
static int __init bnx2fc_mod_init(void);
static void __exit bnx2fc_mod_exit(void);
unsigned int bnx2fc_debug_level;
module_param_named(debug_logging, bnx2fc_debug_level, int, S_IRUGO|S_IWUSR);
static int bnx2fc_cpu_callback(struct notifier_block *nfb,
unsigned long action, void *hcpu);
/* notification function for CPU hotplug events */
static struct notifier_block bnx2fc_cpu_notifier = {
.notifier_call = bnx2fc_cpu_callback,
};
static inline struct net_device *bnx2fc_netdev(const struct fc_lport *lport)
{
return ((struct bnx2fc_interface *)
((struct fcoe_port *)lport_priv(lport))->priv)->netdev;
}
/**
* bnx2fc_get_lesb() - Fill the FCoE Link Error Status Block
* @lport: the local port
* @fc_lesb: the link error status block
*/
static void bnx2fc_get_lesb(struct fc_lport *lport,
struct fc_els_lesb *fc_lesb)
{
struct net_device *netdev = bnx2fc_netdev(lport);
__fcoe_get_lesb(lport, fc_lesb, netdev);
}
static void bnx2fc_clean_rx_queue(struct fc_lport *lp)
{
struct fcoe_percpu_s *bg;
struct fcoe_rcv_info *fr;
struct sk_buff_head *list;
struct sk_buff *skb, *next;
struct sk_buff *head;
bg = &bnx2fc_global;
spin_lock_bh(&bg->fcoe_rx_list.lock);
list = &bg->fcoe_rx_list;
head = list->next;
for (skb = head; skb != (struct sk_buff *)list;
skb = next) {
next = skb->next;
fr = fcoe_dev_from_skb(skb);
if (fr->fr_dev == lp) {
__skb_unlink(skb, list);
kfree_skb(skb);
}
}
spin_unlock_bh(&bg->fcoe_rx_list.lock);
}
int bnx2fc_get_paged_crc_eof(struct sk_buff *skb, int tlen)
{
int rc;
spin_lock(&bnx2fc_global_lock);
rc = fcoe_get_paged_crc_eof(skb, tlen, &bnx2fc_global);
spin_unlock(&bnx2fc_global_lock);
return rc;
}
static void bnx2fc_abort_io(struct fc_lport *lport)
{
/*
* This function is no-op for bnx2fc, but we do
* not want to leave it as NULL either, as libfc
* can call the default function which is
* fc_fcp_abort_io.
*/
}
static void bnx2fc_cleanup(struct fc_lport *lport)
{
struct fcoe_port *port = lport_priv(lport);
struct bnx2fc_interface *interface = port->priv;
struct bnx2fc_hba *hba = interface->hba;
struct bnx2fc_rport *tgt;
int i;
BNX2FC_MISC_DBG("Entered %s\n", __func__);
mutex_lock(&hba->hba_mutex);
spin_lock_bh(&hba->hba_lock);
for (i = 0; i < BNX2FC_NUM_MAX_SESS; i++) {
tgt = hba->tgt_ofld_list[i];
if (tgt) {
/* Cleanup IOs belonging to requested vport */
if (tgt->port == port) {
spin_unlock_bh(&hba->hba_lock);
BNX2FC_TGT_DBG(tgt, "flush/cleanup\n");
bnx2fc_flush_active_ios(tgt);
spin_lock_bh(&hba->hba_lock);
}
}
}
spin_unlock_bh(&hba->hba_lock);
mutex_unlock(&hba->hba_mutex);
}
static int bnx2fc_xmit_l2_frame(struct bnx2fc_rport *tgt,
struct fc_frame *fp)
{
struct fc_rport_priv *rdata = tgt->rdata;
struct fc_frame_header *fh;
int rc = 0;
fh = fc_frame_header_get(fp);
BNX2FC_TGT_DBG(tgt, "Xmit L2 frame rport = 0x%x, oxid = 0x%x, "
"r_ctl = 0x%x\n", rdata->ids.port_id,
ntohs(fh->fh_ox_id), fh->fh_r_ctl);
if ((fh->fh_type == FC_TYPE_ELS) &&
(fh->fh_r_ctl == FC_RCTL_ELS_REQ)) {
switch (fc_frame_payload_op(fp)) {
case ELS_ADISC:
rc = bnx2fc_send_adisc(tgt, fp);
break;
case ELS_LOGO:
rc = bnx2fc_send_logo(tgt, fp);
break;
case ELS_RLS:
rc = bnx2fc_send_rls(tgt, fp);
break;
default:
break;
}
} else if ((fh->fh_type == FC_TYPE_BLS) &&
(fh->fh_r_ctl == FC_RCTL_BA_ABTS))
BNX2FC_TGT_DBG(tgt, "ABTS frame\n");
else {
BNX2FC_TGT_DBG(tgt, "Send L2 frame type 0x%x "
"rctl 0x%x thru non-offload path\n",
fh->fh_type, fh->fh_r_ctl);
return -ENODEV;
}
if (rc)
return -ENOMEM;
else
return 0;
}
/**
* bnx2fc_xmit - bnx2fc's FCoE frame transmit function
*
* @lport: the associated local port
* @fp: the fc_frame to be transmitted
*/
static int bnx2fc_xmit(struct fc_lport *lport, struct fc_frame *fp)
{
struct ethhdr *eh;
struct fcoe_crc_eof *cp;
struct sk_buff *skb;
struct fc_frame_header *fh;
struct bnx2fc_interface *interface;
struct bnx2fc_hba *hba;
struct fcoe_port *port;
struct fcoe_hdr *hp;
struct bnx2fc_rport *tgt;
struct fcoe_dev_stats *stats;
u8 sof, eof;
u32 crc;
unsigned int hlen, tlen, elen;
int wlen, rc = 0;
port = (struct fcoe_port *)lport_priv(lport);
interface = port->priv;
hba = interface->hba;
fh = fc_frame_header_get(fp);
skb = fp_skb(fp);
if (!lport->link_up) {
BNX2FC_HBA_DBG(lport, "bnx2fc_xmit link down\n");
kfree_skb(skb);
return 0;
}
if (unlikely(fh->fh_r_ctl == FC_RCTL_ELS_REQ)) {
if (!interface->ctlr.sel_fcf) {
BNX2FC_HBA_DBG(lport, "FCF not selected yet!\n");
kfree_skb(skb);
return -EINVAL;
}
if (fcoe_ctlr_els_send(&interface->ctlr, lport, skb))
return 0;
}
sof = fr_sof(fp);
eof = fr_eof(fp);
/*
* Snoop the frame header to check if the frame is for
* an offloaded session
*/
/*
* tgt_ofld_list access is synchronized using
* both hba mutex and hba lock. Atleast hba mutex or
* hba lock needs to be held for read access.
*/
spin_lock_bh(&hba->hba_lock);
tgt = bnx2fc_tgt_lookup(port, ntoh24(fh->fh_d_id));
if (tgt && (test_bit(BNX2FC_FLAG_SESSION_READY, &tgt->flags))) {
/* This frame is for offloaded session */
BNX2FC_HBA_DBG(lport, "xmit: Frame is for offloaded session "
"port_id = 0x%x\n", ntoh24(fh->fh_d_id));
spin_unlock_bh(&hba->hba_lock);
rc = bnx2fc_xmit_l2_frame(tgt, fp);
if (rc != -ENODEV) {
kfree_skb(skb);
return rc;
}
} else {
spin_unlock_bh(&hba->hba_lock);
}
elen = sizeof(struct ethhdr);
hlen = sizeof(struct fcoe_hdr);
tlen = sizeof(struct fcoe_crc_eof);
wlen = (skb->len - tlen + sizeof(crc)) / FCOE_WORD_TO_BYTE;
skb->ip_summed = CHECKSUM_NONE;
crc = fcoe_fc_crc(fp);
/* copy port crc and eof to the skb buff */
if (skb_is_nonlinear(skb)) {
skb_frag_t *frag;
if (bnx2fc_get_paged_crc_eof(skb, tlen)) {
kfree_skb(skb);
return -ENOMEM;
}
frag = &skb_shinfo(skb)->frags[skb_shinfo(skb)->nr_frags - 1];
cp = kmap_atomic(skb_frag_page(frag)) + frag->page_offset;
} else {
cp = (struct fcoe_crc_eof *)skb_put(skb, tlen);
}
memset(cp, 0, sizeof(*cp));
cp->fcoe_eof = eof;
cp->fcoe_crc32 = cpu_to_le32(~crc);
if (skb_is_nonlinear(skb)) {
kunmap_atomic(cp);
cp = NULL;
}
/* adjust skb network/transport offsets to match mac/fcoe/port */
skb_push(skb, elen + hlen);
skb_reset_mac_header(skb);
skb_reset_network_header(skb);
skb->mac_len = elen;
skb->protocol = htons(ETH_P_FCOE);
skb->dev = interface->netdev;
/* fill up mac and fcoe headers */
eh = eth_hdr(skb);
eh->h_proto = htons(ETH_P_FCOE);
if (interface->ctlr.map_dest)
fc_fcoe_set_mac(eh->h_dest, fh->fh_d_id);
else
/* insert GW address */
memcpy(eh->h_dest, interface->ctlr.dest_addr, ETH_ALEN);
if (unlikely(interface->ctlr.flogi_oxid != FC_XID_UNKNOWN))
memcpy(eh->h_source, interface->ctlr.ctl_src_addr, ETH_ALEN);
else
memcpy(eh->h_source, port->data_src_addr, ETH_ALEN);
hp = (struct fcoe_hdr *)(eh + 1);
memset(hp, 0, sizeof(*hp));
if (FC_FCOE_VER)
FC_FCOE_ENCAPS_VER(hp, FC_FCOE_VER);
hp->fcoe_sof = sof;
/* fcoe lso, mss is in max_payload which is non-zero for FCP data */
if (lport->seq_offload && fr_max_payload(fp)) {
skb_shinfo(skb)->gso_type = SKB_GSO_FCOE;
skb_shinfo(skb)->gso_size = fr_max_payload(fp);
} else {
skb_shinfo(skb)->gso_type = 0;
skb_shinfo(skb)->gso_size = 0;
}
/*update tx stats */
stats = per_cpu_ptr(lport->dev_stats, get_cpu());
stats->TxFrames++;
stats->TxWords += wlen;
put_cpu();
/* send down to lld */
fr_dev(fp) = lport;
if (port->fcoe_pending_queue.qlen)
fcoe_check_wait_queue(lport, skb);
else if (fcoe_start_io(skb))
fcoe_check_wait_queue(lport, skb);
return 0;
}
/**
* bnx2fc_rcv - This is bnx2fc's receive function called by NET_RX_SOFTIRQ
*
* @skb: the receive socket buffer
* @dev: associated net device
* @ptype: context
* @olddev: last device
*
* This function receives the packet and builds FC frame and passes it up
*/
static int bnx2fc_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *ptype, struct net_device *olddev)
{
struct fc_lport *lport;
struct bnx2fc_interface *interface;
struct fc_frame_header *fh;
struct fcoe_rcv_info *fr;
struct fcoe_percpu_s *bg;
unsigned short oxid;
interface = container_of(ptype, struct bnx2fc_interface,
fcoe_packet_type);
lport = interface->ctlr.lp;
if (unlikely(lport == NULL)) {
printk(KERN_ERR PFX "bnx2fc_rcv: lport is NULL\n");
goto err;
}
if (unlikely(eth_hdr(skb)->h_proto != htons(ETH_P_FCOE))) {
printk(KERN_ERR PFX "bnx2fc_rcv: Wrong FC type frame\n");
goto err;
}
/*
* Check for minimum frame length, and make sure required FCoE
* and FC headers are pulled into the linear data area.
*/
if (unlikely((skb->len < FCOE_MIN_FRAME) ||
!pskb_may_pull(skb, FCOE_HEADER_LEN)))
goto err;
skb_set_transport_header(skb, sizeof(struct fcoe_hdr));
fh = (struct fc_frame_header *) skb_transport_header(skb);
oxid = ntohs(fh->fh_ox_id);
fr = fcoe_dev_from_skb(skb);
fr->fr_dev = lport;
bg = &bnx2fc_global;
spin_lock(&bg->fcoe_rx_list.lock);
__skb_queue_tail(&bg->fcoe_rx_list, skb);
if (bg->fcoe_rx_list.qlen == 1)
wake_up_process(bg->thread);
spin_unlock(&bg->fcoe_rx_list.lock);
return 0;
err:
kfree_skb(skb);
return -1;
}
static int bnx2fc_l2_rcv_thread(void *arg)
{
struct fcoe_percpu_s *bg = arg;
struct sk_buff *skb;
set_user_nice(current, -20);
set_current_state(TASK_INTERRUPTIBLE);
while (!kthread_should_stop()) {
schedule();
spin_lock_bh(&bg->fcoe_rx_list.lock);
while ((skb = __skb_dequeue(&bg->fcoe_rx_list)) != NULL) {
spin_unlock_bh(&bg->fcoe_rx_list.lock);
bnx2fc_recv_frame(skb);
spin_lock_bh(&bg->fcoe_rx_list.lock);
}
__set_current_state(TASK_INTERRUPTIBLE);
spin_unlock_bh(&bg->fcoe_rx_list.lock);
}
__set_current_state(TASK_RUNNING);
return 0;
}
static void bnx2fc_recv_frame(struct sk_buff *skb)
{
u32 fr_len;
struct fc_lport *lport;
struct fcoe_rcv_info *fr;
struct fcoe_dev_stats *stats;
struct fc_frame_header *fh;
struct fcoe_crc_eof crc_eof;
struct fc_frame *fp;
struct fc_lport *vn_port;
struct fcoe_port *port;
u8 *mac = NULL;
u8 *dest_mac = NULL;
struct fcoe_hdr *hp;
fr = fcoe_dev_from_skb(skb);
lport = fr->fr_dev;
if (unlikely(lport == NULL)) {
printk(KERN_ERR PFX "Invalid lport struct\n");
kfree_skb(skb);
return;
}
if (skb_is_nonlinear(skb))
skb_linearize(skb);
mac = eth_hdr(skb)->h_source;
dest_mac = eth_hdr(skb)->h_dest;
/* Pull the header */
hp = (struct fcoe_hdr *) skb_network_header(skb);
fh = (struct fc_frame_header *) skb_transport_header(skb);
skb_pull(skb, sizeof(struct fcoe_hdr));
fr_len = skb->len - sizeof(struct fcoe_crc_eof);
stats = per_cpu_ptr(lport->dev_stats, get_cpu());
stats->RxFrames++;
stats->RxWords += fr_len / FCOE_WORD_TO_BYTE;
fp = (struct fc_frame *)skb;
fc_frame_init(fp);
fr_dev(fp) = lport;
fr_sof(fp) = hp->fcoe_sof;
if (skb_copy_bits(skb, fr_len, &crc_eof, sizeof(crc_eof))) {
put_cpu();
kfree_skb(skb);
return;
}
fr_eof(fp) = crc_eof.fcoe_eof;
fr_crc(fp) = crc_eof.fcoe_crc32;
if (pskb_trim(skb, fr_len)) {
put_cpu();
kfree_skb(skb);
return;
}
fh = fc_frame_header_get(fp);
vn_port = fc_vport_id_lookup(lport, ntoh24(fh->fh_d_id));
if (vn_port) {
port = lport_priv(vn_port);
if (compare_ether_addr(port->data_src_addr, dest_mac)
!= 0) {
BNX2FC_HBA_DBG(lport, "fpma mismatch\n");
put_cpu();
kfree_skb(skb);
return;
}
}
if (fh->fh_r_ctl == FC_RCTL_DD_SOL_DATA &&
fh->fh_type == FC_TYPE_FCP) {
/* Drop FCP data. We dont this in L2 path */
put_cpu();
kfree_skb(skb);
return;
}
if (fh->fh_r_ctl == FC_RCTL_ELS_REQ &&
fh->fh_type == FC_TYPE_ELS) {
switch (fc_frame_payload_op(fp)) {
case ELS_LOGO:
if (ntoh24(fh->fh_s_id) == FC_FID_FLOGI) {
/* drop non-FIP LOGO */
put_cpu();
kfree_skb(skb);
return;
}
break;
}
}
if (fh->fh_r_ctl == FC_RCTL_BA_ABTS) {
/* Drop incoming ABTS */
put_cpu();
kfree_skb(skb);
return;
}
if (le32_to_cpu(fr_crc(fp)) !=
~crc32(~0, skb->data, fr_len)) {
if (stats->InvalidCRCCount < 5)
printk(KERN_WARNING PFX "dropping frame with "
"CRC error\n");
stats->InvalidCRCCount++;
put_cpu();
kfree_skb(skb);
return;
}
put_cpu();
fc_exch_recv(lport, fp);
}
/**
* bnx2fc_percpu_io_thread - thread per cpu for ios
*
* @arg: ptr to bnx2fc_percpu_info structure
*/
int bnx2fc_percpu_io_thread(void *arg)
{
struct bnx2fc_percpu_s *p = arg;
struct bnx2fc_work *work, *tmp;
LIST_HEAD(work_list);
set_user_nice(current, -20);
set_current_state(TASK_INTERRUPTIBLE);
while (!kthread_should_stop()) {
schedule();
spin_lock_bh(&p->fp_work_lock);
while (!list_empty(&p->work_list)) {
list_splice_init(&p->work_list, &work_list);
spin_unlock_bh(&p->fp_work_lock);
list_for_each_entry_safe(work, tmp, &work_list, list) {
list_del_init(&work->list);
bnx2fc_process_cq_compl(work->tgt, work->wqe);
kfree(work);
}
spin_lock_bh(&p->fp_work_lock);
}
__set_current_state(TASK_INTERRUPTIBLE);
spin_unlock_bh(&p->fp_work_lock);
}
__set_current_state(TASK_RUNNING);
return 0;
}
static struct fc_host_statistics *bnx2fc_get_host_stats(struct Scsi_Host *shost)
{
struct fc_host_statistics *bnx2fc_stats;
struct fc_lport *lport = shost_priv(shost);
struct fcoe_port *port = lport_priv(lport);
struct bnx2fc_interface *interface = port->priv;
struct bnx2fc_hba *hba = interface->hba;
struct fcoe_statistics_params *fw_stats;
int rc = 0;
fw_stats = (struct fcoe_statistics_params *)hba->stats_buffer;
if (!fw_stats)
return NULL;
bnx2fc_stats = fc_get_host_stats(shost);
init_completion(&hba->stat_req_done);
if (bnx2fc_send_stat_req(hba))
return bnx2fc_stats;
rc = wait_for_completion_timeout(&hba->stat_req_done, (2 * HZ));
if (!rc) {
BNX2FC_HBA_DBG(lport, "FW stat req timed out\n");
return bnx2fc_stats;
}
bnx2fc_stats->invalid_crc_count += fw_stats->rx_stat2.fc_crc_cnt;
bnx2fc_stats->tx_frames += fw_stats->tx_stat.fcoe_tx_pkt_cnt;
bnx2fc_stats->tx_words += (fw_stats->tx_stat.fcoe_tx_byte_cnt) / 4;
bnx2fc_stats->rx_frames += fw_stats->rx_stat0.fcoe_rx_pkt_cnt;
bnx2fc_stats->rx_words += (fw_stats->rx_stat0.fcoe_rx_byte_cnt) / 4;
bnx2fc_stats->dumped_frames = 0;
bnx2fc_stats->lip_count = 0;
bnx2fc_stats->nos_count = 0;
bnx2fc_stats->loss_of_sync_count = 0;
bnx2fc_stats->loss_of_signal_count = 0;
bnx2fc_stats->prim_seq_protocol_err_count = 0;
return bnx2fc_stats;
}
static int bnx2fc_shost_config(struct fc_lport *lport, struct device *dev)
{
struct fcoe_port *port = lport_priv(lport);
struct bnx2fc_interface *interface = port->priv;
struct Scsi_Host *shost = lport->host;
int rc = 0;
shost->max_cmd_len = BNX2FC_MAX_CMD_LEN;
shost->max_lun = BNX2FC_MAX_LUN;
shost->max_id = BNX2FC_MAX_FCP_TGT;
shost->max_channel = 0;
if (lport->vport)
shost->transportt = bnx2fc_vport_xport_template;
else
shost->transportt = bnx2fc_transport_template;
/* Add the new host to SCSI-ml */
rc = scsi_add_host(lport->host, dev);
if (rc) {
printk(KERN_ERR PFX "Error on scsi_add_host\n");
return rc;
}
if (!lport->vport)
fc_host_max_npiv_vports(lport->host) = USHRT_MAX;
sprintf(fc_host_symbolic_name(lport->host), "%s v%s over %s",
BNX2FC_NAME, BNX2FC_VERSION,
interface->netdev->name);
return 0;
}
static void bnx2fc_link_speed_update(struct fc_lport *lport)
{
struct fcoe_port *port = lport_priv(lport);
struct bnx2fc_interface *interface = port->priv;
struct net_device *netdev = interface->netdev;
struct ethtool_cmd ecmd;
if (!__ethtool_get_settings(netdev, &ecmd)) {
lport->link_supported_speeds &=
~(FC_PORTSPEED_1GBIT | FC_PORTSPEED_10GBIT);
if (ecmd.supported & (SUPPORTED_1000baseT_Half |
SUPPORTED_1000baseT_Full))
lport->link_supported_speeds |= FC_PORTSPEED_1GBIT;
if (ecmd.supported & SUPPORTED_10000baseT_Full)
lport->link_supported_speeds |= FC_PORTSPEED_10GBIT;
switch (ethtool_cmd_speed(&ecmd)) {
case SPEED_1000:
lport->link_speed = FC_PORTSPEED_1GBIT;
break;
case SPEED_2500:
lport->link_speed = FC_PORTSPEED_2GBIT;
break;
case SPEED_10000:
lport->link_speed = FC_PORTSPEED_10GBIT;
break;
}
}
}
static int bnx2fc_link_ok(struct fc_lport *lport)
{
struct fcoe_port *port = lport_priv(lport);
struct bnx2fc_interface *interface = port->priv;
struct bnx2fc_hba *hba = interface->hba;
struct net_device *dev = hba->phys_dev;
int rc = 0;
if ((dev->flags & IFF_UP) && netif_carrier_ok(dev))
clear_bit(ADAPTER_STATE_LINK_DOWN, &hba->adapter_state);
else {
set_bit(ADAPTER_STATE_LINK_DOWN, &hba->adapter_state);
rc = -1;
}
return rc;
}
/**
* bnx2fc_get_link_state - get network link state
*
* @hba: adapter instance pointer
*
* updates adapter structure flag based on netdev state
*/
void bnx2fc_get_link_state(struct bnx2fc_hba *hba)
{
if (test_bit(__LINK_STATE_NOCARRIER, &hba->phys_dev->state))
set_bit(ADAPTER_STATE_LINK_DOWN, &hba->adapter_state);
else
clear_bit(ADAPTER_STATE_LINK_DOWN, &hba->adapter_state);
}
static int bnx2fc_net_config(struct fc_lport *lport, struct net_device *netdev)
{
struct bnx2fc_hba *hba;
struct bnx2fc_interface *interface;
struct fcoe_port *port;
u64 wwnn, wwpn;
port = lport_priv(lport);
interface = port->priv;
hba = interface->hba;
/* require support for get_pauseparam ethtool op. */
if (!hba->phys_dev->ethtool_ops ||
!hba->phys_dev->ethtool_ops->get_pauseparam)
return -EOPNOTSUPP;
if (fc_set_mfs(lport, BNX2FC_MFS))
return -EINVAL;
skb_queue_head_init(&port->fcoe_pending_queue);
port->fcoe_pending_queue_active = 0;
setup_timer(&port->timer, fcoe_queue_timer, (unsigned long) lport);
bnx2fc_link_speed_update(lport);
if (!lport->vport) {
if (fcoe_get_wwn(netdev, &wwnn, NETDEV_FCOE_WWNN))
wwnn = fcoe_wwn_from_mac(interface->ctlr.ctl_src_addr,
1, 0);
BNX2FC_HBA_DBG(lport, "WWNN = 0x%llx\n", wwnn);
fc_set_wwnn(lport, wwnn);
if (fcoe_get_wwn(netdev, &wwpn, NETDEV_FCOE_WWPN))
wwpn = fcoe_wwn_from_mac(interface->ctlr.ctl_src_addr,
2, 0);
BNX2FC_HBA_DBG(lport, "WWPN = 0x%llx\n", wwpn);
fc_set_wwpn(lport, wwpn);
}
return 0;
}
static void bnx2fc_destroy_timer(unsigned long data)
{
struct bnx2fc_hba *hba = (struct bnx2fc_hba *)data;
printk(KERN_ERR PFX "ERROR:bnx2fc_destroy_timer - "
"Destroy compl not received!!\n");
set_bit(BNX2FC_FLAG_DESTROY_CMPL, &hba->flags);
wake_up_interruptible(&hba->destroy_wait);
}
/**
* bnx2fc_indicate_netevent - Generic netdev event handler
*
* @context: adapter structure pointer
* @event: event type
* @vlan_id: vlan id - associated vlan id with this event
*
* Handles NETDEV_UP, NETDEV_DOWN, NETDEV_GOING_DOWN,NETDEV_CHANGE and
* NETDEV_CHANGE_MTU events. Handle NETDEV_UNREGISTER only for vlans.
*/
static void bnx2fc_indicate_netevent(void *context, unsigned long event,
u16 vlan_id)
{
struct bnx2fc_hba *hba = (struct bnx2fc_hba *)context;
struct fc_lport *lport;
struct fc_lport *vport;
struct bnx2fc_interface *interface, *tmp;
int wait_for_upload = 0;
u32 link_possible = 1;
if (vlan_id != 0 && event != NETDEV_UNREGISTER)
return;
switch (event) {
case NETDEV_UP:
if (!test_bit(ADAPTER_STATE_UP, &hba->adapter_state))
printk(KERN_ERR "indicate_netevent: "\
"hba is not UP!!\n");
break;
case NETDEV_DOWN:
clear_bit(ADAPTER_STATE_GOING_DOWN, &hba->adapter_state);
clear_bit(ADAPTER_STATE_UP, &hba->adapter_state);
link_possible = 0;
break;
case NETDEV_GOING_DOWN:
set_bit(ADAPTER_STATE_GOING_DOWN, &hba->adapter_state);
link_possible = 0;
break;
case NETDEV_CHANGE:
break;
case NETDEV_UNREGISTER:
if (!vlan_id)
return;
mutex_lock(&bnx2fc_dev_lock);
list_for_each_entry_safe(interface, tmp, &if_list, list) {
if (interface->hba == hba &&
interface->vlan_id == (vlan_id & VLAN_VID_MASK))
__bnx2fc_destroy(interface);
}
mutex_unlock(&bnx2fc_dev_lock);
return;
default:
printk(KERN_ERR PFX "Unkonwn netevent %ld", event);
return;
}
mutex_lock(&bnx2fc_dev_lock);
list_for_each_entry(interface, &if_list, list) {
if (interface->hba != hba)
continue;
lport = interface->ctlr.lp;
BNX2FC_HBA_DBG(lport, "netevent handler - event=%s %ld\n",
interface->netdev->name, event);
bnx2fc_link_speed_update(lport);
if (link_possible && !bnx2fc_link_ok(lport)) {
/* Reset max recv frame size to default */
fc_set_mfs(lport, BNX2FC_MFS);
/*
* ctlr link up will only be handled during
* enable to avoid sending discovery solicitation
* on a stale vlan
*/
if (interface->enabled)
fcoe_ctlr_link_up(&interface->ctlr);
} else if (fcoe_ctlr_link_down(&interface->ctlr)) {
mutex_lock(&lport->lp_mutex);
list_for_each_entry(vport, &lport->vports, list)
fc_host_port_type(vport->host) =
FC_PORTTYPE_UNKNOWN;
mutex_unlock(&lport->lp_mutex);
fc_host_port_type(lport->host) = FC_PORTTYPE_UNKNOWN;
per_cpu_ptr(lport->dev_stats,
get_cpu())->LinkFailureCount++;
put_cpu();
fcoe_clean_pending_queue(lport);
wait_for_upload = 1;
}
}
mutex_unlock(&bnx2fc_dev_lock);
if (wait_for_upload) {
clear_bit(ADAPTER_STATE_READY, &hba->adapter_state);
init_waitqueue_head(&hba->shutdown_wait);
BNX2FC_MISC_DBG("indicate_netevent "
"num_ofld_sess = %d\n",
hba->num_ofld_sess);
hba->wait_for_link_down = 1;
wait_event_interruptible(hba->shutdown_wait,
(hba->num_ofld_sess == 0));
BNX2FC_MISC_DBG("wakeup - num_ofld_sess = %d\n",
hba->num_ofld_sess);
hba->wait_for_link_down = 0;
if (signal_pending(current))
flush_signals(current);
}
}
static int bnx2fc_libfc_config(struct fc_lport *lport)
{
/* Set the function pointers set by bnx2fc driver */
memcpy(&lport->tt, &bnx2fc_libfc_fcn_templ,
sizeof(struct libfc_function_template));
fc_elsct_init(lport);
fc_exch_init(lport);
fc_rport_init(lport);
fc_disc_init(lport);
return 0;
}
static int bnx2fc_em_config(struct fc_lport *lport)
{
int max_xid;
if (nr_cpu_ids <= 2)
max_xid = FCOE_XIDS_PER_CPU;
else
max_xid = FCOE_MAX_XID;
if (!fc_exch_mgr_alloc(lport, FC_CLASS_3, FCOE_MIN_XID,
max_xid, NULL)) {
printk(KERN_ERR PFX "em_config:fc_exch_mgr_alloc failed\n");
return -ENOMEM;
}
return 0;
}
static int bnx2fc_lport_config(struct fc_lport *lport)
{
lport->link_up = 0;
lport->qfull = 0;
lport->max_retry_count = BNX2FC_MAX_RETRY_CNT;
lport->max_rport_retry_count = BNX2FC_MAX_RPORT_RETRY_CNT;
lport->e_d_tov = 2 * 1000;
lport->r_a_tov = 10 * 1000;
lport->service_params = (FCP_SPPF_INIT_FCN | FCP_SPPF_RD_XRDY_DIS |
FCP_SPPF_RETRY | FCP_SPPF_CONF_COMPL);
lport->does_npiv = 1;
memset(&lport->rnid_gen, 0, sizeof(struct fc_els_rnid_gen));
lport->rnid_gen.rnid_atype = BNX2FC_RNID_HBA;
/* alloc stats structure */
if (fc_lport_init_stats(lport))
return -ENOMEM;
/* Finish fc_lport configuration */
fc_lport_config(lport);
return 0;
}
/**
* bnx2fc_fip_recv - handle a received FIP frame.
*
* @skb: the received skb
* @dev: associated &net_device
* @ptype: the &packet_type structure which was used to register this handler.
* @orig_dev: original receive &net_device, in case @ dev is a bond.
*
* Returns: 0 for success
*/
static int bnx2fc_fip_recv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *ptype,
struct net_device *orig_dev)
{
struct bnx2fc_interface *interface;
interface = container_of(ptype, struct bnx2fc_interface,
fip_packet_type);
fcoe_ctlr_recv(&interface->ctlr, skb);
return 0;
}
/**
* bnx2fc_update_src_mac - Update Ethernet MAC filters.
*
* @fip: FCoE controller.
* @old: Unicast MAC address to delete if the MAC is non-zero.
* @new: Unicast MAC address to add.
*
* Remove any previously-set unicast MAC filter.
* Add secondary FCoE MAC address filter for our OUI.
*/
static void bnx2fc_update_src_mac(struct fc_lport *lport, u8 *addr)
{
struct fcoe_port *port = lport_priv(lport);
memcpy(port->data_src_addr, addr, ETH_ALEN);
}
/**
* bnx2fc_get_src_mac - return the ethernet source address for an lport
*
* @lport: libfc port
*/
static u8 *bnx2fc_get_src_mac(struct fc_lport *lport)
{
struct fcoe_port *port;
port = (struct fcoe_port *)lport_priv(lport);
return port->data_src_addr;
}
/**
* bnx2fc_fip_send - send an Ethernet-encapsulated FIP frame.
*
* @fip: FCoE controller.
* @skb: FIP Packet.
*/
static void bnx2fc_fip_send(struct fcoe_ctlr *fip, struct sk_buff *skb)
{
skb->dev = bnx2fc_from_ctlr(fip)->netdev;
dev_queue_xmit(skb);
}
static int bnx2fc_vport_create(struct fc_vport *vport, bool disabled)
{
struct Scsi_Host *shost = vport_to_shost(vport);
struct fc_lport *n_port = shost_priv(shost);
struct fcoe_port *port = lport_priv(n_port);
struct bnx2fc_interface *interface = port->priv;
struct net_device *netdev = interface->netdev;
struct fc_lport *vn_port;
int rc;
char buf[32];
rc = fcoe_validate_vport_create(vport);
if (rc) {
fcoe_wwn_to_str(vport->port_name, buf, sizeof(buf));
printk(KERN_ERR PFX "Failed to create vport, "
"WWPN (0x%s) already exists\n",
buf);
return rc;
}
if (!test_bit(BNX2FC_FLAG_FW_INIT_DONE, &interface->hba->flags)) {
printk(KERN_ERR PFX "vn ports cannot be created on"
"this interface\n");
return -EIO;
}
rtnl_lock();
mutex_lock(&bnx2fc_dev_lock);
vn_port = bnx2fc_if_create(interface, &vport->dev, 1);
mutex_unlock(&bnx2fc_dev_lock);
rtnl_unlock();
if (IS_ERR(vn_port)) {
printk(KERN_ERR PFX "bnx2fc_vport_create (%s) failed\n",
netdev->name);
return -EIO;
}
if (disabled) {
fc_vport_set_state(vport, FC_VPORT_DISABLED);
} else {
vn_port->boot_time = jiffies;
fc_lport_init(vn_port);
fc_fabric_login(vn_port);
fc_vport_setlink(vn_port);
}
return 0;
}
static void bnx2fc_free_vport(struct bnx2fc_hba *hba, struct fc_lport *lport)
{
struct bnx2fc_lport *blport, *tmp;
spin_lock_bh(&hba->hba_lock);
list_for_each_entry_safe(blport, tmp, &hba->vports, list) {
if (blport->lport == lport) {
list_del(&blport->list);
kfree(blport);
}
}
spin_unlock_bh(&hba->hba_lock);
}
static int bnx2fc_vport_destroy(struct fc_vport *vport)
{
struct Scsi_Host *shost = vport_to_shost(vport);
struct fc_lport *n_port = shost_priv(shost);
struct fc_lport *vn_port = vport->dd_data;
struct fcoe_port *port = lport_priv(vn_port);
struct bnx2fc_interface *interface = port->priv;
struct fc_lport *v_port;
bool found = false;
mutex_lock(&n_port->lp_mutex);
list_for_each_entry(v_port, &n_port->vports, list)
if (v_port->vport == vport) {
found = true;
break;
}
if (!found) {
mutex_unlock(&n_port->lp_mutex);
return -ENOENT;
}
list_del(&vn_port->list);
mutex_unlock(&n_port->lp_mutex);
bnx2fc_free_vport(interface->hba, port->lport);
bnx2fc_port_shutdown(port->lport);
bnx2fc_interface_put(interface);
queue_work(bnx2fc_wq, &port->destroy_work);
return 0;
}
static int bnx2fc_vport_disable(struct fc_vport *vport, bool disable)
{
struct fc_lport *lport = vport->dd_data;
if (disable) {
fc_vport_set_state(vport, FC_VPORT_DISABLED);
fc_fabric_logoff(lport);
} else {
lport->boot_time = jiffies;
fc_fabric_login(lport);
fc_vport_setlink(lport);
}
return 0;
}
static int bnx2fc_interface_setup(struct bnx2fc_interface *interface)
{
struct net_device *netdev = interface->netdev;
struct net_device *physdev = interface->hba->phys_dev;
struct netdev_hw_addr *ha;
int sel_san_mac = 0;
/* setup Source MAC Address */
rcu_read_lock();
for_each_dev_addr(physdev, ha) {
BNX2FC_MISC_DBG("net_config: ha->type = %d, fip_mac = ",
ha->type);
printk(KERN_INFO "%2x:%2x:%2x:%2x:%2x:%2x\n", ha->addr[0],
ha->addr[1], ha->addr[2], ha->addr[3],
ha->addr[4], ha->addr[5]);
if ((ha->type == NETDEV_HW_ADDR_T_SAN) &&
(is_valid_ether_addr(ha->addr))) {
memcpy(interface->ctlr.ctl_src_addr, ha->addr,
ETH_ALEN);
sel_san_mac = 1;
BNX2FC_MISC_DBG("Found SAN MAC\n");
}
}
rcu_read_unlock();
if (!sel_san_mac)
return -ENODEV;
interface->fip_packet_type.func = bnx2fc_fip_recv;
interface->fip_packet_type.type = htons(ETH_P_FIP);
interface->fip_packet_type.dev = netdev;
dev_add_pack(&interface->fip_packet_type);
interface->fcoe_packet_type.func = bnx2fc_rcv;
interface->fcoe_packet_type.type = __constant_htons(ETH_P_FCOE);
interface->fcoe_packet_type.dev = netdev;
dev_add_pack(&interface->fcoe_packet_type);
return 0;
}
static int bnx2fc_attach_transport(void)
{
bnx2fc_transport_template =
fc_attach_transport(&bnx2fc_transport_function);
if (bnx2fc_transport_template == NULL) {
printk(KERN_ERR PFX "Failed to attach FC transport\n");
return -ENODEV;
}
bnx2fc_vport_xport_template =
fc_attach_transport(&bnx2fc_vport_xport_function);
if (bnx2fc_vport_xport_template == NULL) {
printk(KERN_ERR PFX
"Failed to attach FC transport for vport\n");
fc_release_transport(bnx2fc_transport_template);
bnx2fc_transport_template = NULL;
return -ENODEV;
}
return 0;
}
static void bnx2fc_release_transport(void)
{
fc_release_transport(bnx2fc_transport_template);
fc_release_transport(bnx2fc_vport_xport_template);
bnx2fc_transport_template = NULL;
bnx2fc_vport_xport_template = NULL;
}
static void bnx2fc_interface_release(struct kref *kref)
{
struct bnx2fc_interface *interface;
struct net_device *netdev;
interface = container_of(kref, struct bnx2fc_interface, kref);
BNX2FC_MISC_DBG("Interface is being released\n");
netdev = interface->netdev;
/* tear-down FIP controller */
if (test_and_clear_bit(BNX2FC_CTLR_INIT_DONE, &interface->if_flags))
fcoe_ctlr_destroy(&interface->ctlr);
kfree(interface);
dev_put(netdev);
module_put(THIS_MODULE);
}
static inline void bnx2fc_interface_get(struct bnx2fc_interface *interface)
{
kref_get(&interface->kref);
}
static inline void bnx2fc_interface_put(struct bnx2fc_interface *interface)
{
kref_put(&interface->kref, bnx2fc_interface_release);
}
static void bnx2fc_hba_destroy(struct bnx2fc_hba *hba)
{
/* Free the command manager */
if (hba->cmd_mgr) {
bnx2fc_cmd_mgr_free(hba->cmd_mgr);
hba->cmd_mgr = NULL;
}
kfree(hba->tgt_ofld_list);
bnx2fc_unbind_pcidev(hba);
kfree(hba);
}
/**
* bnx2fc_hba_create - create a new bnx2fc hba
*
* @cnic: pointer to cnic device
*
* Creates a new FCoE hba on the given device.
*
*/
static struct bnx2fc_hba *bnx2fc_hba_create(struct cnic_dev *cnic)
{
struct bnx2fc_hba *hba;
int rc;
hba = kzalloc(sizeof(*hba), GFP_KERNEL);
if (!hba) {
printk(KERN_ERR PFX "Unable to allocate hba structure\n");
return NULL;
}
spin_lock_init(&hba->hba_lock);
mutex_init(&hba->hba_mutex);
hba->cnic = cnic;
rc = bnx2fc_bind_pcidev(hba);
if (rc) {
printk(KERN_ERR PFX "create_adapter: bind error\n");
goto bind_err;
}
hba->phys_dev = cnic->netdev;
hba->next_conn_id = 0;
hba->tgt_ofld_list =
kzalloc(sizeof(struct bnx2fc_rport *) * BNX2FC_NUM_MAX_SESS,
GFP_KERNEL);
if (!hba->tgt_ofld_list) {
printk(KERN_ERR PFX "Unable to allocate tgt offload list\n");
goto tgtofld_err;
}
hba->num_ofld_sess = 0;
hba->cmd_mgr = bnx2fc_cmd_mgr_alloc(hba, BNX2FC_MIN_XID,
BNX2FC_MAX_XID);
if (!hba->cmd_mgr) {
printk(KERN_ERR PFX "em_config:bnx2fc_cmd_mgr_alloc failed\n");
goto cmgr_err;
}
init_waitqueue_head(&hba->shutdown_wait);
init_waitqueue_head(&hba->destroy_wait);
INIT_LIST_HEAD(&hba->vports);
return hba;
cmgr_err:
kfree(hba->tgt_ofld_list);
tgtofld_err:
bnx2fc_unbind_pcidev(hba);
bind_err:
kfree(hba);
return NULL;
}
struct bnx2fc_interface *bnx2fc_interface_create(struct bnx2fc_hba *hba,
struct net_device *netdev,
enum fip_state fip_mode)
{
struct bnx2fc_interface *interface;
int rc = 0;
interface = kzalloc(sizeof(*interface), GFP_KERNEL);
if (!interface) {
printk(KERN_ERR PFX "Unable to allocate interface structure\n");
return NULL;
}
dev_hold(netdev);
kref_init(&interface->kref);
interface->hba = hba;
interface->netdev = netdev;
/* Initialize FIP */
fcoe_ctlr_init(&interface->ctlr, fip_mode);
interface->ctlr.send = bnx2fc_fip_send;
interface->ctlr.update_mac = bnx2fc_update_src_mac;
interface->ctlr.get_src_addr = bnx2fc_get_src_mac;
set_bit(BNX2FC_CTLR_INIT_DONE, &interface->if_flags);
rc = bnx2fc_interface_setup(interface);
if (!rc)
return interface;
fcoe_ctlr_destroy(&interface->ctlr);
dev_put(netdev);
kfree(interface);
return NULL;
}
/**
* bnx2fc_if_create - Create FCoE instance on a given interface
*
* @interface: FCoE interface to create a local port on
* @parent: Device pointer to be the parent in sysfs for the SCSI host
* @npiv: Indicates if the port is vport or not
*
* Creates a fc_lport instance and a Scsi_Host instance and configure them.
*
* Returns: Allocated fc_lport or an error pointer
*/
static struct fc_lport *bnx2fc_if_create(struct bnx2fc_interface *interface,
struct device *parent, int npiv)
{
struct fc_lport *lport, *n_port;
struct fcoe_port *port;
struct Scsi_Host *shost;
struct fc_vport *vport = dev_to_vport(parent);
struct bnx2fc_lport *blport;
struct bnx2fc_hba *hba;
int rc = 0;
blport = kzalloc(sizeof(struct bnx2fc_lport), GFP_KERNEL);
if (!blport) {
BNX2FC_HBA_DBG(interface->ctlr.lp, "Unable to alloc blport\n");
return NULL;
}
/* Allocate Scsi_Host structure */
if (!npiv)
lport = libfc_host_alloc(&bnx2fc_shost_template, sizeof(*port));
else
lport = libfc_vport_create(vport, sizeof(*port));
if (!lport) {
printk(KERN_ERR PFX "could not allocate scsi host structure\n");
goto free_blport;
}
shost = lport->host;
port = lport_priv(lport);
port->lport = lport;
port->priv = interface;
INIT_WORK(&port->destroy_work, bnx2fc_destroy_work);
/* Configure fcoe_port */
rc = bnx2fc_lport_config(lport);
if (rc)
goto lp_config_err;
if (npiv) {
printk(KERN_ERR PFX "Setting vport names, 0x%llX 0x%llX\n",
vport->node_name, vport->port_name);
fc_set_wwnn(lport, vport->node_name);
fc_set_wwpn(lport, vport->port_name);
}
/* Configure netdev and networking properties of the lport */
rc = bnx2fc_net_config(lport, interface->netdev);
if (rc) {
printk(KERN_ERR PFX "Error on bnx2fc_net_config\n");
goto lp_config_err;
}
rc = bnx2fc_shost_config(lport, parent);
if (rc) {
printk(KERN_ERR PFX "Couldnt configure shost for %s\n",
interface->netdev->name);
goto lp_config_err;
}
/* Initialize the libfc library */
rc = bnx2fc_libfc_config(lport);
if (rc) {
printk(KERN_ERR PFX "Couldnt configure libfc\n");
goto shost_err;
}
fc_host_port_type(lport->host) = FC_PORTTYPE_UNKNOWN;
/* Allocate exchange manager */
if (!npiv)
rc = bnx2fc_em_config(lport);
else {
shost = vport_to_shost(vport);
n_port = shost_priv(shost);
rc = fc_exch_mgr_list_clone(n_port, lport);
}
if (rc) {
printk(KERN_ERR PFX "Error on bnx2fc_em_config\n");
goto shost_err;
}
bnx2fc_interface_get(interface);
hba = interface->hba;
spin_lock_bh(&hba->hba_lock);
blport->lport = lport;
list_add_tail(&blport->list, &hba->vports);
spin_unlock_bh(&hba->hba_lock);
return lport;
shost_err:
scsi_remove_host(shost);
lp_config_err:
scsi_host_put(lport->host);
free_blport:
kfree(blport);
return NULL;
}
static void bnx2fc_net_cleanup(struct bnx2fc_interface *interface)
{
/* Dont listen for Ethernet packets anymore */
__dev_remove_pack(&interface->fcoe_packet_type);
__dev_remove_pack(&interface->fip_packet_type);
synchronize_net();
}
static void bnx2fc_interface_cleanup(struct bnx2fc_interface *interface)
{
struct fc_lport *lport = interface->ctlr.lp;
struct fcoe_port *port = lport_priv(lport);
struct bnx2fc_hba *hba = interface->hba;
/* Stop the transmit retry timer */
del_timer_sync(&port->timer);
/* Free existing transmit skbs */
fcoe_clean_pending_queue(lport);
bnx2fc_net_cleanup(interface);
bnx2fc_free_vport(hba, lport);
}
static void bnx2fc_if_destroy(struct fc_lport *lport)
{
/* Free queued packets for the receive thread */
bnx2fc_clean_rx_queue(lport);
/* Detach from scsi-ml */
fc_remove_host(lport->host);
scsi_remove_host(lport->host);
/*
* Note that only the physical lport will have the exchange manager.
* for vports, this function is NOP
*/
fc_exch_mgr_free(lport);
/* Free memory used by statistical counters */
fc_lport_free_stats(lport);
/* Release Scsi_Host */
scsi_host_put(lport->host);
}
static void __bnx2fc_destroy(struct bnx2fc_interface *interface)
{
struct fc_lport *lport = interface->ctlr.lp;
struct fcoe_port *port = lport_priv(lport);
bnx2fc_interface_cleanup(interface);
bnx2fc_stop(interface);
list_del(&interface->list);
bnx2fc_interface_put(interface);
queue_work(bnx2fc_wq, &port->destroy_work);
}
/**
* bnx2fc_destroy - Destroy a bnx2fc FCoE interface
*
* @buffer: The name of the Ethernet interface to be destroyed
* @kp: The associated kernel parameter
*
* Called from sysfs.
*
* Returns: 0 for success
*/
static int bnx2fc_destroy(struct net_device *netdev)
{
struct bnx2fc_interface *interface = NULL;
struct workqueue_struct *timer_work_queue;
int rc = 0;
rtnl_lock();
mutex_lock(&bnx2fc_dev_lock);
interface = bnx2fc_interface_lookup(netdev);
if (!interface || !interface->ctlr.lp) {
rc = -ENODEV;
printk(KERN_ERR PFX "bnx2fc_destroy: interface or lport not found\n");
goto netdev_err;
}
timer_work_queue = interface->timer_work_queue;
__bnx2fc_destroy(interface);
destroy_workqueue(timer_work_queue);
netdev_err:
mutex_unlock(&bnx2fc_dev_lock);
rtnl_unlock();
return rc;
}
static void bnx2fc_destroy_work(struct work_struct *work)
{
struct fcoe_port *port;
struct fc_lport *lport;
port = container_of(work, struct fcoe_port, destroy_work);
lport = port->lport;
BNX2FC_HBA_DBG(lport, "Entered bnx2fc_destroy_work\n");
bnx2fc_if_destroy(lport);
}
static void bnx2fc_unbind_adapter_devices(struct bnx2fc_hba *hba)
{
bnx2fc_free_fw_resc(hba);
bnx2fc_free_task_ctx(hba);
}
/**
* bnx2fc_bind_adapter_devices - binds bnx2fc adapter with the associated
* pci structure
*
* @hba: Adapter instance
*/
static int bnx2fc_bind_adapter_devices(struct bnx2fc_hba *hba)
{
if (bnx2fc_setup_task_ctx(hba))
goto mem_err;
if (bnx2fc_setup_fw_resc(hba))
goto mem_err;
return 0;
mem_err:
bnx2fc_unbind_adapter_devices(hba);
return -ENOMEM;
}
static int bnx2fc_bind_pcidev(struct bnx2fc_hba *hba)
{
struct cnic_dev *cnic;
if (!hba->cnic) {
printk(KERN_ERR PFX "cnic is NULL\n");
return -ENODEV;
}
cnic = hba->cnic;
hba->pcidev = cnic->pcidev;
if (hba->pcidev)
pci_dev_get(hba->pcidev);
return 0;
}
static void bnx2fc_unbind_pcidev(struct bnx2fc_hba *hba)
{
if (hba->pcidev)
pci_dev_put(hba->pcidev);
hba->pcidev = NULL;
}
/**
* bnx2fc_ulp_start - cnic callback to initialize & start adapter instance
*
* @handle: transport handle pointing to adapter struture
*
* This function maps adapter structure to pcidev structure and initiates
* firmware handshake to enable/initialize on-chip FCoE components.
* This bnx2fc - cnic interface api callback is used after following
* conditions are met -
* a) underlying network interface is up (marked by event NETDEV_UP
* from netdev
* b) bnx2fc adatper structure is registered.
*/
static void bnx2fc_ulp_start(void *handle)
{
struct bnx2fc_hba *hba = handle;
struct bnx2fc_interface *interface;
struct fc_lport *lport;
mutex_lock(&bnx2fc_dev_lock);
if (!test_bit(BNX2FC_FLAG_FW_INIT_DONE, &hba->flags))
bnx2fc_fw_init(hba);
BNX2FC_MISC_DBG("bnx2fc started.\n");
list_for_each_entry(interface, &if_list, list) {
if (interface->hba == hba) {
lport = interface->ctlr.lp;
/* Kick off Fabric discovery*/
printk(KERN_ERR PFX "ulp_init: start discovery\n");
lport->tt.frame_send = bnx2fc_xmit;
bnx2fc_start_disc(interface);
}
}
mutex_unlock(&bnx2fc_dev_lock);
}
static void bnx2fc_port_shutdown(struct fc_lport *lport)
{
BNX2FC_MISC_DBG("Entered %s\n", __func__);
fc_fabric_logoff(lport);
fc_lport_destroy(lport);
}
static void bnx2fc_stop(struct bnx2fc_interface *interface)
{
struct fc_lport *lport;
struct fc_lport *vport;
if (!test_bit(BNX2FC_FLAG_FW_INIT_DONE, &interface->hba->flags))
return;
lport = interface->ctlr.lp;
bnx2fc_port_shutdown(lport);
mutex_lock(&lport->lp_mutex);
list_for_each_entry(vport, &lport->vports, list)
fc_host_port_type(vport->host) =
FC_PORTTYPE_UNKNOWN;
mutex_unlock(&lport->lp_mutex);
fc_host_port_type(lport->host) = FC_PORTTYPE_UNKNOWN;
fcoe_ctlr_link_down(&interface->ctlr);
fcoe_clean_pending_queue(lport);
}
static int bnx2fc_fw_init(struct bnx2fc_hba *hba)
{
#define BNX2FC_INIT_POLL_TIME (1000 / HZ)
int rc = -1;
int i = HZ;
rc = bnx2fc_bind_adapter_devices(hba);
if (rc) {
printk(KERN_ALERT PFX
"bnx2fc_bind_adapter_devices failed - rc = %d\n", rc);
goto err_out;
}
rc = bnx2fc_send_fw_fcoe_init_msg(hba);
if (rc) {
printk(KERN_ALERT PFX
"bnx2fc_send_fw_fcoe_init_msg failed - rc = %d\n", rc);
goto err_unbind;
}
/*
* Wait until the adapter init message is complete, and adapter
* state is UP.
*/
while (!test_bit(ADAPTER_STATE_UP, &hba->adapter_state) && i--)
msleep(BNX2FC_INIT_POLL_TIME);
if (!test_bit(ADAPTER_STATE_UP, &hba->adapter_state)) {
printk(KERN_ERR PFX "bnx2fc_start: %s failed to initialize. "
"Ignoring...\n",
hba->cnic->netdev->name);
rc = -1;
goto err_unbind;
}
set_bit(BNX2FC_FLAG_FW_INIT_DONE, &hba->flags);
return 0;
err_unbind:
bnx2fc_unbind_adapter_devices(hba);
err_out:
return rc;
}
static void bnx2fc_fw_destroy(struct bnx2fc_hba *hba)
{
if (test_and_clear_bit(BNX2FC_FLAG_FW_INIT_DONE, &hba->flags)) {
if (bnx2fc_send_fw_fcoe_destroy_msg(hba) == 0) {
init_timer(&hba->destroy_timer);
hba->destroy_timer.expires = BNX2FC_FW_TIMEOUT +
jiffies;
hba->destroy_timer.function = bnx2fc_destroy_timer;
hba->destroy_timer.data = (unsigned long)hba;
add_timer(&hba->destroy_timer);
wait_event_interruptible(hba->destroy_wait,
test_bit(BNX2FC_FLAG_DESTROY_CMPL,
&hba->flags));
clear_bit(BNX2FC_FLAG_DESTROY_CMPL, &hba->flags);
/* This should never happen */
if (signal_pending(current))
flush_signals(current);
del_timer_sync(&hba->destroy_timer);
}
bnx2fc_unbind_adapter_devices(hba);
}
}
/**
* bnx2fc_ulp_stop - cnic callback to shutdown adapter instance
*
* @handle: transport handle pointing to adapter structure
*
* Driver checks if adapter is already in shutdown mode, if not start
* the shutdown process.
*/
static void bnx2fc_ulp_stop(void *handle)
{
struct bnx2fc_hba *hba = handle;
struct bnx2fc_interface *interface;
printk(KERN_ERR "ULP_STOP\n");
mutex_lock(&bnx2fc_dev_lock);
if (!test_bit(BNX2FC_FLAG_FW_INIT_DONE, &hba->flags))
goto exit;
list_for_each_entry(interface, &if_list, list) {
if (interface->hba == hba)
bnx2fc_stop(interface);
}
BUG_ON(hba->num_ofld_sess != 0);
mutex_lock(&hba->hba_mutex);
clear_bit(ADAPTER_STATE_UP, &hba->adapter_state);
clear_bit(ADAPTER_STATE_GOING_DOWN,
&hba->adapter_state);
clear_bit(ADAPTER_STATE_READY, &hba->adapter_state);
mutex_unlock(&hba->hba_mutex);
bnx2fc_fw_destroy(hba);
exit:
mutex_unlock(&bnx2fc_dev_lock);
}
static void bnx2fc_start_disc(struct bnx2fc_interface *interface)
{
struct fc_lport *lport;
int wait_cnt = 0;
BNX2FC_MISC_DBG("Entered %s\n", __func__);
/* Kick off FIP/FLOGI */
if (!test_bit(BNX2FC_FLAG_FW_INIT_DONE, &interface->hba->flags)) {
printk(KERN_ERR PFX "Init not done yet\n");
return;
}
lport = interface->ctlr.lp;
BNX2FC_HBA_DBG(lport, "calling fc_fabric_login\n");
if (!bnx2fc_link_ok(lport) && interface->enabled) {
BNX2FC_HBA_DBG(lport, "ctlr_link_up\n");
fcoe_ctlr_link_up(&interface->ctlr);
fc_host_port_type(lport->host) = FC_PORTTYPE_NPORT;
set_bit(ADAPTER_STATE_READY, &interface->hba->adapter_state);
}
/* wait for the FCF to be selected before issuing FLOGI */
while (!interface->ctlr.sel_fcf) {
msleep(250);
/* give up after 3 secs */
if (++wait_cnt > 12)
break;
}
/* Reset max receive frame size to default */
if (fc_set_mfs(lport, BNX2FC_MFS))
return;
fc_lport_init(lport);
fc_fabric_login(lport);
}
/**
* bnx2fc_ulp_init - Initialize an adapter instance
*
* @dev : cnic device handle
* Called from cnic_register_driver() context to initialize all
* enumerated cnic devices. This routine allocates adapter structure
* and other device specific resources.
*/
static void bnx2fc_ulp_init(struct cnic_dev *dev)
{
struct bnx2fc_hba *hba;
int rc = 0;
BNX2FC_MISC_DBG("Entered %s\n", __func__);
/* bnx2fc works only when bnx2x is loaded */
if (!test_bit(CNIC_F_BNX2X_CLASS, &dev->flags) ||
(dev->max_fcoe_conn == 0)) {
printk(KERN_ERR PFX "bnx2fc FCoE not supported on %s,"
" flags: %lx fcoe_conn: %d\n",
dev->netdev->name, dev->flags, dev->max_fcoe_conn);
return;
}
hba = bnx2fc_hba_create(dev);
if (!hba) {
printk(KERN_ERR PFX "hba initialization failed\n");
return;
}
/* Add HBA to the adapter list */
mutex_lock(&bnx2fc_dev_lock);
list_add_tail(&hba->list, &adapter_list);
adapter_count++;
mutex_unlock(&bnx2fc_dev_lock);
clear_bit(BNX2FC_CNIC_REGISTERED, &hba->reg_with_cnic);
rc = dev->register_device(dev, CNIC_ULP_FCOE,
(void *) hba);
if (rc)
printk(KERN_ERR PFX "register_device failed, rc = %d\n", rc);
else
set_bit(BNX2FC_CNIC_REGISTERED, &hba->reg_with_cnic);
}
static int bnx2fc_disable(struct net_device *netdev)
{
struct bnx2fc_interface *interface;
int rc = 0;
rtnl_lock();
mutex_lock(&bnx2fc_dev_lock);
interface = bnx2fc_interface_lookup(netdev);
if (!interface || !interface->ctlr.lp) {
rc = -ENODEV;
printk(KERN_ERR PFX "bnx2fc_disable: interface or lport not found\n");
} else {
interface->enabled = false;
fcoe_ctlr_link_down(&interface->ctlr);
fcoe_clean_pending_queue(interface->ctlr.lp);
}
mutex_unlock(&bnx2fc_dev_lock);
rtnl_unlock();
return rc;
}
static int bnx2fc_enable(struct net_device *netdev)
{
struct bnx2fc_interface *interface;
int rc = 0;
rtnl_lock();
mutex_lock(&bnx2fc_dev_lock);
interface = bnx2fc_interface_lookup(netdev);
if (!interface || !interface->ctlr.lp) {
rc = -ENODEV;
printk(KERN_ERR PFX "bnx2fc_enable: interface or lport not found\n");
} else if (!bnx2fc_link_ok(interface->ctlr.lp)) {
fcoe_ctlr_link_up(&interface->ctlr);
interface->enabled = true;
}
mutex_unlock(&bnx2fc_dev_lock);
rtnl_unlock();
return rc;
}
/**
* bnx2fc_create - Create bnx2fc FCoE interface
*
* @buffer: The name of Ethernet interface to create on
* @kp: The associated kernel param
*
* Called from sysfs.
*
* Returns: 0 for success
*/
static int bnx2fc_create(struct net_device *netdev, enum fip_state fip_mode)
{
struct bnx2fc_interface *interface;
struct bnx2fc_hba *hba;
struct net_device *phys_dev;
struct fc_lport *lport;
struct ethtool_drvinfo drvinfo;
int rc = 0;
int vlan_id;
BNX2FC_MISC_DBG("Entered bnx2fc_create\n");
if (fip_mode != FIP_MODE_FABRIC) {
printk(KERN_ERR "fip mode not FABRIC\n");
return -EIO;
}
rtnl_lock();
mutex_lock(&bnx2fc_dev_lock);
if (!try_module_get(THIS_MODULE)) {
rc = -EINVAL;
goto mod_err;
}
/* obtain physical netdev */
if (netdev->priv_flags & IFF_802_1Q_VLAN) {
phys_dev = vlan_dev_real_dev(netdev);
vlan_id = vlan_dev_vlan_id(netdev);
} else {
printk(KERN_ERR PFX "Not a vlan device\n");
rc = -EINVAL;
goto netdev_err;
}
/* verify if the physical device is a netxtreme2 device */
if (phys_dev->ethtool_ops && phys_dev->ethtool_ops->get_drvinfo) {
memset(&drvinfo, 0, sizeof(drvinfo));
phys_dev->ethtool_ops->get_drvinfo(phys_dev, &drvinfo);
if (strncmp(drvinfo.driver, "bnx2x", strlen("bnx2x"))) {
printk(KERN_ERR PFX "Not a netxtreme2 device\n");
rc = -EINVAL;
goto netdev_err;
}
} else {
printk(KERN_ERR PFX "unable to obtain drv_info\n");
rc = -EINVAL;
goto netdev_err;
}
/* obtain interface and initialize rest of the structure */
hba = bnx2fc_hba_lookup(phys_dev);
if (!hba) {
rc = -ENODEV;
printk(KERN_ERR PFX "bnx2fc_create: hba not found\n");
goto netdev_err;
}
if (bnx2fc_interface_lookup(netdev)) {
rc = -EEXIST;
goto netdev_err;
}
interface = bnx2fc_interface_create(hba, netdev, fip_mode);
if (!interface) {
printk(KERN_ERR PFX "bnx2fc_interface_create failed\n");
goto ifput_err;
}
interface->vlan_id = vlan_id;
interface->vlan_enabled = 1;
interface->timer_work_queue =
create_singlethread_workqueue("bnx2fc_timer_wq");
if (!interface->timer_work_queue) {
printk(KERN_ERR PFX "ulp_init could not create timer_wq\n");
rc = -EINVAL;
goto ifput_err;
}
lport = bnx2fc_if_create(interface, &interface->hba->pcidev->dev, 0);
if (!lport) {
printk(KERN_ERR PFX "Failed to create interface (%s)\n",
netdev->name);
rc = -EINVAL;
goto if_create_err;
}
/* Add interface to if_list */
list_add_tail(&interface->list, &if_list);
lport->boot_time = jiffies;
/* Make this master N_port */
interface->ctlr.lp = lport;
if (!bnx2fc_link_ok(lport)) {
fcoe_ctlr_link_up(&interface->ctlr);
fc_host_port_type(lport->host) = FC_PORTTYPE_NPORT;
set_bit(ADAPTER_STATE_READY, &interface->hba->adapter_state);
}
BNX2FC_HBA_DBG(lport, "create: START DISC\n");
bnx2fc_start_disc(interface);
interface->enabled = true;
/*
* Release from kref_init in bnx2fc_interface_setup, on success
* lport should be holding a reference taken in bnx2fc_if_create
*/
bnx2fc_interface_put(interface);
/* put netdev that was held while calling dev_get_by_name */
mutex_unlock(&bnx2fc_dev_lock);
rtnl_unlock();
return 0;
if_create_err:
destroy_workqueue(interface->timer_work_queue);
ifput_err:
bnx2fc_net_cleanup(interface);
bnx2fc_interface_put(interface);
goto mod_err;
netdev_err:
module_put(THIS_MODULE);
mod_err:
mutex_unlock(&bnx2fc_dev_lock);
rtnl_unlock();
return rc;
}
/**
* bnx2fc_find_hba_for_cnic - maps cnic instance to bnx2fc hba instance
*
* @cnic: Pointer to cnic device instance
*
**/
static struct bnx2fc_hba *bnx2fc_find_hba_for_cnic(struct cnic_dev *cnic)
{
struct list_head *list;
struct list_head *temp;
struct bnx2fc_hba *hba;
/* Called with bnx2fc_dev_lock held */
list_for_each_safe(list, temp, &adapter_list) {
hba = (struct bnx2fc_hba *)list;
if (hba->cnic == cnic)
return hba;
}
return NULL;
}
static struct bnx2fc_interface *bnx2fc_interface_lookup(struct net_device
*netdev)
{
struct bnx2fc_interface *interface;
/* Called with bnx2fc_dev_lock held */
list_for_each_entry(interface, &if_list, list) {
if (interface->netdev == netdev)
return interface;
}
return NULL;
}
static struct bnx2fc_hba *bnx2fc_hba_lookup(struct net_device
*phys_dev)
{
struct bnx2fc_hba *hba;
/* Called with bnx2fc_dev_lock held */
list_for_each_entry(hba, &adapter_list, list) {
if (hba->phys_dev == phys_dev)
return hba;
}
printk(KERN_ERR PFX "adapter_lookup: hba NULL\n");
return NULL;
}
/**
* bnx2fc_ulp_exit - shuts down adapter instance and frees all resources
*
* @dev cnic device handle
*/
static void bnx2fc_ulp_exit(struct cnic_dev *dev)
{
struct bnx2fc_hba *hba;
struct bnx2fc_interface *interface, *tmp;
BNX2FC_MISC_DBG("Entered bnx2fc_ulp_exit\n");
if (!test_bit(CNIC_F_BNX2X_CLASS, &dev->flags)) {
printk(KERN_ERR PFX "bnx2fc port check: %s, flags: %lx\n",
dev->netdev->name, dev->flags);
return;
}
mutex_lock(&bnx2fc_dev_lock);
hba = bnx2fc_find_hba_for_cnic(dev);
if (!hba) {
printk(KERN_ERR PFX "bnx2fc_ulp_exit: hba not found, dev 0%p\n",
dev);
mutex_unlock(&bnx2fc_dev_lock);
return;
}
list_del_init(&hba->list);
adapter_count--;
list_for_each_entry_safe(interface, tmp, &if_list, list)
/* destroy not called yet, move to quiesced list */
if (interface->hba == hba)
__bnx2fc_destroy(interface);
mutex_unlock(&bnx2fc_dev_lock);
bnx2fc_ulp_stop(hba);
/* unregister cnic device */
if (test_and_clear_bit(BNX2FC_CNIC_REGISTERED, &hba->reg_with_cnic))
hba->cnic->unregister_device(hba->cnic, CNIC_ULP_FCOE);
bnx2fc_hba_destroy(hba);
}
/**
* bnx2fc_fcoe_reset - Resets the fcoe
*
* @shost: shost the reset is from
*
* Returns: always 0
*/
static int bnx2fc_fcoe_reset(struct Scsi_Host *shost)
{
struct fc_lport *lport = shost_priv(shost);
fc_lport_reset(lport);
return 0;
}
static bool bnx2fc_match(struct net_device *netdev)
{
mutex_lock(&bnx2fc_dev_lock);
if (netdev->priv_flags & IFF_802_1Q_VLAN) {
struct net_device *phys_dev = vlan_dev_real_dev(netdev);
if (bnx2fc_hba_lookup(phys_dev)) {
mutex_unlock(&bnx2fc_dev_lock);
return true;
}
}
mutex_unlock(&bnx2fc_dev_lock);
return false;
}
static struct fcoe_transport bnx2fc_transport = {
.name = {"bnx2fc"},
.attached = false,
.list = LIST_HEAD_INIT(bnx2fc_transport.list),
.match = bnx2fc_match,
.create = bnx2fc_create,
.destroy = bnx2fc_destroy,
.enable = bnx2fc_enable,
.disable = bnx2fc_disable,
};
/**
* bnx2fc_percpu_thread_create - Create a receive thread for an
* online CPU
*
* @cpu: cpu index for the online cpu
*/
static void bnx2fc_percpu_thread_create(unsigned int cpu)
{
struct bnx2fc_percpu_s *p;
struct task_struct *thread;
p = &per_cpu(bnx2fc_percpu, cpu);
thread = kthread_create(bnx2fc_percpu_io_thread,
(void *)p,
"bnx2fc_thread/%d", cpu);
/* bind thread to the cpu */
if (likely(!IS_ERR(thread))) {
kthread_bind(thread, cpu);
p->iothread = thread;
wake_up_process(thread);
}
}
static void bnx2fc_percpu_thread_destroy(unsigned int cpu)
{
struct bnx2fc_percpu_s *p;
struct task_struct *thread;
struct bnx2fc_work *work, *tmp;
BNX2FC_MISC_DBG("destroying io thread for CPU %d\n", cpu);
/* Prevent any new work from being queued for this CPU */
p = &per_cpu(bnx2fc_percpu, cpu);
spin_lock_bh(&p->fp_work_lock);
thread = p->iothread;
p->iothread = NULL;
/* Free all work in the list */
list_for_each_entry_safe(work, tmp, &p->work_list, list) {
list_del_init(&work->list);
bnx2fc_process_cq_compl(work->tgt, work->wqe);
kfree(work);
}
spin_unlock_bh(&p->fp_work_lock);
if (thread)
kthread_stop(thread);
}
/**
* bnx2fc_cpu_callback - Handler for CPU hotplug events
*
* @nfb: The callback data block
* @action: The event triggering the callback
* @hcpu: The index of the CPU that the event is for
*
* This creates or destroys per-CPU data for fcoe
*
* Returns NOTIFY_OK always.
*/
static int bnx2fc_cpu_callback(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
unsigned cpu = (unsigned long)hcpu;
switch (action) {
case CPU_ONLINE:
case CPU_ONLINE_FROZEN:
printk(PFX "CPU %x online: Create Rx thread\n", cpu);
bnx2fc_percpu_thread_create(cpu);
break;
case CPU_DEAD:
case CPU_DEAD_FROZEN:
printk(PFX "CPU %x offline: Remove Rx thread\n", cpu);
bnx2fc_percpu_thread_destroy(cpu);
break;
default:
break;
}
return NOTIFY_OK;
}
/**
* bnx2fc_mod_init - module init entry point
*
* Initialize driver wide global data structures, and register
* with cnic module
**/
static int __init bnx2fc_mod_init(void)
{
struct fcoe_percpu_s *bg;
struct task_struct *l2_thread;
int rc = 0;
unsigned int cpu = 0;
struct bnx2fc_percpu_s *p;
printk(KERN_INFO PFX "%s", version);
/* register as a fcoe transport */
rc = fcoe_transport_attach(&bnx2fc_transport);
if (rc) {
printk(KERN_ERR "failed to register an fcoe transport, check "
"if libfcoe is loaded\n");
goto out;
}
INIT_LIST_HEAD(&adapter_list);
INIT_LIST_HEAD(&if_list);
mutex_init(&bnx2fc_dev_lock);
adapter_count = 0;
/* Attach FC transport template */
rc = bnx2fc_attach_transport();
if (rc)
goto detach_ft;
bnx2fc_wq = alloc_workqueue("bnx2fc", 0, 0);
if (!bnx2fc_wq) {
rc = -ENOMEM;
goto release_bt;
}
bg = &bnx2fc_global;
skb_queue_head_init(&bg->fcoe_rx_list);
l2_thread = kthread_create(bnx2fc_l2_rcv_thread,
(void *)bg,
"bnx2fc_l2_thread");
if (IS_ERR(l2_thread)) {
rc = PTR_ERR(l2_thread);
goto free_wq;
}
wake_up_process(l2_thread);
spin_lock_bh(&bg->fcoe_rx_list.lock);
bg->thread = l2_thread;
spin_unlock_bh(&bg->fcoe_rx_list.lock);
for_each_possible_cpu(cpu) {
p = &per_cpu(bnx2fc_percpu, cpu);
INIT_LIST_HEAD(&p->work_list);
spin_lock_init(&p->fp_work_lock);
}
for_each_online_cpu(cpu) {
bnx2fc_percpu_thread_create(cpu);
}
/* Initialize per CPU interrupt thread */
register_hotcpu_notifier(&bnx2fc_cpu_notifier);
cnic_register_driver(CNIC_ULP_FCOE, &bnx2fc_cnic_cb);
return 0;
free_wq:
destroy_workqueue(bnx2fc_wq);
release_bt:
bnx2fc_release_transport();
detach_ft:
fcoe_transport_detach(&bnx2fc_transport);
out:
return rc;
}
static void __exit bnx2fc_mod_exit(void)
{
LIST_HEAD(to_be_deleted);
struct bnx2fc_hba *hba, *next;
struct fcoe_percpu_s *bg;
struct task_struct *l2_thread;
struct sk_buff *skb;
unsigned int cpu = 0;
/*
* NOTE: Since cnic calls register_driver routine rtnl_lock,
* it will have higher precedence than bnx2fc_dev_lock.
* unregister_device() cannot be called with bnx2fc_dev_lock
* held.
*/
mutex_lock(&bnx2fc_dev_lock);
list_splice(&adapter_list, &to_be_deleted);
INIT_LIST_HEAD(&adapter_list);
adapter_count = 0;
mutex_unlock(&bnx2fc_dev_lock);
/* Unregister with cnic */
list_for_each_entry_safe(hba, next, &to_be_deleted, list) {
list_del_init(&hba->list);
printk(KERN_ERR PFX "MOD_EXIT:destroy hba = 0x%p\n",
hba);
bnx2fc_ulp_stop(hba);
/* unregister cnic device */
if (test_and_clear_bit(BNX2FC_CNIC_REGISTERED,
&hba->reg_with_cnic))
hba->cnic->unregister_device(hba->cnic,
CNIC_ULP_FCOE);
bnx2fc_hba_destroy(hba);
}
cnic_unregister_driver(CNIC_ULP_FCOE);
/* Destroy global thread */
bg = &bnx2fc_global;
spin_lock_bh(&bg->fcoe_rx_list.lock);
l2_thread = bg->thread;
bg->thread = NULL;
while ((skb = __skb_dequeue(&bg->fcoe_rx_list)) != NULL)
kfree_skb(skb);
spin_unlock_bh(&bg->fcoe_rx_list.lock);
if (l2_thread)
kthread_stop(l2_thread);
unregister_hotcpu_notifier(&bnx2fc_cpu_notifier);
/* Destroy per cpu threads */
for_each_online_cpu(cpu) {
bnx2fc_percpu_thread_destroy(cpu);
}
destroy_workqueue(bnx2fc_wq);
/*
* detach from scsi transport
* must happen after all destroys are done
*/
bnx2fc_release_transport();
/* detach from fcoe transport */
fcoe_transport_detach(&bnx2fc_transport);
}
module_init(bnx2fc_mod_init);
module_exit(bnx2fc_mod_exit);
static struct fc_function_template bnx2fc_transport_function = {
.show_host_node_name = 1,
.show_host_port_name = 1,
.show_host_supported_classes = 1,
.show_host_supported_fc4s = 1,
.show_host_active_fc4s = 1,
.show_host_maxframe_size = 1,
.show_host_port_id = 1,
.show_host_supported_speeds = 1,
.get_host_speed = fc_get_host_speed,
.show_host_speed = 1,
.show_host_port_type = 1,
.get_host_port_state = fc_get_host_port_state,
.show_host_port_state = 1,
.show_host_symbolic_name = 1,
.dd_fcrport_size = (sizeof(struct fc_rport_libfc_priv) +
sizeof(struct bnx2fc_rport)),
.show_rport_maxframe_size = 1,
.show_rport_supported_classes = 1,
.show_host_fabric_name = 1,
.show_starget_node_name = 1,
.show_starget_port_name = 1,
.show_starget_port_id = 1,
.set_rport_dev_loss_tmo = fc_set_rport_loss_tmo,
.show_rport_dev_loss_tmo = 1,
.get_fc_host_stats = bnx2fc_get_host_stats,
.issue_fc_host_lip = bnx2fc_fcoe_reset,
.terminate_rport_io = fc_rport_terminate_io,
.vport_create = bnx2fc_vport_create,
.vport_delete = bnx2fc_vport_destroy,
.vport_disable = bnx2fc_vport_disable,
.bsg_request = fc_lport_bsg_request,
};
static struct fc_function_template bnx2fc_vport_xport_function = {
.show_host_node_name = 1,
.show_host_port_name = 1,
.show_host_supported_classes = 1,
.show_host_supported_fc4s = 1,
.show_host_active_fc4s = 1,
.show_host_maxframe_size = 1,
.show_host_port_id = 1,
.show_host_supported_speeds = 1,
.get_host_speed = fc_get_host_speed,
.show_host_speed = 1,
.show_host_port_type = 1,
.get_host_port_state = fc_get_host_port_state,
.show_host_port_state = 1,
.show_host_symbolic_name = 1,
.dd_fcrport_size = (sizeof(struct fc_rport_libfc_priv) +
sizeof(struct bnx2fc_rport)),
.show_rport_maxframe_size = 1,
.show_rport_supported_classes = 1,
.show_host_fabric_name = 1,
.show_starget_node_name = 1,
.show_starget_port_name = 1,
.show_starget_port_id = 1,
.set_rport_dev_loss_tmo = fc_set_rport_loss_tmo,
.show_rport_dev_loss_tmo = 1,
.get_fc_host_stats = fc_get_host_stats,
.issue_fc_host_lip = bnx2fc_fcoe_reset,
.terminate_rport_io = fc_rport_terminate_io,
.bsg_request = fc_lport_bsg_request,
};
/**
* scsi_host_template structure used while registering with SCSI-ml
*/
static struct scsi_host_template bnx2fc_shost_template = {
.module = THIS_MODULE,
.name = "Broadcom Offload FCoE Initiator",
.queuecommand = bnx2fc_queuecommand,
.eh_abort_handler = bnx2fc_eh_abort, /* abts */
.eh_device_reset_handler = bnx2fc_eh_device_reset, /* lun reset */
.eh_target_reset_handler = bnx2fc_eh_target_reset, /* tgt reset */
.eh_host_reset_handler = fc_eh_host_reset,
.slave_alloc = fc_slave_alloc,
.change_queue_depth = fc_change_queue_depth,
.change_queue_type = fc_change_queue_type,
.this_id = -1,
.cmd_per_lun = 3,
.can_queue = BNX2FC_CAN_QUEUE,
.use_clustering = ENABLE_CLUSTERING,
.sg_tablesize = BNX2FC_MAX_BDS_PER_CMD,
.max_sectors = 512,
};
static struct libfc_function_template bnx2fc_libfc_fcn_templ = {
.frame_send = bnx2fc_xmit,
.elsct_send = bnx2fc_elsct_send,
.fcp_abort_io = bnx2fc_abort_io,
.fcp_cleanup = bnx2fc_cleanup,
.get_lesb = bnx2fc_get_lesb,
.rport_event_callback = bnx2fc_rport_event_handler,
};
/**
* bnx2fc_cnic_cb - global template of bnx2fc - cnic driver interface
* structure carrying callback function pointers
*/
static struct cnic_ulp_ops bnx2fc_cnic_cb = {
.owner = THIS_MODULE,
.cnic_init = bnx2fc_ulp_init,
.cnic_exit = bnx2fc_ulp_exit,
.cnic_start = bnx2fc_ulp_start,
.cnic_stop = bnx2fc_ulp_stop,
.indicate_kcqes = bnx2fc_indicate_kcqe,
.indicate_netevent = bnx2fc_indicate_netevent,
};
| gpl-2.0 |
showp1984/bricked-mako | net/bridge/netfilter/ebtables.c | 4302 | 63137 | /*
* ebtables
*
* Author:
* Bart De Schuymer <bdschuym@pandora.be>
*
* ebtables.c,v 2.0, July, 2002
*
* This code is stongly inspired on the iptables code which is
* Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kmod.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter_bridge/ebtables.h>
#include <linux/spinlock.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <linux/smp.h>
#include <linux/cpumask.h>
#include <net/sock.h>
/* needed for logical [in,out]-dev filtering */
#include "../br_private.h"
#define BUGPRINT(format, args...) printk("kernel msg: ebtables bug: please "\
"report to author: "format, ## args)
/* #define BUGPRINT(format, args...) */
/*
* Each cpu has its own set of counters, so there is no need for write_lock in
* the softirq
* For reading or updating the counters, the user context needs to
* get a write_lock
*/
/* The size of each set of counters is altered to get cache alignment */
#define SMP_ALIGN(x) (((x) + SMP_CACHE_BYTES-1) & ~(SMP_CACHE_BYTES-1))
#define COUNTER_OFFSET(n) (SMP_ALIGN(n * sizeof(struct ebt_counter)))
#define COUNTER_BASE(c, n, cpu) ((struct ebt_counter *)(((char *)c) + \
COUNTER_OFFSET(n) * cpu))
static DEFINE_MUTEX(ebt_mutex);
#ifdef CONFIG_COMPAT
static void ebt_standard_compat_from_user(void *dst, const void *src)
{
int v = *(compat_int_t *)src;
if (v >= 0)
v += xt_compat_calc_jump(NFPROTO_BRIDGE, v);
memcpy(dst, &v, sizeof(v));
}
static int ebt_standard_compat_to_user(void __user *dst, const void *src)
{
compat_int_t cv = *(int *)src;
if (cv >= 0)
cv -= xt_compat_calc_jump(NFPROTO_BRIDGE, cv);
return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0;
}
#endif
static struct xt_target ebt_standard_target = {
.name = "standard",
.revision = 0,
.family = NFPROTO_BRIDGE,
.targetsize = sizeof(int),
#ifdef CONFIG_COMPAT
.compatsize = sizeof(compat_int_t),
.compat_from_user = ebt_standard_compat_from_user,
.compat_to_user = ebt_standard_compat_to_user,
#endif
};
static inline int
ebt_do_watcher(const struct ebt_entry_watcher *w, struct sk_buff *skb,
struct xt_action_param *par)
{
par->target = w->u.watcher;
par->targinfo = w->data;
w->u.watcher->target(skb, par);
/* watchers don't give a verdict */
return 0;
}
static inline int
ebt_do_match(struct ebt_entry_match *m, const struct sk_buff *skb,
struct xt_action_param *par)
{
par->match = m->u.match;
par->matchinfo = m->data;
return m->u.match->match(skb, par) ? EBT_MATCH : EBT_NOMATCH;
}
static inline int
ebt_dev_check(const char *entry, const struct net_device *device)
{
int i = 0;
const char *devname;
if (*entry == '\0')
return 0;
if (!device)
return 1;
devname = device->name;
/* 1 is the wildcard token */
while (entry[i] != '\0' && entry[i] != 1 && entry[i] == devname[i])
i++;
return (devname[i] != entry[i] && entry[i] != 1);
}
#define FWINV2(bool,invflg) ((bool) ^ !!(e->invflags & invflg))
/* process standard matches */
static inline int
ebt_basic_match(const struct ebt_entry *e, const struct sk_buff *skb,
const struct net_device *in, const struct net_device *out)
{
const struct ethhdr *h = eth_hdr(skb);
const struct net_bridge_port *p;
__be16 ethproto;
int verdict, i;
if (vlan_tx_tag_present(skb))
ethproto = htons(ETH_P_8021Q);
else
ethproto = h->h_proto;
if (e->bitmask & EBT_802_3) {
if (FWINV2(ntohs(ethproto) >= 1536, EBT_IPROTO))
return 1;
} else if (!(e->bitmask & EBT_NOPROTO) &&
FWINV2(e->ethproto != ethproto, EBT_IPROTO))
return 1;
if (FWINV2(ebt_dev_check(e->in, in), EBT_IIN))
return 1;
if (FWINV2(ebt_dev_check(e->out, out), EBT_IOUT))
return 1;
/* rcu_read_lock()ed by nf_hook_slow */
if (in && (p = br_port_get_rcu(in)) != NULL &&
FWINV2(ebt_dev_check(e->logical_in, p->br->dev), EBT_ILOGICALIN))
return 1;
if (out && (p = br_port_get_rcu(out)) != NULL &&
FWINV2(ebt_dev_check(e->logical_out, p->br->dev), EBT_ILOGICALOUT))
return 1;
if (e->bitmask & EBT_SOURCEMAC) {
verdict = 0;
for (i = 0; i < 6; i++)
verdict |= (h->h_source[i] ^ e->sourcemac[i]) &
e->sourcemsk[i];
if (FWINV2(verdict != 0, EBT_ISOURCE) )
return 1;
}
if (e->bitmask & EBT_DESTMAC) {
verdict = 0;
for (i = 0; i < 6; i++)
verdict |= (h->h_dest[i] ^ e->destmac[i]) &
e->destmsk[i];
if (FWINV2(verdict != 0, EBT_IDEST) )
return 1;
}
return 0;
}
static inline __pure
struct ebt_entry *ebt_next_entry(const struct ebt_entry *entry)
{
return (void *)entry + entry->next_offset;
}
/* Do some firewalling */
unsigned int ebt_do_table (unsigned int hook, struct sk_buff *skb,
const struct net_device *in, const struct net_device *out,
struct ebt_table *table)
{
int i, nentries;
struct ebt_entry *point;
struct ebt_counter *counter_base, *cb_base;
const struct ebt_entry_target *t;
int verdict, sp = 0;
struct ebt_chainstack *cs;
struct ebt_entries *chaininfo;
const char *base;
const struct ebt_table_info *private;
struct xt_action_param acpar;
acpar.family = NFPROTO_BRIDGE;
acpar.in = in;
acpar.out = out;
acpar.hotdrop = false;
acpar.hooknum = hook;
read_lock_bh(&table->lock);
private = table->private;
cb_base = COUNTER_BASE(private->counters, private->nentries,
smp_processor_id());
if (private->chainstack)
cs = private->chainstack[smp_processor_id()];
else
cs = NULL;
chaininfo = private->hook_entry[hook];
nentries = private->hook_entry[hook]->nentries;
point = (struct ebt_entry *)(private->hook_entry[hook]->data);
counter_base = cb_base + private->hook_entry[hook]->counter_offset;
/* base for chain jumps */
base = private->entries;
i = 0;
while (i < nentries) {
if (ebt_basic_match(point, skb, in, out))
goto letscontinue;
if (EBT_MATCH_ITERATE(point, ebt_do_match, skb, &acpar) != 0)
goto letscontinue;
if (acpar.hotdrop) {
read_unlock_bh(&table->lock);
return NF_DROP;
}
/* increase counter */
(*(counter_base + i)).pcnt++;
(*(counter_base + i)).bcnt += skb->len;
/* these should only watch: not modify, nor tell us
what to do with the packet */
EBT_WATCHER_ITERATE(point, ebt_do_watcher, skb, &acpar);
t = (struct ebt_entry_target *)
(((char *)point) + point->target_offset);
/* standard target */
if (!t->u.target->target)
verdict = ((struct ebt_standard_target *)t)->verdict;
else {
acpar.target = t->u.target;
acpar.targinfo = t->data;
verdict = t->u.target->target(skb, &acpar);
}
if (verdict == EBT_ACCEPT) {
read_unlock_bh(&table->lock);
return NF_ACCEPT;
}
if (verdict == EBT_DROP) {
read_unlock_bh(&table->lock);
return NF_DROP;
}
if (verdict == EBT_RETURN) {
letsreturn:
#ifdef CONFIG_NETFILTER_DEBUG
if (sp == 0) {
BUGPRINT("RETURN on base chain");
/* act like this is EBT_CONTINUE */
goto letscontinue;
}
#endif
sp--;
/* put all the local variables right */
i = cs[sp].n;
chaininfo = cs[sp].chaininfo;
nentries = chaininfo->nentries;
point = cs[sp].e;
counter_base = cb_base +
chaininfo->counter_offset;
continue;
}
if (verdict == EBT_CONTINUE)
goto letscontinue;
#ifdef CONFIG_NETFILTER_DEBUG
if (verdict < 0) {
BUGPRINT("bogus standard verdict\n");
read_unlock_bh(&table->lock);
return NF_DROP;
}
#endif
/* jump to a udc */
cs[sp].n = i + 1;
cs[sp].chaininfo = chaininfo;
cs[sp].e = ebt_next_entry(point);
i = 0;
chaininfo = (struct ebt_entries *) (base + verdict);
#ifdef CONFIG_NETFILTER_DEBUG
if (chaininfo->distinguisher) {
BUGPRINT("jump to non-chain\n");
read_unlock_bh(&table->lock);
return NF_DROP;
}
#endif
nentries = chaininfo->nentries;
point = (struct ebt_entry *)chaininfo->data;
counter_base = cb_base + chaininfo->counter_offset;
sp++;
continue;
letscontinue:
point = ebt_next_entry(point);
i++;
}
/* I actually like this :) */
if (chaininfo->policy == EBT_RETURN)
goto letsreturn;
if (chaininfo->policy == EBT_ACCEPT) {
read_unlock_bh(&table->lock);
return NF_ACCEPT;
}
read_unlock_bh(&table->lock);
return NF_DROP;
}
/* If it succeeds, returns element and locks mutex */
static inline void *
find_inlist_lock_noload(struct list_head *head, const char *name, int *error,
struct mutex *mutex)
{
struct {
struct list_head list;
char name[EBT_FUNCTION_MAXNAMELEN];
} *e;
*error = mutex_lock_interruptible(mutex);
if (*error != 0)
return NULL;
list_for_each_entry(e, head, list) {
if (strcmp(e->name, name) == 0)
return e;
}
*error = -ENOENT;
mutex_unlock(mutex);
return NULL;
}
static void *
find_inlist_lock(struct list_head *head, const char *name, const char *prefix,
int *error, struct mutex *mutex)
{
return try_then_request_module(
find_inlist_lock_noload(head, name, error, mutex),
"%s%s", prefix, name);
}
static inline struct ebt_table *
find_table_lock(struct net *net, const char *name, int *error,
struct mutex *mutex)
{
return find_inlist_lock(&net->xt.tables[NFPROTO_BRIDGE], name,
"ebtable_", error, mutex);
}
static inline int
ebt_check_match(struct ebt_entry_match *m, struct xt_mtchk_param *par,
unsigned int *cnt)
{
const struct ebt_entry *e = par->entryinfo;
struct xt_match *match;
size_t left = ((char *)e + e->watchers_offset) - (char *)m;
int ret;
if (left < sizeof(struct ebt_entry_match) ||
left - sizeof(struct ebt_entry_match) < m->match_size)
return -EINVAL;
match = xt_request_find_match(NFPROTO_BRIDGE, m->u.name, 0);
if (IS_ERR(match))
return PTR_ERR(match);
m->u.match = match;
par->match = match;
par->matchinfo = m->data;
ret = xt_check_match(par, m->match_size,
e->ethproto, e->invflags & EBT_IPROTO);
if (ret < 0) {
module_put(match->me);
return ret;
}
(*cnt)++;
return 0;
}
static inline int
ebt_check_watcher(struct ebt_entry_watcher *w, struct xt_tgchk_param *par,
unsigned int *cnt)
{
const struct ebt_entry *e = par->entryinfo;
struct xt_target *watcher;
size_t left = ((char *)e + e->target_offset) - (char *)w;
int ret;
if (left < sizeof(struct ebt_entry_watcher) ||
left - sizeof(struct ebt_entry_watcher) < w->watcher_size)
return -EINVAL;
watcher = xt_request_find_target(NFPROTO_BRIDGE, w->u.name, 0);
if (IS_ERR(watcher))
return PTR_ERR(watcher);
w->u.watcher = watcher;
par->target = watcher;
par->targinfo = w->data;
ret = xt_check_target(par, w->watcher_size,
e->ethproto, e->invflags & EBT_IPROTO);
if (ret < 0) {
module_put(watcher->me);
return ret;
}
(*cnt)++;
return 0;
}
static int ebt_verify_pointers(const struct ebt_replace *repl,
struct ebt_table_info *newinfo)
{
unsigned int limit = repl->entries_size;
unsigned int valid_hooks = repl->valid_hooks;
unsigned int offset = 0;
int i;
for (i = 0; i < NF_BR_NUMHOOKS; i++)
newinfo->hook_entry[i] = NULL;
newinfo->entries_size = repl->entries_size;
newinfo->nentries = repl->nentries;
while (offset < limit) {
size_t left = limit - offset;
struct ebt_entry *e = (void *)newinfo->entries + offset;
if (left < sizeof(unsigned int))
break;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if ((valid_hooks & (1 << i)) == 0)
continue;
if ((char __user *)repl->hook_entry[i] ==
repl->entries + offset)
break;
}
if (i != NF_BR_NUMHOOKS || !(e->bitmask & EBT_ENTRY_OR_ENTRIES)) {
if (e->bitmask != 0) {
/* we make userspace set this right,
so there is no misunderstanding */
BUGPRINT("EBT_ENTRY_OR_ENTRIES shouldn't be set "
"in distinguisher\n");
return -EINVAL;
}
if (i != NF_BR_NUMHOOKS)
newinfo->hook_entry[i] = (struct ebt_entries *)e;
if (left < sizeof(struct ebt_entries))
break;
offset += sizeof(struct ebt_entries);
} else {
if (left < sizeof(struct ebt_entry))
break;
if (left < e->next_offset)
break;
if (e->next_offset < sizeof(struct ebt_entry))
return -EINVAL;
offset += e->next_offset;
}
}
if (offset != limit) {
BUGPRINT("entries_size too small\n");
return -EINVAL;
}
/* check if all valid hooks have a chain */
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if (!newinfo->hook_entry[i] &&
(valid_hooks & (1 << i))) {
BUGPRINT("Valid hook without chain\n");
return -EINVAL;
}
}
return 0;
}
/*
* this one is very careful, as it is the first function
* to parse the userspace data
*/
static inline int
ebt_check_entry_size_and_hooks(const struct ebt_entry *e,
const struct ebt_table_info *newinfo,
unsigned int *n, unsigned int *cnt,
unsigned int *totalcnt, unsigned int *udc_cnt)
{
int i;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if ((void *)e == (void *)newinfo->hook_entry[i])
break;
}
/* beginning of a new chain
if i == NF_BR_NUMHOOKS it must be a user defined chain */
if (i != NF_BR_NUMHOOKS || !e->bitmask) {
/* this checks if the previous chain has as many entries
as it said it has */
if (*n != *cnt) {
BUGPRINT("nentries does not equal the nr of entries "
"in the chain\n");
return -EINVAL;
}
if (((struct ebt_entries *)e)->policy != EBT_DROP &&
((struct ebt_entries *)e)->policy != EBT_ACCEPT) {
/* only RETURN from udc */
if (i != NF_BR_NUMHOOKS ||
((struct ebt_entries *)e)->policy != EBT_RETURN) {
BUGPRINT("bad policy\n");
return -EINVAL;
}
}
if (i == NF_BR_NUMHOOKS) /* it's a user defined chain */
(*udc_cnt)++;
if (((struct ebt_entries *)e)->counter_offset != *totalcnt) {
BUGPRINT("counter_offset != totalcnt");
return -EINVAL;
}
*n = ((struct ebt_entries *)e)->nentries;
*cnt = 0;
return 0;
}
/* a plain old entry, heh */
if (sizeof(struct ebt_entry) > e->watchers_offset ||
e->watchers_offset > e->target_offset ||
e->target_offset >= e->next_offset) {
BUGPRINT("entry offsets not in right order\n");
return -EINVAL;
}
/* this is not checked anywhere else */
if (e->next_offset - e->target_offset < sizeof(struct ebt_entry_target)) {
BUGPRINT("target size too small\n");
return -EINVAL;
}
(*cnt)++;
(*totalcnt)++;
return 0;
}
struct ebt_cl_stack
{
struct ebt_chainstack cs;
int from;
unsigned int hookmask;
};
/*
* we need these positions to check that the jumps to a different part of the
* entries is a jump to the beginning of a new chain.
*/
static inline int
ebt_get_udc_positions(struct ebt_entry *e, struct ebt_table_info *newinfo,
unsigned int *n, struct ebt_cl_stack *udc)
{
int i;
/* we're only interested in chain starts */
if (e->bitmask)
return 0;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if (newinfo->hook_entry[i] == (struct ebt_entries *)e)
break;
}
/* only care about udc */
if (i != NF_BR_NUMHOOKS)
return 0;
udc[*n].cs.chaininfo = (struct ebt_entries *)e;
/* these initialisations are depended on later in check_chainloops() */
udc[*n].cs.n = 0;
udc[*n].hookmask = 0;
(*n)++;
return 0;
}
static inline int
ebt_cleanup_match(struct ebt_entry_match *m, struct net *net, unsigned int *i)
{
struct xt_mtdtor_param par;
if (i && (*i)-- == 0)
return 1;
par.net = net;
par.match = m->u.match;
par.matchinfo = m->data;
par.family = NFPROTO_BRIDGE;
if (par.match->destroy != NULL)
par.match->destroy(&par);
module_put(par.match->me);
return 0;
}
static inline int
ebt_cleanup_watcher(struct ebt_entry_watcher *w, struct net *net, unsigned int *i)
{
struct xt_tgdtor_param par;
if (i && (*i)-- == 0)
return 1;
par.net = net;
par.target = w->u.watcher;
par.targinfo = w->data;
par.family = NFPROTO_BRIDGE;
if (par.target->destroy != NULL)
par.target->destroy(&par);
module_put(par.target->me);
return 0;
}
static inline int
ebt_cleanup_entry(struct ebt_entry *e, struct net *net, unsigned int *cnt)
{
struct xt_tgdtor_param par;
struct ebt_entry_target *t;
if (e->bitmask == 0)
return 0;
/* we're done */
if (cnt && (*cnt)-- == 0)
return 1;
EBT_WATCHER_ITERATE(e, ebt_cleanup_watcher, net, NULL);
EBT_MATCH_ITERATE(e, ebt_cleanup_match, net, NULL);
t = (struct ebt_entry_target *)(((char *)e) + e->target_offset);
par.net = net;
par.target = t->u.target;
par.targinfo = t->data;
par.family = NFPROTO_BRIDGE;
if (par.target->destroy != NULL)
par.target->destroy(&par);
module_put(par.target->me);
return 0;
}
static inline int
ebt_check_entry(struct ebt_entry *e, struct net *net,
const struct ebt_table_info *newinfo,
const char *name, unsigned int *cnt,
struct ebt_cl_stack *cl_s, unsigned int udc_cnt)
{
struct ebt_entry_target *t;
struct xt_target *target;
unsigned int i, j, hook = 0, hookmask = 0;
size_t gap;
int ret;
struct xt_mtchk_param mtpar;
struct xt_tgchk_param tgpar;
/* don't mess with the struct ebt_entries */
if (e->bitmask == 0)
return 0;
if (e->bitmask & ~EBT_F_MASK) {
BUGPRINT("Unknown flag for bitmask\n");
return -EINVAL;
}
if (e->invflags & ~EBT_INV_MASK) {
BUGPRINT("Unknown flag for inv bitmask\n");
return -EINVAL;
}
if ( (e->bitmask & EBT_NOPROTO) && (e->bitmask & EBT_802_3) ) {
BUGPRINT("NOPROTO & 802_3 not allowed\n");
return -EINVAL;
}
/* what hook do we belong to? */
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if (!newinfo->hook_entry[i])
continue;
if ((char *)newinfo->hook_entry[i] < (char *)e)
hook = i;
else
break;
}
/* (1 << NF_BR_NUMHOOKS) tells the check functions the rule is on
a base chain */
if (i < NF_BR_NUMHOOKS)
hookmask = (1 << hook) | (1 << NF_BR_NUMHOOKS);
else {
for (i = 0; i < udc_cnt; i++)
if ((char *)(cl_s[i].cs.chaininfo) > (char *)e)
break;
if (i == 0)
hookmask = (1 << hook) | (1 << NF_BR_NUMHOOKS);
else
hookmask = cl_s[i - 1].hookmask;
}
i = 0;
mtpar.net = tgpar.net = net;
mtpar.table = tgpar.table = name;
mtpar.entryinfo = tgpar.entryinfo = e;
mtpar.hook_mask = tgpar.hook_mask = hookmask;
mtpar.family = tgpar.family = NFPROTO_BRIDGE;
ret = EBT_MATCH_ITERATE(e, ebt_check_match, &mtpar, &i);
if (ret != 0)
goto cleanup_matches;
j = 0;
ret = EBT_WATCHER_ITERATE(e, ebt_check_watcher, &tgpar, &j);
if (ret != 0)
goto cleanup_watchers;
t = (struct ebt_entry_target *)(((char *)e) + e->target_offset);
gap = e->next_offset - e->target_offset;
target = xt_request_find_target(NFPROTO_BRIDGE, t->u.name, 0);
if (IS_ERR(target)) {
ret = PTR_ERR(target);
goto cleanup_watchers;
}
t->u.target = target;
if (t->u.target == &ebt_standard_target) {
if (gap < sizeof(struct ebt_standard_target)) {
BUGPRINT("Standard target size too big\n");
ret = -EFAULT;
goto cleanup_watchers;
}
if (((struct ebt_standard_target *)t)->verdict <
-NUM_STANDARD_TARGETS) {
BUGPRINT("Invalid standard target\n");
ret = -EFAULT;
goto cleanup_watchers;
}
} else if (t->target_size > gap - sizeof(struct ebt_entry_target)) {
module_put(t->u.target->me);
ret = -EFAULT;
goto cleanup_watchers;
}
tgpar.target = target;
tgpar.targinfo = t->data;
ret = xt_check_target(&tgpar, t->target_size,
e->ethproto, e->invflags & EBT_IPROTO);
if (ret < 0) {
module_put(target->me);
goto cleanup_watchers;
}
(*cnt)++;
return 0;
cleanup_watchers:
EBT_WATCHER_ITERATE(e, ebt_cleanup_watcher, net, &j);
cleanup_matches:
EBT_MATCH_ITERATE(e, ebt_cleanup_match, net, &i);
return ret;
}
/*
* checks for loops and sets the hook mask for udc
* the hook mask for udc tells us from which base chains the udc can be
* accessed. This mask is a parameter to the check() functions of the extensions
*/
static int check_chainloops(const struct ebt_entries *chain, struct ebt_cl_stack *cl_s,
unsigned int udc_cnt, unsigned int hooknr, char *base)
{
int i, chain_nr = -1, pos = 0, nentries = chain->nentries, verdict;
const struct ebt_entry *e = (struct ebt_entry *)chain->data;
const struct ebt_entry_target *t;
while (pos < nentries || chain_nr != -1) {
/* end of udc, go back one 'recursion' step */
if (pos == nentries) {
/* put back values of the time when this chain was called */
e = cl_s[chain_nr].cs.e;
if (cl_s[chain_nr].from != -1)
nentries =
cl_s[cl_s[chain_nr].from].cs.chaininfo->nentries;
else
nentries = chain->nentries;
pos = cl_s[chain_nr].cs.n;
/* make sure we won't see a loop that isn't one */
cl_s[chain_nr].cs.n = 0;
chain_nr = cl_s[chain_nr].from;
if (pos == nentries)
continue;
}
t = (struct ebt_entry_target *)
(((char *)e) + e->target_offset);
if (strcmp(t->u.name, EBT_STANDARD_TARGET))
goto letscontinue;
if (e->target_offset + sizeof(struct ebt_standard_target) >
e->next_offset) {
BUGPRINT("Standard target size too big\n");
return -1;
}
verdict = ((struct ebt_standard_target *)t)->verdict;
if (verdict >= 0) { /* jump to another chain */
struct ebt_entries *hlp2 =
(struct ebt_entries *)(base + verdict);
for (i = 0; i < udc_cnt; i++)
if (hlp2 == cl_s[i].cs.chaininfo)
break;
/* bad destination or loop */
if (i == udc_cnt) {
BUGPRINT("bad destination\n");
return -1;
}
if (cl_s[i].cs.n) {
BUGPRINT("loop\n");
return -1;
}
if (cl_s[i].hookmask & (1 << hooknr))
goto letscontinue;
/* this can't be 0, so the loop test is correct */
cl_s[i].cs.n = pos + 1;
pos = 0;
cl_s[i].cs.e = ebt_next_entry(e);
e = (struct ebt_entry *)(hlp2->data);
nentries = hlp2->nentries;
cl_s[i].from = chain_nr;
chain_nr = i;
/* this udc is accessible from the base chain for hooknr */
cl_s[i].hookmask |= (1 << hooknr);
continue;
}
letscontinue:
e = ebt_next_entry(e);
pos++;
}
return 0;
}
/* do the parsing of the table/chains/entries/matches/watchers/targets, heh */
static int translate_table(struct net *net, const char *name,
struct ebt_table_info *newinfo)
{
unsigned int i, j, k, udc_cnt;
int ret;
struct ebt_cl_stack *cl_s = NULL; /* used in the checking for chain loops */
i = 0;
while (i < NF_BR_NUMHOOKS && !newinfo->hook_entry[i])
i++;
if (i == NF_BR_NUMHOOKS) {
BUGPRINT("No valid hooks specified\n");
return -EINVAL;
}
if (newinfo->hook_entry[i] != (struct ebt_entries *)newinfo->entries) {
BUGPRINT("Chains don't start at beginning\n");
return -EINVAL;
}
/* make sure chains are ordered after each other in same order
as their corresponding hooks */
for (j = i + 1; j < NF_BR_NUMHOOKS; j++) {
if (!newinfo->hook_entry[j])
continue;
if (newinfo->hook_entry[j] <= newinfo->hook_entry[i]) {
BUGPRINT("Hook order must be followed\n");
return -EINVAL;
}
i = j;
}
/* do some early checkings and initialize some things */
i = 0; /* holds the expected nr. of entries for the chain */
j = 0; /* holds the up to now counted entries for the chain */
k = 0; /* holds the total nr. of entries, should equal
newinfo->nentries afterwards */
udc_cnt = 0; /* will hold the nr. of user defined chains (udc) */
ret = EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_check_entry_size_and_hooks, newinfo,
&i, &j, &k, &udc_cnt);
if (ret != 0)
return ret;
if (i != j) {
BUGPRINT("nentries does not equal the nr of entries in the "
"(last) chain\n");
return -EINVAL;
}
if (k != newinfo->nentries) {
BUGPRINT("Total nentries is wrong\n");
return -EINVAL;
}
/* get the location of the udc, put them in an array
while we're at it, allocate the chainstack */
if (udc_cnt) {
/* this will get free'd in do_replace()/ebt_register_table()
if an error occurs */
newinfo->chainstack =
vmalloc(nr_cpu_ids * sizeof(*(newinfo->chainstack)));
if (!newinfo->chainstack)
return -ENOMEM;
for_each_possible_cpu(i) {
newinfo->chainstack[i] =
vmalloc(udc_cnt * sizeof(*(newinfo->chainstack[0])));
if (!newinfo->chainstack[i]) {
while (i)
vfree(newinfo->chainstack[--i]);
vfree(newinfo->chainstack);
newinfo->chainstack = NULL;
return -ENOMEM;
}
}
cl_s = vmalloc(udc_cnt * sizeof(*cl_s));
if (!cl_s)
return -ENOMEM;
i = 0; /* the i'th udc */
EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_get_udc_positions, newinfo, &i, cl_s);
/* sanity check */
if (i != udc_cnt) {
BUGPRINT("i != udc_cnt\n");
vfree(cl_s);
return -EFAULT;
}
}
/* Check for loops */
for (i = 0; i < NF_BR_NUMHOOKS; i++)
if (newinfo->hook_entry[i])
if (check_chainloops(newinfo->hook_entry[i],
cl_s, udc_cnt, i, newinfo->entries)) {
vfree(cl_s);
return -EINVAL;
}
/* we now know the following (along with E=mc²):
- the nr of entries in each chain is right
- the size of the allocated space is right
- all valid hooks have a corresponding chain
- there are no loops
- wrong data can still be on the level of a single entry
- could be there are jumps to places that are not the
beginning of a chain. This can only occur in chains that
are not accessible from any base chains, so we don't care. */
/* used to know what we need to clean up if something goes wrong */
i = 0;
ret = EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_check_entry, net, newinfo, name, &i, cl_s, udc_cnt);
if (ret != 0) {
EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_cleanup_entry, net, &i);
}
vfree(cl_s);
return ret;
}
/* called under write_lock */
static void get_counters(const struct ebt_counter *oldcounters,
struct ebt_counter *counters, unsigned int nentries)
{
int i, cpu;
struct ebt_counter *counter_base;
/* counters of cpu 0 */
memcpy(counters, oldcounters,
sizeof(struct ebt_counter) * nentries);
/* add other counters to those of cpu 0 */
for_each_possible_cpu(cpu) {
if (cpu == 0)
continue;
counter_base = COUNTER_BASE(oldcounters, nentries, cpu);
for (i = 0; i < nentries; i++) {
counters[i].pcnt += counter_base[i].pcnt;
counters[i].bcnt += counter_base[i].bcnt;
}
}
}
static int do_replace_finish(struct net *net, struct ebt_replace *repl,
struct ebt_table_info *newinfo)
{
int ret, i;
struct ebt_counter *counterstmp = NULL;
/* used to be able to unlock earlier */
struct ebt_table_info *table;
struct ebt_table *t;
/* the user wants counters back
the check on the size is done later, when we have the lock */
if (repl->num_counters) {
unsigned long size = repl->num_counters * sizeof(*counterstmp);
counterstmp = vmalloc(size);
if (!counterstmp)
return -ENOMEM;
}
newinfo->chainstack = NULL;
ret = ebt_verify_pointers(repl, newinfo);
if (ret != 0)
goto free_counterstmp;
ret = translate_table(net, repl->name, newinfo);
if (ret != 0)
goto free_counterstmp;
t = find_table_lock(net, repl->name, &ret, &ebt_mutex);
if (!t) {
ret = -ENOENT;
goto free_iterate;
}
/* the table doesn't like it */
if (t->check && (ret = t->check(newinfo, repl->valid_hooks)))
goto free_unlock;
if (repl->num_counters && repl->num_counters != t->private->nentries) {
BUGPRINT("Wrong nr. of counters requested\n");
ret = -EINVAL;
goto free_unlock;
}
/* we have the mutex lock, so no danger in reading this pointer */
table = t->private;
/* make sure the table can only be rmmod'ed if it contains no rules */
if (!table->nentries && newinfo->nentries && !try_module_get(t->me)) {
ret = -ENOENT;
goto free_unlock;
} else if (table->nentries && !newinfo->nentries)
module_put(t->me);
/* we need an atomic snapshot of the counters */
write_lock_bh(&t->lock);
if (repl->num_counters)
get_counters(t->private->counters, counterstmp,
t->private->nentries);
t->private = newinfo;
write_unlock_bh(&t->lock);
mutex_unlock(&ebt_mutex);
/* so, a user can change the chains while having messed up her counter
allocation. Only reason why this is done is because this way the lock
is held only once, while this doesn't bring the kernel into a
dangerous state. */
if (repl->num_counters &&
copy_to_user(repl->counters, counterstmp,
repl->num_counters * sizeof(struct ebt_counter))) {
ret = -EFAULT;
}
else
ret = 0;
/* decrease module count and free resources */
EBT_ENTRY_ITERATE(table->entries, table->entries_size,
ebt_cleanup_entry, net, NULL);
vfree(table->entries);
if (table->chainstack) {
for_each_possible_cpu(i)
vfree(table->chainstack[i]);
vfree(table->chainstack);
}
vfree(table);
vfree(counterstmp);
return ret;
free_unlock:
mutex_unlock(&ebt_mutex);
free_iterate:
EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_cleanup_entry, net, NULL);
free_counterstmp:
vfree(counterstmp);
/* can be initialized in translate_table() */
if (newinfo->chainstack) {
for_each_possible_cpu(i)
vfree(newinfo->chainstack[i]);
vfree(newinfo->chainstack);
}
return ret;
}
/* replace the table */
static int do_replace(struct net *net, const void __user *user,
unsigned int len)
{
int ret, countersize;
struct ebt_table_info *newinfo;
struct ebt_replace tmp;
if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
return -EFAULT;
if (len != sizeof(tmp) + tmp.entries_size) {
BUGPRINT("Wrong len argument\n");
return -EINVAL;
}
if (tmp.entries_size == 0) {
BUGPRINT("Entries_size never zero\n");
return -EINVAL;
}
/* overflow check */
if (tmp.nentries >= ((INT_MAX - sizeof(struct ebt_table_info)) /
NR_CPUS - SMP_CACHE_BYTES) / sizeof(struct ebt_counter))
return -ENOMEM;
if (tmp.num_counters >= INT_MAX / sizeof(struct ebt_counter))
return -ENOMEM;
tmp.name[sizeof(tmp.name) - 1] = 0;
countersize = COUNTER_OFFSET(tmp.nentries) * nr_cpu_ids;
newinfo = vmalloc(sizeof(*newinfo) + countersize);
if (!newinfo)
return -ENOMEM;
if (countersize)
memset(newinfo->counters, 0, countersize);
newinfo->entries = vmalloc(tmp.entries_size);
if (!newinfo->entries) {
ret = -ENOMEM;
goto free_newinfo;
}
if (copy_from_user(
newinfo->entries, tmp.entries, tmp.entries_size) != 0) {
BUGPRINT("Couldn't copy entries from userspace\n");
ret = -EFAULT;
goto free_entries;
}
ret = do_replace_finish(net, &tmp, newinfo);
if (ret == 0)
return ret;
free_entries:
vfree(newinfo->entries);
free_newinfo:
vfree(newinfo);
return ret;
}
struct ebt_table *
ebt_register_table(struct net *net, const struct ebt_table *input_table)
{
struct ebt_table_info *newinfo;
struct ebt_table *t, *table;
struct ebt_replace_kernel *repl;
int ret, i, countersize;
void *p;
if (input_table == NULL || (repl = input_table->table) == NULL ||
repl->entries == NULL || repl->entries_size == 0 ||
repl->counters != NULL || input_table->private != NULL) {
BUGPRINT("Bad table data for ebt_register_table!!!\n");
return ERR_PTR(-EINVAL);
}
/* Don't add one table to multiple lists. */
table = kmemdup(input_table, sizeof(struct ebt_table), GFP_KERNEL);
if (!table) {
ret = -ENOMEM;
goto out;
}
countersize = COUNTER_OFFSET(repl->nentries) * nr_cpu_ids;
newinfo = vmalloc(sizeof(*newinfo) + countersize);
ret = -ENOMEM;
if (!newinfo)
goto free_table;
p = vmalloc(repl->entries_size);
if (!p)
goto free_newinfo;
memcpy(p, repl->entries, repl->entries_size);
newinfo->entries = p;
newinfo->entries_size = repl->entries_size;
newinfo->nentries = repl->nentries;
if (countersize)
memset(newinfo->counters, 0, countersize);
/* fill in newinfo and parse the entries */
newinfo->chainstack = NULL;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if ((repl->valid_hooks & (1 << i)) == 0)
newinfo->hook_entry[i] = NULL;
else
newinfo->hook_entry[i] = p +
((char *)repl->hook_entry[i] - repl->entries);
}
ret = translate_table(net, repl->name, newinfo);
if (ret != 0) {
BUGPRINT("Translate_table failed\n");
goto free_chainstack;
}
if (table->check && table->check(newinfo, table->valid_hooks)) {
BUGPRINT("The table doesn't like its own initial data, lol\n");
ret = -EINVAL;
goto free_chainstack;
}
table->private = newinfo;
rwlock_init(&table->lock);
ret = mutex_lock_interruptible(&ebt_mutex);
if (ret != 0)
goto free_chainstack;
list_for_each_entry(t, &net->xt.tables[NFPROTO_BRIDGE], list) {
if (strcmp(t->name, table->name) == 0) {
ret = -EEXIST;
BUGPRINT("Table name already exists\n");
goto free_unlock;
}
}
/* Hold a reference count if the chains aren't empty */
if (newinfo->nentries && !try_module_get(table->me)) {
ret = -ENOENT;
goto free_unlock;
}
list_add(&table->list, &net->xt.tables[NFPROTO_BRIDGE]);
mutex_unlock(&ebt_mutex);
return table;
free_unlock:
mutex_unlock(&ebt_mutex);
free_chainstack:
if (newinfo->chainstack) {
for_each_possible_cpu(i)
vfree(newinfo->chainstack[i]);
vfree(newinfo->chainstack);
}
vfree(newinfo->entries);
free_newinfo:
vfree(newinfo);
free_table:
kfree(table);
out:
return ERR_PTR(ret);
}
void ebt_unregister_table(struct net *net, struct ebt_table *table)
{
int i;
if (!table) {
BUGPRINT("Request to unregister NULL table!!!\n");
return;
}
mutex_lock(&ebt_mutex);
list_del(&table->list);
mutex_unlock(&ebt_mutex);
EBT_ENTRY_ITERATE(table->private->entries, table->private->entries_size,
ebt_cleanup_entry, net, NULL);
if (table->private->nentries)
module_put(table->me);
vfree(table->private->entries);
if (table->private->chainstack) {
for_each_possible_cpu(i)
vfree(table->private->chainstack[i]);
vfree(table->private->chainstack);
}
vfree(table->private);
kfree(table);
}
/* userspace just supplied us with counters */
static int do_update_counters(struct net *net, const char *name,
struct ebt_counter __user *counters,
unsigned int num_counters,
const void __user *user, unsigned int len)
{
int i, ret;
struct ebt_counter *tmp;
struct ebt_table *t;
if (num_counters == 0)
return -EINVAL;
tmp = vmalloc(num_counters * sizeof(*tmp));
if (!tmp)
return -ENOMEM;
t = find_table_lock(net, name, &ret, &ebt_mutex);
if (!t)
goto free_tmp;
if (num_counters != t->private->nentries) {
BUGPRINT("Wrong nr of counters\n");
ret = -EINVAL;
goto unlock_mutex;
}
if (copy_from_user(tmp, counters, num_counters * sizeof(*counters))) {
ret = -EFAULT;
goto unlock_mutex;
}
/* we want an atomic add of the counters */
write_lock_bh(&t->lock);
/* we add to the counters of the first cpu */
for (i = 0; i < num_counters; i++) {
t->private->counters[i].pcnt += tmp[i].pcnt;
t->private->counters[i].bcnt += tmp[i].bcnt;
}
write_unlock_bh(&t->lock);
ret = 0;
unlock_mutex:
mutex_unlock(&ebt_mutex);
free_tmp:
vfree(tmp);
return ret;
}
static int update_counters(struct net *net, const void __user *user,
unsigned int len)
{
struct ebt_replace hlp;
if (copy_from_user(&hlp, user, sizeof(hlp)))
return -EFAULT;
if (len != sizeof(hlp) + hlp.num_counters * sizeof(struct ebt_counter))
return -EINVAL;
return do_update_counters(net, hlp.name, hlp.counters,
hlp.num_counters, user, len);
}
static inline int ebt_make_matchname(const struct ebt_entry_match *m,
const char *base, char __user *ubase)
{
char __user *hlp = ubase + ((char *)m - base);
char name[EBT_FUNCTION_MAXNAMELEN] = {};
/* ebtables expects 32 bytes long names but xt_match names are 29 bytes
long. Copy 29 bytes and fill remaining bytes with zeroes. */
strncpy(name, m->u.match->name, sizeof(name));
if (copy_to_user(hlp, name, EBT_FUNCTION_MAXNAMELEN))
return -EFAULT;
return 0;
}
static inline int ebt_make_watchername(const struct ebt_entry_watcher *w,
const char *base, char __user *ubase)
{
char __user *hlp = ubase + ((char *)w - base);
char name[EBT_FUNCTION_MAXNAMELEN] = {};
strncpy(name, w->u.watcher->name, sizeof(name));
if (copy_to_user(hlp , name, EBT_FUNCTION_MAXNAMELEN))
return -EFAULT;
return 0;
}
static inline int
ebt_make_names(struct ebt_entry *e, const char *base, char __user *ubase)
{
int ret;
char __user *hlp;
const struct ebt_entry_target *t;
char name[EBT_FUNCTION_MAXNAMELEN] = {};
if (e->bitmask == 0)
return 0;
hlp = ubase + (((char *)e + e->target_offset) - base);
t = (struct ebt_entry_target *)(((char *)e) + e->target_offset);
ret = EBT_MATCH_ITERATE(e, ebt_make_matchname, base, ubase);
if (ret != 0)
return ret;
ret = EBT_WATCHER_ITERATE(e, ebt_make_watchername, base, ubase);
if (ret != 0)
return ret;
strncpy(name, t->u.target->name, sizeof(name));
if (copy_to_user(hlp, name, EBT_FUNCTION_MAXNAMELEN))
return -EFAULT;
return 0;
}
static int copy_counters_to_user(struct ebt_table *t,
const struct ebt_counter *oldcounters,
void __user *user, unsigned int num_counters,
unsigned int nentries)
{
struct ebt_counter *counterstmp;
int ret = 0;
/* userspace might not need the counters */
if (num_counters == 0)
return 0;
if (num_counters != nentries) {
BUGPRINT("Num_counters wrong\n");
return -EINVAL;
}
counterstmp = vmalloc(nentries * sizeof(*counterstmp));
if (!counterstmp)
return -ENOMEM;
write_lock_bh(&t->lock);
get_counters(oldcounters, counterstmp, nentries);
write_unlock_bh(&t->lock);
if (copy_to_user(user, counterstmp,
nentries * sizeof(struct ebt_counter)))
ret = -EFAULT;
vfree(counterstmp);
return ret;
}
/* called with ebt_mutex locked */
static int copy_everything_to_user(struct ebt_table *t, void __user *user,
const int *len, int cmd)
{
struct ebt_replace tmp;
const struct ebt_counter *oldcounters;
unsigned int entries_size, nentries;
int ret;
char *entries;
if (cmd == EBT_SO_GET_ENTRIES) {
entries_size = t->private->entries_size;
nentries = t->private->nentries;
entries = t->private->entries;
oldcounters = t->private->counters;
} else {
entries_size = t->table->entries_size;
nentries = t->table->nentries;
entries = t->table->entries;
oldcounters = t->table->counters;
}
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
if (*len != sizeof(struct ebt_replace) + entries_size +
(tmp.num_counters? nentries * sizeof(struct ebt_counter): 0))
return -EINVAL;
if (tmp.nentries != nentries) {
BUGPRINT("Nentries wrong\n");
return -EINVAL;
}
if (tmp.entries_size != entries_size) {
BUGPRINT("Wrong size\n");
return -EINVAL;
}
ret = copy_counters_to_user(t, oldcounters, tmp.counters,
tmp.num_counters, nentries);
if (ret)
return ret;
if (copy_to_user(tmp.entries, entries, entries_size)) {
BUGPRINT("Couldn't copy entries to userspace\n");
return -EFAULT;
}
/* set the match/watcher/target names right */
return EBT_ENTRY_ITERATE(entries, entries_size,
ebt_make_names, entries, tmp.entries);
}
static int do_ebt_set_ctl(struct sock *sk,
int cmd, void __user *user, unsigned int len)
{
int ret;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
switch(cmd) {
case EBT_SO_SET_ENTRIES:
ret = do_replace(sock_net(sk), user, len);
break;
case EBT_SO_SET_COUNTERS:
ret = update_counters(sock_net(sk), user, len);
break;
default:
ret = -EINVAL;
}
return ret;
}
static int do_ebt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
{
int ret;
struct ebt_replace tmp;
struct ebt_table *t;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
t = find_table_lock(sock_net(sk), tmp.name, &ret, &ebt_mutex);
if (!t)
return ret;
switch(cmd) {
case EBT_SO_GET_INFO:
case EBT_SO_GET_INIT_INFO:
if (*len != sizeof(struct ebt_replace)){
ret = -EINVAL;
mutex_unlock(&ebt_mutex);
break;
}
if (cmd == EBT_SO_GET_INFO) {
tmp.nentries = t->private->nentries;
tmp.entries_size = t->private->entries_size;
tmp.valid_hooks = t->valid_hooks;
} else {
tmp.nentries = t->table->nentries;
tmp.entries_size = t->table->entries_size;
tmp.valid_hooks = t->table->valid_hooks;
}
mutex_unlock(&ebt_mutex);
if (copy_to_user(user, &tmp, *len) != 0){
BUGPRINT("c2u Didn't work\n");
ret = -EFAULT;
break;
}
ret = 0;
break;
case EBT_SO_GET_ENTRIES:
case EBT_SO_GET_INIT_ENTRIES:
ret = copy_everything_to_user(t, user, len, cmd);
mutex_unlock(&ebt_mutex);
break;
default:
mutex_unlock(&ebt_mutex);
ret = -EINVAL;
}
return ret;
}
#ifdef CONFIG_COMPAT
/* 32 bit-userspace compatibility definitions. */
struct compat_ebt_replace {
char name[EBT_TABLE_MAXNAMELEN];
compat_uint_t valid_hooks;
compat_uint_t nentries;
compat_uint_t entries_size;
/* start of the chains */
compat_uptr_t hook_entry[NF_BR_NUMHOOKS];
/* nr of counters userspace expects back */
compat_uint_t num_counters;
/* where the kernel will put the old counters. */
compat_uptr_t counters;
compat_uptr_t entries;
};
/* struct ebt_entry_match, _target and _watcher have same layout */
struct compat_ebt_entry_mwt {
union {
char name[EBT_FUNCTION_MAXNAMELEN];
compat_uptr_t ptr;
} u;
compat_uint_t match_size;
compat_uint_t data[0];
};
/* account for possible padding between match_size and ->data */
static int ebt_compat_entry_padsize(void)
{
BUILD_BUG_ON(XT_ALIGN(sizeof(struct ebt_entry_match)) <
COMPAT_XT_ALIGN(sizeof(struct compat_ebt_entry_mwt)));
return (int) XT_ALIGN(sizeof(struct ebt_entry_match)) -
COMPAT_XT_ALIGN(sizeof(struct compat_ebt_entry_mwt));
}
static int ebt_compat_match_offset(const struct xt_match *match,
unsigned int userlen)
{
/*
* ebt_among needs special handling. The kernel .matchsize is
* set to -1 at registration time; at runtime an EBT_ALIGN()ed
* value is expected.
* Example: userspace sends 4500, ebt_among.c wants 4504.
*/
if (unlikely(match->matchsize == -1))
return XT_ALIGN(userlen) - COMPAT_XT_ALIGN(userlen);
return xt_compat_match_offset(match);
}
static int compat_match_to_user(struct ebt_entry_match *m, void __user **dstptr,
unsigned int *size)
{
const struct xt_match *match = m->u.match;
struct compat_ebt_entry_mwt __user *cm = *dstptr;
int off = ebt_compat_match_offset(match, m->match_size);
compat_uint_t msize = m->match_size - off;
BUG_ON(off >= m->match_size);
if (copy_to_user(cm->u.name, match->name,
strlen(match->name) + 1) || put_user(msize, &cm->match_size))
return -EFAULT;
if (match->compat_to_user) {
if (match->compat_to_user(cm->data, m->data))
return -EFAULT;
} else if (copy_to_user(cm->data, m->data, msize))
return -EFAULT;
*size -= ebt_compat_entry_padsize() + off;
*dstptr = cm->data;
*dstptr += msize;
return 0;
}
static int compat_target_to_user(struct ebt_entry_target *t,
void __user **dstptr,
unsigned int *size)
{
const struct xt_target *target = t->u.target;
struct compat_ebt_entry_mwt __user *cm = *dstptr;
int off = xt_compat_target_offset(target);
compat_uint_t tsize = t->target_size - off;
BUG_ON(off >= t->target_size);
if (copy_to_user(cm->u.name, target->name,
strlen(target->name) + 1) || put_user(tsize, &cm->match_size))
return -EFAULT;
if (target->compat_to_user) {
if (target->compat_to_user(cm->data, t->data))
return -EFAULT;
} else if (copy_to_user(cm->data, t->data, tsize))
return -EFAULT;
*size -= ebt_compat_entry_padsize() + off;
*dstptr = cm->data;
*dstptr += tsize;
return 0;
}
static int compat_watcher_to_user(struct ebt_entry_watcher *w,
void __user **dstptr,
unsigned int *size)
{
return compat_target_to_user((struct ebt_entry_target *)w,
dstptr, size);
}
static int compat_copy_entry_to_user(struct ebt_entry *e, void __user **dstptr,
unsigned int *size)
{
struct ebt_entry_target *t;
struct ebt_entry __user *ce;
u32 watchers_offset, target_offset, next_offset;
compat_uint_t origsize;
int ret;
if (e->bitmask == 0) {
if (*size < sizeof(struct ebt_entries))
return -EINVAL;
if (copy_to_user(*dstptr, e, sizeof(struct ebt_entries)))
return -EFAULT;
*dstptr += sizeof(struct ebt_entries);
*size -= sizeof(struct ebt_entries);
return 0;
}
if (*size < sizeof(*ce))
return -EINVAL;
ce = (struct ebt_entry __user *)*dstptr;
if (copy_to_user(ce, e, sizeof(*ce)))
return -EFAULT;
origsize = *size;
*dstptr += sizeof(*ce);
ret = EBT_MATCH_ITERATE(e, compat_match_to_user, dstptr, size);
if (ret)
return ret;
watchers_offset = e->watchers_offset - (origsize - *size);
ret = EBT_WATCHER_ITERATE(e, compat_watcher_to_user, dstptr, size);
if (ret)
return ret;
target_offset = e->target_offset - (origsize - *size);
t = (struct ebt_entry_target *) ((char *) e + e->target_offset);
ret = compat_target_to_user(t, dstptr, size);
if (ret)
return ret;
next_offset = e->next_offset - (origsize - *size);
if (put_user(watchers_offset, &ce->watchers_offset) ||
put_user(target_offset, &ce->target_offset) ||
put_user(next_offset, &ce->next_offset))
return -EFAULT;
*size -= sizeof(*ce);
return 0;
}
static int compat_calc_match(struct ebt_entry_match *m, int *off)
{
*off += ebt_compat_match_offset(m->u.match, m->match_size);
*off += ebt_compat_entry_padsize();
return 0;
}
static int compat_calc_watcher(struct ebt_entry_watcher *w, int *off)
{
*off += xt_compat_target_offset(w->u.watcher);
*off += ebt_compat_entry_padsize();
return 0;
}
static int compat_calc_entry(const struct ebt_entry *e,
const struct ebt_table_info *info,
const void *base,
struct compat_ebt_replace *newinfo)
{
const struct ebt_entry_target *t;
unsigned int entry_offset;
int off, ret, i;
if (e->bitmask == 0)
return 0;
off = 0;
entry_offset = (void *)e - base;
EBT_MATCH_ITERATE(e, compat_calc_match, &off);
EBT_WATCHER_ITERATE(e, compat_calc_watcher, &off);
t = (const struct ebt_entry_target *) ((char *) e + e->target_offset);
off += xt_compat_target_offset(t->u.target);
off += ebt_compat_entry_padsize();
newinfo->entries_size -= off;
ret = xt_compat_add_offset(NFPROTO_BRIDGE, entry_offset, off);
if (ret)
return ret;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
const void *hookptr = info->hook_entry[i];
if (info->hook_entry[i] &&
(e < (struct ebt_entry *)(base - hookptr))) {
newinfo->hook_entry[i] -= off;
pr_debug("0x%08X -> 0x%08X\n",
newinfo->hook_entry[i] + off,
newinfo->hook_entry[i]);
}
}
return 0;
}
static int compat_table_info(const struct ebt_table_info *info,
struct compat_ebt_replace *newinfo)
{
unsigned int size = info->entries_size;
const void *entries = info->entries;
newinfo->entries_size = size;
xt_compat_init_offsets(NFPROTO_BRIDGE, info->nentries);
return EBT_ENTRY_ITERATE(entries, size, compat_calc_entry, info,
entries, newinfo);
}
static int compat_copy_everything_to_user(struct ebt_table *t,
void __user *user, int *len, int cmd)
{
struct compat_ebt_replace repl, tmp;
struct ebt_counter *oldcounters;
struct ebt_table_info tinfo;
int ret;
void __user *pos;
memset(&tinfo, 0, sizeof(tinfo));
if (cmd == EBT_SO_GET_ENTRIES) {
tinfo.entries_size = t->private->entries_size;
tinfo.nentries = t->private->nentries;
tinfo.entries = t->private->entries;
oldcounters = t->private->counters;
} else {
tinfo.entries_size = t->table->entries_size;
tinfo.nentries = t->table->nentries;
tinfo.entries = t->table->entries;
oldcounters = t->table->counters;
}
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
if (tmp.nentries != tinfo.nentries ||
(tmp.num_counters && tmp.num_counters != tinfo.nentries))
return -EINVAL;
memcpy(&repl, &tmp, sizeof(repl));
if (cmd == EBT_SO_GET_ENTRIES)
ret = compat_table_info(t->private, &repl);
else
ret = compat_table_info(&tinfo, &repl);
if (ret)
return ret;
if (*len != sizeof(tmp) + repl.entries_size +
(tmp.num_counters? tinfo.nentries * sizeof(struct ebt_counter): 0)) {
pr_err("wrong size: *len %d, entries_size %u, replsz %d\n",
*len, tinfo.entries_size, repl.entries_size);
return -EINVAL;
}
/* userspace might not need the counters */
ret = copy_counters_to_user(t, oldcounters, compat_ptr(tmp.counters),
tmp.num_counters, tinfo.nentries);
if (ret)
return ret;
pos = compat_ptr(tmp.entries);
return EBT_ENTRY_ITERATE(tinfo.entries, tinfo.entries_size,
compat_copy_entry_to_user, &pos, &tmp.entries_size);
}
struct ebt_entries_buf_state {
char *buf_kern_start; /* kernel buffer to copy (translated) data to */
u32 buf_kern_len; /* total size of kernel buffer */
u32 buf_kern_offset; /* amount of data copied so far */
u32 buf_user_offset; /* read position in userspace buffer */
};
static int ebt_buf_count(struct ebt_entries_buf_state *state, unsigned int sz)
{
state->buf_kern_offset += sz;
return state->buf_kern_offset >= sz ? 0 : -EINVAL;
}
static int ebt_buf_add(struct ebt_entries_buf_state *state,
void *data, unsigned int sz)
{
if (state->buf_kern_start == NULL)
goto count_only;
BUG_ON(state->buf_kern_offset + sz > state->buf_kern_len);
memcpy(state->buf_kern_start + state->buf_kern_offset, data, sz);
count_only:
state->buf_user_offset += sz;
return ebt_buf_count(state, sz);
}
static int ebt_buf_add_pad(struct ebt_entries_buf_state *state, unsigned int sz)
{
char *b = state->buf_kern_start;
BUG_ON(b && state->buf_kern_offset > state->buf_kern_len);
if (b != NULL && sz > 0)
memset(b + state->buf_kern_offset, 0, sz);
/* do not adjust ->buf_user_offset here, we added kernel-side padding */
return ebt_buf_count(state, sz);
}
enum compat_mwt {
EBT_COMPAT_MATCH,
EBT_COMPAT_WATCHER,
EBT_COMPAT_TARGET,
};
static int compat_mtw_from_user(struct compat_ebt_entry_mwt *mwt,
enum compat_mwt compat_mwt,
struct ebt_entries_buf_state *state,
const unsigned char *base)
{
char name[EBT_FUNCTION_MAXNAMELEN];
struct xt_match *match;
struct xt_target *wt;
void *dst = NULL;
int off, pad = 0;
unsigned int size_kern, match_size = mwt->match_size;
strlcpy(name, mwt->u.name, sizeof(name));
if (state->buf_kern_start)
dst = state->buf_kern_start + state->buf_kern_offset;
switch (compat_mwt) {
case EBT_COMPAT_MATCH:
match = xt_request_find_match(NFPROTO_BRIDGE, name, 0);
if (IS_ERR(match))
return PTR_ERR(match);
off = ebt_compat_match_offset(match, match_size);
if (dst) {
if (match->compat_from_user)
match->compat_from_user(dst, mwt->data);
else
memcpy(dst, mwt->data, match_size);
}
size_kern = match->matchsize;
if (unlikely(size_kern == -1))
size_kern = match_size;
module_put(match->me);
break;
case EBT_COMPAT_WATCHER: /* fallthrough */
case EBT_COMPAT_TARGET:
wt = xt_request_find_target(NFPROTO_BRIDGE, name, 0);
if (IS_ERR(wt))
return PTR_ERR(wt);
off = xt_compat_target_offset(wt);
if (dst) {
if (wt->compat_from_user)
wt->compat_from_user(dst, mwt->data);
else
memcpy(dst, mwt->data, match_size);
}
size_kern = wt->targetsize;
module_put(wt->me);
break;
default:
return -EINVAL;
}
state->buf_kern_offset += match_size + off;
state->buf_user_offset += match_size;
pad = XT_ALIGN(size_kern) - size_kern;
if (pad > 0 && dst) {
BUG_ON(state->buf_kern_len <= pad);
BUG_ON(state->buf_kern_offset - (match_size + off) + size_kern > state->buf_kern_len - pad);
memset(dst + size_kern, 0, pad);
}
return off + match_size;
}
/*
* return size of all matches, watchers or target, including necessary
* alignment and padding.
*/
static int ebt_size_mwt(struct compat_ebt_entry_mwt *match32,
unsigned int size_left, enum compat_mwt type,
struct ebt_entries_buf_state *state, const void *base)
{
int growth = 0;
char *buf;
if (size_left == 0)
return 0;
buf = (char *) match32;
while (size_left >= sizeof(*match32)) {
struct ebt_entry_match *match_kern;
int ret;
match_kern = (struct ebt_entry_match *) state->buf_kern_start;
if (match_kern) {
char *tmp;
tmp = state->buf_kern_start + state->buf_kern_offset;
match_kern = (struct ebt_entry_match *) tmp;
}
ret = ebt_buf_add(state, buf, sizeof(*match32));
if (ret < 0)
return ret;
size_left -= sizeof(*match32);
/* add padding before match->data (if any) */
ret = ebt_buf_add_pad(state, ebt_compat_entry_padsize());
if (ret < 0)
return ret;
if (match32->match_size > size_left)
return -EINVAL;
size_left -= match32->match_size;
ret = compat_mtw_from_user(match32, type, state, base);
if (ret < 0)
return ret;
BUG_ON(ret < match32->match_size);
growth += ret - match32->match_size;
growth += ebt_compat_entry_padsize();
buf += sizeof(*match32);
buf += match32->match_size;
if (match_kern)
match_kern->match_size = ret;
WARN_ON(type == EBT_COMPAT_TARGET && size_left);
match32 = (struct compat_ebt_entry_mwt *) buf;
}
return growth;
}
/* called for all ebt_entry structures. */
static int size_entry_mwt(struct ebt_entry *entry, const unsigned char *base,
unsigned int *total,
struct ebt_entries_buf_state *state)
{
unsigned int i, j, startoff, new_offset = 0;
/* stores match/watchers/targets & offset of next struct ebt_entry: */
unsigned int offsets[4];
unsigned int *offsets_update = NULL;
int ret;
char *buf_start;
if (*total < sizeof(struct ebt_entries))
return -EINVAL;
if (!entry->bitmask) {
*total -= sizeof(struct ebt_entries);
return ebt_buf_add(state, entry, sizeof(struct ebt_entries));
}
if (*total < sizeof(*entry) || entry->next_offset < sizeof(*entry))
return -EINVAL;
startoff = state->buf_user_offset;
/* pull in most part of ebt_entry, it does not need to be changed. */
ret = ebt_buf_add(state, entry,
offsetof(struct ebt_entry, watchers_offset));
if (ret < 0)
return ret;
offsets[0] = sizeof(struct ebt_entry); /* matches come first */
memcpy(&offsets[1], &entry->watchers_offset,
sizeof(offsets) - sizeof(offsets[0]));
if (state->buf_kern_start) {
buf_start = state->buf_kern_start + state->buf_kern_offset;
offsets_update = (unsigned int *) buf_start;
}
ret = ebt_buf_add(state, &offsets[1],
sizeof(offsets) - sizeof(offsets[0]));
if (ret < 0)
return ret;
buf_start = (char *) entry;
/*
* 0: matches offset, always follows ebt_entry.
* 1: watchers offset, from ebt_entry structure
* 2: target offset, from ebt_entry structure
* 3: next ebt_entry offset, from ebt_entry structure
*
* offsets are relative to beginning of struct ebt_entry (i.e., 0).
*/
for (i = 0, j = 1 ; j < 4 ; j++, i++) {
struct compat_ebt_entry_mwt *match32;
unsigned int size;
char *buf = buf_start;
buf = buf_start + offsets[i];
if (offsets[i] > offsets[j])
return -EINVAL;
match32 = (struct compat_ebt_entry_mwt *) buf;
size = offsets[j] - offsets[i];
ret = ebt_size_mwt(match32, size, i, state, base);
if (ret < 0)
return ret;
new_offset += ret;
if (offsets_update && new_offset) {
pr_debug("change offset %d to %d\n",
offsets_update[i], offsets[j] + new_offset);
offsets_update[i] = offsets[j] + new_offset;
}
}
if (state->buf_kern_start == NULL) {
unsigned int offset = buf_start - (char *) base;
ret = xt_compat_add_offset(NFPROTO_BRIDGE, offset, new_offset);
if (ret < 0)
return ret;
}
startoff = state->buf_user_offset - startoff;
BUG_ON(*total < startoff);
*total -= startoff;
return 0;
}
/*
* repl->entries_size is the size of the ebt_entry blob in userspace.
* It might need more memory when copied to a 64 bit kernel in case
* userspace is 32-bit. So, first task: find out how much memory is needed.
*
* Called before validation is performed.
*/
static int compat_copy_entries(unsigned char *data, unsigned int size_user,
struct ebt_entries_buf_state *state)
{
unsigned int size_remaining = size_user;
int ret;
ret = EBT_ENTRY_ITERATE(data, size_user, size_entry_mwt, data,
&size_remaining, state);
if (ret < 0)
return ret;
WARN_ON(size_remaining);
return state->buf_kern_offset;
}
static int compat_copy_ebt_replace_from_user(struct ebt_replace *repl,
void __user *user, unsigned int len)
{
struct compat_ebt_replace tmp;
int i;
if (len < sizeof(tmp))
return -EINVAL;
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
if (len != sizeof(tmp) + tmp.entries_size)
return -EINVAL;
if (tmp.entries_size == 0)
return -EINVAL;
if (tmp.nentries >= ((INT_MAX - sizeof(struct ebt_table_info)) /
NR_CPUS - SMP_CACHE_BYTES) / sizeof(struct ebt_counter))
return -ENOMEM;
if (tmp.num_counters >= INT_MAX / sizeof(struct ebt_counter))
return -ENOMEM;
memcpy(repl, &tmp, offsetof(struct ebt_replace, hook_entry));
/* starting with hook_entry, 32 vs. 64 bit structures are different */
for (i = 0; i < NF_BR_NUMHOOKS; i++)
repl->hook_entry[i] = compat_ptr(tmp.hook_entry[i]);
repl->num_counters = tmp.num_counters;
repl->counters = compat_ptr(tmp.counters);
repl->entries = compat_ptr(tmp.entries);
return 0;
}
static int compat_do_replace(struct net *net, void __user *user,
unsigned int len)
{
int ret, i, countersize, size64;
struct ebt_table_info *newinfo;
struct ebt_replace tmp;
struct ebt_entries_buf_state state;
void *entries_tmp;
ret = compat_copy_ebt_replace_from_user(&tmp, user, len);
if (ret) {
/* try real handler in case userland supplied needed padding */
if (ret == -EINVAL && do_replace(net, user, len) == 0)
ret = 0;
return ret;
}
countersize = COUNTER_OFFSET(tmp.nentries) * nr_cpu_ids;
newinfo = vmalloc(sizeof(*newinfo) + countersize);
if (!newinfo)
return -ENOMEM;
if (countersize)
memset(newinfo->counters, 0, countersize);
memset(&state, 0, sizeof(state));
newinfo->entries = vmalloc(tmp.entries_size);
if (!newinfo->entries) {
ret = -ENOMEM;
goto free_newinfo;
}
if (copy_from_user(
newinfo->entries, tmp.entries, tmp.entries_size) != 0) {
ret = -EFAULT;
goto free_entries;
}
entries_tmp = newinfo->entries;
xt_compat_lock(NFPROTO_BRIDGE);
xt_compat_init_offsets(NFPROTO_BRIDGE, tmp.nentries);
ret = compat_copy_entries(entries_tmp, tmp.entries_size, &state);
if (ret < 0)
goto out_unlock;
pr_debug("tmp.entries_size %d, kern off %d, user off %d delta %d\n",
tmp.entries_size, state.buf_kern_offset, state.buf_user_offset,
xt_compat_calc_jump(NFPROTO_BRIDGE, tmp.entries_size));
size64 = ret;
newinfo->entries = vmalloc(size64);
if (!newinfo->entries) {
vfree(entries_tmp);
ret = -ENOMEM;
goto out_unlock;
}
memset(&state, 0, sizeof(state));
state.buf_kern_start = newinfo->entries;
state.buf_kern_len = size64;
ret = compat_copy_entries(entries_tmp, tmp.entries_size, &state);
BUG_ON(ret < 0); /* parses same data again */
vfree(entries_tmp);
tmp.entries_size = size64;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
char __user *usrptr;
if (tmp.hook_entry[i]) {
unsigned int delta;
usrptr = (char __user *) tmp.hook_entry[i];
delta = usrptr - tmp.entries;
usrptr += xt_compat_calc_jump(NFPROTO_BRIDGE, delta);
tmp.hook_entry[i] = (struct ebt_entries __user *)usrptr;
}
}
xt_compat_flush_offsets(NFPROTO_BRIDGE);
xt_compat_unlock(NFPROTO_BRIDGE);
ret = do_replace_finish(net, &tmp, newinfo);
if (ret == 0)
return ret;
free_entries:
vfree(newinfo->entries);
free_newinfo:
vfree(newinfo);
return ret;
out_unlock:
xt_compat_flush_offsets(NFPROTO_BRIDGE);
xt_compat_unlock(NFPROTO_BRIDGE);
goto free_entries;
}
static int compat_update_counters(struct net *net, void __user *user,
unsigned int len)
{
struct compat_ebt_replace hlp;
if (copy_from_user(&hlp, user, sizeof(hlp)))
return -EFAULT;
/* try real handler in case userland supplied needed padding */
if (len != sizeof(hlp) + hlp.num_counters * sizeof(struct ebt_counter))
return update_counters(net, user, len);
return do_update_counters(net, hlp.name, compat_ptr(hlp.counters),
hlp.num_counters, user, len);
}
static int compat_do_ebt_set_ctl(struct sock *sk,
int cmd, void __user *user, unsigned int len)
{
int ret;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case EBT_SO_SET_ENTRIES:
ret = compat_do_replace(sock_net(sk), user, len);
break;
case EBT_SO_SET_COUNTERS:
ret = compat_update_counters(sock_net(sk), user, len);
break;
default:
ret = -EINVAL;
}
return ret;
}
static int compat_do_ebt_get_ctl(struct sock *sk, int cmd,
void __user *user, int *len)
{
int ret;
struct compat_ebt_replace tmp;
struct ebt_table *t;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
/* try real handler in case userland supplied needed padding */
if ((cmd == EBT_SO_GET_INFO ||
cmd == EBT_SO_GET_INIT_INFO) && *len != sizeof(tmp))
return do_ebt_get_ctl(sk, cmd, user, len);
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
t = find_table_lock(sock_net(sk), tmp.name, &ret, &ebt_mutex);
if (!t)
return ret;
xt_compat_lock(NFPROTO_BRIDGE);
switch (cmd) {
case EBT_SO_GET_INFO:
tmp.nentries = t->private->nentries;
ret = compat_table_info(t->private, &tmp);
if (ret)
goto out;
tmp.valid_hooks = t->valid_hooks;
if (copy_to_user(user, &tmp, *len) != 0) {
ret = -EFAULT;
break;
}
ret = 0;
break;
case EBT_SO_GET_INIT_INFO:
tmp.nentries = t->table->nentries;
tmp.entries_size = t->table->entries_size;
tmp.valid_hooks = t->table->valid_hooks;
if (copy_to_user(user, &tmp, *len) != 0) {
ret = -EFAULT;
break;
}
ret = 0;
break;
case EBT_SO_GET_ENTRIES:
case EBT_SO_GET_INIT_ENTRIES:
/*
* try real handler first in case of userland-side padding.
* in case we are dealing with an 'ordinary' 32 bit binary
* without 64bit compatibility padding, this will fail right
* after copy_from_user when the *len argument is validated.
*
* the compat_ variant needs to do one pass over the kernel
* data set to adjust for size differences before it the check.
*/
if (copy_everything_to_user(t, user, len, cmd) == 0)
ret = 0;
else
ret = compat_copy_everything_to_user(t, user, len, cmd);
break;
default:
ret = -EINVAL;
}
out:
xt_compat_flush_offsets(NFPROTO_BRIDGE);
xt_compat_unlock(NFPROTO_BRIDGE);
mutex_unlock(&ebt_mutex);
return ret;
}
#endif
static struct nf_sockopt_ops ebt_sockopts =
{
.pf = PF_INET,
.set_optmin = EBT_BASE_CTL,
.set_optmax = EBT_SO_SET_MAX + 1,
.set = do_ebt_set_ctl,
#ifdef CONFIG_COMPAT
.compat_set = compat_do_ebt_set_ctl,
#endif
.get_optmin = EBT_BASE_CTL,
.get_optmax = EBT_SO_GET_MAX + 1,
.get = do_ebt_get_ctl,
#ifdef CONFIG_COMPAT
.compat_get = compat_do_ebt_get_ctl,
#endif
.owner = THIS_MODULE,
};
static int __init ebtables_init(void)
{
int ret;
ret = xt_register_target(&ebt_standard_target);
if (ret < 0)
return ret;
ret = nf_register_sockopt(&ebt_sockopts);
if (ret < 0) {
xt_unregister_target(&ebt_standard_target);
return ret;
}
printk(KERN_INFO "Ebtables v2.0 registered\n");
return 0;
}
static void __exit ebtables_fini(void)
{
nf_unregister_sockopt(&ebt_sockopts);
xt_unregister_target(&ebt_standard_target);
printk(KERN_INFO "Ebtables v2.0 unregistered\n");
}
EXPORT_SYMBOL(ebt_register_table);
EXPORT_SYMBOL(ebt_unregister_table);
EXPORT_SYMBOL(ebt_do_table);
module_init(ebtables_init);
module_exit(ebtables_fini);
MODULE_LICENSE("GPL");
| gpl-2.0 |
airidosas252/jellykernel_kitkat | security/tomoyo/common.c | 4814 | 77273 | /*
* security/tomoyo/common.c
*
* Copyright (C) 2005-2011 NTT DATA CORPORATION
*/
#include <linux/uaccess.h>
#include <linux/slab.h>
#include <linux/security.h>
#include "common.h"
/* String table for operation mode. */
const char * const tomoyo_mode[TOMOYO_CONFIG_MAX_MODE] = {
[TOMOYO_CONFIG_DISABLED] = "disabled",
[TOMOYO_CONFIG_LEARNING] = "learning",
[TOMOYO_CONFIG_PERMISSIVE] = "permissive",
[TOMOYO_CONFIG_ENFORCING] = "enforcing"
};
/* String table for /sys/kernel/security/tomoyo/profile */
const char * const tomoyo_mac_keywords[TOMOYO_MAX_MAC_INDEX
+ TOMOYO_MAX_MAC_CATEGORY_INDEX] = {
/* CONFIG::file group */
[TOMOYO_MAC_FILE_EXECUTE] = "execute",
[TOMOYO_MAC_FILE_OPEN] = "open",
[TOMOYO_MAC_FILE_CREATE] = "create",
[TOMOYO_MAC_FILE_UNLINK] = "unlink",
[TOMOYO_MAC_FILE_GETATTR] = "getattr",
[TOMOYO_MAC_FILE_MKDIR] = "mkdir",
[TOMOYO_MAC_FILE_RMDIR] = "rmdir",
[TOMOYO_MAC_FILE_MKFIFO] = "mkfifo",
[TOMOYO_MAC_FILE_MKSOCK] = "mksock",
[TOMOYO_MAC_FILE_TRUNCATE] = "truncate",
[TOMOYO_MAC_FILE_SYMLINK] = "symlink",
[TOMOYO_MAC_FILE_MKBLOCK] = "mkblock",
[TOMOYO_MAC_FILE_MKCHAR] = "mkchar",
[TOMOYO_MAC_FILE_LINK] = "link",
[TOMOYO_MAC_FILE_RENAME] = "rename",
[TOMOYO_MAC_FILE_CHMOD] = "chmod",
[TOMOYO_MAC_FILE_CHOWN] = "chown",
[TOMOYO_MAC_FILE_CHGRP] = "chgrp",
[TOMOYO_MAC_FILE_IOCTL] = "ioctl",
[TOMOYO_MAC_FILE_CHROOT] = "chroot",
[TOMOYO_MAC_FILE_MOUNT] = "mount",
[TOMOYO_MAC_FILE_UMOUNT] = "unmount",
[TOMOYO_MAC_FILE_PIVOT_ROOT] = "pivot_root",
/* CONFIG::network group */
[TOMOYO_MAC_NETWORK_INET_STREAM_BIND] = "inet_stream_bind",
[TOMOYO_MAC_NETWORK_INET_STREAM_LISTEN] = "inet_stream_listen",
[TOMOYO_MAC_NETWORK_INET_STREAM_CONNECT] = "inet_stream_connect",
[TOMOYO_MAC_NETWORK_INET_DGRAM_BIND] = "inet_dgram_bind",
[TOMOYO_MAC_NETWORK_INET_DGRAM_SEND] = "inet_dgram_send",
[TOMOYO_MAC_NETWORK_INET_RAW_BIND] = "inet_raw_bind",
[TOMOYO_MAC_NETWORK_INET_RAW_SEND] = "inet_raw_send",
[TOMOYO_MAC_NETWORK_UNIX_STREAM_BIND] = "unix_stream_bind",
[TOMOYO_MAC_NETWORK_UNIX_STREAM_LISTEN] = "unix_stream_listen",
[TOMOYO_MAC_NETWORK_UNIX_STREAM_CONNECT] = "unix_stream_connect",
[TOMOYO_MAC_NETWORK_UNIX_DGRAM_BIND] = "unix_dgram_bind",
[TOMOYO_MAC_NETWORK_UNIX_DGRAM_SEND] = "unix_dgram_send",
[TOMOYO_MAC_NETWORK_UNIX_SEQPACKET_BIND] = "unix_seqpacket_bind",
[TOMOYO_MAC_NETWORK_UNIX_SEQPACKET_LISTEN] = "unix_seqpacket_listen",
[TOMOYO_MAC_NETWORK_UNIX_SEQPACKET_CONNECT] = "unix_seqpacket_connect",
/* CONFIG::misc group */
[TOMOYO_MAC_ENVIRON] = "env",
/* CONFIG group */
[TOMOYO_MAX_MAC_INDEX + TOMOYO_MAC_CATEGORY_FILE] = "file",
[TOMOYO_MAX_MAC_INDEX + TOMOYO_MAC_CATEGORY_NETWORK] = "network",
[TOMOYO_MAX_MAC_INDEX + TOMOYO_MAC_CATEGORY_MISC] = "misc",
};
/* String table for conditions. */
const char * const tomoyo_condition_keyword[TOMOYO_MAX_CONDITION_KEYWORD] = {
[TOMOYO_TASK_UID] = "task.uid",
[TOMOYO_TASK_EUID] = "task.euid",
[TOMOYO_TASK_SUID] = "task.suid",
[TOMOYO_TASK_FSUID] = "task.fsuid",
[TOMOYO_TASK_GID] = "task.gid",
[TOMOYO_TASK_EGID] = "task.egid",
[TOMOYO_TASK_SGID] = "task.sgid",
[TOMOYO_TASK_FSGID] = "task.fsgid",
[TOMOYO_TASK_PID] = "task.pid",
[TOMOYO_TASK_PPID] = "task.ppid",
[TOMOYO_EXEC_ARGC] = "exec.argc",
[TOMOYO_EXEC_ENVC] = "exec.envc",
[TOMOYO_TYPE_IS_SOCKET] = "socket",
[TOMOYO_TYPE_IS_SYMLINK] = "symlink",
[TOMOYO_TYPE_IS_FILE] = "file",
[TOMOYO_TYPE_IS_BLOCK_DEV] = "block",
[TOMOYO_TYPE_IS_DIRECTORY] = "directory",
[TOMOYO_TYPE_IS_CHAR_DEV] = "char",
[TOMOYO_TYPE_IS_FIFO] = "fifo",
[TOMOYO_MODE_SETUID] = "setuid",
[TOMOYO_MODE_SETGID] = "setgid",
[TOMOYO_MODE_STICKY] = "sticky",
[TOMOYO_MODE_OWNER_READ] = "owner_read",
[TOMOYO_MODE_OWNER_WRITE] = "owner_write",
[TOMOYO_MODE_OWNER_EXECUTE] = "owner_execute",
[TOMOYO_MODE_GROUP_READ] = "group_read",
[TOMOYO_MODE_GROUP_WRITE] = "group_write",
[TOMOYO_MODE_GROUP_EXECUTE] = "group_execute",
[TOMOYO_MODE_OTHERS_READ] = "others_read",
[TOMOYO_MODE_OTHERS_WRITE] = "others_write",
[TOMOYO_MODE_OTHERS_EXECUTE] = "others_execute",
[TOMOYO_EXEC_REALPATH] = "exec.realpath",
[TOMOYO_SYMLINK_TARGET] = "symlink.target",
[TOMOYO_PATH1_UID] = "path1.uid",
[TOMOYO_PATH1_GID] = "path1.gid",
[TOMOYO_PATH1_INO] = "path1.ino",
[TOMOYO_PATH1_MAJOR] = "path1.major",
[TOMOYO_PATH1_MINOR] = "path1.minor",
[TOMOYO_PATH1_PERM] = "path1.perm",
[TOMOYO_PATH1_TYPE] = "path1.type",
[TOMOYO_PATH1_DEV_MAJOR] = "path1.dev_major",
[TOMOYO_PATH1_DEV_MINOR] = "path1.dev_minor",
[TOMOYO_PATH2_UID] = "path2.uid",
[TOMOYO_PATH2_GID] = "path2.gid",
[TOMOYO_PATH2_INO] = "path2.ino",
[TOMOYO_PATH2_MAJOR] = "path2.major",
[TOMOYO_PATH2_MINOR] = "path2.minor",
[TOMOYO_PATH2_PERM] = "path2.perm",
[TOMOYO_PATH2_TYPE] = "path2.type",
[TOMOYO_PATH2_DEV_MAJOR] = "path2.dev_major",
[TOMOYO_PATH2_DEV_MINOR] = "path2.dev_minor",
[TOMOYO_PATH1_PARENT_UID] = "path1.parent.uid",
[TOMOYO_PATH1_PARENT_GID] = "path1.parent.gid",
[TOMOYO_PATH1_PARENT_INO] = "path1.parent.ino",
[TOMOYO_PATH1_PARENT_PERM] = "path1.parent.perm",
[TOMOYO_PATH2_PARENT_UID] = "path2.parent.uid",
[TOMOYO_PATH2_PARENT_GID] = "path2.parent.gid",
[TOMOYO_PATH2_PARENT_INO] = "path2.parent.ino",
[TOMOYO_PATH2_PARENT_PERM] = "path2.parent.perm",
};
/* String table for PREFERENCE keyword. */
static const char * const tomoyo_pref_keywords[TOMOYO_MAX_PREF] = {
[TOMOYO_PREF_MAX_AUDIT_LOG] = "max_audit_log",
[TOMOYO_PREF_MAX_LEARNING_ENTRY] = "max_learning_entry",
};
/* String table for path operation. */
const char * const tomoyo_path_keyword[TOMOYO_MAX_PATH_OPERATION] = {
[TOMOYO_TYPE_EXECUTE] = "execute",
[TOMOYO_TYPE_READ] = "read",
[TOMOYO_TYPE_WRITE] = "write",
[TOMOYO_TYPE_APPEND] = "append",
[TOMOYO_TYPE_UNLINK] = "unlink",
[TOMOYO_TYPE_GETATTR] = "getattr",
[TOMOYO_TYPE_RMDIR] = "rmdir",
[TOMOYO_TYPE_TRUNCATE] = "truncate",
[TOMOYO_TYPE_SYMLINK] = "symlink",
[TOMOYO_TYPE_CHROOT] = "chroot",
[TOMOYO_TYPE_UMOUNT] = "unmount",
};
/* String table for socket's operation. */
const char * const tomoyo_socket_keyword[TOMOYO_MAX_NETWORK_OPERATION] = {
[TOMOYO_NETWORK_BIND] = "bind",
[TOMOYO_NETWORK_LISTEN] = "listen",
[TOMOYO_NETWORK_CONNECT] = "connect",
[TOMOYO_NETWORK_SEND] = "send",
};
/* String table for categories. */
static const char * const tomoyo_category_keywords
[TOMOYO_MAX_MAC_CATEGORY_INDEX] = {
[TOMOYO_MAC_CATEGORY_FILE] = "file",
[TOMOYO_MAC_CATEGORY_NETWORK] = "network",
[TOMOYO_MAC_CATEGORY_MISC] = "misc",
};
/* Permit policy management by non-root user? */
static bool tomoyo_manage_by_non_root;
/* Utility functions. */
/**
* tomoyo_yesno - Return "yes" or "no".
*
* @value: Bool value.
*/
const char *tomoyo_yesno(const unsigned int value)
{
return value ? "yes" : "no";
}
/**
* tomoyo_addprintf - strncat()-like-snprintf().
*
* @buffer: Buffer to write to. Must be '\0'-terminated.
* @len: Size of @buffer.
* @fmt: The printf()'s format string, followed by parameters.
*
* Returns nothing.
*/
static void tomoyo_addprintf(char *buffer, int len, const char *fmt, ...)
{
va_list args;
const int pos = strlen(buffer);
va_start(args, fmt);
vsnprintf(buffer + pos, len - pos - 1, fmt, args);
va_end(args);
}
/**
* tomoyo_flush - Flush queued string to userspace's buffer.
*
* @head: Pointer to "struct tomoyo_io_buffer".
*
* Returns true if all data was flushed, false otherwise.
*/
static bool tomoyo_flush(struct tomoyo_io_buffer *head)
{
while (head->r.w_pos) {
const char *w = head->r.w[0];
size_t len = strlen(w);
if (len) {
if (len > head->read_user_buf_avail)
len = head->read_user_buf_avail;
if (!len)
return false;
if (copy_to_user(head->read_user_buf, w, len))
return false;
head->read_user_buf_avail -= len;
head->read_user_buf += len;
w += len;
}
head->r.w[0] = w;
if (*w)
return false;
/* Add '\0' for audit logs and query. */
if (head->poll) {
if (!head->read_user_buf_avail ||
copy_to_user(head->read_user_buf, "", 1))
return false;
head->read_user_buf_avail--;
head->read_user_buf++;
}
head->r.w_pos--;
for (len = 0; len < head->r.w_pos; len++)
head->r.w[len] = head->r.w[len + 1];
}
head->r.avail = 0;
return true;
}
/**
* tomoyo_set_string - Queue string to "struct tomoyo_io_buffer" structure.
*
* @head: Pointer to "struct tomoyo_io_buffer".
* @string: String to print.
*
* Note that @string has to be kept valid until @head is kfree()d.
* This means that char[] allocated on stack memory cannot be passed to
* this function. Use tomoyo_io_printf() for char[] allocated on stack memory.
*/
static void tomoyo_set_string(struct tomoyo_io_buffer *head, const char *string)
{
if (head->r.w_pos < TOMOYO_MAX_IO_READ_QUEUE) {
head->r.w[head->r.w_pos++] = string;
tomoyo_flush(head);
} else
WARN_ON(1);
}
static void tomoyo_io_printf(struct tomoyo_io_buffer *head, const char *fmt,
...) __printf(2, 3);
/**
* tomoyo_io_printf - printf() to "struct tomoyo_io_buffer" structure.
*
* @head: Pointer to "struct tomoyo_io_buffer".
* @fmt: The printf()'s format string, followed by parameters.
*/
static void tomoyo_io_printf(struct tomoyo_io_buffer *head, const char *fmt,
...)
{
va_list args;
size_t len;
size_t pos = head->r.avail;
int size = head->readbuf_size - pos;
if (size <= 0)
return;
va_start(args, fmt);
len = vsnprintf(head->read_buf + pos, size, fmt, args) + 1;
va_end(args);
if (pos + len >= head->readbuf_size) {
WARN_ON(1);
return;
}
head->r.avail += len;
tomoyo_set_string(head, head->read_buf + pos);
}
/**
* tomoyo_set_space - Put a space to "struct tomoyo_io_buffer" structure.
*
* @head: Pointer to "struct tomoyo_io_buffer".
*
* Returns nothing.
*/
static void tomoyo_set_space(struct tomoyo_io_buffer *head)
{
tomoyo_set_string(head, " ");
}
/**
* tomoyo_set_lf - Put a line feed to "struct tomoyo_io_buffer" structure.
*
* @head: Pointer to "struct tomoyo_io_buffer".
*
* Returns nothing.
*/
static bool tomoyo_set_lf(struct tomoyo_io_buffer *head)
{
tomoyo_set_string(head, "\n");
return !head->r.w_pos;
}
/**
* tomoyo_set_slash - Put a shash to "struct tomoyo_io_buffer" structure.
*
* @head: Pointer to "struct tomoyo_io_buffer".
*
* Returns nothing.
*/
static void tomoyo_set_slash(struct tomoyo_io_buffer *head)
{
tomoyo_set_string(head, "/");
}
/* List of namespaces. */
LIST_HEAD(tomoyo_namespace_list);
/* True if namespace other than tomoyo_kernel_namespace is defined. */
static bool tomoyo_namespace_enabled;
/**
* tomoyo_init_policy_namespace - Initialize namespace.
*
* @ns: Pointer to "struct tomoyo_policy_namespace".
*
* Returns nothing.
*/
void tomoyo_init_policy_namespace(struct tomoyo_policy_namespace *ns)
{
unsigned int idx;
for (idx = 0; idx < TOMOYO_MAX_ACL_GROUPS; idx++)
INIT_LIST_HEAD(&ns->acl_group[idx]);
for (idx = 0; idx < TOMOYO_MAX_GROUP; idx++)
INIT_LIST_HEAD(&ns->group_list[idx]);
for (idx = 0; idx < TOMOYO_MAX_POLICY; idx++)
INIT_LIST_HEAD(&ns->policy_list[idx]);
ns->profile_version = 20110903;
tomoyo_namespace_enabled = !list_empty(&tomoyo_namespace_list);
list_add_tail_rcu(&ns->namespace_list, &tomoyo_namespace_list);
}
/**
* tomoyo_print_namespace - Print namespace header.
*
* @head: Pointer to "struct tomoyo_io_buffer".
*
* Returns nothing.
*/
static void tomoyo_print_namespace(struct tomoyo_io_buffer *head)
{
if (!tomoyo_namespace_enabled)
return;
tomoyo_set_string(head,
container_of(head->r.ns,
struct tomoyo_policy_namespace,
namespace_list)->name);
tomoyo_set_space(head);
}
/**
* tomoyo_print_name_union - Print a tomoyo_name_union.
*
* @head: Pointer to "struct tomoyo_io_buffer".
* @ptr: Pointer to "struct tomoyo_name_union".
*/
static void tomoyo_print_name_union(struct tomoyo_io_buffer *head,
const struct tomoyo_name_union *ptr)
{
tomoyo_set_space(head);
if (ptr->group) {
tomoyo_set_string(head, "@");
tomoyo_set_string(head, ptr->group->group_name->name);
} else {
tomoyo_set_string(head, ptr->filename->name);
}
}
/**
* tomoyo_print_name_union_quoted - Print a tomoyo_name_union with a quote.
*
* @head: Pointer to "struct tomoyo_io_buffer".
* @ptr: Pointer to "struct tomoyo_name_union".
*
* Returns nothing.
*/
static void tomoyo_print_name_union_quoted(struct tomoyo_io_buffer *head,
const struct tomoyo_name_union *ptr)
{
if (ptr->group) {
tomoyo_set_string(head, "@");
tomoyo_set_string(head, ptr->group->group_name->name);
} else {
tomoyo_set_string(head, "\"");
tomoyo_set_string(head, ptr->filename->name);
tomoyo_set_string(head, "\"");
}
}
/**
* tomoyo_print_number_union_nospace - Print a tomoyo_number_union without a space.
*
* @head: Pointer to "struct tomoyo_io_buffer".
* @ptr: Pointer to "struct tomoyo_number_union".
*
* Returns nothing.
*/
static void tomoyo_print_number_union_nospace
(struct tomoyo_io_buffer *head, const struct tomoyo_number_union *ptr)
{
if (ptr->group) {
tomoyo_set_string(head, "@");
tomoyo_set_string(head, ptr->group->group_name->name);
} else {
int i;
unsigned long min = ptr->values[0];
const unsigned long max = ptr->values[1];
u8 min_type = ptr->value_type[0];
const u8 max_type = ptr->value_type[1];
char buffer[128];
buffer[0] = '\0';
for (i = 0; i < 2; i++) {
switch (min_type) {
case TOMOYO_VALUE_TYPE_HEXADECIMAL:
tomoyo_addprintf(buffer, sizeof(buffer),
"0x%lX", min);
break;
case TOMOYO_VALUE_TYPE_OCTAL:
tomoyo_addprintf(buffer, sizeof(buffer),
"0%lo", min);
break;
default:
tomoyo_addprintf(buffer, sizeof(buffer), "%lu",
min);
break;
}
if (min == max && min_type == max_type)
break;
tomoyo_addprintf(buffer, sizeof(buffer), "-");
min_type = max_type;
min = max;
}
tomoyo_io_printf(head, "%s", buffer);
}
}
/**
* tomoyo_print_number_union - Print a tomoyo_number_union.
*
* @head: Pointer to "struct tomoyo_io_buffer".
* @ptr: Pointer to "struct tomoyo_number_union".
*
* Returns nothing.
*/
static void tomoyo_print_number_union(struct tomoyo_io_buffer *head,
const struct tomoyo_number_union *ptr)
{
tomoyo_set_space(head);
tomoyo_print_number_union_nospace(head, ptr);
}
/**
* tomoyo_assign_profile - Create a new profile.
*
* @ns: Pointer to "struct tomoyo_policy_namespace".
* @profile: Profile number to create.
*
* Returns pointer to "struct tomoyo_profile" on success, NULL otherwise.
*/
static struct tomoyo_profile *tomoyo_assign_profile
(struct tomoyo_policy_namespace *ns, const unsigned int profile)
{
struct tomoyo_profile *ptr;
struct tomoyo_profile *entry;
if (profile >= TOMOYO_MAX_PROFILES)
return NULL;
ptr = ns->profile_ptr[profile];
if (ptr)
return ptr;
entry = kzalloc(sizeof(*entry), GFP_NOFS);
if (mutex_lock_interruptible(&tomoyo_policy_lock))
goto out;
ptr = ns->profile_ptr[profile];
if (!ptr && tomoyo_memory_ok(entry)) {
ptr = entry;
ptr->default_config = TOMOYO_CONFIG_DISABLED |
TOMOYO_CONFIG_WANT_GRANT_LOG |
TOMOYO_CONFIG_WANT_REJECT_LOG;
memset(ptr->config, TOMOYO_CONFIG_USE_DEFAULT,
sizeof(ptr->config));
ptr->pref[TOMOYO_PREF_MAX_AUDIT_LOG] =
CONFIG_SECURITY_TOMOYO_MAX_AUDIT_LOG;
ptr->pref[TOMOYO_PREF_MAX_LEARNING_ENTRY] =
CONFIG_SECURITY_TOMOYO_MAX_ACCEPT_ENTRY;
mb(); /* Avoid out-of-order execution. */
ns->profile_ptr[profile] = ptr;
entry = NULL;
}
mutex_unlock(&tomoyo_policy_lock);
out:
kfree(entry);
return ptr;
}
/**
* tomoyo_profile - Find a profile.
*
* @ns: Pointer to "struct tomoyo_policy_namespace".
* @profile: Profile number to find.
*
* Returns pointer to "struct tomoyo_profile".
*/
struct tomoyo_profile *tomoyo_profile(const struct tomoyo_policy_namespace *ns,
const u8 profile)
{
static struct tomoyo_profile tomoyo_null_profile;
struct tomoyo_profile *ptr = ns->profile_ptr[profile];
if (!ptr)
ptr = &tomoyo_null_profile;
return ptr;
}
/**
* tomoyo_find_yesno - Find values for specified keyword.
*
* @string: String to check.
* @find: Name of keyword.
*
* Returns 1 if "@find=yes" was found, 0 if "@find=no" was found, -1 otherwise.
*/
static s8 tomoyo_find_yesno(const char *string, const char *find)
{
const char *cp = strstr(string, find);
if (cp) {
cp += strlen(find);
if (!strncmp(cp, "=yes", 4))
return 1;
else if (!strncmp(cp, "=no", 3))
return 0;
}
return -1;
}
/**
* tomoyo_set_uint - Set value for specified preference.
*
* @i: Pointer to "unsigned int".
* @string: String to check.
* @find: Name of keyword.
*
* Returns nothing.
*/
static void tomoyo_set_uint(unsigned int *i, const char *string,
const char *find)
{
const char *cp = strstr(string, find);
if (cp)
sscanf(cp + strlen(find), "=%u", i);
}
/**
* tomoyo_set_mode - Set mode for specified profile.
*
* @name: Name of functionality.
* @value: Mode for @name.
* @profile: Pointer to "struct tomoyo_profile".
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_set_mode(char *name, const char *value,
struct tomoyo_profile *profile)
{
u8 i;
u8 config;
if (!strcmp(name, "CONFIG")) {
i = TOMOYO_MAX_MAC_INDEX + TOMOYO_MAX_MAC_CATEGORY_INDEX;
config = profile->default_config;
} else if (tomoyo_str_starts(&name, "CONFIG::")) {
config = 0;
for (i = 0; i < TOMOYO_MAX_MAC_INDEX
+ TOMOYO_MAX_MAC_CATEGORY_INDEX; i++) {
int len = 0;
if (i < TOMOYO_MAX_MAC_INDEX) {
const u8 c = tomoyo_index2category[i];
const char *category =
tomoyo_category_keywords[c];
len = strlen(category);
if (strncmp(name, category, len) ||
name[len++] != ':' || name[len++] != ':')
continue;
}
if (strcmp(name + len, tomoyo_mac_keywords[i]))
continue;
config = profile->config[i];
break;
}
if (i == TOMOYO_MAX_MAC_INDEX + TOMOYO_MAX_MAC_CATEGORY_INDEX)
return -EINVAL;
} else {
return -EINVAL;
}
if (strstr(value, "use_default")) {
config = TOMOYO_CONFIG_USE_DEFAULT;
} else {
u8 mode;
for (mode = 0; mode < 4; mode++)
if (strstr(value, tomoyo_mode[mode]))
/*
* Update lower 3 bits in order to distinguish
* 'config' from 'TOMOYO_CONFIG_USE_DEAFULT'.
*/
config = (config & ~7) | mode;
if (config != TOMOYO_CONFIG_USE_DEFAULT) {
switch (tomoyo_find_yesno(value, "grant_log")) {
case 1:
config |= TOMOYO_CONFIG_WANT_GRANT_LOG;
break;
case 0:
config &= ~TOMOYO_CONFIG_WANT_GRANT_LOG;
break;
}
switch (tomoyo_find_yesno(value, "reject_log")) {
case 1:
config |= TOMOYO_CONFIG_WANT_REJECT_LOG;
break;
case 0:
config &= ~TOMOYO_CONFIG_WANT_REJECT_LOG;
break;
}
}
}
if (i < TOMOYO_MAX_MAC_INDEX + TOMOYO_MAX_MAC_CATEGORY_INDEX)
profile->config[i] = config;
else if (config != TOMOYO_CONFIG_USE_DEFAULT)
profile->default_config = config;
return 0;
}
/**
* tomoyo_write_profile - Write profile table.
*
* @head: Pointer to "struct tomoyo_io_buffer".
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_write_profile(struct tomoyo_io_buffer *head)
{
char *data = head->write_buf;
unsigned int i;
char *cp;
struct tomoyo_profile *profile;
if (sscanf(data, "PROFILE_VERSION=%u", &head->w.ns->profile_version)
== 1)
return 0;
i = simple_strtoul(data, &cp, 10);
if (*cp != '-')
return -EINVAL;
data = cp + 1;
profile = tomoyo_assign_profile(head->w.ns, i);
if (!profile)
return -EINVAL;
cp = strchr(data, '=');
if (!cp)
return -EINVAL;
*cp++ = '\0';
if (!strcmp(data, "COMMENT")) {
static DEFINE_SPINLOCK(lock);
const struct tomoyo_path_info *new_comment
= tomoyo_get_name(cp);
const struct tomoyo_path_info *old_comment;
if (!new_comment)
return -ENOMEM;
spin_lock(&lock);
old_comment = profile->comment;
profile->comment = new_comment;
spin_unlock(&lock);
tomoyo_put_name(old_comment);
return 0;
}
if (!strcmp(data, "PREFERENCE")) {
for (i = 0; i < TOMOYO_MAX_PREF; i++)
tomoyo_set_uint(&profile->pref[i], cp,
tomoyo_pref_keywords[i]);
return 0;
}
return tomoyo_set_mode(data, cp, profile);
}
/**
* tomoyo_print_config - Print mode for specified functionality.
*
* @head: Pointer to "struct tomoyo_io_buffer".
* @config: Mode for that functionality.
*
* Returns nothing.
*
* Caller prints functionality's name.
*/
static void tomoyo_print_config(struct tomoyo_io_buffer *head, const u8 config)
{
tomoyo_io_printf(head, "={ mode=%s grant_log=%s reject_log=%s }\n",
tomoyo_mode[config & 3],
tomoyo_yesno(config & TOMOYO_CONFIG_WANT_GRANT_LOG),
tomoyo_yesno(config & TOMOYO_CONFIG_WANT_REJECT_LOG));
}
/**
* tomoyo_read_profile - Read profile table.
*
* @head: Pointer to "struct tomoyo_io_buffer".
*
* Returns nothing.
*/
static void tomoyo_read_profile(struct tomoyo_io_buffer *head)
{
u8 index;
struct tomoyo_policy_namespace *ns =
container_of(head->r.ns, typeof(*ns), namespace_list);
const struct tomoyo_profile *profile;
if (head->r.eof)
return;
next:
index = head->r.index;
profile = ns->profile_ptr[index];
switch (head->r.step) {
case 0:
tomoyo_print_namespace(head);
tomoyo_io_printf(head, "PROFILE_VERSION=%u\n",
ns->profile_version);
head->r.step++;
break;
case 1:
for ( ; head->r.index < TOMOYO_MAX_PROFILES;
head->r.index++)
if (ns->profile_ptr[head->r.index])
break;
if (head->r.index == TOMOYO_MAX_PROFILES) {
head->r.eof = true;
return;
}
head->r.step++;
break;
case 2:
{
u8 i;
const struct tomoyo_path_info *comment =
profile->comment;
tomoyo_print_namespace(head);
tomoyo_io_printf(head, "%u-COMMENT=", index);
tomoyo_set_string(head, comment ? comment->name : "");
tomoyo_set_lf(head);
tomoyo_print_namespace(head);
tomoyo_io_printf(head, "%u-PREFERENCE={ ", index);
for (i = 0; i < TOMOYO_MAX_PREF; i++)
tomoyo_io_printf(head, "%s=%u ",
tomoyo_pref_keywords[i],
profile->pref[i]);
tomoyo_set_string(head, "}\n");
head->r.step++;
}
break;
case 3:
{
tomoyo_print_namespace(head);
tomoyo_io_printf(head, "%u-%s", index, "CONFIG");
tomoyo_print_config(head, profile->default_config);
head->r.bit = 0;
head->r.step++;
}
break;
case 4:
for ( ; head->r.bit < TOMOYO_MAX_MAC_INDEX
+ TOMOYO_MAX_MAC_CATEGORY_INDEX; head->r.bit++) {
const u8 i = head->r.bit;
const u8 config = profile->config[i];
if (config == TOMOYO_CONFIG_USE_DEFAULT)
continue;
tomoyo_print_namespace(head);
if (i < TOMOYO_MAX_MAC_INDEX)
tomoyo_io_printf(head, "%u-CONFIG::%s::%s",
index,
tomoyo_category_keywords
[tomoyo_index2category[i]],
tomoyo_mac_keywords[i]);
else
tomoyo_io_printf(head, "%u-CONFIG::%s", index,
tomoyo_mac_keywords[i]);
tomoyo_print_config(head, config);
head->r.bit++;
break;
}
if (head->r.bit == TOMOYO_MAX_MAC_INDEX
+ TOMOYO_MAX_MAC_CATEGORY_INDEX) {
head->r.index++;
head->r.step = 1;
}
break;
}
if (tomoyo_flush(head))
goto next;
}
/**
* tomoyo_same_manager - Check for duplicated "struct tomoyo_manager" entry.
*
* @a: Pointer to "struct tomoyo_acl_head".
* @b: Pointer to "struct tomoyo_acl_head".
*
* Returns true if @a == @b, false otherwise.
*/
static bool tomoyo_same_manager(const struct tomoyo_acl_head *a,
const struct tomoyo_acl_head *b)
{
return container_of(a, struct tomoyo_manager, head)->manager ==
container_of(b, struct tomoyo_manager, head)->manager;
}
/**
* tomoyo_update_manager_entry - Add a manager entry.
*
* @manager: The path to manager or the domainnamme.
* @is_delete: True if it is a delete request.
*
* Returns 0 on success, negative value otherwise.
*
* Caller holds tomoyo_read_lock().
*/
static int tomoyo_update_manager_entry(const char *manager,
const bool is_delete)
{
struct tomoyo_manager e = { };
struct tomoyo_acl_param param = {
/* .ns = &tomoyo_kernel_namespace, */
.is_delete = is_delete,
.list = &tomoyo_kernel_namespace.
policy_list[TOMOYO_ID_MANAGER],
};
int error = is_delete ? -ENOENT : -ENOMEM;
if (tomoyo_domain_def(manager)) {
if (!tomoyo_correct_domain(manager))
return -EINVAL;
e.is_domain = true;
} else {
if (!tomoyo_correct_path(manager))
return -EINVAL;
}
e.manager = tomoyo_get_name(manager);
if (e.manager) {
error = tomoyo_update_policy(&e.head, sizeof(e), ¶m,
tomoyo_same_manager);
tomoyo_put_name(e.manager);
}
return error;
}
/**
* tomoyo_write_manager - Write manager policy.
*
* @head: Pointer to "struct tomoyo_io_buffer".
*
* Returns 0 on success, negative value otherwise.
*
* Caller holds tomoyo_read_lock().
*/
static int tomoyo_write_manager(struct tomoyo_io_buffer *head)
{
char *data = head->write_buf;
if (!strcmp(data, "manage_by_non_root")) {
tomoyo_manage_by_non_root = !head->w.is_delete;
return 0;
}
return tomoyo_update_manager_entry(data, head->w.is_delete);
}
/**
* tomoyo_read_manager - Read manager policy.
*
* @head: Pointer to "struct tomoyo_io_buffer".
*
* Caller holds tomoyo_read_lock().
*/
static void tomoyo_read_manager(struct tomoyo_io_buffer *head)
{
if (head->r.eof)
return;
list_for_each_cookie(head->r.acl, &tomoyo_kernel_namespace.
policy_list[TOMOYO_ID_MANAGER]) {
struct tomoyo_manager *ptr =
list_entry(head->r.acl, typeof(*ptr), head.list);
if (ptr->head.is_deleted)
continue;
if (!tomoyo_flush(head))
return;
tomoyo_set_string(head, ptr->manager->name);
tomoyo_set_lf(head);
}
head->r.eof = true;
}
/**
* tomoyo_manager - Check whether the current process is a policy manager.
*
* Returns true if the current process is permitted to modify policy
* via /sys/kernel/security/tomoyo/ interface.
*
* Caller holds tomoyo_read_lock().
*/
static bool tomoyo_manager(void)
{
struct tomoyo_manager *ptr;
const char *exe;
const struct task_struct *task = current;
const struct tomoyo_path_info *domainname = tomoyo_domain()->domainname;
bool found = false;
if (!tomoyo_policy_loaded)
return true;
if (!tomoyo_manage_by_non_root && (task->cred->uid || task->cred->euid))
return false;
list_for_each_entry_rcu(ptr, &tomoyo_kernel_namespace.
policy_list[TOMOYO_ID_MANAGER], head.list) {
if (!ptr->head.is_deleted && ptr->is_domain
&& !tomoyo_pathcmp(domainname, ptr->manager)) {
found = true;
break;
}
}
if (found)
return true;
exe = tomoyo_get_exe();
if (!exe)
return false;
list_for_each_entry_rcu(ptr, &tomoyo_kernel_namespace.
policy_list[TOMOYO_ID_MANAGER], head.list) {
if (!ptr->head.is_deleted && !ptr->is_domain
&& !strcmp(exe, ptr->manager->name)) {
found = true;
break;
}
}
if (!found) { /* Reduce error messages. */
static pid_t last_pid;
const pid_t pid = current->pid;
if (last_pid != pid) {
printk(KERN_WARNING "%s ( %s ) is not permitted to "
"update policies.\n", domainname->name, exe);
last_pid = pid;
}
}
kfree(exe);
return found;
}
static struct tomoyo_domain_info *tomoyo_find_domain_by_qid
(unsigned int serial);
/**
* tomoyo_select_domain - Parse select command.
*
* @head: Pointer to "struct tomoyo_io_buffer".
* @data: String to parse.
*
* Returns true on success, false otherwise.
*
* Caller holds tomoyo_read_lock().
*/
static bool tomoyo_select_domain(struct tomoyo_io_buffer *head,
const char *data)
{
unsigned int pid;
struct tomoyo_domain_info *domain = NULL;
bool global_pid = false;
if (strncmp(data, "select ", 7))
return false;
data += 7;
if (sscanf(data, "pid=%u", &pid) == 1 ||
(global_pid = true, sscanf(data, "global-pid=%u", &pid) == 1)) {
struct task_struct *p;
rcu_read_lock();
if (global_pid)
p = find_task_by_pid_ns(pid, &init_pid_ns);
else
p = find_task_by_vpid(pid);
if (p)
domain = tomoyo_real_domain(p);
rcu_read_unlock();
} else if (!strncmp(data, "domain=", 7)) {
if (tomoyo_domain_def(data + 7))
domain = tomoyo_find_domain(data + 7);
} else if (sscanf(data, "Q=%u", &pid) == 1) {
domain = tomoyo_find_domain_by_qid(pid);
} else
return false;
head->w.domain = domain;
/* Accessing read_buf is safe because head->io_sem is held. */
if (!head->read_buf)
return true; /* Do nothing if open(O_WRONLY). */
memset(&head->r, 0, sizeof(head->r));
head->r.print_this_domain_only = true;
if (domain)
head->r.domain = &domain->list;
else
head->r.eof = 1;
tomoyo_io_printf(head, "# select %s\n", data);
if (domain && domain->is_deleted)
tomoyo_io_printf(head, "# This is a deleted domain.\n");
return true;
}
/**
* tomoyo_same_task_acl - Check for duplicated "struct tomoyo_task_acl" entry.
*
* @a: Pointer to "struct tomoyo_acl_info".
* @b: Pointer to "struct tomoyo_acl_info".
*
* Returns true if @a == @b, false otherwise.
*/
static bool tomoyo_same_task_acl(const struct tomoyo_acl_info *a,
const struct tomoyo_acl_info *b)
{
const struct tomoyo_task_acl *p1 = container_of(a, typeof(*p1), head);
const struct tomoyo_task_acl *p2 = container_of(b, typeof(*p2), head);
return p1->domainname == p2->domainname;
}
/**
* tomoyo_write_task - Update task related list.
*
* @param: Pointer to "struct tomoyo_acl_param".
*
* Returns 0 on success, negative value otherwise.
*
* Caller holds tomoyo_read_lock().
*/
static int tomoyo_write_task(struct tomoyo_acl_param *param)
{
int error = -EINVAL;
if (tomoyo_str_starts(¶m->data, "manual_domain_transition ")) {
struct tomoyo_task_acl e = {
.head.type = TOMOYO_TYPE_MANUAL_TASK_ACL,
.domainname = tomoyo_get_domainname(param),
};
if (e.domainname)
error = tomoyo_update_domain(&e.head, sizeof(e), param,
tomoyo_same_task_acl,
NULL);
tomoyo_put_name(e.domainname);
}
return error;
}
/**
* tomoyo_delete_domain - Delete a domain.
*
* @domainname: The name of domain.
*
* Returns 0 on success, negative value otherwise.
*
* Caller holds tomoyo_read_lock().
*/
static int tomoyo_delete_domain(char *domainname)
{
struct tomoyo_domain_info *domain;
struct tomoyo_path_info name;
name.name = domainname;
tomoyo_fill_path_info(&name);
if (mutex_lock_interruptible(&tomoyo_policy_lock))
return -EINTR;
/* Is there an active domain? */
list_for_each_entry_rcu(domain, &tomoyo_domain_list, list) {
/* Never delete tomoyo_kernel_domain */
if (domain == &tomoyo_kernel_domain)
continue;
if (domain->is_deleted ||
tomoyo_pathcmp(domain->domainname, &name))
continue;
domain->is_deleted = true;
break;
}
mutex_unlock(&tomoyo_policy_lock);
return 0;
}
/**
* tomoyo_write_domain2 - Write domain policy.
*
* @ns: Pointer to "struct tomoyo_policy_namespace".
* @list: Pointer to "struct list_head".
* @data: Policy to be interpreted.
* @is_delete: True if it is a delete request.
*
* Returns 0 on success, negative value otherwise.
*
* Caller holds tomoyo_read_lock().
*/
static int tomoyo_write_domain2(struct tomoyo_policy_namespace *ns,
struct list_head *list, char *data,
const bool is_delete)
{
struct tomoyo_acl_param param = {
.ns = ns,
.list = list,
.data = data,
.is_delete = is_delete,
};
static const struct {
const char *keyword;
int (*write) (struct tomoyo_acl_param *);
} tomoyo_callback[5] = {
{ "file ", tomoyo_write_file },
{ "network inet ", tomoyo_write_inet_network },
{ "network unix ", tomoyo_write_unix_network },
{ "misc ", tomoyo_write_misc },
{ "task ", tomoyo_write_task },
};
u8 i;
for (i = 0; i < ARRAY_SIZE(tomoyo_callback); i++) {
if (!tomoyo_str_starts(¶m.data,
tomoyo_callback[i].keyword))
continue;
return tomoyo_callback[i].write(¶m);
}
return -EINVAL;
}
/* String table for domain flags. */
const char * const tomoyo_dif[TOMOYO_MAX_DOMAIN_INFO_FLAGS] = {
[TOMOYO_DIF_QUOTA_WARNED] = "quota_exceeded\n",
[TOMOYO_DIF_TRANSITION_FAILED] = "transition_failed\n",
};
/**
* tomoyo_write_domain - Write domain policy.
*
* @head: Pointer to "struct tomoyo_io_buffer".
*
* Returns 0 on success, negative value otherwise.
*
* Caller holds tomoyo_read_lock().
*/
static int tomoyo_write_domain(struct tomoyo_io_buffer *head)
{
char *data = head->write_buf;
struct tomoyo_policy_namespace *ns;
struct tomoyo_domain_info *domain = head->w.domain;
const bool is_delete = head->w.is_delete;
bool is_select = !is_delete && tomoyo_str_starts(&data, "select ");
unsigned int profile;
if (*data == '<') {
int ret = 0;
domain = NULL;
if (is_delete)
ret = tomoyo_delete_domain(data);
else if (is_select)
domain = tomoyo_find_domain(data);
else
domain = tomoyo_assign_domain(data, false);
head->w.domain = domain;
return ret;
}
if (!domain)
return -EINVAL;
ns = domain->ns;
if (sscanf(data, "use_profile %u", &profile) == 1
&& profile < TOMOYO_MAX_PROFILES) {
if (!tomoyo_policy_loaded || ns->profile_ptr[profile])
domain->profile = (u8) profile;
return 0;
}
if (sscanf(data, "use_group %u\n", &profile) == 1
&& profile < TOMOYO_MAX_ACL_GROUPS) {
if (!is_delete)
domain->group = (u8) profile;
return 0;
}
for (profile = 0; profile < TOMOYO_MAX_DOMAIN_INFO_FLAGS; profile++) {
const char *cp = tomoyo_dif[profile];
if (strncmp(data, cp, strlen(cp) - 1))
continue;
domain->flags[profile] = !is_delete;
return 0;
}
return tomoyo_write_domain2(ns, &domain->acl_info_list, data,
is_delete);
}
/**
* tomoyo_print_condition - Print condition part.
*
* @head: Pointer to "struct tomoyo_io_buffer".
* @cond: Pointer to "struct tomoyo_condition".
*
* Returns true on success, false otherwise.
*/
static bool tomoyo_print_condition(struct tomoyo_io_buffer *head,
const struct tomoyo_condition *cond)
{
switch (head->r.cond_step) {
case 0:
head->r.cond_index = 0;
head->r.cond_step++;
if (cond->transit) {
tomoyo_set_space(head);
tomoyo_set_string(head, cond->transit->name);
}
/* fall through */
case 1:
{
const u16 condc = cond->condc;
const struct tomoyo_condition_element *condp =
(typeof(condp)) (cond + 1);
const struct tomoyo_number_union *numbers_p =
(typeof(numbers_p)) (condp + condc);
const struct tomoyo_name_union *names_p =
(typeof(names_p))
(numbers_p + cond->numbers_count);
const struct tomoyo_argv *argv =
(typeof(argv)) (names_p + cond->names_count);
const struct tomoyo_envp *envp =
(typeof(envp)) (argv + cond->argc);
u16 skip;
for (skip = 0; skip < head->r.cond_index; skip++) {
const u8 left = condp->left;
const u8 right = condp->right;
condp++;
switch (left) {
case TOMOYO_ARGV_ENTRY:
argv++;
continue;
case TOMOYO_ENVP_ENTRY:
envp++;
continue;
case TOMOYO_NUMBER_UNION:
numbers_p++;
break;
}
switch (right) {
case TOMOYO_NAME_UNION:
names_p++;
break;
case TOMOYO_NUMBER_UNION:
numbers_p++;
break;
}
}
while (head->r.cond_index < condc) {
const u8 match = condp->equals;
const u8 left = condp->left;
const u8 right = condp->right;
if (!tomoyo_flush(head))
return false;
condp++;
head->r.cond_index++;
tomoyo_set_space(head);
switch (left) {
case TOMOYO_ARGV_ENTRY:
tomoyo_io_printf(head,
"exec.argv[%lu]%s=\"",
argv->index, argv->
is_not ? "!" : "");
tomoyo_set_string(head,
argv->value->name);
tomoyo_set_string(head, "\"");
argv++;
continue;
case TOMOYO_ENVP_ENTRY:
tomoyo_set_string(head,
"exec.envp[\"");
tomoyo_set_string(head,
envp->name->name);
tomoyo_io_printf(head, "\"]%s=", envp->
is_not ? "!" : "");
if (envp->value) {
tomoyo_set_string(head, "\"");
tomoyo_set_string(head, envp->
value->name);
tomoyo_set_string(head, "\"");
} else {
tomoyo_set_string(head,
"NULL");
}
envp++;
continue;
case TOMOYO_NUMBER_UNION:
tomoyo_print_number_union_nospace
(head, numbers_p++);
break;
default:
tomoyo_set_string(head,
tomoyo_condition_keyword[left]);
break;
}
tomoyo_set_string(head, match ? "=" : "!=");
switch (right) {
case TOMOYO_NAME_UNION:
tomoyo_print_name_union_quoted
(head, names_p++);
break;
case TOMOYO_NUMBER_UNION:
tomoyo_print_number_union_nospace
(head, numbers_p++);
break;
default:
tomoyo_set_string(head,
tomoyo_condition_keyword[right]);
break;
}
}
}
head->r.cond_step++;
/* fall through */
case 2:
if (!tomoyo_flush(head))
break;
head->r.cond_step++;
/* fall through */
case 3:
if (cond->grant_log != TOMOYO_GRANTLOG_AUTO)
tomoyo_io_printf(head, " grant_log=%s",
tomoyo_yesno(cond->grant_log ==
TOMOYO_GRANTLOG_YES));
tomoyo_set_lf(head);
return true;
}
return false;
}
/**
* tomoyo_set_group - Print "acl_group " header keyword and category name.
*
* @head: Pointer to "struct tomoyo_io_buffer".
* @category: Category name.
*
* Returns nothing.
*/
static void tomoyo_set_group(struct tomoyo_io_buffer *head,
const char *category)
{
if (head->type == TOMOYO_EXCEPTIONPOLICY) {
tomoyo_print_namespace(head);
tomoyo_io_printf(head, "acl_group %u ",
head->r.acl_group_index);
}
tomoyo_set_string(head, category);
}
/**
* tomoyo_print_entry - Print an ACL entry.
*
* @head: Pointer to "struct tomoyo_io_buffer".
* @acl: Pointer to an ACL entry.
*
* Returns true on success, false otherwise.
*/
static bool tomoyo_print_entry(struct tomoyo_io_buffer *head,
struct tomoyo_acl_info *acl)
{
const u8 acl_type = acl->type;
bool first = true;
u8 bit;
if (head->r.print_cond_part)
goto print_cond_part;
if (acl->is_deleted)
return true;
if (!tomoyo_flush(head))
return false;
else if (acl_type == TOMOYO_TYPE_PATH_ACL) {
struct tomoyo_path_acl *ptr =
container_of(acl, typeof(*ptr), head);
const u16 perm = ptr->perm;
for (bit = 0; bit < TOMOYO_MAX_PATH_OPERATION; bit++) {
if (!(perm & (1 << bit)))
continue;
if (head->r.print_transition_related_only &&
bit != TOMOYO_TYPE_EXECUTE)
continue;
if (first) {
tomoyo_set_group(head, "file ");
first = false;
} else {
tomoyo_set_slash(head);
}
tomoyo_set_string(head, tomoyo_path_keyword[bit]);
}
if (first)
return true;
tomoyo_print_name_union(head, &ptr->name);
} else if (acl_type == TOMOYO_TYPE_MANUAL_TASK_ACL) {
struct tomoyo_task_acl *ptr =
container_of(acl, typeof(*ptr), head);
tomoyo_set_group(head, "task ");
tomoyo_set_string(head, "manual_domain_transition ");
tomoyo_set_string(head, ptr->domainname->name);
} else if (head->r.print_transition_related_only) {
return true;
} else if (acl_type == TOMOYO_TYPE_PATH2_ACL) {
struct tomoyo_path2_acl *ptr =
container_of(acl, typeof(*ptr), head);
const u8 perm = ptr->perm;
for (bit = 0; bit < TOMOYO_MAX_PATH2_OPERATION; bit++) {
if (!(perm & (1 << bit)))
continue;
if (first) {
tomoyo_set_group(head, "file ");
first = false;
} else {
tomoyo_set_slash(head);
}
tomoyo_set_string(head, tomoyo_mac_keywords
[tomoyo_pp2mac[bit]]);
}
if (first)
return true;
tomoyo_print_name_union(head, &ptr->name1);
tomoyo_print_name_union(head, &ptr->name2);
} else if (acl_type == TOMOYO_TYPE_PATH_NUMBER_ACL) {
struct tomoyo_path_number_acl *ptr =
container_of(acl, typeof(*ptr), head);
const u8 perm = ptr->perm;
for (bit = 0; bit < TOMOYO_MAX_PATH_NUMBER_OPERATION; bit++) {
if (!(perm & (1 << bit)))
continue;
if (first) {
tomoyo_set_group(head, "file ");
first = false;
} else {
tomoyo_set_slash(head);
}
tomoyo_set_string(head, tomoyo_mac_keywords
[tomoyo_pn2mac[bit]]);
}
if (first)
return true;
tomoyo_print_name_union(head, &ptr->name);
tomoyo_print_number_union(head, &ptr->number);
} else if (acl_type == TOMOYO_TYPE_MKDEV_ACL) {
struct tomoyo_mkdev_acl *ptr =
container_of(acl, typeof(*ptr), head);
const u8 perm = ptr->perm;
for (bit = 0; bit < TOMOYO_MAX_MKDEV_OPERATION; bit++) {
if (!(perm & (1 << bit)))
continue;
if (first) {
tomoyo_set_group(head, "file ");
first = false;
} else {
tomoyo_set_slash(head);
}
tomoyo_set_string(head, tomoyo_mac_keywords
[tomoyo_pnnn2mac[bit]]);
}
if (first)
return true;
tomoyo_print_name_union(head, &ptr->name);
tomoyo_print_number_union(head, &ptr->mode);
tomoyo_print_number_union(head, &ptr->major);
tomoyo_print_number_union(head, &ptr->minor);
} else if (acl_type == TOMOYO_TYPE_INET_ACL) {
struct tomoyo_inet_acl *ptr =
container_of(acl, typeof(*ptr), head);
const u8 perm = ptr->perm;
for (bit = 0; bit < TOMOYO_MAX_NETWORK_OPERATION; bit++) {
if (!(perm & (1 << bit)))
continue;
if (first) {
tomoyo_set_group(head, "network inet ");
tomoyo_set_string(head, tomoyo_proto_keyword
[ptr->protocol]);
tomoyo_set_space(head);
first = false;
} else {
tomoyo_set_slash(head);
}
tomoyo_set_string(head, tomoyo_socket_keyword[bit]);
}
if (first)
return true;
tomoyo_set_space(head);
if (ptr->address.group) {
tomoyo_set_string(head, "@");
tomoyo_set_string(head, ptr->address.group->group_name
->name);
} else {
char buf[128];
tomoyo_print_ip(buf, sizeof(buf), &ptr->address);
tomoyo_io_printf(head, "%s", buf);
}
tomoyo_print_number_union(head, &ptr->port);
} else if (acl_type == TOMOYO_TYPE_UNIX_ACL) {
struct tomoyo_unix_acl *ptr =
container_of(acl, typeof(*ptr), head);
const u8 perm = ptr->perm;
for (bit = 0; bit < TOMOYO_MAX_NETWORK_OPERATION; bit++) {
if (!(perm & (1 << bit)))
continue;
if (first) {
tomoyo_set_group(head, "network unix ");
tomoyo_set_string(head, tomoyo_proto_keyword
[ptr->protocol]);
tomoyo_set_space(head);
first = false;
} else {
tomoyo_set_slash(head);
}
tomoyo_set_string(head, tomoyo_socket_keyword[bit]);
}
if (first)
return true;
tomoyo_print_name_union(head, &ptr->name);
} else if (acl_type == TOMOYO_TYPE_MOUNT_ACL) {
struct tomoyo_mount_acl *ptr =
container_of(acl, typeof(*ptr), head);
tomoyo_set_group(head, "file mount");
tomoyo_print_name_union(head, &ptr->dev_name);
tomoyo_print_name_union(head, &ptr->dir_name);
tomoyo_print_name_union(head, &ptr->fs_type);
tomoyo_print_number_union(head, &ptr->flags);
} else if (acl_type == TOMOYO_TYPE_ENV_ACL) {
struct tomoyo_env_acl *ptr =
container_of(acl, typeof(*ptr), head);
tomoyo_set_group(head, "misc env ");
tomoyo_set_string(head, ptr->env->name);
}
if (acl->cond) {
head->r.print_cond_part = true;
head->r.cond_step = 0;
if (!tomoyo_flush(head))
return false;
print_cond_part:
if (!tomoyo_print_condition(head, acl->cond))
return false;
head->r.print_cond_part = false;
} else {
tomoyo_set_lf(head);
}
return true;
}
/**
* tomoyo_read_domain2 - Read domain policy.
*
* @head: Pointer to "struct tomoyo_io_buffer".
* @list: Pointer to "struct list_head".
*
* Caller holds tomoyo_read_lock().
*
* Returns true on success, false otherwise.
*/
static bool tomoyo_read_domain2(struct tomoyo_io_buffer *head,
struct list_head *list)
{
list_for_each_cookie(head->r.acl, list) {
struct tomoyo_acl_info *ptr =
list_entry(head->r.acl, typeof(*ptr), list);
if (!tomoyo_print_entry(head, ptr))
return false;
}
head->r.acl = NULL;
return true;
}
/**
* tomoyo_read_domain - Read domain policy.
*
* @head: Pointer to "struct tomoyo_io_buffer".
*
* Caller holds tomoyo_read_lock().
*/
static void tomoyo_read_domain(struct tomoyo_io_buffer *head)
{
if (head->r.eof)
return;
list_for_each_cookie(head->r.domain, &tomoyo_domain_list) {
struct tomoyo_domain_info *domain =
list_entry(head->r.domain, typeof(*domain), list);
switch (head->r.step) {
u8 i;
case 0:
if (domain->is_deleted &&
!head->r.print_this_domain_only)
continue;
/* Print domainname and flags. */
tomoyo_set_string(head, domain->domainname->name);
tomoyo_set_lf(head);
tomoyo_io_printf(head, "use_profile %u\n",
domain->profile);
tomoyo_io_printf(head, "use_group %u\n",
domain->group);
for (i = 0; i < TOMOYO_MAX_DOMAIN_INFO_FLAGS; i++)
if (domain->flags[i])
tomoyo_set_string(head, tomoyo_dif[i]);
head->r.step++;
tomoyo_set_lf(head);
/* fall through */
case 1:
if (!tomoyo_read_domain2(head, &domain->acl_info_list))
return;
head->r.step++;
if (!tomoyo_set_lf(head))
return;
/* fall through */
case 2:
head->r.step = 0;
if (head->r.print_this_domain_only)
goto done;
}
}
done:
head->r.eof = true;
}
/**
* tomoyo_write_pid: Specify PID to obtain domainname.
*
* @head: Pointer to "struct tomoyo_io_buffer".
*
* Returns 0.
*/
static int tomoyo_write_pid(struct tomoyo_io_buffer *head)
{
head->r.eof = false;
return 0;
}
/**
* tomoyo_read_pid - Get domainname of the specified PID.
*
* @head: Pointer to "struct tomoyo_io_buffer".
*
* Returns the domainname which the specified PID is in on success,
* empty string otherwise.
* The PID is specified by tomoyo_write_pid() so that the user can obtain
* using read()/write() interface rather than sysctl() interface.
*/
static void tomoyo_read_pid(struct tomoyo_io_buffer *head)
{
char *buf = head->write_buf;
bool global_pid = false;
unsigned int pid;
struct task_struct *p;
struct tomoyo_domain_info *domain = NULL;
/* Accessing write_buf is safe because head->io_sem is held. */
if (!buf) {
head->r.eof = true;
return; /* Do nothing if open(O_RDONLY). */
}
if (head->r.w_pos || head->r.eof)
return;
head->r.eof = true;
if (tomoyo_str_starts(&buf, "global-pid "))
global_pid = true;
pid = (unsigned int) simple_strtoul(buf, NULL, 10);
rcu_read_lock();
if (global_pid)
p = find_task_by_pid_ns(pid, &init_pid_ns);
else
p = find_task_by_vpid(pid);
if (p)
domain = tomoyo_real_domain(p);
rcu_read_unlock();
if (!domain)
return;
tomoyo_io_printf(head, "%u %u ", pid, domain->profile);
tomoyo_set_string(head, domain->domainname->name);
}
/* String table for domain transition control keywords. */
static const char *tomoyo_transition_type[TOMOYO_MAX_TRANSITION_TYPE] = {
[TOMOYO_TRANSITION_CONTROL_NO_RESET] = "no_reset_domain ",
[TOMOYO_TRANSITION_CONTROL_RESET] = "reset_domain ",
[TOMOYO_TRANSITION_CONTROL_NO_INITIALIZE] = "no_initialize_domain ",
[TOMOYO_TRANSITION_CONTROL_INITIALIZE] = "initialize_domain ",
[TOMOYO_TRANSITION_CONTROL_NO_KEEP] = "no_keep_domain ",
[TOMOYO_TRANSITION_CONTROL_KEEP] = "keep_domain ",
};
/* String table for grouping keywords. */
static const char *tomoyo_group_name[TOMOYO_MAX_GROUP] = {
[TOMOYO_PATH_GROUP] = "path_group ",
[TOMOYO_NUMBER_GROUP] = "number_group ",
[TOMOYO_ADDRESS_GROUP] = "address_group ",
};
/**
* tomoyo_write_exception - Write exception policy.
*
* @head: Pointer to "struct tomoyo_io_buffer".
*
* Returns 0 on success, negative value otherwise.
*
* Caller holds tomoyo_read_lock().
*/
static int tomoyo_write_exception(struct tomoyo_io_buffer *head)
{
const bool is_delete = head->w.is_delete;
struct tomoyo_acl_param param = {
.ns = head->w.ns,
.is_delete = is_delete,
.data = head->write_buf,
};
u8 i;
if (tomoyo_str_starts(¶m.data, "aggregator "))
return tomoyo_write_aggregator(¶m);
for (i = 0; i < TOMOYO_MAX_TRANSITION_TYPE; i++)
if (tomoyo_str_starts(¶m.data, tomoyo_transition_type[i]))
return tomoyo_write_transition_control(¶m, i);
for (i = 0; i < TOMOYO_MAX_GROUP; i++)
if (tomoyo_str_starts(¶m.data, tomoyo_group_name[i]))
return tomoyo_write_group(¶m, i);
if (tomoyo_str_starts(¶m.data, "acl_group ")) {
unsigned int group;
char *data;
group = simple_strtoul(param.data, &data, 10);
if (group < TOMOYO_MAX_ACL_GROUPS && *data++ == ' ')
return tomoyo_write_domain2
(head->w.ns, &head->w.ns->acl_group[group],
data, is_delete);
}
return -EINVAL;
}
/**
* tomoyo_read_group - Read "struct tomoyo_path_group"/"struct tomoyo_number_group"/"struct tomoyo_address_group" list.
*
* @head: Pointer to "struct tomoyo_io_buffer".
* @idx: Index number.
*
* Returns true on success, false otherwise.
*
* Caller holds tomoyo_read_lock().
*/
static bool tomoyo_read_group(struct tomoyo_io_buffer *head, const int idx)
{
struct tomoyo_policy_namespace *ns =
container_of(head->r.ns, typeof(*ns), namespace_list);
struct list_head *list = &ns->group_list[idx];
list_for_each_cookie(head->r.group, list) {
struct tomoyo_group *group =
list_entry(head->r.group, typeof(*group), head.list);
list_for_each_cookie(head->r.acl, &group->member_list) {
struct tomoyo_acl_head *ptr =
list_entry(head->r.acl, typeof(*ptr), list);
if (ptr->is_deleted)
continue;
if (!tomoyo_flush(head))
return false;
tomoyo_print_namespace(head);
tomoyo_set_string(head, tomoyo_group_name[idx]);
tomoyo_set_string(head, group->group_name->name);
if (idx == TOMOYO_PATH_GROUP) {
tomoyo_set_space(head);
tomoyo_set_string(head, container_of
(ptr, struct tomoyo_path_group,
head)->member_name->name);
} else if (idx == TOMOYO_NUMBER_GROUP) {
tomoyo_print_number_union(head, &container_of
(ptr,
struct tomoyo_number_group,
head)->number);
} else if (idx == TOMOYO_ADDRESS_GROUP) {
char buffer[128];
struct tomoyo_address_group *member =
container_of(ptr, typeof(*member),
head);
tomoyo_print_ip(buffer, sizeof(buffer),
&member->address);
tomoyo_io_printf(head, " %s", buffer);
}
tomoyo_set_lf(head);
}
head->r.acl = NULL;
}
head->r.group = NULL;
return true;
}
/**
* tomoyo_read_policy - Read "struct tomoyo_..._entry" list.
*
* @head: Pointer to "struct tomoyo_io_buffer".
* @idx: Index number.
*
* Returns true on success, false otherwise.
*
* Caller holds tomoyo_read_lock().
*/
static bool tomoyo_read_policy(struct tomoyo_io_buffer *head, const int idx)
{
struct tomoyo_policy_namespace *ns =
container_of(head->r.ns, typeof(*ns), namespace_list);
struct list_head *list = &ns->policy_list[idx];
list_for_each_cookie(head->r.acl, list) {
struct tomoyo_acl_head *acl =
container_of(head->r.acl, typeof(*acl), list);
if (acl->is_deleted)
continue;
if (!tomoyo_flush(head))
return false;
switch (idx) {
case TOMOYO_ID_TRANSITION_CONTROL:
{
struct tomoyo_transition_control *ptr =
container_of(acl, typeof(*ptr), head);
tomoyo_print_namespace(head);
tomoyo_set_string(head, tomoyo_transition_type
[ptr->type]);
tomoyo_set_string(head, ptr->program ?
ptr->program->name : "any");
tomoyo_set_string(head, " from ");
tomoyo_set_string(head, ptr->domainname ?
ptr->domainname->name :
"any");
}
break;
case TOMOYO_ID_AGGREGATOR:
{
struct tomoyo_aggregator *ptr =
container_of(acl, typeof(*ptr), head);
tomoyo_print_namespace(head);
tomoyo_set_string(head, "aggregator ");
tomoyo_set_string(head,
ptr->original_name->name);
tomoyo_set_space(head);
tomoyo_set_string(head,
ptr->aggregated_name->name);
}
break;
default:
continue;
}
tomoyo_set_lf(head);
}
head->r.acl = NULL;
return true;
}
/**
* tomoyo_read_exception - Read exception policy.
*
* @head: Pointer to "struct tomoyo_io_buffer".
*
* Caller holds tomoyo_read_lock().
*/
static void tomoyo_read_exception(struct tomoyo_io_buffer *head)
{
struct tomoyo_policy_namespace *ns =
container_of(head->r.ns, typeof(*ns), namespace_list);
if (head->r.eof)
return;
while (head->r.step < TOMOYO_MAX_POLICY &&
tomoyo_read_policy(head, head->r.step))
head->r.step++;
if (head->r.step < TOMOYO_MAX_POLICY)
return;
while (head->r.step < TOMOYO_MAX_POLICY + TOMOYO_MAX_GROUP &&
tomoyo_read_group(head, head->r.step - TOMOYO_MAX_POLICY))
head->r.step++;
if (head->r.step < TOMOYO_MAX_POLICY + TOMOYO_MAX_GROUP)
return;
while (head->r.step < TOMOYO_MAX_POLICY + TOMOYO_MAX_GROUP
+ TOMOYO_MAX_ACL_GROUPS) {
head->r.acl_group_index = head->r.step - TOMOYO_MAX_POLICY
- TOMOYO_MAX_GROUP;
if (!tomoyo_read_domain2(head, &ns->acl_group
[head->r.acl_group_index]))
return;
head->r.step++;
}
head->r.eof = true;
}
/* Wait queue for kernel -> userspace notification. */
static DECLARE_WAIT_QUEUE_HEAD(tomoyo_query_wait);
/* Wait queue for userspace -> kernel notification. */
static DECLARE_WAIT_QUEUE_HEAD(tomoyo_answer_wait);
/* Structure for query. */
struct tomoyo_query {
struct list_head list;
struct tomoyo_domain_info *domain;
char *query;
size_t query_len;
unsigned int serial;
u8 timer;
u8 answer;
u8 retry;
};
/* The list for "struct tomoyo_query". */
static LIST_HEAD(tomoyo_query_list);
/* Lock for manipulating tomoyo_query_list. */
static DEFINE_SPINLOCK(tomoyo_query_list_lock);
/*
* Number of "struct file" referring /sys/kernel/security/tomoyo/query
* interface.
*/
static atomic_t tomoyo_query_observers = ATOMIC_INIT(0);
/**
* tomoyo_truncate - Truncate a line.
*
* @str: String to truncate.
*
* Returns length of truncated @str.
*/
static int tomoyo_truncate(char *str)
{
char *start = str;
while (*(unsigned char *) str > (unsigned char) ' ')
str++;
*str = '\0';
return strlen(start) + 1;
}
/**
* tomoyo_add_entry - Add an ACL to current thread's domain. Used by learning mode.
*
* @domain: Pointer to "struct tomoyo_domain_info".
* @header: Lines containing ACL.
*
* Returns nothing.
*/
static void tomoyo_add_entry(struct tomoyo_domain_info *domain, char *header)
{
char *buffer;
char *realpath = NULL;
char *argv0 = NULL;
char *symlink = NULL;
char *cp = strchr(header, '\n');
int len;
if (!cp)
return;
cp = strchr(cp + 1, '\n');
if (!cp)
return;
*cp++ = '\0';
len = strlen(cp) + 1;
/* strstr() will return NULL if ordering is wrong. */
if (*cp == 'f') {
argv0 = strstr(header, " argv[]={ \"");
if (argv0) {
argv0 += 10;
len += tomoyo_truncate(argv0) + 14;
}
realpath = strstr(header, " exec={ realpath=\"");
if (realpath) {
realpath += 8;
len += tomoyo_truncate(realpath) + 6;
}
symlink = strstr(header, " symlink.target=\"");
if (symlink)
len += tomoyo_truncate(symlink + 1) + 1;
}
buffer = kmalloc(len, GFP_NOFS);
if (!buffer)
return;
snprintf(buffer, len - 1, "%s", cp);
if (realpath)
tomoyo_addprintf(buffer, len, " exec.%s", realpath);
if (argv0)
tomoyo_addprintf(buffer, len, " exec.argv[0]=%s", argv0);
if (symlink)
tomoyo_addprintf(buffer, len, "%s", symlink);
tomoyo_normalize_line(buffer);
if (!tomoyo_write_domain2(domain->ns, &domain->acl_info_list, buffer,
false))
tomoyo_update_stat(TOMOYO_STAT_POLICY_UPDATES);
kfree(buffer);
}
/**
* tomoyo_supervisor - Ask for the supervisor's decision.
*
* @r: Pointer to "struct tomoyo_request_info".
* @fmt: The printf()'s format string, followed by parameters.
*
* Returns 0 if the supervisor decided to permit the access request which
* violated the policy in enforcing mode, TOMOYO_RETRY_REQUEST if the
* supervisor decided to retry the access request which violated the policy in
* enforcing mode, 0 if it is not in enforcing mode, -EPERM otherwise.
*/
int tomoyo_supervisor(struct tomoyo_request_info *r, const char *fmt, ...)
{
va_list args;
int error;
int len;
static unsigned int tomoyo_serial;
struct tomoyo_query entry = { };
bool quota_exceeded = false;
va_start(args, fmt);
len = vsnprintf((char *) &len, 1, fmt, args) + 1;
va_end(args);
/* Write /sys/kernel/security/tomoyo/audit. */
va_start(args, fmt);
tomoyo_write_log2(r, len, fmt, args);
va_end(args);
/* Nothing more to do if granted. */
if (r->granted)
return 0;
if (r->mode)
tomoyo_update_stat(r->mode);
switch (r->mode) {
case TOMOYO_CONFIG_ENFORCING:
error = -EPERM;
if (atomic_read(&tomoyo_query_observers))
break;
goto out;
case TOMOYO_CONFIG_LEARNING:
error = 0;
/* Check max_learning_entry parameter. */
if (tomoyo_domain_quota_is_ok(r))
break;
/* fall through */
default:
return 0;
}
/* Get message. */
va_start(args, fmt);
entry.query = tomoyo_init_log(r, len, fmt, args);
va_end(args);
if (!entry.query)
goto out;
entry.query_len = strlen(entry.query) + 1;
if (!error) {
tomoyo_add_entry(r->domain, entry.query);
goto out;
}
len = tomoyo_round2(entry.query_len);
entry.domain = r->domain;
spin_lock(&tomoyo_query_list_lock);
if (tomoyo_memory_quota[TOMOYO_MEMORY_QUERY] &&
tomoyo_memory_used[TOMOYO_MEMORY_QUERY] + len
>= tomoyo_memory_quota[TOMOYO_MEMORY_QUERY]) {
quota_exceeded = true;
} else {
entry.serial = tomoyo_serial++;
entry.retry = r->retry;
tomoyo_memory_used[TOMOYO_MEMORY_QUERY] += len;
list_add_tail(&entry.list, &tomoyo_query_list);
}
spin_unlock(&tomoyo_query_list_lock);
if (quota_exceeded)
goto out;
/* Give 10 seconds for supervisor's opinion. */
while (entry.timer < 10) {
wake_up_all(&tomoyo_query_wait);
if (wait_event_interruptible_timeout
(tomoyo_answer_wait, entry.answer ||
!atomic_read(&tomoyo_query_observers), HZ))
break;
else
entry.timer++;
}
spin_lock(&tomoyo_query_list_lock);
list_del(&entry.list);
tomoyo_memory_used[TOMOYO_MEMORY_QUERY] -= len;
spin_unlock(&tomoyo_query_list_lock);
switch (entry.answer) {
case 3: /* Asked to retry by administrator. */
error = TOMOYO_RETRY_REQUEST;
r->retry++;
break;
case 1:
/* Granted by administrator. */
error = 0;
break;
default:
/* Timed out or rejected by administrator. */
break;
}
out:
kfree(entry.query);
return error;
}
/**
* tomoyo_find_domain_by_qid - Get domain by query id.
*
* @serial: Query ID assigned by tomoyo_supervisor().
*
* Returns pointer to "struct tomoyo_domain_info" if found, NULL otherwise.
*/
static struct tomoyo_domain_info *tomoyo_find_domain_by_qid
(unsigned int serial)
{
struct tomoyo_query *ptr;
struct tomoyo_domain_info *domain = NULL;
spin_lock(&tomoyo_query_list_lock);
list_for_each_entry(ptr, &tomoyo_query_list, list) {
if (ptr->serial != serial)
continue;
domain = ptr->domain;
break;
}
spin_unlock(&tomoyo_query_list_lock);
return domain;
}
/**
* tomoyo_poll_query - poll() for /sys/kernel/security/tomoyo/query.
*
* @file: Pointer to "struct file".
* @wait: Pointer to "poll_table".
*
* Returns POLLIN | POLLRDNORM when ready to read, 0 otherwise.
*
* Waits for access requests which violated policy in enforcing mode.
*/
static unsigned int tomoyo_poll_query(struct file *file, poll_table *wait)
{
if (!list_empty(&tomoyo_query_list))
return POLLIN | POLLRDNORM;
poll_wait(file, &tomoyo_query_wait, wait);
if (!list_empty(&tomoyo_query_list))
return POLLIN | POLLRDNORM;
return 0;
}
/**
* tomoyo_read_query - Read access requests which violated policy in enforcing mode.
*
* @head: Pointer to "struct tomoyo_io_buffer".
*/
static void tomoyo_read_query(struct tomoyo_io_buffer *head)
{
struct list_head *tmp;
unsigned int pos = 0;
size_t len = 0;
char *buf;
if (head->r.w_pos)
return;
if (head->read_buf) {
kfree(head->read_buf);
head->read_buf = NULL;
}
spin_lock(&tomoyo_query_list_lock);
list_for_each(tmp, &tomoyo_query_list) {
struct tomoyo_query *ptr = list_entry(tmp, typeof(*ptr), list);
if (pos++ != head->r.query_index)
continue;
len = ptr->query_len;
break;
}
spin_unlock(&tomoyo_query_list_lock);
if (!len) {
head->r.query_index = 0;
return;
}
buf = kzalloc(len + 32, GFP_NOFS);
if (!buf)
return;
pos = 0;
spin_lock(&tomoyo_query_list_lock);
list_for_each(tmp, &tomoyo_query_list) {
struct tomoyo_query *ptr = list_entry(tmp, typeof(*ptr), list);
if (pos++ != head->r.query_index)
continue;
/*
* Some query can be skipped because tomoyo_query_list
* can change, but I don't care.
*/
if (len == ptr->query_len)
snprintf(buf, len + 31, "Q%u-%hu\n%s", ptr->serial,
ptr->retry, ptr->query);
break;
}
spin_unlock(&tomoyo_query_list_lock);
if (buf[0]) {
head->read_buf = buf;
head->r.w[head->r.w_pos++] = buf;
head->r.query_index++;
} else {
kfree(buf);
}
}
/**
* tomoyo_write_answer - Write the supervisor's decision.
*
* @head: Pointer to "struct tomoyo_io_buffer".
*
* Returns 0 on success, -EINVAL otherwise.
*/
static int tomoyo_write_answer(struct tomoyo_io_buffer *head)
{
char *data = head->write_buf;
struct list_head *tmp;
unsigned int serial;
unsigned int answer;
spin_lock(&tomoyo_query_list_lock);
list_for_each(tmp, &tomoyo_query_list) {
struct tomoyo_query *ptr = list_entry(tmp, typeof(*ptr), list);
ptr->timer = 0;
}
spin_unlock(&tomoyo_query_list_lock);
if (sscanf(data, "A%u=%u", &serial, &answer) != 2)
return -EINVAL;
spin_lock(&tomoyo_query_list_lock);
list_for_each(tmp, &tomoyo_query_list) {
struct tomoyo_query *ptr = list_entry(tmp, typeof(*ptr), list);
if (ptr->serial != serial)
continue;
ptr->answer = answer;
/* Remove from tomoyo_query_list. */
if (ptr->answer)
list_del_init(&ptr->list);
break;
}
spin_unlock(&tomoyo_query_list_lock);
return 0;
}
/**
* tomoyo_read_version: Get version.
*
* @head: Pointer to "struct tomoyo_io_buffer".
*
* Returns version information.
*/
static void tomoyo_read_version(struct tomoyo_io_buffer *head)
{
if (!head->r.eof) {
tomoyo_io_printf(head, "2.5.0");
head->r.eof = true;
}
}
/* String table for /sys/kernel/security/tomoyo/stat interface. */
static const char * const tomoyo_policy_headers[TOMOYO_MAX_POLICY_STAT] = {
[TOMOYO_STAT_POLICY_UPDATES] = "update:",
[TOMOYO_STAT_POLICY_LEARNING] = "violation in learning mode:",
[TOMOYO_STAT_POLICY_PERMISSIVE] = "violation in permissive mode:",
[TOMOYO_STAT_POLICY_ENFORCING] = "violation in enforcing mode:",
};
/* String table for /sys/kernel/security/tomoyo/stat interface. */
static const char * const tomoyo_memory_headers[TOMOYO_MAX_MEMORY_STAT] = {
[TOMOYO_MEMORY_POLICY] = "policy:",
[TOMOYO_MEMORY_AUDIT] = "audit log:",
[TOMOYO_MEMORY_QUERY] = "query message:",
};
/* Timestamp counter for last updated. */
static unsigned int tomoyo_stat_updated[TOMOYO_MAX_POLICY_STAT];
/* Counter for number of updates. */
static unsigned int tomoyo_stat_modified[TOMOYO_MAX_POLICY_STAT];
/**
* tomoyo_update_stat - Update statistic counters.
*
* @index: Index for policy type.
*
* Returns nothing.
*/
void tomoyo_update_stat(const u8 index)
{
struct timeval tv;
do_gettimeofday(&tv);
/*
* I don't use atomic operations because race condition is not fatal.
*/
tomoyo_stat_updated[index]++;
tomoyo_stat_modified[index] = tv.tv_sec;
}
/**
* tomoyo_read_stat - Read statistic data.
*
* @head: Pointer to "struct tomoyo_io_buffer".
*
* Returns nothing.
*/
static void tomoyo_read_stat(struct tomoyo_io_buffer *head)
{
u8 i;
unsigned int total = 0;
if (head->r.eof)
return;
for (i = 0; i < TOMOYO_MAX_POLICY_STAT; i++) {
tomoyo_io_printf(head, "Policy %-30s %10u",
tomoyo_policy_headers[i],
tomoyo_stat_updated[i]);
if (tomoyo_stat_modified[i]) {
struct tomoyo_time stamp;
tomoyo_convert_time(tomoyo_stat_modified[i], &stamp);
tomoyo_io_printf(head, " (Last: %04u/%02u/%02u "
"%02u:%02u:%02u)",
stamp.year, stamp.month, stamp.day,
stamp.hour, stamp.min, stamp.sec);
}
tomoyo_set_lf(head);
}
for (i = 0; i < TOMOYO_MAX_MEMORY_STAT; i++) {
unsigned int used = tomoyo_memory_used[i];
total += used;
tomoyo_io_printf(head, "Memory used by %-22s %10u",
tomoyo_memory_headers[i], used);
used = tomoyo_memory_quota[i];
if (used)
tomoyo_io_printf(head, " (Quota: %10u)", used);
tomoyo_set_lf(head);
}
tomoyo_io_printf(head, "Total memory used: %10u\n",
total);
head->r.eof = true;
}
/**
* tomoyo_write_stat - Set memory quota.
*
* @head: Pointer to "struct tomoyo_io_buffer".
*
* Returns 0.
*/
static int tomoyo_write_stat(struct tomoyo_io_buffer *head)
{
char *data = head->write_buf;
u8 i;
if (tomoyo_str_starts(&data, "Memory used by "))
for (i = 0; i < TOMOYO_MAX_MEMORY_STAT; i++)
if (tomoyo_str_starts(&data, tomoyo_memory_headers[i]))
sscanf(data, "%u", &tomoyo_memory_quota[i]);
return 0;
}
/**
* tomoyo_open_control - open() for /sys/kernel/security/tomoyo/ interface.
*
* @type: Type of interface.
* @file: Pointer to "struct file".
*
* Returns 0 on success, negative value otherwise.
*/
int tomoyo_open_control(const u8 type, struct file *file)
{
struct tomoyo_io_buffer *head = kzalloc(sizeof(*head), GFP_NOFS);
if (!head)
return -ENOMEM;
mutex_init(&head->io_sem);
head->type = type;
switch (type) {
case TOMOYO_DOMAINPOLICY:
/* /sys/kernel/security/tomoyo/domain_policy */
head->write = tomoyo_write_domain;
head->read = tomoyo_read_domain;
break;
case TOMOYO_EXCEPTIONPOLICY:
/* /sys/kernel/security/tomoyo/exception_policy */
head->write = tomoyo_write_exception;
head->read = tomoyo_read_exception;
break;
case TOMOYO_AUDIT:
/* /sys/kernel/security/tomoyo/audit */
head->poll = tomoyo_poll_log;
head->read = tomoyo_read_log;
break;
case TOMOYO_PROCESS_STATUS:
/* /sys/kernel/security/tomoyo/.process_status */
head->write = tomoyo_write_pid;
head->read = tomoyo_read_pid;
break;
case TOMOYO_VERSION:
/* /sys/kernel/security/tomoyo/version */
head->read = tomoyo_read_version;
head->readbuf_size = 128;
break;
case TOMOYO_STAT:
/* /sys/kernel/security/tomoyo/stat */
head->write = tomoyo_write_stat;
head->read = tomoyo_read_stat;
head->readbuf_size = 1024;
break;
case TOMOYO_PROFILE:
/* /sys/kernel/security/tomoyo/profile */
head->write = tomoyo_write_profile;
head->read = tomoyo_read_profile;
break;
case TOMOYO_QUERY: /* /sys/kernel/security/tomoyo/query */
head->poll = tomoyo_poll_query;
head->write = tomoyo_write_answer;
head->read = tomoyo_read_query;
break;
case TOMOYO_MANAGER:
/* /sys/kernel/security/tomoyo/manager */
head->write = tomoyo_write_manager;
head->read = tomoyo_read_manager;
break;
}
if (!(file->f_mode & FMODE_READ)) {
/*
* No need to allocate read_buf since it is not opened
* for reading.
*/
head->read = NULL;
head->poll = NULL;
} else if (!head->poll) {
/* Don't allocate read_buf for poll() access. */
if (!head->readbuf_size)
head->readbuf_size = 4096 * 2;
head->read_buf = kzalloc(head->readbuf_size, GFP_NOFS);
if (!head->read_buf) {
kfree(head);
return -ENOMEM;
}
}
if (!(file->f_mode & FMODE_WRITE)) {
/*
* No need to allocate write_buf since it is not opened
* for writing.
*/
head->write = NULL;
} else if (head->write) {
head->writebuf_size = 4096 * 2;
head->write_buf = kzalloc(head->writebuf_size, GFP_NOFS);
if (!head->write_buf) {
kfree(head->read_buf);
kfree(head);
return -ENOMEM;
}
}
/*
* If the file is /sys/kernel/security/tomoyo/query , increment the
* observer counter.
* The obserber counter is used by tomoyo_supervisor() to see if
* there is some process monitoring /sys/kernel/security/tomoyo/query.
*/
if (type == TOMOYO_QUERY)
atomic_inc(&tomoyo_query_observers);
file->private_data = head;
tomoyo_notify_gc(head, true);
return 0;
}
/**
* tomoyo_poll_control - poll() for /sys/kernel/security/tomoyo/ interface.
*
* @file: Pointer to "struct file".
* @wait: Pointer to "poll_table". Maybe NULL.
*
* Returns POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM if ready to read/write,
* POLLOUT | POLLWRNORM otherwise.
*/
unsigned int tomoyo_poll_control(struct file *file, poll_table *wait)
{
struct tomoyo_io_buffer *head = file->private_data;
if (head->poll)
return head->poll(file, wait) | POLLOUT | POLLWRNORM;
return POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM;
}
/**
* tomoyo_set_namespace_cursor - Set namespace to read.
*
* @head: Pointer to "struct tomoyo_io_buffer".
*
* Returns nothing.
*/
static inline void tomoyo_set_namespace_cursor(struct tomoyo_io_buffer *head)
{
struct list_head *ns;
if (head->type != TOMOYO_EXCEPTIONPOLICY &&
head->type != TOMOYO_PROFILE)
return;
/*
* If this is the first read, or reading previous namespace finished
* and has more namespaces to read, update the namespace cursor.
*/
ns = head->r.ns;
if (!ns || (head->r.eof && ns->next != &tomoyo_namespace_list)) {
/* Clearing is OK because tomoyo_flush() returned true. */
memset(&head->r, 0, sizeof(head->r));
head->r.ns = ns ? ns->next : tomoyo_namespace_list.next;
}
}
/**
* tomoyo_has_more_namespace - Check for unread namespaces.
*
* @head: Pointer to "struct tomoyo_io_buffer".
*
* Returns true if we have more entries to print, false otherwise.
*/
static inline bool tomoyo_has_more_namespace(struct tomoyo_io_buffer *head)
{
return (head->type == TOMOYO_EXCEPTIONPOLICY ||
head->type == TOMOYO_PROFILE) && head->r.eof &&
head->r.ns->next != &tomoyo_namespace_list;
}
/**
* tomoyo_read_control - read() for /sys/kernel/security/tomoyo/ interface.
*
* @head: Pointer to "struct tomoyo_io_buffer".
* @buffer: Poiner to buffer to write to.
* @buffer_len: Size of @buffer.
*
* Returns bytes read on success, negative value otherwise.
*/
ssize_t tomoyo_read_control(struct tomoyo_io_buffer *head, char __user *buffer,
const int buffer_len)
{
int len;
int idx;
if (!head->read)
return -ENOSYS;
if (mutex_lock_interruptible(&head->io_sem))
return -EINTR;
head->read_user_buf = buffer;
head->read_user_buf_avail = buffer_len;
idx = tomoyo_read_lock();
if (tomoyo_flush(head))
/* Call the policy handler. */
do {
tomoyo_set_namespace_cursor(head);
head->read(head);
} while (tomoyo_flush(head) &&
tomoyo_has_more_namespace(head));
tomoyo_read_unlock(idx);
len = head->read_user_buf - buffer;
mutex_unlock(&head->io_sem);
return len;
}
/**
* tomoyo_parse_policy - Parse a policy line.
*
* @head: Poiter to "struct tomoyo_io_buffer".
* @line: Line to parse.
*
* Returns 0 on success, negative value otherwise.
*
* Caller holds tomoyo_read_lock().
*/
static int tomoyo_parse_policy(struct tomoyo_io_buffer *head, char *line)
{
/* Delete request? */
head->w.is_delete = !strncmp(line, "delete ", 7);
if (head->w.is_delete)
memmove(line, line + 7, strlen(line + 7) + 1);
/* Selecting namespace to update. */
if (head->type == TOMOYO_EXCEPTIONPOLICY ||
head->type == TOMOYO_PROFILE) {
if (*line == '<') {
char *cp = strchr(line, ' ');
if (cp) {
*cp++ = '\0';
head->w.ns = tomoyo_assign_namespace(line);
memmove(line, cp, strlen(cp) + 1);
} else
head->w.ns = NULL;
} else
head->w.ns = &tomoyo_kernel_namespace;
/* Don't allow updating if namespace is invalid. */
if (!head->w.ns)
return -ENOENT;
}
/* Do the update. */
return head->write(head);
}
/**
* tomoyo_write_control - write() for /sys/kernel/security/tomoyo/ interface.
*
* @head: Pointer to "struct tomoyo_io_buffer".
* @buffer: Pointer to buffer to read from.
* @buffer_len: Size of @buffer.
*
* Returns @buffer_len on success, negative value otherwise.
*/
ssize_t tomoyo_write_control(struct tomoyo_io_buffer *head,
const char __user *buffer, const int buffer_len)
{
int error = buffer_len;
size_t avail_len = buffer_len;
char *cp0 = head->write_buf;
int idx;
if (!head->write)
return -ENOSYS;
if (!access_ok(VERIFY_READ, buffer, buffer_len))
return -EFAULT;
if (mutex_lock_interruptible(&head->io_sem))
return -EINTR;
head->read_user_buf_avail = 0;
idx = tomoyo_read_lock();
/* Read a line and dispatch it to the policy handler. */
while (avail_len > 0) {
char c;
if (head->w.avail >= head->writebuf_size - 1) {
const int len = head->writebuf_size * 2;
char *cp = kzalloc(len, GFP_NOFS);
if (!cp) {
error = -ENOMEM;
break;
}
memmove(cp, cp0, head->w.avail);
kfree(cp0);
head->write_buf = cp;
cp0 = cp;
head->writebuf_size = len;
}
if (get_user(c, buffer)) {
error = -EFAULT;
break;
}
buffer++;
avail_len--;
cp0[head->w.avail++] = c;
if (c != '\n')
continue;
cp0[head->w.avail - 1] = '\0';
head->w.avail = 0;
tomoyo_normalize_line(cp0);
if (!strcmp(cp0, "reset")) {
head->w.ns = &tomoyo_kernel_namespace;
head->w.domain = NULL;
memset(&head->r, 0, sizeof(head->r));
continue;
}
/* Don't allow updating policies by non manager programs. */
switch (head->type) {
case TOMOYO_PROCESS_STATUS:
/* This does not write anything. */
break;
case TOMOYO_DOMAINPOLICY:
if (tomoyo_select_domain(head, cp0))
continue;
/* fall through */
case TOMOYO_EXCEPTIONPOLICY:
if (!strcmp(cp0, "select transition_only")) {
head->r.print_transition_related_only = true;
continue;
}
/* fall through */
default:
if (!tomoyo_manager()) {
error = -EPERM;
goto out;
}
}
switch (tomoyo_parse_policy(head, cp0)) {
case -EPERM:
error = -EPERM;
goto out;
case 0:
switch (head->type) {
case TOMOYO_DOMAINPOLICY:
case TOMOYO_EXCEPTIONPOLICY:
case TOMOYO_STAT:
case TOMOYO_PROFILE:
case TOMOYO_MANAGER:
tomoyo_update_stat(TOMOYO_STAT_POLICY_UPDATES);
break;
default:
break;
}
break;
}
}
out:
tomoyo_read_unlock(idx);
mutex_unlock(&head->io_sem);
return error;
}
/**
* tomoyo_close_control - close() for /sys/kernel/security/tomoyo/ interface.
*
* @head: Pointer to "struct tomoyo_io_buffer".
*
* Returns 0.
*/
int tomoyo_close_control(struct tomoyo_io_buffer *head)
{
/*
* If the file is /sys/kernel/security/tomoyo/query , decrement the
* observer counter.
*/
if (head->type == TOMOYO_QUERY &&
atomic_dec_and_test(&tomoyo_query_observers))
wake_up_all(&tomoyo_answer_wait);
tomoyo_notify_gc(head, false);
return 0;
}
/**
* tomoyo_check_profile - Check all profiles currently assigned to domains are defined.
*/
void tomoyo_check_profile(void)
{
struct tomoyo_domain_info *domain;
const int idx = tomoyo_read_lock();
tomoyo_policy_loaded = true;
printk(KERN_INFO "TOMOYO: 2.5.0\n");
list_for_each_entry_rcu(domain, &tomoyo_domain_list, list) {
const u8 profile = domain->profile;
const struct tomoyo_policy_namespace *ns = domain->ns;
if (ns->profile_version != 20110903)
printk(KERN_ERR
"Profile version %u is not supported.\n",
ns->profile_version);
else if (!ns->profile_ptr[profile])
printk(KERN_ERR
"Profile %u (used by '%s') is not defined.\n",
profile, domain->domainname->name);
else
continue;
printk(KERN_ERR
"Userland tools for TOMOYO 2.5 must be installed and "
"policy must be initialized.\n");
printk(KERN_ERR "Please see http://tomoyo.sourceforge.jp/2.5/ "
"for more information.\n");
panic("STOP!");
}
tomoyo_read_unlock(idx);
printk(KERN_INFO "Mandatory Access Control activated.\n");
}
/**
* tomoyo_load_builtin_policy - Load built-in policy.
*
* Returns nothing.
*/
void __init tomoyo_load_builtin_policy(void)
{
/*
* This include file is manually created and contains built-in policy
* named "tomoyo_builtin_profile", "tomoyo_builtin_exception_policy",
* "tomoyo_builtin_domain_policy", "tomoyo_builtin_manager",
* "tomoyo_builtin_stat" in the form of "static char [] __initdata".
*/
#include "builtin-policy.h"
u8 i;
const int idx = tomoyo_read_lock();
for (i = 0; i < 5; i++) {
struct tomoyo_io_buffer head = { };
char *start = "";
switch (i) {
case 0:
start = tomoyo_builtin_profile;
head.type = TOMOYO_PROFILE;
head.write = tomoyo_write_profile;
break;
case 1:
start = tomoyo_builtin_exception_policy;
head.type = TOMOYO_EXCEPTIONPOLICY;
head.write = tomoyo_write_exception;
break;
case 2:
start = tomoyo_builtin_domain_policy;
head.type = TOMOYO_DOMAINPOLICY;
head.write = tomoyo_write_domain;
break;
case 3:
start = tomoyo_builtin_manager;
head.type = TOMOYO_MANAGER;
head.write = tomoyo_write_manager;
break;
case 4:
start = tomoyo_builtin_stat;
head.type = TOMOYO_STAT;
head.write = tomoyo_write_stat;
break;
}
while (1) {
char *end = strchr(start, '\n');
if (!end)
break;
*end = '\0';
tomoyo_normalize_line(start);
head.write_buf = start;
tomoyo_parse_policy(&head, start);
start = end + 1;
}
}
tomoyo_read_unlock(idx);
#ifdef CONFIG_SECURITY_TOMOYO_OMIT_USERSPACE_LOADER
tomoyo_check_profile();
#endif
}
| gpl-2.0 |
AOSParadox/android_kernel_oneplus_msm8974 | drivers/net/ethernet/freescale/gianfar_ethtool.c | 4814 | 47049 | /*
* drivers/net/ethernet/freescale/gianfar_ethtool.c
*
* Gianfar Ethernet Driver
* Ethtool support for Gianfar Enet
* Based on e1000 ethtool support
*
* Author: Andy Fleming
* Maintainer: Kumar Gala
* Modifier: Sandeep Gopalpet <sandeep.kumar@freescale.com>
*
* Copyright 2003-2006, 2008-2009, 2011 Freescale Semiconductor, Inc.
*
* This software may be used and distributed according to
* the terms of the GNU Public License, Version 2, incorporated herein
* by reference.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/spinlock.h>
#include <linux/mm.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/uaccess.h>
#include <linux/module.h>
#include <linux/crc32.h>
#include <asm/types.h>
#include <linux/ethtool.h>
#include <linux/mii.h>
#include <linux/phy.h>
#include <linux/sort.h>
#include <linux/if_vlan.h>
#include "gianfar.h"
extern void gfar_start(struct net_device *dev);
extern int gfar_clean_rx_ring(struct gfar_priv_rx_q *rx_queue, int rx_work_limit);
#define GFAR_MAX_COAL_USECS 0xffff
#define GFAR_MAX_COAL_FRAMES 0xff
static void gfar_fill_stats(struct net_device *dev, struct ethtool_stats *dummy,
u64 * buf);
static void gfar_gstrings(struct net_device *dev, u32 stringset, u8 * buf);
static int gfar_gcoalesce(struct net_device *dev, struct ethtool_coalesce *cvals);
static int gfar_scoalesce(struct net_device *dev, struct ethtool_coalesce *cvals);
static void gfar_gringparam(struct net_device *dev, struct ethtool_ringparam *rvals);
static int gfar_sringparam(struct net_device *dev, struct ethtool_ringparam *rvals);
static void gfar_gdrvinfo(struct net_device *dev, struct ethtool_drvinfo *drvinfo);
static const char stat_gstrings[][ETH_GSTRING_LEN] = {
"rx-dropped-by-kernel",
"rx-large-frame-errors",
"rx-short-frame-errors",
"rx-non-octet-errors",
"rx-crc-errors",
"rx-overrun-errors",
"rx-busy-errors",
"rx-babbling-errors",
"rx-truncated-frames",
"ethernet-bus-error",
"tx-babbling-errors",
"tx-underrun-errors",
"rx-skb-missing-errors",
"tx-timeout-errors",
"tx-rx-64-frames",
"tx-rx-65-127-frames",
"tx-rx-128-255-frames",
"tx-rx-256-511-frames",
"tx-rx-512-1023-frames",
"tx-rx-1024-1518-frames",
"tx-rx-1519-1522-good-vlan",
"rx-bytes",
"rx-packets",
"rx-fcs-errors",
"receive-multicast-packet",
"receive-broadcast-packet",
"rx-control-frame-packets",
"rx-pause-frame-packets",
"rx-unknown-op-code",
"rx-alignment-error",
"rx-frame-length-error",
"rx-code-error",
"rx-carrier-sense-error",
"rx-undersize-packets",
"rx-oversize-packets",
"rx-fragmented-frames",
"rx-jabber-frames",
"rx-dropped-frames",
"tx-byte-counter",
"tx-packets",
"tx-multicast-packets",
"tx-broadcast-packets",
"tx-pause-control-frames",
"tx-deferral-packets",
"tx-excessive-deferral-packets",
"tx-single-collision-packets",
"tx-multiple-collision-packets",
"tx-late-collision-packets",
"tx-excessive-collision-packets",
"tx-total-collision",
"reserved",
"tx-dropped-frames",
"tx-jabber-frames",
"tx-fcs-errors",
"tx-control-frames",
"tx-oversize-frames",
"tx-undersize-frames",
"tx-fragmented-frames",
};
/* Fill in a buffer with the strings which correspond to the
* stats */
static void gfar_gstrings(struct net_device *dev, u32 stringset, u8 * buf)
{
struct gfar_private *priv = netdev_priv(dev);
if (priv->device_flags & FSL_GIANFAR_DEV_HAS_RMON)
memcpy(buf, stat_gstrings, GFAR_STATS_LEN * ETH_GSTRING_LEN);
else
memcpy(buf, stat_gstrings,
GFAR_EXTRA_STATS_LEN * ETH_GSTRING_LEN);
}
/* Fill in an array of 64-bit statistics from various sources.
* This array will be appended to the end of the ethtool_stats
* structure, and returned to user space
*/
static void gfar_fill_stats(struct net_device *dev, struct ethtool_stats *dummy, u64 * buf)
{
int i;
struct gfar_private *priv = netdev_priv(dev);
struct gfar __iomem *regs = priv->gfargrp[0].regs;
u64 *extra = (u64 *) & priv->extra_stats;
if (priv->device_flags & FSL_GIANFAR_DEV_HAS_RMON) {
u32 __iomem *rmon = (u32 __iomem *) ®s->rmon;
struct gfar_stats *stats = (struct gfar_stats *) buf;
for (i = 0; i < GFAR_RMON_LEN; i++)
stats->rmon[i] = (u64) gfar_read(&rmon[i]);
for (i = 0; i < GFAR_EXTRA_STATS_LEN; i++)
stats->extra[i] = extra[i];
} else
for (i = 0; i < GFAR_EXTRA_STATS_LEN; i++)
buf[i] = extra[i];
}
static int gfar_sset_count(struct net_device *dev, int sset)
{
struct gfar_private *priv = netdev_priv(dev);
switch (sset) {
case ETH_SS_STATS:
if (priv->device_flags & FSL_GIANFAR_DEV_HAS_RMON)
return GFAR_STATS_LEN;
else
return GFAR_EXTRA_STATS_LEN;
default:
return -EOPNOTSUPP;
}
}
/* Fills in the drvinfo structure with some basic info */
static void gfar_gdrvinfo(struct net_device *dev, struct
ethtool_drvinfo *drvinfo)
{
strncpy(drvinfo->driver, DRV_NAME, GFAR_INFOSTR_LEN);
strncpy(drvinfo->version, gfar_driver_version, GFAR_INFOSTR_LEN);
strncpy(drvinfo->fw_version, "N/A", GFAR_INFOSTR_LEN);
strncpy(drvinfo->bus_info, "N/A", GFAR_INFOSTR_LEN);
drvinfo->regdump_len = 0;
drvinfo->eedump_len = 0;
}
static int gfar_ssettings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct gfar_private *priv = netdev_priv(dev);
struct phy_device *phydev = priv->phydev;
if (NULL == phydev)
return -ENODEV;
return phy_ethtool_sset(phydev, cmd);
}
/* Return the current settings in the ethtool_cmd structure */
static int gfar_gsettings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct gfar_private *priv = netdev_priv(dev);
struct phy_device *phydev = priv->phydev;
struct gfar_priv_rx_q *rx_queue = NULL;
struct gfar_priv_tx_q *tx_queue = NULL;
if (NULL == phydev)
return -ENODEV;
tx_queue = priv->tx_queue[0];
rx_queue = priv->rx_queue[0];
/* etsec-1.7 and older versions have only one txic
* and rxic regs although they support multiple queues */
cmd->maxtxpkt = get_icft_value(tx_queue->txic);
cmd->maxrxpkt = get_icft_value(rx_queue->rxic);
return phy_ethtool_gset(phydev, cmd);
}
/* Return the length of the register structure */
static int gfar_reglen(struct net_device *dev)
{
return sizeof (struct gfar);
}
/* Return a dump of the GFAR register space */
static void gfar_get_regs(struct net_device *dev, struct ethtool_regs *regs, void *regbuf)
{
int i;
struct gfar_private *priv = netdev_priv(dev);
u32 __iomem *theregs = (u32 __iomem *) priv->gfargrp[0].regs;
u32 *buf = (u32 *) regbuf;
for (i = 0; i < sizeof (struct gfar) / sizeof (u32); i++)
buf[i] = gfar_read(&theregs[i]);
}
/* Convert microseconds to ethernet clock ticks, which changes
* depending on what speed the controller is running at */
static unsigned int gfar_usecs2ticks(struct gfar_private *priv, unsigned int usecs)
{
unsigned int count;
/* The timer is different, depending on the interface speed */
switch (priv->phydev->speed) {
case SPEED_1000:
count = GFAR_GBIT_TIME;
break;
case SPEED_100:
count = GFAR_100_TIME;
break;
case SPEED_10:
default:
count = GFAR_10_TIME;
break;
}
/* Make sure we return a number greater than 0
* if usecs > 0 */
return (usecs * 1000 + count - 1) / count;
}
/* Convert ethernet clock ticks to microseconds */
static unsigned int gfar_ticks2usecs(struct gfar_private *priv, unsigned int ticks)
{
unsigned int count;
/* The timer is different, depending on the interface speed */
switch (priv->phydev->speed) {
case SPEED_1000:
count = GFAR_GBIT_TIME;
break;
case SPEED_100:
count = GFAR_100_TIME;
break;
case SPEED_10:
default:
count = GFAR_10_TIME;
break;
}
/* Make sure we return a number greater than 0 */
/* if ticks is > 0 */
return (ticks * count) / 1000;
}
/* Get the coalescing parameters, and put them in the cvals
* structure. */
static int gfar_gcoalesce(struct net_device *dev, struct ethtool_coalesce *cvals)
{
struct gfar_private *priv = netdev_priv(dev);
struct gfar_priv_rx_q *rx_queue = NULL;
struct gfar_priv_tx_q *tx_queue = NULL;
unsigned long rxtime;
unsigned long rxcount;
unsigned long txtime;
unsigned long txcount;
if (!(priv->device_flags & FSL_GIANFAR_DEV_HAS_COALESCE))
return -EOPNOTSUPP;
if (NULL == priv->phydev)
return -ENODEV;
rx_queue = priv->rx_queue[0];
tx_queue = priv->tx_queue[0];
rxtime = get_ictt_value(rx_queue->rxic);
rxcount = get_icft_value(rx_queue->rxic);
txtime = get_ictt_value(tx_queue->txic);
txcount = get_icft_value(tx_queue->txic);
cvals->rx_coalesce_usecs = gfar_ticks2usecs(priv, rxtime);
cvals->rx_max_coalesced_frames = rxcount;
cvals->tx_coalesce_usecs = gfar_ticks2usecs(priv, txtime);
cvals->tx_max_coalesced_frames = txcount;
cvals->use_adaptive_rx_coalesce = 0;
cvals->use_adaptive_tx_coalesce = 0;
cvals->pkt_rate_low = 0;
cvals->rx_coalesce_usecs_low = 0;
cvals->rx_max_coalesced_frames_low = 0;
cvals->tx_coalesce_usecs_low = 0;
cvals->tx_max_coalesced_frames_low = 0;
/* When the packet rate is below pkt_rate_high but above
* pkt_rate_low (both measured in packets per second) the
* normal {rx,tx}_* coalescing parameters are used.
*/
/* When the packet rate is (measured in packets per second)
* is above pkt_rate_high, the {rx,tx}_*_high parameters are
* used.
*/
cvals->pkt_rate_high = 0;
cvals->rx_coalesce_usecs_high = 0;
cvals->rx_max_coalesced_frames_high = 0;
cvals->tx_coalesce_usecs_high = 0;
cvals->tx_max_coalesced_frames_high = 0;
/* How often to do adaptive coalescing packet rate sampling,
* measured in seconds. Must not be zero.
*/
cvals->rate_sample_interval = 0;
return 0;
}
/* Change the coalescing values.
* Both cvals->*_usecs and cvals->*_frames have to be > 0
* in order for coalescing to be active
*/
static int gfar_scoalesce(struct net_device *dev, struct ethtool_coalesce *cvals)
{
struct gfar_private *priv = netdev_priv(dev);
int i = 0;
if (!(priv->device_flags & FSL_GIANFAR_DEV_HAS_COALESCE))
return -EOPNOTSUPP;
/* Set up rx coalescing */
/* As of now, we will enable/disable coalescing for all
* queues together in case of eTSEC2, this will be modified
* along with the ethtool interface */
if ((cvals->rx_coalesce_usecs == 0) ||
(cvals->rx_max_coalesced_frames == 0)) {
for (i = 0; i < priv->num_rx_queues; i++)
priv->rx_queue[i]->rxcoalescing = 0;
} else {
for (i = 0; i < priv->num_rx_queues; i++)
priv->rx_queue[i]->rxcoalescing = 1;
}
if (NULL == priv->phydev)
return -ENODEV;
/* Check the bounds of the values */
if (cvals->rx_coalesce_usecs > GFAR_MAX_COAL_USECS) {
pr_info("Coalescing is limited to %d microseconds\n",
GFAR_MAX_COAL_USECS);
return -EINVAL;
}
if (cvals->rx_max_coalesced_frames > GFAR_MAX_COAL_FRAMES) {
pr_info("Coalescing is limited to %d frames\n",
GFAR_MAX_COAL_FRAMES);
return -EINVAL;
}
for (i = 0; i < priv->num_rx_queues; i++) {
priv->rx_queue[i]->rxic = mk_ic_value(
cvals->rx_max_coalesced_frames,
gfar_usecs2ticks(priv, cvals->rx_coalesce_usecs));
}
/* Set up tx coalescing */
if ((cvals->tx_coalesce_usecs == 0) ||
(cvals->tx_max_coalesced_frames == 0)) {
for (i = 0; i < priv->num_tx_queues; i++)
priv->tx_queue[i]->txcoalescing = 0;
} else {
for (i = 0; i < priv->num_tx_queues; i++)
priv->tx_queue[i]->txcoalescing = 1;
}
/* Check the bounds of the values */
if (cvals->tx_coalesce_usecs > GFAR_MAX_COAL_USECS) {
pr_info("Coalescing is limited to %d microseconds\n",
GFAR_MAX_COAL_USECS);
return -EINVAL;
}
if (cvals->tx_max_coalesced_frames > GFAR_MAX_COAL_FRAMES) {
pr_info("Coalescing is limited to %d frames\n",
GFAR_MAX_COAL_FRAMES);
return -EINVAL;
}
for (i = 0; i < priv->num_tx_queues; i++) {
priv->tx_queue[i]->txic = mk_ic_value(
cvals->tx_max_coalesced_frames,
gfar_usecs2ticks(priv, cvals->tx_coalesce_usecs));
}
gfar_configure_coalescing(priv, 0xFF, 0xFF);
return 0;
}
/* Fills in rvals with the current ring parameters. Currently,
* rx, rx_mini, and rx_jumbo rings are the same size, as mini and
* jumbo are ignored by the driver */
static void gfar_gringparam(struct net_device *dev, struct ethtool_ringparam *rvals)
{
struct gfar_private *priv = netdev_priv(dev);
struct gfar_priv_tx_q *tx_queue = NULL;
struct gfar_priv_rx_q *rx_queue = NULL;
tx_queue = priv->tx_queue[0];
rx_queue = priv->rx_queue[0];
rvals->rx_max_pending = GFAR_RX_MAX_RING_SIZE;
rvals->rx_mini_max_pending = GFAR_RX_MAX_RING_SIZE;
rvals->rx_jumbo_max_pending = GFAR_RX_MAX_RING_SIZE;
rvals->tx_max_pending = GFAR_TX_MAX_RING_SIZE;
/* Values changeable by the user. The valid values are
* in the range 1 to the "*_max_pending" counterpart above.
*/
rvals->rx_pending = rx_queue->rx_ring_size;
rvals->rx_mini_pending = rx_queue->rx_ring_size;
rvals->rx_jumbo_pending = rx_queue->rx_ring_size;
rvals->tx_pending = tx_queue->tx_ring_size;
}
/* Change the current ring parameters, stopping the controller if
* necessary so that we don't mess things up while we're in
* motion. We wait for the ring to be clean before reallocating
* the rings. */
static int gfar_sringparam(struct net_device *dev, struct ethtool_ringparam *rvals)
{
struct gfar_private *priv = netdev_priv(dev);
int err = 0, i = 0;
if (rvals->rx_pending > GFAR_RX_MAX_RING_SIZE)
return -EINVAL;
if (!is_power_of_2(rvals->rx_pending)) {
netdev_err(dev, "Ring sizes must be a power of 2\n");
return -EINVAL;
}
if (rvals->tx_pending > GFAR_TX_MAX_RING_SIZE)
return -EINVAL;
if (!is_power_of_2(rvals->tx_pending)) {
netdev_err(dev, "Ring sizes must be a power of 2\n");
return -EINVAL;
}
if (dev->flags & IFF_UP) {
unsigned long flags;
/* Halt TX and RX, and process the frames which
* have already been received */
local_irq_save(flags);
lock_tx_qs(priv);
lock_rx_qs(priv);
gfar_halt(dev);
unlock_rx_qs(priv);
unlock_tx_qs(priv);
local_irq_restore(flags);
for (i = 0; i < priv->num_rx_queues; i++)
gfar_clean_rx_ring(priv->rx_queue[i],
priv->rx_queue[i]->rx_ring_size);
/* Now we take down the rings to rebuild them */
stop_gfar(dev);
}
/* Change the size */
for (i = 0; i < priv->num_rx_queues; i++) {
priv->rx_queue[i]->rx_ring_size = rvals->rx_pending;
priv->tx_queue[i]->tx_ring_size = rvals->tx_pending;
priv->tx_queue[i]->num_txbdfree = priv->tx_queue[i]->tx_ring_size;
}
/* Rebuild the rings with the new size */
if (dev->flags & IFF_UP) {
err = startup_gfar(dev);
netif_tx_wake_all_queues(dev);
}
return err;
}
int gfar_set_features(struct net_device *dev, netdev_features_t features)
{
struct gfar_private *priv = netdev_priv(dev);
unsigned long flags;
int err = 0, i = 0;
netdev_features_t changed = dev->features ^ features;
if (changed & (NETIF_F_HW_VLAN_TX|NETIF_F_HW_VLAN_RX))
gfar_vlan_mode(dev, features);
if (!(changed & NETIF_F_RXCSUM))
return 0;
if (dev->flags & IFF_UP) {
/* Halt TX and RX, and process the frames which
* have already been received */
local_irq_save(flags);
lock_tx_qs(priv);
lock_rx_qs(priv);
gfar_halt(dev);
unlock_tx_qs(priv);
unlock_rx_qs(priv);
local_irq_restore(flags);
for (i = 0; i < priv->num_rx_queues; i++)
gfar_clean_rx_ring(priv->rx_queue[i],
priv->rx_queue[i]->rx_ring_size);
/* Now we take down the rings to rebuild them */
stop_gfar(dev);
dev->features = features;
err = startup_gfar(dev);
netif_tx_wake_all_queues(dev);
}
return err;
}
static uint32_t gfar_get_msglevel(struct net_device *dev)
{
struct gfar_private *priv = netdev_priv(dev);
return priv->msg_enable;
}
static void gfar_set_msglevel(struct net_device *dev, uint32_t data)
{
struct gfar_private *priv = netdev_priv(dev);
priv->msg_enable = data;
}
#ifdef CONFIG_PM
static void gfar_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
struct gfar_private *priv = netdev_priv(dev);
if (priv->device_flags & FSL_GIANFAR_DEV_HAS_MAGIC_PACKET) {
wol->supported = WAKE_MAGIC;
wol->wolopts = priv->wol_en ? WAKE_MAGIC : 0;
} else {
wol->supported = wol->wolopts = 0;
}
}
static int gfar_set_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
struct gfar_private *priv = netdev_priv(dev);
unsigned long flags;
if (!(priv->device_flags & FSL_GIANFAR_DEV_HAS_MAGIC_PACKET) &&
wol->wolopts != 0)
return -EINVAL;
if (wol->wolopts & ~WAKE_MAGIC)
return -EINVAL;
device_set_wakeup_enable(&dev->dev, wol->wolopts & WAKE_MAGIC);
spin_lock_irqsave(&priv->bflock, flags);
priv->wol_en = !!device_may_wakeup(&dev->dev);
spin_unlock_irqrestore(&priv->bflock, flags);
return 0;
}
#endif
static void ethflow_to_filer_rules (struct gfar_private *priv, u64 ethflow)
{
u32 fcr = 0x0, fpr = FPR_FILER_MASK;
if (ethflow & RXH_L2DA) {
fcr = RQFCR_PID_DAH |RQFCR_CMP_NOMATCH |
RQFCR_HASH | RQFCR_AND | RQFCR_HASHTBL_0;
priv->ftp_rqfpr[priv->cur_filer_idx] = fpr;
priv->ftp_rqfcr[priv->cur_filer_idx] = fcr;
gfar_write_filer(priv, priv->cur_filer_idx, fcr, fpr);
priv->cur_filer_idx = priv->cur_filer_idx - 1;
fcr = RQFCR_PID_DAL | RQFCR_AND | RQFCR_CMP_NOMATCH |
RQFCR_HASH | RQFCR_AND | RQFCR_HASHTBL_0;
priv->ftp_rqfpr[priv->cur_filer_idx] = fpr;
priv->ftp_rqfcr[priv->cur_filer_idx] = fcr;
gfar_write_filer(priv, priv->cur_filer_idx, fcr, fpr);
priv->cur_filer_idx = priv->cur_filer_idx - 1;
}
if (ethflow & RXH_VLAN) {
fcr = RQFCR_PID_VID | RQFCR_CMP_NOMATCH | RQFCR_HASH |
RQFCR_AND | RQFCR_HASHTBL_0;
gfar_write_filer(priv, priv->cur_filer_idx, fcr, fpr);
priv->ftp_rqfpr[priv->cur_filer_idx] = fpr;
priv->ftp_rqfcr[priv->cur_filer_idx] = fcr;
priv->cur_filer_idx = priv->cur_filer_idx - 1;
}
if (ethflow & RXH_IP_SRC) {
fcr = RQFCR_PID_SIA | RQFCR_CMP_NOMATCH | RQFCR_HASH |
RQFCR_AND | RQFCR_HASHTBL_0;
priv->ftp_rqfpr[priv->cur_filer_idx] = fpr;
priv->ftp_rqfcr[priv->cur_filer_idx] = fcr;
gfar_write_filer(priv, priv->cur_filer_idx, fcr, fpr);
priv->cur_filer_idx = priv->cur_filer_idx - 1;
}
if (ethflow & (RXH_IP_DST)) {
fcr = RQFCR_PID_DIA | RQFCR_CMP_NOMATCH | RQFCR_HASH |
RQFCR_AND | RQFCR_HASHTBL_0;
priv->ftp_rqfpr[priv->cur_filer_idx] = fpr;
priv->ftp_rqfcr[priv->cur_filer_idx] = fcr;
gfar_write_filer(priv, priv->cur_filer_idx, fcr, fpr);
priv->cur_filer_idx = priv->cur_filer_idx - 1;
}
if (ethflow & RXH_L3_PROTO) {
fcr = RQFCR_PID_L4P | RQFCR_CMP_NOMATCH | RQFCR_HASH |
RQFCR_AND | RQFCR_HASHTBL_0;
priv->ftp_rqfpr[priv->cur_filer_idx] = fpr;
priv->ftp_rqfcr[priv->cur_filer_idx] = fcr;
gfar_write_filer(priv, priv->cur_filer_idx, fcr, fpr);
priv->cur_filer_idx = priv->cur_filer_idx - 1;
}
if (ethflow & RXH_L4_B_0_1) {
fcr = RQFCR_PID_SPT | RQFCR_CMP_NOMATCH | RQFCR_HASH |
RQFCR_AND | RQFCR_HASHTBL_0;
priv->ftp_rqfpr[priv->cur_filer_idx] = fpr;
priv->ftp_rqfcr[priv->cur_filer_idx] = fcr;
gfar_write_filer(priv, priv->cur_filer_idx, fcr, fpr);
priv->cur_filer_idx = priv->cur_filer_idx - 1;
}
if (ethflow & RXH_L4_B_2_3) {
fcr = RQFCR_PID_DPT | RQFCR_CMP_NOMATCH | RQFCR_HASH |
RQFCR_AND | RQFCR_HASHTBL_0;
priv->ftp_rqfpr[priv->cur_filer_idx] = fpr;
priv->ftp_rqfcr[priv->cur_filer_idx] = fcr;
gfar_write_filer(priv, priv->cur_filer_idx, fcr, fpr);
priv->cur_filer_idx = priv->cur_filer_idx - 1;
}
}
static int gfar_ethflow_to_filer_table(struct gfar_private *priv, u64 ethflow, u64 class)
{
unsigned int last_rule_idx = priv->cur_filer_idx;
unsigned int cmp_rqfpr;
unsigned int *local_rqfpr;
unsigned int *local_rqfcr;
int i = 0x0, k = 0x0;
int j = MAX_FILER_IDX, l = 0x0;
int ret = 1;
local_rqfpr = kmalloc(sizeof(unsigned int) * (MAX_FILER_IDX + 1),
GFP_KERNEL);
local_rqfcr = kmalloc(sizeof(unsigned int) * (MAX_FILER_IDX + 1),
GFP_KERNEL);
if (!local_rqfpr || !local_rqfcr) {
pr_err("Out of memory\n");
ret = 0;
goto err;
}
switch (class) {
case TCP_V4_FLOW:
cmp_rqfpr = RQFPR_IPV4 |RQFPR_TCP;
break;
case UDP_V4_FLOW:
cmp_rqfpr = RQFPR_IPV4 |RQFPR_UDP;
break;
case TCP_V6_FLOW:
cmp_rqfpr = RQFPR_IPV6 |RQFPR_TCP;
break;
case UDP_V6_FLOW:
cmp_rqfpr = RQFPR_IPV6 |RQFPR_UDP;
break;
default:
pr_err("Right now this class is not supported\n");
ret = 0;
goto err;
}
for (i = 0; i < MAX_FILER_IDX + 1; i++) {
local_rqfpr[j] = priv->ftp_rqfpr[i];
local_rqfcr[j] = priv->ftp_rqfcr[i];
j--;
if ((priv->ftp_rqfcr[i] == (RQFCR_PID_PARSE |
RQFCR_CLE |RQFCR_AND)) &&
(priv->ftp_rqfpr[i] == cmp_rqfpr))
break;
}
if (i == MAX_FILER_IDX + 1) {
pr_err("No parse rule found, can't create hash rules\n");
ret = 0;
goto err;
}
/* If a match was found, then it begins the starting of a cluster rule
* if it was already programmed, we need to overwrite these rules
*/
for (l = i+1; l < MAX_FILER_IDX; l++) {
if ((priv->ftp_rqfcr[l] & RQFCR_CLE) &&
!(priv->ftp_rqfcr[l] & RQFCR_AND)) {
priv->ftp_rqfcr[l] = RQFCR_CLE | RQFCR_CMP_EXACT |
RQFCR_HASHTBL_0 | RQFCR_PID_MASK;
priv->ftp_rqfpr[l] = FPR_FILER_MASK;
gfar_write_filer(priv, l, priv->ftp_rqfcr[l],
priv->ftp_rqfpr[l]);
break;
}
if (!(priv->ftp_rqfcr[l] & RQFCR_CLE) &&
(priv->ftp_rqfcr[l] & RQFCR_AND))
continue;
else {
local_rqfpr[j] = priv->ftp_rqfpr[l];
local_rqfcr[j] = priv->ftp_rqfcr[l];
j--;
}
}
priv->cur_filer_idx = l - 1;
last_rule_idx = l;
/* hash rules */
ethflow_to_filer_rules(priv, ethflow);
/* Write back the popped out rules again */
for (k = j+1; k < MAX_FILER_IDX; k++) {
priv->ftp_rqfpr[priv->cur_filer_idx] = local_rqfpr[k];
priv->ftp_rqfcr[priv->cur_filer_idx] = local_rqfcr[k];
gfar_write_filer(priv, priv->cur_filer_idx,
local_rqfcr[k], local_rqfpr[k]);
if (!priv->cur_filer_idx)
break;
priv->cur_filer_idx = priv->cur_filer_idx - 1;
}
err:
kfree(local_rqfcr);
kfree(local_rqfpr);
return ret;
}
static int gfar_set_hash_opts(struct gfar_private *priv, struct ethtool_rxnfc *cmd)
{
/* write the filer rules here */
if (!gfar_ethflow_to_filer_table(priv, cmd->data, cmd->flow_type))
return -EINVAL;
return 0;
}
static int gfar_check_filer_hardware(struct gfar_private *priv)
{
struct gfar __iomem *regs = NULL;
u32 i;
regs = priv->gfargrp[0].regs;
/* Check if we are in FIFO mode */
i = gfar_read(®s->ecntrl);
i &= ECNTRL_FIFM;
if (i == ECNTRL_FIFM) {
netdev_notice(priv->ndev, "Interface in FIFO mode\n");
i = gfar_read(®s->rctrl);
i &= RCTRL_PRSDEP_MASK | RCTRL_PRSFM;
if (i == (RCTRL_PRSDEP_MASK | RCTRL_PRSFM)) {
netdev_info(priv->ndev,
"Receive Queue Filtering enabled\n");
} else {
netdev_warn(priv->ndev,
"Receive Queue Filtering disabled\n");
return -EOPNOTSUPP;
}
}
/* Or in standard mode */
else {
i = gfar_read(®s->rctrl);
i &= RCTRL_PRSDEP_MASK;
if (i == RCTRL_PRSDEP_MASK) {
netdev_info(priv->ndev,
"Receive Queue Filtering enabled\n");
} else {
netdev_warn(priv->ndev,
"Receive Queue Filtering disabled\n");
return -EOPNOTSUPP;
}
}
/* Sets the properties for arbitrary filer rule
* to the first 4 Layer 4 Bytes */
regs->rbifx = 0xC0C1C2C3;
return 0;
}
static int gfar_comp_asc(const void *a, const void *b)
{
return memcmp(a, b, 4);
}
static int gfar_comp_desc(const void *a, const void *b)
{
return -memcmp(a, b, 4);
}
static void gfar_swap(void *a, void *b, int size)
{
u32 *_a = a;
u32 *_b = b;
swap(_a[0], _b[0]);
swap(_a[1], _b[1]);
swap(_a[2], _b[2]);
swap(_a[3], _b[3]);
}
/* Write a mask to filer cache */
static void gfar_set_mask(u32 mask, struct filer_table *tab)
{
tab->fe[tab->index].ctrl = RQFCR_AND | RQFCR_PID_MASK | RQFCR_CMP_EXACT;
tab->fe[tab->index].prop = mask;
tab->index++;
}
/* Sets parse bits (e.g. IP or TCP) */
static void gfar_set_parse_bits(u32 value, u32 mask, struct filer_table *tab)
{
gfar_set_mask(mask, tab);
tab->fe[tab->index].ctrl = RQFCR_CMP_EXACT | RQFCR_PID_PARSE
| RQFCR_AND;
tab->fe[tab->index].prop = value;
tab->index++;
}
static void gfar_set_general_attribute(u32 value, u32 mask, u32 flag,
struct filer_table *tab)
{
gfar_set_mask(mask, tab);
tab->fe[tab->index].ctrl = RQFCR_CMP_EXACT | RQFCR_AND | flag;
tab->fe[tab->index].prop = value;
tab->index++;
}
/*
* For setting a tuple of value and mask of type flag
* Example:
* IP-Src = 10.0.0.0/255.0.0.0
* value: 0x0A000000 mask: FF000000 flag: RQFPR_IPV4
*
* Ethtool gives us a value=0 and mask=~0 for don't care a tuple
* For a don't care mask it gives us a 0
*
* The check if don't care and the mask adjustment if mask=0 is done for VLAN
* and MAC stuff on an upper level (due to missing information on this level).
* For these guys we can discard them if they are value=0 and mask=0.
*
* Further the all masks are one-padded for better hardware efficiency.
*/
static void gfar_set_attribute(u32 value, u32 mask, u32 flag,
struct filer_table *tab)
{
switch (flag) {
/* 3bit */
case RQFCR_PID_PRI:
if (!(value | mask))
return;
mask |= RQFCR_PID_PRI_MASK;
break;
/* 8bit */
case RQFCR_PID_L4P:
case RQFCR_PID_TOS:
if (!~(mask | RQFCR_PID_L4P_MASK))
return;
if (!mask)
mask = ~0;
else
mask |= RQFCR_PID_L4P_MASK;
break;
/* 12bit */
case RQFCR_PID_VID:
if (!(value | mask))
return;
mask |= RQFCR_PID_VID_MASK;
break;
/* 16bit */
case RQFCR_PID_DPT:
case RQFCR_PID_SPT:
case RQFCR_PID_ETY:
if (!~(mask | RQFCR_PID_PORT_MASK))
return;
if (!mask)
mask = ~0;
else
mask |= RQFCR_PID_PORT_MASK;
break;
/* 24bit */
case RQFCR_PID_DAH:
case RQFCR_PID_DAL:
case RQFCR_PID_SAH:
case RQFCR_PID_SAL:
if (!(value | mask))
return;
mask |= RQFCR_PID_MAC_MASK;
break;
/* for all real 32bit masks */
default:
if (!~mask)
return;
if (!mask)
mask = ~0;
break;
}
gfar_set_general_attribute(value, mask, flag, tab);
}
/* Translates value and mask for UDP, TCP or SCTP */
static void gfar_set_basic_ip(struct ethtool_tcpip4_spec *value,
struct ethtool_tcpip4_spec *mask, struct filer_table *tab)
{
gfar_set_attribute(value->ip4src, mask->ip4src, RQFCR_PID_SIA, tab);
gfar_set_attribute(value->ip4dst, mask->ip4dst, RQFCR_PID_DIA, tab);
gfar_set_attribute(value->pdst, mask->pdst, RQFCR_PID_DPT, tab);
gfar_set_attribute(value->psrc, mask->psrc, RQFCR_PID_SPT, tab);
gfar_set_attribute(value->tos, mask->tos, RQFCR_PID_TOS, tab);
}
/* Translates value and mask for RAW-IP4 */
static void gfar_set_user_ip(struct ethtool_usrip4_spec *value,
struct ethtool_usrip4_spec *mask, struct filer_table *tab)
{
gfar_set_attribute(value->ip4src, mask->ip4src, RQFCR_PID_SIA, tab);
gfar_set_attribute(value->ip4dst, mask->ip4dst, RQFCR_PID_DIA, tab);
gfar_set_attribute(value->tos, mask->tos, RQFCR_PID_TOS, tab);
gfar_set_attribute(value->proto, mask->proto, RQFCR_PID_L4P, tab);
gfar_set_attribute(value->l4_4_bytes, mask->l4_4_bytes, RQFCR_PID_ARB,
tab);
}
/* Translates value and mask for ETHER spec */
static void gfar_set_ether(struct ethhdr *value, struct ethhdr *mask,
struct filer_table *tab)
{
u32 upper_temp_mask = 0;
u32 lower_temp_mask = 0;
/* Source address */
if (!is_broadcast_ether_addr(mask->h_source)) {
if (is_zero_ether_addr(mask->h_source)) {
upper_temp_mask = 0xFFFFFFFF;
lower_temp_mask = 0xFFFFFFFF;
} else {
upper_temp_mask = mask->h_source[0] << 16
| mask->h_source[1] << 8
| mask->h_source[2];
lower_temp_mask = mask->h_source[3] << 16
| mask->h_source[4] << 8
| mask->h_source[5];
}
/* Upper 24bit */
gfar_set_attribute(
value->h_source[0] << 16 | value->h_source[1]
<< 8 | value->h_source[2],
upper_temp_mask, RQFCR_PID_SAH, tab);
/* And the same for the lower part */
gfar_set_attribute(
value->h_source[3] << 16 | value->h_source[4]
<< 8 | value->h_source[5],
lower_temp_mask, RQFCR_PID_SAL, tab);
}
/* Destination address */
if (!is_broadcast_ether_addr(mask->h_dest)) {
/* Special for destination is limited broadcast */
if ((is_broadcast_ether_addr(value->h_dest)
&& is_zero_ether_addr(mask->h_dest))) {
gfar_set_parse_bits(RQFPR_EBC, RQFPR_EBC, tab);
} else {
if (is_zero_ether_addr(mask->h_dest)) {
upper_temp_mask = 0xFFFFFFFF;
lower_temp_mask = 0xFFFFFFFF;
} else {
upper_temp_mask = mask->h_dest[0] << 16
| mask->h_dest[1] << 8
| mask->h_dest[2];
lower_temp_mask = mask->h_dest[3] << 16
| mask->h_dest[4] << 8
| mask->h_dest[5];
}
/* Upper 24bit */
gfar_set_attribute(
value->h_dest[0] << 16
| value->h_dest[1] << 8
| value->h_dest[2],
upper_temp_mask, RQFCR_PID_DAH, tab);
/* And the same for the lower part */
gfar_set_attribute(
value->h_dest[3] << 16
| value->h_dest[4] << 8
| value->h_dest[5],
lower_temp_mask, RQFCR_PID_DAL, tab);
}
}
gfar_set_attribute(value->h_proto, mask->h_proto, RQFCR_PID_ETY, tab);
}
/* Convert a rule to binary filter format of gianfar */
static int gfar_convert_to_filer(struct ethtool_rx_flow_spec *rule,
struct filer_table *tab)
{
u32 vlan = 0, vlan_mask = 0;
u32 id = 0, id_mask = 0;
u32 cfi = 0, cfi_mask = 0;
u32 prio = 0, prio_mask = 0;
u32 old_index = tab->index;
/* Check if vlan is wanted */
if ((rule->flow_type & FLOW_EXT) && (rule->m_ext.vlan_tci != 0xFFFF)) {
if (!rule->m_ext.vlan_tci)
rule->m_ext.vlan_tci = 0xFFFF;
vlan = RQFPR_VLN;
vlan_mask = RQFPR_VLN;
/* Separate the fields */
id = rule->h_ext.vlan_tci & VLAN_VID_MASK;
id_mask = rule->m_ext.vlan_tci & VLAN_VID_MASK;
cfi = rule->h_ext.vlan_tci & VLAN_CFI_MASK;
cfi_mask = rule->m_ext.vlan_tci & VLAN_CFI_MASK;
prio = (rule->h_ext.vlan_tci & VLAN_PRIO_MASK) >> VLAN_PRIO_SHIFT;
prio_mask = (rule->m_ext.vlan_tci & VLAN_PRIO_MASK) >> VLAN_PRIO_SHIFT;
if (cfi == VLAN_TAG_PRESENT && cfi_mask == VLAN_TAG_PRESENT) {
vlan |= RQFPR_CFI;
vlan_mask |= RQFPR_CFI;
} else if (cfi != VLAN_TAG_PRESENT && cfi_mask == VLAN_TAG_PRESENT) {
vlan_mask |= RQFPR_CFI;
}
}
switch (rule->flow_type & ~FLOW_EXT) {
case TCP_V4_FLOW:
gfar_set_parse_bits(RQFPR_IPV4 | RQFPR_TCP | vlan,
RQFPR_IPV4 | RQFPR_TCP | vlan_mask, tab);
gfar_set_basic_ip(&rule->h_u.tcp_ip4_spec,
&rule->m_u.tcp_ip4_spec, tab);
break;
case UDP_V4_FLOW:
gfar_set_parse_bits(RQFPR_IPV4 | RQFPR_UDP | vlan,
RQFPR_IPV4 | RQFPR_UDP | vlan_mask, tab);
gfar_set_basic_ip(&rule->h_u.udp_ip4_spec,
&rule->m_u.udp_ip4_spec, tab);
break;
case SCTP_V4_FLOW:
gfar_set_parse_bits(RQFPR_IPV4 | vlan, RQFPR_IPV4 | vlan_mask,
tab);
gfar_set_attribute(132, 0, RQFCR_PID_L4P, tab);
gfar_set_basic_ip((struct ethtool_tcpip4_spec *) &rule->h_u,
(struct ethtool_tcpip4_spec *) &rule->m_u, tab);
break;
case IP_USER_FLOW:
gfar_set_parse_bits(RQFPR_IPV4 | vlan, RQFPR_IPV4 | vlan_mask,
tab);
gfar_set_user_ip((struct ethtool_usrip4_spec *) &rule->h_u,
(struct ethtool_usrip4_spec *) &rule->m_u, tab);
break;
case ETHER_FLOW:
if (vlan)
gfar_set_parse_bits(vlan, vlan_mask, tab);
gfar_set_ether((struct ethhdr *) &rule->h_u,
(struct ethhdr *) &rule->m_u, tab);
break;
default:
return -1;
}
/* Set the vlan attributes in the end */
if (vlan) {
gfar_set_attribute(id, id_mask, RQFCR_PID_VID, tab);
gfar_set_attribute(prio, prio_mask, RQFCR_PID_PRI, tab);
}
/* If there has been nothing written till now, it must be a default */
if (tab->index == old_index) {
gfar_set_mask(0xFFFFFFFF, tab);
tab->fe[tab->index].ctrl = 0x20;
tab->fe[tab->index].prop = 0x0;
tab->index++;
}
/* Remove last AND */
tab->fe[tab->index - 1].ctrl &= (~RQFCR_AND);
/* Specify which queue to use or to drop */
if (rule->ring_cookie == RX_CLS_FLOW_DISC)
tab->fe[tab->index - 1].ctrl |= RQFCR_RJE;
else
tab->fe[tab->index - 1].ctrl |= (rule->ring_cookie << 10);
/* Only big enough entries can be clustered */
if (tab->index > (old_index + 2)) {
tab->fe[old_index + 1].ctrl |= RQFCR_CLE;
tab->fe[tab->index - 1].ctrl |= RQFCR_CLE;
}
/* In rare cases the cache can be full while there is free space in hw */
if (tab->index > MAX_FILER_CACHE_IDX - 1)
return -EBUSY;
return 0;
}
/* Copy size filer entries */
static void gfar_copy_filer_entries(struct gfar_filer_entry dst[0],
struct gfar_filer_entry src[0], s32 size)
{
while (size > 0) {
size--;
dst[size].ctrl = src[size].ctrl;
dst[size].prop = src[size].prop;
}
}
/* Delete the contents of the filer-table between start and end
* and collapse them */
static int gfar_trim_filer_entries(u32 begin, u32 end, struct filer_table *tab)
{
int length;
if (end > MAX_FILER_CACHE_IDX || end < begin)
return -EINVAL;
end++;
length = end - begin;
/* Copy */
while (end < tab->index) {
tab->fe[begin].ctrl = tab->fe[end].ctrl;
tab->fe[begin++].prop = tab->fe[end++].prop;
}
/* Fill up with don't cares */
while (begin < tab->index) {
tab->fe[begin].ctrl = 0x60;
tab->fe[begin].prop = 0xFFFFFFFF;
begin++;
}
tab->index -= length;
return 0;
}
/* Make space on the wanted location */
static int gfar_expand_filer_entries(u32 begin, u32 length,
struct filer_table *tab)
{
if (length == 0 || length + tab->index > MAX_FILER_CACHE_IDX || begin
> MAX_FILER_CACHE_IDX)
return -EINVAL;
gfar_copy_filer_entries(&(tab->fe[begin + length]), &(tab->fe[begin]),
tab->index - length + 1);
tab->index += length;
return 0;
}
static int gfar_get_next_cluster_start(int start, struct filer_table *tab)
{
for (; (start < tab->index) && (start < MAX_FILER_CACHE_IDX - 1); start++) {
if ((tab->fe[start].ctrl & (RQFCR_AND | RQFCR_CLE))
== (RQFCR_AND | RQFCR_CLE))
return start;
}
return -1;
}
static int gfar_get_next_cluster_end(int start, struct filer_table *tab)
{
for (; (start < tab->index) && (start < MAX_FILER_CACHE_IDX - 1); start++) {
if ((tab->fe[start].ctrl & (RQFCR_AND | RQFCR_CLE))
== (RQFCR_CLE))
return start;
}
return -1;
}
/*
* Uses hardwares clustering option to reduce
* the number of filer table entries
*/
static void gfar_cluster_filer(struct filer_table *tab)
{
s32 i = -1, j, iend, jend;
while ((i = gfar_get_next_cluster_start(++i, tab)) != -1) {
j = i;
while ((j = gfar_get_next_cluster_start(++j, tab)) != -1) {
/*
* The cluster entries self and the previous one
* (a mask) must be identical!
*/
if (tab->fe[i].ctrl != tab->fe[j].ctrl)
break;
if (tab->fe[i].prop != tab->fe[j].prop)
break;
if (tab->fe[i - 1].ctrl != tab->fe[j - 1].ctrl)
break;
if (tab->fe[i - 1].prop != tab->fe[j - 1].prop)
break;
iend = gfar_get_next_cluster_end(i, tab);
jend = gfar_get_next_cluster_end(j, tab);
if (jend == -1 || iend == -1)
break;
/*
* First we make some free space, where our cluster
* element should be. Then we copy it there and finally
* delete in from its old location.
*/
if (gfar_expand_filer_entries(iend, (jend - j), tab)
== -EINVAL)
break;
gfar_copy_filer_entries(&(tab->fe[iend + 1]),
&(tab->fe[jend + 1]), jend - j);
if (gfar_trim_filer_entries(jend - 1,
jend + (jend - j), tab) == -EINVAL)
return;
/* Mask out cluster bit */
tab->fe[iend].ctrl &= ~(RQFCR_CLE);
}
}
}
/* Swaps the masked bits of a1<>a2 and b1<>b2 */
static void gfar_swap_bits(struct gfar_filer_entry *a1,
struct gfar_filer_entry *a2, struct gfar_filer_entry *b1,
struct gfar_filer_entry *b2, u32 mask)
{
u32 temp[4];
temp[0] = a1->ctrl & mask;
temp[1] = a2->ctrl & mask;
temp[2] = b1->ctrl & mask;
temp[3] = b2->ctrl & mask;
a1->ctrl &= ~mask;
a2->ctrl &= ~mask;
b1->ctrl &= ~mask;
b2->ctrl &= ~mask;
a1->ctrl |= temp[1];
a2->ctrl |= temp[0];
b1->ctrl |= temp[3];
b2->ctrl |= temp[2];
}
/*
* Generate a list consisting of masks values with their start and
* end of validity and block as indicator for parts belonging
* together (glued by ANDs) in mask_table
*/
static u32 gfar_generate_mask_table(struct gfar_mask_entry *mask_table,
struct filer_table *tab)
{
u32 i, and_index = 0, block_index = 1;
for (i = 0; i < tab->index; i++) {
/* LSByte of control = 0 sets a mask */
if (!(tab->fe[i].ctrl & 0xF)) {
mask_table[and_index].mask = tab->fe[i].prop;
mask_table[and_index].start = i;
mask_table[and_index].block = block_index;
if (and_index >= 1)
mask_table[and_index - 1].end = i - 1;
and_index++;
}
/* cluster starts and ends will be separated because they should
* hold their position */
if (tab->fe[i].ctrl & RQFCR_CLE)
block_index++;
/* A not set AND indicates the end of a depended block */
if (!(tab->fe[i].ctrl & RQFCR_AND))
block_index++;
}
mask_table[and_index - 1].end = i - 1;
return and_index;
}
/*
* Sorts the entries of mask_table by the values of the masks.
* Important: The 0xFF80 flags of the first and last entry of a
* block must hold their position (which queue, CLusterEnable, ReJEct,
* AND)
*/
static void gfar_sort_mask_table(struct gfar_mask_entry *mask_table,
struct filer_table *temp_table, u32 and_index)
{
/* Pointer to compare function (_asc or _desc) */
int (*gfar_comp)(const void *, const void *);
u32 i, size = 0, start = 0, prev = 1;
u32 old_first, old_last, new_first, new_last;
gfar_comp = &gfar_comp_desc;
for (i = 0; i < and_index; i++) {
if (prev != mask_table[i].block) {
old_first = mask_table[start].start + 1;
old_last = mask_table[i - 1].end;
sort(mask_table + start, size,
sizeof(struct gfar_mask_entry),
gfar_comp, &gfar_swap);
/* Toggle order for every block. This makes the
* thing more efficient! */
if (gfar_comp == gfar_comp_desc)
gfar_comp = &gfar_comp_asc;
else
gfar_comp = &gfar_comp_desc;
new_first = mask_table[start].start + 1;
new_last = mask_table[i - 1].end;
gfar_swap_bits(&temp_table->fe[new_first],
&temp_table->fe[old_first],
&temp_table->fe[new_last],
&temp_table->fe[old_last],
RQFCR_QUEUE | RQFCR_CLE |
RQFCR_RJE | RQFCR_AND
);
start = i;
size = 0;
}
size++;
prev = mask_table[i].block;
}
}
/*
* Reduces the number of masks needed in the filer table to save entries
* This is done by sorting the masks of a depended block. A depended block is
* identified by gluing ANDs or CLE. The sorting order toggles after every
* block. Of course entries in scope of a mask must change their location with
* it.
*/
static int gfar_optimize_filer_masks(struct filer_table *tab)
{
struct filer_table *temp_table;
struct gfar_mask_entry *mask_table;
u32 and_index = 0, previous_mask = 0, i = 0, j = 0, size = 0;
s32 ret = 0;
/* We need a copy of the filer table because
* we want to change its order */
temp_table = kmemdup(tab, sizeof(*temp_table), GFP_KERNEL);
if (temp_table == NULL)
return -ENOMEM;
mask_table = kcalloc(MAX_FILER_CACHE_IDX / 2 + 1,
sizeof(struct gfar_mask_entry), GFP_KERNEL);
if (mask_table == NULL) {
ret = -ENOMEM;
goto end;
}
and_index = gfar_generate_mask_table(mask_table, tab);
gfar_sort_mask_table(mask_table, temp_table, and_index);
/* Now we can copy the data from our duplicated filer table to
* the real one in the order the mask table says */
for (i = 0; i < and_index; i++) {
size = mask_table[i].end - mask_table[i].start + 1;
gfar_copy_filer_entries(&(tab->fe[j]),
&(temp_table->fe[mask_table[i].start]), size);
j += size;
}
/* And finally we just have to check for duplicated masks and drop the
* second ones */
for (i = 0; i < tab->index && i < MAX_FILER_CACHE_IDX; i++) {
if (tab->fe[i].ctrl == 0x80) {
previous_mask = i++;
break;
}
}
for (; i < tab->index && i < MAX_FILER_CACHE_IDX; i++) {
if (tab->fe[i].ctrl == 0x80) {
if (tab->fe[i].prop == tab->fe[previous_mask].prop) {
/* Two identical ones found!
* So drop the second one! */
gfar_trim_filer_entries(i, i, tab);
} else
/* Not identical! */
previous_mask = i;
}
}
kfree(mask_table);
end: kfree(temp_table);
return ret;
}
/* Write the bit-pattern from software's buffer to hardware registers */
static int gfar_write_filer_table(struct gfar_private *priv,
struct filer_table *tab)
{
u32 i = 0;
if (tab->index > MAX_FILER_IDX - 1)
return -EBUSY;
/* Avoid inconsistent filer table to be processed */
lock_rx_qs(priv);
/* Fill regular entries */
for (; i < MAX_FILER_IDX - 1 && (tab->fe[i].ctrl | tab->fe[i].ctrl); i++)
gfar_write_filer(priv, i, tab->fe[i].ctrl, tab->fe[i].prop);
/* Fill the rest with fall-troughs */
for (; i < MAX_FILER_IDX - 1; i++)
gfar_write_filer(priv, i, 0x60, 0xFFFFFFFF);
/* Last entry must be default accept
* because that's what people expect */
gfar_write_filer(priv, i, 0x20, 0x0);
unlock_rx_qs(priv);
return 0;
}
static int gfar_check_capability(struct ethtool_rx_flow_spec *flow,
struct gfar_private *priv)
{
if (flow->flow_type & FLOW_EXT) {
if (~flow->m_ext.data[0] || ~flow->m_ext.data[1])
netdev_warn(priv->ndev,
"User-specific data not supported!\n");
if (~flow->m_ext.vlan_etype)
netdev_warn(priv->ndev,
"VLAN-etype not supported!\n");
}
if (flow->flow_type == IP_USER_FLOW)
if (flow->h_u.usr_ip4_spec.ip_ver != ETH_RX_NFC_IP4)
netdev_warn(priv->ndev,
"IP-Version differing from IPv4 not supported!\n");
return 0;
}
static int gfar_process_filer_changes(struct gfar_private *priv)
{
struct ethtool_flow_spec_container *j;
struct filer_table *tab;
s32 i = 0;
s32 ret = 0;
/* So index is set to zero, too! */
tab = kzalloc(sizeof(*tab), GFP_KERNEL);
if (tab == NULL)
return -ENOMEM;
/* Now convert the existing filer data from flow_spec into
* filer tables binary format */
list_for_each_entry(j, &priv->rx_list.list, list) {
ret = gfar_convert_to_filer(&j->fs, tab);
if (ret == -EBUSY) {
netdev_err(priv->ndev, "Rule not added: No free space!\n");
goto end;
}
if (ret == -1) {
netdev_err(priv->ndev, "Rule not added: Unsupported Flow-type!\n");
goto end;
}
}
i = tab->index;
/* Optimizations to save entries */
gfar_cluster_filer(tab);
gfar_optimize_filer_masks(tab);
pr_debug("\n\tSummary:\n"
"\tData on hardware: %d\n"
"\tCompression rate: %d%%\n",
tab->index, 100 - (100 * tab->index) / i);
/* Write everything to hardware */
ret = gfar_write_filer_table(priv, tab);
if (ret == -EBUSY) {
netdev_err(priv->ndev, "Rule not added: No free space!\n");
goto end;
}
end: kfree(tab);
return ret;
}
static void gfar_invert_masks(struct ethtool_rx_flow_spec *flow)
{
u32 i = 0;
for (i = 0; i < sizeof(flow->m_u); i++)
flow->m_u.hdata[i] ^= 0xFF;
flow->m_ext.vlan_etype ^= 0xFFFF;
flow->m_ext.vlan_tci ^= 0xFFFF;
flow->m_ext.data[0] ^= ~0;
flow->m_ext.data[1] ^= ~0;
}
static int gfar_add_cls(struct gfar_private *priv,
struct ethtool_rx_flow_spec *flow)
{
struct ethtool_flow_spec_container *temp, *comp;
int ret = 0;
temp = kmalloc(sizeof(*temp), GFP_KERNEL);
if (temp == NULL)
return -ENOMEM;
memcpy(&temp->fs, flow, sizeof(temp->fs));
gfar_invert_masks(&temp->fs);
ret = gfar_check_capability(&temp->fs, priv);
if (ret)
goto clean_mem;
/* Link in the new element at the right @location */
if (list_empty(&priv->rx_list.list)) {
ret = gfar_check_filer_hardware(priv);
if (ret != 0)
goto clean_mem;
list_add(&temp->list, &priv->rx_list.list);
goto process;
} else {
list_for_each_entry(comp, &priv->rx_list.list, list) {
if (comp->fs.location > flow->location) {
list_add_tail(&temp->list, &comp->list);
goto process;
}
if (comp->fs.location == flow->location) {
netdev_err(priv->ndev,
"Rule not added: ID %d not free!\n",
flow->location);
ret = -EBUSY;
goto clean_mem;
}
}
list_add_tail(&temp->list, &priv->rx_list.list);
}
process:
ret = gfar_process_filer_changes(priv);
if (ret)
goto clean_list;
priv->rx_list.count++;
return ret;
clean_list:
list_del(&temp->list);
clean_mem:
kfree(temp);
return ret;
}
static int gfar_del_cls(struct gfar_private *priv, u32 loc)
{
struct ethtool_flow_spec_container *comp;
u32 ret = -EINVAL;
if (list_empty(&priv->rx_list.list))
return ret;
list_for_each_entry(comp, &priv->rx_list.list, list) {
if (comp->fs.location == loc) {
list_del(&comp->list);
kfree(comp);
priv->rx_list.count--;
gfar_process_filer_changes(priv);
ret = 0;
break;
}
}
return ret;
}
static int gfar_get_cls(struct gfar_private *priv, struct ethtool_rxnfc *cmd)
{
struct ethtool_flow_spec_container *comp;
u32 ret = -EINVAL;
list_for_each_entry(comp, &priv->rx_list.list, list) {
if (comp->fs.location == cmd->fs.location) {
memcpy(&cmd->fs, &comp->fs, sizeof(cmd->fs));
gfar_invert_masks(&cmd->fs);
ret = 0;
break;
}
}
return ret;
}
static int gfar_get_cls_all(struct gfar_private *priv,
struct ethtool_rxnfc *cmd, u32 *rule_locs)
{
struct ethtool_flow_spec_container *comp;
u32 i = 0;
list_for_each_entry(comp, &priv->rx_list.list, list) {
if (i == cmd->rule_cnt)
return -EMSGSIZE;
rule_locs[i] = comp->fs.location;
i++;
}
cmd->data = MAX_FILER_IDX;
cmd->rule_cnt = i;
return 0;
}
static int gfar_set_nfc(struct net_device *dev, struct ethtool_rxnfc *cmd)
{
struct gfar_private *priv = netdev_priv(dev);
int ret = 0;
mutex_lock(&priv->rx_queue_access);
switch (cmd->cmd) {
case ETHTOOL_SRXFH:
ret = gfar_set_hash_opts(priv, cmd);
break;
case ETHTOOL_SRXCLSRLINS:
if ((cmd->fs.ring_cookie != RX_CLS_FLOW_DISC &&
cmd->fs.ring_cookie >= priv->num_rx_queues) ||
cmd->fs.location >= MAX_FILER_IDX) {
ret = -EINVAL;
break;
}
ret = gfar_add_cls(priv, &cmd->fs);
break;
case ETHTOOL_SRXCLSRLDEL:
ret = gfar_del_cls(priv, cmd->fs.location);
break;
default:
ret = -EINVAL;
}
mutex_unlock(&priv->rx_queue_access);
return ret;
}
static int gfar_get_nfc(struct net_device *dev, struct ethtool_rxnfc *cmd,
u32 *rule_locs)
{
struct gfar_private *priv = netdev_priv(dev);
int ret = 0;
switch (cmd->cmd) {
case ETHTOOL_GRXRINGS:
cmd->data = priv->num_rx_queues;
break;
case ETHTOOL_GRXCLSRLCNT:
cmd->rule_cnt = priv->rx_list.count;
break;
case ETHTOOL_GRXCLSRULE:
ret = gfar_get_cls(priv, cmd);
break;
case ETHTOOL_GRXCLSRLALL:
ret = gfar_get_cls_all(priv, cmd, rule_locs);
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
const struct ethtool_ops gfar_ethtool_ops = {
.get_settings = gfar_gsettings,
.set_settings = gfar_ssettings,
.get_drvinfo = gfar_gdrvinfo,
.get_regs_len = gfar_reglen,
.get_regs = gfar_get_regs,
.get_link = ethtool_op_get_link,
.get_coalesce = gfar_gcoalesce,
.set_coalesce = gfar_scoalesce,
.get_ringparam = gfar_gringparam,
.set_ringparam = gfar_sringparam,
.get_strings = gfar_gstrings,
.get_sset_count = gfar_sset_count,
.get_ethtool_stats = gfar_fill_stats,
.get_msglevel = gfar_get_msglevel,
.set_msglevel = gfar_set_msglevel,
#ifdef CONFIG_PM
.get_wol = gfar_get_wol,
.set_wol = gfar_set_wol,
#endif
.set_rxnfc = gfar_set_nfc,
.get_rxnfc = gfar_get_nfc,
};
| gpl-2.0 |
z8cpaul/lsikernel-3.4 | arch/arm/mach-s3c2410/pll.c | 5070 | 3665 | /* arch/arm/mach-s3c2410/pll.c
*
* Copyright (c) 2006-2007 Simtec Electronics
* http://armlinux.simtec.co.uk/
* Ben Dooks <ben@simtec.co.uk>
* Vincent Sanders <vince@arm.linux.org.uk>
*
* S3C2410 CPU PLL tables
*
* 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/kernel.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/list.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <plat/cpu.h>
#include <plat/cpu-freq-core.h>
static struct cpufreq_frequency_table pll_vals_12MHz[] = {
{ .frequency = 34000000, .index = PLLVAL(82, 2, 3), },
{ .frequency = 45000000, .index = PLLVAL(82, 1, 3), },
{ .frequency = 51000000, .index = PLLVAL(161, 3, 3), },
{ .frequency = 48000000, .index = PLLVAL(120, 2, 3), },
{ .frequency = 56000000, .index = PLLVAL(142, 2, 3), },
{ .frequency = 68000000, .index = PLLVAL(82, 2, 2), },
{ .frequency = 79000000, .index = PLLVAL(71, 1, 2), },
{ .frequency = 85000000, .index = PLLVAL(105, 2, 2), },
{ .frequency = 90000000, .index = PLLVAL(112, 2, 2), },
{ .frequency = 101000000, .index = PLLVAL(127, 2, 2), },
{ .frequency = 113000000, .index = PLLVAL(105, 1, 2), },
{ .frequency = 118000000, .index = PLLVAL(150, 2, 2), },
{ .frequency = 124000000, .index = PLLVAL(116, 1, 2), },
{ .frequency = 135000000, .index = PLLVAL(82, 2, 1), },
{ .frequency = 147000000, .index = PLLVAL(90, 2, 1), },
{ .frequency = 152000000, .index = PLLVAL(68, 1, 1), },
{ .frequency = 158000000, .index = PLLVAL(71, 1, 1), },
{ .frequency = 170000000, .index = PLLVAL(77, 1, 1), },
{ .frequency = 180000000, .index = PLLVAL(82, 1, 1), },
{ .frequency = 186000000, .index = PLLVAL(85, 1, 1), },
{ .frequency = 192000000, .index = PLLVAL(88, 1, 1), },
{ .frequency = 203000000, .index = PLLVAL(161, 3, 1), },
/* 2410A extras */
{ .frequency = 210000000, .index = PLLVAL(132, 2, 1), },
{ .frequency = 226000000, .index = PLLVAL(105, 1, 1), },
{ .frequency = 266000000, .index = PLLVAL(125, 1, 1), },
{ .frequency = 268000000, .index = PLLVAL(126, 1, 1), },
{ .frequency = 270000000, .index = PLLVAL(127, 1, 1), },
};
static int s3c2410_plls_add(struct device *dev, struct subsys_interface *sif)
{
return s3c_plltab_register(pll_vals_12MHz, ARRAY_SIZE(pll_vals_12MHz));
}
static struct subsys_interface s3c2410_plls_interface = {
.name = "s3c2410_plls",
.subsys = &s3c2410_subsys,
.add_dev = s3c2410_plls_add,
};
static int __init s3c2410_pll_init(void)
{
return subsys_interface_register(&s3c2410_plls_interface);
}
arch_initcall(s3c2410_pll_init);
static struct subsys_interface s3c2410a_plls_interface = {
.name = "s3c2410a_plls",
.subsys = &s3c2410a_subsys,
.add_dev = s3c2410_plls_add,
};
static int __init s3c2410a_pll_init(void)
{
return subsys_interface_register(&s3c2410a_plls_interface);
}
arch_initcall(s3c2410a_pll_init);
| gpl-2.0 |
jmartinc/video_visstrim | arch/arm/mach-s3c2410/pll.c | 5070 | 3665 | /* arch/arm/mach-s3c2410/pll.c
*
* Copyright (c) 2006-2007 Simtec Electronics
* http://armlinux.simtec.co.uk/
* Ben Dooks <ben@simtec.co.uk>
* Vincent Sanders <vince@arm.linux.org.uk>
*
* S3C2410 CPU PLL tables
*
* 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/kernel.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/list.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <plat/cpu.h>
#include <plat/cpu-freq-core.h>
static struct cpufreq_frequency_table pll_vals_12MHz[] = {
{ .frequency = 34000000, .index = PLLVAL(82, 2, 3), },
{ .frequency = 45000000, .index = PLLVAL(82, 1, 3), },
{ .frequency = 51000000, .index = PLLVAL(161, 3, 3), },
{ .frequency = 48000000, .index = PLLVAL(120, 2, 3), },
{ .frequency = 56000000, .index = PLLVAL(142, 2, 3), },
{ .frequency = 68000000, .index = PLLVAL(82, 2, 2), },
{ .frequency = 79000000, .index = PLLVAL(71, 1, 2), },
{ .frequency = 85000000, .index = PLLVAL(105, 2, 2), },
{ .frequency = 90000000, .index = PLLVAL(112, 2, 2), },
{ .frequency = 101000000, .index = PLLVAL(127, 2, 2), },
{ .frequency = 113000000, .index = PLLVAL(105, 1, 2), },
{ .frequency = 118000000, .index = PLLVAL(150, 2, 2), },
{ .frequency = 124000000, .index = PLLVAL(116, 1, 2), },
{ .frequency = 135000000, .index = PLLVAL(82, 2, 1), },
{ .frequency = 147000000, .index = PLLVAL(90, 2, 1), },
{ .frequency = 152000000, .index = PLLVAL(68, 1, 1), },
{ .frequency = 158000000, .index = PLLVAL(71, 1, 1), },
{ .frequency = 170000000, .index = PLLVAL(77, 1, 1), },
{ .frequency = 180000000, .index = PLLVAL(82, 1, 1), },
{ .frequency = 186000000, .index = PLLVAL(85, 1, 1), },
{ .frequency = 192000000, .index = PLLVAL(88, 1, 1), },
{ .frequency = 203000000, .index = PLLVAL(161, 3, 1), },
/* 2410A extras */
{ .frequency = 210000000, .index = PLLVAL(132, 2, 1), },
{ .frequency = 226000000, .index = PLLVAL(105, 1, 1), },
{ .frequency = 266000000, .index = PLLVAL(125, 1, 1), },
{ .frequency = 268000000, .index = PLLVAL(126, 1, 1), },
{ .frequency = 270000000, .index = PLLVAL(127, 1, 1), },
};
static int s3c2410_plls_add(struct device *dev, struct subsys_interface *sif)
{
return s3c_plltab_register(pll_vals_12MHz, ARRAY_SIZE(pll_vals_12MHz));
}
static struct subsys_interface s3c2410_plls_interface = {
.name = "s3c2410_plls",
.subsys = &s3c2410_subsys,
.add_dev = s3c2410_plls_add,
};
static int __init s3c2410_pll_init(void)
{
return subsys_interface_register(&s3c2410_plls_interface);
}
arch_initcall(s3c2410_pll_init);
static struct subsys_interface s3c2410a_plls_interface = {
.name = "s3c2410a_plls",
.subsys = &s3c2410a_subsys,
.add_dev = s3c2410_plls_add,
};
static int __init s3c2410a_pll_init(void)
{
return subsys_interface_register(&s3c2410a_plls_interface);
}
arch_initcall(s3c2410a_pll_init);
| gpl-2.0 |
crpalmer/android_kernel_samsung_msm8974 | arch/arm/mach-s3c2412/cpu-freq.c | 5070 | 6231 | /* linux/arch/arm/mach-s3c2412/cpu-freq.c
*
* Copyright 2008 Simtec Electronics
* http://armlinux.simtec.co.uk/
* Ben Dooks <ben@simtec.co.uk>
*
* S3C2412 CPU Frequency scalling
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/cpufreq.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/io.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <mach/regs-clock.h>
#include <mach/regs-s3c2412-mem.h>
#include <plat/cpu.h>
#include <plat/clock.h>
#include <plat/cpu-freq-core.h>
/* our clock resources. */
static struct clk *xtal;
static struct clk *fclk;
static struct clk *hclk;
static struct clk *armclk;
/* HDIV: 1, 2, 3, 4, 6, 8 */
static int s3c2412_cpufreq_calcdivs(struct s3c_cpufreq_config *cfg)
{
unsigned int hdiv, pdiv, armdiv, dvs;
unsigned long hclk, fclk, armclk, armdiv_clk;
unsigned long hclk_max;
fclk = cfg->freq.fclk;
armclk = cfg->freq.armclk;
hclk_max = cfg->max.hclk;
/* We can't run hclk above armclk as at the best we have to
* have armclk and hclk in dvs mode. */
if (hclk_max > armclk)
hclk_max = armclk;
s3c_freq_dbg("%s: fclk=%lu, armclk=%lu, hclk_max=%lu\n",
__func__, fclk, armclk, hclk_max);
s3c_freq_dbg("%s: want f=%lu, arm=%lu, h=%lu, p=%lu\n",
__func__, cfg->freq.fclk, cfg->freq.armclk,
cfg->freq.hclk, cfg->freq.pclk);
armdiv = fclk / armclk;
if (armdiv < 1)
armdiv = 1;
if (armdiv > 2)
armdiv = 2;
cfg->divs.arm_divisor = armdiv;
armdiv_clk = fclk / armdiv;
hdiv = armdiv_clk / hclk_max;
if (hdiv < 1)
hdiv = 1;
cfg->freq.hclk = hclk = armdiv_clk / hdiv;
/* set dvs depending on whether we reached armclk or not. */
cfg->divs.dvs = dvs = armclk < armdiv_clk;
/* update the actual armclk we achieved. */
cfg->freq.armclk = dvs ? hclk : armdiv_clk;
s3c_freq_dbg("%s: armclk %lu, hclk %lu, armdiv %d, hdiv %d, dvs %d\n",
__func__, armclk, hclk, armdiv, hdiv, cfg->divs.dvs);
if (hdiv > 4)
goto invalid;
pdiv = (hclk > cfg->max.pclk) ? 2 : 1;
if ((hclk / pdiv) > cfg->max.pclk)
pdiv++;
cfg->freq.pclk = hclk / pdiv;
s3c_freq_dbg("%s: pdiv %d\n", __func__, pdiv);
if (pdiv > 2)
goto invalid;
pdiv *= hdiv;
/* store the result, and then return */
cfg->divs.h_divisor = hdiv * armdiv;
cfg->divs.p_divisor = pdiv * armdiv;
return 0;
invalid:
return -EINVAL;
}
static void s3c2412_cpufreq_setdivs(struct s3c_cpufreq_config *cfg)
{
unsigned long clkdiv;
unsigned long olddiv;
olddiv = clkdiv = __raw_readl(S3C2410_CLKDIVN);
/* clear off current clock info */
clkdiv &= ~S3C2412_CLKDIVN_ARMDIVN;
clkdiv &= ~S3C2412_CLKDIVN_HDIVN_MASK;
clkdiv &= ~S3C2412_CLKDIVN_PDIVN;
if (cfg->divs.arm_divisor == 2)
clkdiv |= S3C2412_CLKDIVN_ARMDIVN;
clkdiv |= ((cfg->divs.h_divisor / cfg->divs.arm_divisor) - 1);
if (cfg->divs.p_divisor != cfg->divs.h_divisor)
clkdiv |= S3C2412_CLKDIVN_PDIVN;
s3c_freq_dbg("%s: div %08lx => %08lx\n", __func__, olddiv, clkdiv);
__raw_writel(clkdiv, S3C2410_CLKDIVN);
clk_set_parent(armclk, cfg->divs.dvs ? hclk : fclk);
}
static void s3c2412_cpufreq_setrefresh(struct s3c_cpufreq_config *cfg)
{
struct s3c_cpufreq_board *board = cfg->board;
unsigned long refresh;
s3c_freq_dbg("%s: refresh %u ns, hclk %lu\n", __func__,
board->refresh, cfg->freq.hclk);
/* Reduce both the refresh time (in ns) and the frequency (in MHz)
* by 10 each to ensure that we do not overflow 32 bit numbers. This
* should work for HCLK up to 133MHz and refresh period up to 30usec.
*/
refresh = (board->refresh / 10);
refresh *= (cfg->freq.hclk / 100);
refresh /= (1 * 1000 * 1000); /* 10^6 */
s3c_freq_dbg("%s: setting refresh 0x%08lx\n", __func__, refresh);
__raw_writel(refresh, S3C2412_REFRESH);
}
/* set the default cpu frequency information, based on an 200MHz part
* as we have no other way of detecting the speed rating in software.
*/
static struct s3c_cpufreq_info s3c2412_cpufreq_info = {
.max = {
.fclk = 200000000,
.hclk = 100000000,
.pclk = 50000000,
},
.latency = 5000000, /* 5ms */
.locktime_m = 150,
.locktime_u = 150,
.locktime_bits = 16,
.name = "s3c2412",
.set_refresh = s3c2412_cpufreq_setrefresh,
.set_divs = s3c2412_cpufreq_setdivs,
.calc_divs = s3c2412_cpufreq_calcdivs,
.calc_iotiming = s3c2412_iotiming_calc,
.set_iotiming = s3c2412_iotiming_set,
.get_iotiming = s3c2412_iotiming_get,
.resume_clocks = s3c2412_setup_clocks,
.debug_io_show = s3c_cpufreq_debugfs_call(s3c2412_iotiming_debugfs),
};
static int s3c2412_cpufreq_add(struct device *dev,
struct subsys_interface *sif)
{
unsigned long fclk_rate;
hclk = clk_get(NULL, "hclk");
if (IS_ERR(hclk)) {
printk(KERN_ERR "%s: cannot find hclk clock\n", __func__);
return -ENOENT;
}
fclk = clk_get(NULL, "fclk");
if (IS_ERR(fclk)) {
printk(KERN_ERR "%s: cannot find fclk clock\n", __func__);
goto err_fclk;
}
fclk_rate = clk_get_rate(fclk);
if (fclk_rate > 200000000) {
printk(KERN_INFO
"%s: fclk %ld MHz, assuming 266MHz capable part\n",
__func__, fclk_rate / 1000000);
s3c2412_cpufreq_info.max.fclk = 266000000;
s3c2412_cpufreq_info.max.hclk = 133000000;
s3c2412_cpufreq_info.max.pclk = 66000000;
}
armclk = clk_get(NULL, "armclk");
if (IS_ERR(armclk)) {
printk(KERN_ERR "%s: cannot find arm clock\n", __func__);
goto err_armclk;
}
xtal = clk_get(NULL, "xtal");
if (IS_ERR(xtal)) {
printk(KERN_ERR "%s: cannot find xtal clock\n", __func__);
goto err_xtal;
}
return s3c_cpufreq_register(&s3c2412_cpufreq_info);
err_xtal:
clk_put(armclk);
err_armclk:
clk_put(fclk);
err_fclk:
clk_put(hclk);
return -ENOENT;
}
static struct subsys_interface s3c2412_cpufreq_interface = {
.name = "s3c2412_cpufreq",
.subsys = &s3c2412_subsys,
.add_dev = s3c2412_cpufreq_add,
};
static int s3c2412_cpufreq_init(void)
{
return subsys_interface_register(&s3c2412_cpufreq_interface);
}
arch_initcall(s3c2412_cpufreq_init);
| gpl-2.0 |
TeamJB/kernel_htc_t6 | drivers/i2c/busses/i2c-highlander.c | 5070 | 11169 | /*
* Renesas Solutions Highlander FPGA I2C/SMBus support.
*
* Supported devices: R0P7780LC0011RL, R0P7785LC0011RL
*
* Copyright (C) 2008 Paul Mundt
* Copyright (C) 2008 Renesas Solutions Corp.
* Copyright (C) 2008 Atom Create Engineering Co., Ltd.
*
* This file is subject to the terms and conditions of the GNU General
* Public License version 2. See the file "COPYING" in the main directory
* of this archive for more details.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/i2c.h>
#include <linux/platform_device.h>
#include <linux/completion.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <linux/slab.h>
#define SMCR 0x00
#define SMCR_START (1 << 0)
#define SMCR_IRIC (1 << 1)
#define SMCR_BBSY (1 << 2)
#define SMCR_ACKE (1 << 3)
#define SMCR_RST (1 << 4)
#define SMCR_IEIC (1 << 6)
#define SMSMADR 0x02
#define SMMR 0x04
#define SMMR_MODE0 (1 << 0)
#define SMMR_MODE1 (1 << 1)
#define SMMR_CAP (1 << 3)
#define SMMR_TMMD (1 << 4)
#define SMMR_SP (1 << 7)
#define SMSADR 0x06
#define SMTRDR 0x46
struct highlander_i2c_dev {
struct device *dev;
void __iomem *base;
struct i2c_adapter adapter;
struct completion cmd_complete;
unsigned long last_read_time;
int irq;
u8 *buf;
size_t buf_len;
};
static bool iic_force_poll, iic_force_normal;
static int iic_timeout = 1000, iic_read_delay;
static inline void highlander_i2c_irq_enable(struct highlander_i2c_dev *dev)
{
iowrite16(ioread16(dev->base + SMCR) | SMCR_IEIC, dev->base + SMCR);
}
static inline void highlander_i2c_irq_disable(struct highlander_i2c_dev *dev)
{
iowrite16(ioread16(dev->base + SMCR) & ~SMCR_IEIC, dev->base + SMCR);
}
static inline void highlander_i2c_start(struct highlander_i2c_dev *dev)
{
iowrite16(ioread16(dev->base + SMCR) | SMCR_START, dev->base + SMCR);
}
static inline void highlander_i2c_done(struct highlander_i2c_dev *dev)
{
iowrite16(ioread16(dev->base + SMCR) | SMCR_IRIC, dev->base + SMCR);
}
static void highlander_i2c_setup(struct highlander_i2c_dev *dev)
{
u16 smmr;
smmr = ioread16(dev->base + SMMR);
smmr |= SMMR_TMMD;
if (iic_force_normal)
smmr &= ~SMMR_SP;
else
smmr |= SMMR_SP;
iowrite16(smmr, dev->base + SMMR);
}
static void smbus_write_data(u8 *src, u16 *dst, int len)
{
for (; len > 1; len -= 2) {
*dst++ = be16_to_cpup((__be16 *)src);
src += 2;
}
if (len)
*dst = *src << 8;
}
static void smbus_read_data(u16 *src, u8 *dst, int len)
{
for (; len > 1; len -= 2) {
*(__be16 *)dst = cpu_to_be16p(src++);
dst += 2;
}
if (len)
*dst = *src >> 8;
}
static void highlander_i2c_command(struct highlander_i2c_dev *dev,
u8 command, int len)
{
unsigned int i;
u16 cmd = (command << 8) | command;
for (i = 0; i < len; i += 2) {
if (len - i == 1)
cmd = command << 8;
iowrite16(cmd, dev->base + SMSADR + i);
dev_dbg(dev->dev, "command data[%x] 0x%04x\n", i/2, cmd);
}
}
static int highlander_i2c_wait_for_bbsy(struct highlander_i2c_dev *dev)
{
unsigned long timeout;
timeout = jiffies + msecs_to_jiffies(iic_timeout);
while (ioread16(dev->base + SMCR) & SMCR_BBSY) {
if (time_after(jiffies, timeout)) {
dev_warn(dev->dev, "timeout waiting for bus ready\n");
return -ETIMEDOUT;
}
msleep(1);
}
return 0;
}
static int highlander_i2c_reset(struct highlander_i2c_dev *dev)
{
iowrite16(ioread16(dev->base + SMCR) | SMCR_RST, dev->base + SMCR);
return highlander_i2c_wait_for_bbsy(dev);
}
static int highlander_i2c_wait_for_ack(struct highlander_i2c_dev *dev)
{
u16 tmp = ioread16(dev->base + SMCR);
if ((tmp & (SMCR_IRIC | SMCR_ACKE)) == SMCR_ACKE) {
dev_warn(dev->dev, "ack abnormality\n");
return highlander_i2c_reset(dev);
}
return 0;
}
static irqreturn_t highlander_i2c_irq(int irq, void *dev_id)
{
struct highlander_i2c_dev *dev = dev_id;
highlander_i2c_done(dev);
complete(&dev->cmd_complete);
return IRQ_HANDLED;
}
static void highlander_i2c_poll(struct highlander_i2c_dev *dev)
{
unsigned long timeout;
u16 smcr;
timeout = jiffies + msecs_to_jiffies(iic_timeout);
for (;;) {
smcr = ioread16(dev->base + SMCR);
/*
* Don't bother checking ACKE here, this and the reset
* are handled in highlander_i2c_wait_xfer_done() when
* waiting for the ACK.
*/
if (smcr & SMCR_IRIC)
return;
if (time_after(jiffies, timeout))
break;
cpu_relax();
cond_resched();
}
dev_err(dev->dev, "polling timed out\n");
}
static inline int highlander_i2c_wait_xfer_done(struct highlander_i2c_dev *dev)
{
if (dev->irq)
wait_for_completion_timeout(&dev->cmd_complete,
msecs_to_jiffies(iic_timeout));
else
/* busy looping, the IRQ of champions */
highlander_i2c_poll(dev);
return highlander_i2c_wait_for_ack(dev);
}
static int highlander_i2c_read(struct highlander_i2c_dev *dev)
{
int i, cnt;
u16 data[16];
if (highlander_i2c_wait_for_bbsy(dev))
return -EAGAIN;
highlander_i2c_start(dev);
if (highlander_i2c_wait_xfer_done(dev)) {
dev_err(dev->dev, "Arbitration loss\n");
return -EAGAIN;
}
/*
* The R0P7780LC0011RL FPGA needs a significant delay between
* data read cycles, otherwise the transceiver gets confused and
* garbage is returned when the read is subsequently aborted.
*
* It is not sufficient to wait for BBSY.
*
* While this generally only applies to the older SH7780-based
* Highlanders, the same issue can be observed on SH7785 ones,
* albeit less frequently. SH7780-based Highlanders may need
* this to be as high as 1000 ms.
*/
if (iic_read_delay && time_before(jiffies, dev->last_read_time +
msecs_to_jiffies(iic_read_delay)))
msleep(jiffies_to_msecs((dev->last_read_time +
msecs_to_jiffies(iic_read_delay)) - jiffies));
cnt = (dev->buf_len + 1) >> 1;
for (i = 0; i < cnt; i++) {
data[i] = ioread16(dev->base + SMTRDR + (i * sizeof(u16)));
dev_dbg(dev->dev, "read data[%x] 0x%04x\n", i, data[i]);
}
smbus_read_data(data, dev->buf, dev->buf_len);
dev->last_read_time = jiffies;
return 0;
}
static int highlander_i2c_write(struct highlander_i2c_dev *dev)
{
int i, cnt;
u16 data[16];
smbus_write_data(dev->buf, data, dev->buf_len);
cnt = (dev->buf_len + 1) >> 1;
for (i = 0; i < cnt; i++) {
iowrite16(data[i], dev->base + SMTRDR + (i * sizeof(u16)));
dev_dbg(dev->dev, "write data[%x] 0x%04x\n", i, data[i]);
}
if (highlander_i2c_wait_for_bbsy(dev))
return -EAGAIN;
highlander_i2c_start(dev);
return highlander_i2c_wait_xfer_done(dev);
}
static int highlander_i2c_smbus_xfer(struct i2c_adapter *adap, u16 addr,
unsigned short flags, char read_write,
u8 command, int size,
union i2c_smbus_data *data)
{
struct highlander_i2c_dev *dev = i2c_get_adapdata(adap);
u16 tmp;
init_completion(&dev->cmd_complete);
dev_dbg(dev->dev, "addr %04x, command %02x, read_write %d, size %d\n",
addr, command, read_write, size);
/*
* Set up the buffer and transfer size
*/
switch (size) {
case I2C_SMBUS_BYTE_DATA:
dev->buf = &data->byte;
dev->buf_len = 1;
break;
case I2C_SMBUS_I2C_BLOCK_DATA:
dev->buf = &data->block[1];
dev->buf_len = data->block[0];
break;
default:
dev_err(dev->dev, "unsupported command %d\n", size);
return -EINVAL;
}
/*
* Encode the mode setting
*/
tmp = ioread16(dev->base + SMMR);
tmp &= ~(SMMR_MODE0 | SMMR_MODE1);
switch (dev->buf_len) {
case 1:
/* default */
break;
case 8:
tmp |= SMMR_MODE0;
break;
case 16:
tmp |= SMMR_MODE1;
break;
case 32:
tmp |= (SMMR_MODE0 | SMMR_MODE1);
break;
default:
dev_err(dev->dev, "unsupported xfer size %d\n", dev->buf_len);
return -EINVAL;
}
iowrite16(tmp, dev->base + SMMR);
/* Ensure we're in a sane state */
highlander_i2c_done(dev);
/* Set slave address */
iowrite16((addr << 1) | read_write, dev->base + SMSMADR);
highlander_i2c_command(dev, command, dev->buf_len);
if (read_write == I2C_SMBUS_READ)
return highlander_i2c_read(dev);
else
return highlander_i2c_write(dev);
}
static u32 highlander_i2c_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_SMBUS_I2C_BLOCK;
}
static const struct i2c_algorithm highlander_i2c_algo = {
.smbus_xfer = highlander_i2c_smbus_xfer,
.functionality = highlander_i2c_func,
};
static int __devinit highlander_i2c_probe(struct platform_device *pdev)
{
struct highlander_i2c_dev *dev;
struct i2c_adapter *adap;
struct resource *res;
int ret;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (unlikely(!res)) {
dev_err(&pdev->dev, "no mem resource\n");
return -ENODEV;
}
dev = kzalloc(sizeof(struct highlander_i2c_dev), GFP_KERNEL);
if (unlikely(!dev))
return -ENOMEM;
dev->base = ioremap_nocache(res->start, resource_size(res));
if (unlikely(!dev->base)) {
ret = -ENXIO;
goto err;
}
dev->dev = &pdev->dev;
platform_set_drvdata(pdev, dev);
dev->irq = platform_get_irq(pdev, 0);
if (iic_force_poll)
dev->irq = 0;
if (dev->irq) {
ret = request_irq(dev->irq, highlander_i2c_irq, 0,
pdev->name, dev);
if (unlikely(ret))
goto err_unmap;
highlander_i2c_irq_enable(dev);
} else {
dev_notice(&pdev->dev, "no IRQ, using polling mode\n");
highlander_i2c_irq_disable(dev);
}
dev->last_read_time = jiffies; /* initial read jiffies */
highlander_i2c_setup(dev);
adap = &dev->adapter;
i2c_set_adapdata(adap, dev);
adap->owner = THIS_MODULE;
adap->class = I2C_CLASS_HWMON;
strlcpy(adap->name, "HL FPGA I2C adapter", sizeof(adap->name));
adap->algo = &highlander_i2c_algo;
adap->dev.parent = &pdev->dev;
adap->nr = pdev->id;
/*
* Reset the adapter
*/
ret = highlander_i2c_reset(dev);
if (unlikely(ret)) {
dev_err(&pdev->dev, "controller didn't come up\n");
goto err_free_irq;
}
ret = i2c_add_numbered_adapter(adap);
if (unlikely(ret)) {
dev_err(&pdev->dev, "failure adding adapter\n");
goto err_free_irq;
}
return 0;
err_free_irq:
if (dev->irq)
free_irq(dev->irq, dev);
err_unmap:
iounmap(dev->base);
err:
kfree(dev);
platform_set_drvdata(pdev, NULL);
return ret;
}
static int __devexit highlander_i2c_remove(struct platform_device *pdev)
{
struct highlander_i2c_dev *dev = platform_get_drvdata(pdev);
i2c_del_adapter(&dev->adapter);
if (dev->irq)
free_irq(dev->irq, dev);
iounmap(dev->base);
kfree(dev);
platform_set_drvdata(pdev, NULL);
return 0;
}
static struct platform_driver highlander_i2c_driver = {
.driver = {
.name = "i2c-highlander",
.owner = THIS_MODULE,
},
.probe = highlander_i2c_probe,
.remove = __devexit_p(highlander_i2c_remove),
};
module_platform_driver(highlander_i2c_driver);
MODULE_AUTHOR("Paul Mundt");
MODULE_DESCRIPTION("Renesas Highlander FPGA I2C/SMBus adapter");
MODULE_LICENSE("GPL v2");
module_param(iic_force_poll, bool, 0);
module_param(iic_force_normal, bool, 0);
module_param(iic_timeout, int, 0);
module_param(iic_read_delay, int, 0);
MODULE_PARM_DESC(iic_force_poll, "Force polling mode");
MODULE_PARM_DESC(iic_force_normal,
"Force normal mode (100 kHz), default is fast mode (400 kHz)");
MODULE_PARM_DESC(iic_timeout, "Set timeout value in msecs (default 1000 ms)");
MODULE_PARM_DESC(iic_read_delay,
"Delay between data read cycles (default 0 ms)");
| gpl-2.0 |
bluechiptechnology/Rx3_linux_3.0.35_4.0.0 | drivers/scsi/arm/oak.c | 5070 | 4783 | /*
* Oak Generic NCR5380 driver
*
* Copyright 1995-2002, Russell King
*/
#include <linux/module.h>
#include <linux/signal.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <linux/blkdev.h>
#include <linux/init.h>
#include <asm/ecard.h>
#include <asm/io.h>
#include <asm/system.h>
#include "../scsi.h"
#include <scsi/scsi_host.h>
#define AUTOSENSE
/*#define PSEUDO_DMA*/
#define OAKSCSI_PUBLIC_RELEASE 1
#define priv(host) ((struct NCR5380_hostdata *)(host)->hostdata)
#define NCR5380_local_declare() void __iomem *_base
#define NCR5380_setup(host) _base = priv(host)->base
#define NCR5380_read(reg) readb(_base + ((reg) << 2))
#define NCR5380_write(reg, value) writeb(value, _base + ((reg) << 2))
#define NCR5380_intr oakscsi_intr
#define NCR5380_queue_command oakscsi_queue_command
#define NCR5380_proc_info oakscsi_proc_info
#define NCR5380_implementation_fields \
void __iomem *base
#define BOARD_NORMAL 0
#define BOARD_NCR53C400 1
#include "../NCR5380.h"
#undef START_DMA_INITIATOR_RECEIVE_REG
#define START_DMA_INITIATOR_RECEIVE_REG (128 + 7)
const char * oakscsi_info (struct Scsi_Host *spnt)
{
return "";
}
#define STAT ((128 + 16) << 2)
#define DATA ((128 + 8) << 2)
static inline int NCR5380_pwrite(struct Scsi_Host *instance, unsigned char *addr,
int len)
{
void __iomem *base = priv(instance)->base;
printk("writing %p len %d\n",addr, len);
if(!len) return -1;
while(1)
{
int status;
while (((status = readw(base + STAT)) & 0x100)==0);
}
}
static inline int NCR5380_pread(struct Scsi_Host *instance, unsigned char *addr,
int len)
{
void __iomem *base = priv(instance)->base;
printk("reading %p len %d\n", addr, len);
while(len > 0)
{
unsigned int status, timeout;
unsigned long b;
timeout = 0x01FFFFFF;
while (((status = readw(base + STAT)) & 0x100)==0)
{
timeout--;
if(status & 0x200 || !timeout)
{
printk("status = %08X\n", status);
return 1;
}
}
if(len >= 128)
{
readsw(base + DATA, addr, 128);
addr += 128;
len -= 128;
}
else
{
b = (unsigned long) readw(base + DATA);
*addr ++ = b;
len -= 1;
if(len)
*addr ++ = b>>8;
len -= 1;
}
}
return 0;
}
#undef STAT
#undef DATA
#include "../NCR5380.c"
static struct scsi_host_template oakscsi_template = {
.module = THIS_MODULE,
.proc_info = oakscsi_proc_info,
.name = "Oak 16-bit SCSI",
.info = oakscsi_info,
.queuecommand = oakscsi_queue_command,
.eh_abort_handler = NCR5380_abort,
.eh_bus_reset_handler = NCR5380_bus_reset,
.can_queue = 16,
.this_id = 7,
.sg_tablesize = SG_ALL,
.cmd_per_lun = 2,
.use_clustering = DISABLE_CLUSTERING,
.proc_name = "oakscsi",
};
static int __devinit
oakscsi_probe(struct expansion_card *ec, const struct ecard_id *id)
{
struct Scsi_Host *host;
int ret = -ENOMEM;
ret = ecard_request_resources(ec);
if (ret)
goto out;
host = scsi_host_alloc(&oakscsi_template, sizeof(struct NCR5380_hostdata));
if (!host) {
ret = -ENOMEM;
goto release;
}
priv(host)->base = ioremap(ecard_resource_start(ec, ECARD_RES_MEMC),
ecard_resource_len(ec, ECARD_RES_MEMC));
if (!priv(host)->base) {
ret = -ENOMEM;
goto unreg;
}
host->irq = IRQ_NONE;
host->n_io_port = 255;
NCR5380_init(host, 0);
printk("scsi%d: at port 0x%08lx irqs disabled",
host->host_no, host->io_port);
printk(" options CAN_QUEUE=%d CMD_PER_LUN=%d release=%d",
host->can_queue, host->cmd_per_lun, OAKSCSI_PUBLIC_RELEASE);
printk("\nscsi%d:", host->host_no);
NCR5380_print_options(host);
printk("\n");
ret = scsi_add_host(host, &ec->dev);
if (ret)
goto out_unmap;
scsi_scan_host(host);
goto out;
out_unmap:
iounmap(priv(host)->base);
unreg:
scsi_host_put(host);
release:
ecard_release_resources(ec);
out:
return ret;
}
static void __devexit oakscsi_remove(struct expansion_card *ec)
{
struct Scsi_Host *host = ecard_get_drvdata(ec);
ecard_set_drvdata(ec, NULL);
scsi_remove_host(host);
NCR5380_exit(host);
iounmap(priv(host)->base);
scsi_host_put(host);
ecard_release_resources(ec);
}
static const struct ecard_id oakscsi_cids[] = {
{ MANU_OAK, PROD_OAK_SCSI },
{ 0xffff, 0xffff }
};
static struct ecard_driver oakscsi_driver = {
.probe = oakscsi_probe,
.remove = __devexit_p(oakscsi_remove),
.id_table = oakscsi_cids,
.drv = {
.name = "oakscsi",
},
};
static int __init oakscsi_init(void)
{
return ecard_register_driver(&oakscsi_driver);
}
static void __exit oakscsi_exit(void)
{
ecard_remove_driver(&oakscsi_driver);
}
module_init(oakscsi_init);
module_exit(oakscsi_exit);
MODULE_AUTHOR("Russell King");
MODULE_DESCRIPTION("Oak SCSI driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
NoelMacwan/android_kernel_sony_msm8928 | arch/arm/mach-s3c2440/s3c2440-cpufreq.c | 5070 | 7338 | /* linux/arch/arm/plat-s3c24xx/s3c2440-cpufreq.c
*
* Copyright (c) 2006-2009 Simtec Electronics
* http://armlinux.simtec.co.uk/
* Ben Dooks <ben@simtec.co.uk>
* Vincent Sanders <vince@simtec.co.uk>
*
* S3C2440/S3C2442 CPU Frequency scaling
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/cpufreq.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <mach/regs-clock.h>
#include <plat/cpu.h>
#include <plat/cpu-freq-core.h>
#include <plat/clock.h>
static struct clk *xtal;
static struct clk *fclk;
static struct clk *hclk;
static struct clk *armclk;
/* HDIV: 1, 2, 3, 4, 6, 8 */
static inline int within_khz(unsigned long a, unsigned long b)
{
long diff = a - b;
return (diff >= -1000 && diff <= 1000);
}
/**
* s3c2440_cpufreq_calcdivs - calculate divider settings
* @cfg: The cpu frequency settings.
*
* Calcualte the divider values for the given frequency settings
* specified in @cfg. The values are stored in @cfg for later use
* by the relevant set routine if the request settings can be reached.
*/
int s3c2440_cpufreq_calcdivs(struct s3c_cpufreq_config *cfg)
{
unsigned int hdiv, pdiv;
unsigned long hclk, fclk, armclk;
unsigned long hclk_max;
fclk = cfg->freq.fclk;
armclk = cfg->freq.armclk;
hclk_max = cfg->max.hclk;
s3c_freq_dbg("%s: fclk is %lu, armclk %lu, max hclk %lu\n",
__func__, fclk, armclk, hclk_max);
if (armclk > fclk) {
printk(KERN_WARNING "%s: armclk > fclk\n", __func__);
armclk = fclk;
}
/* if we are in DVS, we need HCLK to be <= ARMCLK */
if (armclk < fclk && armclk < hclk_max)
hclk_max = armclk;
for (hdiv = 1; hdiv < 9; hdiv++) {
if (hdiv == 5 || hdiv == 7)
hdiv++;
hclk = (fclk / hdiv);
if (hclk <= hclk_max || within_khz(hclk, hclk_max))
break;
}
s3c_freq_dbg("%s: hclk %lu, div %d\n", __func__, hclk, hdiv);
if (hdiv > 8)
goto invalid;
pdiv = (hclk > cfg->max.pclk) ? 2 : 1;
if ((hclk / pdiv) > cfg->max.pclk)
pdiv++;
s3c_freq_dbg("%s: pdiv %d\n", __func__, pdiv);
if (pdiv > 2)
goto invalid;
pdiv *= hdiv;
/* calculate a valid armclk */
if (armclk < hclk)
armclk = hclk;
/* if we're running armclk lower than fclk, this really means
* that the system should go into dvs mode, which means that
* armclk is connected to hclk. */
if (armclk < fclk) {
cfg->divs.dvs = 1;
armclk = hclk;
} else
cfg->divs.dvs = 0;
cfg->freq.armclk = armclk;
/* store the result, and then return */
cfg->divs.h_divisor = hdiv;
cfg->divs.p_divisor = pdiv;
return 0;
invalid:
return -EINVAL;
}
#define CAMDIVN_HCLK_HALF (S3C2440_CAMDIVN_HCLK3_HALF | \
S3C2440_CAMDIVN_HCLK4_HALF)
/**
* s3c2440_cpufreq_setdivs - set the cpu frequency divider settings
* @cfg: The cpu frequency settings.
*
* Set the divisors from the settings in @cfg, which where generated
* during the calculation phase by s3c2440_cpufreq_calcdivs().
*/
static void s3c2440_cpufreq_setdivs(struct s3c_cpufreq_config *cfg)
{
unsigned long clkdiv, camdiv;
s3c_freq_dbg("%s: divsiors: h=%d, p=%d\n", __func__,
cfg->divs.h_divisor, cfg->divs.p_divisor);
clkdiv = __raw_readl(S3C2410_CLKDIVN);
camdiv = __raw_readl(S3C2440_CAMDIVN);
clkdiv &= ~(S3C2440_CLKDIVN_HDIVN_MASK | S3C2440_CLKDIVN_PDIVN);
camdiv &= ~CAMDIVN_HCLK_HALF;
switch (cfg->divs.h_divisor) {
case 1:
clkdiv |= S3C2440_CLKDIVN_HDIVN_1;
break;
case 2:
clkdiv |= S3C2440_CLKDIVN_HDIVN_2;
break;
case 6:
camdiv |= S3C2440_CAMDIVN_HCLK3_HALF;
case 3:
clkdiv |= S3C2440_CLKDIVN_HDIVN_3_6;
break;
case 8:
camdiv |= S3C2440_CAMDIVN_HCLK4_HALF;
case 4:
clkdiv |= S3C2440_CLKDIVN_HDIVN_4_8;
break;
default:
BUG(); /* we don't expect to get here. */
}
if (cfg->divs.p_divisor != cfg->divs.h_divisor)
clkdiv |= S3C2440_CLKDIVN_PDIVN;
/* todo - set pclk. */
/* Write the divisors first with hclk intentionally halved so that
* when we write clkdiv we will under-frequency instead of over. We
* then make a short delay and remove the hclk halving if necessary.
*/
__raw_writel(camdiv | CAMDIVN_HCLK_HALF, S3C2440_CAMDIVN);
__raw_writel(clkdiv, S3C2410_CLKDIVN);
ndelay(20);
__raw_writel(camdiv, S3C2440_CAMDIVN);
clk_set_parent(armclk, cfg->divs.dvs ? hclk : fclk);
}
static int run_freq_for(unsigned long max_hclk, unsigned long fclk,
int *divs,
struct cpufreq_frequency_table *table,
size_t table_size)
{
unsigned long freq;
int index = 0;
int div;
for (div = *divs; div > 0; div = *divs++) {
freq = fclk / div;
if (freq > max_hclk && div != 1)
continue;
freq /= 1000; /* table is in kHz */
index = s3c_cpufreq_addfreq(table, index, table_size, freq);
if (index < 0)
break;
}
return index;
}
static int hclk_divs[] = { 1, 2, 3, 4, 6, 8, -1 };
static int s3c2440_cpufreq_calctable(struct s3c_cpufreq_config *cfg,
struct cpufreq_frequency_table *table,
size_t table_size)
{
int ret;
WARN_ON(cfg->info == NULL);
WARN_ON(cfg->board == NULL);
ret = run_freq_for(cfg->info->max.hclk,
cfg->info->max.fclk,
hclk_divs,
table, table_size);
s3c_freq_dbg("%s: returning %d\n", __func__, ret);
return ret;
}
struct s3c_cpufreq_info s3c2440_cpufreq_info = {
.max = {
.fclk = 400000000,
.hclk = 133333333,
.pclk = 66666666,
},
.locktime_m = 300,
.locktime_u = 300,
.locktime_bits = 16,
.name = "s3c244x",
.calc_iotiming = s3c2410_iotiming_calc,
.set_iotiming = s3c2410_iotiming_set,
.get_iotiming = s3c2410_iotiming_get,
.set_fvco = s3c2410_set_fvco,
.set_refresh = s3c2410_cpufreq_setrefresh,
.set_divs = s3c2440_cpufreq_setdivs,
.calc_divs = s3c2440_cpufreq_calcdivs,
.calc_freqtable = s3c2440_cpufreq_calctable,
.resume_clocks = s3c244x_setup_clocks,
.debug_io_show = s3c_cpufreq_debugfs_call(s3c2410_iotiming_debugfs),
};
static int s3c2440_cpufreq_add(struct device *dev,
struct subsys_interface *sif)
{
xtal = s3c_cpufreq_clk_get(NULL, "xtal");
hclk = s3c_cpufreq_clk_get(NULL, "hclk");
fclk = s3c_cpufreq_clk_get(NULL, "fclk");
armclk = s3c_cpufreq_clk_get(NULL, "armclk");
if (IS_ERR(xtal) || IS_ERR(hclk) || IS_ERR(fclk) || IS_ERR(armclk)) {
printk(KERN_ERR "%s: failed to get clocks\n", __func__);
return -ENOENT;
}
return s3c_cpufreq_register(&s3c2440_cpufreq_info);
}
static struct subsys_interface s3c2440_cpufreq_interface = {
.name = "s3c2440_cpufreq",
.subsys = &s3c2440_subsys,
.add_dev = s3c2440_cpufreq_add,
};
static int s3c2440_cpufreq_init(void)
{
return subsys_interface_register(&s3c2440_cpufreq_interface);
}
/* arch_initcall adds the clocks we need, so use subsys_initcall. */
subsys_initcall(s3c2440_cpufreq_init);
static struct subsys_interface s3c2442_cpufreq_interface = {
.name = "s3c2442_cpufreq",
.subsys = &s3c2442_subsys,
.add_dev = s3c2440_cpufreq_add,
};
static int s3c2442_cpufreq_init(void)
{
return subsys_interface_register(&s3c2442_cpufreq_interface);
}
subsys_initcall(s3c2442_cpufreq_init);
| gpl-2.0 |
andi34/android_kernel_oneplus_one | drivers/spi/spi-mpc52xx.c | 5070 | 14783 | /*
* MPC52xx SPI bus driver.
*
* Copyright (C) 2008 Secret Lab Technologies Ltd.
*
* This file is released under the GPLv2
*
* This is the driver for the MPC5200's dedicated SPI controller.
*
* Note: this driver does not support the MPC5200 PSC in SPI mode. For
* that driver see drivers/spi/mpc52xx_psc_spi.c
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/of_platform.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/spi/spi.h>
#include <linux/io.h>
#include <linux/of_gpio.h>
#include <linux/slab.h>
#include <asm/time.h>
#include <asm/mpc52xx.h>
MODULE_AUTHOR("Grant Likely <grant.likely@secretlab.ca>");
MODULE_DESCRIPTION("MPC52xx SPI (non-PSC) Driver");
MODULE_LICENSE("GPL");
/* Register offsets */
#define SPI_CTRL1 0x00
#define SPI_CTRL1_SPIE (1 << 7)
#define SPI_CTRL1_SPE (1 << 6)
#define SPI_CTRL1_MSTR (1 << 4)
#define SPI_CTRL1_CPOL (1 << 3)
#define SPI_CTRL1_CPHA (1 << 2)
#define SPI_CTRL1_SSOE (1 << 1)
#define SPI_CTRL1_LSBFE (1 << 0)
#define SPI_CTRL2 0x01
#define SPI_BRR 0x04
#define SPI_STATUS 0x05
#define SPI_STATUS_SPIF (1 << 7)
#define SPI_STATUS_WCOL (1 << 6)
#define SPI_STATUS_MODF (1 << 4)
#define SPI_DATA 0x09
#define SPI_PORTDATA 0x0d
#define SPI_DATADIR 0x10
/* FSM state return values */
#define FSM_STOP 0 /* Nothing more for the state machine to */
/* do. If something interesting happens */
/* then an IRQ will be received */
#define FSM_POLL 1 /* need to poll for completion, an IRQ is */
/* not expected */
#define FSM_CONTINUE 2 /* Keep iterating the state machine */
/* Driver internal data */
struct mpc52xx_spi {
struct spi_master *master;
void __iomem *regs;
int irq0; /* MODF irq */
int irq1; /* SPIF irq */
unsigned int ipb_freq;
/* Statistics; not used now, but will be reintroduced for debugfs */
int msg_count;
int wcol_count;
int wcol_ticks;
u32 wcol_tx_timestamp;
int modf_count;
int byte_count;
struct list_head queue; /* queue of pending messages */
spinlock_t lock;
struct work_struct work;
/* Details of current transfer (length, and buffer pointers) */
struct spi_message *message; /* current message */
struct spi_transfer *transfer; /* current transfer */
int (*state)(int irq, struct mpc52xx_spi *ms, u8 status, u8 data);
int len;
int timestamp;
u8 *rx_buf;
const u8 *tx_buf;
int cs_change;
int gpio_cs_count;
unsigned int *gpio_cs;
};
/*
* CS control function
*/
static void mpc52xx_spi_chipsel(struct mpc52xx_spi *ms, int value)
{
int cs;
if (ms->gpio_cs_count > 0) {
cs = ms->message->spi->chip_select;
gpio_set_value(ms->gpio_cs[cs], value ? 0 : 1);
} else
out_8(ms->regs + SPI_PORTDATA, value ? 0 : 0x08);
}
/*
* Start a new transfer. This is called both by the idle state
* for the first transfer in a message, and by the wait state when the
* previous transfer in a message is complete.
*/
static void mpc52xx_spi_start_transfer(struct mpc52xx_spi *ms)
{
ms->rx_buf = ms->transfer->rx_buf;
ms->tx_buf = ms->transfer->tx_buf;
ms->len = ms->transfer->len;
/* Activate the chip select */
if (ms->cs_change)
mpc52xx_spi_chipsel(ms, 1);
ms->cs_change = ms->transfer->cs_change;
/* Write out the first byte */
ms->wcol_tx_timestamp = get_tbl();
if (ms->tx_buf)
out_8(ms->regs + SPI_DATA, *ms->tx_buf++);
else
out_8(ms->regs + SPI_DATA, 0);
}
/* Forward declaration of state handlers */
static int mpc52xx_spi_fsmstate_transfer(int irq, struct mpc52xx_spi *ms,
u8 status, u8 data);
static int mpc52xx_spi_fsmstate_wait(int irq, struct mpc52xx_spi *ms,
u8 status, u8 data);
/*
* IDLE state
*
* No transfers are in progress; if another transfer is pending then retrieve
* it and kick it off. Otherwise, stop processing the state machine
*/
static int
mpc52xx_spi_fsmstate_idle(int irq, struct mpc52xx_spi *ms, u8 status, u8 data)
{
struct spi_device *spi;
int spr, sppr;
u8 ctrl1;
if (status && (irq != NO_IRQ))
dev_err(&ms->master->dev, "spurious irq, status=0x%.2x\n",
status);
/* Check if there is another transfer waiting. */
if (list_empty(&ms->queue))
return FSM_STOP;
/* get the head of the queue */
ms->message = list_first_entry(&ms->queue, struct spi_message, queue);
list_del_init(&ms->message->queue);
/* Setup the controller parameters */
ctrl1 = SPI_CTRL1_SPIE | SPI_CTRL1_SPE | SPI_CTRL1_MSTR;
spi = ms->message->spi;
if (spi->mode & SPI_CPHA)
ctrl1 |= SPI_CTRL1_CPHA;
if (spi->mode & SPI_CPOL)
ctrl1 |= SPI_CTRL1_CPOL;
if (spi->mode & SPI_LSB_FIRST)
ctrl1 |= SPI_CTRL1_LSBFE;
out_8(ms->regs + SPI_CTRL1, ctrl1);
/* Setup the controller speed */
/* minimum divider is '2'. Also, add '1' to force rounding the
* divider up. */
sppr = ((ms->ipb_freq / ms->message->spi->max_speed_hz) + 1) >> 1;
spr = 0;
if (sppr < 1)
sppr = 1;
while (((sppr - 1) & ~0x7) != 0) {
sppr = (sppr + 1) >> 1; /* add '1' to force rounding up */
spr++;
}
sppr--; /* sppr quantity in register is offset by 1 */
if (spr > 7) {
/* Don't overrun limits of SPI baudrate register */
spr = 7;
sppr = 7;
}
out_8(ms->regs + SPI_BRR, sppr << 4 | spr); /* Set speed */
ms->cs_change = 1;
ms->transfer = container_of(ms->message->transfers.next,
struct spi_transfer, transfer_list);
mpc52xx_spi_start_transfer(ms);
ms->state = mpc52xx_spi_fsmstate_transfer;
return FSM_CONTINUE;
}
/*
* TRANSFER state
*
* In the middle of a transfer. If the SPI core has completed processing
* a byte, then read out the received data and write out the next byte
* (unless this transfer is finished; in which case go on to the wait
* state)
*/
static int mpc52xx_spi_fsmstate_transfer(int irq, struct mpc52xx_spi *ms,
u8 status, u8 data)
{
if (!status)
return ms->irq0 ? FSM_STOP : FSM_POLL;
if (status & SPI_STATUS_WCOL) {
/* The SPI controller is stoopid. At slower speeds, it may
* raise the SPIF flag before the state machine is actually
* finished, which causes a collision (internal to the state
* machine only). The manual recommends inserting a delay
* between receiving the interrupt and sending the next byte,
* but it can also be worked around simply by retrying the
* transfer which is what we do here. */
ms->wcol_count++;
ms->wcol_ticks += get_tbl() - ms->wcol_tx_timestamp;
ms->wcol_tx_timestamp = get_tbl();
data = 0;
if (ms->tx_buf)
data = *(ms->tx_buf - 1);
out_8(ms->regs + SPI_DATA, data); /* try again */
return FSM_CONTINUE;
} else if (status & SPI_STATUS_MODF) {
ms->modf_count++;
dev_err(&ms->master->dev, "mode fault\n");
mpc52xx_spi_chipsel(ms, 0);
ms->message->status = -EIO;
ms->message->complete(ms->message->context);
ms->state = mpc52xx_spi_fsmstate_idle;
return FSM_CONTINUE;
}
/* Read data out of the spi device */
ms->byte_count++;
if (ms->rx_buf)
*ms->rx_buf++ = data;
/* Is the transfer complete? */
ms->len--;
if (ms->len == 0) {
ms->timestamp = get_tbl();
ms->timestamp += ms->transfer->delay_usecs * tb_ticks_per_usec;
ms->state = mpc52xx_spi_fsmstate_wait;
return FSM_CONTINUE;
}
/* Write out the next byte */
ms->wcol_tx_timestamp = get_tbl();
if (ms->tx_buf)
out_8(ms->regs + SPI_DATA, *ms->tx_buf++);
else
out_8(ms->regs + SPI_DATA, 0);
return FSM_CONTINUE;
}
/*
* WAIT state
*
* A transfer has completed; need to wait for the delay period to complete
* before starting the next transfer
*/
static int
mpc52xx_spi_fsmstate_wait(int irq, struct mpc52xx_spi *ms, u8 status, u8 data)
{
if (status && irq)
dev_err(&ms->master->dev, "spurious irq, status=0x%.2x\n",
status);
if (((int)get_tbl()) - ms->timestamp < 0)
return FSM_POLL;
ms->message->actual_length += ms->transfer->len;
/* Check if there is another transfer in this message. If there
* aren't then deactivate CS, notify sender, and drop back to idle
* to start the next message. */
if (ms->transfer->transfer_list.next == &ms->message->transfers) {
ms->msg_count++;
mpc52xx_spi_chipsel(ms, 0);
ms->message->status = 0;
ms->message->complete(ms->message->context);
ms->state = mpc52xx_spi_fsmstate_idle;
return FSM_CONTINUE;
}
/* There is another transfer; kick it off */
if (ms->cs_change)
mpc52xx_spi_chipsel(ms, 0);
ms->transfer = container_of(ms->transfer->transfer_list.next,
struct spi_transfer, transfer_list);
mpc52xx_spi_start_transfer(ms);
ms->state = mpc52xx_spi_fsmstate_transfer;
return FSM_CONTINUE;
}
/**
* mpc52xx_spi_fsm_process - Finite State Machine iteration function
* @irq: irq number that triggered the FSM or 0 for polling
* @ms: pointer to mpc52xx_spi driver data
*/
static void mpc52xx_spi_fsm_process(int irq, struct mpc52xx_spi *ms)
{
int rc = FSM_CONTINUE;
u8 status, data;
while (rc == FSM_CONTINUE) {
/* Interrupt cleared by read of STATUS followed by
* read of DATA registers */
status = in_8(ms->regs + SPI_STATUS);
data = in_8(ms->regs + SPI_DATA);
rc = ms->state(irq, ms, status, data);
}
if (rc == FSM_POLL)
schedule_work(&ms->work);
}
/**
* mpc52xx_spi_irq - IRQ handler
*/
static irqreturn_t mpc52xx_spi_irq(int irq, void *_ms)
{
struct mpc52xx_spi *ms = _ms;
spin_lock(&ms->lock);
mpc52xx_spi_fsm_process(irq, ms);
spin_unlock(&ms->lock);
return IRQ_HANDLED;
}
/**
* mpc52xx_spi_wq - Workqueue function for polling the state machine
*/
static void mpc52xx_spi_wq(struct work_struct *work)
{
struct mpc52xx_spi *ms = container_of(work, struct mpc52xx_spi, work);
unsigned long flags;
spin_lock_irqsave(&ms->lock, flags);
mpc52xx_spi_fsm_process(0, ms);
spin_unlock_irqrestore(&ms->lock, flags);
}
/*
* spi_master ops
*/
static int mpc52xx_spi_setup(struct spi_device *spi)
{
if (spi->bits_per_word % 8)
return -EINVAL;
if (spi->mode & ~(SPI_CPOL | SPI_CPHA | SPI_LSB_FIRST))
return -EINVAL;
if (spi->chip_select >= spi->master->num_chipselect)
return -EINVAL;
return 0;
}
static int mpc52xx_spi_transfer(struct spi_device *spi, struct spi_message *m)
{
struct mpc52xx_spi *ms = spi_master_get_devdata(spi->master);
unsigned long flags;
m->actual_length = 0;
m->status = -EINPROGRESS;
spin_lock_irqsave(&ms->lock, flags);
list_add_tail(&m->queue, &ms->queue);
spin_unlock_irqrestore(&ms->lock, flags);
schedule_work(&ms->work);
return 0;
}
/*
* OF Platform Bus Binding
*/
static int __devinit mpc52xx_spi_probe(struct platform_device *op)
{
struct spi_master *master;
struct mpc52xx_spi *ms;
void __iomem *regs;
u8 ctrl1;
int rc, i = 0;
int gpio_cs;
/* MMIO registers */
dev_dbg(&op->dev, "probing mpc5200 SPI device\n");
regs = of_iomap(op->dev.of_node, 0);
if (!regs)
return -ENODEV;
/* initialize the device */
ctrl1 = SPI_CTRL1_SPIE | SPI_CTRL1_SPE | SPI_CTRL1_MSTR;
out_8(regs + SPI_CTRL1, ctrl1);
out_8(regs + SPI_CTRL2, 0x0);
out_8(regs + SPI_DATADIR, 0xe); /* Set output pins */
out_8(regs + SPI_PORTDATA, 0x8); /* Deassert /SS signal */
/* Clear the status register and re-read it to check for a MODF
* failure. This driver cannot currently handle multiple masters
* on the SPI bus. This fault will also occur if the SPI signals
* are not connected to any pins (port_config setting) */
in_8(regs + SPI_STATUS);
out_8(regs + SPI_CTRL1, ctrl1);
in_8(regs + SPI_DATA);
if (in_8(regs + SPI_STATUS) & SPI_STATUS_MODF) {
dev_err(&op->dev, "mode fault; is port_config correct?\n");
rc = -EIO;
goto err_init;
}
dev_dbg(&op->dev, "allocating spi_master struct\n");
master = spi_alloc_master(&op->dev, sizeof *ms);
if (!master) {
rc = -ENOMEM;
goto err_alloc;
}
master->bus_num = -1;
master->setup = mpc52xx_spi_setup;
master->transfer = mpc52xx_spi_transfer;
master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_LSB_FIRST;
master->dev.of_node = op->dev.of_node;
dev_set_drvdata(&op->dev, master);
ms = spi_master_get_devdata(master);
ms->master = master;
ms->regs = regs;
ms->irq0 = irq_of_parse_and_map(op->dev.of_node, 0);
ms->irq1 = irq_of_parse_and_map(op->dev.of_node, 1);
ms->state = mpc52xx_spi_fsmstate_idle;
ms->ipb_freq = mpc5xxx_get_bus_frequency(op->dev.of_node);
ms->gpio_cs_count = of_gpio_count(op->dev.of_node);
if (ms->gpio_cs_count > 0) {
master->num_chipselect = ms->gpio_cs_count;
ms->gpio_cs = kmalloc(ms->gpio_cs_count * sizeof(unsigned int),
GFP_KERNEL);
if (!ms->gpio_cs) {
rc = -ENOMEM;
goto err_alloc;
}
for (i = 0; i < ms->gpio_cs_count; i++) {
gpio_cs = of_get_gpio(op->dev.of_node, i);
if (gpio_cs < 0) {
dev_err(&op->dev,
"could not parse the gpio field "
"in oftree\n");
rc = -ENODEV;
goto err_gpio;
}
rc = gpio_request(gpio_cs, dev_name(&op->dev));
if (rc) {
dev_err(&op->dev,
"can't request spi cs gpio #%d "
"on gpio line %d\n", i, gpio_cs);
goto err_gpio;
}
gpio_direction_output(gpio_cs, 1);
ms->gpio_cs[i] = gpio_cs;
}
} else {
master->num_chipselect = 1;
}
spin_lock_init(&ms->lock);
INIT_LIST_HEAD(&ms->queue);
INIT_WORK(&ms->work, mpc52xx_spi_wq);
/* Decide if interrupts can be used */
if (ms->irq0 && ms->irq1) {
rc = request_irq(ms->irq0, mpc52xx_spi_irq, 0,
"mpc5200-spi-modf", ms);
rc |= request_irq(ms->irq1, mpc52xx_spi_irq, 0,
"mpc5200-spi-spif", ms);
if (rc) {
free_irq(ms->irq0, ms);
free_irq(ms->irq1, ms);
ms->irq0 = ms->irq1 = 0;
}
} else {
/* operate in polled mode */
ms->irq0 = ms->irq1 = 0;
}
if (!ms->irq0)
dev_info(&op->dev, "using polled mode\n");
dev_dbg(&op->dev, "registering spi_master struct\n");
rc = spi_register_master(master);
if (rc)
goto err_register;
dev_info(&ms->master->dev, "registered MPC5200 SPI bus\n");
return rc;
err_register:
dev_err(&ms->master->dev, "initialization failed\n");
spi_master_put(master);
err_gpio:
while (i-- > 0)
gpio_free(ms->gpio_cs[i]);
kfree(ms->gpio_cs);
err_alloc:
err_init:
iounmap(regs);
return rc;
}
static int __devexit mpc52xx_spi_remove(struct platform_device *op)
{
struct spi_master *master = dev_get_drvdata(&op->dev);
struct mpc52xx_spi *ms = spi_master_get_devdata(master);
int i;
free_irq(ms->irq0, ms);
free_irq(ms->irq1, ms);
for (i = 0; i < ms->gpio_cs_count; i++)
gpio_free(ms->gpio_cs[i]);
kfree(ms->gpio_cs);
spi_unregister_master(master);
spi_master_put(master);
iounmap(ms->regs);
return 0;
}
static const struct of_device_id mpc52xx_spi_match[] __devinitconst = {
{ .compatible = "fsl,mpc5200-spi", },
{}
};
MODULE_DEVICE_TABLE(of, mpc52xx_spi_match);
static struct platform_driver mpc52xx_spi_of_driver = {
.driver = {
.name = "mpc52xx-spi",
.owner = THIS_MODULE,
.of_match_table = mpc52xx_spi_match,
},
.probe = mpc52xx_spi_probe,
.remove = __devexit_p(mpc52xx_spi_remove),
};
module_platform_driver(mpc52xx_spi_of_driver);
| gpl-2.0 |
nasty007/kernel_msm | drivers/staging/rtl8712/rtl871x_cmd.c | 5070 | 32679 | /******************************************************************************
* rtl871x_cmd.c
*
* Copyright(c) 2007 - 2010 Realtek Corporation. All rights reserved.
* Linux device driver for RTL8192SU
*
* 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
*
* Modifications for inclusion into the Linux staging tree are
* Copyright(c) 2010 Larry Finger. All rights reserved.
*
* Contact information:
* WLAN FAE <wlanfae@realtek.com>
* Larry Finger <Larry.Finger@lwfinger.net>
*
******************************************************************************/
#define _RTL871X_CMD_C_
#include <linux/compiler.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/kref.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <linux/usb.h>
#include <linux/usb/ch9.h>
#include <linux/circ_buf.h>
#include <linux/uaccess.h>
#include <asm/byteorder.h>
#include <linux/atomic.h>
#include <linux/semaphore.h>
#include <linux/rtnetlink.h>
#include "osdep_service.h"
#include "drv_types.h"
#include "recv_osdep.h"
#include "mlme_osdep.h"
#include "rtl871x_byteorder.h"
/*
Caller and the r8712_cmd_thread can protect cmd_q by spin_lock.
No irqsave is necessary.
*/
static sint _init_cmd_priv(struct cmd_priv *pcmdpriv)
{
sema_init(&(pcmdpriv->cmd_queue_sema), 0);
sema_init(&(pcmdpriv->terminate_cmdthread_sema), 0);
_init_queue(&(pcmdpriv->cmd_queue));
/* allocate DMA-able/Non-Page memory for cmd_buf and rsp_buf */
pcmdpriv->cmd_seq = 1;
pcmdpriv->cmd_allocated_buf = _malloc(MAX_CMDSZ + CMDBUFF_ALIGN_SZ);
if (pcmdpriv->cmd_allocated_buf == NULL)
return _FAIL;
pcmdpriv->cmd_buf = pcmdpriv->cmd_allocated_buf + CMDBUFF_ALIGN_SZ -
((addr_t)(pcmdpriv->cmd_allocated_buf) &
(CMDBUFF_ALIGN_SZ-1));
pcmdpriv->rsp_allocated_buf = _malloc(MAX_RSPSZ + 4);
if (pcmdpriv->rsp_allocated_buf == NULL)
return _FAIL;
pcmdpriv->rsp_buf = pcmdpriv->rsp_allocated_buf + 4 -
((addr_t)(pcmdpriv->rsp_allocated_buf) & 3);
pcmdpriv->cmd_issued_cnt = 0;
pcmdpriv->cmd_done_cnt = 0;
pcmdpriv->rsp_cnt = 0;
return _SUCCESS;
}
static sint _init_evt_priv(struct evt_priv *pevtpriv)
{
/* allocate DMA-able/Non-Page memory for cmd_buf and rsp_buf */
pevtpriv->event_seq = 0;
pevtpriv->evt_allocated_buf = _malloc(MAX_EVTSZ + 4);
if (pevtpriv->evt_allocated_buf == NULL)
return _FAIL;
pevtpriv->evt_buf = pevtpriv->evt_allocated_buf + 4 -
((addr_t)(pevtpriv->evt_allocated_buf) & 3);
pevtpriv->evt_done_cnt = 0;
return _SUCCESS;
}
static void _free_evt_priv(struct evt_priv *pevtpriv)
{
kfree(pevtpriv->evt_allocated_buf);
}
static void _free_cmd_priv(struct cmd_priv *pcmdpriv)
{
if (pcmdpriv) {
kfree(pcmdpriv->cmd_allocated_buf);
kfree(pcmdpriv->rsp_allocated_buf);
}
}
/*
Calling Context:
_enqueue_cmd can only be called between kernel thread,
since only spin_lock is used.
ISR/Call-Back functions can't call this sub-function.
*/
static sint _enqueue_cmd(struct __queue *queue, struct cmd_obj *obj)
{
unsigned long irqL;
if (obj == NULL)
return _SUCCESS;
spin_lock_irqsave(&queue->lock, irqL);
list_insert_tail(&obj->list, &queue->queue);
spin_unlock_irqrestore(&queue->lock, irqL);
return _SUCCESS;
}
static struct cmd_obj *_dequeue_cmd(struct __queue *queue)
{
unsigned long irqL;
struct cmd_obj *obj;
spin_lock_irqsave(&(queue->lock), irqL);
if (is_list_empty(&(queue->queue)))
obj = NULL;
else {
obj = LIST_CONTAINOR(get_next(&(queue->queue)),
struct cmd_obj, list);
list_delete(&obj->list);
}
spin_unlock_irqrestore(&(queue->lock), irqL);
return obj;
}
u32 r8712_init_cmd_priv(struct cmd_priv *pcmdpriv)
{
return _init_cmd_priv(pcmdpriv);
}
u32 r8712_init_evt_priv(struct evt_priv *pevtpriv)
{
return _init_evt_priv(pevtpriv);
}
void r8712_free_evt_priv(struct evt_priv *pevtpriv)
{
_free_evt_priv(pevtpriv);
}
void r8712_free_cmd_priv(struct cmd_priv *pcmdpriv)
{
_free_cmd_priv(pcmdpriv);
}
u32 r8712_enqueue_cmd(struct cmd_priv *pcmdpriv, struct cmd_obj *obj)
{
int res;
if (pcmdpriv->padapter->eeprompriv.bautoload_fail_flag == true)
return _FAIL;
res = _enqueue_cmd(&pcmdpriv->cmd_queue, obj);
up(&pcmdpriv->cmd_queue_sema);
return res;
}
u32 r8712_enqueue_cmd_ex(struct cmd_priv *pcmdpriv, struct cmd_obj *obj)
{
unsigned long irqL;
struct __queue *queue;
if (obj == NULL)
return _SUCCESS;
if (pcmdpriv->padapter->eeprompriv.bautoload_fail_flag == true)
return _FAIL;
queue = &pcmdpriv->cmd_queue;
spin_lock_irqsave(&queue->lock, irqL);
list_insert_tail(&obj->list, &queue->queue);
spin_unlock_irqrestore(&queue->lock, irqL);
up(&pcmdpriv->cmd_queue_sema);
return _SUCCESS;
}
struct cmd_obj *r8712_dequeue_cmd(struct __queue *queue)
{
return _dequeue_cmd(queue);
}
void r8712_free_cmd_obj(struct cmd_obj *pcmd)
{
if ((pcmd->cmdcode != _JoinBss_CMD_) &&
(pcmd->cmdcode != _CreateBss_CMD_))
kfree((unsigned char *)pcmd->parmbuf);
if (pcmd->rsp != NULL) {
if (pcmd->rspsz != 0)
kfree((unsigned char *)pcmd->rsp);
}
kfree((unsigned char *)pcmd);
}
/*
r8712_sitesurvey_cmd(~)
### NOTE:#### (!!!!)
MUST TAKE CARE THAT BEFORE CALLING THIS FUNC,
YOU SHOULD HAVE LOCKED pmlmepriv->lock
*/
u8 r8712_sitesurvey_cmd(struct _adapter *padapter,
struct ndis_802_11_ssid *pssid)
{
struct cmd_obj *ph2c;
struct sitesurvey_parm *psurveyPara;
struct cmd_priv *pcmdpriv = &padapter->cmdpriv;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
ph2c = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (ph2c == NULL)
return _FAIL;
psurveyPara = (struct sitesurvey_parm *)_malloc(
sizeof(struct sitesurvey_parm));
if (psurveyPara == NULL) {
kfree((unsigned char *) ph2c);
return _FAIL;
}
init_h2fwcmd_w_parm_no_rsp(ph2c, psurveyPara,
GEN_CMD_CODE(_SiteSurvey));
psurveyPara->bsslimit = cpu_to_le32(48);
psurveyPara->passive_mode = cpu_to_le32(pmlmepriv->passive_mode);
psurveyPara->ss_ssidlen = 0;
memset(psurveyPara->ss_ssid, 0, IW_ESSID_MAX_SIZE + 1);
if ((pssid != NULL) && (pssid->SsidLength)) {
memcpy(psurveyPara->ss_ssid, pssid->Ssid, pssid->SsidLength);
psurveyPara->ss_ssidlen = cpu_to_le32(pssid->SsidLength);
}
set_fwstate(pmlmepriv, _FW_UNDER_SURVEY);
r8712_enqueue_cmd(pcmdpriv, ph2c);
_set_timer(&pmlmepriv->scan_to_timer, SCANNING_TIMEOUT);
padapter->ledpriv.LedControlHandler(padapter, LED_CTL_SITE_SURVEY);
padapter->blnEnableRxFF0Filter = 0;
return _SUCCESS;
}
u8 r8712_setdatarate_cmd(struct _adapter *padapter, u8 *rateset)
{
struct cmd_obj *ph2c;
struct setdatarate_parm *pbsetdataratepara;
struct cmd_priv *pcmdpriv = &padapter->cmdpriv;
ph2c = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (ph2c == NULL)
return _FAIL;
pbsetdataratepara = (struct setdatarate_parm *)_malloc(
sizeof(struct setdatarate_parm));
if (pbsetdataratepara == NULL) {
kfree((u8 *) ph2c);
return _FAIL;
}
init_h2fwcmd_w_parm_no_rsp(ph2c, pbsetdataratepara,
GEN_CMD_CODE(_SetDataRate));
pbsetdataratepara->mac_id = 5;
memcpy(pbsetdataratepara->datarates, rateset, NumRates);
r8712_enqueue_cmd(pcmdpriv, ph2c);
return _SUCCESS;
}
u8 r8712_set_chplan_cmd(struct _adapter *padapter, int chplan)
{
struct cmd_obj *ph2c;
struct SetChannelPlan_param *psetchplanpara;
struct cmd_priv *pcmdpriv = &padapter->cmdpriv;
ph2c = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (ph2c == NULL)
return _FAIL;
psetchplanpara = (struct SetChannelPlan_param *)
_malloc(sizeof(struct SetChannelPlan_param));
if (psetchplanpara == NULL) {
kfree((u8 *) ph2c);
return _FAIL;
}
init_h2fwcmd_w_parm_no_rsp(ph2c, psetchplanpara,
GEN_CMD_CODE(_SetChannelPlan));
psetchplanpara->ChannelPlan = chplan;
r8712_enqueue_cmd(pcmdpriv, ph2c);
return _SUCCESS;
}
u8 r8712_setbasicrate_cmd(struct _adapter *padapter, u8 *rateset)
{
struct cmd_obj *ph2c;
struct setbasicrate_parm *pssetbasicratepara;
struct cmd_priv *pcmdpriv = &padapter->cmdpriv;
ph2c = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (ph2c == NULL)
return _FAIL;
pssetbasicratepara = (struct setbasicrate_parm *)_malloc(
sizeof(struct setbasicrate_parm));
if (pssetbasicratepara == NULL) {
kfree((u8 *) ph2c);
return _FAIL;
}
init_h2fwcmd_w_parm_no_rsp(ph2c, pssetbasicratepara,
_SetBasicRate_CMD_);
memcpy(pssetbasicratepara->basicrates, rateset, NumRates);
r8712_enqueue_cmd(pcmdpriv, ph2c);
return _SUCCESS;
}
/* power tracking mechanism setting */
u8 r8712_setptm_cmd(struct _adapter *padapter, u8 type)
{
struct cmd_obj *ph2c;
struct writePTM_parm *pwriteptmparm;
struct cmd_priv *pcmdpriv = &padapter->cmdpriv;
ph2c = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (ph2c == NULL)
return _FAIL;
pwriteptmparm = (struct writePTM_parm *)
_malloc(sizeof(struct writePTM_parm));
if (pwriteptmparm == NULL) {
kfree((u8 *) ph2c);
return _FAIL;
}
init_h2fwcmd_w_parm_no_rsp(ph2c, pwriteptmparm, GEN_CMD_CODE(_SetPT));
pwriteptmparm->type = type;
r8712_enqueue_cmd(pcmdpriv, ph2c);
return _SUCCESS;
}
u8 r8712_setfwdig_cmd(struct _adapter *padapter, u8 type)
{
struct cmd_obj *ph2c;
struct writePTM_parm *pwriteptmparm;
struct cmd_priv *pcmdpriv = &padapter->cmdpriv;
ph2c = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (ph2c == NULL)
return _FAIL;
pwriteptmparm = (struct writePTM_parm *)
_malloc(sizeof(struct setdig_parm));
if (pwriteptmparm == NULL) {
kfree((u8 *) ph2c);
return _FAIL;
}
init_h2fwcmd_w_parm_no_rsp(ph2c, pwriteptmparm, GEN_CMD_CODE(_SetDIG));
pwriteptmparm->type = type;
r8712_enqueue_cmd(pcmdpriv, ph2c);
return _SUCCESS;
}
u8 r8712_setfwra_cmd(struct _adapter *padapter, u8 type)
{
struct cmd_obj *ph2c;
struct writePTM_parm *pwriteptmparm;
struct cmd_priv *pcmdpriv = &padapter->cmdpriv;
ph2c = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (ph2c == NULL)
return _FAIL;
pwriteptmparm = (struct writePTM_parm *)
_malloc(sizeof(struct setra_parm));
if (pwriteptmparm == NULL) {
kfree((u8 *) ph2c);
return _FAIL;
}
init_h2fwcmd_w_parm_no_rsp(ph2c, pwriteptmparm, GEN_CMD_CODE(_SetRA));
pwriteptmparm->type = type;
r8712_enqueue_cmd(pcmdpriv, ph2c);
return _SUCCESS;
}
u8 r8712_setrfreg_cmd(struct _adapter *padapter, u8 offset, u32 val)
{
struct cmd_obj *ph2c;
struct writeRF_parm *pwriterfparm;
struct cmd_priv *pcmdpriv = &padapter->cmdpriv;
ph2c = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (ph2c == NULL)
return _FAIL;
pwriterfparm = (struct writeRF_parm *)_malloc(
sizeof(struct writeRF_parm));
if (pwriterfparm == NULL) {
kfree((u8 *) ph2c);
return _FAIL;
}
init_h2fwcmd_w_parm_no_rsp(ph2c, pwriterfparm, GEN_CMD_CODE(_SetRFReg));
pwriterfparm->offset = offset;
pwriterfparm->value = val;
r8712_enqueue_cmd(pcmdpriv, ph2c);
return _SUCCESS;
}
u8 r8712_getrfreg_cmd(struct _adapter *padapter, u8 offset, u8 *pval)
{
struct cmd_obj *ph2c;
struct readRF_parm *prdrfparm;
struct cmd_priv *pcmdpriv = &padapter->cmdpriv;
ph2c = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (ph2c == NULL)
return _FAIL;
prdrfparm = (struct readRF_parm *)_malloc(sizeof(struct readRF_parm));
if (prdrfparm == NULL) {
kfree((u8 *) ph2c);
return _FAIL;
}
_init_listhead(&ph2c->list);
ph2c->cmdcode = GEN_CMD_CODE(_GetRFReg);
ph2c->parmbuf = (unsigned char *)prdrfparm;
ph2c->cmdsz = sizeof(struct readRF_parm);
ph2c->rsp = pval;
ph2c->rspsz = sizeof(struct readRF_rsp);
prdrfparm->offset = offset;
r8712_enqueue_cmd(pcmdpriv, ph2c);
return _SUCCESS;
}
void r8712_getbbrfreg_cmdrsp_callback(struct _adapter *padapter,
struct cmd_obj *pcmd)
{
kfree(pcmd->parmbuf);
kfree(pcmd);
padapter->mppriv.workparam.bcompleted = true;
}
void r8712_readtssi_cmdrsp_callback(struct _adapter *padapter,
struct cmd_obj *pcmd)
{
kfree(pcmd->parmbuf);
kfree(pcmd);
padapter->mppriv.workparam.bcompleted = true;
}
u8 r8712_createbss_cmd(struct _adapter *padapter)
{
struct cmd_obj *pcmd;
struct cmd_priv *pcmdpriv = &padapter->cmdpriv;
struct wlan_bssid_ex *pdev_network =
&padapter->registrypriv.dev_network;
padapter->ledpriv.LedControlHandler(padapter, LED_CTL_START_TO_LINK);
pcmd = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (pcmd == NULL)
return _FAIL;
_init_listhead(&pcmd->list);
pcmd->cmdcode = _CreateBss_CMD_;
pcmd->parmbuf = (unsigned char *)pdev_network;
pcmd->cmdsz = r8712_get_ndis_wlan_bssid_ex_sz((
struct ndis_wlan_bssid_ex *)
pdev_network);
pcmd->rsp = NULL;
pcmd->rspsz = 0;
/* notes: translate IELength & Length after assign to cmdsz; */
pdev_network->Length = cpu_to_le32(pcmd->cmdsz);
pdev_network->IELength = cpu_to_le32(pdev_network->IELength);
pdev_network->Ssid.SsidLength = cpu_to_le32(
pdev_network->Ssid.SsidLength);
r8712_enqueue_cmd(pcmdpriv, pcmd);
return _SUCCESS;
}
u8 r8712_joinbss_cmd(struct _adapter *padapter, struct wlan_network *pnetwork)
{
u8 *auth;
uint t_len = 0;
struct ndis_wlan_bssid_ex *psecnetwork;
struct cmd_obj *pcmd;
struct cmd_priv *pcmdpriv = &padapter->cmdpriv;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct qos_priv *pqospriv = &pmlmepriv->qospriv;
struct security_priv *psecuritypriv = &padapter->securitypriv;
struct registry_priv *pregistrypriv = &padapter->registrypriv;
enum NDIS_802_11_NETWORK_INFRASTRUCTURE ndis_network_mode = pnetwork->
network.InfrastructureMode;
padapter->ledpriv.LedControlHandler(padapter, LED_CTL_START_TO_LINK);
pcmd = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (pcmd == NULL)
return _FAIL;
t_len = sizeof(u32) + 6 * sizeof(unsigned char) + 2 +
sizeof(struct ndis_802_11_ssid) + sizeof(u32) +
sizeof(s32) +
sizeof(enum NDIS_802_11_NETWORK_TYPE) +
sizeof(struct NDIS_802_11_CONFIGURATION) +
sizeof(enum NDIS_802_11_NETWORK_INFRASTRUCTURE) +
sizeof(NDIS_802_11_RATES_EX) +
sizeof(u32) + MAX_IE_SZ;
/* for hidden ap to set fw_state here */
if (check_fwstate(pmlmepriv, WIFI_STATION_STATE|WIFI_ADHOC_STATE) !=
true) {
switch (ndis_network_mode) {
case Ndis802_11IBSS:
pmlmepriv->fw_state |= WIFI_ADHOC_STATE;
break;
case Ndis802_11Infrastructure:
pmlmepriv->fw_state |= WIFI_STATION_STATE;
break;
case Ndis802_11APMode:
case Ndis802_11AutoUnknown:
case Ndis802_11InfrastructureMax:
break;
}
}
psecnetwork = (struct ndis_wlan_bssid_ex *)&psecuritypriv->sec_bss;
if (psecnetwork == NULL) {
kfree(pcmd);
return _FAIL;
}
memset(psecnetwork, 0, t_len);
memcpy(psecnetwork, &pnetwork->network, t_len);
auth = &psecuritypriv->authenticator_ie[0];
psecuritypriv->authenticator_ie[0] = (unsigned char)
psecnetwork->IELength;
if ((psecnetwork->IELength-12) < (256 - 1))
memcpy(&psecuritypriv->authenticator_ie[1],
&psecnetwork->IEs[12], psecnetwork->IELength-12);
else
memcpy(&psecuritypriv->authenticator_ie[1],
&psecnetwork->IEs[12], (256-1));
psecnetwork->IELength = 0;
/* If the the driver wants to use the bssid to create the connection.
* If not, we copy the connecting AP's MAC address to it so that
* the driver just has the bssid information for PMKIDList searching.
*/
if (pmlmepriv->assoc_by_bssid == false)
memcpy(&pmlmepriv->assoc_bssid[0],
&pnetwork->network.MacAddress[0], ETH_ALEN);
psecnetwork->IELength = r8712_restruct_sec_ie(padapter,
&pnetwork->network.IEs[0],
&psecnetwork->IEs[0],
pnetwork->network.IELength);
pqospriv->qos_option = 0;
if (pregistrypriv->wmm_enable) {
u32 tmp_len;
tmp_len = r8712_restruct_wmm_ie(padapter,
&pnetwork->network.IEs[0],
&psecnetwork->IEs[0],
pnetwork->network.IELength,
psecnetwork->IELength);
if (psecnetwork->IELength != tmp_len) {
psecnetwork->IELength = tmp_len;
pqospriv->qos_option = 1; /* WMM IE in beacon */
} else
pqospriv->qos_option = 0; /* no WMM IE in beacon */
}
if (pregistrypriv->ht_enable) {
/* For WEP mode, we will use the bg mode to do the connection
* to avoid some IOT issues, especially for Realtek 8192u
* SoftAP.
*/
if ((padapter->securitypriv.PrivacyAlgrthm != _WEP40_) &&
(padapter->securitypriv.PrivacyAlgrthm != _WEP104_)) {
/* restructure_ht_ie */
r8712_restructure_ht_ie(padapter,
&pnetwork->network.IEs[0],
&psecnetwork->IEs[0],
pnetwork->network.IELength,
&psecnetwork->IELength);
}
}
psecuritypriv->supplicant_ie[0] = (u8)psecnetwork->IELength;
if (psecnetwork->IELength < 255)
memcpy(&psecuritypriv->supplicant_ie[1], &psecnetwork->IEs[0],
psecnetwork->IELength);
else
memcpy(&psecuritypriv->supplicant_ie[1], &psecnetwork->IEs[0],
255);
/* get cmdsz before endian conversion */
pcmd->cmdsz = r8712_get_ndis_wlan_bssid_ex_sz(psecnetwork);
#ifdef __BIG_ENDIAN
/* wlan_network endian conversion */
psecnetwork->Length = cpu_to_le32(psecnetwork->Length);
psecnetwork->Ssid.SsidLength = cpu_to_le32(
psecnetwork->Ssid.SsidLength);
psecnetwork->Privacy = cpu_to_le32(psecnetwork->Privacy);
psecnetwork->Rssi = cpu_to_le32(psecnetwork->Rssi);
psecnetwork->NetworkTypeInUse = cpu_to_le32(
psecnetwork->NetworkTypeInUse);
psecnetwork->Configuration.ATIMWindow = cpu_to_le32(
psecnetwork->Configuration.ATIMWindow);
psecnetwork->Configuration.BeaconPeriod = cpu_to_le32(
psecnetwork->Configuration.BeaconPeriod);
psecnetwork->Configuration.DSConfig = cpu_to_le32(
psecnetwork->Configuration.DSConfig);
psecnetwork->Configuration.FHConfig.DwellTime = cpu_to_le32(
psecnetwork->Configuration.FHConfig.DwellTime);
psecnetwork->Configuration.FHConfig.HopPattern = cpu_to_le32(
psecnetwork->Configuration.FHConfig.HopPattern);
psecnetwork->Configuration.FHConfig.HopSet = cpu_to_le32(
psecnetwork->Configuration.FHConfig.HopSet);
psecnetwork->Configuration.FHConfig.Length = cpu_to_le32(
psecnetwork->Configuration.FHConfig.Length);
psecnetwork->Configuration.Length = cpu_to_le32(
psecnetwork->Configuration.Length);
psecnetwork->InfrastructureMode = cpu_to_le32(
psecnetwork->InfrastructureMode);
psecnetwork->IELength = cpu_to_le32(psecnetwork->IELength);
#endif
_init_listhead(&pcmd->list);
pcmd->cmdcode = _JoinBss_CMD_;
pcmd->parmbuf = (unsigned char *)psecnetwork;
pcmd->rsp = NULL;
pcmd->rspsz = 0;
r8712_enqueue_cmd(pcmdpriv, pcmd);
return _SUCCESS;
}
u8 r8712_disassoc_cmd(struct _adapter *padapter) /* for sta_mode */
{
struct cmd_obj *pdisconnect_cmd;
struct disconnect_parm *pdisconnect;
struct cmd_priv *pcmdpriv = &padapter->cmdpriv;
pdisconnect_cmd = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (pdisconnect_cmd == NULL)
return _FAIL;
pdisconnect = (struct disconnect_parm *)_malloc(
sizeof(struct disconnect_parm));
if (pdisconnect == NULL) {
kfree((u8 *)pdisconnect_cmd);
return _FAIL;
}
init_h2fwcmd_w_parm_no_rsp(pdisconnect_cmd, pdisconnect,
_DisConnect_CMD_);
r8712_enqueue_cmd(pcmdpriv, pdisconnect_cmd);
return _SUCCESS;
}
u8 r8712_setopmode_cmd(struct _adapter *padapter,
enum NDIS_802_11_NETWORK_INFRASTRUCTURE networktype)
{
struct cmd_obj *ph2c;
struct setopmode_parm *psetop;
struct cmd_priv *pcmdpriv = &padapter->cmdpriv;
ph2c = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (ph2c == NULL)
return _FAIL;
psetop = (struct setopmode_parm *)_malloc(
sizeof(struct setopmode_parm));
if (psetop == NULL) {
kfree((u8 *) ph2c);
return _FAIL;
}
init_h2fwcmd_w_parm_no_rsp(ph2c, psetop, _SetOpMode_CMD_);
psetop->mode = (u8)networktype;
r8712_enqueue_cmd(pcmdpriv, ph2c);
return _SUCCESS;
}
u8 r8712_setstakey_cmd(struct _adapter *padapter, u8 *psta, u8 unicast_key)
{
struct cmd_obj *ph2c;
struct set_stakey_parm *psetstakey_para;
struct cmd_priv *pcmdpriv = &padapter->cmdpriv;
struct set_stakey_rsp *psetstakey_rsp = NULL;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct security_priv *psecuritypriv = &padapter->securitypriv;
struct sta_info *sta = (struct sta_info *)psta;
ph2c = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (ph2c == NULL)
return _FAIL;
psetstakey_para = (struct set_stakey_parm *)_malloc(
sizeof(struct set_stakey_parm));
if (psetstakey_para == NULL) {
kfree((u8 *) ph2c);
return _FAIL;
}
psetstakey_rsp = (struct set_stakey_rsp *)_malloc(
sizeof(struct set_stakey_rsp));
if (psetstakey_rsp == NULL) {
kfree((u8 *) ph2c);
kfree((u8 *) psetstakey_para);
return _FAIL;
}
init_h2fwcmd_w_parm_no_rsp(ph2c, psetstakey_para, _SetStaKey_CMD_);
ph2c->rsp = (u8 *) psetstakey_rsp;
ph2c->rspsz = sizeof(struct set_stakey_rsp);
memcpy(psetstakey_para->addr, sta->hwaddr, ETH_ALEN);
if (check_fwstate(pmlmepriv, WIFI_STATION_STATE))
psetstakey_para->algorithm = (unsigned char)
psecuritypriv->PrivacyAlgrthm;
else
GET_ENCRY_ALGO(psecuritypriv, sta,
psetstakey_para->algorithm, false);
if (unicast_key == true)
memcpy(&psetstakey_para->key, &sta->x_UncstKey, 16);
else
memcpy(&psetstakey_para->key,
&psecuritypriv->XGrpKey[
psecuritypriv->XGrpKeyid - 1]. skey, 16);
r8712_enqueue_cmd(pcmdpriv, ph2c);
return _SUCCESS;
}
u8 r8712_setrfintfs_cmd(struct _adapter *padapter, u8 mode)
{
struct cmd_obj *ph2c;
struct setrfintfs_parm *psetrfintfsparm;
struct cmd_priv *pcmdpriv = &padapter->cmdpriv;
ph2c = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (ph2c == NULL)
return _FAIL;
psetrfintfsparm = (struct setrfintfs_parm *)_malloc(
sizeof(struct setrfintfs_parm));
if (psetrfintfsparm == NULL) {
kfree((unsigned char *) ph2c);
return _FAIL;
}
init_h2fwcmd_w_parm_no_rsp(ph2c, psetrfintfsparm,
GEN_CMD_CODE(_SetRFIntFs));
psetrfintfsparm->rfintfs = mode;
r8712_enqueue_cmd(pcmdpriv, ph2c);
return _SUCCESS;
}
u8 r8712_setrttbl_cmd(struct _adapter *padapter,
struct setratable_parm *prate_table)
{
struct cmd_obj *ph2c;
struct setratable_parm *psetrttblparm;
struct cmd_priv *pcmdpriv = &padapter->cmdpriv;
ph2c = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (ph2c == NULL)
return _FAIL;
psetrttblparm = (struct setratable_parm *)_malloc(
sizeof(struct setratable_parm));
if (psetrttblparm == NULL) {
kfree((unsigned char *)ph2c);
return _FAIL;
}
init_h2fwcmd_w_parm_no_rsp(ph2c, psetrttblparm,
GEN_CMD_CODE(_SetRaTable));
memcpy(psetrttblparm, prate_table, sizeof(struct setratable_parm));
r8712_enqueue_cmd(pcmdpriv, ph2c);
return _SUCCESS;
}
u8 r8712_gettssi_cmd(struct _adapter *padapter, u8 offset, u8 *pval)
{
struct cmd_priv *pcmdpriv = &padapter->cmdpriv;
struct cmd_obj *ph2c;
struct readTSSI_parm *prdtssiparm;
ph2c = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (ph2c == NULL)
return _FAIL;
prdtssiparm = (struct readTSSI_parm *)
_malloc(sizeof(struct readTSSI_parm));
if (prdtssiparm == NULL) {
kfree((unsigned char *) ph2c);
return _FAIL;
}
_init_listhead(&ph2c->list);
ph2c->cmdcode = GEN_CMD_CODE(_ReadTSSI);
ph2c->parmbuf = (unsigned char *)prdtssiparm;
ph2c->cmdsz = sizeof(struct readTSSI_parm);
ph2c->rsp = pval;
ph2c->rspsz = sizeof(struct readTSSI_rsp);
prdtssiparm->offset = offset;
r8712_enqueue_cmd(pcmdpriv, ph2c);
return _SUCCESS;
}
u8 r8712_setMacAddr_cmd(struct _adapter *padapter, u8 *mac_addr)
{
struct cmd_priv *pcmdpriv = &padapter->cmdpriv;
struct cmd_obj *ph2c;
struct SetMacAddr_param *psetMacAddr_para;
ph2c = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (ph2c == NULL)
return _FAIL;
psetMacAddr_para = (struct SetMacAddr_param *)_malloc(
sizeof(struct SetMacAddr_param));
if (psetMacAddr_para == NULL) {
kfree((u8 *) ph2c);
return _FAIL;
}
init_h2fwcmd_w_parm_no_rsp(ph2c, psetMacAddr_para,
_SetMacAddress_CMD_);
memcpy(psetMacAddr_para->MacAddr, mac_addr, ETH_ALEN);
r8712_enqueue_cmd(pcmdpriv, ph2c);
return _SUCCESS;
}
u8 r8712_setassocsta_cmd(struct _adapter *padapter, u8 *mac_addr)
{
struct cmd_priv *pcmdpriv = &padapter->cmdpriv;
struct cmd_obj *ph2c;
struct set_assocsta_parm *psetassocsta_para;
struct set_stakey_rsp *psetassocsta_rsp = NULL;
ph2c = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (ph2c == NULL)
return _FAIL;
psetassocsta_para = (struct set_assocsta_parm *)
_malloc(sizeof(struct set_assocsta_parm));
if (psetassocsta_para == NULL) {
kfree((u8 *) ph2c);
return _FAIL;
}
psetassocsta_rsp = (struct set_stakey_rsp *)_malloc(
sizeof(struct set_assocsta_rsp));
if (psetassocsta_rsp == NULL) {
kfree((u8 *)ph2c);
kfree((u8 *)psetassocsta_para);
return _FAIL;
}
init_h2fwcmd_w_parm_no_rsp(ph2c, psetassocsta_para, _SetAssocSta_CMD_);
ph2c->rsp = (u8 *) psetassocsta_rsp;
ph2c->rspsz = sizeof(struct set_assocsta_rsp);
memcpy(psetassocsta_para->addr, mac_addr, ETH_ALEN);
r8712_enqueue_cmd(pcmdpriv, ph2c);
return _SUCCESS;
}
u8 r8712_addbareq_cmd(struct _adapter *padapter, u8 tid)
{
struct cmd_priv *pcmdpriv = &padapter->cmdpriv;
struct cmd_obj *ph2c;
struct addBaReq_parm *paddbareq_parm;
ph2c = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (ph2c == NULL)
return _FAIL;
paddbareq_parm = (struct addBaReq_parm *)_malloc(
sizeof(struct addBaReq_parm));
if (paddbareq_parm == NULL) {
kfree((unsigned char *)ph2c);
return _FAIL;
}
paddbareq_parm->tid = tid;
init_h2fwcmd_w_parm_no_rsp(ph2c, paddbareq_parm,
GEN_CMD_CODE(_AddBAReq));
r8712_enqueue_cmd_ex(pcmdpriv, ph2c);
return _SUCCESS;
}
u8 r8712_wdg_wk_cmd(struct _adapter *padapter)
{
struct cmd_obj *ph2c;
struct drvint_cmd_parm *pdrvintcmd_param;
struct cmd_priv *pcmdpriv = &padapter->cmdpriv;
ph2c = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (ph2c == NULL)
return _FAIL;
pdrvintcmd_param = (struct drvint_cmd_parm *)_malloc(
sizeof(struct drvint_cmd_parm));
if (pdrvintcmd_param == NULL) {
kfree((unsigned char *)ph2c);
return _FAIL;
}
pdrvintcmd_param->i_cid = WDG_WK_CID;
pdrvintcmd_param->sz = 0;
pdrvintcmd_param->pbuf = NULL;
init_h2fwcmd_w_parm_no_rsp(ph2c, pdrvintcmd_param, _DRV_INT_CMD_);
r8712_enqueue_cmd_ex(pcmdpriv, ph2c);
return _SUCCESS;
}
void r8712_survey_cmd_callback(struct _adapter *padapter, struct cmd_obj *pcmd)
{
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
if (pcmd->res != H2C_SUCCESS)
clr_fwstate(pmlmepriv, _FW_UNDER_SURVEY);
r8712_free_cmd_obj(pcmd);
}
void r8712_disassoc_cmd_callback(struct _adapter *padapter,
struct cmd_obj *pcmd)
{
unsigned long irqL;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
if (pcmd->res != H2C_SUCCESS) {
spin_lock_irqsave(&pmlmepriv->lock, irqL);
set_fwstate(pmlmepriv, _FW_LINKED);
spin_unlock_irqrestore(&pmlmepriv->lock, irqL);
return;
}
r8712_free_cmd_obj(pcmd);
}
void r8712_joinbss_cmd_callback(struct _adapter *padapter, struct cmd_obj *pcmd)
{
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
if ((pcmd->res != H2C_SUCCESS))
_set_timer(&pmlmepriv->assoc_timer, 1);
r8712_free_cmd_obj(pcmd);
}
void r8712_createbss_cmd_callback(struct _adapter *padapter,
struct cmd_obj *pcmd)
{
unsigned long irqL;
u8 timer_cancelled;
struct sta_info *psta = NULL;
struct wlan_network *pwlan = NULL;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct ndis_wlan_bssid_ex *pnetwork = (struct ndis_wlan_bssid_ex *)
pcmd->parmbuf;
struct wlan_network *tgt_network = &(pmlmepriv->cur_network);
if ((pcmd->res != H2C_SUCCESS))
_set_timer(&pmlmepriv->assoc_timer, 1);
_cancel_timer(&pmlmepriv->assoc_timer, &timer_cancelled);
#ifdef __BIG_ENDIAN
/* endian_convert */
pnetwork->Length = le32_to_cpu(pnetwork->Length);
pnetwork->Ssid.SsidLength = le32_to_cpu(pnetwork->Ssid.SsidLength);
pnetwork->Privacy = le32_to_cpu(pnetwork->Privacy);
pnetwork->Rssi = le32_to_cpu(pnetwork->Rssi);
pnetwork->NetworkTypeInUse = le32_to_cpu(pnetwork->NetworkTypeInUse);
pnetwork->Configuration.ATIMWindow = le32_to_cpu(pnetwork->
Configuration.ATIMWindow);
pnetwork->Configuration.DSConfig = le32_to_cpu(pnetwork->
Configuration.DSConfig);
pnetwork->Configuration.FHConfig.DwellTime = le32_to_cpu(pnetwork->
Configuration.FHConfig.DwellTime);
pnetwork->Configuration.FHConfig.HopPattern = le32_to_cpu(pnetwork->
Configuration.FHConfig.HopPattern);
pnetwork->Configuration.FHConfig.HopSet = le32_to_cpu(pnetwork->
Configuration.FHConfig.HopSet);
pnetwork->Configuration.FHConfig.Length = le32_to_cpu(pnetwork->
Configuration.FHConfig.Length);
pnetwork->Configuration.Length = le32_to_cpu(pnetwork->
Configuration.Length);
pnetwork->InfrastructureMode = le32_to_cpu(pnetwork->
InfrastructureMode);
pnetwork->IELength = le32_to_cpu(pnetwork->IELength);
#endif
spin_lock_irqsave(&pmlmepriv->lock, irqL);
if ((pmlmepriv->fw_state) & WIFI_AP_STATE) {
psta = r8712_get_stainfo(&padapter->stapriv,
pnetwork->MacAddress);
if (!psta) {
psta = r8712_alloc_stainfo(&padapter->stapriv,
pnetwork->MacAddress);
if (psta == NULL)
goto createbss_cmd_fail ;
}
r8712_indicate_connect(padapter);
} else {
pwlan = _r8712_alloc_network(pmlmepriv);
if (pwlan == NULL) {
pwlan = r8712_get_oldest_wlan_network(
&pmlmepriv->scanned_queue);
if (pwlan == NULL)
goto createbss_cmd_fail;
pwlan->last_scanned = jiffies;
} else
list_insert_tail(&(pwlan->list),
&pmlmepriv->scanned_queue.queue);
pnetwork->Length = r8712_get_ndis_wlan_bssid_ex_sz(pnetwork);
memcpy(&(pwlan->network), pnetwork, pnetwork->Length);
pwlan->fixed = true;
memcpy(&tgt_network->network, pnetwork,
(r8712_get_ndis_wlan_bssid_ex_sz(pnetwork)));
if (pmlmepriv->fw_state & _FW_UNDER_LINKING)
pmlmepriv->fw_state ^= _FW_UNDER_LINKING;
/* we will set _FW_LINKED when there is one more sat to
* join us (stassoc_event_callback) */
}
createbss_cmd_fail:
spin_unlock_irqrestore(&pmlmepriv->lock, irqL);
r8712_free_cmd_obj(pcmd);
}
void r8712_setstaKey_cmdrsp_callback(struct _adapter *padapter,
struct cmd_obj *pcmd)
{
struct sta_priv *pstapriv = &padapter->stapriv;
struct set_stakey_rsp *psetstakey_rsp = (struct set_stakey_rsp *)
(pcmd->rsp);
struct sta_info *psta = r8712_get_stainfo(pstapriv,
psetstakey_rsp->addr);
if (psta == NULL)
goto exit;
psta->aid = psta->mac_id = psetstakey_rsp->keyid; /*CAM_ID(CAM_ENTRY)*/
exit:
r8712_free_cmd_obj(pcmd);
}
void r8712_setassocsta_cmdrsp_callback(struct _adapter *padapter,
struct cmd_obj *pcmd)
{
unsigned long irqL;
struct sta_priv *pstapriv = &padapter->stapriv;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct set_assocsta_parm *passocsta_parm =
(struct set_assocsta_parm *)(pcmd->parmbuf);
struct set_assocsta_rsp *passocsta_rsp =
(struct set_assocsta_rsp *) (pcmd->rsp);
struct sta_info *psta = r8712_get_stainfo(pstapriv,
passocsta_parm->addr);
if (psta == NULL)
return;
psta->aid = psta->mac_id = passocsta_rsp->cam_id;
spin_lock_irqsave(&pmlmepriv->lock, irqL);
if ((check_fwstate(pmlmepriv, WIFI_MP_STATE)) &&
(check_fwstate(pmlmepriv, _FW_UNDER_LINKING)))
pmlmepriv->fw_state ^= _FW_UNDER_LINKING;
set_fwstate(pmlmepriv, _FW_LINKED);
spin_unlock_irqrestore(&pmlmepriv->lock, irqL);
r8712_free_cmd_obj(pcmd);
}
u8 r8712_disconnectCtrlEx_cmd(struct _adapter *adapter, u32 enableDrvCtrl,
u32 tryPktCnt, u32 tryPktInterval, u32 firstStageTO)
{
struct cmd_obj *ph2c;
struct DisconnectCtrlEx_param *param;
struct cmd_priv *pcmdpriv = &adapter->cmdpriv;
ph2c = (struct cmd_obj *)_malloc(sizeof(struct cmd_obj));
if (ph2c == NULL)
return _FAIL;
param = (struct DisconnectCtrlEx_param *)
_malloc(sizeof(struct DisconnectCtrlEx_param));
if (param == NULL) {
kfree((unsigned char *) ph2c);
return _FAIL;
}
memset(param, 0, sizeof(struct DisconnectCtrlEx_param));
param->EnableDrvCtrl = (unsigned char)enableDrvCtrl;
param->TryPktCnt = (unsigned char)tryPktCnt;
param->TryPktInterval = (unsigned char)tryPktInterval;
param->FirstStageTO = (unsigned int)firstStageTO;
init_h2fwcmd_w_parm_no_rsp(ph2c, param,
GEN_CMD_CODE(_DisconnectCtrlEx));
r8712_enqueue_cmd(pcmdpriv, ph2c);
return _SUCCESS;
}
| gpl-2.0 |
mcmenaminadrian/Linux-devel | net/atm/atm_misc.c | 9678 | 2635 | /* net/atm/atm_misc.c - Various functions for use by ATM drivers */
/* Written 1995-2000 by Werner Almesberger, EPFL ICA */
#include <linux/module.h>
#include <linux/atm.h>
#include <linux/atmdev.h>
#include <linux/skbuff.h>
#include <linux/sonet.h>
#include <linux/bitops.h>
#include <linux/errno.h>
#include <linux/atomic.h>
int atm_charge(struct atm_vcc *vcc, int truesize)
{
atm_force_charge(vcc, truesize);
if (atomic_read(&sk_atm(vcc)->sk_rmem_alloc) <= sk_atm(vcc)->sk_rcvbuf)
return 1;
atm_return(vcc, truesize);
atomic_inc(&vcc->stats->rx_drop);
return 0;
}
EXPORT_SYMBOL(atm_charge);
struct sk_buff *atm_alloc_charge(struct atm_vcc *vcc, int pdu_size,
gfp_t gfp_flags)
{
struct sock *sk = sk_atm(vcc);
int guess = SKB_TRUESIZE(pdu_size);
atm_force_charge(vcc, guess);
if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) {
struct sk_buff *skb = alloc_skb(pdu_size, gfp_flags);
if (skb) {
atomic_add(skb->truesize-guess,
&sk->sk_rmem_alloc);
return skb;
}
}
atm_return(vcc, guess);
atomic_inc(&vcc->stats->rx_drop);
return NULL;
}
EXPORT_SYMBOL(atm_alloc_charge);
/*
* atm_pcr_goal returns the positive PCR if it should be rounded up, the
* negative PCR if it should be rounded down, and zero if the maximum available
* bandwidth should be used.
*
* The rules are as follows (* = maximum, - = absent (0), x = value "x",
* (x+ = x or next value above x, x- = x or next value below):
*
* min max pcr result min max pcr result
* - - - * (UBR only) x - - x+
* - - * * x - * *
* - - z z- x - z z-
* - * - * x * - x+
* - * * * x * * *
* - * z z- x * z z-
* - y - y- x y - x+
* - y * y- x y * y-
* - y z z- x y z z-
*
* All non-error cases can be converted with the following simple set of rules:
*
* if pcr == z then z-
* else if min == x && pcr == - then x+
* else if max == y then y-
* else *
*/
int atm_pcr_goal(const struct atm_trafprm *tp)
{
if (tp->pcr && tp->pcr != ATM_MAX_PCR)
return -tp->pcr;
if (tp->min_pcr && !tp->pcr)
return tp->min_pcr;
if (tp->max_pcr != ATM_MAX_PCR)
return -tp->max_pcr;
return 0;
}
EXPORT_SYMBOL(atm_pcr_goal);
void sonet_copy_stats(struct k_sonet_stats *from, struct sonet_stats *to)
{
#define __HANDLE_ITEM(i) to->i = atomic_read(&from->i)
__SONET_ITEMS
#undef __HANDLE_ITEM
}
EXPORT_SYMBOL(sonet_copy_stats);
void sonet_subtract_stats(struct k_sonet_stats *from, struct sonet_stats *to)
{
#define __HANDLE_ITEM(i) atomic_sub(to->i, &from->i)
__SONET_ITEMS
#undef __HANDLE_ITEM
}
EXPORT_SYMBOL(sonet_subtract_stats);
| gpl-2.0 |
kierank/p2-kernel | drivers/video/omap/lcd_inn1510.c | 207 | 3018 | /*
* LCD panel support for the TI OMAP1510 Innovator board
*
* Copyright (C) 2004 Nokia Corporation
* Author: Imre Deak <imre.deak@nokia.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <mach/fpga.h>
#include <mach/omapfb.h>
static int innovator1510_panel_init(struct lcd_panel *panel,
struct omapfb_device *fbdev)
{
return 0;
}
static void innovator1510_panel_cleanup(struct lcd_panel *panel)
{
}
static int innovator1510_panel_enable(struct lcd_panel *panel)
{
fpga_write(0x7, OMAP1510_FPGA_LCD_PANEL_CONTROL);
return 0;
}
static void innovator1510_panel_disable(struct lcd_panel *panel)
{
fpga_write(0x0, OMAP1510_FPGA_LCD_PANEL_CONTROL);
}
static unsigned long innovator1510_panel_get_caps(struct lcd_panel *panel)
{
return 0;
}
struct lcd_panel innovator1510_panel = {
.name = "inn1510",
.config = OMAP_LCDC_PANEL_TFT,
.bpp = 16,
.data_lines = 16,
.x_res = 240,
.y_res = 320,
.pixel_clock = 12500,
.hsw = 40,
.hfp = 40,
.hbp = 72,
.vsw = 1,
.vfp = 1,
.vbp = 0,
.pcd = 12,
.init = innovator1510_panel_init,
.cleanup = innovator1510_panel_cleanup,
.enable = innovator1510_panel_enable,
.disable = innovator1510_panel_disable,
.get_caps = innovator1510_panel_get_caps,
};
static int innovator1510_panel_probe(struct platform_device *pdev)
{
omapfb_register_panel(&innovator1510_panel);
return 0;
}
static int innovator1510_panel_remove(struct platform_device *pdev)
{
return 0;
}
static int innovator1510_panel_suspend(struct platform_device *pdev,
pm_message_t mesg)
{
return 0;
}
static int innovator1510_panel_resume(struct platform_device *pdev)
{
return 0;
}
struct platform_driver innovator1510_panel_driver = {
.probe = innovator1510_panel_probe,
.remove = innovator1510_panel_remove,
.suspend = innovator1510_panel_suspend,
.resume = innovator1510_panel_resume,
.driver = {
.name = "lcd_inn1510",
.owner = THIS_MODULE,
},
};
static int innovator1510_panel_drv_init(void)
{
return platform_driver_register(&innovator1510_panel_driver);
}
static void innovator1510_panel_drv_cleanup(void)
{
platform_driver_unregister(&innovator1510_panel_driver);
}
module_init(innovator1510_panel_drv_init);
module_exit(innovator1510_panel_drv_cleanup);
| gpl-2.0 |
kvinodhbabu/linux | fs/f2fs/dir.c | 207 | 21310 | /*
* fs/f2fs/dir.c
*
* Copyright (c) 2012 Samsung Electronics Co., Ltd.
* http://www.samsung.com/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/fs.h>
#include <linux/f2fs_fs.h>
#include "f2fs.h"
#include "node.h"
#include "acl.h"
#include "xattr.h"
static unsigned long dir_blocks(struct inode *inode)
{
return ((unsigned long long) (i_size_read(inode) + PAGE_CACHE_SIZE - 1))
>> PAGE_CACHE_SHIFT;
}
static unsigned int dir_buckets(unsigned int level, int dir_level)
{
if (level + dir_level < MAX_DIR_HASH_DEPTH / 2)
return 1 << (level + dir_level);
else
return MAX_DIR_BUCKETS;
}
static unsigned int bucket_blocks(unsigned int level)
{
if (level < MAX_DIR_HASH_DEPTH / 2)
return 2;
else
return 4;
}
unsigned char f2fs_filetype_table[F2FS_FT_MAX] = {
[F2FS_FT_UNKNOWN] = DT_UNKNOWN,
[F2FS_FT_REG_FILE] = DT_REG,
[F2FS_FT_DIR] = DT_DIR,
[F2FS_FT_CHRDEV] = DT_CHR,
[F2FS_FT_BLKDEV] = DT_BLK,
[F2FS_FT_FIFO] = DT_FIFO,
[F2FS_FT_SOCK] = DT_SOCK,
[F2FS_FT_SYMLINK] = DT_LNK,
};
#define S_SHIFT 12
static unsigned char f2fs_type_by_mode[S_IFMT >> S_SHIFT] = {
[S_IFREG >> S_SHIFT] = F2FS_FT_REG_FILE,
[S_IFDIR >> S_SHIFT] = F2FS_FT_DIR,
[S_IFCHR >> S_SHIFT] = F2FS_FT_CHRDEV,
[S_IFBLK >> S_SHIFT] = F2FS_FT_BLKDEV,
[S_IFIFO >> S_SHIFT] = F2FS_FT_FIFO,
[S_IFSOCK >> S_SHIFT] = F2FS_FT_SOCK,
[S_IFLNK >> S_SHIFT] = F2FS_FT_SYMLINK,
};
void set_de_type(struct f2fs_dir_entry *de, umode_t mode)
{
de->file_type = f2fs_type_by_mode[(mode & S_IFMT) >> S_SHIFT];
}
static unsigned long dir_block_index(unsigned int level,
int dir_level, unsigned int idx)
{
unsigned long i;
unsigned long bidx = 0;
for (i = 0; i < level; i++)
bidx += dir_buckets(i, dir_level) * bucket_blocks(i);
bidx += idx * bucket_blocks(level);
return bidx;
}
static struct f2fs_dir_entry *find_in_block(struct page *dentry_page,
struct f2fs_filename *fname,
f2fs_hash_t namehash,
int *max_slots,
struct page **res_page)
{
struct f2fs_dentry_block *dentry_blk;
struct f2fs_dir_entry *de;
struct f2fs_dentry_ptr d;
dentry_blk = (struct f2fs_dentry_block *)kmap(dentry_page);
make_dentry_ptr(NULL, &d, (void *)dentry_blk, 1);
de = find_target_dentry(fname, namehash, max_slots, &d);
if (de)
*res_page = dentry_page;
else
kunmap(dentry_page);
/*
* For the most part, it should be a bug when name_len is zero.
* We stop here for figuring out where the bugs has occurred.
*/
f2fs_bug_on(F2FS_P_SB(dentry_page), d.max < 0);
return de;
}
struct f2fs_dir_entry *find_target_dentry(struct f2fs_filename *fname,
f2fs_hash_t namehash, int *max_slots,
struct f2fs_dentry_ptr *d)
{
struct f2fs_dir_entry *de;
unsigned long bit_pos = 0;
int max_len = 0;
struct f2fs_str de_name = FSTR_INIT(NULL, 0);
struct f2fs_str *name = &fname->disk_name;
if (max_slots)
*max_slots = 0;
while (bit_pos < d->max) {
if (!test_bit_le(bit_pos, d->bitmap)) {
bit_pos++;
max_len++;
continue;
}
de = &d->dentry[bit_pos];
/* encrypted case */
de_name.name = d->filename[bit_pos];
de_name.len = le16_to_cpu(de->name_len);
/* show encrypted name */
if (fname->hash) {
if (de->hash_code == fname->hash)
goto found;
} else if (de_name.len == name->len &&
de->hash_code == namehash &&
!memcmp(de_name.name, name->name, name->len))
goto found;
if (max_slots && max_len > *max_slots)
*max_slots = max_len;
max_len = 0;
/* remain bug on condition */
if (unlikely(!de->name_len))
d->max = -1;
bit_pos += GET_DENTRY_SLOTS(le16_to_cpu(de->name_len));
}
de = NULL;
found:
if (max_slots && max_len > *max_slots)
*max_slots = max_len;
return de;
}
static struct f2fs_dir_entry *find_in_level(struct inode *dir,
unsigned int level,
struct f2fs_filename *fname,
struct page **res_page)
{
struct qstr name = FSTR_TO_QSTR(&fname->disk_name);
int s = GET_DENTRY_SLOTS(name.len);
unsigned int nbucket, nblock;
unsigned int bidx, end_block;
struct page *dentry_page;
struct f2fs_dir_entry *de = NULL;
bool room = false;
int max_slots;
f2fs_hash_t namehash;
namehash = f2fs_dentry_hash(&name);
f2fs_bug_on(F2FS_I_SB(dir), level > MAX_DIR_HASH_DEPTH);
nbucket = dir_buckets(level, F2FS_I(dir)->i_dir_level);
nblock = bucket_blocks(level);
bidx = dir_block_index(level, F2FS_I(dir)->i_dir_level,
le32_to_cpu(namehash) % nbucket);
end_block = bidx + nblock;
for (; bidx < end_block; bidx++) {
/* no need to allocate new dentry pages to all the indices */
dentry_page = find_data_page(dir, bidx);
if (IS_ERR(dentry_page)) {
room = true;
continue;
}
de = find_in_block(dentry_page, fname, namehash, &max_slots,
res_page);
if (de)
break;
if (max_slots >= s)
room = true;
f2fs_put_page(dentry_page, 0);
}
if (!de && room && F2FS_I(dir)->chash != namehash) {
F2FS_I(dir)->chash = namehash;
F2FS_I(dir)->clevel = level;
}
return de;
}
/*
* Find an entry in the specified directory with the wanted name.
* It returns the page where the entry was found (as a parameter - res_page),
* and the entry itself. Page is returned mapped and unlocked.
* Entry is guaranteed to be valid.
*/
struct f2fs_dir_entry *f2fs_find_entry(struct inode *dir,
struct qstr *child, struct page **res_page)
{
unsigned long npages = dir_blocks(dir);
struct f2fs_dir_entry *de = NULL;
unsigned int max_depth;
unsigned int level;
struct f2fs_filename fname;
int err;
*res_page = NULL;
err = f2fs_fname_setup_filename(dir, child, 1, &fname);
if (err)
return NULL;
if (f2fs_has_inline_dentry(dir)) {
de = find_in_inline_dir(dir, &fname, res_page);
goto out;
}
if (npages == 0)
goto out;
max_depth = F2FS_I(dir)->i_current_depth;
for (level = 0; level < max_depth; level++) {
de = find_in_level(dir, level, &fname, res_page);
if (de)
break;
}
out:
f2fs_fname_free_filename(&fname);
return de;
}
struct f2fs_dir_entry *f2fs_parent_dir(struct inode *dir, struct page **p)
{
struct page *page;
struct f2fs_dir_entry *de;
struct f2fs_dentry_block *dentry_blk;
if (f2fs_has_inline_dentry(dir))
return f2fs_parent_inline_dir(dir, p);
page = get_lock_data_page(dir, 0);
if (IS_ERR(page))
return NULL;
dentry_blk = kmap(page);
de = &dentry_blk->dentry[1];
*p = page;
unlock_page(page);
return de;
}
ino_t f2fs_inode_by_name(struct inode *dir, struct qstr *qstr)
{
ino_t res = 0;
struct f2fs_dir_entry *de;
struct page *page;
de = f2fs_find_entry(dir, qstr, &page);
if (de) {
res = le32_to_cpu(de->ino);
f2fs_dentry_kunmap(dir, page);
f2fs_put_page(page, 0);
}
return res;
}
void f2fs_set_link(struct inode *dir, struct f2fs_dir_entry *de,
struct page *page, struct inode *inode)
{
enum page_type type = f2fs_has_inline_dentry(dir) ? NODE : DATA;
lock_page(page);
f2fs_wait_on_page_writeback(page, type);
de->ino = cpu_to_le32(inode->i_ino);
set_de_type(de, inode->i_mode);
f2fs_dentry_kunmap(dir, page);
set_page_dirty(page);
dir->i_mtime = dir->i_ctime = CURRENT_TIME;
mark_inode_dirty(dir);
f2fs_put_page(page, 1);
}
static void init_dent_inode(const struct qstr *name, struct page *ipage)
{
struct f2fs_inode *ri;
f2fs_wait_on_page_writeback(ipage, NODE);
/* copy name info. to this inode page */
ri = F2FS_INODE(ipage);
ri->i_namelen = cpu_to_le32(name->len);
memcpy(ri->i_name, name->name, name->len);
set_page_dirty(ipage);
}
int update_dent_inode(struct inode *inode, struct inode *to,
const struct qstr *name)
{
struct page *page;
if (file_enc_name(to))
return 0;
page = get_node_page(F2FS_I_SB(inode), inode->i_ino);
if (IS_ERR(page))
return PTR_ERR(page);
init_dent_inode(name, page);
f2fs_put_page(page, 1);
return 0;
}
void do_make_empty_dir(struct inode *inode, struct inode *parent,
struct f2fs_dentry_ptr *d)
{
struct f2fs_dir_entry *de;
de = &d->dentry[0];
de->name_len = cpu_to_le16(1);
de->hash_code = 0;
de->ino = cpu_to_le32(inode->i_ino);
memcpy(d->filename[0], ".", 1);
set_de_type(de, inode->i_mode);
de = &d->dentry[1];
de->hash_code = 0;
de->name_len = cpu_to_le16(2);
de->ino = cpu_to_le32(parent->i_ino);
memcpy(d->filename[1], "..", 2);
set_de_type(de, parent->i_mode);
test_and_set_bit_le(0, (void *)d->bitmap);
test_and_set_bit_le(1, (void *)d->bitmap);
}
static int make_empty_dir(struct inode *inode,
struct inode *parent, struct page *page)
{
struct page *dentry_page;
struct f2fs_dentry_block *dentry_blk;
struct f2fs_dentry_ptr d;
if (f2fs_has_inline_dentry(inode))
return make_empty_inline_dir(inode, parent, page);
dentry_page = get_new_data_page(inode, page, 0, true);
if (IS_ERR(dentry_page))
return PTR_ERR(dentry_page);
dentry_blk = kmap_atomic(dentry_page);
make_dentry_ptr(NULL, &d, (void *)dentry_blk, 1);
do_make_empty_dir(inode, parent, &d);
kunmap_atomic(dentry_blk);
set_page_dirty(dentry_page);
f2fs_put_page(dentry_page, 1);
return 0;
}
struct page *init_inode_metadata(struct inode *inode, struct inode *dir,
const struct qstr *name, struct page *dpage)
{
struct page *page;
int err;
if (is_inode_flag_set(F2FS_I(inode), FI_NEW_INODE)) {
page = new_inode_page(inode);
if (IS_ERR(page))
return page;
if (S_ISDIR(inode->i_mode)) {
err = make_empty_dir(inode, dir, page);
if (err)
goto error;
}
err = f2fs_init_acl(inode, dir, page, dpage);
if (err)
goto put_error;
err = f2fs_init_security(inode, dir, name, page);
if (err)
goto put_error;
if (f2fs_encrypted_inode(dir) && f2fs_may_encrypt(inode)) {
err = f2fs_inherit_context(dir, inode, page);
if (err)
goto put_error;
}
} else {
page = get_node_page(F2FS_I_SB(dir), inode->i_ino);
if (IS_ERR(page))
return page;
set_cold_node(inode, page);
}
if (name)
init_dent_inode(name, page);
/*
* This file should be checkpointed during fsync.
* We lost i_pino from now on.
*/
if (is_inode_flag_set(F2FS_I(inode), FI_INC_LINK)) {
file_lost_pino(inode);
/*
* If link the tmpfile to alias through linkat path,
* we should remove this inode from orphan list.
*/
if (inode->i_nlink == 0)
remove_orphan_inode(F2FS_I_SB(dir), inode->i_ino);
inc_nlink(inode);
}
return page;
put_error:
f2fs_put_page(page, 1);
error:
/* once the failed inode becomes a bad inode, i_mode is S_IFREG */
truncate_inode_pages(&inode->i_data, 0);
truncate_blocks(inode, 0, false);
remove_dirty_dir_inode(inode);
remove_inode_page(inode);
return ERR_PTR(err);
}
void update_parent_metadata(struct inode *dir, struct inode *inode,
unsigned int current_depth)
{
if (inode && is_inode_flag_set(F2FS_I(inode), FI_NEW_INODE)) {
if (S_ISDIR(inode->i_mode)) {
inc_nlink(dir);
set_inode_flag(F2FS_I(dir), FI_UPDATE_DIR);
}
clear_inode_flag(F2FS_I(inode), FI_NEW_INODE);
}
dir->i_mtime = dir->i_ctime = CURRENT_TIME;
mark_inode_dirty(dir);
if (F2FS_I(dir)->i_current_depth != current_depth) {
F2FS_I(dir)->i_current_depth = current_depth;
set_inode_flag(F2FS_I(dir), FI_UPDATE_DIR);
}
if (inode && is_inode_flag_set(F2FS_I(inode), FI_INC_LINK))
clear_inode_flag(F2FS_I(inode), FI_INC_LINK);
}
int room_for_filename(const void *bitmap, int slots, int max_slots)
{
int bit_start = 0;
int zero_start, zero_end;
next:
zero_start = find_next_zero_bit_le(bitmap, max_slots, bit_start);
if (zero_start >= max_slots)
return max_slots;
zero_end = find_next_bit_le(bitmap, max_slots, zero_start);
if (zero_end - zero_start >= slots)
return zero_start;
bit_start = zero_end + 1;
if (zero_end + 1 >= max_slots)
return max_slots;
goto next;
}
void f2fs_update_dentry(nid_t ino, umode_t mode, struct f2fs_dentry_ptr *d,
const struct qstr *name, f2fs_hash_t name_hash,
unsigned int bit_pos)
{
struct f2fs_dir_entry *de;
int slots = GET_DENTRY_SLOTS(name->len);
int i;
de = &d->dentry[bit_pos];
de->hash_code = name_hash;
de->name_len = cpu_to_le16(name->len);
memcpy(d->filename[bit_pos], name->name, name->len);
de->ino = cpu_to_le32(ino);
set_de_type(de, mode);
for (i = 0; i < slots; i++)
test_and_set_bit_le(bit_pos + i, (void *)d->bitmap);
}
/*
* Caller should grab and release a rwsem by calling f2fs_lock_op() and
* f2fs_unlock_op().
*/
int __f2fs_add_link(struct inode *dir, const struct qstr *name,
struct inode *inode, nid_t ino, umode_t mode)
{
unsigned int bit_pos;
unsigned int level;
unsigned int current_depth;
unsigned long bidx, block;
f2fs_hash_t dentry_hash;
unsigned int nbucket, nblock;
struct page *dentry_page = NULL;
struct f2fs_dentry_block *dentry_blk = NULL;
struct f2fs_dentry_ptr d;
struct page *page = NULL;
struct f2fs_filename fname;
struct qstr new_name;
int slots, err;
err = f2fs_fname_setup_filename(dir, name, 0, &fname);
if (err)
return err;
new_name.name = fname_name(&fname);
new_name.len = fname_len(&fname);
if (f2fs_has_inline_dentry(dir)) {
err = f2fs_add_inline_entry(dir, &new_name, inode, ino, mode);
if (!err || err != -EAGAIN)
goto out;
else
err = 0;
}
level = 0;
slots = GET_DENTRY_SLOTS(new_name.len);
dentry_hash = f2fs_dentry_hash(&new_name);
current_depth = F2FS_I(dir)->i_current_depth;
if (F2FS_I(dir)->chash == dentry_hash) {
level = F2FS_I(dir)->clevel;
F2FS_I(dir)->chash = 0;
}
start:
if (unlikely(current_depth == MAX_DIR_HASH_DEPTH)) {
err = -ENOSPC;
goto out;
}
/* Increase the depth, if required */
if (level == current_depth)
++current_depth;
nbucket = dir_buckets(level, F2FS_I(dir)->i_dir_level);
nblock = bucket_blocks(level);
bidx = dir_block_index(level, F2FS_I(dir)->i_dir_level,
(le32_to_cpu(dentry_hash) % nbucket));
for (block = bidx; block <= (bidx + nblock - 1); block++) {
dentry_page = get_new_data_page(dir, NULL, block, true);
if (IS_ERR(dentry_page)) {
err = PTR_ERR(dentry_page);
goto out;
}
dentry_blk = kmap(dentry_page);
bit_pos = room_for_filename(&dentry_blk->dentry_bitmap,
slots, NR_DENTRY_IN_BLOCK);
if (bit_pos < NR_DENTRY_IN_BLOCK)
goto add_dentry;
kunmap(dentry_page);
f2fs_put_page(dentry_page, 1);
}
/* Move to next level to find the empty slot for new dentry */
++level;
goto start;
add_dentry:
f2fs_wait_on_page_writeback(dentry_page, DATA);
if (inode) {
down_write(&F2FS_I(inode)->i_sem);
page = init_inode_metadata(inode, dir, &new_name, NULL);
if (IS_ERR(page)) {
err = PTR_ERR(page);
goto fail;
}
if (f2fs_encrypted_inode(dir))
file_set_enc_name(inode);
}
make_dentry_ptr(NULL, &d, (void *)dentry_blk, 1);
f2fs_update_dentry(ino, mode, &d, &new_name, dentry_hash, bit_pos);
set_page_dirty(dentry_page);
if (inode) {
/* we don't need to mark_inode_dirty now */
F2FS_I(inode)->i_pino = dir->i_ino;
update_inode(inode, page);
f2fs_put_page(page, 1);
}
update_parent_metadata(dir, inode, current_depth);
fail:
if (inode)
up_write(&F2FS_I(inode)->i_sem);
if (is_inode_flag_set(F2FS_I(dir), FI_UPDATE_DIR)) {
update_inode_page(dir);
clear_inode_flag(F2FS_I(dir), FI_UPDATE_DIR);
}
kunmap(dentry_page);
f2fs_put_page(dentry_page, 1);
out:
f2fs_fname_free_filename(&fname);
return err;
}
int f2fs_do_tmpfile(struct inode *inode, struct inode *dir)
{
struct page *page;
int err = 0;
down_write(&F2FS_I(inode)->i_sem);
page = init_inode_metadata(inode, dir, NULL, NULL);
if (IS_ERR(page)) {
err = PTR_ERR(page);
goto fail;
}
/* we don't need to mark_inode_dirty now */
update_inode(inode, page);
f2fs_put_page(page, 1);
clear_inode_flag(F2FS_I(inode), FI_NEW_INODE);
fail:
up_write(&F2FS_I(inode)->i_sem);
return err;
}
void f2fs_drop_nlink(struct inode *dir, struct inode *inode, struct page *page)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(dir);
down_write(&F2FS_I(inode)->i_sem);
if (S_ISDIR(inode->i_mode)) {
drop_nlink(dir);
if (page)
update_inode(dir, page);
else
update_inode_page(dir);
}
inode->i_ctime = CURRENT_TIME;
drop_nlink(inode);
if (S_ISDIR(inode->i_mode)) {
drop_nlink(inode);
i_size_write(inode, 0);
}
up_write(&F2FS_I(inode)->i_sem);
update_inode_page(inode);
if (inode->i_nlink == 0)
add_orphan_inode(sbi, inode->i_ino);
else
release_orphan_inode(sbi);
}
/*
* It only removes the dentry from the dentry page, corresponding name
* entry in name page does not need to be touched during deletion.
*/
void f2fs_delete_entry(struct f2fs_dir_entry *dentry, struct page *page,
struct inode *dir, struct inode *inode)
{
struct f2fs_dentry_block *dentry_blk;
unsigned int bit_pos;
int slots = GET_DENTRY_SLOTS(le16_to_cpu(dentry->name_len));
int i;
if (f2fs_has_inline_dentry(dir))
return f2fs_delete_inline_entry(dentry, page, dir, inode);
lock_page(page);
f2fs_wait_on_page_writeback(page, DATA);
dentry_blk = page_address(page);
bit_pos = dentry - dentry_blk->dentry;
for (i = 0; i < slots; i++)
clear_bit_le(bit_pos + i, &dentry_blk->dentry_bitmap);
/* Let's check and deallocate this dentry page */
bit_pos = find_next_bit_le(&dentry_blk->dentry_bitmap,
NR_DENTRY_IN_BLOCK,
0);
kunmap(page); /* kunmap - pair of f2fs_find_entry */
set_page_dirty(page);
dir->i_ctime = dir->i_mtime = CURRENT_TIME;
if (inode)
f2fs_drop_nlink(dir, inode, NULL);
if (bit_pos == NR_DENTRY_IN_BLOCK &&
!truncate_hole(dir, page->index, page->index + 1)) {
clear_page_dirty_for_io(page);
ClearPagePrivate(page);
ClearPageUptodate(page);
inode_dec_dirty_pages(dir);
}
f2fs_put_page(page, 1);
}
bool f2fs_empty_dir(struct inode *dir)
{
unsigned long bidx;
struct page *dentry_page;
unsigned int bit_pos;
struct f2fs_dentry_block *dentry_blk;
unsigned long nblock = dir_blocks(dir);
if (f2fs_has_inline_dentry(dir))
return f2fs_empty_inline_dir(dir);
for (bidx = 0; bidx < nblock; bidx++) {
dentry_page = get_lock_data_page(dir, bidx);
if (IS_ERR(dentry_page)) {
if (PTR_ERR(dentry_page) == -ENOENT)
continue;
else
return false;
}
dentry_blk = kmap_atomic(dentry_page);
if (bidx == 0)
bit_pos = 2;
else
bit_pos = 0;
bit_pos = find_next_bit_le(&dentry_blk->dentry_bitmap,
NR_DENTRY_IN_BLOCK,
bit_pos);
kunmap_atomic(dentry_blk);
f2fs_put_page(dentry_page, 1);
if (bit_pos < NR_DENTRY_IN_BLOCK)
return false;
}
return true;
}
bool f2fs_fill_dentries(struct dir_context *ctx, struct f2fs_dentry_ptr *d,
unsigned int start_pos, struct f2fs_str *fstr)
{
unsigned char d_type = DT_UNKNOWN;
unsigned int bit_pos;
struct f2fs_dir_entry *de = NULL;
struct f2fs_str de_name = FSTR_INIT(NULL, 0);
bit_pos = ((unsigned long)ctx->pos % d->max);
while (bit_pos < d->max) {
bit_pos = find_next_bit_le(d->bitmap, d->max, bit_pos);
if (bit_pos >= d->max)
break;
de = &d->dentry[bit_pos];
if (de->file_type < F2FS_FT_MAX)
d_type = f2fs_filetype_table[de->file_type];
else
d_type = DT_UNKNOWN;
/* encrypted case */
de_name.name = d->filename[bit_pos];
de_name.len = le16_to_cpu(de->name_len);
if (f2fs_encrypted_inode(d->inode)) {
int save_len = fstr->len;
int ret;
ret = f2fs_fname_disk_to_usr(d->inode, &de->hash_code,
&de_name, fstr);
de_name = *fstr;
fstr->len = save_len;
if (ret < 0)
return true;
}
if (!dir_emit(ctx, de_name.name, de_name.len,
le32_to_cpu(de->ino), d_type))
return true;
bit_pos += GET_DENTRY_SLOTS(le16_to_cpu(de->name_len));
ctx->pos = start_pos + bit_pos;
}
return false;
}
static int f2fs_readdir(struct file *file, struct dir_context *ctx)
{
struct inode *inode = file_inode(file);
unsigned long npages = dir_blocks(inode);
struct f2fs_dentry_block *dentry_blk = NULL;
struct page *dentry_page = NULL;
struct file_ra_state *ra = &file->f_ra;
unsigned int n = ((unsigned long)ctx->pos / NR_DENTRY_IN_BLOCK);
struct f2fs_dentry_ptr d;
struct f2fs_str fstr = FSTR_INIT(NULL, 0);
int err = 0;
if (f2fs_encrypted_inode(inode)) {
err = f2fs_get_encryption_info(inode);
if (err)
return err;
err = f2fs_fname_crypto_alloc_buffer(inode, F2FS_NAME_LEN,
&fstr);
if (err < 0)
return err;
}
if (f2fs_has_inline_dentry(inode)) {
err = f2fs_read_inline_dir(file, ctx, &fstr);
goto out;
}
/* readahead for multi pages of dir */
if (npages - n > 1 && !ra_has_index(ra, n))
page_cache_sync_readahead(inode->i_mapping, ra, file, n,
min(npages - n, (pgoff_t)MAX_DIR_RA_PAGES));
for (; n < npages; n++) {
dentry_page = get_lock_data_page(inode, n);
if (IS_ERR(dentry_page))
continue;
dentry_blk = kmap(dentry_page);
make_dentry_ptr(inode, &d, (void *)dentry_blk, 1);
if (f2fs_fill_dentries(ctx, &d, n * NR_DENTRY_IN_BLOCK, &fstr))
goto stop;
ctx->pos = (n + 1) * NR_DENTRY_IN_BLOCK;
kunmap(dentry_page);
f2fs_put_page(dentry_page, 1);
dentry_page = NULL;
}
stop:
if (dentry_page && !IS_ERR(dentry_page)) {
kunmap(dentry_page);
f2fs_put_page(dentry_page, 1);
}
out:
f2fs_fname_crypto_free_buffer(&fstr);
return err;
}
const struct file_operations f2fs_dir_operations = {
.llseek = generic_file_llseek,
.read = generic_read_dir,
.iterate = f2fs_readdir,
.fsync = f2fs_sync_file,
.unlocked_ioctl = f2fs_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = f2fs_compat_ioctl,
#endif
};
| gpl-2.0 |
jeboo/zte_a2017U_B27 | drivers/misc/ioc4.c | 463 | 14522 | /*
* 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) 2005-2006 Silicon Graphics, Inc. All Rights Reserved.
*/
/* This file contains the master driver module for use by SGI IOC4 subdrivers.
*
* It allocates any resources shared between multiple subdevices, and
* provides accessor functions (where needed) and the like for those
* resources. It also provides a mechanism for the subdevice modules
* to support loading and unloading.
*
* Non-shared resources (e.g. external interrupt A_INT_OUT register page
* alias, serial port and UART registers) are handled by the subdevice
* modules themselves.
*
* This is all necessary because IOC4 is not implemented as a multi-function
* PCI device, but an amalgamation of disparate registers for several
* types of device (ATA, serial, external interrupts). The normal
* resource management in the kernel doesn't have quite the right interfaces
* to handle this situation (e.g. multiple modules can't claim the same
* PCI ID), thus this IOC4 master module.
*/
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/ioc4.h>
#include <linux/ktime.h>
#include <linux/slab.h>
#include <linux/mutex.h>
#include <linux/time.h>
#include <asm/io.h>
/***************
* Definitions *
***************/
/* Tweakable values */
/* PCI bus speed detection/calibration */
#define IOC4_CALIBRATE_COUNT 63 /* Calibration cycle period */
#define IOC4_CALIBRATE_CYCLES 256 /* Average over this many cycles */
#define IOC4_CALIBRATE_DISCARD 2 /* Discard first few cycles */
#define IOC4_CALIBRATE_LOW_MHZ 25 /* Lower bound on bus speed sanity */
#define IOC4_CALIBRATE_HIGH_MHZ 75 /* Upper bound on bus speed sanity */
#define IOC4_CALIBRATE_DEFAULT_MHZ 66 /* Assumed if sanity check fails */
/************************
* Submodule management *
************************/
static DEFINE_MUTEX(ioc4_mutex);
static LIST_HEAD(ioc4_devices);
static LIST_HEAD(ioc4_submodules);
/* Register an IOC4 submodule */
int
ioc4_register_submodule(struct ioc4_submodule *is)
{
struct ioc4_driver_data *idd;
mutex_lock(&ioc4_mutex);
list_add(&is->is_list, &ioc4_submodules);
/* Initialize submodule for each IOC4 */
if (!is->is_probe)
goto out;
list_for_each_entry(idd, &ioc4_devices, idd_list) {
if (is->is_probe(idd)) {
printk(KERN_WARNING
"%s: IOC4 submodule %s probe failed "
"for pci_dev %s",
__func__, module_name(is->is_owner),
pci_name(idd->idd_pdev));
}
}
out:
mutex_unlock(&ioc4_mutex);
return 0;
}
/* Unregister an IOC4 submodule */
void
ioc4_unregister_submodule(struct ioc4_submodule *is)
{
struct ioc4_driver_data *idd;
mutex_lock(&ioc4_mutex);
list_del(&is->is_list);
/* Remove submodule for each IOC4 */
if (!is->is_remove)
goto out;
list_for_each_entry(idd, &ioc4_devices, idd_list) {
if (is->is_remove(idd)) {
printk(KERN_WARNING
"%s: IOC4 submodule %s remove failed "
"for pci_dev %s.\n",
__func__, module_name(is->is_owner),
pci_name(idd->idd_pdev));
}
}
out:
mutex_unlock(&ioc4_mutex);
}
/*********************
* Device management *
*********************/
#define IOC4_CALIBRATE_LOW_LIMIT \
(1000*IOC4_EXTINT_COUNT_DIVISOR/IOC4_CALIBRATE_LOW_MHZ)
#define IOC4_CALIBRATE_HIGH_LIMIT \
(1000*IOC4_EXTINT_COUNT_DIVISOR/IOC4_CALIBRATE_HIGH_MHZ)
#define IOC4_CALIBRATE_DEFAULT \
(1000*IOC4_EXTINT_COUNT_DIVISOR/IOC4_CALIBRATE_DEFAULT_MHZ)
#define IOC4_CALIBRATE_END \
(IOC4_CALIBRATE_CYCLES + IOC4_CALIBRATE_DISCARD)
#define IOC4_INT_OUT_MODE_TOGGLE 0x7 /* Toggle INT_OUT every COUNT+1 ticks */
/* Determines external interrupt output clock period of the PCI bus an
* IOC4 is attached to. This value can be used to determine the PCI
* bus speed.
*
* IOC4 has a design feature that various internal timers are derived from
* the PCI bus clock. This causes IOC4 device drivers to need to take the
* bus speed into account when setting various register values (e.g. INT_OUT
* register COUNT field, UART divisors, etc). Since this information is
* needed by several subdrivers, it is determined by the main IOC4 driver,
* even though the following code utilizes external interrupt registers
* to perform the speed calculation.
*/
static void
ioc4_clock_calibrate(struct ioc4_driver_data *idd)
{
union ioc4_int_out int_out;
union ioc4_gpcr gpcr;
unsigned int state, last_state = 1;
uint64_t start, end, period;
unsigned int count = 0;
/* Enable output */
gpcr.raw = 0;
gpcr.fields.dir = IOC4_GPCR_DIR_0;
gpcr.fields.int_out_en = 1;
writel(gpcr.raw, &idd->idd_misc_regs->gpcr_s.raw);
/* Reset to power-on state */
writel(0, &idd->idd_misc_regs->int_out.raw);
mmiowb();
/* Set up square wave */
int_out.raw = 0;
int_out.fields.count = IOC4_CALIBRATE_COUNT;
int_out.fields.mode = IOC4_INT_OUT_MODE_TOGGLE;
int_out.fields.diag = 0;
writel(int_out.raw, &idd->idd_misc_regs->int_out.raw);
mmiowb();
/* Check square wave period averaged over some number of cycles */
do {
int_out.raw = readl(&idd->idd_misc_regs->int_out.raw);
state = int_out.fields.int_out;
if (!last_state && state) {
count++;
if (count == IOC4_CALIBRATE_END) {
end = ktime_get_ns();
break;
} else if (count == IOC4_CALIBRATE_DISCARD)
start = ktime_get_ns();
}
last_state = state;
} while (1);
/* Calculation rearranged to preserve intermediate precision.
* Logically:
* 1. "end - start" gives us the measurement period over all
* the square wave cycles.
* 2. Divide by number of square wave cycles to get the period
* of a square wave cycle.
* 3. Divide by 2*(int_out.fields.count+1), which is the formula
* by which the IOC4 generates the square wave, to get the
* period of an IOC4 INT_OUT count.
*/
period = (end - start) /
(IOC4_CALIBRATE_CYCLES * 2 * (IOC4_CALIBRATE_COUNT + 1));
/* Bounds check the result. */
if (period > IOC4_CALIBRATE_LOW_LIMIT ||
period < IOC4_CALIBRATE_HIGH_LIMIT) {
printk(KERN_INFO
"IOC4 %s: Clock calibration failed. Assuming"
"PCI clock is %d ns.\n",
pci_name(idd->idd_pdev),
IOC4_CALIBRATE_DEFAULT / IOC4_EXTINT_COUNT_DIVISOR);
period = IOC4_CALIBRATE_DEFAULT;
} else {
u64 ns = period;
do_div(ns, IOC4_EXTINT_COUNT_DIVISOR);
printk(KERN_DEBUG
"IOC4 %s: PCI clock is %llu ns.\n",
pci_name(idd->idd_pdev), (unsigned long long)ns);
}
/* Remember results. We store the extint clock period rather
* than the PCI clock period so that greater precision is
* retained. Divide by IOC4_EXTINT_COUNT_DIVISOR to get
* PCI clock period.
*/
idd->count_period = period;
}
/* There are three variants of IOC4 cards: IO9, IO10, and PCI-RT.
* Each brings out different combinations of IOC4 signals, thus.
* the IOC4 subdrivers need to know to which we're attached.
*
* We look for the presence of a SCSI (IO9) or SATA (IO10) controller
* on the same PCI bus at slot number 3 to differentiate IO9 from IO10.
* If neither is present, it's a PCI-RT.
*/
static unsigned int
ioc4_variant(struct ioc4_driver_data *idd)
{
struct pci_dev *pdev = NULL;
int found = 0;
/* IO9: Look for a QLogic ISP 12160 at the same bus and slot 3. */
do {
pdev = pci_get_device(PCI_VENDOR_ID_QLOGIC,
PCI_DEVICE_ID_QLOGIC_ISP12160, pdev);
if (pdev &&
idd->idd_pdev->bus->number == pdev->bus->number &&
3 == PCI_SLOT(pdev->devfn))
found = 1;
} while (pdev && !found);
if (NULL != pdev) {
pci_dev_put(pdev);
return IOC4_VARIANT_IO9;
}
/* IO10: Look for a Vitesse VSC 7174 at the same bus and slot 3. */
pdev = NULL;
do {
pdev = pci_get_device(PCI_VENDOR_ID_VITESSE,
PCI_DEVICE_ID_VITESSE_VSC7174, pdev);
if (pdev &&
idd->idd_pdev->bus->number == pdev->bus->number &&
3 == PCI_SLOT(pdev->devfn))
found = 1;
} while (pdev && !found);
if (NULL != pdev) {
pci_dev_put(pdev);
return IOC4_VARIANT_IO10;
}
/* PCI-RT: No SCSI/SATA controller will be present */
return IOC4_VARIANT_PCI_RT;
}
static void
ioc4_load_modules(struct work_struct *work)
{
request_module("sgiioc4");
}
static DECLARE_WORK(ioc4_load_modules_work, ioc4_load_modules);
/* Adds a new instance of an IOC4 card */
static int
ioc4_probe(struct pci_dev *pdev, const struct pci_device_id *pci_id)
{
struct ioc4_driver_data *idd;
struct ioc4_submodule *is;
uint32_t pcmd;
int ret;
/* Enable IOC4 and take ownership of it */
if ((ret = pci_enable_device(pdev))) {
printk(KERN_WARNING
"%s: Failed to enable IOC4 device for pci_dev %s.\n",
__func__, pci_name(pdev));
goto out;
}
pci_set_master(pdev);
/* Set up per-IOC4 data */
idd = kmalloc(sizeof(struct ioc4_driver_data), GFP_KERNEL);
if (!idd) {
printk(KERN_WARNING
"%s: Failed to allocate IOC4 data for pci_dev %s.\n",
__func__, pci_name(pdev));
ret = -ENODEV;
goto out_idd;
}
idd->idd_pdev = pdev;
idd->idd_pci_id = pci_id;
/* Map IOC4 misc registers. These are shared between subdevices
* so the main IOC4 module manages them.
*/
idd->idd_bar0 = pci_resource_start(idd->idd_pdev, 0);
if (!idd->idd_bar0) {
printk(KERN_WARNING
"%s: Unable to find IOC4 misc resource "
"for pci_dev %s.\n",
__func__, pci_name(idd->idd_pdev));
ret = -ENODEV;
goto out_pci;
}
if (!request_mem_region(idd->idd_bar0, sizeof(struct ioc4_misc_regs),
"ioc4_misc")) {
printk(KERN_WARNING
"%s: Unable to request IOC4 misc region "
"for pci_dev %s.\n",
__func__, pci_name(idd->idd_pdev));
ret = -ENODEV;
goto out_pci;
}
idd->idd_misc_regs = ioremap(idd->idd_bar0,
sizeof(struct ioc4_misc_regs));
if (!idd->idd_misc_regs) {
printk(KERN_WARNING
"%s: Unable to remap IOC4 misc region "
"for pci_dev %s.\n",
__func__, pci_name(idd->idd_pdev));
ret = -ENODEV;
goto out_misc_region;
}
/* Failsafe portion of per-IOC4 initialization */
/* Detect card variant */
idd->idd_variant = ioc4_variant(idd);
printk(KERN_INFO "IOC4 %s: %s card detected.\n", pci_name(pdev),
idd->idd_variant == IOC4_VARIANT_IO9 ? "IO9" :
idd->idd_variant == IOC4_VARIANT_PCI_RT ? "PCI-RT" :
idd->idd_variant == IOC4_VARIANT_IO10 ? "IO10" : "unknown");
/* Initialize IOC4 */
pci_read_config_dword(idd->idd_pdev, PCI_COMMAND, &pcmd);
pci_write_config_dword(idd->idd_pdev, PCI_COMMAND,
pcmd | PCI_COMMAND_PARITY | PCI_COMMAND_SERR);
/* Determine PCI clock */
ioc4_clock_calibrate(idd);
/* Disable/clear all interrupts. Need to do this here lest
* one submodule request the shared IOC4 IRQ, but interrupt
* is generated by a different subdevice.
*/
/* Disable */
writel(~0, &idd->idd_misc_regs->other_iec.raw);
writel(~0, &idd->idd_misc_regs->sio_iec);
/* Clear (i.e. acknowledge) */
writel(~0, &idd->idd_misc_regs->other_ir.raw);
writel(~0, &idd->idd_misc_regs->sio_ir);
/* Track PCI-device specific data */
idd->idd_serial_data = NULL;
pci_set_drvdata(idd->idd_pdev, idd);
mutex_lock(&ioc4_mutex);
list_add_tail(&idd->idd_list, &ioc4_devices);
/* Add this IOC4 to all submodules */
list_for_each_entry(is, &ioc4_submodules, is_list) {
if (is->is_probe && is->is_probe(idd)) {
printk(KERN_WARNING
"%s: IOC4 submodule 0x%s probe failed "
"for pci_dev %s.\n",
__func__, module_name(is->is_owner),
pci_name(idd->idd_pdev));
}
}
mutex_unlock(&ioc4_mutex);
/* Request sgiioc4 IDE driver on boards that bring that functionality
* off of IOC4. The root filesystem may be hosted on a drive connected
* to IOC4, so we need to make sure the sgiioc4 driver is loaded as it
* won't be picked up by modprobes due to the ioc4 module owning the
* PCI device.
*/
if (idd->idd_variant != IOC4_VARIANT_PCI_RT) {
/* Request the module from a work procedure as the modprobe
* goes out to a userland helper and that will hang if done
* directly from ioc4_probe().
*/
printk(KERN_INFO "IOC4 loading sgiioc4 submodule\n");
schedule_work(&ioc4_load_modules_work);
}
return 0;
out_misc_region:
release_mem_region(idd->idd_bar0, sizeof(struct ioc4_misc_regs));
out_pci:
kfree(idd);
out_idd:
pci_disable_device(pdev);
out:
return ret;
}
/* Removes a particular instance of an IOC4 card. */
static void
ioc4_remove(struct pci_dev *pdev)
{
struct ioc4_submodule *is;
struct ioc4_driver_data *idd;
idd = pci_get_drvdata(pdev);
/* Remove this IOC4 from all submodules */
mutex_lock(&ioc4_mutex);
list_for_each_entry(is, &ioc4_submodules, is_list) {
if (is->is_remove && is->is_remove(idd)) {
printk(KERN_WARNING
"%s: IOC4 submodule 0x%s remove failed "
"for pci_dev %s.\n",
__func__, module_name(is->is_owner),
pci_name(idd->idd_pdev));
}
}
mutex_unlock(&ioc4_mutex);
/* Release resources */
iounmap(idd->idd_misc_regs);
if (!idd->idd_bar0) {
printk(KERN_WARNING
"%s: Unable to get IOC4 misc mapping for pci_dev %s. "
"Device removal may be incomplete.\n",
__func__, pci_name(idd->idd_pdev));
}
release_mem_region(idd->idd_bar0, sizeof(struct ioc4_misc_regs));
/* Disable IOC4 and relinquish */
pci_disable_device(pdev);
/* Remove and free driver data */
mutex_lock(&ioc4_mutex);
list_del(&idd->idd_list);
mutex_unlock(&ioc4_mutex);
kfree(idd);
}
static struct pci_device_id ioc4_id_table[] = {
{PCI_VENDOR_ID_SGI, PCI_DEVICE_ID_SGI_IOC4, PCI_ANY_ID,
PCI_ANY_ID, 0x0b4000, 0xFFFFFF},
{0}
};
static struct pci_driver ioc4_driver = {
.name = "IOC4",
.id_table = ioc4_id_table,
.probe = ioc4_probe,
.remove = ioc4_remove,
};
MODULE_DEVICE_TABLE(pci, ioc4_id_table);
/*********************
* Module management *
*********************/
/* Module load */
static int __init
ioc4_init(void)
{
return pci_register_driver(&ioc4_driver);
}
/* Module unload */
static void __exit
ioc4_exit(void)
{
/* Ensure ioc4_load_modules() has completed before exiting */
flush_work(&ioc4_load_modules_work);
pci_unregister_driver(&ioc4_driver);
}
module_init(ioc4_init);
module_exit(ioc4_exit);
MODULE_AUTHOR("Brent Casavant - Silicon Graphics, Inc. <bcasavan@sgi.com>");
MODULE_DESCRIPTION("PCI driver master module for SGI IOC4 Base-IO Card");
MODULE_LICENSE("GPL");
EXPORT_SYMBOL(ioc4_register_submodule);
EXPORT_SYMBOL(ioc4_unregister_submodule);
| gpl-2.0 |
FlorentRevest/kernel | drivers/usb/host/pci-quirks.c | 719 | 27901 | /*
* This file contains code to reset and initialize USB host controllers.
* Some of it includes work-arounds for PCI hardware and BIOS quirks.
* It may need to run early during booting -- before USB would normally
* initialize -- to ensure that Linux doesn't use any legacy modes.
*
* Copyright (c) 1999 Martin Mares <mj@ucw.cz>
* (and others)
*/
#include <linux/types.h>
#include <linux/kconfig.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/export.h>
#include <linux/acpi.h>
#include <linux/dmi.h>
#include "pci-quirks.h"
#include "xhci-ext-caps.h"
#define UHCI_USBLEGSUP 0xc0 /* legacy support */
#define UHCI_USBCMD 0 /* command register */
#define UHCI_USBINTR 4 /* interrupt register */
#define UHCI_USBLEGSUP_RWC 0x8f00 /* the R/WC bits */
#define UHCI_USBLEGSUP_RO 0x5040 /* R/O and reserved bits */
#define UHCI_USBCMD_RUN 0x0001 /* RUN/STOP bit */
#define UHCI_USBCMD_HCRESET 0x0002 /* Host Controller reset */
#define UHCI_USBCMD_EGSM 0x0008 /* Global Suspend Mode */
#define UHCI_USBCMD_CONFIGURE 0x0040 /* Config Flag */
#define UHCI_USBINTR_RESUME 0x0002 /* Resume interrupt enable */
#define OHCI_CONTROL 0x04
#define OHCI_CMDSTATUS 0x08
#define OHCI_INTRSTATUS 0x0c
#define OHCI_INTRENABLE 0x10
#define OHCI_INTRDISABLE 0x14
#define OHCI_FMINTERVAL 0x34
#define OHCI_HCFS (3 << 6) /* hc functional state */
#define OHCI_HCR (1 << 0) /* host controller reset */
#define OHCI_OCR (1 << 3) /* ownership change request */
#define OHCI_CTRL_RWC (1 << 9) /* remote wakeup connected */
#define OHCI_CTRL_IR (1 << 8) /* interrupt routing */
#define OHCI_INTR_OC (1 << 30) /* ownership change */
#define EHCI_HCC_PARAMS 0x08 /* extended capabilities */
#define EHCI_USBCMD 0 /* command register */
#define EHCI_USBCMD_RUN (1 << 0) /* RUN/STOP bit */
#define EHCI_USBSTS 4 /* status register */
#define EHCI_USBSTS_HALTED (1 << 12) /* HCHalted bit */
#define EHCI_USBINTR 8 /* interrupt register */
#define EHCI_CONFIGFLAG 0x40 /* configured flag register */
#define EHCI_USBLEGSUP 0 /* legacy support register */
#define EHCI_USBLEGSUP_BIOS (1 << 16) /* BIOS semaphore */
#define EHCI_USBLEGSUP_OS (1 << 24) /* OS semaphore */
#define EHCI_USBLEGCTLSTS 4 /* legacy control/status */
#define EHCI_USBLEGCTLSTS_SOOE (1 << 13) /* SMI on ownership change */
/* AMD quirk use */
#define AB_REG_BAR_LOW 0xe0
#define AB_REG_BAR_HIGH 0xe1
#define AB_REG_BAR_SB700 0xf0
#define AB_INDX(addr) ((addr) + 0x00)
#define AB_DATA(addr) ((addr) + 0x04)
#define AX_INDXC 0x30
#define AX_DATAC 0x34
#define NB_PCIE_INDX_ADDR 0xe0
#define NB_PCIE_INDX_DATA 0xe4
#define PCIE_P_CNTL 0x10040
#define BIF_NB 0x10002
#define NB_PIF0_PWRDOWN_0 0x01100012
#define NB_PIF0_PWRDOWN_1 0x01100013
#define USB_INTEL_XUSB2PR 0xD0
#define USB_INTEL_USB2PRM 0xD4
#define USB_INTEL_USB3_PSSEN 0xD8
#define USB_INTEL_USB3PRM 0xDC
static struct amd_chipset_info {
struct pci_dev *nb_dev;
struct pci_dev *smbus_dev;
int nb_type;
int sb_type;
int isoc_reqs;
int probe_count;
int probe_result;
} amd_chipset;
static DEFINE_SPINLOCK(amd_lock);
int usb_amd_find_chipset_info(void)
{
u8 rev = 0;
unsigned long flags;
struct amd_chipset_info info;
int ret;
spin_lock_irqsave(&amd_lock, flags);
/* probe only once */
if (amd_chipset.probe_count > 0) {
amd_chipset.probe_count++;
spin_unlock_irqrestore(&amd_lock, flags);
return amd_chipset.probe_result;
}
memset(&info, 0, sizeof(info));
spin_unlock_irqrestore(&amd_lock, flags);
info.smbus_dev = pci_get_device(PCI_VENDOR_ID_ATI, 0x4385, NULL);
if (info.smbus_dev) {
rev = info.smbus_dev->revision;
if (rev >= 0x40)
info.sb_type = 1;
else if (rev >= 0x30 && rev <= 0x3b)
info.sb_type = 3;
} else {
info.smbus_dev = pci_get_device(PCI_VENDOR_ID_AMD,
0x780b, NULL);
if (!info.smbus_dev) {
ret = 0;
goto commit;
}
rev = info.smbus_dev->revision;
if (rev >= 0x11 && rev <= 0x18)
info.sb_type = 2;
}
if (info.sb_type == 0) {
if (info.smbus_dev) {
pci_dev_put(info.smbus_dev);
info.smbus_dev = NULL;
}
ret = 0;
goto commit;
}
info.nb_dev = pci_get_device(PCI_VENDOR_ID_AMD, 0x9601, NULL);
if (info.nb_dev) {
info.nb_type = 1;
} else {
info.nb_dev = pci_get_device(PCI_VENDOR_ID_AMD, 0x1510, NULL);
if (info.nb_dev) {
info.nb_type = 2;
} else {
info.nb_dev = pci_get_device(PCI_VENDOR_ID_AMD,
0x9600, NULL);
if (info.nb_dev)
info.nb_type = 3;
}
}
ret = info.probe_result = 1;
printk(KERN_DEBUG "QUIRK: Enable AMD PLL fix\n");
commit:
spin_lock_irqsave(&amd_lock, flags);
if (amd_chipset.probe_count > 0) {
/* race - someone else was faster - drop devices */
/* Mark that we where here */
amd_chipset.probe_count++;
ret = amd_chipset.probe_result;
spin_unlock_irqrestore(&amd_lock, flags);
if (info.nb_dev)
pci_dev_put(info.nb_dev);
if (info.smbus_dev)
pci_dev_put(info.smbus_dev);
} else {
/* no race - commit the result */
info.probe_count++;
amd_chipset = info;
spin_unlock_irqrestore(&amd_lock, flags);
}
return ret;
}
EXPORT_SYMBOL_GPL(usb_amd_find_chipset_info);
/*
* The hardware normally enables the A-link power management feature, which
* lets the system lower the power consumption in idle states.
*
* This USB quirk prevents the link going into that lower power state
* during isochronous transfers.
*
* Without this quirk, isochronous stream on OHCI/EHCI/xHCI controllers of
* some AMD platforms may stutter or have breaks occasionally.
*/
static void usb_amd_quirk_pll(int disable)
{
u32 addr, addr_low, addr_high, val;
u32 bit = disable ? 0 : 1;
unsigned long flags;
spin_lock_irqsave(&amd_lock, flags);
if (disable) {
amd_chipset.isoc_reqs++;
if (amd_chipset.isoc_reqs > 1) {
spin_unlock_irqrestore(&amd_lock, flags);
return;
}
} else {
amd_chipset.isoc_reqs--;
if (amd_chipset.isoc_reqs > 0) {
spin_unlock_irqrestore(&amd_lock, flags);
return;
}
}
if (amd_chipset.sb_type == 1 || amd_chipset.sb_type == 2) {
outb_p(AB_REG_BAR_LOW, 0xcd6);
addr_low = inb_p(0xcd7);
outb_p(AB_REG_BAR_HIGH, 0xcd6);
addr_high = inb_p(0xcd7);
addr = addr_high << 8 | addr_low;
outl_p(0x30, AB_INDX(addr));
outl_p(0x40, AB_DATA(addr));
outl_p(0x34, AB_INDX(addr));
val = inl_p(AB_DATA(addr));
} else if (amd_chipset.sb_type == 3) {
pci_read_config_dword(amd_chipset.smbus_dev,
AB_REG_BAR_SB700, &addr);
outl(AX_INDXC, AB_INDX(addr));
outl(0x40, AB_DATA(addr));
outl(AX_DATAC, AB_INDX(addr));
val = inl(AB_DATA(addr));
} else {
spin_unlock_irqrestore(&amd_lock, flags);
return;
}
if (disable) {
val &= ~0x08;
val |= (1 << 4) | (1 << 9);
} else {
val |= 0x08;
val &= ~((1 << 4) | (1 << 9));
}
outl_p(val, AB_DATA(addr));
if (!amd_chipset.nb_dev) {
spin_unlock_irqrestore(&amd_lock, flags);
return;
}
if (amd_chipset.nb_type == 1 || amd_chipset.nb_type == 3) {
addr = PCIE_P_CNTL;
pci_write_config_dword(amd_chipset.nb_dev,
NB_PCIE_INDX_ADDR, addr);
pci_read_config_dword(amd_chipset.nb_dev,
NB_PCIE_INDX_DATA, &val);
val &= ~(1 | (1 << 3) | (1 << 4) | (1 << 9) | (1 << 12));
val |= bit | (bit << 3) | (bit << 12);
val |= ((!bit) << 4) | ((!bit) << 9);
pci_write_config_dword(amd_chipset.nb_dev,
NB_PCIE_INDX_DATA, val);
addr = BIF_NB;
pci_write_config_dword(amd_chipset.nb_dev,
NB_PCIE_INDX_ADDR, addr);
pci_read_config_dword(amd_chipset.nb_dev,
NB_PCIE_INDX_DATA, &val);
val &= ~(1 << 8);
val |= bit << 8;
pci_write_config_dword(amd_chipset.nb_dev,
NB_PCIE_INDX_DATA, val);
} else if (amd_chipset.nb_type == 2) {
addr = NB_PIF0_PWRDOWN_0;
pci_write_config_dword(amd_chipset.nb_dev,
NB_PCIE_INDX_ADDR, addr);
pci_read_config_dword(amd_chipset.nb_dev,
NB_PCIE_INDX_DATA, &val);
if (disable)
val &= ~(0x3f << 7);
else
val |= 0x3f << 7;
pci_write_config_dword(amd_chipset.nb_dev,
NB_PCIE_INDX_DATA, val);
addr = NB_PIF0_PWRDOWN_1;
pci_write_config_dword(amd_chipset.nb_dev,
NB_PCIE_INDX_ADDR, addr);
pci_read_config_dword(amd_chipset.nb_dev,
NB_PCIE_INDX_DATA, &val);
if (disable)
val &= ~(0x3f << 7);
else
val |= 0x3f << 7;
pci_write_config_dword(amd_chipset.nb_dev,
NB_PCIE_INDX_DATA, val);
}
spin_unlock_irqrestore(&amd_lock, flags);
return;
}
void usb_amd_quirk_pll_disable(void)
{
usb_amd_quirk_pll(1);
}
EXPORT_SYMBOL_GPL(usb_amd_quirk_pll_disable);
void usb_amd_quirk_pll_enable(void)
{
usb_amd_quirk_pll(0);
}
EXPORT_SYMBOL_GPL(usb_amd_quirk_pll_enable);
void usb_amd_dev_put(void)
{
struct pci_dev *nb, *smbus;
unsigned long flags;
spin_lock_irqsave(&amd_lock, flags);
amd_chipset.probe_count--;
if (amd_chipset.probe_count > 0) {
spin_unlock_irqrestore(&amd_lock, flags);
return;
}
/* save them to pci_dev_put outside of spinlock */
nb = amd_chipset.nb_dev;
smbus = amd_chipset.smbus_dev;
amd_chipset.nb_dev = NULL;
amd_chipset.smbus_dev = NULL;
amd_chipset.nb_type = 0;
amd_chipset.sb_type = 0;
amd_chipset.isoc_reqs = 0;
amd_chipset.probe_result = 0;
spin_unlock_irqrestore(&amd_lock, flags);
if (nb)
pci_dev_put(nb);
if (smbus)
pci_dev_put(smbus);
}
EXPORT_SYMBOL_GPL(usb_amd_dev_put);
/*
* Make sure the controller is completely inactive, unable to
* generate interrupts or do DMA.
*/
void uhci_reset_hc(struct pci_dev *pdev, unsigned long base)
{
/* Turn off PIRQ enable and SMI enable. (This also turns off the
* BIOS's USB Legacy Support.) Turn off all the R/WC bits too.
*/
pci_write_config_word(pdev, UHCI_USBLEGSUP, UHCI_USBLEGSUP_RWC);
/* Reset the HC - this will force us to get a
* new notification of any already connected
* ports due to the virtual disconnect that it
* implies.
*/
outw(UHCI_USBCMD_HCRESET, base + UHCI_USBCMD);
mb();
udelay(5);
if (inw(base + UHCI_USBCMD) & UHCI_USBCMD_HCRESET)
dev_warn(&pdev->dev, "HCRESET not completed yet!\n");
/* Just to be safe, disable interrupt requests and
* make sure the controller is stopped.
*/
outw(0, base + UHCI_USBINTR);
outw(0, base + UHCI_USBCMD);
}
EXPORT_SYMBOL_GPL(uhci_reset_hc);
/*
* Initialize a controller that was newly discovered or has just been
* resumed. In either case we can't be sure of its previous state.
*
* Returns: 1 if the controller was reset, 0 otherwise.
*/
int uhci_check_and_reset_hc(struct pci_dev *pdev, unsigned long base)
{
u16 legsup;
unsigned int cmd, intr;
/*
* When restarting a suspended controller, we expect all the
* settings to be the same as we left them:
*
* PIRQ and SMI disabled, no R/W bits set in USBLEGSUP;
* Controller is stopped and configured with EGSM set;
* No interrupts enabled except possibly Resume Detect.
*
* If any of these conditions are violated we do a complete reset.
*/
pci_read_config_word(pdev, UHCI_USBLEGSUP, &legsup);
if (legsup & ~(UHCI_USBLEGSUP_RO | UHCI_USBLEGSUP_RWC)) {
dev_dbg(&pdev->dev, "%s: legsup = 0x%04x\n",
__func__, legsup);
goto reset_needed;
}
cmd = inw(base + UHCI_USBCMD);
if ((cmd & UHCI_USBCMD_RUN) || !(cmd & UHCI_USBCMD_CONFIGURE) ||
!(cmd & UHCI_USBCMD_EGSM)) {
dev_dbg(&pdev->dev, "%s: cmd = 0x%04x\n",
__func__, cmd);
goto reset_needed;
}
intr = inw(base + UHCI_USBINTR);
if (intr & (~UHCI_USBINTR_RESUME)) {
dev_dbg(&pdev->dev, "%s: intr = 0x%04x\n",
__func__, intr);
goto reset_needed;
}
return 0;
reset_needed:
dev_dbg(&pdev->dev, "Performing full reset\n");
uhci_reset_hc(pdev, base);
return 1;
}
EXPORT_SYMBOL_GPL(uhci_check_and_reset_hc);
static inline int io_type_enabled(struct pci_dev *pdev, unsigned int mask)
{
u16 cmd;
return !pci_read_config_word(pdev, PCI_COMMAND, &cmd) && (cmd & mask);
}
#define pio_enabled(dev) io_type_enabled(dev, PCI_COMMAND_IO)
#define mmio_enabled(dev) io_type_enabled(dev, PCI_COMMAND_MEMORY)
static void quirk_usb_handoff_uhci(struct pci_dev *pdev)
{
unsigned long base = 0;
int i;
if (!pio_enabled(pdev))
return;
for (i = 0; i < PCI_ROM_RESOURCE; i++)
if ((pci_resource_flags(pdev, i) & IORESOURCE_IO)) {
base = pci_resource_start(pdev, i);
break;
}
if (base)
uhci_check_and_reset_hc(pdev, base);
}
static int mmio_resource_enabled(struct pci_dev *pdev, int idx)
{
return pci_resource_start(pdev, idx) && mmio_enabled(pdev);
}
static void quirk_usb_handoff_ohci(struct pci_dev *pdev)
{
void __iomem *base;
u32 control;
u32 fminterval;
int cnt;
if (!mmio_resource_enabled(pdev, 0))
return;
base = pci_ioremap_bar(pdev, 0);
if (base == NULL)
return;
control = readl(base + OHCI_CONTROL);
/* On PA-RISC, PDC can leave IR set incorrectly; ignore it there. */
#ifdef __hppa__
#define OHCI_CTRL_MASK (OHCI_CTRL_RWC | OHCI_CTRL_IR)
#else
#define OHCI_CTRL_MASK OHCI_CTRL_RWC
if (control & OHCI_CTRL_IR) {
int wait_time = 500; /* arbitrary; 5 seconds */
writel(OHCI_INTR_OC, base + OHCI_INTRENABLE);
writel(OHCI_OCR, base + OHCI_CMDSTATUS);
while (wait_time > 0 &&
readl(base + OHCI_CONTROL) & OHCI_CTRL_IR) {
wait_time -= 10;
msleep(10);
}
if (wait_time <= 0)
dev_warn(&pdev->dev, "OHCI: BIOS handoff failed"
" (BIOS bug?) %08x\n",
readl(base + OHCI_CONTROL));
}
#endif
/* disable interrupts */
writel((u32) ~0, base + OHCI_INTRDISABLE);
/* Reset the USB bus, if the controller isn't already in RESET */
if (control & OHCI_HCFS) {
/* Go into RESET, preserving RWC (and possibly IR) */
writel(control & OHCI_CTRL_MASK, base + OHCI_CONTROL);
readl(base + OHCI_CONTROL);
/* drive bus reset for at least 50 ms (7.1.7.5) */
msleep(50);
}
/* software reset of the controller, preserving HcFmInterval */
fminterval = readl(base + OHCI_FMINTERVAL);
writel(OHCI_HCR, base + OHCI_CMDSTATUS);
/* reset requires max 10 us delay */
for (cnt = 30; cnt > 0; --cnt) { /* ... allow extra time */
if ((readl(base + OHCI_CMDSTATUS) & OHCI_HCR) == 0)
break;
udelay(1);
}
writel(fminterval, base + OHCI_FMINTERVAL);
/* Now the controller is safely in SUSPEND and nothing can wake it up */
iounmap(base);
}
static const struct dmi_system_id ehci_dmi_nohandoff_table[] = {
{
/* Pegatron Lucid (ExoPC) */
.matches = {
DMI_MATCH(DMI_BOARD_NAME, "EXOPG06411"),
DMI_MATCH(DMI_BIOS_VERSION, "Lucid-CE-133"),
},
},
{
/* Pegatron Lucid (Ordissimo AIRIS) */
.matches = {
DMI_MATCH(DMI_BOARD_NAME, "M11JB"),
DMI_MATCH(DMI_BIOS_VERSION, "Lucid-"),
},
},
{
/* Pegatron Lucid (Ordissimo) */
.matches = {
DMI_MATCH(DMI_BOARD_NAME, "Ordissimo"),
DMI_MATCH(DMI_BIOS_VERSION, "Lucid-"),
},
},
{
/* HASEE E200 */
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "HASEE"),
DMI_MATCH(DMI_BOARD_NAME, "E210"),
DMI_MATCH(DMI_BIOS_VERSION, "6.00"),
},
},
{ }
};
static void ehci_bios_handoff(struct pci_dev *pdev,
void __iomem *op_reg_base,
u32 cap, u8 offset)
{
int try_handoff = 1, tried_handoff = 0;
/*
* The Pegatron Lucid tablet sporadically waits for 98 seconds trying
* the handoff on its unused controller. Skip it.
*
* The HASEE E200 hangs when the semaphore is set (bugzilla #77021).
*/
if (pdev->vendor == 0x8086 && (pdev->device == 0x283a ||
pdev->device == 0x27cc)) {
if (dmi_check_system(ehci_dmi_nohandoff_table))
try_handoff = 0;
}
if (try_handoff && (cap & EHCI_USBLEGSUP_BIOS)) {
dev_dbg(&pdev->dev, "EHCI: BIOS handoff\n");
#if 0
/* aleksey_gorelov@phoenix.com reports that some systems need SMI forced on,
* but that seems dubious in general (the BIOS left it off intentionally)
* and is known to prevent some systems from booting. so we won't do this
* unless maybe we can determine when we're on a system that needs SMI forced.
*/
/* BIOS workaround (?): be sure the pre-Linux code
* receives the SMI
*/
pci_read_config_dword(pdev, offset + EHCI_USBLEGCTLSTS, &val);
pci_write_config_dword(pdev, offset + EHCI_USBLEGCTLSTS,
val | EHCI_USBLEGCTLSTS_SOOE);
#endif
/* some systems get upset if this semaphore is
* set for any other reason than forcing a BIOS
* handoff..
*/
pci_write_config_byte(pdev, offset + 3, 1);
}
/* if boot firmware now owns EHCI, spin till it hands it over. */
if (try_handoff) {
int msec = 1000;
while ((cap & EHCI_USBLEGSUP_BIOS) && (msec > 0)) {
tried_handoff = 1;
msleep(10);
msec -= 10;
pci_read_config_dword(pdev, offset, &cap);
}
}
if (cap & EHCI_USBLEGSUP_BIOS) {
/* well, possibly buggy BIOS... try to shut it down,
* and hope nothing goes too wrong
*/
if (try_handoff)
dev_warn(&pdev->dev, "EHCI: BIOS handoff failed"
" (BIOS bug?) %08x\n", cap);
pci_write_config_byte(pdev, offset + 2, 0);
}
/* just in case, always disable EHCI SMIs */
pci_write_config_dword(pdev, offset + EHCI_USBLEGCTLSTS, 0);
/* If the BIOS ever owned the controller then we can't expect
* any power sessions to remain intact.
*/
if (tried_handoff)
writel(0, op_reg_base + EHCI_CONFIGFLAG);
}
static void quirk_usb_disable_ehci(struct pci_dev *pdev)
{
void __iomem *base, *op_reg_base;
u32 hcc_params, cap, val;
u8 offset, cap_length;
int wait_time, count = 256/4;
if (!mmio_resource_enabled(pdev, 0))
return;
base = pci_ioremap_bar(pdev, 0);
if (base == NULL)
return;
cap_length = readb(base);
op_reg_base = base + cap_length;
/* EHCI 0.96 and later may have "extended capabilities"
* spec section 5.1 explains the bios handoff, e.g. for
* booting from USB disk or using a usb keyboard
*/
hcc_params = readl(base + EHCI_HCC_PARAMS);
offset = (hcc_params >> 8) & 0xff;
while (offset && --count) {
pci_read_config_dword(pdev, offset, &cap);
switch (cap & 0xff) {
case 1:
ehci_bios_handoff(pdev, op_reg_base, cap, offset);
break;
case 0: /* Illegal reserved cap, set cap=0 so we exit */
cap = 0; /* then fallthrough... */
default:
dev_warn(&pdev->dev, "EHCI: unrecognized capability "
"%02x\n", cap & 0xff);
}
offset = (cap >> 8) & 0xff;
}
if (!count)
dev_printk(KERN_DEBUG, &pdev->dev, "EHCI: capability loop?\n");
/*
* halt EHCI & disable its interrupts in any case
*/
val = readl(op_reg_base + EHCI_USBSTS);
if ((val & EHCI_USBSTS_HALTED) == 0) {
val = readl(op_reg_base + EHCI_USBCMD);
val &= ~EHCI_USBCMD_RUN;
writel(val, op_reg_base + EHCI_USBCMD);
wait_time = 2000;
do {
writel(0x3f, op_reg_base + EHCI_USBSTS);
udelay(100);
wait_time -= 100;
val = readl(op_reg_base + EHCI_USBSTS);
if ((val == ~(u32)0) || (val & EHCI_USBSTS_HALTED)) {
break;
}
} while (wait_time > 0);
}
writel(0, op_reg_base + EHCI_USBINTR);
writel(0x3f, op_reg_base + EHCI_USBSTS);
iounmap(base);
}
/*
* handshake - spin reading a register until handshake completes
* @ptr: address of hc register to be read
* @mask: bits to look at in result of read
* @done: value of those bits when handshake succeeds
* @wait_usec: timeout in microseconds
* @delay_usec: delay in microseconds to wait between polling
*
* Polls a register every delay_usec microseconds.
* Returns 0 when the mask bits have the value done.
* Returns -ETIMEDOUT if this condition is not true after
* wait_usec microseconds have passed.
*/
static int handshake(void __iomem *ptr, u32 mask, u32 done,
int wait_usec, int delay_usec)
{
u32 result;
do {
result = readl(ptr);
result &= mask;
if (result == done)
return 0;
udelay(delay_usec);
wait_usec -= delay_usec;
} while (wait_usec > 0);
return -ETIMEDOUT;
}
#define PCI_DEVICE_ID_INTEL_LYNX_POINT_XHCI 0x8C31
#define PCI_DEVICE_ID_INTEL_LYNX_POINT_LP_XHCI 0x9C31
bool usb_is_intel_ppt_switchable_xhci(struct pci_dev *pdev)
{
return pdev->class == PCI_CLASS_SERIAL_USB_XHCI &&
pdev->vendor == PCI_VENDOR_ID_INTEL &&
pdev->device == PCI_DEVICE_ID_INTEL_PANTHERPOINT_XHCI;
}
/* The Intel Lynx Point chipset also has switchable ports. */
bool usb_is_intel_lpt_switchable_xhci(struct pci_dev *pdev)
{
return pdev->class == PCI_CLASS_SERIAL_USB_XHCI &&
pdev->vendor == PCI_VENDOR_ID_INTEL &&
(pdev->device == PCI_DEVICE_ID_INTEL_LYNX_POINT_XHCI ||
pdev->device == PCI_DEVICE_ID_INTEL_LYNX_POINT_LP_XHCI);
}
bool usb_is_intel_switchable_xhci(struct pci_dev *pdev)
{
return usb_is_intel_ppt_switchable_xhci(pdev) ||
usb_is_intel_lpt_switchable_xhci(pdev);
}
EXPORT_SYMBOL_GPL(usb_is_intel_switchable_xhci);
/*
* Intel's Panther Point chipset has two host controllers (EHCI and xHCI) that
* share some number of ports. These ports can be switched between either
* controller. Not all of the ports under the EHCI host controller may be
* switchable.
*
* The ports should be switched over to xHCI before PCI probes for any device
* start. This avoids active devices under EHCI being disconnected during the
* port switchover, which could cause loss of data on USB storage devices, or
* failed boot when the root file system is on a USB mass storage device and is
* enumerated under EHCI first.
*
* We write into the xHC's PCI configuration space in some Intel-specific
* registers to switch the ports over. The USB 3.0 terminations and the USB
* 2.0 data wires are switched separately. We want to enable the SuperSpeed
* terminations before switching the USB 2.0 wires over, so that USB 3.0
* devices connect at SuperSpeed, rather than at USB 2.0 speeds.
*/
void usb_enable_xhci_ports(struct pci_dev *xhci_pdev)
{
u32 ports_available;
/* Don't switchover the ports if the user hasn't compiled the xHCI
* driver. Otherwise they will see "dead" USB ports that don't power
* the devices.
*/
if (!IS_ENABLED(CONFIG_USB_XHCI_HCD)) {
dev_warn(&xhci_pdev->dev,
"CONFIG_USB_XHCI_HCD is turned off, "
"defaulting to EHCI.\n");
dev_warn(&xhci_pdev->dev,
"USB 3.0 devices will work at USB 2.0 speeds.\n");
usb_disable_xhci_ports(xhci_pdev);
return;
}
/* Read USB3PRM, the USB 3.0 Port Routing Mask Register
* Indicate the ports that can be changed from OS.
*/
pci_read_config_dword(xhci_pdev, USB_INTEL_USB3PRM,
&ports_available);
dev_dbg(&xhci_pdev->dev, "Configurable ports to enable SuperSpeed: 0x%x\n",
ports_available);
/* Write USB3_PSSEN, the USB 3.0 Port SuperSpeed Enable
* Register, to turn on SuperSpeed terminations for the
* switchable ports.
*/
pci_write_config_dword(xhci_pdev, USB_INTEL_USB3_PSSEN,
cpu_to_le32(ports_available));
pci_read_config_dword(xhci_pdev, USB_INTEL_USB3_PSSEN,
&ports_available);
dev_dbg(&xhci_pdev->dev, "USB 3.0 ports that are now enabled "
"under xHCI: 0x%x\n", ports_available);
/* Read XUSB2PRM, xHCI USB 2.0 Port Routing Mask Register
* Indicate the USB 2.0 ports to be controlled by the xHCI host.
*/
pci_read_config_dword(xhci_pdev, USB_INTEL_USB2PRM,
&ports_available);
dev_dbg(&xhci_pdev->dev, "Configurable USB 2.0 ports to hand over to xCHI: 0x%x\n",
ports_available);
/* Write XUSB2PR, the xHC USB 2.0 Port Routing Register, to
* switch the USB 2.0 power and data lines over to the xHCI
* host.
*/
pci_write_config_dword(xhci_pdev, USB_INTEL_XUSB2PR,
cpu_to_le32(ports_available));
pci_read_config_dword(xhci_pdev, USB_INTEL_XUSB2PR,
&ports_available);
dev_dbg(&xhci_pdev->dev, "USB 2.0 ports that are now switched over "
"to xHCI: 0x%x\n", ports_available);
}
EXPORT_SYMBOL_GPL(usb_enable_xhci_ports);
void usb_disable_xhci_ports(struct pci_dev *xhci_pdev)
{
pci_write_config_dword(xhci_pdev, USB_INTEL_USB3_PSSEN, 0x0);
pci_write_config_dword(xhci_pdev, USB_INTEL_XUSB2PR, 0x0);
}
EXPORT_SYMBOL_GPL(usb_disable_xhci_ports);
/**
* PCI Quirks for xHCI.
*
* Takes care of the handoff between the Pre-OS (i.e. BIOS) and the OS.
* It signals to the BIOS that the OS wants control of the host controller,
* and then waits 5 seconds for the BIOS to hand over control.
* If we timeout, assume the BIOS is broken and take control anyway.
*/
static void quirk_usb_handoff_xhci(struct pci_dev *pdev)
{
void __iomem *base;
int ext_cap_offset;
void __iomem *op_reg_base;
u32 val;
int timeout;
int len = pci_resource_len(pdev, 0);
if (!mmio_resource_enabled(pdev, 0))
return;
base = ioremap_nocache(pci_resource_start(pdev, 0), len);
if (base == NULL)
return;
/*
* Find the Legacy Support Capability register -
* this is optional for xHCI host controllers.
*/
ext_cap_offset = xhci_find_next_cap_offset(base, XHCI_HCC_PARAMS_OFFSET);
do {
if ((ext_cap_offset + sizeof(val)) > len) {
/* We're reading garbage from the controller */
dev_warn(&pdev->dev,
"xHCI controller failing to respond");
return;
}
if (!ext_cap_offset)
/* We've reached the end of the extended capabilities */
goto hc_init;
val = readl(base + ext_cap_offset);
if (XHCI_EXT_CAPS_ID(val) == XHCI_EXT_CAPS_LEGACY)
break;
ext_cap_offset = xhci_find_next_cap_offset(base, ext_cap_offset);
} while (1);
/* If the BIOS owns the HC, signal that the OS wants it, and wait */
if (val & XHCI_HC_BIOS_OWNED) {
writel(val | XHCI_HC_OS_OWNED, base + ext_cap_offset);
/* Wait for 5 seconds with 10 microsecond polling interval */
timeout = handshake(base + ext_cap_offset, XHCI_HC_BIOS_OWNED,
0, 5000, 10);
/* Assume a buggy BIOS and take HC ownership anyway */
if (timeout) {
dev_warn(&pdev->dev, "xHCI BIOS handoff failed"
" (BIOS bug ?) %08x\n", val);
writel(val & ~XHCI_HC_BIOS_OWNED, base + ext_cap_offset);
}
}
val = readl(base + ext_cap_offset + XHCI_LEGACY_CONTROL_OFFSET);
/* Mask off (turn off) any enabled SMIs */
val &= XHCI_LEGACY_DISABLE_SMI;
/* Mask all SMI events bits, RW1C */
val |= XHCI_LEGACY_SMI_EVENTS;
/* Disable any BIOS SMIs and clear all SMI events*/
writel(val, base + ext_cap_offset + XHCI_LEGACY_CONTROL_OFFSET);
hc_init:
if (usb_is_intel_switchable_xhci(pdev))
usb_enable_xhci_ports(pdev);
op_reg_base = base + XHCI_HC_LENGTH(readl(base));
/* Wait for the host controller to be ready before writing any
* operational or runtime registers. Wait 5 seconds and no more.
*/
timeout = handshake(op_reg_base + XHCI_STS_OFFSET, XHCI_STS_CNR, 0,
5000, 10);
/* Assume a buggy HC and start HC initialization anyway */
if (timeout) {
val = readl(op_reg_base + XHCI_STS_OFFSET);
dev_warn(&pdev->dev,
"xHCI HW not ready after 5 sec (HC bug?) "
"status = 0x%x\n", val);
}
/* Send the halt and disable interrupts command */
val = readl(op_reg_base + XHCI_CMD_OFFSET);
val &= ~(XHCI_CMD_RUN | XHCI_IRQS);
writel(val, op_reg_base + XHCI_CMD_OFFSET);
/* Wait for the HC to halt - poll every 125 usec (one microframe). */
timeout = handshake(op_reg_base + XHCI_STS_OFFSET, XHCI_STS_HALT, 1,
XHCI_MAX_HALT_USEC, 125);
if (timeout) {
val = readl(op_reg_base + XHCI_STS_OFFSET);
dev_warn(&pdev->dev,
"xHCI HW did not halt within %d usec "
"status = 0x%x\n", XHCI_MAX_HALT_USEC, val);
}
iounmap(base);
}
static void quirk_usb_early_handoff(struct pci_dev *pdev)
{
/* Skip Netlogic mips SoC's internal PCI USB controller.
* This device does not need/support EHCI/OHCI handoff
*/
if (pdev->vendor == 0x184e) /* vendor Netlogic */
return;
if (pdev->class != PCI_CLASS_SERIAL_USB_UHCI &&
pdev->class != PCI_CLASS_SERIAL_USB_OHCI &&
pdev->class != PCI_CLASS_SERIAL_USB_EHCI &&
pdev->class != PCI_CLASS_SERIAL_USB_XHCI)
return;
if (pci_enable_device(pdev) < 0) {
dev_warn(&pdev->dev, "Can't enable PCI device, "
"BIOS handoff failed.\n");
return;
}
if (pdev->class == PCI_CLASS_SERIAL_USB_UHCI)
quirk_usb_handoff_uhci(pdev);
else if (pdev->class == PCI_CLASS_SERIAL_USB_OHCI)
quirk_usb_handoff_ohci(pdev);
else if (pdev->class == PCI_CLASS_SERIAL_USB_EHCI)
quirk_usb_disable_ehci(pdev);
else if (pdev->class == PCI_CLASS_SERIAL_USB_XHCI)
quirk_usb_handoff_xhci(pdev);
pci_disable_device(pdev);
}
DECLARE_PCI_FIXUP_CLASS_FINAL(PCI_ANY_ID, PCI_ANY_ID,
PCI_CLASS_SERIAL_USB, 8, quirk_usb_early_handoff);
| gpl-2.0 |
Stefan-Schmidt/linux-wpan-next | drivers/nfc/s3fwrn5/nci.c | 719 | 4161 | /*
* NCI based driver for Samsung S3FWRN5 NFC chip
*
* Copyright (C) 2015 Samsung Electrnoics
* Robert Baldyga <r.baldyga@samsung.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2 or later, 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/completion.h>
#include <linux/firmware.h>
#include "s3fwrn5.h"
#include "nci.h"
static int s3fwrn5_nci_prop_rsp(struct nci_dev *ndev, struct sk_buff *skb)
{
__u8 status = skb->data[0];
nci_req_complete(ndev, status);
return 0;
}
static struct nci_driver_ops s3fwrn5_nci_prop_ops[] = {
{
.opcode = nci_opcode_pack(NCI_GID_PROPRIETARY,
NCI_PROP_AGAIN),
.rsp = s3fwrn5_nci_prop_rsp,
},
{
.opcode = nci_opcode_pack(NCI_GID_PROPRIETARY,
NCI_PROP_GET_RFREG),
.rsp = s3fwrn5_nci_prop_rsp,
},
{
.opcode = nci_opcode_pack(NCI_GID_PROPRIETARY,
NCI_PROP_SET_RFREG),
.rsp = s3fwrn5_nci_prop_rsp,
},
{
.opcode = nci_opcode_pack(NCI_GID_PROPRIETARY,
NCI_PROP_GET_RFREG_VER),
.rsp = s3fwrn5_nci_prop_rsp,
},
{
.opcode = nci_opcode_pack(NCI_GID_PROPRIETARY,
NCI_PROP_SET_RFREG_VER),
.rsp = s3fwrn5_nci_prop_rsp,
},
{
.opcode = nci_opcode_pack(NCI_GID_PROPRIETARY,
NCI_PROP_START_RFREG),
.rsp = s3fwrn5_nci_prop_rsp,
},
{
.opcode = nci_opcode_pack(NCI_GID_PROPRIETARY,
NCI_PROP_STOP_RFREG),
.rsp = s3fwrn5_nci_prop_rsp,
},
{
.opcode = nci_opcode_pack(NCI_GID_PROPRIETARY,
NCI_PROP_FW_CFG),
.rsp = s3fwrn5_nci_prop_rsp,
},
{
.opcode = nci_opcode_pack(NCI_GID_PROPRIETARY,
NCI_PROP_WR_RESET),
.rsp = s3fwrn5_nci_prop_rsp,
},
};
void s3fwrn5_nci_get_prop_ops(struct nci_driver_ops **ops, size_t *n)
{
*ops = s3fwrn5_nci_prop_ops;
*n = ARRAY_SIZE(s3fwrn5_nci_prop_ops);
}
#define S3FWRN5_RFREG_SECTION_SIZE 252
int s3fwrn5_nci_rf_configure(struct s3fwrn5_info *info, const char *fw_name)
{
const struct firmware *fw;
struct nci_prop_fw_cfg_cmd fw_cfg;
struct nci_prop_set_rfreg_cmd set_rfreg;
struct nci_prop_stop_rfreg_cmd stop_rfreg;
u32 checksum;
int i, len;
int ret;
ret = request_firmware(&fw, fw_name, &info->ndev->nfc_dev->dev);
if (ret < 0)
return ret;
/* Compute rfreg checksum */
checksum = 0;
for (i = 0; i < fw->size; i += 4)
checksum += *((u32 *)(fw->data+i));
/* Set default clock configuration for external crystal */
fw_cfg.clk_type = 0x01;
fw_cfg.clk_speed = 0xff;
fw_cfg.clk_req = 0xff;
ret = nci_prop_cmd(info->ndev, NCI_PROP_FW_CFG,
sizeof(fw_cfg), (__u8 *)&fw_cfg);
if (ret < 0)
goto out;
/* Start rfreg configuration */
dev_info(&info->ndev->nfc_dev->dev,
"rfreg configuration update: %s\n", fw_name);
ret = nci_prop_cmd(info->ndev, NCI_PROP_START_RFREG, 0, NULL);
if (ret < 0) {
dev_err(&info->ndev->nfc_dev->dev,
"Unable to start rfreg update\n");
goto out;
}
/* Update rfreg */
set_rfreg.index = 0;
for (i = 0; i < fw->size; i += S3FWRN5_RFREG_SECTION_SIZE) {
len = (fw->size - i < S3FWRN5_RFREG_SECTION_SIZE) ?
(fw->size - i) : S3FWRN5_RFREG_SECTION_SIZE;
memcpy(set_rfreg.data, fw->data+i, len);
ret = nci_prop_cmd(info->ndev, NCI_PROP_SET_RFREG,
len+1, (__u8 *)&set_rfreg);
if (ret < 0) {
dev_err(&info->ndev->nfc_dev->dev,
"rfreg update error (code=%d)\n", ret);
goto out;
}
set_rfreg.index++;
}
/* Finish rfreg configuration */
stop_rfreg.checksum = checksum & 0xffff;
ret = nci_prop_cmd(info->ndev, NCI_PROP_STOP_RFREG,
sizeof(stop_rfreg), (__u8 *)&stop_rfreg);
if (ret < 0) {
dev_err(&info->ndev->nfc_dev->dev,
"Unable to stop rfreg update\n");
goto out;
}
dev_info(&info->ndev->nfc_dev->dev,
"rfreg configuration update: success\n");
out:
release_firmware(fw);
return ret;
}
| gpl-2.0 |
davet321/rpi-linux | arch/mips/cavium-octeon/executive/cvmx-cmd-queue.c | 2255 | 9494 | /***********************license start***************
* Author: Cavium Networks
*
* Contact: support@caviumnetworks.com
* This file is part of the OCTEON SDK
*
* Copyright (c) 2003-2008 Cavium Networks
*
* This file 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 file is distributed in the hope that it will be useful, but
* AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
* NONINFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this file; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* or visit http://www.gnu.org/licenses/.
*
* This file may also be available under a different license from Cavium.
* Contact Cavium Networks for more information
***********************license end**************************************/
/*
* Support functions for managing command queues used for
* various hardware blocks.
*/
#include <linux/kernel.h>
#include <asm/octeon/octeon.h>
#include <asm/octeon/cvmx-config.h>
#include <asm/octeon/cvmx-fpa.h>
#include <asm/octeon/cvmx-cmd-queue.h>
#include <asm/octeon/cvmx-npei-defs.h>
#include <asm/octeon/cvmx-pexp-defs.h>
#include <asm/octeon/cvmx-pko-defs.h>
/**
* This application uses this pointer to access the global queue
* state. It points to a bootmem named block.
*/
__cvmx_cmd_queue_all_state_t *__cvmx_cmd_queue_state_ptr;
EXPORT_SYMBOL_GPL(__cvmx_cmd_queue_state_ptr);
/**
* Initialize the Global queue state pointer.
*
* Returns CVMX_CMD_QUEUE_SUCCESS or a failure code
*/
static cvmx_cmd_queue_result_t __cvmx_cmd_queue_init_state_ptr(void)
{
char *alloc_name = "cvmx_cmd_queues";
#if defined(CONFIG_CAVIUM_RESERVE32) && CONFIG_CAVIUM_RESERVE32
extern uint64_t octeon_reserve32_memory;
#endif
if (likely(__cvmx_cmd_queue_state_ptr))
return CVMX_CMD_QUEUE_SUCCESS;
#if defined(CONFIG_CAVIUM_RESERVE32) && CONFIG_CAVIUM_RESERVE32
if (octeon_reserve32_memory)
__cvmx_cmd_queue_state_ptr =
cvmx_bootmem_alloc_named_range(sizeof(*__cvmx_cmd_queue_state_ptr),
octeon_reserve32_memory,
octeon_reserve32_memory +
(CONFIG_CAVIUM_RESERVE32 <<
20) - 1, 128, alloc_name);
else
#endif
__cvmx_cmd_queue_state_ptr =
cvmx_bootmem_alloc_named(sizeof(*__cvmx_cmd_queue_state_ptr),
128,
alloc_name);
if (__cvmx_cmd_queue_state_ptr)
memset(__cvmx_cmd_queue_state_ptr, 0,
sizeof(*__cvmx_cmd_queue_state_ptr));
else {
struct cvmx_bootmem_named_block_desc *block_desc =
cvmx_bootmem_find_named_block(alloc_name);
if (block_desc)
__cvmx_cmd_queue_state_ptr =
cvmx_phys_to_ptr(block_desc->base_addr);
else {
cvmx_dprintf
("ERROR: cvmx_cmd_queue_initialize: Unable to get named block %s.\n",
alloc_name);
return CVMX_CMD_QUEUE_NO_MEMORY;
}
}
return CVMX_CMD_QUEUE_SUCCESS;
}
/**
* Initialize a command queue for use. The initial FPA buffer is
* allocated and the hardware unit is configured to point to the
* new command queue.
*
* @queue_id: Hardware command queue to initialize.
* @max_depth: Maximum outstanding commands that can be queued.
* @fpa_pool: FPA pool the command queues should come from.
* @pool_size: Size of each buffer in the FPA pool (bytes)
*
* Returns CVMX_CMD_QUEUE_SUCCESS or a failure code
*/
cvmx_cmd_queue_result_t cvmx_cmd_queue_initialize(cvmx_cmd_queue_id_t queue_id,
int max_depth, int fpa_pool,
int pool_size)
{
__cvmx_cmd_queue_state_t *qstate;
cvmx_cmd_queue_result_t result = __cvmx_cmd_queue_init_state_ptr();
if (result != CVMX_CMD_QUEUE_SUCCESS)
return result;
qstate = __cvmx_cmd_queue_get_state(queue_id);
if (qstate == NULL)
return CVMX_CMD_QUEUE_INVALID_PARAM;
/*
* We artificially limit max_depth to 1<<20 words. It is an
* arbitrary limit.
*/
if (CVMX_CMD_QUEUE_ENABLE_MAX_DEPTH) {
if ((max_depth < 0) || (max_depth > 1 << 20))
return CVMX_CMD_QUEUE_INVALID_PARAM;
} else if (max_depth != 0)
return CVMX_CMD_QUEUE_INVALID_PARAM;
if ((fpa_pool < 0) || (fpa_pool > 7))
return CVMX_CMD_QUEUE_INVALID_PARAM;
if ((pool_size < 128) || (pool_size > 65536))
return CVMX_CMD_QUEUE_INVALID_PARAM;
/* See if someone else has already initialized the queue */
if (qstate->base_ptr_div128) {
if (max_depth != (int)qstate->max_depth) {
cvmx_dprintf("ERROR: cvmx_cmd_queue_initialize: "
"Queue already initialized with different "
"max_depth (%d).\n",
(int)qstate->max_depth);
return CVMX_CMD_QUEUE_INVALID_PARAM;
}
if (fpa_pool != qstate->fpa_pool) {
cvmx_dprintf("ERROR: cvmx_cmd_queue_initialize: "
"Queue already initialized with different "
"FPA pool (%u).\n",
qstate->fpa_pool);
return CVMX_CMD_QUEUE_INVALID_PARAM;
}
if ((pool_size >> 3) - 1 != qstate->pool_size_m1) {
cvmx_dprintf("ERROR: cvmx_cmd_queue_initialize: "
"Queue already initialized with different "
"FPA pool size (%u).\n",
(qstate->pool_size_m1 + 1) << 3);
return CVMX_CMD_QUEUE_INVALID_PARAM;
}
CVMX_SYNCWS;
return CVMX_CMD_QUEUE_ALREADY_SETUP;
} else {
union cvmx_fpa_ctl_status status;
void *buffer;
status.u64 = cvmx_read_csr(CVMX_FPA_CTL_STATUS);
if (!status.s.enb) {
cvmx_dprintf("ERROR: cvmx_cmd_queue_initialize: "
"FPA is not enabled.\n");
return CVMX_CMD_QUEUE_NO_MEMORY;
}
buffer = cvmx_fpa_alloc(fpa_pool);
if (buffer == NULL) {
cvmx_dprintf("ERROR: cvmx_cmd_queue_initialize: "
"Unable to allocate initial buffer.\n");
return CVMX_CMD_QUEUE_NO_MEMORY;
}
memset(qstate, 0, sizeof(*qstate));
qstate->max_depth = max_depth;
qstate->fpa_pool = fpa_pool;
qstate->pool_size_m1 = (pool_size >> 3) - 1;
qstate->base_ptr_div128 = cvmx_ptr_to_phys(buffer) / 128;
/*
* We zeroed the now serving field so we need to also
* zero the ticket.
*/
__cvmx_cmd_queue_state_ptr->
ticket[__cvmx_cmd_queue_get_index(queue_id)] = 0;
CVMX_SYNCWS;
return CVMX_CMD_QUEUE_SUCCESS;
}
}
/**
* Shutdown a queue a free it's command buffers to the FPA. The
* hardware connected to the queue must be stopped before this
* function is called.
*
* @queue_id: Queue to shutdown
*
* Returns CVMX_CMD_QUEUE_SUCCESS or a failure code
*/
cvmx_cmd_queue_result_t cvmx_cmd_queue_shutdown(cvmx_cmd_queue_id_t queue_id)
{
__cvmx_cmd_queue_state_t *qptr = __cvmx_cmd_queue_get_state(queue_id);
if (qptr == NULL) {
cvmx_dprintf("ERROR: cvmx_cmd_queue_shutdown: Unable to "
"get queue information.\n");
return CVMX_CMD_QUEUE_INVALID_PARAM;
}
if (cvmx_cmd_queue_length(queue_id) > 0) {
cvmx_dprintf("ERROR: cvmx_cmd_queue_shutdown: Queue still "
"has data in it.\n");
return CVMX_CMD_QUEUE_FULL;
}
__cvmx_cmd_queue_lock(queue_id, qptr);
if (qptr->base_ptr_div128) {
cvmx_fpa_free(cvmx_phys_to_ptr
((uint64_t) qptr->base_ptr_div128 << 7),
qptr->fpa_pool, 0);
qptr->base_ptr_div128 = 0;
}
__cvmx_cmd_queue_unlock(qptr);
return CVMX_CMD_QUEUE_SUCCESS;
}
/**
* Return the number of command words pending in the queue. This
* function may be relatively slow for some hardware units.
*
* @queue_id: Hardware command queue to query
*
* Returns Number of outstanding commands
*/
int cvmx_cmd_queue_length(cvmx_cmd_queue_id_t queue_id)
{
if (CVMX_ENABLE_PARAMETER_CHECKING) {
if (__cvmx_cmd_queue_get_state(queue_id) == NULL)
return CVMX_CMD_QUEUE_INVALID_PARAM;
}
/*
* The cast is here so gcc with check that all values in the
* cvmx_cmd_queue_id_t enumeration are here.
*/
switch ((cvmx_cmd_queue_id_t) (queue_id & 0xff0000)) {
case CVMX_CMD_QUEUE_PKO_BASE:
/*
* FIXME: Need atomic lock on
* CVMX_PKO_REG_READ_IDX. Right now we are normally
* called with the queue lock, so that is a SLIGHT
* amount of protection.
*/
cvmx_write_csr(CVMX_PKO_REG_READ_IDX, queue_id & 0xffff);
if (OCTEON_IS_MODEL(OCTEON_CN3XXX)) {
union cvmx_pko_mem_debug9 debug9;
debug9.u64 = cvmx_read_csr(CVMX_PKO_MEM_DEBUG9);
return debug9.cn38xx.doorbell;
} else {
union cvmx_pko_mem_debug8 debug8;
debug8.u64 = cvmx_read_csr(CVMX_PKO_MEM_DEBUG8);
return debug8.cn58xx.doorbell;
}
case CVMX_CMD_QUEUE_ZIP:
case CVMX_CMD_QUEUE_DFA:
case CVMX_CMD_QUEUE_RAID:
/* FIXME: Implement other lengths */
return 0;
case CVMX_CMD_QUEUE_DMA_BASE:
{
union cvmx_npei_dmax_counts dmax_counts;
dmax_counts.u64 =
cvmx_read_csr(CVMX_PEXP_NPEI_DMAX_COUNTS
(queue_id & 0x7));
return dmax_counts.s.dbell;
}
case CVMX_CMD_QUEUE_END:
return CVMX_CMD_QUEUE_INVALID_PARAM;
}
return CVMX_CMD_QUEUE_INVALID_PARAM;
}
/**
* Return the command buffer to be written to. The purpose of this
* function is to allow CVMX routine access t othe low level buffer
* for initial hardware setup. User applications should not call this
* function directly.
*
* @queue_id: Command queue to query
*
* Returns Command buffer or NULL on failure
*/
void *cvmx_cmd_queue_buffer(cvmx_cmd_queue_id_t queue_id)
{
__cvmx_cmd_queue_state_t *qptr = __cvmx_cmd_queue_get_state(queue_id);
if (qptr && qptr->base_ptr_div128)
return cvmx_phys_to_ptr((uint64_t) qptr->base_ptr_div128 << 7);
else
return NULL;
}
| gpl-2.0 |
CowboyEnvy/Android_Kernel_samsung_amazing3gcri | fs/jffs2/readinode.c | 2511 | 44297 | /*
* JFFS2 -- Journalling Flash File System, Version 2.
*
* Copyright © 2001-2007 Red Hat, Inc.
*
* Created by David Woodhouse <dwmw2@infradead.org>
*
* For licensing information, see the file 'LICENCE' in this directory.
*
*/
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include <linux/crc32.h>
#include <linux/pagemap.h>
#include <linux/mtd/mtd.h>
#include <linux/compiler.h>
#include "nodelist.h"
/*
* Check the data CRC of the node.
*
* Returns: 0 if the data CRC is correct;
* 1 - if incorrect;
* error code if an error occurred.
*/
static int check_node_data(struct jffs2_sb_info *c, struct jffs2_tmp_dnode_info *tn)
{
struct jffs2_raw_node_ref *ref = tn->fn->raw;
int err = 0, pointed = 0;
struct jffs2_eraseblock *jeb;
unsigned char *buffer;
uint32_t crc, ofs, len;
size_t retlen;
BUG_ON(tn->csize == 0);
/* Calculate how many bytes were already checked */
ofs = ref_offset(ref) + sizeof(struct jffs2_raw_inode);
len = tn->csize;
if (jffs2_is_writebuffered(c)) {
int adj = ofs % c->wbuf_pagesize;
if (likely(adj))
adj = c->wbuf_pagesize - adj;
if (adj >= tn->csize) {
dbg_readinode("no need to check node at %#08x, data length %u, data starts at %#08x - it has already been checked.\n",
ref_offset(ref), tn->csize, ofs);
goto adj_acc;
}
ofs += adj;
len -= adj;
}
dbg_readinode("check node at %#08x, data length %u, partial CRC %#08x, correct CRC %#08x, data starts at %#08x, start checking from %#08x - %u bytes.\n",
ref_offset(ref), tn->csize, tn->partial_crc, tn->data_crc, ofs - len, ofs, len);
#ifndef __ECOS
/* TODO: instead, incapsulate point() stuff to jffs2_flash_read(),
* adding and jffs2_flash_read_end() interface. */
if (c->mtd->point) {
err = c->mtd->point(c->mtd, ofs, len, &retlen,
(void **)&buffer, NULL);
if (!err && retlen < len) {
JFFS2_WARNING("MTD point returned len too short: %zu instead of %u.\n", retlen, tn->csize);
c->mtd->unpoint(c->mtd, ofs, retlen);
} else if (err)
JFFS2_WARNING("MTD point failed: error code %d.\n", err);
else
pointed = 1; /* succefully pointed to device */
}
#endif
if (!pointed) {
buffer = kmalloc(len, GFP_KERNEL);
if (unlikely(!buffer))
return -ENOMEM;
/* TODO: this is very frequent pattern, make it a separate
* routine */
err = jffs2_flash_read(c, ofs, len, &retlen, buffer);
if (err) {
JFFS2_ERROR("can not read %d bytes from 0x%08x, error code: %d.\n", len, ofs, err);
goto free_out;
}
if (retlen != len) {
JFFS2_ERROR("short read at %#08x: %zd instead of %d.\n", ofs, retlen, len);
err = -EIO;
goto free_out;
}
}
/* Continue calculating CRC */
crc = crc32(tn->partial_crc, buffer, len);
if(!pointed)
kfree(buffer);
#ifndef __ECOS
else
c->mtd->unpoint(c->mtd, ofs, len);
#endif
if (crc != tn->data_crc) {
JFFS2_NOTICE("wrong data CRC in data node at 0x%08x: read %#08x, calculated %#08x.\n",
ref_offset(ref), tn->data_crc, crc);
return 1;
}
adj_acc:
jeb = &c->blocks[ref->flash_offset / c->sector_size];
len = ref_totlen(c, jeb, ref);
/* If it should be REF_NORMAL, it'll get marked as such when
we build the fragtree, shortly. No need to worry about GC
moving it while it's marked REF_PRISTINE -- GC won't happen
till we've finished checking every inode anyway. */
ref->flash_offset |= REF_PRISTINE;
/*
* Mark the node as having been checked and fix the
* accounting accordingly.
*/
spin_lock(&c->erase_completion_lock);
jeb->used_size += len;
jeb->unchecked_size -= len;
c->used_size += len;
c->unchecked_size -= len;
jffs2_dbg_acct_paranoia_check_nolock(c, jeb);
spin_unlock(&c->erase_completion_lock);
return 0;
free_out:
if(!pointed)
kfree(buffer);
#ifndef __ECOS
else
c->mtd->unpoint(c->mtd, ofs, len);
#endif
return err;
}
/*
* Helper function for jffs2_add_older_frag_to_fragtree().
*
* Checks the node if we are in the checking stage.
*/
static int check_tn_node(struct jffs2_sb_info *c, struct jffs2_tmp_dnode_info *tn)
{
int ret;
BUG_ON(ref_obsolete(tn->fn->raw));
/* We only check the data CRC of unchecked nodes */
if (ref_flags(tn->fn->raw) != REF_UNCHECKED)
return 0;
dbg_readinode("check node %#04x-%#04x, phys offs %#08x\n",
tn->fn->ofs, tn->fn->ofs + tn->fn->size, ref_offset(tn->fn->raw));
ret = check_node_data(c, tn);
if (unlikely(ret < 0)) {
JFFS2_ERROR("check_node_data() returned error: %d.\n",
ret);
} else if (unlikely(ret > 0)) {
dbg_readinode("CRC error, mark it obsolete.\n");
jffs2_mark_node_obsolete(c, tn->fn->raw);
}
return ret;
}
static struct jffs2_tmp_dnode_info *jffs2_lookup_tn(struct rb_root *tn_root, uint32_t offset)
{
struct rb_node *next;
struct jffs2_tmp_dnode_info *tn = NULL;
dbg_readinode("root %p, offset %d\n", tn_root, offset);
next = tn_root->rb_node;
while (next) {
tn = rb_entry(next, struct jffs2_tmp_dnode_info, rb);
if (tn->fn->ofs < offset)
next = tn->rb.rb_right;
else if (tn->fn->ofs >= offset)
next = tn->rb.rb_left;
else
break;
}
return tn;
}
static void jffs2_kill_tn(struct jffs2_sb_info *c, struct jffs2_tmp_dnode_info *tn)
{
jffs2_mark_node_obsolete(c, tn->fn->raw);
jffs2_free_full_dnode(tn->fn);
jffs2_free_tmp_dnode_info(tn);
}
/*
* This function is used when we read an inode. Data nodes arrive in
* arbitrary order -- they may be older or newer than the nodes which
* are already in the tree. Where overlaps occur, the older node can
* be discarded as long as the newer passes the CRC check. We don't
* bother to keep track of holes in this rbtree, and neither do we deal
* with frags -- we can have multiple entries starting at the same
* offset, and the one with the smallest length will come first in the
* ordering.
*
* Returns 0 if the node was handled (including marking it obsolete)
* < 0 an if error occurred
*/
static int jffs2_add_tn_to_tree(struct jffs2_sb_info *c,
struct jffs2_readinode_info *rii,
struct jffs2_tmp_dnode_info *tn)
{
uint32_t fn_end = tn->fn->ofs + tn->fn->size;
struct jffs2_tmp_dnode_info *this, *ptn;
dbg_readinode("insert fragment %#04x-%#04x, ver %u at %08x\n", tn->fn->ofs, fn_end, tn->version, ref_offset(tn->fn->raw));
/* If a node has zero dsize, we only have to keep if it if it might be the
node with highest version -- i.e. the one which will end up as f->metadata.
Note that such nodes won't be REF_UNCHECKED since there are no data to
check anyway. */
if (!tn->fn->size) {
if (rii->mdata_tn) {
if (rii->mdata_tn->version < tn->version) {
/* We had a candidate mdata node already */
dbg_readinode("kill old mdata with ver %d\n", rii->mdata_tn->version);
jffs2_kill_tn(c, rii->mdata_tn);
} else {
dbg_readinode("kill new mdata with ver %d (older than existing %d\n",
tn->version, rii->mdata_tn->version);
jffs2_kill_tn(c, tn);
return 0;
}
}
rii->mdata_tn = tn;
dbg_readinode("keep new mdata with ver %d\n", tn->version);
return 0;
}
/* Find the earliest node which _may_ be relevant to this one */
this = jffs2_lookup_tn(&rii->tn_root, tn->fn->ofs);
if (this) {
/* If the node is coincident with another at a lower address,
back up until the other node is found. It may be relevant */
while (this->overlapped) {
ptn = tn_prev(this);
if (!ptn) {
/*
* We killed a node which set the overlapped
* flags during the scan. Fix it up.
*/
this->overlapped = 0;
break;
}
this = ptn;
}
dbg_readinode("'this' found %#04x-%#04x (%s)\n", this->fn->ofs, this->fn->ofs + this->fn->size, this->fn ? "data" : "hole");
}
while (this) {
if (this->fn->ofs > fn_end)
break;
dbg_readinode("Ponder this ver %d, 0x%x-0x%x\n",
this->version, this->fn->ofs, this->fn->size);
if (this->version == tn->version) {
/* Version number collision means REF_PRISTINE GC. Accept either of them
as long as the CRC is correct. Check the one we have already... */
if (!check_tn_node(c, this)) {
/* The one we already had was OK. Keep it and throw away the new one */
dbg_readinode("Like old node. Throw away new\n");
jffs2_kill_tn(c, tn);
return 0;
} else {
/* Who cares if the new one is good; keep it for now anyway. */
dbg_readinode("Like new node. Throw away old\n");
rb_replace_node(&this->rb, &tn->rb, &rii->tn_root);
jffs2_kill_tn(c, this);
/* Same overlapping from in front and behind */
return 0;
}
}
if (this->version < tn->version &&
this->fn->ofs >= tn->fn->ofs &&
this->fn->ofs + this->fn->size <= fn_end) {
/* New node entirely overlaps 'this' */
if (check_tn_node(c, tn)) {
dbg_readinode("new node bad CRC\n");
jffs2_kill_tn(c, tn);
return 0;
}
/* ... and is good. Kill 'this' and any subsequent nodes which are also overlapped */
while (this && this->fn->ofs + this->fn->size <= fn_end) {
struct jffs2_tmp_dnode_info *next = tn_next(this);
if (this->version < tn->version) {
tn_erase(this, &rii->tn_root);
dbg_readinode("Kill overlapped ver %d, 0x%x-0x%x\n",
this->version, this->fn->ofs,
this->fn->ofs+this->fn->size);
jffs2_kill_tn(c, this);
}
this = next;
}
dbg_readinode("Done killing overlapped nodes\n");
continue;
}
if (this->version > tn->version &&
this->fn->ofs <= tn->fn->ofs &&
this->fn->ofs+this->fn->size >= fn_end) {
/* New node entirely overlapped by 'this' */
if (!check_tn_node(c, this)) {
dbg_readinode("Good CRC on old node. Kill new\n");
jffs2_kill_tn(c, tn);
return 0;
}
/* ... but 'this' was bad. Replace it... */
dbg_readinode("Bad CRC on old overlapping node. Kill it\n");
tn_erase(this, &rii->tn_root);
jffs2_kill_tn(c, this);
break;
}
this = tn_next(this);
}
/* We neither completely obsoleted nor were completely
obsoleted by an earlier node. Insert into the tree */
{
struct rb_node *parent;
struct rb_node **link = &rii->tn_root.rb_node;
struct jffs2_tmp_dnode_info *insert_point = NULL;
while (*link) {
parent = *link;
insert_point = rb_entry(parent, struct jffs2_tmp_dnode_info, rb);
if (tn->fn->ofs > insert_point->fn->ofs)
link = &insert_point->rb.rb_right;
else if (tn->fn->ofs < insert_point->fn->ofs ||
tn->fn->size < insert_point->fn->size)
link = &insert_point->rb.rb_left;
else
link = &insert_point->rb.rb_right;
}
rb_link_node(&tn->rb, &insert_point->rb, link);
rb_insert_color(&tn->rb, &rii->tn_root);
}
/* If there's anything behind that overlaps us, note it */
this = tn_prev(tn);
if (this) {
while (1) {
if (this->fn->ofs + this->fn->size > tn->fn->ofs) {
dbg_readinode("Node is overlapped by %p (v %d, 0x%x-0x%x)\n",
this, this->version, this->fn->ofs,
this->fn->ofs+this->fn->size);
tn->overlapped = 1;
break;
}
if (!this->overlapped)
break;
ptn = tn_prev(this);
if (!ptn) {
/*
* We killed a node which set the overlapped
* flags during the scan. Fix it up.
*/
this->overlapped = 0;
break;
}
this = ptn;
}
}
/* If the new node overlaps anything ahead, note it */
this = tn_next(tn);
while (this && this->fn->ofs < fn_end) {
this->overlapped = 1;
dbg_readinode("Node ver %d, 0x%x-0x%x is overlapped\n",
this->version, this->fn->ofs,
this->fn->ofs+this->fn->size);
this = tn_next(this);
}
return 0;
}
/* Trivial function to remove the last node in the tree. Which by definition
has no right-hand -- so can be removed just by making its only child (if
any) take its place under its parent. */
static void eat_last(struct rb_root *root, struct rb_node *node)
{
struct rb_node *parent = rb_parent(node);
struct rb_node **link;
/* LAST! */
BUG_ON(node->rb_right);
if (!parent)
link = &root->rb_node;
else if (node == parent->rb_left)
link = &parent->rb_left;
else
link = &parent->rb_right;
*link = node->rb_left;
/* Colour doesn't matter now. Only the parent pointer. */
if (node->rb_left)
node->rb_left->rb_parent_color = node->rb_parent_color;
}
/* We put this in reverse order, so we can just use eat_last */
static void ver_insert(struct rb_root *ver_root, struct jffs2_tmp_dnode_info *tn)
{
struct rb_node **link = &ver_root->rb_node;
struct rb_node *parent = NULL;
struct jffs2_tmp_dnode_info *this_tn;
while (*link) {
parent = *link;
this_tn = rb_entry(parent, struct jffs2_tmp_dnode_info, rb);
if (tn->version > this_tn->version)
link = &parent->rb_left;
else
link = &parent->rb_right;
}
dbg_readinode("Link new node at %p (root is %p)\n", link, ver_root);
rb_link_node(&tn->rb, parent, link);
rb_insert_color(&tn->rb, ver_root);
}
/* Build final, normal fragtree from tn tree. It doesn't matter which order
we add nodes to the real fragtree, as long as they don't overlap. And
having thrown away the majority of overlapped nodes as we went, there
really shouldn't be many sets of nodes which do overlap. If we start at
the end, we can use the overlap markers -- we can just eat nodes which
aren't overlapped, and when we encounter nodes which _do_ overlap we
sort them all into a temporary tree in version order before replaying them. */
static int jffs2_build_inode_fragtree(struct jffs2_sb_info *c,
struct jffs2_inode_info *f,
struct jffs2_readinode_info *rii)
{
struct jffs2_tmp_dnode_info *pen, *last, *this;
struct rb_root ver_root = RB_ROOT;
uint32_t high_ver = 0;
if (rii->mdata_tn) {
dbg_readinode("potential mdata is ver %d at %p\n", rii->mdata_tn->version, rii->mdata_tn);
high_ver = rii->mdata_tn->version;
rii->latest_ref = rii->mdata_tn->fn->raw;
}
#ifdef JFFS2_DBG_READINODE_MESSAGES
this = tn_last(&rii->tn_root);
while (this) {
dbg_readinode("tn %p ver %d range 0x%x-0x%x ov %d\n", this, this->version, this->fn->ofs,
this->fn->ofs+this->fn->size, this->overlapped);
this = tn_prev(this);
}
#endif
pen = tn_last(&rii->tn_root);
while ((last = pen)) {
pen = tn_prev(last);
eat_last(&rii->tn_root, &last->rb);
ver_insert(&ver_root, last);
if (unlikely(last->overlapped)) {
if (pen)
continue;
/*
* We killed a node which set the overlapped
* flags during the scan. Fix it up.
*/
last->overlapped = 0;
}
/* Now we have a bunch of nodes in reverse version
order, in the tree at ver_root. Most of the time,
there'll actually be only one node in the 'tree',
in fact. */
this = tn_last(&ver_root);
while (this) {
struct jffs2_tmp_dnode_info *vers_next;
int ret;
vers_next = tn_prev(this);
eat_last(&ver_root, &this->rb);
if (check_tn_node(c, this)) {
dbg_readinode("node ver %d, 0x%x-0x%x failed CRC\n",
this->version, this->fn->ofs,
this->fn->ofs+this->fn->size);
jffs2_kill_tn(c, this);
} else {
if (this->version > high_ver) {
/* Note that this is different from the other
highest_version, because this one is only
counting _valid_ nodes which could give the
latest inode metadata */
high_ver = this->version;
rii->latest_ref = this->fn->raw;
}
dbg_readinode("Add %p (v %d, 0x%x-0x%x, ov %d) to fragtree\n",
this, this->version, this->fn->ofs,
this->fn->ofs+this->fn->size, this->overlapped);
ret = jffs2_add_full_dnode_to_inode(c, f, this->fn);
if (ret) {
/* Free the nodes in vers_root; let the caller
deal with the rest */
JFFS2_ERROR("Add node to tree failed %d\n", ret);
while (1) {
vers_next = tn_prev(this);
if (check_tn_node(c, this))
jffs2_mark_node_obsolete(c, this->fn->raw);
jffs2_free_full_dnode(this->fn);
jffs2_free_tmp_dnode_info(this);
this = vers_next;
if (!this)
break;
eat_last(&ver_root, &vers_next->rb);
}
return ret;
}
jffs2_free_tmp_dnode_info(this);
}
this = vers_next;
}
}
return 0;
}
static void jffs2_free_tmp_dnode_info_list(struct rb_root *list)
{
struct rb_node *this;
struct jffs2_tmp_dnode_info *tn;
this = list->rb_node;
/* Now at bottom of tree */
while (this) {
if (this->rb_left)
this = this->rb_left;
else if (this->rb_right)
this = this->rb_right;
else {
tn = rb_entry(this, struct jffs2_tmp_dnode_info, rb);
jffs2_free_full_dnode(tn->fn);
jffs2_free_tmp_dnode_info(tn);
this = rb_parent(this);
if (!this)
break;
if (this->rb_left == &tn->rb)
this->rb_left = NULL;
else if (this->rb_right == &tn->rb)
this->rb_right = NULL;
else BUG();
}
}
*list = RB_ROOT;
}
static void jffs2_free_full_dirent_list(struct jffs2_full_dirent *fd)
{
struct jffs2_full_dirent *next;
while (fd) {
next = fd->next;
jffs2_free_full_dirent(fd);
fd = next;
}
}
/* Returns first valid node after 'ref'. May return 'ref' */
static struct jffs2_raw_node_ref *jffs2_first_valid_node(struct jffs2_raw_node_ref *ref)
{
while (ref && ref->next_in_ino) {
if (!ref_obsolete(ref))
return ref;
dbg_noderef("node at 0x%08x is obsoleted. Ignoring.\n", ref_offset(ref));
ref = ref->next_in_ino;
}
return NULL;
}
/*
* Helper function for jffs2_get_inode_nodes().
* It is called every time an directory entry node is found.
*
* Returns: 0 on success;
* negative error code on failure.
*/
static inline int read_direntry(struct jffs2_sb_info *c, struct jffs2_raw_node_ref *ref,
struct jffs2_raw_dirent *rd, size_t read,
struct jffs2_readinode_info *rii)
{
struct jffs2_full_dirent *fd;
uint32_t crc;
/* Obsoleted. This cannot happen, surely? dwmw2 20020308 */
BUG_ON(ref_obsolete(ref));
crc = crc32(0, rd, sizeof(*rd) - 8);
if (unlikely(crc != je32_to_cpu(rd->node_crc))) {
JFFS2_NOTICE("header CRC failed on dirent node at %#08x: read %#08x, calculated %#08x\n",
ref_offset(ref), je32_to_cpu(rd->node_crc), crc);
jffs2_mark_node_obsolete(c, ref);
return 0;
}
/* If we've never checked the CRCs on this node, check them now */
if (ref_flags(ref) == REF_UNCHECKED) {
struct jffs2_eraseblock *jeb;
int len;
/* Sanity check */
if (unlikely(PAD((rd->nsize + sizeof(*rd))) != PAD(je32_to_cpu(rd->totlen)))) {
JFFS2_ERROR("illegal nsize in node at %#08x: nsize %#02x, totlen %#04x\n",
ref_offset(ref), rd->nsize, je32_to_cpu(rd->totlen));
jffs2_mark_node_obsolete(c, ref);
return 0;
}
jeb = &c->blocks[ref->flash_offset / c->sector_size];
len = ref_totlen(c, jeb, ref);
spin_lock(&c->erase_completion_lock);
jeb->used_size += len;
jeb->unchecked_size -= len;
c->used_size += len;
c->unchecked_size -= len;
ref->flash_offset = ref_offset(ref) | dirent_node_state(rd);
spin_unlock(&c->erase_completion_lock);
}
fd = jffs2_alloc_full_dirent(rd->nsize + 1);
if (unlikely(!fd))
return -ENOMEM;
fd->raw = ref;
fd->version = je32_to_cpu(rd->version);
fd->ino = je32_to_cpu(rd->ino);
fd->type = rd->type;
if (fd->version > rii->highest_version)
rii->highest_version = fd->version;
/* Pick out the mctime of the latest dirent */
if(fd->version > rii->mctime_ver && je32_to_cpu(rd->mctime)) {
rii->mctime_ver = fd->version;
rii->latest_mctime = je32_to_cpu(rd->mctime);
}
/*
* Copy as much of the name as possible from the raw
* dirent we've already read from the flash.
*/
if (read > sizeof(*rd))
memcpy(&fd->name[0], &rd->name[0],
min_t(uint32_t, rd->nsize, (read - sizeof(*rd)) ));
/* Do we need to copy any more of the name directly from the flash? */
if (rd->nsize + sizeof(*rd) > read) {
/* FIXME: point() */
int err;
int already = read - sizeof(*rd);
err = jffs2_flash_read(c, (ref_offset(ref)) + read,
rd->nsize - already, &read, &fd->name[already]);
if (unlikely(read != rd->nsize - already) && likely(!err))
return -EIO;
if (unlikely(err)) {
JFFS2_ERROR("read remainder of name: error %d\n", err);
jffs2_free_full_dirent(fd);
return -EIO;
}
}
fd->nhash = full_name_hash(fd->name, rd->nsize);
fd->next = NULL;
fd->name[rd->nsize] = '\0';
/*
* Wheee. We now have a complete jffs2_full_dirent structure, with
* the name in it and everything. Link it into the list
*/
jffs2_add_fd_to_list(c, fd, &rii->fds);
return 0;
}
/*
* Helper function for jffs2_get_inode_nodes().
* It is called every time an inode node is found.
*
* Returns: 0 on success (possibly after marking a bad node obsolete);
* negative error code on failure.
*/
static inline int read_dnode(struct jffs2_sb_info *c, struct jffs2_raw_node_ref *ref,
struct jffs2_raw_inode *rd, int rdlen,
struct jffs2_readinode_info *rii)
{
struct jffs2_tmp_dnode_info *tn;
uint32_t len, csize;
int ret = 0;
uint32_t crc;
/* Obsoleted. This cannot happen, surely? dwmw2 20020308 */
BUG_ON(ref_obsolete(ref));
crc = crc32(0, rd, sizeof(*rd) - 8);
if (unlikely(crc != je32_to_cpu(rd->node_crc))) {
JFFS2_NOTICE("node CRC failed on dnode at %#08x: read %#08x, calculated %#08x\n",
ref_offset(ref), je32_to_cpu(rd->node_crc), crc);
jffs2_mark_node_obsolete(c, ref);
return 0;
}
tn = jffs2_alloc_tmp_dnode_info();
if (!tn) {
JFFS2_ERROR("failed to allocate tn (%zu bytes).\n", sizeof(*tn));
return -ENOMEM;
}
tn->partial_crc = 0;
csize = je32_to_cpu(rd->csize);
/* If we've never checked the CRCs on this node, check them now */
if (ref_flags(ref) == REF_UNCHECKED) {
/* Sanity checks */
if (unlikely(je32_to_cpu(rd->offset) > je32_to_cpu(rd->isize)) ||
unlikely(PAD(je32_to_cpu(rd->csize) + sizeof(*rd)) != PAD(je32_to_cpu(rd->totlen)))) {
JFFS2_WARNING("inode node header CRC is corrupted at %#08x\n", ref_offset(ref));
jffs2_dbg_dump_node(c, ref_offset(ref));
jffs2_mark_node_obsolete(c, ref);
goto free_out;
}
if (jffs2_is_writebuffered(c) && csize != 0) {
/* At this point we are supposed to check the data CRC
* of our unchecked node. But thus far, we do not
* know whether the node is valid or obsolete. To
* figure this out, we need to walk all the nodes of
* the inode and build the inode fragtree. We don't
* want to spend time checking data of nodes which may
* later be found to be obsolete. So we put off the full
* data CRC checking until we have read all the inode
* nodes and have started building the fragtree.
*
* The fragtree is being built starting with nodes
* having the highest version number, so we'll be able
* to detect whether a node is valid (i.e., it is not
* overlapped by a node with higher version) or not.
* And we'll be able to check only those nodes, which
* are not obsolete.
*
* Of course, this optimization only makes sense in case
* of NAND flashes (or other flashes with
* !jffs2_can_mark_obsolete()), since on NOR flashes
* nodes are marked obsolete physically.
*
* Since NAND flashes (or other flashes with
* jffs2_is_writebuffered(c)) are anyway read by
* fractions of c->wbuf_pagesize, and we have just read
* the node header, it is likely that the starting part
* of the node data is also read when we read the
* header. So we don't mind to check the CRC of the
* starting part of the data of the node now, and check
* the second part later (in jffs2_check_node_data()).
* Of course, we will not need to re-read and re-check
* the NAND page which we have just read. This is why we
* read the whole NAND page at jffs2_get_inode_nodes(),
* while we needed only the node header.
*/
unsigned char *buf;
/* 'buf' will point to the start of data */
buf = (unsigned char *)rd + sizeof(*rd);
/* len will be the read data length */
len = min_t(uint32_t, rdlen - sizeof(*rd), csize);
tn->partial_crc = crc32(0, buf, len);
dbg_readinode("Calculates CRC (%#08x) for %d bytes, csize %d\n", tn->partial_crc, len, csize);
/* If we actually calculated the whole data CRC
* and it is wrong, drop the node. */
if (len >= csize && unlikely(tn->partial_crc != je32_to_cpu(rd->data_crc))) {
JFFS2_NOTICE("wrong data CRC in data node at 0x%08x: read %#08x, calculated %#08x.\n",
ref_offset(ref), tn->partial_crc, je32_to_cpu(rd->data_crc));
jffs2_mark_node_obsolete(c, ref);
goto free_out;
}
} else if (csize == 0) {
/*
* We checked the header CRC. If the node has no data, adjust
* the space accounting now. For other nodes this will be done
* later either when the node is marked obsolete or when its
* data is checked.
*/
struct jffs2_eraseblock *jeb;
dbg_readinode("the node has no data.\n");
jeb = &c->blocks[ref->flash_offset / c->sector_size];
len = ref_totlen(c, jeb, ref);
spin_lock(&c->erase_completion_lock);
jeb->used_size += len;
jeb->unchecked_size -= len;
c->used_size += len;
c->unchecked_size -= len;
ref->flash_offset = ref_offset(ref) | REF_NORMAL;
spin_unlock(&c->erase_completion_lock);
}
}
tn->fn = jffs2_alloc_full_dnode();
if (!tn->fn) {
JFFS2_ERROR("alloc fn failed\n");
ret = -ENOMEM;
goto free_out;
}
tn->version = je32_to_cpu(rd->version);
tn->fn->ofs = je32_to_cpu(rd->offset);
tn->data_crc = je32_to_cpu(rd->data_crc);
tn->csize = csize;
tn->fn->raw = ref;
tn->overlapped = 0;
if (tn->version > rii->highest_version)
rii->highest_version = tn->version;
/* There was a bug where we wrote hole nodes out with
csize/dsize swapped. Deal with it */
if (rd->compr == JFFS2_COMPR_ZERO && !je32_to_cpu(rd->dsize) && csize)
tn->fn->size = csize;
else // normal case...
tn->fn->size = je32_to_cpu(rd->dsize);
dbg_readinode2("dnode @%08x: ver %u, offset %#04x, dsize %#04x, csize %#04x\n",
ref_offset(ref), je32_to_cpu(rd->version),
je32_to_cpu(rd->offset), je32_to_cpu(rd->dsize), csize);
ret = jffs2_add_tn_to_tree(c, rii, tn);
if (ret) {
jffs2_free_full_dnode(tn->fn);
free_out:
jffs2_free_tmp_dnode_info(tn);
return ret;
}
#ifdef JFFS2_DBG_READINODE2_MESSAGES
dbg_readinode2("After adding ver %d:\n", je32_to_cpu(rd->version));
tn = tn_first(&rii->tn_root);
while (tn) {
dbg_readinode2("%p: v %d r 0x%x-0x%x ov %d\n",
tn, tn->version, tn->fn->ofs,
tn->fn->ofs+tn->fn->size, tn->overlapped);
tn = tn_next(tn);
}
#endif
return 0;
}
/*
* Helper function for jffs2_get_inode_nodes().
* It is called every time an unknown node is found.
*
* Returns: 0 on success;
* negative error code on failure.
*/
static inline int read_unknown(struct jffs2_sb_info *c, struct jffs2_raw_node_ref *ref, struct jffs2_unknown_node *un)
{
/* We don't mark unknown nodes as REF_UNCHECKED */
if (ref_flags(ref) == REF_UNCHECKED) {
JFFS2_ERROR("REF_UNCHECKED but unknown node at %#08x\n",
ref_offset(ref));
JFFS2_ERROR("Node is {%04x,%04x,%08x,%08x}. Please report this error.\n",
je16_to_cpu(un->magic), je16_to_cpu(un->nodetype),
je32_to_cpu(un->totlen), je32_to_cpu(un->hdr_crc));
jffs2_mark_node_obsolete(c, ref);
return 0;
}
un->nodetype = cpu_to_je16(JFFS2_NODE_ACCURATE | je16_to_cpu(un->nodetype));
switch(je16_to_cpu(un->nodetype) & JFFS2_COMPAT_MASK) {
case JFFS2_FEATURE_INCOMPAT:
JFFS2_ERROR("unknown INCOMPAT nodetype %#04X at %#08x\n",
je16_to_cpu(un->nodetype), ref_offset(ref));
/* EEP */
BUG();
break;
case JFFS2_FEATURE_ROCOMPAT:
JFFS2_ERROR("unknown ROCOMPAT nodetype %#04X at %#08x\n",
je16_to_cpu(un->nodetype), ref_offset(ref));
BUG_ON(!(c->flags & JFFS2_SB_FLAG_RO));
break;
case JFFS2_FEATURE_RWCOMPAT_COPY:
JFFS2_NOTICE("unknown RWCOMPAT_COPY nodetype %#04X at %#08x\n",
je16_to_cpu(un->nodetype), ref_offset(ref));
break;
case JFFS2_FEATURE_RWCOMPAT_DELETE:
JFFS2_NOTICE("unknown RWCOMPAT_DELETE nodetype %#04X at %#08x\n",
je16_to_cpu(un->nodetype), ref_offset(ref));
jffs2_mark_node_obsolete(c, ref);
return 0;
}
return 0;
}
/*
* Helper function for jffs2_get_inode_nodes().
* The function detects whether more data should be read and reads it if yes.
*
* Returns: 0 on success;
* negative error code on failure.
*/
static int read_more(struct jffs2_sb_info *c, struct jffs2_raw_node_ref *ref,
int needed_len, int *rdlen, unsigned char *buf)
{
int err, to_read = needed_len - *rdlen;
size_t retlen;
uint32_t offs;
if (jffs2_is_writebuffered(c)) {
int rem = to_read % c->wbuf_pagesize;
if (rem)
to_read += c->wbuf_pagesize - rem;
}
/* We need to read more data */
offs = ref_offset(ref) + *rdlen;
dbg_readinode("read more %d bytes\n", to_read);
err = jffs2_flash_read(c, offs, to_read, &retlen, buf + *rdlen);
if (err) {
JFFS2_ERROR("can not read %d bytes from 0x%08x, "
"error code: %d.\n", to_read, offs, err);
return err;
}
if (retlen < to_read) {
JFFS2_ERROR("short read at %#08x: %zu instead of %d.\n",
offs, retlen, to_read);
return -EIO;
}
*rdlen += to_read;
return 0;
}
/* Get tmp_dnode_info and full_dirent for all non-obsolete nodes associated
with this ino. Perform a preliminary ordering on data nodes, throwing away
those which are completely obsoleted by newer ones. The naïve approach we
use to take of just returning them _all_ in version order will cause us to
run out of memory in certain degenerate cases. */
static int jffs2_get_inode_nodes(struct jffs2_sb_info *c, struct jffs2_inode_info *f,
struct jffs2_readinode_info *rii)
{
struct jffs2_raw_node_ref *ref, *valid_ref;
unsigned char *buf = NULL;
union jffs2_node_union *node;
size_t retlen;
int len, err;
rii->mctime_ver = 0;
dbg_readinode("ino #%u\n", f->inocache->ino);
/* FIXME: in case of NOR and available ->point() this
* needs to be fixed. */
len = sizeof(union jffs2_node_union) + c->wbuf_pagesize;
buf = kmalloc(len, GFP_KERNEL);
if (!buf)
return -ENOMEM;
spin_lock(&c->erase_completion_lock);
valid_ref = jffs2_first_valid_node(f->inocache->nodes);
if (!valid_ref && f->inocache->ino != 1)
JFFS2_WARNING("Eep. No valid nodes for ino #%u.\n", f->inocache->ino);
while (valid_ref) {
/* We can hold a pointer to a non-obsolete node without the spinlock,
but _obsolete_ nodes may disappear at any time, if the block
they're in gets erased. So if we mark 'ref' obsolete while we're
not holding the lock, it can go away immediately. For that reason,
we find the next valid node first, before processing 'ref'.
*/
ref = valid_ref;
valid_ref = jffs2_first_valid_node(ref->next_in_ino);
spin_unlock(&c->erase_completion_lock);
cond_resched();
/*
* At this point we don't know the type of the node we're going
* to read, so we do not know the size of its header. In order
* to minimize the amount of flash IO we assume the header is
* of size = JFFS2_MIN_NODE_HEADER.
*/
len = JFFS2_MIN_NODE_HEADER;
if (jffs2_is_writebuffered(c)) {
int end, rem;
/*
* We are about to read JFFS2_MIN_NODE_HEADER bytes,
* but this flash has some minimal I/O unit. It is
* possible that we'll need to read more soon, so read
* up to the next min. I/O unit, in order not to
* re-read the same min. I/O unit twice.
*/
end = ref_offset(ref) + len;
rem = end % c->wbuf_pagesize;
if (rem)
end += c->wbuf_pagesize - rem;
len = end - ref_offset(ref);
}
dbg_readinode("read %d bytes at %#08x(%d).\n", len, ref_offset(ref), ref_flags(ref));
/* FIXME: point() */
err = jffs2_flash_read(c, ref_offset(ref), len, &retlen, buf);
if (err) {
JFFS2_ERROR("can not read %d bytes from 0x%08x, " "error code: %d.\n", len, ref_offset(ref), err);
goto free_out;
}
if (retlen < len) {
JFFS2_ERROR("short read at %#08x: %zu instead of %d.\n", ref_offset(ref), retlen, len);
err = -EIO;
goto free_out;
}
node = (union jffs2_node_union *)buf;
/* No need to mask in the valid bit; it shouldn't be invalid */
if (je32_to_cpu(node->u.hdr_crc) != crc32(0, node, sizeof(node->u)-4)) {
JFFS2_NOTICE("Node header CRC failed at %#08x. {%04x,%04x,%08x,%08x}\n",
ref_offset(ref), je16_to_cpu(node->u.magic),
je16_to_cpu(node->u.nodetype),
je32_to_cpu(node->u.totlen),
je32_to_cpu(node->u.hdr_crc));
jffs2_dbg_dump_node(c, ref_offset(ref));
jffs2_mark_node_obsolete(c, ref);
goto cont;
}
if (je16_to_cpu(node->u.magic) != JFFS2_MAGIC_BITMASK) {
/* Not a JFFS2 node, whinge and move on */
JFFS2_NOTICE("Wrong magic bitmask 0x%04x in node header at %#08x.\n",
je16_to_cpu(node->u.magic), ref_offset(ref));
jffs2_mark_node_obsolete(c, ref);
goto cont;
}
switch (je16_to_cpu(node->u.nodetype)) {
case JFFS2_NODETYPE_DIRENT:
if (JFFS2_MIN_NODE_HEADER < sizeof(struct jffs2_raw_dirent) &&
len < sizeof(struct jffs2_raw_dirent)) {
err = read_more(c, ref, sizeof(struct jffs2_raw_dirent), &len, buf);
if (unlikely(err))
goto free_out;
}
err = read_direntry(c, ref, &node->d, retlen, rii);
if (unlikely(err))
goto free_out;
break;
case JFFS2_NODETYPE_INODE:
if (JFFS2_MIN_NODE_HEADER < sizeof(struct jffs2_raw_inode) &&
len < sizeof(struct jffs2_raw_inode)) {
err = read_more(c, ref, sizeof(struct jffs2_raw_inode), &len, buf);
if (unlikely(err))
goto free_out;
}
err = read_dnode(c, ref, &node->i, len, rii);
if (unlikely(err))
goto free_out;
break;
default:
if (JFFS2_MIN_NODE_HEADER < sizeof(struct jffs2_unknown_node) &&
len < sizeof(struct jffs2_unknown_node)) {
err = read_more(c, ref, sizeof(struct jffs2_unknown_node), &len, buf);
if (unlikely(err))
goto free_out;
}
err = read_unknown(c, ref, &node->u);
if (unlikely(err))
goto free_out;
}
cont:
spin_lock(&c->erase_completion_lock);
}
spin_unlock(&c->erase_completion_lock);
kfree(buf);
f->highest_version = rii->highest_version;
dbg_readinode("nodes of inode #%u were read, the highest version is %u, latest_mctime %u, mctime_ver %u.\n",
f->inocache->ino, rii->highest_version, rii->latest_mctime,
rii->mctime_ver);
return 0;
free_out:
jffs2_free_tmp_dnode_info_list(&rii->tn_root);
jffs2_free_full_dirent_list(rii->fds);
rii->fds = NULL;
kfree(buf);
return err;
}
static int jffs2_do_read_inode_internal(struct jffs2_sb_info *c,
struct jffs2_inode_info *f,
struct jffs2_raw_inode *latest_node)
{
struct jffs2_readinode_info rii;
uint32_t crc, new_size;
size_t retlen;
int ret;
dbg_readinode("ino #%u pino/nlink is %d\n", f->inocache->ino,
f->inocache->pino_nlink);
memset(&rii, 0, sizeof(rii));
/* Grab all nodes relevant to this ino */
ret = jffs2_get_inode_nodes(c, f, &rii);
if (ret) {
JFFS2_ERROR("cannot read nodes for ino %u, returned error is %d\n", f->inocache->ino, ret);
if (f->inocache->state == INO_STATE_READING)
jffs2_set_inocache_state(c, f->inocache, INO_STATE_CHECKEDABSENT);
return ret;
}
ret = jffs2_build_inode_fragtree(c, f, &rii);
if (ret) {
JFFS2_ERROR("Failed to build final fragtree for inode #%u: error %d\n",
f->inocache->ino, ret);
if (f->inocache->state == INO_STATE_READING)
jffs2_set_inocache_state(c, f->inocache, INO_STATE_CHECKEDABSENT);
jffs2_free_tmp_dnode_info_list(&rii.tn_root);
/* FIXME: We could at least crc-check them all */
if (rii.mdata_tn) {
jffs2_free_full_dnode(rii.mdata_tn->fn);
jffs2_free_tmp_dnode_info(rii.mdata_tn);
rii.mdata_tn = NULL;
}
return ret;
}
if (rii.mdata_tn) {
if (rii.mdata_tn->fn->raw == rii.latest_ref) {
f->metadata = rii.mdata_tn->fn;
jffs2_free_tmp_dnode_info(rii.mdata_tn);
} else {
jffs2_kill_tn(c, rii.mdata_tn);
}
rii.mdata_tn = NULL;
}
f->dents = rii.fds;
jffs2_dbg_fragtree_paranoia_check_nolock(f);
if (unlikely(!rii.latest_ref)) {
/* No data nodes for this inode. */
if (f->inocache->ino != 1) {
JFFS2_WARNING("no data nodes found for ino #%u\n", f->inocache->ino);
if (!rii.fds) {
if (f->inocache->state == INO_STATE_READING)
jffs2_set_inocache_state(c, f->inocache, INO_STATE_CHECKEDABSENT);
return -EIO;
}
JFFS2_NOTICE("but it has children so we fake some modes for it\n");
}
latest_node->mode = cpu_to_jemode(S_IFDIR|S_IRUGO|S_IWUSR|S_IXUGO);
latest_node->version = cpu_to_je32(0);
latest_node->atime = latest_node->ctime = latest_node->mtime = cpu_to_je32(0);
latest_node->isize = cpu_to_je32(0);
latest_node->gid = cpu_to_je16(0);
latest_node->uid = cpu_to_je16(0);
if (f->inocache->state == INO_STATE_READING)
jffs2_set_inocache_state(c, f->inocache, INO_STATE_PRESENT);
return 0;
}
ret = jffs2_flash_read(c, ref_offset(rii.latest_ref), sizeof(*latest_node), &retlen, (void *)latest_node);
if (ret || retlen != sizeof(*latest_node)) {
JFFS2_ERROR("failed to read from flash: error %d, %zd of %zd bytes read\n",
ret, retlen, sizeof(*latest_node));
/* FIXME: If this fails, there seems to be a memory leak. Find it. */
mutex_unlock(&f->sem);
jffs2_do_clear_inode(c, f);
return ret?ret:-EIO;
}
crc = crc32(0, latest_node, sizeof(*latest_node)-8);
if (crc != je32_to_cpu(latest_node->node_crc)) {
JFFS2_ERROR("CRC failed for read_inode of inode %u at physical location 0x%x\n",
f->inocache->ino, ref_offset(rii.latest_ref));
mutex_unlock(&f->sem);
jffs2_do_clear_inode(c, f);
return -EIO;
}
switch(jemode_to_cpu(latest_node->mode) & S_IFMT) {
case S_IFDIR:
if (rii.mctime_ver > je32_to_cpu(latest_node->version)) {
/* The times in the latest_node are actually older than
mctime in the latest dirent. Cheat. */
latest_node->ctime = latest_node->mtime = cpu_to_je32(rii.latest_mctime);
}
break;
case S_IFREG:
/* If it was a regular file, truncate it to the latest node's isize */
new_size = jffs2_truncate_fragtree(c, &f->fragtree, je32_to_cpu(latest_node->isize));
if (new_size != je32_to_cpu(latest_node->isize)) {
JFFS2_WARNING("Truncating ino #%u to %d bytes failed because it only had %d bytes to start with!\n",
f->inocache->ino, je32_to_cpu(latest_node->isize), new_size);
latest_node->isize = cpu_to_je32(new_size);
}
break;
case S_IFLNK:
/* Hack to work around broken isize in old symlink code.
Remove this when dwmw2 comes to his senses and stops
symlinks from being an entirely gratuitous special
case. */
if (!je32_to_cpu(latest_node->isize))
latest_node->isize = latest_node->dsize;
if (f->inocache->state != INO_STATE_CHECKING) {
/* Symlink's inode data is the target path. Read it and
* keep in RAM to facilitate quick follow symlink
* operation. */
f->target = kmalloc(je32_to_cpu(latest_node->csize) + 1, GFP_KERNEL);
if (!f->target) {
JFFS2_ERROR("can't allocate %d bytes of memory for the symlink target path cache\n", je32_to_cpu(latest_node->csize));
mutex_unlock(&f->sem);
jffs2_do_clear_inode(c, f);
return -ENOMEM;
}
ret = jffs2_flash_read(c, ref_offset(rii.latest_ref) + sizeof(*latest_node),
je32_to_cpu(latest_node->csize), &retlen, (char *)f->target);
if (ret || retlen != je32_to_cpu(latest_node->csize)) {
if (retlen != je32_to_cpu(latest_node->csize))
ret = -EIO;
kfree(f->target);
f->target = NULL;
mutex_unlock(&f->sem);
jffs2_do_clear_inode(c, f);
return ret;
}
f->target[je32_to_cpu(latest_node->csize)] = '\0';
dbg_readinode("symlink's target '%s' cached\n", f->target);
}
/* fall through... */
case S_IFBLK:
case S_IFCHR:
/* Certain inode types should have only one data node, and it's
kept as the metadata node */
if (f->metadata) {
JFFS2_ERROR("Argh. Special inode #%u with mode 0%o had metadata node\n",
f->inocache->ino, jemode_to_cpu(latest_node->mode));
mutex_unlock(&f->sem);
jffs2_do_clear_inode(c, f);
return -EIO;
}
if (!frag_first(&f->fragtree)) {
JFFS2_ERROR("Argh. Special inode #%u with mode 0%o has no fragments\n",
f->inocache->ino, jemode_to_cpu(latest_node->mode));
mutex_unlock(&f->sem);
jffs2_do_clear_inode(c, f);
return -EIO;
}
/* ASSERT: f->fraglist != NULL */
if (frag_next(frag_first(&f->fragtree))) {
JFFS2_ERROR("Argh. Special inode #%u with mode 0x%x had more than one node\n",
f->inocache->ino, jemode_to_cpu(latest_node->mode));
/* FIXME: Deal with it - check crc32, check for duplicate node, check times and discard the older one */
mutex_unlock(&f->sem);
jffs2_do_clear_inode(c, f);
return -EIO;
}
/* OK. We're happy */
f->metadata = frag_first(&f->fragtree)->node;
jffs2_free_node_frag(frag_first(&f->fragtree));
f->fragtree = RB_ROOT;
break;
}
if (f->inocache->state == INO_STATE_READING)
jffs2_set_inocache_state(c, f->inocache, INO_STATE_PRESENT);
return 0;
}
/* Scan the list of all nodes present for this ino, build map of versions, etc. */
int jffs2_do_read_inode(struct jffs2_sb_info *c, struct jffs2_inode_info *f,
uint32_t ino, struct jffs2_raw_inode *latest_node)
{
dbg_readinode("read inode #%u\n", ino);
retry_inocache:
spin_lock(&c->inocache_lock);
f->inocache = jffs2_get_ino_cache(c, ino);
if (f->inocache) {
/* Check its state. We may need to wait before we can use it */
switch(f->inocache->state) {
case INO_STATE_UNCHECKED:
case INO_STATE_CHECKEDABSENT:
f->inocache->state = INO_STATE_READING;
break;
case INO_STATE_CHECKING:
case INO_STATE_GC:
/* If it's in either of these states, we need
to wait for whoever's got it to finish and
put it back. */
dbg_readinode("waiting for ino #%u in state %d\n", ino, f->inocache->state);
sleep_on_spinunlock(&c->inocache_wq, &c->inocache_lock);
goto retry_inocache;
case INO_STATE_READING:
case INO_STATE_PRESENT:
/* Eep. This should never happen. It can
happen if Linux calls read_inode() again
before clear_inode() has finished though. */
JFFS2_ERROR("Eep. Trying to read_inode #%u when it's already in state %d!\n", ino, f->inocache->state);
/* Fail. That's probably better than allowing it to succeed */
f->inocache = NULL;
break;
default:
BUG();
}
}
spin_unlock(&c->inocache_lock);
if (!f->inocache && ino == 1) {
/* Special case - no root inode on medium */
f->inocache = jffs2_alloc_inode_cache();
if (!f->inocache) {
JFFS2_ERROR("cannot allocate inocache for root inode\n");
return -ENOMEM;
}
dbg_readinode("creating inocache for root inode\n");
memset(f->inocache, 0, sizeof(struct jffs2_inode_cache));
f->inocache->ino = f->inocache->pino_nlink = 1;
f->inocache->nodes = (struct jffs2_raw_node_ref *)f->inocache;
f->inocache->state = INO_STATE_READING;
jffs2_add_ino_cache(c, f->inocache);
}
if (!f->inocache) {
JFFS2_ERROR("requestied to read an nonexistent ino %u\n", ino);
return -ENOENT;
}
return jffs2_do_read_inode_internal(c, f, latest_node);
}
int jffs2_do_crccheck_inode(struct jffs2_sb_info *c, struct jffs2_inode_cache *ic)
{
struct jffs2_raw_inode n;
struct jffs2_inode_info *f = kzalloc(sizeof(*f), GFP_KERNEL);
int ret;
if (!f)
return -ENOMEM;
mutex_init(&f->sem);
mutex_lock(&f->sem);
f->inocache = ic;
ret = jffs2_do_read_inode_internal(c, f, &n);
if (!ret) {
mutex_unlock(&f->sem);
jffs2_do_clear_inode(c, f);
}
kfree (f);
return ret;
}
void jffs2_do_clear_inode(struct jffs2_sb_info *c, struct jffs2_inode_info *f)
{
struct jffs2_full_dirent *fd, *fds;
int deleted;
jffs2_xattr_delete_inode(c, f->inocache);
mutex_lock(&f->sem);
deleted = f->inocache && !f->inocache->pino_nlink;
if (f->inocache && f->inocache->state != INO_STATE_CHECKING)
jffs2_set_inocache_state(c, f->inocache, INO_STATE_CLEARING);
if (f->metadata) {
if (deleted)
jffs2_mark_node_obsolete(c, f->metadata->raw);
jffs2_free_full_dnode(f->metadata);
}
jffs2_kill_fragtree(&f->fragtree, deleted?c:NULL);
if (f->target) {
kfree(f->target);
f->target = NULL;
}
fds = f->dents;
while(fds) {
fd = fds;
fds = fd->next;
jffs2_free_full_dirent(fd);
}
if (f->inocache && f->inocache->state != INO_STATE_CHECKING) {
jffs2_set_inocache_state(c, f->inocache, INO_STATE_CHECKEDABSENT);
if (f->inocache->nodes == (void *)f->inocache)
jffs2_del_ino_cache(c, f->inocache);
}
mutex_unlock(&f->sem);
}
| gpl-2.0 |
FullGreen/cyanogenmod_kernel_samsung_smdk4412 | drivers/net/ixgb/ixgb_main.c | 2767 | 63444 | /*******************************************************************************
Intel PRO/10GbE Linux driver
Copyright(c) 1999 - 2008 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
Linux NICS <linux.nics@intel.com>
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/prefetch.h>
#include "ixgb.h"
char ixgb_driver_name[] = "ixgb";
static char ixgb_driver_string[] = "Intel(R) PRO/10GbE Network Driver";
#define DRIVERNAPI "-NAPI"
#define DRV_VERSION "1.0.135-k2" DRIVERNAPI
const char ixgb_driver_version[] = DRV_VERSION;
static const char ixgb_copyright[] = "Copyright (c) 1999-2008 Intel Corporation.";
#define IXGB_CB_LENGTH 256
static unsigned int copybreak __read_mostly = IXGB_CB_LENGTH;
module_param(copybreak, uint, 0644);
MODULE_PARM_DESC(copybreak,
"Maximum size of packet that is copied to a new buffer on receive");
/* ixgb_pci_tbl - PCI Device ID Table
*
* Wildcard entries (PCI_ANY_ID) should come last
* Last entry must be all 0s
*
* { Vendor ID, Device ID, SubVendor ID, SubDevice ID,
* Class, Class Mask, private data (not used) }
*/
static DEFINE_PCI_DEVICE_TABLE(ixgb_pci_tbl) = {
{INTEL_VENDOR_ID, IXGB_DEVICE_ID_82597EX,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{INTEL_VENDOR_ID, IXGB_DEVICE_ID_82597EX_CX4,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{INTEL_VENDOR_ID, IXGB_DEVICE_ID_82597EX_SR,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{INTEL_VENDOR_ID, IXGB_DEVICE_ID_82597EX_LR,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
/* required last entry */
{0,}
};
MODULE_DEVICE_TABLE(pci, ixgb_pci_tbl);
/* Local Function Prototypes */
static int ixgb_init_module(void);
static void ixgb_exit_module(void);
static int ixgb_probe(struct pci_dev *pdev, const struct pci_device_id *ent);
static void __devexit ixgb_remove(struct pci_dev *pdev);
static int ixgb_sw_init(struct ixgb_adapter *adapter);
static int ixgb_open(struct net_device *netdev);
static int ixgb_close(struct net_device *netdev);
static void ixgb_configure_tx(struct ixgb_adapter *adapter);
static void ixgb_configure_rx(struct ixgb_adapter *adapter);
static void ixgb_setup_rctl(struct ixgb_adapter *adapter);
static void ixgb_clean_tx_ring(struct ixgb_adapter *adapter);
static void ixgb_clean_rx_ring(struct ixgb_adapter *adapter);
static void ixgb_set_multi(struct net_device *netdev);
static void ixgb_watchdog(unsigned long data);
static netdev_tx_t ixgb_xmit_frame(struct sk_buff *skb,
struct net_device *netdev);
static struct net_device_stats *ixgb_get_stats(struct net_device *netdev);
static int ixgb_change_mtu(struct net_device *netdev, int new_mtu);
static int ixgb_set_mac(struct net_device *netdev, void *p);
static irqreturn_t ixgb_intr(int irq, void *data);
static bool ixgb_clean_tx_irq(struct ixgb_adapter *adapter);
static int ixgb_clean(struct napi_struct *, int);
static bool ixgb_clean_rx_irq(struct ixgb_adapter *, int *, int);
static void ixgb_alloc_rx_buffers(struct ixgb_adapter *, int);
static void ixgb_tx_timeout(struct net_device *dev);
static void ixgb_tx_timeout_task(struct work_struct *work);
static void ixgb_vlan_strip_enable(struct ixgb_adapter *adapter);
static void ixgb_vlan_strip_disable(struct ixgb_adapter *adapter);
static void ixgb_vlan_rx_add_vid(struct net_device *netdev, u16 vid);
static void ixgb_vlan_rx_kill_vid(struct net_device *netdev, u16 vid);
static void ixgb_restore_vlan(struct ixgb_adapter *adapter);
#ifdef CONFIG_NET_POLL_CONTROLLER
/* for netdump / net console */
static void ixgb_netpoll(struct net_device *dev);
#endif
static pci_ers_result_t ixgb_io_error_detected (struct pci_dev *pdev,
enum pci_channel_state state);
static pci_ers_result_t ixgb_io_slot_reset (struct pci_dev *pdev);
static void ixgb_io_resume (struct pci_dev *pdev);
static struct pci_error_handlers ixgb_err_handler = {
.error_detected = ixgb_io_error_detected,
.slot_reset = ixgb_io_slot_reset,
.resume = ixgb_io_resume,
};
static struct pci_driver ixgb_driver = {
.name = ixgb_driver_name,
.id_table = ixgb_pci_tbl,
.probe = ixgb_probe,
.remove = __devexit_p(ixgb_remove),
.err_handler = &ixgb_err_handler
};
MODULE_AUTHOR("Intel Corporation, <linux.nics@intel.com>");
MODULE_DESCRIPTION("Intel(R) PRO/10GbE Network Driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
#define DEFAULT_DEBUG_LEVEL_SHIFT 3
static int debug = DEFAULT_DEBUG_LEVEL_SHIFT;
module_param(debug, int, 0);
MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all)");
/**
* ixgb_init_module - Driver Registration Routine
*
* ixgb_init_module is the first routine called when the driver is
* loaded. All it does is register with the PCI subsystem.
**/
static int __init
ixgb_init_module(void)
{
pr_info("%s - version %s\n", ixgb_driver_string, ixgb_driver_version);
pr_info("%s\n", ixgb_copyright);
return pci_register_driver(&ixgb_driver);
}
module_init(ixgb_init_module);
/**
* ixgb_exit_module - Driver Exit Cleanup Routine
*
* ixgb_exit_module is called just before the driver is removed
* from memory.
**/
static void __exit
ixgb_exit_module(void)
{
pci_unregister_driver(&ixgb_driver);
}
module_exit(ixgb_exit_module);
/**
* ixgb_irq_disable - Mask off interrupt generation on the NIC
* @adapter: board private structure
**/
static void
ixgb_irq_disable(struct ixgb_adapter *adapter)
{
IXGB_WRITE_REG(&adapter->hw, IMC, ~0);
IXGB_WRITE_FLUSH(&adapter->hw);
synchronize_irq(adapter->pdev->irq);
}
/**
* ixgb_irq_enable - Enable default interrupt generation settings
* @adapter: board private structure
**/
static void
ixgb_irq_enable(struct ixgb_adapter *adapter)
{
u32 val = IXGB_INT_RXT0 | IXGB_INT_RXDMT0 |
IXGB_INT_TXDW | IXGB_INT_LSC;
if (adapter->hw.subsystem_vendor_id == SUN_SUBVENDOR_ID)
val |= IXGB_INT_GPI0;
IXGB_WRITE_REG(&adapter->hw, IMS, val);
IXGB_WRITE_FLUSH(&adapter->hw);
}
int
ixgb_up(struct ixgb_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
int err, irq_flags = IRQF_SHARED;
int max_frame = netdev->mtu + ENET_HEADER_SIZE + ENET_FCS_LENGTH;
struct ixgb_hw *hw = &adapter->hw;
/* hardware has been reset, we need to reload some things */
ixgb_rar_set(hw, netdev->dev_addr, 0);
ixgb_set_multi(netdev);
ixgb_restore_vlan(adapter);
ixgb_configure_tx(adapter);
ixgb_setup_rctl(adapter);
ixgb_configure_rx(adapter);
ixgb_alloc_rx_buffers(adapter, IXGB_DESC_UNUSED(&adapter->rx_ring));
/* disable interrupts and get the hardware into a known state */
IXGB_WRITE_REG(&adapter->hw, IMC, 0xffffffff);
/* only enable MSI if bus is in PCI-X mode */
if (IXGB_READ_REG(&adapter->hw, STATUS) & IXGB_STATUS_PCIX_MODE) {
err = pci_enable_msi(adapter->pdev);
if (!err) {
adapter->have_msi = 1;
irq_flags = 0;
}
/* proceed to try to request regular interrupt */
}
err = request_irq(adapter->pdev->irq, ixgb_intr, irq_flags,
netdev->name, netdev);
if (err) {
if (adapter->have_msi)
pci_disable_msi(adapter->pdev);
netif_err(adapter, probe, adapter->netdev,
"Unable to allocate interrupt Error: %d\n", err);
return err;
}
if ((hw->max_frame_size != max_frame) ||
(hw->max_frame_size !=
(IXGB_READ_REG(hw, MFS) >> IXGB_MFS_SHIFT))) {
hw->max_frame_size = max_frame;
IXGB_WRITE_REG(hw, MFS, hw->max_frame_size << IXGB_MFS_SHIFT);
if (hw->max_frame_size >
IXGB_MAX_ENET_FRAME_SIZE_WITHOUT_FCS + ENET_FCS_LENGTH) {
u32 ctrl0 = IXGB_READ_REG(hw, CTRL0);
if (!(ctrl0 & IXGB_CTRL0_JFE)) {
ctrl0 |= IXGB_CTRL0_JFE;
IXGB_WRITE_REG(hw, CTRL0, ctrl0);
}
}
}
clear_bit(__IXGB_DOWN, &adapter->flags);
napi_enable(&adapter->napi);
ixgb_irq_enable(adapter);
netif_wake_queue(netdev);
mod_timer(&adapter->watchdog_timer, jiffies);
return 0;
}
void
ixgb_down(struct ixgb_adapter *adapter, bool kill_watchdog)
{
struct net_device *netdev = adapter->netdev;
/* prevent the interrupt handler from restarting watchdog */
set_bit(__IXGB_DOWN, &adapter->flags);
napi_disable(&adapter->napi);
/* waiting for NAPI to complete can re-enable interrupts */
ixgb_irq_disable(adapter);
free_irq(adapter->pdev->irq, netdev);
if (adapter->have_msi)
pci_disable_msi(adapter->pdev);
if (kill_watchdog)
del_timer_sync(&adapter->watchdog_timer);
adapter->link_speed = 0;
adapter->link_duplex = 0;
netif_carrier_off(netdev);
netif_stop_queue(netdev);
ixgb_reset(adapter);
ixgb_clean_tx_ring(adapter);
ixgb_clean_rx_ring(adapter);
}
void
ixgb_reset(struct ixgb_adapter *adapter)
{
struct ixgb_hw *hw = &adapter->hw;
ixgb_adapter_stop(hw);
if (!ixgb_init_hw(hw))
netif_err(adapter, probe, adapter->netdev, "ixgb_init_hw failed\n");
/* restore frame size information */
IXGB_WRITE_REG(hw, MFS, hw->max_frame_size << IXGB_MFS_SHIFT);
if (hw->max_frame_size >
IXGB_MAX_ENET_FRAME_SIZE_WITHOUT_FCS + ENET_FCS_LENGTH) {
u32 ctrl0 = IXGB_READ_REG(hw, CTRL0);
if (!(ctrl0 & IXGB_CTRL0_JFE)) {
ctrl0 |= IXGB_CTRL0_JFE;
IXGB_WRITE_REG(hw, CTRL0, ctrl0);
}
}
}
static const struct net_device_ops ixgb_netdev_ops = {
.ndo_open = ixgb_open,
.ndo_stop = ixgb_close,
.ndo_start_xmit = ixgb_xmit_frame,
.ndo_get_stats = ixgb_get_stats,
.ndo_set_multicast_list = ixgb_set_multi,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = ixgb_set_mac,
.ndo_change_mtu = ixgb_change_mtu,
.ndo_tx_timeout = ixgb_tx_timeout,
.ndo_vlan_rx_add_vid = ixgb_vlan_rx_add_vid,
.ndo_vlan_rx_kill_vid = ixgb_vlan_rx_kill_vid,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = ixgb_netpoll,
#endif
};
/**
* ixgb_probe - Device Initialization Routine
* @pdev: PCI device information struct
* @ent: entry in ixgb_pci_tbl
*
* Returns 0 on success, negative on failure
*
* ixgb_probe initializes an adapter identified by a pci_dev structure.
* The OS initialization, configuring of the adapter private structure,
* and a hardware reset occur.
**/
static int __devinit
ixgb_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
struct net_device *netdev = NULL;
struct ixgb_adapter *adapter;
static int cards_found = 0;
int pci_using_dac;
int i;
int err;
err = pci_enable_device(pdev);
if (err)
return err;
pci_using_dac = 0;
err = dma_set_mask(&pdev->dev, DMA_BIT_MASK(64));
if (!err) {
err = dma_set_coherent_mask(&pdev->dev, DMA_BIT_MASK(64));
if (!err)
pci_using_dac = 1;
} else {
err = dma_set_mask(&pdev->dev, DMA_BIT_MASK(32));
if (err) {
err = dma_set_coherent_mask(&pdev->dev,
DMA_BIT_MASK(32));
if (err) {
pr_err("No usable DMA configuration, aborting\n");
goto err_dma_mask;
}
}
}
err = pci_request_regions(pdev, ixgb_driver_name);
if (err)
goto err_request_regions;
pci_set_master(pdev);
netdev = alloc_etherdev(sizeof(struct ixgb_adapter));
if (!netdev) {
err = -ENOMEM;
goto err_alloc_etherdev;
}
SET_NETDEV_DEV(netdev, &pdev->dev);
pci_set_drvdata(pdev, netdev);
adapter = netdev_priv(netdev);
adapter->netdev = netdev;
adapter->pdev = pdev;
adapter->hw.back = adapter;
adapter->msg_enable = netif_msg_init(debug, DEFAULT_DEBUG_LEVEL_SHIFT);
adapter->hw.hw_addr = pci_ioremap_bar(pdev, BAR_0);
if (!adapter->hw.hw_addr) {
err = -EIO;
goto err_ioremap;
}
for (i = BAR_1; i <= BAR_5; i++) {
if (pci_resource_len(pdev, i) == 0)
continue;
if (pci_resource_flags(pdev, i) & IORESOURCE_IO) {
adapter->hw.io_base = pci_resource_start(pdev, i);
break;
}
}
netdev->netdev_ops = &ixgb_netdev_ops;
ixgb_set_ethtool_ops(netdev);
netdev->watchdog_timeo = 5 * HZ;
netif_napi_add(netdev, &adapter->napi, ixgb_clean, 64);
strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1);
adapter->bd_number = cards_found;
adapter->link_speed = 0;
adapter->link_duplex = 0;
/* setup the private structure */
err = ixgb_sw_init(adapter);
if (err)
goto err_sw_init;
netdev->features = NETIF_F_SG |
NETIF_F_HW_CSUM |
NETIF_F_HW_VLAN_TX |
NETIF_F_HW_VLAN_RX |
NETIF_F_HW_VLAN_FILTER;
netdev->features |= NETIF_F_TSO;
if (pci_using_dac) {
netdev->features |= NETIF_F_HIGHDMA;
netdev->vlan_features |= NETIF_F_HIGHDMA;
}
/* make sure the EEPROM is good */
if (!ixgb_validate_eeprom_checksum(&adapter->hw)) {
netif_err(adapter, probe, adapter->netdev,
"The EEPROM Checksum Is Not Valid\n");
err = -EIO;
goto err_eeprom;
}
ixgb_get_ee_mac_addr(&adapter->hw, netdev->dev_addr);
memcpy(netdev->perm_addr, netdev->dev_addr, netdev->addr_len);
if (!is_valid_ether_addr(netdev->perm_addr)) {
netif_err(adapter, probe, adapter->netdev, "Invalid MAC Address\n");
err = -EIO;
goto err_eeprom;
}
adapter->part_num = ixgb_get_ee_pba_number(&adapter->hw);
init_timer(&adapter->watchdog_timer);
adapter->watchdog_timer.function = ixgb_watchdog;
adapter->watchdog_timer.data = (unsigned long)adapter;
INIT_WORK(&adapter->tx_timeout_task, ixgb_tx_timeout_task);
strcpy(netdev->name, "eth%d");
err = register_netdev(netdev);
if (err)
goto err_register;
/* carrier off reporting is important to ethtool even BEFORE open */
netif_carrier_off(netdev);
netif_info(adapter, probe, adapter->netdev,
"Intel(R) PRO/10GbE Network Connection\n");
ixgb_check_options(adapter);
/* reset the hardware with the new settings */
ixgb_reset(adapter);
cards_found++;
return 0;
err_register:
err_sw_init:
err_eeprom:
iounmap(adapter->hw.hw_addr);
err_ioremap:
free_netdev(netdev);
err_alloc_etherdev:
pci_release_regions(pdev);
err_request_regions:
err_dma_mask:
pci_disable_device(pdev);
return err;
}
/**
* ixgb_remove - Device Removal Routine
* @pdev: PCI device information struct
*
* ixgb_remove is called by the PCI subsystem to alert the driver
* that it should release a PCI device. The could be caused by a
* Hot-Plug event, or because the driver is going to be removed from
* memory.
**/
static void __devexit
ixgb_remove(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct ixgb_adapter *adapter = netdev_priv(netdev);
cancel_work_sync(&adapter->tx_timeout_task);
unregister_netdev(netdev);
iounmap(adapter->hw.hw_addr);
pci_release_regions(pdev);
free_netdev(netdev);
pci_disable_device(pdev);
}
/**
* ixgb_sw_init - Initialize general software structures (struct ixgb_adapter)
* @adapter: board private structure to initialize
*
* ixgb_sw_init initializes the Adapter private data structure.
* Fields are initialized based on PCI device information and
* OS network device settings (MTU size).
**/
static int __devinit
ixgb_sw_init(struct ixgb_adapter *adapter)
{
struct ixgb_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
/* PCI config space info */
hw->vendor_id = pdev->vendor;
hw->device_id = pdev->device;
hw->subsystem_vendor_id = pdev->subsystem_vendor;
hw->subsystem_id = pdev->subsystem_device;
hw->max_frame_size = netdev->mtu + ENET_HEADER_SIZE + ENET_FCS_LENGTH;
adapter->rx_buffer_len = hw->max_frame_size + 8; /* + 8 for errata */
if ((hw->device_id == IXGB_DEVICE_ID_82597EX) ||
(hw->device_id == IXGB_DEVICE_ID_82597EX_CX4) ||
(hw->device_id == IXGB_DEVICE_ID_82597EX_LR) ||
(hw->device_id == IXGB_DEVICE_ID_82597EX_SR))
hw->mac_type = ixgb_82597;
else {
/* should never have loaded on this device */
netif_err(adapter, probe, adapter->netdev, "unsupported device id\n");
}
/* enable flow control to be programmed */
hw->fc.send_xon = 1;
set_bit(__IXGB_DOWN, &adapter->flags);
return 0;
}
/**
* ixgb_open - Called when a network interface is made active
* @netdev: network interface device structure
*
* Returns 0 on success, negative value on failure
*
* The open entry point is called when a network interface is made
* active by the system (IFF_UP). At this point all resources needed
* for transmit and receive operations are allocated, the interrupt
* handler is registered with the OS, the watchdog timer is started,
* and the stack is notified that the interface is ready.
**/
static int
ixgb_open(struct net_device *netdev)
{
struct ixgb_adapter *adapter = netdev_priv(netdev);
int err;
/* allocate transmit descriptors */
err = ixgb_setup_tx_resources(adapter);
if (err)
goto err_setup_tx;
netif_carrier_off(netdev);
/* allocate receive descriptors */
err = ixgb_setup_rx_resources(adapter);
if (err)
goto err_setup_rx;
err = ixgb_up(adapter);
if (err)
goto err_up;
netif_start_queue(netdev);
return 0;
err_up:
ixgb_free_rx_resources(adapter);
err_setup_rx:
ixgb_free_tx_resources(adapter);
err_setup_tx:
ixgb_reset(adapter);
return err;
}
/**
* ixgb_close - Disables a network interface
* @netdev: network interface device structure
*
* Returns 0, this is not allowed to fail
*
* The close entry point is called when an interface is de-activated
* by the OS. The hardware is still under the drivers control, but
* needs to be disabled. A global MAC reset is issued to stop the
* hardware, and all transmit and receive resources are freed.
**/
static int
ixgb_close(struct net_device *netdev)
{
struct ixgb_adapter *adapter = netdev_priv(netdev);
ixgb_down(adapter, true);
ixgb_free_tx_resources(adapter);
ixgb_free_rx_resources(adapter);
return 0;
}
/**
* ixgb_setup_tx_resources - allocate Tx resources (Descriptors)
* @adapter: board private structure
*
* Return 0 on success, negative on failure
**/
int
ixgb_setup_tx_resources(struct ixgb_adapter *adapter)
{
struct ixgb_desc_ring *txdr = &adapter->tx_ring;
struct pci_dev *pdev = adapter->pdev;
int size;
size = sizeof(struct ixgb_buffer) * txdr->count;
txdr->buffer_info = vzalloc(size);
if (!txdr->buffer_info) {
netif_err(adapter, probe, adapter->netdev,
"Unable to allocate transmit descriptor ring memory\n");
return -ENOMEM;
}
/* round up to nearest 4K */
txdr->size = txdr->count * sizeof(struct ixgb_tx_desc);
txdr->size = ALIGN(txdr->size, 4096);
txdr->desc = dma_alloc_coherent(&pdev->dev, txdr->size, &txdr->dma,
GFP_KERNEL);
if (!txdr->desc) {
vfree(txdr->buffer_info);
netif_err(adapter, probe, adapter->netdev,
"Unable to allocate transmit descriptor memory\n");
return -ENOMEM;
}
memset(txdr->desc, 0, txdr->size);
txdr->next_to_use = 0;
txdr->next_to_clean = 0;
return 0;
}
/**
* ixgb_configure_tx - Configure 82597 Transmit Unit after Reset.
* @adapter: board private structure
*
* Configure the Tx unit of the MAC after a reset.
**/
static void
ixgb_configure_tx(struct ixgb_adapter *adapter)
{
u64 tdba = adapter->tx_ring.dma;
u32 tdlen = adapter->tx_ring.count * sizeof(struct ixgb_tx_desc);
u32 tctl;
struct ixgb_hw *hw = &adapter->hw;
/* Setup the Base and Length of the Tx Descriptor Ring
* tx_ring.dma can be either a 32 or 64 bit value
*/
IXGB_WRITE_REG(hw, TDBAL, (tdba & 0x00000000ffffffffULL));
IXGB_WRITE_REG(hw, TDBAH, (tdba >> 32));
IXGB_WRITE_REG(hw, TDLEN, tdlen);
/* Setup the HW Tx Head and Tail descriptor pointers */
IXGB_WRITE_REG(hw, TDH, 0);
IXGB_WRITE_REG(hw, TDT, 0);
/* don't set up txdctl, it induces performance problems if configured
* incorrectly */
/* Set the Tx Interrupt Delay register */
IXGB_WRITE_REG(hw, TIDV, adapter->tx_int_delay);
/* Program the Transmit Control Register */
tctl = IXGB_TCTL_TCE | IXGB_TCTL_TXEN | IXGB_TCTL_TPDE;
IXGB_WRITE_REG(hw, TCTL, tctl);
/* Setup Transmit Descriptor Settings for this adapter */
adapter->tx_cmd_type =
IXGB_TX_DESC_TYPE |
(adapter->tx_int_delay_enable ? IXGB_TX_DESC_CMD_IDE : 0);
}
/**
* ixgb_setup_rx_resources - allocate Rx resources (Descriptors)
* @adapter: board private structure
*
* Returns 0 on success, negative on failure
**/
int
ixgb_setup_rx_resources(struct ixgb_adapter *adapter)
{
struct ixgb_desc_ring *rxdr = &adapter->rx_ring;
struct pci_dev *pdev = adapter->pdev;
int size;
size = sizeof(struct ixgb_buffer) * rxdr->count;
rxdr->buffer_info = vzalloc(size);
if (!rxdr->buffer_info) {
netif_err(adapter, probe, adapter->netdev,
"Unable to allocate receive descriptor ring\n");
return -ENOMEM;
}
/* Round up to nearest 4K */
rxdr->size = rxdr->count * sizeof(struct ixgb_rx_desc);
rxdr->size = ALIGN(rxdr->size, 4096);
rxdr->desc = dma_alloc_coherent(&pdev->dev, rxdr->size, &rxdr->dma,
GFP_KERNEL);
if (!rxdr->desc) {
vfree(rxdr->buffer_info);
netif_err(adapter, probe, adapter->netdev,
"Unable to allocate receive descriptors\n");
return -ENOMEM;
}
memset(rxdr->desc, 0, rxdr->size);
rxdr->next_to_clean = 0;
rxdr->next_to_use = 0;
return 0;
}
/**
* ixgb_setup_rctl - configure the receive control register
* @adapter: Board private structure
**/
static void
ixgb_setup_rctl(struct ixgb_adapter *adapter)
{
u32 rctl;
rctl = IXGB_READ_REG(&adapter->hw, RCTL);
rctl &= ~(3 << IXGB_RCTL_MO_SHIFT);
rctl |=
IXGB_RCTL_BAM | IXGB_RCTL_RDMTS_1_2 |
IXGB_RCTL_RXEN | IXGB_RCTL_CFF |
(adapter->hw.mc_filter_type << IXGB_RCTL_MO_SHIFT);
rctl |= IXGB_RCTL_SECRC;
if (adapter->rx_buffer_len <= IXGB_RXBUFFER_2048)
rctl |= IXGB_RCTL_BSIZE_2048;
else if (adapter->rx_buffer_len <= IXGB_RXBUFFER_4096)
rctl |= IXGB_RCTL_BSIZE_4096;
else if (adapter->rx_buffer_len <= IXGB_RXBUFFER_8192)
rctl |= IXGB_RCTL_BSIZE_8192;
else if (adapter->rx_buffer_len <= IXGB_RXBUFFER_16384)
rctl |= IXGB_RCTL_BSIZE_16384;
IXGB_WRITE_REG(&adapter->hw, RCTL, rctl);
}
/**
* ixgb_configure_rx - Configure 82597 Receive Unit after Reset.
* @adapter: board private structure
*
* Configure the Rx unit of the MAC after a reset.
**/
static void
ixgb_configure_rx(struct ixgb_adapter *adapter)
{
u64 rdba = adapter->rx_ring.dma;
u32 rdlen = adapter->rx_ring.count * sizeof(struct ixgb_rx_desc);
struct ixgb_hw *hw = &adapter->hw;
u32 rctl;
u32 rxcsum;
/* make sure receives are disabled while setting up the descriptors */
rctl = IXGB_READ_REG(hw, RCTL);
IXGB_WRITE_REG(hw, RCTL, rctl & ~IXGB_RCTL_RXEN);
/* set the Receive Delay Timer Register */
IXGB_WRITE_REG(hw, RDTR, adapter->rx_int_delay);
/* Setup the Base and Length of the Rx Descriptor Ring */
IXGB_WRITE_REG(hw, RDBAL, (rdba & 0x00000000ffffffffULL));
IXGB_WRITE_REG(hw, RDBAH, (rdba >> 32));
IXGB_WRITE_REG(hw, RDLEN, rdlen);
/* Setup the HW Rx Head and Tail Descriptor Pointers */
IXGB_WRITE_REG(hw, RDH, 0);
IXGB_WRITE_REG(hw, RDT, 0);
/* due to the hardware errata with RXDCTL, we are unable to use any of
* the performance enhancing features of it without causing other
* subtle bugs, some of the bugs could include receive length
* corruption at high data rates (WTHRESH > 0) and/or receive
* descriptor ring irregularites (particularly in hardware cache) */
IXGB_WRITE_REG(hw, RXDCTL, 0);
/* Enable Receive Checksum Offload for TCP and UDP */
if (adapter->rx_csum) {
rxcsum = IXGB_READ_REG(hw, RXCSUM);
rxcsum |= IXGB_RXCSUM_TUOFL;
IXGB_WRITE_REG(hw, RXCSUM, rxcsum);
}
/* Enable Receives */
IXGB_WRITE_REG(hw, RCTL, rctl);
}
/**
* ixgb_free_tx_resources - Free Tx Resources
* @adapter: board private structure
*
* Free all transmit software resources
**/
void
ixgb_free_tx_resources(struct ixgb_adapter *adapter)
{
struct pci_dev *pdev = adapter->pdev;
ixgb_clean_tx_ring(adapter);
vfree(adapter->tx_ring.buffer_info);
adapter->tx_ring.buffer_info = NULL;
dma_free_coherent(&pdev->dev, adapter->tx_ring.size,
adapter->tx_ring.desc, adapter->tx_ring.dma);
adapter->tx_ring.desc = NULL;
}
static void
ixgb_unmap_and_free_tx_resource(struct ixgb_adapter *adapter,
struct ixgb_buffer *buffer_info)
{
if (buffer_info->dma) {
if (buffer_info->mapped_as_page)
dma_unmap_page(&adapter->pdev->dev, buffer_info->dma,
buffer_info->length, DMA_TO_DEVICE);
else
dma_unmap_single(&adapter->pdev->dev, buffer_info->dma,
buffer_info->length, DMA_TO_DEVICE);
buffer_info->dma = 0;
}
if (buffer_info->skb) {
dev_kfree_skb_any(buffer_info->skb);
buffer_info->skb = NULL;
}
buffer_info->time_stamp = 0;
/* these fields must always be initialized in tx
* buffer_info->length = 0;
* buffer_info->next_to_watch = 0; */
}
/**
* ixgb_clean_tx_ring - Free Tx Buffers
* @adapter: board private structure
**/
static void
ixgb_clean_tx_ring(struct ixgb_adapter *adapter)
{
struct ixgb_desc_ring *tx_ring = &adapter->tx_ring;
struct ixgb_buffer *buffer_info;
unsigned long size;
unsigned int i;
/* Free all the Tx ring sk_buffs */
for (i = 0; i < tx_ring->count; i++) {
buffer_info = &tx_ring->buffer_info[i];
ixgb_unmap_and_free_tx_resource(adapter, buffer_info);
}
size = sizeof(struct ixgb_buffer) * tx_ring->count;
memset(tx_ring->buffer_info, 0, size);
/* Zero out the descriptor ring */
memset(tx_ring->desc, 0, tx_ring->size);
tx_ring->next_to_use = 0;
tx_ring->next_to_clean = 0;
IXGB_WRITE_REG(&adapter->hw, TDH, 0);
IXGB_WRITE_REG(&adapter->hw, TDT, 0);
}
/**
* ixgb_free_rx_resources - Free Rx Resources
* @adapter: board private structure
*
* Free all receive software resources
**/
void
ixgb_free_rx_resources(struct ixgb_adapter *adapter)
{
struct ixgb_desc_ring *rx_ring = &adapter->rx_ring;
struct pci_dev *pdev = adapter->pdev;
ixgb_clean_rx_ring(adapter);
vfree(rx_ring->buffer_info);
rx_ring->buffer_info = NULL;
dma_free_coherent(&pdev->dev, rx_ring->size, rx_ring->desc,
rx_ring->dma);
rx_ring->desc = NULL;
}
/**
* ixgb_clean_rx_ring - Free Rx Buffers
* @adapter: board private structure
**/
static void
ixgb_clean_rx_ring(struct ixgb_adapter *adapter)
{
struct ixgb_desc_ring *rx_ring = &adapter->rx_ring;
struct ixgb_buffer *buffer_info;
struct pci_dev *pdev = adapter->pdev;
unsigned long size;
unsigned int i;
/* Free all the Rx ring sk_buffs */
for (i = 0; i < rx_ring->count; i++) {
buffer_info = &rx_ring->buffer_info[i];
if (buffer_info->dma) {
dma_unmap_single(&pdev->dev,
buffer_info->dma,
buffer_info->length,
DMA_FROM_DEVICE);
buffer_info->dma = 0;
buffer_info->length = 0;
}
if (buffer_info->skb) {
dev_kfree_skb(buffer_info->skb);
buffer_info->skb = NULL;
}
}
size = sizeof(struct ixgb_buffer) * rx_ring->count;
memset(rx_ring->buffer_info, 0, size);
/* Zero out the descriptor ring */
memset(rx_ring->desc, 0, rx_ring->size);
rx_ring->next_to_clean = 0;
rx_ring->next_to_use = 0;
IXGB_WRITE_REG(&adapter->hw, RDH, 0);
IXGB_WRITE_REG(&adapter->hw, RDT, 0);
}
/**
* ixgb_set_mac - Change the Ethernet Address of the NIC
* @netdev: network interface device structure
* @p: pointer to an address structure
*
* Returns 0 on success, negative on failure
**/
static int
ixgb_set_mac(struct net_device *netdev, void *p)
{
struct ixgb_adapter *adapter = netdev_priv(netdev);
struct sockaddr *addr = p;
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
memcpy(netdev->dev_addr, addr->sa_data, netdev->addr_len);
ixgb_rar_set(&adapter->hw, addr->sa_data, 0);
return 0;
}
/**
* ixgb_set_multi - Multicast and Promiscuous mode set
* @netdev: network interface device structure
*
* The set_multi entry point is called whenever the multicast address
* list or the network interface flags are updated. This routine is
* responsible for configuring the hardware for proper multicast,
* promiscuous mode, and all-multi behavior.
**/
static void
ixgb_set_multi(struct net_device *netdev)
{
struct ixgb_adapter *adapter = netdev_priv(netdev);
struct ixgb_hw *hw = &adapter->hw;
struct netdev_hw_addr *ha;
u32 rctl;
int i;
/* Check for Promiscuous and All Multicast modes */
rctl = IXGB_READ_REG(hw, RCTL);
if (netdev->flags & IFF_PROMISC) {
rctl |= (IXGB_RCTL_UPE | IXGB_RCTL_MPE);
/* disable VLAN filtering */
rctl &= ~IXGB_RCTL_CFIEN;
rctl &= ~IXGB_RCTL_VFE;
} else {
if (netdev->flags & IFF_ALLMULTI) {
rctl |= IXGB_RCTL_MPE;
rctl &= ~IXGB_RCTL_UPE;
} else {
rctl &= ~(IXGB_RCTL_UPE | IXGB_RCTL_MPE);
}
/* enable VLAN filtering */
rctl |= IXGB_RCTL_VFE;
rctl &= ~IXGB_RCTL_CFIEN;
}
if (netdev_mc_count(netdev) > IXGB_MAX_NUM_MULTICAST_ADDRESSES) {
rctl |= IXGB_RCTL_MPE;
IXGB_WRITE_REG(hw, RCTL, rctl);
} else {
u8 mta[IXGB_MAX_NUM_MULTICAST_ADDRESSES *
IXGB_ETH_LENGTH_OF_ADDRESS];
IXGB_WRITE_REG(hw, RCTL, rctl);
i = 0;
netdev_for_each_mc_addr(ha, netdev)
memcpy(&mta[i++ * IXGB_ETH_LENGTH_OF_ADDRESS],
ha->addr, IXGB_ETH_LENGTH_OF_ADDRESS);
ixgb_mc_addr_list_update(hw, mta, netdev_mc_count(netdev), 0);
}
if (netdev->features & NETIF_F_HW_VLAN_RX)
ixgb_vlan_strip_enable(adapter);
else
ixgb_vlan_strip_disable(adapter);
}
/**
* ixgb_watchdog - Timer Call-back
* @data: pointer to netdev cast into an unsigned long
**/
static void
ixgb_watchdog(unsigned long data)
{
struct ixgb_adapter *adapter = (struct ixgb_adapter *)data;
struct net_device *netdev = adapter->netdev;
struct ixgb_desc_ring *txdr = &adapter->tx_ring;
ixgb_check_for_link(&adapter->hw);
if (ixgb_check_for_bad_link(&adapter->hw)) {
/* force the reset path */
netif_stop_queue(netdev);
}
if (adapter->hw.link_up) {
if (!netif_carrier_ok(netdev)) {
netdev_info(netdev,
"NIC Link is Up 10 Gbps Full Duplex, Flow Control: %s\n",
(adapter->hw.fc.type == ixgb_fc_full) ?
"RX/TX" :
(adapter->hw.fc.type == ixgb_fc_rx_pause) ?
"RX" :
(adapter->hw.fc.type == ixgb_fc_tx_pause) ?
"TX" : "None");
adapter->link_speed = 10000;
adapter->link_duplex = FULL_DUPLEX;
netif_carrier_on(netdev);
}
} else {
if (netif_carrier_ok(netdev)) {
adapter->link_speed = 0;
adapter->link_duplex = 0;
netdev_info(netdev, "NIC Link is Down\n");
netif_carrier_off(netdev);
}
}
ixgb_update_stats(adapter);
if (!netif_carrier_ok(netdev)) {
if (IXGB_DESC_UNUSED(txdr) + 1 < txdr->count) {
/* We've lost link, so the controller stops DMA,
* but we've got queued Tx work that's never going
* to get done, so reset controller to flush Tx.
* (Do the reset outside of interrupt context). */
schedule_work(&adapter->tx_timeout_task);
/* return immediately since reset is imminent */
return;
}
}
/* Force detection of hung controller every watchdog period */
adapter->detect_tx_hung = true;
/* generate an interrupt to force clean up of any stragglers */
IXGB_WRITE_REG(&adapter->hw, ICS, IXGB_INT_TXDW);
/* Reset the timer */
mod_timer(&adapter->watchdog_timer, jiffies + 2 * HZ);
}
#define IXGB_TX_FLAGS_CSUM 0x00000001
#define IXGB_TX_FLAGS_VLAN 0x00000002
#define IXGB_TX_FLAGS_TSO 0x00000004
static int
ixgb_tso(struct ixgb_adapter *adapter, struct sk_buff *skb)
{
struct ixgb_context_desc *context_desc;
unsigned int i;
u8 ipcss, ipcso, tucss, tucso, hdr_len;
u16 ipcse, tucse, mss;
int err;
if (likely(skb_is_gso(skb))) {
struct ixgb_buffer *buffer_info;
struct iphdr *iph;
if (skb_header_cloned(skb)) {
err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
if (err)
return err;
}
hdr_len = skb_transport_offset(skb) + tcp_hdrlen(skb);
mss = skb_shinfo(skb)->gso_size;
iph = ip_hdr(skb);
iph->tot_len = 0;
iph->check = 0;
tcp_hdr(skb)->check = ~csum_tcpudp_magic(iph->saddr,
iph->daddr, 0,
IPPROTO_TCP, 0);
ipcss = skb_network_offset(skb);
ipcso = (void *)&(iph->check) - (void *)skb->data;
ipcse = skb_transport_offset(skb) - 1;
tucss = skb_transport_offset(skb);
tucso = (void *)&(tcp_hdr(skb)->check) - (void *)skb->data;
tucse = 0;
i = adapter->tx_ring.next_to_use;
context_desc = IXGB_CONTEXT_DESC(adapter->tx_ring, i);
buffer_info = &adapter->tx_ring.buffer_info[i];
WARN_ON(buffer_info->dma != 0);
context_desc->ipcss = ipcss;
context_desc->ipcso = ipcso;
context_desc->ipcse = cpu_to_le16(ipcse);
context_desc->tucss = tucss;
context_desc->tucso = tucso;
context_desc->tucse = cpu_to_le16(tucse);
context_desc->mss = cpu_to_le16(mss);
context_desc->hdr_len = hdr_len;
context_desc->status = 0;
context_desc->cmd_type_len = cpu_to_le32(
IXGB_CONTEXT_DESC_TYPE
| IXGB_CONTEXT_DESC_CMD_TSE
| IXGB_CONTEXT_DESC_CMD_IP
| IXGB_CONTEXT_DESC_CMD_TCP
| IXGB_CONTEXT_DESC_CMD_IDE
| (skb->len - (hdr_len)));
if (++i == adapter->tx_ring.count) i = 0;
adapter->tx_ring.next_to_use = i;
return 1;
}
return 0;
}
static bool
ixgb_tx_csum(struct ixgb_adapter *adapter, struct sk_buff *skb)
{
struct ixgb_context_desc *context_desc;
unsigned int i;
u8 css, cso;
if (likely(skb->ip_summed == CHECKSUM_PARTIAL)) {
struct ixgb_buffer *buffer_info;
css = skb_checksum_start_offset(skb);
cso = css + skb->csum_offset;
i = adapter->tx_ring.next_to_use;
context_desc = IXGB_CONTEXT_DESC(adapter->tx_ring, i);
buffer_info = &adapter->tx_ring.buffer_info[i];
WARN_ON(buffer_info->dma != 0);
context_desc->tucss = css;
context_desc->tucso = cso;
context_desc->tucse = 0;
/* zero out any previously existing data in one instruction */
*(u32 *)&(context_desc->ipcss) = 0;
context_desc->status = 0;
context_desc->hdr_len = 0;
context_desc->mss = 0;
context_desc->cmd_type_len =
cpu_to_le32(IXGB_CONTEXT_DESC_TYPE
| IXGB_TX_DESC_CMD_IDE);
if (++i == adapter->tx_ring.count) i = 0;
adapter->tx_ring.next_to_use = i;
return true;
}
return false;
}
#define IXGB_MAX_TXD_PWR 14
#define IXGB_MAX_DATA_PER_TXD (1<<IXGB_MAX_TXD_PWR)
static int
ixgb_tx_map(struct ixgb_adapter *adapter, struct sk_buff *skb,
unsigned int first)
{
struct ixgb_desc_ring *tx_ring = &adapter->tx_ring;
struct pci_dev *pdev = adapter->pdev;
struct ixgb_buffer *buffer_info;
int len = skb_headlen(skb);
unsigned int offset = 0, size, count = 0, i;
unsigned int mss = skb_shinfo(skb)->gso_size;
unsigned int nr_frags = skb_shinfo(skb)->nr_frags;
unsigned int f;
i = tx_ring->next_to_use;
while (len) {
buffer_info = &tx_ring->buffer_info[i];
size = min(len, IXGB_MAX_DATA_PER_TXD);
/* Workaround for premature desc write-backs
* in TSO mode. Append 4-byte sentinel desc */
if (unlikely(mss && !nr_frags && size == len && size > 8))
size -= 4;
buffer_info->length = size;
WARN_ON(buffer_info->dma != 0);
buffer_info->time_stamp = jiffies;
buffer_info->mapped_as_page = false;
buffer_info->dma = dma_map_single(&pdev->dev,
skb->data + offset,
size, DMA_TO_DEVICE);
if (dma_mapping_error(&pdev->dev, buffer_info->dma))
goto dma_error;
buffer_info->next_to_watch = 0;
len -= size;
offset += size;
count++;
if (len) {
i++;
if (i == tx_ring->count)
i = 0;
}
}
for (f = 0; f < nr_frags; f++) {
struct skb_frag_struct *frag;
frag = &skb_shinfo(skb)->frags[f];
len = frag->size;
offset = frag->page_offset;
while (len) {
i++;
if (i == tx_ring->count)
i = 0;
buffer_info = &tx_ring->buffer_info[i];
size = min(len, IXGB_MAX_DATA_PER_TXD);
/* Workaround for premature desc write-backs
* in TSO mode. Append 4-byte sentinel desc */
if (unlikely(mss && (f == (nr_frags - 1))
&& size == len && size > 8))
size -= 4;
buffer_info->length = size;
buffer_info->time_stamp = jiffies;
buffer_info->mapped_as_page = true;
buffer_info->dma =
dma_map_page(&pdev->dev, frag->page,
offset, size, DMA_TO_DEVICE);
if (dma_mapping_error(&pdev->dev, buffer_info->dma))
goto dma_error;
buffer_info->next_to_watch = 0;
len -= size;
offset += size;
count++;
}
}
tx_ring->buffer_info[i].skb = skb;
tx_ring->buffer_info[first].next_to_watch = i;
return count;
dma_error:
dev_err(&pdev->dev, "TX DMA map failed\n");
buffer_info->dma = 0;
if (count)
count--;
while (count--) {
if (i==0)
i += tx_ring->count;
i--;
buffer_info = &tx_ring->buffer_info[i];
ixgb_unmap_and_free_tx_resource(adapter, buffer_info);
}
return 0;
}
static void
ixgb_tx_queue(struct ixgb_adapter *adapter, int count, int vlan_id,int tx_flags)
{
struct ixgb_desc_ring *tx_ring = &adapter->tx_ring;
struct ixgb_tx_desc *tx_desc = NULL;
struct ixgb_buffer *buffer_info;
u32 cmd_type_len = adapter->tx_cmd_type;
u8 status = 0;
u8 popts = 0;
unsigned int i;
if (tx_flags & IXGB_TX_FLAGS_TSO) {
cmd_type_len |= IXGB_TX_DESC_CMD_TSE;
popts |= (IXGB_TX_DESC_POPTS_IXSM | IXGB_TX_DESC_POPTS_TXSM);
}
if (tx_flags & IXGB_TX_FLAGS_CSUM)
popts |= IXGB_TX_DESC_POPTS_TXSM;
if (tx_flags & IXGB_TX_FLAGS_VLAN)
cmd_type_len |= IXGB_TX_DESC_CMD_VLE;
i = tx_ring->next_to_use;
while (count--) {
buffer_info = &tx_ring->buffer_info[i];
tx_desc = IXGB_TX_DESC(*tx_ring, i);
tx_desc->buff_addr = cpu_to_le64(buffer_info->dma);
tx_desc->cmd_type_len =
cpu_to_le32(cmd_type_len | buffer_info->length);
tx_desc->status = status;
tx_desc->popts = popts;
tx_desc->vlan = cpu_to_le16(vlan_id);
if (++i == tx_ring->count) i = 0;
}
tx_desc->cmd_type_len |=
cpu_to_le32(IXGB_TX_DESC_CMD_EOP | IXGB_TX_DESC_CMD_RS);
/* Force memory writes to complete before letting h/w
* know there are new descriptors to fetch. (Only
* applicable for weak-ordered memory model archs,
* such as IA-64). */
wmb();
tx_ring->next_to_use = i;
IXGB_WRITE_REG(&adapter->hw, TDT, i);
}
static int __ixgb_maybe_stop_tx(struct net_device *netdev, int size)
{
struct ixgb_adapter *adapter = netdev_priv(netdev);
struct ixgb_desc_ring *tx_ring = &adapter->tx_ring;
netif_stop_queue(netdev);
/* Herbert's original patch had:
* smp_mb__after_netif_stop_queue();
* but since that doesn't exist yet, just open code it. */
smp_mb();
/* We need to check again in a case another CPU has just
* made room available. */
if (likely(IXGB_DESC_UNUSED(tx_ring) < size))
return -EBUSY;
/* A reprieve! */
netif_start_queue(netdev);
++adapter->restart_queue;
return 0;
}
static int ixgb_maybe_stop_tx(struct net_device *netdev,
struct ixgb_desc_ring *tx_ring, int size)
{
if (likely(IXGB_DESC_UNUSED(tx_ring) >= size))
return 0;
return __ixgb_maybe_stop_tx(netdev, size);
}
/* Tx Descriptors needed, worst case */
#define TXD_USE_COUNT(S) (((S) >> IXGB_MAX_TXD_PWR) + \
(((S) & (IXGB_MAX_DATA_PER_TXD - 1)) ? 1 : 0))
#define DESC_NEEDED TXD_USE_COUNT(IXGB_MAX_DATA_PER_TXD) /* skb->date */ + \
MAX_SKB_FRAGS * TXD_USE_COUNT(PAGE_SIZE) + 1 /* for context */ \
+ 1 /* one more needed for sentinel TSO workaround */
static netdev_tx_t
ixgb_xmit_frame(struct sk_buff *skb, struct net_device *netdev)
{
struct ixgb_adapter *adapter = netdev_priv(netdev);
unsigned int first;
unsigned int tx_flags = 0;
int vlan_id = 0;
int count = 0;
int tso;
if (test_bit(__IXGB_DOWN, &adapter->flags)) {
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
if (skb->len <= 0) {
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
if (unlikely(ixgb_maybe_stop_tx(netdev, &adapter->tx_ring,
DESC_NEEDED)))
return NETDEV_TX_BUSY;
if (vlan_tx_tag_present(skb)) {
tx_flags |= IXGB_TX_FLAGS_VLAN;
vlan_id = vlan_tx_tag_get(skb);
}
first = adapter->tx_ring.next_to_use;
tso = ixgb_tso(adapter, skb);
if (tso < 0) {
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
if (likely(tso))
tx_flags |= IXGB_TX_FLAGS_TSO;
else if (ixgb_tx_csum(adapter, skb))
tx_flags |= IXGB_TX_FLAGS_CSUM;
count = ixgb_tx_map(adapter, skb, first);
if (count) {
ixgb_tx_queue(adapter, count, vlan_id, tx_flags);
/* Make sure there is space in the ring for the next send. */
ixgb_maybe_stop_tx(netdev, &adapter->tx_ring, DESC_NEEDED);
} else {
dev_kfree_skb_any(skb);
adapter->tx_ring.buffer_info[first].time_stamp = 0;
adapter->tx_ring.next_to_use = first;
}
return NETDEV_TX_OK;
}
/**
* ixgb_tx_timeout - Respond to a Tx Hang
* @netdev: network interface device structure
**/
static void
ixgb_tx_timeout(struct net_device *netdev)
{
struct ixgb_adapter *adapter = netdev_priv(netdev);
/* Do the reset outside of interrupt context */
schedule_work(&adapter->tx_timeout_task);
}
static void
ixgb_tx_timeout_task(struct work_struct *work)
{
struct ixgb_adapter *adapter =
container_of(work, struct ixgb_adapter, tx_timeout_task);
adapter->tx_timeout_count++;
ixgb_down(adapter, true);
ixgb_up(adapter);
}
/**
* ixgb_get_stats - Get System Network Statistics
* @netdev: network interface device structure
*
* Returns the address of the device statistics structure.
* The statistics are actually updated from the timer callback.
**/
static struct net_device_stats *
ixgb_get_stats(struct net_device *netdev)
{
return &netdev->stats;
}
/**
* ixgb_change_mtu - Change the Maximum Transfer Unit
* @netdev: network interface device structure
* @new_mtu: new value for maximum frame size
*
* Returns 0 on success, negative on failure
**/
static int
ixgb_change_mtu(struct net_device *netdev, int new_mtu)
{
struct ixgb_adapter *adapter = netdev_priv(netdev);
int max_frame = new_mtu + ENET_HEADER_SIZE + ENET_FCS_LENGTH;
int old_max_frame = netdev->mtu + ENET_HEADER_SIZE + ENET_FCS_LENGTH;
/* MTU < 68 is an error for IPv4 traffic, just don't allow it */
if ((new_mtu < 68) ||
(max_frame > IXGB_MAX_JUMBO_FRAME_SIZE + ENET_FCS_LENGTH)) {
netif_err(adapter, probe, adapter->netdev,
"Invalid MTU setting %d\n", new_mtu);
return -EINVAL;
}
if (old_max_frame == max_frame)
return 0;
if (netif_running(netdev))
ixgb_down(adapter, true);
adapter->rx_buffer_len = max_frame + 8; /* + 8 for errata */
netdev->mtu = new_mtu;
if (netif_running(netdev))
ixgb_up(adapter);
return 0;
}
/**
* ixgb_update_stats - Update the board statistics counters.
* @adapter: board private structure
**/
void
ixgb_update_stats(struct ixgb_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
/* Prevent stats update while adapter is being reset */
if (pci_channel_offline(pdev))
return;
if ((netdev->flags & IFF_PROMISC) || (netdev->flags & IFF_ALLMULTI) ||
(netdev_mc_count(netdev) > IXGB_MAX_NUM_MULTICAST_ADDRESSES)) {
u64 multi = IXGB_READ_REG(&adapter->hw, MPRCL);
u32 bcast_l = IXGB_READ_REG(&adapter->hw, BPRCL);
u32 bcast_h = IXGB_READ_REG(&adapter->hw, BPRCH);
u64 bcast = ((u64)bcast_h << 32) | bcast_l;
multi |= ((u64)IXGB_READ_REG(&adapter->hw, MPRCH) << 32);
/* fix up multicast stats by removing broadcasts */
if (multi >= bcast)
multi -= bcast;
adapter->stats.mprcl += (multi & 0xFFFFFFFF);
adapter->stats.mprch += (multi >> 32);
adapter->stats.bprcl += bcast_l;
adapter->stats.bprch += bcast_h;
} else {
adapter->stats.mprcl += IXGB_READ_REG(&adapter->hw, MPRCL);
adapter->stats.mprch += IXGB_READ_REG(&adapter->hw, MPRCH);
adapter->stats.bprcl += IXGB_READ_REG(&adapter->hw, BPRCL);
adapter->stats.bprch += IXGB_READ_REG(&adapter->hw, BPRCH);
}
adapter->stats.tprl += IXGB_READ_REG(&adapter->hw, TPRL);
adapter->stats.tprh += IXGB_READ_REG(&adapter->hw, TPRH);
adapter->stats.gprcl += IXGB_READ_REG(&adapter->hw, GPRCL);
adapter->stats.gprch += IXGB_READ_REG(&adapter->hw, GPRCH);
adapter->stats.uprcl += IXGB_READ_REG(&adapter->hw, UPRCL);
adapter->stats.uprch += IXGB_READ_REG(&adapter->hw, UPRCH);
adapter->stats.vprcl += IXGB_READ_REG(&adapter->hw, VPRCL);
adapter->stats.vprch += IXGB_READ_REG(&adapter->hw, VPRCH);
adapter->stats.jprcl += IXGB_READ_REG(&adapter->hw, JPRCL);
adapter->stats.jprch += IXGB_READ_REG(&adapter->hw, JPRCH);
adapter->stats.gorcl += IXGB_READ_REG(&adapter->hw, GORCL);
adapter->stats.gorch += IXGB_READ_REG(&adapter->hw, GORCH);
adapter->stats.torl += IXGB_READ_REG(&adapter->hw, TORL);
adapter->stats.torh += IXGB_READ_REG(&adapter->hw, TORH);
adapter->stats.rnbc += IXGB_READ_REG(&adapter->hw, RNBC);
adapter->stats.ruc += IXGB_READ_REG(&adapter->hw, RUC);
adapter->stats.roc += IXGB_READ_REG(&adapter->hw, ROC);
adapter->stats.rlec += IXGB_READ_REG(&adapter->hw, RLEC);
adapter->stats.crcerrs += IXGB_READ_REG(&adapter->hw, CRCERRS);
adapter->stats.icbc += IXGB_READ_REG(&adapter->hw, ICBC);
adapter->stats.ecbc += IXGB_READ_REG(&adapter->hw, ECBC);
adapter->stats.mpc += IXGB_READ_REG(&adapter->hw, MPC);
adapter->stats.tptl += IXGB_READ_REG(&adapter->hw, TPTL);
adapter->stats.tpth += IXGB_READ_REG(&adapter->hw, TPTH);
adapter->stats.gptcl += IXGB_READ_REG(&adapter->hw, GPTCL);
adapter->stats.gptch += IXGB_READ_REG(&adapter->hw, GPTCH);
adapter->stats.bptcl += IXGB_READ_REG(&adapter->hw, BPTCL);
adapter->stats.bptch += IXGB_READ_REG(&adapter->hw, BPTCH);
adapter->stats.mptcl += IXGB_READ_REG(&adapter->hw, MPTCL);
adapter->stats.mptch += IXGB_READ_REG(&adapter->hw, MPTCH);
adapter->stats.uptcl += IXGB_READ_REG(&adapter->hw, UPTCL);
adapter->stats.uptch += IXGB_READ_REG(&adapter->hw, UPTCH);
adapter->stats.vptcl += IXGB_READ_REG(&adapter->hw, VPTCL);
adapter->stats.vptch += IXGB_READ_REG(&adapter->hw, VPTCH);
adapter->stats.jptcl += IXGB_READ_REG(&adapter->hw, JPTCL);
adapter->stats.jptch += IXGB_READ_REG(&adapter->hw, JPTCH);
adapter->stats.gotcl += IXGB_READ_REG(&adapter->hw, GOTCL);
adapter->stats.gotch += IXGB_READ_REG(&adapter->hw, GOTCH);
adapter->stats.totl += IXGB_READ_REG(&adapter->hw, TOTL);
adapter->stats.toth += IXGB_READ_REG(&adapter->hw, TOTH);
adapter->stats.dc += IXGB_READ_REG(&adapter->hw, DC);
adapter->stats.plt64c += IXGB_READ_REG(&adapter->hw, PLT64C);
adapter->stats.tsctc += IXGB_READ_REG(&adapter->hw, TSCTC);
adapter->stats.tsctfc += IXGB_READ_REG(&adapter->hw, TSCTFC);
adapter->stats.ibic += IXGB_READ_REG(&adapter->hw, IBIC);
adapter->stats.rfc += IXGB_READ_REG(&adapter->hw, RFC);
adapter->stats.lfc += IXGB_READ_REG(&adapter->hw, LFC);
adapter->stats.pfrc += IXGB_READ_REG(&adapter->hw, PFRC);
adapter->stats.pftc += IXGB_READ_REG(&adapter->hw, PFTC);
adapter->stats.mcfrc += IXGB_READ_REG(&adapter->hw, MCFRC);
adapter->stats.mcftc += IXGB_READ_REG(&adapter->hw, MCFTC);
adapter->stats.xonrxc += IXGB_READ_REG(&adapter->hw, XONRXC);
adapter->stats.xontxc += IXGB_READ_REG(&adapter->hw, XONTXC);
adapter->stats.xoffrxc += IXGB_READ_REG(&adapter->hw, XOFFRXC);
adapter->stats.xofftxc += IXGB_READ_REG(&adapter->hw, XOFFTXC);
adapter->stats.rjc += IXGB_READ_REG(&adapter->hw, RJC);
/* Fill out the OS statistics structure */
netdev->stats.rx_packets = adapter->stats.gprcl;
netdev->stats.tx_packets = adapter->stats.gptcl;
netdev->stats.rx_bytes = adapter->stats.gorcl;
netdev->stats.tx_bytes = adapter->stats.gotcl;
netdev->stats.multicast = adapter->stats.mprcl;
netdev->stats.collisions = 0;
/* ignore RLEC as it reports errors for padded (<64bytes) frames
* with a length in the type/len field */
netdev->stats.rx_errors =
/* adapter->stats.rnbc + */ adapter->stats.crcerrs +
adapter->stats.ruc +
adapter->stats.roc /*+ adapter->stats.rlec */ +
adapter->stats.icbc +
adapter->stats.ecbc + adapter->stats.mpc;
/* see above
* netdev->stats.rx_length_errors = adapter->stats.rlec;
*/
netdev->stats.rx_crc_errors = adapter->stats.crcerrs;
netdev->stats.rx_fifo_errors = adapter->stats.mpc;
netdev->stats.rx_missed_errors = adapter->stats.mpc;
netdev->stats.rx_over_errors = adapter->stats.mpc;
netdev->stats.tx_errors = 0;
netdev->stats.rx_frame_errors = 0;
netdev->stats.tx_aborted_errors = 0;
netdev->stats.tx_carrier_errors = 0;
netdev->stats.tx_fifo_errors = 0;
netdev->stats.tx_heartbeat_errors = 0;
netdev->stats.tx_window_errors = 0;
}
#define IXGB_MAX_INTR 10
/**
* ixgb_intr - Interrupt Handler
* @irq: interrupt number
* @data: pointer to a network interface device structure
**/
static irqreturn_t
ixgb_intr(int irq, void *data)
{
struct net_device *netdev = data;
struct ixgb_adapter *adapter = netdev_priv(netdev);
struct ixgb_hw *hw = &adapter->hw;
u32 icr = IXGB_READ_REG(hw, ICR);
if (unlikely(!icr))
return IRQ_NONE; /* Not our interrupt */
if (unlikely(icr & (IXGB_INT_RXSEQ | IXGB_INT_LSC)))
if (!test_bit(__IXGB_DOWN, &adapter->flags))
mod_timer(&adapter->watchdog_timer, jiffies);
if (napi_schedule_prep(&adapter->napi)) {
/* Disable interrupts and register for poll. The flush
of the posted write is intentionally left out.
*/
IXGB_WRITE_REG(&adapter->hw, IMC, ~0);
__napi_schedule(&adapter->napi);
}
return IRQ_HANDLED;
}
/**
* ixgb_clean - NAPI Rx polling callback
* @adapter: board private structure
**/
static int
ixgb_clean(struct napi_struct *napi, int budget)
{
struct ixgb_adapter *adapter = container_of(napi, struct ixgb_adapter, napi);
int work_done = 0;
ixgb_clean_tx_irq(adapter);
ixgb_clean_rx_irq(adapter, &work_done, budget);
/* If budget not fully consumed, exit the polling mode */
if (work_done < budget) {
napi_complete(napi);
if (!test_bit(__IXGB_DOWN, &adapter->flags))
ixgb_irq_enable(adapter);
}
return work_done;
}
/**
* ixgb_clean_tx_irq - Reclaim resources after transmit completes
* @adapter: board private structure
**/
static bool
ixgb_clean_tx_irq(struct ixgb_adapter *adapter)
{
struct ixgb_desc_ring *tx_ring = &adapter->tx_ring;
struct net_device *netdev = adapter->netdev;
struct ixgb_tx_desc *tx_desc, *eop_desc;
struct ixgb_buffer *buffer_info;
unsigned int i, eop;
bool cleaned = false;
i = tx_ring->next_to_clean;
eop = tx_ring->buffer_info[i].next_to_watch;
eop_desc = IXGB_TX_DESC(*tx_ring, eop);
while (eop_desc->status & IXGB_TX_DESC_STATUS_DD) {
rmb(); /* read buffer_info after eop_desc */
for (cleaned = false; !cleaned; ) {
tx_desc = IXGB_TX_DESC(*tx_ring, i);
buffer_info = &tx_ring->buffer_info[i];
if (tx_desc->popts &
(IXGB_TX_DESC_POPTS_TXSM |
IXGB_TX_DESC_POPTS_IXSM))
adapter->hw_csum_tx_good++;
ixgb_unmap_and_free_tx_resource(adapter, buffer_info);
*(u32 *)&(tx_desc->status) = 0;
cleaned = (i == eop);
if (++i == tx_ring->count) i = 0;
}
eop = tx_ring->buffer_info[i].next_to_watch;
eop_desc = IXGB_TX_DESC(*tx_ring, eop);
}
tx_ring->next_to_clean = i;
if (unlikely(cleaned && netif_carrier_ok(netdev) &&
IXGB_DESC_UNUSED(tx_ring) >= DESC_NEEDED)) {
/* Make sure that anybody stopping the queue after this
* sees the new next_to_clean. */
smp_mb();
if (netif_queue_stopped(netdev) &&
!(test_bit(__IXGB_DOWN, &adapter->flags))) {
netif_wake_queue(netdev);
++adapter->restart_queue;
}
}
if (adapter->detect_tx_hung) {
/* detect a transmit hang in hardware, this serializes the
* check with the clearing of time_stamp and movement of i */
adapter->detect_tx_hung = false;
if (tx_ring->buffer_info[eop].time_stamp &&
time_after(jiffies, tx_ring->buffer_info[eop].time_stamp + HZ)
&& !(IXGB_READ_REG(&adapter->hw, STATUS) &
IXGB_STATUS_TXOFF)) {
/* detected Tx unit hang */
netif_err(adapter, drv, adapter->netdev,
"Detected Tx Unit Hang\n"
" TDH <%x>\n"
" TDT <%x>\n"
" next_to_use <%x>\n"
" next_to_clean <%x>\n"
"buffer_info[next_to_clean]\n"
" time_stamp <%lx>\n"
" next_to_watch <%x>\n"
" jiffies <%lx>\n"
" next_to_watch.status <%x>\n",
IXGB_READ_REG(&adapter->hw, TDH),
IXGB_READ_REG(&adapter->hw, TDT),
tx_ring->next_to_use,
tx_ring->next_to_clean,
tx_ring->buffer_info[eop].time_stamp,
eop,
jiffies,
eop_desc->status);
netif_stop_queue(netdev);
}
}
return cleaned;
}
/**
* ixgb_rx_checksum - Receive Checksum Offload for 82597.
* @adapter: board private structure
* @rx_desc: receive descriptor
* @sk_buff: socket buffer with received data
**/
static void
ixgb_rx_checksum(struct ixgb_adapter *adapter,
struct ixgb_rx_desc *rx_desc,
struct sk_buff *skb)
{
/* Ignore Checksum bit is set OR
* TCP Checksum has not been calculated
*/
if ((rx_desc->status & IXGB_RX_DESC_STATUS_IXSM) ||
(!(rx_desc->status & IXGB_RX_DESC_STATUS_TCPCS))) {
skb_checksum_none_assert(skb);
return;
}
/* At this point we know the hardware did the TCP checksum */
/* now look at the TCP checksum error bit */
if (rx_desc->errors & IXGB_RX_DESC_ERRORS_TCPE) {
/* let the stack verify checksum errors */
skb_checksum_none_assert(skb);
adapter->hw_csum_rx_error++;
} else {
/* TCP checksum is good */
skb->ip_summed = CHECKSUM_UNNECESSARY;
adapter->hw_csum_rx_good++;
}
}
/*
* this should improve performance for small packets with large amounts
* of reassembly being done in the stack
*/
static void ixgb_check_copybreak(struct net_device *netdev,
struct ixgb_buffer *buffer_info,
u32 length, struct sk_buff **skb)
{
struct sk_buff *new_skb;
if (length > copybreak)
return;
new_skb = netdev_alloc_skb_ip_align(netdev, length);
if (!new_skb)
return;
skb_copy_to_linear_data_offset(new_skb, -NET_IP_ALIGN,
(*skb)->data - NET_IP_ALIGN,
length + NET_IP_ALIGN);
/* save the skb in buffer_info as good */
buffer_info->skb = *skb;
*skb = new_skb;
}
/**
* ixgb_clean_rx_irq - Send received data up the network stack,
* @adapter: board private structure
**/
static bool
ixgb_clean_rx_irq(struct ixgb_adapter *adapter, int *work_done, int work_to_do)
{
struct ixgb_desc_ring *rx_ring = &adapter->rx_ring;
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
struct ixgb_rx_desc *rx_desc, *next_rxd;
struct ixgb_buffer *buffer_info, *next_buffer, *next2_buffer;
u32 length;
unsigned int i, j;
int cleaned_count = 0;
bool cleaned = false;
i = rx_ring->next_to_clean;
rx_desc = IXGB_RX_DESC(*rx_ring, i);
buffer_info = &rx_ring->buffer_info[i];
while (rx_desc->status & IXGB_RX_DESC_STATUS_DD) {
struct sk_buff *skb;
u8 status;
if (*work_done >= work_to_do)
break;
(*work_done)++;
rmb(); /* read descriptor and rx_buffer_info after status DD */
status = rx_desc->status;
skb = buffer_info->skb;
buffer_info->skb = NULL;
prefetch(skb->data - NET_IP_ALIGN);
if (++i == rx_ring->count)
i = 0;
next_rxd = IXGB_RX_DESC(*rx_ring, i);
prefetch(next_rxd);
j = i + 1;
if (j == rx_ring->count)
j = 0;
next2_buffer = &rx_ring->buffer_info[j];
prefetch(next2_buffer);
next_buffer = &rx_ring->buffer_info[i];
cleaned = true;
cleaned_count++;
dma_unmap_single(&pdev->dev,
buffer_info->dma,
buffer_info->length,
DMA_FROM_DEVICE);
buffer_info->dma = 0;
length = le16_to_cpu(rx_desc->length);
rx_desc->length = 0;
if (unlikely(!(status & IXGB_RX_DESC_STATUS_EOP))) {
/* All receives must fit into a single buffer */
IXGB_DBG("Receive packet consumed multiple buffers "
"length<%x>\n", length);
dev_kfree_skb_irq(skb);
goto rxdesc_done;
}
if (unlikely(rx_desc->errors &
(IXGB_RX_DESC_ERRORS_CE | IXGB_RX_DESC_ERRORS_SE |
IXGB_RX_DESC_ERRORS_P | IXGB_RX_DESC_ERRORS_RXE))) {
dev_kfree_skb_irq(skb);
goto rxdesc_done;
}
ixgb_check_copybreak(netdev, buffer_info, length, &skb);
/* Good Receive */
skb_put(skb, length);
/* Receive Checksum Offload */
ixgb_rx_checksum(adapter, rx_desc, skb);
skb->protocol = eth_type_trans(skb, netdev);
if (status & IXGB_RX_DESC_STATUS_VP)
__vlan_hwaccel_put_tag(skb,
le16_to_cpu(rx_desc->special));
netif_receive_skb(skb);
rxdesc_done:
/* clean up descriptor, might be written over by hw */
rx_desc->status = 0;
/* return some buffers to hardware, one at a time is too slow */
if (unlikely(cleaned_count >= IXGB_RX_BUFFER_WRITE)) {
ixgb_alloc_rx_buffers(adapter, cleaned_count);
cleaned_count = 0;
}
/* use prefetched values */
rx_desc = next_rxd;
buffer_info = next_buffer;
}
rx_ring->next_to_clean = i;
cleaned_count = IXGB_DESC_UNUSED(rx_ring);
if (cleaned_count)
ixgb_alloc_rx_buffers(adapter, cleaned_count);
return cleaned;
}
/**
* ixgb_alloc_rx_buffers - Replace used receive buffers
* @adapter: address of board private structure
**/
static void
ixgb_alloc_rx_buffers(struct ixgb_adapter *adapter, int cleaned_count)
{
struct ixgb_desc_ring *rx_ring = &adapter->rx_ring;
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
struct ixgb_rx_desc *rx_desc;
struct ixgb_buffer *buffer_info;
struct sk_buff *skb;
unsigned int i;
long cleancount;
i = rx_ring->next_to_use;
buffer_info = &rx_ring->buffer_info[i];
cleancount = IXGB_DESC_UNUSED(rx_ring);
/* leave three descriptors unused */
while (--cleancount > 2 && cleaned_count--) {
/* recycle! its good for you */
skb = buffer_info->skb;
if (skb) {
skb_trim(skb, 0);
goto map_skb;
}
skb = netdev_alloc_skb_ip_align(netdev, adapter->rx_buffer_len);
if (unlikely(!skb)) {
/* Better luck next round */
adapter->alloc_rx_buff_failed++;
break;
}
buffer_info->skb = skb;
buffer_info->length = adapter->rx_buffer_len;
map_skb:
buffer_info->dma = dma_map_single(&pdev->dev,
skb->data,
adapter->rx_buffer_len,
DMA_FROM_DEVICE);
rx_desc = IXGB_RX_DESC(*rx_ring, i);
rx_desc->buff_addr = cpu_to_le64(buffer_info->dma);
/* guarantee DD bit not set now before h/w gets descriptor
* this is the rest of the workaround for h/w double
* writeback. */
rx_desc->status = 0;
if (++i == rx_ring->count) i = 0;
buffer_info = &rx_ring->buffer_info[i];
}
if (likely(rx_ring->next_to_use != i)) {
rx_ring->next_to_use = i;
if (unlikely(i-- == 0))
i = (rx_ring->count - 1);
/* Force memory writes to complete before letting h/w
* know there are new descriptors to fetch. (Only
* applicable for weak-ordered memory model archs, such
* as IA-64). */
wmb();
IXGB_WRITE_REG(&adapter->hw, RDT, i);
}
}
static void
ixgb_vlan_strip_enable(struct ixgb_adapter *adapter)
{
u32 ctrl;
/* enable VLAN tag insert/strip */
ctrl = IXGB_READ_REG(&adapter->hw, CTRL0);
ctrl |= IXGB_CTRL0_VME;
IXGB_WRITE_REG(&adapter->hw, CTRL0, ctrl);
}
static void
ixgb_vlan_strip_disable(struct ixgb_adapter *adapter)
{
u32 ctrl;
/* disable VLAN tag insert/strip */
ctrl = IXGB_READ_REG(&adapter->hw, CTRL0);
ctrl &= ~IXGB_CTRL0_VME;
IXGB_WRITE_REG(&adapter->hw, CTRL0, ctrl);
}
static void
ixgb_vlan_rx_add_vid(struct net_device *netdev, u16 vid)
{
struct ixgb_adapter *adapter = netdev_priv(netdev);
u32 vfta, index;
/* add VID to filter table */
index = (vid >> 5) & 0x7F;
vfta = IXGB_READ_REG_ARRAY(&adapter->hw, VFTA, index);
vfta |= (1 << (vid & 0x1F));
ixgb_write_vfta(&adapter->hw, index, vfta);
set_bit(vid, adapter->active_vlans);
}
static void
ixgb_vlan_rx_kill_vid(struct net_device *netdev, u16 vid)
{
struct ixgb_adapter *adapter = netdev_priv(netdev);
u32 vfta, index;
/* remove VID from filter table */
index = (vid >> 5) & 0x7F;
vfta = IXGB_READ_REG_ARRAY(&adapter->hw, VFTA, index);
vfta &= ~(1 << (vid & 0x1F));
ixgb_write_vfta(&adapter->hw, index, vfta);
clear_bit(vid, adapter->active_vlans);
}
static void
ixgb_restore_vlan(struct ixgb_adapter *adapter)
{
u16 vid;
for_each_set_bit(vid, adapter->active_vlans, VLAN_N_VID)
ixgb_vlan_rx_add_vid(adapter->netdev, vid);
}
#ifdef CONFIG_NET_POLL_CONTROLLER
/*
* Polling 'interrupt' - used by things like netconsole to send skbs
* without having to re-enable interrupts. It's not called while
* the interrupt routine is executing.
*/
static void ixgb_netpoll(struct net_device *dev)
{
struct ixgb_adapter *adapter = netdev_priv(dev);
disable_irq(adapter->pdev->irq);
ixgb_intr(adapter->pdev->irq, dev);
enable_irq(adapter->pdev->irq);
}
#endif
/**
* ixgb_io_error_detected() - called when PCI error is detected
* @pdev pointer to pci device with error
* @state pci channel state after error
*
* This callback is called by the PCI subsystem whenever
* a PCI bus error is detected.
*/
static pci_ers_result_t ixgb_io_error_detected(struct pci_dev *pdev,
enum pci_channel_state state)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct ixgb_adapter *adapter = netdev_priv(netdev);
netif_device_detach(netdev);
if (state == pci_channel_io_perm_failure)
return PCI_ERS_RESULT_DISCONNECT;
if (netif_running(netdev))
ixgb_down(adapter, true);
pci_disable_device(pdev);
/* Request a slot reset. */
return PCI_ERS_RESULT_NEED_RESET;
}
/**
* ixgb_io_slot_reset - called after the pci bus has been reset.
* @pdev pointer to pci device with error
*
* This callback is called after the PCI bus has been reset.
* Basically, this tries to restart the card from scratch.
* This is a shortened version of the device probe/discovery code,
* it resembles the first-half of the ixgb_probe() routine.
*/
static pci_ers_result_t ixgb_io_slot_reset(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct ixgb_adapter *adapter = netdev_priv(netdev);
if (pci_enable_device(pdev)) {
netif_err(adapter, probe, adapter->netdev,
"Cannot re-enable PCI device after reset\n");
return PCI_ERS_RESULT_DISCONNECT;
}
/* Perform card reset only on one instance of the card */
if (0 != PCI_FUNC (pdev->devfn))
return PCI_ERS_RESULT_RECOVERED;
pci_set_master(pdev);
netif_carrier_off(netdev);
netif_stop_queue(netdev);
ixgb_reset(adapter);
/* Make sure the EEPROM is good */
if (!ixgb_validate_eeprom_checksum(&adapter->hw)) {
netif_err(adapter, probe, adapter->netdev,
"After reset, the EEPROM checksum is not valid\n");
return PCI_ERS_RESULT_DISCONNECT;
}
ixgb_get_ee_mac_addr(&adapter->hw, netdev->dev_addr);
memcpy(netdev->perm_addr, netdev->dev_addr, netdev->addr_len);
if (!is_valid_ether_addr(netdev->perm_addr)) {
netif_err(adapter, probe, adapter->netdev,
"After reset, invalid MAC address\n");
return PCI_ERS_RESULT_DISCONNECT;
}
return PCI_ERS_RESULT_RECOVERED;
}
/**
* ixgb_io_resume - called when its OK to resume normal operations
* @pdev pointer to pci device with error
*
* The error recovery driver tells us that its OK to resume
* normal operation. Implementation resembles the second-half
* of the ixgb_probe() routine.
*/
static void ixgb_io_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct ixgb_adapter *adapter = netdev_priv(netdev);
pci_set_master(pdev);
if (netif_running(netdev)) {
if (ixgb_up(adapter)) {
pr_err("can't bring device back up after reset\n");
return;
}
}
netif_device_attach(netdev);
mod_timer(&adapter->watchdog_timer, jiffies);
}
/* ixgb_main.c */
| gpl-2.0 |
CatcherXue/linux | drivers/staging/wlags49_h2/hcf.c | 2767 | 231224 | /************************************************************************************************************
*
* FILE : HCF.C
*
* DATE : $Date: 2004/08/05 11:47:10 $ $Revision: 1.10 $
* Original: 2004/06/02 10:22:22 Revision: 1.85 Tag: hcf7_t20040602_01
* Original: 2004/04/15 09:24:41 Revision: 1.63 Tag: hcf7_t7_20040415_01
* Original: 2004/04/13 14:22:44 Revision: 1.62 Tag: t7_20040413_01
* Original: 2004/04/01 15:32:55 Revision: 1.59 Tag: t7_20040401_01
* Original: 2004/03/10 15:39:27 Revision: 1.55 Tag: t20040310_01
* Original: 2004/03/04 11:03:37 Revision: 1.53 Tag: t20040304_01
* Original: 2004/03/02 14:51:21 Revision: 1.50 Tag: t20040302_03
* Original: 2004/02/24 13:00:27 Revision: 1.43 Tag: t20040224_01
* Original: 2004/02/19 10:57:25 Revision: 1.39 Tag: t20040219_01
*
* AUTHOR : Nico Valster
*
* SPECIFICATION: ........
*
* DESCRIPTION : HCF Routines for Hermes-II (callable via the Wireless Connection I/F or WCI)
* Local Support Routines for above procedures
*
* Customizable via HCFCFG.H, which is included by HCF.H
*
*************************************************************************************************************
*
*
* SOFTWARE LICENSE
*
* This software is provided subject to the following terms and conditions,
* which you should read carefully before using the software. Using this
* software indicates your acceptance of these terms and conditions. If you do
* not agree with these terms and conditions, do not use the software.
*
* COPYRIGHT © 1994 - 1995 by AT&T. All Rights Reserved
* COPYRIGHT © 1996 - 2000 by Lucent Technologies. All Rights Reserved
* COPYRIGHT © 2001 - 2004 by Agere Systems Inc. All Rights Reserved
* All rights reserved.
*
* Redistribution and use in source or binary forms, with or without
* modifications, are permitted provided that the following conditions are met:
*
* . Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following Disclaimer as comments in the code as
* well as in the documentation and/or other materials provided with the
* distribution.
*
* . Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following Disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* . Neither the name of Agere Systems Inc. nor the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* Disclaimer
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, INFRINGEMENT AND THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ANY
* USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE IS SOLELY AT THE USERS OWN
* RISK. IN NO EVENT SHALL AGERE SYSTEMS INC. OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, INCLUDING, BUT NOT LIMITED TO, CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
*
************************************************************************************************************/
/************************************************************************************************************
**
** Implementation Notes
**
* - a leading marker of //! is used. The purpose of such a sequence is to help to understand the flow
* An example is: //!rc = HCF_SUCCESS;
* if this is superfluous because rc is already guaranteed to be 0 but it shows to the (maintenance)
* programmer it is an intentional omission at the place where someone could consider it most appropriate at
* first glance
* - using near pointers in a model where ss!=ds is an invitation for disaster, so be aware of how you specify
* your model and how you define variables which are used at interrupt time
* - remember that sign extension on 32 bit platforms may cause problems unless code is carefully constructed,
* e.g. use "(hcf_16)~foo" rather than "~foo"
*
************************************************************************************************************/
#include "hcf.h" // HCF and MSF common include file
#include "hcfdef.h" // HCF specific include file
#include "mmd.h" // MoreModularDriver common include file
#include <linux/bug.h>
#include <linux/kernel.h>
#if ! defined offsetof
#define offsetof(s,m) ((unsigned int)&(((s *)0)->m))
#endif // offsetof
/***********************************************************************************************************/
/*************************************** PROTOTYPES ******************************************************/
/***********************************************************************************************************/
HCF_STATIC int cmd_exe( IFBP ifbp, hcf_16 cmd_code, hcf_16 par_0 );
HCF_STATIC int init( IFBP ifbp );
HCF_STATIC int put_info( IFBP ifbp, LTVP ltvp );
HCF_STATIC int put_info_mb( IFBP ifbp, CFG_MB_INFO_STRCT FAR * ltvp );
#if (HCF_TYPE) & HCF_TYPE_WPA
HCF_STATIC void calc_mic( hcf_32* p, hcf_32 M );
void calc_mic_rx_frag( IFBP ifbp, wci_bufp p, int len );
void calc_mic_tx_frag( IFBP ifbp, wci_bufp p, int len );
HCF_STATIC int check_mic( IFBP ifbp );
#endif // HCF_TYPE_WPA
HCF_STATIC void calibrate( IFBP ifbp );
HCF_STATIC int cmd_cmpl( IFBP ifbp );
HCF_STATIC hcf_16 get_fid( IFBP ifbp );
HCF_STATIC void isr_info( IFBP ifbp );
#if HCF_DMA
HCF_STATIC DESC_STRCT* get_frame_lst(IFBP ifbp, int tx_rx_flag);
#endif // HCF_DMA
HCF_STATIC void get_frag( IFBP ifbp, wci_bufp bufp, int len BE_PAR( int word_len ) ); //char*, byte count (usually even)
#if HCF_DMA
HCF_STATIC void put_frame_lst( IFBP ifbp, DESC_STRCT *descp, int tx_rx_flag );
#endif // HCF_DMA
HCF_STATIC void put_frag( IFBP ifbp, wci_bufp bufp, int len BE_PAR( int word_len ) );
HCF_STATIC void put_frag_finalize( IFBP ifbp );
HCF_STATIC int setup_bap( IFBP ifbp, hcf_16 fid, int offset, int type );
#if (HCF_ASSERT) & HCF_ASSERT_PRINTF
static int fw_printf(IFBP ifbp, CFG_FW_PRINTF_STRCT FAR *ltvp);
#endif // HCF_ASSERT_PRINTF
HCF_STATIC int download( IFBP ifbp, CFG_PROG_STRCT FAR *ltvp );
HCF_STATIC hcf_8 hcf_encap( wci_bufp type );
HCF_STATIC hcf_8 null_addr[4] = { 0, 0, 0, 0 };
#if ! defined IN_PORT_WORD //replace I/O Macros with logging facility
extern FILE *log_file;
#define IN_PORT_WORD(port) in_port_word( (hcf_io)(port) )
static hcf_16 in_port_word( hcf_io port ) {
hcf_16 i = (hcf_16)_inpw( port );
if ( log_file ) {
fprintf( log_file, "\nR %2.2x %4.4x", (port)&0xFF, i);
}
return i;
} // in_port_word
#define OUT_PORT_WORD(port, value) out_port_word( (hcf_io)(port), (hcf_16)(value) )
static void out_port_word( hcf_io port, hcf_16 value ) {
_outpw( port, value );
if ( log_file ) {
fprintf( log_file, "\nW %2.02x %4.04x", (port)&0xFF, value );
}
}
void IN_PORT_STRING_32( hcf_io prt, hcf_32 FAR * dst, int n) {
int i = 0;
hcf_16 FAR * p;
if ( log_file ) {
fprintf( log_file, "\nread string_32 length %04x (%04d) at port %02.2x to addr %lp",
(hcf_16)n, (hcf_16)n, (hcf_16)(prt)&0xFF, dst);
}
while ( n-- ) {
p = (hcf_16 FAR *)dst;
*p++ = (hcf_16)_inpw( prt );
*p = (hcf_16)_inpw( prt );
if ( log_file ) {
fprintf( log_file, "%s%08lx ", i++ % 0x08 ? " " : "\n", *dst);
}
dst++;
}
} // IN_PORT_STRING_32
void IN_PORT_STRING_8_16( hcf_io prt, hcf_8 FAR * dst, int n) { //also handles byte alignment problems
hcf_16 FAR * p = (hcf_16 FAR *)dst; //this needs more elaborate code in non-x86 platforms
int i = 0;
if ( log_file ) {
fprintf( log_file, "\nread string_16 length %04x (%04d) at port %02.2x to addr %lp",
(hcf_16)n, (hcf_16)n, (hcf_16)(prt)&0xFF, dst );
}
while ( n-- ) {
*p =(hcf_16)_inpw( prt);
if ( log_file ) {
if ( i++ % 0x10 ) {
fprintf( log_file, "%04x ", *p);
} else {
fprintf( log_file, "\n%04x ", *p);
}
}
p++;
}
} // IN_PORT_STRING_8_16
void OUT_PORT_STRING_32( hcf_io prt, hcf_32 FAR * src, int n) {
int i = 0;
hcf_16 FAR * p;
if ( log_file ) {
fprintf( log_file, "\nwrite string_32 length %04x (%04d) at port %02.2x",
(hcf_16)n, (hcf_16)n, (hcf_16)(prt)&0xFF);
}
while ( n-- ) {
p = (hcf_16 FAR *)src;
_outpw( prt, *p++ );
_outpw( prt, *p );
if ( log_file ) {
fprintf( log_file, "%s%08lx ", i++ % 0x08 ? " " : "\n", *src);
}
src++;
}
} // OUT_PORT_STRING_32
void OUT_PORT_STRING_8_16( hcf_io prt, hcf_8 FAR * src, int n) { //also handles byte alignment problems
hcf_16 FAR * p = (hcf_16 FAR *)src; //this needs more elaborate code in non-x86 platforms
int i = 0;
if ( log_file ) {
fprintf( log_file, "\nwrite string_16 length %04x (%04d) at port %04x", n, n, (hcf_16)prt);
}
while ( n-- ) {
(void)_outpw( prt, *p);
if ( log_file ) {
if ( i++ % 0x10 ) {
fprintf( log_file, "%04x ", *p);
} else {
fprintf( log_file, "\n%04x ", *p);
}
}
p++;
}
} // OUT_PORT_STRING_8_16
#endif // IN_PORT_WORD
/************************************************************************************************************
******************************* D A T A D E F I N I T I O N S ********************************************
************************************************************************************************************/
#if HCF_ASSERT
IFBP BASED assert_ifbp = NULL; //to make asserts easily work under MMD and DHF
#endif // HCF_ASSERT
/* SNAP header to be inserted in Ethernet-II frames */
HCF_STATIC hcf_8 BASED snap_header[] = { 0xAA, 0xAA, 0x03, 0x00, 0x00, //5 bytes signature +
0 }; //1 byte protocol identifier
#if (HCF_TYPE) & HCF_TYPE_WPA
HCF_STATIC hcf_8 BASED mic_pad[8] = { 0x5A, 0, 0, 0, 0, 0, 0, 0 }; //MIC padding of message
#endif // HCF_TYPE_WPA
#if defined MSF_COMPONENT_ID
CFG_IDENTITY_STRCT BASED cfg_drv_identity = {
sizeof(cfg_drv_identity)/sizeof(hcf_16) - 1, //length of RID
CFG_DRV_IDENTITY, // (0x0826)
MSF_COMPONENT_ID,
MSF_COMPONENT_VAR,
MSF_COMPONENT_MAJOR_VER,
MSF_COMPONENT_MINOR_VER
} ;
CFG_RANGES_STRCT BASED cfg_drv_sup_range = {
sizeof(cfg_drv_sup_range)/sizeof(hcf_16) - 1, //length of RID
CFG_DRV_SUP_RANGE, // (0x0827)
COMP_ROLE_SUPL,
COMP_ID_DUI,
{{ DUI_COMPAT_VAR,
DUI_COMPAT_BOT,
DUI_COMPAT_TOP
}}
} ;
struct CFG_RANGE3_STRCT BASED cfg_drv_act_ranges_pri = {
sizeof(cfg_drv_act_ranges_pri)/sizeof(hcf_16) - 1, //length of RID
CFG_DRV_ACT_RANGES_PRI, // (0x0828)
COMP_ROLE_ACT,
COMP_ID_PRI,
{
{ 0, 0, 0 }, // HCF_PRI_VAR_1 not supported by HCF 7
{ 0, 0, 0 }, // HCF_PRI_VAR_2 not supported by HCF 7
{ 3, //var_rec[2] - Variant number
CFG_DRV_ACT_RANGES_PRI_3_BOTTOM, // - Bottom Compatibility
CFG_DRV_ACT_RANGES_PRI_3_TOP // - Top Compatibility
}
}
} ;
struct CFG_RANGE4_STRCT BASED cfg_drv_act_ranges_sta = {
sizeof(cfg_drv_act_ranges_sta)/sizeof(hcf_16) - 1, //length of RID
CFG_DRV_ACT_RANGES_STA, // (0x0829)
COMP_ROLE_ACT,
COMP_ID_STA,
{
#if defined HCF_STA_VAR_1
{ 1, //var_rec[1] - Variant number
CFG_DRV_ACT_RANGES_STA_1_BOTTOM, // - Bottom Compatibility
CFG_DRV_ACT_RANGES_STA_1_TOP // - Top Compatibility
},
#else
{ 0, 0, 0 },
#endif // HCF_STA_VAR_1
#if defined HCF_STA_VAR_2
{ 2, //var_rec[1] - Variant number
CFG_DRV_ACT_RANGES_STA_2_BOTTOM, // - Bottom Compatibility
CFG_DRV_ACT_RANGES_STA_2_TOP // - Top Compatibility
},
#else
{ 0, 0, 0 },
#endif // HCF_STA_VAR_2
// For Native_USB (Not used!)
#if defined HCF_STA_VAR_3
{ 3, //var_rec[1] - Variant number
CFG_DRV_ACT_RANGES_STA_3_BOTTOM, // - Bottom Compatibility
CFG_DRV_ACT_RANGES_STA_3_TOP // - Top Compatibility
},
#else
{ 0, 0, 0 },
#endif // HCF_STA_VAR_3
// Warp
#if defined HCF_STA_VAR_4
{ 4, //var_rec[1] - Variant number
CFG_DRV_ACT_RANGES_STA_4_BOTTOM, // - Bottom Compatibility
CFG_DRV_ACT_RANGES_STA_4_TOP // - Top Compatibility
}
#else
{ 0, 0, 0 }
#endif // HCF_STA_VAR_4
}
} ;
struct CFG_RANGE6_STRCT BASED cfg_drv_act_ranges_hsi = {
sizeof(cfg_drv_act_ranges_hsi)/sizeof(hcf_16) - 1, //length of RID
CFG_DRV_ACT_RANGES_HSI, // (0x082A)
COMP_ROLE_ACT,
COMP_ID_HSI,
{
#if defined HCF_HSI_VAR_0 // Controlled deployment
{ 0, // var_rec[1] - Variant number
CFG_DRV_ACT_RANGES_HSI_0_BOTTOM, // - Bottom Compatibility
CFG_DRV_ACT_RANGES_HSI_0_TOP // - Top Compatibility
},
#else
{ 0, 0, 0 },
#endif // HCF_HSI_VAR_0
{ 0, 0, 0 }, // HCF_HSI_VAR_1 not supported by HCF 7
{ 0, 0, 0 }, // HCF_HSI_VAR_2 not supported by HCF 7
{ 0, 0, 0 }, // HCF_HSI_VAR_3 not supported by HCF 7
#if defined HCF_HSI_VAR_4 // Hermes-II all types
{ 4, // var_rec[1] - Variant number
CFG_DRV_ACT_RANGES_HSI_4_BOTTOM, // - Bottom Compatibility
CFG_DRV_ACT_RANGES_HSI_4_TOP // - Top Compatibility
},
#else
{ 0, 0, 0 },
#endif // HCF_HSI_VAR_4
#if defined HCF_HSI_VAR_5 // WARP Hermes-2.5
{ 5, // var_rec[1] - Variant number
CFG_DRV_ACT_RANGES_HSI_5_BOTTOM, // - Bottom Compatibility
CFG_DRV_ACT_RANGES_HSI_5_TOP // - Top Compatibility
}
#else
{ 0, 0, 0 }
#endif // HCF_HSI_VAR_5
}
} ;
CFG_RANGE4_STRCT BASED cfg_drv_act_ranges_apf = {
sizeof(cfg_drv_act_ranges_apf)/sizeof(hcf_16) - 1, //length of RID
CFG_DRV_ACT_RANGES_APF, // (0x082B)
COMP_ROLE_ACT,
COMP_ID_APF,
{
#if defined HCF_APF_VAR_1 //(Fake) Hermes-I
{ 1, //var_rec[1] - Variant number
CFG_DRV_ACT_RANGES_APF_1_BOTTOM, // - Bottom Compatibility
CFG_DRV_ACT_RANGES_APF_1_TOP // - Top Compatibility
},
#else
{ 0, 0, 0 },
#endif // HCF_APF_VAR_1
#if defined HCF_APF_VAR_2 //Hermes-II
{ 2, // var_rec[1] - Variant number
CFG_DRV_ACT_RANGES_APF_2_BOTTOM, // - Bottom Compatibility
CFG_DRV_ACT_RANGES_APF_2_TOP // - Top Compatibility
},
#else
{ 0, 0, 0 },
#endif // HCF_APF_VAR_2
#if defined HCF_APF_VAR_3 // Native_USB
{ 3, // var_rec[1] - Variant number
CFG_DRV_ACT_RANGES_APF_3_BOTTOM, // - Bottom Compatibility !!!!!see note below!!!!!!!
CFG_DRV_ACT_RANGES_APF_3_TOP // - Top Compatibility
},
#else
{ 0, 0, 0 },
#endif // HCF_APF_VAR_3
#if defined HCF_APF_VAR_4 // WARP Hermes 2.5
{ 4, // var_rec[1] - Variant number
CFG_DRV_ACT_RANGES_APF_4_BOTTOM, // - Bottom Compatibility !!!!!see note below!!!!!!!
CFG_DRV_ACT_RANGES_APF_4_TOP // - Top Compatibility
}
#else
{ 0, 0, 0 }
#endif // HCF_APF_VAR_4
}
} ;
#define HCF_VERSION TEXT( "HCF$Revision: 1.10 $" )
static struct /*CFG_HCF_OPT_STRCT*/ {
hcf_16 len; //length of cfg_hcf_opt struct
hcf_16 typ; //type 0x082C
hcf_16 v0; //offset HCF_VERSION
hcf_16 v1; // MSF_COMPONENT_ID
hcf_16 v2; // HCF_ALIGN
hcf_16 v3; // HCF_ASSERT
hcf_16 v4; // HCF_BIG_ENDIAN
hcf_16 v5; // /* HCF_DLV | HCF_DLNV */
hcf_16 v6; // HCF_DMA
hcf_16 v7; // HCF_ENCAP
hcf_16 v8; // HCF_EXT
hcf_16 v9; // HCF_INT_ON
hcf_16 v10; // HCF_IO
hcf_16 v11; // HCF_LEGACY
hcf_16 v12; // HCF_MAX_LTV
hcf_16 v13; // HCF_PROT_TIME
hcf_16 v14; // HCF_SLEEP
hcf_16 v15; // HCF_TALLIES
hcf_16 v16; // HCF_TYPE
hcf_16 v17; // HCF_NIC_TAL_CNT
hcf_16 v18; // HCF_HCF_TAL_CNT
hcf_16 v19; // offset tallies
char val[sizeof(HCF_VERSION)];
} BASED cfg_hcf_opt = {
sizeof(cfg_hcf_opt)/sizeof(hcf_16) -1,
CFG_HCF_OPT, // (0x082C)
( sizeof(cfg_hcf_opt) - sizeof(HCF_VERSION) - 4 )/sizeof(hcf_16),
#if defined MSF_COMPONENT_ID
MSF_COMPONENT_ID,
#else
0,
#endif // MSF_COMPONENT_ID
HCF_ALIGN,
HCF_ASSERT,
HCF_BIG_ENDIAN,
0, // /* HCF_DLV | HCF_DLNV*/,
HCF_DMA,
HCF_ENCAP,
HCF_EXT,
HCF_INT_ON,
HCF_IO,
HCF_LEGACY,
HCF_MAX_LTV,
HCF_PROT_TIME,
HCF_SLEEP,
HCF_TALLIES,
HCF_TYPE,
#if (HCF_TALLIES) & ( HCF_TALLIES_NIC | HCF_TALLIES_HCF )
HCF_NIC_TAL_CNT,
HCF_HCF_TAL_CNT,
offsetof(IFB_STRCT, IFB_TallyLen ),
#else
0, 0, 0,
#endif // HCF_TALLIES_NIC / HCF_TALLIES_HCF
HCF_VERSION
}; // cfg_hcf_opt
#endif // MSF_COMPONENT_ID
HCF_STATIC LTV_STRCT BASED cfg_null = { 1, CFG_NULL, {0} };
HCF_STATIC hcf_16* BASED xxxx[ ] = {
&cfg_null.len, //CFG_NULL 0x0820
#if defined MSF_COMPONENT_ID
&cfg_drv_identity.len, //CFG_DRV_IDENTITY 0x0826
&cfg_drv_sup_range.len, //CFG_DRV_SUP_RANGE 0x0827
&cfg_drv_act_ranges_pri.len, //CFG_DRV_ACT_RANGES_PRI 0x0828
&cfg_drv_act_ranges_sta.len, //CFG_DRV_ACT_RANGES_STA 0x0829
&cfg_drv_act_ranges_hsi.len, //CFG_DRV_ACT_RANGES_HSI 0x082A
&cfg_drv_act_ranges_apf.len, //CFG_DRV_ACT_RANGES_APF 0x082B
&cfg_hcf_opt.len, //CFG_HCF_OPT 0x082C
NULL, //IFB_PRIIdentity placeholder 0xFD02
NULL, //IFB_PRISup placeholder 0xFD03
#endif // MSF_COMPONENT_ID
NULL //endsentinel
};
#define xxxx_PRI_IDENTITY_OFFSET (ARRAY_SIZE(xxxx) - 3)
/************************************************************************************************************
************************** T O P L E V E L H C F R O U T I N E S **************************************
************************************************************************************************************/
/************************************************************************************************************
*
*.MODULE int hcf_action( IFBP ifbp, hcf_16 action )
*.PURPOSE Changes the run-time Card behavior.
* Performs Miscellanuous actions.
*
*.ARGUMENTS
* ifbp address of the Interface Block
* action number identifying the type of change
* - HCF_ACT_INT_FORCE_ON enable interrupt generation by WaveLAN NIC
* - HCF_ACT_INT_OFF disable interrupt generation by WaveLAN NIC
* - HCF_ACT_INT_ON compensate 1 HCF_ACT_INT_OFF, enable interrupt generation if balance reached
* - HCF_ACT_PRS_SCAN Hermes Probe Response Scan (F102) command
* - HCF_ACT_RX_ACK acknowledge non-DMA receiver to Hermes
* - HCF_ACT_SCAN Hermes Inquire Scan (F101) command (non-WARP only)
* - HCF_ACT_SLEEP DDS Sleep request
* - HCF_ACT_TALLIES Hermes Inquire Tallies (F100) command
*
*.RETURNS
* HCF_SUCCESS all (including invalid)
* HCF_INT_PENDING HCF_ACT_INT_OFF, interrupt pending
* HCF_ERR_NO_NIC HCF_ACT_INT_OFF, NIC presence check fails
*
*.CONDITIONS
* Except for hcf_action with HCF_ACT_INT_FORCE_ON or HCF_ACT_INT_OFF as parameter or hcf_connect with an I/O
* address (i.e. not HCF_DISCONNECT), all hcf-function calls MUST be preceded by a call of hcf_action with
* HCF_ACT_INT_OFF as parameter.
* Note that hcf_connect defaults to NIC interrupt disabled mode, i.e. as if hcf_action( HCF_ACT_INT_OFF )
* was called.
*
*.DESCRIPTION
* hcf_action supports the following mode changing action-code pairs that are antonyms
* - HCF_ACT_INT_[FORCE_]ON / HCF_ACT_INT_OFF
*
* Additionally hcf_action can start the following actions in the NIC:
* - HCF_ACT_PRS_SCAN
* - HCF_ACT_RX_ACK
* - HCF_ACT_SCAN
* - HCF_ACT_SLEEP
* - HCF_ACT_TALLIES
*
* o HCF_ACT_INT_OFF: Sets NIC Interrupts mode Disabled.
* This command, and the associated [Force] Enable NIC interrupts command, are only available if the HCF_INT_ON
* compile time option is not set at 0x0000.
*
* o HCF_ACT_INT_ON: Sets NIC Interrupts mode Enabled.
* Enable NIC Interrupts, depending on the number of preceding Disable NIC Interrupt calls.
*
* o HCF_ACT_INT_FORCE_ON: Force NIC Interrupts mode Enabled.
* Sets NIC Interrupts mode Enabled, regardless off the number of preceding Disable NIC Interrupt calls.
*
* The disabling and enabling of interrupts are antonyms.
* These actions must be balanced.
* For each "disable interrupts" there must be a matching "enable interrupts".
* The disable interrupts may be executed multiple times in a row without intervening enable interrupts, in
* other words, the disable interrupts may be nested.
* The interrupt generation mechanism is disabled at the first call with HCF_ACT_INT_OFF.
* The interrupt generation mechanism is re-enabled when the number of calls with HCF_ACT_INT_ON matches the
* number of calls with INT_OFF.
*
* It is not allowed to have more Enable NIC Interrupts calls than Disable NIC Interrupts calls.
* The interrupt generation mechanism is initially (i.e. after hcf_connect) disabled.
* An MSF based on a interrupt strategy must call hcf_action with INT_ON in its initialization logic.
*
*! The INT_OFF/INT_ON housekeeping is initialized at 0x0000 by hcf_connect, causing the interrupt generation
* mechanism to be disabled at first. This suits MSF implementation based on a polling strategy.
*
* o HCF_ACT_SLEEP: Initiates the Disconnected DeepSleep process
* This command is only available if the HCF_DDS compile time option is set. It triggers the F/W to start the
* sleep handshaking. Regardless whether the Host initiates a Disconnected DeepSleep (DDS) or the F/W initiates
* a Connected DeepSleep (CDS), the Host-F/W sleep handshaking is completed when the NIC Interrupts mode is
* enabled (by means of the balancing HCF_ACT_INT_ON), i.e. at that moment the F/W really goes into sleep mode.
* The F/W is wokenup by the HCF when the NIC Interrupts mode are disabled, i.e. at the first HCF_ACT_INT_OFF
* after going into sleep.
*
* The following Miscellaneous actions are defined:
*
* o HCF_ACT_RX_ACK: Receiver Acknowledgement (non-DMA, non-USB mode only)
* Acking the receiver, frees the NIC memory used to hold the Rx frame and allows the F/W to
* report the existence of the next Rx frame.
* If the MSF does not need access (any longer) to the current frame, e.g. because it is rejected based on the
* look ahead or copied to another buffer, the receiver may be acked. Acking earlier is assumed to have the
* potential of improving the performance.
* If the MSF does not explicitly ack the receiver, the acking is done implicitly if:
* - the received frame fits in the look ahead buffer, by the hcf_service_nic call that reported the Rx frame
* - if not in the above step, by hcf_rcv_msg (assuming hcf_rcv_msg is called)
* - if neither of the above implicit acks nor an explicit ack by the MSF, by the first hcf_service_nic after
* the hcf_service_nic that reported the Rx frame.
* Note: If an Rx frame is already acked, an explicit ACK by the MSF acts as a NoOperation.
*
* o HCF_ACT_TALLIES: Inquire Tallies command
* This command is only operational if the F/W is enabled.
* The Inquire Tallies command requests the F/W to provide its current set of tallies.
* See also hcf_get_info with CFG_TALLIES as parameter.
*
* o HCF_ACT_PRS_SCAN: Inquire Probe Response Scan command
* This command is only operational if the F/W is enabled.
* The Probe Response Scan command starts a scan sequence.
* The HCF puts the result of this action in an MSF defined buffer (see CFG_RID_LOG_STRCT).
*
* o HCF_ACT_SCAN: Inquire Scan command
* This command is only supported for HII F/W (i.e. pre-WARP) and it is operational if the F/W is enabled.
* The Inquire Scan command starts a scan sequence.
* The HCF puts the result of this action in an MSF defined buffer (see CFG_RID_LOG_STRCT).
*
* Assert fails if
* - ifbp has a recognizable out-of-range value.
* - NIC interrupts are not disabled while required by parameter action.
* - an invalid code is specified in parameter action.
* - HCF_ACT_INT_ON commands outnumber the HCF_ACT_INT_OFF commands.
* - reentrancy, may be caused by calling hcf_functions without adequate protection against NIC interrupts or
* multi-threading
*
* - Since the HCF does not maintain status information relative to the F/W enabled state, it is not asserted
* whether HCF_ACT_SCAN, HCF_ACT_PRS_SCAN or HCF_ACT_TALLIES are only used while F/W is enabled.
*
*.DIAGRAM
* 0: The assert embedded in HCFLOGENTRY checks against re-entrancy. Re-entrancy could be caused by a MSF logic
* at task-level calling hcf_functions without shielding with HCF_ACT_ON/_OFF. However the HCF_ACT_INT_OFF
* action itself can per definition not be protected this way. Based on code inspection, it can be concluded,
* that there is no re-entrancy PROBLEM in this particular flow. It does not seem worth the trouble to
* explicitly check for this condition (although there was a report of an MSF which ran into this assert.
* 2:IFB_IntOffCnt is used to balance the INT_OFF and INT_ON calls. Disabling of the interrupts is achieved by
* writing a zero to the Hermes IntEn register. In a shared interrupt environment (e.g. the mini-PCI NDIS
* driver) it is considered more correct to return the status HCF_INT_PENDING if and only if, the current
* invocation of hcf_service_nic is (apparently) called in the ISR when the ISR was activated as result of a
* change in HREG_EV_STAT matching a bit in HREG_INT_EN, i.e. not if invoked as result of another device
* generating an interrupt on the shared interrupt line.
* Note 1: it has been observed that under certain adverse conditions on certain platforms the writing of
* HREG_INT_EN can apparently fail, therefore it is paramount that HREG_INT_EN is written again with 0 for
* each and every call to HCF_ACT_INT_OFF.
* Note 2: it has been observed that under certain H/W & S/W architectures this logic is called when there is
* no NIC at all. To cater for this, the value of HREG_INT_EN is validated. If the unused bit 0x0100 is set,
* it is assumed there is no NIC.
* Note 3: During the download process, some versions of the F/W reset HREG_SW_0, hence checking this
* register for HCF_MAGIC (the classical NIC presence test) when HCF_ACT_INT_OFF is called due to another
* card interrupting via a shared IRQ during a download, fails.
*4: The construction "if ( ifbp->IFB_IntOffCnt-- == 0 )" is optimal (in the sense of shortest/quickest
* path in error free flows) but NOT fail safe in case of too many INT_ON invocations compared to INT_OFF).
* Enabling of the interrupts is achieved by writing the Hermes IntEn register.
* - If the HCF is in Defunct mode, the interrupts stay disabled.
* - Under "normal" conditions, the HCF is only interested in Info Events, Rx Events and Notify Events.
* - When the HCF is out of Tx/Notify resources, the HCF is also interested in Alloc Events.
* - via HCF_EXT, the MSF programmer can also request HREG_EV_TICK and/or HREG_EV_TX_EXC interrupts.
* For DMA operation, the DMA hardware handles the alloc events. The DMA engine will generate a 'TxDmaDone'
* event as soon as it has pumped a frame from host ram into NIC-RAM (note that the frame does not have to be
* transmitted then), and a 'RxDmaDone' event as soon as a received frame has been pumped from NIC-RAM into
* host ram. Note that the 'alloc' event has been removed from the event-mask, because the DMA engine will
* react to and acknowledge this event.
*6: ack the "old" Rx-event. See "Rx Buffer free strategy" in hcf_service_nic above for more explanation.
* IFB_RxFID and IFB_RxLen must be cleared to bring both the internal HCF house keeping and the information
* supplied to the MSF in the state "no frame received".
*8: The HCF_ACT_SCAN, HCF_ACT_PRS_SCAN and HCF_ACT_TALLIES activity are merged by "clever" algebraic
* manipulations of the RID-values and action codes, so foregoing robustness against migration problems for
* ease of implementation. The assumptions about numerical relationships between CFG_TALLIES etc and
* HCF_ACT_TALLIES etc are checked by the "#if" statements just prior to the body of this routine, resulting
* in: err "maintenance" during compilation if the assumptions are no longer met. The writing of HREG_PARAM_1
* with 0x3FFF in case of an PRS scan, is a kludge to get around lack of specification, hence different
* implementation in F/W and Host.
* When there is no NIC RAM available, some versions of the Hermes F/W do report 0x7F00 as error in the
* Result field of the Status register and some F/W versions don't. To mask this difference to the MSF all
* return codes of the Hermes are ignored ("best" and "most simple" solution to these types of analomies with
* an acceptable loss due to ignoring all error situations as well).
* The "No inquire space" is reported via the Hermes tallies.
*30: do not HCFASSERT( rc, rc ) since rc == HCF_INT_PENDING is no error
*
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
#if ( (HCF_TYPE) & HCF_TYPE_HII5 ) == 0
#if CFG_SCAN != CFG_TALLIES - HCF_ACT_TALLIES + HCF_ACT_SCAN
err: "maintenance" apparently inviolated the underlying assumption about the numerical values of these macros
#endif
#endif // HCF_TYPE_HII5
#if CFG_PRS_SCAN != CFG_TALLIES - HCF_ACT_TALLIES + HCF_ACT_PRS_SCAN
err: "maintenance" apparently inviolated the underlying assumption about the numerical values of these macros
#endif
int
hcf_action( IFBP ifbp, hcf_16 action )
{
int rc = HCF_SUCCESS;
HCFASSERT( ifbp->IFB_Magic == HCF_MAGIC, ifbp->IFB_Magic );
#if HCF_INT_ON
HCFLOGENTRY( action == HCF_ACT_INT_FORCE_ON ? HCF_TRACE_ACTION_KLUDGE : HCF_TRACE_ACTION, action ); /* 0 */
#if (HCF_SLEEP)
HCFASSERT( ifbp->IFB_IntOffCnt != 0xFFFE || action == HCF_ACT_INT_OFF,
MERGE_2( action, ifbp->IFB_IntOffCnt ) );
#else
HCFASSERT( ifbp->IFB_IntOffCnt != 0xFFFE, action );
#endif // HCF_SLEEP
HCFASSERT( ifbp->IFB_IntOffCnt != 0xFFFF ||
action == HCF_ACT_INT_OFF || action == HCF_ACT_INT_FORCE_ON, action );
HCFASSERT( ifbp->IFB_IntOffCnt <= 16 || ifbp->IFB_IntOffCnt >= 0xFFFE,
MERGE_2( action, ifbp->IFB_IntOffCnt ) ); //nesting more than 16 deep seems unreasonable
#endif // HCF_INT_ON
switch (action) {
#if HCF_INT_ON
hcf_16 i;
case HCF_ACT_INT_OFF: // Disable Interrupt generation
#if HCF_SLEEP
if ( ifbp->IFB_IntOffCnt == 0xFFFE ) { // WakeUp test ;?tie this to the "new" super-LinkStat
ifbp->IFB_IntOffCnt++; // restore conventional I/F
OPW(HREG_IO, HREG_IO_WAKEUP_ASYNC ); // set wakeup bit
OPW(HREG_IO, HREG_IO_WAKEUP_ASYNC ); // set wakeup bit to counteract the clearing by F/W
// 800 us latency before FW switches to high power
MSF_WAIT(800); // MSF-defined function to wait n microseconds.
//OOR if ( ifbp->IFB_DSLinkStat & CFG_LINK_STAT_DS_OOR ) { // OutOfRange
// printk(KERN_NOTICE "ACT_INT_OFF: Deepsleep phase terminated, enable and go to AwaitConnection\n" ); //;?remove me 1 day
// hcf_cntl( ifbp, HCF_CNTL_ENABLE );
// }
// ifbp->IFB_DSLinkStat &= ~( CFG_LINK_STAT_DS_IR | CFG_LINK_STAT_DS_OOR); //clear IR/OOR state
}
#endif // HCF_SLEEP
/*2*/ ifbp->IFB_IntOffCnt++;
//! rc = 0;
i = IPW( HREG_INT_EN );
OPW( HREG_INT_EN, 0 );
if ( i & 0x1000 ) {
rc = HCF_ERR_NO_NIC;
} else {
if ( i & IPW( HREG_EV_STAT ) ) {
rc = HCF_INT_PENDING;
}
}
break;
case HCF_ACT_INT_FORCE_ON: // Enforce Enable Interrupt generation
ifbp->IFB_IntOffCnt = 0;
//Fall through in HCF_ACT_INT_ON
case HCF_ACT_INT_ON: // Enable Interrupt generation
/*4*/ if ( ifbp->IFB_IntOffCnt-- == 0 && ifbp->IFB_CardStat == 0 ) {
//determine Interrupt Event mask
#if HCF_DMA
if ( ifbp->IFB_CntlOpt & USE_DMA ) {
i = HREG_EV_INFO | HREG_EV_RDMAD | HREG_EV_TDMAD | HREG_EV_TX_EXT; //mask when DMA active
} else
#endif // HCF_DMA
{
i = HREG_EV_INFO | HREG_EV_RX | HREG_EV_TX_EXT; //mask when DMA not active
if ( ifbp->IFB_RscInd == 0 ) {
i |= HREG_EV_ALLOC; //mask when no TxFID available
}
}
#if HCF_SLEEP
if ( ( IPW(HREG_EV_STAT) & ( i | HREG_EV_SLEEP_REQ ) ) == HREG_EV_SLEEP_REQ ) {
// firmware indicates it would like to go into sleep modus
// only acknowledge this request if no other events that can cause an interrupt are pending
ifbp->IFB_IntOffCnt--; //becomes 0xFFFE
OPW( HREG_INT_EN, i | HREG_EV_TICK );
OPW( HREG_EV_ACK, HREG_EV_SLEEP_REQ | HREG_EV_TICK | HREG_EV_ACK_REG_READY );
} else
#endif // HCF_SLEEP
{
OPW( HREG_INT_EN, i | HREG_EV_SLEEP_REQ );
}
}
break;
#endif // HCF_INT_ON
#if (HCF_SLEEP) & HCF_DDS
case HCF_ACT_SLEEP: // DDS Sleep request
hcf_cntl( ifbp, HCF_CNTL_DISABLE );
cmd_exe( ifbp, HCMD_SLEEP, 0 );
break;
// case HCF_ACT_WAKEUP: // DDS Wakeup request
// HCFASSERT( ifbp->IFB_IntOffCnt == 0xFFFE, ifbp->IFB_IntOffCnt );
// ifbp->IFB_IntOffCnt++; // restore conventional I/F
// OPW( HREG_IO, HREG_IO_WAKEUP_ASYNC );
// MSF_WAIT(800); // MSF-defined function to wait n microseconds.
// rc = hcf_action( ifbp, HCF_ACT_INT_OFF ); /*bogus, IFB_IntOffCnt == 0xFFFF, so if you carefully look
// *at the #if HCF_DDS statements, HCF_ACT_INT_OFF is empty
// *for DDS. "Much" better would be to merge the flows for
// *DDS and DEEP_SLEEP
// */
// break;
#endif // HCF_DDS
case HCF_ACT_RX_ACK: //Receiver ACK
/*6*/ if ( ifbp->IFB_RxFID ) {
DAWA_ACK( HREG_EV_RX );
}
ifbp->IFB_RxFID = ifbp->IFB_RxLen = 0;
break;
/*8*/ case HCF_ACT_PRS_SCAN: // Hermes PRS Scan (F102)
OPW( HREG_PARAM_1, 0x3FFF );
//Fall through in HCF_ACT_TALLIES
case HCF_ACT_TALLIES: // Hermes Inquire Tallies (F100)
#if ( (HCF_TYPE) & HCF_TYPE_HII5 ) == 0
case HCF_ACT_SCAN: // Hermes Inquire Scan (F101)
#endif // HCF_TYPE_HII5
/*!! the assumptions about numerical relationships between CFG_TALLIES etc and HCF_ACT_TALLIES etc
* are checked by #if statements just prior to this routine resulting in: err "maintenance" */
cmd_exe( ifbp, HCMD_INQUIRE, action - HCF_ACT_TALLIES + CFG_TALLIES );
break;
default:
HCFASSERT( DO_ASSERT, action );
break;
}
//! do not HCFASSERT( rc == HCF_SUCCESS, rc ) /* 30*/
HCFLOGEXIT( HCF_TRACE_ACTION );
return rc;
} // hcf_action
/************************************************************************************************************
*
*.MODULE int hcf_cntl( IFBP ifbp, hcf_16 cmd )
*.PURPOSE Connect or disconnect a specific port to a specific network.
*!! ;???????????????? continue needs more explanation
* recovers by means of "continue" when the connect process in CCX mode fails
* Enables or disables data transmission and reception for the NIC.
* Activates static NIC configuration for a specific port at connect.
* Activates static configuration for all ports at enable.
*
*.ARGUMENTS
* ifbp address of the Interface Block
* cmd 0x001F: Hermes command (disable, enable, connect, disconnect, continue)
* HCF_CNTL_ENABLE Enable
* HCF_CNTL_DISABLE Disable
* HCF_CNTL_CONTINUE Continue
* HCF_CNTL_CONNECT Connect
* HCF_CNTL_DISCONNECT Disconnect
* 0x0100: command qualifier (continue)
* HCMD_RETRY retry flag
* 0x0700: port number (connect/disconnect)
* HCF_PORT_0 MAC Port 0
* HCF_PORT_1 MAC Port 1
* HCF_PORT_2 MAC Port 2
* HCF_PORT_3 MAC Port 3
* HCF_PORT_4 MAC Port 4
* HCF_PORT_5 MAC Port 5
* HCF_PORT_6 MAC Port 6
*
*.RETURNS
* HCF_SUCCESS
*!! via cmd_exe
* HCF_ERR_NO_NIC
* HCF_ERR_DEFUNCT_...
* HCF_ERR_TIME_OUT
*
*.DESCRIPTION
* The parameter cmd contains a number of subfields.
* The actual value for cmd is created by logical or-ing the appropriate mnemonics for the subfields.
* The field 0x001F contains the command code
* - HCF_CNTL_ENABLE
* - HCF_CNTL_DISABLE
* - HCF_CNTL_CONNECT
* - HCF_CNTL_DISCONNECT
* - HCF_CNTL_CONTINUE
*
* For HCF_CNTL_CONTINUE, the field 0x0100 contains the retry flag HCMD_RETRY.
* For HCF_CNTL_CONNECT and HCF_CNTL_DISCONNECT, the field 0x0700 contains the port number as HCF_PORT_#.
* For Station as well as AccessPoint F/W, MAC Port 0 is the "normal" communication channel.
* For AccessPoint F/W, MAC Port 1 through 6 control the WDS links.
*
* Note that despite the names HCF_CNTL_DISABLE and HCF_CNTL_ENABLE, hcf_cntl does not influence the NIC
* Interrupts mode.
*
* The Connect is used by the MSF to bring a particular port in an inactive state as far as data transmission
* and reception are concerned.
* When a particular port is disconnected:
* - the F/W disables the receiver for that port.
* - the F/W ignores send commands for that port.
* - all frames (Receive as well as pending Transmit) for that port on the NIC are discarded.
*
* When the NIC is disabled, above list applies to all ports, i.e. the result is like all ports are
* disconnected.
*
* When a particular port is connected:
* - the F/W effectuates the static configuration for that port.
* - enables the receiver for that port.
* - accepts send commands for that port.
*
* Enabling has the following effects:
* - the F/W effectuates the static configuration for all ports.
* The F/W only updates its static configuration at a transition from disabled to enabled or from
* disconnected to connected.
* In order to enforce the static configuration, the MSF must assure that such a transition takes place.
* Due to such a disable/enable or disconnect/connect sequence, Rx/Tx frames may be lost, in other words,
* configuration may impact communication.
* - The DMA Engine (if applicable) is enabled.
* Note that the Enable Function by itself only enables data transmission and reception, it
* does not enable the Interrupt Generation mechanism. This is done by hcf_action.
*
* Disabling has the following effects:
*!! ;?????is the following statement really true
* - it acts as a disconnect on all ports.
* - The DMA Engine (if applicable) is disabled.
*
* For impact of the disable command on the behavior of hcf_dma_tx/rx_get see the appropriate sections.
*
* Although the Enable/Disable and Connect/Disconnect are antonyms, there is no restriction on their sequencing,
* in other words, they may be called multiple times in arbitrary sequence without being paired or balanced.
* Each time one of these functions is called, the effects of the preceding calls cease.
*
* Assert fails if
* - ifbp has a recognizable out-of-range value.
* - NIC interrupts are not disabled.
* - A command other than Continue, Enable, Disable, Connect or Disconnect is given.
* - An invalid combination of the subfields is given or a bit outside the subfields is given.
* - any return code besides HCF_SUCCESS.
* - reentrancy, may be caused by calling a hcf_function without adequate protection against NIC interrupts or
* multi-threading
*
*.DIAGRAM
* hcf_cntl takes successively the following actions:
*2: If the HCF is in Defunct mode or incompatible with the Primary or Station Supplier in the Hermes,
* hcf_cntl() returns immediately with HCF_ERR_NO_NIC;? as status.
*8: when the port is disabled, the DMA engine needs to be de-activated, so the host can safely reclaim tx
* packets from the tx descriptor chain.
*
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
int
hcf_cntl( IFBP ifbp, hcf_16 cmd )
{
int rc = HCF_ERR_INCOMP_FW;
#if HCF_ASSERT
{ int x = cmd & HCMD_CMD_CODE;
if ( x == HCF_CNTL_CONTINUE ) x &= ~HCMD_RETRY;
else if ( (x == HCMD_DISABLE || x == HCMD_ENABLE) && ifbp->IFB_FWIdentity.comp_id == COMP_ID_FW_AP ) {
x &= ~HFS_TX_CNTL_PORT;
}
HCFASSERT( x==HCF_CNTL_ENABLE || x==HCF_CNTL_DISABLE || HCF_CNTL_CONTINUE ||
x==HCF_CNTL_CONNECT || x==HCF_CNTL_DISCONNECT, cmd );
}
#endif // HCF_ASSERT
// #if (HCF_SLEEP) & HCF_DDS
// HCFASSERT( ifbp->IFB_IntOffCnt != 0xFFFE, cmd );
// #endif // HCF_DDS
HCFLOGENTRY( HCF_TRACE_CNTL, cmd );
if ( ifbp->IFB_CardStat == 0 ) { /*2*/
/*6*/ rc = cmd_exe( ifbp, cmd, 0 );
#if (HCF_SLEEP) & HCF_DDS
ifbp->IFB_TickCnt = 0; //start 2 second period (with 1 tick uncertanty)
#endif // HCF_DDS
}
#if HCF_DMA
//!rlav : note that this piece of code is always executed, regardless of the DEFUNCT bit in IFB_CardStat.
// The reason behind this is that the MSF should be able to get all its DMA resources back from the HCF,
// even if the hardware is disfunctional. Practical example under Windows : surprise removal.
if ( ifbp->IFB_CntlOpt & USE_DMA ) {
hcf_io io_port = ifbp->IFB_IOBase;
DESC_STRCT *p;
if ( cmd == HCF_CNTL_DISABLE || cmd == HCF_CNTL_ENABLE ) {
OUT_PORT_DWORD( (io_port + HREG_DMA_CTRL), DMA_CTRLSTAT_RESET); /*8*/
ifbp->IFB_CntlOpt &= ~DMA_ENABLED;
}
if ( cmd == HCF_CNTL_ENABLE ) {
OUT_PORT_DWORD( (io_port + HREG_DMA_CTRL), DMA_CTRLSTAT_GO);
/* ;? by rewriting hcf_dma_rx_put you can probably just call hcf_dma_rx_put( ifbp->IFB_FirstDesc[DMA_RX] )
* as additional beneficiary side effect, the SOP and EOP bits will also be cleared
*/
ifbp->IFB_CntlOpt |= DMA_ENABLED;
HCFASSERT( NT_ASSERT, NEVER_TESTED );
// make the entire rx descriptor chain DMA-owned, so the DMA engine can (re-)use it.
p = ifbp->IFB_FirstDesc[DMA_RX];
if (p != NULL) { //;? Think this over again in the light of the new chaining strategy
if ( 1 ) { //begin alternative
HCFASSERT( NT_ASSERT, NEVER_TESTED );
put_frame_lst( ifbp, ifbp->IFB_FirstDesc[DMA_RX], DMA_RX );
if ( ifbp->IFB_FirstDesc[DMA_RX] ) {
put_frame_lst( ifbp, ifbp->IFB_FirstDesc[DMA_RX]->next_desc_addr, DMA_RX );
}
} else {
while ( p ) {
//p->buf_cntl.cntl_stat |= DESC_DMA_OWNED;
p->BUF_CNT |= DESC_DMA_OWNED;
p = p->next_desc_addr;
}
// a rx chain is available so hand it over to the DMA engine
p = ifbp->IFB_FirstDesc[DMA_RX];
OUT_PORT_DWORD( (io_port + HREG_RXDMA_PTR32), p->desc_phys_addr);
} //end alternative
}
}
}
#endif // HCF_DMA
HCFASSERT( rc == HCF_SUCCESS, rc );
HCFLOGEXIT( HCF_TRACE_CNTL );
return rc;
} // hcf_cntl
/************************************************************************************************************
*
*.MODULE int hcf_connect( IFBP ifbp, hcf_io io_base )
*.PURPOSE Grants access right for the HCF to the IFB.
* Initializes Card and HCF housekeeping.
*
*.ARGUMENTS
* ifbp (near) address of the Interface Block
* io_base non-USB: I/O Base address of the NIC (connect)
* non-USB: HCF_DISCONNECT
* USB: HCF_CONNECT, HCF_DISCONNECT
*
*.RETURNS
* HCF_SUCCESS
* HCF_ERR_INCOMP_PRI
* HCF_ERR_INCOMP_FW
* HCF_ERR_DEFUNCT_CMD_SEQ
*!! HCF_ERR_NO_NIC really returned ;?
* HCF_ERR_NO_NIC
* HCF_ERR_TIME_OUT
*
* MSF-accessible fields of Result Block:
* IFB_IOBase entry parameter io_base
* IFB_IORange HREG_IO_RANGE (0x40/0x80)
* IFB_Version version of the IFB layout
* IFB_FWIdentity CFG_FW_IDENTITY_STRCT, specifies the identity of the
* "running" F/W, i.e. tertiary F/W under normal conditions
* IFB_FWSup CFG_SUP_RANGE_STRCT, specifies the supplier range of
* the "running" F/W, i.e. tertiary F/W under normal conditions
* IFB_HSISup CFG_SUP_RANGE_STRCT, specifies the HW/SW I/F range of the NIC
* IFB_PRIIdentity CFG_PRI_IDENTITY_STRCT, specifies the Identity of the Primary F/W
* IFB_PRISup CFG_SUP_RANGE_STRCT, specifies the supplier range of the Primary F/W
* all other all MSF accessible fields, which are not specified above, are zero-filled
*
*.CONDITIONS
* It is the responsibility of the MSF to assure the correctness of the I/O Base address.
*
* Note: hcf_connect defaults to NIC interrupt disabled mode, i.e. as if hcf_action( HCF_ACT_INT_OFF )
* was called.
*
*.DESCRIPTION
* hcf_connect passes the MSF-defined location of the IFB to the HCF and grants or revokes access right for the
* HCF to the IFB. Revoking is done by specifying HCF_DISCONNECT rather than an I/O address for the parameter
* io_base. Every call of hcf_connect in "connect" mode, must eventually be followed by a call of hcf_connect
* in "disconnect" mode. Calling hcf_connect in "connect"/"disconnect" mode can not be nested.
* The IFB address must be used as a handle with all subsequent HCF-function calls and the HCF uses the IFB
* address as a handle when it performs a call(back) of an MSF-function (i.e. msf_assert).
*
* Note that not only the MSF accessible fields are cleared, but also all internal housekeeping
* information is re-initialized.
* This implies that all settings which are done via hcf_action and hcf_put_info (e.g. CFG_MB_ASSERT, CFG_REG_MB,
* CFG_REG_INFO_LOG) must be done again. The only field which is not cleared, is IFB_MSFSup.
*
* If HCF_INT_ON is selected as compile option, NIC interrupts are disabled.
*
* Assert fails if
* - ifbp is not properly aligned ( ref chapter HCF_ALIGN in 4.1.1)
* - I/O Base Address is not a multiple of 0x40 (note: 0x0000 is explicitly allowed).
*
*.DIAGRAM
*
*0: Throughout hcf_connect you need to distinguish the connect from the disconnect case, which requires
* some attention about what to use as "I/O" address when for which purpose.
*2:
*2a: Reset H-II by toggling reset bit in IO-register on and off.
* The HCF_TYPE_PRELOADED caters for the DOS environment where H-II is loaded by a separate program to
* overcome the 64k size limit posed on DOS drivers.
* The macro OPW is not yet useable because the IFB_IOBase field is not set.
* Note 1: hopefully the clearing and initializing of the IFB (see below) acts as a delay which meets the
* specification for S/W reset
* Note 2: it turns out that on some H/W constellations, the clock to access the EEProm is not lowered
* to an appropriate frequency by HREG_IO_SRESET. By giving an HCMD_INI first, this problem is worked around.
*2b: Experimentally it is determined over a wide range of F/W versions that are waiting for the for Cmd bit in
* Ev register gives a workable strategy. The available documentation does not give much clues.
*4: clear and initialize the IFB
* The HCF house keeping info is designed such that zero is the appropriate initial value for as much as
* feasible IFB-items.
* The readable fields mentioned in the description section and some HCF specific fields are given their
* actual value.
* IFB_TickIni is initialized at best guess before calibration
* Hcf_connect defaults to "no interrupt generation" (implicitly achieved by the zero-filling).
*6: Register compile-time linked MSF Routine and set default filter level
* cast needed to get around the "near" problem in DOS COM model
* er C2446: no conversion from void (__near __cdecl *)(unsigned char __far *,unsigned int,unsigned short,int)
* to void (__far __cdecl *)(unsigned char __far *,unsigned int,unsigned short,int)
*8: If a command is apparently still active (as indicated by the Busy bit in Cmd register) this may indicate a
* blocked cmd pipe line. To unblock the following actions are done:
* - Ack everything
* - Wait for Busy bit drop in Cmd register
* - Wait for Cmd bit raise in Ev register
* The two waits are combined in a single HCF_WAIT_WHILE to optimize memory size. If either of these waits
* fail (prot_cnt becomes 0), then something is serious wrong. Rather than PANICK, the assumption is that the
* next cmd_exe will fail, causing the HCF to go into DEFUNCT mode
*10: Ack everything to unblock a (possibly blocked) cmd pipe line
* Note 1: it is very likely that an Alloc event is pending and very well possible that a (Send) Cmd event is
* pending on non-initial calls
* Note 2: it is assumed that this strategy takes away the need to ack every conceivable event after an
* Hermes Initialize
*12: Only H-II NEEDS the Hermes Initialize command. Due to the different semantics for H-I and H-II
* Initialize command, init() does not (and can not, since it is called e.g. after a download) execute the
* Hermes Initialize command. Executing the Hermes Initialize command for H-I would not harm but not do
* anything useful either, so it is skipped.
* The return status of cmd_exe is ignored. It is assumed that if cmd_exe fails, init fails too
*14: use io_base as a flag to merge hcf_connect and hcf_disconnect into 1 routine
* the call to init and its subsequent call of cmd_exe will return HCF_ERR_NO_NIC if appropriate. This status
* is (badly) needed by some legacy combination of NT4 and card services which do not yield an I/O address in
* time.
*
*.NOTICE
* On platforms where the NULL-pointer is not a bit-pattern of all zeros, the zero-filling of the IFB results
* in an incorrect initialization of pointers.
* The implementation of the MailBox manipulation in put_mb_info protects against the absence of a MailBox
* based on IFB_MBSize, IFB_MBWp and ifbp->IFB_MBRp. This has ramifications on the initialization of the
* MailBox via hcf_put_info with the CFG_REG_MB type, but it prevents dependency on the "NULL-"ness of
* IFB_MBp.
*
*.NOTICE
* There are a number of problems when asserting and logging hcf_connect, e.g.
* - Asserting on re-entrancy of hcf_connect by means of
* "HCFASSERT( (ifbp->IFB_AssertTrace & HCF_ASSERT_CONNECT) == 0, 0 )" is not useful because IFB contents
* are undefined
* - Asserting before the IFB is cleared will cause mdd_assert() to interpret the garbage in IFB_AssertRtn
* as a routine address
* Therefore HCFTRACE nor HCFLOGENTRY is called by hcf_connect.
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
int
hcf_connect( IFBP ifbp, hcf_io io_base )
{
int rc = HCF_SUCCESS;
hcf_io io_addr;
hcf_32 prot_cnt;
hcf_8 *q;
LTV_STRCT x;
#if HCF_ASSERT
hcf_16 xa = ifbp->IFB_FWIdentity.typ;
/* is assumed to cause an assert later on if hcf_connect is called without intervening hcf_disconnect.
* xa == CFG_FW_IDENTITY in subsequent calls without preceding hcf_disconnect,
* xa == 0 in subsequent calls with preceding hcf_disconnect,
* xa == "garbage" (any value except CFG_FW_IDENTITY is acceptable) in the initial call
*/
#endif // HCF_ASSERT
if ( io_base == HCF_DISCONNECT ) { //disconnect
io_addr = ifbp->IFB_IOBase;
OPW( HREG_INT_EN, 0 ); //;?workaround against dying F/W on subsequent hcf_connect calls
} else { //connect /* 0 */
io_addr = io_base;
}
#if 0 //;? if a subsequent hcf_connect is preceded by an hcf_disconnect the wakeup is not needed !!
#if HCF_SLEEP
OUT_PORT_WORD( .....+HREG_IO, HREG_IO_WAKEUP_ASYNC ); //OPW not yet useable
MSF_WAIT(800); // MSF-defined function to wait n microseconds.
note that MSF_WAIT uses not yet defined!!!! IFB_IOBase and IFB_TickIni (via PROT_CNT_INI)
so be careful if this code is restored
#endif // HCF_SLEEP
#endif // 0
#if ( (HCF_TYPE) & HCF_TYPE_PRELOADED ) == 0 //switch clock back for SEEPROM access !!!
OUT_PORT_WORD( io_addr + HREG_CMD, HCMD_INI ); //OPW not yet useable
prot_cnt = INI_TICK_INI;
HCF_WAIT_WHILE( (IN_PORT_WORD( io_addr + HREG_EV_STAT) & HREG_EV_CMD) == 0 );
OUT_PORT_WORD( (io_addr + HREG_IO), HREG_IO_SRESET ); //OPW not yet useable /* 2a*/
#endif // HCF_TYPE_PRELOADED
for ( q = (hcf_8*)(&ifbp->IFB_Magic); q > (hcf_8*)ifbp; *--q = 0 ) /*NOP*/; /* 4 */
ifbp->IFB_Magic = HCF_MAGIC;
ifbp->IFB_Version = IFB_VERSION;
#if defined MSF_COMPONENT_ID //a new IFB demonstrates how dirty the solution is
xxxx[xxxx_PRI_IDENTITY_OFFSET] = NULL; //IFB_PRIIdentity placeholder 0xFD02
xxxx[xxxx_PRI_IDENTITY_OFFSET+1] = NULL; //IFB_PRISup placeholder 0xFD03
#endif // MSF_COMPONENT_ID
#if (HCF_TALLIES) & ( HCF_TALLIES_NIC | HCF_TALLIES_HCF )
ifbp->IFB_TallyLen = 1 + 2 * (HCF_NIC_TAL_CNT + HCF_HCF_TAL_CNT); //convert # of Tallies to L value for LTV
ifbp->IFB_TallyTyp = CFG_TALLIES; //IFB_TallyTyp: set T value
#endif // HCF_TALLIES_NIC / HCF_TALLIES_HCF
ifbp->IFB_IOBase = io_addr; //set IO_Base asap, so asserts via HREG_SW_2 don't harm
ifbp->IFB_IORange = HREG_IO_RANGE;
ifbp->IFB_CntlOpt = USE_16BIT;
#if HCF_ASSERT
assert_ifbp = ifbp;
ifbp->IFB_AssertLvl = 1;
#if (HCF_ASSERT) & HCF_ASSERT_LNK_MSF_RTN
if ( io_base != HCF_DISCONNECT ) {
ifbp->IFB_AssertRtn = (MSF_ASSERT_RTNP)msf_assert; /* 6 */
}
#endif // HCF_ASSERT_LNK_MSF_RTN
#if (HCF_ASSERT) & HCF_ASSERT_MB //build the structure to pass the assert info to hcf_put_info
ifbp->IFB_AssertStrct.len = sizeof(ifbp->IFB_AssertStrct)/sizeof(hcf_16) - 1;
ifbp->IFB_AssertStrct.typ = CFG_MB_INFO;
ifbp->IFB_AssertStrct.base_typ = CFG_MB_ASSERT;
ifbp->IFB_AssertStrct.frag_cnt = 1;
ifbp->IFB_AssertStrct.frag_buf[0].frag_len =
( offsetof(IFB_STRCT, IFB_AssertLvl) - offsetof(IFB_STRCT, IFB_AssertLine) ) / sizeof(hcf_16);
ifbp->IFB_AssertStrct.frag_buf[0].frag_addr = &ifbp->IFB_AssertLine;
#endif // HCF_ASSERT_MB
#endif // HCF_ASSERT
IF_PROT_TIME( prot_cnt = ifbp->IFB_TickIni = INI_TICK_INI );
#if ( (HCF_TYPE) & HCF_TYPE_PRELOADED ) == 0
//!! No asserts before Reset-bit in HREG_IO is cleared
OPW( HREG_IO, 0x0000 ); //OPW useable /* 2b*/
HCF_WAIT_WHILE( (IPW( HREG_EV_STAT) & HREG_EV_CMD) == 0 );
IF_PROT_TIME( HCFASSERT( prot_cnt, IPW( HREG_EV_STAT) ) );
IF_PROT_TIME( if ( prot_cnt ) prot_cnt = ifbp->IFB_TickIni );
#endif // HCF_TYPE_PRELOADED
//!! No asserts before Reset-bit in HREG_IO is cleared
HCFASSERT( DO_ASSERT, MERGE_2( HCF_ASSERT, 0xCAF0 ) ); //just to proof that the complete assert machinery is working
HCFASSERT( xa != CFG_FW_IDENTITY, 0 ); // assert if hcf_connect is called without intervening hcf_disconnect.
HCFASSERT( ((hcf_32)(void*)ifbp & (HCF_ALIGN-1) ) == 0, (hcf_32)(void*)ifbp );
HCFASSERT( (io_addr & 0x003F) == 0, io_addr );
//if Busy bit in Cmd register
if (IPW( HREG_CMD ) & HCMD_BUSY ) { /* 8 */
//. Ack all to unblock a (possibly) blocked cmd pipe line
OPW( HREG_EV_ACK, ~HREG_EV_SLEEP_REQ );
//. Wait for Busy bit drop in Cmd register
//. Wait for Cmd bit raise in Ev register
HCF_WAIT_WHILE( ( IPW( HREG_CMD ) & HCMD_BUSY ) && (IPW( HREG_EV_STAT) & HREG_EV_CMD) == 0 );
IF_PROT_TIME( HCFASSERT( prot_cnt, IPW( HREG_EV_STAT) ) ); /* if prot_cnt == 0, cmd_exe will fail, causing DEFUNCT */
}
OPW( HREG_EV_ACK, ~HREG_EV_SLEEP_REQ );
#if ( (HCF_TYPE) & HCF_TYPE_PRELOADED ) == 0 /*12*/
(void)cmd_exe( ifbp, HCMD_INI, 0 );
#endif // HCF_TYPE_PRELOADED
if ( io_base != HCF_DISCONNECT ) {
rc = init( ifbp ); /*14*/
if ( rc == HCF_SUCCESS ) {
x.len = 2;
x.typ = CFG_NIC_BUS_TYPE;
(void)hcf_get_info( ifbp, &x );
ifbp->IFB_BusType = x.val[0];
//CFG_NIC_BUS_TYPE not supported -> default 32 bits/DMA, MSF has to overrule via CFG_CNTL_OPT
if ( x.len == 0 || x.val[0] == 0x0002 || x.val[0] == 0x0003 ) {
#if (HCF_IO) & HCF_IO_32BITS
ifbp->IFB_CntlOpt &= ~USE_16BIT; //reset USE_16BIT
#endif // HCF_IO_32BITS
#if HCF_DMA
ifbp->IFB_CntlOpt |= USE_DMA; //SET DMA
#else
ifbp->IFB_IORange = 0x40 /*i.s.o. HREG_IO_RANGE*/;
#endif // HCF_DMA
}
}
} else HCFASSERT( ( ifbp->IFB_Magic ^= HCF_MAGIC ) == 0, ifbp->IFB_Magic ) /*NOP*/;
/* of above HCFASSERT only the side effect is needed, NOP in case HCFASSERT is dummy */
ifbp->IFB_IOBase = io_base; /* 0*/
return rc;
} // hcf_connect
#if HCF_DMA
/************************************************************************************************************
* Function get_frame_lst
* - resolve the "last host-owned descriptor" problems when a descriptor list is reclaimed by the MSF.
*
* The FrameList to be reclaimed as well as the DescriptorList always start in IFB_FirstDesc[tx_rx_flag]
* and this is always the "current" DELWA Descriptor.
*
* If a FrameList is available, the last descriptor of the FrameList to turned into a new DELWA Descriptor:
* - a copy is made from the information in the last descriptor of the FrameList into the current
* DELWA Descriptor
* - the remainder of the DescriptorList is detached from the copy by setting the next_desc_addr at NULL
* - the DMA control bits of the copy are cleared to do not confuse the MSF
* - the copy of the last descriptor (i.e. the "old" DELWA Descriptor) is chained to the prev Descriptor
* of the FrameList, thus replacing the original last Descriptor of the FrameList.
* - IFB_FirstDesc is changed to the address of that replaced (original) last descriptor of the FrameList,
* i.e. the "new" DELWA Descriptor.
*
* This function makes a copy of that last host-owned descriptor, so the MSF will get a copy of the descriptor.
* On top of that, it adjusts DMA related fields in the IFB structure.
// perform a copying-scheme to circumvent the 'last host owned descriptor cannot be reclaimed' limitation imposed by H2.5's DMA hardware design
// a 'reclaim descriptor' should be available in the HCF:
*
* Returns: address of the first descriptor of the FrameList
*
8: Be careful once you start re-ordering the steps in the copy process, that it still works for cases
* of FrameLists of 1, 2 and more than 2 descriptors
*
* Input parameters:
* tx_rx_flag : specifies 'transmit' or 'receive' descriptor.
*
************************************************************************************************************/
HCF_STATIC DESC_STRCT*
get_frame_lst( IFBP ifbp, int tx_rx_flag )
{
DESC_STRCT *head = ifbp->IFB_FirstDesc[tx_rx_flag];
DESC_STRCT *copy, *p, *prev;
HCFASSERT( tx_rx_flag == DMA_RX || tx_rx_flag == DMA_TX, tx_rx_flag );
//if FrameList
if ( head ) {
//. search for last descriptor of first FrameList
p = prev = head;
while ( ( p->BUF_SIZE & DESC_EOP ) == 0 && p->next_desc_addr ) {
if ( ( ifbp->IFB_CntlOpt & DMA_ENABLED ) == 0 ) { //clear control bits when disabled
p->BUF_CNT &= DESC_CNT_MASK;
}
prev = p;
p = p->next_desc_addr;
}
//. if DMA enabled
if ( ifbp->IFB_CntlOpt & DMA_ENABLED ) {
//. . if last descriptor of FrameList is DMA owned
//. . or if FrameList is single (DELWA) Descriptor
if ( p->BUF_CNT & DESC_DMA_OWNED || head->next_desc_addr == NULL ) {
//. . . refuse to return FrameList to caller
head = NULL;
}
}
}
//if returnable FrameList found
if ( head ) {
//. if FrameList is single (DELWA) Descriptor (implies DMA disabled)
if ( head->next_desc_addr == NULL ) {
//. . clear DescriptorList
/*;?ifbp->IFB_LastDesc[tx_rx_flag] =*/ ifbp->IFB_FirstDesc[tx_rx_flag] = NULL;
//. else
} else {
//. . strip hardware-related bits from last descriptor
//. . remove DELWA Descriptor from head of DescriptorList
copy = head;
head = head->next_desc_addr;
//. . exchange first (Confined) and last (possibly imprisoned) Descriptor
copy->buf_phys_addr = p->buf_phys_addr;
copy->buf_addr = p->buf_addr;
copy->BUF_SIZE = p->BUF_SIZE &= DESC_CNT_MASK; //get rid of DESC_EOP and possibly DESC_SOP
copy->BUF_CNT = p->BUF_CNT &= DESC_CNT_MASK; //get rid of DESC_DMA_OWNED
#if (HCF_EXT) & HCF_DESC_STRCT_EXT
copy->DESC_MSFSup = p->DESC_MSFSup;
#endif // HCF_DESC_STRCT_EXT
//. . turn into a DELWA Descriptor
p->buf_addr = NULL;
//. . chain copy to prev /* 8*/
prev->next_desc_addr = copy;
//. . detach remainder of the DescriptorList from FrameList
copy->next_desc_addr = NULL;
copy->next_desc_phys_addr = 0xDEAD0000; //! just to be nice, not really needed
//. . save the new start (i.e. DELWA Descriptor) in IFB_FirstDesc
ifbp->IFB_FirstDesc[tx_rx_flag] = p;
}
//. strip DESC_SOP from first descriptor
head->BUF_SIZE &= DESC_CNT_MASK;
//head->BUF_CNT &= DESC_CNT_MASK; get rid of DESC_DMA_OWNED
head->next_desc_phys_addr = 0xDEAD0000; //! just to be nice, not really needed
}
//return the just detached FrameList (if any)
return head;
} // get_frame_lst
/************************************************************************************************************
* Function put_frame_lst
*
* This function
*
* Returns: address of the first descriptor of the FrameList
*
* Input parameters:
* tx_rx_flag : specifies 'transmit' or 'receive' descriptor.
*
* The following list should be kept in sync with hcf_dma_tx/rx_put, in order to get them in the WCI-spec !!!!
* Assert fails if
* - DMA is not enabled
* - descriptor list is NULL
* - a descriptor in the descriptor list is not double word aligned
* - a count of size field of a descriptor contains control bits, i.e. bits in the high order nibble.
* - the DELWA descriptor is not a "singleton" DescriptorList.
* - the DELWA descriptor is not the first Descriptor supplied
* - a non_DMA descriptor is supplied before the DELWA Descriptor is supplied
* - Possibly more checks could be added !!!!!!!!!!!!!
*.NOTICE
* The asserts marked with *sc* are really sanity checks for the HCF, they can (supposedly) not be influenced
* by incorrect MSF behavior
// The MSF is required to supply the HCF with a single descriptor for MSF tx reclaim purposes.
// This 'reclaim descriptor' can be recognized by the fact that its buf_addr field is zero.
*********************************************************************************************
* Although not required from a hardware perspective:
* - make each descriptor in this rx-chain DMA-owned.
* - Also set the count to zero. EOP and SOP bits are also cleared.
*********************************************************************************************/
HCF_STATIC void
put_frame_lst( IFBP ifbp, DESC_STRCT *descp, int tx_rx_flag )
{
DESC_STRCT *p = descp;
hcf_16 port;
HCFASSERT( ifbp->IFB_CntlOpt & USE_DMA, ifbp->IFB_CntlOpt); //only hcf_dma_tx_put must also be DMA_ENABLED
HCFASSERT( tx_rx_flag == DMA_RX || tx_rx_flag == DMA_TX, tx_rx_flag );
HCFASSERT( p , 0 );
while ( p ) {
HCFASSERT( ((hcf_32)p & 3 ) == 0, (hcf_32)p );
HCFASSERT( (p->BUF_CNT & ~DESC_CNT_MASK) == 0, p->BUF_CNT );
HCFASSERT( (p->BUF_SIZE & ~DESC_CNT_MASK) == 0, p->BUF_SIZE );
p->BUF_SIZE &= DESC_CNT_MASK; //!!this SHOULD be superfluous in case of correct MSF
p->BUF_CNT &= tx_rx_flag == DMA_RX ? 0 : DESC_CNT_MASK; //!!this SHOULD be superfluous in case of correct MSF
p->BUF_CNT |= DESC_DMA_OWNED;
if ( p->next_desc_addr ) {
// HCFASSERT( p->buf_addr && p->buf_phys_addr && p->BUF_SIZE && +/- p->BUF_SIZE, ... );
HCFASSERT( p->next_desc_addr->desc_phys_addr, (hcf_32)p->next_desc_addr );
p->next_desc_phys_addr = p->next_desc_addr->desc_phys_addr;
} else { //
p->next_desc_phys_addr = 0;
if ( p->buf_addr == NULL ) { // DELWA Descriptor
HCFASSERT( descp == p, (hcf_32)descp ); //singleton DescriptorList
HCFASSERT( ifbp->IFB_FirstDesc[tx_rx_flag] == NULL, (hcf_32)ifbp->IFB_FirstDesc[tx_rx_flag]);
HCFASSERT( ifbp->IFB_LastDesc[tx_rx_flag] == NULL, (hcf_32)ifbp->IFB_LastDesc[tx_rx_flag]);
descp->BUF_CNT = 0; //&= ~DESC_DMA_OWNED;
ifbp->IFB_FirstDesc[tx_rx_flag] = descp;
// part of alternative ifbp->IFB_LastDesc[tx_rx_flag] = ifbp->IFB_FirstDesc[tx_rx_flag] = descp;
// if "recycling" a FrameList
// (e.g. called from hcf_cntl( HCF_CNTL_ENABLE )
// . prepare for activation DMA controller
// part of alternative descp = descp->next_desc_addr;
} else { //a "real" FrameList, hand it over to the DMA engine
HCFASSERT( ifbp->IFB_FirstDesc[tx_rx_flag], (hcf_32)descp );
HCFASSERT( ifbp->IFB_LastDesc[tx_rx_flag], (hcf_32)descp );
HCFASSERT( ifbp->IFB_LastDesc[tx_rx_flag]->next_desc_addr == NULL,
(hcf_32)ifbp->IFB_LastDesc[tx_rx_flag]->next_desc_addr);
// p->buf_cntl.cntl_stat |= DESC_DMA_OWNED;
ifbp->IFB_LastDesc[tx_rx_flag]->next_desc_addr = descp;
ifbp->IFB_LastDesc[tx_rx_flag]->next_desc_phys_addr = descp->desc_phys_addr;
port = HREG_RXDMA_PTR32;
if ( tx_rx_flag ) {
p->BUF_SIZE |= DESC_EOP; // p points at the last descriptor in the caller-supplied descriptor chain
descp->BUF_SIZE |= DESC_SOP;
port = HREG_TXDMA_PTR32;
}
OUT_PORT_DWORD( (ifbp->IFB_IOBase + port), descp->desc_phys_addr );
}
ifbp->IFB_LastDesc[tx_rx_flag] = p;
}
p = p->next_desc_addr;
}
} // put_frame_lst
/************************************************************************************************************
*
*.MODULE DESC_STRCT* hcf_dma_rx_get( IFBP ifbp )
*.PURPOSE decapsulate a message and provides that message to the MSF.
* reclaim all descriptors in the rx descriptor chain.
*
*.ARGUMENTS
* ifbp address of the Interface Block
*
*.RETURNS
* pointer to a FrameList
*
*.DESCRIPTION
* hcf_dma_rx_get is intended to return a received frame when such a frame is deposited in Host memory by the
* DMA engine. In addition hcf_dma_rx_get can be used to reclaim all descriptors in the rx descriptor chain
* when the DMA Engine is disabled, e.g. as part of a driver unloading strategy.
* hcf_dma_rx_get must be called repeatedly by the MSF when hcf_service_nic signals availability of a rx frame
* through the HREG_EV_RDMAD flag of IFB_DmaPackets. The calling must stop when a NULL pointer is returned, at
* which time the HREG_EV_RDMAD flag is also cleared by the HCF to arm the mechanism for the next frame
* reception.
* Regardless whether the DMA Engine is currently enabled (as controlled via hcf_cntl), if the DMA controller
* deposited an Rx-frame in the Rx-DescriptorList, this frame is detached from the Rx-DescriptorList,
* transformed into a FrameList (i.e. updating the housekeeping fields in the descriptors) and returned to the
* caller.
* If no such Rx-frame is available in the Rx-DescriptorList, the behavior of hcf_dma_rx_get depends on the
* status of the DMA Engine.
* If the DMA Engine is enabled, a NULL pointer is returned.
* If the DMA Engine is disabled, the following strategy is used:
* - the complete Rx-DescriptorList is returned. The DELWA Descriptor is not part of the Rx-DescriptorList.
* - If there is no Rx-DescriptorList, the DELWA Descriptor is returned.
* - If there is no DELWA Descriptor, a NULL pointer is returned.
*
* If the MSF performs an disable/enable sequence without exhausting the Rx-DescriptorList as described above,
* the enable command will reset all house keeping information, i.e. already received but not yet by the MSF
* retrieved frames are lost and the next frame will be received starting with the oldest descriptor.
*
* The HCF can be used in 2 fashions: with and without decapsulation for data transfer.
* This is controlled at compile time by the HCF_ENC bit of the HCF_ENCAP system constant.
* If appropriate, decapsulation is done by moving some data inside the buffers and updating the descriptors
* accordingly.
*!! ;?????where did I describe why a simple manipulation with the count values does not suffice?
*
*.DIAGRAM
*
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
DESC_STRCT*
hcf_dma_rx_get (IFBP ifbp)
{
DESC_STRCT *descp; // pointer to start of FrameList
descp = get_frame_lst( ifbp, DMA_RX );
if ( descp && descp->buf_addr ) {
//skip decapsulation at confined descriptor
#if (HCF_ENCAP) == HCF_ENC
int i;
DESC_STRCT *p = descp->next_desc_addr; //pointer to 2nd descriptor of frame
HCFASSERT(p, 0);
// The 2nd descriptor contains (maybe) a SNAP header plus part or whole of the payload.
//determine decapsulation sub-flag in RxFS
i = *(wci_recordp)&descp->buf_addr[HFS_STAT] & ( HFS_STAT_MSG_TYPE | HFS_STAT_ERR );
if ( i == HFS_STAT_TUNNEL ||
( i == HFS_STAT_1042 && hcf_encap( (wci_bufp)&p->buf_addr[HCF_DASA_SIZE] ) != ENC_TUNNEL )) {
// The 2nd descriptor contains a SNAP header plus part or whole of the payload.
HCFASSERT( p->BUF_CNT == (p->buf_addr[5] + (p->buf_addr[4]<<8) + 2*6 + 2 - 8), p->BUF_CNT );
// perform decapsulation
HCFASSERT(p->BUF_SIZE >=8, p->BUF_SIZE);
// move SA[2:5] in the second buffer to replace part of the SNAP header
for ( i=3; i >= 0; i--) p->buf_addr[i+8] = p->buf_addr[i];
// copy DA[0:5], SA[0:1] from first buffer to second buffer
for ( i=0; i<8; i++) p->buf_addr[i] = descp->buf_addr[HFS_ADDR_DEST + i];
// make first buffer shorter in count
descp->BUF_CNT = HFS_ADDR_DEST;
}
}
#endif // HCF_ENC
if ( descp == NULL ) ifbp->IFB_DmaPackets &= (hcf_16)~HREG_EV_RDMAD; //;?could be integrated into get_frame_lst
HCFLOGEXIT( HCF_TRACE_DMA_RX_GET );
return descp;
} // hcf_dma_rx_get
/************************************************************************************************************
*
*.MODULE void hcf_dma_rx_put( IFBP ifbp, DESC_STRCT *descp )
*.PURPOSE supply buffers for receive purposes.
* supply the Rx-DELWA descriptor.
*
*.ARGUMENTS
* ifbp address of the Interface Block
* descp address of a DescriptorList
*
*.RETURNS N.A.
*
*.DESCRIPTION
* This function is called by the MSF to supply the HCF with new/more buffers for receive purposes.
* The HCF can be used in 2 fashions: with and without encapsulation for data transfer.
* This is controlled at compile time by the HCF_ENC bit of the HCF_ENCAP system constant.
* As a consequence, some additional constraints apply to the number of descriptor and the buffers associated
* with the first 2 descriptors. Independent of the encapsulation feature, the COUNT fields are ignored.
* A special case is the supplying of the DELWA descriptor, which must be supplied as the first descriptor.
*
* Assert fails if
* - ifbp has a recognizable out-of-range value.
* - NIC interrupts are not disabled while required by parameter action.
* - in case decapsulation by the HCF is selected:
* - The first databuffer does not have the exact size corresponding with the RxFS up to the 802.3 DestAddr
* field (== 29 words).
* - The FrameList does not consists of at least 2 Descriptors.
* - The second databuffer does not have the minimum size of 8 bytes.
*!! The 2nd part of the list of asserts should be kept in sync with put_frame_lst, in order to get
*!! them in the WCI-spec !!!!
* - DMA is not enabled
* - descriptor list is NULL
* - a descriptor in the descriptor list is not double word aligned
* - a count of size field of a descriptor contains control bits, i.e. bits in the high order nibble.
* - the DELWA descriptor is not a "singleton" DescriptorList.
* - the DELWA descriptor is not the first Descriptor supplied
* - a non_DMA descriptor is supplied before the DELWA Descriptor is supplied
*!! - Possibly more checks could be added !!!!!!!!!!!!!
*
*.DIAGRAM
*
*
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
void
hcf_dma_rx_put( IFBP ifbp, DESC_STRCT *descp )
{
HCFLOGENTRY( HCF_TRACE_DMA_RX_PUT, 0xDA01 );
HCFASSERT( ifbp->IFB_Magic == HCF_MAGIC, ifbp->IFB_Magic );
HCFASSERT_INT;
put_frame_lst( ifbp, descp, DMA_RX );
#if HCF_ASSERT && (HCF_ENCAP) == HCF_ENC
if ( descp->buf_addr ) {
HCFASSERT( descp->BUF_SIZE == HCF_DMA_RX_BUF1_SIZE, descp->BUF_SIZE );
HCFASSERT( descp->next_desc_addr, 0 ); // first descriptor should be followed by another descriptor
// The second DB is for SNAP and payload purposes. It should be a minimum of 12 bytes in size.
HCFASSERT( descp->next_desc_addr->BUF_SIZE >= 12, descp->next_desc_addr->BUF_SIZE );
}
#endif // HCFASSERT / HCF_ENC
HCFLOGEXIT( HCF_TRACE_DMA_RX_PUT );
} // hcf_dma_rx_put
/************************************************************************************************************
*
*.MODULE DESC_STRCT* hcf_dma_tx_get( IFBP ifbp )
*.PURPOSE DMA mode: reclaims and decapsulates packets in the tx descriptor chain if:
* - A Tx packet has been copied from host-RAM into NIC-RAM by the DMA engine
* - The Hermes/DMAengine have been disabled
*
*.ARGUMENTS
* ifbp address of the Interface Block
*
*.RETURNS
* pointer to a reclaimed Tx packet.
*
*.DESCRIPTION
* impact of the disable command:
* When a non-empty pool of Tx descriptors exists (created by means of hcf_dma_put_tx), the MSF
* is supposed to empty that pool by means of hcf_dma_tx_get calls after the disable in an
* disable/enable sequence.
*
*.DIAGRAM
*
*.NOTICE
*
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
DESC_STRCT*
hcf_dma_tx_get( IFBP ifbp )
{
DESC_STRCT *descp; // pointer to start of FrameList
descp = get_frame_lst( ifbp, DMA_TX );
if ( descp && descp->buf_addr ) {
//skip decapsulation at confined descriptor
#if (HCF_ENCAP) == HCF_ENC
if ( ( descp->BUF_CNT == HFS_TYPE )) {
// perform decapsulation if needed
descp->next_desc_addr->buf_phys_addr -= HCF_DASA_SIZE;
descp->next_desc_addr->BUF_CNT += HCF_DASA_SIZE;
}
#endif // HCF_ENC
}
if ( descp == NULL ) { //;?could be integrated into get_frame_lst
ifbp->IFB_DmaPackets &= (hcf_16)~HREG_EV_TDMAD;
}
HCFLOGEXIT( HCF_TRACE_DMA_TX_GET );
return descp;
} // hcf_dma_tx_get
/************************************************************************************************************
*
*.MODULE void hcf_dma_tx_put( IFBP ifbp, DESC_STRCT *descp, hcf_16 tx_cntl )
*.PURPOSE puts a packet in the Tx DMA queue in host ram and kicks off the TxDma engine.
* supply the Tx-DELWA descriptor.
*
*.ARGUMENTS
* ifbp address of the Interface Block
* descp address of Tx Descriptor Chain (i.e. a single Tx frame)
* tx_cntl indicates MAC-port and (Hermes) options
*
*.RETURNS N.A.
*
*.DESCRIPTION
* The HCF can be used in 2 fashions: with and without encapsulation for data transfer.
* This is controlled at compile time by the HCF_ENC bit of the HCF_ENCAP system constant.
*
* Regardless of the HCF_ENCAP system constant, the descriptor list created to describe the frame to be
* transmitted, must supply space to contain the 802.11 header, preceding the actual frame to be transmitted.
* Basically, this only supplies working storage to the HCF which passes this on to the DMA engine.
* As a consequence the contents of this space do not matter.
* Nevertheless BUF_CNT must take in account this storage.
* This working space to contain the 802.11 header may not be fragmented, the first buffer must be
* sufficiently large to contain at least the 802.11 header, i.e. HFS_ADDR_DEST (29 words or 0x3A bytes).
* This way, the HCF can simply, regardless whether or not the HCF encapsulates the frame, write the parameter
* tx_cntl at offset 0x36 (HFS_TX_CNTL) in the first buffer.
* Note that it is allowed to have part or all of the actual frame represented by the first descriptor as long
* as the requirement for storage for the 802.11 header is met, i.e. the 802.3 frame starts at offset
* HFS_ADDR_DEST.
* Except for the Assert on the 1st buffer in case of Encapsualtion, the SIZE fields are ignored.
*
* In case the encapsulation feature is compiled in, there are the following additional requirements.
* o The BUF_CNT of the first buffer changes from a minimum of 0x3A bytes to exactly 0x3A, i.e. the workspace
* to store the 802.11 header
* o The BUF_SIZE of the first buffer is at least the space needed to store the
* - 802.11 header (29 words)
* - 802.3 header, i.e. 12 bytes addressing information and 2 bytes length field
* - 6 bytes SNAP-header
* This results in 39 words or 0x4E bytes or HFS_TYPE.
* Note that if the BUF_SIZE is larger than 0x4E, this surplus is not used.
* o The actual frame begins in the 2nd descriptor (which is already implied by the BUF_CNT == 0x3A requirement) and the associated buffer contains at least the 802.3 header, i.e. the 14 bytes representing addressing information and length/type field
*
* When the HCF does not encapsulates (i.e. length/type field <= 1500), no changes are made to descriptors
* or buffers.
*
* When the HCF actually encapsulates (i.e. length/type field > 1500), it successively writes, starting at
* offset HFS_ADDR_DEST (0x3A) in the first buffer:
* - the 802.3 addressing information, copied from the begin of the second buffer
* - the frame length, derived from the total length of the individual fragments, corrected for the SNAP
* header length and Type field and ignoring the Destination Address, Source Address and Length field
* - the appropriate snap header (Tunnel or 1042, depending on the value of the type field).
*
* The information in the first two descriptors is adjusted accordingly:
* - the first descriptor count is changed from 0x3A to 0x4E (HFS_TYPE), which matches 0x3A + 12 + 2 + 6
* - the second descriptor count is decreased by 12, being the moved addressing information
* - the second descriptor (physical) buffer address is increased by 12.
*
* When the descriptors are returned by hcf_dma_tx_get, the transformation of the first two descriptors is
* undone.
*
* Under any of the above scenarios, the assert BUF_CNT <= BUF_SIZE must be true for all descriptors
* In case of encapsulation, BUF_SIZE of the 1st descriptor is asserted to be at least HFS_TYPE (0x4E), so it is NOT tested.
*
* Assert fails if
* - ifbp has a recognizable out-of-range value.
* - tx_cntl has a recognizable out-of-range value.
* - NIC interrupts are not disabled while required by parameter action.
* - in case encapsulation by the HCF is selected:
* - The FrameList does not consists of at least 2 Descriptors.
* - The first databuffer does not contain exactly the (space for) the 802.11 header (== 28 words)
* - The first databuffer does not have a size to additionally accommodate the 802.3 header and the
* SNAP header of the frame after encapsulation (== 39 words).
* - The second databuffer does not contain at least DA, SA and 'type/length' (==14 bytes or 7 words)
*!! The 2nd part of the list of asserts should be kept in sync with put_frame_lst, in order to get
*!! them in the WCI-spec !!!!
* - DMA is not enabled
* - descriptor list is NULL
* - a descriptor in the descriptor list is not double word aligned
* - a count of size field of a descriptor contains control bits, i.e. bits in the high order nibble.
* - the DELWA descriptor is not a "singleton" DescriptorList.
* - the DELWA descriptor is not the first Descriptor supplied
* - a non_DMA descriptor is supplied before the DELWA Descriptor is supplied
*!! - Possibly more checks could be added !!!!!!!!!!!!!
*.DIAGRAM
*
*.NOTICE
*
*.ENDDOC END DOCUMENTATION
*
*
*1: Write tx_cntl parameter to HFS_TX_CNTL field into the Hermes-specific header in buffer 1
*4: determine whether encapsulation is needed and write the type (tunnel or 1042) already at the appropriate
* offset in the 1st buffer
*6: Build the encapsualtion enveloppe in the free space at the end of the 1st buffer
* - Copy DA/SA fields from the 2nd buffer
* - Calculate total length of the message (snap-header + type-field + the length of all buffer fragments
* associated with the 802.3 frame (i.e all descriptors except the first), but not the DestinationAddress,
* SourceAddress and length-field)
* Assert the message length
* Write length. Note that the message is in BE format, hence on LE platforms the length must be converted
* ;? THIS IS NOT WHAT CURRENTLY IS IMPLEMENTED
* - Write snap header. Note that the last byte of the snap header is NOT copied, that byte is already in
* place as result of the call to hcf_encap.
* Note that there are many ways to skin a cat. To express the offsets in the 1st buffer while writing
* the snap header, HFS_TYPE is chosen as a reference point to make it easier to grasp that the snap header
* and encapsualtion type are at least relative in the right.
*8: modify 1st descriptor to reflect moved part of the 802.3 header + Snap-header
* modify 2nd descriptor to skip the moved part of the 802.3 header (DA/SA
*10: set each descriptor to 'DMA owned', clear all other control bits.
* Set SOP bit on first descriptor. Set EOP bit on last descriptor.
*12: Either append the current frame to an existing descriptor list or
*14: create a list beginning with the current frame
*16: remember the new end of the list
*20: hand the frame over to the DMA engine
************************************************************************************************************/
void
hcf_dma_tx_put( IFBP ifbp, DESC_STRCT *descp, hcf_16 tx_cntl )
{
DESC_STRCT *p = descp->next_desc_addr;
int i;
#if HCF_ASSERT
int x = ifbp->IFB_FWIdentity.comp_id == COMP_ID_FW_AP ? tx_cntl & ~HFS_TX_CNTL_PORT : tx_cntl;
HCFASSERT( (x & ~HCF_TX_CNTL_MASK ) == 0, tx_cntl );
#endif // HCF_ASSERT
HCFLOGENTRY( HCF_TRACE_DMA_TX_PUT, 0xDA03 );
HCFASSERT( ifbp->IFB_Magic == HCF_MAGIC, ifbp->IFB_Magic );
HCFASSERT_INT;
HCFASSERT( ( ifbp->IFB_CntlOpt & (USE_DMA|DMA_ENABLED) ) == (USE_DMA|DMA_ENABLED), ifbp->IFB_CntlOpt);
if ( descp->buf_addr ) {
*(hcf_16*)(descp->buf_addr + HFS_TX_CNTL) = tx_cntl; /*1*/
#if (HCF_ENCAP) == HCF_ENC
HCFASSERT( descp->next_desc_addr, 0 ); //at least 2 descripors
HCFASSERT( descp->BUF_CNT == HFS_ADDR_DEST, descp->BUF_CNT ); //exact length required for 1st buffer
HCFASSERT( descp->BUF_SIZE >= HCF_DMA_TX_BUF1_SIZE, descp->BUF_SIZE ); //minimal storage for encapsulation
HCFASSERT( p->BUF_CNT >= 14, p->BUF_CNT ); //at least DA, SA and 'type' in 2nd buffer
descp->buf_addr[HFS_TYPE-1] = hcf_encap(&descp->next_desc_addr->buf_addr[HCF_DASA_SIZE]); /*4*/
if ( descp->buf_addr[HFS_TYPE-1] != ENC_NONE ) {
for ( i=0; i < HCF_DASA_SIZE; i++ ) { /*6*/
descp->buf_addr[i + HFS_ADDR_DEST] = descp->next_desc_addr->buf_addr[i];
}
i = sizeof(snap_header) + 2 - ( 2*6 + 2 );
do { i += p->BUF_CNT; } while ( ( p = p->next_desc_addr ) != NULL );
*(hcf_16*)(&descp->buf_addr[HFS_LEN]) = CNV_END_SHORT(i); //!! this converts on ALL platforms, how does that relate to the CCX code
for ( i=0; i < sizeof(snap_header) - 1; i++) {
descp->buf_addr[HFS_TYPE - sizeof(snap_header) + i] = snap_header[i];
}
descp->BUF_CNT = HFS_TYPE; /*8*/
descp->next_desc_addr->buf_phys_addr += HCF_DASA_SIZE;
descp->next_desc_addr->BUF_CNT -= HCF_DASA_SIZE;
}
#endif // HCF_ENC
}
put_frame_lst( ifbp, descp, DMA_TX );
HCFLOGEXIT( HCF_TRACE_DMA_TX_PUT );
} // hcf_dma_tx_put
#endif // HCF_DMA
/************************************************************************************************************
*
*.MODULE hcf_8 hcf_encap( wci_bufp type )
*.PURPOSE test whether RFC1042 or Bridge-Tunnel encapsulation is needed.
*
*.ARGUMENTS
* type (Far) pointer to the (Big Endian) Type/Length field in the message
*
*.RETURNS
* ENC_NONE len/type is "len" ( (BIG_ENDIAN)type <= 1500 )
* ENC_TUNNEL len/type is "type" and 0x80F3 or 0x8137
* ENC_1042 len/type is "type" but not 0x80F3 or 0x8137
*
*.CONDITIONS
* NIC Interrupts d.c
*
*.DESCRIPTION
* Type must point to the Len/Type field of the message, this is the 2-byte field immediately after the 6 byte
* Destination Address and 6 byte Source Address. The 2 successive bytes addressed by type are interpreted as
* a Big Endian value. If that value is less than or equal to 1500, the message is assumed to be in 802.3
* format. Otherwise the message is assumed to be in Ethernet-II format. Depending on the value of Len/Typ,
* Bridge Tunnel or RFC1042 encapsulation is needed.
*
*.DIAGRAM
*
* 1: presume 802.3, hence preset return value at ENC_NONE
* 2: convert type from "network" Endian format to native Endian
* 4: the litmus test to distinguish type and len.
* The hard code "magic" value of 1500 is intentional and should NOT be replaced by a mnemonic because it is
* not related at all to the maximum frame size supported by the Hermes.
* 6: check type against:
* 0x80F3 //AppleTalk Address Resolution Protocol (AARP)
* 0x8137 //IPX
* to determine the type of encapsulation
*
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
HCF_STATIC hcf_8
hcf_encap( wci_bufp type )
{
hcf_8 rc = ENC_NONE; /* 1 */
hcf_16 t = (hcf_16)(*type<<8) + *(type+1); /* 2 */
if ( t > 1500 ) { /* 4 */
if ( t == 0x8137 || t == 0x80F3 ) {
rc = ENC_TUNNEL; /* 6 */
} else {
rc = ENC_1042;
}
}
return rc;
} // hcf_encap
/************************************************************************************************************
*
*.MODULE int hcf_get_info( IFBP ifbp, LTVP ltvp )
*.PURPOSE Obtains transient and persistent configuration information from the Card and from the HCF.
*
*.ARGUMENTS
* ifbp address of the Interface Block
* ltvp address of LengthTypeValue structure specifying the "what" and the "how much" of the
* information to be collected from the HCF or from the Hermes
*
*.RETURNS
* HCF_ERR_LEN The provided buffer was too small
* HCF_SUCCESS Success
*!! via cmd_exe ( type >= CFG_RID_FW_MIN )
* HCF_ERR_NO_NIC NIC removed during retrieval
* HCF_ERR_TIME_OUT Expected Hermes event did not occur in expected time
*!! via cmd_exe and setup_bap (type >= CFG_RID_FW_MIN )
* HCF_ERR_DEFUNCT_... HCF is in defunct mode (bits 0x7F reflect cause)
*
*.DESCRIPTION
* The T-field of the LTV-record (provided by the MSF in parameter ltvp) specifies the RID wanted. The RID
* information identified by the T-field is copied into the V-field.
* On entry, the L-field specifies the size of the buffer, also called the "Initial DataLength". The L-value
* includes the size of the T-field, but not the size of the L-field itself.
* On return, the L-field indicates the number of words actually contained by the Type and Value fields.
* As the size of the Type field in the LTV-record is included in the "Initial DataLength" of the record, the
* V-field can contain at most "Initial DataLength" - 1 words of data.
* Copying stops if either the complete Information is copied or if the number of words indicated by the
* "Initial DataLength" were copied. The "Initial DataLength" acts as a safe guard against Configuration
* Information blocks that have different sizes for different F/W versions, e.g. when later versions support
* more tallies than earlier versions.
* If the size of Value field of the RID exceeds the size of the "Initial DataLength" -1, as much data
* as fits is copied, and an error status of HCF_ERR_LEN is returned.
*
* It is the responsibility of the MSF to detect card removal and re-insertion and not call the HCF when the
* NIC is absent. The MSF cannot, however, timely detect a Card removal if the Card is removed while
* hcf_get_info is in progress. Therefore, the HCF performs its own check on Card presence after the read
* operation of the NIC data. If the Card is not present or removed during the execution of hcf_get_info,
* HCF_ERR_NO_NIC is returned and the content of the Data Buffer is unpredictable. This check is not performed
* in case of the "HCF embedded" pseudo RIDs like CFG_TALLIES.
*
* Assert fails if
* - ifbp has a recognizable out-of-range value.
* - reentrancy, may be caused by calling hcf_functions without adequate protection
* against NIC interrupts or multi-threading.
* - ltvp is a NULL pointer.
* - length field of the LTV-record at entry is 0 or 1 or has an excessive value (i.e. exceeds HCF_MAX_LTV).
* - type field of the LTV-record is invalid.
*
*.DIAGRAM
* Hcf_get_mb_info copies the contents of the oldest MailBox Info block in the MailBox to PC RAM. If len is
* less than the size of the MailBox Info block, only as much as fits in the PC RAM buffer is copied. After
* the copying the MailBox Read pointer is updated to point to the next MailBox Info block, hence the
* remainder of an "oversized" MailBox Info block is lost. The truncation of the MailBox Info block is NOT
* reflected in the return status. Note that hcf_get_info guarantees the length of the PC RAM buffer meets
* the minimum requirements of at least 2, so no PC RAM buffer overrun.
*
* Calling hcf_get_mb_info when their is no MailBox Info block available or when there is no MailBox at all,
* results in a "NULL" MailBox Info block.
*
*12: see NOTICE
*17: The return status of cmd_wait and the first hcfio_in_string can be ignored, because when one fails, the
* other fails via the IFB_DefunctStat mechanism
*20: "HCFASSERT( rc == HCF_SUCCESS, rc )" is not suitable because this will always trigger as side effect of
* the HCFASSERT in hcf_put_info which calls hcf_get_info to figure out whether the RID exists at all.
*.NOTICE
*
* "HCF embedded" pseudo RIDs:
* CFG_MB_INFO, CFG_TALLIES, CFG_DRV_IDENTITY, CFG_DRV_SUP_RANGE, CFG_DRV_ACT_RANGES_PRI,
* CFG_DRV_ACT_RANGES_STA, CFG_DRV_ACT_RANGES_HSI
* Note the HCF_ERR_LEN is NOT adequately set, when L >= 2 but less than needed
*
* Remarks: Transfers operation information and transient and persistent configuration information from the
* Card and from the HCF to the MSF.
* The exact layout of the provided data structure depends on the action code. Copying stops if either the
* complete Configuration Information is copied or if the number of bytes indicated by len is copied. Len
* acts as a safe guard against Configuration Information blocks which have different sizes for different
* Hermes versions, e.g. when later versions support more tallies than earlier versions. It is a conscious
* decision that unused parts of the PC RAM buffer are not cleared.
*
* Remarks: The only error against which is protected is the "Read error" as result of Card removal. Only the
* last hcf_io_string need to be protected because if the first fails the second will fail as well. Checking
* for cmd_exe errors is supposed superfluous because problems in cmd_exe are already caught or will be
* caught by hcf_enable.
*
* CFG_MB_INFO: copy the oldest MailBox Info Block or the "null" block if none available.
*
* The mechanism to HCF_ASSERT on invalid typ-codes in the LTV record is based on the following strategy:
* - during the pseudo-asynchronous Hermes commands (diagnose, download) only CFG_MB_INFO is acceptable
* - some codes (e.g. CFG_TALLIES) are explicitly handled by the HCF which implies that these codes
* are valid
* - all other codes in the range 0xFC00 through 0xFFFF are passed to the Hermes. The Hermes returns an
* LTV record with a zero value in the L-field for all Typ-codes it does not recognize. This is
* defined and intended behavior, so HCF_ASSERT does not catch on this phenomena.
* - all remaining codes are invalid and cause an ASSERT.
*
*.CONDITIONS
* In case of USB, HCF_MAX_MSG ;?USED;? to limit the amount of data that can be retrieved via hcf_get_info.
*
*
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
int
hcf_get_info( IFBP ifbp, LTVP ltvp )
{
int rc = HCF_SUCCESS;
hcf_16 len = ltvp->len;
hcf_16 type = ltvp->typ;
wci_recordp p = <vp->len; //destination word pointer (in LTV record)
hcf_16 *q = NULL; /* source word pointer Note!! DOS COM can't cope with FAR
* as a consequence MailBox must be near which is usually true anyway
*/
int i;
HCFLOGENTRY( HCF_TRACE_GET_INFO, ltvp->typ );
HCFASSERT( ifbp->IFB_Magic == HCF_MAGIC, ifbp->IFB_Magic );
HCFASSERT_INT;
HCFASSERT( ltvp, 0 );
HCFASSERT( 1 < ltvp->len && ltvp->len <= HCF_MAX_LTV + 1, MERGE_2( ltvp->typ, ltvp->len ) );
ltvp->len = 0; //default to: No Info Available
//filter out all specials
for ( i = 0; ( q = xxxx[i] ) != NULL && q[1] != type; i++ ) /*NOP*/;
#if HCF_TALLIES
if ( type == CFG_TALLIES ) { /*3*/
(void)hcf_action( ifbp, HCF_ACT_TALLIES );
q = (hcf_16*)&ifbp->IFB_TallyLen;
}
#endif // HCF_TALLIES
if ( type == CFG_MB_INFO ) {
if ( ifbp->IFB_MBInfoLen ) {
if ( ifbp->IFB_MBp[ifbp->IFB_MBRp] == 0xFFFF ) {
ifbp->IFB_MBRp = 0; //;?Probably superfluous
}
q = &ifbp->IFB_MBp[ifbp->IFB_MBRp];
ifbp->IFB_MBRp += *q + 1; //update read pointer
if ( ifbp->IFB_MBp[ifbp->IFB_MBRp] == 0xFFFF ) {
ifbp->IFB_MBRp = 0;
}
ifbp->IFB_MBInfoLen = ifbp->IFB_MBp[ifbp->IFB_MBRp];
}
}
if ( q != NULL ) { //a special or CFG_TALLIES or CFG_MB_INFO
i = min( len, *q ) + 1; //total size of destination (including T-field)
while ( i-- ) {
*p++ = *q;
#if (HCF_TALLIES) & HCF_TALLIES_RESET
if ( q > &ifbp->IFB_TallyTyp && type == CFG_TALLIES ) {
*q = 0;
}
#endif // HCF_TALLIES_RESET
q++;
}
} else { // not a special nor CFG_TALLIES nor CFG_MB_INFO
if ( type == CFG_CNTL_OPT ) { //read back effective options
ltvp->len = 2;
ltvp->val[0] = ifbp->IFB_CntlOpt;
#if (HCF_EXT) & HCF_EXT_NIC_ACCESS
} else if ( type == CFG_PROD_DATA ) { //only needed for some test tool on top of H-II NDIS driver
hcf_io io_port;
wci_bufp pt; //pointer with the "right" type, just to help ease writing macros with embedded assembly
OPW( HREG_AUX_PAGE, (hcf_16)(PLUG_DATA_OFFSET >> 7) );
OPW( HREG_AUX_OFFSET, (hcf_16)(PLUG_DATA_OFFSET & 0x7E) );
io_port = ifbp->IFB_IOBase + HREG_AUX_DATA; //to prevent side effects of the MSF-defined macro
p = ltvp->val; //destination char pointer (in LTV record)
i = len - 1;
if (i > 0 ) {
pt = (wci_bufp)p; //just to help ease writing macros with embedded assembly
IN_PORT_STRING_8_16( io_port, pt, i ); //space used by T: -1
}
} else if ( type == CFG_CMD_HCF ) {
#define P ((CFG_CMD_HCF_STRCT FAR *)ltvp)
HCFASSERT( P->cmd == CFG_CMD_HCF_REG_ACCESS, P->cmd ); //only Hermes register access supported
if ( P->cmd == CFG_CMD_HCF_REG_ACCESS ) {
HCFASSERT( P->mode < ifbp->IFB_IOBase, P->mode ); //Check Register space
ltvp->len = min( len, 4 ); //RESTORE ltv length
P->add_info = IPW( P->mode );
}
#undef P
#endif // HCF_EXT_NIC_ACCESS
#if (HCF_ASSERT) & HCF_ASSERT_PRINTF
} else if (type == CFG_FW_PRINTF) {
rc = fw_printf(ifbp, (CFG_FW_PRINTF_STRCT*)ltvp);
#endif // HCF_ASSERT_PRINTF
} else if ( type >= CFG_RID_FW_MIN ) {
//;? by using HCMD_BUSY option when calling cmd_exe, using a get_frag with length 0 just to set up the
//;? BAP and calling cmd_cmpl, you could merge the 2 Busy waits. Whether this really helps (and what
//;? would be the optimal sequence in cmd_exe and get_frag) would have to be MEASURED
/*17*/ if ( ( rc = cmd_exe( ifbp, HCMD_ACCESS, type ) ) == HCF_SUCCESS &&
( rc = setup_bap( ifbp, type, 0, IO_IN ) ) == HCF_SUCCESS ) {
get_frag( ifbp, (wci_bufp)<vp->len, 2*len+2 BE_PAR(2) );
if ( IPW( HREG_STAT ) == 0xFFFF ) { //NIC removal test
ltvp->len = 0;
HCFASSERT( DO_ASSERT, type );
}
}
/*12*/ } else HCFASSERT( DO_ASSERT, type ) /*NOP*/; //NOP in case HCFASSERT is dummy
}
if ( len < ltvp->len ) {
ltvp->len = len;
if ( rc == HCF_SUCCESS ) {
rc = HCF_ERR_LEN;
}
}
HCFASSERT( rc == HCF_SUCCESS || ( rc == HCF_ERR_LEN && ifbp->IFB_AssertTrace & 1<<HCF_TRACE_PUT_INFO ),
MERGE_2( type, rc ) ); /*20*/
HCFLOGEXIT( HCF_TRACE_GET_INFO );
return rc;
} // hcf_get_info
/************************************************************************************************************
*
*.MODULE int hcf_put_info( IFBP ifbp, LTVP ltvp )
*.PURPOSE Transfers operation and configuration information to the Card and to the HCF.
*
*.ARGUMENTS
* ifbp address of the Interface Block
* ltvp specifies the RID (as defined by Hermes I/F) or pseudo-RID (as defined by WCI)
*
*.RETURNS
* HCF_SUCCESS
*!! via cmd_exe
* HCF_ERR_NO_NIC NIC removed during data retrieval
* HCF_ERR_TIME_OUT Expected F/W event did not occur in time
* HCF_ERR_DEFUNCT_...
*!! via download CFG_DLNV_START <= type <= CFG_DL_STOP
*!! via put_info CFG_RID_CFG_MIN <= type <= CFG_RID_CFG_MAX
*!! via put_frag
*
*.DESCRIPTION
* The L-field of the LTV-record (provided by the MSF in parameter ltvp) specifies the size of the buffer.
* The L-value includes the size of the T-field, but not the size of the L-field.
* The T- field specifies the RID placed in the V-field by the MSF.
*
* Not all CFG-codes can be used for hcf_put_info. The following CFG-codes are valid for hcf_put_info:
* o One of the CFG-codes in the group "Network Parameters, Static Configuration Entities"
* Changes made by hcf_put_info to CFG_codes in this group will not affect the F/W
* and HCF behavior until hcf_cntl_port( HCF_PORT_ENABLE) is called.
* o One of the CFG-codes in the group "Network Parameters, Dynamic Configuration Entities"
* Changes made by hcf_put_info to CFG_codes will affect the F/W and HCF behavior immediately.
* o CFG_PROG.
* This code is used to initiate and terminate the process to download data either to
* volatile or to non-volatile RAM on the NIC as well as for the actual download.
* o CFG-codes related to the HCF behavior.
* The related CFG-codes are:
* - CFG_REG_MB
* - CFG_REG_ASSERT_RTNP
* - CFG_REG_INFO_LOG
* - CFG_CMD_NIC
* - CFG_CMD_DONGLE
* - CFG_CMD_HCF
* - CFG_NOTIFY
*
* All LTV-records "unknown" to the HCF are forwarded to the F/W.
*
* Assert fails if
* - ifbp has a recognizable out-of-range value.
* - ltvp is a NULL pointer.
* - hcf_put_info was called without prior call to hcf_connect
* - type field of the LTV-record is invalid, i.e. neither HCF nor F/W can handle the value.
* - length field of the LTV-record at entry is less than 1 or exceeds MAX_LTV_SIZE.
* - registering a MailBox with size less than 60 or a non-aligned buffer address is used.
* - reentrancy, may be caused by calling hcf_functions without adequate protection against
* NIC interrupts or multi-threading.
*
*.DIAGRAM
*
*.NOTICE
* Remarks: In case of Hermes Configuration LTVs, the codes for the type are "cleverly" chosen to be
* identical to the RID. Hermes Configuration information is copied from the provided data structure into the
* Card.
* In case of HCF Configuration LTVs, the type values are chosen in a range which does not overlap the
* RID-range.
*
*20:
*
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
int
hcf_put_info( IFBP ifbp, LTVP ltvp )
{
int rc = HCF_SUCCESS;
HCFLOGENTRY( HCF_TRACE_PUT_INFO, ltvp->typ );
HCFASSERT( ifbp->IFB_Magic == HCF_MAGIC, ifbp->IFB_Magic );
HCFASSERT_INT;
HCFASSERT( ltvp, 0 );
HCFASSERT( 1 < ltvp->len && ltvp->len <= HCF_MAX_LTV + 1, ltvp->len );
//all codes between 0xFA00 and 0xFCFF are passed to Hermes
#if (HCF_TYPE) & HCF_TYPE_WPA
{
hcf_16 i;
hcf_32 FAR * key_p;
if ( ltvp->typ == CFG_ADD_TKIP_DEFAULT_KEY || ltvp->typ == CFG_ADD_TKIP_MAPPED_KEY ) {
key_p = (hcf_32*)((CFG_ADD_TKIP_MAPPED_KEY_STRCT FAR *)ltvp)->tx_mic_key;
i = TX_KEY; //i.e. TxKeyIndicator == 1, KeyID == 0
if ( ltvp->typ == CFG_ADD_TKIP_DEFAULT_KEY ) {
key_p = (hcf_32*)((CFG_ADD_TKIP_DEFAULT_KEY_STRCT FAR *)ltvp)->tx_mic_key;
i = CNV_LITTLE_TO_SHORT(((CFG_ADD_TKIP_DEFAULT_KEY_STRCT FAR *)ltvp)->tkip_key_id_info);
}
if ( i & TX_KEY ) { /* TxKeyIndicator == 1
(either really set by MSF in case of DEFAULT or faked by HCF in case of MAPPED ) */
ifbp->IFB_MICTxCntl = (hcf_16)( HFS_TX_CNTL_MIC | (i & KEY_ID )<<8 );
ifbp->IFB_MICTxKey[0] = CNV_LONGP_TO_LITTLE( key_p );
ifbp->IFB_MICTxKey[1] = CNV_LONGP_TO_LITTLE( (key_p+1) );
}
i = ( i & KEY_ID ) * 2;
ifbp->IFB_MICRxKey[i] = CNV_LONGP_TO_LITTLE( (key_p+2) );
ifbp->IFB_MICRxKey[i+1] = CNV_LONGP_TO_LITTLE( (key_p+3) );
}
#define P ((CFG_REMOVE_TKIP_DEFAULT_KEY_STRCT FAR *)ltvp)
if ( ( ltvp->typ == CFG_REMOVE_TKIP_MAPPED_KEY ) ||
( ltvp->typ == CFG_REMOVE_TKIP_DEFAULT_KEY &&
( (ifbp->IFB_MICTxCntl >> 8) & KEY_ID ) == CNV_SHORT_TO_LITTLE(P->tkip_key_id )
)
) { ifbp->IFB_MICTxCntl = 0; } //disable MIC-engine
#undef P
}
#endif // HCF_TYPE_WPA
if ( ltvp->typ == CFG_PROG ) {
rc = download( ifbp, (CFG_PROG_STRCT FAR *)ltvp );
} else switch (ltvp->typ) {
#if (HCF_ASSERT) & HCF_ASSERT_RT_MSF_RTN
case CFG_REG_ASSERT_RTNP: //Register MSF Routines
#define P ((CFG_REG_ASSERT_RTNP_STRCT FAR *)ltvp)
ifbp->IFB_AssertRtn = P->rtnp;
// ifbp->IFB_AssertLvl = P->lvl; //TODO not yet supported so default is set in hcf_connect
HCFASSERT( DO_ASSERT, MERGE_2( HCF_ASSERT, 0xCAF1 ) ); //just to proof that the complete assert machinery is working
#undef P
break;
#endif // HCF_ASSERT_RT_MSF_RTN
#if (HCF_EXT) & HCF_EXT_INFO_LOG
case CFG_REG_INFO_LOG: //Register Log filter
ifbp->IFB_RIDLogp = ((CFG_RID_LOG_STRCT FAR*)ltvp)->recordp;
break;
#endif // HCF_EXT_INFO_LOG
case CFG_CNTL_OPT: //overrule option
HCFASSERT( ( ltvp->val[0] & ~(USE_DMA | USE_16BIT) ) == 0, ltvp->val[0] );
if ( ( ltvp->val[0] & USE_DMA ) == 0 ) ifbp->IFB_CntlOpt &= ~USE_DMA;
ifbp->IFB_CntlOpt |= ltvp->val[0] & USE_16BIT;
break;
case CFG_REG_MB: //Register MailBox
#define P ((CFG_REG_MB_STRCT FAR *)ltvp)
HCFASSERT( ( (hcf_32)P->mb_addr & 0x0001 ) == 0, (hcf_32)P->mb_addr );
HCFASSERT( (P)->mb_size >= 60, (P)->mb_size );
ifbp->IFB_MBp = P->mb_addr;
/* if no MB present, size must be 0 for ;?the old;? put_info_mb to work correctly */
ifbp->IFB_MBSize = ifbp->IFB_MBp == NULL ? 0 : P->mb_size;
ifbp->IFB_MBWp = ifbp->IFB_MBRp = 0;
ifbp->IFB_MBp[0] = 0; //flag the MailBox as empty
ifbp->IFB_MBInfoLen = 0;
HCFASSERT( ifbp->IFB_MBSize >= 60 || ifbp->IFB_MBp == NULL, ifbp->IFB_MBSize );
#undef P
break;
case CFG_MB_INFO: //store MailBoxInfoBlock
rc = put_info_mb( ifbp, (CFG_MB_INFO_STRCT FAR *)ltvp );
break;
#if (HCF_EXT) & HCF_EXT_NIC_ACCESS
case CFG_CMD_NIC:
#define P ((CFG_CMD_NIC_STRCT FAR *)ltvp)
OPW( HREG_PARAM_2, P->parm2 );
OPW( HREG_PARAM_1, P->parm1 );
rc = cmd_exe( ifbp, P->cmd, P->parm0 );
P->hcf_stat = (hcf_16)rc;
P->stat = IPW( HREG_STAT );
P->resp0 = IPW( HREG_RESP_0 );
P->resp1 = IPW( HREG_RESP_1 );
P->resp2 = IPW( HREG_RESP_2 );
P->ifb_err_cmd = ifbp->IFB_ErrCmd;
P->ifb_err_qualifier = ifbp->IFB_ErrQualifier;
#undef P
break;
case CFG_CMD_HCF:
#define P ((CFG_CMD_HCF_STRCT FAR *)ltvp)
HCFASSERT( P->cmd == CFG_CMD_HCF_REG_ACCESS, P->cmd ); //only Hermes register access supported
if ( P->cmd == CFG_CMD_HCF_REG_ACCESS ) {
HCFASSERT( P->mode < ifbp->IFB_IOBase, P->mode ); //Check Register space
OPW( P->mode, P->add_info);
}
#undef P
break;
#endif // HCF_EXT_NIC_ACCESS
#if (HCF_ASSERT) & HCF_ASSERT_PRINTF
case CFG_FW_PRINTF_BUFFER_LOCATION:
ifbp->IFB_FwPfBuff = *(CFG_FW_PRINTF_BUFFER_LOCATION_STRCT*)ltvp;
break;
#endif // HCF_ASSERT_PRINTF
default: //pass everything unknown above the "FID" range to the Hermes or Dongle
rc = put_info( ifbp, ltvp );
}
//DO NOT !!! HCFASSERT( rc == HCF_SUCCESS, rc ) /* 20 */
HCFLOGEXIT( HCF_TRACE_PUT_INFO );
return rc;
} // hcf_put_info
/************************************************************************************************************
*
*.MODULE int hcf_rcv_msg( IFBP ifbp, DESC_STRCT *descp, unsigned int offset )
*.PURPOSE All: decapsulate a message.
* pre-HermesII.5: verify MIC.
* non-USB, non-DMA mode: Transfer a message from the NIC to the Host and acknowledge reception.
* USB: Transform a message from proprietary USB format to 802.3 format
*
*.ARGUMENTS
* ifbp address of the Interface Block
* descp Pointer to the Descriptor List location.
* offset USB: not used
* non-USB: specifies the beginning of the data to be obtained (0 corresponds with DestAddr field
* of frame).
*
*.RETURNS
* HCF_SUCCESS No WPA error ( or HCF_ERR_MIC already reported by hcf_service_nic)
* HCF_ERR_MIC message contains an erroneous MIC ( HCF_SUCCESS is reported if HCF_ERR_MIC is already
* reported by hcf_service_nic)
* HCF_ERR_NO_NIC NIC removed during data retrieval
* HCF_ERR_DEFUNCT...
*
*.DESCRIPTION
* The Receive Message Function can be executed by the MSF to obtain the Data Info fields of the message that
* is reported to be available by the Service NIC Function.
*
* The Receive Message Function copies the message data available in the Card memory into a buffer structure
* provided by the MSF.
* Only data of the message indicated by the Service NIC Function can be obtained.
* Execution of the Service NIC function may result in the availability of a new message, but it definitely
* makes the message reported by the preceding Service NIC function, unavailable.
*
* in non-USB/non-DMA mode, hcf_rcv_msg starts the copy process at the (non-negative) offset requested by the
* parameter offset, relative to HFS_ADDR_DEST, e.g offset 0 starts copying from the Destination Address, the
* very begin of the 802.3 frame message. Offset must either lay within the part of the 802.3 frame as stored
* by hcf_service_nic in the lookahead buffer or be just behind it, i.e. the first byte not yet read.
* When offset is within lookahead, data is copied from lookahead.
* When offset is beyond lookahead, data is read directly from RxFS in NIC with disregard of the actual value
* of offset
*
*.NOTICE:
* o at entry: look ahead buffer as passed with hcf_service_nic is still accessible and unchanged
* o at exit: Receive Frame in NIC memory is released
*
* Description:
* Starting at the byte indicated by the Offset value, the bytes are copied from the Data Info
* Part of the current Receive Frame Structure to the Host memory data buffer structure
* identified by descp.
* The maximum value for Offset is the number of characters of the 802.3 frame read into the
* look ahead buffer by hcf_service_nic (i.e. the look ahead buffer size minus
* Control and 802.11 fields)
* If Offset is less than the maximum value, copying starts from the look ahead buffer till the
* end of that buffer is reached
* Then (or if the maximum value is specified for Offset), the
* message is directly copied from NIC memory to Host memory.
* If an invalid (i.e. too large) offset is specified, an assert catches but the buffer contents are
* undefined.
* Copying stops if either:
* o the end of the 802.3 frame is reached
* o the Descriptor with a NULL pointer in the next_desc_addr field is reached
*
* When the copying stops, the receiver is ack'ed, thus freeing the NIC memory where the frame is stored
* As a consequence, hcf_rcv_msg can only be called once for any particular Rx frame.
*
* For the time being (PCI Bus mastering not yet supported), only the following fields of each
* of the descriptors in the descriptor list must be set by the MSF:
* o buf_cntl.buf_dim[1]
* o *next_desc_addr
* o *buf_addr
* At return from hcf_rcv_msg, the field buf_cntl.buf_dim[0] of the used Descriptors reflects
* the number of bytes in the buffer corresponding with the Descriptor.
* On the last used Descriptor, buf_cntl.buf_dim[0] is less or equal to buf_cntl.buf_dim[1].
* On all preceding Descriptors buf_cntl.buf_dim[0] is equal to buf_cntl.buf_dim[1].
* On all succeeding (unused) Descriptors, buf_cntl.buf_dim[0] is zero.
* Note: this I/F is based on the assumptions how the I/F needed for PCI Bus mastering will
* be, so it may change.
*
* The most likely handling of HCF_ERR_NO_NIC by the MSF is to drop the already copied
* data as elegantly as possible under the constraints and requirements posed by the (N)OS.
* If no received Frame Structure is pending, "Success" rather than "Read error" is returned.
* This error constitutes a logic flaw in the MSF
* The HCF can only catch a minority of this
* type of errors
* Based on consistency ideas, the HCF catches none of these errors.
*
* Assert fails if
* - ifbp has a recognizable out-of-range value
* - there is no unacknowledged Rx-message available
* - offset is out of range (outside look ahead buffer)
* - descp is a NULL pointer
* - any of the descriptors is not double word aligned
* - reentrancy, may be caused by calling hcf_functions without adequate protection
* against NIC interrupts or multi-threading.
* - Interrupts are enabled.
*
*.DIAGRAM
*
*.NOTICE
* - by using unsigned int as type for offset, no need to worry about negative offsets
* - Asserting on being enabled/present is superfluous, since a non-zero IFB_lal implies that hcf_service_nic
* was called and detected a Rx-message. A zero IFB_lal will set the BUF_CNT field of at least the first
* descriptor to zero.
*
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
int
hcf_rcv_msg( IFBP ifbp, DESC_STRCT *descp, unsigned int offset )
{
int rc = HCF_SUCCESS;
wci_bufp cp; //char oriented working pointer
hcf_16 i;
int tot_len = ifbp->IFB_RxLen - offset; //total length
wci_bufp lap = ifbp->IFB_lap + offset; //start address in LookAhead Buffer
hcf_16 lal = ifbp->IFB_lal - offset; //available data within LookAhead Buffer
hcf_16 j;
HCFLOGENTRY( HCF_TRACE_RCV_MSG, offset );
HCFASSERT( ifbp->IFB_Magic == HCF_MAGIC, ifbp->IFB_Magic );
HCFASSERT_INT;
HCFASSERT( descp, HCF_TRACE_RCV_MSG );
HCFASSERT( ifbp->IFB_RxLen, HCF_TRACE_RCV_MSG );
HCFASSERT( ifbp->IFB_RxLen >= offset, MERGE_2( offset, ifbp->IFB_RxLen ) );
HCFASSERT( ifbp->IFB_lal >= offset, offset );
HCFASSERT( (ifbp->IFB_CntlOpt & USE_DMA) == 0, 0xDADA );
if ( tot_len < 0 ) {
lal = 0; tot_len = 0; //suppress all copying activity in the do--while loop
}
do { //loop over all available fragments
// obnoxious hcf.c(1480) : warning C4769: conversion of near pointer to long integer
HCFASSERT( ((hcf_32)descp & 3 ) == 0, (hcf_32)descp );
cp = descp->buf_addr;
j = min( (hcf_16)tot_len, descp->BUF_SIZE ); //minimum of "what's` available" and fragment size
descp->BUF_CNT = j;
tot_len -= j; //adjust length still to go
if ( lal ) { //if lookahead Buffer not yet completely copied
i = min( lal, j ); //minimum of "what's available" in LookAhead and fragment size
lal -= i; //adjust length still available in LookAhead
j -= i; //adjust length still available in current fragment
/*;? while loop could be improved by moving words but that is complicated on platforms with
* alignment requirements*/
while ( i-- ) *cp++ = *lap++;
}
if ( j ) { //if LookAhead Buffer exhausted but still space in fragment, copy directly from NIC RAM
get_frag( ifbp, cp, j BE_PAR(0) );
CALC_RX_MIC( cp, j );
}
} while ( ( descp = descp->next_desc_addr ) != NULL );
#if (HCF_TYPE) & HCF_TYPE_WPA
if ( ifbp->IFB_RxFID ) {
rc = check_mic( ifbp ); //prevents MIC error report if hcf_service_nic already consumed all
}
#endif // HCF_TYPE_WPA
(void)hcf_action( ifbp, HCF_ACT_RX_ACK ); //only 1 shot to get the data, so free the resources in the NIC
HCFASSERT( rc == HCF_SUCCESS, rc );
HCFLOGEXIT( HCF_TRACE_RCV_MSG );
return rc;
} // hcf_rcv_msg
/************************************************************************************************************
*
*.MODULE int hcf_send_msg( IFBP ifbp, DESC_STRCT *descp, hcf_16 tx_cntl )
*.PURPOSE Encapsulate a message and append padding and MIC.
* non-USB: Transfers the resulting message from Host to NIC and initiates transmission.
* USB: Transfer resulting message into a flat buffer.
*
*.ARGUMENTS
* ifbp address of the Interface Block
* descp pointer to the DescriptorList or NULL
* tx_cntl indicates MAC-port and (Hermes) options
* HFS_TX_CNTL_SPECTRALINK
* HFS_TX_CNTL_PRIO
* HFS_TX_CNTL_TX_OK
* HFS_TX_CNTL_TX_EX
* HFS_TX_CNTL_TX_DELAY
* HFS_TX_CNTL_TX_CONT
* HCF_PORT_0 MAC Port 0 (default)
* HCF_PORT_1 (AP only) MAC Port 1
* HCF_PORT_2 (AP only) MAC Port 2
* HCF_PORT_3 (AP only) MAC Port 3
* HCF_PORT_4 (AP only) MAC Port 4
* HCF_PORT_5 (AP only) MAC Port 5
* HCF_PORT_6 (AP only) MAC Port 6
*
*.RETURNS
* HCF_SUCCESS
* HCF_ERR_DEFUNCT_..
* HCF_ERR_TIME_OUT
*
*.DESCRIPTION:
* The Send Message Function embodies 2 functions:
* o transfers a message (including MAC header) from the provided buffer structure in Host memory to the Transmit
* Frame Structure (TxFS) in NIC memory.
* o Issue a send command to the F/W to actually transmit the contents of the TxFS.
*
* Control is based on the Resource Indicator IFB_RscInd.
* The Resource Indicator is maintained by the HCF and should only be interpreted but not changed by the MSF.
* The MSF must check IFB_RscInd to be non-zero before executing the call to the Send Message Function.
* When no resources are available, the MSF must handle the queuing of the Transmit frame and check the
* Resource Indicator periodically after calling hcf_service_nic.
*
* The Send Message Functions transfers a message to NIC memory when it is called with a non-NULL descp.
* Before the Send Message Function is invoked this way, the Resource Indicator (IFB_RscInd) must be checked.
* If the Resource is not available, Send Message Function execution must be postponed until after processing of
* a next hcf_service_nic it appears that the Resource has become available.
* The message is copied from the buffer structure identified by descp to the NIC.
* Copying stops if a NULL pointer in the next_desc_addr field is reached.
* Hcf_send_msg does not check for transmit buffer overflow, because the F/W does this protection.
* In case of a transmit buffer overflow, the surplus which does not fit in the buffer is simply dropped.
*
* The Send Message Function activates the F/W to actually send the message to the medium when the
* HFS_TX_CNTL_TX_DELAY bit of the tx_cntl parameter is not set.
* If the descp parameter of the current call is non-NULL, the message as represented by descp is send.
* If the descp parameter of the current call is NULL, and if the preceding call of the Send Message Function had
* a non-NULL descp and the preceding call had the HFS_TX_CNTL_TX_DELAY bit of tx_cntl set, then the message as
* represented by the descp of the preceding call is send.
*
* Hcf_send_msg supports encapsulation (see HCF_ENCAP) of Ethernet-II frames.
* An Ethernet-II frame is transferred to the Transmit Frame structure as an 802.3 frame.
* Hcf_send_msg distinguishes between an 802.3 and an Ethernet-II frame by looking at the data length/type field
* of the frame. If this field contains a value larger than 1514, the frame is considered to be an Ethernet-II
* frame, otherwise it is treated as an 802.3 frame.
* To ease implementation of the HCF, this type/type field must be located in the first descriptor structure,
* i.e. the 1st fragment must have a size of at least 14 (to contain DestAddr, SrcAddr and Len/Type field).
* An Ethernet-II frame is encapsulated by inserting a SNAP header between the addressing information and the
* type field. This insertion is transparent for the MSF.
* The HCF contains a fixed table that stores a number of types. If the value specified by the type/type field
* occurs in this table, Bridge Tunnel Encapsulation is used, otherwise RFC1042 encapsulation is used.
* Bridge Tunnel uses AA AA 03 00 00 F8 as SNAP header,
* RFC1042 uses AA AA 03 00 00 00 as SNAP header.
* The table currently contains:
* 0 0x80F3 AppleTalk Address Resolution Protocol (AARP)
* 0 0x8137 IPX
*
* The algorithm to distinguish between 802.3 and Ethernet-II frames limits the maximum length for frames of
* 802.3 frames to 1514 bytes.
* Encapsulation can be suppressed by means of the system constant HCF_ENCAP, e.g. to support proprietary
* protocols with 802.3 like frames with a size larger than 1514 bytes.
*
* In case the HCF encapsulates the frame, the number of bytes that is actually transmitted is determined by the
* cumulative value of the buf_cntl.buf_dim[0] fields.
* In case the HCF does not encapsulate the frame, the number of bytes that is actually transmitted is not
* determined by the cumulative value of the buf_cntl.buf_dim[DESC_CNTL_CNT] fields of the desc_strct's but by
* the Length field of the 802.3 frame.
* If there is a conflict between the cumulative value of the buf_cntl.buf_dim[0] fields and the
* 802.3 Length field the 802.3 Length field determines the number of bytes actually transmitted by the NIC while
* the cumulative value of the buf_cntl.buf_dim[0] fields determines the position of the MIC, hence a mismatch
* will result in MIC errors on the Receiving side.
* Currently this problem is flagged on the Transmit side by an Assert.
* The following fields of each of the descriptors in the descriptor list must be set by the MSF:
* o buf_cntl.buf_dim[0]
* o *next_desc_addr
* o *buf_addr
*
* All bits of the tx_cntl parameter except HFS_TX_CNTL_TX_DELAY and the HCF_PORT# bits are passed to the F/W via
* the HFS_TX_CNTL field of the TxFS.
*
* Note that hcf_send_msg does not detect NIC absence. The MSF is supposed to have its own -platform dependent-
* way to recognize card removal/insertion.
* The total system must be robust against card removal and there is no principal difference between card removal
* just after hcf_send_msg returns but before the actual transmission took place or sometime earlier.
*
* Assert fails if
* - ifbp has a recognizable out-of-range value
* - descp is a NULL pointer
* - no resources for PIF available.
* - Interrupts are enabled.
* - reentrancy, may be caused by calling hcf_functions without adequate protection
* against NIC interrupts or multi-threading.
*
*.DIAGRAM
*4: for the normal case (i.e. no HFS_TX_CNTL_TX_DELAY option active), a fid is acquired via the
* routine get_fid. If no FID is acquired, the remainder is skipped without an error notification. After
* all, the MSF is not supposed to call hcf_send_msg when no Resource is available.
*7: The ControlField of the TxFS is written. Since put_frag can only return the fatal Defunct or "No NIC", the
* return status can be ignored because when it fails, cmd_wait will fail as well. (see also the note on the
* need for a return code below).
* Note that HFS_TX_CNTL has different values for H-I, H-I/WPA and H-II and HFS_ADDR_DEST has different
* values for H-I (regardless of WPA) and H-II.
* By writing 17, 1 or 2 ( implying 16, 0 or 1 garbage word after HFS_TX_CNTL) the BAP just gets to
* HFS_ADDR_DEST for H-I, H-I/WPA and H-II respectively.
*10: if neither encapsulation nor MIC calculation is needed, splitting the first fragment in two does not
* really help but it makes the flow easier to follow to do not optimize on this difference
*
* hcf_send_msg checks whether the frame is an Ethernet-II rather than an "official" 802.3 frame.
* The E-II check is based on the length/type field in the MAC header. If this field has a value larger than
* 1500, E-II is assumed. The implementation of this test fails if the length/type field is not in the first
* descriptor. If E-II is recognized, a SNAP header is inserted. This SNAP header represents either RFC1042
* or Bridge-Tunnel encapsulation, depending on the return status of the support routine hcf_encap.
*
*.NOTICE
* hcf_send_msg leaves the responsibility to only send messages on enabled ports at the MSF level.
* This is considered the strategy which is sufficiently adequate for all "robust" MSFs, have the least
* processor utilization and being still acceptable robust at the WCI !!!!!
*
* hcf_send_msg does not NEED a return value to report NIC absence or removal during the execution of
* hcf_send_msg(), because the MSF and higher layers must be able to cope anyway with the NIC being removed
* after a successful completion of hcf_send_msg() but before the actual transmission took place.
* To accommodate user expectations the current implementation does report NIC absence.
* Defunct blocks all NIC access and will (also) be reported on a number of other calls.
*
* hcf_send_msg does not check for transmit buffer overflow because the Hermes does this protection.
* In case of a transmit buffer overflow, the surplus which does not fit in the buffer is simply dropped.
* Note that this possibly results in the transmission of incomplete frames.
*
* After some deliberation with F/W team, it is decided that - being in the twilight zone of not knowing
* whether the problem at hand is an MSF bug, HCF buf, F/W bug, H/W malfunction or even something else - there
* is no "best thing to do" in case of a failing send, hence the HCF considers the TxFID ownership to be taken
* over by the F/W and hopes for an Allocate event in due time
*
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
int
hcf_send_msg( IFBP ifbp, DESC_STRCT *descp, hcf_16 tx_cntl )
{
int rc = HCF_SUCCESS;
DESC_STRCT *p /* = descp*/; //working pointer
hcf_16 len; // total byte count
hcf_16 i;
hcf_16 fid = 0;
HCFASSERT( ifbp->IFB_RscInd || descp == NULL, ifbp->IFB_RscInd );
HCFASSERT( (ifbp->IFB_CntlOpt & USE_DMA) == 0, 0xDADB );
HCFLOGENTRY( HCF_TRACE_SEND_MSG, tx_cntl );
HCFASSERT( ifbp->IFB_Magic == HCF_MAGIC, ifbp->IFB_Magic );
HCFASSERT_INT;
/* obnoxious c:/hcf/hcf.c(1480) : warning C4769: conversion of near pointer to long integer,
* so skip */
HCFASSERT( ((hcf_32)descp & 3 ) == 0, (hcf_32)descp );
#if HCF_ASSERT
{ int x = ifbp->IFB_FWIdentity.comp_id == COMP_ID_FW_AP ? tx_cntl & ~HFS_TX_CNTL_PORT : tx_cntl;
HCFASSERT( (x & ~HCF_TX_CNTL_MASK ) == 0, tx_cntl );
}
#endif // HCF_ASSERT
if ( descp ) ifbp->IFB_TxFID = 0; //cancel a pre-put message
/* the following initialization code is redundant for a pre-put message
* but moving it inside the "if fid" logic makes the merging with the
* USB flow awkward
*/
#if (HCF_TYPE) & HCF_TYPE_WPA
tx_cntl |= ifbp->IFB_MICTxCntl;
#endif // HCF_TYPE_WPA
fid = ifbp->IFB_TxFID;
if (fid == 0 && ( fid = get_fid( ifbp ) ) != 0 ) /* 4 */
/* skip the next compound statement if:
- pre-put message or
- no fid available (which should never occur if the MSF adheres to the WCI)
*/
{ // to match the closing curly bracket of above "if" in case of HCF_TYPE_USB
//calculate total length ;? superfluous unless CCX or Encapsulation
len = 0;
p = descp;
do len += p->BUF_CNT; while ( ( p = p->next_desc_addr ) != NULL );
p = descp;
//;? HCFASSERT( len <= HCF_MAX_MSG, len );
/*7*/ (void)setup_bap( ifbp, fid, HFS_TX_CNTL, IO_OUT );
#if (HCF_TYPE) & HCF_TYPE_TX_DELAY
HCFASSERT( ( descp != NULL ) ^ ( tx_cntl & HFS_TX_CNTL_TX_DELAY ), tx_cntl );
if ( tx_cntl & HFS_TX_CNTL_TX_DELAY ) {
tx_cntl &= ~HFS_TX_CNTL_TX_DELAY; //!!HFS_TX_CNTL_TX_DELAY no longer available
ifbp->IFB_TxFID = fid;
fid = 0; //!!fid no longer available, be careful when modifying code
}
#endif // HCF_TYPE_TX_DELAY
OPW( HREG_DATA_1, tx_cntl ) ;
OPW( HREG_DATA_1, 0 );
HCFASSERT( p->BUF_CNT >= 14, p->BUF_CNT );
/* assume DestAddr/SrcAddr/Len/Type ALWAYS contained in 1st fragment
* otherwise life gets too cumbersome for MIC and Encapsulation !!!!!!!!
if ( p->BUF_CNT >= 14 ) { alternatively: add a safety escape !!!!!!!!!!!! } */
CALC_TX_MIC( NULL, -1 ); //initialize MIC
/*10*/ put_frag( ifbp, p->buf_addr, HCF_DASA_SIZE BE_PAR(0) ); //write DA, SA with MIC calculation
CALC_TX_MIC( p->buf_addr, HCF_DASA_SIZE ); //MIC over DA, SA
CALC_TX_MIC( null_addr, 4 ); //MIC over (virtual) priority field
//if encapsulation needed
#if (HCF_ENCAP) == HCF_ENC
//write length (with SNAP-header,Type, without //DA,SA,Length ) no MIC calc.
if ( ( snap_header[sizeof(snap_header)-1] = hcf_encap( &p->buf_addr[HCF_DASA_SIZE] ) ) != ENC_NONE ) {
OPW( HREG_DATA_1, CNV_END_SHORT( len + (sizeof(snap_header) + 2) - ( 2*6 + 2 ) ) );
//write splice with MIC calculation
put_frag( ifbp, snap_header, sizeof(snap_header) BE_PAR(0) );
CALC_TX_MIC( snap_header, sizeof(snap_header) ); //MIC over 6 byte SNAP
i = HCF_DASA_SIZE;
} else
#endif // HCF_ENC
{
OPW( HREG_DATA_1, *(wci_recordp)&p->buf_addr[HCF_DASA_SIZE] );
i = 14;
}
//complete 1st fragment starting with Type with MIC calculation
put_frag( ifbp, &p->buf_addr[i], p->BUF_CNT - i BE_PAR(0) );
CALC_TX_MIC( &p->buf_addr[i], p->BUF_CNT - i );
//do the remaining fragments with MIC calculation
while ( ( p = p->next_desc_addr ) != NULL ) {
/* obnoxious c:/hcf/hcf.c(1480) : warning C4769: conversion of near pointer to long integer,
* so skip */
HCFASSERT( ((hcf_32)p & 3 ) == 0, (hcf_32)p );
put_frag( ifbp, p->buf_addr, p->BUF_CNT BE_PAR(0) );
CALC_TX_MIC( p->buf_addr, p->BUF_CNT );
}
//pad message, finalize MIC calculation and write MIC to NIC
put_frag_finalize( ifbp );
}
if ( fid ) {
/*16*/ rc = cmd_exe( ifbp, HCMD_BUSY | HCMD_TX | HCMD_RECL, fid );
ifbp->IFB_TxFID = 0;
/* probably this (i.e. no RscInd AND "HREG_EV_ALLOC") at this point in time occurs so infrequent,
* that it might just as well be acceptable to skip this
* "optimization" code and handle that additional interrupt once in a while
*/
// 180 degree error in logic ;? #if ALLOC_15
/*20*/ if ( ifbp->IFB_RscInd == 0 ) {
ifbp->IFB_RscInd = get_fid( ifbp );
}
// #endif // ALLOC_15
}
// HCFASSERT( level::ifbp->IFB_RscInd, ifbp->IFB_RscInd );
HCFLOGEXIT( HCF_TRACE_SEND_MSG );
return rc;
} // hcf_send_msg
/************************************************************************************************************
*
*.MODULE int hcf_service_nic( IFBP ifbp, wci_bufp bufp, unsigned int len )
*.PURPOSE Services (most) NIC events.
* Provides received message
* Provides status information.
*
*.ARGUMENTS
* ifbp address of the Interface Block
* In non-DMA mode:
* bufp address of char buffer, sufficiently large to hold the first part of the RxFS up through HFS_TYPE
* len length in bytes of buffer specified by bufp
* value between HFS_TYPE + 2 and HFS_ADDR_DEST + HCF_MAX_MSG
*
*.RETURNS
* HCF_SUCCESS
* HCF_ERR_MIC message contains an erroneous MIC (only if frame fits completely in bufp)
*
*.DESCRIPTION
*
* MSF-accessible fields of Result Block
* - IFB_RxLen 0 or Frame size.
* - IFB_MBInfoLen 0 or the L-field of the oldest MBIB.
* - IFB_RscInd
* - IFB_HCF_Tallies updated if a corresponding event occurred.
* - IFB_NIC_Tallies updated if a Tally Info frame received from the NIC.
* - IFB_DmaPackets
* - IFB_TxFsStat
* - IFB_TxFsSwSup
* - IFB_LinkStat reflects new link status or 0x0000 if no change relative to previous hcf_service_nic call.
or
* - IFB_LinkStat link status, 0x8000 reflects change relative to previous hcf_service_nic call.
*
* When IFB_MBInfoLen is non-zero, at least one MBIB is available.
*
* IFB_RxLen reflects the number of received bytes in 802.3 view (Including DestAddr, SrcAddr and Length,
* excluding MIC-padding, MIC and sum check) of active Rx Frame Structure. If no Rx Data s available, IFB_RxLen
* equals 0x0000.
* Repeated execution causes the Service NIC Function to provide information about subsequently received
* messages, irrespective whether a hcf_rcv_msg or hcf_action(HCF_ACT_RX) is performed in between.
*
* When IFB_RxLen is non-zero, a Received Frame Structure is available to be routed to the protocol stack.
* When Monitor Mode is not active, this is guaranteed to be an error-free non-WMP frame.
* In case of Monitor Mode, it may also be a frame with an error or a WMP frame.
* Erroneous frames have a non-zero error-sub field in the HFS_STAT field in the look ahead buffer.
*
* If a Receive message is available in NIC RAM, the Receive Frame Structure is (partly) copied from the NIC to
* the buffer identified by bufp.
* Copying stops either after len bytes or when the complete 802.3 frame is copied.
* During the copying the message is decapsulated (if appropriate).
* If the frame is read completely by hcf_service_nic (i.e. the frame fits completely in the lookahead buffer),
* the frame is automatically ACK'ed to the F/W and still available via the look ahead buffer and hcf_rcv_msg.
* Only if the frame is read completely by hcf_service_nic, hcf_service_nic checks the MIC and sets the return
* status accordingly. In this case, hcf_rcv_msg does not check the MIC.
*
* The MIC calculation algorithm works more efficient if the length of the look ahead buffer is
* such that it fits exactly 4 n bytes of the 802.3 frame, i.e. len == HFS_ADDR_DEST + 4*n.
*
* The Service NIC Function supports the NIC event service handling process.
* It performs the appropriate actions to service the NIC, such that the event cause is eliminated and related
* information is saved.
* The Service NIC Function is executed by the MSF ISR or polling routine as first step to determine the event
* cause(s). It is the responsibility of the MSF to perform all not directly NIC related interrupt service
* actions, e.g. in a PC environment this includes servicing the PIC, and managing the Processor Interrupt
* Enabling/Disabling.
* In case of a polled based system, the Service NIC Function must be executed "frequently".
* The Service NIC Function may have side effects related to the Mailbox and Resource Indicator (IFB_RscInd).
*
* hcf_service_nic returns:
* - The length of the data in the available MBIB (IFB_MBInfoLen)
* - Changes in the link status (IFB_LinkStat)
* - The length of the data in the available Receive Frame Structure (IFB_RxLen)
* - updated IFB_RscInd
* - Updated Tallies
*
* hcf_service_nic is presumed to neither interrupt other HCF-tasks nor to be interrupted by other HCF-tasks.
* A way to achieve this is to precede hcf_service_nic as well as all other HCF-tasks with a call to
* hcf_action to disable the card interrupts and, after all work is completed, with a call to hcf_action to
* restore (which is not necessarily the same as enabling) the card interrupts.
* In case of a polled environment, it is assumed that the MSF programmer is sufficiently familiar with the
* specific requirements of that environment to translate the interrupt strategy to a polled strategy.
*
* hcf_service_nic services the following Hermes events:
* - HREG_EV_INFO Asynchronous Information Frame
* - HREG_EV_INFO_DROP WMAC did not have sufficient RAM to build Unsolicited Information Frame
* - HREG_EV_TX_EXC (if applicable, i.e. selected via HCF_EXT_INT_TX_EX bit of HCF_EXT)
* - HREG_EV_SLEEP_REQ (if applicable, i.e. selected via HCF_DDS/HCF_CDS bit of HCF_SLEEP)
* ** in non_DMA mode
* - HREG_EV_ALLOC Asynchronous part of Allocation/Reclaim completed while out of resources at
* completion of hcf_send_msg/notify
* - HREG_EV_RX the detection of the availability of received messages
* including WaveLAN Management Protocol (WMP) message processing
* ** in DMA mode
* - HREG_EV_RDMAD
* - HREG_EV_TDMAD
*!! hcf_service_nic does not service the following Hermes events:
*!! HREG_EV_TX (the "OK" Tx Event) is no longer supported by the WCI, if it occurs it is unclear
*!! what the cause is, so no meaningful strategy is available. Not acking the bit is
*!! probably the best help that can be given to the debugger.
*!! HREG_EV_CMD handled in cmd_wait.
*!! HREG_EV_FW_DMA (i.e. HREG_EV_RXDMA, HREG_EV_TXDMA and_EV_LPESC) are either not used or used
*!! between the F/W and the DMA engine.
*!! HREG_EV_ACK_REG_READY is only applicable for H-II (i.e. not HII.5 and up, see DAWA)
*
* If, in non-DMA mode, a Rx message is available, its length is reflected by the IFB_RxLen field of the IFB.
* This length reflects the data itself and the Destination Address, Source Address and DataLength/Type field
* but not the SNAP-header in case of decapsulation by the HCF. If no message is available, IFB_RxLen is
* zero. Former versions of the HCF handled WMP messages and supported a "monitor" mode in hcf_service_nic,
* which deposited certain or all Rx messages in the MailBox. The responsibility to handle these frames is
* moved to the MSF. The HCF offers as supports hcf_put_info with CFG_MB_INFO as parameter to emulate the old
* implementation under control of the MSF.
*
* **Rx Buffer free strategy
* When hcf_service_nic reports the availability of a non-DMA message, the MSF can access that message by
* means of hcf_rcv_msg. It must be prevented that the LAN Controller writes new data in the NIC buffer
* before the MSF is finished with the current message. The NIC buffer is returned to the LAN Controller
* when:
* - the complete frame fits in the lookahead buffer or
* - hcf_rcv_msg is called or
* - hcf_action with HCF_ACT_RX is called or
* - hcf_service_nic is called again
* It can be reasoned that hcf_action( INT_ON ) should not be given before the MSF has completely processed
* a reported Rx-frame. The reason is that the INT_ON action is guaranteed to cause a (Rx-)interrupt (the
* MSF is processing a Rx-frame, hence the Rx-event bit in the Hermes register must be active). This
* interrupt will cause hcf_service_nic to be called, which will cause the ack-ing of the "last" Rx-event
* to the Hermes, causing the Hermes to discard the associated NIC RAM buffer.
* Assert fails if
* - ifbp is zero or other recognizable out-of-range value.
* - hcf_service_nic is called without a prior call to hcf_connect.
* - interrupts are enabled.
* - reentrancy, may be caused by calling hcf_functions without adequate protection
* against NIC interrupts or multi-threading.
*
*
*.DIAGRAM
*1: IFB_LinkStat is cleared, if a LinkStatus frame is received, IFB_LinkStat will be updated accordingly
* by isr_info.
or
*1: IFB_LinkStat change indication is cleared. If a LinkStatus frame is received, IFB_LinkStat will be updated
* accordingly by isr_info.
*2: IFB_RxLen must be cleared before the NIC presence check otherwise:
* - this value may stay non-zero if the NIC is pulled out at an inconvenient moment.
* - the RxAck on a zero-FID needs a zero-value for IFB_RxLen to work
* Note that as side-effect of the hcf_action call, the remainder of Rx related info is re-initialized as
* well.
*4: In case of Defunct mode, the information supplied by Hermes is unreliable, so the body of
* hcf_service_nic is skipped. Since hcf_cntl turns into a NOP if Primary or Station F/W is incompatible,
* hcf_service_nic is also skipped in those cases.
* To prevent that hcf_service_nic reports bogus information to the MSF with all - possibly difficult to
* debug - undesirable side effects, it is paramount to check the NIC presence. In former days the presence
* test was based on the Hermes register HREG_SW_0. Since in HCF_ACT_INT_OFF is chosen for strategy based on
* HREG_EV_STAT, this is now also used in hcf_service_nic. The motivation to change strategy is partly
* due to inconsistent F/W implementations with respect to HREG_SW_0 manipulation around reset and download.
* Note that in polled environments Card Removal is not detected by INT_OFF which makes the check in
* hcf_service_nic even more important.
*8: The event status register of the Hermes is sampled
* The assert checks for unexpected events ;?????????????????????????????????????.
* - HREG_EV_INFO_DROP is explicitly excluded from the acceptable HREG_EV_STAT bits because it indicates
* a too heavily loaded system.
* - HREG_EV_ACK_REG_READY is 0x0000 for H-I (and hopefully H-II.5)
*
*
* HREG_EV_TX_EXC is accepted (via HREG_EV_TX_EXT) if and only if HCF_EXT_INT_TX_EX set in the HCF_EXT
* definition at compile time.
* The following activities are handled:
* - Alloc events are handled by hcf_send_msg (and notify). Only if there is no "spare" resource, the
* alloc event is superficially serviced by hcf_service_nic to create a pseudo-resource with value
* 0x001. This value is recognized by get_fid (called by hcf_send_msg and notify) where the real
* TxFid is retrieved and the Hermes is acked and - hopefully - the "normal" case with a spare TxFid
* in IFB_RscInd is restored.
* - Info drop events are handled by incrementing a tally
* - LinkEvent (including solicited and unsolicited tallies) are handled by procedure isr_info.
* - TxEx (if selected at compile time) is handled by copying the significant part of the TxFS
* into the IFB for further processing by the MSF.
* Note the complication of the zero-FID protection sub-scheme in DAWA.
* Note, the Ack of all of above events is handled at the end of hcf_service_nic
*16: In case of non-DMA ( either not compiled in or due to a run-time choice):
* If an Rx-frame is available, first the FID of that frame is read, including the complication of the
* zero-FID protection sub-scheme in DAWA. Note that such a zero-FID is acknowledged at the end of
* hcf_service_nic and that this depends on the IFB_RxLen initialization in the begin of hcf_service_nic.
* The Assert validates the HCF assumption about Hermes implementation upon which the range of
* Pseudo-RIDs is based.
* Then the control fields up to the start of the 802.3 frame are read from the NIC into the lookahead buffer.
* The status field is converted to native Endianness.
* The length is, after implicit Endianness conversion if needed, and adjustment for the 14 bytes of the
* 802.3 MAC header, stored in IFB_RxLen.
* In MAC Monitor mode, 802.11 control frames with a TOTAL length of 14 are received, so without this
* length adjustment, IFB_RxLen could not be used to distinguish these frames from "no frame".
* No MIC calculation processes are associated with the reading of these Control fields.
*26: This length test feels like superfluous robustness against malformed frames, but it turned out to be
* needed in the real (hostile) world.
* The decapsulation check needs sufficient data to represent DA, SA, L, SNAP and Type which amounts to
* 22 bytes. In MAC Monitor mode, 802.11 control frames with a smaller length are received. To prevent
* that the implementation goes haywire, a check on the length is needed.
* The actual decapsulation takes place on the fly in the copying process by overwriting the SNAP header.
* Note that in case of decapsulation the SNAP header is not passed to the MSF, hence IFB_RxLen must be
* compensated for the SNAP header length.
* The 22 bytes needed for decapsulation are (more than) sufficient for the exceptional handling of the
* MIC algorithm of the L-field (replacing the 2 byte L-field with 4 0x00 bytes).
*30: The 12 in the no-WPA branch corresponds with the get_frag, the 2 with the IPW of the WPA branch
*32: If Hermes reported MIC-presence, than the MIC engine is initialized with the non-dummy MIC calculation
* routine address and appropriate key.
*34: The 8 bytes after the DA, SA, L are read and it is checked whether decapsulation is needed i.e.:
* - the Hermes reported Tunnel encapsulation or
* - the Hermes reported 1042 Encapsulation and hcf_encap reports that the HCF would not have used
* 1042 as the encapsulation mechanism
* Note that the first field of the RxFS in bufp has Native Endianness due to the conversion done by the
* BE_PAR in get_frag.
*36: The Type field is the only word kept (after moving) of the just read 8 bytes, it is moved to the
* L-field. The original L-field and 6 byte SNAP header are discarded, so IFB_RxLen and buf_addr must
* be adjusted by 8.
*40: Determine how much of the frame (starting with DA) fits in the Lookahead buffer, then read the not-yet
* read data into the lookahead buffer.
* If the lookahead buffer contains the complete message, check the MIC. The majority considered this
* I/F more appropriate then have the MSF call hcf_get_data only to check the MIC.
*44: Since the complete message is copied from NIC RAM to PC RAM, the Rx can be acknowledged to the Hermes
* to optimize the flow ( a better chance to get new Rx data in the next pass through hcf_service_nic ).
* This acknowledgement can not be done via hcf_action( HCF_ACT_RX_ACK ) because this also clears
* IFB_RxLEN thus corrupting the I/F to the MSF.
*;?: In case of DMA (compiled in and activated):
*54: Limiting the number of places where the F/W is acked (e.g. the merging of the Rx-ACK with the other
* ACKs), is supposed to diminish the potential of race conditions in the F/W.
* Note 1: The CMD event is acknowledged in cmd_cmpl
* Note 2: HREG_EV_ACK_REG_READY is 0x0000 for H-I (and hopefully H-II.5)
* Note 3: The ALLOC event is acknowledged in get_fid (except for the initialization flow)
*
*.NOTICE
* The Non-DMA HREG_EV_RX is handled different compared with the other F/W events.
* The HREG_EV_RX event is acknowledged by the first hcf_service_nic call after the
* hcf_service_nic call that reported the occurrence of this event.
* This acknowledgment
* makes the next Receive Frame Structure (if any) available.
* An updated IFB_RxLen
* field reflects this availability.
*
*.NOTICE
* The minimum size for Len must supply space for:
* - an F/W dependent number of bytes of Control Info field including the 802.11 Header field
* - Destination Address
* - Source Address
* - Length field
* - [ SNAP Header]
* - [ Ethernet-II Type]
* This results in 68 for Hermes-I and 80 for Hermes-II
* This way the minimum amount of information is available needed by the HCF to determine whether the frame
* must be decapsulated.
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
int
hcf_service_nic( IFBP ifbp, wci_bufp bufp, unsigned int len )
{
int rc = HCF_SUCCESS;
hcf_16 stat;
wci_bufp buf_addr;
hcf_16 i;
HCFLOGENTRY( HCF_TRACE_SERVICE_NIC, ifbp->IFB_IntOffCnt );
HCFASSERT( ifbp->IFB_Magic == HCF_MAGIC, ifbp->IFB_Magic );
HCFASSERT_INT;
ifbp->IFB_LinkStat = 0; // ;? to be obsoleted ASAP /* 1*/
ifbp->IFB_DSLinkStat &= ~CFG_LINK_STAT_CHANGE; /* 1*/
(void)hcf_action( ifbp, HCF_ACT_RX_ACK ); /* 2*/
if ( ifbp->IFB_CardStat == 0 && ( stat = IPW( HREG_EV_STAT ) ) != 0xFFFF ) { /* 4*/
/* IF_NOT_DMA( HCFASSERT( !( stat & ~HREG_EV_BASIC_MASK, stat ) )
* IF_NOT_USE_DMA( HCFASSERT( !( stat & ~HREG_EV_BASIC_MASK, stat ) )
* IF_USE_DMA( HCFASSERT( !( stat & ~( HREG_EV_BASIC_MASK ^ ( HREG_EV_...DMA.... ), stat ) )
*/
/* 8*/
if ( ifbp->IFB_RscInd == 0 && stat & HREG_EV_ALLOC ) { //Note: IFB_RscInd is ALWAYS 1 for DMA
ifbp->IFB_RscInd = 1;
}
IF_TALLY( if ( stat & HREG_EV_INFO_DROP ) { ifbp->IFB_HCF_Tallies.NoBufInfo++; } );
#if (HCF_EXT) & HCF_EXT_INT_TICK
if ( stat & HREG_EV_TICK ) {
ifbp->IFB_TickCnt++;
}
#if 0 // (HCF_SLEEP) & HCF_DDS
if ( ifbp->IFB_TickCnt == 3 && ( ifbp->IFB_DSLinkStat & CFG_LINK_STAT_CONNECTED ) == 0 ) {
CFG_DDS_TICK_TIME_STRCT ltv;
// 2 second period (with 1 tick uncertanty) in not-connected mode -->go into DS_OOR
hcf_action( ifbp, HCF_ACT_SLEEP );
ifbp->IFB_DSLinkStat |= CFG_LINK_STAT_DS_OOR; //set OutOfRange
ltv.len = 2;
ltv.typ = CFG_DDS_TICK_TIME;
ltv.tick_time = ( ( ifbp->IFB_DSLinkStat & CFG_LINK_STAT_TIMER ) + 0x10 ) *64; //78 is more right
hcf_put_info( ifbp, (LTVP)<v );
printk(KERN_NOTICE "Preparing for sleep, link_status: %04X, timer : %d\n",
ifbp->IFB_DSLinkStat, ltv.tick_time );//;?remove me 1 day
ifbp->IFB_TickCnt++; //;?just to make sure we do not keep on printing above message
if ( ltv.tick_time < 300 * 125 ) ifbp->IFB_DSLinkStat += 0x0010;
}
#endif // HCF_DDS
#endif // HCF_EXT_INT_TICK
if ( stat & HREG_EV_INFO ) {
isr_info( ifbp );
}
#if (HCF_EXT) & HCF_EXT_INT_TX_EX
if ( stat & HREG_EV_TX_EXT && ( i = IPW( HREG_TX_COMPL_FID ) ) != 0 /*DAWA*/ ) {
DAWA_ZERO_FID( HREG_TX_COMPL_FID );
(void)setup_bap( ifbp, i, 0, IO_IN );
get_frag( ifbp, &ifbp->IFB_TxFsStat, HFS_SWSUP BE_PAR(1) );
}
#endif // HCF_EXT_INT_TX_EX
//!rlav DMA engine will handle the rx event, not the driver
#if HCF_DMA
if ( !( ifbp->IFB_CntlOpt & USE_DMA ) ) //!! be aware of the logical indentations
#endif // HCF_DMA
/*16*/ if ( stat & HREG_EV_RX && ( ifbp->IFB_RxFID = IPW( HREG_RX_FID ) ) != 0 ) { //if 0 then DAWA_ACK
HCFASSERT( bufp, len );
HCFASSERT( len >= HFS_DAT + 2, len );
DAWA_ZERO_FID( HREG_RX_FID );
HCFASSERT( ifbp->IFB_RxFID < CFG_PROD_DATA, ifbp->IFB_RxFID);
(void)setup_bap( ifbp, ifbp->IFB_RxFID, 0, IO_IN );
get_frag( ifbp, bufp, HFS_ADDR_DEST BE_PAR(1) );
ifbp->IFB_lap = buf_addr = bufp + HFS_ADDR_DEST;
ifbp->IFB_RxLen = (hcf_16)(bufp[HFS_DAT_LEN] + (bufp[HFS_DAT_LEN+1]<<8) + 2*6 + 2);
/*26*/ if ( ifbp->IFB_RxLen >= 22 ) { // convenient for MIC calculation (5 DWs + 1 "skipped" W)
//. get DA,SA,Len/Type and (SNAP,Type or 8 data bytes)
/*30*/ get_frag( ifbp, buf_addr, 22 BE_PAR(0) );
/*32*/ CALC_RX_MIC( bufp, -1 ); //. initialize MIC
CALC_RX_MIC( buf_addr, HCF_DASA_SIZE ); //. MIC over DA, SA
CALC_RX_MIC( null_addr, 4 ); //. MIC over (virtual) priority field
CALC_RX_MIC( buf_addr+14, 8 ); //. skip Len, MIC over SNAP,Type or 8 data bytes)
buf_addr += 22;
#if (HCF_ENCAP) == HCF_ENC
HCFASSERT( len >= HFS_DAT + 2 + sizeof(snap_header), len );
/*34*/ i = *(wci_recordp)&bufp[HFS_STAT] & ( HFS_STAT_MSG_TYPE | HFS_STAT_ERR );
if ( i == HFS_STAT_TUNNEL ||
( i == HFS_STAT_1042 && hcf_encap( (wci_bufp)&bufp[HFS_TYPE] ) != ENC_TUNNEL ) ) {
//. copy E-II Type to 802.3 LEN field
/*36*/ bufp[HFS_LEN ] = bufp[HFS_TYPE ];
bufp[HFS_LEN+1] = bufp[HFS_TYPE+1];
//. discard Snap by overwriting with data
ifbp->IFB_RxLen -= (HFS_TYPE - HFS_LEN);
buf_addr -= ( HFS_TYPE - HFS_LEN ); // this happens to bring us at a DW boundary of 36
}
#endif // HCF_ENC
}
/*40*/ ifbp->IFB_lal = min( (hcf_16)(len - HFS_ADDR_DEST), ifbp->IFB_RxLen );
i = ifbp->IFB_lal - ( buf_addr - ( bufp + HFS_ADDR_DEST ) );
get_frag( ifbp, buf_addr, i BE_PAR(0) );
CALC_RX_MIC( buf_addr, i );
#if (HCF_TYPE) & HCF_TYPE_WPA
if ( ifbp->IFB_lal == ifbp->IFB_RxLen ) {
rc = check_mic( ifbp );
}
#endif // HCF_TYPE_WPA
/*44*/ if ( len - HFS_ADDR_DEST >= ifbp->IFB_RxLen ) {
ifbp->IFB_RxFID = 0;
} else { /* IFB_RxFID is cleared, so you do not get another Rx_Ack at next entry of hcf_service_nic */
stat &= (hcf_16)~HREG_EV_RX; //don't ack Rx if processing not yet completed
}
}
// in case of DMA: signal availability of rx and/or tx packets to MSF
IF_USE_DMA( ifbp->IFB_DmaPackets |= stat & ( HREG_EV_RDMAD | HREG_EV_TDMAD ) );
// rlav : pending HREG_EV_RDMAD or HREG_EV_TDMAD events get acknowledged here.
/*54*/ stat &= (hcf_16)~( HREG_EV_SLEEP_REQ | HREG_EV_CMD | HREG_EV_ACK_REG_READY | HREG_EV_ALLOC | HREG_EV_FW_DMA );
//a positive mask would be easier to understand /*54*/ stat &= (hcf_16)~( HREG_EV_SLEEP_REQ | HREG_EV_CMD | HREG_EV_ACK_REG_READY | HREG_EV_ALLOC | HREG_EV_FW_DMA );
IF_USE_DMA( stat &= (hcf_16)~HREG_EV_RX );
if ( stat ) {
DAWA_ACK( stat ); /*DAWA*/
}
}
HCFLOGEXIT( HCF_TRACE_SERVICE_NIC );
return rc;
} // hcf_service_nic
/************************************************************************************************************
************************** H C F S U P P O R T R O U T I N E S ******************************************
************************************************************************************************************/
/************************************************************************************************************
*
*.SUBMODULE void calc_mic( hcf_32* p, hcf_32 m )
*.PURPOSE calculate MIC on a quad byte.
*
*.ARGUMENTS
* p address of the MIC
* m 32 bit value to be processed by the MIC calculation engine
*
*.RETURNS N.A.
*
*.DESCRIPTION
* calc_mic is the implementation of the MIC algorithm. It is a monkey-see monkey-do copy of
* Michael::appendByte()
* of Appendix C of ..........
*
*
*.DIAGRAM
*
*.NOTICE
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
#if (HCF_TYPE) & HCF_TYPE_WPA
#define ROL32( A, n ) ( ((A) << (n)) | ( ((A)>>(32-(n))) & ( (1UL << (n)) - 1 ) ) )
#define ROR32( A, n ) ROL32( (A), 32-(n) )
#define L *p
#define R *(p+1)
void
calc_mic( hcf_32* p, hcf_32 m )
{
#if HCF_BIG_ENDIAN
m = (m >> 16) | (m << 16);
#endif // HCF_BIG_ENDIAN
L ^= m;
R ^= ROL32( L, 17 );
L += R;
R ^= ((L & 0xff00ff00) >> 8) | ((L & 0x00ff00ff) << 8);
L += R;
R ^= ROL32( L, 3 );
L += R;
R ^= ROR32( L, 2 );
L += R;
} // calc_mic
#undef R
#undef L
#endif // HCF_TYPE_WPA
#if (HCF_TYPE) & HCF_TYPE_WPA
/************************************************************************************************************
*
*.SUBMODULE void calc_mic_rx_frag( IFBP ifbp, wci_bufp p, int len )
*.PURPOSE calculate MIC on a single fragment.
*
*.ARGUMENTS
* ifbp address of the Interface Block
* bufp (byte) address of buffer
* len length in bytes of buffer specified by bufp
*
*.RETURNS N.A.
*
*.DESCRIPTION
* calc_mic_rx_frag ........
*
* The MIC is located in the IFB.
* The MIC is separate for Tx and Rx, thus allowing hcf_send_msg to occur between hcf_service_nic and
* hcf_rcv_msg.
*
*
*.DIAGRAM
*
*.NOTICE
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
void
calc_mic_rx_frag( IFBP ifbp, wci_bufp p, int len )
{
static union { hcf_32 x32; hcf_16 x16[2]; hcf_8 x8[4]; } x; //* area to accumulate 4 bytes input for MIC engine
int i;
if ( len == -1 ) { //initialize MIC housekeeping
i = *(wci_recordp)&p[HFS_STAT];
/* i = CNV_SHORTP_TO_LITTLE(&p[HFS_STAT]); should not be neede to prevent alignment poroblems
* since len == -1 if and only if p is lookahaead buffer which MUST be word aligned
* to be re-investigated by NvR
*/
if ( ( i & HFS_STAT_MIC ) == 0 ) {
ifbp->IFB_MICRxCarry = 0xFFFF; //suppress MIC calculation
} else {
ifbp->IFB_MICRxCarry = 0;
//* Note that "coincidentally" the bit positions used in HFS_STAT
//* correspond with the offset of the key in IFB_MICKey
i = ( i & HFS_STAT_MIC_KEY_ID ) >> 10; /* coincidentally no shift needed for i itself */
ifbp->IFB_MICRx[0] = CNV_LONG_TO_LITTLE(ifbp->IFB_MICRxKey[i ]);
ifbp->IFB_MICRx[1] = CNV_LONG_TO_LITTLE(ifbp->IFB_MICRxKey[i+1]);
}
} else {
if ( ifbp->IFB_MICRxCarry == 0 ) {
x.x32 = CNV_LONGP_TO_LITTLE(p);
p += 4;
if ( len < 4 ) {
ifbp->IFB_MICRxCarry = (hcf_16)len;
} else {
ifbp->IFB_MICRxCarry = 4;
len -= 4;
}
} else while ( ifbp->IFB_MICRxCarry < 4 && len ) { //note for hcf_16 applies: 0xFFFF > 4
x.x8[ifbp->IFB_MICRxCarry++] = *p++;
len--;
}
while ( ifbp->IFB_MICRxCarry == 4 ) { //contrived so we have only 1 call to calc_mic so we could bring it in-line
calc_mic( ifbp->IFB_MICRx, x.x32 );
x.x32 = CNV_LONGP_TO_LITTLE(p);
p += 4;
if ( len < 4 ) {
ifbp->IFB_MICRxCarry = (hcf_16)len;
}
len -= 4;
}
}
} // calc_mic_rx_frag
#endif // HCF_TYPE_WPA
#if (HCF_TYPE) & HCF_TYPE_WPA
/************************************************************************************************************
*
*.SUBMODULE void calc_mic_tx_frag( IFBP ifbp, wci_bufp p, int len )
*.PURPOSE calculate MIC on a single fragment.
*
*.ARGUMENTS
* ifbp address of the Interface Block
* bufp (byte) address of buffer
* len length in bytes of buffer specified by bufp
*
*.RETURNS N.A.
*
*.DESCRIPTION
* calc_mic_tx_frag ........
*
* The MIC is located in the IFB.
* The MIC is separate for Tx and Rx, thus allowing hcf_send_msg to occur between hcf_service_nic and
* hcf_rcv_msg.
*
*
*.DIAGRAM
*
*.NOTICE
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
void
calc_mic_tx_frag( IFBP ifbp, wci_bufp p, int len )
{
static union { hcf_32 x32; hcf_16 x16[2]; hcf_8 x8[4]; } x; //* area to accumulate 4 bytes input for MIC engine
//if initialization request
if ( len == -1 ) {
//. presume MIC calculation disabled
ifbp->IFB_MICTxCarry = 0xFFFF;
//. if MIC calculation enabled
if ( ifbp->IFB_MICTxCntl ) {
//. . clear MIC carry
ifbp->IFB_MICTxCarry = 0;
//. . initialize MIC-engine
ifbp->IFB_MICTx[0] = CNV_LONG_TO_LITTLE(ifbp->IFB_MICTxKey[0]); /*Tx always uses Key 0 */
ifbp->IFB_MICTx[1] = CNV_LONG_TO_LITTLE(ifbp->IFB_MICTxKey[1]);
}
//else
} else {
//. if MIC enabled (Tx) / if MIC present (Rx)
//. and no carry from previous calc_mic_frag
if ( ifbp->IFB_MICTxCarry == 0 ) {
//. . preset accu with 4 bytes from buffer
x.x32 = CNV_LONGP_TO_LITTLE(p);
//. . adjust pointer accordingly
p += 4;
//. . if buffer contained less then 4 bytes
if ( len < 4 ) {
//. . . promote valid bytes in accu to carry
//. . . flag accu to contain incomplete double word
ifbp->IFB_MICTxCarry = (hcf_16)len;
//. . else
} else {
//. . . flag accu to contain complete double word
ifbp->IFB_MICTxCarry = 4;
//. . adjust remaining buffer length
len -= 4;
}
//. else if MIC enabled
//. and if carry bytes from previous calc_mic_tx_frag
//. . move (1-3) bytes from carry into accu
} else while ( ifbp->IFB_MICTxCarry < 4 && len ) { /* note for hcf_16 applies: 0xFFFF > 4 */
x.x8[ifbp->IFB_MICTxCarry++] = *p++;
len--;
}
//. while accu contains complete double word
//. and MIC enabled
while ( ifbp->IFB_MICTxCarry == 4 ) {
//. . pass accu to MIC engine
calc_mic( ifbp->IFB_MICTx, x.x32 );
//. . copy next 4 bytes from buffer to accu
x.x32 = CNV_LONGP_TO_LITTLE(p);
//. . adjust buffer pointer
p += 4;
//. . if buffer contained less then 4 bytes
//. . . promote valid bytes in accu to carry
//. . . flag accu to contain incomplete double word
if ( len < 4 ) {
ifbp->IFB_MICTxCarry = (hcf_16)len;
}
//. . adjust remaining buffer length
len -= 4;
}
}
} // calc_mic_tx_frag
#endif // HCF_TYPE_WPA
#if HCF_PROT_TIME
/************************************************************************************************************
*
*.SUBMODULE void calibrate( IFBP ifbp )
*.PURPOSE calibrates the S/W protection counter against the Hermes Timer tick.
*
*.ARGUMENTS
* ifbp address of the Interface Block
*
*.RETURNS N.A.
*
*.DESCRIPTION
* calibrates the S/W protection counter against the Hermes Timer tick
* IFB_TickIni is the value used to initialize the S/W protection counter such that the expiration period
* more or less independent of the processor speed. If IFB_TickIni is not yet calibrated, it is done now.
* This calibration is "reasonably" accurate because the Hermes is in a quiet state as a result of the
* Initialize command.
*
*
*.DIAGRAM
*
*1: IFB_TickIni is initialized at INI_TICK_INI by hcf_connect. If calibrate succeeds, IFB_TickIni is
* guaranteed to be changed. As a consequence there will be only 1 shot at calibration (regardless of the
* number of init calls) under normal circumstances.
*2: Calibration is done HCF_PROT_TIME_CNT times. This diminish the effects of jitter and interference,
* especially in a pre-emptive environment. HCF_PROT_TIME_CNT is in the range of 16 through 32 and derived
* from the HCF_PROT_TIME specified by the MSF programmer. The divisor needed to scale HCF_PROT_TIME into the
* 16-32 range, is used as a multiplicator after the calibration, to scale the found value back to the
* requested range. This way a compromise is achieved between accuracy and duration of the calibration
* process.
*3: Acknowledge the Timer Tick Event.
* Each cycle is limited to at most INI_TICK_INI samples of the TimerTick status of the Hermes.
* Since the start of calibrate is unrelated to the Hermes Internal Timer, the first interval may last from 0
* to the normal interval, all subsequent intervals should be the full length of the Hermes Tick interval.
* The Hermes Timer Tick is not reprogrammed by the HCF, hence it is running at the default of 10 k
* microseconds.
*4: If the Timer Tick Event is continuously up (prot_cnt still has the value INI_TICK_INI) or no Timer Tick
* Event occurred before the protection counter expired, reset IFB_TickIni to INI_TICK_INI,
* set the defunct bit of IFB_CardStat (thus rendering the Hermes inoperable) and exit the calibrate routine.
*8: ifbp->IFB_TickIni is multiplied to scale the found value back to the requested range as explained under 2.
*
*.NOTICE
* o Although there are a number of viewpoints possible, calibrate() uses as error strategy that a single
* failure of the Hermes TimerTick is considered fatal.
* o There is no hard and concrete time-out value defined for Hermes activities. The default 1 seconds is
* believed to be sufficiently "relaxed" for real life and to be sufficiently short to be still useful in an
* environment with humans.
* o Note that via IFB_DefunctStat time outs in cmd_wait and in hcfio_string block all Hermes access till the
* next init so functions which call a mix of cmd_wait and hcfio_string only need to check the return status
* of the last call
* o The return code is preset at Time out.
* The additional complication that no calibrated value for the protection count can be assumed since
* calibrate() does not yet have determined a calibrated value (a catch 22), is handled by setting the
* initial value at INI_TICK_INI (by hcf_connect). This approach is considered safe, because:
* - the HCF does not use the pipeline mechanism of Hermes commands.
* - the likelihood of failure (the only time when protection count is relevant) is small.
* - the time will be sufficiently large on a fast machine (busy bit drops on good NIC before counter
* expires)
* - the time will be sufficiently small on a slow machine (counter expires on bad NIC before the end user
* switches the power off in despair
* The time needed to wrap a 32 bit counter around is longer than many humans want to wait, hence the more or
* less arbitrary value of 0x40000L is chosen, assuming it does not take too long on an XT and is not too
* short on a scream-machine.
*
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
HCF_STATIC void
calibrate( IFBP ifbp )
{
int cnt = HCF_PROT_TIME_CNT;
hcf_32 prot_cnt;
HCFTRACE( ifbp, HCF_TRACE_CALIBRATE );
if ( ifbp->IFB_TickIni == INI_TICK_INI ) { /*1*/
ifbp->IFB_TickIni = 0; /*2*/
while ( cnt-- ) {
prot_cnt = INI_TICK_INI;
OPW( HREG_EV_ACK, HREG_EV_TICK ); /*3*/
while ( (IPW( HREG_EV_STAT ) & HREG_EV_TICK) == 0 && --prot_cnt ) {
ifbp->IFB_TickIni++;
}
if ( prot_cnt == 0 || prot_cnt == INI_TICK_INI ) { /*4*/
ifbp->IFB_TickIni = INI_TICK_INI;
ifbp->IFB_DefunctStat = HCF_ERR_DEFUNCT_TIMER;
ifbp->IFB_CardStat |= CARD_STAT_DEFUNCT;
HCFASSERT( DO_ASSERT, prot_cnt );
}
}
ifbp->IFB_TickIni <<= HCF_PROT_TIME_SHFT; /*8*/
}
HCFTRACE( ifbp, HCF_TRACE_CALIBRATE | HCF_TRACE_EXIT );
} // calibrate
#endif // HCF_PROT_TIME
#if (HCF_TYPE) & HCF_TYPE_WPA
/************************************************************************************************************
*
*.SUBMODULE int check_mic( IFBP ifbp )
*.PURPOSE verifies the MIC of a received non-USB frame.
*
*.ARGUMENTS
* ifbp address of the Interface Block
*
*.RETURNS
* HCF_SUCCESS
* HCF_ERR_MIC
*
*.DESCRIPTION
*
*
*.DIAGRAM
*
*4: test whether or not a MIC is reported by the Hermes
*14: the calculated MIC and the received MIC are compared, the return status is set when there is a mismatch
*
*.NOTICE
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
int
check_mic( IFBP ifbp )
{
int rc = HCF_SUCCESS;
hcf_32 x32[2]; //* area to save rcvd 8 bytes MIC
//if MIC present in RxFS
if ( *(wci_recordp)&ifbp->IFB_lap[-HFS_ADDR_DEST] & HFS_STAT_MIC ) {
//or if ( ifbp->IFB_MICRxCarry != 0xFFFF )
CALC_RX_MIC( mic_pad, 8 ); //. process up to 3 remaining bytes of data and append 5 to 8 bytes of padding to MIC calculation
get_frag( ifbp, (wci_bufp)x32, 8 BE_PAR(0));//. get 8 byte MIC from NIC
//. if calculated and received MIC do not match
//. . set status at HCF_ERR_MIC
/*14*/ if ( x32[0] != CNV_LITTLE_TO_LONG(ifbp->IFB_MICRx[0]) ||
x32[1] != CNV_LITTLE_TO_LONG(ifbp->IFB_MICRx[1]) ) {
rc = HCF_ERR_MIC;
}
}
//return status
return rc;
} // check_mic
#endif // HCF_TYPE_WPA
/************************************************************************************************************
*
*.SUBMODULE int cmd_cmpl( IFBP ifbp )
*.PURPOSE waits for Hermes Command Completion.
*
*.ARGUMENTS
* ifbp address of the Interface Block
*
*.RETURNS
* IFB_DefunctStat
* HCF_ERR_TIME_OUT
* HCF_ERR_DEFUNCT_CMD_SEQ
* HCF_SUCCESS
*
*.DESCRIPTION
*
*
*.DIAGRAM
*
*2: Once cmd_cmpl is called, the Busy option bit in IFB_Cmd must be cleared
*4: If Status register and command code don't match either:
* - the Hermes and Host are out of sync ( a fatal error)
* - error bits are reported via the Status Register.
* Out of sync is considered fatal and brings the HCF in Defunct mode
* Errors reported via the Status Register should be caused by sequence violations in Hermes command
* sequences and hence these bugs should have been found during engineering testing. Since there is no
* strategy to cope with this problem, it might as well be ignored at run time. Note that for any particular
* situation where a strategy is formulated to handle the consequences of a particular bug causing a
* particular Error situation reported via the Status Register, the bug should be removed rather than adding
* logic to cope with the consequences of the bug.
* There have been HCF versions where an error report via the Status Register even brought the HCF in defunct
* mode (although it was not yet named like that at that time). This is particular undesirable behavior for a
* general library.
* Simply reporting the error (as "interesting") is debatable. There also have been HCF versions with this
* strategy using the "vague" HCF_FAILURE code.
* The error is reported via:
* - MiscErr tally of the HCF Tally set
* - the (informative) fields IFB_ErrCmd and IFB_ErrQualifier
* - the assert mechanism
*8: Here the Defunct case and the Status error are separately treated
*
*
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
HCF_STATIC int
cmd_cmpl( IFBP ifbp )
{
PROT_CNT_INI;
int rc = HCF_SUCCESS;
hcf_16 stat;
HCFLOGENTRY( HCF_TRACE_CMD_CPL, ifbp->IFB_Cmd );
ifbp->IFB_Cmd &= ~HCMD_BUSY; /* 2 */
HCF_WAIT_WHILE( (IPW( HREG_EV_STAT) & HREG_EV_CMD) == 0 ); /* 4 */
stat = IPW( HREG_STAT );
#if HCF_PROT_TIME
if ( prot_cnt == 0 ) {
IF_TALLY( ifbp->IFB_HCF_Tallies.MiscErr++ );
rc = HCF_ERR_TIME_OUT;
HCFASSERT( DO_ASSERT, ifbp->IFB_Cmd );
} else
#endif // HCF_PROT_TIME
{
DAWA_ACK( HREG_EV_CMD );
/*4*/ if ( stat != (ifbp->IFB_Cmd & HCMD_CMD_CODE) ) {
/*8*/ if ( ( (stat ^ ifbp->IFB_Cmd ) & HCMD_CMD_CODE) != 0 ) {
rc = ifbp->IFB_DefunctStat = HCF_ERR_DEFUNCT_CMD_SEQ;
ifbp->IFB_CardStat |= CARD_STAT_DEFUNCT;
}
IF_TALLY( ifbp->IFB_HCF_Tallies.MiscErr++ );
ifbp->IFB_ErrCmd = stat;
ifbp->IFB_ErrQualifier = IPW( HREG_RESP_0 );
HCFASSERT( DO_ASSERT, MERGE_2( IPW( HREG_PARAM_0 ), ifbp->IFB_Cmd ) );
HCFASSERT( DO_ASSERT, MERGE_2( ifbp->IFB_ErrQualifier, ifbp->IFB_ErrCmd ) );
}
}
HCFASSERT( rc == HCF_SUCCESS, rc);
HCFLOGEXIT( HCF_TRACE_CMD_CPL );
return rc;
} // cmd_cmpl
/************************************************************************************************************
*
*.SUBMODULE int cmd_exe( IFBP ifbp, int cmd_code, int par_0 )
*.PURPOSE Executes synchronous part of Hermes Command and - optionally - waits for Command Completion.
*
*.ARGUMENTS
* ifbp address of the Interface Block
* cmd_code
* par_0
*
*.RETURNS
* IFB_DefunctStat
* HCF_ERR_DEFUNCT_CMD_SEQ
* HCF_SUCCESS
* HCF_ERR_TO_BE_ADDED <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
*
*.DESCRIPTION
* Executes synchronous Hermes Command and waits for Command Completion
*
* The general HCF strategy is to wait for command completion. As a consequence:
* - the read of the busy bit before writing the command register is superfluous
* - the Hermes requirement that no Inquiry command may be executed if there is still an unacknowledged
* Inquiry command outstanding, is automatically met.
* The Tx command uses the "Busy" bit in the cmd_code parameter to deviate from this general HCF strategy.
* The idea is that by not busy-waiting on completion of this frequently used command the processor
* utilization is diminished while using the busy-wait on all other seldom used commands the flow is kept
* simple.
*
*
*
*.DIAGRAM
*
*1: skip the body of cmd_exe when in defunct mode or when - based on the S/W Support register write and
* read back test - there is apparently no NIC.
* Note: we gave up on the "old" strategy to write the S/W Support register at magic only when needed. Due to
* the intricateness of Hermes F/W varieties ( which behave differently as far as corruption of the S/W
* Support register is involved), the increasing number of Hermes commands which do an implicit initialize
* (thus modifying the S/W Support register) and the workarounds of some OS/Support S/W induced aspects (e.g.
* the System Soft library at WinNT which postpones the actual mapping of I/O space up to 30 seconds after
* giving the go-ahead), the "magic" strategy is now reduced to a simple write and read back. This means that
* problems like a bug tramping over the memory mapped Hermes registers will no longer be noticed as side
* effect of the S/W Support register check.
*2: check whether the preceding command skipped the busy wait and if so, check for command completion
*
*.NOTICE
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
HCF_STATIC int
cmd_exe( IFBP ifbp, hcf_16 cmd_code, hcf_16 par_0 ) //if HCMD_BUSY of cmd_code set, then do NOT wait for completion
{
int rc;
HCFLOGENTRY( HCF_TRACE_CMD_EXE, cmd_code );
HCFASSERT( (cmd_code & HCMD_CMD_CODE) != HCMD_TX || cmd_code & HCMD_BUSY, cmd_code ); //Tx must have Busy bit set
OPW( HREG_SW_0, HCF_MAGIC );
if ( IPW( HREG_SW_0 ) == HCF_MAGIC ) { /* 1 */
rc = ifbp->IFB_DefunctStat;
}
else rc = HCF_ERR_NO_NIC;
if ( rc == HCF_SUCCESS ) {
//;?is this a hot idea, better MEASURE performance impact
/*2*/ if ( ifbp->IFB_Cmd & HCMD_BUSY ) {
rc = cmd_cmpl( ifbp );
}
OPW( HREG_PARAM_0, par_0 );
OPW( HREG_CMD, cmd_code &~HCMD_BUSY );
ifbp->IFB_Cmd = cmd_code;
if ( (cmd_code & HCMD_BUSY) == 0 ) { //;?is this a hot idea, better MEASURE performance impact
rc = cmd_cmpl( ifbp );
}
}
HCFASSERT( rc == HCF_SUCCESS, MERGE_2( rc, cmd_code ) );
HCFLOGEXIT( HCF_TRACE_CMD_EXE );
return rc;
} // cmd_exe
/************************************************************************************************************
*
*.SUBMODULE int download( IFBP ifbp, CFG_PROG_STRCT FAR *ltvp )
*.PURPOSE downloads F/W image into NIC and initiates execution of the downloaded F/W.
*
*.ARGUMENTS
* ifbp address of the Interface Block
* ltvp specifies the pseudo-RID (as defined by WCI)
*
*.RETURNS
*
*.DESCRIPTION
*
*
*.DIAGRAM
*1: First, Ack everything to unblock a (possibly) blocked cmd pipe line
* Note 1: it is very likely that an Alloc event is pending and very well possible that a (Send) Cmd event is
* pending
* Note 2: it is assumed that this strategy takes away the need to ack every conceivable event after an
* Hermes Initialize
*
*
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
HCF_STATIC int
download( IFBP ifbp, CFG_PROG_STRCT FAR *ltvp ) //Hermes-II download (volatile only)
{
hcf_16 i;
int rc = HCF_SUCCESS;
wci_bufp cp;
hcf_io io_port = ifbp->IFB_IOBase + HREG_AUX_DATA;
HCFLOGENTRY( HCF_TRACE_DL, ltvp->typ );
#if (HCF_TYPE) & HCF_TYPE_PRELOADED
HCFASSERT( DO_ASSERT, ltvp->mode );
#else
//if initial "program" LTV
if ( ifbp->IFB_DLMode == CFG_PROG_STOP && ltvp->mode == CFG_PROG_VOLATILE) {
//. switch Hermes to initial mode
/*1*/ OPW( HREG_EV_ACK, ~HREG_EV_SLEEP_REQ );
rc = cmd_exe( ifbp, HCMD_INI, 0 ); /* HCMD_INI can not be part of init() because that is called on
* other occasions as well */
rc = init( ifbp );
}
//if final "program" LTV
if ( ltvp->mode == CFG_PROG_STOP && ifbp->IFB_DLMode == CFG_PROG_VOLATILE) {
//. start tertiary (or secondary)
OPW( HREG_PARAM_1, (hcf_16)(ltvp->nic_addr >> 16) );
rc = cmd_exe( ifbp, HCMD_EXECUTE, (hcf_16) ltvp->nic_addr );
if (rc == HCF_SUCCESS) {
rc = init( ifbp ); /*;? do we really want to skip init if cmd_exe failed, i.e.
* IFB_FW_Comp_Id is than possibly incorrect */
}
//else (non-final)
} else {
//. if mode == Readback SEEPROM
#if 0 //;? as long as the next if contains a hard coded 0, might as well leave it out even more obvious
if ( 0 /*len is definitely not want we want;?*/ && ltvp->mode == CFG_PROG_SEEPROM_READBACK ) {
OPW( HREG_PARAM_1, (hcf_16)(ltvp->nic_addr >> 16) );
OPW( HREG_PARAM_2, (hcf_16)((ltvp->len - 4) << 1) );
//. . perform Hermes prog cmd with appropriate mode bits
rc = cmd_exe( ifbp, HCMD_PROGRAM | ltvp->mode, (hcf_16)ltvp->nic_addr );
//. . set up NIC RAM addressability according Resp0-1
OPW( HREG_AUX_PAGE, IPW( HREG_RESP_1) );
OPW( HREG_AUX_OFFSET, IPW( HREG_RESP_0) );
//. . set up L-field of LTV according Resp2
i = ( IPW( HREG_RESP_2 ) + 1 ) / 2; // i contains max buffer size in words, a probably not very useful piece of information ;?
/*Nico's code based on i is the "real amount of data available"
if ( ltvp->len - 4 < i ) rc = HCF_ERR_LEN;
else ltvp->len = i + 4;
*/
/* Rolands code based on the idea that a MSF should not ask for more than is available
// check if number of bytes requested exceeds max buffer size
if ( ltvp->len - 4 > i ) {
rc = HCF_ERR_LEN;
ltvp->len = i + 4;
}
*/
//. . copy data from NIC via AUX port to LTV
cp = (wci_bufp)ltvp->host_addr; /*IN_PORT_STRING_8_16 macro may modify its parameters*/
i = ltvp->len - 4;
IN_PORT_STRING_8_16( io_port, cp, i ); //!!!WORD length, cp MUST be a char pointer // $$ char
//. else (non-final programming)
} else
#endif //;? as long as the above if contains a hard coded 0, might as well leave it out even more obvious
{ //. . get number of words to program
HCFASSERT( ltvp->segment_size, *ltvp->host_addr );
i = ltvp->segment_size/2;
//. . copy data (words) from LTV via AUX port to NIC
cp = (wci_bufp)ltvp->host_addr; //OUT_PORT_STRING_8_16 macro may modify its parameters
//. . if mode == volatile programming
if ( ltvp->mode == CFG_PROG_VOLATILE ) {
//. . . set up NIC RAM addressability via AUX port
OPW( HREG_AUX_PAGE, (hcf_16)(ltvp->nic_addr >> 16 << 9 | (ltvp->nic_addr & 0xFFFF) >> 7 ) );
OPW( HREG_AUX_OFFSET, (hcf_16)(ltvp->nic_addr & 0x007E) );
OUT_PORT_STRING_8_16( io_port, cp, i ); //!!!WORD length, cp MUST be a char pointer
}
}
}
ifbp->IFB_DLMode = ltvp->mode; //save state in IFB_DLMode
#endif // HCF_TYPE_PRELOADED
HCFASSERT( rc == HCF_SUCCESS, rc );
HCFLOGEXIT( HCF_TRACE_DL );
return rc;
} // download
#if (HCF_ASSERT) & HCF_ASSERT_PRINTF
/**************************************************
* Certain Hermes-II firmware versions can generate
* debug information. This debug information is
* contained in a buffer in nic-RAM, and can be read
* via the aux port.
**************************************************/
HCF_STATIC int
fw_printf(IFBP ifbp, CFG_FW_PRINTF_STRCT FAR *ltvp)
{
int rc = HCF_SUCCESS;
hcf_16 fw_cnt;
// hcf_32 DbMsgBuffer = 0x29D2, DbMsgCount= 0x000029D0;
// hcf_16 DbMsgSize=0x00000080;
hcf_32 DbMsgBuffer;
CFG_FW_PRINTF_BUFFER_LOCATION_STRCT *p = &ifbp->IFB_FwPfBuff;
ltvp->len = 1;
if ( p->DbMsgSize != 0 ) {
// first, check the counter in nic-RAM and compare it to the latest counter value of the HCF
OPW( HREG_AUX_PAGE, (hcf_16)(p->DbMsgCount >> 7) );
OPW( HREG_AUX_OFFSET, (hcf_16)(p->DbMsgCount & 0x7E) );
fw_cnt = ((IPW( HREG_AUX_DATA) >>1 ) & ((hcf_16)p->DbMsgSize - 1));
if ( fw_cnt != ifbp->IFB_DbgPrintF_Cnt ) {
// DbgPrint("fw_cnt=%d IFB_DbgPrintF_Cnt=%d\n", fw_cnt, ifbp->IFB_DbgPrintF_Cnt);
DbMsgBuffer = p->DbMsgBuffer + ifbp->IFB_DbgPrintF_Cnt * 6; // each entry is 3 words
OPW( HREG_AUX_PAGE, (hcf_16)(DbMsgBuffer >> 7) );
OPW( HREG_AUX_OFFSET, (hcf_16)(DbMsgBuffer & 0x7E) );
ltvp->msg_id = IPW(HREG_AUX_DATA);
ltvp->msg_par = IPW(HREG_AUX_DATA);
ltvp->msg_tstamp = IPW(HREG_AUX_DATA);
ltvp->len = 4;
ifbp->IFB_DbgPrintF_Cnt++;
ifbp->IFB_DbgPrintF_Cnt &= (p->DbMsgSize - 1);
}
}
return rc;
};
#endif // HCF_ASSERT_PRINTF
/************************************************************************************************************
*
*.SUBMODULE hcf_16 get_fid( IFBP ifbp )
*.PURPOSE get allocated FID for either transmit or notify.
*
*.ARGUMENTS
* ifbp address of the Interface Block
*
*.RETURNS
* 0 no FID available
* <>0 FID number
*
*.DESCRIPTION
*
*
*.DIAGRAM
* The preference is to use a "pending" alloc. If no alloc is pending, then - if available - the "spare" FID
* is used.
* If the spare FID is used, IFB_RscInd (representing the spare FID) must be cleared
* If the pending alloc is used, the alloc event must be acknowledged to the Hermes.
* In case the spare FID was depleted and the IFB_RscInd has been "faked" as pseudo resource with a 0x0001
* value by hcf_service_nic, IFB_RscInd has to be "corrected" again to its 0x0000 value.
*
* Note that due to the Hermes-II H/W problems which are intended to be worked around by DAWA, the Alloc bit
* in the Event register is no longer a reliable indication of the presence/absence of a FID. The "Clear FID"
* part of the DAWA logic, together with the choice of the definition of the return information from get_fid,
* handle this automatically, i.e. without additional code in get_fid.
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
HCF_STATIC hcf_16
get_fid( IFBP ifbp )
{
hcf_16 fid = 0;
#if ( (HCF_TYPE) & HCF_TYPE_HII5 ) == 0
PROT_CNT_INI;
#endif // HCF_TYPE_HII5
IF_DMA( HCFASSERT(!(ifbp->IFB_CntlOpt & USE_DMA), ifbp->IFB_CntlOpt) );
if ( IPW( HREG_EV_STAT) & HREG_EV_ALLOC) {
fid = IPW( HREG_ALLOC_FID );
HCFASSERT( fid, ifbp->IFB_RscInd );
DAWA_ZERO_FID( HREG_ALLOC_FID );
#if ( (HCF_TYPE) & HCF_TYPE_HII5 ) == 0
HCF_WAIT_WHILE( ( IPW( HREG_EV_STAT ) & HREG_EV_ACK_REG_READY ) == 0 );
HCFASSERT( prot_cnt, IPW( HREG_EV_STAT ) );
#endif // HCF_TYPE_HII5
DAWA_ACK( HREG_EV_ALLOC ); //!!note that HREG_EV_ALLOC is written only once
// 180 degree error in logic ;? #if ALLOC_15
if ( ifbp->IFB_RscInd == 1 ) {
ifbp->IFB_RscInd = 0;
}
//#endif // ALLOC_15
} else {
// 180 degree error in logic ;? #if ALLOC_15
fid = ifbp->IFB_RscInd;
//#endif // ALLOC_15
ifbp->IFB_RscInd = 0;
}
return fid;
} // get_fid
/************************************************************************************************************
*
*.SUBMODULE void get_frag( IFBP ifbp, wci_bufp bufp, int len BE_PAR( int word_len ) )
*.PURPOSE reads with 16/32 bit I/O via BAP1 port from NIC RAM to Host memory.
*
*.ARGUMENTS
* ifbp address of the Interface Block
* bufp (byte) address of buffer
* len length in bytes of buffer specified by bufp
* word_len Big Endian only: number of leading bytes to swap in pairs
*
*.RETURNS N.A.
*
*.DESCRIPTION
* process the single byte (if applicable) read by the previous get_frag and copy len (or len-1) bytes from
* NIC to bufp.
* On a Big Endian platform, the parameter word_len controls the number of leading bytes whose endianness is
* converted (i.e. byte swapped)
*
*
*.DIAGRAM
*10: The PCMCIA card can be removed in the middle of the transfer. By depositing a "magic number" in the
* HREG_SW_0 register of the Hermes at initialization time and by verifying this register, it can be
* determined whether the card is still present. The return status is set accordingly.
* Clearing the buffer is a (relative) cheap way to prevent that failing I/O results in run-away behavior
* because the garbage in the buffer is interpreted by the caller irrespective of the return status (e.g.
* hcf_service_nic has this behavior).
*
*.NOTICE
* It turns out DOS ODI uses zero length fragments. The HCF code can cope with it, but as a consequence, no
* Assert on len is possible
*
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
HCF_STATIC void
get_frag( IFBP ifbp, wci_bufp bufp, int len BE_PAR( int word_len ) )
{
hcf_io io_port = ifbp->IFB_IOBase + HREG_DATA_1; //BAP data register
wci_bufp p = bufp; //working pointer
int i; //prevent side effects from macro
int j;
HCFASSERT( ((hcf_32)bufp & (HCF_ALIGN-1) ) == 0, (hcf_32)bufp );
/*1: here recovery logic for intervening BAP access between hcf_service_nic and hcf_rcv_msg COULD be added
* if current access is RxInitial
* . persistent_offset += len
*/
i = len;
//if buffer length > 0 and carry from previous get_frag
if ( i && ifbp->IFB_CarryIn ) {
//. move carry to buffer
//. adjust buffer length and pointer accordingly
*p++ = (hcf_8)(ifbp->IFB_CarryIn>>8);
i--;
//. clear carry flag
ifbp->IFB_CarryIn = 0;
}
#if (HCF_IO) & HCF_IO_32BITS
//skip zero-length I/O, single byte I/O and I/O not worthwhile (i.e. less than 6 bytes)for DW logic
//if buffer length >= 6 and 32 bits I/O support
if ( !(ifbp->IFB_CntlOpt & USE_16BIT) && i >= 6 ) {
hcf_32 FAR *p4; //prevent side effects from macro
if ( ( (hcf_32)p & 0x1 ) == 0 ) { //. if buffer at least word aligned
if ( (hcf_32)p & 0x2 ) { //. . if buffer not double word aligned
//. . . read single word to get double word aligned
*(wci_recordp)p = IN_PORT_WORD( io_port );
//. . . adjust buffer length and pointer accordingly
p += 2;
i -= 2;
}
//. . read as many double word as possible
p4 = (hcf_32 FAR *)p;
j = i/4;
IN_PORT_STRING_32( io_port, p4, j );
//. . adjust buffer length and pointer accordingly
p += i & ~0x0003;
i &= 0x0003;
}
}
#endif // HCF_IO_32BITS
//if no 32-bit support OR byte aligned OR 1-3 bytes left
if ( i ) {
//. read as many word as possible in "alignment safe" way
j = i/2;
IN_PORT_STRING_8_16( io_port, p, j );
//. if 1 byte left
if ( i & 0x0001 ) {
//. . read 1 word
ifbp->IFB_CarryIn = IN_PORT_WORD( io_port );
//. . store LSB in last char of buffer
bufp[len-1] = (hcf_8)ifbp->IFB_CarryIn;
//. . save MSB in carry, set carry flag
ifbp->IFB_CarryIn |= 0x1;
}
}
#if HCF_BIG_ENDIAN
HCFASSERT( word_len == 0 || word_len == 2 || word_len == 4, word_len );
HCFASSERT( word_len == 0 || ((hcf_32)bufp & 1 ) == 0, (hcf_32)bufp );
HCFASSERT( word_len <= len, MERGE2( word_len, len ) );
//see put_frag for an alternative implementation, but be careful about what are int's and what are
//hcf_16's
if ( word_len ) { //. if there is anything to convert
hcf_8 c;
c = bufp[1]; //. . convert the 1st hcf_16
bufp[1] = bufp[0];
bufp[0] = c;
if ( word_len > 1 ) { //. . if there is to convert more than 1 word ( i.e 2 )
c = bufp[3]; //. . . convert the 2nd hcf_16
bufp[3] = bufp[2];
bufp[2] = c;
}
}
#endif // HCF_BIG_ENDIAN
} // get_frag
/************************************************************************************************************
*
*.SUBMODULE int init( IFBP ifbp )
*.PURPOSE Handles common initialization aspects (H-I init, calibration, config.mngmt, allocation).
*
*.ARGUMENTS
* ifbp address of the Interface Block
*
*.RETURNS
* HCF_ERR_INCOMP_PRI
* HCF_ERR_INCOMP_FW
* HCF_ERR_TIME_OUT
* >>hcf_get_info
* HCF_ERR_NO_NIC
* HCF_ERR_LEN
*
*.DESCRIPTION
* init will successively:
* - in case of a (non-preloaded) H-I, initialize the NIC
* - calibrate the S/W protection timer against the Hermes Timer
* - collect HSI, "active" F/W Configuration Management Information
* - in case active F/W is Primary F/W: collect Primary F/W Configuration Management Information
* - check HSI and Primary F/W compatibility with the HCF
* - in case active F/W is Station or AP F/W: check Station or AP F/W compatibility with the HCF
* - in case active F/W is not Primary F/W: allocate FIDs to be used in transmit/notify process
*
*
*.DIAGRAM
*2: drop all error status bits in IFB_CardStat since they are expected to be re-evaluated.
*4: Ack everything except HREG_EV_SLEEP_REQ. It is very likely that an Alloc event is pending and
* very well possible that a Send Cmd event is pending. Acking HREG_EV_SLEEP_REQ is handled by hcf_action(
* HCF_ACT_INT_ON ) !!!
*10: Calibrate the S/W time-out protection mechanism by calling calibrate(). Note that possible errors
* in the calibration process are nor reported by init but will show up via the defunct mechanism in
* subsequent hcf-calls.
*14: usb_check_comp() is called to have the minimal visual clutter for the legacy H-I USB dongle
* compatibility check.
*16: The following configuration management related information is retrieved from the NIC:
* - HSI supplier
* - F/W Identity
* - F/W supplier
* if appropriate:
* - PRI Identity
* - PRI supplier
* appropriate means on H-I: always
* and on H-II if F/W supplier reflects a primary (i.e. only after an Hermes Reset or Init
* command).
* QUESTION ;? !!!!!! should, For each of the above RIDs the Endianness is converted to native Endianness.
* Only the return code of the first hcf_get_info is used. All hcf_get_info calls are made, regardless of
* the success or failure of the 1st hcf_get_info. The assumptions are:
* - if any call fails, they all fail, so remembering the result of the 1st call is adequate
* - a failing call will overwrite the L-field with a 0x0000 value, which services both as an
* error indication for the values cached in the IFB as making mmd_check_comp fail.
* In case of H-I, when getting the F/W identity fails, the F/W is assumed to be H-I AP F/W pre-dating
* version 9.0 and the F/W Identity and Supplier are faked accordingly.
* In case of H-II, the Primary, Station and AP Identity are merged into a single F/W Identity.
* The same applies to the Supplier information. As a consequence the PRI information can no longer be
* retrieved when a Tertiary runs. To accommodate MSFs and Utilities who depend on PRI information being
* available at any time, this information is cached in the IFB. In this cache the generic "F/W" value of
* the typ-fields is overwritten with the specific (legacy) "PRI" values. To actually re-route the (legacy)
* PRI request via hcf_get_info, the xxxx-table must be set. In case of H-I, this caching, modifying and
* re-routing is not needed because PRI information is always available directly from the NIC. For
* consistency the caching fields in the IFB are filled with the PRI information anyway.
*18: mdd_check_comp() is called to check the Supplier Variant and Range of the Host-S/W I/F (HSI) and the
* Primary Firmware Variant and Range against the Top and Bottom level supported by this HCF. If either of
* these tests fails, the CARD_STAT_INCOMP_PRI bit of IFB_CardStat is set
* Note: There should always be a primary except during production, so this makes the HCF in its current form
* unsuitable for manufacturing test systems like the FTS. This can be remedied by an adding a test like
* ifbp->IFB_PRISup.id == COMP_ID_PRI
*20: In case there is Tertiary F/W and this F/W is Station F/W, the Supplier Variant and Range of the Station
* Firmware function as retrieved from the Hermes is checked against the Top and Bottom level supported by
* this HCF.
* Note: ;? the tertiary F/W compatibility checks could be moved to the DHF, which already has checked the
* CFI and MFI compatibility of the image with the NIC before the image was downloaded.
*28: In case of non-Primary F/W: allocates and acknowledge a (TX or Notify) FID and allocates without
* acknowledge another (TX or Notify) FID (the so-called 1.5 alloc scheme) with the following steps:
* - execute the allocate command by calling cmd_exe
* - wait till either the alloc event or a time-out occurs
* - regardless whether the alloc event occurs, call get_fid to
* - read the FID and save it in IFB_RscInd to be used as "spare FID"
* - acknowledge the alloc event
* - do another "half" allocate to complete the "1.5 Alloc scheme"
* Note that above 3 steps do not harm and thus give the "cheapest" acceptable strategy.
* If a time-out occurred, then report time out status (after all)
*
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
HCF_STATIC int
init( IFBP ifbp )
{
int rc = HCF_SUCCESS;
HCFLOGENTRY( HCF_TRACE_INIT, 0 );
ifbp->IFB_CardStat = 0; /* 2*/
OPW( HREG_EV_ACK, ~HREG_EV_SLEEP_REQ ); /* 4*/
IF_PROT_TIME( calibrate( ifbp ) ); /*10*/
#if 0 // OOR
ifbp->IFB_FWIdentity.len = 2; //misuse the IFB space for a put
ifbp->IFB_FWIdentity.typ = CFG_TICK_TIME;
ifbp->IFB_FWIdentity.comp_id = (1000*1000)/1024 + 1; //roughly 1 second
hcf_put_info( ifbp, (LTVP)&ifbp->IFB_FWIdentity.len );
#endif // OOR
ifbp->IFB_FWIdentity.len = sizeof(CFG_FW_IDENTITY_STRCT)/sizeof(hcf_16) - 1;
ifbp->IFB_FWIdentity.typ = CFG_FW_IDENTITY;
rc = hcf_get_info( ifbp, (LTVP)&ifbp->IFB_FWIdentity.len );
/* ;? conversion should not be needed for mmd_check_comp */
#if HCF_BIG_ENDIAN
ifbp->IFB_FWIdentity.comp_id = CNV_LITTLE_TO_SHORT( ifbp->IFB_FWIdentity.comp_id );
ifbp->IFB_FWIdentity.variant = CNV_LITTLE_TO_SHORT( ifbp->IFB_FWIdentity.variant );
ifbp->IFB_FWIdentity.version_major = CNV_LITTLE_TO_SHORT( ifbp->IFB_FWIdentity.version_major );
ifbp->IFB_FWIdentity.version_minor = CNV_LITTLE_TO_SHORT( ifbp->IFB_FWIdentity.version_minor );
#endif // HCF_BIG_ENDIAN
#if defined MSF_COMPONENT_ID /*14*/
if ( rc == HCF_SUCCESS ) { /*16*/
ifbp->IFB_HSISup.len = sizeof(CFG_SUP_RANGE_STRCT)/sizeof(hcf_16) - 1;
ifbp->IFB_HSISup.typ = CFG_NIC_HSI_SUP_RANGE;
rc = hcf_get_info( ifbp, (LTVP)&ifbp->IFB_HSISup.len );
/* ;? conversion should not be needed for mmd_check_comp , BUT according to a report of a BE-user it is
* should be resolved in the WARP release
* since some compilers make ugly but unnecessary code of these instructions even for LE,
* it is conditionally compiled */
#if HCF_BIG_ENDIAN
ifbp->IFB_HSISup.role = CNV_LITTLE_TO_SHORT( ifbp->IFB_HSISup.role );
ifbp->IFB_HSISup.id = CNV_LITTLE_TO_SHORT( ifbp->IFB_HSISup.id );
ifbp->IFB_HSISup.variant = CNV_LITTLE_TO_SHORT( ifbp->IFB_HSISup.variant );
ifbp->IFB_HSISup.bottom = CNV_LITTLE_TO_SHORT( ifbp->IFB_HSISup.bottom );
ifbp->IFB_HSISup.top = CNV_LITTLE_TO_SHORT( ifbp->IFB_HSISup.top );
#endif // HCF_BIG_ENDIAN
ifbp->IFB_FWSup.len = sizeof(CFG_SUP_RANGE_STRCT)/sizeof(hcf_16) - 1;
ifbp->IFB_FWSup.typ = CFG_FW_SUP_RANGE;
(void)hcf_get_info( ifbp, (LTVP)&ifbp->IFB_FWSup.len );
/* ;? conversion should not be needed for mmd_check_comp */
#if HCF_BIG_ENDIAN
ifbp->IFB_FWSup.role = CNV_LITTLE_TO_SHORT( ifbp->IFB_FWSup.role );
ifbp->IFB_FWSup.id = CNV_LITTLE_TO_SHORT( ifbp->IFB_FWSup.id );
ifbp->IFB_FWSup.variant = CNV_LITTLE_TO_SHORT( ifbp->IFB_FWSup.variant );
ifbp->IFB_FWSup.bottom = CNV_LITTLE_TO_SHORT( ifbp->IFB_FWSup.bottom );
ifbp->IFB_FWSup.top = CNV_LITTLE_TO_SHORT( ifbp->IFB_FWSup.top );
#endif // HCF_BIG_ENDIAN
if ( ifbp->IFB_FWSup.id == COMP_ID_PRI ) { /* 20*/
int i = sizeof( CFG_FW_IDENTITY_STRCT) + sizeof(CFG_SUP_RANGE_STRCT );
while ( i-- ) ((hcf_8*)(&ifbp->IFB_PRIIdentity))[i] = ((hcf_8*)(&ifbp->IFB_FWIdentity))[i];
ifbp->IFB_PRIIdentity.typ = CFG_PRI_IDENTITY;
ifbp->IFB_PRISup.typ = CFG_PRI_SUP_RANGE;
xxxx[xxxx_PRI_IDENTITY_OFFSET] = &ifbp->IFB_PRIIdentity.len;
xxxx[xxxx_PRI_IDENTITY_OFFSET+1] = &ifbp->IFB_PRISup.len;
}
if ( !mmd_check_comp( (void*)&cfg_drv_act_ranges_hsi, &ifbp->IFB_HSISup) /* 22*/
#if ( (HCF_TYPE) & HCF_TYPE_PRELOADED ) == 0
//;? the PRI compatibility check is only relevant for DHF
|| !mmd_check_comp( (void*)&cfg_drv_act_ranges_pri, &ifbp->IFB_PRISup)
#endif // HCF_TYPE_PRELOADED
) {
ifbp->IFB_CardStat = CARD_STAT_INCOMP_PRI;
rc = HCF_ERR_INCOMP_PRI;
}
if ( ( ifbp->IFB_FWSup.id == COMP_ID_STA && !mmd_check_comp( (void*)&cfg_drv_act_ranges_sta, &ifbp->IFB_FWSup) ) ||
( ifbp->IFB_FWSup.id == COMP_ID_APF && !mmd_check_comp( (void*)&cfg_drv_act_ranges_apf, &ifbp->IFB_FWSup) )
) { /* 24 */
ifbp->IFB_CardStat |= CARD_STAT_INCOMP_FW;
rc = HCF_ERR_INCOMP_FW;
}
}
#endif // MSF_COMPONENT_ID
if ( rc == HCF_SUCCESS && ifbp->IFB_FWIdentity.comp_id >= COMP_ID_FW_STA ) {
PROT_CNT_INI;
/**************************************************************************************
* rlav: the DMA engine needs the host to cause a 'hanging alloc event' for it to consume.
* not sure if this is the right spot in the HCF, thinking about hcf_enable...
**************************************************************************************/
rc = cmd_exe( ifbp, HCMD_ALLOC, 0 );
// 180 degree error in logic ;? #if ALLOC_15
// ifbp->IFB_RscInd = 1; //let's hope that by the time hcf_send_msg isa called, there will be a FID
//#else
if ( rc == HCF_SUCCESS ) {
HCF_WAIT_WHILE( (IPW( HREG_EV_STAT ) & HREG_EV_ALLOC) == 0 );
IF_PROT_TIME( HCFASSERT(prot_cnt, IPW( HREG_EV_STAT )) );
#if HCF_DMA
if ( ! ( ifbp->IFB_CntlOpt & USE_DMA ) )
#endif // HCF_DMA
{
ifbp->IFB_RscInd = get_fid( ifbp );
HCFASSERT( ifbp->IFB_RscInd, 0 );
cmd_exe( ifbp, HCMD_ALLOC, 0 );
IF_PROT_TIME( if ( prot_cnt == 0 ) rc = HCF_ERR_TIME_OUT );
}
}
//#endif // ALLOC_15
}
HCFASSERT( rc == HCF_SUCCESS, rc );
HCFLOGEXIT( HCF_TRACE_INIT );
return rc;
} // init
/************************************************************************************************************
*
*.SUBMODULE void isr_info( IFBP ifbp )
*.PURPOSE handles link events.
*
*.ARGUMENTS
* ifbp address of the Interface Block
*
*.RETURNS N.A.
*
*.DESCRIPTION
*
*
*.DIAGRAM
*1: First the FID number corresponding with the InfoEvent is determined.
* Note the complication of the zero-FID protection sub-scheme in DAWA.
* Next the L-field and the T-field are fetched into scratch buffer info.
*2: In case of tallies, the 16 bits Hermes values are accumulated in the IFB into 32 bits values. Info[0]
* is (expected to be) HCF_NIC_TAL_CNT + 1. The contraption "while ( info[0]-- >1 )" rather than
* "while ( --info[0] )" is used because it is dangerous to determine the length of the Value field by
* decrementing info[0]. As a result of a bug in some version of the F/W, info[0] may be 0, resulting
* in a very long loop in the pre-decrement logic.
*4: In case of a link status frame, the information is copied to the IFB field IFB_linkStat
*6: All other than Tallies (including "unknown" ones) are checked against the selection set by the MSF
* via CFG_RID_LOG. If a match is found or the selection set has the wild-card type (i.e non-NULL buffer
* pointer at the terminating zero-type), the frame is copied to the (type-specific) log buffer.
* Note that to accumulate tallies into IFB AND to log them or to log a frame when a specific match occures
* AND based on the wild-card selection, you have to call setup_bap again after the 1st copy.
*
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
HCF_STATIC void
isr_info( IFBP ifbp )
{
hcf_16 info[2], fid;
#if (HCF_EXT) & HCF_EXT_INFO_LOG
RID_LOGP ridp = ifbp->IFB_RIDLogp; //NULL or pointer to array of RID_LOG structures (terminated by zero typ)
#endif // HCF_EXT_INFO_LOG
HCFTRACE( ifbp, HCF_TRACE_ISR_INFO ); /* 1 */
fid = IPW( HREG_INFO_FID );
DAWA_ZERO_FID( HREG_INFO_FID );
if ( fid ) {
(void)setup_bap( ifbp, fid, 0, IO_IN );
get_frag( ifbp, (wci_bufp)info, 4 BE_PAR(2) );
HCFASSERT( info[0] <= HCF_MAX_LTV + 1, MERGE_2( info[1], info[0] ) ); //;? a smaller value makes more sense
#if (HCF_TALLIES) & HCF_TALLIES_NIC //Hermes tally support
if ( info[1] == CFG_TALLIES ) {
hcf_32 *p;
/*2*/ if ( info[0] > HCF_NIC_TAL_CNT ) {
info[0] = HCF_NIC_TAL_CNT + 1;
}
p = (hcf_32*)&ifbp->IFB_NIC_Tallies;
while ( info[0]-- >1 ) *p++ += IPW( HREG_DATA_1 ); //request may return zero length
}
else
#endif // HCF_TALLIES_NIC
{
/*4*/ if ( info[1] == CFG_LINK_STAT ) {
ifbp->IFB_LinkStat = IPW( HREG_DATA_1 );
}
#if (HCF_EXT) & HCF_EXT_INFO_LOG
/*6*/ while ( 1 ) {
if ( ridp->typ == 0 || ridp->typ == info[1] ) {
if ( ridp->bufp ) {
HCFASSERT( ridp->len >= 2, ridp->typ );
ridp->bufp[0] = min((hcf_16)(ridp->len - 1), info[0] ); //save L
ridp->bufp[1] = info[1]; //save T
get_frag( ifbp, (wci_bufp)&ridp->bufp[2], (ridp->bufp[0] - 1)*2 BE_PAR(0) );
}
break;
}
ridp++;
}
#endif // HCF_EXT_INFO_LOG
}
HCFTRACE( ifbp, HCF_TRACE_ISR_INFO | HCF_TRACE_EXIT );
}
return;
} // isr_info
//
//
// #endif // HCF_TALLIES_NIC
// /*4*/ if ( info[1] == CFG_LINK_STAT ) {
// ifbp->IFB_DSLinkStat = IPW( HREG_DATA_1 ) | CFG_LINK_STAT_CHANGE; //corrupts BAP !! ;?
// ifbp->IFB_LinkStat = ifbp->IFB_DSLinkStat & CFG_LINK_STAT_FW; //;? to be obsoleted
// printk(KERN_ERR "linkstatus: %04x\n", ifbp->IFB_DSLinkStat ); //;?remove me 1 day
// #if (HCF_SLEEP) & HCF_DDS
// if ( ( ifbp->IFB_DSLinkStat & CFG_LINK_STAT_CONNECTED ) == 0 ) { //even values are disconnected etc.
// ifbp->IFB_TickCnt = 0; //start 2 second period (with 1 tick uncertanty)
// printk(KERN_NOTICE "isr_info: AwaitConnection phase started, IFB_TickCnt = 0\n" ); //;?remove me 1 day
// }
// #endif // HCF_DDS
// }
// #if (HCF_EXT) & HCF_EXT_INFO_LOG
// /*6*/ while ( 1 ) {
// if ( ridp->typ == 0 || ridp->typ == info[1] ) {
// if ( ridp->bufp ) {
// HCFASSERT( ridp->len >= 2, ridp->typ );
// (void)setup_bap( ifbp, fid, 2, IO_IN ); //restore BAP for tallies, linkstat and specific type followed by wild card
// ridp->bufp[0] = min( ridp->len - 1, info[0] ); //save L
// get_frag( ifbp, (wci_bufp)&ridp->bufp[1], ridp->bufp[0]*2 BE_PAR(0) );
// }
// break; //;?this break is no longer needed due to setup_bap but lets concentrate on DDS first
// }
// ridp++;
// }
// #endif // HCF_EXT_INFO_LOG
// }
// HCFTRACE( ifbp, HCF_TRACE_ISR_INFO | HCF_TRACE_EXIT );
//
//
//
//
// return;
//} // isr_info
/************************************************************************************************************
*
*.SUBMODULE void mdd_assert( IFBP ifbp, unsigned int line_number, hcf_32 q )
*.PURPOSE filters assert on level and interfaces to the MSF supplied msf_assert routine.
*
*.ARGUMENTS
* ifbp address of the Interface Block
* line_number line number of the line which caused the assert
* q qualifier, additional information which may give a clue about the problem
*
*.RETURNS N.A.
*
*.DESCRIPTION
*
*
*.DIAGRAM
*
*.NOTICE
* mdd_assert has been through a turmoil, renaming hcf_assert to assert and hcf_assert again and supporting off
* and on being called from the MSF level and other ( immature ) ModularDriverDevelopment modules like DHF and
* MMD.
* !!!! The assert routine is not an hcf_..... routine in the sense that it may be called by the MSF,
* however it is called from mmd.c and dhf.c, so it must be external.
* To prevent namespace pollution it needs a prefix, to prevent that MSF programmers think that
* they are allowed to call the assert logic, the prefix HCF can't be used, so MDD is selected!!!!
*
* When called from the DHF module the line number is incremented by DHF_FILE_NAME_OFFSET and when called from
* the MMD module by MMD_FILE_NAME_OFFSET.
*
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
#if HCF_ASSERT
void
mdd_assert( IFBP ifbp, unsigned int line_number, hcf_32 q )
{
hcf_16 run_time_flag = ifbp->IFB_AssertLvl;
if ( run_time_flag /* > ;?????? */ ) { //prevent recursive behavior, later to be extended to level filtering
ifbp->IFB_AssertQualifier = q;
ifbp->IFB_AssertLine = (hcf_16)line_number;
#if (HCF_ASSERT) & ( HCF_ASSERT_LNK_MSF_RTN | HCF_ASSERT_RT_MSF_RTN )
if ( ifbp->IFB_AssertRtn ) {
ifbp->IFB_AssertRtn( line_number, ifbp->IFB_AssertTrace, q );
}
#endif // HCF_ASSERT_LNK_MSF_RTN / HCF_ASSERT_RT_MSF_RTN
#if (HCF_ASSERT) & HCF_ASSERT_SW_SUP
OPW( HREG_SW_2, line_number );
OPW( HREG_SW_2, ifbp->IFB_AssertTrace );
OPW( HREG_SW_2, (hcf_16)q );
OPW( HREG_SW_2, (hcf_16)(q >> 16 ) );
#endif // HCF_ASSERT_SW_SUP
#if (HCF_ASSERT) & HCF_ASSERT_MB
ifbp->IFB_AssertLvl = 0; // prevent recursive behavior
hcf_put_info( ifbp, (LTVP)&ifbp->IFB_AssertStrct );
ifbp->IFB_AssertLvl = run_time_flag; // restore appropriate filter level
#endif // HCF_ASSERT_MB
}
} // mdd_assert
#endif // HCF_ASSERT
/************************************************************************************************************
*
*.SUBMODULE void put_frag( IFBP ifbp, wci_bufp bufp, int len BE_PAR( int word_len ) )
*.PURPOSE writes with 16/32 bit I/O via BAP1 port from Host memory to NIC RAM.
*
*.ARGUMENTS
* ifbp address of the Interface Block
* bufp (byte) address of buffer
* len length in bytes of buffer specified by bufp
* word_len Big Endian only: number of leading bytes to swap in pairs
*
*.RETURNS N.A.
*
*.DESCRIPTION
* process the single byte (if applicable) not yet written by the previous put_frag and copy len
* (or len-1) bytes from bufp to NIC.
*
*
*.DIAGRAM
*
*.NOTICE
* It turns out DOS ODI uses zero length fragments. The HCF code can cope with it, but as a consequence, no
* Assert on len is possible
*
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
HCF_STATIC void
put_frag( IFBP ifbp, wci_bufp bufp, int len BE_PAR( int word_len ) )
{
hcf_io io_port = ifbp->IFB_IOBase + HREG_DATA_1; //BAP data register
int i; //prevent side effects from macro
hcf_16 j;
HCFASSERT( ((hcf_32)bufp & (HCF_ALIGN-1) ) == 0, (hcf_32)bufp );
#if HCF_BIG_ENDIAN
HCFASSERT( word_len == 0 || word_len == 2 || word_len == 4, word_len );
HCFASSERT( word_len == 0 || ((hcf_32)bufp & 1 ) == 0, (hcf_32)bufp );
HCFASSERT( word_len <= len, MERGE_2( word_len, len ) );
if ( word_len ) { //if there is anything to convert
//. convert and write the 1st hcf_16
j = bufp[1] | bufp[0]<<8;
OUT_PORT_WORD( io_port, j );
//. update pointer and counter accordingly
len -= 2;
bufp += 2;
if ( word_len > 1 ) { //. if there is to convert more than 1 word ( i.e 2 )
//. . convert and write the 2nd hcf_16
j = bufp[1] | bufp[0]<<8; /*bufp is already incremented by 2*/
OUT_PORT_WORD( io_port, j );
//. . update pointer and counter accordingly
len -= 2;
bufp += 2;
}
}
#endif // HCF_BIG_ENDIAN
i = len;
if ( i && ifbp->IFB_CarryOut ) { //skip zero-length
j = ((*bufp)<<8) + ( ifbp->IFB_CarryOut & 0xFF );
OUT_PORT_WORD( io_port, j );
bufp++; i--;
ifbp->IFB_CarryOut = 0;
}
#if (HCF_IO) & HCF_IO_32BITS
//skip zero-length I/O, single byte I/O and I/O not worthwhile (i.e. less than 6 bytes)for DW logic
//if buffer length >= 6 and 32 bits I/O support
if ( !(ifbp->IFB_CntlOpt & USE_16BIT) && i >= 6 ) {
hcf_32 FAR *p4; //prevent side effects from macro
if ( ( (hcf_32)bufp & 0x1 ) == 0 ) { //. if buffer at least word aligned
if ( (hcf_32)bufp & 0x2 ) { //. . if buffer not double word aligned
//. . . write a single word to get double word aligned
j = *(wci_recordp)bufp; //just to help ease writing macros with embedded assembly
OUT_PORT_WORD( io_port, j );
//. . . adjust buffer length and pointer accordingly
bufp += 2; i -= 2;
}
//. . write as many double word as possible
p4 = (hcf_32 FAR *)bufp;
j = (hcf_16)i/4;
OUT_PORT_STRING_32( io_port, p4, j );
//. . adjust buffer length and pointer accordingly
bufp += i & ~0x0003;
i &= 0x0003;
}
}
#endif // HCF_IO_32BITS
//if no 32-bit support OR byte aligned OR 1 word left
if ( i ) {
//. if odd number of bytes left
if ( i & 0x0001 ) {
//. . save left over byte (before bufp is corrupted) in carry, set carry flag
ifbp->IFB_CarryOut = (hcf_16)bufp[i-1] | 0x0100; //note that i and bufp are always simultaneously modified, &bufp[i-1] is invariant
}
//. write as many word as possible in "alignment safe" way
j = (hcf_16)i/2;
OUT_PORT_STRING_8_16( io_port, bufp, j );
}
} // put_frag
/************************************************************************************************************
*
*.SUBMODULE void put_frag_finalize( IFBP ifbp )
*.PURPOSE cleanup after put_frag for trailing odd byte and MIC transfer to NIC.
*
*.ARGUMENTS
* ifbp address of the Interface Block
*
*.RETURNS N.A.
*
*.DESCRIPTION
* finalize the MIC calculation with the padding pattern, output the last byte (if applicable)
* of the message and the MIC to the TxFS
*
*
*.DIAGRAM
*2: 1 byte of the last put_frag may be still in IFB_CarryOut ( the put_frag carry holder ), so ........
* 1 - 3 bytes of the last put_frag may be still in IFB_tx_32 ( the MIC engine carry holder ), so ........
* The call to the MIC calculation routine feeds these remaining bytes (if any) of put_frag and the
* just as many bytes of the padding as needed to the MIC calculation engine. Note that the "unneeded" pad
* bytes simply end up in the MIC engine carry holder and are never used.
*8: write the remainder of the MIC and possible some garbage to NIC RAM
* Note: i is always 4 (a loop-invariant of the while in point 2)
*
*.NOTICE
*
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
HCF_STATIC void
put_frag_finalize( IFBP ifbp )
{
#if (HCF_TYPE) & HCF_TYPE_WPA
if ( ifbp->IFB_MICTxCarry != 0xFFFF) { //if MIC calculation active
CALC_TX_MIC( mic_pad, 8); //. feed (up to 8 bytes of) virtual padding to MIC engine
//. write (possibly) trailing byte + (most of) MIC
put_frag( ifbp, (wci_bufp)ifbp->IFB_MICTx, 8 BE_PAR(0) );
}
#endif // HCF_TYPE_WPA
put_frag( ifbp, null_addr, 1 BE_PAR(0) ); //write (possibly) trailing data or MIC byte
} // put_frag_finalize
/************************************************************************************************************
*
*.SUBMODULE int put_info( IFBP ifbp, LTVP ltvp )
*.PURPOSE support routine to handle the "basic" task of hcf_put_info to pass RIDs to the NIC.
*
*.ARGUMENTS
* ifbp address of the Interface Block
* ltvp address in NIC RAM where LVT-records are located
*
*.RETURNS
* HCF_SUCCESS
* >>put_frag
* >>cmd_wait
*
*.DESCRIPTION
*
*
*.DIAGRAM
*20: do not write RIDs to NICs which have incompatible Firmware
*24: If the RID does not exist, the L-field is set to zero.
* Note that some RIDs can not be read, e.g. the pseudo RIDs for direct Hermes commands and CFG_DEFAULT_KEYS
*28: If the RID is written successful, pass it to the NIC by means of an Access Write command
*
*.NOTICE
* The mechanism to HCF_ASSERT on invalid typ-codes in the LTV record is based on the following strategy:
* - some codes (e.g. CFG_REG_MB) are explicitly handled by the HCF which implies that these codes
* are valid. These codes are already consumed by hcf_put_info.
* - all other codes are passed to the Hermes. Before the put action is executed, hcf_get_info is called
* with an LTV record with a value of 1 in the L-field and the intended put action type in the Typ-code
* field. If the put action type is valid, it is also valid as a get action type code - except
* for CFG_DEFAULT_KEYS and CFG_ADD_TKIP_DEFAULT_KEY - so the HCF_ASSERT logic of hcf_get_info should
* not catch.
*
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
HCF_STATIC int
put_info( IFBP ifbp, LTVP ltvp )
{
int rc = HCF_SUCCESS;
HCFASSERT( ifbp->IFB_CardStat == 0, MERGE_2( ltvp->typ, ifbp->IFB_CardStat ) );
HCFASSERT( CFG_RID_CFG_MIN <= ltvp->typ && ltvp->typ <= CFG_RID_CFG_MAX, ltvp->typ );
if ( ifbp->IFB_CardStat == 0 && /* 20*/
( ( CFG_RID_CFG_MIN <= ltvp->typ && ltvp->typ <= CFG_RID_CFG_MAX ) ||
( CFG_RID_ENG_MIN <= ltvp->typ /* && ltvp->typ <= 0xFFFF */ ) ) ) {
#if HCF_ASSERT //FCC8, FCB0, FCB4, FCB6, FCB7, FCB8, FCC0, FCC4, FCBC, FCBD, FCBE, FCBF
{
hcf_16 t = ltvp->typ;
LTV_STRCT x = { 2, t, {0} }; /*24*/
hcf_get_info( ifbp, (LTVP)&x );
if ( x.len == 0 &&
( t != CFG_DEFAULT_KEYS && t != CFG_ADD_TKIP_DEFAULT_KEY && t != CFG_REMOVE_TKIP_DEFAULT_KEY &&
t != CFG_ADD_TKIP_MAPPED_KEY && t != CFG_REMOVE_TKIP_MAPPED_KEY &&
t != CFG_HANDOVER_ADDR && t != CFG_DISASSOCIATE_ADDR &&
t != CFG_FCBC && t != CFG_FCBD && t != CFG_FCBE && t != CFG_FCBF &&
t != CFG_DEAUTHENTICATE_ADDR
)
) {
HCFASSERT( DO_ASSERT, ltvp->typ );
}
}
#endif // HCF_ASSERT
rc = setup_bap( ifbp, ltvp->typ, 0, IO_OUT );
put_frag( ifbp, (wci_bufp)ltvp, 2*ltvp->len + 2 BE_PAR(2) );
/*28*/ if ( rc == HCF_SUCCESS ) {
rc = cmd_exe( ifbp, HCMD_ACCESS + HCMD_ACCESS_WRITE, ltvp->typ );
}
}
return rc;
} // put_info
/************************************************************************************************************
*
*.SUBMODULE int put_info_mb( IFBP ifbp, CFG_MB_INFO_STRCT FAR * ltvp )
*.PURPOSE accumulates a ( series of) buffers into a single Info block into the MailBox.
*
*.ARGUMENTS
* ifbp address of the Interface Block
* ltvp address of structure specifying the "type" and the fragments of the information to be synthesized
* as an LTV into the MailBox
*
*.RETURNS
*
*.DESCRIPTION
* If the data does not fit (including no MailBox is available), the IFB_MBTally is incremented and an
* error status is returned.
* HCF_ASSERT does not catch.
* Calling put_info_mb when their is no MailBox available, is considered a design error in the MSF.
*
* Note that there is always at least 1 word of unused space in the mail box.
* As a consequence:
* - no problem in pointer arithmetic (MB_RP == MB_WP means unambiguously mail box is completely empty
* - There is always free space to write an L field with a value of zero after each MB_Info block. This
* allows for an easy scan mechanism in the "get MB_Info block" logic.
*
*
*.DIAGRAM
*1: Calculate L field of the MBIB, i.e. 1 for the T-field + the cumulative length of the fragments.
*2: The free space in the MailBox is calculated (2a: free part from Write Ptr to Read Ptr, 2b: free part
* turns out to wrap around) . If this space suffices to store the number of words reflected by len (T-field
* + Value-field) plus the additional MailBox Info L-field + a trailing 0 to act as the L-field of a trailing
* dummy or empty LTV record, then a MailBox Info block is build in the MailBox consisting of
* - the value len in the first word
* - type in the second word
* - a copy of the contents of the fragments in the second and higher word
*
*4: Since put_info_mb() can more or less directly be called from the MSF level, the I/F must be robust
* against out-of-range variables. As failsafe coding, the MB update is skipped by changing tlen to 0 if
* len == 0; This will indirectly cause an assert as result of the violation of the next if clause.
*6: Check whether the free space in MailBox suffices (this covers the complete absence of the MailBox).
* Note that len is unsigned, so even MSF I/F violation works out O.K.
* The '2' in the expression "len+2" is used because 1 word is needed for L itself and 1 word is needed
* for the zero-sentinel
*8: update MailBox Info length report to MSF with "oldest" MB Info Block size. Be careful here, if you get
* here before the MailBox is registered, you can't read from the buffer addressed by IFB_MBp (it is the
* Null buffer) so don't move this code till the end of this routine but keep it where there is garuanteed
* a buffer.
*
*.NOTICE
* boundary testing depends on the fact that IFB_MBSize is guaranteed to be zero if no MailBox is present,
* and to a lesser degree, that IFB_MBWp = IFB_MBRp = 0
*
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
HCF_STATIC int
put_info_mb( IFBP ifbp, CFG_MB_INFO_STRCT FAR * ltvp )
{
int rc = HCF_SUCCESS;
hcf_16 i; //work counter
hcf_16 *dp; //destination pointer (in MailBox)
wci_recordp sp; //source pointer
hcf_16 len; //total length to copy to MailBox
hcf_16 tlen; //free length/working length/offset in WMP frame
if ( ifbp->IFB_MBp == NULL ) return rc; //;?not sufficient
HCFASSERT( ifbp->IFB_MBp != NULL, 0 ); //!!!be careful, don't get into an endless recursion
HCFASSERT( ifbp->IFB_MBSize, 0 );
len = 1; /* 1 */
for ( i = 0; i < ltvp->frag_cnt; i++ ) {
len += ltvp->frag_buf[i].frag_len;
}
if ( ifbp->IFB_MBRp > ifbp->IFB_MBWp ) {
tlen = ifbp->IFB_MBRp - ifbp->IFB_MBWp; /* 2a*/
} else {
if ( ifbp->IFB_MBRp == ifbp->IFB_MBWp ) {
ifbp->IFB_MBRp = ifbp->IFB_MBWp = 0; // optimize Wrapping
}
tlen = ifbp->IFB_MBSize - ifbp->IFB_MBWp; /* 2b*/
if ( ( tlen <= len + 2 ) && ( len + 2 < ifbp->IFB_MBRp ) ) { //if trailing space is too small but
// leading space is sufficiently large
ifbp->IFB_MBp[ifbp->IFB_MBWp] = 0xFFFF; //flag dummy LTV to fill the trailing space
ifbp->IFB_MBWp = 0; //reset WritePointer to begin of MailBox
tlen = ifbp->IFB_MBRp; //get new available space size
}
}
dp = &ifbp->IFB_MBp[ifbp->IFB_MBWp];
if ( len == 0 ) {
tlen = 0; //;? what is this good for
}
if ( len + 2 >= tlen ){ /* 6 */
//Do Not ASSERT, this is a normal condition
IF_TALLY( ifbp->IFB_HCF_Tallies.NoBufMB++ );
rc = HCF_ERR_LEN;
} else {
*dp++ = len; //write Len (= size of T+V in words to MB_Info block
*dp++ = ltvp->base_typ; //write Type to MB_Info block
ifbp->IFB_MBWp += len + 1; //update WritePointer of MailBox
for ( i = 0; i < ltvp->frag_cnt; i++ ) { // process each of the fragments
sp = ltvp->frag_buf[i].frag_addr;
len = ltvp->frag_buf[i].frag_len;
while ( len-- ) *dp++ = *sp++;
}
ifbp->IFB_MBp[ifbp->IFB_MBWp] = 0; //to assure get_info for CFG_MB_INFO stops
ifbp->IFB_MBInfoLen = ifbp->IFB_MBp[ifbp->IFB_MBRp]; /* 8 */
}
return rc;
} // put_info_mb
/************************************************************************************************************
*
*.SUBMODULE int setup_bap( IFBP ifbp, hcf_16 fid, int offset, int type )
*.PURPOSE set up data access to NIC RAM via BAP_1.
*
*.ARGUMENTS
* ifbp address of I/F Block
* fid FID/RID
* offset !!even!! offset in FID/RID
* type IO_IN, IO_OUT
*
*.RETURNS
* HCF_SUCCESS O.K
* HCF_ERR_NO_NIC card is removed
* HCF_ERR_DEFUNCT_TIME_OUT Fatal malfunction detected
* HCF_ERR_DEFUNCT_..... if and only if IFB_DefunctStat <> 0
*
*.DESCRIPTION
*
* A non-zero return status indicates:
* - the NIC is considered nonoperational, e.g. due to a time-out of some Hermes activity in the past
* - BAP_1 could not properly be initialized
* - the card is removed before completion of the data transfer
* In all other cases, a zero is returned.
* BAP Initialization failure indicates an H/W error which is very likely to signal complete H/W failure.
* Once a BAP Initialization failure has occurred all subsequent interactions with the Hermes will return a
* "defunct" status till the Hermes is re-initialized by means of an hcf_connect.
*
* A BAP is a set of registers (Offset, Select and Data) offering read/write access to a particular FID or
* RID. This access is based on a auto-increment feature.
* There are two BAPs but these days the HCF uses only BAP_1 and leaves BAP_0 to the PCI Busmastering H/W.
*
* The BAP-mechanism is based on the Busy bit in the Offset register (see the Hermes definition). The waiting
* for Busy must occur between writing the Offset register and accessing the Data register. The
* implementation to wait for the Busy bit drop after each write to the Offset register, implies that the
* requirement that the Busy bit is low before the Select register is written, is automatically met.
* BAP-setup may be time consuming (e.g. 380 usec for large offsets occurs frequently). The wait for Busy bit
* drop is protected by a loop counter, which is initialized with IFB_TickIni, which is calibrated in init.
*
* The NIC I/F is optimized for word transfer and can only handle word transfer at a word boundary in NIC
* RAM. The intended solution for transfer of a single byte has multiple H/W flaws. There have been different
* S/W Workaround strategies. RID access is hcf_16 based by "nature", so no byte access problems. For Tx/Rx
* FID access, the byte logic became obsolete by absorbing it in the double word oriented nature of the MIC
* feature.
*
*
*.DIAGRAM
*
*2: the test on rc checks whether the HCF went into "defunct" mode ( e.g. BAP initialization or a call to
* cmd_wait did ever fail).
*4: the select register and offset register are set
* the offset register is monitored till a successful condition (no busy bit) is detected or till the
* (calibrated) protection counter expires
* If the counter expires, this is reflected in IFB_DefunctStat, so all subsequent calls to setup_bap fail
* immediately ( see 2)
*6: initialization of the carry as used by pet/get_frag
*8: HREG_OFFSET_ERR is ignored as error because:
* a: the Hermes is robust against it
* b: it is not known what causes it (probably a bug), hence no strategy can be specified which level is
* to handle this error in which way. In the past, it could be induced by the MSF level, e.g. by calling
* hcf_rcv_msg while there was no Rx-FID available. Since this is an MSF-error which is caught by ASSERT,
* there is no run-time action required by the HCF.
* Lumping the Offset error in with the Busy bit error, as has been done in the past turns out to be a
* disaster or a life saver, just depending on what the cause of the error is. Since no prediction can be
* done about the future, it is "felt" to be the best strategy to ignore this error. One day the code was
* accompanied by the following comment:
* // ignore HREG_OFFSET_ERR, someone, supposedly the MSF programmer ;) made a bug. Since we don't know
* // what is going on, we might as well go on - under management pressure - by ignoring it
*
*.ENDDOC END DOCUMENTATION
*
************************************************************************************************************/
HCF_STATIC int
setup_bap( IFBP ifbp, hcf_16 fid, int offset, int type )
{
PROT_CNT_INI;
int rc;
HCFTRACE( ifbp, HCF_TRACE_STRIO );
rc = ifbp->IFB_DefunctStat;
if (rc == HCF_SUCCESS) { /*2*/
OPW( HREG_SELECT_1, fid ); /*4*/
OPW( HREG_OFFSET_1, offset );
if ( type == IO_IN ) {
ifbp->IFB_CarryIn = 0;
}
else ifbp->IFB_CarryOut = 0;
HCF_WAIT_WHILE( IPW( HREG_OFFSET_1) & HCMD_BUSY );
HCFASSERT( !( IPW( HREG_OFFSET_1) & HREG_OFFSET_ERR ), MERGE_2( fid, offset ) ); /*8*/
if ( prot_cnt == 0 ) {
HCFASSERT( DO_ASSERT, MERGE_2( fid, offset ) );
rc = ifbp->IFB_DefunctStat = HCF_ERR_DEFUNCT_TIME_OUT;
ifbp->IFB_CardStat |= CARD_STAT_DEFUNCT;
}
}
HCFTRACE( ifbp, HCF_TRACE_STRIO | HCF_TRACE_EXIT );
return rc;
} // setup_bap
| gpl-2.0 |
GameTheory-/android_kernel_lge_l1m | sound/soc/codecs/wm1250-ev1.c | 2767 | 2773 | /*
* Driver for the 1250-EV1 audio I/O module
*
* Copyright 2011 Wolfson Microelectronics plc
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/i2c.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
static const struct snd_soc_dapm_widget wm1250_ev1_dapm_widgets[] = {
SND_SOC_DAPM_ADC("ADC", "wm1250-ev1 Capture", SND_SOC_NOPM, 0, 0),
SND_SOC_DAPM_DAC("DAC", "wm1250-ev1 Playback", SND_SOC_NOPM, 0, 0),
SND_SOC_DAPM_INPUT("WM1250 Input"),
SND_SOC_DAPM_OUTPUT("WM1250 Output"),
};
static const struct snd_soc_dapm_route wm1250_ev1_dapm_routes[] = {
{ "ADC", NULL, "WM1250 Input" },
{ "WM1250 Output", NULL, "DAC" },
};
static struct snd_soc_dai_driver wm1250_ev1_dai = {
.name = "wm1250-ev1",
.playback = {
.stream_name = "Playback",
.channels_min = 1,
.channels_max = 1,
.rates = SNDRV_PCM_RATE_8000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
},
.capture = {
.stream_name = "Capture",
.channels_min = 1,
.channels_max = 1,
.rates = SNDRV_PCM_RATE_8000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
},
};
static struct snd_soc_codec_driver soc_codec_dev_wm1250_ev1 = {
.dapm_widgets = wm1250_ev1_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(wm1250_ev1_dapm_widgets),
.dapm_routes = wm1250_ev1_dapm_routes,
.num_dapm_routes = ARRAY_SIZE(wm1250_ev1_dapm_routes),
};
static int __devinit wm1250_ev1_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
return snd_soc_register_codec(&i2c->dev, &soc_codec_dev_wm1250_ev1,
&wm1250_ev1_dai, 1);
}
static int __devexit wm1250_ev1_remove(struct i2c_client *i2c)
{
snd_soc_unregister_codec(&i2c->dev);
return 0;
}
static const struct i2c_device_id wm1250_ev1_i2c_id[] = {
{ "wm1250-ev1", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, wm1250_ev1_i2c_id);
static struct i2c_driver wm1250_ev1_i2c_driver = {
.driver = {
.name = "wm1250-ev1",
.owner = THIS_MODULE,
},
.probe = wm1250_ev1_probe,
.remove = __devexit_p(wm1250_ev1_remove),
.id_table = wm1250_ev1_i2c_id,
};
static int __init wm1250_ev1_modinit(void)
{
int ret = 0;
ret = i2c_add_driver(&wm1250_ev1_i2c_driver);
if (ret != 0)
pr_err("Failed to register WM1250-EV1 I2C driver: %d\n", ret);
return ret;
}
module_init(wm1250_ev1_modinit);
static void __exit wm1250_ev1_exit(void)
{
i2c_del_driver(&wm1250_ev1_i2c_driver);
}
module_exit(wm1250_ev1_exit);
MODULE_AUTHOR("Mark Brown <broonie@opensource.wolfsonmicro.com>");
MODULE_DESCRIPTION("WM1250-EV1 audio I/O module driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Trinityhaxxor/Trinity_Kernel_msm8660_XperiaS | drivers/media/video/mt9p031.c | 4815 | 25843 | /*
* Driver for MT9P031 CMOS Image Sensor from Aptina
*
* Copyright (C) 2011, Laurent Pinchart <laurent.pinchart@ideasonboard.com>
* Copyright (C) 2011, Javier Martin <javier.martin@vista-silicon.com>
* Copyright (C) 2011, Guennadi Liakhovetski <g.liakhovetski@gmx.de>
*
* Based on the MT9V032 driver and Bastian Hecht's code.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/log2.h>
#include <linux/pm.h>
#include <linux/slab.h>
#include <linux/videodev2.h>
#include <media/mt9p031.h>
#include <media/v4l2-chip-ident.h>
#include <media/v4l2-ctrls.h>
#include <media/v4l2-device.h>
#include <media/v4l2-subdev.h>
#include "aptina-pll.h"
#define MT9P031_PIXEL_ARRAY_WIDTH 2752
#define MT9P031_PIXEL_ARRAY_HEIGHT 2004
#define MT9P031_CHIP_VERSION 0x00
#define MT9P031_CHIP_VERSION_VALUE 0x1801
#define MT9P031_ROW_START 0x01
#define MT9P031_ROW_START_MIN 0
#define MT9P031_ROW_START_MAX 2004
#define MT9P031_ROW_START_DEF 54
#define MT9P031_COLUMN_START 0x02
#define MT9P031_COLUMN_START_MIN 0
#define MT9P031_COLUMN_START_MAX 2750
#define MT9P031_COLUMN_START_DEF 16
#define MT9P031_WINDOW_HEIGHT 0x03
#define MT9P031_WINDOW_HEIGHT_MIN 2
#define MT9P031_WINDOW_HEIGHT_MAX 2006
#define MT9P031_WINDOW_HEIGHT_DEF 1944
#define MT9P031_WINDOW_WIDTH 0x04
#define MT9P031_WINDOW_WIDTH_MIN 2
#define MT9P031_WINDOW_WIDTH_MAX 2752
#define MT9P031_WINDOW_WIDTH_DEF 2592
#define MT9P031_HORIZONTAL_BLANK 0x05
#define MT9P031_HORIZONTAL_BLANK_MIN 0
#define MT9P031_HORIZONTAL_BLANK_MAX 4095
#define MT9P031_VERTICAL_BLANK 0x06
#define MT9P031_VERTICAL_BLANK_MIN 0
#define MT9P031_VERTICAL_BLANK_MAX 4095
#define MT9P031_VERTICAL_BLANK_DEF 25
#define MT9P031_OUTPUT_CONTROL 0x07
#define MT9P031_OUTPUT_CONTROL_CEN 2
#define MT9P031_OUTPUT_CONTROL_SYN 1
#define MT9P031_OUTPUT_CONTROL_DEF 0x1f82
#define MT9P031_SHUTTER_WIDTH_UPPER 0x08
#define MT9P031_SHUTTER_WIDTH_LOWER 0x09
#define MT9P031_SHUTTER_WIDTH_MIN 1
#define MT9P031_SHUTTER_WIDTH_MAX 1048575
#define MT9P031_SHUTTER_WIDTH_DEF 1943
#define MT9P031_PLL_CONTROL 0x10
#define MT9P031_PLL_CONTROL_PWROFF 0x0050
#define MT9P031_PLL_CONTROL_PWRON 0x0051
#define MT9P031_PLL_CONTROL_USEPLL 0x0052
#define MT9P031_PLL_CONFIG_1 0x11
#define MT9P031_PLL_CONFIG_2 0x12
#define MT9P031_PIXEL_CLOCK_CONTROL 0x0a
#define MT9P031_FRAME_RESTART 0x0b
#define MT9P031_SHUTTER_DELAY 0x0c
#define MT9P031_RST 0x0d
#define MT9P031_RST_ENABLE 1
#define MT9P031_RST_DISABLE 0
#define MT9P031_READ_MODE_1 0x1e
#define MT9P031_READ_MODE_2 0x20
#define MT9P031_READ_MODE_2_ROW_MIR (1 << 15)
#define MT9P031_READ_MODE_2_COL_MIR (1 << 14)
#define MT9P031_READ_MODE_2_ROW_BLC (1 << 6)
#define MT9P031_ROW_ADDRESS_MODE 0x22
#define MT9P031_COLUMN_ADDRESS_MODE 0x23
#define MT9P031_GLOBAL_GAIN 0x35
#define MT9P031_GLOBAL_GAIN_MIN 8
#define MT9P031_GLOBAL_GAIN_MAX 1024
#define MT9P031_GLOBAL_GAIN_DEF 8
#define MT9P031_GLOBAL_GAIN_MULT (1 << 6)
#define MT9P031_ROW_BLACK_DEF_OFFSET 0x4b
#define MT9P031_TEST_PATTERN 0xa0
#define MT9P031_TEST_PATTERN_SHIFT 3
#define MT9P031_TEST_PATTERN_ENABLE (1 << 0)
#define MT9P031_TEST_PATTERN_DISABLE (0 << 0)
#define MT9P031_TEST_PATTERN_GREEN 0xa1
#define MT9P031_TEST_PATTERN_RED 0xa2
#define MT9P031_TEST_PATTERN_BLUE 0xa3
struct mt9p031 {
struct v4l2_subdev subdev;
struct media_pad pad;
struct v4l2_rect crop; /* Sensor window */
struct v4l2_mbus_framefmt format;
struct v4l2_ctrl_handler ctrls;
struct mt9p031_platform_data *pdata;
struct mutex power_lock; /* lock to protect power_count */
int power_count;
struct aptina_pll pll;
/* Registers cache */
u16 output_control;
u16 mode2;
};
static struct mt9p031 *to_mt9p031(struct v4l2_subdev *sd)
{
return container_of(sd, struct mt9p031, subdev);
}
static int mt9p031_read(struct i2c_client *client, u8 reg)
{
return i2c_smbus_read_word_swapped(client, reg);
}
static int mt9p031_write(struct i2c_client *client, u8 reg, u16 data)
{
return i2c_smbus_write_word_swapped(client, reg, data);
}
static int mt9p031_set_output_control(struct mt9p031 *mt9p031, u16 clear,
u16 set)
{
struct i2c_client *client = v4l2_get_subdevdata(&mt9p031->subdev);
u16 value = (mt9p031->output_control & ~clear) | set;
int ret;
ret = mt9p031_write(client, MT9P031_OUTPUT_CONTROL, value);
if (ret < 0)
return ret;
mt9p031->output_control = value;
return 0;
}
static int mt9p031_set_mode2(struct mt9p031 *mt9p031, u16 clear, u16 set)
{
struct i2c_client *client = v4l2_get_subdevdata(&mt9p031->subdev);
u16 value = (mt9p031->mode2 & ~clear) | set;
int ret;
ret = mt9p031_write(client, MT9P031_READ_MODE_2, value);
if (ret < 0)
return ret;
mt9p031->mode2 = value;
return 0;
}
static int mt9p031_reset(struct mt9p031 *mt9p031)
{
struct i2c_client *client = v4l2_get_subdevdata(&mt9p031->subdev);
int ret;
/* Disable chip output, synchronous option update */
ret = mt9p031_write(client, MT9P031_RST, MT9P031_RST_ENABLE);
if (ret < 0)
return ret;
ret = mt9p031_write(client, MT9P031_RST, MT9P031_RST_DISABLE);
if (ret < 0)
return ret;
return mt9p031_set_output_control(mt9p031, MT9P031_OUTPUT_CONTROL_CEN,
0);
}
static int mt9p031_pll_setup(struct mt9p031 *mt9p031)
{
static const struct aptina_pll_limits limits = {
.ext_clock_min = 6000000,
.ext_clock_max = 27000000,
.int_clock_min = 2000000,
.int_clock_max = 13500000,
.out_clock_min = 180000000,
.out_clock_max = 360000000,
.pix_clock_max = 96000000,
.n_min = 1,
.n_max = 64,
.m_min = 16,
.m_max = 255,
.p1_min = 1,
.p1_max = 128,
};
struct i2c_client *client = v4l2_get_subdevdata(&mt9p031->subdev);
struct mt9p031_platform_data *pdata = mt9p031->pdata;
mt9p031->pll.ext_clock = pdata->ext_freq;
mt9p031->pll.pix_clock = pdata->target_freq;
return aptina_pll_calculate(&client->dev, &limits, &mt9p031->pll);
}
static int mt9p031_pll_enable(struct mt9p031 *mt9p031)
{
struct i2c_client *client = v4l2_get_subdevdata(&mt9p031->subdev);
int ret;
ret = mt9p031_write(client, MT9P031_PLL_CONTROL,
MT9P031_PLL_CONTROL_PWRON);
if (ret < 0)
return ret;
ret = mt9p031_write(client, MT9P031_PLL_CONFIG_1,
(mt9p031->pll.m << 8) | (mt9p031->pll.n - 1));
if (ret < 0)
return ret;
ret = mt9p031_write(client, MT9P031_PLL_CONFIG_2, mt9p031->pll.p1 - 1);
if (ret < 0)
return ret;
usleep_range(1000, 2000);
ret = mt9p031_write(client, MT9P031_PLL_CONTROL,
MT9P031_PLL_CONTROL_PWRON |
MT9P031_PLL_CONTROL_USEPLL);
return ret;
}
static inline int mt9p031_pll_disable(struct mt9p031 *mt9p031)
{
struct i2c_client *client = v4l2_get_subdevdata(&mt9p031->subdev);
return mt9p031_write(client, MT9P031_PLL_CONTROL,
MT9P031_PLL_CONTROL_PWROFF);
}
static int mt9p031_power_on(struct mt9p031 *mt9p031)
{
/* Ensure RESET_BAR is low */
if (mt9p031->pdata->reset) {
mt9p031->pdata->reset(&mt9p031->subdev, 1);
usleep_range(1000, 2000);
}
/* Emable clock */
if (mt9p031->pdata->set_xclk)
mt9p031->pdata->set_xclk(&mt9p031->subdev,
mt9p031->pdata->ext_freq);
/* Now RESET_BAR must be high */
if (mt9p031->pdata->reset) {
mt9p031->pdata->reset(&mt9p031->subdev, 0);
usleep_range(1000, 2000);
}
return 0;
}
static void mt9p031_power_off(struct mt9p031 *mt9p031)
{
if (mt9p031->pdata->reset) {
mt9p031->pdata->reset(&mt9p031->subdev, 1);
usleep_range(1000, 2000);
}
if (mt9p031->pdata->set_xclk)
mt9p031->pdata->set_xclk(&mt9p031->subdev, 0);
}
static int __mt9p031_set_power(struct mt9p031 *mt9p031, bool on)
{
struct i2c_client *client = v4l2_get_subdevdata(&mt9p031->subdev);
int ret;
if (!on) {
mt9p031_power_off(mt9p031);
return 0;
}
ret = mt9p031_power_on(mt9p031);
if (ret < 0)
return ret;
ret = mt9p031_reset(mt9p031);
if (ret < 0) {
dev_err(&client->dev, "Failed to reset the camera\n");
return ret;
}
return v4l2_ctrl_handler_setup(&mt9p031->ctrls);
}
/* -----------------------------------------------------------------------------
* V4L2 subdev video operations
*/
static int mt9p031_set_params(struct mt9p031 *mt9p031)
{
struct i2c_client *client = v4l2_get_subdevdata(&mt9p031->subdev);
struct v4l2_mbus_framefmt *format = &mt9p031->format;
const struct v4l2_rect *crop = &mt9p031->crop;
unsigned int hblank;
unsigned int vblank;
unsigned int xskip;
unsigned int yskip;
unsigned int xbin;
unsigned int ybin;
int ret;
/* Windows position and size.
*
* TODO: Make sure the start coordinates and window size match the
* skipping, binning and mirroring (see description of registers 2 and 4
* in table 13, and Binning section on page 41).
*/
ret = mt9p031_write(client, MT9P031_COLUMN_START, crop->left);
if (ret < 0)
return ret;
ret = mt9p031_write(client, MT9P031_ROW_START, crop->top);
if (ret < 0)
return ret;
ret = mt9p031_write(client, MT9P031_WINDOW_WIDTH, crop->width - 1);
if (ret < 0)
return ret;
ret = mt9p031_write(client, MT9P031_WINDOW_HEIGHT, crop->height - 1);
if (ret < 0)
return ret;
/* Row and column binning and skipping. Use the maximum binning value
* compatible with the skipping settings.
*/
xskip = DIV_ROUND_CLOSEST(crop->width, format->width);
yskip = DIV_ROUND_CLOSEST(crop->height, format->height);
xbin = 1 << (ffs(xskip) - 1);
ybin = 1 << (ffs(yskip) - 1);
ret = mt9p031_write(client, MT9P031_COLUMN_ADDRESS_MODE,
((xbin - 1) << 4) | (xskip - 1));
if (ret < 0)
return ret;
ret = mt9p031_write(client, MT9P031_ROW_ADDRESS_MODE,
((ybin - 1) << 4) | (yskip - 1));
if (ret < 0)
return ret;
/* Blanking - use minimum value for horizontal blanking and default
* value for vertical blanking.
*/
hblank = 346 * ybin + 64 + (80 >> max_t(unsigned int, xbin, 3));
vblank = MT9P031_VERTICAL_BLANK_DEF;
ret = mt9p031_write(client, MT9P031_HORIZONTAL_BLANK, hblank);
if (ret < 0)
return ret;
ret = mt9p031_write(client, MT9P031_VERTICAL_BLANK, vblank);
if (ret < 0)
return ret;
return ret;
}
static int mt9p031_s_stream(struct v4l2_subdev *subdev, int enable)
{
struct mt9p031 *mt9p031 = to_mt9p031(subdev);
int ret;
if (!enable) {
/* Stop sensor readout */
ret = mt9p031_set_output_control(mt9p031,
MT9P031_OUTPUT_CONTROL_CEN, 0);
if (ret < 0)
return ret;
return mt9p031_pll_disable(mt9p031);
}
ret = mt9p031_set_params(mt9p031);
if (ret < 0)
return ret;
/* Switch to master "normal" mode */
ret = mt9p031_set_output_control(mt9p031, 0,
MT9P031_OUTPUT_CONTROL_CEN);
if (ret < 0)
return ret;
return mt9p031_pll_enable(mt9p031);
}
static int mt9p031_enum_mbus_code(struct v4l2_subdev *subdev,
struct v4l2_subdev_fh *fh,
struct v4l2_subdev_mbus_code_enum *code)
{
struct mt9p031 *mt9p031 = to_mt9p031(subdev);
if (code->pad || code->index)
return -EINVAL;
code->code = mt9p031->format.code;
return 0;
}
static int mt9p031_enum_frame_size(struct v4l2_subdev *subdev,
struct v4l2_subdev_fh *fh,
struct v4l2_subdev_frame_size_enum *fse)
{
struct mt9p031 *mt9p031 = to_mt9p031(subdev);
if (fse->index >= 8 || fse->code != mt9p031->format.code)
return -EINVAL;
fse->min_width = MT9P031_WINDOW_WIDTH_DEF
/ min_t(unsigned int, 7, fse->index + 1);
fse->max_width = fse->min_width;
fse->min_height = MT9P031_WINDOW_HEIGHT_DEF / (fse->index + 1);
fse->max_height = fse->min_height;
return 0;
}
static struct v4l2_mbus_framefmt *
__mt9p031_get_pad_format(struct mt9p031 *mt9p031, struct v4l2_subdev_fh *fh,
unsigned int pad, u32 which)
{
switch (which) {
case V4L2_SUBDEV_FORMAT_TRY:
return v4l2_subdev_get_try_format(fh, pad);
case V4L2_SUBDEV_FORMAT_ACTIVE:
return &mt9p031->format;
default:
return NULL;
}
}
static struct v4l2_rect *
__mt9p031_get_pad_crop(struct mt9p031 *mt9p031, struct v4l2_subdev_fh *fh,
unsigned int pad, u32 which)
{
switch (which) {
case V4L2_SUBDEV_FORMAT_TRY:
return v4l2_subdev_get_try_crop(fh, pad);
case V4L2_SUBDEV_FORMAT_ACTIVE:
return &mt9p031->crop;
default:
return NULL;
}
}
static int mt9p031_get_format(struct v4l2_subdev *subdev,
struct v4l2_subdev_fh *fh,
struct v4l2_subdev_format *fmt)
{
struct mt9p031 *mt9p031 = to_mt9p031(subdev);
fmt->format = *__mt9p031_get_pad_format(mt9p031, fh, fmt->pad,
fmt->which);
return 0;
}
static int mt9p031_set_format(struct v4l2_subdev *subdev,
struct v4l2_subdev_fh *fh,
struct v4l2_subdev_format *format)
{
struct mt9p031 *mt9p031 = to_mt9p031(subdev);
struct v4l2_mbus_framefmt *__format;
struct v4l2_rect *__crop;
unsigned int width;
unsigned int height;
unsigned int hratio;
unsigned int vratio;
__crop = __mt9p031_get_pad_crop(mt9p031, fh, format->pad,
format->which);
/* Clamp the width and height to avoid dividing by zero. */
width = clamp_t(unsigned int, ALIGN(format->format.width, 2),
max(__crop->width / 7, MT9P031_WINDOW_WIDTH_MIN),
__crop->width);
height = clamp_t(unsigned int, ALIGN(format->format.height, 2),
max(__crop->height / 8, MT9P031_WINDOW_HEIGHT_MIN),
__crop->height);
hratio = DIV_ROUND_CLOSEST(__crop->width, width);
vratio = DIV_ROUND_CLOSEST(__crop->height, height);
__format = __mt9p031_get_pad_format(mt9p031, fh, format->pad,
format->which);
__format->width = __crop->width / hratio;
__format->height = __crop->height / vratio;
format->format = *__format;
return 0;
}
static int mt9p031_get_crop(struct v4l2_subdev *subdev,
struct v4l2_subdev_fh *fh,
struct v4l2_subdev_crop *crop)
{
struct mt9p031 *mt9p031 = to_mt9p031(subdev);
crop->rect = *__mt9p031_get_pad_crop(mt9p031, fh, crop->pad,
crop->which);
return 0;
}
static int mt9p031_set_crop(struct v4l2_subdev *subdev,
struct v4l2_subdev_fh *fh,
struct v4l2_subdev_crop *crop)
{
struct mt9p031 *mt9p031 = to_mt9p031(subdev);
struct v4l2_mbus_framefmt *__format;
struct v4l2_rect *__crop;
struct v4l2_rect rect;
/* Clamp the crop rectangle boundaries and align them to a multiple of 2
* pixels to ensure a GRBG Bayer pattern.
*/
rect.left = clamp(ALIGN(crop->rect.left, 2), MT9P031_COLUMN_START_MIN,
MT9P031_COLUMN_START_MAX);
rect.top = clamp(ALIGN(crop->rect.top, 2), MT9P031_ROW_START_MIN,
MT9P031_ROW_START_MAX);
rect.width = clamp(ALIGN(crop->rect.width, 2),
MT9P031_WINDOW_WIDTH_MIN,
MT9P031_WINDOW_WIDTH_MAX);
rect.height = clamp(ALIGN(crop->rect.height, 2),
MT9P031_WINDOW_HEIGHT_MIN,
MT9P031_WINDOW_HEIGHT_MAX);
rect.width = min(rect.width, MT9P031_PIXEL_ARRAY_WIDTH - rect.left);
rect.height = min(rect.height, MT9P031_PIXEL_ARRAY_HEIGHT - rect.top);
__crop = __mt9p031_get_pad_crop(mt9p031, fh, crop->pad, crop->which);
if (rect.width != __crop->width || rect.height != __crop->height) {
/* Reset the output image size if the crop rectangle size has
* been modified.
*/
__format = __mt9p031_get_pad_format(mt9p031, fh, crop->pad,
crop->which);
__format->width = rect.width;
__format->height = rect.height;
}
*__crop = rect;
crop->rect = rect;
return 0;
}
/* -----------------------------------------------------------------------------
* V4L2 subdev control operations
*/
#define V4L2_CID_TEST_PATTERN (V4L2_CID_USER_BASE | 0x1001)
static int mt9p031_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct mt9p031 *mt9p031 =
container_of(ctrl->handler, struct mt9p031, ctrls);
struct i2c_client *client = v4l2_get_subdevdata(&mt9p031->subdev);
u16 data;
int ret;
switch (ctrl->id) {
case V4L2_CID_EXPOSURE:
ret = mt9p031_write(client, MT9P031_SHUTTER_WIDTH_UPPER,
(ctrl->val >> 16) & 0xffff);
if (ret < 0)
return ret;
return mt9p031_write(client, MT9P031_SHUTTER_WIDTH_LOWER,
ctrl->val & 0xffff);
case V4L2_CID_GAIN:
/* Gain is controlled by 2 analog stages and a digital stage.
* Valid values for the 3 stages are
*
* Stage Min Max Step
* ------------------------------------------
* First analog stage x1 x2 1
* Second analog stage x1 x4 0.125
* Digital stage x1 x16 0.125
*
* To minimize noise, the gain stages should be used in the
* second analog stage, first analog stage, digital stage order.
* Gain from a previous stage should be pushed to its maximum
* value before the next stage is used.
*/
if (ctrl->val <= 32) {
data = ctrl->val;
} else if (ctrl->val <= 64) {
ctrl->val &= ~1;
data = (1 << 6) | (ctrl->val >> 1);
} else {
ctrl->val &= ~7;
data = ((ctrl->val - 64) << 5) | (1 << 6) | 32;
}
return mt9p031_write(client, MT9P031_GLOBAL_GAIN, data);
case V4L2_CID_HFLIP:
if (ctrl->val)
return mt9p031_set_mode2(mt9p031,
0, MT9P031_READ_MODE_2_COL_MIR);
else
return mt9p031_set_mode2(mt9p031,
MT9P031_READ_MODE_2_COL_MIR, 0);
case V4L2_CID_VFLIP:
if (ctrl->val)
return mt9p031_set_mode2(mt9p031,
0, MT9P031_READ_MODE_2_ROW_MIR);
else
return mt9p031_set_mode2(mt9p031,
MT9P031_READ_MODE_2_ROW_MIR, 0);
case V4L2_CID_TEST_PATTERN:
if (!ctrl->val) {
ret = mt9p031_set_mode2(mt9p031,
0, MT9P031_READ_MODE_2_ROW_BLC);
if (ret < 0)
return ret;
return mt9p031_write(client, MT9P031_TEST_PATTERN,
MT9P031_TEST_PATTERN_DISABLE);
}
ret = mt9p031_write(client, MT9P031_TEST_PATTERN_GREEN, 0x05a0);
if (ret < 0)
return ret;
ret = mt9p031_write(client, MT9P031_TEST_PATTERN_RED, 0x0a50);
if (ret < 0)
return ret;
ret = mt9p031_write(client, MT9P031_TEST_PATTERN_BLUE, 0x0aa0);
if (ret < 0)
return ret;
ret = mt9p031_set_mode2(mt9p031, MT9P031_READ_MODE_2_ROW_BLC,
0);
if (ret < 0)
return ret;
ret = mt9p031_write(client, MT9P031_ROW_BLACK_DEF_OFFSET, 0);
if (ret < 0)
return ret;
return mt9p031_write(client, MT9P031_TEST_PATTERN,
((ctrl->val - 1) << MT9P031_TEST_PATTERN_SHIFT)
| MT9P031_TEST_PATTERN_ENABLE);
}
return 0;
}
static struct v4l2_ctrl_ops mt9p031_ctrl_ops = {
.s_ctrl = mt9p031_s_ctrl,
};
static const char * const mt9p031_test_pattern_menu[] = {
"Disabled",
"Color Field",
"Horizontal Gradient",
"Vertical Gradient",
"Diagonal Gradient",
"Classic Test Pattern",
"Walking 1s",
"Monochrome Horizontal Bars",
"Monochrome Vertical Bars",
"Vertical Color Bars",
};
static const struct v4l2_ctrl_config mt9p031_ctrls[] = {
{
.ops = &mt9p031_ctrl_ops,
.id = V4L2_CID_TEST_PATTERN,
.type = V4L2_CTRL_TYPE_MENU,
.name = "Test Pattern",
.min = 0,
.max = ARRAY_SIZE(mt9p031_test_pattern_menu) - 1,
.step = 0,
.def = 0,
.flags = 0,
.menu_skip_mask = 0,
.qmenu = mt9p031_test_pattern_menu,
}
};
/* -----------------------------------------------------------------------------
* V4L2 subdev core operations
*/
static int mt9p031_set_power(struct v4l2_subdev *subdev, int on)
{
struct mt9p031 *mt9p031 = to_mt9p031(subdev);
int ret = 0;
mutex_lock(&mt9p031->power_lock);
/* If the power count is modified from 0 to != 0 or from != 0 to 0,
* update the power state.
*/
if (mt9p031->power_count == !on) {
ret = __mt9p031_set_power(mt9p031, !!on);
if (ret < 0)
goto out;
}
/* Update the power count. */
mt9p031->power_count += on ? 1 : -1;
WARN_ON(mt9p031->power_count < 0);
out:
mutex_unlock(&mt9p031->power_lock);
return ret;
}
/* -----------------------------------------------------------------------------
* V4L2 subdev internal operations
*/
static int mt9p031_registered(struct v4l2_subdev *subdev)
{
struct i2c_client *client = v4l2_get_subdevdata(subdev);
struct mt9p031 *mt9p031 = to_mt9p031(subdev);
s32 data;
int ret;
ret = mt9p031_power_on(mt9p031);
if (ret < 0) {
dev_err(&client->dev, "MT9P031 power up failed\n");
return ret;
}
/* Read out the chip version register */
data = mt9p031_read(client, MT9P031_CHIP_VERSION);
if (data != MT9P031_CHIP_VERSION_VALUE) {
dev_err(&client->dev, "MT9P031 not detected, wrong version "
"0x%04x\n", data);
return -ENODEV;
}
mt9p031_power_off(mt9p031);
dev_info(&client->dev, "MT9P031 detected at address 0x%02x\n",
client->addr);
return ret;
}
static int mt9p031_open(struct v4l2_subdev *subdev, struct v4l2_subdev_fh *fh)
{
struct mt9p031 *mt9p031 = to_mt9p031(subdev);
struct v4l2_mbus_framefmt *format;
struct v4l2_rect *crop;
crop = v4l2_subdev_get_try_crop(fh, 0);
crop->left = MT9P031_COLUMN_START_DEF;
crop->top = MT9P031_ROW_START_DEF;
crop->width = MT9P031_WINDOW_WIDTH_DEF;
crop->height = MT9P031_WINDOW_HEIGHT_DEF;
format = v4l2_subdev_get_try_format(fh, 0);
if (mt9p031->pdata->version == MT9P031_MONOCHROME_VERSION)
format->code = V4L2_MBUS_FMT_Y12_1X12;
else
format->code = V4L2_MBUS_FMT_SGRBG12_1X12;
format->width = MT9P031_WINDOW_WIDTH_DEF;
format->height = MT9P031_WINDOW_HEIGHT_DEF;
format->field = V4L2_FIELD_NONE;
format->colorspace = V4L2_COLORSPACE_SRGB;
return mt9p031_set_power(subdev, 1);
}
static int mt9p031_close(struct v4l2_subdev *subdev, struct v4l2_subdev_fh *fh)
{
return mt9p031_set_power(subdev, 0);
}
static struct v4l2_subdev_core_ops mt9p031_subdev_core_ops = {
.s_power = mt9p031_set_power,
};
static struct v4l2_subdev_video_ops mt9p031_subdev_video_ops = {
.s_stream = mt9p031_s_stream,
};
static struct v4l2_subdev_pad_ops mt9p031_subdev_pad_ops = {
.enum_mbus_code = mt9p031_enum_mbus_code,
.enum_frame_size = mt9p031_enum_frame_size,
.get_fmt = mt9p031_get_format,
.set_fmt = mt9p031_set_format,
.get_crop = mt9p031_get_crop,
.set_crop = mt9p031_set_crop,
};
static struct v4l2_subdev_ops mt9p031_subdev_ops = {
.core = &mt9p031_subdev_core_ops,
.video = &mt9p031_subdev_video_ops,
.pad = &mt9p031_subdev_pad_ops,
};
static const struct v4l2_subdev_internal_ops mt9p031_subdev_internal_ops = {
.registered = mt9p031_registered,
.open = mt9p031_open,
.close = mt9p031_close,
};
/* -----------------------------------------------------------------------------
* Driver initialization and probing
*/
static int mt9p031_probe(struct i2c_client *client,
const struct i2c_device_id *did)
{
struct mt9p031_platform_data *pdata = client->dev.platform_data;
struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent);
struct mt9p031 *mt9p031;
unsigned int i;
int ret;
if (pdata == NULL) {
dev_err(&client->dev, "No platform data\n");
return -EINVAL;
}
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_WORD_DATA)) {
dev_warn(&client->dev,
"I2C-Adapter doesn't support I2C_FUNC_SMBUS_WORD\n");
return -EIO;
}
mt9p031 = kzalloc(sizeof(*mt9p031), GFP_KERNEL);
if (mt9p031 == NULL)
return -ENOMEM;
mt9p031->pdata = pdata;
mt9p031->output_control = MT9P031_OUTPUT_CONTROL_DEF;
mt9p031->mode2 = MT9P031_READ_MODE_2_ROW_BLC;
v4l2_ctrl_handler_init(&mt9p031->ctrls, ARRAY_SIZE(mt9p031_ctrls) + 4);
v4l2_ctrl_new_std(&mt9p031->ctrls, &mt9p031_ctrl_ops,
V4L2_CID_EXPOSURE, MT9P031_SHUTTER_WIDTH_MIN,
MT9P031_SHUTTER_WIDTH_MAX, 1,
MT9P031_SHUTTER_WIDTH_DEF);
v4l2_ctrl_new_std(&mt9p031->ctrls, &mt9p031_ctrl_ops,
V4L2_CID_GAIN, MT9P031_GLOBAL_GAIN_MIN,
MT9P031_GLOBAL_GAIN_MAX, 1, MT9P031_GLOBAL_GAIN_DEF);
v4l2_ctrl_new_std(&mt9p031->ctrls, &mt9p031_ctrl_ops,
V4L2_CID_HFLIP, 0, 1, 1, 0);
v4l2_ctrl_new_std(&mt9p031->ctrls, &mt9p031_ctrl_ops,
V4L2_CID_VFLIP, 0, 1, 1, 0);
for (i = 0; i < ARRAY_SIZE(mt9p031_ctrls); ++i)
v4l2_ctrl_new_custom(&mt9p031->ctrls, &mt9p031_ctrls[i], NULL);
mt9p031->subdev.ctrl_handler = &mt9p031->ctrls;
if (mt9p031->ctrls.error)
printk(KERN_INFO "%s: control initialization error %d\n",
__func__, mt9p031->ctrls.error);
mutex_init(&mt9p031->power_lock);
v4l2_i2c_subdev_init(&mt9p031->subdev, client, &mt9p031_subdev_ops);
mt9p031->subdev.internal_ops = &mt9p031_subdev_internal_ops;
mt9p031->pad.flags = MEDIA_PAD_FL_SOURCE;
ret = media_entity_init(&mt9p031->subdev.entity, 1, &mt9p031->pad, 0);
if (ret < 0)
goto done;
mt9p031->subdev.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE;
mt9p031->crop.width = MT9P031_WINDOW_WIDTH_DEF;
mt9p031->crop.height = MT9P031_WINDOW_HEIGHT_DEF;
mt9p031->crop.left = MT9P031_COLUMN_START_DEF;
mt9p031->crop.top = MT9P031_ROW_START_DEF;
if (mt9p031->pdata->version == MT9P031_MONOCHROME_VERSION)
mt9p031->format.code = V4L2_MBUS_FMT_Y12_1X12;
else
mt9p031->format.code = V4L2_MBUS_FMT_SGRBG12_1X12;
mt9p031->format.width = MT9P031_WINDOW_WIDTH_DEF;
mt9p031->format.height = MT9P031_WINDOW_HEIGHT_DEF;
mt9p031->format.field = V4L2_FIELD_NONE;
mt9p031->format.colorspace = V4L2_COLORSPACE_SRGB;
ret = mt9p031_pll_setup(mt9p031);
done:
if (ret < 0) {
v4l2_ctrl_handler_free(&mt9p031->ctrls);
media_entity_cleanup(&mt9p031->subdev.entity);
kfree(mt9p031);
}
return ret;
}
static int mt9p031_remove(struct i2c_client *client)
{
struct v4l2_subdev *subdev = i2c_get_clientdata(client);
struct mt9p031 *mt9p031 = to_mt9p031(subdev);
v4l2_ctrl_handler_free(&mt9p031->ctrls);
v4l2_device_unregister_subdev(subdev);
media_entity_cleanup(&subdev->entity);
kfree(mt9p031);
return 0;
}
static const struct i2c_device_id mt9p031_id[] = {
{ "mt9p031", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, mt9p031_id);
static struct i2c_driver mt9p031_i2c_driver = {
.driver = {
.name = "mt9p031",
},
.probe = mt9p031_probe,
.remove = mt9p031_remove,
.id_table = mt9p031_id,
};
module_i2c_driver(mt9p031_i2c_driver);
MODULE_DESCRIPTION("Aptina MT9P031 Camera driver");
MODULE_AUTHOR("Bastian Hecht <hechtb@gmail.com>");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
christer12/android_kernel_samsung_msm8974 | drivers/char/agp/ati-agp.c | 9167 | 14939 | /*
* ATi AGPGART routines.
*/
#include <linux/types.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/agp_backend.h>
#include <asm/agp.h>
#include "agp.h"
#define ATI_GART_MMBASE_ADDR 0x14
#define ATI_RS100_APSIZE 0xac
#define ATI_RS100_IG_AGPMODE 0xb0
#define ATI_RS300_APSIZE 0xf8
#define ATI_RS300_IG_AGPMODE 0xfc
#define ATI_GART_FEATURE_ID 0x00
#define ATI_GART_BASE 0x04
#define ATI_GART_CACHE_SZBASE 0x08
#define ATI_GART_CACHE_CNTRL 0x0c
#define ATI_GART_CACHE_ENTRY_CNTRL 0x10
static const struct aper_size_info_lvl2 ati_generic_sizes[7] =
{
{2048, 524288, 0x0000000c},
{1024, 262144, 0x0000000a},
{512, 131072, 0x00000008},
{256, 65536, 0x00000006},
{128, 32768, 0x00000004},
{64, 16384, 0x00000002},
{32, 8192, 0x00000000}
};
static struct gatt_mask ati_generic_masks[] =
{
{ .mask = 1, .type = 0}
};
struct ati_page_map {
unsigned long *real;
unsigned long __iomem *remapped;
};
static struct _ati_generic_private {
volatile u8 __iomem *registers;
struct ati_page_map **gatt_pages;
int num_tables;
} ati_generic_private;
static int ati_create_page_map(struct ati_page_map *page_map)
{
int i, err = 0;
page_map->real = (unsigned long *) __get_free_page(GFP_KERNEL);
if (page_map->real == NULL)
return -ENOMEM;
set_memory_uc((unsigned long)page_map->real, 1);
err = map_page_into_agp(virt_to_page(page_map->real));
page_map->remapped = page_map->real;
for (i = 0; i < PAGE_SIZE / sizeof(unsigned long); i++) {
writel(agp_bridge->scratch_page, page_map->remapped+i);
readl(page_map->remapped+i); /* PCI Posting. */
}
return 0;
}
static void ati_free_page_map(struct ati_page_map *page_map)
{
unmap_page_from_agp(virt_to_page(page_map->real));
set_memory_wb((unsigned long)page_map->real, 1);
free_page((unsigned long) page_map->real);
}
static void ati_free_gatt_pages(void)
{
int i;
struct ati_page_map **tables;
struct ati_page_map *entry;
tables = ati_generic_private.gatt_pages;
for (i = 0; i < ati_generic_private.num_tables; i++) {
entry = tables[i];
if (entry != NULL) {
if (entry->real != NULL)
ati_free_page_map(entry);
kfree(entry);
}
}
kfree(tables);
}
static int ati_create_gatt_pages(int nr_tables)
{
struct ati_page_map **tables;
struct ati_page_map *entry;
int retval = 0;
int i;
tables = kzalloc((nr_tables + 1) * sizeof(struct ati_page_map *),GFP_KERNEL);
if (tables == NULL)
return -ENOMEM;
for (i = 0; i < nr_tables; i++) {
entry = kzalloc(sizeof(struct ati_page_map), GFP_KERNEL);
tables[i] = entry;
if (entry == NULL) {
retval = -ENOMEM;
break;
}
retval = ati_create_page_map(entry);
if (retval != 0)
break;
}
ati_generic_private.num_tables = i;
ati_generic_private.gatt_pages = tables;
if (retval != 0)
ati_free_gatt_pages();
return retval;
}
static int is_r200(void)
{
if ((agp_bridge->dev->device == PCI_DEVICE_ID_ATI_RS100) ||
(agp_bridge->dev->device == PCI_DEVICE_ID_ATI_RS200) ||
(agp_bridge->dev->device == PCI_DEVICE_ID_ATI_RS200_B) ||
(agp_bridge->dev->device == PCI_DEVICE_ID_ATI_RS250))
return 1;
return 0;
}
static int ati_fetch_size(void)
{
int i;
u32 temp;
struct aper_size_info_lvl2 *values;
if (is_r200())
pci_read_config_dword(agp_bridge->dev, ATI_RS100_APSIZE, &temp);
else
pci_read_config_dword(agp_bridge->dev, ATI_RS300_APSIZE, &temp);
temp = (temp & 0x0000000e);
values = A_SIZE_LVL2(agp_bridge->driver->aperture_sizes);
for (i = 0; i < agp_bridge->driver->num_aperture_sizes; i++) {
if (temp == values[i].size_value) {
agp_bridge->previous_size =
agp_bridge->current_size = (void *) (values + i);
agp_bridge->aperture_size_idx = i;
return values[i].size;
}
}
return 0;
}
static void ati_tlbflush(struct agp_memory * mem)
{
writel(1, ati_generic_private.registers+ATI_GART_CACHE_CNTRL);
readl(ati_generic_private.registers+ATI_GART_CACHE_CNTRL); /* PCI Posting. */
}
static void ati_cleanup(void)
{
struct aper_size_info_lvl2 *previous_size;
u32 temp;
previous_size = A_SIZE_LVL2(agp_bridge->previous_size);
/* Write back the previous size and disable gart translation */
if (is_r200()) {
pci_read_config_dword(agp_bridge->dev, ATI_RS100_APSIZE, &temp);
temp = ((temp & ~(0x0000000f)) | previous_size->size_value);
pci_write_config_dword(agp_bridge->dev, ATI_RS100_APSIZE, temp);
} else {
pci_read_config_dword(agp_bridge->dev, ATI_RS300_APSIZE, &temp);
temp = ((temp & ~(0x0000000f)) | previous_size->size_value);
pci_write_config_dword(agp_bridge->dev, ATI_RS300_APSIZE, temp);
}
iounmap((volatile u8 __iomem *)ati_generic_private.registers);
}
static int ati_configure(void)
{
u32 temp;
/* Get the memory mapped registers */
pci_read_config_dword(agp_bridge->dev, ATI_GART_MMBASE_ADDR, &temp);
temp = (temp & 0xfffff000);
ati_generic_private.registers = (volatile u8 __iomem *) ioremap(temp, 4096);
if (!ati_generic_private.registers)
return -ENOMEM;
if (is_r200())
pci_write_config_dword(agp_bridge->dev, ATI_RS100_IG_AGPMODE, 0x20000);
else
pci_write_config_dword(agp_bridge->dev, ATI_RS300_IG_AGPMODE, 0x20000);
/* address to map too */
/*
pci_read_config_dword(agp_bridge.dev, AGP_APBASE, &temp);
agp_bridge.gart_bus_addr = (temp & PCI_BASE_ADDRESS_MEM_MASK);
printk(KERN_INFO PFX "IGP320 gart_bus_addr: %x\n", agp_bridge.gart_bus_addr);
*/
writel(0x60000, ati_generic_private.registers+ATI_GART_FEATURE_ID);
readl(ati_generic_private.registers+ATI_GART_FEATURE_ID); /* PCI Posting.*/
/* SIGNALED_SYSTEM_ERROR @ NB_STATUS */
pci_read_config_dword(agp_bridge->dev, 4, &temp);
pci_write_config_dword(agp_bridge->dev, 4, temp | (1<<14));
/* Write out the address of the gatt table */
writel(agp_bridge->gatt_bus_addr, ati_generic_private.registers+ATI_GART_BASE);
readl(ati_generic_private.registers+ATI_GART_BASE); /* PCI Posting. */
return 0;
}
#ifdef CONFIG_PM
static int agp_ati_suspend(struct pci_dev *dev, pm_message_t state)
{
pci_save_state(dev);
pci_set_power_state(dev, 3);
return 0;
}
static int agp_ati_resume(struct pci_dev *dev)
{
pci_set_power_state(dev, 0);
pci_restore_state(dev);
return ati_configure();
}
#endif
/*
*Since we don't need contiguous memory we just try
* to get the gatt table once
*/
#define GET_PAGE_DIR_OFF(addr) (addr >> 22)
#define GET_PAGE_DIR_IDX(addr) (GET_PAGE_DIR_OFF(addr) - \
GET_PAGE_DIR_OFF(agp_bridge->gart_bus_addr))
#define GET_GATT_OFF(addr) ((addr & 0x003ff000) >> 12)
#undef GET_GATT
#define GET_GATT(addr) (ati_generic_private.gatt_pages[\
GET_PAGE_DIR_IDX(addr)]->remapped)
static int ati_insert_memory(struct agp_memory * mem,
off_t pg_start, int type)
{
int i, j, num_entries;
unsigned long __iomem *cur_gatt;
unsigned long addr;
int mask_type;
num_entries = A_SIZE_LVL2(agp_bridge->current_size)->num_entries;
mask_type = agp_generic_type_to_mask_type(mem->bridge, type);
if (mask_type != 0 || type != mem->type)
return -EINVAL;
if (mem->page_count == 0)
return 0;
if ((pg_start + mem->page_count) > num_entries)
return -EINVAL;
j = pg_start;
while (j < (pg_start + mem->page_count)) {
addr = (j * PAGE_SIZE) + agp_bridge->gart_bus_addr;
cur_gatt = GET_GATT(addr);
if (!PGE_EMPTY(agp_bridge,readl(cur_gatt+GET_GATT_OFF(addr))))
return -EBUSY;
j++;
}
if (!mem->is_flushed) {
/*CACHE_FLUSH(); */
global_cache_flush();
mem->is_flushed = true;
}
for (i = 0, j = pg_start; i < mem->page_count; i++, j++) {
addr = (j * PAGE_SIZE) + agp_bridge->gart_bus_addr;
cur_gatt = GET_GATT(addr);
writel(agp_bridge->driver->mask_memory(agp_bridge,
page_to_phys(mem->pages[i]),
mem->type),
cur_gatt+GET_GATT_OFF(addr));
}
readl(GET_GATT(agp_bridge->gart_bus_addr)); /* PCI posting */
agp_bridge->driver->tlb_flush(mem);
return 0;
}
static int ati_remove_memory(struct agp_memory * mem, off_t pg_start,
int type)
{
int i;
unsigned long __iomem *cur_gatt;
unsigned long addr;
int mask_type;
mask_type = agp_generic_type_to_mask_type(mem->bridge, type);
if (mask_type != 0 || type != mem->type)
return -EINVAL;
if (mem->page_count == 0)
return 0;
for (i = pg_start; i < (mem->page_count + pg_start); i++) {
addr = (i * PAGE_SIZE) + agp_bridge->gart_bus_addr;
cur_gatt = GET_GATT(addr);
writel(agp_bridge->scratch_page, cur_gatt+GET_GATT_OFF(addr));
}
readl(GET_GATT(agp_bridge->gart_bus_addr)); /* PCI posting */
agp_bridge->driver->tlb_flush(mem);
return 0;
}
static int ati_create_gatt_table(struct agp_bridge_data *bridge)
{
struct aper_size_info_lvl2 *value;
struct ati_page_map page_dir;
unsigned long __iomem *cur_gatt;
unsigned long addr;
int retval;
u32 temp;
int i;
struct aper_size_info_lvl2 *current_size;
value = A_SIZE_LVL2(agp_bridge->current_size);
retval = ati_create_page_map(&page_dir);
if (retval != 0)
return retval;
retval = ati_create_gatt_pages(value->num_entries / 1024);
if (retval != 0) {
ati_free_page_map(&page_dir);
return retval;
}
agp_bridge->gatt_table_real = (u32 *)page_dir.real;
agp_bridge->gatt_table = (u32 __iomem *) page_dir.remapped;
agp_bridge->gatt_bus_addr = virt_to_phys(page_dir.real);
/* Write out the size register */
current_size = A_SIZE_LVL2(agp_bridge->current_size);
if (is_r200()) {
pci_read_config_dword(agp_bridge->dev, ATI_RS100_APSIZE, &temp);
temp = (((temp & ~(0x0000000e)) | current_size->size_value)
| 0x00000001);
pci_write_config_dword(agp_bridge->dev, ATI_RS100_APSIZE, temp);
pci_read_config_dword(agp_bridge->dev, ATI_RS100_APSIZE, &temp);
} else {
pci_read_config_dword(agp_bridge->dev, ATI_RS300_APSIZE, &temp);
temp = (((temp & ~(0x0000000e)) | current_size->size_value)
| 0x00000001);
pci_write_config_dword(agp_bridge->dev, ATI_RS300_APSIZE, temp);
pci_read_config_dword(agp_bridge->dev, ATI_RS300_APSIZE, &temp);
}
/*
* Get the address for the gart region.
* This is a bus address even on the alpha, b/c its
* used to program the agp master not the cpu
*/
pci_read_config_dword(agp_bridge->dev, AGP_APBASE, &temp);
addr = (temp & PCI_BASE_ADDRESS_MEM_MASK);
agp_bridge->gart_bus_addr = addr;
/* Calculate the agp offset */
for (i = 0; i < value->num_entries / 1024; i++, addr += 0x00400000) {
writel(virt_to_phys(ati_generic_private.gatt_pages[i]->real) | 1,
page_dir.remapped+GET_PAGE_DIR_OFF(addr));
readl(page_dir.remapped+GET_PAGE_DIR_OFF(addr)); /* PCI Posting. */
}
for (i = 0; i < value->num_entries; i++) {
addr = (i * PAGE_SIZE) + agp_bridge->gart_bus_addr;
cur_gatt = GET_GATT(addr);
writel(agp_bridge->scratch_page, cur_gatt+GET_GATT_OFF(addr));
}
return 0;
}
static int ati_free_gatt_table(struct agp_bridge_data *bridge)
{
struct ati_page_map page_dir;
page_dir.real = (unsigned long *)agp_bridge->gatt_table_real;
page_dir.remapped = (unsigned long __iomem *)agp_bridge->gatt_table;
ati_free_gatt_pages();
ati_free_page_map(&page_dir);
return 0;
}
static const struct agp_bridge_driver ati_generic_bridge = {
.owner = THIS_MODULE,
.aperture_sizes = ati_generic_sizes,
.size_type = LVL2_APER_SIZE,
.num_aperture_sizes = 7,
.needs_scratch_page = true,
.configure = ati_configure,
.fetch_size = ati_fetch_size,
.cleanup = ati_cleanup,
.tlb_flush = ati_tlbflush,
.mask_memory = agp_generic_mask_memory,
.masks = ati_generic_masks,
.agp_enable = agp_generic_enable,
.cache_flush = global_cache_flush,
.create_gatt_table = ati_create_gatt_table,
.free_gatt_table = ati_free_gatt_table,
.insert_memory = ati_insert_memory,
.remove_memory = ati_remove_memory,
.alloc_by_type = agp_generic_alloc_by_type,
.free_by_type = agp_generic_free_by_type,
.agp_alloc_page = agp_generic_alloc_page,
.agp_alloc_pages = agp_generic_alloc_pages,
.agp_destroy_page = agp_generic_destroy_page,
.agp_destroy_pages = agp_generic_destroy_pages,
.agp_type_to_mask_type = agp_generic_type_to_mask_type,
};
static struct agp_device_ids ati_agp_device_ids[] __devinitdata =
{
{
.device_id = PCI_DEVICE_ID_ATI_RS100,
.chipset_name = "IGP320/M",
},
{
.device_id = PCI_DEVICE_ID_ATI_RS200,
.chipset_name = "IGP330/340/345/350/M",
},
{
.device_id = PCI_DEVICE_ID_ATI_RS200_B,
.chipset_name = "IGP345M",
},
{
.device_id = PCI_DEVICE_ID_ATI_RS250,
.chipset_name = "IGP7000/M",
},
{
.device_id = PCI_DEVICE_ID_ATI_RS300_100,
.chipset_name = "IGP9100/M",
},
{
.device_id = PCI_DEVICE_ID_ATI_RS300_133,
.chipset_name = "IGP9100/M",
},
{
.device_id = PCI_DEVICE_ID_ATI_RS300_166,
.chipset_name = "IGP9100/M",
},
{
.device_id = PCI_DEVICE_ID_ATI_RS300_200,
.chipset_name = "IGP9100/M",
},
{
.device_id = PCI_DEVICE_ID_ATI_RS350_133,
.chipset_name = "IGP9000/M",
},
{
.device_id = PCI_DEVICE_ID_ATI_RS350_200,
.chipset_name = "IGP9100/M",
},
{ }, /* dummy final entry, always present */
};
static int __devinit agp_ati_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct agp_device_ids *devs = ati_agp_device_ids;
struct agp_bridge_data *bridge;
u8 cap_ptr;
int j;
cap_ptr = pci_find_capability(pdev, PCI_CAP_ID_AGP);
if (!cap_ptr)
return -ENODEV;
/* probe for known chipsets */
for (j = 0; devs[j].chipset_name; j++) {
if (pdev->device == devs[j].device_id)
goto found;
}
dev_err(&pdev->dev, "unsupported Ati chipset [%04x/%04x])\n",
pdev->vendor, pdev->device);
return -ENODEV;
found:
bridge = agp_alloc_bridge();
if (!bridge)
return -ENOMEM;
bridge->dev = pdev;
bridge->capndx = cap_ptr;
bridge->driver = &ati_generic_bridge;
dev_info(&pdev->dev, "Ati %s chipset\n", devs[j].chipset_name);
/* Fill in the mode register */
pci_read_config_dword(pdev,
bridge->capndx+PCI_AGP_STATUS,
&bridge->mode);
pci_set_drvdata(pdev, bridge);
return agp_add_bridge(bridge);
}
static void __devexit agp_ati_remove(struct pci_dev *pdev)
{
struct agp_bridge_data *bridge = pci_get_drvdata(pdev);
agp_remove_bridge(bridge);
agp_put_bridge(bridge);
}
static struct pci_device_id agp_ati_pci_table[] = {
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_ATI,
.device = PCI_ANY_ID,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{ }
};
MODULE_DEVICE_TABLE(pci, agp_ati_pci_table);
static struct pci_driver agp_ati_pci_driver = {
.name = "agpgart-ati",
.id_table = agp_ati_pci_table,
.probe = agp_ati_probe,
.remove = agp_ati_remove,
#ifdef CONFIG_PM
.suspend = agp_ati_suspend,
.resume = agp_ati_resume,
#endif
};
static int __init agp_ati_init(void)
{
if (agp_off)
return -EINVAL;
return pci_register_driver(&agp_ati_pci_driver);
}
static void __exit agp_ati_cleanup(void)
{
pci_unregister_driver(&agp_ati_pci_driver);
}
module_init(agp_ati_init);
module_exit(agp_ati_cleanup);
MODULE_AUTHOR("Dave Jones <davej@redhat.com>");
MODULE_LICENSE("GPL and additional rights");
| gpl-2.0 |
mahound/Cyanogenmod_kernel_samsung_loganreltexx | drivers/net/wireless/iwmc3200wifi/eeprom.c | 9167 | 6651 | /*
* Intel Wireless Multicomm 3200 WiFi driver
*
* Copyright (C) 2009 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 <ilw@linux.intel.com>
* Samuel Ortiz <samuel.ortiz@intel.com>
* Zhu Yi <yi.zhu@intel.com>
*
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include "iwm.h"
#include "umac.h"
#include "commands.h"
#include "eeprom.h"
static struct iwm_eeprom_entry eeprom_map[] = {
[IWM_EEPROM_SIG] =
{"Signature", IWM_EEPROM_SIG_OFF, IWM_EEPROM_SIG_LEN},
[IWM_EEPROM_VERSION] =
{"Version", IWM_EEPROM_VERSION_OFF, IWM_EEPROM_VERSION_LEN},
[IWM_EEPROM_OEM_HW_VERSION] =
{"OEM HW version", IWM_EEPROM_OEM_HW_VERSION_OFF,
IWM_EEPROM_OEM_HW_VERSION_LEN},
[IWM_EEPROM_MAC_VERSION] =
{"MAC version", IWM_EEPROM_MAC_VERSION_OFF, IWM_EEPROM_MAC_VERSION_LEN},
[IWM_EEPROM_CARD_ID] =
{"Card ID", IWM_EEPROM_CARD_ID_OFF, IWM_EEPROM_CARD_ID_LEN},
[IWM_EEPROM_RADIO_CONF] =
{"Radio config", IWM_EEPROM_RADIO_CONF_OFF, IWM_EEPROM_RADIO_CONF_LEN},
[IWM_EEPROM_SKU_CAP] =
{"SKU capabilities", IWM_EEPROM_SKU_CAP_OFF, IWM_EEPROM_SKU_CAP_LEN},
[IWM_EEPROM_FAT_CHANNELS_CAP] =
{"HT channels capabilities", IWM_EEPROM_FAT_CHANNELS_CAP_OFF,
IWM_EEPROM_FAT_CHANNELS_CAP_LEN},
[IWM_EEPROM_CALIB_RXIQ_OFFSET] =
{"RX IQ offset", IWM_EEPROM_CALIB_RXIQ_OFF, IWM_EEPROM_INDIRECT_LEN},
[IWM_EEPROM_CALIB_RXIQ] =
{"Calib RX IQ", 0, IWM_EEPROM_CALIB_RXIQ_LEN},
};
static int iwm_eeprom_read(struct iwm_priv *iwm, u8 eeprom_id)
{
int ret;
u32 entry_size, chunk_size, data_offset = 0, addr_offset = 0;
u32 addr;
struct iwm_udma_wifi_cmd udma_cmd;
struct iwm_umac_cmd umac_cmd;
struct iwm_umac_cmd_eeprom_proxy eeprom_cmd;
if (eeprom_id > (IWM_EEPROM_LAST - 1))
return -EINVAL;
entry_size = eeprom_map[eeprom_id].length;
if (eeprom_id >= IWM_EEPROM_INDIRECT_DATA) {
/* indirect data */
u32 off_id = eeprom_id - IWM_EEPROM_INDIRECT_DATA +
IWM_EEPROM_INDIRECT_OFFSET;
eeprom_map[eeprom_id].offset =
*(u16 *)(iwm->eeprom + eeprom_map[off_id].offset) << 1;
}
addr = eeprom_map[eeprom_id].offset;
udma_cmd.eop = 1;
udma_cmd.credit_group = 0x4;
udma_cmd.ra_tid = UMAC_HDI_ACT_TBL_IDX_HOST_CMD;
udma_cmd.lmac_offset = 0;
umac_cmd.id = UMAC_CMD_OPCODE_EEPROM_PROXY;
umac_cmd.resp = 1;
while (entry_size > 0) {
chunk_size = min_t(u32, entry_size, IWM_MAX_EEPROM_DATA_LEN);
eeprom_cmd.hdr.type =
cpu_to_le32(IWM_UMAC_CMD_EEPROM_TYPE_READ);
eeprom_cmd.hdr.offset = cpu_to_le32(addr + addr_offset);
eeprom_cmd.hdr.len = cpu_to_le32(chunk_size);
ret = iwm_hal_send_umac_cmd(iwm, &udma_cmd,
&umac_cmd, &eeprom_cmd,
sizeof(struct iwm_umac_cmd_eeprom_proxy));
if (ret < 0) {
IWM_ERR(iwm, "Couldn't read eeprom\n");
return ret;
}
ret = iwm_notif_handle(iwm, UMAC_CMD_OPCODE_EEPROM_PROXY,
IWM_SRC_UMAC, 2*HZ);
if (ret < 0) {
IWM_ERR(iwm, "Did not get any eeprom answer\n");
return ret;
}
data_offset += chunk_size;
addr_offset += chunk_size;
entry_size -= chunk_size;
}
return 0;
}
u8 *iwm_eeprom_access(struct iwm_priv *iwm, u8 eeprom_id)
{
if (!iwm->eeprom)
return ERR_PTR(-ENODEV);
return iwm->eeprom + eeprom_map[eeprom_id].offset;
}
int iwm_eeprom_fat_channels(struct iwm_priv *iwm)
{
struct wiphy *wiphy = iwm_to_wiphy(iwm);
struct ieee80211_supported_band *band;
u16 *channels, i;
channels = (u16 *)iwm_eeprom_access(iwm, IWM_EEPROM_FAT_CHANNELS_CAP);
if (IS_ERR(channels))
return PTR_ERR(channels);
band = wiphy->bands[IEEE80211_BAND_2GHZ];
band->ht_cap.ht_supported = true;
for (i = 0; i < IWM_EEPROM_FAT_CHANNELS_24; i++)
if (!(channels[i] & IWM_EEPROM_FAT_CHANNEL_ENABLED))
band->ht_cap.ht_supported = false;
band = wiphy->bands[IEEE80211_BAND_5GHZ];
band->ht_cap.ht_supported = true;
for (i = IWM_EEPROM_FAT_CHANNELS_24; i < IWM_EEPROM_FAT_CHANNELS; i++)
if (!(channels[i] & IWM_EEPROM_FAT_CHANNEL_ENABLED))
band->ht_cap.ht_supported = false;
return 0;
}
u32 iwm_eeprom_wireless_mode(struct iwm_priv *iwm)
{
u16 sku_cap;
u32 wireless_mode = 0;
sku_cap = *((u16 *)iwm_eeprom_access(iwm, IWM_EEPROM_SKU_CAP));
if (sku_cap & IWM_EEPROM_SKU_CAP_BAND_24GHZ)
wireless_mode |= WIRELESS_MODE_11G;
if (sku_cap & IWM_EEPROM_SKU_CAP_BAND_52GHZ)
wireless_mode |= WIRELESS_MODE_11A;
if (sku_cap & IWM_EEPROM_SKU_CAP_11N_ENABLE)
wireless_mode |= WIRELESS_MODE_11N;
return wireless_mode;
}
int iwm_eeprom_init(struct iwm_priv *iwm)
{
int i, ret = 0;
char name[32];
iwm->eeprom = kzalloc(IWM_EEPROM_LEN, GFP_KERNEL);
if (!iwm->eeprom)
return -ENOMEM;
for (i = IWM_EEPROM_FIRST; i < IWM_EEPROM_LAST; i++) {
ret = iwm_eeprom_read(iwm, i);
if (ret < 0) {
IWM_ERR(iwm, "Couldn't read eeprom entry #%d: %s\n",
i, eeprom_map[i].name);
break;
}
}
IWM_DBG_BOOT(iwm, DBG, "EEPROM dump:\n");
for (i = IWM_EEPROM_FIRST; i < IWM_EEPROM_LAST; i++) {
memset(name, 0, 32);
sprintf(name, "%s: ", eeprom_map[i].name);
IWM_HEXDUMP(iwm, DBG, BOOT, name,
iwm->eeprom + eeprom_map[i].offset,
eeprom_map[i].length);
}
return ret;
}
void iwm_eeprom_exit(struct iwm_priv *iwm)
{
kfree(iwm->eeprom);
}
| gpl-2.0 |
elelinux/android_kernel_htc_pyramid | arch/x86/mm/testmmiotrace.c | 13519 | 3123 | /*
* Written by Pekka Paalanen, 2008-2009 <pq@iki.fi>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/io.h>
#include <linux/mmiotrace.h>
static unsigned long mmio_address;
module_param(mmio_address, ulong, 0);
MODULE_PARM_DESC(mmio_address, " Start address of the mapping of 16 kB "
"(or 8 MB if read_far is non-zero).");
static unsigned long read_far = 0x400100;
module_param(read_far, ulong, 0);
MODULE_PARM_DESC(read_far, " Offset of a 32-bit read within 8 MB "
"(default: 0x400100).");
static unsigned v16(unsigned i)
{
return i * 12 + 7;
}
static unsigned v32(unsigned i)
{
return i * 212371 + 13;
}
static void do_write_test(void __iomem *p)
{
unsigned int i;
pr_info("write test.\n");
mmiotrace_printk("Write test.\n");
for (i = 0; i < 256; i++)
iowrite8(i, p + i);
for (i = 1024; i < (5 * 1024); i += 2)
iowrite16(v16(i), p + i);
for (i = (5 * 1024); i < (16 * 1024); i += 4)
iowrite32(v32(i), p + i);
}
static void do_read_test(void __iomem *p)
{
unsigned int i;
unsigned errs[3] = { 0 };
pr_info("read test.\n");
mmiotrace_printk("Read test.\n");
for (i = 0; i < 256; i++)
if (ioread8(p + i) != i)
++errs[0];
for (i = 1024; i < (5 * 1024); i += 2)
if (ioread16(p + i) != v16(i))
++errs[1];
for (i = (5 * 1024); i < (16 * 1024); i += 4)
if (ioread32(p + i) != v32(i))
++errs[2];
mmiotrace_printk("Read errors: 8-bit %d, 16-bit %d, 32-bit %d.\n",
errs[0], errs[1], errs[2]);
}
static void do_read_far_test(void __iomem *p)
{
pr_info("read far test.\n");
mmiotrace_printk("Read far test.\n");
ioread32(p + read_far);
}
static void do_test(unsigned long size)
{
void __iomem *p = ioremap_nocache(mmio_address, size);
if (!p) {
pr_err("could not ioremap, aborting.\n");
return;
}
mmiotrace_printk("ioremap returned %p.\n", p);
do_write_test(p);
do_read_test(p);
if (read_far && read_far < size - 4)
do_read_far_test(p);
iounmap(p);
}
/*
* Tests how mmiotrace behaves in face of multiple ioremap / iounmaps in
* a short time. We had a bug in deferred freeing procedure which tried
* to free this region multiple times (ioremap can reuse the same address
* for many mappings).
*/
static void do_test_bulk_ioremapping(void)
{
void __iomem *p;
int i;
for (i = 0; i < 10; ++i) {
p = ioremap_nocache(mmio_address, PAGE_SIZE);
if (p)
iounmap(p);
}
/* Force freeing. If it will crash we will know why. */
synchronize_rcu();
}
static int __init init(void)
{
unsigned long size = (read_far) ? (8 << 20) : (16 << 10);
if (mmio_address == 0) {
pr_err("you have to use the module argument mmio_address.\n");
pr_err("DO NOT LOAD THIS MODULE UNLESS YOU REALLY KNOW WHAT YOU ARE DOING!\n");
return -ENXIO;
}
pr_warning("WARNING: mapping %lu kB @ 0x%08lx in PCI address space, "
"and writing 16 kB of rubbish in there.\n",
size >> 10, mmio_address);
do_test(size);
do_test_bulk_ioremapping();
pr_info("All done.\n");
return 0;
}
static void __exit cleanup(void)
{
pr_debug("unloaded.\n");
}
module_init(init);
module_exit(cleanup);
MODULE_LICENSE("GPL");
| gpl-2.0 |
Quarx2k/jordan-kernel | drivers/media/dvb/siano/smscoreapi.c | 464 | 43088 | /*
* Siano core API module
*
* This file contains implementation for the interface to sms core component
*
* author: Uri Shkolnik
*
* Copyright (c), 2005-2008 Siano Mobile Silicon, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
*
* 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/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/dma-mapping.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/firmware.h>
#include <linux/wait.h>
#include <asm/byteorder.h>
#include "smscoreapi.h"
#include "sms-cards.h"
#include "smsir.h"
#include "smsendian.h"
static int sms_dbg;
module_param_named(debug, sms_dbg, int, 0644);
MODULE_PARM_DESC(debug, "set debug level (info=1, adv=2 (or-able))");
struct smscore_device_notifyee_t {
struct list_head entry;
hotplug_t hotplug;
};
struct smscore_idlist_t {
struct list_head entry;
int id;
int data_type;
};
struct smscore_client_t {
struct list_head entry;
struct smscore_device_t *coredev;
void *context;
struct list_head idlist;
onresponse_t onresponse_handler;
onremove_t onremove_handler;
};
void smscore_set_board_id(struct smscore_device_t *core, int id)
{
core->board_id = id;
}
int smscore_led_state(struct smscore_device_t *core, int led)
{
if (led >= 0)
core->led_state = led;
return core->led_state;
}
EXPORT_SYMBOL_GPL(smscore_set_board_id);
int smscore_get_board_id(struct smscore_device_t *core)
{
return core->board_id;
}
EXPORT_SYMBOL_GPL(smscore_get_board_id);
struct smscore_registry_entry_t {
struct list_head entry;
char devpath[32];
int mode;
enum sms_device_type_st type;
};
static struct list_head g_smscore_notifyees;
static struct list_head g_smscore_devices;
static struct mutex g_smscore_deviceslock;
static struct list_head g_smscore_registry;
static struct mutex g_smscore_registrylock;
static int default_mode = 4;
module_param(default_mode, int, 0644);
MODULE_PARM_DESC(default_mode, "default firmware id (device mode)");
static struct smscore_registry_entry_t *smscore_find_registry(char *devpath)
{
struct smscore_registry_entry_t *entry;
struct list_head *next;
kmutex_lock(&g_smscore_registrylock);
for (next = g_smscore_registry.next;
next != &g_smscore_registry;
next = next->next) {
entry = (struct smscore_registry_entry_t *) next;
if (!strcmp(entry->devpath, devpath)) {
kmutex_unlock(&g_smscore_registrylock);
return entry;
}
}
entry = (struct smscore_registry_entry_t *)
kmalloc(sizeof(struct smscore_registry_entry_t),
GFP_KERNEL);
if (entry) {
entry->mode = default_mode;
strcpy(entry->devpath, devpath);
list_add(&entry->entry, &g_smscore_registry);
} else
sms_err("failed to create smscore_registry.");
kmutex_unlock(&g_smscore_registrylock);
return entry;
}
int smscore_registry_getmode(char *devpath)
{
struct smscore_registry_entry_t *entry;
entry = smscore_find_registry(devpath);
if (entry)
return entry->mode;
else
sms_err("No registry found.");
return default_mode;
}
EXPORT_SYMBOL_GPL(smscore_registry_getmode);
static enum sms_device_type_st smscore_registry_gettype(char *devpath)
{
struct smscore_registry_entry_t *entry;
entry = smscore_find_registry(devpath);
if (entry)
return entry->type;
else
sms_err("No registry found.");
return -1;
}
void smscore_registry_setmode(char *devpath, int mode)
{
struct smscore_registry_entry_t *entry;
entry = smscore_find_registry(devpath);
if (entry)
entry->mode = mode;
else
sms_err("No registry found.");
}
static void smscore_registry_settype(char *devpath,
enum sms_device_type_st type)
{
struct smscore_registry_entry_t *entry;
entry = smscore_find_registry(devpath);
if (entry)
entry->type = type;
else
sms_err("No registry found.");
}
static void list_add_locked(struct list_head *new, struct list_head *head,
spinlock_t *lock)
{
unsigned long flags;
spin_lock_irqsave(lock, flags);
list_add(new, head);
spin_unlock_irqrestore(lock, flags);
}
/**
* register a client callback that called when device plugged in/unplugged
* NOTE: if devices exist callback is called immediately for each device
*
* @param hotplug callback
*
* @return 0 on success, <0 on error.
*/
int smscore_register_hotplug(hotplug_t hotplug)
{
struct smscore_device_notifyee_t *notifyee;
struct list_head *next, *first;
int rc = 0;
kmutex_lock(&g_smscore_deviceslock);
notifyee = kmalloc(sizeof(struct smscore_device_notifyee_t),
GFP_KERNEL);
if (notifyee) {
/* now notify callback about existing devices */
first = &g_smscore_devices;
for (next = first->next;
next != first && !rc;
next = next->next) {
struct smscore_device_t *coredev =
(struct smscore_device_t *) next;
rc = hotplug(coredev, coredev->device, 1);
}
if (rc >= 0) {
notifyee->hotplug = hotplug;
list_add(¬ifyee->entry, &g_smscore_notifyees);
} else
kfree(notifyee);
} else
rc = -ENOMEM;
kmutex_unlock(&g_smscore_deviceslock);
return rc;
}
EXPORT_SYMBOL_GPL(smscore_register_hotplug);
/**
* unregister a client callback that called when device plugged in/unplugged
*
* @param hotplug callback
*
*/
void smscore_unregister_hotplug(hotplug_t hotplug)
{
struct list_head *next, *first;
kmutex_lock(&g_smscore_deviceslock);
first = &g_smscore_notifyees;
for (next = first->next; next != first;) {
struct smscore_device_notifyee_t *notifyee =
(struct smscore_device_notifyee_t *) next;
next = next->next;
if (notifyee->hotplug == hotplug) {
list_del(¬ifyee->entry);
kfree(notifyee);
}
}
kmutex_unlock(&g_smscore_deviceslock);
}
EXPORT_SYMBOL_GPL(smscore_unregister_hotplug);
static void smscore_notify_clients(struct smscore_device_t *coredev)
{
struct smscore_client_t *client;
/* the client must call smscore_unregister_client from remove handler */
while (!list_empty(&coredev->clients)) {
client = (struct smscore_client_t *) coredev->clients.next;
client->onremove_handler(client->context);
}
}
static int smscore_notify_callbacks(struct smscore_device_t *coredev,
struct device *device, int arrival)
{
struct list_head *next, *first;
int rc = 0;
/* note: must be called under g_deviceslock */
first = &g_smscore_notifyees;
for (next = first->next; next != first; next = next->next) {
rc = ((struct smscore_device_notifyee_t *) next)->
hotplug(coredev, device, arrival);
if (rc < 0)
break;
}
return rc;
}
static struct
smscore_buffer_t *smscore_createbuffer(u8 *buffer, void *common_buffer,
dma_addr_t common_buffer_phys)
{
struct smscore_buffer_t *cb =
kmalloc(sizeof(struct smscore_buffer_t), GFP_KERNEL);
if (!cb) {
sms_info("kmalloc(...) failed");
return NULL;
}
cb->p = buffer;
cb->offset_in_common = buffer - (u8 *) common_buffer;
cb->phys = common_buffer_phys + cb->offset_in_common;
return cb;
}
/**
* creates coredev object for a device, prepares buffers,
* creates buffer mappings, notifies registered hotplugs about new device.
*
* @param params device pointer to struct with device specific parameters
* and handlers
* @param coredev pointer to a value that receives created coredev object
*
* @return 0 on success, <0 on error.
*/
int smscore_register_device(struct smsdevice_params_t *params,
struct smscore_device_t **coredev)
{
struct smscore_device_t *dev;
u8 *buffer;
dev = kzalloc(sizeof(struct smscore_device_t), GFP_KERNEL);
if (!dev) {
sms_info("kzalloc(...) failed");
return -ENOMEM;
}
/* init list entry so it could be safe in smscore_unregister_device */
INIT_LIST_HEAD(&dev->entry);
/* init queues */
INIT_LIST_HEAD(&dev->clients);
INIT_LIST_HEAD(&dev->buffers);
/* init locks */
spin_lock_init(&dev->clientslock);
spin_lock_init(&dev->bufferslock);
/* init completion events */
init_completion(&dev->version_ex_done);
init_completion(&dev->data_download_done);
init_completion(&dev->trigger_done);
init_completion(&dev->init_device_done);
init_completion(&dev->reload_start_done);
init_completion(&dev->resume_done);
init_completion(&dev->gpio_configuration_done);
init_completion(&dev->gpio_set_level_done);
init_completion(&dev->gpio_get_level_done);
init_completion(&dev->ir_init_done);
/* Buffer management */
init_waitqueue_head(&dev->buffer_mng_waitq);
/* alloc common buffer */
dev->common_buffer_size = params->buffer_size * params->num_buffers;
dev->common_buffer = dma_alloc_coherent(NULL, dev->common_buffer_size,
&dev->common_buffer_phys,
GFP_KERNEL | GFP_DMA);
if (!dev->common_buffer) {
smscore_unregister_device(dev);
return -ENOMEM;
}
/* prepare dma buffers */
for (buffer = dev->common_buffer;
dev->num_buffers < params->num_buffers;
dev->num_buffers++, buffer += params->buffer_size) {
struct smscore_buffer_t *cb =
smscore_createbuffer(buffer, dev->common_buffer,
dev->common_buffer_phys);
if (!cb) {
smscore_unregister_device(dev);
return -ENOMEM;
}
smscore_putbuffer(dev, cb);
}
sms_info("allocated %d buffers", dev->num_buffers);
dev->mode = DEVICE_MODE_NONE;
dev->context = params->context;
dev->device = params->device;
dev->setmode_handler = params->setmode_handler;
dev->detectmode_handler = params->detectmode_handler;
dev->sendrequest_handler = params->sendrequest_handler;
dev->preload_handler = params->preload_handler;
dev->postload_handler = params->postload_handler;
dev->device_flags = params->flags;
strcpy(dev->devpath, params->devpath);
smscore_registry_settype(dev->devpath, params->device_type);
/* add device to devices list */
kmutex_lock(&g_smscore_deviceslock);
list_add(&dev->entry, &g_smscore_devices);
kmutex_unlock(&g_smscore_deviceslock);
*coredev = dev;
sms_info("device %p created", dev);
return 0;
}
EXPORT_SYMBOL_GPL(smscore_register_device);
static int smscore_sendrequest_and_wait(struct smscore_device_t *coredev,
void *buffer, size_t size, struct completion *completion) {
int rc = coredev->sendrequest_handler(coredev->context, buffer, size);
if (rc < 0) {
sms_info("sendrequest returned error %d", rc);
return rc;
}
return wait_for_completion_timeout(completion,
msecs_to_jiffies(SMS_PROTOCOL_MAX_RAOUNDTRIP_MS)) ?
0 : -ETIME;
}
/**
* Starts & enables IR operations
*
* @return 0 on success, < 0 on error.
*/
static int smscore_init_ir(struct smscore_device_t *coredev)
{
int ir_io;
int rc;
void *buffer;
coredev->ir.input_dev = NULL;
ir_io = sms_get_board(smscore_get_board_id(coredev))->board_cfg.ir;
if (ir_io) {/* only if IR port exist we use IR sub-module */
sms_info("IR loading");
rc = sms_ir_init(coredev);
if (rc != 0)
sms_err("Error initialization DTV IR sub-module");
else {
buffer = kmalloc(sizeof(struct SmsMsgData_ST2) +
SMS_DMA_ALIGNMENT,
GFP_KERNEL | GFP_DMA);
if (buffer) {
struct SmsMsgData_ST2 *msg =
(struct SmsMsgData_ST2 *)
SMS_ALIGN_ADDRESS(buffer);
SMS_INIT_MSG(&msg->xMsgHeader,
MSG_SMS_START_IR_REQ,
sizeof(struct SmsMsgData_ST2));
msg->msgData[0] = coredev->ir.controller;
msg->msgData[1] = coredev->ir.timeout;
smsendian_handle_tx_message(
(struct SmsMsgHdr_ST2 *)msg);
rc = smscore_sendrequest_and_wait(coredev, msg,
msg->xMsgHeader. msgLength,
&coredev->ir_init_done);
kfree(buffer);
} else
sms_err
("Sending IR initialization message failed");
}
} else
sms_info("IR port has not been detected");
return 0;
}
/**
* sets initial device mode and notifies client hotplugs that device is ready
*
* @param coredev pointer to a coredev object returned by
* smscore_register_device
*
* @return 0 on success, <0 on error.
*/
int smscore_start_device(struct smscore_device_t *coredev)
{
int rc = smscore_set_device_mode(
coredev, smscore_registry_getmode(coredev->devpath));
if (rc < 0) {
sms_info("set device mode faile , rc %d", rc);
return rc;
}
kmutex_lock(&g_smscore_deviceslock);
rc = smscore_notify_callbacks(coredev, coredev->device, 1);
smscore_init_ir(coredev);
sms_info("device %p started, rc %d", coredev, rc);
kmutex_unlock(&g_smscore_deviceslock);
return rc;
}
EXPORT_SYMBOL_GPL(smscore_start_device);
static int smscore_load_firmware_family2(struct smscore_device_t *coredev,
void *buffer, size_t size)
{
struct SmsFirmware_ST *firmware = (struct SmsFirmware_ST *) buffer;
struct SmsMsgHdr_ST *msg;
u32 mem_address;
u8 *payload = firmware->Payload;
int rc = 0;
firmware->StartAddress = le32_to_cpu(firmware->StartAddress);
firmware->Length = le32_to_cpu(firmware->Length);
mem_address = firmware->StartAddress;
sms_info("loading FW to addr 0x%x size %d",
mem_address, firmware->Length);
if (coredev->preload_handler) {
rc = coredev->preload_handler(coredev->context);
if (rc < 0)
return rc;
}
/* PAGE_SIZE buffer shall be enough and dma aligned */
msg = kmalloc(PAGE_SIZE, GFP_KERNEL | GFP_DMA);
if (!msg)
return -ENOMEM;
if (coredev->mode != DEVICE_MODE_NONE) {
sms_debug("sending reload command.");
SMS_INIT_MSG(msg, MSG_SW_RELOAD_START_REQ,
sizeof(struct SmsMsgHdr_ST));
rc = smscore_sendrequest_and_wait(coredev, msg,
msg->msgLength,
&coredev->reload_start_done);
mem_address = *(u32 *) &payload[20];
}
while (size && rc >= 0) {
struct SmsDataDownload_ST *DataMsg =
(struct SmsDataDownload_ST *) msg;
int payload_size = min((int) size, SMS_MAX_PAYLOAD_SIZE);
SMS_INIT_MSG(msg, MSG_SMS_DATA_DOWNLOAD_REQ,
(u16)(sizeof(struct SmsMsgHdr_ST) +
sizeof(u32) + payload_size));
DataMsg->MemAddr = mem_address;
memcpy(DataMsg->Payload, payload, payload_size);
if ((coredev->device_flags & SMS_ROM_NO_RESPONSE) &&
(coredev->mode == DEVICE_MODE_NONE))
rc = coredev->sendrequest_handler(
coredev->context, DataMsg,
DataMsg->xMsgHeader.msgLength);
else
rc = smscore_sendrequest_and_wait(
coredev, DataMsg,
DataMsg->xMsgHeader.msgLength,
&coredev->data_download_done);
payload += payload_size;
size -= payload_size;
mem_address += payload_size;
}
if (rc >= 0) {
if (coredev->mode == DEVICE_MODE_NONE) {
struct SmsMsgData_ST *TriggerMsg =
(struct SmsMsgData_ST *) msg;
SMS_INIT_MSG(msg, MSG_SMS_SWDOWNLOAD_TRIGGER_REQ,
sizeof(struct SmsMsgHdr_ST) +
sizeof(u32) * 5);
TriggerMsg->msgData[0] = firmware->StartAddress;
/* Entry point */
TriggerMsg->msgData[1] = 5; /* Priority */
TriggerMsg->msgData[2] = 0x200; /* Stack size */
TriggerMsg->msgData[3] = 0; /* Parameter */
TriggerMsg->msgData[4] = 4; /* Task ID */
if (coredev->device_flags & SMS_ROM_NO_RESPONSE) {
rc = coredev->sendrequest_handler(
coredev->context, TriggerMsg,
TriggerMsg->xMsgHeader.msgLength);
msleep(100);
} else
rc = smscore_sendrequest_and_wait(
coredev, TriggerMsg,
TriggerMsg->xMsgHeader.msgLength,
&coredev->trigger_done);
} else {
SMS_INIT_MSG(msg, MSG_SW_RELOAD_EXEC_REQ,
sizeof(struct SmsMsgHdr_ST));
rc = coredev->sendrequest_handler(coredev->context,
msg, msg->msgLength);
}
msleep(500);
}
sms_debug("rc=%d, postload=%p ", rc,
coredev->postload_handler);
kfree(msg);
return ((rc >= 0) && coredev->postload_handler) ?
coredev->postload_handler(coredev->context) :
rc;
}
/**
* loads specified firmware into a buffer and calls device loadfirmware_handler
*
* @param coredev pointer to a coredev object returned by
* smscore_register_device
* @param filename null-terminated string specifies firmware file name
* @param loadfirmware_handler device handler that loads firmware
*
* @return 0 on success, <0 on error.
*/
static int smscore_load_firmware_from_file(struct smscore_device_t *coredev,
char *filename,
loadfirmware_t loadfirmware_handler)
{
int rc = -ENOENT;
const struct firmware *fw;
u8 *fw_buffer;
if (loadfirmware_handler == NULL && !(coredev->device_flags &
SMS_DEVICE_FAMILY2))
return -EINVAL;
rc = request_firmware(&fw, filename, coredev->device);
if (rc < 0) {
sms_info("failed to open \"%s\"", filename);
return rc;
}
sms_info("read FW %s, size=%zd", filename, fw->size);
fw_buffer = kmalloc(ALIGN(fw->size, SMS_ALLOC_ALIGNMENT),
GFP_KERNEL | GFP_DMA);
if (fw_buffer) {
memcpy(fw_buffer, fw->data, fw->size);
rc = (coredev->device_flags & SMS_DEVICE_FAMILY2) ?
smscore_load_firmware_family2(coredev,
fw_buffer,
fw->size) :
loadfirmware_handler(coredev->context,
fw_buffer, fw->size);
kfree(fw_buffer);
} else {
sms_info("failed to allocate firmware buffer");
rc = -ENOMEM;
}
release_firmware(fw);
return rc;
}
/**
* notifies all clients registered with the device, notifies hotplugs,
* frees all buffers and coredev object
*
* @param coredev pointer to a coredev object returned by
* smscore_register_device
*
* @return 0 on success, <0 on error.
*/
void smscore_unregister_device(struct smscore_device_t *coredev)
{
struct smscore_buffer_t *cb;
int num_buffers = 0;
int retry = 0;
kmutex_lock(&g_smscore_deviceslock);
/* Release input device (IR) resources */
sms_ir_exit(coredev);
smscore_notify_clients(coredev);
smscore_notify_callbacks(coredev, NULL, 0);
/* at this point all buffers should be back
* onresponse must no longer be called */
while (1) {
while (!list_empty(&coredev->buffers)) {
cb = (struct smscore_buffer_t *) coredev->buffers.next;
list_del(&cb->entry);
kfree(cb);
num_buffers++;
}
if (num_buffers == coredev->num_buffers)
break;
if (++retry > 10) {
sms_info("exiting although "
"not all buffers released.");
break;
}
sms_info("waiting for %d buffer(s)",
coredev->num_buffers - num_buffers);
msleep(100);
}
sms_info("freed %d buffers", num_buffers);
if (coredev->common_buffer)
dma_free_coherent(NULL, coredev->common_buffer_size,
coredev->common_buffer, coredev->common_buffer_phys);
if (coredev->fw_buf != NULL)
kfree(coredev->fw_buf);
list_del(&coredev->entry);
kfree(coredev);
kmutex_unlock(&g_smscore_deviceslock);
sms_info("device %p destroyed", coredev);
}
EXPORT_SYMBOL_GPL(smscore_unregister_device);
static int smscore_detect_mode(struct smscore_device_t *coredev)
{
void *buffer = kmalloc(sizeof(struct SmsMsgHdr_ST) + SMS_DMA_ALIGNMENT,
GFP_KERNEL | GFP_DMA);
struct SmsMsgHdr_ST *msg =
(struct SmsMsgHdr_ST *) SMS_ALIGN_ADDRESS(buffer);
int rc;
if (!buffer)
return -ENOMEM;
SMS_INIT_MSG(msg, MSG_SMS_GET_VERSION_EX_REQ,
sizeof(struct SmsMsgHdr_ST));
rc = smscore_sendrequest_and_wait(coredev, msg, msg->msgLength,
&coredev->version_ex_done);
if (rc == -ETIME) {
sms_err("MSG_SMS_GET_VERSION_EX_REQ failed first try");
if (wait_for_completion_timeout(&coredev->resume_done,
msecs_to_jiffies(5000))) {
rc = smscore_sendrequest_and_wait(
coredev, msg, msg->msgLength,
&coredev->version_ex_done);
if (rc < 0)
sms_err("MSG_SMS_GET_VERSION_EX_REQ failed "
"second try, rc %d", rc);
} else
rc = -ETIME;
}
kfree(buffer);
return rc;
}
static char *smscore_fw_lkup[][SMS_NUM_OF_DEVICE_TYPES] = {
/*Stellar NOVA A0 Nova B0 VEGA*/
/*DVBT*/
{"none", "dvb_nova_12mhz.inp", "dvb_nova_12mhz_b0.inp", "none"},
/*DVBH*/
{"none", "dvb_nova_12mhz.inp", "dvb_nova_12mhz_b0.inp", "none"},
/*TDMB*/
{"none", "tdmb_nova_12mhz.inp", "tdmb_nova_12mhz_b0.inp", "none"},
/*DABIP*/
{"none", "none", "none", "none"},
/*BDA*/
{"none", "dvb_nova_12mhz.inp", "dvb_nova_12mhz_b0.inp", "none"},
/*ISDBT*/
{"none", "isdbt_nova_12mhz.inp", "isdbt_nova_12mhz_b0.inp", "none"},
/*ISDBTBDA*/
{"none", "isdbt_nova_12mhz.inp", "isdbt_nova_12mhz_b0.inp", "none"},
/*CMMB*/
{"none", "none", "none", "cmmb_vega_12mhz.inp"}
};
static inline char *sms_get_fw_name(struct smscore_device_t *coredev,
int mode, enum sms_device_type_st type)
{
char **fw = sms_get_board(smscore_get_board_id(coredev))->fw;
return (fw && fw[mode]) ? fw[mode] : smscore_fw_lkup[mode][type];
}
/**
* calls device handler to change mode of operation
* NOTE: stellar/usb may disconnect when changing mode
*
* @param coredev pointer to a coredev object returned by
* smscore_register_device
* @param mode requested mode of operation
*
* @return 0 on success, <0 on error.
*/
int smscore_set_device_mode(struct smscore_device_t *coredev, int mode)
{
void *buffer;
int rc = 0;
enum sms_device_type_st type;
sms_debug("set device mode to %d", mode);
if (coredev->device_flags & SMS_DEVICE_FAMILY2) {
if (mode < DEVICE_MODE_DVBT || mode >= DEVICE_MODE_RAW_TUNER) {
sms_err("invalid mode specified %d", mode);
return -EINVAL;
}
smscore_registry_setmode(coredev->devpath, mode);
if (!(coredev->device_flags & SMS_DEVICE_NOT_READY)) {
rc = smscore_detect_mode(coredev);
if (rc < 0) {
sms_err("mode detect failed %d", rc);
return rc;
}
}
if (coredev->mode == mode) {
sms_info("device mode %d already set", mode);
return 0;
}
if (!(coredev->modes_supported & (1 << mode))) {
char *fw_filename;
type = smscore_registry_gettype(coredev->devpath);
fw_filename = sms_get_fw_name(coredev, mode, type);
rc = smscore_load_firmware_from_file(coredev,
fw_filename, NULL);
if (rc < 0) {
sms_warn("error %d loading firmware: %s, "
"trying again with default firmware",
rc, fw_filename);
/* try again with the default firmware */
fw_filename = smscore_fw_lkup[mode][type];
rc = smscore_load_firmware_from_file(coredev,
fw_filename, NULL);
if (rc < 0) {
sms_warn("error %d loading "
"firmware: %s", rc,
fw_filename);
return rc;
}
}
sms_log("firmware download success: %s", fw_filename);
} else
sms_info("mode %d supported by running "
"firmware", mode);
buffer = kmalloc(sizeof(struct SmsMsgData_ST) +
SMS_DMA_ALIGNMENT, GFP_KERNEL | GFP_DMA);
if (buffer) {
struct SmsMsgData_ST *msg =
(struct SmsMsgData_ST *)
SMS_ALIGN_ADDRESS(buffer);
SMS_INIT_MSG(&msg->xMsgHeader, MSG_SMS_INIT_DEVICE_REQ,
sizeof(struct SmsMsgData_ST));
msg->msgData[0] = mode;
rc = smscore_sendrequest_and_wait(
coredev, msg, msg->xMsgHeader.msgLength,
&coredev->init_device_done);
kfree(buffer);
} else {
sms_err("Could not allocate buffer for "
"init device message.");
rc = -ENOMEM;
}
} else {
if (mode < DEVICE_MODE_DVBT || mode > DEVICE_MODE_DVBT_BDA) {
sms_err("invalid mode specified %d", mode);
return -EINVAL;
}
smscore_registry_setmode(coredev->devpath, mode);
if (coredev->detectmode_handler)
coredev->detectmode_handler(coredev->context,
&coredev->mode);
if (coredev->mode != mode && coredev->setmode_handler)
rc = coredev->setmode_handler(coredev->context, mode);
}
if (rc >= 0) {
coredev->mode = mode;
coredev->device_flags &= ~SMS_DEVICE_NOT_READY;
}
if (rc < 0)
sms_err("return error code %d.", rc);
return rc;
}
/**
* calls device handler to get current mode of operation
*
* @param coredev pointer to a coredev object returned by
* smscore_register_device
*
* @return current mode
*/
int smscore_get_device_mode(struct smscore_device_t *coredev)
{
return coredev->mode;
}
EXPORT_SYMBOL_GPL(smscore_get_device_mode);
/**
* find client by response id & type within the clients list.
* return client handle or NULL.
*
* @param coredev pointer to a coredev object returned by
* smscore_register_device
* @param data_type client data type (SMS_DONT_CARE for all types)
* @param id client id (SMS_DONT_CARE for all id)
*
*/
static struct
smscore_client_t *smscore_find_client(struct smscore_device_t *coredev,
int data_type, int id)
{
struct smscore_client_t *client = NULL;
struct list_head *next, *first;
unsigned long flags;
struct list_head *firstid, *nextid;
spin_lock_irqsave(&coredev->clientslock, flags);
first = &coredev->clients;
for (next = first->next;
(next != first) && !client;
next = next->next) {
firstid = &((struct smscore_client_t *)next)->idlist;
for (nextid = firstid->next;
nextid != firstid;
nextid = nextid->next) {
if ((((struct smscore_idlist_t *)nextid)->id == id) &&
(((struct smscore_idlist_t *)nextid)->data_type == data_type ||
(((struct smscore_idlist_t *)nextid)->data_type == 0))) {
client = (struct smscore_client_t *) next;
break;
}
}
}
spin_unlock_irqrestore(&coredev->clientslock, flags);
return client;
}
/**
* find client by response id/type, call clients onresponse handler
* return buffer to pool on error
*
* @param coredev pointer to a coredev object returned by
* smscore_register_device
* @param cb pointer to response buffer descriptor
*
*/
void smscore_onresponse(struct smscore_device_t *coredev,
struct smscore_buffer_t *cb) {
struct SmsMsgHdr_ST *phdr = (struct SmsMsgHdr_ST *) ((u8 *) cb->p
+ cb->offset);
struct smscore_client_t *client;
int rc = -EBUSY;
static unsigned long last_sample_time; /* = 0; */
static int data_total; /* = 0; */
unsigned long time_now = jiffies_to_msecs(jiffies);
if (!last_sample_time)
last_sample_time = time_now;
if (time_now - last_sample_time > 10000) {
sms_debug("\ndata rate %d bytes/secs",
(int)((data_total * 1000) /
(time_now - last_sample_time)));
last_sample_time = time_now;
data_total = 0;
}
data_total += cb->size;
/* Do we need to re-route? */
if ((phdr->msgType == MSG_SMS_HO_PER_SLICES_IND) ||
(phdr->msgType == MSG_SMS_TRANSMISSION_IND)) {
if (coredev->mode == DEVICE_MODE_DVBT_BDA)
phdr->msgDstId = DVBT_BDA_CONTROL_MSG_ID;
}
client = smscore_find_client(coredev, phdr->msgType, phdr->msgDstId);
/* If no client registered for type & id,
* check for control client where type is not registered */
if (client)
rc = client->onresponse_handler(client->context, cb);
if (rc < 0) {
switch (phdr->msgType) {
case MSG_SMS_GET_VERSION_EX_RES:
{
struct SmsVersionRes_ST *ver =
(struct SmsVersionRes_ST *) phdr;
sms_debug("MSG_SMS_GET_VERSION_EX_RES "
"id %d prots 0x%x ver %d.%d",
ver->FirmwareId, ver->SupportedProtocols,
ver->RomVersionMajor, ver->RomVersionMinor);
coredev->mode = ver->FirmwareId == 255 ?
DEVICE_MODE_NONE : ver->FirmwareId;
coredev->modes_supported = ver->SupportedProtocols;
complete(&coredev->version_ex_done);
break;
}
case MSG_SMS_INIT_DEVICE_RES:
sms_debug("MSG_SMS_INIT_DEVICE_RES");
complete(&coredev->init_device_done);
break;
case MSG_SW_RELOAD_START_RES:
sms_debug("MSG_SW_RELOAD_START_RES");
complete(&coredev->reload_start_done);
break;
case MSG_SMS_DATA_DOWNLOAD_RES:
complete(&coredev->data_download_done);
break;
case MSG_SW_RELOAD_EXEC_RES:
sms_debug("MSG_SW_RELOAD_EXEC_RES");
break;
case MSG_SMS_SWDOWNLOAD_TRIGGER_RES:
sms_debug("MSG_SMS_SWDOWNLOAD_TRIGGER_RES");
complete(&coredev->trigger_done);
break;
case MSG_SMS_SLEEP_RESUME_COMP_IND:
complete(&coredev->resume_done);
break;
case MSG_SMS_GPIO_CONFIG_EX_RES:
sms_debug("MSG_SMS_GPIO_CONFIG_EX_RES");
complete(&coredev->gpio_configuration_done);
break;
case MSG_SMS_GPIO_SET_LEVEL_RES:
sms_debug("MSG_SMS_GPIO_SET_LEVEL_RES");
complete(&coredev->gpio_set_level_done);
break;
case MSG_SMS_GPIO_GET_LEVEL_RES:
{
u32 *msgdata = (u32 *) phdr;
coredev->gpio_get_res = msgdata[1];
sms_debug("MSG_SMS_GPIO_GET_LEVEL_RES gpio level %d",
coredev->gpio_get_res);
complete(&coredev->gpio_get_level_done);
break;
}
case MSG_SMS_START_IR_RES:
complete(&coredev->ir_init_done);
break;
case MSG_SMS_IR_SAMPLES_IND:
sms_ir_event(coredev,
(const char *)
((char *)phdr
+ sizeof(struct SmsMsgHdr_ST)),
(int)phdr->msgLength
- sizeof(struct SmsMsgHdr_ST));
break;
default:
break;
}
smscore_putbuffer(coredev, cb);
}
}
EXPORT_SYMBOL_GPL(smscore_onresponse);
/**
* return pointer to next free buffer descriptor from core pool
*
* @param coredev pointer to a coredev object returned by
* smscore_register_device
*
* @return pointer to descriptor on success, NULL on error.
*/
struct smscore_buffer_t *smscore_getbuffer(struct smscore_device_t *coredev)
{
struct smscore_buffer_t *cb = NULL;
unsigned long flags;
DEFINE_WAIT(wait);
spin_lock_irqsave(&coredev->bufferslock, flags);
/* This function must return a valid buffer, since the buffer list is
* finite, we check that there is an available buffer, if not, we wait
* until such buffer become available.
*/
prepare_to_wait(&coredev->buffer_mng_waitq, &wait, TASK_INTERRUPTIBLE);
if (list_empty(&coredev->buffers))
schedule();
finish_wait(&coredev->buffer_mng_waitq, &wait);
cb = (struct smscore_buffer_t *) coredev->buffers.next;
list_del(&cb->entry);
spin_unlock_irqrestore(&coredev->bufferslock, flags);
return cb;
}
EXPORT_SYMBOL_GPL(smscore_getbuffer);
/**
* return buffer descriptor to a pool
*
* @param coredev pointer to a coredev object returned by
* smscore_register_device
* @param cb pointer buffer descriptor
*
*/
void smscore_putbuffer(struct smscore_device_t *coredev,
struct smscore_buffer_t *cb) {
wake_up_interruptible(&coredev->buffer_mng_waitq);
list_add_locked(&cb->entry, &coredev->buffers, &coredev->bufferslock);
}
EXPORT_SYMBOL_GPL(smscore_putbuffer);
static int smscore_validate_client(struct smscore_device_t *coredev,
struct smscore_client_t *client,
int data_type, int id)
{
struct smscore_idlist_t *listentry;
struct smscore_client_t *registered_client;
if (!client) {
sms_err("bad parameter.");
return -EFAULT;
}
registered_client = smscore_find_client(coredev, data_type, id);
if (registered_client == client)
return 0;
if (registered_client) {
sms_err("The msg ID already registered to another client.");
return -EEXIST;
}
listentry = kzalloc(sizeof(struct smscore_idlist_t), GFP_KERNEL);
if (!listentry) {
sms_err("Can't allocate memory for client id.");
return -ENOMEM;
}
listentry->id = id;
listentry->data_type = data_type;
list_add_locked(&listentry->entry, &client->idlist,
&coredev->clientslock);
return 0;
}
/**
* creates smsclient object, check that id is taken by another client
*
* @param coredev pointer to a coredev object from clients hotplug
* @param initial_id all messages with this id would be sent to this client
* @param data_type all messages of this type would be sent to this client
* @param onresponse_handler client handler that is called to
* process incoming messages
* @param onremove_handler client handler that is called when device is removed
* @param context client-specific context
* @param client pointer to a value that receives created smsclient object
*
* @return 0 on success, <0 on error.
*/
int smscore_register_client(struct smscore_device_t *coredev,
struct smsclient_params_t *params,
struct smscore_client_t **client)
{
struct smscore_client_t *newclient;
/* check that no other channel with same parameters exists */
if (smscore_find_client(coredev, params->data_type,
params->initial_id)) {
sms_err("Client already exist.");
return -EEXIST;
}
newclient = kzalloc(sizeof(struct smscore_client_t), GFP_KERNEL);
if (!newclient) {
sms_err("Failed to allocate memory for client.");
return -ENOMEM;
}
INIT_LIST_HEAD(&newclient->idlist);
newclient->coredev = coredev;
newclient->onresponse_handler = params->onresponse_handler;
newclient->onremove_handler = params->onremove_handler;
newclient->context = params->context;
list_add_locked(&newclient->entry, &coredev->clients,
&coredev->clientslock);
smscore_validate_client(coredev, newclient, params->data_type,
params->initial_id);
*client = newclient;
sms_debug("%p %d %d", params->context, params->data_type,
params->initial_id);
return 0;
}
EXPORT_SYMBOL_GPL(smscore_register_client);
/**
* frees smsclient object and all subclients associated with it
*
* @param client pointer to smsclient object returned by
* smscore_register_client
*
*/
void smscore_unregister_client(struct smscore_client_t *client)
{
struct smscore_device_t *coredev = client->coredev;
unsigned long flags;
spin_lock_irqsave(&coredev->clientslock, flags);
while (!list_empty(&client->idlist)) {
struct smscore_idlist_t *identry =
(struct smscore_idlist_t *) client->idlist.next;
list_del(&identry->entry);
kfree(identry);
}
sms_info("%p", client->context);
list_del(&client->entry);
kfree(client);
spin_unlock_irqrestore(&coredev->clientslock, flags);
}
EXPORT_SYMBOL_GPL(smscore_unregister_client);
/**
* verifies that source id is not taken by another client,
* calls device handler to send requests to the device
*
* @param client pointer to smsclient object returned by
* smscore_register_client
* @param buffer pointer to a request buffer
* @param size size (in bytes) of request buffer
*
* @return 0 on success, <0 on error.
*/
int smsclient_sendrequest(struct smscore_client_t *client,
void *buffer, size_t size)
{
struct smscore_device_t *coredev;
struct SmsMsgHdr_ST *phdr = (struct SmsMsgHdr_ST *) buffer;
int rc;
if (client == NULL) {
sms_err("Got NULL client");
return -EINVAL;
}
coredev = client->coredev;
/* check that no other channel with same id exists */
if (coredev == NULL) {
sms_err("Got NULL coredev");
return -EINVAL;
}
rc = smscore_validate_client(client->coredev, client, 0,
phdr->msgSrcId);
if (rc < 0)
return rc;
return coredev->sendrequest_handler(coredev->context, buffer, size);
}
EXPORT_SYMBOL_GPL(smsclient_sendrequest);
/* old GPIO managments implementation */
int smscore_configure_gpio(struct smscore_device_t *coredev, u32 pin,
struct smscore_config_gpio *pinconfig)
{
struct {
struct SmsMsgHdr_ST hdr;
u32 data[6];
} msg;
if (coredev->device_flags & SMS_DEVICE_FAMILY2) {
msg.hdr.msgSrcId = DVBT_BDA_CONTROL_MSG_ID;
msg.hdr.msgDstId = HIF_TASK;
msg.hdr.msgFlags = 0;
msg.hdr.msgType = MSG_SMS_GPIO_CONFIG_EX_REQ;
msg.hdr.msgLength = sizeof(msg);
msg.data[0] = pin;
msg.data[1] = pinconfig->pullupdown;
/* Convert slew rate for Nova: Fast(0) = 3 / Slow(1) = 0; */
msg.data[2] = pinconfig->outputslewrate == 0 ? 3 : 0;
switch (pinconfig->outputdriving) {
case SMS_GPIO_OUTPUTDRIVING_16mA:
msg.data[3] = 7; /* Nova - 16mA */
break;
case SMS_GPIO_OUTPUTDRIVING_12mA:
msg.data[3] = 5; /* Nova - 11mA */
break;
case SMS_GPIO_OUTPUTDRIVING_8mA:
msg.data[3] = 3; /* Nova - 7mA */
break;
case SMS_GPIO_OUTPUTDRIVING_4mA:
default:
msg.data[3] = 2; /* Nova - 4mA */
break;
}
msg.data[4] = pinconfig->direction;
msg.data[5] = 0;
} else /* TODO: SMS_DEVICE_FAMILY1 */
return -EINVAL;
return coredev->sendrequest_handler(coredev->context,
&msg, sizeof(msg));
}
int smscore_set_gpio(struct smscore_device_t *coredev, u32 pin, int level)
{
struct {
struct SmsMsgHdr_ST hdr;
u32 data[3];
} msg;
if (pin > MAX_GPIO_PIN_NUMBER)
return -EINVAL;
msg.hdr.msgSrcId = DVBT_BDA_CONTROL_MSG_ID;
msg.hdr.msgDstId = HIF_TASK;
msg.hdr.msgFlags = 0;
msg.hdr.msgType = MSG_SMS_GPIO_SET_LEVEL_REQ;
msg.hdr.msgLength = sizeof(msg);
msg.data[0] = pin;
msg.data[1] = level ? 1 : 0;
msg.data[2] = 0;
return coredev->sendrequest_handler(coredev->context,
&msg, sizeof(msg));
}
/* new GPIO management implementation */
static int GetGpioPinParams(u32 PinNum, u32 *pTranslatedPinNum,
u32 *pGroupNum, u32 *pGroupCfg) {
*pGroupCfg = 1;
if (PinNum >= 0 && PinNum <= 1) {
*pTranslatedPinNum = 0;
*pGroupNum = 9;
*pGroupCfg = 2;
} else if (PinNum >= 2 && PinNum <= 6) {
*pTranslatedPinNum = 2;
*pGroupNum = 0;
*pGroupCfg = 2;
} else if (PinNum >= 7 && PinNum <= 11) {
*pTranslatedPinNum = 7;
*pGroupNum = 1;
} else if (PinNum >= 12 && PinNum <= 15) {
*pTranslatedPinNum = 12;
*pGroupNum = 2;
*pGroupCfg = 3;
} else if (PinNum == 16) {
*pTranslatedPinNum = 16;
*pGroupNum = 23;
} else if (PinNum >= 17 && PinNum <= 24) {
*pTranslatedPinNum = 17;
*pGroupNum = 3;
} else if (PinNum == 25) {
*pTranslatedPinNum = 25;
*pGroupNum = 6;
} else if (PinNum >= 26 && PinNum <= 28) {
*pTranslatedPinNum = 26;
*pGroupNum = 4;
} else if (PinNum == 29) {
*pTranslatedPinNum = 29;
*pGroupNum = 5;
*pGroupCfg = 2;
} else if (PinNum == 30) {
*pTranslatedPinNum = 30;
*pGroupNum = 8;
} else if (PinNum == 31) {
*pTranslatedPinNum = 31;
*pGroupNum = 17;
} else
return -1;
*pGroupCfg <<= 24;
return 0;
}
int smscore_gpio_configure(struct smscore_device_t *coredev, u8 PinNum,
struct smscore_gpio_config *pGpioConfig) {
u32 totalLen;
u32 TranslatedPinNum = 0;
u32 GroupNum = 0;
u32 ElectricChar;
u32 groupCfg;
void *buffer;
int rc;
struct SetGpioMsg {
struct SmsMsgHdr_ST xMsgHeader;
u32 msgData[6];
} *pMsg;
if (PinNum > MAX_GPIO_PIN_NUMBER)
return -EINVAL;
if (pGpioConfig == NULL)
return -EINVAL;
totalLen = sizeof(struct SmsMsgHdr_ST) + (sizeof(u32) * 6);
buffer = kmalloc(totalLen + SMS_DMA_ALIGNMENT,
GFP_KERNEL | GFP_DMA);
if (!buffer)
return -ENOMEM;
pMsg = (struct SetGpioMsg *) SMS_ALIGN_ADDRESS(buffer);
pMsg->xMsgHeader.msgSrcId = DVBT_BDA_CONTROL_MSG_ID;
pMsg->xMsgHeader.msgDstId = HIF_TASK;
pMsg->xMsgHeader.msgFlags = 0;
pMsg->xMsgHeader.msgLength = (u16) totalLen;
pMsg->msgData[0] = PinNum;
if (!(coredev->device_flags & SMS_DEVICE_FAMILY2)) {
pMsg->xMsgHeader.msgType = MSG_SMS_GPIO_CONFIG_REQ;
if (GetGpioPinParams(PinNum, &TranslatedPinNum, &GroupNum,
&groupCfg) != 0)
return -EINVAL;
pMsg->msgData[1] = TranslatedPinNum;
pMsg->msgData[2] = GroupNum;
ElectricChar = (pGpioConfig->PullUpDown)
| (pGpioConfig->InputCharacteristics << 2)
| (pGpioConfig->OutputSlewRate << 3)
| (pGpioConfig->OutputDriving << 4);
pMsg->msgData[3] = ElectricChar;
pMsg->msgData[4] = pGpioConfig->Direction;
pMsg->msgData[5] = groupCfg;
} else {
pMsg->xMsgHeader.msgType = MSG_SMS_GPIO_CONFIG_EX_REQ;
pMsg->msgData[1] = pGpioConfig->PullUpDown;
pMsg->msgData[2] = pGpioConfig->OutputSlewRate;
pMsg->msgData[3] = pGpioConfig->OutputDriving;
pMsg->msgData[4] = pGpioConfig->Direction;
pMsg->msgData[5] = 0;
}
smsendian_handle_tx_message((struct SmsMsgHdr_ST *)pMsg);
rc = smscore_sendrequest_and_wait(coredev, pMsg, totalLen,
&coredev->gpio_configuration_done);
if (rc != 0) {
if (rc == -ETIME)
sms_err("smscore_gpio_configure timeout");
else
sms_err("smscore_gpio_configure error");
}
kfree(buffer);
return rc;
}
int smscore_gpio_set_level(struct smscore_device_t *coredev, u8 PinNum,
u8 NewLevel) {
u32 totalLen;
int rc;
void *buffer;
struct SetGpioMsg {
struct SmsMsgHdr_ST xMsgHeader;
u32 msgData[3]; /* keep it 3 ! */
} *pMsg;
if ((NewLevel > 1) || (PinNum > MAX_GPIO_PIN_NUMBER) ||
(PinNum > MAX_GPIO_PIN_NUMBER))
return -EINVAL;
totalLen = sizeof(struct SmsMsgHdr_ST) +
(3 * sizeof(u32)); /* keep it 3 ! */
buffer = kmalloc(totalLen + SMS_DMA_ALIGNMENT,
GFP_KERNEL | GFP_DMA);
if (!buffer)
return -ENOMEM;
pMsg = (struct SetGpioMsg *) SMS_ALIGN_ADDRESS(buffer);
pMsg->xMsgHeader.msgSrcId = DVBT_BDA_CONTROL_MSG_ID;
pMsg->xMsgHeader.msgDstId = HIF_TASK;
pMsg->xMsgHeader.msgFlags = 0;
pMsg->xMsgHeader.msgType = MSG_SMS_GPIO_SET_LEVEL_REQ;
pMsg->xMsgHeader.msgLength = (u16) totalLen;
pMsg->msgData[0] = PinNum;
pMsg->msgData[1] = NewLevel;
/* Send message to SMS */
smsendian_handle_tx_message((struct SmsMsgHdr_ST *)pMsg);
rc = smscore_sendrequest_and_wait(coredev, pMsg, totalLen,
&coredev->gpio_set_level_done);
if (rc != 0) {
if (rc == -ETIME)
sms_err("smscore_gpio_set_level timeout");
else
sms_err("smscore_gpio_set_level error");
}
kfree(buffer);
return rc;
}
int smscore_gpio_get_level(struct smscore_device_t *coredev, u8 PinNum,
u8 *level) {
u32 totalLen;
int rc;
void *buffer;
struct SetGpioMsg {
struct SmsMsgHdr_ST xMsgHeader;
u32 msgData[2];
} *pMsg;
if (PinNum > MAX_GPIO_PIN_NUMBER)
return -EINVAL;
totalLen = sizeof(struct SmsMsgHdr_ST) + (2 * sizeof(u32));
buffer = kmalloc(totalLen + SMS_DMA_ALIGNMENT,
GFP_KERNEL | GFP_DMA);
if (!buffer)
return -ENOMEM;
pMsg = (struct SetGpioMsg *) SMS_ALIGN_ADDRESS(buffer);
pMsg->xMsgHeader.msgSrcId = DVBT_BDA_CONTROL_MSG_ID;
pMsg->xMsgHeader.msgDstId = HIF_TASK;
pMsg->xMsgHeader.msgFlags = 0;
pMsg->xMsgHeader.msgType = MSG_SMS_GPIO_GET_LEVEL_REQ;
pMsg->xMsgHeader.msgLength = (u16) totalLen;
pMsg->msgData[0] = PinNum;
pMsg->msgData[1] = 0;
/* Send message to SMS */
smsendian_handle_tx_message((struct SmsMsgHdr_ST *)pMsg);
rc = smscore_sendrequest_and_wait(coredev, pMsg, totalLen,
&coredev->gpio_get_level_done);
if (rc != 0) {
if (rc == -ETIME)
sms_err("smscore_gpio_get_level timeout");
else
sms_err("smscore_gpio_get_level error");
}
kfree(buffer);
/* Its a race between other gpio_get_level() and the copy of the single
* global 'coredev->gpio_get_res' to the function's variable 'level'
*/
*level = coredev->gpio_get_res;
return rc;
}
static int __init smscore_module_init(void)
{
int rc = 0;
INIT_LIST_HEAD(&g_smscore_notifyees);
INIT_LIST_HEAD(&g_smscore_devices);
kmutex_init(&g_smscore_deviceslock);
INIT_LIST_HEAD(&g_smscore_registry);
kmutex_init(&g_smscore_registrylock);
return rc;
}
static void __exit smscore_module_exit(void)
{
kmutex_lock(&g_smscore_deviceslock);
while (!list_empty(&g_smscore_notifyees)) {
struct smscore_device_notifyee_t *notifyee =
(struct smscore_device_notifyee_t *)
g_smscore_notifyees.next;
list_del(¬ifyee->entry);
kfree(notifyee);
}
kmutex_unlock(&g_smscore_deviceslock);
kmutex_lock(&g_smscore_registrylock);
while (!list_empty(&g_smscore_registry)) {
struct smscore_registry_entry_t *entry =
(struct smscore_registry_entry_t *)
g_smscore_registry.next;
list_del(&entry->entry);
kfree(entry);
}
kmutex_unlock(&g_smscore_registrylock);
sms_debug("");
}
module_init(smscore_module_init);
module_exit(smscore_module_exit);
MODULE_DESCRIPTION("Siano MDTV Core module");
MODULE_AUTHOR("Siano Mobile Silicon, Inc. (uris@siano-ms.com)");
MODULE_LICENSE("GPL");
| gpl-2.0 |
sdadier/gb_kernel_2.6.32.9-mtd | Kernel/drivers/scsi/bfa/fcbuild.c | 464 | 38214 | /*
* Copyright (c) 2005-2009 Brocade Communications Systems, Inc.
* All rights reserved
* www.brocade.com
*
* Linux driver for Brocade Fibre Channel Host Bus Adapter.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License (GPL) Version 2 as
* published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
/*
* fcbuild.c - FC link service frame building and parsing routines
*/
#include <bfa_os_inc.h>
#include "fcbuild.h"
/*
* static build functions
*/
static void fc_els_rsp_build(struct fchs_s *fchs, u32 d_id, u32 s_id,
u16 ox_id);
static void fc_bls_rsp_build(struct fchs_s *fchs, u32 d_id, u32 s_id,
u16 ox_id);
static struct fchs_s fc_els_req_tmpl;
static struct fchs_s fc_els_rsp_tmpl;
static struct fchs_s fc_bls_req_tmpl;
static struct fchs_s fc_bls_rsp_tmpl;
static struct fc_ba_acc_s ba_acc_tmpl;
static struct fc_logi_s plogi_tmpl;
static struct fc_prli_s prli_tmpl;
static struct fc_rrq_s rrq_tmpl;
static struct fchs_s fcp_fchs_tmpl;
void
fcbuild_init(void)
{
/*
* fc_els_req_tmpl
*/
fc_els_req_tmpl.routing = FC_RTG_EXT_LINK;
fc_els_req_tmpl.cat_info = FC_CAT_LD_REQUEST;
fc_els_req_tmpl.type = FC_TYPE_ELS;
fc_els_req_tmpl.f_ctl =
bfa_os_hton3b(FCTL_SEQ_INI | FCTL_FS_EXCH | FCTL_END_SEQ |
FCTL_SI_XFER);
fc_els_req_tmpl.rx_id = FC_RXID_ANY;
/*
* fc_els_rsp_tmpl
*/
fc_els_rsp_tmpl.routing = FC_RTG_EXT_LINK;
fc_els_rsp_tmpl.cat_info = FC_CAT_LD_REPLY;
fc_els_rsp_tmpl.type = FC_TYPE_ELS;
fc_els_rsp_tmpl.f_ctl =
bfa_os_hton3b(FCTL_EC_RESP | FCTL_SEQ_INI | FCTL_LS_EXCH |
FCTL_END_SEQ | FCTL_SI_XFER);
fc_els_rsp_tmpl.rx_id = FC_RXID_ANY;
/*
* fc_bls_req_tmpl
*/
fc_bls_req_tmpl.routing = FC_RTG_BASIC_LINK;
fc_bls_req_tmpl.type = FC_TYPE_BLS;
fc_bls_req_tmpl.f_ctl = bfa_os_hton3b(FCTL_END_SEQ | FCTL_SI_XFER);
fc_bls_req_tmpl.rx_id = FC_RXID_ANY;
/*
* fc_bls_rsp_tmpl
*/
fc_bls_rsp_tmpl.routing = FC_RTG_BASIC_LINK;
fc_bls_rsp_tmpl.cat_info = FC_CAT_BA_ACC;
fc_bls_rsp_tmpl.type = FC_TYPE_BLS;
fc_bls_rsp_tmpl.f_ctl =
bfa_os_hton3b(FCTL_EC_RESP | FCTL_SEQ_INI | FCTL_LS_EXCH |
FCTL_END_SEQ | FCTL_SI_XFER);
fc_bls_rsp_tmpl.rx_id = FC_RXID_ANY;
/*
* ba_acc_tmpl
*/
ba_acc_tmpl.seq_id_valid = 0;
ba_acc_tmpl.low_seq_cnt = 0;
ba_acc_tmpl.high_seq_cnt = 0xFFFF;
/*
* plogi_tmpl
*/
plogi_tmpl.csp.verhi = FC_PH_VER_PH_3;
plogi_tmpl.csp.verlo = FC_PH_VER_4_3;
plogi_tmpl.csp.bbcred = bfa_os_htons(0x0004);
plogi_tmpl.csp.ciro = 0x1;
plogi_tmpl.csp.cisc = 0x0;
plogi_tmpl.csp.altbbcred = 0x0;
plogi_tmpl.csp.conseq = bfa_os_htons(0x00FF);
plogi_tmpl.csp.ro_bitmap = bfa_os_htons(0x0002);
plogi_tmpl.csp.e_d_tov = bfa_os_htonl(2000);
plogi_tmpl.class3.class_valid = 1;
plogi_tmpl.class3.sequential = 1;
plogi_tmpl.class3.conseq = 0xFF;
plogi_tmpl.class3.ospx = 1;
/*
* prli_tmpl
*/
prli_tmpl.command = FC_ELS_PRLI;
prli_tmpl.pglen = 0x10;
prli_tmpl.pagebytes = bfa_os_htons(0x0014);
prli_tmpl.parampage.type = FC_TYPE_FCP;
prli_tmpl.parampage.imagepair = 1;
prli_tmpl.parampage.servparams.rxrdisab = 1;
/*
* rrq_tmpl
*/
rrq_tmpl.els_cmd.els_code = FC_ELS_RRQ;
/*
* fcp_fchs_tmpl
*/
fcp_fchs_tmpl.routing = FC_RTG_FC4_DEV_DATA;
fcp_fchs_tmpl.cat_info = FC_CAT_UNSOLICIT_CMD;
fcp_fchs_tmpl.type = FC_TYPE_FCP;
fcp_fchs_tmpl.f_ctl =
bfa_os_hton3b(FCTL_FS_EXCH | FCTL_END_SEQ | FCTL_SI_XFER);
fcp_fchs_tmpl.seq_id = 1;
fcp_fchs_tmpl.rx_id = FC_RXID_ANY;
}
static void
fc_gs_fchdr_build(struct fchs_s *fchs, u32 d_id, u32 s_id,
u32 ox_id)
{
bfa_os_memset(fchs, 0, sizeof(struct fchs_s));
fchs->routing = FC_RTG_FC4_DEV_DATA;
fchs->cat_info = FC_CAT_UNSOLICIT_CTRL;
fchs->type = FC_TYPE_SERVICES;
fchs->f_ctl =
bfa_os_hton3b(FCTL_SEQ_INI | FCTL_FS_EXCH | FCTL_END_SEQ |
FCTL_SI_XFER);
fchs->rx_id = FC_RXID_ANY;
fchs->d_id = (d_id);
fchs->s_id = (s_id);
fchs->ox_id = bfa_os_htons(ox_id);
/**
* @todo no need to set ox_id for request
* no need to set rx_id for response
*/
}
void
fc_els_req_build(struct fchs_s *fchs, u32 d_id, u32 s_id,
u16 ox_id)
{
bfa_os_memcpy(fchs, &fc_els_req_tmpl, sizeof(struct fchs_s));
fchs->d_id = (d_id);
fchs->s_id = (s_id);
fchs->ox_id = bfa_os_htons(ox_id);
}
static void
fc_els_rsp_build(struct fchs_s *fchs, u32 d_id, u32 s_id,
u16 ox_id)
{
bfa_os_memcpy(fchs, &fc_els_rsp_tmpl, sizeof(struct fchs_s));
fchs->d_id = d_id;
fchs->s_id = s_id;
fchs->ox_id = ox_id;
}
enum fc_parse_status
fc_els_rsp_parse(struct fchs_s *fchs, int len)
{
struct fc_els_cmd_s *els_cmd = (struct fc_els_cmd_s *) (fchs + 1);
struct fc_ls_rjt_s *ls_rjt = (struct fc_ls_rjt_s *) els_cmd;
len = len;
switch (els_cmd->els_code) {
case FC_ELS_LS_RJT:
if (ls_rjt->reason_code == FC_LS_RJT_RSN_LOGICAL_BUSY)
return (FC_PARSE_BUSY);
else
return (FC_PARSE_FAILURE);
case FC_ELS_ACC:
return (FC_PARSE_OK);
}
return (FC_PARSE_OK);
}
static void
fc_bls_rsp_build(struct fchs_s *fchs, u32 d_id, u32 s_id,
u16 ox_id)
{
bfa_os_memcpy(fchs, &fc_bls_rsp_tmpl, sizeof(struct fchs_s));
fchs->d_id = d_id;
fchs->s_id = s_id;
fchs->ox_id = ox_id;
}
static u16
fc_plogi_x_build(struct fchs_s *fchs, void *pld, u32 d_id, u32 s_id,
u16 ox_id, wwn_t port_name, wwn_t node_name,
u16 pdu_size, u8 els_code)
{
struct fc_logi_s *plogi = (struct fc_logi_s *) (pld);
bfa_os_memcpy(plogi, &plogi_tmpl, sizeof(struct fc_logi_s));
plogi->els_cmd.els_code = els_code;
if (els_code == FC_ELS_PLOGI)
fc_els_req_build(fchs, d_id, s_id, ox_id);
else
fc_els_rsp_build(fchs, d_id, s_id, ox_id);
plogi->csp.rxsz = plogi->class3.rxsz = bfa_os_htons(pdu_size);
bfa_os_memcpy(&plogi->port_name, &port_name, sizeof(wwn_t));
bfa_os_memcpy(&plogi->node_name, &node_name, sizeof(wwn_t));
return (sizeof(struct fc_logi_s));
}
u16
fc_flogi_build(struct fchs_s *fchs, struct fc_logi_s *flogi, u32 s_id,
u16 ox_id, wwn_t port_name, wwn_t node_name,
u16 pdu_size, u8 set_npiv, u8 set_auth,
u16 local_bb_credits)
{
u32 d_id = bfa_os_hton3b(FC_FABRIC_PORT);
u32 *vvl_info;
bfa_os_memcpy(flogi, &plogi_tmpl, sizeof(struct fc_logi_s));
flogi->els_cmd.els_code = FC_ELS_FLOGI;
fc_els_req_build(fchs, d_id, s_id, ox_id);
flogi->csp.rxsz = flogi->class3.rxsz = bfa_os_htons(pdu_size);
flogi->port_name = port_name;
flogi->node_name = node_name;
/*
* Set the NPIV Capability Bit ( word 1, bit 31) of Common
* Service Parameters.
*/
flogi->csp.ciro = set_npiv;
/* set AUTH capability */
flogi->csp.security = set_auth;
flogi->csp.bbcred = bfa_os_htons(local_bb_credits);
/* Set brcd token in VVL */
vvl_info = (u32 *)&flogi->vvl[0];
/* set the flag to indicate the presence of VVL */
flogi->csp.npiv_supp = 1; /* @todo. field name is not correct */
vvl_info[0] = bfa_os_htonl(FLOGI_VVL_BRCD);
return (sizeof(struct fc_logi_s));
}
u16
fc_flogi_acc_build(struct fchs_s *fchs, struct fc_logi_s *flogi, u32 s_id,
u16 ox_id, wwn_t port_name, wwn_t node_name,
u16 pdu_size, u16 local_bb_credits)
{
u32 d_id = 0;
bfa_os_memcpy(flogi, &plogi_tmpl, sizeof(struct fc_logi_s));
fc_els_rsp_build(fchs, d_id, s_id, ox_id);
flogi->els_cmd.els_code = FC_ELS_ACC;
flogi->csp.rxsz = flogi->class3.rxsz = bfa_os_htons(pdu_size);
flogi->port_name = port_name;
flogi->node_name = node_name;
flogi->csp.bbcred = bfa_os_htons(local_bb_credits);
return (sizeof(struct fc_logi_s));
}
u16
fc_fdisc_build(struct fchs_s *fchs, struct fc_logi_s *flogi, u32 s_id,
u16 ox_id, wwn_t port_name, wwn_t node_name,
u16 pdu_size)
{
u32 d_id = bfa_os_hton3b(FC_FABRIC_PORT);
bfa_os_memcpy(flogi, &plogi_tmpl, sizeof(struct fc_logi_s));
flogi->els_cmd.els_code = FC_ELS_FDISC;
fc_els_req_build(fchs, d_id, s_id, ox_id);
flogi->csp.rxsz = flogi->class3.rxsz = bfa_os_htons(pdu_size);
flogi->port_name = port_name;
flogi->node_name = node_name;
return (sizeof(struct fc_logi_s));
}
u16
fc_plogi_build(struct fchs_s *fchs, void *pld, u32 d_id, u32 s_id,
u16 ox_id, wwn_t port_name, wwn_t node_name,
u16 pdu_size)
{
return fc_plogi_x_build(fchs, pld, d_id, s_id, ox_id, port_name,
node_name, pdu_size, FC_ELS_PLOGI);
}
u16
fc_plogi_acc_build(struct fchs_s *fchs, void *pld, u32 d_id, u32 s_id,
u16 ox_id, wwn_t port_name, wwn_t node_name,
u16 pdu_size)
{
return fc_plogi_x_build(fchs, pld, d_id, s_id, ox_id, port_name,
node_name, pdu_size, FC_ELS_ACC);
}
enum fc_parse_status
fc_plogi_rsp_parse(struct fchs_s *fchs, int len, wwn_t port_name)
{
struct fc_els_cmd_s *els_cmd = (struct fc_els_cmd_s *) (fchs + 1);
struct fc_logi_s *plogi;
struct fc_ls_rjt_s *ls_rjt;
switch (els_cmd->els_code) {
case FC_ELS_LS_RJT:
ls_rjt = (struct fc_ls_rjt_s *) (fchs + 1);
if (ls_rjt->reason_code == FC_LS_RJT_RSN_LOGICAL_BUSY)
return (FC_PARSE_BUSY);
else
return (FC_PARSE_FAILURE);
case FC_ELS_ACC:
plogi = (struct fc_logi_s *) (fchs + 1);
if (len < sizeof(struct fc_logi_s))
return (FC_PARSE_FAILURE);
if (!wwn_is_equal(plogi->port_name, port_name))
return (FC_PARSE_FAILURE);
if (!plogi->class3.class_valid)
return (FC_PARSE_FAILURE);
if (bfa_os_ntohs(plogi->class3.rxsz) < (FC_MIN_PDUSZ))
return (FC_PARSE_FAILURE);
return (FC_PARSE_OK);
default:
return (FC_PARSE_FAILURE);
}
}
enum fc_parse_status
fc_plogi_parse(struct fchs_s *fchs)
{
struct fc_logi_s *plogi = (struct fc_logi_s *) (fchs + 1);
if (plogi->class3.class_valid != 1)
return FC_PARSE_FAILURE;
if ((bfa_os_ntohs(plogi->class3.rxsz) < FC_MIN_PDUSZ)
|| (bfa_os_ntohs(plogi->class3.rxsz) > FC_MAX_PDUSZ)
|| (plogi->class3.rxsz == 0))
return (FC_PARSE_FAILURE);
return FC_PARSE_OK;
}
u16
fc_prli_build(struct fchs_s *fchs, void *pld, u32 d_id, u32 s_id,
u16 ox_id)
{
struct fc_prli_s *prli = (struct fc_prli_s *) (pld);
fc_els_req_build(fchs, d_id, s_id, ox_id);
bfa_os_memcpy(prli, &prli_tmpl, sizeof(struct fc_prli_s));
prli->command = FC_ELS_PRLI;
prli->parampage.servparams.initiator = 1;
prli->parampage.servparams.retry = 1;
prli->parampage.servparams.rec_support = 1;
prli->parampage.servparams.task_retry_id = 0;
prli->parampage.servparams.confirm = 1;
return (sizeof(struct fc_prli_s));
}
u16
fc_prli_acc_build(struct fchs_s *fchs, void *pld, u32 d_id, u32 s_id,
u16 ox_id, enum bfa_port_role role)
{
struct fc_prli_s *prli = (struct fc_prli_s *) (pld);
fc_els_rsp_build(fchs, d_id, s_id, ox_id);
bfa_os_memcpy(prli, &prli_tmpl, sizeof(struct fc_prli_s));
prli->command = FC_ELS_ACC;
if ((role & BFA_PORT_ROLE_FCP_TM) == BFA_PORT_ROLE_FCP_TM)
prli->parampage.servparams.target = 1;
else
prli->parampage.servparams.initiator = 1;
prli->parampage.rspcode = FC_PRLI_ACC_XQTD;
return (sizeof(struct fc_prli_s));
}
enum fc_parse_status
fc_prli_rsp_parse(struct fc_prli_s *prli, int len)
{
if (len < sizeof(struct fc_prli_s))
return (FC_PARSE_FAILURE);
if (prli->command != FC_ELS_ACC)
return (FC_PARSE_FAILURE);
if ((prli->parampage.rspcode != FC_PRLI_ACC_XQTD)
&& (prli->parampage.rspcode != FC_PRLI_ACC_PREDEF_IMG))
return (FC_PARSE_FAILURE);
if (prli->parampage.servparams.target != 1)
return (FC_PARSE_FAILURE);
return (FC_PARSE_OK);
}
enum fc_parse_status
fc_prli_parse(struct fc_prli_s *prli)
{
if (prli->parampage.type != FC_TYPE_FCP)
return (FC_PARSE_FAILURE);
if (!prli->parampage.imagepair)
return (FC_PARSE_FAILURE);
if (!prli->parampage.servparams.initiator)
return (FC_PARSE_FAILURE);
return (FC_PARSE_OK);
}
u16
fc_logo_build(struct fchs_s *fchs, struct fc_logo_s *logo, u32 d_id,
u32 s_id, u16 ox_id, wwn_t port_name)
{
fc_els_req_build(fchs, d_id, s_id, ox_id);
memset(logo, '\0', sizeof(struct fc_logo_s));
logo->els_cmd.els_code = FC_ELS_LOGO;
logo->nport_id = (s_id);
logo->orig_port_name = port_name;
return (sizeof(struct fc_logo_s));
}
static u16
fc_adisc_x_build(struct fchs_s *fchs, struct fc_adisc_s *adisc, u32 d_id,
u32 s_id, u16 ox_id, wwn_t port_name,
wwn_t node_name, u8 els_code)
{
memset(adisc, '\0', sizeof(struct fc_adisc_s));
adisc->els_cmd.els_code = els_code;
if (els_code == FC_ELS_ADISC)
fc_els_req_build(fchs, d_id, s_id, ox_id);
else
fc_els_rsp_build(fchs, d_id, s_id, ox_id);
adisc->orig_HA = 0;
adisc->orig_port_name = port_name;
adisc->orig_node_name = node_name;
adisc->nport_id = (s_id);
return (sizeof(struct fc_adisc_s));
}
u16
fc_adisc_build(struct fchs_s *fchs, struct fc_adisc_s *adisc, u32 d_id,
u32 s_id, u16 ox_id, wwn_t port_name,
wwn_t node_name)
{
return fc_adisc_x_build(fchs, adisc, d_id, s_id, ox_id, port_name,
node_name, FC_ELS_ADISC);
}
u16
fc_adisc_acc_build(struct fchs_s *fchs, struct fc_adisc_s *adisc, u32 d_id,
u32 s_id, u16 ox_id, wwn_t port_name,
wwn_t node_name)
{
return fc_adisc_x_build(fchs, adisc, d_id, s_id, ox_id, port_name,
node_name, FC_ELS_ACC);
}
enum fc_parse_status
fc_adisc_rsp_parse(struct fc_adisc_s *adisc, int len, wwn_t port_name,
wwn_t node_name)
{
if (len < sizeof(struct fc_adisc_s))
return (FC_PARSE_FAILURE);
if (adisc->els_cmd.els_code != FC_ELS_ACC)
return (FC_PARSE_FAILURE);
if (!wwn_is_equal(adisc->orig_port_name, port_name))
return (FC_PARSE_FAILURE);
return (FC_PARSE_OK);
}
enum fc_parse_status
fc_adisc_parse(struct fchs_s *fchs, void *pld, u32 host_dap,
wwn_t node_name, wwn_t port_name)
{
struct fc_adisc_s *adisc = (struct fc_adisc_s *) pld;
if (adisc->els_cmd.els_code != FC_ELS_ACC)
return (FC_PARSE_FAILURE);
if ((adisc->nport_id == (host_dap))
&& wwn_is_equal(adisc->orig_port_name, port_name)
&& wwn_is_equal(adisc->orig_node_name, node_name))
return (FC_PARSE_OK);
return (FC_PARSE_FAILURE);
}
enum fc_parse_status
fc_pdisc_parse(struct fchs_s *fchs, wwn_t node_name, wwn_t port_name)
{
struct fc_logi_s *pdisc = (struct fc_logi_s *) (fchs + 1);
if (pdisc->class3.class_valid != 1)
return FC_PARSE_FAILURE;
if ((bfa_os_ntohs(pdisc->class3.rxsz) <
(FC_MIN_PDUSZ - sizeof(struct fchs_s)))
|| (pdisc->class3.rxsz == 0))
return (FC_PARSE_FAILURE);
if (!wwn_is_equal(pdisc->port_name, port_name))
return (FC_PARSE_FAILURE);
if (!wwn_is_equal(pdisc->node_name, node_name))
return (FC_PARSE_FAILURE);
return FC_PARSE_OK;
}
u16
fc_abts_build(struct fchs_s *fchs, u32 d_id, u32 s_id, u16 ox_id)
{
bfa_os_memcpy(fchs, &fc_bls_req_tmpl, sizeof(struct fchs_s));
fchs->cat_info = FC_CAT_ABTS;
fchs->d_id = (d_id);
fchs->s_id = (s_id);
fchs->ox_id = bfa_os_htons(ox_id);
return (sizeof(struct fchs_s));
}
enum fc_parse_status
fc_abts_rsp_parse(struct fchs_s *fchs, int len)
{
if ((fchs->cat_info == FC_CAT_BA_ACC)
|| (fchs->cat_info == FC_CAT_BA_RJT))
return (FC_PARSE_OK);
return (FC_PARSE_FAILURE);
}
u16
fc_rrq_build(struct fchs_s *fchs, struct fc_rrq_s *rrq, u32 d_id,
u32 s_id, u16 ox_id, u16 rrq_oxid)
{
fc_els_req_build(fchs, d_id, s_id, ox_id);
/*
* build rrq payload
*/
bfa_os_memcpy(rrq, &rrq_tmpl, sizeof(struct fc_rrq_s));
rrq->s_id = (s_id);
rrq->ox_id = bfa_os_htons(rrq_oxid);
rrq->rx_id = FC_RXID_ANY;
return (sizeof(struct fc_rrq_s));
}
u16
fc_logo_acc_build(struct fchs_s *fchs, void *pld, u32 d_id, u32 s_id,
u16 ox_id)
{
struct fc_els_cmd_s *acc = pld;
fc_els_rsp_build(fchs, d_id, s_id, ox_id);
memset(acc, 0, sizeof(struct fc_els_cmd_s));
acc->els_code = FC_ELS_ACC;
return (sizeof(struct fc_els_cmd_s));
}
u16
fc_ls_rjt_build(struct fchs_s *fchs, struct fc_ls_rjt_s *ls_rjt, u32 d_id,
u32 s_id, u16 ox_id, u8 reason_code,
u8 reason_code_expl)
{
fc_els_rsp_build(fchs, d_id, s_id, ox_id);
memset(ls_rjt, 0, sizeof(struct fc_ls_rjt_s));
ls_rjt->els_cmd.els_code = FC_ELS_LS_RJT;
ls_rjt->reason_code = reason_code;
ls_rjt->reason_code_expl = reason_code_expl;
ls_rjt->vendor_unique = 0x00;
return (sizeof(struct fc_ls_rjt_s));
}
u16
fc_ba_acc_build(struct fchs_s *fchs, struct fc_ba_acc_s *ba_acc, u32 d_id,
u32 s_id, u16 ox_id, u16 rx_id)
{
fc_bls_rsp_build(fchs, d_id, s_id, ox_id);
bfa_os_memcpy(ba_acc, &ba_acc_tmpl, sizeof(struct fc_ba_acc_s));
fchs->rx_id = rx_id;
ba_acc->ox_id = fchs->ox_id;
ba_acc->rx_id = fchs->rx_id;
return (sizeof(struct fc_ba_acc_s));
}
u16
fc_ls_acc_build(struct fchs_s *fchs, struct fc_els_cmd_s *els_cmd,
u32 d_id, u32 s_id, u16 ox_id)
{
fc_els_rsp_build(fchs, d_id, s_id, ox_id);
memset(els_cmd, 0, sizeof(struct fc_els_cmd_s));
els_cmd->els_code = FC_ELS_ACC;
return (sizeof(struct fc_els_cmd_s));
}
int
fc_logout_params_pages(struct fchs_s *fc_frame, u8 els_code)
{
int num_pages = 0;
struct fc_prlo_s *prlo;
struct fc_tprlo_s *tprlo;
if (els_code == FC_ELS_PRLO) {
prlo = (struct fc_prlo_s *) (fc_frame + 1);
num_pages = (bfa_os_ntohs(prlo->payload_len) - 4) / 16;
} else {
tprlo = (struct fc_tprlo_s *) (fc_frame + 1);
num_pages = (bfa_os_ntohs(tprlo->payload_len) - 4) / 16;
}
return num_pages;
}
u16
fc_tprlo_acc_build(struct fchs_s *fchs, struct fc_tprlo_acc_s *tprlo_acc,
u32 d_id, u32 s_id, u16 ox_id,
int num_pages)
{
int page;
fc_els_rsp_build(fchs, d_id, s_id, ox_id);
memset(tprlo_acc, 0, (num_pages * 16) + 4);
tprlo_acc->command = FC_ELS_ACC;
tprlo_acc->page_len = 0x10;
tprlo_acc->payload_len = bfa_os_htons((num_pages * 16) + 4);
for (page = 0; page < num_pages; page++) {
tprlo_acc->tprlo_acc_params[page].opa_valid = 0;
tprlo_acc->tprlo_acc_params[page].rpa_valid = 0;
tprlo_acc->tprlo_acc_params[page].fc4type_csp = FC_TYPE_FCP;
tprlo_acc->tprlo_acc_params[page].orig_process_assc = 0;
tprlo_acc->tprlo_acc_params[page].resp_process_assc = 0;
}
return (bfa_os_ntohs(tprlo_acc->payload_len));
}
u16
fc_prlo_acc_build(struct fchs_s *fchs, struct fc_prlo_acc_s *prlo_acc,
u32 d_id, u32 s_id, u16 ox_id,
int num_pages)
{
int page;
fc_els_rsp_build(fchs, d_id, s_id, ox_id);
memset(prlo_acc, 0, (num_pages * 16) + 4);
prlo_acc->command = FC_ELS_ACC;
prlo_acc->page_len = 0x10;
prlo_acc->payload_len = bfa_os_htons((num_pages * 16) + 4);
for (page = 0; page < num_pages; page++) {
prlo_acc->prlo_acc_params[page].opa_valid = 0;
prlo_acc->prlo_acc_params[page].rpa_valid = 0;
prlo_acc->prlo_acc_params[page].fc4type_csp = FC_TYPE_FCP;
prlo_acc->prlo_acc_params[page].orig_process_assc = 0;
prlo_acc->prlo_acc_params[page].resp_process_assc = 0;
}
return (bfa_os_ntohs(prlo_acc->payload_len));
}
u16
fc_rnid_build(struct fchs_s *fchs, struct fc_rnid_cmd_s *rnid, u32 d_id,
u32 s_id, u16 ox_id, u32 data_format)
{
fc_els_req_build(fchs, d_id, s_id, ox_id);
memset(rnid, 0, sizeof(struct fc_rnid_cmd_s));
rnid->els_cmd.els_code = FC_ELS_RNID;
rnid->node_id_data_format = data_format;
return (sizeof(struct fc_rnid_cmd_s));
}
u16
fc_rnid_acc_build(struct fchs_s *fchs, struct fc_rnid_acc_s *rnid_acc,
u32 d_id, u32 s_id, u16 ox_id,
u32 data_format,
struct fc_rnid_common_id_data_s *common_id_data,
struct fc_rnid_general_topology_data_s *gen_topo_data)
{
memset(rnid_acc, 0, sizeof(struct fc_rnid_acc_s));
fc_els_rsp_build(fchs, d_id, s_id, ox_id);
rnid_acc->els_cmd.els_code = FC_ELS_ACC;
rnid_acc->node_id_data_format = data_format;
rnid_acc->common_id_data_length =
sizeof(struct fc_rnid_common_id_data_s);
rnid_acc->common_id_data = *common_id_data;
if (data_format == RNID_NODEID_DATA_FORMAT_DISCOVERY) {
rnid_acc->specific_id_data_length =
sizeof(struct fc_rnid_general_topology_data_s);
bfa_os_assign(rnid_acc->gen_topology_data, *gen_topo_data);
return (sizeof(struct fc_rnid_acc_s));
} else {
return (sizeof(struct fc_rnid_acc_s) -
sizeof(struct fc_rnid_general_topology_data_s));
}
}
u16
fc_rpsc_build(struct fchs_s *fchs, struct fc_rpsc_cmd_s *rpsc, u32 d_id,
u32 s_id, u16 ox_id)
{
fc_els_req_build(fchs, d_id, s_id, ox_id);
memset(rpsc, 0, sizeof(struct fc_rpsc_cmd_s));
rpsc->els_cmd.els_code = FC_ELS_RPSC;
return (sizeof(struct fc_rpsc_cmd_s));
}
u16
fc_rpsc2_build(struct fchs_s *fchs, struct fc_rpsc2_cmd_s *rpsc2,
u32 d_id, u32 s_id, u32 *pid_list,
u16 npids)
{
u32 dctlr_id = FC_DOMAIN_CTRLR(bfa_os_hton3b(d_id));
int i = 0;
fc_els_req_build(fchs, bfa_os_hton3b(dctlr_id), s_id, 0);
memset(rpsc2, 0, sizeof(struct fc_rpsc2_cmd_s));
rpsc2->els_cmd.els_code = FC_ELS_RPSC;
rpsc2->token = bfa_os_htonl(FC_BRCD_TOKEN);
rpsc2->num_pids = bfa_os_htons(npids);
for (i = 0; i < npids; i++)
rpsc2->pid_list[i].pid = pid_list[i];
return (sizeof(struct fc_rpsc2_cmd_s) + ((npids - 1) *
(sizeof(u32))));
}
u16
fc_rpsc_acc_build(struct fchs_s *fchs, struct fc_rpsc_acc_s *rpsc_acc,
u32 d_id, u32 s_id, u16 ox_id,
struct fc_rpsc_speed_info_s *oper_speed)
{
memset(rpsc_acc, 0, sizeof(struct fc_rpsc_acc_s));
fc_els_rsp_build(fchs, d_id, s_id, ox_id);
rpsc_acc->command = FC_ELS_ACC;
rpsc_acc->num_entries = bfa_os_htons(1);
rpsc_acc->speed_info[0].port_speed_cap =
bfa_os_htons(oper_speed->port_speed_cap);
rpsc_acc->speed_info[0].port_op_speed =
bfa_os_htons(oper_speed->port_op_speed);
return (sizeof(struct fc_rpsc_acc_s));
}
/*
* TBD -
* . get rid of unnecessary memsets
*/
u16
fc_logo_rsp_parse(struct fchs_s *fchs, int len)
{
struct fc_els_cmd_s *els_cmd = (struct fc_els_cmd_s *) (fchs + 1);
len = len;
if (els_cmd->els_code != FC_ELS_ACC)
return FC_PARSE_FAILURE;
return FC_PARSE_OK;
}
u16
fc_pdisc_build(struct fchs_s *fchs, u32 d_id, u32 s_id,
u16 ox_id, wwn_t port_name, wwn_t node_name,
u16 pdu_size)
{
struct fc_logi_s *pdisc = (struct fc_logi_s *) (fchs + 1);
bfa_os_memcpy(pdisc, &plogi_tmpl, sizeof(struct fc_logi_s));
pdisc->els_cmd.els_code = FC_ELS_PDISC;
fc_els_req_build(fchs, d_id, s_id, ox_id);
pdisc->csp.rxsz = pdisc->class3.rxsz = bfa_os_htons(pdu_size);
pdisc->port_name = port_name;
pdisc->node_name = node_name;
return (sizeof(struct fc_logi_s));
}
u16
fc_pdisc_rsp_parse(struct fchs_s *fchs, int len, wwn_t port_name)
{
struct fc_logi_s *pdisc = (struct fc_logi_s *) (fchs + 1);
if (len < sizeof(struct fc_logi_s))
return (FC_PARSE_LEN_INVAL);
if (pdisc->els_cmd.els_code != FC_ELS_ACC)
return (FC_PARSE_ACC_INVAL);
if (!wwn_is_equal(pdisc->port_name, port_name))
return (FC_PARSE_PWWN_NOT_EQUAL);
if (!pdisc->class3.class_valid)
return (FC_PARSE_NWWN_NOT_EQUAL);
if (bfa_os_ntohs(pdisc->class3.rxsz) < (FC_MIN_PDUSZ))
return (FC_PARSE_RXSZ_INVAL);
return (FC_PARSE_OK);
}
u16
fc_prlo_build(struct fchs_s *fchs, u32 d_id, u32 s_id, u16 ox_id,
int num_pages)
{
struct fc_prlo_s *prlo = (struct fc_prlo_s *) (fchs + 1);
int page;
fc_els_req_build(fchs, d_id, s_id, ox_id);
memset(prlo, 0, (num_pages * 16) + 4);
prlo->command = FC_ELS_PRLO;
prlo->page_len = 0x10;
prlo->payload_len = bfa_os_htons((num_pages * 16) + 4);
for (page = 0; page < num_pages; page++) {
prlo->prlo_params[page].type = FC_TYPE_FCP;
prlo->prlo_params[page].opa_valid = 0;
prlo->prlo_params[page].rpa_valid = 0;
prlo->prlo_params[page].orig_process_assc = 0;
prlo->prlo_params[page].resp_process_assc = 0;
}
return (bfa_os_ntohs(prlo->payload_len));
}
u16
fc_prlo_rsp_parse(struct fchs_s *fchs, int len)
{
struct fc_prlo_acc_s *prlo = (struct fc_prlo_acc_s *) (fchs + 1);
int num_pages = 0;
int page = 0;
len = len;
if (prlo->command != FC_ELS_ACC)
return (FC_PARSE_FAILURE);
num_pages = ((bfa_os_ntohs(prlo->payload_len)) - 4) / 16;
for (page = 0; page < num_pages; page++) {
if (prlo->prlo_acc_params[page].type != FC_TYPE_FCP)
return FC_PARSE_FAILURE;
if (prlo->prlo_acc_params[page].opa_valid != 0)
return FC_PARSE_FAILURE;
if (prlo->prlo_acc_params[page].rpa_valid != 0)
return FC_PARSE_FAILURE;
if (prlo->prlo_acc_params[page].orig_process_assc != 0)
return FC_PARSE_FAILURE;
if (prlo->prlo_acc_params[page].resp_process_assc != 0)
return FC_PARSE_FAILURE;
}
return (FC_PARSE_OK);
}
u16
fc_tprlo_build(struct fchs_s *fchs, u32 d_id, u32 s_id,
u16 ox_id, int num_pages,
enum fc_tprlo_type tprlo_type, u32 tpr_id)
{
struct fc_tprlo_s *tprlo = (struct fc_tprlo_s *) (fchs + 1);
int page;
fc_els_req_build(fchs, d_id, s_id, ox_id);
memset(tprlo, 0, (num_pages * 16) + 4);
tprlo->command = FC_ELS_TPRLO;
tprlo->page_len = 0x10;
tprlo->payload_len = bfa_os_htons((num_pages * 16) + 4);
for (page = 0; page < num_pages; page++) {
tprlo->tprlo_params[page].type = FC_TYPE_FCP;
tprlo->tprlo_params[page].opa_valid = 0;
tprlo->tprlo_params[page].rpa_valid = 0;
tprlo->tprlo_params[page].orig_process_assc = 0;
tprlo->tprlo_params[page].resp_process_assc = 0;
if (tprlo_type == FC_GLOBAL_LOGO) {
tprlo->tprlo_params[page].global_process_logout = 1;
} else if (tprlo_type == FC_TPR_LOGO) {
tprlo->tprlo_params[page].tpo_nport_valid = 1;
tprlo->tprlo_params[page].tpo_nport_id = (tpr_id);
}
}
return (bfa_os_ntohs(tprlo->payload_len));
}
u16
fc_tprlo_rsp_parse(struct fchs_s *fchs, int len)
{
struct fc_tprlo_acc_s *tprlo = (struct fc_tprlo_acc_s *) (fchs + 1);
int num_pages = 0;
int page = 0;
len = len;
if (tprlo->command != FC_ELS_ACC)
return (FC_PARSE_ACC_INVAL);
num_pages = (bfa_os_ntohs(tprlo->payload_len) - 4) / 16;
for (page = 0; page < num_pages; page++) {
if (tprlo->tprlo_acc_params[page].type != FC_TYPE_FCP)
return (FC_PARSE_NOT_FCP);
if (tprlo->tprlo_acc_params[page].opa_valid != 0)
return (FC_PARSE_OPAFLAG_INVAL);
if (tprlo->tprlo_acc_params[page].rpa_valid != 0)
return (FC_PARSE_RPAFLAG_INVAL);
if (tprlo->tprlo_acc_params[page].orig_process_assc != 0)
return (FC_PARSE_OPA_INVAL);
if (tprlo->tprlo_acc_params[page].resp_process_assc != 0)
return (FC_PARSE_RPA_INVAL);
}
return (FC_PARSE_OK);
}
enum fc_parse_status
fc_rrq_rsp_parse(struct fchs_s *fchs, int len)
{
struct fc_els_cmd_s *els_cmd = (struct fc_els_cmd_s *) (fchs + 1);
len = len;
if (els_cmd->els_code != FC_ELS_ACC)
return FC_PARSE_FAILURE;
return FC_PARSE_OK;
}
u16
fc_ba_rjt_build(struct fchs_s *fchs, u32 d_id, u32 s_id,
u16 ox_id, u32 reason_code,
u32 reason_expl)
{
struct fc_ba_rjt_s *ba_rjt = (struct fc_ba_rjt_s *) (fchs + 1);
fc_bls_rsp_build(fchs, d_id, s_id, ox_id);
fchs->cat_info = FC_CAT_BA_RJT;
ba_rjt->reason_code = reason_code;
ba_rjt->reason_expl = reason_expl;
return (sizeof(struct fc_ba_rjt_s));
}
static void
fc_gs_cthdr_build(struct ct_hdr_s *cthdr, u32 s_id, u16 cmd_code)
{
bfa_os_memset(cthdr, 0, sizeof(struct ct_hdr_s));
cthdr->rev_id = CT_GS3_REVISION;
cthdr->gs_type = CT_GSTYPE_DIRSERVICE;
cthdr->gs_sub_type = CT_GSSUBTYPE_NAMESERVER;
cthdr->cmd_rsp_code = bfa_os_htons(cmd_code);
}
static void
fc_gs_fdmi_cthdr_build(struct ct_hdr_s *cthdr, u32 s_id, u16 cmd_code)
{
bfa_os_memset(cthdr, 0, sizeof(struct ct_hdr_s));
cthdr->rev_id = CT_GS3_REVISION;
cthdr->gs_type = CT_GSTYPE_MGMTSERVICE;
cthdr->gs_sub_type = CT_GSSUBTYPE_HBA_MGMTSERVER;
cthdr->cmd_rsp_code = bfa_os_htons(cmd_code);
}
static void
fc_gs_ms_cthdr_build(struct ct_hdr_s *cthdr, u32 s_id, u16 cmd_code,
u8 sub_type)
{
bfa_os_memset(cthdr, 0, sizeof(struct ct_hdr_s));
cthdr->rev_id = CT_GS3_REVISION;
cthdr->gs_type = CT_GSTYPE_MGMTSERVICE;
cthdr->gs_sub_type = sub_type;
cthdr->cmd_rsp_code = bfa_os_htons(cmd_code);
}
u16
fc_gidpn_build(struct fchs_s *fchs, void *pyld, u32 s_id, u16 ox_id,
wwn_t port_name)
{
struct ct_hdr_s *cthdr = (struct ct_hdr_s *) pyld;
struct fcgs_gidpn_req_s *gidpn =
(struct fcgs_gidpn_req_s *) (cthdr + 1);
u32 d_id = bfa_os_hton3b(FC_NAME_SERVER);
fc_gs_fchdr_build(fchs, d_id, s_id, ox_id);
fc_gs_cthdr_build(cthdr, s_id, GS_GID_PN);
bfa_os_memset(gidpn, 0, sizeof(struct fcgs_gidpn_req_s));
gidpn->port_name = port_name;
return (sizeof(struct fcgs_gidpn_req_s) + sizeof(struct ct_hdr_s));
}
u16
fc_gpnid_build(struct fchs_s *fchs, void *pyld, u32 s_id, u16 ox_id,
u32 port_id)
{
struct ct_hdr_s *cthdr = (struct ct_hdr_s *) pyld;
fcgs_gpnid_req_t *gpnid = (fcgs_gpnid_req_t *) (cthdr + 1);
u32 d_id = bfa_os_hton3b(FC_NAME_SERVER);
fc_gs_fchdr_build(fchs, d_id, s_id, ox_id);
fc_gs_cthdr_build(cthdr, s_id, GS_GPN_ID);
bfa_os_memset(gpnid, 0, sizeof(fcgs_gpnid_req_t));
gpnid->dap = port_id;
return (sizeof(fcgs_gpnid_req_t) + sizeof(struct ct_hdr_s));
}
u16
fc_gnnid_build(struct fchs_s *fchs, void *pyld, u32 s_id, u16 ox_id,
u32 port_id)
{
struct ct_hdr_s *cthdr = (struct ct_hdr_s *) pyld;
fcgs_gnnid_req_t *gnnid = (fcgs_gnnid_req_t *) (cthdr + 1);
u32 d_id = bfa_os_hton3b(FC_NAME_SERVER);
fc_gs_fchdr_build(fchs, d_id, s_id, ox_id);
fc_gs_cthdr_build(cthdr, s_id, GS_GNN_ID);
bfa_os_memset(gnnid, 0, sizeof(fcgs_gnnid_req_t));
gnnid->dap = port_id;
return (sizeof(fcgs_gnnid_req_t) + sizeof(struct ct_hdr_s));
}
u16
fc_ct_rsp_parse(struct ct_hdr_s *cthdr)
{
if (bfa_os_ntohs(cthdr->cmd_rsp_code) != CT_RSP_ACCEPT) {
if (cthdr->reason_code == CT_RSN_LOGICAL_BUSY)
return FC_PARSE_BUSY;
else
return FC_PARSE_FAILURE;
}
return FC_PARSE_OK;
}
u16
fc_scr_build(struct fchs_s *fchs, struct fc_scr_s *scr, u8 set_br_reg,
u32 s_id, u16 ox_id)
{
u32 d_id = bfa_os_hton3b(FC_FABRIC_CONTROLLER);
fc_els_req_build(fchs, d_id, s_id, ox_id);
bfa_os_memset(scr, 0, sizeof(struct fc_scr_s));
scr->command = FC_ELS_SCR;
scr->reg_func = FC_SCR_REG_FUNC_FULL;
if (set_br_reg)
scr->vu_reg_func = FC_VU_SCR_REG_FUNC_FABRIC_NAME_CHANGE;
return (sizeof(struct fc_scr_s));
}
u16
fc_rscn_build(struct fchs_s *fchs, struct fc_rscn_pl_s *rscn, u32 s_id,
u16 ox_id)
{
u32 d_id = bfa_os_hton3b(FC_FABRIC_CONTROLLER);
u16 payldlen;
fc_els_req_build(fchs, d_id, s_id, ox_id);
rscn->command = FC_ELS_RSCN;
rscn->pagelen = sizeof(rscn->event[0]);
payldlen = sizeof(u32) + rscn->pagelen;
rscn->payldlen = bfa_os_htons(payldlen);
rscn->event[0].format = FC_RSCN_FORMAT_PORTID;
rscn->event[0].portid = s_id;
return (sizeof(struct fc_rscn_pl_s));
}
u16
fc_rftid_build(struct fchs_s *fchs, void *pyld, u32 s_id, u16 ox_id,
enum bfa_port_role roles)
{
struct ct_hdr_s *cthdr = (struct ct_hdr_s *) pyld;
struct fcgs_rftid_req_s *rftid =
(struct fcgs_rftid_req_s *) (cthdr + 1);
u32 type_value, d_id = bfa_os_hton3b(FC_NAME_SERVER);
u8 index;
fc_gs_fchdr_build(fchs, d_id, s_id, ox_id);
fc_gs_cthdr_build(cthdr, s_id, GS_RFT_ID);
bfa_os_memset(rftid, 0, sizeof(struct fcgs_rftid_req_s));
rftid->dap = s_id;
/* By default, FCP FC4 Type is registered */
index = FC_TYPE_FCP >> 5;
type_value = 1 << (FC_TYPE_FCP % 32);
rftid->fc4_type[index] = bfa_os_htonl(type_value);
if (roles & BFA_PORT_ROLE_FCP_IPFC) {
index = FC_TYPE_IP >> 5;
type_value = 1 << (FC_TYPE_IP % 32);
rftid->fc4_type[index] |= bfa_os_htonl(type_value);
}
return (sizeof(struct fcgs_rftid_req_s) + sizeof(struct ct_hdr_s));
}
u16
fc_rftid_build_sol(struct fchs_s *fchs, void *pyld, u32 s_id,
u16 ox_id, u8 *fc4_bitmap,
u32 bitmap_size)
{
struct ct_hdr_s *cthdr = (struct ct_hdr_s *) pyld;
struct fcgs_rftid_req_s *rftid =
(struct fcgs_rftid_req_s *) (cthdr + 1);
u32 d_id = bfa_os_hton3b(FC_NAME_SERVER);
fc_gs_fchdr_build(fchs, d_id, s_id, ox_id);
fc_gs_cthdr_build(cthdr, s_id, GS_RFT_ID);
bfa_os_memset(rftid, 0, sizeof(struct fcgs_rftid_req_s));
rftid->dap = s_id;
bfa_os_memcpy((void *)rftid->fc4_type, (void *)fc4_bitmap,
(bitmap_size < 32 ? bitmap_size : 32));
return (sizeof(struct fcgs_rftid_req_s) + sizeof(struct ct_hdr_s));
}
u16
fc_rffid_build(struct fchs_s *fchs, void *pyld, u32 s_id, u16 ox_id,
u8 fc4_type, u8 fc4_ftrs)
{
struct ct_hdr_s *cthdr = (struct ct_hdr_s *) pyld;
struct fcgs_rffid_req_s *rffid =
(struct fcgs_rffid_req_s *) (cthdr + 1);
u32 d_id = bfa_os_hton3b(FC_NAME_SERVER);
fc_gs_fchdr_build(fchs, d_id, s_id, ox_id);
fc_gs_cthdr_build(cthdr, s_id, GS_RFF_ID);
bfa_os_memset(rffid, 0, sizeof(struct fcgs_rffid_req_s));
rffid->dap = s_id;
rffid->fc4ftr_bits = fc4_ftrs;
rffid->fc4_type = fc4_type;
return (sizeof(struct fcgs_rffid_req_s) + sizeof(struct ct_hdr_s));
}
u16
fc_rspnid_build(struct fchs_s *fchs, void *pyld, u32 s_id, u16 ox_id,
u8 *name)
{
struct ct_hdr_s *cthdr = (struct ct_hdr_s *) pyld;
struct fcgs_rspnid_req_s *rspnid =
(struct fcgs_rspnid_req_s *) (cthdr + 1);
u32 d_id = bfa_os_hton3b(FC_NAME_SERVER);
fc_gs_fchdr_build(fchs, d_id, s_id, ox_id);
fc_gs_cthdr_build(cthdr, s_id, GS_RSPN_ID);
bfa_os_memset(rspnid, 0, sizeof(struct fcgs_rspnid_req_s));
rspnid->dap = s_id;
rspnid->spn_len = (u8) strlen((char *)name);
strncpy((char *)rspnid->spn, (char *)name, rspnid->spn_len);
return (sizeof(struct fcgs_rspnid_req_s) + sizeof(struct ct_hdr_s));
}
u16
fc_gid_ft_build(struct fchs_s *fchs, void *pyld, u32 s_id,
u8 fc4_type)
{
struct ct_hdr_s *cthdr = (struct ct_hdr_s *) pyld;
struct fcgs_gidft_req_s *gidft =
(struct fcgs_gidft_req_s *) (cthdr + 1);
u32 d_id = bfa_os_hton3b(FC_NAME_SERVER);
fc_gs_fchdr_build(fchs, d_id, s_id, 0);
fc_gs_cthdr_build(cthdr, s_id, GS_GID_FT);
bfa_os_memset(gidft, 0, sizeof(struct fcgs_gidft_req_s));
gidft->fc4_type = fc4_type;
gidft->domain_id = 0;
gidft->area_id = 0;
return (sizeof(struct fcgs_gidft_req_s) + sizeof(struct ct_hdr_s));
}
u16
fc_rpnid_build(struct fchs_s *fchs, void *pyld, u32 s_id, u32 port_id,
wwn_t port_name)
{
struct ct_hdr_s *cthdr = (struct ct_hdr_s *) pyld;
struct fcgs_rpnid_req_s *rpnid =
(struct fcgs_rpnid_req_s *) (cthdr + 1);
u32 d_id = bfa_os_hton3b(FC_NAME_SERVER);
fc_gs_fchdr_build(fchs, d_id, s_id, 0);
fc_gs_cthdr_build(cthdr, s_id, GS_RPN_ID);
bfa_os_memset(rpnid, 0, sizeof(struct fcgs_rpnid_req_s));
rpnid->port_id = port_id;
rpnid->port_name = port_name;
return (sizeof(struct fcgs_rpnid_req_s) + sizeof(struct ct_hdr_s));
}
u16
fc_rnnid_build(struct fchs_s *fchs, void *pyld, u32 s_id, u32 port_id,
wwn_t node_name)
{
struct ct_hdr_s *cthdr = (struct ct_hdr_s *) pyld;
struct fcgs_rnnid_req_s *rnnid =
(struct fcgs_rnnid_req_s *) (cthdr + 1);
u32 d_id = bfa_os_hton3b(FC_NAME_SERVER);
fc_gs_fchdr_build(fchs, d_id, s_id, 0);
fc_gs_cthdr_build(cthdr, s_id, GS_RNN_ID);
bfa_os_memset(rnnid, 0, sizeof(struct fcgs_rnnid_req_s));
rnnid->port_id = port_id;
rnnid->node_name = node_name;
return (sizeof(struct fcgs_rnnid_req_s) + sizeof(struct ct_hdr_s));
}
u16
fc_rcsid_build(struct fchs_s *fchs, void *pyld, u32 s_id, u32 port_id,
u32 cos)
{
struct ct_hdr_s *cthdr = (struct ct_hdr_s *) pyld;
struct fcgs_rcsid_req_s *rcsid =
(struct fcgs_rcsid_req_s *) (cthdr + 1);
u32 d_id = bfa_os_hton3b(FC_NAME_SERVER);
fc_gs_fchdr_build(fchs, d_id, s_id, 0);
fc_gs_cthdr_build(cthdr, s_id, GS_RCS_ID);
bfa_os_memset(rcsid, 0, sizeof(struct fcgs_rcsid_req_s));
rcsid->port_id = port_id;
rcsid->cos = cos;
return (sizeof(struct fcgs_rcsid_req_s) + sizeof(struct ct_hdr_s));
}
u16
fc_rptid_build(struct fchs_s *fchs, void *pyld, u32 s_id, u32 port_id,
u8 port_type)
{
struct ct_hdr_s *cthdr = (struct ct_hdr_s *) pyld;
struct fcgs_rptid_req_s *rptid =
(struct fcgs_rptid_req_s *) (cthdr + 1);
u32 d_id = bfa_os_hton3b(FC_NAME_SERVER);
fc_gs_fchdr_build(fchs, d_id, s_id, 0);
fc_gs_cthdr_build(cthdr, s_id, GS_RPT_ID);
bfa_os_memset(rptid, 0, sizeof(struct fcgs_rptid_req_s));
rptid->port_id = port_id;
rptid->port_type = port_type;
return (sizeof(struct fcgs_rptid_req_s) + sizeof(struct ct_hdr_s));
}
u16
fc_ganxt_build(struct fchs_s *fchs, void *pyld, u32 s_id, u32 port_id)
{
struct ct_hdr_s *cthdr = (struct ct_hdr_s *) pyld;
struct fcgs_ganxt_req_s *ganxt =
(struct fcgs_ganxt_req_s *) (cthdr + 1);
u32 d_id = bfa_os_hton3b(FC_NAME_SERVER);
fc_gs_fchdr_build(fchs, d_id, s_id, 0);
fc_gs_cthdr_build(cthdr, s_id, GS_GA_NXT);
bfa_os_memset(ganxt, 0, sizeof(struct fcgs_ganxt_req_s));
ganxt->port_id = port_id;
return (sizeof(struct ct_hdr_s) + sizeof(struct fcgs_ganxt_req_s));
}
/*
* Builds fc hdr and ct hdr for FDMI requests.
*/
u16
fc_fdmi_reqhdr_build(struct fchs_s *fchs, void *pyld, u32 s_id,
u16 cmd_code)
{
struct ct_hdr_s *cthdr = (struct ct_hdr_s *) pyld;
u32 d_id = bfa_os_hton3b(FC_MGMT_SERVER);
fc_gs_fchdr_build(fchs, d_id, s_id, 0);
fc_gs_fdmi_cthdr_build(cthdr, s_id, cmd_code);
return (sizeof(struct ct_hdr_s));
}
/*
* Given a FC4 Type, this function returns a fc4 type bitmask
*/
void
fc_get_fc4type_bitmask(u8 fc4_type, u8 *bit_mask)
{
u8 index;
u32 *ptr = (u32 *) bit_mask;
u32 type_value;
/*
* @todo : Check for bitmask size
*/
index = fc4_type >> 5;
type_value = 1 << (fc4_type % 32);
ptr[index] = bfa_os_htonl(type_value);
}
/*
* GMAL Request
*/
u16
fc_gmal_req_build(struct fchs_s *fchs, void *pyld, u32 s_id, wwn_t wwn)
{
struct ct_hdr_s *cthdr = (struct ct_hdr_s *) pyld;
fcgs_gmal_req_t *gmal = (fcgs_gmal_req_t *) (cthdr + 1);
u32 d_id = bfa_os_hton3b(FC_MGMT_SERVER);
fc_gs_fchdr_build(fchs, d_id, s_id, 0);
fc_gs_ms_cthdr_build(cthdr, s_id, GS_FC_GMAL_CMD,
CT_GSSUBTYPE_CFGSERVER);
bfa_os_memset(gmal, 0, sizeof(fcgs_gmal_req_t));
gmal->wwn = wwn;
return (sizeof(struct ct_hdr_s) + sizeof(fcgs_gmal_req_t));
}
/*
* GFN (Get Fabric Name) Request
*/
u16
fc_gfn_req_build(struct fchs_s *fchs, void *pyld, u32 s_id, wwn_t wwn)
{
struct ct_hdr_s *cthdr = (struct ct_hdr_s *) pyld;
fcgs_gfn_req_t *gfn = (fcgs_gfn_req_t *) (cthdr + 1);
u32 d_id = bfa_os_hton3b(FC_MGMT_SERVER);
fc_gs_fchdr_build(fchs, d_id, s_id, 0);
fc_gs_ms_cthdr_build(cthdr, s_id, GS_FC_GFN_CMD,
CT_GSSUBTYPE_CFGSERVER);
bfa_os_memset(gfn, 0, sizeof(fcgs_gfn_req_t));
gfn->wwn = wwn;
return (sizeof(struct ct_hdr_s) + sizeof(fcgs_gfn_req_t));
}
| gpl-2.0 |
telf/TDR_watchdog_RFC_1 | drivers/cpufreq/exynos4x12-cpufreq.c | 976 | 6827 | /*
* Copyright (c) 2010-2012 Samsung Electronics Co., Ltd.
* http://www.samsung.com
*
* EXYNOS4X12 - CPU frequency scaling support
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/cpufreq.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include "exynos-cpufreq.h"
static struct clk *cpu_clk;
static struct clk *moutcore;
static struct clk *mout_mpll;
static struct clk *mout_apll;
static struct exynos_dvfs_info *cpufreq;
static unsigned int exynos4x12_volt_table[] = {
1350000, 1287500, 1250000, 1187500, 1137500, 1087500, 1037500,
1000000, 987500, 975000, 950000, 925000, 900000, 900000
};
static struct cpufreq_frequency_table exynos4x12_freq_table[] = {
{CPUFREQ_BOOST_FREQ, L0, 1500 * 1000},
{0, L1, 1400 * 1000},
{0, L2, 1300 * 1000},
{0, L3, 1200 * 1000},
{0, L4, 1100 * 1000},
{0, L5, 1000 * 1000},
{0, L6, 900 * 1000},
{0, L7, 800 * 1000},
{0, L8, 700 * 1000},
{0, L9, 600 * 1000},
{0, L10, 500 * 1000},
{0, L11, 400 * 1000},
{0, L12, 300 * 1000},
{0, L13, 200 * 1000},
{0, 0, CPUFREQ_TABLE_END},
};
static struct apll_freq *apll_freq_4x12;
static struct apll_freq apll_freq_4212[] = {
/*
* values:
* freq
* clock divider for CORE, COREM0, COREM1, PERIPH, ATB, PCLK_DBG, APLL, CORE2
* clock divider for COPY, HPM, RESERVED
* PLL M, P, S
*/
APLL_FREQ(1500, 0, 3, 7, 0, 6, 1, 2, 0, 6, 2, 0, 250, 4, 0),
APLL_FREQ(1400, 0, 3, 7, 0, 6, 1, 2, 0, 6, 2, 0, 175, 3, 0),
APLL_FREQ(1300, 0, 3, 7, 0, 5, 1, 2, 0, 5, 2, 0, 325, 6, 0),
APLL_FREQ(1200, 0, 3, 7, 0, 5, 1, 2, 0, 5, 2, 0, 200, 4, 0),
APLL_FREQ(1100, 0, 3, 6, 0, 4, 1, 2, 0, 4, 2, 0, 275, 6, 0),
APLL_FREQ(1000, 0, 2, 5, 0, 4, 1, 1, 0, 4, 2, 0, 125, 3, 0),
APLL_FREQ(900, 0, 2, 5, 0, 3, 1, 1, 0, 3, 2, 0, 150, 4, 0),
APLL_FREQ(800, 0, 2, 5, 0, 3, 1, 1, 0, 3, 2, 0, 100, 3, 0),
APLL_FREQ(700, 0, 2, 4, 0, 3, 1, 1, 0, 3, 2, 0, 175, 3, 1),
APLL_FREQ(600, 0, 2, 4, 0, 3, 1, 1, 0, 3, 2, 0, 200, 4, 1),
APLL_FREQ(500, 0, 2, 4, 0, 3, 1, 1, 0, 3, 2, 0, 125, 3, 1),
APLL_FREQ(400, 0, 2, 4, 0, 3, 1, 1, 0, 3, 2, 0, 100, 3, 1),
APLL_FREQ(300, 0, 2, 4, 0, 2, 1, 1, 0, 3, 2, 0, 200, 4, 2),
APLL_FREQ(200, 0, 1, 3, 0, 1, 1, 1, 0, 3, 2, 0, 100, 3, 2),
};
static struct apll_freq apll_freq_4412[] = {
/*
* values:
* freq
* clock divider for CORE, COREM0, COREM1, PERIPH, ATB, PCLK_DBG, APLL, CORE2
* clock divider for COPY, HPM, CORES
* PLL M, P, S
*/
APLL_FREQ(1500, 0, 3, 7, 0, 6, 1, 2, 0, 6, 0, 7, 250, 4, 0),
APLL_FREQ(1400, 0, 3, 7, 0, 6, 1, 2, 0, 6, 0, 6, 175, 3, 0),
APLL_FREQ(1300, 0, 3, 7, 0, 5, 1, 2, 0, 5, 0, 6, 325, 6, 0),
APLL_FREQ(1200, 0, 3, 7, 0, 5, 1, 2, 0, 5, 0, 5, 200, 4, 0),
APLL_FREQ(1100, 0, 3, 6, 0, 4, 1, 2, 0, 4, 0, 5, 275, 6, 0),
APLL_FREQ(1000, 0, 2, 5, 0, 4, 1, 1, 0, 4, 0, 4, 125, 3, 0),
APLL_FREQ(900, 0, 2, 5, 0, 3, 1, 1, 0, 3, 0, 4, 150, 4, 0),
APLL_FREQ(800, 0, 2, 5, 0, 3, 1, 1, 0, 3, 0, 3, 100, 3, 0),
APLL_FREQ(700, 0, 2, 4, 0, 3, 1, 1, 0, 3, 0, 3, 175, 3, 1),
APLL_FREQ(600, 0, 2, 4, 0, 3, 1, 1, 0, 3, 0, 2, 200, 4, 1),
APLL_FREQ(500, 0, 2, 4, 0, 3, 1, 1, 0, 3, 0, 2, 125, 3, 1),
APLL_FREQ(400, 0, 2, 4, 0, 3, 1, 1, 0, 3, 0, 1, 100, 3, 1),
APLL_FREQ(300, 0, 2, 4, 0, 2, 1, 1, 0, 3, 0, 1, 200, 4, 2),
APLL_FREQ(200, 0, 1, 3, 0, 1, 1, 1, 0, 3, 0, 0, 100, 3, 2),
};
static void exynos4x12_set_clkdiv(unsigned int div_index)
{
unsigned int tmp;
/* Change Divider - CPU0 */
tmp = apll_freq_4x12[div_index].clk_div_cpu0;
__raw_writel(tmp, cpufreq->cmu_regs + EXYNOS4_CLKDIV_CPU);
while (__raw_readl(cpufreq->cmu_regs + EXYNOS4_CLKDIV_STATCPU)
& 0x11111111)
cpu_relax();
/* Change Divider - CPU1 */
tmp = apll_freq_4x12[div_index].clk_div_cpu1;
__raw_writel(tmp, cpufreq->cmu_regs + EXYNOS4_CLKDIV_CPU1);
do {
cpu_relax();
tmp = __raw_readl(cpufreq->cmu_regs + EXYNOS4_CLKDIV_STATCPU1);
} while (tmp != 0x0);
}
static void exynos4x12_set_apll(unsigned int index)
{
unsigned int tmp, freq = apll_freq_4x12[index].freq;
/* MUX_CORE_SEL = MPLL, ARMCLK uses MPLL for lock time */
clk_set_parent(moutcore, mout_mpll);
do {
cpu_relax();
tmp = (__raw_readl(cpufreq->cmu_regs + EXYNOS4_CLKMUX_STATCPU)
>> EXYNOS4_CLKSRC_CPU_MUXCORE_SHIFT);
tmp &= 0x7;
} while (tmp != 0x2);
clk_set_rate(mout_apll, freq * 1000);
/* MUX_CORE_SEL = APLL */
clk_set_parent(moutcore, mout_apll);
do {
cpu_relax();
tmp = __raw_readl(cpufreq->cmu_regs + EXYNOS4_CLKMUX_STATCPU);
tmp &= EXYNOS4_CLKMUX_STATCPU_MUXCORE_MASK;
} while (tmp != (0x1 << EXYNOS4_CLKSRC_CPU_MUXCORE_SHIFT));
}
static void exynos4x12_set_frequency(unsigned int old_index,
unsigned int new_index)
{
if (old_index > new_index) {
exynos4x12_set_clkdiv(new_index);
exynos4x12_set_apll(new_index);
} else if (old_index < new_index) {
exynos4x12_set_apll(new_index);
exynos4x12_set_clkdiv(new_index);
}
}
int exynos4x12_cpufreq_init(struct exynos_dvfs_info *info)
{
struct device_node *np;
unsigned long rate;
/*
* HACK: This is a temporary workaround to get access to clock
* controller registers directly and remove static mappings and
* dependencies on platform headers. It is necessary to enable
* Exynos multi-platform support and will be removed together with
* this whole driver as soon as Exynos gets migrated to use
* cpufreq-dt driver.
*/
np = of_find_compatible_node(NULL, NULL, "samsung,exynos4412-clock");
if (!np) {
pr_err("%s: failed to find clock controller DT node\n",
__func__);
return -ENODEV;
}
info->cmu_regs = of_iomap(np, 0);
if (!info->cmu_regs) {
pr_err("%s: failed to map CMU registers\n", __func__);
return -EFAULT;
}
cpu_clk = clk_get(NULL, "armclk");
if (IS_ERR(cpu_clk))
return PTR_ERR(cpu_clk);
moutcore = clk_get(NULL, "moutcore");
if (IS_ERR(moutcore))
goto err_moutcore;
mout_mpll = clk_get(NULL, "mout_mpll");
if (IS_ERR(mout_mpll))
goto err_mout_mpll;
rate = clk_get_rate(mout_mpll) / 1000;
mout_apll = clk_get(NULL, "mout_apll");
if (IS_ERR(mout_apll))
goto err_mout_apll;
if (info->type == EXYNOS_SOC_4212)
apll_freq_4x12 = apll_freq_4212;
else
apll_freq_4x12 = apll_freq_4412;
info->mpll_freq_khz = rate;
/* 800Mhz */
info->pll_safe_idx = L7;
info->cpu_clk = cpu_clk;
info->volt_table = exynos4x12_volt_table;
info->freq_table = exynos4x12_freq_table;
info->set_freq = exynos4x12_set_frequency;
cpufreq = info;
return 0;
err_mout_apll:
clk_put(mout_mpll);
err_mout_mpll:
clk_put(moutcore);
err_moutcore:
clk_put(cpu_clk);
pr_debug("%s: failed initialization\n", __func__);
return -EINVAL;
}
| gpl-2.0 |
sbryan12144/BeastMode-Elite | sound/pcmcia/vx/vxpocket.c | 1488 | 8705 | /*
* Driver for Digigram VXpocket V2/440 soundcards
*
* Copyright (c) 2002 by Takashi Iwai <tiwai@suse.de>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/moduleparam.h>
#include <linux/slab.h>
#include <sound/core.h>
#include "vxpocket.h"
#include <pcmcia/ciscode.h>
#include <pcmcia/cisreg.h>
#include <sound/initval.h>
#include <sound/tlv.h>
/*
*/
MODULE_AUTHOR("Takashi Iwai <tiwai@suse.de>");
MODULE_DESCRIPTION("Digigram VXPocket");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{Digigram,VXPocket},{Digigram,VXPocket440}}");
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_PNP; /* Enable switches */
static int ibl[SNDRV_CARDS];
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for VXPocket soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for VXPocket soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable VXPocket soundcard.");
module_param_array(ibl, int, NULL, 0444);
MODULE_PARM_DESC(ibl, "Capture IBL size for VXPocket soundcard.");
/*
*/
static unsigned int card_alloc;
/*
*/
static void vxpocket_release(struct pcmcia_device *link)
{
pcmcia_disable_device(link);
}
/*
* destructor, called from snd_card_free_when_closed()
*/
static int snd_vxpocket_dev_free(struct snd_device *device)
{
struct vx_core *chip = device->device_data;
snd_vx_free_firmware(chip);
kfree(chip);
return 0;
}
/*
* Hardware information
*/
/* VX-pocket V2
*
* 1 DSP, 1 sync UER
* 1 programmable clock (NIY)
* 1 stereo analog input (line/micro)
* 1 stereo analog output
* Only output levels can be modified
*/
static const DECLARE_TLV_DB_SCALE(db_scale_old_vol, -11350, 50, 0);
static struct snd_vx_hardware vxpocket_hw = {
.name = "VXPocket",
.type = VX_TYPE_VXPOCKET,
/* hardware specs */
.num_codecs = 1,
.num_ins = 1,
.num_outs = 1,
.output_level_max = VX_ANALOG_OUT_LEVEL_MAX,
.output_level_db_scale = db_scale_old_vol,
};
/* VX-pocket 440
*
* 1 DSP, 1 sync UER, 1 sync World Clock (NIY)
* SMPTE (NIY)
* 2 stereo analog input (line/micro)
* 2 stereo analog output
* Only output levels can be modified
* UER, but only for the first two inputs and outputs.
*/
static struct snd_vx_hardware vxp440_hw = {
.name = "VXPocket440",
.type = VX_TYPE_VXP440,
/* hardware specs */
.num_codecs = 2,
.num_ins = 2,
.num_outs = 2,
.output_level_max = VX_ANALOG_OUT_LEVEL_MAX,
.output_level_db_scale = db_scale_old_vol,
};
/*
* create vxpocket instance
*/
static int snd_vxpocket_new(struct snd_card *card, int ibl,
struct pcmcia_device *link,
struct snd_vxpocket **chip_ret)
{
struct vx_core *chip;
struct snd_vxpocket *vxp;
static struct snd_device_ops ops = {
.dev_free = snd_vxpocket_dev_free,
};
int err;
chip = snd_vx_create(card, &vxpocket_hw, &snd_vxpocket_ops,
sizeof(struct snd_vxpocket) - sizeof(struct vx_core));
if (!chip)
return -ENOMEM;
err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);
if (err < 0) {
kfree(chip);
return err;
}
chip->ibl.size = ibl;
vxp = (struct snd_vxpocket *)chip;
vxp->p_dev = link;
link->priv = chip;
link->resource[0]->flags |= IO_DATA_PATH_WIDTH_AUTO;
link->resource[0]->end = 16;
link->config_flags |= CONF_ENABLE_IRQ;
link->config_index = 1;
link->config_regs = PRESENT_OPTION;
*chip_ret = vxp;
return 0;
}
/**
* snd_vxpocket_assign_resources - initialize the hardware and card instance.
* @port: i/o port for the card
* @irq: irq number for the card
*
* this function assigns the specified port and irq, boot the card,
* create pcm and control instances, and initialize the rest hardware.
*
* returns 0 if successful, or a negative error code.
*/
static int snd_vxpocket_assign_resources(struct vx_core *chip, int port, int irq)
{
int err;
struct snd_card *card = chip->card;
struct snd_vxpocket *vxp = (struct snd_vxpocket *)chip;
snd_printdd(KERN_DEBUG "vxpocket assign resources: port = 0x%x, irq = %d\n", port, irq);
vxp->port = port;
sprintf(card->shortname, "Digigram %s", card->driver);
sprintf(card->longname, "%s at 0x%x, irq %i",
card->shortname, port, irq);
chip->irq = irq;
if ((err = snd_vx_setup_firmware(chip)) < 0)
return err;
return 0;
}
/*
* configuration callback
*/
static int vxpocket_config(struct pcmcia_device *link)
{
struct vx_core *chip = link->priv;
int ret;
snd_printdd(KERN_DEBUG "vxpocket_config called\n");
/* redefine hardware record according to the VERSION1 string */
if (!strcmp(link->prod_id[1], "VX-POCKET")) {
snd_printdd("VX-pocket is detected\n");
} else {
snd_printdd("VX-pocket 440 is detected\n");
/* overwrite the hardware information */
chip->hw = &vxp440_hw;
chip->type = vxp440_hw.type;
strcpy(chip->card->driver, vxp440_hw.name);
}
ret = pcmcia_request_io(link);
if (ret)
goto failed;
ret = pcmcia_request_exclusive_irq(link, snd_vx_irq_handler);
if (ret)
goto failed;
ret = pcmcia_enable_device(link);
if (ret)
goto failed;
chip->dev = &link->dev;
snd_card_set_dev(chip->card, chip->dev);
if (snd_vxpocket_assign_resources(chip, link->resource[0]->start,
link->irq) < 0)
goto failed;
return 0;
failed:
pcmcia_disable_device(link);
return -ENODEV;
}
#ifdef CONFIG_PM
static int vxp_suspend(struct pcmcia_device *link)
{
struct vx_core *chip = link->priv;
snd_printdd(KERN_DEBUG "SUSPEND\n");
if (chip) {
snd_printdd(KERN_DEBUG "snd_vx_suspend calling\n");
snd_vx_suspend(chip, PMSG_SUSPEND);
}
return 0;
}
static int vxp_resume(struct pcmcia_device *link)
{
struct vx_core *chip = link->priv;
snd_printdd(KERN_DEBUG "RESUME\n");
if (pcmcia_dev_present(link)) {
//struct snd_vxpocket *vxp = (struct snd_vxpocket *)chip;
if (chip) {
snd_printdd(KERN_DEBUG "calling snd_vx_resume\n");
snd_vx_resume(chip);
}
}
snd_printdd(KERN_DEBUG "resume done!\n");
return 0;
}
#endif
/*
*/
static int vxpocket_probe(struct pcmcia_device *p_dev)
{
struct snd_card *card;
struct snd_vxpocket *vxp;
int i, err;
/* find an empty slot from the card list */
for (i = 0; i < SNDRV_CARDS; i++) {
if (!(card_alloc & (1 << i)))
break;
}
if (i >= SNDRV_CARDS) {
snd_printk(KERN_ERR "vxpocket: too many cards found\n");
return -EINVAL;
}
if (! enable[i])
return -ENODEV; /* disabled explicitly */
/* ok, create a card instance */
err = snd_card_create(index[i], id[i], THIS_MODULE, 0, &card);
if (err < 0) {
snd_printk(KERN_ERR "vxpocket: cannot create a card instance\n");
return err;
}
err = snd_vxpocket_new(card, ibl[i], p_dev, &vxp);
if (err < 0) {
snd_card_free(card);
return err;
}
card->private_data = vxp;
vxp->index = i;
card_alloc |= 1 << i;
vxp->p_dev = p_dev;
return vxpocket_config(p_dev);
}
static void vxpocket_detach(struct pcmcia_device *link)
{
struct snd_vxpocket *vxp;
struct vx_core *chip;
if (! link)
return;
vxp = link->priv;
chip = (struct vx_core *)vxp;
card_alloc &= ~(1 << vxp->index);
chip->chip_status |= VX_STAT_IS_STALE; /* to be sure */
snd_card_disconnect(chip->card);
vxpocket_release(link);
snd_card_free_when_closed(chip->card);
}
/*
* Module entry points
*/
static const struct pcmcia_device_id vxp_ids[] = {
PCMCIA_DEVICE_MANF_CARD(0x01f1, 0x0100),
PCMCIA_DEVICE_NULL
};
MODULE_DEVICE_TABLE(pcmcia, vxp_ids);
static struct pcmcia_driver vxp_cs_driver = {
.owner = THIS_MODULE,
.name = "snd-vxpocket",
.probe = vxpocket_probe,
.remove = vxpocket_detach,
.id_table = vxp_ids,
#ifdef CONFIG_PM
.suspend = vxp_suspend,
.resume = vxp_resume,
#endif
};
static int __init init_vxpocket(void)
{
return pcmcia_register_driver(&vxp_cs_driver);
}
static void __exit exit_vxpocket(void)
{
pcmcia_unregister_driver(&vxp_cs_driver);
}
module_init(init_vxpocket);
module_exit(exit_vxpocket);
| gpl-2.0 |
gandalfk7/arietta_kernel3.18.1 | drivers/net/irda/sh_sir.c | 1744 | 18104 | /*
* SuperH IrDA Driver
*
* Copyright (C) 2009 Renesas Solutions Corp.
* Kuninori Morimoto <morimoto.kuninori@renesas.com>
*
* Based on bfin_sir.c
* Copyright 2006-2009 Analog Devices Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/io.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <net/irda/wrapper.h>
#include <net/irda/irda_device.h>
#include <asm/clock.h>
#define DRIVER_NAME "sh_sir"
#define RX_PHASE (1 << 0)
#define TX_PHASE (1 << 1)
#define TX_COMP_PHASE (1 << 2) /* tx complete */
#define NONE_PHASE (1 << 31)
#define IRIF_RINTCLR 0x0016 /* DMA rx interrupt source clear */
#define IRIF_TINTCLR 0x0018 /* DMA tx interrupt source clear */
#define IRIF_SIR0 0x0020 /* IrDA-SIR10 control */
#define IRIF_SIR1 0x0022 /* IrDA-SIR10 baudrate error correction */
#define IRIF_SIR2 0x0024 /* IrDA-SIR10 baudrate count */
#define IRIF_SIR3 0x0026 /* IrDA-SIR10 status */
#define IRIF_SIR_FRM 0x0028 /* Hardware frame processing set */
#define IRIF_SIR_EOF 0x002A /* EOF value */
#define IRIF_SIR_FLG 0x002C /* Flag clear */
#define IRIF_UART_STS2 0x002E /* UART status 2 */
#define IRIF_UART0 0x0030 /* UART control */
#define IRIF_UART1 0x0032 /* UART status */
#define IRIF_UART2 0x0034 /* UART mode */
#define IRIF_UART3 0x0036 /* UART transmit data */
#define IRIF_UART4 0x0038 /* UART receive data */
#define IRIF_UART5 0x003A /* UART interrupt mask */
#define IRIF_UART6 0x003C /* UART baud rate error correction */
#define IRIF_UART7 0x003E /* UART baud rate count set */
#define IRIF_CRC0 0x0040 /* CRC engine control */
#define IRIF_CRC1 0x0042 /* CRC engine input data */
#define IRIF_CRC2 0x0044 /* CRC engine calculation */
#define IRIF_CRC3 0x0046 /* CRC engine output data 1 */
#define IRIF_CRC4 0x0048 /* CRC engine output data 2 */
/* IRIF_SIR0 */
#define IRTPW (1 << 1) /* transmit pulse width select */
#define IRERRC (1 << 0) /* Clear receive pulse width error */
/* IRIF_SIR3 */
#define IRERR (1 << 0) /* received pulse width Error */
/* IRIF_SIR_FRM */
#define EOFD (1 << 9) /* EOF detection flag */
#define FRER (1 << 8) /* Frame Error bit */
#define FRP (1 << 0) /* Frame processing set */
/* IRIF_UART_STS2 */
#define IRSME (1 << 6) /* Receive Sum Error flag */
#define IROVE (1 << 5) /* Receive Overrun Error flag */
#define IRFRE (1 << 4) /* Receive Framing Error flag */
#define IRPRE (1 << 3) /* Receive Parity Error flag */
/* IRIF_UART0_*/
#define TBEC (1 << 2) /* Transmit Data Clear */
#define RIE (1 << 1) /* Receive Enable */
#define TIE (1 << 0) /* Transmit Enable */
/* IRIF_UART1 */
#define URSME (1 << 6) /* Receive Sum Error Flag */
#define UROVE (1 << 5) /* Receive Overrun Error Flag */
#define URFRE (1 << 4) /* Receive Framing Error Flag */
#define URPRE (1 << 3) /* Receive Parity Error Flag */
#define RBF (1 << 2) /* Receive Buffer Full Flag */
#define TSBE (1 << 1) /* Transmit Shift Buffer Empty Flag */
#define TBE (1 << 0) /* Transmit Buffer Empty flag */
#define TBCOMP (TSBE | TBE)
/* IRIF_UART5 */
#define RSEIM (1 << 6) /* Receive Sum Error Flag IRQ Mask */
#define RBFIM (1 << 2) /* Receive Buffer Full Flag IRQ Mask */
#define TSBEIM (1 << 1) /* Transmit Shift Buffer Empty Flag IRQ Mask */
#define TBEIM (1 << 0) /* Transmit Buffer Empty Flag IRQ Mask */
#define RX_MASK (RSEIM | RBFIM)
/* IRIF_CRC0 */
#define CRC_RST (1 << 15) /* CRC Engine Reset */
#define CRC_CT_MASK 0x0FFF
/************************************************************************
structure
************************************************************************/
struct sh_sir_self {
void __iomem *membase;
unsigned int irq;
struct clk *clk;
struct net_device *ndev;
struct irlap_cb *irlap;
struct qos_info qos;
iobuff_t tx_buff;
iobuff_t rx_buff;
};
/************************************************************************
common function
************************************************************************/
static void sh_sir_write(struct sh_sir_self *self, u32 offset, u16 data)
{
iowrite16(data, self->membase + offset);
}
static u16 sh_sir_read(struct sh_sir_self *self, u32 offset)
{
return ioread16(self->membase + offset);
}
static void sh_sir_update_bits(struct sh_sir_self *self, u32 offset,
u16 mask, u16 data)
{
u16 old, new;
old = sh_sir_read(self, offset);
new = (old & ~mask) | data;
if (old != new)
sh_sir_write(self, offset, new);
}
/************************************************************************
CRC function
************************************************************************/
static void sh_sir_crc_reset(struct sh_sir_self *self)
{
sh_sir_write(self, IRIF_CRC0, CRC_RST);
}
static void sh_sir_crc_add(struct sh_sir_self *self, u8 data)
{
sh_sir_write(self, IRIF_CRC1, (u16)data);
}
static u16 sh_sir_crc_cnt(struct sh_sir_self *self)
{
return CRC_CT_MASK & sh_sir_read(self, IRIF_CRC0);
}
static u16 sh_sir_crc_out(struct sh_sir_self *self)
{
return sh_sir_read(self, IRIF_CRC4);
}
static int sh_sir_crc_init(struct sh_sir_self *self)
{
struct device *dev = &self->ndev->dev;
int ret = -EIO;
u16 val;
sh_sir_crc_reset(self);
sh_sir_crc_add(self, 0xCC);
sh_sir_crc_add(self, 0xF5);
sh_sir_crc_add(self, 0xF1);
sh_sir_crc_add(self, 0xA7);
val = sh_sir_crc_cnt(self);
if (4 != val) {
dev_err(dev, "CRC count error %x\n", val);
goto crc_init_out;
}
val = sh_sir_crc_out(self);
if (0x51DF != val) {
dev_err(dev, "CRC result error%x\n", val);
goto crc_init_out;
}
ret = 0;
crc_init_out:
sh_sir_crc_reset(self);
return ret;
}
/************************************************************************
baud rate functions
************************************************************************/
#define SCLK_BASE 1843200 /* 1.8432MHz */
static u32 sh_sir_find_sclk(struct clk *irda_clk)
{
struct cpufreq_frequency_table *freq_table = irda_clk->freq_table;
struct cpufreq_frequency_table *pos;
struct clk *pclk = clk_get(NULL, "peripheral_clk");
u32 limit, min = 0xffffffff, tmp;
int index = 0;
limit = clk_get_rate(pclk);
clk_put(pclk);
/* IrDA can not set over peripheral_clk */
cpufreq_for_each_valid_entry(pos, freq_table) {
u32 freq = pos->frequency;
/* IrDA should not over peripheral_clk */
if (freq > limit)
continue;
tmp = freq % SCLK_BASE;
if (tmp < min) {
min = tmp;
index = pos - freq_table;
}
}
return freq_table[index].frequency;
}
#define ERR_ROUNDING(a) ((a + 5000) / 10000)
static int sh_sir_set_baudrate(struct sh_sir_self *self, u32 baudrate)
{
struct clk *clk;
struct device *dev = &self->ndev->dev;
u32 rate;
u16 uabca, uabc;
u16 irbca, irbc;
u32 min, rerr, tmp;
int i;
/* Baud Rate Error Correction x 10000 */
u32 rate_err_array[] = {
0, 625, 1250, 1875,
2500, 3125, 3750, 4375,
5000, 5625, 6250, 6875,
7500, 8125, 8750, 9375,
};
/*
* FIXME
*
* it support 9600 only now
*/
switch (baudrate) {
case 9600:
break;
default:
dev_err(dev, "un-supported baudrate %d\n", baudrate);
return -EIO;
}
clk = clk_get(NULL, "irda_clk");
if (IS_ERR(clk)) {
dev_err(dev, "can not get irda_clk\n");
return -EIO;
}
clk_set_rate(clk, sh_sir_find_sclk(clk));
rate = clk_get_rate(clk);
clk_put(clk);
dev_dbg(dev, "selected sclk = %d\n", rate);
/*
* CALCULATION
*
* 1843200 = system rate / (irbca + (irbc + 1))
*/
irbc = rate / SCLK_BASE;
tmp = rate - (SCLK_BASE * irbc);
tmp *= 10000;
rerr = tmp / SCLK_BASE;
min = 0xffffffff;
irbca = 0;
for (i = 0; i < ARRAY_SIZE(rate_err_array); i++) {
tmp = abs(rate_err_array[i] - rerr);
if (min > tmp) {
min = tmp;
irbca = i;
}
}
tmp = rate / (irbc + ERR_ROUNDING(rate_err_array[irbca]));
if ((SCLK_BASE / 100) < abs(tmp - SCLK_BASE))
dev_warn(dev, "IrDA freq error margin over %d\n", tmp);
dev_dbg(dev, "target = %d, result = %d, infrared = %d.%d\n",
SCLK_BASE, tmp, irbc, rate_err_array[irbca]);
irbca = (irbca & 0xF) << 4;
irbc = (irbc - 1) & 0xF;
if (!irbc) {
dev_err(dev, "sh_sir can not set 0 in IRIF_SIR2\n");
return -EIO;
}
sh_sir_write(self, IRIF_SIR0, IRTPW | IRERRC);
sh_sir_write(self, IRIF_SIR1, irbca);
sh_sir_write(self, IRIF_SIR2, irbc);
/*
* CALCULATION
*
* BaudRate[bps] = system rate / (uabca + (uabc + 1) x 16)
*/
uabc = rate / baudrate;
uabc = (uabc / 16) - 1;
uabc = (uabc + 1) * 16;
tmp = rate - (uabc * baudrate);
tmp *= 10000;
rerr = tmp / baudrate;
min = 0xffffffff;
uabca = 0;
for (i = 0; i < ARRAY_SIZE(rate_err_array); i++) {
tmp = abs(rate_err_array[i] - rerr);
if (min > tmp) {
min = tmp;
uabca = i;
}
}
tmp = rate / (uabc + ERR_ROUNDING(rate_err_array[uabca]));
if ((baudrate / 100) < abs(tmp - baudrate))
dev_warn(dev, "UART freq error margin over %d\n", tmp);
dev_dbg(dev, "target = %d, result = %d, uart = %d.%d\n",
baudrate, tmp,
uabc, rate_err_array[uabca]);
uabca = (uabca & 0xF) << 4;
uabc = (uabc / 16) - 1;
sh_sir_write(self, IRIF_UART6, uabca);
sh_sir_write(self, IRIF_UART7, uabc);
return 0;
}
/************************************************************************
iobuf function
************************************************************************/
static int __sh_sir_init_iobuf(iobuff_t *io, int size)
{
io->head = kmalloc(size, GFP_KERNEL);
if (!io->head)
return -ENOMEM;
io->truesize = size;
io->in_frame = FALSE;
io->state = OUTSIDE_FRAME;
io->data = io->head;
return 0;
}
static void sh_sir_remove_iobuf(struct sh_sir_self *self)
{
kfree(self->rx_buff.head);
kfree(self->tx_buff.head);
self->rx_buff.head = NULL;
self->tx_buff.head = NULL;
}
static int sh_sir_init_iobuf(struct sh_sir_self *self, int rxsize, int txsize)
{
int err = -ENOMEM;
if (self->rx_buff.head ||
self->tx_buff.head) {
dev_err(&self->ndev->dev, "iobuff has already existed.");
return err;
}
err = __sh_sir_init_iobuf(&self->rx_buff, rxsize);
if (err)
goto iobuf_err;
err = __sh_sir_init_iobuf(&self->tx_buff, txsize);
iobuf_err:
if (err)
sh_sir_remove_iobuf(self);
return err;
}
/************************************************************************
status function
************************************************************************/
static void sh_sir_clear_all_err(struct sh_sir_self *self)
{
/* Clear error flag for receive pulse width */
sh_sir_update_bits(self, IRIF_SIR0, IRERRC, IRERRC);
/* Clear frame / EOF error flag */
sh_sir_write(self, IRIF_SIR_FLG, 0xffff);
/* Clear all status error */
sh_sir_write(self, IRIF_UART_STS2, 0);
}
static void sh_sir_set_phase(struct sh_sir_self *self, int phase)
{
u16 uart5 = 0;
u16 uart0 = 0;
switch (phase) {
case TX_PHASE:
uart5 = TBEIM;
uart0 = TBEC | TIE;
break;
case TX_COMP_PHASE:
uart5 = TSBEIM;
uart0 = TIE;
break;
case RX_PHASE:
uart5 = RX_MASK;
uart0 = RIE;
break;
default:
break;
}
sh_sir_write(self, IRIF_UART5, uart5);
sh_sir_write(self, IRIF_UART0, uart0);
}
static int sh_sir_is_which_phase(struct sh_sir_self *self)
{
u16 val = sh_sir_read(self, IRIF_UART5);
if (val & TBEIM)
return TX_PHASE;
if (val & TSBEIM)
return TX_COMP_PHASE;
if (val & RX_MASK)
return RX_PHASE;
return NONE_PHASE;
}
static void sh_sir_tx(struct sh_sir_self *self, int phase)
{
switch (phase) {
case TX_PHASE:
if (0 >= self->tx_buff.len) {
sh_sir_set_phase(self, TX_COMP_PHASE);
} else {
sh_sir_write(self, IRIF_UART3, self->tx_buff.data[0]);
self->tx_buff.len--;
self->tx_buff.data++;
}
break;
case TX_COMP_PHASE:
sh_sir_set_phase(self, RX_PHASE);
netif_wake_queue(self->ndev);
break;
default:
dev_err(&self->ndev->dev, "should not happen\n");
break;
}
}
static int sh_sir_read_data(struct sh_sir_self *self)
{
u16 val = 0;
int timeout = 1024;
while (timeout--) {
val = sh_sir_read(self, IRIF_UART1);
/* data get */
if (val & RBF) {
if (val & (URSME | UROVE | URFRE | URPRE))
break;
return (int)sh_sir_read(self, IRIF_UART4);
}
udelay(1);
}
dev_err(&self->ndev->dev, "UART1 %04x : STATUS %04x\n",
val, sh_sir_read(self, IRIF_UART_STS2));
/* read data register for clear error */
sh_sir_read(self, IRIF_UART4);
return -1;
}
static void sh_sir_rx(struct sh_sir_self *self)
{
int timeout = 1024;
int data;
while (timeout--) {
data = sh_sir_read_data(self);
if (data < 0)
break;
async_unwrap_char(self->ndev, &self->ndev->stats,
&self->rx_buff, (u8)data);
self->ndev->last_rx = jiffies;
if (EOFD & sh_sir_read(self, IRIF_SIR_FRM))
continue;
break;
}
}
static irqreturn_t sh_sir_irq(int irq, void *dev_id)
{
struct sh_sir_self *self = dev_id;
struct device *dev = &self->ndev->dev;
int phase = sh_sir_is_which_phase(self);
switch (phase) {
case TX_COMP_PHASE:
case TX_PHASE:
sh_sir_tx(self, phase);
break;
case RX_PHASE:
if (sh_sir_read(self, IRIF_SIR3))
dev_err(dev, "rcv pulse width error occurred\n");
sh_sir_rx(self);
sh_sir_clear_all_err(self);
break;
default:
dev_err(dev, "unknown interrupt\n");
}
return IRQ_HANDLED;
}
/************************************************************************
net_device_ops function
************************************************************************/
static int sh_sir_hard_xmit(struct sk_buff *skb, struct net_device *ndev)
{
struct sh_sir_self *self = netdev_priv(ndev);
int speed = irda_get_next_speed(skb);
if ((0 < speed) &&
(9600 != speed)) {
dev_err(&ndev->dev, "support 9600 only (%d)\n", speed);
return -EIO;
}
netif_stop_queue(ndev);
self->tx_buff.data = self->tx_buff.head;
self->tx_buff.len = 0;
if (skb->len)
self->tx_buff.len = async_wrap_skb(skb, self->tx_buff.data,
self->tx_buff.truesize);
sh_sir_set_phase(self, TX_PHASE);
dev_kfree_skb(skb);
return 0;
}
static int sh_sir_ioctl(struct net_device *ndev, struct ifreq *ifreq, int cmd)
{
/*
* FIXME
*
* This function is needed for irda framework.
* But nothing to do now
*/
return 0;
}
static struct net_device_stats *sh_sir_stats(struct net_device *ndev)
{
struct sh_sir_self *self = netdev_priv(ndev);
return &self->ndev->stats;
}
static int sh_sir_open(struct net_device *ndev)
{
struct sh_sir_self *self = netdev_priv(ndev);
int err;
clk_enable(self->clk);
err = sh_sir_crc_init(self);
if (err)
goto open_err;
sh_sir_set_baudrate(self, 9600);
self->irlap = irlap_open(ndev, &self->qos, DRIVER_NAME);
if (!self->irlap) {
err = -ENODEV;
goto open_err;
}
/*
* Now enable the interrupt then start the queue
*/
sh_sir_update_bits(self, IRIF_SIR_FRM, FRP, FRP);
sh_sir_read(self, IRIF_UART1); /* flag clear */
sh_sir_read(self, IRIF_UART4); /* flag clear */
sh_sir_set_phase(self, RX_PHASE);
netif_start_queue(ndev);
dev_info(&self->ndev->dev, "opened\n");
return 0;
open_err:
clk_disable(self->clk);
return err;
}
static int sh_sir_stop(struct net_device *ndev)
{
struct sh_sir_self *self = netdev_priv(ndev);
/* Stop IrLAP */
if (self->irlap) {
irlap_close(self->irlap);
self->irlap = NULL;
}
netif_stop_queue(ndev);
dev_info(&ndev->dev, "stopped\n");
return 0;
}
static const struct net_device_ops sh_sir_ndo = {
.ndo_open = sh_sir_open,
.ndo_stop = sh_sir_stop,
.ndo_start_xmit = sh_sir_hard_xmit,
.ndo_do_ioctl = sh_sir_ioctl,
.ndo_get_stats = sh_sir_stats,
};
/************************************************************************
platform_driver function
************************************************************************/
static int sh_sir_probe(struct platform_device *pdev)
{
struct net_device *ndev;
struct sh_sir_self *self;
struct resource *res;
char clk_name[8];
int irq;
int err = -ENOMEM;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
irq = platform_get_irq(pdev, 0);
if (!res || irq < 0) {
dev_err(&pdev->dev, "Not enough platform resources.\n");
goto exit;
}
ndev = alloc_irdadev(sizeof(*self));
if (!ndev)
goto exit;
self = netdev_priv(ndev);
self->membase = ioremap_nocache(res->start, resource_size(res));
if (!self->membase) {
err = -ENXIO;
dev_err(&pdev->dev, "Unable to ioremap.\n");
goto err_mem_1;
}
err = sh_sir_init_iobuf(self, IRDA_SKB_MAX_MTU, IRDA_SIR_MAX_FRAME);
if (err)
goto err_mem_2;
snprintf(clk_name, sizeof(clk_name), "irda%d", pdev->id);
self->clk = clk_get(&pdev->dev, clk_name);
if (IS_ERR(self->clk)) {
dev_err(&pdev->dev, "cannot get clock \"%s\"\n", clk_name);
err = -ENODEV;
goto err_mem_3;
}
irda_init_max_qos_capabilies(&self->qos);
ndev->netdev_ops = &sh_sir_ndo;
ndev->irq = irq;
self->ndev = ndev;
self->qos.baud_rate.bits &= IR_9600; /* FIXME */
self->qos.min_turn_time.bits = 1; /* 10 ms or more */
irda_qos_bits_to_value(&self->qos);
err = register_netdev(ndev);
if (err)
goto err_mem_4;
platform_set_drvdata(pdev, ndev);
err = devm_request_irq(&pdev->dev, irq, sh_sir_irq, 0, "sh_sir", self);
if (err) {
dev_warn(&pdev->dev, "Unable to attach sh_sir interrupt\n");
goto err_mem_4;
}
dev_info(&pdev->dev, "SuperH IrDA probed\n");
goto exit;
err_mem_4:
clk_put(self->clk);
err_mem_3:
sh_sir_remove_iobuf(self);
err_mem_2:
iounmap(self->membase);
err_mem_1:
free_netdev(ndev);
exit:
return err;
}
static int sh_sir_remove(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct sh_sir_self *self = netdev_priv(ndev);
if (!self)
return 0;
unregister_netdev(ndev);
clk_put(self->clk);
sh_sir_remove_iobuf(self);
iounmap(self->membase);
free_netdev(ndev);
return 0;
}
static struct platform_driver sh_sir_driver = {
.probe = sh_sir_probe,
.remove = sh_sir_remove,
.driver = {
.name = DRIVER_NAME,
},
};
module_platform_driver(sh_sir_driver);
MODULE_AUTHOR("Kuninori Morimoto <morimoto.kuninori@renesas.com>");
MODULE_DESCRIPTION("SuperH IrDA driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
ArtisteHsu/jetson-tk1-r21.2-kernel | arch/s390/kernel/process.c | 2000 | 7328 | /*
* This file handles the architecture dependent parts of process handling.
*
* Copyright IBM Corp. 1999, 2009
* Author(s): Martin Schwidefsky <schwidefsky@de.ibm.com>,
* Hartmut Penner <hp@de.ibm.com>,
* Denis Joseph Barrow,
*/
#include <linux/compiler.h>
#include <linux/cpu.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/elfcore.h>
#include <linux/smp.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/tick.h>
#include <linux/personality.h>
#include <linux/syscalls.h>
#include <linux/compat.h>
#include <linux/kprobes.h>
#include <linux/random.h>
#include <linux/module.h>
#include <asm/io.h>
#include <asm/processor.h>
#include <asm/vtimer.h>
#include <asm/exec.h>
#include <asm/irq.h>
#include <asm/nmi.h>
#include <asm/smp.h>
#include <asm/switch_to.h>
#include <asm/runtime_instr.h>
#include "entry.h"
asmlinkage void ret_from_fork(void) asm ("ret_from_fork");
/*
* Return saved PC of a blocked thread. used in kernel/sched.
* resume in entry.S does not create a new stack frame, it
* just stores the registers %r6-%r15 to the frame given by
* schedule. We want to return the address of the caller of
* schedule, so we have to walk the backchain one time to
* find the frame schedule() store its return address.
*/
unsigned long thread_saved_pc(struct task_struct *tsk)
{
struct stack_frame *sf, *low, *high;
if (!tsk || !task_stack_page(tsk))
return 0;
low = task_stack_page(tsk);
high = (struct stack_frame *) task_pt_regs(tsk);
sf = (struct stack_frame *) (tsk->thread.ksp & PSW_ADDR_INSN);
if (sf <= low || sf > high)
return 0;
sf = (struct stack_frame *) (sf->back_chain & PSW_ADDR_INSN);
if (sf <= low || sf > high)
return 0;
return sf->gprs[8];
}
void arch_cpu_idle(void)
{
local_mcck_disable();
if (test_thread_flag(TIF_MCCK_PENDING)) {
local_mcck_enable();
local_irq_enable();
return;
}
/* Halt the cpu and keep track of cpu time accounting. */
vtime_stop_cpu();
}
void arch_cpu_idle_exit(void)
{
if (test_thread_flag(TIF_MCCK_PENDING))
s390_handle_mcck();
}
void arch_cpu_idle_dead(void)
{
cpu_die();
}
extern void __kprobes kernel_thread_starter(void);
/*
* Free current thread data structures etc..
*/
void exit_thread(void)
{
exit_thread_runtime_instr();
}
void flush_thread(void)
{
}
void release_thread(struct task_struct *dead_task)
{
}
int copy_thread(unsigned long clone_flags, unsigned long new_stackp,
unsigned long arg, struct task_struct *p)
{
struct thread_info *ti;
struct fake_frame
{
struct stack_frame sf;
struct pt_regs childregs;
} *frame;
frame = container_of(task_pt_regs(p), struct fake_frame, childregs);
p->thread.ksp = (unsigned long) frame;
/* Save access registers to new thread structure. */
save_access_regs(&p->thread.acrs[0]);
/* start new process with ar4 pointing to the correct address space */
p->thread.mm_segment = get_fs();
/* Don't copy debug registers */
memset(&p->thread.per_user, 0, sizeof(p->thread.per_user));
memset(&p->thread.per_event, 0, sizeof(p->thread.per_event));
clear_tsk_thread_flag(p, TIF_SINGLE_STEP);
clear_tsk_thread_flag(p, TIF_PER_TRAP);
/* Initialize per thread user and system timer values */
ti = task_thread_info(p);
ti->user_timer = 0;
ti->system_timer = 0;
frame->sf.back_chain = 0;
/* new return point is ret_from_fork */
frame->sf.gprs[8] = (unsigned long) ret_from_fork;
/* fake return stack for resume(), don't go back to schedule */
frame->sf.gprs[9] = (unsigned long) frame;
/* Store access registers to kernel stack of new process. */
if (unlikely(p->flags & PF_KTHREAD)) {
/* kernel thread */
memset(&frame->childregs, 0, sizeof(struct pt_regs));
frame->childregs.psw.mask = psw_kernel_bits | PSW_MASK_DAT |
PSW_MASK_IO | PSW_MASK_EXT | PSW_MASK_MCHECK;
frame->childregs.psw.addr = PSW_ADDR_AMODE |
(unsigned long) kernel_thread_starter;
frame->childregs.gprs[9] = new_stackp; /* function */
frame->childregs.gprs[10] = arg;
frame->childregs.gprs[11] = (unsigned long) do_exit;
frame->childregs.orig_gpr2 = -1;
return 0;
}
frame->childregs = *current_pt_regs();
frame->childregs.gprs[2] = 0; /* child returns 0 on fork. */
if (new_stackp)
frame->childregs.gprs[15] = new_stackp;
/* Don't copy runtime instrumentation info */
p->thread.ri_cb = NULL;
p->thread.ri_signum = 0;
frame->childregs.psw.mask &= ~PSW_MASK_RI;
#ifndef CONFIG_64BIT
/*
* save fprs to current->thread.fp_regs to merge them with
* the emulated registers and then copy the result to the child.
*/
save_fp_regs(¤t->thread.fp_regs);
memcpy(&p->thread.fp_regs, ¤t->thread.fp_regs,
sizeof(s390_fp_regs));
/* Set a new TLS ? */
if (clone_flags & CLONE_SETTLS)
p->thread.acrs[0] = frame->childregs.gprs[6];
#else /* CONFIG_64BIT */
/* Save the fpu registers to new thread structure. */
save_fp_regs(&p->thread.fp_regs);
/* Set a new TLS ? */
if (clone_flags & CLONE_SETTLS) {
unsigned long tls = frame->childregs.gprs[6];
if (is_compat_task()) {
p->thread.acrs[0] = (unsigned int)tls;
} else {
p->thread.acrs[0] = (unsigned int)(tls >> 32);
p->thread.acrs[1] = (unsigned int)tls;
}
}
#endif /* CONFIG_64BIT */
return 0;
}
asmlinkage void execve_tail(void)
{
current->thread.fp_regs.fpc = 0;
if (MACHINE_HAS_IEEE)
asm volatile("sfpc %0,%0" : : "d" (0));
}
/*
* fill in the FPU structure for a core dump.
*/
int dump_fpu (struct pt_regs * regs, s390_fp_regs *fpregs)
{
#ifndef CONFIG_64BIT
/*
* save fprs to current->thread.fp_regs to merge them with
* the emulated registers and then copy the result to the dump.
*/
save_fp_regs(¤t->thread.fp_regs);
memcpy(fpregs, ¤t->thread.fp_regs, sizeof(s390_fp_regs));
#else /* CONFIG_64BIT */
save_fp_regs(fpregs);
#endif /* CONFIG_64BIT */
return 1;
}
EXPORT_SYMBOL(dump_fpu);
unsigned long get_wchan(struct task_struct *p)
{
struct stack_frame *sf, *low, *high;
unsigned long return_address;
int count;
if (!p || p == current || p->state == TASK_RUNNING || !task_stack_page(p))
return 0;
low = task_stack_page(p);
high = (struct stack_frame *) task_pt_regs(p);
sf = (struct stack_frame *) (p->thread.ksp & PSW_ADDR_INSN);
if (sf <= low || sf > high)
return 0;
for (count = 0; count < 16; count++) {
sf = (struct stack_frame *) (sf->back_chain & PSW_ADDR_INSN);
if (sf <= low || sf > high)
return 0;
return_address = sf->gprs[8] & PSW_ADDR_INSN;
if (!in_sched_functions(return_address))
return return_address;
}
return 0;
}
unsigned long arch_align_stack(unsigned long sp)
{
if (!(current->personality & ADDR_NO_RANDOMIZE) && randomize_va_space)
sp -= get_random_int() & ~PAGE_MASK;
return sp & ~0xf;
}
static inline unsigned long brk_rnd(void)
{
/* 8MB for 32bit, 1GB for 64bit */
if (is_32bit_task())
return (get_random_int() & 0x7ffUL) << PAGE_SHIFT;
else
return (get_random_int() & 0x3ffffUL) << PAGE_SHIFT;
}
unsigned long arch_randomize_brk(struct mm_struct *mm)
{
unsigned long ret = PAGE_ALIGN(mm->brk + brk_rnd());
if (ret < mm->brk)
return mm->brk;
return ret;
}
unsigned long randomize_et_dyn(unsigned long base)
{
unsigned long ret = PAGE_ALIGN(base + brk_rnd());
if (!(current->flags & PF_RANDOMIZE))
return base;
if (ret < base)
return base;
return ret;
}
| gpl-2.0 |
sandymanu/sandy_sambar_8994 | drivers/usb/phy/phy-rcar-usb.c | 2256 | 5133 | /*
* Renesas R-Car USB phy driver
*
* Copyright (C) 2012 Renesas Solutions Corp.
* Kuninori Morimoto <kuninori.morimoto.gx@renesas.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/delay.h>
#include <linux/io.h>
#include <linux/usb/otg.h>
#include <linux/platform_device.h>
#include <linux/spinlock.h>
#include <linux/module.h>
/* USBH common register */
#define USBPCTRL0 0x0800
#define USBPCTRL1 0x0804
#define USBST 0x0808
#define USBEH0 0x080C
#define USBOH0 0x081C
#define USBCTL0 0x0858
#define EIIBC1 0x0094
#define EIIBC2 0x009C
/* USBPCTRL1 */
#define PHY_RST (1 << 2)
#define PLL_ENB (1 << 1)
#define PHY_ENB (1 << 0)
/* USBST */
#define ST_ACT (1 << 31)
#define ST_PLL (1 << 30)
struct rcar_usb_phy_priv {
struct usb_phy phy;
spinlock_t lock;
void __iomem *reg0;
void __iomem *reg1;
int counter;
};
#define usb_phy_to_priv(p) container_of(p, struct rcar_usb_phy_priv, phy)
/*
* USB initial/install operation.
*
* This function setup USB phy.
* The used value and setting order came from
* [USB :: Initial setting] on datasheet.
*/
static int rcar_usb_phy_init(struct usb_phy *phy)
{
struct rcar_usb_phy_priv *priv = usb_phy_to_priv(phy);
struct device *dev = phy->dev;
void __iomem *reg0 = priv->reg0;
void __iomem *reg1 = priv->reg1;
int i;
u32 val;
unsigned long flags;
spin_lock_irqsave(&priv->lock, flags);
if (priv->counter++ == 0) {
/*
* USB phy start-up
*/
/* (1) USB-PHY standby release */
iowrite32(PHY_ENB, (reg0 + USBPCTRL1));
/* (2) start USB-PHY internal PLL */
iowrite32(PHY_ENB | PLL_ENB, (reg0 + USBPCTRL1));
/* (3) USB module status check */
for (i = 0; i < 1024; i++) {
udelay(10);
val = ioread32(reg0 + USBST);
if (val == (ST_ACT | ST_PLL))
break;
}
if (val != (ST_ACT | ST_PLL)) {
dev_err(dev, "USB phy not ready\n");
goto phy_init_end;
}
/* (4) USB-PHY reset clear */
iowrite32(PHY_ENB | PLL_ENB | PHY_RST, (reg0 + USBPCTRL1));
/* set platform specific port settings */
iowrite32(0x00000000, (reg0 + USBPCTRL0));
/*
* EHCI IP internal buffer setting
* EHCI IP internal buffer enable
*
* These are recommended value of a datasheet
* see [USB :: EHCI internal buffer setting]
*/
iowrite32(0x00ff0040, (reg0 + EIIBC1));
iowrite32(0x00ff0040, (reg1 + EIIBC1));
iowrite32(0x00000001, (reg0 + EIIBC2));
iowrite32(0x00000001, (reg1 + EIIBC2));
/*
* Bus alignment settings
*/
/* (1) EHCI bus alignment (little endian) */
iowrite32(0x00000000, (reg0 + USBEH0));
/* (1) OHCI bus alignment (little endian) */
iowrite32(0x00000000, (reg0 + USBOH0));
}
phy_init_end:
spin_unlock_irqrestore(&priv->lock, flags);
return 0;
}
static void rcar_usb_phy_shutdown(struct usb_phy *phy)
{
struct rcar_usb_phy_priv *priv = usb_phy_to_priv(phy);
void __iomem *reg0 = priv->reg0;
unsigned long flags;
spin_lock_irqsave(&priv->lock, flags);
if (priv->counter-- == 1) { /* last user */
iowrite32(0x00000000, (reg0 + USBPCTRL0));
iowrite32(0x00000000, (reg0 + USBPCTRL1));
}
spin_unlock_irqrestore(&priv->lock, flags);
}
static int rcar_usb_phy_probe(struct platform_device *pdev)
{
struct rcar_usb_phy_priv *priv;
struct resource *res0, *res1;
struct device *dev = &pdev->dev;
void __iomem *reg0, *reg1;
int ret;
res0 = platform_get_resource(pdev, IORESOURCE_MEM, 0);
res1 = platform_get_resource(pdev, IORESOURCE_MEM, 1);
if (!res0 || !res1) {
dev_err(dev, "Not enough platform resources\n");
return -EINVAL;
}
/*
* CAUTION
*
* Because this phy address is also mapped under OHCI/EHCI address area,
* this driver can't use devm_request_and_ioremap(dev, res) here
*/
reg0 = devm_ioremap_nocache(dev, res0->start, resource_size(res0));
reg1 = devm_ioremap_nocache(dev, res1->start, resource_size(res1));
if (!reg0 || !reg1) {
dev_err(dev, "ioremap error\n");
return -ENOMEM;
}
priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL);
if (!priv) {
dev_err(dev, "priv data allocation error\n");
return -ENOMEM;
}
priv->reg0 = reg0;
priv->reg1 = reg1;
priv->counter = 0;
priv->phy.dev = dev;
priv->phy.label = dev_name(dev);
priv->phy.init = rcar_usb_phy_init;
priv->phy.shutdown = rcar_usb_phy_shutdown;
spin_lock_init(&priv->lock);
ret = usb_add_phy(&priv->phy, USB_PHY_TYPE_USB2);
if (ret < 0) {
dev_err(dev, "usb phy addition error\n");
return ret;
}
platform_set_drvdata(pdev, priv);
return ret;
}
static int rcar_usb_phy_remove(struct platform_device *pdev)
{
struct rcar_usb_phy_priv *priv = platform_get_drvdata(pdev);
usb_remove_phy(&priv->phy);
return 0;
}
static struct platform_driver rcar_usb_phy_driver = {
.driver = {
.name = "rcar_usb_phy",
},
.probe = rcar_usb_phy_probe,
.remove = rcar_usb_phy_remove,
};
module_platform_driver(rcar_usb_phy_driver);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Renesas R-Car USB phy");
MODULE_AUTHOR("Kuninori Morimoto <kuninori.morimoto.gx@renesas.com>");
| gpl-2.0 |
Swapnil133609/Zeus_exp | drivers/usb/gadget/uvc_v4l2.c | 2768 | 8407 | /*
* uvc_v4l2.c -- USB Video Class Gadget driver
*
* Copyright (C) 2009-2010
* Laurent Pinchart (laurent.pinchart@ideasonboard.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/kernel.h>
#include <linux/device.h>
#include <linux/errno.h>
#include <linux/list.h>
#include <linux/mutex.h>
#include <linux/videodev2.h>
#include <linux/vmalloc.h>
#include <linux/wait.h>
#include <media/v4l2-dev.h>
#include <media/v4l2-event.h>
#include <media/v4l2-ioctl.h>
#include "uvc.h"
#include "uvc_queue.h"
/* --------------------------------------------------------------------------
* Requests handling
*/
static int
uvc_send_response(struct uvc_device *uvc, struct uvc_request_data *data)
{
struct usb_composite_dev *cdev = uvc->func.config->cdev;
struct usb_request *req = uvc->control_req;
if (data->length < 0)
return usb_ep_set_halt(cdev->gadget->ep0);
req->length = min_t(unsigned int, uvc->event_length, data->length);
req->zero = data->length < uvc->event_length;
memcpy(req->buf, data->data, req->length);
return usb_ep_queue(cdev->gadget->ep0, req, GFP_KERNEL);
}
/* --------------------------------------------------------------------------
* V4L2
*/
struct uvc_format
{
u8 bpp;
u32 fcc;
};
static struct uvc_format uvc_formats[] = {
{ 16, V4L2_PIX_FMT_YUYV },
{ 0, V4L2_PIX_FMT_MJPEG },
};
static int
uvc_v4l2_get_format(struct uvc_video *video, struct v4l2_format *fmt)
{
fmt->fmt.pix.pixelformat = video->fcc;
fmt->fmt.pix.width = video->width;
fmt->fmt.pix.height = video->height;
fmt->fmt.pix.field = V4L2_FIELD_NONE;
fmt->fmt.pix.bytesperline = video->bpp * video->width / 8;
fmt->fmt.pix.sizeimage = video->imagesize;
fmt->fmt.pix.colorspace = V4L2_COLORSPACE_SRGB;
fmt->fmt.pix.priv = 0;
return 0;
}
static int
uvc_v4l2_set_format(struct uvc_video *video, struct v4l2_format *fmt)
{
struct uvc_format *format;
unsigned int imagesize;
unsigned int bpl;
unsigned int i;
for (i = 0; i < ARRAY_SIZE(uvc_formats); ++i) {
format = &uvc_formats[i];
if (format->fcc == fmt->fmt.pix.pixelformat)
break;
}
if (i == ARRAY_SIZE(uvc_formats)) {
printk(KERN_INFO "Unsupported format 0x%08x.\n",
fmt->fmt.pix.pixelformat);
return -EINVAL;
}
bpl = format->bpp * fmt->fmt.pix.width / 8;
imagesize = bpl ? bpl * fmt->fmt.pix.height : fmt->fmt.pix.sizeimage;
video->fcc = format->fcc;
video->bpp = format->bpp;
video->width = fmt->fmt.pix.width;
video->height = fmt->fmt.pix.height;
video->imagesize = imagesize;
fmt->fmt.pix.field = V4L2_FIELD_NONE;
fmt->fmt.pix.bytesperline = bpl;
fmt->fmt.pix.sizeimage = imagesize;
fmt->fmt.pix.colorspace = V4L2_COLORSPACE_SRGB;
fmt->fmt.pix.priv = 0;
return 0;
}
static int
uvc_v4l2_open(struct file *file)
{
struct video_device *vdev = video_devdata(file);
struct uvc_device *uvc = video_get_drvdata(vdev);
struct uvc_file_handle *handle;
handle = kzalloc(sizeof(*handle), GFP_KERNEL);
if (handle == NULL)
return -ENOMEM;
v4l2_fh_init(&handle->vfh, vdev);
v4l2_fh_add(&handle->vfh);
handle->device = &uvc->video;
file->private_data = &handle->vfh;
uvc_function_connect(uvc);
return 0;
}
static int
uvc_v4l2_release(struct file *file)
{
struct video_device *vdev = video_devdata(file);
struct uvc_device *uvc = video_get_drvdata(vdev);
struct uvc_file_handle *handle = to_uvc_file_handle(file->private_data);
struct uvc_video *video = handle->device;
uvc_function_disconnect(uvc);
uvc_video_enable(video, 0);
uvc_free_buffers(&video->queue);
file->private_data = NULL;
v4l2_fh_del(&handle->vfh);
v4l2_fh_exit(&handle->vfh);
kfree(handle);
return 0;
}
static long
uvc_v4l2_do_ioctl(struct file *file, unsigned int cmd, void *arg)
{
struct video_device *vdev = video_devdata(file);
struct uvc_device *uvc = video_get_drvdata(vdev);
struct uvc_file_handle *handle = to_uvc_file_handle(file->private_data);
struct usb_composite_dev *cdev = uvc->func.config->cdev;
struct uvc_video *video = &uvc->video;
int ret = 0;
switch (cmd) {
/* Query capabilities */
case VIDIOC_QUERYCAP:
{
struct v4l2_capability *cap = arg;
memset(cap, 0, sizeof *cap);
strlcpy(cap->driver, "g_uvc", sizeof(cap->driver));
strlcpy(cap->card, cdev->gadget->name, sizeof(cap->card));
strlcpy(cap->bus_info, dev_name(&cdev->gadget->dev),
sizeof cap->bus_info);
cap->version = DRIVER_VERSION_NUMBER;
cap->capabilities = V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_STREAMING;
break;
}
/* Get & Set format */
case VIDIOC_G_FMT:
{
struct v4l2_format *fmt = arg;
if (fmt->type != video->queue.queue.type)
return -EINVAL;
return uvc_v4l2_get_format(video, fmt);
}
case VIDIOC_S_FMT:
{
struct v4l2_format *fmt = arg;
if (fmt->type != video->queue.queue.type)
return -EINVAL;
return uvc_v4l2_set_format(video, fmt);
}
/* Buffers & streaming */
case VIDIOC_REQBUFS:
{
struct v4l2_requestbuffers *rb = arg;
if (rb->type != video->queue.queue.type)
return -EINVAL;
ret = uvc_alloc_buffers(&video->queue, rb);
if (ret < 0)
return ret;
ret = 0;
break;
}
case VIDIOC_QUERYBUF:
{
struct v4l2_buffer *buf = arg;
return uvc_query_buffer(&video->queue, buf);
}
case VIDIOC_QBUF:
if ((ret = uvc_queue_buffer(&video->queue, arg)) < 0)
return ret;
return uvc_video_pump(video);
case VIDIOC_DQBUF:
return uvc_dequeue_buffer(&video->queue, arg,
file->f_flags & O_NONBLOCK);
case VIDIOC_STREAMON:
{
int *type = arg;
if (*type != video->queue.queue.type)
return -EINVAL;
/* Enable UVC video. */
ret = uvc_video_enable(video, 1);
if (ret < 0)
return ret;
/*
* Complete the alternate setting selection setup phase now that
* userspace is ready to provide video frames.
*/
uvc_function_setup_continue(uvc);
uvc->state = UVC_STATE_STREAMING;
return 0;
}
case VIDIOC_STREAMOFF:
{
int *type = arg;
if (*type != video->queue.queue.type)
return -EINVAL;
return uvc_video_enable(video, 0);
}
/* Events */
case VIDIOC_DQEVENT:
{
struct v4l2_event *event = arg;
ret = v4l2_event_dequeue(&handle->vfh, event,
file->f_flags & O_NONBLOCK);
if (ret == 0 && event->type == UVC_EVENT_SETUP) {
struct uvc_event *uvc_event = (void *)&event->u.data;
/* Tell the complete callback to generate an event for
* the next request that will be enqueued by
* uvc_event_write.
*/
uvc->event_setup_out =
!(uvc_event->req.bRequestType & USB_DIR_IN);
uvc->event_length = uvc_event->req.wLength;
}
return ret;
}
case VIDIOC_SUBSCRIBE_EVENT:
{
struct v4l2_event_subscription *sub = arg;
if (sub->type < UVC_EVENT_FIRST || sub->type > UVC_EVENT_LAST)
return -EINVAL;
return v4l2_event_subscribe(&handle->vfh, arg, 2, NULL);
}
case VIDIOC_UNSUBSCRIBE_EVENT:
return v4l2_event_unsubscribe(&handle->vfh, arg);
case UVCIOC_SEND_RESPONSE:
ret = uvc_send_response(uvc, arg);
break;
default:
return -ENOIOCTLCMD;
}
return ret;
}
static long
uvc_v4l2_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
return video_usercopy(file, cmd, arg, uvc_v4l2_do_ioctl);
}
static int
uvc_v4l2_mmap(struct file *file, struct vm_area_struct *vma)
{
struct video_device *vdev = video_devdata(file);
struct uvc_device *uvc = video_get_drvdata(vdev);
return uvc_queue_mmap(&uvc->video.queue, vma);
}
static unsigned int
uvc_v4l2_poll(struct file *file, poll_table *wait)
{
struct video_device *vdev = video_devdata(file);
struct uvc_device *uvc = video_get_drvdata(vdev);
return uvc_queue_poll(&uvc->video.queue, file, wait);
}
#ifndef CONFIG_MMU
static unsigned long uvc_v4l2_get_unmapped_area(struct file *file,
unsigned long addr, unsigned long len, unsigned long pgoff,
unsigned long flags)
{
struct video_device *vdev = video_devdata(file);
struct uvc_device *uvc = video_get_drvdata(vdev);
return uvc_queue_get_unmapped_area(&uvc->video.queue, pgoff);
}
#endif
static struct v4l2_file_operations uvc_v4l2_fops = {
.owner = THIS_MODULE,
.open = uvc_v4l2_open,
.release = uvc_v4l2_release,
.ioctl = uvc_v4l2_ioctl,
.mmap = uvc_v4l2_mmap,
.poll = uvc_v4l2_poll,
#ifndef CONFIG_MMU
.get_unmapped_area = uvc_v4l2_get_unmapped_area,
#endif
};
| gpl-2.0 |
GenTarkin/SGH-T769-kernel | drivers/net/arm/at91_ether.c | 3536 | 37546 | /*
* Ethernet driver for the Atmel AT91RM9200 (Thunder)
*
* Copyright (C) 2003 SAN People (Pty) Ltd
*
* Based on an earlier Atmel EMAC macrocell driver by Atmel and Lineo Inc.
* Initial version by Rick Bronson 01/11/2003
*
* Intel LXT971A PHY support by Christopher Bahns & David Knickerbocker
* (Polaroid Corporation)
*
* Realtek RTL8201(B)L PHY support by Roman Avramenko <roman@imsystems.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.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/mii.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/dma-mapping.h>
#include <linux/ethtool.h>
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <linux/gfp.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <asm/mach-types.h>
#include <mach/at91rm9200_emac.h>
#include <mach/gpio.h>
#include <mach/board.h>
#include "at91_ether.h"
#define DRV_NAME "at91_ether"
#define DRV_VERSION "1.0"
#define LINK_POLL_INTERVAL (HZ)
/* ..................................................................... */
/*
* Read from a EMAC register.
*/
static inline unsigned long at91_emac_read(unsigned int reg)
{
void __iomem *emac_base = (void __iomem *)AT91_VA_BASE_EMAC;
return __raw_readl(emac_base + reg);
}
/*
* Write to a EMAC register.
*/
static inline void at91_emac_write(unsigned int reg, unsigned long value)
{
void __iomem *emac_base = (void __iomem *)AT91_VA_BASE_EMAC;
__raw_writel(value, emac_base + reg);
}
/* ........................... PHY INTERFACE ........................... */
/*
* Enable the MDIO bit in MAC control register
* When not called from an interrupt-handler, access to the PHY must be
* protected by a spinlock.
*/
static void enable_mdi(void)
{
unsigned long ctl;
ctl = at91_emac_read(AT91_EMAC_CTL);
at91_emac_write(AT91_EMAC_CTL, ctl | AT91_EMAC_MPE); /* enable management port */
}
/*
* Disable the MDIO bit in the MAC control register
*/
static void disable_mdi(void)
{
unsigned long ctl;
ctl = at91_emac_read(AT91_EMAC_CTL);
at91_emac_write(AT91_EMAC_CTL, ctl & ~AT91_EMAC_MPE); /* disable management port */
}
/*
* Wait until the PHY operation is complete.
*/
static inline void at91_phy_wait(void) {
unsigned long timeout = jiffies + 2;
while (!(at91_emac_read(AT91_EMAC_SR) & AT91_EMAC_SR_IDLE)) {
if (time_after(jiffies, timeout)) {
printk("at91_ether: MIO timeout\n");
break;
}
cpu_relax();
}
}
/*
* Write value to the a PHY register
* Note: MDI interface is assumed to already have been enabled.
*/
static void write_phy(unsigned char phy_addr, unsigned char address, unsigned int value)
{
at91_emac_write(AT91_EMAC_MAN, AT91_EMAC_MAN_802_3 | AT91_EMAC_RW_W
| ((phy_addr & 0x1f) << 23) | (address << 18) | (value & AT91_EMAC_DATA));
/* Wait until IDLE bit in Network Status register is cleared */
at91_phy_wait();
}
/*
* Read value stored in a PHY register.
* Note: MDI interface is assumed to already have been enabled.
*/
static void read_phy(unsigned char phy_addr, unsigned char address, unsigned int *value)
{
at91_emac_write(AT91_EMAC_MAN, AT91_EMAC_MAN_802_3 | AT91_EMAC_RW_R
| ((phy_addr & 0x1f) << 23) | (address << 18));
/* Wait until IDLE bit in Network Status register is cleared */
at91_phy_wait();
*value = at91_emac_read(AT91_EMAC_MAN) & AT91_EMAC_DATA;
}
/* ........................... PHY MANAGEMENT .......................... */
/*
* Access the PHY to determine the current link speed and mode, and update the
* MAC accordingly.
* If no link or auto-negotiation is busy, then no changes are made.
*/
static void update_linkspeed(struct net_device *dev, int silent)
{
struct at91_private *lp = netdev_priv(dev);
unsigned int bmsr, bmcr, lpa, mac_cfg;
unsigned int speed, duplex;
if (!mii_link_ok(&lp->mii)) { /* no link */
netif_carrier_off(dev);
if (!silent)
printk(KERN_INFO "%s: Link down.\n", dev->name);
return;
}
/* Link up, or auto-negotiation still in progress */
read_phy(lp->phy_address, MII_BMSR, &bmsr);
read_phy(lp->phy_address, MII_BMCR, &bmcr);
if (bmcr & BMCR_ANENABLE) { /* AutoNegotiation is enabled */
if (!(bmsr & BMSR_ANEGCOMPLETE))
return; /* Do nothing - another interrupt generated when negotiation complete */
read_phy(lp->phy_address, MII_LPA, &lpa);
if ((lpa & LPA_100FULL) || (lpa & LPA_100HALF)) speed = SPEED_100;
else speed = SPEED_10;
if ((lpa & LPA_100FULL) || (lpa & LPA_10FULL)) duplex = DUPLEX_FULL;
else duplex = DUPLEX_HALF;
} else {
speed = (bmcr & BMCR_SPEED100) ? SPEED_100 : SPEED_10;
duplex = (bmcr & BMCR_FULLDPLX) ? DUPLEX_FULL : DUPLEX_HALF;
}
/* Update the MAC */
mac_cfg = at91_emac_read(AT91_EMAC_CFG) & ~(AT91_EMAC_SPD | AT91_EMAC_FD);
if (speed == SPEED_100) {
if (duplex == DUPLEX_FULL) /* 100 Full Duplex */
mac_cfg |= AT91_EMAC_SPD | AT91_EMAC_FD;
else /* 100 Half Duplex */
mac_cfg |= AT91_EMAC_SPD;
} else {
if (duplex == DUPLEX_FULL) /* 10 Full Duplex */
mac_cfg |= AT91_EMAC_FD;
else {} /* 10 Half Duplex */
}
at91_emac_write(AT91_EMAC_CFG, mac_cfg);
if (!silent)
printk(KERN_INFO "%s: Link now %i-%s\n", dev->name, speed, (duplex == DUPLEX_FULL) ? "FullDuplex" : "HalfDuplex");
netif_carrier_on(dev);
}
/*
* Handle interrupts from the PHY
*/
static irqreturn_t at91ether_phy_interrupt(int irq, void *dev_id)
{
struct net_device *dev = (struct net_device *) dev_id;
struct at91_private *lp = netdev_priv(dev);
unsigned int phy;
/*
* This hander is triggered on both edges, but the PHY chips expect
* level-triggering. We therefore have to check if the PHY actually has
* an IRQ pending.
*/
enable_mdi();
if ((lp->phy_type == MII_DM9161_ID) || (lp->phy_type == MII_DM9161A_ID)) {
read_phy(lp->phy_address, MII_DSINTR_REG, &phy); /* ack interrupt in Davicom PHY */
if (!(phy & (1 << 0)))
goto done;
}
else if (lp->phy_type == MII_LXT971A_ID) {
read_phy(lp->phy_address, MII_ISINTS_REG, &phy); /* ack interrupt in Intel PHY */
if (!(phy & (1 << 2)))
goto done;
}
else if (lp->phy_type == MII_BCM5221_ID) {
read_phy(lp->phy_address, MII_BCMINTR_REG, &phy); /* ack interrupt in Broadcom PHY */
if (!(phy & (1 << 0)))
goto done;
}
else if (lp->phy_type == MII_KS8721_ID) {
read_phy(lp->phy_address, MII_TPISTATUS, &phy); /* ack interrupt in Micrel PHY */
if (!(phy & ((1 << 2) | 1)))
goto done;
}
else if (lp->phy_type == MII_T78Q21x3_ID) { /* ack interrupt in Teridian PHY */
read_phy(lp->phy_address, MII_T78Q21INT_REG, &phy);
if (!(phy & ((1 << 2) | 1)))
goto done;
}
else if (lp->phy_type == MII_DP83848_ID) {
read_phy(lp->phy_address, MII_DPPHYSTS_REG, &phy); /* ack interrupt in DP83848 PHY */
if (!(phy & (1 << 7)))
goto done;
}
update_linkspeed(dev, 0);
done:
disable_mdi();
return IRQ_HANDLED;
}
/*
* Initialize and enable the PHY interrupt for link-state changes
*/
static void enable_phyirq(struct net_device *dev)
{
struct at91_private *lp = netdev_priv(dev);
unsigned int dsintr, irq_number;
int status;
irq_number = lp->board_data.phy_irq_pin;
if (!irq_number) {
/*
* PHY doesn't have an IRQ pin (RTL8201, DP83847, AC101L),
* or board does not have it connected.
*/
mod_timer(&lp->check_timer, jiffies + LINK_POLL_INTERVAL);
return;
}
status = request_irq(irq_number, at91ether_phy_interrupt, 0, dev->name, dev);
if (status) {
printk(KERN_ERR "at91_ether: PHY IRQ %d request failed - status %d!\n", irq_number, status);
return;
}
spin_lock_irq(&lp->lock);
enable_mdi();
if ((lp->phy_type == MII_DM9161_ID) || (lp->phy_type == MII_DM9161A_ID)) { /* for Davicom PHY */
read_phy(lp->phy_address, MII_DSINTR_REG, &dsintr);
dsintr = dsintr & ~0xf00; /* clear bits 8..11 */
write_phy(lp->phy_address, MII_DSINTR_REG, dsintr);
}
else if (lp->phy_type == MII_LXT971A_ID) { /* for Intel PHY */
read_phy(lp->phy_address, MII_ISINTE_REG, &dsintr);
dsintr = dsintr | 0xf2; /* set bits 1, 4..7 */
write_phy(lp->phy_address, MII_ISINTE_REG, dsintr);
}
else if (lp->phy_type == MII_BCM5221_ID) { /* for Broadcom PHY */
dsintr = (1 << 15) | ( 1 << 14);
write_phy(lp->phy_address, MII_BCMINTR_REG, dsintr);
}
else if (lp->phy_type == MII_KS8721_ID) { /* for Micrel PHY */
dsintr = (1 << 10) | ( 1 << 8);
write_phy(lp->phy_address, MII_TPISTATUS, dsintr);
}
else if (lp->phy_type == MII_T78Q21x3_ID) { /* for Teridian PHY */
read_phy(lp->phy_address, MII_T78Q21INT_REG, &dsintr);
dsintr = dsintr | 0x500; /* set bits 8, 10 */
write_phy(lp->phy_address, MII_T78Q21INT_REG, dsintr);
}
else if (lp->phy_type == MII_DP83848_ID) { /* National Semiconductor DP83848 PHY */
read_phy(lp->phy_address, MII_DPMISR_REG, &dsintr);
dsintr = dsintr | 0x3c; /* set bits 2..5 */
write_phy(lp->phy_address, MII_DPMISR_REG, dsintr);
read_phy(lp->phy_address, MII_DPMICR_REG, &dsintr);
dsintr = dsintr | 0x3; /* set bits 0,1 */
write_phy(lp->phy_address, MII_DPMICR_REG, dsintr);
}
disable_mdi();
spin_unlock_irq(&lp->lock);
}
/*
* Disable the PHY interrupt
*/
static void disable_phyirq(struct net_device *dev)
{
struct at91_private *lp = netdev_priv(dev);
unsigned int dsintr;
unsigned int irq_number;
irq_number = lp->board_data.phy_irq_pin;
if (!irq_number) {
del_timer_sync(&lp->check_timer);
return;
}
spin_lock_irq(&lp->lock);
enable_mdi();
if ((lp->phy_type == MII_DM9161_ID) || (lp->phy_type == MII_DM9161A_ID)) { /* for Davicom PHY */
read_phy(lp->phy_address, MII_DSINTR_REG, &dsintr);
dsintr = dsintr | 0xf00; /* set bits 8..11 */
write_phy(lp->phy_address, MII_DSINTR_REG, dsintr);
}
else if (lp->phy_type == MII_LXT971A_ID) { /* for Intel PHY */
read_phy(lp->phy_address, MII_ISINTE_REG, &dsintr);
dsintr = dsintr & ~0xf2; /* clear bits 1, 4..7 */
write_phy(lp->phy_address, MII_ISINTE_REG, dsintr);
}
else if (lp->phy_type == MII_BCM5221_ID) { /* for Broadcom PHY */
read_phy(lp->phy_address, MII_BCMINTR_REG, &dsintr);
dsintr = ~(1 << 14);
write_phy(lp->phy_address, MII_BCMINTR_REG, dsintr);
}
else if (lp->phy_type == MII_KS8721_ID) { /* for Micrel PHY */
read_phy(lp->phy_address, MII_TPISTATUS, &dsintr);
dsintr = ~((1 << 10) | (1 << 8));
write_phy(lp->phy_address, MII_TPISTATUS, dsintr);
}
else if (lp->phy_type == MII_T78Q21x3_ID) { /* for Teridian PHY */
read_phy(lp->phy_address, MII_T78Q21INT_REG, &dsintr);
dsintr = dsintr & ~0x500; /* clear bits 8, 10 */
write_phy(lp->phy_address, MII_T78Q21INT_REG, dsintr);
}
else if (lp->phy_type == MII_DP83848_ID) { /* National Semiconductor DP83848 PHY */
read_phy(lp->phy_address, MII_DPMICR_REG, &dsintr);
dsintr = dsintr & ~0x3; /* clear bits 0, 1 */
write_phy(lp->phy_address, MII_DPMICR_REG, dsintr);
read_phy(lp->phy_address, MII_DPMISR_REG, &dsintr);
dsintr = dsintr & ~0x3c; /* clear bits 2..5 */
write_phy(lp->phy_address, MII_DPMISR_REG, dsintr);
}
disable_mdi();
spin_unlock_irq(&lp->lock);
free_irq(irq_number, dev); /* Free interrupt handler */
}
/*
* Perform a software reset of the PHY.
*/
#if 0
static void reset_phy(struct net_device *dev)
{
struct at91_private *lp = netdev_priv(dev);
unsigned int bmcr;
spin_lock_irq(&lp->lock);
enable_mdi();
/* Perform PHY reset */
write_phy(lp->phy_address, MII_BMCR, BMCR_RESET);
/* Wait until PHY reset is complete */
do {
read_phy(lp->phy_address, MII_BMCR, &bmcr);
} while (!(bmcr & BMCR_RESET));
disable_mdi();
spin_unlock_irq(&lp->lock);
}
#endif
static void at91ether_check_link(unsigned long dev_id)
{
struct net_device *dev = (struct net_device *) dev_id;
struct at91_private *lp = netdev_priv(dev);
enable_mdi();
update_linkspeed(dev, 1);
disable_mdi();
mod_timer(&lp->check_timer, jiffies + LINK_POLL_INTERVAL);
}
/* ......................... ADDRESS MANAGEMENT ........................ */
/*
* NOTE: Your bootloader must always set the MAC address correctly before
* booting into Linux.
*
* - It must always set the MAC address after reset, even if it doesn't
* happen to access the Ethernet while it's booting. Some versions of
* U-Boot on the AT91RM9200-DK do not do this.
*
* - Likewise it must store the addresses in the correct byte order.
* MicroMonitor (uMon) on the CSB337 does this incorrectly (and
* continues to do so, for bug-compatibility).
*/
static short __init unpack_mac_address(struct net_device *dev, unsigned int hi, unsigned int lo)
{
char addr[6];
if (machine_is_csb337()) {
addr[5] = (lo & 0xff); /* The CSB337 bootloader stores the MAC the wrong-way around */
addr[4] = (lo & 0xff00) >> 8;
addr[3] = (lo & 0xff0000) >> 16;
addr[2] = (lo & 0xff000000) >> 24;
addr[1] = (hi & 0xff);
addr[0] = (hi & 0xff00) >> 8;
}
else {
addr[0] = (lo & 0xff);
addr[1] = (lo & 0xff00) >> 8;
addr[2] = (lo & 0xff0000) >> 16;
addr[3] = (lo & 0xff000000) >> 24;
addr[4] = (hi & 0xff);
addr[5] = (hi & 0xff00) >> 8;
}
if (is_valid_ether_addr(addr)) {
memcpy(dev->dev_addr, &addr, 6);
return 1;
}
return 0;
}
/*
* Set the ethernet MAC address in dev->dev_addr
*/
static void __init get_mac_address(struct net_device *dev)
{
/* Check Specific-Address 1 */
if (unpack_mac_address(dev, at91_emac_read(AT91_EMAC_SA1H), at91_emac_read(AT91_EMAC_SA1L)))
return;
/* Check Specific-Address 2 */
if (unpack_mac_address(dev, at91_emac_read(AT91_EMAC_SA2H), at91_emac_read(AT91_EMAC_SA2L)))
return;
/* Check Specific-Address 3 */
if (unpack_mac_address(dev, at91_emac_read(AT91_EMAC_SA3H), at91_emac_read(AT91_EMAC_SA3L)))
return;
/* Check Specific-Address 4 */
if (unpack_mac_address(dev, at91_emac_read(AT91_EMAC_SA4H), at91_emac_read(AT91_EMAC_SA4L)))
return;
printk(KERN_ERR "at91_ether: Your bootloader did not configure a MAC address.\n");
}
/*
* Program the hardware MAC address from dev->dev_addr.
*/
static void update_mac_address(struct net_device *dev)
{
at91_emac_write(AT91_EMAC_SA1L, (dev->dev_addr[3] << 24) | (dev->dev_addr[2] << 16) | (dev->dev_addr[1] << 8) | (dev->dev_addr[0]));
at91_emac_write(AT91_EMAC_SA1H, (dev->dev_addr[5] << 8) | (dev->dev_addr[4]));
at91_emac_write(AT91_EMAC_SA2L, 0);
at91_emac_write(AT91_EMAC_SA2H, 0);
}
/*
* Store the new hardware address in dev->dev_addr, and update the MAC.
*/
static int set_mac_address(struct net_device *dev, void* addr)
{
struct sockaddr *address = addr;
if (!is_valid_ether_addr(address->sa_data))
return -EADDRNOTAVAIL;
memcpy(dev->dev_addr, address->sa_data, dev->addr_len);
update_mac_address(dev);
printk("%s: Setting MAC address to %pM\n", dev->name,
dev->dev_addr);
return 0;
}
static int inline hash_bit_value(int bitnr, __u8 *addr)
{
if (addr[bitnr / 8] & (1 << (bitnr % 8)))
return 1;
return 0;
}
/*
* The hash address register is 64 bits long and takes up two locations in the memory map.
* The least significant bits are stored in EMAC_HSL and the most significant
* bits in EMAC_HSH.
*
* The unicast hash enable and the multicast hash enable bits in the network configuration
* register enable the reception of hash matched frames. The destination address is
* reduced to a 6 bit index into the 64 bit hash register using the following hash function.
* The hash function is an exclusive or of every sixth bit of the destination address.
* hash_index[5] = da[5] ^ da[11] ^ da[17] ^ da[23] ^ da[29] ^ da[35] ^ da[41] ^ da[47]
* hash_index[4] = da[4] ^ da[10] ^ da[16] ^ da[22] ^ da[28] ^ da[34] ^ da[40] ^ da[46]
* hash_index[3] = da[3] ^ da[09] ^ da[15] ^ da[21] ^ da[27] ^ da[33] ^ da[39] ^ da[45]
* hash_index[2] = da[2] ^ da[08] ^ da[14] ^ da[20] ^ da[26] ^ da[32] ^ da[38] ^ da[44]
* hash_index[1] = da[1] ^ da[07] ^ da[13] ^ da[19] ^ da[25] ^ da[31] ^ da[37] ^ da[43]
* hash_index[0] = da[0] ^ da[06] ^ da[12] ^ da[18] ^ da[24] ^ da[30] ^ da[36] ^ da[42]
* da[0] represents the least significant bit of the first byte received, that is, the multicast/
* unicast indicator, and da[47] represents the most significant bit of the last byte
* received.
* If the hash index points to a bit that is set in the hash register then the frame will be
* matched according to whether the frame is multicast or unicast.
* A multicast match will be signalled if the multicast hash enable bit is set, da[0] is 1 and
* the hash index points to a bit set in the hash register.
* A unicast match will be signalled if the unicast hash enable bit is set, da[0] is 0 and the
* hash index points to a bit set in the hash register.
* To receive all multicast frames, the hash register should be set with all ones and the
* multicast hash enable bit should be set in the network configuration register.
*/
/*
* Return the hash index value for the specified address.
*/
static int hash_get_index(__u8 *addr)
{
int i, j, bitval;
int hash_index = 0;
for (j = 0; j < 6; j++) {
for (i = 0, bitval = 0; i < 8; i++)
bitval ^= hash_bit_value(i*6 + j, addr);
hash_index |= (bitval << j);
}
return hash_index;
}
/*
* Add multicast addresses to the internal multicast-hash table.
*/
static void at91ether_sethashtable(struct net_device *dev)
{
struct netdev_hw_addr *ha;
unsigned long mc_filter[2];
unsigned int bitnr;
mc_filter[0] = mc_filter[1] = 0;
netdev_for_each_mc_addr(ha, dev) {
bitnr = hash_get_index(ha->addr);
mc_filter[bitnr >> 5] |= 1 << (bitnr & 31);
}
at91_emac_write(AT91_EMAC_HSL, mc_filter[0]);
at91_emac_write(AT91_EMAC_HSH, mc_filter[1]);
}
/*
* Enable/Disable promiscuous and multicast modes.
*/
static void at91ether_set_multicast_list(struct net_device *dev)
{
unsigned long cfg;
cfg = at91_emac_read(AT91_EMAC_CFG);
if (dev->flags & IFF_PROMISC) /* Enable promiscuous mode */
cfg |= AT91_EMAC_CAF;
else if (dev->flags & (~IFF_PROMISC)) /* Disable promiscuous mode */
cfg &= ~AT91_EMAC_CAF;
if (dev->flags & IFF_ALLMULTI) { /* Enable all multicast mode */
at91_emac_write(AT91_EMAC_HSH, -1);
at91_emac_write(AT91_EMAC_HSL, -1);
cfg |= AT91_EMAC_MTI;
} else if (!netdev_mc_empty(dev)) { /* Enable specific multicasts */
at91ether_sethashtable(dev);
cfg |= AT91_EMAC_MTI;
} else if (dev->flags & (~IFF_ALLMULTI)) { /* Disable all multicast mode */
at91_emac_write(AT91_EMAC_HSH, 0);
at91_emac_write(AT91_EMAC_HSL, 0);
cfg &= ~AT91_EMAC_MTI;
}
at91_emac_write(AT91_EMAC_CFG, cfg);
}
/* ......................... ETHTOOL SUPPORT ........................... */
static int mdio_read(struct net_device *dev, int phy_id, int location)
{
unsigned int value;
read_phy(phy_id, location, &value);
return value;
}
static void mdio_write(struct net_device *dev, int phy_id, int location, int value)
{
write_phy(phy_id, location, value);
}
static int at91ether_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct at91_private *lp = netdev_priv(dev);
int ret;
spin_lock_irq(&lp->lock);
enable_mdi();
ret = mii_ethtool_gset(&lp->mii, cmd);
disable_mdi();
spin_unlock_irq(&lp->lock);
if (lp->phy_media == PORT_FIBRE) { /* override media type since mii.c doesn't know */
cmd->supported = SUPPORTED_FIBRE;
cmd->port = PORT_FIBRE;
}
return ret;
}
static int at91ether_set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct at91_private *lp = netdev_priv(dev);
int ret;
spin_lock_irq(&lp->lock);
enable_mdi();
ret = mii_ethtool_sset(&lp->mii, cmd);
disable_mdi();
spin_unlock_irq(&lp->lock);
return ret;
}
static int at91ether_nwayreset(struct net_device *dev)
{
struct at91_private *lp = netdev_priv(dev);
int ret;
spin_lock_irq(&lp->lock);
enable_mdi();
ret = mii_nway_restart(&lp->mii);
disable_mdi();
spin_unlock_irq(&lp->lock);
return ret;
}
static void at91ether_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
strlcpy(info->version, DRV_VERSION, sizeof(info->version));
strlcpy(info->bus_info, dev_name(dev->dev.parent), sizeof(info->bus_info));
}
static const struct ethtool_ops at91ether_ethtool_ops = {
.get_settings = at91ether_get_settings,
.set_settings = at91ether_set_settings,
.get_drvinfo = at91ether_get_drvinfo,
.nway_reset = at91ether_nwayreset,
.get_link = ethtool_op_get_link,
};
static int at91ether_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
{
struct at91_private *lp = netdev_priv(dev);
int res;
if (!netif_running(dev))
return -EINVAL;
spin_lock_irq(&lp->lock);
enable_mdi();
res = generic_mii_ioctl(&lp->mii, if_mii(rq), cmd, NULL);
disable_mdi();
spin_unlock_irq(&lp->lock);
return res;
}
/* ................................ MAC ................................ */
/*
* Initialize and start the Receiver and Transmit subsystems
*/
static void at91ether_start(struct net_device *dev)
{
struct at91_private *lp = netdev_priv(dev);
struct recv_desc_bufs *dlist, *dlist_phys;
int i;
unsigned long ctl;
dlist = lp->dlist;
dlist_phys = lp->dlist_phys;
for (i = 0; i < MAX_RX_DESCR; i++) {
dlist->descriptors[i].addr = (unsigned int) &dlist_phys->recv_buf[i][0];
dlist->descriptors[i].size = 0;
}
/* Set the Wrap bit on the last descriptor */
dlist->descriptors[i-1].addr |= EMAC_DESC_WRAP;
/* Reset buffer index */
lp->rxBuffIndex = 0;
/* Program address of descriptor list in Rx Buffer Queue register */
at91_emac_write(AT91_EMAC_RBQP, (unsigned long) dlist_phys);
/* Enable Receive and Transmit */
ctl = at91_emac_read(AT91_EMAC_CTL);
at91_emac_write(AT91_EMAC_CTL, ctl | AT91_EMAC_RE | AT91_EMAC_TE);
}
/*
* Open the ethernet interface
*/
static int at91ether_open(struct net_device *dev)
{
struct at91_private *lp = netdev_priv(dev);
unsigned long ctl;
if (!is_valid_ether_addr(dev->dev_addr))
return -EADDRNOTAVAIL;
clk_enable(lp->ether_clk); /* Re-enable Peripheral clock */
/* Clear internal statistics */
ctl = at91_emac_read(AT91_EMAC_CTL);
at91_emac_write(AT91_EMAC_CTL, ctl | AT91_EMAC_CSR);
/* Update the MAC address (incase user has changed it) */
update_mac_address(dev);
/* Enable PHY interrupt */
enable_phyirq(dev);
/* Enable MAC interrupts */
at91_emac_write(AT91_EMAC_IER, AT91_EMAC_RCOM | AT91_EMAC_RBNA
| AT91_EMAC_TUND | AT91_EMAC_RTRY | AT91_EMAC_TCOM
| AT91_EMAC_ROVR | AT91_EMAC_ABT);
/* Determine current link speed */
spin_lock_irq(&lp->lock);
enable_mdi();
update_linkspeed(dev, 0);
disable_mdi();
spin_unlock_irq(&lp->lock);
at91ether_start(dev);
netif_start_queue(dev);
return 0;
}
/*
* Close the interface
*/
static int at91ether_close(struct net_device *dev)
{
struct at91_private *lp = netdev_priv(dev);
unsigned long ctl;
/* Disable Receiver and Transmitter */
ctl = at91_emac_read(AT91_EMAC_CTL);
at91_emac_write(AT91_EMAC_CTL, ctl & ~(AT91_EMAC_TE | AT91_EMAC_RE));
/* Disable PHY interrupt */
disable_phyirq(dev);
/* Disable MAC interrupts */
at91_emac_write(AT91_EMAC_IDR, AT91_EMAC_RCOM | AT91_EMAC_RBNA
| AT91_EMAC_TUND | AT91_EMAC_RTRY | AT91_EMAC_TCOM
| AT91_EMAC_ROVR | AT91_EMAC_ABT);
netif_stop_queue(dev);
clk_disable(lp->ether_clk); /* Disable Peripheral clock */
return 0;
}
/*
* Transmit packet.
*/
static int at91ether_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct at91_private *lp = netdev_priv(dev);
if (at91_emac_read(AT91_EMAC_TSR) & AT91_EMAC_TSR_BNQ) {
netif_stop_queue(dev);
/* Store packet information (to free when Tx completed) */
lp->skb = skb;
lp->skb_length = skb->len;
lp->skb_physaddr = dma_map_single(NULL, skb->data, skb->len, DMA_TO_DEVICE);
dev->stats.tx_bytes += skb->len;
/* Set address of the data in the Transmit Address register */
at91_emac_write(AT91_EMAC_TAR, lp->skb_physaddr);
/* Set length of the packet in the Transmit Control register */
at91_emac_write(AT91_EMAC_TCR, skb->len);
} else {
printk(KERN_ERR "at91_ether.c: at91ether_start_xmit() called, but device is busy!\n");
return NETDEV_TX_BUSY; /* if we return anything but zero, dev.c:1055 calls kfree_skb(skb)
on this skb, he also reports -ENETDOWN and printk's, so either
we free and return(0) or don't free and return 1 */
}
return NETDEV_TX_OK;
}
/*
* Update the current statistics from the internal statistics registers.
*/
static struct net_device_stats *at91ether_stats(struct net_device *dev)
{
int ale, lenerr, seqe, lcol, ecol;
if (netif_running(dev)) {
dev->stats.rx_packets += at91_emac_read(AT91_EMAC_OK); /* Good frames received */
ale = at91_emac_read(AT91_EMAC_ALE);
dev->stats.rx_frame_errors += ale; /* Alignment errors */
lenerr = at91_emac_read(AT91_EMAC_ELR) + at91_emac_read(AT91_EMAC_USF);
dev->stats.rx_length_errors += lenerr; /* Excessive Length or Undersize Frame error */
seqe = at91_emac_read(AT91_EMAC_SEQE);
dev->stats.rx_crc_errors += seqe; /* CRC error */
dev->stats.rx_fifo_errors += at91_emac_read(AT91_EMAC_DRFC); /* Receive buffer not available */
dev->stats.rx_errors += (ale + lenerr + seqe
+ at91_emac_read(AT91_EMAC_CDE) + at91_emac_read(AT91_EMAC_RJB));
dev->stats.tx_packets += at91_emac_read(AT91_EMAC_FRA); /* Frames successfully transmitted */
dev->stats.tx_fifo_errors += at91_emac_read(AT91_EMAC_TUE); /* Transmit FIFO underruns */
dev->stats.tx_carrier_errors += at91_emac_read(AT91_EMAC_CSE); /* Carrier Sense errors */
dev->stats.tx_heartbeat_errors += at91_emac_read(AT91_EMAC_SQEE);/* Heartbeat error */
lcol = at91_emac_read(AT91_EMAC_LCOL);
ecol = at91_emac_read(AT91_EMAC_ECOL);
dev->stats.tx_window_errors += lcol; /* Late collisions */
dev->stats.tx_aborted_errors += ecol; /* 16 collisions */
dev->stats.collisions += (at91_emac_read(AT91_EMAC_SCOL) + at91_emac_read(AT91_EMAC_MCOL) + lcol + ecol);
}
return &dev->stats;
}
/*
* Extract received frame from buffer descriptors and sent to upper layers.
* (Called from interrupt context)
*/
static void at91ether_rx(struct net_device *dev)
{
struct at91_private *lp = netdev_priv(dev);
struct recv_desc_bufs *dlist;
unsigned char *p_recv;
struct sk_buff *skb;
unsigned int pktlen;
dlist = lp->dlist;
while (dlist->descriptors[lp->rxBuffIndex].addr & EMAC_DESC_DONE) {
p_recv = dlist->recv_buf[lp->rxBuffIndex];
pktlen = dlist->descriptors[lp->rxBuffIndex].size & 0x7ff; /* Length of frame including FCS */
skb = dev_alloc_skb(pktlen + 2);
if (skb != NULL) {
skb_reserve(skb, 2);
memcpy(skb_put(skb, pktlen), p_recv, pktlen);
skb->protocol = eth_type_trans(skb, dev);
dev->stats.rx_bytes += pktlen;
netif_rx(skb);
}
else {
dev->stats.rx_dropped += 1;
printk(KERN_NOTICE "%s: Memory squeeze, dropping packet.\n", dev->name);
}
if (dlist->descriptors[lp->rxBuffIndex].size & EMAC_MULTICAST)
dev->stats.multicast++;
dlist->descriptors[lp->rxBuffIndex].addr &= ~EMAC_DESC_DONE; /* reset ownership bit */
if (lp->rxBuffIndex == MAX_RX_DESCR-1) /* wrap after last buffer */
lp->rxBuffIndex = 0;
else
lp->rxBuffIndex++;
}
}
/*
* MAC interrupt handler
*/
static irqreturn_t at91ether_interrupt(int irq, void *dev_id)
{
struct net_device *dev = (struct net_device *) dev_id;
struct at91_private *lp = netdev_priv(dev);
unsigned long intstatus, ctl;
/* MAC Interrupt Status register indicates what interrupts are pending.
It is automatically cleared once read. */
intstatus = at91_emac_read(AT91_EMAC_ISR);
if (intstatus & AT91_EMAC_RCOM) /* Receive complete */
at91ether_rx(dev);
if (intstatus & AT91_EMAC_TCOM) { /* Transmit complete */
/* The TCOM bit is set even if the transmission failed. */
if (intstatus & (AT91_EMAC_TUND | AT91_EMAC_RTRY))
dev->stats.tx_errors += 1;
if (lp->skb) {
dev_kfree_skb_irq(lp->skb);
lp->skb = NULL;
dma_unmap_single(NULL, lp->skb_physaddr, lp->skb_length, DMA_TO_DEVICE);
}
netif_wake_queue(dev);
}
/* Work-around for Errata #11 */
if (intstatus & AT91_EMAC_RBNA) {
ctl = at91_emac_read(AT91_EMAC_CTL);
at91_emac_write(AT91_EMAC_CTL, ctl & ~AT91_EMAC_RE);
at91_emac_write(AT91_EMAC_CTL, ctl | AT91_EMAC_RE);
}
if (intstatus & AT91_EMAC_ROVR)
printk("%s: ROVR error\n", dev->name);
return IRQ_HANDLED;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void at91ether_poll_controller(struct net_device *dev)
{
unsigned long flags;
local_irq_save(flags);
at91ether_interrupt(dev->irq, dev);
local_irq_restore(flags);
}
#endif
static const struct net_device_ops at91ether_netdev_ops = {
.ndo_open = at91ether_open,
.ndo_stop = at91ether_close,
.ndo_start_xmit = at91ether_start_xmit,
.ndo_get_stats = at91ether_stats,
.ndo_set_multicast_list = at91ether_set_multicast_list,
.ndo_set_mac_address = set_mac_address,
.ndo_do_ioctl = at91ether_ioctl,
.ndo_validate_addr = eth_validate_addr,
.ndo_change_mtu = eth_change_mtu,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = at91ether_poll_controller,
#endif
};
/*
* Initialize the ethernet interface
*/
static int __init at91ether_setup(unsigned long phy_type, unsigned short phy_address,
struct platform_device *pdev, struct clk *ether_clk)
{
struct at91_eth_data *board_data = pdev->dev.platform_data;
struct net_device *dev;
struct at91_private *lp;
unsigned int val;
int res;
dev = alloc_etherdev(sizeof(struct at91_private));
if (!dev)
return -ENOMEM;
dev->base_addr = AT91_VA_BASE_EMAC;
dev->irq = AT91RM9200_ID_EMAC;
/* Install the interrupt handler */
if (request_irq(dev->irq, at91ether_interrupt, 0, dev->name, dev)) {
free_netdev(dev);
return -EBUSY;
}
/* Allocate memory for DMA Receive descriptors */
lp = netdev_priv(dev);
lp->dlist = (struct recv_desc_bufs *) dma_alloc_coherent(NULL, sizeof(struct recv_desc_bufs), (dma_addr_t *) &lp->dlist_phys, GFP_KERNEL);
if (lp->dlist == NULL) {
free_irq(dev->irq, dev);
free_netdev(dev);
return -ENOMEM;
}
lp->board_data = *board_data;
lp->ether_clk = ether_clk;
platform_set_drvdata(pdev, dev);
spin_lock_init(&lp->lock);
ether_setup(dev);
dev->netdev_ops = &at91ether_netdev_ops;
dev->ethtool_ops = &at91ether_ethtool_ops;
SET_NETDEV_DEV(dev, &pdev->dev);
get_mac_address(dev); /* Get ethernet address and store it in dev->dev_addr */
update_mac_address(dev); /* Program ethernet address into MAC */
at91_emac_write(AT91_EMAC_CTL, 0);
if (lp->board_data.is_rmii)
at91_emac_write(AT91_EMAC_CFG, AT91_EMAC_CLK_DIV32 | AT91_EMAC_BIG | AT91_EMAC_RMII);
else
at91_emac_write(AT91_EMAC_CFG, AT91_EMAC_CLK_DIV32 | AT91_EMAC_BIG);
/* Perform PHY-specific initialization */
spin_lock_irq(&lp->lock);
enable_mdi();
if ((phy_type == MII_DM9161_ID) || (lp->phy_type == MII_DM9161A_ID)) {
read_phy(phy_address, MII_DSCR_REG, &val);
if ((val & (1 << 10)) == 0) /* DSCR bit 10 is 0 -- fiber mode */
lp->phy_media = PORT_FIBRE;
} else if (machine_is_csb337()) {
/* mix link activity status into LED2 link state */
write_phy(phy_address, MII_LEDCTRL_REG, 0x0d22);
} else if (machine_is_ecbat91())
write_phy(phy_address, MII_LEDCTRL_REG, 0x156A);
disable_mdi();
spin_unlock_irq(&lp->lock);
lp->mii.dev = dev; /* Support for ethtool */
lp->mii.mdio_read = mdio_read;
lp->mii.mdio_write = mdio_write;
lp->mii.phy_id = phy_address;
lp->mii.phy_id_mask = 0x1f;
lp->mii.reg_num_mask = 0x1f;
lp->phy_type = phy_type; /* Type of PHY connected */
lp->phy_address = phy_address; /* MDI address of PHY */
/* Register the network interface */
res = register_netdev(dev);
if (res) {
free_irq(dev->irq, dev);
free_netdev(dev);
dma_free_coherent(NULL, sizeof(struct recv_desc_bufs), lp->dlist, (dma_addr_t)lp->dlist_phys);
return res;
}
/* Determine current link speed */
spin_lock_irq(&lp->lock);
enable_mdi();
update_linkspeed(dev, 0);
disable_mdi();
spin_unlock_irq(&lp->lock);
netif_carrier_off(dev); /* will be enabled in open() */
/* If board has no PHY IRQ, use a timer to poll the PHY */
if (!lp->board_data.phy_irq_pin) {
init_timer(&lp->check_timer);
lp->check_timer.data = (unsigned long)dev;
lp->check_timer.function = at91ether_check_link;
} else if (lp->board_data.phy_irq_pin >= 32)
gpio_request(lp->board_data.phy_irq_pin, "ethernet_phy");
/* Display ethernet banner */
printk(KERN_INFO "%s: AT91 ethernet at 0x%08x int=%d %s%s (%pM)\n",
dev->name, (uint) dev->base_addr, dev->irq,
at91_emac_read(AT91_EMAC_CFG) & AT91_EMAC_SPD ? "100-" : "10-",
at91_emac_read(AT91_EMAC_CFG) & AT91_EMAC_FD ? "FullDuplex" : "HalfDuplex",
dev->dev_addr);
if ((phy_type == MII_DM9161_ID) || (lp->phy_type == MII_DM9161A_ID))
printk(KERN_INFO "%s: Davicom 9161 PHY %s\n", dev->name, (lp->phy_media == PORT_FIBRE) ? "(Fiber)" : "(Copper)");
else if (phy_type == MII_LXT971A_ID)
printk(KERN_INFO "%s: Intel LXT971A PHY\n", dev->name);
else if (phy_type == MII_RTL8201_ID)
printk(KERN_INFO "%s: Realtek RTL8201(B)L PHY\n", dev->name);
else if (phy_type == MII_BCM5221_ID)
printk(KERN_INFO "%s: Broadcom BCM5221 PHY\n", dev->name);
else if (phy_type == MII_DP83847_ID)
printk(KERN_INFO "%s: National Semiconductor DP83847 PHY\n", dev->name);
else if (phy_type == MII_DP83848_ID)
printk(KERN_INFO "%s: National Semiconductor DP83848 PHY\n", dev->name);
else if (phy_type == MII_AC101L_ID)
printk(KERN_INFO "%s: Altima AC101L PHY\n", dev->name);
else if (phy_type == MII_KS8721_ID)
printk(KERN_INFO "%s: Micrel KS8721 PHY\n", dev->name);
else if (phy_type == MII_T78Q21x3_ID)
printk(KERN_INFO "%s: Teridian 78Q21x3 PHY\n", dev->name);
else if (phy_type == MII_LAN83C185_ID)
printk(KERN_INFO "%s: SMSC LAN83C185 PHY\n", dev->name);
return 0;
}
/*
* Detect MAC and PHY and perform initialization
*/
static int __init at91ether_probe(struct platform_device *pdev)
{
unsigned int phyid1, phyid2;
int detected = -1;
unsigned long phy_id;
unsigned short phy_address = 0;
struct clk *ether_clk;
ether_clk = clk_get(&pdev->dev, "ether_clk");
if (IS_ERR(ether_clk)) {
printk(KERN_ERR "at91_ether: no clock defined\n");
return -ENODEV;
}
clk_enable(ether_clk); /* Enable Peripheral clock */
while ((detected != 0) && (phy_address < 32)) {
/* Read the PHY ID registers */
enable_mdi();
read_phy(phy_address, MII_PHYSID1, &phyid1);
read_phy(phy_address, MII_PHYSID2, &phyid2);
disable_mdi();
phy_id = (phyid1 << 16) | (phyid2 & 0xfff0);
switch (phy_id) {
case MII_DM9161_ID: /* Davicom 9161: PHY_ID1 = 0x181, PHY_ID2 = B881 */
case MII_DM9161A_ID: /* Davicom 9161A: PHY_ID1 = 0x181, PHY_ID2 = B8A0 */
case MII_LXT971A_ID: /* Intel LXT971A: PHY_ID1 = 0x13, PHY_ID2 = 78E0 */
case MII_RTL8201_ID: /* Realtek RTL8201: PHY_ID1 = 0, PHY_ID2 = 0x8201 */
case MII_BCM5221_ID: /* Broadcom BCM5221: PHY_ID1 = 0x40, PHY_ID2 = 0x61e0 */
case MII_DP83847_ID: /* National Semiconductor DP83847: */
case MII_DP83848_ID: /* National Semiconductor DP83848: */
case MII_AC101L_ID: /* Altima AC101L: PHY_ID1 = 0x22, PHY_ID2 = 0x5520 */
case MII_KS8721_ID: /* Micrel KS8721: PHY_ID1 = 0x22, PHY_ID2 = 0x1610 */
case MII_T78Q21x3_ID: /* Teridian 78Q21x3: PHY_ID1 = 0x0E, PHY_ID2 = 7237 */
case MII_LAN83C185_ID: /* SMSC LAN83C185: PHY_ID1 = 0x0007, PHY_ID2 = 0xC0A1 */
detected = at91ether_setup(phy_id, phy_address, pdev, ether_clk);
break;
}
phy_address++;
}
clk_disable(ether_clk); /* Disable Peripheral clock */
return detected;
}
static int __devexit at91ether_remove(struct platform_device *pdev)
{
struct net_device *dev = platform_get_drvdata(pdev);
struct at91_private *lp = netdev_priv(dev);
if (lp->board_data.phy_irq_pin >= 32)
gpio_free(lp->board_data.phy_irq_pin);
unregister_netdev(dev);
free_irq(dev->irq, dev);
dma_free_coherent(NULL, sizeof(struct recv_desc_bufs), lp->dlist, (dma_addr_t)lp->dlist_phys);
clk_put(lp->ether_clk);
platform_set_drvdata(pdev, NULL);
free_netdev(dev);
return 0;
}
#ifdef CONFIG_PM
static int at91ether_suspend(struct platform_device *pdev, pm_message_t mesg)
{
struct net_device *net_dev = platform_get_drvdata(pdev);
struct at91_private *lp = netdev_priv(net_dev);
int phy_irq = lp->board_data.phy_irq_pin;
if (netif_running(net_dev)) {
if (phy_irq)
disable_irq(phy_irq);
netif_stop_queue(net_dev);
netif_device_detach(net_dev);
clk_disable(lp->ether_clk);
}
return 0;
}
static int at91ether_resume(struct platform_device *pdev)
{
struct net_device *net_dev = platform_get_drvdata(pdev);
struct at91_private *lp = netdev_priv(net_dev);
int phy_irq = lp->board_data.phy_irq_pin;
if (netif_running(net_dev)) {
clk_enable(lp->ether_clk);
netif_device_attach(net_dev);
netif_start_queue(net_dev);
if (phy_irq)
enable_irq(phy_irq);
}
return 0;
}
#else
#define at91ether_suspend NULL
#define at91ether_resume NULL
#endif
static struct platform_driver at91ether_driver = {
.remove = __devexit_p(at91ether_remove),
.suspend = at91ether_suspend,
.resume = at91ether_resume,
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
},
};
static int __init at91ether_init(void)
{
return platform_driver_probe(&at91ether_driver, at91ether_probe);
}
static void __exit at91ether_exit(void)
{
platform_driver_unregister(&at91ether_driver);
}
module_init(at91ether_init)
module_exit(at91ether_exit)
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("AT91RM9200 EMAC Ethernet driver");
MODULE_AUTHOR("Andrew Victor");
MODULE_ALIAS("platform:" DRV_NAME);
| gpl-2.0 |
emceethemouth/kernel_flo | sound/soc/codecs/sigmadsp.c | 3536 | 5298 | /*
* Load Analog Devices SigmaStudio firmware files
*
* Copyright 2009-2011 Analog Devices Inc.
*
* Licensed under the GPL-2 or later.
*/
#include <linux/crc32.h>
#include <linux/delay.h>
#include <linux/firmware.h>
#include <linux/kernel.h>
#include <linux/i2c.h>
#include <linux/regmap.h>
#include <linux/module.h>
#include "sigmadsp.h"
#define SIGMA_MAGIC "ADISIGM"
struct sigma_firmware_header {
unsigned char magic[7];
u8 version;
__le32 crc;
} __packed;
enum {
SIGMA_ACTION_WRITEXBYTES = 0,
SIGMA_ACTION_WRITESINGLE,
SIGMA_ACTION_WRITESAFELOAD,
SIGMA_ACTION_DELAY,
SIGMA_ACTION_PLLWAIT,
SIGMA_ACTION_NOOP,
SIGMA_ACTION_END,
};
struct sigma_action {
u8 instr;
u8 len_hi;
__le16 len;
__be16 addr;
unsigned char payload[];
} __packed;
struct sigma_firmware {
const struct firmware *fw;
size_t pos;
void *control_data;
int (*write)(void *control_data, const struct sigma_action *sa,
size_t len);
};
static inline u32 sigma_action_len(struct sigma_action *sa)
{
return (sa->len_hi << 16) | le16_to_cpu(sa->len);
}
static size_t sigma_action_size(struct sigma_action *sa)
{
size_t payload = 0;
switch (sa->instr) {
case SIGMA_ACTION_WRITEXBYTES:
case SIGMA_ACTION_WRITESINGLE:
case SIGMA_ACTION_WRITESAFELOAD:
payload = sigma_action_len(sa);
break;
default:
break;
}
payload = ALIGN(payload, 2);
return payload + sizeof(struct sigma_action);
}
/*
* Returns a negative error value in case of an error, 0 if processing of
* the firmware should be stopped after this action, 1 otherwise.
*/
static int
process_sigma_action(struct sigma_firmware *ssfw, struct sigma_action *sa)
{
size_t len = sigma_action_len(sa);
int ret;
pr_debug("%s: instr:%i addr:%#x len:%zu\n", __func__,
sa->instr, sa->addr, len);
switch (sa->instr) {
case SIGMA_ACTION_WRITEXBYTES:
case SIGMA_ACTION_WRITESINGLE:
case SIGMA_ACTION_WRITESAFELOAD:
ret = ssfw->write(ssfw->control_data, sa, len);
if (ret < 0)
return -EINVAL;
break;
case SIGMA_ACTION_DELAY:
udelay(len);
len = 0;
break;
case SIGMA_ACTION_END:
return 0;
default:
return -EINVAL;
}
return 1;
}
static int
process_sigma_actions(struct sigma_firmware *ssfw)
{
struct sigma_action *sa;
size_t size;
int ret;
while (ssfw->pos + sizeof(*sa) <= ssfw->fw->size) {
sa = (struct sigma_action *)(ssfw->fw->data + ssfw->pos);
size = sigma_action_size(sa);
ssfw->pos += size;
if (ssfw->pos > ssfw->fw->size || size == 0)
break;
ret = process_sigma_action(ssfw, sa);
pr_debug("%s: action returned %i\n", __func__, ret);
if (ret <= 0)
return ret;
}
if (ssfw->pos != ssfw->fw->size)
return -EINVAL;
return 0;
}
static int _process_sigma_firmware(struct device *dev,
struct sigma_firmware *ssfw, const char *name)
{
int ret;
struct sigma_firmware_header *ssfw_head;
const struct firmware *fw;
u32 crc;
pr_debug("%s: loading firmware %s\n", __func__, name);
/* first load the blob */
ret = request_firmware(&fw, name, dev);
if (ret) {
pr_debug("%s: request_firmware() failed with %i\n", __func__, ret);
return ret;
}
ssfw->fw = fw;
/* then verify the header */
ret = -EINVAL;
/*
* Reject too small or unreasonable large files. The upper limit has been
* chosen a bit arbitrarily, but it should be enough for all practical
* purposes and having the limit makes it easier to avoid integer
* overflows later in the loading process.
*/
if (fw->size < sizeof(*ssfw_head) || fw->size >= 0x4000000) {
dev_err(dev, "Failed to load firmware: Invalid size\n");
goto done;
}
ssfw_head = (void *)fw->data;
if (memcmp(ssfw_head->magic, SIGMA_MAGIC, ARRAY_SIZE(ssfw_head->magic))) {
dev_err(dev, "Failed to load firmware: Invalid magic\n");
goto done;
}
crc = crc32(0, fw->data + sizeof(*ssfw_head),
fw->size - sizeof(*ssfw_head));
pr_debug("%s: crc=%x\n", __func__, crc);
if (crc != le32_to_cpu(ssfw_head->crc)) {
dev_err(dev, "Failed to load firmware: Wrong crc checksum: expected %x got %x\n",
le32_to_cpu(ssfw_head->crc), crc);
goto done;
}
ssfw->pos = sizeof(*ssfw_head);
/* finally process all of the actions */
ret = process_sigma_actions(ssfw);
done:
release_firmware(fw);
pr_debug("%s: loaded %s\n", __func__, name);
return ret;
}
#if IS_ENABLED(CONFIG_I2C)
static int sigma_action_write_i2c(void *control_data,
const struct sigma_action *sa, size_t len)
{
return i2c_master_send(control_data, (const unsigned char *)&sa->addr,
len);
}
int process_sigma_firmware(struct i2c_client *client, const char *name)
{
struct sigma_firmware ssfw;
ssfw.control_data = client;
ssfw.write = sigma_action_write_i2c;
return _process_sigma_firmware(&client->dev, &ssfw, name);
}
EXPORT_SYMBOL(process_sigma_firmware);
#endif
#if IS_ENABLED(CONFIG_REGMAP)
static int sigma_action_write_regmap(void *control_data,
const struct sigma_action *sa, size_t len)
{
return regmap_raw_write(control_data, le16_to_cpu(sa->addr),
sa->payload, len - 2);
}
int process_sigma_firmware_regmap(struct device *dev, struct regmap *regmap,
const char *name)
{
struct sigma_firmware ssfw;
ssfw.control_data = regmap;
ssfw.write = sigma_action_write_regmap;
return _process_sigma_firmware(dev, &ssfw, name);
}
EXPORT_SYMBOL(process_sigma_firmware_regmap);
#endif
MODULE_LICENSE("GPL");
| gpl-2.0 |
zachf714/android_kernel_asus_tf101-3.x | drivers/media/video/davinci/dm355_ccdc.c | 4048 | 29455 | /*
* Copyright (C) 2005-2009 Texas Instruments 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.
*
* 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
*
* CCDC hardware module for DM355
* ------------------------------
*
* This module is for configuring DM355 CCD controller of VPFE to capture
* Raw yuv or Bayer RGB data from a decoder. CCDC has several modules
* such as Defect Pixel Correction, Color Space Conversion etc to
* pre-process the Bayer RGB data, before writing it to SDRAM. This
* module also allows application to configure individual
* module parameters through VPFE_CMD_S_CCDC_RAW_PARAMS IOCTL.
* To do so, application include dm355_ccdc.h and vpfe_capture.h header
* files. The setparams() API is called by vpfe_capture driver
* to configure module parameters
*
* TODO: 1) Raw bayer parameter settings and bayer capture
* 2) Split module parameter structure to module specific ioctl structs
* 3) add support for lense shading correction
* 4) investigate if enum used for user space type definition
* to be replaced by #defines or integer
*/
#include <linux/platform_device.h>
#include <linux/uaccess.h>
#include <linux/videodev2.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <media/davinci/dm355_ccdc.h>
#include <media/davinci/vpss.h>
#include "dm355_ccdc_regs.h"
#include "ccdc_hw_device.h"
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("CCDC Driver for DM355");
MODULE_AUTHOR("Texas Instruments");
static struct ccdc_oper_config {
struct device *dev;
/* CCDC interface type */
enum vpfe_hw_if_type if_type;
/* Raw Bayer configuration */
struct ccdc_params_raw bayer;
/* YCbCr configuration */
struct ccdc_params_ycbcr ycbcr;
/* Master clock */
struct clk *mclk;
/* slave clock */
struct clk *sclk;
/* ccdc base address */
void __iomem *base_addr;
} ccdc_cfg = {
/* Raw configurations */
.bayer = {
.pix_fmt = CCDC_PIXFMT_RAW,
.frm_fmt = CCDC_FRMFMT_PROGRESSIVE,
.win = CCDC_WIN_VGA,
.fid_pol = VPFE_PINPOL_POSITIVE,
.vd_pol = VPFE_PINPOL_POSITIVE,
.hd_pol = VPFE_PINPOL_POSITIVE,
.gain = {
.r_ye = 256,
.gb_g = 256,
.gr_cy = 256,
.b_mg = 256
},
.config_params = {
.datasft = 2,
.mfilt1 = CCDC_NO_MEDIAN_FILTER1,
.mfilt2 = CCDC_NO_MEDIAN_FILTER2,
.alaw = {
.gama_wd = 2,
},
.blk_clamp = {
.sample_pixel = 1,
.dc_sub = 25
},
.col_pat_field0 = {
.olop = CCDC_GREEN_BLUE,
.olep = CCDC_BLUE,
.elop = CCDC_RED,
.elep = CCDC_GREEN_RED
},
.col_pat_field1 = {
.olop = CCDC_GREEN_BLUE,
.olep = CCDC_BLUE,
.elop = CCDC_RED,
.elep = CCDC_GREEN_RED
},
},
},
/* YCbCr configuration */
.ycbcr = {
.win = CCDC_WIN_PAL,
.pix_fmt = CCDC_PIXFMT_YCBCR_8BIT,
.frm_fmt = CCDC_FRMFMT_INTERLACED,
.fid_pol = VPFE_PINPOL_POSITIVE,
.vd_pol = VPFE_PINPOL_POSITIVE,
.hd_pol = VPFE_PINPOL_POSITIVE,
.bt656_enable = 1,
.pix_order = CCDC_PIXORDER_CBYCRY,
.buf_type = CCDC_BUFTYPE_FLD_INTERLEAVED
},
};
/* Raw Bayer formats */
static u32 ccdc_raw_bayer_pix_formats[] =
{V4L2_PIX_FMT_SBGGR8, V4L2_PIX_FMT_SBGGR16};
/* Raw YUV formats */
static u32 ccdc_raw_yuv_pix_formats[] =
{V4L2_PIX_FMT_UYVY, V4L2_PIX_FMT_YUYV};
/* register access routines */
static inline u32 regr(u32 offset)
{
return __raw_readl(ccdc_cfg.base_addr + offset);
}
static inline void regw(u32 val, u32 offset)
{
__raw_writel(val, ccdc_cfg.base_addr + offset);
}
static void ccdc_enable(int en)
{
unsigned int temp;
temp = regr(SYNCEN);
temp &= (~CCDC_SYNCEN_VDHDEN_MASK);
temp |= (en & CCDC_SYNCEN_VDHDEN_MASK);
regw(temp, SYNCEN);
}
static void ccdc_enable_output_to_sdram(int en)
{
unsigned int temp;
temp = regr(SYNCEN);
temp &= (~(CCDC_SYNCEN_WEN_MASK));
temp |= ((en << CCDC_SYNCEN_WEN_SHIFT) & CCDC_SYNCEN_WEN_MASK);
regw(temp, SYNCEN);
}
static void ccdc_config_gain_offset(void)
{
/* configure gain */
regw(ccdc_cfg.bayer.gain.r_ye, RYEGAIN);
regw(ccdc_cfg.bayer.gain.gr_cy, GRCYGAIN);
regw(ccdc_cfg.bayer.gain.gb_g, GBGGAIN);
regw(ccdc_cfg.bayer.gain.b_mg, BMGGAIN);
/* configure offset */
regw(ccdc_cfg.bayer.ccdc_offset, OFFSET);
}
/*
* ccdc_restore_defaults()
* This function restore power on defaults in the ccdc registers
*/
static int ccdc_restore_defaults(void)
{
int i;
dev_dbg(ccdc_cfg.dev, "\nstarting ccdc_restore_defaults...");
/* set all registers to zero */
for (i = 0; i <= CCDC_REG_LAST; i += 4)
regw(0, i);
/* now override the values with power on defaults in registers */
regw(MODESET_DEFAULT, MODESET);
/* no culling support */
regw(CULH_DEFAULT, CULH);
regw(CULV_DEFAULT, CULV);
/* Set default Gain and Offset */
ccdc_cfg.bayer.gain.r_ye = GAIN_DEFAULT;
ccdc_cfg.bayer.gain.gb_g = GAIN_DEFAULT;
ccdc_cfg.bayer.gain.gr_cy = GAIN_DEFAULT;
ccdc_cfg.bayer.gain.b_mg = GAIN_DEFAULT;
ccdc_config_gain_offset();
regw(OUTCLIP_DEFAULT, OUTCLIP);
regw(LSCCFG2_DEFAULT, LSCCFG2);
/* select ccdc input */
if (vpss_select_ccdc_source(VPSS_CCDCIN)) {
dev_dbg(ccdc_cfg.dev, "\ncouldn't select ccdc input source");
return -EFAULT;
}
/* select ccdc clock */
if (vpss_enable_clock(VPSS_CCDC_CLOCK, 1) < 0) {
dev_dbg(ccdc_cfg.dev, "\ncouldn't enable ccdc clock");
return -EFAULT;
}
dev_dbg(ccdc_cfg.dev, "\nEnd of ccdc_restore_defaults...");
return 0;
}
static int ccdc_open(struct device *device)
{
return ccdc_restore_defaults();
}
static int ccdc_close(struct device *device)
{
/* disable clock */
vpss_enable_clock(VPSS_CCDC_CLOCK, 0);
/* do nothing for now */
return 0;
}
/*
* ccdc_setwin()
* This function will configure the window size to
* be capture in CCDC reg.
*/
static void ccdc_setwin(struct v4l2_rect *image_win,
enum ccdc_frmfmt frm_fmt, int ppc)
{
int horz_start, horz_nr_pixels;
int vert_start, vert_nr_lines;
int mid_img = 0;
dev_dbg(ccdc_cfg.dev, "\nStarting ccdc_setwin...");
/*
* ppc - per pixel count. indicates how many pixels per cell
* output to SDRAM. example, for ycbcr, it is one y and one c, so 2.
* raw capture this is 1
*/
horz_start = image_win->left << (ppc - 1);
horz_nr_pixels = ((image_win->width) << (ppc - 1)) - 1;
/* Writing the horizontal info into the registers */
regw(horz_start, SPH);
regw(horz_nr_pixels, NPH);
vert_start = image_win->top;
if (frm_fmt == CCDC_FRMFMT_INTERLACED) {
vert_nr_lines = (image_win->height >> 1) - 1;
vert_start >>= 1;
/* Since first line doesn't have any data */
vert_start += 1;
/* configure VDINT0 and VDINT1 */
regw(vert_start, VDINT0);
} else {
/* Since first line doesn't have any data */
vert_start += 1;
vert_nr_lines = image_win->height - 1;
/* configure VDINT0 and VDINT1 */
mid_img = vert_start + (image_win->height / 2);
regw(vert_start, VDINT0);
regw(mid_img, VDINT1);
}
regw(vert_start & CCDC_START_VER_ONE_MASK, SLV0);
regw(vert_start & CCDC_START_VER_TWO_MASK, SLV1);
regw(vert_nr_lines & CCDC_NUM_LINES_VER, NLV);
dev_dbg(ccdc_cfg.dev, "\nEnd of ccdc_setwin...");
}
static int validate_ccdc_param(struct ccdc_config_params_raw *ccdcparam)
{
if (ccdcparam->datasft < CCDC_DATA_NO_SHIFT ||
ccdcparam->datasft > CCDC_DATA_SHIFT_6BIT) {
dev_dbg(ccdc_cfg.dev, "Invalid value of data shift\n");
return -EINVAL;
}
if (ccdcparam->mfilt1 < CCDC_NO_MEDIAN_FILTER1 ||
ccdcparam->mfilt1 > CCDC_MEDIAN_FILTER1) {
dev_dbg(ccdc_cfg.dev, "Invalid value of median filter1\n");
return -EINVAL;
}
if (ccdcparam->mfilt2 < CCDC_NO_MEDIAN_FILTER2 ||
ccdcparam->mfilt2 > CCDC_MEDIAN_FILTER2) {
dev_dbg(ccdc_cfg.dev, "Invalid value of median filter2\n");
return -EINVAL;
}
if ((ccdcparam->med_filt_thres < 0) ||
(ccdcparam->med_filt_thres > CCDC_MED_FILT_THRESH)) {
dev_dbg(ccdc_cfg.dev,
"Invalid value of median filter thresold\n");
return -EINVAL;
}
if (ccdcparam->data_sz < CCDC_DATA_16BITS ||
ccdcparam->data_sz > CCDC_DATA_8BITS) {
dev_dbg(ccdc_cfg.dev, "Invalid value of data size\n");
return -EINVAL;
}
if (ccdcparam->alaw.enable) {
if (ccdcparam->alaw.gama_wd < CCDC_GAMMA_BITS_13_4 ||
ccdcparam->alaw.gama_wd > CCDC_GAMMA_BITS_09_0) {
dev_dbg(ccdc_cfg.dev, "Invalid value of ALAW\n");
return -EINVAL;
}
}
if (ccdcparam->blk_clamp.b_clamp_enable) {
if (ccdcparam->blk_clamp.sample_pixel < CCDC_SAMPLE_1PIXELS ||
ccdcparam->blk_clamp.sample_pixel > CCDC_SAMPLE_16PIXELS) {
dev_dbg(ccdc_cfg.dev,
"Invalid value of sample pixel\n");
return -EINVAL;
}
if (ccdcparam->blk_clamp.sample_ln < CCDC_SAMPLE_1LINES ||
ccdcparam->blk_clamp.sample_ln > CCDC_SAMPLE_16LINES) {
dev_dbg(ccdc_cfg.dev,
"Invalid value of sample lines\n");
return -EINVAL;
}
}
return 0;
}
/* Parameter operations */
static int ccdc_set_params(void __user *params)
{
struct ccdc_config_params_raw ccdc_raw_params;
int x;
/* only raw module parameters can be set through the IOCTL */
if (ccdc_cfg.if_type != VPFE_RAW_BAYER)
return -EINVAL;
x = copy_from_user(&ccdc_raw_params, params, sizeof(ccdc_raw_params));
if (x) {
dev_dbg(ccdc_cfg.dev, "ccdc_set_params: error in copying ccdc"
"params, %d\n", x);
return -EFAULT;
}
if (!validate_ccdc_param(&ccdc_raw_params)) {
memcpy(&ccdc_cfg.bayer.config_params,
&ccdc_raw_params,
sizeof(ccdc_raw_params));
return 0;
}
return -EINVAL;
}
/* This function will configure CCDC for YCbCr video capture */
static void ccdc_config_ycbcr(void)
{
struct ccdc_params_ycbcr *params = &ccdc_cfg.ycbcr;
u32 temp;
/* first set the CCDC power on defaults values in all registers */
dev_dbg(ccdc_cfg.dev, "\nStarting ccdc_config_ycbcr...");
ccdc_restore_defaults();
/* configure pixel format & video frame format */
temp = (((params->pix_fmt & CCDC_INPUT_MODE_MASK) <<
CCDC_INPUT_MODE_SHIFT) |
((params->frm_fmt & CCDC_FRM_FMT_MASK) <<
CCDC_FRM_FMT_SHIFT));
/* setup BT.656 sync mode */
if (params->bt656_enable) {
regw(CCDC_REC656IF_BT656_EN, REC656IF);
/*
* configure the FID, VD, HD pin polarity fld,hd pol positive,
* vd negative, 8-bit pack mode
*/
temp |= CCDC_VD_POL_NEGATIVE;
} else { /* y/c external sync mode */
temp |= (((params->fid_pol & CCDC_FID_POL_MASK) <<
CCDC_FID_POL_SHIFT) |
((params->hd_pol & CCDC_HD_POL_MASK) <<
CCDC_HD_POL_SHIFT) |
((params->vd_pol & CCDC_VD_POL_MASK) <<
CCDC_VD_POL_SHIFT));
}
/* pack the data to 8-bit */
temp |= CCDC_DATA_PACK_ENABLE;
regw(temp, MODESET);
/* configure video window */
ccdc_setwin(¶ms->win, params->frm_fmt, 2);
/* configure the order of y cb cr in SD-RAM */
temp = (params->pix_order << CCDC_Y8POS_SHIFT);
temp |= CCDC_LATCH_ON_VSYNC_DISABLE | CCDC_CCDCFG_FIDMD_NO_LATCH_VSYNC;
regw(temp, CCDCFG);
/*
* configure the horizontal line offset. This is done by rounding up
* width to a multiple of 16 pixels and multiply by two to account for
* y:cb:cr 4:2:2 data
*/
regw(((params->win.width * 2 + 31) >> 5), HSIZE);
/* configure the memory line offset */
if (params->buf_type == CCDC_BUFTYPE_FLD_INTERLEAVED) {
/* two fields are interleaved in memory */
regw(CCDC_SDOFST_FIELD_INTERLEAVED, SDOFST);
}
dev_dbg(ccdc_cfg.dev, "\nEnd of ccdc_config_ycbcr...\n");
}
/*
* ccdc_config_black_clamp()
* configure parameters for Optical Black Clamp
*/
static void ccdc_config_black_clamp(struct ccdc_black_clamp *bclamp)
{
u32 val;
if (!bclamp->b_clamp_enable) {
/* configure DCSub */
regw(bclamp->dc_sub & CCDC_BLK_DC_SUB_MASK, DCSUB);
regw(0x0000, CLAMP);
return;
}
/* Enable the Black clamping, set sample lines and pixels */
val = (bclamp->start_pixel & CCDC_BLK_ST_PXL_MASK) |
((bclamp->sample_pixel & CCDC_BLK_SAMPLE_LN_MASK) <<
CCDC_BLK_SAMPLE_LN_SHIFT) | CCDC_BLK_CLAMP_ENABLE;
regw(val, CLAMP);
/* If Black clamping is enable then make dcsub 0 */
val = (bclamp->sample_ln & CCDC_NUM_LINE_CALC_MASK)
<< CCDC_NUM_LINE_CALC_SHIFT;
regw(val, DCSUB);
}
/*
* ccdc_config_black_compense()
* configure parameters for Black Compensation
*/
static void ccdc_config_black_compense(struct ccdc_black_compensation *bcomp)
{
u32 val;
val = (bcomp->b & CCDC_BLK_COMP_MASK) |
((bcomp->gb & CCDC_BLK_COMP_MASK) <<
CCDC_BLK_COMP_GB_COMP_SHIFT);
regw(val, BLKCMP1);
val = ((bcomp->gr & CCDC_BLK_COMP_MASK) <<
CCDC_BLK_COMP_GR_COMP_SHIFT) |
((bcomp->r & CCDC_BLK_COMP_MASK) <<
CCDC_BLK_COMP_R_COMP_SHIFT);
regw(val, BLKCMP0);
}
/*
* ccdc_write_dfc_entry()
* write an entry in the dfc table.
*/
int ccdc_write_dfc_entry(int index, struct ccdc_vertical_dft *dfc)
{
/* TODO This is to be re-visited and adjusted */
#define DFC_WRITE_WAIT_COUNT 1000
u32 val, count = DFC_WRITE_WAIT_COUNT;
regw(dfc->dft_corr_vert[index], DFCMEM0);
regw(dfc->dft_corr_horz[index], DFCMEM1);
regw(dfc->dft_corr_sub1[index], DFCMEM2);
regw(dfc->dft_corr_sub2[index], DFCMEM3);
regw(dfc->dft_corr_sub3[index], DFCMEM4);
/* set WR bit to write */
val = regr(DFCMEMCTL) | CCDC_DFCMEMCTL_DFCMWR_MASK;
regw(val, DFCMEMCTL);
/*
* Assume, it is very short. If we get an error, we need to
* adjust this value
*/
while (regr(DFCMEMCTL) & CCDC_DFCMEMCTL_DFCMWR_MASK)
count--;
/*
* TODO We expect the count to be non-zero to be successful. Adjust
* the count if write requires more time
*/
if (count) {
dev_err(ccdc_cfg.dev, "defect table write timeout !!!\n");
return -1;
}
return 0;
}
/*
* ccdc_config_vdfc()
* configure parameters for Vertical Defect Correction
*/
static int ccdc_config_vdfc(struct ccdc_vertical_dft *dfc)
{
u32 val;
int i;
/* Configure General Defect Correction. The table used is from IPIPE */
val = dfc->gen_dft_en & CCDC_DFCCTL_GDFCEN_MASK;
/* Configure Vertical Defect Correction if needed */
if (!dfc->ver_dft_en) {
/* Enable only General Defect Correction */
regw(val, DFCCTL);
return 0;
}
if (dfc->table_size > CCDC_DFT_TABLE_SIZE)
return -EINVAL;
val |= CCDC_DFCCTL_VDFC_DISABLE;
val |= (dfc->dft_corr_ctl.vdfcsl & CCDC_DFCCTL_VDFCSL_MASK) <<
CCDC_DFCCTL_VDFCSL_SHIFT;
val |= (dfc->dft_corr_ctl.vdfcuda & CCDC_DFCCTL_VDFCUDA_MASK) <<
CCDC_DFCCTL_VDFCUDA_SHIFT;
val |= (dfc->dft_corr_ctl.vdflsft & CCDC_DFCCTL_VDFLSFT_MASK) <<
CCDC_DFCCTL_VDFLSFT_SHIFT;
regw(val , DFCCTL);
/* clear address ptr to offset 0 */
val = CCDC_DFCMEMCTL_DFCMARST_MASK << CCDC_DFCMEMCTL_DFCMARST_SHIFT;
/* write defect table entries */
for (i = 0; i < dfc->table_size; i++) {
/* increment address for non zero index */
if (i != 0)
val = CCDC_DFCMEMCTL_INC_ADDR;
regw(val, DFCMEMCTL);
if (ccdc_write_dfc_entry(i, dfc) < 0)
return -EFAULT;
}
/* update saturation level and enable dfc */
regw(dfc->saturation_ctl & CCDC_VDC_DFCVSAT_MASK, DFCVSAT);
val = regr(DFCCTL) | (CCDC_DFCCTL_VDFCEN_MASK <<
CCDC_DFCCTL_VDFCEN_SHIFT);
regw(val, DFCCTL);
return 0;
}
/*
* ccdc_config_csc()
* configure parameters for color space conversion
* Each register CSCM0-7 has two values in S8Q5 format.
*/
static void ccdc_config_csc(struct ccdc_csc *csc)
{
u32 val1, val2;
int i;
if (!csc->enable)
return;
/* Enable the CSC sub-module */
regw(CCDC_CSC_ENABLE, CSCCTL);
/* Converting the co-eff as per the format of the register */
for (i = 0; i < CCDC_CSC_COEFF_TABLE_SIZE; i++) {
if ((i % 2) == 0) {
/* CSCM - LSB */
val1 = (csc->coeff[i].integer &
CCDC_CSC_COEF_INTEG_MASK)
<< CCDC_CSC_COEF_INTEG_SHIFT;
/*
* convert decimal part to binary. Use 2 decimal
* precision, user values range from .00 - 0.99
*/
val1 |= (((csc->coeff[i].decimal &
CCDC_CSC_COEF_DECIMAL_MASK) *
CCDC_CSC_DEC_MAX) / 100);
} else {
/* CSCM - MSB */
val2 = (csc->coeff[i].integer &
CCDC_CSC_COEF_INTEG_MASK)
<< CCDC_CSC_COEF_INTEG_SHIFT;
val2 |= (((csc->coeff[i].decimal &
CCDC_CSC_COEF_DECIMAL_MASK) *
CCDC_CSC_DEC_MAX) / 100);
val2 <<= CCDC_CSCM_MSB_SHIFT;
val2 |= val1;
regw(val2, (CSCM0 + ((i - 1) << 1)));
}
}
}
/*
* ccdc_config_color_patterns()
* configure parameters for color patterns
*/
static void ccdc_config_color_patterns(struct ccdc_col_pat *pat0,
struct ccdc_col_pat *pat1)
{
u32 val;
val = (pat0->olop | (pat0->olep << 2) | (pat0->elop << 4) |
(pat0->elep << 6) | (pat1->olop << 8) | (pat1->olep << 10) |
(pat1->elop << 12) | (pat1->elep << 14));
regw(val, COLPTN);
}
/* This function will configure CCDC for Raw mode image capture */
static int ccdc_config_raw(void)
{
struct ccdc_params_raw *params = &ccdc_cfg.bayer;
struct ccdc_config_params_raw *config_params =
&ccdc_cfg.bayer.config_params;
unsigned int val;
dev_dbg(ccdc_cfg.dev, "\nStarting ccdc_config_raw...");
/* restore power on defaults to register */
ccdc_restore_defaults();
/* CCDCFG register:
* set CCD Not to swap input since input is RAW data
* set FID detection function to Latch at V-Sync
* set WENLOG - ccdc valid area to AND
* set TRGSEL to WENBIT
* set EXTRG to DISABLE
* disable latching function on VSYNC - shadowed registers
*/
regw(CCDC_YCINSWP_RAW | CCDC_CCDCFG_FIDMD_LATCH_VSYNC |
CCDC_CCDCFG_WENLOG_AND | CCDC_CCDCFG_TRGSEL_WEN |
CCDC_CCDCFG_EXTRG_DISABLE | CCDC_LATCH_ON_VSYNC_DISABLE, CCDCFG);
/*
* Set VDHD direction to input, input type to raw input
* normal data polarity, do not use external WEN
*/
val = (CCDC_VDHDOUT_INPUT | CCDC_RAW_IP_MODE | CCDC_DATAPOL_NORMAL |
CCDC_EXWEN_DISABLE);
/*
* Configure the vertical sync polarity (MODESET.VDPOL), horizontal
* sync polarity (MODESET.HDPOL), field id polarity (MODESET.FLDPOL),
* frame format(progressive or interlace), & pixel format (Input mode)
*/
val |= (((params->vd_pol & CCDC_VD_POL_MASK) << CCDC_VD_POL_SHIFT) |
((params->hd_pol & CCDC_HD_POL_MASK) << CCDC_HD_POL_SHIFT) |
((params->fid_pol & CCDC_FID_POL_MASK) << CCDC_FID_POL_SHIFT) |
((params->frm_fmt & CCDC_FRM_FMT_MASK) << CCDC_FRM_FMT_SHIFT) |
((params->pix_fmt & CCDC_PIX_FMT_MASK) << CCDC_PIX_FMT_SHIFT));
/* set pack for alaw compression */
if ((config_params->data_sz == CCDC_DATA_8BITS) ||
config_params->alaw.enable)
val |= CCDC_DATA_PACK_ENABLE;
/* Configure for LPF */
if (config_params->lpf_enable)
val |= (config_params->lpf_enable & CCDC_LPF_MASK) <<
CCDC_LPF_SHIFT;
/* Configure the data shift */
val |= (config_params->datasft & CCDC_DATASFT_MASK) <<
CCDC_DATASFT_SHIFT;
regw(val , MODESET);
dev_dbg(ccdc_cfg.dev, "\nWriting 0x%x to MODESET...\n", val);
/* Configure the Median Filter threshold */
regw((config_params->med_filt_thres) & CCDC_MED_FILT_THRESH, MEDFILT);
/* Configure GAMMAWD register. defaur 11-2, and Mosaic cfa pattern */
val = CCDC_GAMMA_BITS_11_2 << CCDC_GAMMAWD_INPUT_SHIFT |
CCDC_CFA_MOSAIC;
/* Enable and configure aLaw register if needed */
if (config_params->alaw.enable) {
val |= (CCDC_ALAW_ENABLE |
((config_params->alaw.gama_wd &
CCDC_ALAW_GAMA_WD_MASK) <<
CCDC_GAMMAWD_INPUT_SHIFT));
}
/* Configure Median filter1 & filter2 */
val |= ((config_params->mfilt1 << CCDC_MFILT1_SHIFT) |
(config_params->mfilt2 << CCDC_MFILT2_SHIFT));
regw(val, GAMMAWD);
dev_dbg(ccdc_cfg.dev, "\nWriting 0x%x to GAMMAWD...\n", val);
/* configure video window */
ccdc_setwin(¶ms->win, params->frm_fmt, 1);
/* Optical Clamp Averaging */
ccdc_config_black_clamp(&config_params->blk_clamp);
/* Black level compensation */
ccdc_config_black_compense(&config_params->blk_comp);
/* Vertical Defect Correction if needed */
if (ccdc_config_vdfc(&config_params->vertical_dft) < 0)
return -EFAULT;
/* color space conversion */
ccdc_config_csc(&config_params->csc);
/* color pattern */
ccdc_config_color_patterns(&config_params->col_pat_field0,
&config_params->col_pat_field1);
/* Configure the Gain & offset control */
ccdc_config_gain_offset();
dev_dbg(ccdc_cfg.dev, "\nWriting %x to COLPTN...\n", val);
/* Configure DATAOFST register */
val = (config_params->data_offset.horz_offset & CCDC_DATAOFST_MASK) <<
CCDC_DATAOFST_H_SHIFT;
val |= (config_params->data_offset.vert_offset & CCDC_DATAOFST_MASK) <<
CCDC_DATAOFST_V_SHIFT;
regw(val, DATAOFST);
/* configuring HSIZE register */
val = (params->horz_flip_enable & CCDC_HSIZE_FLIP_MASK) <<
CCDC_HSIZE_FLIP_SHIFT;
/* If pack 8 is enable then 1 pixel will take 1 byte */
if ((config_params->data_sz == CCDC_DATA_8BITS) ||
config_params->alaw.enable) {
val |= (((params->win.width) + 31) >> 5) &
CCDC_HSIZE_VAL_MASK;
/* adjust to multiple of 32 */
dev_dbg(ccdc_cfg.dev, "\nWriting 0x%x to HSIZE...\n",
(((params->win.width) + 31) >> 5) &
CCDC_HSIZE_VAL_MASK);
} else {
/* else one pixel will take 2 byte */
val |= (((params->win.width * 2) + 31) >> 5) &
CCDC_HSIZE_VAL_MASK;
dev_dbg(ccdc_cfg.dev, "\nWriting 0x%x to HSIZE...\n",
(((params->win.width * 2) + 31) >> 5) &
CCDC_HSIZE_VAL_MASK);
}
regw(val, HSIZE);
/* Configure SDOFST register */
if (params->frm_fmt == CCDC_FRMFMT_INTERLACED) {
if (params->image_invert_enable) {
/* For interlace inverse mode */
regw(CCDC_SDOFST_INTERLACE_INVERSE, SDOFST);
dev_dbg(ccdc_cfg.dev, "\nWriting %x to SDOFST...\n",
CCDC_SDOFST_INTERLACE_INVERSE);
} else {
/* For interlace non inverse mode */
regw(CCDC_SDOFST_INTERLACE_NORMAL, SDOFST);
dev_dbg(ccdc_cfg.dev, "\nWriting %x to SDOFST...\n",
CCDC_SDOFST_INTERLACE_NORMAL);
}
} else if (params->frm_fmt == CCDC_FRMFMT_PROGRESSIVE) {
if (params->image_invert_enable) {
/* For progessive inverse mode */
regw(CCDC_SDOFST_PROGRESSIVE_INVERSE, SDOFST);
dev_dbg(ccdc_cfg.dev, "\nWriting %x to SDOFST...\n",
CCDC_SDOFST_PROGRESSIVE_INVERSE);
} else {
/* For progessive non inverse mode */
regw(CCDC_SDOFST_PROGRESSIVE_NORMAL, SDOFST);
dev_dbg(ccdc_cfg.dev, "\nWriting %x to SDOFST...\n",
CCDC_SDOFST_PROGRESSIVE_NORMAL);
}
}
dev_dbg(ccdc_cfg.dev, "\nend of ccdc_config_raw...");
return 0;
}
static int ccdc_configure(void)
{
if (ccdc_cfg.if_type == VPFE_RAW_BAYER)
return ccdc_config_raw();
else
ccdc_config_ycbcr();
return 0;
}
static int ccdc_set_buftype(enum ccdc_buftype buf_type)
{
if (ccdc_cfg.if_type == VPFE_RAW_BAYER)
ccdc_cfg.bayer.buf_type = buf_type;
else
ccdc_cfg.ycbcr.buf_type = buf_type;
return 0;
}
static enum ccdc_buftype ccdc_get_buftype(void)
{
if (ccdc_cfg.if_type == VPFE_RAW_BAYER)
return ccdc_cfg.bayer.buf_type;
return ccdc_cfg.ycbcr.buf_type;
}
static int ccdc_enum_pix(u32 *pix, int i)
{
int ret = -EINVAL;
if (ccdc_cfg.if_type == VPFE_RAW_BAYER) {
if (i < ARRAY_SIZE(ccdc_raw_bayer_pix_formats)) {
*pix = ccdc_raw_bayer_pix_formats[i];
ret = 0;
}
} else {
if (i < ARRAY_SIZE(ccdc_raw_yuv_pix_formats)) {
*pix = ccdc_raw_yuv_pix_formats[i];
ret = 0;
}
}
return ret;
}
static int ccdc_set_pixel_format(u32 pixfmt)
{
struct ccdc_a_law *alaw = &ccdc_cfg.bayer.config_params.alaw;
if (ccdc_cfg.if_type == VPFE_RAW_BAYER) {
ccdc_cfg.bayer.pix_fmt = CCDC_PIXFMT_RAW;
if (pixfmt == V4L2_PIX_FMT_SBGGR8)
alaw->enable = 1;
else if (pixfmt != V4L2_PIX_FMT_SBGGR16)
return -EINVAL;
} else {
if (pixfmt == V4L2_PIX_FMT_YUYV)
ccdc_cfg.ycbcr.pix_order = CCDC_PIXORDER_YCBYCR;
else if (pixfmt == V4L2_PIX_FMT_UYVY)
ccdc_cfg.ycbcr.pix_order = CCDC_PIXORDER_CBYCRY;
else
return -EINVAL;
}
return 0;
}
static u32 ccdc_get_pixel_format(void)
{
struct ccdc_a_law *alaw = &ccdc_cfg.bayer.config_params.alaw;
u32 pixfmt;
if (ccdc_cfg.if_type == VPFE_RAW_BAYER)
if (alaw->enable)
pixfmt = V4L2_PIX_FMT_SBGGR8;
else
pixfmt = V4L2_PIX_FMT_SBGGR16;
else {
if (ccdc_cfg.ycbcr.pix_order == CCDC_PIXORDER_YCBYCR)
pixfmt = V4L2_PIX_FMT_YUYV;
else
pixfmt = V4L2_PIX_FMT_UYVY;
}
return pixfmt;
}
static int ccdc_set_image_window(struct v4l2_rect *win)
{
if (ccdc_cfg.if_type == VPFE_RAW_BAYER)
ccdc_cfg.bayer.win = *win;
else
ccdc_cfg.ycbcr.win = *win;
return 0;
}
static void ccdc_get_image_window(struct v4l2_rect *win)
{
if (ccdc_cfg.if_type == VPFE_RAW_BAYER)
*win = ccdc_cfg.bayer.win;
else
*win = ccdc_cfg.ycbcr.win;
}
static unsigned int ccdc_get_line_length(void)
{
struct ccdc_config_params_raw *config_params =
&ccdc_cfg.bayer.config_params;
unsigned int len;
if (ccdc_cfg.if_type == VPFE_RAW_BAYER) {
if ((config_params->alaw.enable) ||
(config_params->data_sz == CCDC_DATA_8BITS))
len = ccdc_cfg.bayer.win.width;
else
len = ccdc_cfg.bayer.win.width * 2;
} else
len = ccdc_cfg.ycbcr.win.width * 2;
return ALIGN(len, 32);
}
static int ccdc_set_frame_format(enum ccdc_frmfmt frm_fmt)
{
if (ccdc_cfg.if_type == VPFE_RAW_BAYER)
ccdc_cfg.bayer.frm_fmt = frm_fmt;
else
ccdc_cfg.ycbcr.frm_fmt = frm_fmt;
return 0;
}
static enum ccdc_frmfmt ccdc_get_frame_format(void)
{
if (ccdc_cfg.if_type == VPFE_RAW_BAYER)
return ccdc_cfg.bayer.frm_fmt;
else
return ccdc_cfg.ycbcr.frm_fmt;
}
static int ccdc_getfid(void)
{
return (regr(MODESET) >> 15) & 1;
}
/* misc operations */
static inline void ccdc_setfbaddr(unsigned long addr)
{
regw((addr >> 21) & 0x007f, STADRH);
regw((addr >> 5) & 0x0ffff, STADRL);
}
static int ccdc_set_hw_if_params(struct vpfe_hw_if_param *params)
{
ccdc_cfg.if_type = params->if_type;
switch (params->if_type) {
case VPFE_BT656:
case VPFE_YCBCR_SYNC_16:
case VPFE_YCBCR_SYNC_8:
ccdc_cfg.ycbcr.vd_pol = params->vdpol;
ccdc_cfg.ycbcr.hd_pol = params->hdpol;
break;
default:
/* TODO add support for raw bayer here */
return -EINVAL;
}
return 0;
}
static struct ccdc_hw_device ccdc_hw_dev = {
.name = "DM355 CCDC",
.owner = THIS_MODULE,
.hw_ops = {
.open = ccdc_open,
.close = ccdc_close,
.enable = ccdc_enable,
.enable_out_to_sdram = ccdc_enable_output_to_sdram,
.set_hw_if_params = ccdc_set_hw_if_params,
.set_params = ccdc_set_params,
.configure = ccdc_configure,
.set_buftype = ccdc_set_buftype,
.get_buftype = ccdc_get_buftype,
.enum_pix = ccdc_enum_pix,
.set_pixel_format = ccdc_set_pixel_format,
.get_pixel_format = ccdc_get_pixel_format,
.set_frame_format = ccdc_set_frame_format,
.get_frame_format = ccdc_get_frame_format,
.set_image_window = ccdc_set_image_window,
.get_image_window = ccdc_get_image_window,
.get_line_length = ccdc_get_line_length,
.setfbaddr = ccdc_setfbaddr,
.getfid = ccdc_getfid,
},
};
static int __init dm355_ccdc_probe(struct platform_device *pdev)
{
void (*setup_pinmux)(void);
struct resource *res;
int status = 0;
/*
* first try to register with vpfe. If not correct platform, then we
* don't have to iomap
*/
status = vpfe_register_ccdc_device(&ccdc_hw_dev);
if (status < 0)
return status;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
status = -ENODEV;
goto fail_nores;
}
res = request_mem_region(res->start, resource_size(res), res->name);
if (!res) {
status = -EBUSY;
goto fail_nores;
}
ccdc_cfg.base_addr = ioremap_nocache(res->start, resource_size(res));
if (!ccdc_cfg.base_addr) {
status = -ENOMEM;
goto fail_nomem;
}
/* Get and enable Master clock */
ccdc_cfg.mclk = clk_get(&pdev->dev, "master");
if (IS_ERR(ccdc_cfg.mclk)) {
status = PTR_ERR(ccdc_cfg.mclk);
goto fail_nomap;
}
if (clk_enable(ccdc_cfg.mclk)) {
status = -ENODEV;
goto fail_mclk;
}
/* Get and enable Slave clock */
ccdc_cfg.sclk = clk_get(&pdev->dev, "slave");
if (IS_ERR(ccdc_cfg.sclk)) {
status = PTR_ERR(ccdc_cfg.sclk);
goto fail_mclk;
}
if (clk_enable(ccdc_cfg.sclk)) {
status = -ENODEV;
goto fail_sclk;
}
/* Platform data holds setup_pinmux function ptr */
if (NULL == pdev->dev.platform_data) {
status = -ENODEV;
goto fail_sclk;
}
setup_pinmux = pdev->dev.platform_data;
/*
* setup Mux configuration for ccdc which may be different for
* different SoCs using this CCDC
*/
setup_pinmux();
ccdc_cfg.dev = &pdev->dev;
printk(KERN_NOTICE "%s is registered with vpfe.\n", ccdc_hw_dev.name);
return 0;
fail_sclk:
clk_put(ccdc_cfg.sclk);
fail_mclk:
clk_put(ccdc_cfg.mclk);
fail_nomap:
iounmap(ccdc_cfg.base_addr);
fail_nomem:
release_mem_region(res->start, resource_size(res));
fail_nores:
vpfe_unregister_ccdc_device(&ccdc_hw_dev);
return status;
}
static int dm355_ccdc_remove(struct platform_device *pdev)
{
struct resource *res;
clk_put(ccdc_cfg.mclk);
clk_put(ccdc_cfg.sclk);
iounmap(ccdc_cfg.base_addr);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (res)
release_mem_region(res->start, resource_size(res));
vpfe_unregister_ccdc_device(&ccdc_hw_dev);
return 0;
}
static struct platform_driver dm355_ccdc_driver = {
.driver = {
.name = "dm355_ccdc",
.owner = THIS_MODULE,
},
.remove = __devexit_p(dm355_ccdc_remove),
.probe = dm355_ccdc_probe,
};
static int __init dm355_ccdc_init(void)
{
return platform_driver_register(&dm355_ccdc_driver);
}
static void __exit dm355_ccdc_exit(void)
{
platform_driver_unregister(&dm355_ccdc_driver);
}
module_init(dm355_ccdc_init);
module_exit(dm355_ccdc_exit);
| gpl-2.0 |
CyanogenMod/lge-kernel-msm7x27 | arch/um/drivers/net_user.c | 4304 | 5349 | /*
* Copyright (C) 2001 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
* Licensed under the GPL
*/
#include <stdio.h>
#include <unistd.h>
#include <stdarg.h>
#include <errno.h>
#include <stddef.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include "net_user.h"
#include "kern_constants.h"
#include "os.h"
#include "um_malloc.h"
#include "user.h"
int tap_open_common(void *dev, char *gate_addr)
{
int tap_addr[4];
if (gate_addr == NULL)
return 0;
if (sscanf(gate_addr, "%d.%d.%d.%d", &tap_addr[0],
&tap_addr[1], &tap_addr[2], &tap_addr[3]) != 4) {
printk(UM_KERN_ERR "Invalid tap IP address - '%s'\n",
gate_addr);
return -EINVAL;
}
return 0;
}
void tap_check_ips(char *gate_addr, unsigned char *eth_addr)
{
int tap_addr[4];
if ((gate_addr != NULL) &&
(sscanf(gate_addr, "%d.%d.%d.%d", &tap_addr[0],
&tap_addr[1], &tap_addr[2], &tap_addr[3]) == 4) &&
(eth_addr[0] == tap_addr[0]) &&
(eth_addr[1] == tap_addr[1]) &&
(eth_addr[2] == tap_addr[2]) &&
(eth_addr[3] == tap_addr[3])) {
printk(UM_KERN_ERR "The tap IP address and the UML eth IP "
"address must be different\n");
}
}
/* Do reliable error handling as this fails frequently enough. */
void read_output(int fd, char *output, int len)
{
int remain, ret, expected;
char c;
char *str;
if (output == NULL) {
output = &c;
len = sizeof(c);
}
*output = '\0';
ret = read(fd, &remain, sizeof(remain));
if (ret != sizeof(remain)) {
if (ret < 0)
ret = -errno;
expected = sizeof(remain);
str = "length";
goto err;
}
while (remain != 0) {
expected = (remain < len) ? remain : len;
ret = read(fd, output, expected);
if (ret != expected) {
if (ret < 0)
ret = -errno;
str = "data";
goto err;
}
remain -= ret;
}
return;
err:
if (ret < 0)
printk(UM_KERN_ERR "read_output - read of %s failed, "
"errno = %d\n", str, -ret);
else
printk(UM_KERN_ERR "read_output - read of %s failed, read only "
"%d of %d bytes\n", str, ret, expected);
}
int net_read(int fd, void *buf, int len)
{
int n;
n = read(fd, buf, len);
if ((n < 0) && (errno == EAGAIN))
return 0;
else if (n == 0)
return -ENOTCONN;
return n;
}
int net_recvfrom(int fd, void *buf, int len)
{
int n;
CATCH_EINTR(n = recvfrom(fd, buf, len, 0, NULL, NULL));
if (n < 0) {
if (errno == EAGAIN)
return 0;
return -errno;
}
else if (n == 0)
return -ENOTCONN;
return n;
}
int net_write(int fd, void *buf, int len)
{
int n;
n = write(fd, buf, len);
if ((n < 0) && (errno == EAGAIN))
return 0;
else if (n == 0)
return -ENOTCONN;
return n;
}
int net_send(int fd, void *buf, int len)
{
int n;
CATCH_EINTR(n = send(fd, buf, len, 0));
if (n < 0) {
if (errno == EAGAIN)
return 0;
return -errno;
}
else if (n == 0)
return -ENOTCONN;
return n;
}
int net_sendto(int fd, void *buf, int len, void *to, int sock_len)
{
int n;
CATCH_EINTR(n = sendto(fd, buf, len, 0, (struct sockaddr *) to,
sock_len));
if (n < 0) {
if (errno == EAGAIN)
return 0;
return -errno;
}
else if (n == 0)
return -ENOTCONN;
return n;
}
struct change_pre_exec_data {
int close_me;
int stdout;
};
static void change_pre_exec(void *arg)
{
struct change_pre_exec_data *data = arg;
close(data->close_me);
dup2(data->stdout, 1);
}
static int change_tramp(char **argv, char *output, int output_len)
{
int pid, fds[2], err;
struct change_pre_exec_data pe_data;
err = os_pipe(fds, 1, 0);
if (err < 0) {
printk(UM_KERN_ERR "change_tramp - pipe failed, err = %d\n",
-err);
return err;
}
pe_data.close_me = fds[0];
pe_data.stdout = fds[1];
pid = run_helper(change_pre_exec, &pe_data, argv);
if (pid > 0) /* Avoid hang as we won't get data in failure case. */
read_output(fds[0], output, output_len);
close(fds[0]);
close(fds[1]);
if (pid > 0)
helper_wait(pid);
return pid;
}
static void change(char *dev, char *what, unsigned char *addr,
unsigned char *netmask)
{
char addr_buf[sizeof("255.255.255.255\0")];
char netmask_buf[sizeof("255.255.255.255\0")];
char version[sizeof("nnnnn\0")];
char *argv[] = { "uml_net", version, what, dev, addr_buf,
netmask_buf, NULL };
char *output;
int output_len, pid;
sprintf(version, "%d", UML_NET_VERSION);
sprintf(addr_buf, "%d.%d.%d.%d", addr[0], addr[1], addr[2], addr[3]);
sprintf(netmask_buf, "%d.%d.%d.%d", netmask[0], netmask[1],
netmask[2], netmask[3]);
output_len = UM_KERN_PAGE_SIZE;
output = uml_kmalloc(output_len, UM_GFP_KERNEL);
if (output == NULL)
printk(UM_KERN_ERR "change : failed to allocate output "
"buffer\n");
pid = change_tramp(argv, output, output_len);
if (pid < 0) return;
if (output != NULL) {
printk("%s", output);
kfree(output);
}
}
void open_addr(unsigned char *addr, unsigned char *netmask, void *arg)
{
change(arg, "add", addr, netmask);
}
void close_addr(unsigned char *addr, unsigned char *netmask, void *arg)
{
change(arg, "del", addr, netmask);
}
char *split_if_spec(char *str, ...)
{
char **arg, *end;
va_list ap;
va_start(ap, str);
while ((arg = va_arg(ap, char **)) != NULL) {
if (*str == '\0')
return NULL;
end = strchr(str, ',');
if (end != str)
*arg = str;
if (end == NULL)
return NULL;
*end++ = '\0';
str = end;
}
va_end(ap);
return str;
}
| gpl-2.0 |
lordeko/NebulaKernel | arch/mips/mti-malta/malta-time.c | 4560 | 4090 | /*
* Carsten Langgaard, carstenl@mips.com
* Copyright (C) 1999,2000 MIPS Technologies, Inc. All rights reserved.
*
* This program is free software; you can distribute it and/or modify it
* under the terms of the GNU General Public License (Version 2) as
* published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
*
* Setting up the clock on the MIPS boards.
*/
#include <linux/types.h>
#include <linux/i8253.h>
#include <linux/init.h>
#include <linux/kernel_stat.h>
#include <linux/sched.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <linux/time.h>
#include <linux/timex.h>
#include <linux/mc146818rtc.h>
#include <asm/mipsregs.h>
#include <asm/mipsmtregs.h>
#include <asm/hardirq.h>
#include <asm/irq.h>
#include <asm/div64.h>
#include <asm/cpu.h>
#include <asm/setup.h>
#include <asm/time.h>
#include <asm/mc146818-time.h>
#include <asm/msc01_ic.h>
#include <asm/mips-boards/generic.h>
#include <asm/mips-boards/prom.h>
#include <asm/mips-boards/maltaint.h>
unsigned long cpu_khz;
static int mips_cpu_timer_irq;
static int mips_cpu_perf_irq;
extern int cp0_perfcount_irq;
static void mips_timer_dispatch(void)
{
do_IRQ(mips_cpu_timer_irq);
}
static void mips_perf_dispatch(void)
{
do_IRQ(mips_cpu_perf_irq);
}
/*
* Estimate CPU frequency. Sets mips_hpt_frequency as a side-effect
*/
static unsigned int __init estimate_cpu_frequency(void)
{
unsigned int prid = read_c0_prid() & 0xffff00;
unsigned int count;
unsigned long flags;
unsigned int start;
local_irq_save(flags);
/* Start counter exactly on falling edge of update flag */
while (CMOS_READ(RTC_REG_A) & RTC_UIP);
while (!(CMOS_READ(RTC_REG_A) & RTC_UIP));
/* Start r4k counter. */
start = read_c0_count();
/* Read counter exactly on falling edge of update flag */
while (CMOS_READ(RTC_REG_A) & RTC_UIP);
while (!(CMOS_READ(RTC_REG_A) & RTC_UIP));
count = read_c0_count() - start;
/* restore interrupts */
local_irq_restore(flags);
mips_hpt_frequency = count;
if ((prid != (PRID_COMP_MIPS | PRID_IMP_20KC)) &&
(prid != (PRID_COMP_MIPS | PRID_IMP_25KF)))
count *= 2;
count += 5000; /* round */
count -= count%10000;
return count;
}
void read_persistent_clock(struct timespec *ts)
{
ts->tv_sec = mc146818_get_cmos_time();
ts->tv_nsec = 0;
}
static void __init plat_perf_setup(void)
{
#ifdef MSC01E_INT_BASE
if (cpu_has_veic) {
set_vi_handler(MSC01E_INT_PERFCTR, mips_perf_dispatch);
mips_cpu_perf_irq = MSC01E_INT_BASE + MSC01E_INT_PERFCTR;
} else
#endif
if (cp0_perfcount_irq >= 0) {
if (cpu_has_vint)
set_vi_handler(cp0_perfcount_irq, mips_perf_dispatch);
mips_cpu_perf_irq = MIPS_CPU_IRQ_BASE + cp0_perfcount_irq;
#ifdef CONFIG_SMP
irq_set_handler(mips_cpu_perf_irq, handle_percpu_irq);
#endif
}
}
unsigned int __cpuinit get_c0_compare_int(void)
{
#ifdef MSC01E_INT_BASE
if (cpu_has_veic) {
set_vi_handler(MSC01E_INT_CPUCTR, mips_timer_dispatch);
mips_cpu_timer_irq = MSC01E_INT_BASE + MSC01E_INT_CPUCTR;
} else
#endif
{
if (cpu_has_vint)
set_vi_handler(cp0_compare_irq, mips_timer_dispatch);
mips_cpu_timer_irq = MIPS_CPU_IRQ_BASE + cp0_compare_irq;
}
return mips_cpu_timer_irq;
}
void __init plat_time_init(void)
{
unsigned int est_freq;
/* Set Data mode - binary. */
CMOS_WRITE(CMOS_READ(RTC_CONTROL) | RTC_DM_BINARY, RTC_CONTROL);
est_freq = estimate_cpu_frequency();
printk("CPU frequency %d.%02d MHz\n", est_freq/1000000,
(est_freq%1000000)*100/1000000);
cpu_khz = est_freq / 1000;
mips_scroll_message();
#ifdef CONFIG_I8253 /* Only Malta has a PIT */
setup_pit_timer();
#endif
plat_perf_setup();
}
| gpl-2.0 |
justindriggers/android_kernel_glass_glass-1 | drivers/net/wireless/rtlwifi/cam.c | 4816 | 10328 | /******************************************************************************
*
* 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 <linux/export.h>
#include "wifi.h"
#include "cam.h"
void rtl_cam_reset_sec_info(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtlpriv->sec.use_defaultkey = false;
rtlpriv->sec.pairwise_enc_algorithm = NO_ENCRYPTION;
rtlpriv->sec.group_enc_algorithm = NO_ENCRYPTION;
memset(rtlpriv->sec.key_buf, 0, KEY_BUF_SIZE * MAX_KEY_LEN);
memset(rtlpriv->sec.key_len, 0, KEY_BUF_SIZE);
rtlpriv->sec.pairwise_key = NULL;
}
static void rtl_cam_program_entry(struct ieee80211_hw *hw, u32 entry_no,
u8 *mac_addr, u8 *key_cont_128, u16 us_config)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u32 target_command;
u32 target_content = 0;
u8 entry_i;
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD,
"key_cont_128:\n %x:%x:%x:%x:%x:%x\n",
key_cont_128[0], key_cont_128[1],
key_cont_128[2], key_cont_128[3],
key_cont_128[4], key_cont_128[5]);
for (entry_i = 0; entry_i < CAM_CONTENT_COUNT; entry_i++) {
target_command = entry_i + CAM_CONTENT_COUNT * entry_no;
target_command = target_command | BIT(31) | BIT(16);
if (entry_i == 0) {
target_content = (u32) (*(mac_addr + 0)) << 16 |
(u32) (*(mac_addr + 1)) << 24 | (u32) us_config;
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[WCAMI],
target_content);
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[RWCAM],
target_command);
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD, "WRITE %x: %x\n",
rtlpriv->cfg->maps[WCAMI], target_content);
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD,
"The Key ID is %d\n", entry_no);
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD, "WRITE %x: %x\n",
rtlpriv->cfg->maps[RWCAM], target_command);
} else if (entry_i == 1) {
target_content = (u32) (*(mac_addr + 5)) << 24 |
(u32) (*(mac_addr + 4)) << 16 |
(u32) (*(mac_addr + 3)) << 8 |
(u32) (*(mac_addr + 2));
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[WCAMI],
target_content);
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[RWCAM],
target_command);
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD, "WRITE A4: %x\n",
target_content);
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD, "WRITE A0: %x\n",
target_command);
} else {
target_content =
(u32) (*(key_cont_128 + (entry_i * 4 - 8) + 3)) <<
24 | (u32) (*(key_cont_128 + (entry_i * 4 - 8) + 2))
<< 16 |
(u32) (*(key_cont_128 + (entry_i * 4 - 8) + 1)) << 8
| (u32) (*(key_cont_128 + (entry_i * 4 - 8) + 0));
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[WCAMI],
target_content);
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[RWCAM],
target_command);
udelay(100);
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD, "WRITE A4: %x\n",
target_content);
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD, "WRITE A0: %x\n",
target_command);
}
}
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD, "after set key, usconfig:%x\n",
us_config);
}
u8 rtl_cam_add_one_entry(struct ieee80211_hw *hw, u8 *mac_addr,
u32 ul_key_id, u32 ul_entry_idx, u32 ul_enc_alg,
u32 ul_default_key, u8 *key_content)
{
u32 us_config;
struct rtl_priv *rtlpriv = rtl_priv(hw);
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"EntryNo:%x, ulKeyId=%x, ulEncAlg=%x, ulUseDK=%x MacAddr %pM\n",
ul_entry_idx, ul_key_id, ul_enc_alg,
ul_default_key, mac_addr);
if (ul_key_id == TOTAL_CAM_ENTRY) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"<=== ulKeyId exceed!\n");
return 0;
}
if (ul_default_key == 1) {
us_config = CFG_VALID | ((u16) (ul_enc_alg) << 2);
} else {
us_config = CFG_VALID | ((ul_enc_alg) << 2) | ul_key_id;
}
rtl_cam_program_entry(hw, ul_entry_idx, mac_addr,
(u8 *) key_content, us_config);
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG, "<===\n");
return 1;
}
EXPORT_SYMBOL(rtl_cam_add_one_entry);
int rtl_cam_delete_one_entry(struct ieee80211_hw *hw,
u8 *mac_addr, u32 ul_key_id)
{
u32 ul_command;
struct rtl_priv *rtlpriv = rtl_priv(hw);
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG, "key_idx:%d\n", ul_key_id);
ul_command = ul_key_id * CAM_CONTENT_COUNT;
ul_command = ul_command | BIT(31) | BIT(16);
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[WCAMI], 0);
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[RWCAM], ul_command);
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"rtl_cam_delete_one_entry(): WRITE A4: %x\n", 0);
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"rtl_cam_delete_one_entry(): WRITE A0: %x\n", ul_command);
return 0;
}
EXPORT_SYMBOL(rtl_cam_delete_one_entry);
void rtl_cam_reset_all_entry(struct ieee80211_hw *hw)
{
u32 ul_command;
struct rtl_priv *rtlpriv = rtl_priv(hw);
ul_command = BIT(31) | BIT(30);
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[RWCAM], ul_command);
}
EXPORT_SYMBOL(rtl_cam_reset_all_entry);
void rtl_cam_mark_invalid(struct ieee80211_hw *hw, u8 uc_index)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u32 ul_command;
u32 ul_content;
u32 ul_enc_algo = rtlpriv->cfg->maps[SEC_CAM_AES];
switch (rtlpriv->sec.pairwise_enc_algorithm) {
case WEP40_ENCRYPTION:
ul_enc_algo = rtlpriv->cfg->maps[SEC_CAM_WEP40];
break;
case WEP104_ENCRYPTION:
ul_enc_algo = rtlpriv->cfg->maps[SEC_CAM_WEP104];
break;
case TKIP_ENCRYPTION:
ul_enc_algo = rtlpriv->cfg->maps[SEC_CAM_TKIP];
break;
case AESCCMP_ENCRYPTION:
ul_enc_algo = rtlpriv->cfg->maps[SEC_CAM_AES];
break;
default:
ul_enc_algo = rtlpriv->cfg->maps[SEC_CAM_AES];
}
ul_content = (uc_index & 3) | ((u16) (ul_enc_algo) << 2);
ul_content |= BIT(15);
ul_command = CAM_CONTENT_COUNT * uc_index;
ul_command = ul_command | BIT(31) | BIT(16);
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[WCAMI], ul_content);
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[RWCAM], ul_command);
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"rtl_cam_mark_invalid(): WRITE A4: %x\n", ul_content);
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"rtl_cam_mark_invalid(): WRITE A0: %x\n", ul_command);
}
EXPORT_SYMBOL(rtl_cam_mark_invalid);
void rtl_cam_empty_entry(struct ieee80211_hw *hw, u8 uc_index)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u32 ul_command;
u32 ul_content;
u32 ul_encalgo = rtlpriv->cfg->maps[SEC_CAM_AES];
u8 entry_i;
switch (rtlpriv->sec.pairwise_enc_algorithm) {
case WEP40_ENCRYPTION:
ul_encalgo = rtlpriv->cfg->maps[SEC_CAM_WEP40];
break;
case WEP104_ENCRYPTION:
ul_encalgo = rtlpriv->cfg->maps[SEC_CAM_WEP104];
break;
case TKIP_ENCRYPTION:
ul_encalgo = rtlpriv->cfg->maps[SEC_CAM_TKIP];
break;
case AESCCMP_ENCRYPTION:
ul_encalgo = rtlpriv->cfg->maps[SEC_CAM_AES];
break;
default:
ul_encalgo = rtlpriv->cfg->maps[SEC_CAM_AES];
}
for (entry_i = 0; entry_i < CAM_CONTENT_COUNT; entry_i++) {
if (entry_i == 0) {
ul_content =
(uc_index & 0x03) | ((u16) (ul_encalgo) << 2);
ul_content |= BIT(15);
} else {
ul_content = 0;
}
ul_command = CAM_CONTENT_COUNT * uc_index + entry_i;
ul_command = ul_command | BIT(31) | BIT(16);
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[WCAMI], ul_content);
rtl_write_dword(rtlpriv, rtlpriv->cfg->maps[RWCAM], ul_command);
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD,
"rtl_cam_empty_entry(): WRITE A4: %x\n",
ul_content);
RT_TRACE(rtlpriv, COMP_SEC, DBG_LOUD,
"rtl_cam_empty_entry(): WRITE A0: %x\n",
ul_command);
}
}
EXPORT_SYMBOL(rtl_cam_empty_entry);
u8 rtl_cam_get_free_entry(struct ieee80211_hw *hw, u8 *sta_addr)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u32 bitmap = (rtlpriv->sec.hwsec_cam_bitmap) >> 4;
u8 entry_idx = 0;
u8 i, *addr;
if (NULL == sta_addr) {
RT_TRACE(rtlpriv, COMP_SEC, DBG_EMERG, "sta_addr is NULL\n");
return TOTAL_CAM_ENTRY;
}
/* Does STA already exist? */
for (i = 4; i < TOTAL_CAM_ENTRY; i++) {
addr = rtlpriv->sec.hwsec_cam_sta_addr[i];
if (memcmp(addr, sta_addr, ETH_ALEN) == 0)
return i;
}
/* Get a free CAM entry. */
for (entry_idx = 4; entry_idx < TOTAL_CAM_ENTRY; entry_idx++) {
if ((bitmap & BIT(0)) == 0) {
RT_TRACE(rtlpriv, COMP_SEC, DBG_EMERG,
"-----hwsec_cam_bitmap: 0x%x entry_idx=%d\n",
rtlpriv->sec.hwsec_cam_bitmap, entry_idx);
rtlpriv->sec.hwsec_cam_bitmap |= BIT(0) << entry_idx;
memcpy(rtlpriv->sec.hwsec_cam_sta_addr[entry_idx],
sta_addr, ETH_ALEN);
return entry_idx;
}
bitmap = bitmap >> 1;
}
return TOTAL_CAM_ENTRY;
}
EXPORT_SYMBOL(rtl_cam_get_free_entry);
void rtl_cam_del_entry(struct ieee80211_hw *hw, u8 *sta_addr)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u32 bitmap;
u8 i, *addr;
if (NULL == sta_addr) {
RT_TRACE(rtlpriv, COMP_SEC, DBG_EMERG, "sta_addr is NULL\n");
}
if ((sta_addr[0]|sta_addr[1]|sta_addr[2]|sta_addr[3]|\
sta_addr[4]|sta_addr[5]) == 0) {
RT_TRACE(rtlpriv, COMP_SEC, DBG_EMERG,
"sta_addr is 00:00:00:00:00:00\n");
return;
}
/* Does STA already exist? */
for (i = 4; i < TOTAL_CAM_ENTRY; i++) {
addr = rtlpriv->sec.hwsec_cam_sta_addr[i];
bitmap = (rtlpriv->sec.hwsec_cam_bitmap) >> i;
if (((bitmap & BIT(0)) == BIT(0)) &&
(memcmp(addr, sta_addr, ETH_ALEN) == 0)) {
/* Remove from HW Security CAM */
memset(rtlpriv->sec.hwsec_cam_sta_addr[i], 0, ETH_ALEN);
rtlpriv->sec.hwsec_cam_bitmap &= ~(BIT(0) << i);
pr_info("&&&&&&&&&del entry %d\n", i);
}
}
return;
}
EXPORT_SYMBOL(rtl_cam_del_entry);
| gpl-2.0 |
curbthepain/android_kernel_htc_a11chl | drivers/net/ethernet/intel/e100.c | 4816 | 92986 | /*******************************************************************************
Intel PRO/100 Linux driver
Copyright(c) 1999 - 2006 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
Linux NICS <linux.nics@intel.com>
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
/*
* e100.c: Intel(R) PRO/100 ethernet driver
*
* (Re)written 2003 by scott.feldman@intel.com. Based loosely on
* original e100 driver, but better described as a munging of
* e100, e1000, eepro100, tg3, 8139cp, and other drivers.
*
* References:
* Intel 8255x 10/100 Mbps Ethernet Controller Family,
* Open Source Software Developers Manual,
* http://sourceforge.net/projects/e1000
*
*
* Theory of Operation
*
* I. General
*
* The driver supports Intel(R) 10/100 Mbps PCI Fast Ethernet
* controller family, which includes the 82557, 82558, 82559, 82550,
* 82551, and 82562 devices. 82558 and greater controllers
* integrate the Intel 82555 PHY. The controllers are used in
* server and client network interface cards, as well as in
* LAN-On-Motherboard (LOM), CardBus, MiniPCI, and ICHx
* configurations. 8255x supports a 32-bit linear addressing
* mode and operates at 33Mhz PCI clock rate.
*
* II. Driver Operation
*
* Memory-mapped mode is used exclusively to access the device's
* shared-memory structure, the Control/Status Registers (CSR). All
* setup, configuration, and control of the device, including queuing
* of Tx, Rx, and configuration commands is through the CSR.
* cmd_lock serializes accesses to the CSR command register. cb_lock
* protects the shared Command Block List (CBL).
*
* 8255x is highly MII-compliant and all access to the PHY go
* through the Management Data Interface (MDI). Consequently, the
* driver leverages the mii.c library shared with other MII-compliant
* devices.
*
* Big- and Little-Endian byte order as well as 32- and 64-bit
* archs are supported. Weak-ordered memory and non-cache-coherent
* archs are supported.
*
* III. Transmit
*
* A Tx skb is mapped and hangs off of a TCB. TCBs are linked
* together in a fixed-size ring (CBL) thus forming the flexible mode
* memory structure. A TCB marked with the suspend-bit indicates
* the end of the ring. The last TCB processed suspends the
* controller, and the controller can be restarted by issue a CU
* resume command to continue from the suspend point, or a CU start
* command to start at a given position in the ring.
*
* Non-Tx commands (config, multicast setup, etc) are linked
* into the CBL ring along with Tx commands. The common structure
* used for both Tx and non-Tx commands is the Command Block (CB).
*
* cb_to_use is the next CB to use for queuing a command; cb_to_clean
* is the next CB to check for completion; cb_to_send is the first
* CB to start on in case of a previous failure to resume. CB clean
* up happens in interrupt context in response to a CU interrupt.
* cbs_avail keeps track of number of free CB resources available.
*
* Hardware padding of short packets to minimum packet size is
* enabled. 82557 pads with 7Eh, while the later controllers pad
* with 00h.
*
* IV. Receive
*
* The Receive Frame Area (RFA) comprises a ring of Receive Frame
* Descriptors (RFD) + data buffer, thus forming the simplified mode
* memory structure. Rx skbs are allocated to contain both the RFD
* and the data buffer, but the RFD is pulled off before the skb is
* indicated. The data buffer is aligned such that encapsulated
* protocol headers are u32-aligned. Since the RFD is part of the
* mapped shared memory, and completion status is contained within
* the RFD, the RFD must be dma_sync'ed to maintain a consistent
* view from software and hardware.
*
* In order to keep updates to the RFD link field from colliding with
* hardware writes to mark packets complete, we use the feature that
* hardware will not write to a size 0 descriptor and mark the previous
* packet as end-of-list (EL). After updating the link, we remove EL
* and only then restore the size such that hardware may use the
* previous-to-end RFD.
*
* Under typical operation, the receive unit (RU) is start once,
* and the controller happily fills RFDs as frames arrive. If
* replacement RFDs cannot be allocated, or the RU goes non-active,
* the RU must be restarted. Frame arrival generates an interrupt,
* and Rx indication and re-allocation happen in the same context,
* therefore no locking is required. A software-generated interrupt
* is generated from the watchdog to recover from a failed allocation
* scenario where all Rx resources have been indicated and none re-
* placed.
*
* V. Miscellaneous
*
* VLAN offloading of tagging, stripping and filtering is not
* supported, but driver will accommodate the extra 4-byte VLAN tag
* for processing by upper layers. Tx/Rx Checksum offloading is not
* supported. Tx Scatter/Gather is not supported. Jumbo Frames is
* not supported (hardware limitation).
*
* MagicPacket(tm) WoL support is enabled/disabled via ethtool.
*
* Thanks to JC (jchapman@katalix.com) for helping with
* testing/troubleshooting the development driver.
*
* TODO:
* o several entry points race with dev->close
* o check for tx-no-resources/stop Q races with tx clean/wake Q
*
* FIXES:
* 2005/12/02 - Michael O'Donnell <Michael.ODonnell at stratus dot com>
* - Stratus87247: protect MDI control register manipulations
* 2009/06/01 - Andreas Mohr <andi at lisas dot de>
* - add clean lowlevel I/O emulation for cards with MII-lacking PHYs
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/hardirq.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/dma-mapping.h>
#include <linux/dmapool.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/mii.h>
#include <linux/if_vlan.h>
#include <linux/skbuff.h>
#include <linux/ethtool.h>
#include <linux/string.h>
#include <linux/firmware.h>
#include <linux/rtnetlink.h>
#include <asm/unaligned.h>
#define DRV_NAME "e100"
#define DRV_EXT "-NAPI"
#define DRV_VERSION "3.5.24-k2"DRV_EXT
#define DRV_DESCRIPTION "Intel(R) PRO/100 Network Driver"
#define DRV_COPYRIGHT "Copyright(c) 1999-2006 Intel Corporation"
#define E100_WATCHDOG_PERIOD (2 * HZ)
#define E100_NAPI_WEIGHT 16
#define FIRMWARE_D101M "e100/d101m_ucode.bin"
#define FIRMWARE_D101S "e100/d101s_ucode.bin"
#define FIRMWARE_D102E "e100/d102e_ucode.bin"
MODULE_DESCRIPTION(DRV_DESCRIPTION);
MODULE_AUTHOR(DRV_COPYRIGHT);
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
MODULE_FIRMWARE(FIRMWARE_D101M);
MODULE_FIRMWARE(FIRMWARE_D101S);
MODULE_FIRMWARE(FIRMWARE_D102E);
static int debug = 3;
static int eeprom_bad_csum_allow = 0;
static int use_io = 0;
module_param(debug, int, 0);
module_param(eeprom_bad_csum_allow, int, 0);
module_param(use_io, int, 0);
MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all)");
MODULE_PARM_DESC(eeprom_bad_csum_allow, "Allow bad eeprom checksums");
MODULE_PARM_DESC(use_io, "Force use of i/o access mode");
#define INTEL_8255X_ETHERNET_DEVICE(device_id, ich) {\
PCI_VENDOR_ID_INTEL, device_id, PCI_ANY_ID, PCI_ANY_ID, \
PCI_CLASS_NETWORK_ETHERNET << 8, 0xFFFF00, ich }
static DEFINE_PCI_DEVICE_TABLE(e100_id_table) = {
INTEL_8255X_ETHERNET_DEVICE(0x1029, 0),
INTEL_8255X_ETHERNET_DEVICE(0x1030, 0),
INTEL_8255X_ETHERNET_DEVICE(0x1031, 3),
INTEL_8255X_ETHERNET_DEVICE(0x1032, 3),
INTEL_8255X_ETHERNET_DEVICE(0x1033, 3),
INTEL_8255X_ETHERNET_DEVICE(0x1034, 3),
INTEL_8255X_ETHERNET_DEVICE(0x1038, 3),
INTEL_8255X_ETHERNET_DEVICE(0x1039, 4),
INTEL_8255X_ETHERNET_DEVICE(0x103A, 4),
INTEL_8255X_ETHERNET_DEVICE(0x103B, 4),
INTEL_8255X_ETHERNET_DEVICE(0x103C, 4),
INTEL_8255X_ETHERNET_DEVICE(0x103D, 4),
INTEL_8255X_ETHERNET_DEVICE(0x103E, 4),
INTEL_8255X_ETHERNET_DEVICE(0x1050, 5),
INTEL_8255X_ETHERNET_DEVICE(0x1051, 5),
INTEL_8255X_ETHERNET_DEVICE(0x1052, 5),
INTEL_8255X_ETHERNET_DEVICE(0x1053, 5),
INTEL_8255X_ETHERNET_DEVICE(0x1054, 5),
INTEL_8255X_ETHERNET_DEVICE(0x1055, 5),
INTEL_8255X_ETHERNET_DEVICE(0x1056, 5),
INTEL_8255X_ETHERNET_DEVICE(0x1057, 5),
INTEL_8255X_ETHERNET_DEVICE(0x1059, 0),
INTEL_8255X_ETHERNET_DEVICE(0x1064, 6),
INTEL_8255X_ETHERNET_DEVICE(0x1065, 6),
INTEL_8255X_ETHERNET_DEVICE(0x1066, 6),
INTEL_8255X_ETHERNET_DEVICE(0x1067, 6),
INTEL_8255X_ETHERNET_DEVICE(0x1068, 6),
INTEL_8255X_ETHERNET_DEVICE(0x1069, 6),
INTEL_8255X_ETHERNET_DEVICE(0x106A, 6),
INTEL_8255X_ETHERNET_DEVICE(0x106B, 6),
INTEL_8255X_ETHERNET_DEVICE(0x1091, 7),
INTEL_8255X_ETHERNET_DEVICE(0x1092, 7),
INTEL_8255X_ETHERNET_DEVICE(0x1093, 7),
INTEL_8255X_ETHERNET_DEVICE(0x1094, 7),
INTEL_8255X_ETHERNET_DEVICE(0x1095, 7),
INTEL_8255X_ETHERNET_DEVICE(0x10fe, 7),
INTEL_8255X_ETHERNET_DEVICE(0x1209, 0),
INTEL_8255X_ETHERNET_DEVICE(0x1229, 0),
INTEL_8255X_ETHERNET_DEVICE(0x2449, 2),
INTEL_8255X_ETHERNET_DEVICE(0x2459, 2),
INTEL_8255X_ETHERNET_DEVICE(0x245D, 2),
INTEL_8255X_ETHERNET_DEVICE(0x27DC, 7),
{ 0, }
};
MODULE_DEVICE_TABLE(pci, e100_id_table);
enum mac {
mac_82557_D100_A = 0,
mac_82557_D100_B = 1,
mac_82557_D100_C = 2,
mac_82558_D101_A4 = 4,
mac_82558_D101_B0 = 5,
mac_82559_D101M = 8,
mac_82559_D101S = 9,
mac_82550_D102 = 12,
mac_82550_D102_C = 13,
mac_82551_E = 14,
mac_82551_F = 15,
mac_82551_10 = 16,
mac_unknown = 0xFF,
};
enum phy {
phy_100a = 0x000003E0,
phy_100c = 0x035002A8,
phy_82555_tx = 0x015002A8,
phy_nsc_tx = 0x5C002000,
phy_82562_et = 0x033002A8,
phy_82562_em = 0x032002A8,
phy_82562_ek = 0x031002A8,
phy_82562_eh = 0x017002A8,
phy_82552_v = 0xd061004d,
phy_unknown = 0xFFFFFFFF,
};
/* CSR (Control/Status Registers) */
struct csr {
struct {
u8 status;
u8 stat_ack;
u8 cmd_lo;
u8 cmd_hi;
u32 gen_ptr;
} scb;
u32 port;
u16 flash_ctrl;
u8 eeprom_ctrl_lo;
u8 eeprom_ctrl_hi;
u32 mdi_ctrl;
u32 rx_dma_count;
};
enum scb_status {
rus_no_res = 0x08,
rus_ready = 0x10,
rus_mask = 0x3C,
};
enum ru_state {
RU_SUSPENDED = 0,
RU_RUNNING = 1,
RU_UNINITIALIZED = -1,
};
enum scb_stat_ack {
stat_ack_not_ours = 0x00,
stat_ack_sw_gen = 0x04,
stat_ack_rnr = 0x10,
stat_ack_cu_idle = 0x20,
stat_ack_frame_rx = 0x40,
stat_ack_cu_cmd_done = 0x80,
stat_ack_not_present = 0xFF,
stat_ack_rx = (stat_ack_sw_gen | stat_ack_rnr | stat_ack_frame_rx),
stat_ack_tx = (stat_ack_cu_idle | stat_ack_cu_cmd_done),
};
enum scb_cmd_hi {
irq_mask_none = 0x00,
irq_mask_all = 0x01,
irq_sw_gen = 0x02,
};
enum scb_cmd_lo {
cuc_nop = 0x00,
ruc_start = 0x01,
ruc_load_base = 0x06,
cuc_start = 0x10,
cuc_resume = 0x20,
cuc_dump_addr = 0x40,
cuc_dump_stats = 0x50,
cuc_load_base = 0x60,
cuc_dump_reset = 0x70,
};
enum cuc_dump {
cuc_dump_complete = 0x0000A005,
cuc_dump_reset_complete = 0x0000A007,
};
enum port {
software_reset = 0x0000,
selftest = 0x0001,
selective_reset = 0x0002,
};
enum eeprom_ctrl_lo {
eesk = 0x01,
eecs = 0x02,
eedi = 0x04,
eedo = 0x08,
};
enum mdi_ctrl {
mdi_write = 0x04000000,
mdi_read = 0x08000000,
mdi_ready = 0x10000000,
};
enum eeprom_op {
op_write = 0x05,
op_read = 0x06,
op_ewds = 0x10,
op_ewen = 0x13,
};
enum eeprom_offsets {
eeprom_cnfg_mdix = 0x03,
eeprom_phy_iface = 0x06,
eeprom_id = 0x0A,
eeprom_config_asf = 0x0D,
eeprom_smbus_addr = 0x90,
};
enum eeprom_cnfg_mdix {
eeprom_mdix_enabled = 0x0080,
};
enum eeprom_phy_iface {
NoSuchPhy = 0,
I82553AB,
I82553C,
I82503,
DP83840,
S80C240,
S80C24,
I82555,
DP83840A = 10,
};
enum eeprom_id {
eeprom_id_wol = 0x0020,
};
enum eeprom_config_asf {
eeprom_asf = 0x8000,
eeprom_gcl = 0x4000,
};
enum cb_status {
cb_complete = 0x8000,
cb_ok = 0x2000,
};
/**
* cb_command - Command Block flags
* @cb_tx_nc: 0: controler does CRC (normal), 1: CRC from skb memory
*/
enum cb_command {
cb_nop = 0x0000,
cb_iaaddr = 0x0001,
cb_config = 0x0002,
cb_multi = 0x0003,
cb_tx = 0x0004,
cb_ucode = 0x0005,
cb_dump = 0x0006,
cb_tx_sf = 0x0008,
cb_tx_nc = 0x0010,
cb_cid = 0x1f00,
cb_i = 0x2000,
cb_s = 0x4000,
cb_el = 0x8000,
};
struct rfd {
__le16 status;
__le16 command;
__le32 link;
__le32 rbd;
__le16 actual_size;
__le16 size;
};
struct rx {
struct rx *next, *prev;
struct sk_buff *skb;
dma_addr_t dma_addr;
};
#if defined(__BIG_ENDIAN_BITFIELD)
#define X(a,b) b,a
#else
#define X(a,b) a,b
#endif
struct config {
/*0*/ u8 X(byte_count:6, pad0:2);
/*1*/ u8 X(X(rx_fifo_limit:4, tx_fifo_limit:3), pad1:1);
/*2*/ u8 adaptive_ifs;
/*3*/ u8 X(X(X(X(mwi_enable:1, type_enable:1), read_align_enable:1),
term_write_cache_line:1), pad3:4);
/*4*/ u8 X(rx_dma_max_count:7, pad4:1);
/*5*/ u8 X(tx_dma_max_count:7, dma_max_count_enable:1);
/*6*/ u8 X(X(X(X(X(X(X(late_scb_update:1, direct_rx_dma:1),
tno_intr:1), cna_intr:1), standard_tcb:1), standard_stat_counter:1),
rx_save_overruns : 1), rx_save_bad_frames : 1);
/*7*/ u8 X(X(X(X(X(rx_discard_short_frames:1, tx_underrun_retry:2),
pad7:2), rx_extended_rfd:1), tx_two_frames_in_fifo:1),
tx_dynamic_tbd:1);
/*8*/ u8 X(X(mii_mode:1, pad8:6), csma_disabled:1);
/*9*/ u8 X(X(X(X(X(rx_tcpudp_checksum:1, pad9:3), vlan_arp_tco:1),
link_status_wake:1), arp_wake:1), mcmatch_wake:1);
/*10*/ u8 X(X(X(pad10:3, no_source_addr_insertion:1), preamble_length:2),
loopback:2);
/*11*/ u8 X(linear_priority:3, pad11:5);
/*12*/ u8 X(X(linear_priority_mode:1, pad12:3), ifs:4);
/*13*/ u8 ip_addr_lo;
/*14*/ u8 ip_addr_hi;
/*15*/ u8 X(X(X(X(X(X(X(promiscuous_mode:1, broadcast_disabled:1),
wait_after_win:1), pad15_1:1), ignore_ul_bit:1), crc_16_bit:1),
pad15_2:1), crs_or_cdt:1);
/*16*/ u8 fc_delay_lo;
/*17*/ u8 fc_delay_hi;
/*18*/ u8 X(X(X(X(X(rx_stripping:1, tx_padding:1), rx_crc_transfer:1),
rx_long_ok:1), fc_priority_threshold:3), pad18:1);
/*19*/ u8 X(X(X(X(X(X(X(addr_wake:1, magic_packet_disable:1),
fc_disable:1), fc_restop:1), fc_restart:1), fc_reject:1),
full_duplex_force:1), full_duplex_pin:1);
/*20*/ u8 X(X(X(pad20_1:5, fc_priority_location:1), multi_ia:1), pad20_2:1);
/*21*/ u8 X(X(pad21_1:3, multicast_all:1), pad21_2:4);
/*22*/ u8 X(X(rx_d102_mode:1, rx_vlan_drop:1), pad22:6);
u8 pad_d102[9];
};
#define E100_MAX_MULTICAST_ADDRS 64
struct multi {
__le16 count;
u8 addr[E100_MAX_MULTICAST_ADDRS * ETH_ALEN + 2/*pad*/];
};
/* Important: keep total struct u32-aligned */
#define UCODE_SIZE 134
struct cb {
__le16 status;
__le16 command;
__le32 link;
union {
u8 iaaddr[ETH_ALEN];
__le32 ucode[UCODE_SIZE];
struct config config;
struct multi multi;
struct {
u32 tbd_array;
u16 tcb_byte_count;
u8 threshold;
u8 tbd_count;
struct {
__le32 buf_addr;
__le16 size;
u16 eol;
} tbd;
} tcb;
__le32 dump_buffer_addr;
} u;
struct cb *next, *prev;
dma_addr_t dma_addr;
struct sk_buff *skb;
};
enum loopback {
lb_none = 0, lb_mac = 1, lb_phy = 3,
};
struct stats {
__le32 tx_good_frames, tx_max_collisions, tx_late_collisions,
tx_underruns, tx_lost_crs, tx_deferred, tx_single_collisions,
tx_multiple_collisions, tx_total_collisions;
__le32 rx_good_frames, rx_crc_errors, rx_alignment_errors,
rx_resource_errors, rx_overrun_errors, rx_cdt_errors,
rx_short_frame_errors;
__le32 fc_xmt_pause, fc_rcv_pause, fc_rcv_unsupported;
__le16 xmt_tco_frames, rcv_tco_frames;
__le32 complete;
};
struct mem {
struct {
u32 signature;
u32 result;
} selftest;
struct stats stats;
u8 dump_buf[596];
};
struct param_range {
u32 min;
u32 max;
u32 count;
};
struct params {
struct param_range rfds;
struct param_range cbs;
};
struct nic {
/* Begin: frequently used values: keep adjacent for cache effect */
u32 msg_enable ____cacheline_aligned;
struct net_device *netdev;
struct pci_dev *pdev;
u16 (*mdio_ctrl)(struct nic *nic, u32 addr, u32 dir, u32 reg, u16 data);
struct rx *rxs ____cacheline_aligned;
struct rx *rx_to_use;
struct rx *rx_to_clean;
struct rfd blank_rfd;
enum ru_state ru_running;
spinlock_t cb_lock ____cacheline_aligned;
spinlock_t cmd_lock;
struct csr __iomem *csr;
enum scb_cmd_lo cuc_cmd;
unsigned int cbs_avail;
struct napi_struct napi;
struct cb *cbs;
struct cb *cb_to_use;
struct cb *cb_to_send;
struct cb *cb_to_clean;
__le16 tx_command;
/* End: frequently used values: keep adjacent for cache effect */
enum {
ich = (1 << 0),
promiscuous = (1 << 1),
multicast_all = (1 << 2),
wol_magic = (1 << 3),
ich_10h_workaround = (1 << 4),
} flags ____cacheline_aligned;
enum mac mac;
enum phy phy;
struct params params;
struct timer_list watchdog;
struct mii_if_info mii;
struct work_struct tx_timeout_task;
enum loopback loopback;
struct mem *mem;
dma_addr_t dma_addr;
struct pci_pool *cbs_pool;
dma_addr_t cbs_dma_addr;
u8 adaptive_ifs;
u8 tx_threshold;
u32 tx_frames;
u32 tx_collisions;
u32 tx_deferred;
u32 tx_single_collisions;
u32 tx_multiple_collisions;
u32 tx_fc_pause;
u32 tx_tco_frames;
u32 rx_fc_pause;
u32 rx_fc_unsupported;
u32 rx_tco_frames;
u32 rx_short_frame_errors;
u32 rx_over_length_errors;
u16 eeprom_wc;
__le16 eeprom[256];
spinlock_t mdio_lock;
const struct firmware *fw;
};
static inline void e100_write_flush(struct nic *nic)
{
/* Flush previous PCI writes through intermediate bridges
* by doing a benign read */
(void)ioread8(&nic->csr->scb.status);
}
static void e100_enable_irq(struct nic *nic)
{
unsigned long flags;
spin_lock_irqsave(&nic->cmd_lock, flags);
iowrite8(irq_mask_none, &nic->csr->scb.cmd_hi);
e100_write_flush(nic);
spin_unlock_irqrestore(&nic->cmd_lock, flags);
}
static void e100_disable_irq(struct nic *nic)
{
unsigned long flags;
spin_lock_irqsave(&nic->cmd_lock, flags);
iowrite8(irq_mask_all, &nic->csr->scb.cmd_hi);
e100_write_flush(nic);
spin_unlock_irqrestore(&nic->cmd_lock, flags);
}
static void e100_hw_reset(struct nic *nic)
{
/* Put CU and RU into idle with a selective reset to get
* device off of PCI bus */
iowrite32(selective_reset, &nic->csr->port);
e100_write_flush(nic); udelay(20);
/* Now fully reset device */
iowrite32(software_reset, &nic->csr->port);
e100_write_flush(nic); udelay(20);
/* Mask off our interrupt line - it's unmasked after reset */
e100_disable_irq(nic);
}
static int e100_self_test(struct nic *nic)
{
u32 dma_addr = nic->dma_addr + offsetof(struct mem, selftest);
/* Passing the self-test is a pretty good indication
* that the device can DMA to/from host memory */
nic->mem->selftest.signature = 0;
nic->mem->selftest.result = 0xFFFFFFFF;
iowrite32(selftest | dma_addr, &nic->csr->port);
e100_write_flush(nic);
/* Wait 10 msec for self-test to complete */
msleep(10);
/* Interrupts are enabled after self-test */
e100_disable_irq(nic);
/* Check results of self-test */
if (nic->mem->selftest.result != 0) {
netif_err(nic, hw, nic->netdev,
"Self-test failed: result=0x%08X\n",
nic->mem->selftest.result);
return -ETIMEDOUT;
}
if (nic->mem->selftest.signature == 0) {
netif_err(nic, hw, nic->netdev, "Self-test failed: timed out\n");
return -ETIMEDOUT;
}
return 0;
}
static void e100_eeprom_write(struct nic *nic, u16 addr_len, u16 addr, __le16 data)
{
u32 cmd_addr_data[3];
u8 ctrl;
int i, j;
/* Three cmds: write/erase enable, write data, write/erase disable */
cmd_addr_data[0] = op_ewen << (addr_len - 2);
cmd_addr_data[1] = (((op_write << addr_len) | addr) << 16) |
le16_to_cpu(data);
cmd_addr_data[2] = op_ewds << (addr_len - 2);
/* Bit-bang cmds to write word to eeprom */
for (j = 0; j < 3; j++) {
/* Chip select */
iowrite8(eecs | eesk, &nic->csr->eeprom_ctrl_lo);
e100_write_flush(nic); udelay(4);
for (i = 31; i >= 0; i--) {
ctrl = (cmd_addr_data[j] & (1 << i)) ?
eecs | eedi : eecs;
iowrite8(ctrl, &nic->csr->eeprom_ctrl_lo);
e100_write_flush(nic); udelay(4);
iowrite8(ctrl | eesk, &nic->csr->eeprom_ctrl_lo);
e100_write_flush(nic); udelay(4);
}
/* Wait 10 msec for cmd to complete */
msleep(10);
/* Chip deselect */
iowrite8(0, &nic->csr->eeprom_ctrl_lo);
e100_write_flush(nic); udelay(4);
}
};
/* General technique stolen from the eepro100 driver - very clever */
static __le16 e100_eeprom_read(struct nic *nic, u16 *addr_len, u16 addr)
{
u32 cmd_addr_data;
u16 data = 0;
u8 ctrl;
int i;
cmd_addr_data = ((op_read << *addr_len) | addr) << 16;
/* Chip select */
iowrite8(eecs | eesk, &nic->csr->eeprom_ctrl_lo);
e100_write_flush(nic); udelay(4);
/* Bit-bang to read word from eeprom */
for (i = 31; i >= 0; i--) {
ctrl = (cmd_addr_data & (1 << i)) ? eecs | eedi : eecs;
iowrite8(ctrl, &nic->csr->eeprom_ctrl_lo);
e100_write_flush(nic); udelay(4);
iowrite8(ctrl | eesk, &nic->csr->eeprom_ctrl_lo);
e100_write_flush(nic); udelay(4);
/* Eeprom drives a dummy zero to EEDO after receiving
* complete address. Use this to adjust addr_len. */
ctrl = ioread8(&nic->csr->eeprom_ctrl_lo);
if (!(ctrl & eedo) && i > 16) {
*addr_len -= (i - 16);
i = 17;
}
data = (data << 1) | (ctrl & eedo ? 1 : 0);
}
/* Chip deselect */
iowrite8(0, &nic->csr->eeprom_ctrl_lo);
e100_write_flush(nic); udelay(4);
return cpu_to_le16(data);
};
/* Load entire EEPROM image into driver cache and validate checksum */
static int e100_eeprom_load(struct nic *nic)
{
u16 addr, addr_len = 8, checksum = 0;
/* Try reading with an 8-bit addr len to discover actual addr len */
e100_eeprom_read(nic, &addr_len, 0);
nic->eeprom_wc = 1 << addr_len;
for (addr = 0; addr < nic->eeprom_wc; addr++) {
nic->eeprom[addr] = e100_eeprom_read(nic, &addr_len, addr);
if (addr < nic->eeprom_wc - 1)
checksum += le16_to_cpu(nic->eeprom[addr]);
}
/* The checksum, stored in the last word, is calculated such that
* the sum of words should be 0xBABA */
if (cpu_to_le16(0xBABA - checksum) != nic->eeprom[nic->eeprom_wc - 1]) {
netif_err(nic, probe, nic->netdev, "EEPROM corrupted\n");
if (!eeprom_bad_csum_allow)
return -EAGAIN;
}
return 0;
}
/* Save (portion of) driver EEPROM cache to device and update checksum */
static int e100_eeprom_save(struct nic *nic, u16 start, u16 count)
{
u16 addr, addr_len = 8, checksum = 0;
/* Try reading with an 8-bit addr len to discover actual addr len */
e100_eeprom_read(nic, &addr_len, 0);
nic->eeprom_wc = 1 << addr_len;
if (start + count >= nic->eeprom_wc)
return -EINVAL;
for (addr = start; addr < start + count; addr++)
e100_eeprom_write(nic, addr_len, addr, nic->eeprom[addr]);
/* The checksum, stored in the last word, is calculated such that
* the sum of words should be 0xBABA */
for (addr = 0; addr < nic->eeprom_wc - 1; addr++)
checksum += le16_to_cpu(nic->eeprom[addr]);
nic->eeprom[nic->eeprom_wc - 1] = cpu_to_le16(0xBABA - checksum);
e100_eeprom_write(nic, addr_len, nic->eeprom_wc - 1,
nic->eeprom[nic->eeprom_wc - 1]);
return 0;
}
#define E100_WAIT_SCB_TIMEOUT 20000 /* we might have to wait 100ms!!! */
#define E100_WAIT_SCB_FAST 20 /* delay like the old code */
static int e100_exec_cmd(struct nic *nic, u8 cmd, dma_addr_t dma_addr)
{
unsigned long flags;
unsigned int i;
int err = 0;
spin_lock_irqsave(&nic->cmd_lock, flags);
/* Previous command is accepted when SCB clears */
for (i = 0; i < E100_WAIT_SCB_TIMEOUT; i++) {
if (likely(!ioread8(&nic->csr->scb.cmd_lo)))
break;
cpu_relax();
if (unlikely(i > E100_WAIT_SCB_FAST))
udelay(5);
}
if (unlikely(i == E100_WAIT_SCB_TIMEOUT)) {
err = -EAGAIN;
goto err_unlock;
}
if (unlikely(cmd != cuc_resume))
iowrite32(dma_addr, &nic->csr->scb.gen_ptr);
iowrite8(cmd, &nic->csr->scb.cmd_lo);
err_unlock:
spin_unlock_irqrestore(&nic->cmd_lock, flags);
return err;
}
static int e100_exec_cb(struct nic *nic, struct sk_buff *skb,
void (*cb_prepare)(struct nic *, struct cb *, struct sk_buff *))
{
struct cb *cb;
unsigned long flags;
int err = 0;
spin_lock_irqsave(&nic->cb_lock, flags);
if (unlikely(!nic->cbs_avail)) {
err = -ENOMEM;
goto err_unlock;
}
cb = nic->cb_to_use;
nic->cb_to_use = cb->next;
nic->cbs_avail--;
cb->skb = skb;
if (unlikely(!nic->cbs_avail))
err = -ENOSPC;
cb_prepare(nic, cb, skb);
/* Order is important otherwise we'll be in a race with h/w:
* set S-bit in current first, then clear S-bit in previous. */
cb->command |= cpu_to_le16(cb_s);
wmb();
cb->prev->command &= cpu_to_le16(~cb_s);
while (nic->cb_to_send != nic->cb_to_use) {
if (unlikely(e100_exec_cmd(nic, nic->cuc_cmd,
nic->cb_to_send->dma_addr))) {
/* Ok, here's where things get sticky. It's
* possible that we can't schedule the command
* because the controller is too busy, so
* let's just queue the command and try again
* when another command is scheduled. */
if (err == -ENOSPC) {
//request a reset
schedule_work(&nic->tx_timeout_task);
}
break;
} else {
nic->cuc_cmd = cuc_resume;
nic->cb_to_send = nic->cb_to_send->next;
}
}
err_unlock:
spin_unlock_irqrestore(&nic->cb_lock, flags);
return err;
}
static int mdio_read(struct net_device *netdev, int addr, int reg)
{
struct nic *nic = netdev_priv(netdev);
return nic->mdio_ctrl(nic, addr, mdi_read, reg, 0);
}
static void mdio_write(struct net_device *netdev, int addr, int reg, int data)
{
struct nic *nic = netdev_priv(netdev);
nic->mdio_ctrl(nic, addr, mdi_write, reg, data);
}
/* the standard mdio_ctrl() function for usual MII-compliant hardware */
static u16 mdio_ctrl_hw(struct nic *nic, u32 addr, u32 dir, u32 reg, u16 data)
{
u32 data_out = 0;
unsigned int i;
unsigned long flags;
/*
* Stratus87247: we shouldn't be writing the MDI control
* register until the Ready bit shows True. Also, since
* manipulation of the MDI control registers is a multi-step
* procedure it should be done under lock.
*/
spin_lock_irqsave(&nic->mdio_lock, flags);
for (i = 100; i; --i) {
if (ioread32(&nic->csr->mdi_ctrl) & mdi_ready)
break;
udelay(20);
}
if (unlikely(!i)) {
netdev_err(nic->netdev, "e100.mdio_ctrl won't go Ready\n");
spin_unlock_irqrestore(&nic->mdio_lock, flags);
return 0; /* No way to indicate timeout error */
}
iowrite32((reg << 16) | (addr << 21) | dir | data, &nic->csr->mdi_ctrl);
for (i = 0; i < 100; i++) {
udelay(20);
if ((data_out = ioread32(&nic->csr->mdi_ctrl)) & mdi_ready)
break;
}
spin_unlock_irqrestore(&nic->mdio_lock, flags);
netif_printk(nic, hw, KERN_DEBUG, nic->netdev,
"%s:addr=%d, reg=%d, data_in=0x%04X, data_out=0x%04X\n",
dir == mdi_read ? "READ" : "WRITE",
addr, reg, data, data_out);
return (u16)data_out;
}
/* slightly tweaked mdio_ctrl() function for phy_82552_v specifics */
static u16 mdio_ctrl_phy_82552_v(struct nic *nic,
u32 addr,
u32 dir,
u32 reg,
u16 data)
{
if ((reg == MII_BMCR) && (dir == mdi_write)) {
if (data & (BMCR_ANRESTART | BMCR_ANENABLE)) {
u16 advert = mdio_read(nic->netdev, nic->mii.phy_id,
MII_ADVERTISE);
/*
* Workaround Si issue where sometimes the part will not
* autoneg to 100Mbps even when advertised.
*/
if (advert & ADVERTISE_100FULL)
data |= BMCR_SPEED100 | BMCR_FULLDPLX;
else if (advert & ADVERTISE_100HALF)
data |= BMCR_SPEED100;
}
}
return mdio_ctrl_hw(nic, addr, dir, reg, data);
}
/* Fully software-emulated mdio_ctrl() function for cards without
* MII-compliant PHYs.
* For now, this is mainly geared towards 80c24 support; in case of further
* requirements for other types (i82503, ...?) either extend this mechanism
* or split it, whichever is cleaner.
*/
static u16 mdio_ctrl_phy_mii_emulated(struct nic *nic,
u32 addr,
u32 dir,
u32 reg,
u16 data)
{
/* might need to allocate a netdev_priv'ed register array eventually
* to be able to record state changes, but for now
* some fully hardcoded register handling ought to be ok I guess. */
if (dir == mdi_read) {
switch (reg) {
case MII_BMCR:
/* Auto-negotiation, right? */
return BMCR_ANENABLE |
BMCR_FULLDPLX;
case MII_BMSR:
return BMSR_LSTATUS /* for mii_link_ok() */ |
BMSR_ANEGCAPABLE |
BMSR_10FULL;
case MII_ADVERTISE:
/* 80c24 is a "combo card" PHY, right? */
return ADVERTISE_10HALF |
ADVERTISE_10FULL;
default:
netif_printk(nic, hw, KERN_DEBUG, nic->netdev,
"%s:addr=%d, reg=%d, data=0x%04X: unimplemented emulation!\n",
dir == mdi_read ? "READ" : "WRITE",
addr, reg, data);
return 0xFFFF;
}
} else {
switch (reg) {
default:
netif_printk(nic, hw, KERN_DEBUG, nic->netdev,
"%s:addr=%d, reg=%d, data=0x%04X: unimplemented emulation!\n",
dir == mdi_read ? "READ" : "WRITE",
addr, reg, data);
return 0xFFFF;
}
}
}
static inline int e100_phy_supports_mii(struct nic *nic)
{
/* for now, just check it by comparing whether we
are using MII software emulation.
*/
return (nic->mdio_ctrl != mdio_ctrl_phy_mii_emulated);
}
static void e100_get_defaults(struct nic *nic)
{
struct param_range rfds = { .min = 16, .max = 256, .count = 256 };
struct param_range cbs = { .min = 64, .max = 256, .count = 128 };
/* MAC type is encoded as rev ID; exception: ICH is treated as 82559 */
nic->mac = (nic->flags & ich) ? mac_82559_D101M : nic->pdev->revision;
if (nic->mac == mac_unknown)
nic->mac = mac_82557_D100_A;
nic->params.rfds = rfds;
nic->params.cbs = cbs;
/* Quadwords to DMA into FIFO before starting frame transmit */
nic->tx_threshold = 0xE0;
/* no interrupt for every tx completion, delay = 256us if not 557 */
nic->tx_command = cpu_to_le16(cb_tx | cb_tx_sf |
((nic->mac >= mac_82558_D101_A4) ? cb_cid : cb_i));
/* Template for a freshly allocated RFD */
nic->blank_rfd.command = 0;
nic->blank_rfd.rbd = cpu_to_le32(0xFFFFFFFF);
nic->blank_rfd.size = cpu_to_le16(VLAN_ETH_FRAME_LEN + ETH_FCS_LEN);
/* MII setup */
nic->mii.phy_id_mask = 0x1F;
nic->mii.reg_num_mask = 0x1F;
nic->mii.dev = nic->netdev;
nic->mii.mdio_read = mdio_read;
nic->mii.mdio_write = mdio_write;
}
static void e100_configure(struct nic *nic, struct cb *cb, struct sk_buff *skb)
{
struct config *config = &cb->u.config;
u8 *c = (u8 *)config;
struct net_device *netdev = nic->netdev;
cb->command = cpu_to_le16(cb_config);
memset(config, 0, sizeof(struct config));
config->byte_count = 0x16; /* bytes in this struct */
config->rx_fifo_limit = 0x8; /* bytes in FIFO before DMA */
config->direct_rx_dma = 0x1; /* reserved */
config->standard_tcb = 0x1; /* 1=standard, 0=extended */
config->standard_stat_counter = 0x1; /* 1=standard, 0=extended */
config->rx_discard_short_frames = 0x1; /* 1=discard, 0=pass */
config->tx_underrun_retry = 0x3; /* # of underrun retries */
if (e100_phy_supports_mii(nic))
config->mii_mode = 1; /* 1=MII mode, 0=i82503 mode */
config->pad10 = 0x6;
config->no_source_addr_insertion = 0x1; /* 1=no, 0=yes */
config->preamble_length = 0x2; /* 0=1, 1=3, 2=7, 3=15 bytes */
config->ifs = 0x6; /* x16 = inter frame spacing */
config->ip_addr_hi = 0xF2; /* ARP IP filter - not used */
config->pad15_1 = 0x1;
config->pad15_2 = 0x1;
config->crs_or_cdt = 0x0; /* 0=CRS only, 1=CRS or CDT */
config->fc_delay_hi = 0x40; /* time delay for fc frame */
config->tx_padding = 0x1; /* 1=pad short frames */
config->fc_priority_threshold = 0x7; /* 7=priority fc disabled */
config->pad18 = 0x1;
config->full_duplex_pin = 0x1; /* 1=examine FDX# pin */
config->pad20_1 = 0x1F;
config->fc_priority_location = 0x1; /* 1=byte#31, 0=byte#19 */
config->pad21_1 = 0x5;
config->adaptive_ifs = nic->adaptive_ifs;
config->loopback = nic->loopback;
if (nic->mii.force_media && nic->mii.full_duplex)
config->full_duplex_force = 0x1; /* 1=force, 0=auto */
if (nic->flags & promiscuous || nic->loopback) {
config->rx_save_bad_frames = 0x1; /* 1=save, 0=discard */
config->rx_discard_short_frames = 0x0; /* 1=discard, 0=save */
config->promiscuous_mode = 0x1; /* 1=on, 0=off */
}
if (unlikely(netdev->features & NETIF_F_RXFCS))
config->rx_crc_transfer = 0x1; /* 1=save, 0=discard */
if (nic->flags & multicast_all)
config->multicast_all = 0x1; /* 1=accept, 0=no */
/* disable WoL when up */
if (netif_running(nic->netdev) || !(nic->flags & wol_magic))
config->magic_packet_disable = 0x1; /* 1=off, 0=on */
if (nic->mac >= mac_82558_D101_A4) {
config->fc_disable = 0x1; /* 1=Tx fc off, 0=Tx fc on */
config->mwi_enable = 0x1; /* 1=enable, 0=disable */
config->standard_tcb = 0x0; /* 1=standard, 0=extended */
config->rx_long_ok = 0x1; /* 1=VLANs ok, 0=standard */
if (nic->mac >= mac_82559_D101M) {
config->tno_intr = 0x1; /* TCO stats enable */
/* Enable TCO in extended config */
if (nic->mac >= mac_82551_10) {
config->byte_count = 0x20; /* extended bytes */
config->rx_d102_mode = 0x1; /* GMRC for TCO */
}
} else {
config->standard_stat_counter = 0x0;
}
}
if (netdev->features & NETIF_F_RXALL) {
config->rx_save_overruns = 0x1; /* 1=save, 0=discard */
config->rx_save_bad_frames = 0x1; /* 1=save, 0=discard */
config->rx_discard_short_frames = 0x0; /* 1=discard, 0=save */
}
netif_printk(nic, hw, KERN_DEBUG, nic->netdev,
"[00-07]=%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X\n",
c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7]);
netif_printk(nic, hw, KERN_DEBUG, nic->netdev,
"[08-15]=%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X\n",
c[8], c[9], c[10], c[11], c[12], c[13], c[14], c[15]);
netif_printk(nic, hw, KERN_DEBUG, nic->netdev,
"[16-23]=%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X\n",
c[16], c[17], c[18], c[19], c[20], c[21], c[22], c[23]);
}
/*************************************************************************
* CPUSaver parameters
*
* All CPUSaver parameters are 16-bit literals that are part of a
* "move immediate value" instruction. By changing the value of
* the literal in the instruction before the code is loaded, the
* driver can change the algorithm.
*
* INTDELAY - This loads the dead-man timer with its initial value.
* When this timer expires the interrupt is asserted, and the
* timer is reset each time a new packet is received. (see
* BUNDLEMAX below to set the limit on number of chained packets)
* The current default is 0x600 or 1536. Experiments show that
* the value should probably stay within the 0x200 - 0x1000.
*
* BUNDLEMAX -
* This sets the maximum number of frames that will be bundled. In
* some situations, such as the TCP windowing algorithm, it may be
* better to limit the growth of the bundle size than let it go as
* high as it can, because that could cause too much added latency.
* The default is six, because this is the number of packets in the
* default TCP window size. A value of 1 would make CPUSaver indicate
* an interrupt for every frame received. If you do not want to put
* a limit on the bundle size, set this value to xFFFF.
*
* BUNDLESMALL -
* This contains a bit-mask describing the minimum size frame that
* will be bundled. The default masks the lower 7 bits, which means
* that any frame less than 128 bytes in length will not be bundled,
* but will instead immediately generate an interrupt. This does
* not affect the current bundle in any way. Any frame that is 128
* bytes or large will be bundled normally. This feature is meant
* to provide immediate indication of ACK frames in a TCP environment.
* Customers were seeing poor performance when a machine with CPUSaver
* enabled was sending but not receiving. The delay introduced when
* the ACKs were received was enough to reduce total throughput, because
* the sender would sit idle until the ACK was finally seen.
*
* The current default is 0xFF80, which masks out the lower 7 bits.
* This means that any frame which is x7F (127) bytes or smaller
* will cause an immediate interrupt. Because this value must be a
* bit mask, there are only a few valid values that can be used. To
* turn this feature off, the driver can write the value xFFFF to the
* lower word of this instruction (in the same way that the other
* parameters are used). Likewise, a value of 0xF800 (2047) would
* cause an interrupt to be generated for every frame, because all
* standard Ethernet frames are <= 2047 bytes in length.
*************************************************************************/
/* if you wish to disable the ucode functionality, while maintaining the
* workarounds it provides, set the following defines to:
* BUNDLESMALL 0
* BUNDLEMAX 1
* INTDELAY 1
*/
#define BUNDLESMALL 1
#define BUNDLEMAX (u16)6
#define INTDELAY (u16)1536 /* 0x600 */
/* Initialize firmware */
static const struct firmware *e100_request_firmware(struct nic *nic)
{
const char *fw_name;
const struct firmware *fw = nic->fw;
u8 timer, bundle, min_size;
int err = 0;
/* do not load u-code for ICH devices */
if (nic->flags & ich)
return NULL;
/* Search for ucode match against h/w revision */
if (nic->mac == mac_82559_D101M)
fw_name = FIRMWARE_D101M;
else if (nic->mac == mac_82559_D101S)
fw_name = FIRMWARE_D101S;
else if (nic->mac == mac_82551_F || nic->mac == mac_82551_10)
fw_name = FIRMWARE_D102E;
else /* No ucode on other devices */
return NULL;
/* If the firmware has not previously been loaded, request a pointer
* to it. If it was previously loaded, we are reinitializing the
* adapter, possibly in a resume from hibernate, in which case
* request_firmware() cannot be used.
*/
if (!fw)
err = request_firmware(&fw, fw_name, &nic->pdev->dev);
if (err) {
netif_err(nic, probe, nic->netdev,
"Failed to load firmware \"%s\": %d\n",
fw_name, err);
return ERR_PTR(err);
}
/* Firmware should be precisely UCODE_SIZE (words) plus three bytes
indicating the offsets for BUNDLESMALL, BUNDLEMAX, INTDELAY */
if (fw->size != UCODE_SIZE * 4 + 3) {
netif_err(nic, probe, nic->netdev,
"Firmware \"%s\" has wrong size %zu\n",
fw_name, fw->size);
release_firmware(fw);
return ERR_PTR(-EINVAL);
}
/* Read timer, bundle and min_size from end of firmware blob */
timer = fw->data[UCODE_SIZE * 4];
bundle = fw->data[UCODE_SIZE * 4 + 1];
min_size = fw->data[UCODE_SIZE * 4 + 2];
if (timer >= UCODE_SIZE || bundle >= UCODE_SIZE ||
min_size >= UCODE_SIZE) {
netif_err(nic, probe, nic->netdev,
"\"%s\" has bogus offset values (0x%x,0x%x,0x%x)\n",
fw_name, timer, bundle, min_size);
release_firmware(fw);
return ERR_PTR(-EINVAL);
}
/* OK, firmware is validated and ready to use. Save a pointer
* to it in the nic */
nic->fw = fw;
return fw;
}
static void e100_setup_ucode(struct nic *nic, struct cb *cb,
struct sk_buff *skb)
{
const struct firmware *fw = (void *)skb;
u8 timer, bundle, min_size;
/* It's not a real skb; we just abused the fact that e100_exec_cb
will pass it through to here... */
cb->skb = NULL;
/* firmware is stored as little endian already */
memcpy(cb->u.ucode, fw->data, UCODE_SIZE * 4);
/* Read timer, bundle and min_size from end of firmware blob */
timer = fw->data[UCODE_SIZE * 4];
bundle = fw->data[UCODE_SIZE * 4 + 1];
min_size = fw->data[UCODE_SIZE * 4 + 2];
/* Insert user-tunable settings in cb->u.ucode */
cb->u.ucode[timer] &= cpu_to_le32(0xFFFF0000);
cb->u.ucode[timer] |= cpu_to_le32(INTDELAY);
cb->u.ucode[bundle] &= cpu_to_le32(0xFFFF0000);
cb->u.ucode[bundle] |= cpu_to_le32(BUNDLEMAX);
cb->u.ucode[min_size] &= cpu_to_le32(0xFFFF0000);
cb->u.ucode[min_size] |= cpu_to_le32((BUNDLESMALL) ? 0xFFFF : 0xFF80);
cb->command = cpu_to_le16(cb_ucode | cb_el);
}
static inline int e100_load_ucode_wait(struct nic *nic)
{
const struct firmware *fw;
int err = 0, counter = 50;
struct cb *cb = nic->cb_to_clean;
fw = e100_request_firmware(nic);
/* If it's NULL, then no ucode is required */
if (!fw || IS_ERR(fw))
return PTR_ERR(fw);
if ((err = e100_exec_cb(nic, (void *)fw, e100_setup_ucode)))
netif_err(nic, probe, nic->netdev,
"ucode cmd failed with error %d\n", err);
/* must restart cuc */
nic->cuc_cmd = cuc_start;
/* wait for completion */
e100_write_flush(nic);
udelay(10);
/* wait for possibly (ouch) 500ms */
while (!(cb->status & cpu_to_le16(cb_complete))) {
msleep(10);
if (!--counter) break;
}
/* ack any interrupts, something could have been set */
iowrite8(~0, &nic->csr->scb.stat_ack);
/* if the command failed, or is not OK, notify and return */
if (!counter || !(cb->status & cpu_to_le16(cb_ok))) {
netif_err(nic, probe, nic->netdev, "ucode load failed\n");
err = -EPERM;
}
return err;
}
static void e100_setup_iaaddr(struct nic *nic, struct cb *cb,
struct sk_buff *skb)
{
cb->command = cpu_to_le16(cb_iaaddr);
memcpy(cb->u.iaaddr, nic->netdev->dev_addr, ETH_ALEN);
}
static void e100_dump(struct nic *nic, struct cb *cb, struct sk_buff *skb)
{
cb->command = cpu_to_le16(cb_dump);
cb->u.dump_buffer_addr = cpu_to_le32(nic->dma_addr +
offsetof(struct mem, dump_buf));
}
static int e100_phy_check_without_mii(struct nic *nic)
{
u8 phy_type;
int without_mii;
phy_type = (nic->eeprom[eeprom_phy_iface] >> 8) & 0x0f;
switch (phy_type) {
case NoSuchPhy: /* Non-MII PHY; UNTESTED! */
case I82503: /* Non-MII PHY; UNTESTED! */
case S80C24: /* Non-MII PHY; tested and working */
/* paragraph from the FreeBSD driver, "FXP_PHY_80C24":
* The Seeq 80c24 AutoDUPLEX(tm) Ethernet Interface Adapter
* doesn't have a programming interface of any sort. The
* media is sensed automatically based on how the link partner
* is configured. This is, in essence, manual configuration.
*/
netif_info(nic, probe, nic->netdev,
"found MII-less i82503 or 80c24 or other PHY\n");
nic->mdio_ctrl = mdio_ctrl_phy_mii_emulated;
nic->mii.phy_id = 0; /* is this ok for an MII-less PHY? */
/* these might be needed for certain MII-less cards...
* nic->flags |= ich;
* nic->flags |= ich_10h_workaround; */
without_mii = 1;
break;
default:
without_mii = 0;
break;
}
return without_mii;
}
#define NCONFIG_AUTO_SWITCH 0x0080
#define MII_NSC_CONG MII_RESV1
#define NSC_CONG_ENABLE 0x0100
#define NSC_CONG_TXREADY 0x0400
#define ADVERTISE_FC_SUPPORTED 0x0400
static int e100_phy_init(struct nic *nic)
{
struct net_device *netdev = nic->netdev;
u32 addr;
u16 bmcr, stat, id_lo, id_hi, cong;
/* Discover phy addr by searching addrs in order {1,0,2,..., 31} */
for (addr = 0; addr < 32; addr++) {
nic->mii.phy_id = (addr == 0) ? 1 : (addr == 1) ? 0 : addr;
bmcr = mdio_read(netdev, nic->mii.phy_id, MII_BMCR);
stat = mdio_read(netdev, nic->mii.phy_id, MII_BMSR);
stat = mdio_read(netdev, nic->mii.phy_id, MII_BMSR);
if (!((bmcr == 0xFFFF) || ((stat == 0) && (bmcr == 0))))
break;
}
if (addr == 32) {
/* uhoh, no PHY detected: check whether we seem to be some
* weird, rare variant which is *known* to not have any MII.
* But do this AFTER MII checking only, since this does
* lookup of EEPROM values which may easily be unreliable. */
if (e100_phy_check_without_mii(nic))
return 0; /* simply return and hope for the best */
else {
/* for unknown cases log a fatal error */
netif_err(nic, hw, nic->netdev,
"Failed to locate any known PHY, aborting\n");
return -EAGAIN;
}
} else
netif_printk(nic, hw, KERN_DEBUG, nic->netdev,
"phy_addr = %d\n", nic->mii.phy_id);
/* Get phy ID */
id_lo = mdio_read(netdev, nic->mii.phy_id, MII_PHYSID1);
id_hi = mdio_read(netdev, nic->mii.phy_id, MII_PHYSID2);
nic->phy = (u32)id_hi << 16 | (u32)id_lo;
netif_printk(nic, hw, KERN_DEBUG, nic->netdev,
"phy ID = 0x%08X\n", nic->phy);
/* Select the phy and isolate the rest */
for (addr = 0; addr < 32; addr++) {
if (addr != nic->mii.phy_id) {
mdio_write(netdev, addr, MII_BMCR, BMCR_ISOLATE);
} else if (nic->phy != phy_82552_v) {
bmcr = mdio_read(netdev, addr, MII_BMCR);
mdio_write(netdev, addr, MII_BMCR,
bmcr & ~BMCR_ISOLATE);
}
}
/*
* Workaround for 82552:
* Clear the ISOLATE bit on selected phy_id last (mirrored on all
* other phy_id's) using bmcr value from addr discovery loop above.
*/
if (nic->phy == phy_82552_v)
mdio_write(netdev, nic->mii.phy_id, MII_BMCR,
bmcr & ~BMCR_ISOLATE);
/* Handle National tx phys */
#define NCS_PHY_MODEL_MASK 0xFFF0FFFF
if ((nic->phy & NCS_PHY_MODEL_MASK) == phy_nsc_tx) {
/* Disable congestion control */
cong = mdio_read(netdev, nic->mii.phy_id, MII_NSC_CONG);
cong |= NSC_CONG_TXREADY;
cong &= ~NSC_CONG_ENABLE;
mdio_write(netdev, nic->mii.phy_id, MII_NSC_CONG, cong);
}
if (nic->phy == phy_82552_v) {
u16 advert = mdio_read(netdev, nic->mii.phy_id, MII_ADVERTISE);
/* assign special tweaked mdio_ctrl() function */
nic->mdio_ctrl = mdio_ctrl_phy_82552_v;
/* Workaround Si not advertising flow-control during autoneg */
advert |= ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM;
mdio_write(netdev, nic->mii.phy_id, MII_ADVERTISE, advert);
/* Reset for the above changes to take effect */
bmcr = mdio_read(netdev, nic->mii.phy_id, MII_BMCR);
bmcr |= BMCR_RESET;
mdio_write(netdev, nic->mii.phy_id, MII_BMCR, bmcr);
} else if ((nic->mac >= mac_82550_D102) || ((nic->flags & ich) &&
(mdio_read(netdev, nic->mii.phy_id, MII_TPISTATUS) & 0x8000) &&
!(nic->eeprom[eeprom_cnfg_mdix] & eeprom_mdix_enabled))) {
/* enable/disable MDI/MDI-X auto-switching. */
mdio_write(netdev, nic->mii.phy_id, MII_NCONFIG,
nic->mii.force_media ? 0 : NCONFIG_AUTO_SWITCH);
}
return 0;
}
static int e100_hw_init(struct nic *nic)
{
int err = 0;
e100_hw_reset(nic);
netif_err(nic, hw, nic->netdev, "e100_hw_init\n");
if (!in_interrupt() && (err = e100_self_test(nic)))
return err;
if ((err = e100_phy_init(nic)))
return err;
if ((err = e100_exec_cmd(nic, cuc_load_base, 0)))
return err;
if ((err = e100_exec_cmd(nic, ruc_load_base, 0)))
return err;
if ((err = e100_load_ucode_wait(nic)))
return err;
if ((err = e100_exec_cb(nic, NULL, e100_configure)))
return err;
if ((err = e100_exec_cb(nic, NULL, e100_setup_iaaddr)))
return err;
if ((err = e100_exec_cmd(nic, cuc_dump_addr,
nic->dma_addr + offsetof(struct mem, stats))))
return err;
if ((err = e100_exec_cmd(nic, cuc_dump_reset, 0)))
return err;
e100_disable_irq(nic);
return 0;
}
static void e100_multi(struct nic *nic, struct cb *cb, struct sk_buff *skb)
{
struct net_device *netdev = nic->netdev;
struct netdev_hw_addr *ha;
u16 i, count = min(netdev_mc_count(netdev), E100_MAX_MULTICAST_ADDRS);
cb->command = cpu_to_le16(cb_multi);
cb->u.multi.count = cpu_to_le16(count * ETH_ALEN);
i = 0;
netdev_for_each_mc_addr(ha, netdev) {
if (i == count)
break;
memcpy(&cb->u.multi.addr[i++ * ETH_ALEN], &ha->addr,
ETH_ALEN);
}
}
static void e100_set_multicast_list(struct net_device *netdev)
{
struct nic *nic = netdev_priv(netdev);
netif_printk(nic, hw, KERN_DEBUG, nic->netdev,
"mc_count=%d, flags=0x%04X\n",
netdev_mc_count(netdev), netdev->flags);
if (netdev->flags & IFF_PROMISC)
nic->flags |= promiscuous;
else
nic->flags &= ~promiscuous;
if (netdev->flags & IFF_ALLMULTI ||
netdev_mc_count(netdev) > E100_MAX_MULTICAST_ADDRS)
nic->flags |= multicast_all;
else
nic->flags &= ~multicast_all;
e100_exec_cb(nic, NULL, e100_configure);
e100_exec_cb(nic, NULL, e100_multi);
}
static void e100_update_stats(struct nic *nic)
{
struct net_device *dev = nic->netdev;
struct net_device_stats *ns = &dev->stats;
struct stats *s = &nic->mem->stats;
__le32 *complete = (nic->mac < mac_82558_D101_A4) ? &s->fc_xmt_pause :
(nic->mac < mac_82559_D101M) ? (__le32 *)&s->xmt_tco_frames :
&s->complete;
/* Device's stats reporting may take several microseconds to
* complete, so we're always waiting for results of the
* previous command. */
if (*complete == cpu_to_le32(cuc_dump_reset_complete)) {
*complete = 0;
nic->tx_frames = le32_to_cpu(s->tx_good_frames);
nic->tx_collisions = le32_to_cpu(s->tx_total_collisions);
ns->tx_aborted_errors += le32_to_cpu(s->tx_max_collisions);
ns->tx_window_errors += le32_to_cpu(s->tx_late_collisions);
ns->tx_carrier_errors += le32_to_cpu(s->tx_lost_crs);
ns->tx_fifo_errors += le32_to_cpu(s->tx_underruns);
ns->collisions += nic->tx_collisions;
ns->tx_errors += le32_to_cpu(s->tx_max_collisions) +
le32_to_cpu(s->tx_lost_crs);
nic->rx_short_frame_errors +=
le32_to_cpu(s->rx_short_frame_errors);
ns->rx_length_errors = nic->rx_short_frame_errors +
nic->rx_over_length_errors;
ns->rx_crc_errors += le32_to_cpu(s->rx_crc_errors);
ns->rx_frame_errors += le32_to_cpu(s->rx_alignment_errors);
ns->rx_over_errors += le32_to_cpu(s->rx_overrun_errors);
ns->rx_fifo_errors += le32_to_cpu(s->rx_overrun_errors);
ns->rx_missed_errors += le32_to_cpu(s->rx_resource_errors);
ns->rx_errors += le32_to_cpu(s->rx_crc_errors) +
le32_to_cpu(s->rx_alignment_errors) +
le32_to_cpu(s->rx_short_frame_errors) +
le32_to_cpu(s->rx_cdt_errors);
nic->tx_deferred += le32_to_cpu(s->tx_deferred);
nic->tx_single_collisions +=
le32_to_cpu(s->tx_single_collisions);
nic->tx_multiple_collisions +=
le32_to_cpu(s->tx_multiple_collisions);
if (nic->mac >= mac_82558_D101_A4) {
nic->tx_fc_pause += le32_to_cpu(s->fc_xmt_pause);
nic->rx_fc_pause += le32_to_cpu(s->fc_rcv_pause);
nic->rx_fc_unsupported +=
le32_to_cpu(s->fc_rcv_unsupported);
if (nic->mac >= mac_82559_D101M) {
nic->tx_tco_frames +=
le16_to_cpu(s->xmt_tco_frames);
nic->rx_tco_frames +=
le16_to_cpu(s->rcv_tco_frames);
}
}
}
if (e100_exec_cmd(nic, cuc_dump_reset, 0))
netif_printk(nic, tx_err, KERN_DEBUG, nic->netdev,
"exec cuc_dump_reset failed\n");
}
static void e100_adjust_adaptive_ifs(struct nic *nic, int speed, int duplex)
{
/* Adjust inter-frame-spacing (IFS) between two transmits if
* we're getting collisions on a half-duplex connection. */
if (duplex == DUPLEX_HALF) {
u32 prev = nic->adaptive_ifs;
u32 min_frames = (speed == SPEED_100) ? 1000 : 100;
if ((nic->tx_frames / 32 < nic->tx_collisions) &&
(nic->tx_frames > min_frames)) {
if (nic->adaptive_ifs < 60)
nic->adaptive_ifs += 5;
} else if (nic->tx_frames < min_frames) {
if (nic->adaptive_ifs >= 5)
nic->adaptive_ifs -= 5;
}
if (nic->adaptive_ifs != prev)
e100_exec_cb(nic, NULL, e100_configure);
}
}
static void e100_watchdog(unsigned long data)
{
struct nic *nic = (struct nic *)data;
struct ethtool_cmd cmd = { .cmd = ETHTOOL_GSET };
u32 speed;
netif_printk(nic, timer, KERN_DEBUG, nic->netdev,
"right now = %ld\n", jiffies);
/* mii library handles link maintenance tasks */
mii_ethtool_gset(&nic->mii, &cmd);
speed = ethtool_cmd_speed(&cmd);
if (mii_link_ok(&nic->mii) && !netif_carrier_ok(nic->netdev)) {
netdev_info(nic->netdev, "NIC Link is Up %u Mbps %s Duplex\n",
speed == SPEED_100 ? 100 : 10,
cmd.duplex == DUPLEX_FULL ? "Full" : "Half");
} else if (!mii_link_ok(&nic->mii) && netif_carrier_ok(nic->netdev)) {
netdev_info(nic->netdev, "NIC Link is Down\n");
}
mii_check_link(&nic->mii);
/* Software generated interrupt to recover from (rare) Rx
* allocation failure.
* Unfortunately have to use a spinlock to not re-enable interrupts
* accidentally, due to hardware that shares a register between the
* interrupt mask bit and the SW Interrupt generation bit */
spin_lock_irq(&nic->cmd_lock);
iowrite8(ioread8(&nic->csr->scb.cmd_hi) | irq_sw_gen,&nic->csr->scb.cmd_hi);
e100_write_flush(nic);
spin_unlock_irq(&nic->cmd_lock);
e100_update_stats(nic);
e100_adjust_adaptive_ifs(nic, speed, cmd.duplex);
if (nic->mac <= mac_82557_D100_C)
/* Issue a multicast command to workaround a 557 lock up */
e100_set_multicast_list(nic->netdev);
if (nic->flags & ich && speed == SPEED_10 && cmd.duplex == DUPLEX_HALF)
/* Need SW workaround for ICH[x] 10Mbps/half duplex Tx hang. */
nic->flags |= ich_10h_workaround;
else
nic->flags &= ~ich_10h_workaround;
mod_timer(&nic->watchdog,
round_jiffies(jiffies + E100_WATCHDOG_PERIOD));
}
static void e100_xmit_prepare(struct nic *nic, struct cb *cb,
struct sk_buff *skb)
{
cb->command = nic->tx_command;
/*
* Use the last 4 bytes of the SKB payload packet as the CRC, used for
* testing, ie sending frames with bad CRC.
*/
if (unlikely(skb->no_fcs))
cb->command |= __constant_cpu_to_le16(cb_tx_nc);
else
cb->command &= ~__constant_cpu_to_le16(cb_tx_nc);
/* interrupt every 16 packets regardless of delay */
if ((nic->cbs_avail & ~15) == nic->cbs_avail)
cb->command |= cpu_to_le16(cb_i);
cb->u.tcb.tbd_array = cb->dma_addr + offsetof(struct cb, u.tcb.tbd);
cb->u.tcb.tcb_byte_count = 0;
cb->u.tcb.threshold = nic->tx_threshold;
cb->u.tcb.tbd_count = 1;
cb->u.tcb.tbd.buf_addr = cpu_to_le32(pci_map_single(nic->pdev,
skb->data, skb->len, PCI_DMA_TODEVICE));
/* check for mapping failure? */
cb->u.tcb.tbd.size = cpu_to_le16(skb->len);
}
static netdev_tx_t e100_xmit_frame(struct sk_buff *skb,
struct net_device *netdev)
{
struct nic *nic = netdev_priv(netdev);
int err;
if (nic->flags & ich_10h_workaround) {
/* SW workaround for ICH[x] 10Mbps/half duplex Tx hang.
Issue a NOP command followed by a 1us delay before
issuing the Tx command. */
if (e100_exec_cmd(nic, cuc_nop, 0))
netif_printk(nic, tx_err, KERN_DEBUG, nic->netdev,
"exec cuc_nop failed\n");
udelay(1);
}
err = e100_exec_cb(nic, skb, e100_xmit_prepare);
switch (err) {
case -ENOSPC:
/* We queued the skb, but now we're out of space. */
netif_printk(nic, tx_err, KERN_DEBUG, nic->netdev,
"No space for CB\n");
netif_stop_queue(netdev);
break;
case -ENOMEM:
/* This is a hard error - log it. */
netif_printk(nic, tx_err, KERN_DEBUG, nic->netdev,
"Out of Tx resources, returning skb\n");
netif_stop_queue(netdev);
return NETDEV_TX_BUSY;
}
return NETDEV_TX_OK;
}
static int e100_tx_clean(struct nic *nic)
{
struct net_device *dev = nic->netdev;
struct cb *cb;
int tx_cleaned = 0;
spin_lock(&nic->cb_lock);
/* Clean CBs marked complete */
for (cb = nic->cb_to_clean;
cb->status & cpu_to_le16(cb_complete);
cb = nic->cb_to_clean = cb->next) {
rmb(); /* read skb after status */
netif_printk(nic, tx_done, KERN_DEBUG, nic->netdev,
"cb[%d]->status = 0x%04X\n",
(int)(((void*)cb - (void*)nic->cbs)/sizeof(struct cb)),
cb->status);
if (likely(cb->skb != NULL)) {
dev->stats.tx_packets++;
dev->stats.tx_bytes += cb->skb->len;
pci_unmap_single(nic->pdev,
le32_to_cpu(cb->u.tcb.tbd.buf_addr),
le16_to_cpu(cb->u.tcb.tbd.size),
PCI_DMA_TODEVICE);
dev_kfree_skb_any(cb->skb);
cb->skb = NULL;
tx_cleaned = 1;
}
cb->status = 0;
nic->cbs_avail++;
}
spin_unlock(&nic->cb_lock);
/* Recover from running out of Tx resources in xmit_frame */
if (unlikely(tx_cleaned && netif_queue_stopped(nic->netdev)))
netif_wake_queue(nic->netdev);
return tx_cleaned;
}
static void e100_clean_cbs(struct nic *nic)
{
if (nic->cbs) {
while (nic->cbs_avail != nic->params.cbs.count) {
struct cb *cb = nic->cb_to_clean;
if (cb->skb) {
pci_unmap_single(nic->pdev,
le32_to_cpu(cb->u.tcb.tbd.buf_addr),
le16_to_cpu(cb->u.tcb.tbd.size),
PCI_DMA_TODEVICE);
dev_kfree_skb(cb->skb);
}
nic->cb_to_clean = nic->cb_to_clean->next;
nic->cbs_avail++;
}
pci_pool_free(nic->cbs_pool, nic->cbs, nic->cbs_dma_addr);
nic->cbs = NULL;
nic->cbs_avail = 0;
}
nic->cuc_cmd = cuc_start;
nic->cb_to_use = nic->cb_to_send = nic->cb_to_clean =
nic->cbs;
}
static int e100_alloc_cbs(struct nic *nic)
{
struct cb *cb;
unsigned int i, count = nic->params.cbs.count;
nic->cuc_cmd = cuc_start;
nic->cb_to_use = nic->cb_to_send = nic->cb_to_clean = NULL;
nic->cbs_avail = 0;
nic->cbs = pci_pool_alloc(nic->cbs_pool, GFP_KERNEL,
&nic->cbs_dma_addr);
if (!nic->cbs)
return -ENOMEM;
memset(nic->cbs, 0, count * sizeof(struct cb));
for (cb = nic->cbs, i = 0; i < count; cb++, i++) {
cb->next = (i + 1 < count) ? cb + 1 : nic->cbs;
cb->prev = (i == 0) ? nic->cbs + count - 1 : cb - 1;
cb->dma_addr = nic->cbs_dma_addr + i * sizeof(struct cb);
cb->link = cpu_to_le32(nic->cbs_dma_addr +
((i+1) % count) * sizeof(struct cb));
}
nic->cb_to_use = nic->cb_to_send = nic->cb_to_clean = nic->cbs;
nic->cbs_avail = count;
return 0;
}
static inline void e100_start_receiver(struct nic *nic, struct rx *rx)
{
if (!nic->rxs) return;
if (RU_SUSPENDED != nic->ru_running) return;
/* handle init time starts */
if (!rx) rx = nic->rxs;
/* (Re)start RU if suspended or idle and RFA is non-NULL */
if (rx->skb) {
e100_exec_cmd(nic, ruc_start, rx->dma_addr);
nic->ru_running = RU_RUNNING;
}
}
#define RFD_BUF_LEN (sizeof(struct rfd) + VLAN_ETH_FRAME_LEN + ETH_FCS_LEN)
static int e100_rx_alloc_skb(struct nic *nic, struct rx *rx)
{
if (!(rx->skb = netdev_alloc_skb_ip_align(nic->netdev, RFD_BUF_LEN)))
return -ENOMEM;
/* Init, and map the RFD. */
skb_copy_to_linear_data(rx->skb, &nic->blank_rfd, sizeof(struct rfd));
rx->dma_addr = pci_map_single(nic->pdev, rx->skb->data,
RFD_BUF_LEN, PCI_DMA_BIDIRECTIONAL);
if (pci_dma_mapping_error(nic->pdev, rx->dma_addr)) {
dev_kfree_skb_any(rx->skb);
rx->skb = NULL;
rx->dma_addr = 0;
return -ENOMEM;
}
/* Link the RFD to end of RFA by linking previous RFD to
* this one. We are safe to touch the previous RFD because
* it is protected by the before last buffer's el bit being set */
if (rx->prev->skb) {
struct rfd *prev_rfd = (struct rfd *)rx->prev->skb->data;
put_unaligned_le32(rx->dma_addr, &prev_rfd->link);
pci_dma_sync_single_for_device(nic->pdev, rx->prev->dma_addr,
sizeof(struct rfd), PCI_DMA_BIDIRECTIONAL);
}
return 0;
}
static int e100_rx_indicate(struct nic *nic, struct rx *rx,
unsigned int *work_done, unsigned int work_to_do)
{
struct net_device *dev = nic->netdev;
struct sk_buff *skb = rx->skb;
struct rfd *rfd = (struct rfd *)skb->data;
u16 rfd_status, actual_size;
u16 fcs_pad = 0;
if (unlikely(work_done && *work_done >= work_to_do))
return -EAGAIN;
/* Need to sync before taking a peek at cb_complete bit */
pci_dma_sync_single_for_cpu(nic->pdev, rx->dma_addr,
sizeof(struct rfd), PCI_DMA_BIDIRECTIONAL);
rfd_status = le16_to_cpu(rfd->status);
netif_printk(nic, rx_status, KERN_DEBUG, nic->netdev,
"status=0x%04X\n", rfd_status);
rmb(); /* read size after status bit */
/* If data isn't ready, nothing to indicate */
if (unlikely(!(rfd_status & cb_complete))) {
/* If the next buffer has the el bit, but we think the receiver
* is still running, check to see if it really stopped while
* we had interrupts off.
* This allows for a fast restart without re-enabling
* interrupts */
if ((le16_to_cpu(rfd->command) & cb_el) &&
(RU_RUNNING == nic->ru_running))
if (ioread8(&nic->csr->scb.status) & rus_no_res)
nic->ru_running = RU_SUSPENDED;
pci_dma_sync_single_for_device(nic->pdev, rx->dma_addr,
sizeof(struct rfd),
PCI_DMA_FROMDEVICE);
return -ENODATA;
}
/* Get actual data size */
if (unlikely(dev->features & NETIF_F_RXFCS))
fcs_pad = 4;
actual_size = le16_to_cpu(rfd->actual_size) & 0x3FFF;
if (unlikely(actual_size > RFD_BUF_LEN - sizeof(struct rfd)))
actual_size = RFD_BUF_LEN - sizeof(struct rfd);
/* Get data */
pci_unmap_single(nic->pdev, rx->dma_addr,
RFD_BUF_LEN, PCI_DMA_BIDIRECTIONAL);
/* If this buffer has the el bit, but we think the receiver
* is still running, check to see if it really stopped while
* we had interrupts off.
* This allows for a fast restart without re-enabling interrupts.
* This can happen when the RU sees the size change but also sees
* the el bit set. */
if ((le16_to_cpu(rfd->command) & cb_el) &&
(RU_RUNNING == nic->ru_running)) {
if (ioread8(&nic->csr->scb.status) & rus_no_res)
nic->ru_running = RU_SUSPENDED;
}
/* Pull off the RFD and put the actual data (minus eth hdr) */
skb_reserve(skb, sizeof(struct rfd));
skb_put(skb, actual_size);
skb->protocol = eth_type_trans(skb, nic->netdev);
/* If we are receiving all frames, then don't bother
* checking for errors.
*/
if (unlikely(dev->features & NETIF_F_RXALL)) {
if (actual_size > ETH_DATA_LEN + VLAN_ETH_HLEN + fcs_pad)
/* Received oversized frame, but keep it. */
nic->rx_over_length_errors++;
goto process_skb;
}
if (unlikely(!(rfd_status & cb_ok))) {
/* Don't indicate if hardware indicates errors */
dev_kfree_skb_any(skb);
} else if (actual_size > ETH_DATA_LEN + VLAN_ETH_HLEN + fcs_pad) {
/* Don't indicate oversized frames */
nic->rx_over_length_errors++;
dev_kfree_skb_any(skb);
} else {
process_skb:
dev->stats.rx_packets++;
dev->stats.rx_bytes += (actual_size - fcs_pad);
netif_receive_skb(skb);
if (work_done)
(*work_done)++;
}
rx->skb = NULL;
return 0;
}
static void e100_rx_clean(struct nic *nic, unsigned int *work_done,
unsigned int work_to_do)
{
struct rx *rx;
int restart_required = 0, err = 0;
struct rx *old_before_last_rx, *new_before_last_rx;
struct rfd *old_before_last_rfd, *new_before_last_rfd;
/* Indicate newly arrived packets */
for (rx = nic->rx_to_clean; rx->skb; rx = nic->rx_to_clean = rx->next) {
err = e100_rx_indicate(nic, rx, work_done, work_to_do);
/* Hit quota or no more to clean */
if (-EAGAIN == err || -ENODATA == err)
break;
}
/* On EAGAIN, hit quota so have more work to do, restart once
* cleanup is complete.
* Else, are we already rnr? then pay attention!!! this ensures that
* the state machine progression never allows a start with a
* partially cleaned list, avoiding a race between hardware
* and rx_to_clean when in NAPI mode */
if (-EAGAIN != err && RU_SUSPENDED == nic->ru_running)
restart_required = 1;
old_before_last_rx = nic->rx_to_use->prev->prev;
old_before_last_rfd = (struct rfd *)old_before_last_rx->skb->data;
/* Alloc new skbs to refill list */
for (rx = nic->rx_to_use; !rx->skb; rx = nic->rx_to_use = rx->next) {
if (unlikely(e100_rx_alloc_skb(nic, rx)))
break; /* Better luck next time (see watchdog) */
}
new_before_last_rx = nic->rx_to_use->prev->prev;
if (new_before_last_rx != old_before_last_rx) {
/* Set the el-bit on the buffer that is before the last buffer.
* This lets us update the next pointer on the last buffer
* without worrying about hardware touching it.
* We set the size to 0 to prevent hardware from touching this
* buffer.
* When the hardware hits the before last buffer with el-bit
* and size of 0, it will RNR interrupt, the RUS will go into
* the No Resources state. It will not complete nor write to
* this buffer. */
new_before_last_rfd =
(struct rfd *)new_before_last_rx->skb->data;
new_before_last_rfd->size = 0;
new_before_last_rfd->command |= cpu_to_le16(cb_el);
pci_dma_sync_single_for_device(nic->pdev,
new_before_last_rx->dma_addr, sizeof(struct rfd),
PCI_DMA_BIDIRECTIONAL);
/* Now that we have a new stopping point, we can clear the old
* stopping point. We must sync twice to get the proper
* ordering on the hardware side of things. */
old_before_last_rfd->command &= ~cpu_to_le16(cb_el);
pci_dma_sync_single_for_device(nic->pdev,
old_before_last_rx->dma_addr, sizeof(struct rfd),
PCI_DMA_BIDIRECTIONAL);
old_before_last_rfd->size = cpu_to_le16(VLAN_ETH_FRAME_LEN
+ ETH_FCS_LEN);
pci_dma_sync_single_for_device(nic->pdev,
old_before_last_rx->dma_addr, sizeof(struct rfd),
PCI_DMA_BIDIRECTIONAL);
}
if (restart_required) {
// ack the rnr?
iowrite8(stat_ack_rnr, &nic->csr->scb.stat_ack);
e100_start_receiver(nic, nic->rx_to_clean);
if (work_done)
(*work_done)++;
}
}
static void e100_rx_clean_list(struct nic *nic)
{
struct rx *rx;
unsigned int i, count = nic->params.rfds.count;
nic->ru_running = RU_UNINITIALIZED;
if (nic->rxs) {
for (rx = nic->rxs, i = 0; i < count; rx++, i++) {
if (rx->skb) {
pci_unmap_single(nic->pdev, rx->dma_addr,
RFD_BUF_LEN, PCI_DMA_BIDIRECTIONAL);
dev_kfree_skb(rx->skb);
}
}
kfree(nic->rxs);
nic->rxs = NULL;
}
nic->rx_to_use = nic->rx_to_clean = NULL;
}
static int e100_rx_alloc_list(struct nic *nic)
{
struct rx *rx;
unsigned int i, count = nic->params.rfds.count;
struct rfd *before_last;
nic->rx_to_use = nic->rx_to_clean = NULL;
nic->ru_running = RU_UNINITIALIZED;
if (!(nic->rxs = kcalloc(count, sizeof(struct rx), GFP_ATOMIC)))
return -ENOMEM;
for (rx = nic->rxs, i = 0; i < count; rx++, i++) {
rx->next = (i + 1 < count) ? rx + 1 : nic->rxs;
rx->prev = (i == 0) ? nic->rxs + count - 1 : rx - 1;
if (e100_rx_alloc_skb(nic, rx)) {
e100_rx_clean_list(nic);
return -ENOMEM;
}
}
/* Set the el-bit on the buffer that is before the last buffer.
* This lets us update the next pointer on the last buffer without
* worrying about hardware touching it.
* We set the size to 0 to prevent hardware from touching this buffer.
* When the hardware hits the before last buffer with el-bit and size
* of 0, it will RNR interrupt, the RU will go into the No Resources
* state. It will not complete nor write to this buffer. */
rx = nic->rxs->prev->prev;
before_last = (struct rfd *)rx->skb->data;
before_last->command |= cpu_to_le16(cb_el);
before_last->size = 0;
pci_dma_sync_single_for_device(nic->pdev, rx->dma_addr,
sizeof(struct rfd), PCI_DMA_BIDIRECTIONAL);
nic->rx_to_use = nic->rx_to_clean = nic->rxs;
nic->ru_running = RU_SUSPENDED;
return 0;
}
static irqreturn_t e100_intr(int irq, void *dev_id)
{
struct net_device *netdev = dev_id;
struct nic *nic = netdev_priv(netdev);
u8 stat_ack = ioread8(&nic->csr->scb.stat_ack);
netif_printk(nic, intr, KERN_DEBUG, nic->netdev,
"stat_ack = 0x%02X\n", stat_ack);
if (stat_ack == stat_ack_not_ours || /* Not our interrupt */
stat_ack == stat_ack_not_present) /* Hardware is ejected */
return IRQ_NONE;
/* Ack interrupt(s) */
iowrite8(stat_ack, &nic->csr->scb.stat_ack);
/* We hit Receive No Resource (RNR); restart RU after cleaning */
if (stat_ack & stat_ack_rnr)
nic->ru_running = RU_SUSPENDED;
if (likely(napi_schedule_prep(&nic->napi))) {
e100_disable_irq(nic);
__napi_schedule(&nic->napi);
}
return IRQ_HANDLED;
}
static int e100_poll(struct napi_struct *napi, int budget)
{
struct nic *nic = container_of(napi, struct nic, napi);
unsigned int work_done = 0;
e100_rx_clean(nic, &work_done, budget);
e100_tx_clean(nic);
/* If budget not fully consumed, exit the polling mode */
if (work_done < budget) {
napi_complete(napi);
e100_enable_irq(nic);
}
return work_done;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void e100_netpoll(struct net_device *netdev)
{
struct nic *nic = netdev_priv(netdev);
e100_disable_irq(nic);
e100_intr(nic->pdev->irq, netdev);
e100_tx_clean(nic);
e100_enable_irq(nic);
}
#endif
static int e100_set_mac_address(struct net_device *netdev, void *p)
{
struct nic *nic = netdev_priv(netdev);
struct sockaddr *addr = p;
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
memcpy(netdev->dev_addr, addr->sa_data, netdev->addr_len);
e100_exec_cb(nic, NULL, e100_setup_iaaddr);
return 0;
}
static int e100_change_mtu(struct net_device *netdev, int new_mtu)
{
if (new_mtu < ETH_ZLEN || new_mtu > ETH_DATA_LEN)
return -EINVAL;
netdev->mtu = new_mtu;
return 0;
}
static int e100_asf(struct nic *nic)
{
/* ASF can be enabled from eeprom */
return (nic->pdev->device >= 0x1050) && (nic->pdev->device <= 0x1057) &&
(nic->eeprom[eeprom_config_asf] & eeprom_asf) &&
!(nic->eeprom[eeprom_config_asf] & eeprom_gcl) &&
((nic->eeprom[eeprom_smbus_addr] & 0xFF) != 0xFE);
}
static int e100_up(struct nic *nic)
{
int err;
if ((err = e100_rx_alloc_list(nic)))
return err;
if ((err = e100_alloc_cbs(nic)))
goto err_rx_clean_list;
if ((err = e100_hw_init(nic)))
goto err_clean_cbs;
e100_set_multicast_list(nic->netdev);
e100_start_receiver(nic, NULL);
mod_timer(&nic->watchdog, jiffies);
if ((err = request_irq(nic->pdev->irq, e100_intr, IRQF_SHARED,
nic->netdev->name, nic->netdev)))
goto err_no_irq;
netif_wake_queue(nic->netdev);
napi_enable(&nic->napi);
/* enable ints _after_ enabling poll, preventing a race between
* disable ints+schedule */
e100_enable_irq(nic);
return 0;
err_no_irq:
del_timer_sync(&nic->watchdog);
err_clean_cbs:
e100_clean_cbs(nic);
err_rx_clean_list:
e100_rx_clean_list(nic);
return err;
}
static void e100_down(struct nic *nic)
{
/* wait here for poll to complete */
napi_disable(&nic->napi);
netif_stop_queue(nic->netdev);
e100_hw_reset(nic);
free_irq(nic->pdev->irq, nic->netdev);
del_timer_sync(&nic->watchdog);
netif_carrier_off(nic->netdev);
e100_clean_cbs(nic);
e100_rx_clean_list(nic);
}
static void e100_tx_timeout(struct net_device *netdev)
{
struct nic *nic = netdev_priv(netdev);
/* Reset outside of interrupt context, to avoid request_irq
* in interrupt context */
schedule_work(&nic->tx_timeout_task);
}
static void e100_tx_timeout_task(struct work_struct *work)
{
struct nic *nic = container_of(work, struct nic, tx_timeout_task);
struct net_device *netdev = nic->netdev;
netif_printk(nic, tx_err, KERN_DEBUG, nic->netdev,
"scb.status=0x%02X\n", ioread8(&nic->csr->scb.status));
rtnl_lock();
if (netif_running(netdev)) {
e100_down(netdev_priv(netdev));
e100_up(netdev_priv(netdev));
}
rtnl_unlock();
}
static int e100_loopback_test(struct nic *nic, enum loopback loopback_mode)
{
int err;
struct sk_buff *skb;
/* Use driver resources to perform internal MAC or PHY
* loopback test. A single packet is prepared and transmitted
* in loopback mode, and the test passes if the received
* packet compares byte-for-byte to the transmitted packet. */
if ((err = e100_rx_alloc_list(nic)))
return err;
if ((err = e100_alloc_cbs(nic)))
goto err_clean_rx;
/* ICH PHY loopback is broken so do MAC loopback instead */
if (nic->flags & ich && loopback_mode == lb_phy)
loopback_mode = lb_mac;
nic->loopback = loopback_mode;
if ((err = e100_hw_init(nic)))
goto err_loopback_none;
if (loopback_mode == lb_phy)
mdio_write(nic->netdev, nic->mii.phy_id, MII_BMCR,
BMCR_LOOPBACK);
e100_start_receiver(nic, NULL);
if (!(skb = netdev_alloc_skb(nic->netdev, ETH_DATA_LEN))) {
err = -ENOMEM;
goto err_loopback_none;
}
skb_put(skb, ETH_DATA_LEN);
memset(skb->data, 0xFF, ETH_DATA_LEN);
e100_xmit_frame(skb, nic->netdev);
msleep(10);
pci_dma_sync_single_for_cpu(nic->pdev, nic->rx_to_clean->dma_addr,
RFD_BUF_LEN, PCI_DMA_BIDIRECTIONAL);
if (memcmp(nic->rx_to_clean->skb->data + sizeof(struct rfd),
skb->data, ETH_DATA_LEN))
err = -EAGAIN;
err_loopback_none:
mdio_write(nic->netdev, nic->mii.phy_id, MII_BMCR, 0);
nic->loopback = lb_none;
e100_clean_cbs(nic);
e100_hw_reset(nic);
err_clean_rx:
e100_rx_clean_list(nic);
return err;
}
#define MII_LED_CONTROL 0x1B
#define E100_82552_LED_OVERRIDE 0x19
#define E100_82552_LED_ON 0x000F /* LEDTX and LED_RX both on */
#define E100_82552_LED_OFF 0x000A /* LEDTX and LED_RX both off */
static int e100_get_settings(struct net_device *netdev, struct ethtool_cmd *cmd)
{
struct nic *nic = netdev_priv(netdev);
return mii_ethtool_gset(&nic->mii, cmd);
}
static int e100_set_settings(struct net_device *netdev, struct ethtool_cmd *cmd)
{
struct nic *nic = netdev_priv(netdev);
int err;
mdio_write(netdev, nic->mii.phy_id, MII_BMCR, BMCR_RESET);
err = mii_ethtool_sset(&nic->mii, cmd);
e100_exec_cb(nic, NULL, e100_configure);
return err;
}
static void e100_get_drvinfo(struct net_device *netdev,
struct ethtool_drvinfo *info)
{
struct nic *nic = netdev_priv(netdev);
strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
strlcpy(info->version, DRV_VERSION, sizeof(info->version));
strlcpy(info->bus_info, pci_name(nic->pdev),
sizeof(info->bus_info));
}
#define E100_PHY_REGS 0x1C
static int e100_get_regs_len(struct net_device *netdev)
{
struct nic *nic = netdev_priv(netdev);
return 1 + E100_PHY_REGS + sizeof(nic->mem->dump_buf);
}
static void e100_get_regs(struct net_device *netdev,
struct ethtool_regs *regs, void *p)
{
struct nic *nic = netdev_priv(netdev);
u32 *buff = p;
int i;
regs->version = (1 << 24) | nic->pdev->revision;
buff[0] = ioread8(&nic->csr->scb.cmd_hi) << 24 |
ioread8(&nic->csr->scb.cmd_lo) << 16 |
ioread16(&nic->csr->scb.status);
for (i = E100_PHY_REGS; i >= 0; i--)
buff[1 + E100_PHY_REGS - i] =
mdio_read(netdev, nic->mii.phy_id, i);
memset(nic->mem->dump_buf, 0, sizeof(nic->mem->dump_buf));
e100_exec_cb(nic, NULL, e100_dump);
msleep(10);
memcpy(&buff[2 + E100_PHY_REGS], nic->mem->dump_buf,
sizeof(nic->mem->dump_buf));
}
static void e100_get_wol(struct net_device *netdev, struct ethtool_wolinfo *wol)
{
struct nic *nic = netdev_priv(netdev);
wol->supported = (nic->mac >= mac_82558_D101_A4) ? WAKE_MAGIC : 0;
wol->wolopts = (nic->flags & wol_magic) ? WAKE_MAGIC : 0;
}
static int e100_set_wol(struct net_device *netdev, struct ethtool_wolinfo *wol)
{
struct nic *nic = netdev_priv(netdev);
if ((wol->wolopts && wol->wolopts != WAKE_MAGIC) ||
!device_can_wakeup(&nic->pdev->dev))
return -EOPNOTSUPP;
if (wol->wolopts)
nic->flags |= wol_magic;
else
nic->flags &= ~wol_magic;
device_set_wakeup_enable(&nic->pdev->dev, wol->wolopts);
e100_exec_cb(nic, NULL, e100_configure);
return 0;
}
static u32 e100_get_msglevel(struct net_device *netdev)
{
struct nic *nic = netdev_priv(netdev);
return nic->msg_enable;
}
static void e100_set_msglevel(struct net_device *netdev, u32 value)
{
struct nic *nic = netdev_priv(netdev);
nic->msg_enable = value;
}
static int e100_nway_reset(struct net_device *netdev)
{
struct nic *nic = netdev_priv(netdev);
return mii_nway_restart(&nic->mii);
}
static u32 e100_get_link(struct net_device *netdev)
{
struct nic *nic = netdev_priv(netdev);
return mii_link_ok(&nic->mii);
}
static int e100_get_eeprom_len(struct net_device *netdev)
{
struct nic *nic = netdev_priv(netdev);
return nic->eeprom_wc << 1;
}
#define E100_EEPROM_MAGIC 0x1234
static int e100_get_eeprom(struct net_device *netdev,
struct ethtool_eeprom *eeprom, u8 *bytes)
{
struct nic *nic = netdev_priv(netdev);
eeprom->magic = E100_EEPROM_MAGIC;
memcpy(bytes, &((u8 *)nic->eeprom)[eeprom->offset], eeprom->len);
return 0;
}
static int e100_set_eeprom(struct net_device *netdev,
struct ethtool_eeprom *eeprom, u8 *bytes)
{
struct nic *nic = netdev_priv(netdev);
if (eeprom->magic != E100_EEPROM_MAGIC)
return -EINVAL;
memcpy(&((u8 *)nic->eeprom)[eeprom->offset], bytes, eeprom->len);
return e100_eeprom_save(nic, eeprom->offset >> 1,
(eeprom->len >> 1) + 1);
}
static void e100_get_ringparam(struct net_device *netdev,
struct ethtool_ringparam *ring)
{
struct nic *nic = netdev_priv(netdev);
struct param_range *rfds = &nic->params.rfds;
struct param_range *cbs = &nic->params.cbs;
ring->rx_max_pending = rfds->max;
ring->tx_max_pending = cbs->max;
ring->rx_pending = rfds->count;
ring->tx_pending = cbs->count;
}
static int e100_set_ringparam(struct net_device *netdev,
struct ethtool_ringparam *ring)
{
struct nic *nic = netdev_priv(netdev);
struct param_range *rfds = &nic->params.rfds;
struct param_range *cbs = &nic->params.cbs;
if ((ring->rx_mini_pending) || (ring->rx_jumbo_pending))
return -EINVAL;
if (netif_running(netdev))
e100_down(nic);
rfds->count = max(ring->rx_pending, rfds->min);
rfds->count = min(rfds->count, rfds->max);
cbs->count = max(ring->tx_pending, cbs->min);
cbs->count = min(cbs->count, cbs->max);
netif_info(nic, drv, nic->netdev, "Ring Param settings: rx: %d, tx %d\n",
rfds->count, cbs->count);
if (netif_running(netdev))
e100_up(nic);
return 0;
}
static const char e100_gstrings_test[][ETH_GSTRING_LEN] = {
"Link test (on/offline)",
"Eeprom test (on/offline)",
"Self test (offline)",
"Mac loopback (offline)",
"Phy loopback (offline)",
};
#define E100_TEST_LEN ARRAY_SIZE(e100_gstrings_test)
static void e100_diag_test(struct net_device *netdev,
struct ethtool_test *test, u64 *data)
{
struct ethtool_cmd cmd;
struct nic *nic = netdev_priv(netdev);
int i, err;
memset(data, 0, E100_TEST_LEN * sizeof(u64));
data[0] = !mii_link_ok(&nic->mii);
data[1] = e100_eeprom_load(nic);
if (test->flags & ETH_TEST_FL_OFFLINE) {
/* save speed, duplex & autoneg settings */
err = mii_ethtool_gset(&nic->mii, &cmd);
if (netif_running(netdev))
e100_down(nic);
data[2] = e100_self_test(nic);
data[3] = e100_loopback_test(nic, lb_mac);
data[4] = e100_loopback_test(nic, lb_phy);
/* restore speed, duplex & autoneg settings */
err = mii_ethtool_sset(&nic->mii, &cmd);
if (netif_running(netdev))
e100_up(nic);
}
for (i = 0; i < E100_TEST_LEN; i++)
test->flags |= data[i] ? ETH_TEST_FL_FAILED : 0;
msleep_interruptible(4 * 1000);
}
static int e100_set_phys_id(struct net_device *netdev,
enum ethtool_phys_id_state state)
{
struct nic *nic = netdev_priv(netdev);
enum led_state {
led_on = 0x01,
led_off = 0x04,
led_on_559 = 0x05,
led_on_557 = 0x07,
};
u16 led_reg = (nic->phy == phy_82552_v) ? E100_82552_LED_OVERRIDE :
MII_LED_CONTROL;
u16 leds = 0;
switch (state) {
case ETHTOOL_ID_ACTIVE:
return 2;
case ETHTOOL_ID_ON:
leds = (nic->phy == phy_82552_v) ? E100_82552_LED_ON :
(nic->mac < mac_82559_D101M) ? led_on_557 : led_on_559;
break;
case ETHTOOL_ID_OFF:
leds = (nic->phy == phy_82552_v) ? E100_82552_LED_OFF : led_off;
break;
case ETHTOOL_ID_INACTIVE:
break;
}
mdio_write(netdev, nic->mii.phy_id, led_reg, leds);
return 0;
}
static const char e100_gstrings_stats[][ETH_GSTRING_LEN] = {
"rx_packets", "tx_packets", "rx_bytes", "tx_bytes", "rx_errors",
"tx_errors", "rx_dropped", "tx_dropped", "multicast", "collisions",
"rx_length_errors", "rx_over_errors", "rx_crc_errors",
"rx_frame_errors", "rx_fifo_errors", "rx_missed_errors",
"tx_aborted_errors", "tx_carrier_errors", "tx_fifo_errors",
"tx_heartbeat_errors", "tx_window_errors",
/* device-specific stats */
"tx_deferred", "tx_single_collisions", "tx_multi_collisions",
"tx_flow_control_pause", "rx_flow_control_pause",
"rx_flow_control_unsupported", "tx_tco_packets", "rx_tco_packets",
"rx_short_frame_errors", "rx_over_length_errors",
};
#define E100_NET_STATS_LEN 21
#define E100_STATS_LEN ARRAY_SIZE(e100_gstrings_stats)
static int e100_get_sset_count(struct net_device *netdev, int sset)
{
switch (sset) {
case ETH_SS_TEST:
return E100_TEST_LEN;
case ETH_SS_STATS:
return E100_STATS_LEN;
default:
return -EOPNOTSUPP;
}
}
static void e100_get_ethtool_stats(struct net_device *netdev,
struct ethtool_stats *stats, u64 *data)
{
struct nic *nic = netdev_priv(netdev);
int i;
for (i = 0; i < E100_NET_STATS_LEN; i++)
data[i] = ((unsigned long *)&netdev->stats)[i];
data[i++] = nic->tx_deferred;
data[i++] = nic->tx_single_collisions;
data[i++] = nic->tx_multiple_collisions;
data[i++] = nic->tx_fc_pause;
data[i++] = nic->rx_fc_pause;
data[i++] = nic->rx_fc_unsupported;
data[i++] = nic->tx_tco_frames;
data[i++] = nic->rx_tco_frames;
data[i++] = nic->rx_short_frame_errors;
data[i++] = nic->rx_over_length_errors;
}
static void e100_get_strings(struct net_device *netdev, u32 stringset, u8 *data)
{
switch (stringset) {
case ETH_SS_TEST:
memcpy(data, *e100_gstrings_test, sizeof(e100_gstrings_test));
break;
case ETH_SS_STATS:
memcpy(data, *e100_gstrings_stats, sizeof(e100_gstrings_stats));
break;
}
}
static const struct ethtool_ops e100_ethtool_ops = {
.get_settings = e100_get_settings,
.set_settings = e100_set_settings,
.get_drvinfo = e100_get_drvinfo,
.get_regs_len = e100_get_regs_len,
.get_regs = e100_get_regs,
.get_wol = e100_get_wol,
.set_wol = e100_set_wol,
.get_msglevel = e100_get_msglevel,
.set_msglevel = e100_set_msglevel,
.nway_reset = e100_nway_reset,
.get_link = e100_get_link,
.get_eeprom_len = e100_get_eeprom_len,
.get_eeprom = e100_get_eeprom,
.set_eeprom = e100_set_eeprom,
.get_ringparam = e100_get_ringparam,
.set_ringparam = e100_set_ringparam,
.self_test = e100_diag_test,
.get_strings = e100_get_strings,
.set_phys_id = e100_set_phys_id,
.get_ethtool_stats = e100_get_ethtool_stats,
.get_sset_count = e100_get_sset_count,
};
static int e100_do_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
{
struct nic *nic = netdev_priv(netdev);
return generic_mii_ioctl(&nic->mii, if_mii(ifr), cmd, NULL);
}
static int e100_alloc(struct nic *nic)
{
nic->mem = pci_alloc_consistent(nic->pdev, sizeof(struct mem),
&nic->dma_addr);
return nic->mem ? 0 : -ENOMEM;
}
static void e100_free(struct nic *nic)
{
if (nic->mem) {
pci_free_consistent(nic->pdev, sizeof(struct mem),
nic->mem, nic->dma_addr);
nic->mem = NULL;
}
}
static int e100_open(struct net_device *netdev)
{
struct nic *nic = netdev_priv(netdev);
int err = 0;
netif_carrier_off(netdev);
if ((err = e100_up(nic)))
netif_err(nic, ifup, nic->netdev, "Cannot open interface, aborting\n");
return err;
}
static int e100_close(struct net_device *netdev)
{
e100_down(netdev_priv(netdev));
return 0;
}
static int e100_set_features(struct net_device *netdev,
netdev_features_t features)
{
struct nic *nic = netdev_priv(netdev);
netdev_features_t changed = features ^ netdev->features;
if (!(changed & (NETIF_F_RXFCS | NETIF_F_RXALL)))
return 0;
netdev->features = features;
e100_exec_cb(nic, NULL, e100_configure);
return 0;
}
static const struct net_device_ops e100_netdev_ops = {
.ndo_open = e100_open,
.ndo_stop = e100_close,
.ndo_start_xmit = e100_xmit_frame,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_rx_mode = e100_set_multicast_list,
.ndo_set_mac_address = e100_set_mac_address,
.ndo_change_mtu = e100_change_mtu,
.ndo_do_ioctl = e100_do_ioctl,
.ndo_tx_timeout = e100_tx_timeout,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = e100_netpoll,
#endif
.ndo_set_features = e100_set_features,
};
static int __devinit e100_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct net_device *netdev;
struct nic *nic;
int err;
if (!(netdev = alloc_etherdev(sizeof(struct nic))))
return -ENOMEM;
netdev->hw_features |= NETIF_F_RXFCS;
netdev->priv_flags |= IFF_SUPP_NOFCS;
netdev->hw_features |= NETIF_F_RXALL;
netdev->netdev_ops = &e100_netdev_ops;
SET_ETHTOOL_OPS(netdev, &e100_ethtool_ops);
netdev->watchdog_timeo = E100_WATCHDOG_PERIOD;
strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1);
nic = netdev_priv(netdev);
netif_napi_add(netdev, &nic->napi, e100_poll, E100_NAPI_WEIGHT);
nic->netdev = netdev;
nic->pdev = pdev;
nic->msg_enable = (1 << debug) - 1;
nic->mdio_ctrl = mdio_ctrl_hw;
pci_set_drvdata(pdev, netdev);
if ((err = pci_enable_device(pdev))) {
netif_err(nic, probe, nic->netdev, "Cannot enable PCI device, aborting\n");
goto err_out_free_dev;
}
if (!(pci_resource_flags(pdev, 0) & IORESOURCE_MEM)) {
netif_err(nic, probe, nic->netdev, "Cannot find proper PCI device base address, aborting\n");
err = -ENODEV;
goto err_out_disable_pdev;
}
if ((err = pci_request_regions(pdev, DRV_NAME))) {
netif_err(nic, probe, nic->netdev, "Cannot obtain PCI resources, aborting\n");
goto err_out_disable_pdev;
}
if ((err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32)))) {
netif_err(nic, probe, nic->netdev, "No usable DMA configuration, aborting\n");
goto err_out_free_res;
}
SET_NETDEV_DEV(netdev, &pdev->dev);
if (use_io)
netif_info(nic, probe, nic->netdev, "using i/o access mode\n");
nic->csr = pci_iomap(pdev, (use_io ? 1 : 0), sizeof(struct csr));
if (!nic->csr) {
netif_err(nic, probe, nic->netdev, "Cannot map device registers, aborting\n");
err = -ENOMEM;
goto err_out_free_res;
}
if (ent->driver_data)
nic->flags |= ich;
else
nic->flags &= ~ich;
e100_get_defaults(nic);
/* D100 MAC doesn't allow rx of vlan packets with normal MTU */
if (nic->mac < mac_82558_D101_A4)
netdev->features |= NETIF_F_VLAN_CHALLENGED;
/* locks must be initialized before calling hw_reset */
spin_lock_init(&nic->cb_lock);
spin_lock_init(&nic->cmd_lock);
spin_lock_init(&nic->mdio_lock);
/* Reset the device before pci_set_master() in case device is in some
* funky state and has an interrupt pending - hint: we don't have the
* interrupt handler registered yet. */
e100_hw_reset(nic);
pci_set_master(pdev);
init_timer(&nic->watchdog);
nic->watchdog.function = e100_watchdog;
nic->watchdog.data = (unsigned long)nic;
INIT_WORK(&nic->tx_timeout_task, e100_tx_timeout_task);
if ((err = e100_alloc(nic))) {
netif_err(nic, probe, nic->netdev, "Cannot alloc driver memory, aborting\n");
goto err_out_iounmap;
}
if ((err = e100_eeprom_load(nic)))
goto err_out_free;
e100_phy_init(nic);
memcpy(netdev->dev_addr, nic->eeprom, ETH_ALEN);
memcpy(netdev->perm_addr, nic->eeprom, ETH_ALEN);
if (!is_valid_ether_addr(netdev->perm_addr)) {
if (!eeprom_bad_csum_allow) {
netif_err(nic, probe, nic->netdev, "Invalid MAC address from EEPROM, aborting\n");
err = -EAGAIN;
goto err_out_free;
} else {
netif_err(nic, probe, nic->netdev, "Invalid MAC address from EEPROM, you MUST configure one.\n");
}
}
/* Wol magic packet can be enabled from eeprom */
if ((nic->mac >= mac_82558_D101_A4) &&
(nic->eeprom[eeprom_id] & eeprom_id_wol)) {
nic->flags |= wol_magic;
device_set_wakeup_enable(&pdev->dev, true);
}
/* ack any pending wake events, disable PME */
pci_pme_active(pdev, false);
strcpy(netdev->name, "eth%d");
if ((err = register_netdev(netdev))) {
netif_err(nic, probe, nic->netdev, "Cannot register net device, aborting\n");
goto err_out_free;
}
nic->cbs_pool = pci_pool_create(netdev->name,
nic->pdev,
nic->params.cbs.max * sizeof(struct cb),
sizeof(u32),
0);
netif_info(nic, probe, nic->netdev,
"addr 0x%llx, irq %d, MAC addr %pM\n",
(unsigned long long)pci_resource_start(pdev, use_io ? 1 : 0),
pdev->irq, netdev->dev_addr);
return 0;
err_out_free:
e100_free(nic);
err_out_iounmap:
pci_iounmap(pdev, nic->csr);
err_out_free_res:
pci_release_regions(pdev);
err_out_disable_pdev:
pci_disable_device(pdev);
err_out_free_dev:
pci_set_drvdata(pdev, NULL);
free_netdev(netdev);
return err;
}
static void __devexit e100_remove(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
if (netdev) {
struct nic *nic = netdev_priv(netdev);
unregister_netdev(netdev);
e100_free(nic);
pci_iounmap(pdev, nic->csr);
pci_pool_destroy(nic->cbs_pool);
free_netdev(netdev);
pci_release_regions(pdev);
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
}
}
#define E100_82552_SMARTSPEED 0x14 /* SmartSpeed Ctrl register */
#define E100_82552_REV_ANEG 0x0200 /* Reverse auto-negotiation */
#define E100_82552_ANEG_NOW 0x0400 /* Auto-negotiate now */
static void __e100_shutdown(struct pci_dev *pdev, bool *enable_wake)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct nic *nic = netdev_priv(netdev);
if (netif_running(netdev))
e100_down(nic);
netif_device_detach(netdev);
pci_save_state(pdev);
if ((nic->flags & wol_magic) | e100_asf(nic)) {
/* enable reverse auto-negotiation */
if (nic->phy == phy_82552_v) {
u16 smartspeed = mdio_read(netdev, nic->mii.phy_id,
E100_82552_SMARTSPEED);
mdio_write(netdev, nic->mii.phy_id,
E100_82552_SMARTSPEED, smartspeed |
E100_82552_REV_ANEG | E100_82552_ANEG_NOW);
}
*enable_wake = true;
} else {
*enable_wake = false;
}
pci_disable_device(pdev);
}
static int __e100_power_off(struct pci_dev *pdev, bool wake)
{
if (wake)
return pci_prepare_to_sleep(pdev);
pci_wake_from_d3(pdev, false);
pci_set_power_state(pdev, PCI_D3hot);
return 0;
}
#ifdef CONFIG_PM
static int e100_suspend(struct pci_dev *pdev, pm_message_t state)
{
bool wake;
__e100_shutdown(pdev, &wake);
return __e100_power_off(pdev, wake);
}
static int e100_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct nic *nic = netdev_priv(netdev);
pci_set_power_state(pdev, PCI_D0);
pci_restore_state(pdev);
/* ack any pending wake events, disable PME */
pci_enable_wake(pdev, 0, 0);
/* disable reverse auto-negotiation */
if (nic->phy == phy_82552_v) {
u16 smartspeed = mdio_read(netdev, nic->mii.phy_id,
E100_82552_SMARTSPEED);
mdio_write(netdev, nic->mii.phy_id,
E100_82552_SMARTSPEED,
smartspeed & ~(E100_82552_REV_ANEG));
}
netif_device_attach(netdev);
if (netif_running(netdev))
e100_up(nic);
return 0;
}
#endif /* CONFIG_PM */
static void e100_shutdown(struct pci_dev *pdev)
{
bool wake;
__e100_shutdown(pdev, &wake);
if (system_state == SYSTEM_POWER_OFF)
__e100_power_off(pdev, wake);
}
/* ------------------ PCI Error Recovery infrastructure -------------- */
/**
* e100_io_error_detected - called when PCI error is detected.
* @pdev: Pointer to PCI device
* @state: The current pci connection state
*/
static pci_ers_result_t e100_io_error_detected(struct pci_dev *pdev, pci_channel_state_t state)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct nic *nic = netdev_priv(netdev);
netif_device_detach(netdev);
if (state == pci_channel_io_perm_failure)
return PCI_ERS_RESULT_DISCONNECT;
if (netif_running(netdev))
e100_down(nic);
pci_disable_device(pdev);
/* Request a slot reset. */
return PCI_ERS_RESULT_NEED_RESET;
}
/**
* e100_io_slot_reset - called after the pci bus has been reset.
* @pdev: Pointer to PCI device
*
* Restart the card from scratch.
*/
static pci_ers_result_t e100_io_slot_reset(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct nic *nic = netdev_priv(netdev);
if (pci_enable_device(pdev)) {
pr_err("Cannot re-enable PCI device after reset\n");
return PCI_ERS_RESULT_DISCONNECT;
}
pci_set_master(pdev);
/* Only one device per card can do a reset */
if (0 != PCI_FUNC(pdev->devfn))
return PCI_ERS_RESULT_RECOVERED;
e100_hw_reset(nic);
e100_phy_init(nic);
return PCI_ERS_RESULT_RECOVERED;
}
/**
* e100_io_resume - resume normal operations
* @pdev: Pointer to PCI device
*
* Resume normal operations after an error recovery
* sequence has been completed.
*/
static void e100_io_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct nic *nic = netdev_priv(netdev);
/* ack any pending wake events, disable PME */
pci_enable_wake(pdev, 0, 0);
netif_device_attach(netdev);
if (netif_running(netdev)) {
e100_open(netdev);
mod_timer(&nic->watchdog, jiffies);
}
}
static struct pci_error_handlers e100_err_handler = {
.error_detected = e100_io_error_detected,
.slot_reset = e100_io_slot_reset,
.resume = e100_io_resume,
};
static struct pci_driver e100_driver = {
.name = DRV_NAME,
.id_table = e100_id_table,
.probe = e100_probe,
.remove = __devexit_p(e100_remove),
#ifdef CONFIG_PM
/* Power Management hooks */
.suspend = e100_suspend,
.resume = e100_resume,
#endif
.shutdown = e100_shutdown,
.err_handler = &e100_err_handler,
};
static int __init e100_init_module(void)
{
if (((1 << debug) - 1) & NETIF_MSG_DRV) {
pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
pr_info("%s\n", DRV_COPYRIGHT);
}
return pci_register_driver(&e100_driver);
}
static void __exit e100_cleanup_module(void)
{
pci_unregister_driver(&e100_driver);
}
module_init(e100_init_module);
module_exit(e100_cleanup_module);
| gpl-2.0 |
Quarx2k/android_kernel_lge_msm8226 | drivers/input/misc/rb532_button.c | 5072 | 2723 | /*
* Support for the S1 button on Routerboard 532
*
* Copyright (C) 2009 Phil Sutter <n0-1@freewrt.org>
*/
#include <linux/input-polldev.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <asm/mach-rc32434/gpio.h>
#include <asm/mach-rc32434/rb.h>
#define DRV_NAME "rb532-button"
#define RB532_BTN_RATE 100 /* msec */
#define RB532_BTN_KSYM BTN_0
/* The S1 button state is provided by GPIO pin 1. But as this
* pin is also used for uart input as alternate function, the
* operational modes must be switched first:
* 1) disable uart using set_latch_u5()
* 2) turn off alternate function implicitly through
* gpio_direction_input()
* 3) read the GPIO's current value
* 4) undo step 2 by enabling alternate function (in this
* mode the GPIO direction is fixed, so no change needed)
* 5) turn on uart again
* The GPIO value occurs to be inverted, so pin high means
* button is not pressed.
*/
static bool rb532_button_pressed(void)
{
int val;
set_latch_u5(0, LO_FOFF);
gpio_direction_input(GPIO_BTN_S1);
val = gpio_get_value(GPIO_BTN_S1);
rb532_gpio_set_func(GPIO_BTN_S1);
set_latch_u5(LO_FOFF, 0);
return !val;
}
static void rb532_button_poll(struct input_polled_dev *poll_dev)
{
input_report_key(poll_dev->input, RB532_BTN_KSYM,
rb532_button_pressed());
input_sync(poll_dev->input);
}
static int __devinit rb532_button_probe(struct platform_device *pdev)
{
struct input_polled_dev *poll_dev;
int error;
poll_dev = input_allocate_polled_device();
if (!poll_dev)
return -ENOMEM;
poll_dev->poll = rb532_button_poll;
poll_dev->poll_interval = RB532_BTN_RATE;
poll_dev->input->name = "rb532 button";
poll_dev->input->phys = "rb532/button0";
poll_dev->input->id.bustype = BUS_HOST;
poll_dev->input->dev.parent = &pdev->dev;
dev_set_drvdata(&pdev->dev, poll_dev);
input_set_capability(poll_dev->input, EV_KEY, RB532_BTN_KSYM);
error = input_register_polled_device(poll_dev);
if (error) {
input_free_polled_device(poll_dev);
return error;
}
return 0;
}
static int __devexit rb532_button_remove(struct platform_device *pdev)
{
struct input_polled_dev *poll_dev = dev_get_drvdata(&pdev->dev);
input_unregister_polled_device(poll_dev);
input_free_polled_device(poll_dev);
dev_set_drvdata(&pdev->dev, NULL);
return 0;
}
static struct platform_driver rb532_button_driver = {
.probe = rb532_button_probe,
.remove = __devexit_p(rb532_button_remove),
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
},
};
module_platform_driver(rb532_button_driver);
MODULE_AUTHOR("Phil Sutter <n0-1@freewrt.org>");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Support for S1 button on Routerboard 532");
MODULE_ALIAS("platform:" DRV_NAME);
| gpl-2.0 |
JustAkan/lge-kernel-gproj | drivers/net/ethernet/toshiba/ps3_gelic_net.c | 5072 | 49278 | /*
* PS3 gelic network driver.
*
* Copyright (C) 2007 Sony Computer Entertainment Inc.
* Copyright 2006, 2007 Sony Corporation
*
* This file is based on: spider_net.c
*
* (C) Copyright IBM Corp. 2005
*
* Authors : Utz Bacher <utz.bacher@de.ibm.com>
* Jens Osterkamp <Jens.Osterkamp@de.ibm.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#undef DEBUG
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/if_vlan.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/dma-mapping.h>
#include <net/checksum.h>
#include <asm/firmware.h>
#include <asm/ps3.h>
#include <asm/lv1call.h>
#include "ps3_gelic_net.h"
#include "ps3_gelic_wireless.h"
#define DRV_NAME "Gelic Network Driver"
#define DRV_VERSION "2.0"
MODULE_AUTHOR("SCE Inc.");
MODULE_DESCRIPTION("Gelic Network driver");
MODULE_LICENSE("GPL");
static inline void gelic_card_enable_rxdmac(struct gelic_card *card);
static inline void gelic_card_disable_rxdmac(struct gelic_card *card);
static inline void gelic_card_disable_txdmac(struct gelic_card *card);
static inline void gelic_card_reset_chain(struct gelic_card *card,
struct gelic_descr_chain *chain,
struct gelic_descr *start_descr);
/* set irq_mask */
int gelic_card_set_irq_mask(struct gelic_card *card, u64 mask)
{
int status;
status = lv1_net_set_interrupt_mask(bus_id(card), dev_id(card),
mask, 0);
if (status)
dev_info(ctodev(card),
"%s failed %d\n", __func__, status);
return status;
}
static inline void gelic_card_rx_irq_on(struct gelic_card *card)
{
card->irq_mask |= GELIC_CARD_RXINT;
gelic_card_set_irq_mask(card, card->irq_mask);
}
static inline void gelic_card_rx_irq_off(struct gelic_card *card)
{
card->irq_mask &= ~GELIC_CARD_RXINT;
gelic_card_set_irq_mask(card, card->irq_mask);
}
static void gelic_card_get_ether_port_status(struct gelic_card *card,
int inform)
{
u64 v2;
struct net_device *ether_netdev;
lv1_net_control(bus_id(card), dev_id(card),
GELIC_LV1_GET_ETH_PORT_STATUS,
GELIC_LV1_VLAN_TX_ETHERNET_0, 0, 0,
&card->ether_port_status, &v2);
if (inform) {
ether_netdev = card->netdev[GELIC_PORT_ETHERNET_0];
if (card->ether_port_status & GELIC_LV1_ETHER_LINK_UP)
netif_carrier_on(ether_netdev);
else
netif_carrier_off(ether_netdev);
}
}
static int gelic_card_set_link_mode(struct gelic_card *card, int mode)
{
int status;
u64 v1, v2;
status = lv1_net_control(bus_id(card), dev_id(card),
GELIC_LV1_SET_NEGOTIATION_MODE,
GELIC_LV1_PHY_ETHERNET_0, mode, 0, &v1, &v2);
if (status) {
pr_info("%s: failed setting negotiation mode %d\n", __func__,
status);
return -EBUSY;
}
card->link_mode = mode;
return 0;
}
void gelic_card_up(struct gelic_card *card)
{
pr_debug("%s: called\n", __func__);
mutex_lock(&card->updown_lock);
if (atomic_inc_return(&card->users) == 1) {
pr_debug("%s: real do\n", __func__);
/* enable irq */
gelic_card_set_irq_mask(card, card->irq_mask);
/* start rx */
gelic_card_enable_rxdmac(card);
napi_enable(&card->napi);
}
mutex_unlock(&card->updown_lock);
pr_debug("%s: done\n", __func__);
}
void gelic_card_down(struct gelic_card *card)
{
u64 mask;
pr_debug("%s: called\n", __func__);
mutex_lock(&card->updown_lock);
if (atomic_dec_if_positive(&card->users) == 0) {
pr_debug("%s: real do\n", __func__);
napi_disable(&card->napi);
/*
* Disable irq. Wireless interrupts will
* be disabled later if any
*/
mask = card->irq_mask & (GELIC_CARD_WLAN_EVENT_RECEIVED |
GELIC_CARD_WLAN_COMMAND_COMPLETED);
gelic_card_set_irq_mask(card, mask);
/* stop rx */
gelic_card_disable_rxdmac(card);
gelic_card_reset_chain(card, &card->rx_chain,
card->descr + GELIC_NET_TX_DESCRIPTORS);
/* stop tx */
gelic_card_disable_txdmac(card);
}
mutex_unlock(&card->updown_lock);
pr_debug("%s: done\n", __func__);
}
/**
* gelic_descr_get_status -- returns the status of a descriptor
* @descr: descriptor to look at
*
* returns the status as in the dmac_cmd_status field of the descriptor
*/
static enum gelic_descr_dma_status
gelic_descr_get_status(struct gelic_descr *descr)
{
return be32_to_cpu(descr->dmac_cmd_status) & GELIC_DESCR_DMA_STAT_MASK;
}
/**
* gelic_descr_set_status -- sets the status of a descriptor
* @descr: descriptor to change
* @status: status to set in the descriptor
*
* changes the status to the specified value. Doesn't change other bits
* in the status
*/
static void gelic_descr_set_status(struct gelic_descr *descr,
enum gelic_descr_dma_status status)
{
descr->dmac_cmd_status = cpu_to_be32(status |
(be32_to_cpu(descr->dmac_cmd_status) &
~GELIC_DESCR_DMA_STAT_MASK));
/*
* dma_cmd_status field is used to indicate whether the descriptor
* is valid or not.
* Usually caller of this function wants to inform that to the
* hardware, so we assure here the hardware sees the change.
*/
wmb();
}
/**
* gelic_card_free_chain - free descriptor chain
* @card: card structure
* @descr_in: address of desc
*/
static void gelic_card_free_chain(struct gelic_card *card,
struct gelic_descr *descr_in)
{
struct gelic_descr *descr;
for (descr = descr_in; descr && descr->bus_addr; descr = descr->next) {
dma_unmap_single(ctodev(card), descr->bus_addr,
GELIC_DESCR_SIZE, DMA_BIDIRECTIONAL);
descr->bus_addr = 0;
}
}
/**
* gelic_card_init_chain - links descriptor chain
* @card: card structure
* @chain: address of chain
* @start_descr: address of descriptor array
* @no: number of descriptors
*
* we manage a circular list that mirrors the hardware structure,
* except that the hardware uses bus addresses.
*
* returns 0 on success, <0 on failure
*/
static int __devinit gelic_card_init_chain(struct gelic_card *card,
struct gelic_descr_chain *chain,
struct gelic_descr *start_descr,
int no)
{
int i;
struct gelic_descr *descr;
descr = start_descr;
memset(descr, 0, sizeof(*descr) * no);
/* set up the hardware pointers in each descriptor */
for (i = 0; i < no; i++, descr++) {
gelic_descr_set_status(descr, GELIC_DESCR_DMA_NOT_IN_USE);
descr->bus_addr =
dma_map_single(ctodev(card), descr,
GELIC_DESCR_SIZE,
DMA_BIDIRECTIONAL);
if (!descr->bus_addr)
goto iommu_error;
descr->next = descr + 1;
descr->prev = descr - 1;
}
/* make them as ring */
(descr - 1)->next = start_descr;
start_descr->prev = (descr - 1);
/* chain bus addr of hw descriptor */
descr = start_descr;
for (i = 0; i < no; i++, descr++) {
descr->next_descr_addr = cpu_to_be32(descr->next->bus_addr);
}
chain->head = start_descr;
chain->tail = start_descr;
/* do not chain last hw descriptor */
(descr - 1)->next_descr_addr = 0;
return 0;
iommu_error:
for (i--, descr--; 0 <= i; i--, descr--)
if (descr->bus_addr)
dma_unmap_single(ctodev(card), descr->bus_addr,
GELIC_DESCR_SIZE,
DMA_BIDIRECTIONAL);
return -ENOMEM;
}
/**
* gelic_card_reset_chain - reset status of a descriptor chain
* @card: card structure
* @chain: address of chain
* @start_descr: address of descriptor array
*
* Reset the status of dma descriptors to ready state
* and re-initialize the hardware chain for later use
*/
static void gelic_card_reset_chain(struct gelic_card *card,
struct gelic_descr_chain *chain,
struct gelic_descr *start_descr)
{
struct gelic_descr *descr;
for (descr = start_descr; start_descr != descr->next; descr++) {
gelic_descr_set_status(descr, GELIC_DESCR_DMA_CARDOWNED);
descr->next_descr_addr = cpu_to_be32(descr->next->bus_addr);
}
chain->head = start_descr;
chain->tail = (descr - 1);
(descr - 1)->next_descr_addr = 0;
}
/**
* gelic_descr_prepare_rx - reinitializes a rx descriptor
* @card: card structure
* @descr: descriptor to re-init
*
* return 0 on success, <0 on failure
*
* allocates a new rx skb, iommu-maps it and attaches it to the descriptor.
* Activate the descriptor state-wise
*/
static int gelic_descr_prepare_rx(struct gelic_card *card,
struct gelic_descr *descr)
{
int offset;
unsigned int bufsize;
if (gelic_descr_get_status(descr) != GELIC_DESCR_DMA_NOT_IN_USE)
dev_info(ctodev(card), "%s: ERROR status\n", __func__);
/* we need to round up the buffer size to a multiple of 128 */
bufsize = ALIGN(GELIC_NET_MAX_MTU, GELIC_NET_RXBUF_ALIGN);
/* and we need to have it 128 byte aligned, therefore we allocate a
* bit more */
descr->skb = dev_alloc_skb(bufsize + GELIC_NET_RXBUF_ALIGN - 1);
if (!descr->skb) {
descr->buf_addr = 0; /* tell DMAC don't touch memory */
dev_info(ctodev(card),
"%s:allocate skb failed !!\n", __func__);
return -ENOMEM;
}
descr->buf_size = cpu_to_be32(bufsize);
descr->dmac_cmd_status = 0;
descr->result_size = 0;
descr->valid_size = 0;
descr->data_error = 0;
offset = ((unsigned long)descr->skb->data) &
(GELIC_NET_RXBUF_ALIGN - 1);
if (offset)
skb_reserve(descr->skb, GELIC_NET_RXBUF_ALIGN - offset);
/* io-mmu-map the skb */
descr->buf_addr = cpu_to_be32(dma_map_single(ctodev(card),
descr->skb->data,
GELIC_NET_MAX_MTU,
DMA_FROM_DEVICE));
if (!descr->buf_addr) {
dev_kfree_skb_any(descr->skb);
descr->skb = NULL;
dev_info(ctodev(card),
"%s:Could not iommu-map rx buffer\n", __func__);
gelic_descr_set_status(descr, GELIC_DESCR_DMA_NOT_IN_USE);
return -ENOMEM;
} else {
gelic_descr_set_status(descr, GELIC_DESCR_DMA_CARDOWNED);
return 0;
}
}
/**
* gelic_card_release_rx_chain - free all skb of rx descr
* @card: card structure
*
*/
static void gelic_card_release_rx_chain(struct gelic_card *card)
{
struct gelic_descr *descr = card->rx_chain.head;
do {
if (descr->skb) {
dma_unmap_single(ctodev(card),
be32_to_cpu(descr->buf_addr),
descr->skb->len,
DMA_FROM_DEVICE);
descr->buf_addr = 0;
dev_kfree_skb_any(descr->skb);
descr->skb = NULL;
gelic_descr_set_status(descr,
GELIC_DESCR_DMA_NOT_IN_USE);
}
descr = descr->next;
} while (descr != card->rx_chain.head);
}
/**
* gelic_card_fill_rx_chain - fills descriptors/skbs in the rx chains
* @card: card structure
*
* fills all descriptors in the rx chain: allocates skbs
* and iommu-maps them.
* returns 0 on success, < 0 on failure
*/
static int gelic_card_fill_rx_chain(struct gelic_card *card)
{
struct gelic_descr *descr = card->rx_chain.head;
int ret;
do {
if (!descr->skb) {
ret = gelic_descr_prepare_rx(card, descr);
if (ret)
goto rewind;
}
descr = descr->next;
} while (descr != card->rx_chain.head);
return 0;
rewind:
gelic_card_release_rx_chain(card);
return ret;
}
/**
* gelic_card_alloc_rx_skbs - allocates rx skbs in rx descriptor chains
* @card: card structure
*
* returns 0 on success, < 0 on failure
*/
static int __devinit gelic_card_alloc_rx_skbs(struct gelic_card *card)
{
struct gelic_descr_chain *chain;
int ret;
chain = &card->rx_chain;
ret = gelic_card_fill_rx_chain(card);
chain->tail = card->rx_top->prev; /* point to the last */
return ret;
}
/**
* gelic_descr_release_tx - processes a used tx descriptor
* @card: card structure
* @descr: descriptor to release
*
* releases a used tx descriptor (unmapping, freeing of skb)
*/
static void gelic_descr_release_tx(struct gelic_card *card,
struct gelic_descr *descr)
{
struct sk_buff *skb = descr->skb;
BUG_ON(!(be32_to_cpu(descr->data_status) & GELIC_DESCR_TX_TAIL));
dma_unmap_single(ctodev(card), be32_to_cpu(descr->buf_addr), skb->len,
DMA_TO_DEVICE);
dev_kfree_skb_any(skb);
descr->buf_addr = 0;
descr->buf_size = 0;
descr->next_descr_addr = 0;
descr->result_size = 0;
descr->valid_size = 0;
descr->data_status = 0;
descr->data_error = 0;
descr->skb = NULL;
/* set descr status */
gelic_descr_set_status(descr, GELIC_DESCR_DMA_NOT_IN_USE);
}
static void gelic_card_stop_queues(struct gelic_card *card)
{
netif_stop_queue(card->netdev[GELIC_PORT_ETHERNET_0]);
if (card->netdev[GELIC_PORT_WIRELESS])
netif_stop_queue(card->netdev[GELIC_PORT_WIRELESS]);
}
static void gelic_card_wake_queues(struct gelic_card *card)
{
netif_wake_queue(card->netdev[GELIC_PORT_ETHERNET_0]);
if (card->netdev[GELIC_PORT_WIRELESS])
netif_wake_queue(card->netdev[GELIC_PORT_WIRELESS]);
}
/**
* gelic_card_release_tx_chain - processes sent tx descriptors
* @card: adapter structure
* @stop: net_stop sequence
*
* releases the tx descriptors that gelic has finished with
*/
static void gelic_card_release_tx_chain(struct gelic_card *card, int stop)
{
struct gelic_descr_chain *tx_chain;
enum gelic_descr_dma_status status;
struct net_device *netdev;
int release = 0;
for (tx_chain = &card->tx_chain;
tx_chain->head != tx_chain->tail && tx_chain->tail;
tx_chain->tail = tx_chain->tail->next) {
status = gelic_descr_get_status(tx_chain->tail);
netdev = tx_chain->tail->skb->dev;
switch (status) {
case GELIC_DESCR_DMA_RESPONSE_ERROR:
case GELIC_DESCR_DMA_PROTECTION_ERROR:
case GELIC_DESCR_DMA_FORCE_END:
if (printk_ratelimit())
dev_info(ctodev(card),
"%s: forcing end of tx descriptor " \
"with status %x\n",
__func__, status);
netdev->stats.tx_dropped++;
break;
case GELIC_DESCR_DMA_COMPLETE:
if (tx_chain->tail->skb) {
netdev->stats.tx_packets++;
netdev->stats.tx_bytes +=
tx_chain->tail->skb->len;
}
break;
case GELIC_DESCR_DMA_CARDOWNED:
/* pending tx request */
default:
/* any other value (== GELIC_DESCR_DMA_NOT_IN_USE) */
if (!stop)
goto out;
}
gelic_descr_release_tx(card, tx_chain->tail);
release ++;
}
out:
if (!stop && release)
gelic_card_wake_queues(card);
}
/**
* gelic_net_set_multi - sets multicast addresses and promisc flags
* @netdev: interface device structure
*
* gelic_net_set_multi configures multicast addresses as needed for the
* netdev interface. It also sets up multicast, allmulti and promisc
* flags appropriately
*/
void gelic_net_set_multi(struct net_device *netdev)
{
struct gelic_card *card = netdev_card(netdev);
struct netdev_hw_addr *ha;
unsigned int i;
uint8_t *p;
u64 addr;
int status;
/* clear all multicast address */
status = lv1_net_remove_multicast_address(bus_id(card), dev_id(card),
0, 1);
if (status)
dev_err(ctodev(card),
"lv1_net_remove_multicast_address failed %d\n",
status);
/* set broadcast address */
status = lv1_net_add_multicast_address(bus_id(card), dev_id(card),
GELIC_NET_BROADCAST_ADDR, 0);
if (status)
dev_err(ctodev(card),
"lv1_net_add_multicast_address failed, %d\n",
status);
if ((netdev->flags & IFF_ALLMULTI) ||
(netdev_mc_count(netdev) > GELIC_NET_MC_COUNT_MAX)) {
status = lv1_net_add_multicast_address(bus_id(card),
dev_id(card),
0, 1);
if (status)
dev_err(ctodev(card),
"lv1_net_add_multicast_address failed, %d\n",
status);
return;
}
/* set multicast addresses */
netdev_for_each_mc_addr(ha, netdev) {
addr = 0;
p = ha->addr;
for (i = 0; i < ETH_ALEN; i++) {
addr <<= 8;
addr |= *p++;
}
status = lv1_net_add_multicast_address(bus_id(card),
dev_id(card),
addr, 0);
if (status)
dev_err(ctodev(card),
"lv1_net_add_multicast_address failed, %d\n",
status);
}
}
/**
* gelic_card_enable_rxdmac - enables the receive DMA controller
* @card: card structure
*
* gelic_card_enable_rxdmac enables the DMA controller by setting RX_DMA_EN
* in the GDADMACCNTR register
*/
static inline void gelic_card_enable_rxdmac(struct gelic_card *card)
{
int status;
#ifdef DEBUG
if (gelic_descr_get_status(card->rx_chain.head) !=
GELIC_DESCR_DMA_CARDOWNED) {
printk(KERN_ERR "%s: status=%x\n", __func__,
be32_to_cpu(card->rx_chain.head->dmac_cmd_status));
printk(KERN_ERR "%s: nextphy=%x\n", __func__,
be32_to_cpu(card->rx_chain.head->next_descr_addr));
printk(KERN_ERR "%s: head=%p\n", __func__,
card->rx_chain.head);
}
#endif
status = lv1_net_start_rx_dma(bus_id(card), dev_id(card),
card->rx_chain.head->bus_addr, 0);
if (status)
dev_info(ctodev(card),
"lv1_net_start_rx_dma failed, status=%d\n", status);
}
/**
* gelic_card_disable_rxdmac - disables the receive DMA controller
* @card: card structure
*
* gelic_card_disable_rxdmac terminates processing on the DMA controller by
* turing off DMA and issuing a force end
*/
static inline void gelic_card_disable_rxdmac(struct gelic_card *card)
{
int status;
/* this hvc blocks until the DMA in progress really stopped */
status = lv1_net_stop_rx_dma(bus_id(card), dev_id(card));
if (status)
dev_err(ctodev(card),
"lv1_net_stop_rx_dma failed, %d\n", status);
}
/**
* gelic_card_disable_txdmac - disables the transmit DMA controller
* @card: card structure
*
* gelic_card_disable_txdmac terminates processing on the DMA controller by
* turing off DMA and issuing a force end
*/
static inline void gelic_card_disable_txdmac(struct gelic_card *card)
{
int status;
/* this hvc blocks until the DMA in progress really stopped */
status = lv1_net_stop_tx_dma(bus_id(card), dev_id(card));
if (status)
dev_err(ctodev(card),
"lv1_net_stop_tx_dma failed, status=%d\n", status);
}
/**
* gelic_net_stop - called upon ifconfig down
* @netdev: interface device structure
*
* always returns 0
*/
int gelic_net_stop(struct net_device *netdev)
{
struct gelic_card *card;
pr_debug("%s: start\n", __func__);
netif_stop_queue(netdev);
netif_carrier_off(netdev);
card = netdev_card(netdev);
gelic_card_down(card);
pr_debug("%s: done\n", __func__);
return 0;
}
/**
* gelic_card_get_next_tx_descr - returns the next available tx descriptor
* @card: device structure to get descriptor from
*
* returns the address of the next descriptor, or NULL if not available.
*/
static struct gelic_descr *
gelic_card_get_next_tx_descr(struct gelic_card *card)
{
if (!card->tx_chain.head)
return NULL;
/* see if the next descriptor is free */
if (card->tx_chain.tail != card->tx_chain.head->next &&
gelic_descr_get_status(card->tx_chain.head) ==
GELIC_DESCR_DMA_NOT_IN_USE)
return card->tx_chain.head;
else
return NULL;
}
/**
* gelic_net_set_txdescr_cmdstat - sets the tx descriptor command field
* @descr: descriptor structure to fill out
* @skb: packet to consider
*
* fills out the command and status field of the descriptor structure,
* depending on hardware checksum settings. This function assumes a wmb()
* has executed before.
*/
static void gelic_descr_set_tx_cmdstat(struct gelic_descr *descr,
struct sk_buff *skb)
{
if (skb->ip_summed != CHECKSUM_PARTIAL)
descr->dmac_cmd_status =
cpu_to_be32(GELIC_DESCR_DMA_CMD_NO_CHKSUM |
GELIC_DESCR_TX_DMA_FRAME_TAIL);
else {
/* is packet ip?
* if yes: tcp? udp? */
if (skb->protocol == htons(ETH_P_IP)) {
if (ip_hdr(skb)->protocol == IPPROTO_TCP)
descr->dmac_cmd_status =
cpu_to_be32(GELIC_DESCR_DMA_CMD_TCP_CHKSUM |
GELIC_DESCR_TX_DMA_FRAME_TAIL);
else if (ip_hdr(skb)->protocol == IPPROTO_UDP)
descr->dmac_cmd_status =
cpu_to_be32(GELIC_DESCR_DMA_CMD_UDP_CHKSUM |
GELIC_DESCR_TX_DMA_FRAME_TAIL);
else /*
* the stack should checksum non-tcp and non-udp
* packets on his own: NETIF_F_IP_CSUM
*/
descr->dmac_cmd_status =
cpu_to_be32(GELIC_DESCR_DMA_CMD_NO_CHKSUM |
GELIC_DESCR_TX_DMA_FRAME_TAIL);
}
}
}
static inline struct sk_buff *gelic_put_vlan_tag(struct sk_buff *skb,
unsigned short tag)
{
struct vlan_ethhdr *veth;
static unsigned int c;
if (skb_headroom(skb) < VLAN_HLEN) {
struct sk_buff *sk_tmp = skb;
pr_debug("%s: hd=%d c=%ud\n", __func__, skb_headroom(skb), c);
skb = skb_realloc_headroom(sk_tmp, VLAN_HLEN);
if (!skb)
return NULL;
dev_kfree_skb_any(sk_tmp);
}
veth = (struct vlan_ethhdr *)skb_push(skb, VLAN_HLEN);
/* Move the mac addresses to the top of buffer */
memmove(skb->data, skb->data + VLAN_HLEN, 2 * ETH_ALEN);
veth->h_vlan_proto = cpu_to_be16(ETH_P_8021Q);
veth->h_vlan_TCI = htons(tag);
return skb;
}
/**
* gelic_descr_prepare_tx - setup a descriptor for sending packets
* @card: card structure
* @descr: descriptor structure
* @skb: packet to use
*
* returns 0 on success, <0 on failure.
*
*/
static int gelic_descr_prepare_tx(struct gelic_card *card,
struct gelic_descr *descr,
struct sk_buff *skb)
{
dma_addr_t buf;
if (card->vlan_required) {
struct sk_buff *skb_tmp;
enum gelic_port_type type;
type = netdev_port(skb->dev)->type;
skb_tmp = gelic_put_vlan_tag(skb,
card->vlan[type].tx);
if (!skb_tmp)
return -ENOMEM;
skb = skb_tmp;
}
buf = dma_map_single(ctodev(card), skb->data, skb->len, DMA_TO_DEVICE);
if (!buf) {
dev_err(ctodev(card),
"dma map 2 failed (%p, %i). Dropping packet\n",
skb->data, skb->len);
return -ENOMEM;
}
descr->buf_addr = cpu_to_be32(buf);
descr->buf_size = cpu_to_be32(skb->len);
descr->skb = skb;
descr->data_status = 0;
descr->next_descr_addr = 0; /* terminate hw descr */
gelic_descr_set_tx_cmdstat(descr, skb);
/* bump free descriptor pointer */
card->tx_chain.head = descr->next;
return 0;
}
/**
* gelic_card_kick_txdma - enables TX DMA processing
* @card: card structure
* @descr: descriptor address to enable TX processing at
*
*/
static int gelic_card_kick_txdma(struct gelic_card *card,
struct gelic_descr *descr)
{
int status = 0;
if (card->tx_dma_progress)
return 0;
if (gelic_descr_get_status(descr) == GELIC_DESCR_DMA_CARDOWNED) {
card->tx_dma_progress = 1;
status = lv1_net_start_tx_dma(bus_id(card), dev_id(card),
descr->bus_addr, 0);
if (status) {
card->tx_dma_progress = 0;
dev_info(ctodev(card), "lv1_net_start_txdma failed," \
"status=%d\n", status);
}
}
return status;
}
/**
* gelic_net_xmit - transmits a frame over the device
* @skb: packet to send out
* @netdev: interface device structure
*
* returns 0 on success, <0 on failure
*/
int gelic_net_xmit(struct sk_buff *skb, struct net_device *netdev)
{
struct gelic_card *card = netdev_card(netdev);
struct gelic_descr *descr;
int result;
unsigned long flags;
spin_lock_irqsave(&card->tx_lock, flags);
gelic_card_release_tx_chain(card, 0);
descr = gelic_card_get_next_tx_descr(card);
if (!descr) {
/*
* no more descriptors free
*/
gelic_card_stop_queues(card);
spin_unlock_irqrestore(&card->tx_lock, flags);
return NETDEV_TX_BUSY;
}
result = gelic_descr_prepare_tx(card, descr, skb);
if (result) {
/*
* DMA map failed. As chances are that failure
* would continue, just release skb and return
*/
netdev->stats.tx_dropped++;
dev_kfree_skb_any(skb);
spin_unlock_irqrestore(&card->tx_lock, flags);
return NETDEV_TX_OK;
}
/*
* link this prepared descriptor to previous one
* to achieve high performance
*/
descr->prev->next_descr_addr = cpu_to_be32(descr->bus_addr);
/*
* as hardware descriptor is modified in the above lines,
* ensure that the hardware sees it
*/
wmb();
if (gelic_card_kick_txdma(card, descr)) {
/*
* kick failed.
* release descriptor which was just prepared
*/
netdev->stats.tx_dropped++;
/* don't trigger BUG_ON() in gelic_descr_release_tx */
descr->data_status = cpu_to_be32(GELIC_DESCR_TX_TAIL);
gelic_descr_release_tx(card, descr);
/* reset head */
card->tx_chain.head = descr;
/* reset hw termination */
descr->prev->next_descr_addr = 0;
dev_info(ctodev(card), "%s: kick failure\n", __func__);
}
spin_unlock_irqrestore(&card->tx_lock, flags);
return NETDEV_TX_OK;
}
/**
* gelic_net_pass_skb_up - takes an skb from a descriptor and passes it on
* @descr: descriptor to process
* @card: card structure
* @netdev: net_device structure to be passed packet
*
* iommu-unmaps the skb, fills out skb structure and passes the data to the
* stack. The descriptor state is not changed.
*/
static void gelic_net_pass_skb_up(struct gelic_descr *descr,
struct gelic_card *card,
struct net_device *netdev)
{
struct sk_buff *skb = descr->skb;
u32 data_status, data_error;
data_status = be32_to_cpu(descr->data_status);
data_error = be32_to_cpu(descr->data_error);
/* unmap skb buffer */
dma_unmap_single(ctodev(card), be32_to_cpu(descr->buf_addr),
GELIC_NET_MAX_MTU,
DMA_FROM_DEVICE);
skb_put(skb, be32_to_cpu(descr->valid_size)?
be32_to_cpu(descr->valid_size) :
be32_to_cpu(descr->result_size));
if (!descr->valid_size)
dev_info(ctodev(card), "buffer full %x %x %x\n",
be32_to_cpu(descr->result_size),
be32_to_cpu(descr->buf_size),
be32_to_cpu(descr->dmac_cmd_status));
descr->skb = NULL;
/*
* the card put 2 bytes vlan tag in front
* of the ethernet frame
*/
skb_pull(skb, 2);
skb->protocol = eth_type_trans(skb, netdev);
/* checksum offload */
if (netdev->features & NETIF_F_RXCSUM) {
if ((data_status & GELIC_DESCR_DATA_STATUS_CHK_MASK) &&
(!(data_error & GELIC_DESCR_DATA_ERROR_CHK_MASK)))
skb->ip_summed = CHECKSUM_UNNECESSARY;
else
skb_checksum_none_assert(skb);
} else
skb_checksum_none_assert(skb);
/* update netdevice statistics */
netdev->stats.rx_packets++;
netdev->stats.rx_bytes += skb->len;
/* pass skb up to stack */
netif_receive_skb(skb);
}
/**
* gelic_card_decode_one_descr - processes an rx descriptor
* @card: card structure
*
* returns 1 if a packet has been sent to the stack, otherwise 0
*
* processes an rx descriptor by iommu-unmapping the data buffer and passing
* the packet up to the stack
*/
static int gelic_card_decode_one_descr(struct gelic_card *card)
{
enum gelic_descr_dma_status status;
struct gelic_descr_chain *chain = &card->rx_chain;
struct gelic_descr *descr = chain->head;
struct net_device *netdev = NULL;
int dmac_chain_ended;
status = gelic_descr_get_status(descr);
if (status == GELIC_DESCR_DMA_CARDOWNED)
return 0;
if (status == GELIC_DESCR_DMA_NOT_IN_USE) {
dev_dbg(ctodev(card), "dormant descr? %p\n", descr);
return 0;
}
/* netdevice select */
if (card->vlan_required) {
unsigned int i;
u16 vid;
vid = *(u16 *)(descr->skb->data) & VLAN_VID_MASK;
for (i = 0; i < GELIC_PORT_MAX; i++) {
if (card->vlan[i].rx == vid) {
netdev = card->netdev[i];
break;
}
}
if (GELIC_PORT_MAX <= i) {
pr_info("%s: unknown packet vid=%x\n", __func__, vid);
goto refill;
}
} else
netdev = card->netdev[GELIC_PORT_ETHERNET_0];
if ((status == GELIC_DESCR_DMA_RESPONSE_ERROR) ||
(status == GELIC_DESCR_DMA_PROTECTION_ERROR) ||
(status == GELIC_DESCR_DMA_FORCE_END)) {
dev_info(ctodev(card), "dropping RX descriptor with state %x\n",
status);
netdev->stats.rx_dropped++;
goto refill;
}
if (status == GELIC_DESCR_DMA_BUFFER_FULL) {
/*
* Buffer full would occur if and only if
* the frame length was longer than the size of this
* descriptor's buffer. If the frame length was equal
* to or shorter than buffer'size, FRAME_END condition
* would occur.
* Anyway this frame was longer than the MTU,
* just drop it.
*/
dev_info(ctodev(card), "overlength frame\n");
goto refill;
}
/*
* descriptors any other than FRAME_END here should
* be treated as error.
*/
if (status != GELIC_DESCR_DMA_FRAME_END) {
dev_dbg(ctodev(card), "RX descriptor with state %x\n",
status);
goto refill;
}
/* ok, we've got a packet in descr */
gelic_net_pass_skb_up(descr, card, netdev);
refill:
/* is the current descriptor terminated with next_descr == NULL? */
dmac_chain_ended =
be32_to_cpu(descr->dmac_cmd_status) &
GELIC_DESCR_RX_DMA_CHAIN_END;
/*
* So that always DMAC can see the end
* of the descriptor chain to avoid
* from unwanted DMAC overrun.
*/
descr->next_descr_addr = 0;
/* change the descriptor state: */
gelic_descr_set_status(descr, GELIC_DESCR_DMA_NOT_IN_USE);
/*
* this call can fail, but for now, just leave this
* decriptor without skb
*/
gelic_descr_prepare_rx(card, descr);
chain->tail = descr;
chain->head = descr->next;
/*
* Set this descriptor the end of the chain.
*/
descr->prev->next_descr_addr = cpu_to_be32(descr->bus_addr);
/*
* If dmac chain was met, DMAC stopped.
* thus re-enable it
*/
if (dmac_chain_ended)
gelic_card_enable_rxdmac(card);
return 1;
}
/**
* gelic_net_poll - NAPI poll function called by the stack to return packets
* @napi: napi structure
* @budget: number of packets we can pass to the stack at most
*
* returns the number of the processed packets
*
*/
static int gelic_net_poll(struct napi_struct *napi, int budget)
{
struct gelic_card *card = container_of(napi, struct gelic_card, napi);
int packets_done = 0;
while (packets_done < budget) {
if (!gelic_card_decode_one_descr(card))
break;
packets_done++;
}
if (packets_done < budget) {
napi_complete(napi);
gelic_card_rx_irq_on(card);
}
return packets_done;
}
/**
* gelic_net_change_mtu - changes the MTU of an interface
* @netdev: interface device structure
* @new_mtu: new MTU value
*
* returns 0 on success, <0 on failure
*/
int gelic_net_change_mtu(struct net_device *netdev, int new_mtu)
{
/* no need to re-alloc skbs or so -- the max mtu is about 2.3k
* and mtu is outbound only anyway */
if ((new_mtu < GELIC_NET_MIN_MTU) ||
(new_mtu > GELIC_NET_MAX_MTU)) {
return -EINVAL;
}
netdev->mtu = new_mtu;
return 0;
}
/**
* gelic_card_interrupt - event handler for gelic_net
*/
static irqreturn_t gelic_card_interrupt(int irq, void *ptr)
{
unsigned long flags;
struct gelic_card *card = ptr;
u64 status;
status = card->irq_status;
if (!status)
return IRQ_NONE;
status &= card->irq_mask;
if (status & GELIC_CARD_RXINT) {
gelic_card_rx_irq_off(card);
napi_schedule(&card->napi);
}
if (status & GELIC_CARD_TXINT) {
spin_lock_irqsave(&card->tx_lock, flags);
card->tx_dma_progress = 0;
gelic_card_release_tx_chain(card, 0);
/* kick outstanding tx descriptor if any */
gelic_card_kick_txdma(card, card->tx_chain.tail);
spin_unlock_irqrestore(&card->tx_lock, flags);
}
/* ether port status changed */
if (status & GELIC_CARD_PORT_STATUS_CHANGED)
gelic_card_get_ether_port_status(card, 1);
#ifdef CONFIG_GELIC_WIRELESS
if (status & (GELIC_CARD_WLAN_EVENT_RECEIVED |
GELIC_CARD_WLAN_COMMAND_COMPLETED))
gelic_wl_interrupt(card->netdev[GELIC_PORT_WIRELESS], status);
#endif
return IRQ_HANDLED;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
/**
* gelic_net_poll_controller - artificial interrupt for netconsole etc.
* @netdev: interface device structure
*
* see Documentation/networking/netconsole.txt
*/
void gelic_net_poll_controller(struct net_device *netdev)
{
struct gelic_card *card = netdev_card(netdev);
gelic_card_set_irq_mask(card, 0);
gelic_card_interrupt(netdev->irq, netdev);
gelic_card_set_irq_mask(card, card->irq_mask);
}
#endif /* CONFIG_NET_POLL_CONTROLLER */
/**
* gelic_net_open - called upon ifconfig up
* @netdev: interface device structure
*
* returns 0 on success, <0 on failure
*
* gelic_net_open allocates all the descriptors and memory needed for
* operation, sets up multicast list and enables interrupts
*/
int gelic_net_open(struct net_device *netdev)
{
struct gelic_card *card = netdev_card(netdev);
dev_dbg(ctodev(card), " -> %s %p\n", __func__, netdev);
gelic_card_up(card);
netif_start_queue(netdev);
gelic_card_get_ether_port_status(card, 1);
dev_dbg(ctodev(card), " <- %s\n", __func__);
return 0;
}
void gelic_net_get_drvinfo(struct net_device *netdev,
struct ethtool_drvinfo *info)
{
strncpy(info->driver, DRV_NAME, sizeof(info->driver) - 1);
strncpy(info->version, DRV_VERSION, sizeof(info->version) - 1);
}
static int gelic_ether_get_settings(struct net_device *netdev,
struct ethtool_cmd *cmd)
{
struct gelic_card *card = netdev_card(netdev);
gelic_card_get_ether_port_status(card, 0);
if (card->ether_port_status & GELIC_LV1_ETHER_FULL_DUPLEX)
cmd->duplex = DUPLEX_FULL;
else
cmd->duplex = DUPLEX_HALF;
switch (card->ether_port_status & GELIC_LV1_ETHER_SPEED_MASK) {
case GELIC_LV1_ETHER_SPEED_10:
ethtool_cmd_speed_set(cmd, SPEED_10);
break;
case GELIC_LV1_ETHER_SPEED_100:
ethtool_cmd_speed_set(cmd, SPEED_100);
break;
case GELIC_LV1_ETHER_SPEED_1000:
ethtool_cmd_speed_set(cmd, SPEED_1000);
break;
default:
pr_info("%s: speed unknown\n", __func__);
ethtool_cmd_speed_set(cmd, SPEED_10);
break;
}
cmd->supported = SUPPORTED_TP | SUPPORTED_Autoneg |
SUPPORTED_10baseT_Half | SUPPORTED_10baseT_Full |
SUPPORTED_100baseT_Half | SUPPORTED_100baseT_Full |
SUPPORTED_1000baseT_Full;
cmd->advertising = cmd->supported;
if (card->link_mode & GELIC_LV1_ETHER_AUTO_NEG) {
cmd->autoneg = AUTONEG_ENABLE;
} else {
cmd->autoneg = AUTONEG_DISABLE;
cmd->advertising &= ~ADVERTISED_Autoneg;
}
cmd->port = PORT_TP;
return 0;
}
static int gelic_ether_set_settings(struct net_device *netdev,
struct ethtool_cmd *cmd)
{
struct gelic_card *card = netdev_card(netdev);
u64 mode;
int ret;
if (cmd->autoneg == AUTONEG_ENABLE) {
mode = GELIC_LV1_ETHER_AUTO_NEG;
} else {
switch (cmd->speed) {
case SPEED_10:
mode = GELIC_LV1_ETHER_SPEED_10;
break;
case SPEED_100:
mode = GELIC_LV1_ETHER_SPEED_100;
break;
case SPEED_1000:
mode = GELIC_LV1_ETHER_SPEED_1000;
break;
default:
return -EINVAL;
}
if (cmd->duplex == DUPLEX_FULL)
mode |= GELIC_LV1_ETHER_FULL_DUPLEX;
else if (cmd->speed == SPEED_1000) {
pr_info("1000 half duplex is not supported.\n");
return -EINVAL;
}
}
ret = gelic_card_set_link_mode(card, mode);
if (ret)
return ret;
return 0;
}
static void gelic_net_get_wol(struct net_device *netdev,
struct ethtool_wolinfo *wol)
{
if (0 <= ps3_compare_firmware_version(2, 2, 0))
wol->supported = WAKE_MAGIC;
else
wol->supported = 0;
wol->wolopts = ps3_sys_manager_get_wol() ? wol->supported : 0;
memset(&wol->sopass, 0, sizeof(wol->sopass));
}
static int gelic_net_set_wol(struct net_device *netdev,
struct ethtool_wolinfo *wol)
{
int status;
struct gelic_card *card;
u64 v1, v2;
if (ps3_compare_firmware_version(2, 2, 0) < 0 ||
!capable(CAP_NET_ADMIN))
return -EPERM;
if (wol->wolopts & ~WAKE_MAGIC)
return -EINVAL;
card = netdev_card(netdev);
if (wol->wolopts & WAKE_MAGIC) {
status = lv1_net_control(bus_id(card), dev_id(card),
GELIC_LV1_SET_WOL,
GELIC_LV1_WOL_MAGIC_PACKET,
0, GELIC_LV1_WOL_MP_ENABLE,
&v1, &v2);
if (status) {
pr_info("%s: enabling WOL failed %d\n", __func__,
status);
status = -EIO;
goto done;
}
status = lv1_net_control(bus_id(card), dev_id(card),
GELIC_LV1_SET_WOL,
GELIC_LV1_WOL_ADD_MATCH_ADDR,
0, GELIC_LV1_WOL_MATCH_ALL,
&v1, &v2);
if (!status)
ps3_sys_manager_set_wol(1);
else {
pr_info("%s: enabling WOL filter failed %d\n",
__func__, status);
status = -EIO;
}
} else {
status = lv1_net_control(bus_id(card), dev_id(card),
GELIC_LV1_SET_WOL,
GELIC_LV1_WOL_MAGIC_PACKET,
0, GELIC_LV1_WOL_MP_DISABLE,
&v1, &v2);
if (status) {
pr_info("%s: disabling WOL failed %d\n", __func__,
status);
status = -EIO;
goto done;
}
status = lv1_net_control(bus_id(card), dev_id(card),
GELIC_LV1_SET_WOL,
GELIC_LV1_WOL_DELETE_MATCH_ADDR,
0, GELIC_LV1_WOL_MATCH_ALL,
&v1, &v2);
if (!status)
ps3_sys_manager_set_wol(0);
else {
pr_info("%s: removing WOL filter failed %d\n",
__func__, status);
status = -EIO;
}
}
done:
return status;
}
static const struct ethtool_ops gelic_ether_ethtool_ops = {
.get_drvinfo = gelic_net_get_drvinfo,
.get_settings = gelic_ether_get_settings,
.set_settings = gelic_ether_set_settings,
.get_link = ethtool_op_get_link,
.get_wol = gelic_net_get_wol,
.set_wol = gelic_net_set_wol,
};
/**
* gelic_net_tx_timeout_task - task scheduled by the watchdog timeout
* function (to be called not under interrupt status)
* @work: work is context of tx timout task
*
* called as task when tx hangs, resets interface (if interface is up)
*/
static void gelic_net_tx_timeout_task(struct work_struct *work)
{
struct gelic_card *card =
container_of(work, struct gelic_card, tx_timeout_task);
struct net_device *netdev = card->netdev[GELIC_PORT_ETHERNET_0];
dev_info(ctodev(card), "%s:Timed out. Restarting...\n", __func__);
if (!(netdev->flags & IFF_UP))
goto out;
netif_device_detach(netdev);
gelic_net_stop(netdev);
gelic_net_open(netdev);
netif_device_attach(netdev);
out:
atomic_dec(&card->tx_timeout_task_counter);
}
/**
* gelic_net_tx_timeout - called when the tx timeout watchdog kicks in.
* @netdev: interface device structure
*
* called, if tx hangs. Schedules a task that resets the interface
*/
void gelic_net_tx_timeout(struct net_device *netdev)
{
struct gelic_card *card;
card = netdev_card(netdev);
atomic_inc(&card->tx_timeout_task_counter);
if (netdev->flags & IFF_UP)
schedule_work(&card->tx_timeout_task);
else
atomic_dec(&card->tx_timeout_task_counter);
}
static const struct net_device_ops gelic_netdevice_ops = {
.ndo_open = gelic_net_open,
.ndo_stop = gelic_net_stop,
.ndo_start_xmit = gelic_net_xmit,
.ndo_set_rx_mode = gelic_net_set_multi,
.ndo_change_mtu = gelic_net_change_mtu,
.ndo_tx_timeout = gelic_net_tx_timeout,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = gelic_net_poll_controller,
#endif
};
/**
* gelic_ether_setup_netdev_ops - initialization of net_device operations
* @netdev: net_device structure
*
* fills out function pointers in the net_device structure
*/
static void __devinit gelic_ether_setup_netdev_ops(struct net_device *netdev,
struct napi_struct *napi)
{
netdev->watchdog_timeo = GELIC_NET_WATCHDOG_TIMEOUT;
/* NAPI */
netif_napi_add(netdev, napi,
gelic_net_poll, GELIC_NET_NAPI_WEIGHT);
netdev->ethtool_ops = &gelic_ether_ethtool_ops;
netdev->netdev_ops = &gelic_netdevice_ops;
}
/**
* gelic_ether_setup_netdev - initialization of net_device
* @netdev: net_device structure
* @card: card structure
*
* Returns 0 on success or <0 on failure
*
* gelic_ether_setup_netdev initializes the net_device structure
* and register it.
**/
int __devinit gelic_net_setup_netdev(struct net_device *netdev,
struct gelic_card *card)
{
int status;
u64 v1, v2;
netdev->hw_features = NETIF_F_IP_CSUM | NETIF_F_RXCSUM;
netdev->features = NETIF_F_IP_CSUM;
if (GELIC_CARD_RX_CSUM_DEFAULT)
netdev->features |= NETIF_F_RXCSUM;
status = lv1_net_control(bus_id(card), dev_id(card),
GELIC_LV1_GET_MAC_ADDRESS,
0, 0, 0, &v1, &v2);
v1 <<= 16;
if (status || !is_valid_ether_addr((u8 *)&v1)) {
dev_info(ctodev(card),
"%s:lv1_net_control GET_MAC_ADDR failed %d\n",
__func__, status);
return -EINVAL;
}
memcpy(netdev->dev_addr, &v1, ETH_ALEN);
if (card->vlan_required) {
netdev->hard_header_len += VLAN_HLEN;
/*
* As vlan is internally used,
* we can not receive vlan packets
*/
netdev->features |= NETIF_F_VLAN_CHALLENGED;
}
status = register_netdev(netdev);
if (status) {
dev_err(ctodev(card), "%s:Couldn't register %s %d\n",
__func__, netdev->name, status);
return status;
}
dev_info(ctodev(card), "%s: MAC addr %pM\n",
netdev->name, netdev->dev_addr);
return 0;
}
/**
* gelic_alloc_card_net - allocates net_device and card structure
*
* returns the card structure or NULL in case of errors
*
* the card and net_device structures are linked to each other
*/
#define GELIC_ALIGN (32)
static struct gelic_card * __devinit gelic_alloc_card_net(struct net_device **netdev)
{
struct gelic_card *card;
struct gelic_port *port;
void *p;
size_t alloc_size;
/*
* gelic requires dma descriptor is 32 bytes aligned and
* the hypervisor requires irq_status is 8 bytes aligned.
*/
BUILD_BUG_ON(offsetof(struct gelic_card, irq_status) % 8);
BUILD_BUG_ON(offsetof(struct gelic_card, descr) % 32);
alloc_size =
sizeof(struct gelic_card) +
sizeof(struct gelic_descr) * GELIC_NET_RX_DESCRIPTORS +
sizeof(struct gelic_descr) * GELIC_NET_TX_DESCRIPTORS +
GELIC_ALIGN - 1;
p = kzalloc(alloc_size, GFP_KERNEL);
if (!p)
return NULL;
card = PTR_ALIGN(p, GELIC_ALIGN);
card->unalign = p;
/*
* alloc netdev
*/
*netdev = alloc_etherdev(sizeof(struct gelic_port));
if (!netdev) {
kfree(card->unalign);
return NULL;
}
port = netdev_priv(*netdev);
/* gelic_port */
port->netdev = *netdev;
port->card = card;
port->type = GELIC_PORT_ETHERNET_0;
/* gelic_card */
card->netdev[GELIC_PORT_ETHERNET_0] = *netdev;
INIT_WORK(&card->tx_timeout_task, gelic_net_tx_timeout_task);
init_waitqueue_head(&card->waitq);
atomic_set(&card->tx_timeout_task_counter, 0);
mutex_init(&card->updown_lock);
atomic_set(&card->users, 0);
return card;
}
static void __devinit gelic_card_get_vlan_info(struct gelic_card *card)
{
u64 v1, v2;
int status;
unsigned int i;
struct {
int tx;
int rx;
} vlan_id_ix[2] = {
[GELIC_PORT_ETHERNET_0] = {
.tx = GELIC_LV1_VLAN_TX_ETHERNET_0,
.rx = GELIC_LV1_VLAN_RX_ETHERNET_0
},
[GELIC_PORT_WIRELESS] = {
.tx = GELIC_LV1_VLAN_TX_WIRELESS,
.rx = GELIC_LV1_VLAN_RX_WIRELESS
}
};
for (i = 0; i < ARRAY_SIZE(vlan_id_ix); i++) {
/* tx tag */
status = lv1_net_control(bus_id(card), dev_id(card),
GELIC_LV1_GET_VLAN_ID,
vlan_id_ix[i].tx,
0, 0, &v1, &v2);
if (status || !v1) {
if (status != LV1_NO_ENTRY)
dev_dbg(ctodev(card),
"get vlan id for tx(%d) failed(%d)\n",
vlan_id_ix[i].tx, status);
card->vlan[i].tx = 0;
card->vlan[i].rx = 0;
continue;
}
card->vlan[i].tx = (u16)v1;
/* rx tag */
status = lv1_net_control(bus_id(card), dev_id(card),
GELIC_LV1_GET_VLAN_ID,
vlan_id_ix[i].rx,
0, 0, &v1, &v2);
if (status || !v1) {
if (status != LV1_NO_ENTRY)
dev_info(ctodev(card),
"get vlan id for rx(%d) failed(%d)\n",
vlan_id_ix[i].rx, status);
card->vlan[i].tx = 0;
card->vlan[i].rx = 0;
continue;
}
card->vlan[i].rx = (u16)v1;
dev_dbg(ctodev(card), "vlan_id[%d] tx=%02x rx=%02x\n",
i, card->vlan[i].tx, card->vlan[i].rx);
}
if (card->vlan[GELIC_PORT_ETHERNET_0].tx) {
BUG_ON(!card->vlan[GELIC_PORT_WIRELESS].tx);
card->vlan_required = 1;
} else
card->vlan_required = 0;
/* check wirelss capable firmware */
if (ps3_compare_firmware_version(1, 6, 0) < 0) {
card->vlan[GELIC_PORT_WIRELESS].tx = 0;
card->vlan[GELIC_PORT_WIRELESS].rx = 0;
}
dev_info(ctodev(card), "internal vlan %s\n",
card->vlan_required? "enabled" : "disabled");
}
/**
* ps3_gelic_driver_probe - add a device to the control of this driver
*/
static int __devinit ps3_gelic_driver_probe(struct ps3_system_bus_device *dev)
{
struct gelic_card *card;
struct net_device *netdev;
int result;
pr_debug("%s: called\n", __func__);
udbg_shutdown_ps3gelic();
result = ps3_open_hv_device(dev);
if (result) {
dev_dbg(&dev->core, "%s:ps3_open_hv_device failed\n",
__func__);
goto fail_open;
}
result = ps3_dma_region_create(dev->d_region);
if (result) {
dev_dbg(&dev->core, "%s:ps3_dma_region_create failed(%d)\n",
__func__, result);
BUG_ON("check region type");
goto fail_dma_region;
}
/* alloc card/netdevice */
card = gelic_alloc_card_net(&netdev);
if (!card) {
dev_info(&dev->core, "%s:gelic_net_alloc_card failed\n",
__func__);
result = -ENOMEM;
goto fail_alloc_card;
}
ps3_system_bus_set_drvdata(dev, card);
card->dev = dev;
/* get internal vlan info */
gelic_card_get_vlan_info(card);
card->link_mode = GELIC_LV1_ETHER_AUTO_NEG;
/* setup interrupt */
result = lv1_net_set_interrupt_status_indicator(bus_id(card),
dev_id(card),
ps3_mm_phys_to_lpar(__pa(&card->irq_status)),
0);
if (result) {
dev_dbg(&dev->core,
"%s:set_interrupt_status_indicator failed: %s\n",
__func__, ps3_result(result));
result = -EIO;
goto fail_status_indicator;
}
result = ps3_sb_event_receive_port_setup(dev, PS3_BINDING_CPU_ANY,
&card->irq);
if (result) {
dev_info(ctodev(card),
"%s:gelic_net_open_device failed (%d)\n",
__func__, result);
result = -EPERM;
goto fail_alloc_irq;
}
result = request_irq(card->irq, gelic_card_interrupt,
IRQF_DISABLED, netdev->name, card);
if (result) {
dev_info(ctodev(card), "%s:request_irq failed (%d)\n",
__func__, result);
goto fail_request_irq;
}
/* setup card structure */
card->irq_mask = GELIC_CARD_RXINT | GELIC_CARD_TXINT |
GELIC_CARD_PORT_STATUS_CHANGED;
if (gelic_card_init_chain(card, &card->tx_chain,
card->descr, GELIC_NET_TX_DESCRIPTORS))
goto fail_alloc_tx;
if (gelic_card_init_chain(card, &card->rx_chain,
card->descr + GELIC_NET_TX_DESCRIPTORS,
GELIC_NET_RX_DESCRIPTORS))
goto fail_alloc_rx;
/* head of chain */
card->tx_top = card->tx_chain.head;
card->rx_top = card->rx_chain.head;
dev_dbg(ctodev(card), "descr rx %p, tx %p, size %#lx, num %#x\n",
card->rx_top, card->tx_top, sizeof(struct gelic_descr),
GELIC_NET_RX_DESCRIPTORS);
/* allocate rx skbs */
if (gelic_card_alloc_rx_skbs(card))
goto fail_alloc_skbs;
spin_lock_init(&card->tx_lock);
card->tx_dma_progress = 0;
/* setup net_device structure */
netdev->irq = card->irq;
SET_NETDEV_DEV(netdev, &card->dev->core);
gelic_ether_setup_netdev_ops(netdev, &card->napi);
result = gelic_net_setup_netdev(netdev, card);
if (result) {
dev_dbg(&dev->core, "%s: setup_netdev failed %d",
__func__, result);
goto fail_setup_netdev;
}
#ifdef CONFIG_GELIC_WIRELESS
if (gelic_wl_driver_probe(card)) {
dev_dbg(&dev->core, "%s: WL init failed\n", __func__);
goto fail_setup_netdev;
}
#endif
pr_debug("%s: done\n", __func__);
return 0;
fail_setup_netdev:
fail_alloc_skbs:
gelic_card_free_chain(card, card->rx_chain.head);
fail_alloc_rx:
gelic_card_free_chain(card, card->tx_chain.head);
fail_alloc_tx:
free_irq(card->irq, card);
netdev->irq = NO_IRQ;
fail_request_irq:
ps3_sb_event_receive_port_destroy(dev, card->irq);
fail_alloc_irq:
lv1_net_set_interrupt_status_indicator(bus_id(card),
bus_id(card),
0, 0);
fail_status_indicator:
ps3_system_bus_set_drvdata(dev, NULL);
kfree(netdev_card(netdev)->unalign);
free_netdev(netdev);
fail_alloc_card:
ps3_dma_region_free(dev->d_region);
fail_dma_region:
ps3_close_hv_device(dev);
fail_open:
return result;
}
/**
* ps3_gelic_driver_remove - remove a device from the control of this driver
*/
static int ps3_gelic_driver_remove(struct ps3_system_bus_device *dev)
{
struct gelic_card *card = ps3_system_bus_get_drvdata(dev);
struct net_device *netdev0;
pr_debug("%s: called\n", __func__);
/* set auto-negotiation */
gelic_card_set_link_mode(card, GELIC_LV1_ETHER_AUTO_NEG);
#ifdef CONFIG_GELIC_WIRELESS
gelic_wl_driver_remove(card);
#endif
/* stop interrupt */
gelic_card_set_irq_mask(card, 0);
/* turn off DMA, force end */
gelic_card_disable_rxdmac(card);
gelic_card_disable_txdmac(card);
/* release chains */
gelic_card_release_tx_chain(card, 1);
gelic_card_release_rx_chain(card);
gelic_card_free_chain(card, card->tx_top);
gelic_card_free_chain(card, card->rx_top);
netdev0 = card->netdev[GELIC_PORT_ETHERNET_0];
/* disconnect event port */
free_irq(card->irq, card);
netdev0->irq = NO_IRQ;
ps3_sb_event_receive_port_destroy(card->dev, card->irq);
wait_event(card->waitq,
atomic_read(&card->tx_timeout_task_counter) == 0);
lv1_net_set_interrupt_status_indicator(bus_id(card), dev_id(card),
0 , 0);
unregister_netdev(netdev0);
kfree(netdev_card(netdev0)->unalign);
free_netdev(netdev0);
ps3_system_bus_set_drvdata(dev, NULL);
ps3_dma_region_free(dev->d_region);
ps3_close_hv_device(dev);
pr_debug("%s: done\n", __func__);
return 0;
}
static struct ps3_system_bus_driver ps3_gelic_driver = {
.match_id = PS3_MATCH_ID_GELIC,
.probe = ps3_gelic_driver_probe,
.remove = ps3_gelic_driver_remove,
.shutdown = ps3_gelic_driver_remove,
.core.name = "ps3_gelic_driver",
.core.owner = THIS_MODULE,
};
static int __init ps3_gelic_driver_init (void)
{
return firmware_has_feature(FW_FEATURE_PS3_LV1)
? ps3_system_bus_driver_register(&ps3_gelic_driver)
: -ENODEV;
}
static void __exit ps3_gelic_driver_exit (void)
{
ps3_system_bus_driver_unregister(&ps3_gelic_driver);
}
module_init(ps3_gelic_driver_init);
module_exit(ps3_gelic_driver_exit);
MODULE_ALIAS(PS3_MODULE_ALIAS_GELIC);
| gpl-2.0 |
zhaochengw/android_kernel_nx403 | drivers/input/misc/pcap_keys.c | 5072 | 3230 | /*
* Input driver for PCAP events:
* * Power key
* * Headphone button
*
* Copyright (c) 2008,2009 Ilya Petrov <ilya.muromec@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/module.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <linux/mfd/ezx-pcap.h>
#include <linux/slab.h>
struct pcap_keys {
struct pcap_chip *pcap;
struct input_dev *input;
};
/* PCAP2 interrupts us on keypress */
static irqreturn_t pcap_keys_handler(int irq, void *_pcap_keys)
{
struct pcap_keys *pcap_keys = _pcap_keys;
int pirq = irq_to_pcap(pcap_keys->pcap, irq);
u32 pstat;
ezx_pcap_read(pcap_keys->pcap, PCAP_REG_PSTAT, &pstat);
pstat &= 1 << pirq;
switch (pirq) {
case PCAP_IRQ_ONOFF:
input_report_key(pcap_keys->input, KEY_POWER, !pstat);
break;
case PCAP_IRQ_MIC:
input_report_key(pcap_keys->input, KEY_HP, !pstat);
break;
}
input_sync(pcap_keys->input);
return IRQ_HANDLED;
}
static int __devinit pcap_keys_probe(struct platform_device *pdev)
{
int err = -ENOMEM;
struct pcap_keys *pcap_keys;
struct input_dev *input_dev;
pcap_keys = kmalloc(sizeof(struct pcap_keys), GFP_KERNEL);
if (!pcap_keys)
return err;
pcap_keys->pcap = dev_get_drvdata(pdev->dev.parent);
input_dev = input_allocate_device();
if (!input_dev)
goto fail;
pcap_keys->input = input_dev;
platform_set_drvdata(pdev, pcap_keys);
input_dev->name = pdev->name;
input_dev->phys = "pcap-keys/input0";
input_dev->id.bustype = BUS_HOST;
input_dev->dev.parent = &pdev->dev;
__set_bit(EV_KEY, input_dev->evbit);
__set_bit(KEY_POWER, input_dev->keybit);
__set_bit(KEY_HP, input_dev->keybit);
err = input_register_device(input_dev);
if (err)
goto fail_allocate;
err = request_irq(pcap_to_irq(pcap_keys->pcap, PCAP_IRQ_ONOFF),
pcap_keys_handler, 0, "Power key", pcap_keys);
if (err)
goto fail_register;
err = request_irq(pcap_to_irq(pcap_keys->pcap, PCAP_IRQ_MIC),
pcap_keys_handler, 0, "Headphone button", pcap_keys);
if (err)
goto fail_pwrkey;
return 0;
fail_pwrkey:
free_irq(pcap_to_irq(pcap_keys->pcap, PCAP_IRQ_ONOFF), pcap_keys);
fail_register:
input_unregister_device(input_dev);
goto fail;
fail_allocate:
input_free_device(input_dev);
fail:
kfree(pcap_keys);
return err;
}
static int __devexit pcap_keys_remove(struct platform_device *pdev)
{
struct pcap_keys *pcap_keys = platform_get_drvdata(pdev);
free_irq(pcap_to_irq(pcap_keys->pcap, PCAP_IRQ_ONOFF), pcap_keys);
free_irq(pcap_to_irq(pcap_keys->pcap, PCAP_IRQ_MIC), pcap_keys);
input_unregister_device(pcap_keys->input);
kfree(pcap_keys);
return 0;
}
static struct platform_driver pcap_keys_device_driver = {
.probe = pcap_keys_probe,
.remove = __devexit_p(pcap_keys_remove),
.driver = {
.name = "pcap-keys",
.owner = THIS_MODULE,
}
};
module_platform_driver(pcap_keys_device_driver);
MODULE_DESCRIPTION("Motorola PCAP2 input events driver");
MODULE_AUTHOR("Ilya Petrov <ilya.muromec@gmail.com>");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:pcap_keys");
| gpl-2.0 |
flar2/m7-Sense | arch/arm/mach-shmobile/clock.c | 5072 | 1234 | /*
* SH-Mobile Clock Framework
*
* Copyright (C) 2010 Magnus Damm
*
* Used together with arch/arm/common/clkdev.c and drivers/sh/clk.c.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/sh_clk.h>
#include <linux/export.h>
int __init shmobile_clk_init(void)
{
/* Kick the child clocks.. */
recalculate_root_clocks();
/* Enable the necessary init clocks */
clk_enable_init_clocks();
return 0;
}
int __clk_get(struct clk *clk)
{
return 1;
}
EXPORT_SYMBOL(__clk_get);
void __clk_put(struct clk *clk)
{
}
EXPORT_SYMBOL(__clk_put);
| gpl-2.0 |
system1357/pdk7105-3.4 | drivers/input/misc/cobalt_btns.c | 5072 | 4430 | /*
* Cobalt button interface driver.
*
* 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/init.h>
#include <linux/input-polldev.h>
#include <linux/ioport.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#define BUTTONS_POLL_INTERVAL 30 /* msec */
#define BUTTONS_COUNT_THRESHOLD 3
#define BUTTONS_STATUS_MASK 0xfe000000
static const unsigned short cobalt_map[] = {
KEY_RESERVED,
KEY_RESTART,
KEY_LEFT,
KEY_UP,
KEY_DOWN,
KEY_RIGHT,
KEY_ENTER,
KEY_SELECT
};
struct buttons_dev {
struct input_polled_dev *poll_dev;
unsigned short keymap[ARRAY_SIZE(cobalt_map)];
int count[ARRAY_SIZE(cobalt_map)];
void __iomem *reg;
};
static void handle_buttons(struct input_polled_dev *dev)
{
struct buttons_dev *bdev = dev->private;
struct input_dev *input = dev->input;
uint32_t status;
int i;
status = ~readl(bdev->reg) >> 24;
for (i = 0; i < ARRAY_SIZE(bdev->keymap); i++) {
if (status & (1U << i)) {
if (++bdev->count[i] == BUTTONS_COUNT_THRESHOLD) {
input_event(input, EV_MSC, MSC_SCAN, i);
input_report_key(input, bdev->keymap[i], 1);
input_sync(input);
}
} else {
if (bdev->count[i] >= BUTTONS_COUNT_THRESHOLD) {
input_event(input, EV_MSC, MSC_SCAN, i);
input_report_key(input, bdev->keymap[i], 0);
input_sync(input);
}
bdev->count[i] = 0;
}
}
}
static int __devinit cobalt_buttons_probe(struct platform_device *pdev)
{
struct buttons_dev *bdev;
struct input_polled_dev *poll_dev;
struct input_dev *input;
struct resource *res;
int error, i;
bdev = kzalloc(sizeof(struct buttons_dev), GFP_KERNEL);
poll_dev = input_allocate_polled_device();
if (!bdev || !poll_dev) {
error = -ENOMEM;
goto err_free_mem;
}
memcpy(bdev->keymap, cobalt_map, sizeof(bdev->keymap));
poll_dev->private = bdev;
poll_dev->poll = handle_buttons;
poll_dev->poll_interval = BUTTONS_POLL_INTERVAL;
input = poll_dev->input;
input->name = "Cobalt buttons";
input->phys = "cobalt/input0";
input->id.bustype = BUS_HOST;
input->dev.parent = &pdev->dev;
input->keycode = bdev->keymap;
input->keycodemax = ARRAY_SIZE(bdev->keymap);
input->keycodesize = sizeof(unsigned short);
input_set_capability(input, EV_MSC, MSC_SCAN);
__set_bit(EV_KEY, input->evbit);
for (i = 0; i < ARRAY_SIZE(cobalt_map); i++)
__set_bit(bdev->keymap[i], input->keybit);
__clear_bit(KEY_RESERVED, input->keybit);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
error = -EBUSY;
goto err_free_mem;
}
bdev->poll_dev = poll_dev;
bdev->reg = ioremap(res->start, resource_size(res));
dev_set_drvdata(&pdev->dev, bdev);
error = input_register_polled_device(poll_dev);
if (error)
goto err_iounmap;
return 0;
err_iounmap:
iounmap(bdev->reg);
err_free_mem:
input_free_polled_device(poll_dev);
kfree(bdev);
dev_set_drvdata(&pdev->dev, NULL);
return error;
}
static int __devexit cobalt_buttons_remove(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct buttons_dev *bdev = dev_get_drvdata(dev);
input_unregister_polled_device(bdev->poll_dev);
input_free_polled_device(bdev->poll_dev);
iounmap(bdev->reg);
kfree(bdev);
dev_set_drvdata(dev, NULL);
return 0;
}
MODULE_AUTHOR("Yoichi Yuasa <yuasa@linux-mips.org>");
MODULE_DESCRIPTION("Cobalt button interface driver");
MODULE_LICENSE("GPL");
/* work with hotplug and coldplug */
MODULE_ALIAS("platform:Cobalt buttons");
static struct platform_driver cobalt_buttons_driver = {
.probe = cobalt_buttons_probe,
.remove = __devexit_p(cobalt_buttons_remove),
.driver = {
.name = "Cobalt buttons",
.owner = THIS_MODULE,
},
};
module_platform_driver(cobalt_buttons_driver);
| gpl-2.0 |
Split-Screen/android_kernel_samsung_hlte | drivers/ata/pata_ixp4xx_cf.c | 5072 | 5685 | /*
* ixp4xx PATA/Compact Flash driver
* Copyright (C) 2006-07 Tower Technologies
* Author: Alessandro Zummo <a.zummo@towertech.it>
*
* An ATA driver to handle a Compact Flash connected
* to the ixp4xx expansion bus in TrueIDE mode. The CF
* must have it chip selects connected to two CS lines
* on the ixp4xx. In the irq is not available, you might
* want to modify both this driver and libata to run in
* polling mode.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/libata.h>
#include <linux/irq.h>
#include <linux/platform_device.h>
#include <scsi/scsi_host.h>
#define DRV_NAME "pata_ixp4xx_cf"
#define DRV_VERSION "0.2"
static int ixp4xx_set_mode(struct ata_link *link, struct ata_device **error)
{
struct ata_device *dev;
ata_for_each_dev(dev, link, ENABLED) {
ata_dev_info(dev, "configured for PIO0\n");
dev->pio_mode = XFER_PIO_0;
dev->xfer_mode = XFER_PIO_0;
dev->xfer_shift = ATA_SHIFT_PIO;
dev->flags |= ATA_DFLAG_PIO;
}
return 0;
}
static unsigned int ixp4xx_mmio_data_xfer(struct ata_device *dev,
unsigned char *buf, unsigned int buflen, int rw)
{
unsigned int i;
unsigned int words = buflen >> 1;
u16 *buf16 = (u16 *) buf;
struct ata_port *ap = dev->link->ap;
void __iomem *mmio = ap->ioaddr.data_addr;
struct ixp4xx_pata_data *data = ap->host->dev->platform_data;
/* set the expansion bus in 16bit mode and restore
* 8 bit mode after the transaction.
*/
*data->cs0_cfg &= ~(0x01);
udelay(100);
/* Transfer multiple of 2 bytes */
if (rw == READ)
for (i = 0; i < words; i++)
buf16[i] = readw(mmio);
else
for (i = 0; i < words; i++)
writew(buf16[i], mmio);
/* Transfer trailing 1 byte, if any. */
if (unlikely(buflen & 0x01)) {
u16 align_buf[1] = { 0 };
unsigned char *trailing_buf = buf + buflen - 1;
if (rw == READ) {
align_buf[0] = readw(mmio);
memcpy(trailing_buf, align_buf, 1);
} else {
memcpy(align_buf, trailing_buf, 1);
writew(align_buf[0], mmio);
}
words++;
}
udelay(100);
*data->cs0_cfg |= 0x01;
return words << 1;
}
static struct scsi_host_template ixp4xx_sht = {
ATA_PIO_SHT(DRV_NAME),
};
static struct ata_port_operations ixp4xx_port_ops = {
.inherits = &ata_sff_port_ops,
.sff_data_xfer = ixp4xx_mmio_data_xfer,
.cable_detect = ata_cable_40wire,
.set_mode = ixp4xx_set_mode,
};
static void ixp4xx_setup_port(struct ata_port *ap,
struct ixp4xx_pata_data *data,
unsigned long raw_cs0, unsigned long raw_cs1)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
unsigned long raw_cmd = raw_cs0;
unsigned long raw_ctl = raw_cs1 + 0x06;
ioaddr->cmd_addr = data->cs0;
ioaddr->altstatus_addr = data->cs1 + 0x06;
ioaddr->ctl_addr = data->cs1 + 0x06;
ata_sff_std_ports(ioaddr);
#ifndef __ARMEB__
/* adjust the addresses to handle the address swizzling of the
* ixp4xx in little endian mode.
*/
*(unsigned long *)&ioaddr->data_addr ^= 0x02;
*(unsigned long *)&ioaddr->cmd_addr ^= 0x03;
*(unsigned long *)&ioaddr->altstatus_addr ^= 0x03;
*(unsigned long *)&ioaddr->ctl_addr ^= 0x03;
*(unsigned long *)&ioaddr->error_addr ^= 0x03;
*(unsigned long *)&ioaddr->feature_addr ^= 0x03;
*(unsigned long *)&ioaddr->nsect_addr ^= 0x03;
*(unsigned long *)&ioaddr->lbal_addr ^= 0x03;
*(unsigned long *)&ioaddr->lbam_addr ^= 0x03;
*(unsigned long *)&ioaddr->lbah_addr ^= 0x03;
*(unsigned long *)&ioaddr->device_addr ^= 0x03;
*(unsigned long *)&ioaddr->status_addr ^= 0x03;
*(unsigned long *)&ioaddr->command_addr ^= 0x03;
raw_cmd ^= 0x03;
raw_ctl ^= 0x03;
#endif
ata_port_desc(ap, "cmd 0x%lx ctl 0x%lx", raw_cmd, raw_ctl);
}
static __devinit int ixp4xx_pata_probe(struct platform_device *pdev)
{
unsigned int irq;
struct resource *cs0, *cs1;
struct ata_host *host;
struct ata_port *ap;
struct ixp4xx_pata_data *data = pdev->dev.platform_data;
cs0 = platform_get_resource(pdev, IORESOURCE_MEM, 0);
cs1 = platform_get_resource(pdev, IORESOURCE_MEM, 1);
if (!cs0 || !cs1)
return -EINVAL;
/* allocate host */
host = ata_host_alloc(&pdev->dev, 1);
if (!host)
return -ENOMEM;
/* acquire resources and fill host */
pdev->dev.coherent_dma_mask = DMA_BIT_MASK(32);
data->cs0 = devm_ioremap(&pdev->dev, cs0->start, 0x1000);
data->cs1 = devm_ioremap(&pdev->dev, cs1->start, 0x1000);
if (!data->cs0 || !data->cs1)
return -ENOMEM;
irq = platform_get_irq(pdev, 0);
if (irq)
irq_set_irq_type(irq, IRQ_TYPE_EDGE_RISING);
/* Setup expansion bus chip selects */
*data->cs0_cfg = data->cs0_bits;
*data->cs1_cfg = data->cs1_bits;
ap = host->ports[0];
ap->ops = &ixp4xx_port_ops;
ap->pio_mask = ATA_PIO4;
ap->flags |= ATA_FLAG_NO_ATAPI;
ixp4xx_setup_port(ap, data, cs0->start, cs1->start);
ata_print_version_once(&pdev->dev, DRV_VERSION);
/* activate host */
return ata_host_activate(host, irq, ata_sff_interrupt, 0, &ixp4xx_sht);
}
static __devexit int ixp4xx_pata_remove(struct platform_device *dev)
{
struct ata_host *host = platform_get_drvdata(dev);
ata_host_detach(host);
return 0;
}
static struct platform_driver ixp4xx_pata_platform_driver = {
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
},
.probe = ixp4xx_pata_probe,
.remove = __devexit_p(ixp4xx_pata_remove),
};
module_platform_driver(ixp4xx_pata_platform_driver);
MODULE_AUTHOR("Alessandro Zummo <a.zummo@towertech.it>");
MODULE_DESCRIPTION("low-level driver for ixp4xx Compact Flash PATA");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
MODULE_ALIAS("platform:" DRV_NAME);
| gpl-2.0 |
huiyiqun/kernel_flo | drivers/input/keyboard/opencores-kbd.c | 5072 | 4238 | /*
* OpenCores Keyboard Controller Driver
* http://www.opencores.org/project,keyboardcontroller
*
* Copyright 2007-2009 HV Sistemas S.L.
*
* Licensed under the GPL-2 or later.
*/
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/ioport.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
struct opencores_kbd {
struct input_dev *input;
struct resource *addr_res;
void __iomem *addr;
int irq;
unsigned short keycodes[128];
};
static irqreturn_t opencores_kbd_isr(int irq, void *dev_id)
{
struct opencores_kbd *opencores_kbd = dev_id;
struct input_dev *input = opencores_kbd->input;
unsigned char c;
c = readb(opencores_kbd->addr);
input_report_key(input, c & 0x7f, c & 0x80 ? 0 : 1);
input_sync(input);
return IRQ_HANDLED;
}
static int __devinit opencores_kbd_probe(struct platform_device *pdev)
{
struct input_dev *input;
struct opencores_kbd *opencores_kbd;
struct resource *res;
int irq, i, error;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&pdev->dev, "missing board memory resource\n");
return -EINVAL;
}
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
dev_err(&pdev->dev, "missing board IRQ resource\n");
return -EINVAL;
}
opencores_kbd = kzalloc(sizeof(*opencores_kbd), GFP_KERNEL);
input = input_allocate_device();
if (!opencores_kbd || !input) {
dev_err(&pdev->dev, "failed to allocate device structures\n");
error = -ENOMEM;
goto err_free_mem;
}
opencores_kbd->addr_res = res;
res = request_mem_region(res->start, resource_size(res), pdev->name);
if (!res) {
dev_err(&pdev->dev, "failed to request I/O memory\n");
error = -EBUSY;
goto err_free_mem;
}
opencores_kbd->addr = ioremap(res->start, resource_size(res));
if (!opencores_kbd->addr) {
dev_err(&pdev->dev, "failed to remap I/O memory\n");
error = -ENXIO;
goto err_rel_mem;
}
opencores_kbd->input = input;
opencores_kbd->irq = irq;
input->name = pdev->name;
input->phys = "opencores-kbd/input0";
input->dev.parent = &pdev->dev;
input_set_drvdata(input, opencores_kbd);
input->id.bustype = BUS_HOST;
input->id.vendor = 0x0001;
input->id.product = 0x0001;
input->id.version = 0x0100;
input->keycode = opencores_kbd->keycodes;
input->keycodesize = sizeof(opencores_kbd->keycodes[0]);
input->keycodemax = ARRAY_SIZE(opencores_kbd->keycodes);
__set_bit(EV_KEY, input->evbit);
for (i = 0; i < ARRAY_SIZE(opencores_kbd->keycodes); i++) {
/*
* OpenCores controller happens to have scancodes match
* our KEY_* definitions.
*/
opencores_kbd->keycodes[i] = i;
__set_bit(opencores_kbd->keycodes[i], input->keybit);
}
__clear_bit(KEY_RESERVED, input->keybit);
error = request_irq(irq, &opencores_kbd_isr,
IRQF_TRIGGER_RISING, pdev->name, opencores_kbd);
if (error) {
dev_err(&pdev->dev, "unable to claim irq %d\n", irq);
goto err_unmap_mem;
}
error = input_register_device(input);
if (error) {
dev_err(&pdev->dev, "unable to register input device\n");
goto err_free_irq;
}
platform_set_drvdata(pdev, opencores_kbd);
return 0;
err_free_irq:
free_irq(irq, opencores_kbd);
err_unmap_mem:
iounmap(opencores_kbd->addr);
err_rel_mem:
release_mem_region(res->start, resource_size(res));
err_free_mem:
input_free_device(input);
kfree(opencores_kbd);
return error;
}
static int __devexit opencores_kbd_remove(struct platform_device *pdev)
{
struct opencores_kbd *opencores_kbd = platform_get_drvdata(pdev);
free_irq(opencores_kbd->irq, opencores_kbd);
iounmap(opencores_kbd->addr);
release_mem_region(opencores_kbd->addr_res->start,
resource_size(opencores_kbd->addr_res));
input_unregister_device(opencores_kbd->input);
kfree(opencores_kbd);
platform_set_drvdata(pdev, NULL);
return 0;
}
static struct platform_driver opencores_kbd_device_driver = {
.probe = opencores_kbd_probe,
.remove = __devexit_p(opencores_kbd_remove),
.driver = {
.name = "opencores-kbd",
},
};
module_platform_driver(opencores_kbd_device_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Javier Herrero <jherrero@hvsistemas.es>");
MODULE_DESCRIPTION("Keyboard driver for OpenCores Keyboard Controller");
| gpl-2.0 |
ghsr/android_kernel_samsung_i9152 | arch/powerpc/platforms/52xx/lite5200.c | 7632 | 5046 | /*
* Freescale Lite5200 board support
*
* Written by: Grant Likely <grant.likely@secretlab.ca>
*
* Copyright (C) Secret Lab Technologies Ltd. 2006. All rights reserved.
* Copyright (C) Freescale Semicondutor, Inc. 2006. All rights reserved.
*
* Description:
* 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/init.h>
#include <linux/pci.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/root_dev.h>
#include <linux/initrd.h>
#include <asm/time.h>
#include <asm/io.h>
#include <asm/machdep.h>
#include <asm/prom.h>
#include <asm/mpc52xx.h>
/* ************************************************************************
*
* Setup the architecture
*
*/
/* mpc5200 device tree match tables */
static struct of_device_id mpc5200_cdm_ids[] __initdata = {
{ .compatible = "fsl,mpc5200-cdm", },
{ .compatible = "mpc5200-cdm", },
{}
};
static struct of_device_id mpc5200_gpio_ids[] __initdata = {
{ .compatible = "fsl,mpc5200-gpio", },
{ .compatible = "mpc5200-gpio", },
{}
};
/*
* Fix clock configuration.
*
* Firmware is supposed to be responsible for this. If you are creating a
* new board port, do *NOT* duplicate this code. Fix your boot firmware
* to set it correctly in the first place
*/
static void __init
lite5200_fix_clock_config(void)
{
struct device_node *np;
struct mpc52xx_cdm __iomem *cdm;
/* Map zones */
np = of_find_matching_node(NULL, mpc5200_cdm_ids);
cdm = of_iomap(np, 0);
of_node_put(np);
if (!cdm) {
printk(KERN_ERR "%s() failed; expect abnormal behaviour\n",
__func__);
return;
}
/* Use internal 48 Mhz */
out_8(&cdm->ext_48mhz_en, 0x00);
out_8(&cdm->fd_enable, 0x01);
if (in_be32(&cdm->rstcfg) & 0x40) /* Assumes 33Mhz clock */
out_be16(&cdm->fd_counters, 0x0001);
else
out_be16(&cdm->fd_counters, 0x5555);
/* Unmap the regs */
iounmap(cdm);
}
/*
* Fix setting of port_config register.
*
* Firmware is supposed to be responsible for this. If you are creating a
* new board port, do *NOT* duplicate this code. Fix your boot firmware
* to set it correctly in the first place
*/
static void __init
lite5200_fix_port_config(void)
{
struct device_node *np;
struct mpc52xx_gpio __iomem *gpio;
u32 port_config;
np = of_find_matching_node(NULL, mpc5200_gpio_ids);
gpio = of_iomap(np, 0);
of_node_put(np);
if (!gpio) {
printk(KERN_ERR "%s() failed. expect abnormal behavior\n",
__func__);
return;
}
/* Set port config */
port_config = in_be32(&gpio->port_config);
port_config &= ~0x00800000; /* 48Mhz internal, pin is GPIO */
port_config &= ~0x00007000; /* USB port : Differential mode */
port_config |= 0x00001000; /* USB 1 only */
port_config &= ~0x03000000; /* ATA CS is on csb_4/5 */
port_config |= 0x01000000;
pr_debug("port_config: old:%x new:%x\n",
in_be32(&gpio->port_config), port_config);
out_be32(&gpio->port_config, port_config);
/* Unmap zone */
iounmap(gpio);
}
#ifdef CONFIG_PM
static void lite5200_suspend_prepare(void __iomem *mbar)
{
u8 pin = 1; /* GPIO_WKUP_1 (GPIO_PSC2_4) */
u8 level = 0; /* wakeup on low level */
mpc52xx_set_wakeup_gpio(pin, level);
/*
* power down usb port
* this needs to be called before of-ohci suspend code
*/
/* set ports to "power switched" and "powered at the same time"
* USB Rh descriptor A: NPS = 0, PSM = 0 */
out_be32(mbar + 0x1048, in_be32(mbar + 0x1048) & ~0x300);
/* USB Rh status: LPS = 1 - turn off power */
out_be32(mbar + 0x1050, 0x00000001);
}
static void lite5200_resume_finish(void __iomem *mbar)
{
/* USB Rh status: LPSC = 1 - turn on power */
out_be32(mbar + 0x1050, 0x00010000);
}
#endif
static void __init lite5200_setup_arch(void)
{
if (ppc_md.progress)
ppc_md.progress("lite5200_setup_arch()", 0);
/* Map important registers from the internal memory map */
mpc52xx_map_common_devices();
/* Some mpc5200 & mpc5200b related configuration */
mpc5200_setup_xlb_arbiter();
/* Fix things that firmware should have done. */
lite5200_fix_clock_config();
lite5200_fix_port_config();
#ifdef CONFIG_PM
mpc52xx_suspend.board_suspend_prepare = lite5200_suspend_prepare;
mpc52xx_suspend.board_resume_finish = lite5200_resume_finish;
lite5200_pm_init();
#endif
mpc52xx_setup_pci();
}
static const char *board[] __initdata = {
"fsl,lite5200",
"fsl,lite5200b",
NULL,
};
/*
* Called very early, MMU is off, device-tree isn't unflattened
*/
static int __init lite5200_probe(void)
{
return of_flat_dt_match(of_get_flat_dt_root(), board);
}
define_machine(lite5200) {
.name = "lite5200",
.probe = lite5200_probe,
.setup_arch = lite5200_setup_arch,
.init = mpc52xx_declare_of_platform_devices,
.init_IRQ = mpc52xx_init_irq,
.get_irq = mpc52xx_get_irq,
.restart = mpc52xx_restart,
.calibrate_decr = generic_calibrate_decr,
};
| gpl-2.0 |
simone201/Talon-SH-Vibrant | net/irda/parameters.c | 11216 | 15732 | /*********************************************************************
*
* Filename: parameters.c
* Version: 1.0
* Description: A more general way to handle (pi,pl,pv) parameters
* Status: Experimental.
* Author: Dag Brattli <dagb@cs.uit.no>
* Created at: Mon Jun 7 10:25:11 1999
* Modified at: Sun Jan 30 14:08:39 2000
* Modified by: Dag Brattli <dagb@cs.uit.no>
*
* Copyright (c) 1999-2000 Dag Brattli, All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
********************************************************************/
#include <linux/types.h>
#include <linux/module.h>
#include <asm/unaligned.h>
#include <asm/byteorder.h>
#include <net/irda/irda.h>
#include <net/irda/parameters.h>
static int irda_extract_integer(void *self, __u8 *buf, int len, __u8 pi,
PV_TYPE type, PI_HANDLER func);
static int irda_extract_string(void *self, __u8 *buf, int len, __u8 pi,
PV_TYPE type, PI_HANDLER func);
static int irda_extract_octseq(void *self, __u8 *buf, int len, __u8 pi,
PV_TYPE type, PI_HANDLER func);
static int irda_extract_no_value(void *self, __u8 *buf, int len, __u8 pi,
PV_TYPE type, PI_HANDLER func);
static int irda_insert_integer(void *self, __u8 *buf, int len, __u8 pi,
PV_TYPE type, PI_HANDLER func);
static int irda_insert_no_value(void *self, __u8 *buf, int len, __u8 pi,
PV_TYPE type, PI_HANDLER func);
static int irda_param_unpack(__u8 *buf, char *fmt, ...);
/* Parameter value call table. Must match PV_TYPE */
static PV_HANDLER pv_extract_table[] = {
irda_extract_integer, /* Handler for any length integers */
irda_extract_integer, /* Handler for 8 bits integers */
irda_extract_integer, /* Handler for 16 bits integers */
irda_extract_string, /* Handler for strings */
irda_extract_integer, /* Handler for 32 bits integers */
irda_extract_octseq, /* Handler for octet sequences */
irda_extract_no_value /* Handler for no value parameters */
};
static PV_HANDLER pv_insert_table[] = {
irda_insert_integer, /* Handler for any length integers */
irda_insert_integer, /* Handler for 8 bits integers */
irda_insert_integer, /* Handler for 16 bits integers */
NULL, /* Handler for strings */
irda_insert_integer, /* Handler for 32 bits integers */
NULL, /* Handler for octet sequences */
irda_insert_no_value /* Handler for no value parameters */
};
/*
* Function irda_insert_no_value (self, buf, len, pi, type, func)
*/
static int irda_insert_no_value(void *self, __u8 *buf, int len, __u8 pi,
PV_TYPE type, PI_HANDLER func)
{
irda_param_t p;
int ret;
p.pi = pi;
p.pl = 0;
/* Call handler for this parameter */
ret = (*func)(self, &p, PV_GET);
/* Extract values anyway, since handler may need them */
irda_param_pack(buf, "bb", p.pi, p.pl);
if (ret < 0)
return ret;
return 2; /* Inserted pl+2 bytes */
}
/*
* Function irda_extract_no_value (self, buf, len, type, func)
*
* Extracts a parameter without a pv field (pl=0)
*
*/
static int irda_extract_no_value(void *self, __u8 *buf, int len, __u8 pi,
PV_TYPE type, PI_HANDLER func)
{
irda_param_t p;
int ret;
/* Extract values anyway, since handler may need them */
irda_param_unpack(buf, "bb", &p.pi, &p.pl);
/* Call handler for this parameter */
ret = (*func)(self, &p, PV_PUT);
if (ret < 0)
return ret;
return 2; /* Extracted pl+2 bytes */
}
/*
* Function irda_insert_integer (self, buf, len, pi, type, func)
*/
static int irda_insert_integer(void *self, __u8 *buf, int len, __u8 pi,
PV_TYPE type, PI_HANDLER func)
{
irda_param_t p;
int n = 0;
int err;
p.pi = pi; /* In case handler needs to know */
p.pl = type & PV_MASK; /* The integer type codes the length as well */
p.pv.i = 0; /* Clear value */
/* Call handler for this parameter */
err = (*func)(self, &p, PV_GET);
if (err < 0)
return err;
/*
* If parameter length is still 0, then (1) this is an any length
* integer, and (2) the handler function does not care which length
* we choose to use, so we pick the one the gives the fewest bytes.
*/
if (p.pl == 0) {
if (p.pv.i < 0xff) {
IRDA_DEBUG(2, "%s(), using 1 byte\n", __func__);
p.pl = 1;
} else if (p.pv.i < 0xffff) {
IRDA_DEBUG(2, "%s(), using 2 bytes\n", __func__);
p.pl = 2;
} else {
IRDA_DEBUG(2, "%s(), using 4 bytes\n", __func__);
p.pl = 4; /* Default length */
}
}
/* Check if buffer is long enough for insertion */
if (len < (2+p.pl)) {
IRDA_WARNING("%s: buffer too short for insertion!\n",
__func__);
return -1;
}
IRDA_DEBUG(2, "%s(), pi=%#x, pl=%d, pi=%d\n", __func__,
p.pi, p.pl, p.pv.i);
switch (p.pl) {
case 1:
n += irda_param_pack(buf, "bbb", p.pi, p.pl, (__u8) p.pv.i);
break;
case 2:
if (type & PV_BIG_ENDIAN)
p.pv.i = cpu_to_be16((__u16) p.pv.i);
else
p.pv.i = cpu_to_le16((__u16) p.pv.i);
n += irda_param_pack(buf, "bbs", p.pi, p.pl, (__u16) p.pv.i);
break;
case 4:
if (type & PV_BIG_ENDIAN)
cpu_to_be32s(&p.pv.i);
else
cpu_to_le32s(&p.pv.i);
n += irda_param_pack(buf, "bbi", p.pi, p.pl, p.pv.i);
break;
default:
IRDA_WARNING("%s: length %d not supported\n",
__func__, p.pl);
/* Skip parameter */
return -1;
}
return p.pl+2; /* Inserted pl+2 bytes */
}
/*
* Function irda_extract integer (self, buf, len, pi, type, func)
*
* Extract a possibly variable length integer from buffer, and call
* handler for processing of the parameter
*/
static int irda_extract_integer(void *self, __u8 *buf, int len, __u8 pi,
PV_TYPE type, PI_HANDLER func)
{
irda_param_t p;
int n = 0;
int extract_len; /* Real length we extract */
int err;
p.pi = pi; /* In case handler needs to know */
p.pl = buf[1]; /* Extract length of value */
p.pv.i = 0; /* Clear value */
extract_len = p.pl; /* Default : extract all */
/* Check if buffer is long enough for parsing */
if (len < (2+p.pl)) {
IRDA_WARNING("%s: buffer too short for parsing! "
"Need %d bytes, but len is only %d\n",
__func__, p.pl, len);
return -1;
}
/*
* Check that the integer length is what we expect it to be. If the
* handler want a 16 bits integer then a 32 bits is not good enough
* PV_INTEGER means that the handler is flexible.
*/
if (((type & PV_MASK) != PV_INTEGER) && ((type & PV_MASK) != p.pl)) {
IRDA_ERROR("%s: invalid parameter length! "
"Expected %d bytes, but value had %d bytes!\n",
__func__, type & PV_MASK, p.pl);
/* Most parameters are bit/byte fields or little endian,
* so it's ok to only extract a subset of it (the subset
* that the handler expect). This is necessary, as some
* broken implementations seems to add extra undefined bits.
* If the parameter is shorter than we expect or is big
* endian, we can't play those tricks. Jean II */
if((p.pl < (type & PV_MASK)) || (type & PV_BIG_ENDIAN)) {
/* Skip parameter */
return p.pl+2;
} else {
/* Extract subset of it, fallthrough */
extract_len = type & PV_MASK;
}
}
switch (extract_len) {
case 1:
n += irda_param_unpack(buf+2, "b", &p.pv.i);
break;
case 2:
n += irda_param_unpack(buf+2, "s", &p.pv.i);
if (type & PV_BIG_ENDIAN)
p.pv.i = be16_to_cpu((__u16) p.pv.i);
else
p.pv.i = le16_to_cpu((__u16) p.pv.i);
break;
case 4:
n += irda_param_unpack(buf+2, "i", &p.pv.i);
if (type & PV_BIG_ENDIAN)
be32_to_cpus(&p.pv.i);
else
le32_to_cpus(&p.pv.i);
break;
default:
IRDA_WARNING("%s: length %d not supported\n",
__func__, p.pl);
/* Skip parameter */
return p.pl+2;
}
IRDA_DEBUG(2, "%s(), pi=%#x, pl=%d, pi=%d\n", __func__,
p.pi, p.pl, p.pv.i);
/* Call handler for this parameter */
err = (*func)(self, &p, PV_PUT);
if (err < 0)
return err;
return p.pl+2; /* Extracted pl+2 bytes */
}
/*
* Function irda_extract_string (self, buf, len, type, func)
*/
static int irda_extract_string(void *self, __u8 *buf, int len, __u8 pi,
PV_TYPE type, PI_HANDLER func)
{
char str[33];
irda_param_t p;
int err;
IRDA_DEBUG(2, "%s()\n", __func__);
p.pi = pi; /* In case handler needs to know */
p.pl = buf[1]; /* Extract length of value */
if (p.pl > 32)
p.pl = 32;
IRDA_DEBUG(2, "%s(), pi=%#x, pl=%d\n", __func__,
p.pi, p.pl);
/* Check if buffer is long enough for parsing */
if (len < (2+p.pl)) {
IRDA_WARNING("%s: buffer too short for parsing! "
"Need %d bytes, but len is only %d\n",
__func__, p.pl, len);
return -1;
}
/* Should be safe to copy string like this since we have already
* checked that the buffer is long enough */
strncpy(str, buf+2, p.pl);
IRDA_DEBUG(2, "%s(), str=0x%02x 0x%02x\n", __func__,
(__u8) str[0], (__u8) str[1]);
/* Null terminate string */
str[p.pl] = '\0';
p.pv.c = str; /* Handler will need to take a copy */
/* Call handler for this parameter */
err = (*func)(self, &p, PV_PUT);
if (err < 0)
return err;
return p.pl+2; /* Extracted pl+2 bytes */
}
/*
* Function irda_extract_octseq (self, buf, len, type, func)
*/
static int irda_extract_octseq(void *self, __u8 *buf, int len, __u8 pi,
PV_TYPE type, PI_HANDLER func)
{
irda_param_t p;
p.pi = pi; /* In case handler needs to know */
p.pl = buf[1]; /* Extract length of value */
/* Check if buffer is long enough for parsing */
if (len < (2+p.pl)) {
IRDA_WARNING("%s: buffer too short for parsing! "
"Need %d bytes, but len is only %d\n",
__func__, p.pl, len);
return -1;
}
IRDA_DEBUG(0, "%s(), not impl\n", __func__);
return p.pl+2; /* Extracted pl+2 bytes */
}
/*
* Function irda_param_pack (skb, fmt, ...)
*
* Format:
* 'i' = 32 bits integer
* 's' = string
*
*/
int irda_param_pack(__u8 *buf, char *fmt, ...)
{
irda_pv_t arg;
va_list args;
char *p;
int n = 0;
va_start(args, fmt);
for (p = fmt; *p != '\0'; p++) {
switch (*p) {
case 'b': /* 8 bits unsigned byte */
buf[n++] = (__u8)va_arg(args, int);
break;
case 's': /* 16 bits unsigned short */
arg.i = (__u16)va_arg(args, int);
put_unaligned((__u16)arg.i, (__u16 *)(buf+n)); n+=2;
break;
case 'i': /* 32 bits unsigned integer */
arg.i = va_arg(args, __u32);
put_unaligned(arg.i, (__u32 *)(buf+n)); n+=4;
break;
#if 0
case 'c': /* \0 terminated string */
arg.c = va_arg(args, char *);
strcpy(buf+n, arg.c);
n += strlen(arg.c) + 1;
break;
#endif
default:
va_end(args);
return -1;
}
}
va_end(args);
return 0;
}
EXPORT_SYMBOL(irda_param_pack);
/*
* Function irda_param_unpack (skb, fmt, ...)
*/
static int irda_param_unpack(__u8 *buf, char *fmt, ...)
{
irda_pv_t arg;
va_list args;
char *p;
int n = 0;
va_start(args, fmt);
for (p = fmt; *p != '\0'; p++) {
switch (*p) {
case 'b': /* 8 bits byte */
arg.ip = va_arg(args, __u32 *);
*arg.ip = buf[n++];
break;
case 's': /* 16 bits short */
arg.ip = va_arg(args, __u32 *);
*arg.ip = get_unaligned((__u16 *)(buf+n)); n+=2;
break;
case 'i': /* 32 bits unsigned integer */
arg.ip = va_arg(args, __u32 *);
*arg.ip = get_unaligned((__u32 *)(buf+n)); n+=4;
break;
#if 0
case 'c': /* \0 terminated string */
arg.c = va_arg(args, char *);
strcpy(arg.c, buf+n);
n += strlen(arg.c) + 1;
break;
#endif
default:
va_end(args);
return -1;
}
}
va_end(args);
return 0;
}
/*
* Function irda_param_insert (self, pi, buf, len, info)
*
* Insert the specified parameter (pi) into buffer. Returns number of
* bytes inserted
*/
int irda_param_insert(void *self, __u8 pi, __u8 *buf, int len,
pi_param_info_t *info)
{
pi_minor_info_t *pi_minor_info;
__u8 pi_minor;
__u8 pi_major;
int type;
int ret = -1;
int n = 0;
IRDA_ASSERT(buf != NULL, return ret;);
IRDA_ASSERT(info != NULL, return ret;);
pi_minor = pi & info->pi_mask;
pi_major = pi >> info->pi_major_offset;
/* Check if the identifier value (pi) is valid */
if ((pi_major > info->len-1) ||
(pi_minor > info->tables[pi_major].len-1))
{
IRDA_DEBUG(0, "%s(), no handler for parameter=0x%02x\n",
__func__, pi);
/* Skip this parameter */
return -1;
}
/* Lookup the info on how to parse this parameter */
pi_minor_info = &info->tables[pi_major].pi_minor_call_table[pi_minor];
/* Find expected data type for this parameter identifier (pi)*/
type = pi_minor_info->type;
/* Check if handler has been implemented */
if (!pi_minor_info->func) {
IRDA_MESSAGE("%s: no handler for pi=%#x\n", __func__, pi);
/* Skip this parameter */
return -1;
}
/* Insert parameter value */
ret = (*pv_insert_table[type & PV_MASK])(self, buf+n, len, pi, type,
pi_minor_info->func);
return ret;
}
EXPORT_SYMBOL(irda_param_insert);
/*
* Function irda_param_extract (self, buf, len, info)
*
* Parse all parameters. If len is correct, then everything should be
* safe. Returns the number of bytes that was parsed
*
*/
static int irda_param_extract(void *self, __u8 *buf, int len,
pi_param_info_t *info)
{
pi_minor_info_t *pi_minor_info;
__u8 pi_minor;
__u8 pi_major;
int type;
int ret = -1;
int n = 0;
IRDA_ASSERT(buf != NULL, return ret;);
IRDA_ASSERT(info != NULL, return ret;);
pi_minor = buf[n] & info->pi_mask;
pi_major = buf[n] >> info->pi_major_offset;
/* Check if the identifier value (pi) is valid */
if ((pi_major > info->len-1) ||
(pi_minor > info->tables[pi_major].len-1))
{
IRDA_DEBUG(0, "%s(), no handler for parameter=0x%02x\n",
__func__, buf[0]);
/* Skip this parameter */
return 2 + buf[n + 1]; /* Continue */
}
/* Lookup the info on how to parse this parameter */
pi_minor_info = &info->tables[pi_major].pi_minor_call_table[pi_minor];
/* Find expected data type for this parameter identifier (pi)*/
type = pi_minor_info->type;
IRDA_DEBUG(3, "%s(), pi=[%d,%d], type=%d\n", __func__,
pi_major, pi_minor, type);
/* Check if handler has been implemented */
if (!pi_minor_info->func) {
IRDA_MESSAGE("%s: no handler for pi=%#x\n",
__func__, buf[n]);
/* Skip this parameter */
return 2 + buf[n + 1]; /* Continue */
}
/* Parse parameter value */
ret = (*pv_extract_table[type & PV_MASK])(self, buf+n, len, buf[n],
type, pi_minor_info->func);
return ret;
}
/*
* Function irda_param_extract_all (self, buf, len, info)
*
* Parse all parameters. If len is correct, then everything should be
* safe. Returns the number of bytes that was parsed
*
*/
int irda_param_extract_all(void *self, __u8 *buf, int len,
pi_param_info_t *info)
{
int ret = -1;
int n = 0;
IRDA_ASSERT(buf != NULL, return ret;);
IRDA_ASSERT(info != NULL, return ret;);
/*
* Parse all parameters. Each parameter must be at least two bytes
* long or else there is no point in trying to parse it
*/
while (len > 2) {
ret = irda_param_extract(self, buf+n, len, info);
if (ret < 0)
return ret;
n += ret;
len -= ret;
}
return n;
}
EXPORT_SYMBOL(irda_param_extract_all);
| gpl-2.0 |
kennethlyn/parallella-lcd-linux | net/sunrpc/auth_gss/gss_generic_token.c | 11472 | 6207 | /*
* linux/net/sunrpc/gss_generic_token.c
*
* Adapted from MIT Kerberos 5-1.2.1 lib/gssapi/generic/util_token.c
*
* Copyright (c) 2000 The Regents of the University of Michigan.
* All rights reserved.
*
* Andy Adamson <andros@umich.edu>
*/
/*
* Copyright 1993 by OpenVision Technologies, Inc.
*
* Permission to use, copy, modify, distribute, and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appears in all copies and
* that both that copyright notice and this permission notice appear in
* supporting documentation, and that the name of OpenVision not be used
* in advertising or publicity pertaining to distribution of the software
* without specific, written prior permission. OpenVision makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
* OPENVISION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
* EVENT SHALL OPENVISION BE LIABLE FOR ANY SPECIAL, 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/types.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/sunrpc/sched.h>
#include <linux/sunrpc/gss_asn1.h>
#ifdef RPC_DEBUG
# define RPCDBG_FACILITY RPCDBG_AUTH
#endif
/* TWRITE_STR from gssapiP_generic.h */
#define TWRITE_STR(ptr, str, len) \
memcpy((ptr), (char *) (str), (len)); \
(ptr) += (len);
/* XXXX this code currently makes the assumption that a mech oid will
never be longer than 127 bytes. This assumption is not inherent in
the interfaces, so the code can be fixed if the OSI namespace
balloons unexpectedly. */
/* Each token looks like this:
0x60 tag for APPLICATION 0, SEQUENCE
(constructed, definite-length)
<length> possible multiple bytes, need to parse/generate
0x06 tag for OBJECT IDENTIFIER
<moid_length> compile-time constant string (assume 1 byte)
<moid_bytes> compile-time constant string
<inner_bytes> the ANY containing the application token
bytes 0,1 are the token type
bytes 2,n are the token data
For the purposes of this abstraction, the token "header" consists of
the sequence tag and length octets, the mech OID DER encoding, and the
first two inner bytes, which indicate the token type. The token
"body" consists of everything else.
*/
static int
der_length_size( int length)
{
if (length < (1<<7))
return 1;
else if (length < (1<<8))
return 2;
#if (SIZEOF_INT == 2)
else
return 3;
#else
else if (length < (1<<16))
return 3;
else if (length < (1<<24))
return 4;
else
return 5;
#endif
}
static void
der_write_length(unsigned char **buf, int length)
{
if (length < (1<<7)) {
*(*buf)++ = (unsigned char) length;
} else {
*(*buf)++ = (unsigned char) (der_length_size(length)+127);
#if (SIZEOF_INT > 2)
if (length >= (1<<24))
*(*buf)++ = (unsigned char) (length>>24);
if (length >= (1<<16))
*(*buf)++ = (unsigned char) ((length>>16)&0xff);
#endif
if (length >= (1<<8))
*(*buf)++ = (unsigned char) ((length>>8)&0xff);
*(*buf)++ = (unsigned char) (length&0xff);
}
}
/* returns decoded length, or < 0 on failure. Advances buf and
decrements bufsize */
static int
der_read_length(unsigned char **buf, int *bufsize)
{
unsigned char sf;
int ret;
if (*bufsize < 1)
return -1;
sf = *(*buf)++;
(*bufsize)--;
if (sf & 0x80) {
if ((sf &= 0x7f) > ((*bufsize)-1))
return -1;
if (sf > SIZEOF_INT)
return -1;
ret = 0;
for (; sf; sf--) {
ret = (ret<<8) + (*(*buf)++);
(*bufsize)--;
}
} else {
ret = sf;
}
return ret;
}
/* returns the length of a token, given the mech oid and the body size */
int
g_token_size(struct xdr_netobj *mech, unsigned int body_size)
{
/* set body_size to sequence contents size */
body_size += 2 + (int) mech->len; /* NEED overflow check */
return 1 + der_length_size(body_size) + body_size;
}
EXPORT_SYMBOL_GPL(g_token_size);
/* fills in a buffer with the token header. The buffer is assumed to
be the right size. buf is advanced past the token header */
void
g_make_token_header(struct xdr_netobj *mech, int body_size, unsigned char **buf)
{
*(*buf)++ = 0x60;
der_write_length(buf, 2 + mech->len + body_size);
*(*buf)++ = 0x06;
*(*buf)++ = (unsigned char) mech->len;
TWRITE_STR(*buf, mech->data, ((int) mech->len));
}
EXPORT_SYMBOL_GPL(g_make_token_header);
/*
* Given a buffer containing a token, reads and verifies the token,
* leaving buf advanced past the token header, and setting body_size
* to the number of remaining bytes. Returns 0 on success,
* G_BAD_TOK_HEADER for a variety of errors, and G_WRONG_MECH if the
* mechanism in the token does not match the mech argument. buf and
* *body_size are left unmodified on error.
*/
u32
g_verify_token_header(struct xdr_netobj *mech, int *body_size,
unsigned char **buf_in, int toksize)
{
unsigned char *buf = *buf_in;
int seqsize;
struct xdr_netobj toid;
int ret = 0;
if ((toksize-=1) < 0)
return G_BAD_TOK_HEADER;
if (*buf++ != 0x60)
return G_BAD_TOK_HEADER;
if ((seqsize = der_read_length(&buf, &toksize)) < 0)
return G_BAD_TOK_HEADER;
if (seqsize != toksize)
return G_BAD_TOK_HEADER;
if ((toksize-=1) < 0)
return G_BAD_TOK_HEADER;
if (*buf++ != 0x06)
return G_BAD_TOK_HEADER;
if ((toksize-=1) < 0)
return G_BAD_TOK_HEADER;
toid.len = *buf++;
if ((toksize-=toid.len) < 0)
return G_BAD_TOK_HEADER;
toid.data = buf;
buf+=toid.len;
if (! g_OID_equal(&toid, mech))
ret = G_WRONG_MECH;
/* G_WRONG_MECH is not returned immediately because it's more important
to return G_BAD_TOK_HEADER if the token header is in fact bad */
if ((toksize-=2) < 0)
return G_BAD_TOK_HEADER;
if (ret)
return ret;
if (!ret) {
*buf_in = buf;
*body_size = toksize;
}
return ret;
}
EXPORT_SYMBOL_GPL(g_verify_token_header);
| gpl-2.0 |
0xD34D/-0xD34D--Kindle-Fire-Kernel | sound/oss/soundcard.c | 465 | 17564 | /*
* linux/sound/oss/soundcard.c
*
* Sound card driver for Linux
*
*
* Copyright (C) by Hannu Savolainen 1993-1997
*
* OSS/Free for Linux is distributed under the GNU GENERAL PUBLIC LICENSE (GPL)
* Version 2 (June 1991). See the "COPYING" file distributed with this software
* for more info.
*
*
* Thomas Sailer : ioctl code reworked (vmalloc/vfree removed)
* integrated sound_switch.c
* Stefan Reinauer : integrated /proc/sound (equals to /dev/sndstat,
* which should disappear in the near future)
* Eric Dumas : devfs support (22-Jan-98) <dumas@linux.eu.org> with
* fixups by C. Scott Ananian <cananian@alumni.princeton.edu>
* Richard Gooch : moved common (non OSS-specific) devices to sound_core.c
* Rob Riggs : Added persistent DMA buffers support (1998/10/17)
* Christoph Hellwig : Some cleanup work (2000/03/01)
*/
#include "sound_config.h"
#include <linux/init.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/signal.h>
#include <linux/fcntl.h>
#include <linux/ctype.h>
#include <linux/stddef.h>
#include <linux/kmod.h>
#include <linux/kernel.h>
#include <asm/dma.h>
#include <asm/io.h>
#include <linux/wait.h>
#include <linux/ioport.h>
#include <linux/major.h>
#include <linux/delay.h>
#include <linux/proc_fs.h>
#include <linux/smp_lock.h>
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/device.h>
/*
* This ought to be moved into include/asm/dma.h
*/
#ifndef valid_dma
#define valid_dma(n) ((n) >= 0 && (n) < MAX_DMA_CHANNELS && (n) != 4)
#endif
/*
* Table for permanently allocated memory (used when unloading the module)
*/
void * sound_mem_blocks[MAX_MEM_BLOCKS];
int sound_nblocks = 0;
/* Persistent DMA buffers */
#ifdef CONFIG_SOUND_DMAP
int sound_dmap_flag = 1;
#else
int sound_dmap_flag = 0;
#endif
static char dma_alloc_map[MAX_DMA_CHANNELS];
#define DMA_MAP_UNAVAIL 0
#define DMA_MAP_FREE 1
#define DMA_MAP_BUSY 2
unsigned long seq_time = 0; /* Time for /dev/sequencer */
extern struct class *sound_class;
/*
* Table for configurable mixer volume handling
*/
static mixer_vol_table mixer_vols[MAX_MIXER_DEV];
static int num_mixer_volumes;
int *load_mixer_volumes(char *name, int *levels, int present)
{
int i, n;
for (i = 0; i < num_mixer_volumes; i++) {
if (strcmp(name, mixer_vols[i].name) == 0) {
if (present)
mixer_vols[i].num = i;
return mixer_vols[i].levels;
}
}
if (num_mixer_volumes >= MAX_MIXER_DEV) {
printk(KERN_ERR "Sound: Too many mixers (%s)\n", name);
return levels;
}
n = num_mixer_volumes++;
strcpy(mixer_vols[n].name, name);
if (present)
mixer_vols[n].num = n;
else
mixer_vols[n].num = -1;
for (i = 0; i < 32; i++)
mixer_vols[n].levels[i] = levels[i];
return mixer_vols[n].levels;
}
EXPORT_SYMBOL(load_mixer_volumes);
static int set_mixer_levels(void __user * arg)
{
/* mixer_vol_table is 174 bytes, so IMHO no reason to not allocate it on the stack */
mixer_vol_table buf;
if (__copy_from_user(&buf, arg, sizeof(buf)))
return -EFAULT;
load_mixer_volumes(buf.name, buf.levels, 0);
if (__copy_to_user(arg, &buf, sizeof(buf)))
return -EFAULT;
return 0;
}
static int get_mixer_levels(void __user * arg)
{
int n;
if (__get_user(n, (int __user *)(&(((mixer_vol_table __user *)arg)->num))))
return -EFAULT;
if (n < 0 || n >= num_mixer_volumes)
return -EINVAL;
if (__copy_to_user(arg, &mixer_vols[n], sizeof(mixer_vol_table)))
return -EFAULT;
return 0;
}
/* 4K page size but our output routines use some slack for overruns */
#define PROC_BLOCK_SIZE (3*1024)
static ssize_t sound_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
{
int dev = iminor(file->f_path.dentry->d_inode);
int ret = -EINVAL;
/*
* The OSS drivers aren't remotely happy without this locking,
* and unless someone fixes them when they are about to bite the
* big one anyway, we might as well bandage here..
*/
lock_kernel();
DEB(printk("sound_read(dev=%d, count=%d)\n", dev, count));
switch (dev & 0x0f) {
case SND_DEV_DSP:
case SND_DEV_DSP16:
case SND_DEV_AUDIO:
ret = audio_read(dev, file, buf, count);
break;
case SND_DEV_SEQ:
case SND_DEV_SEQ2:
ret = sequencer_read(dev, file, buf, count);
break;
case SND_DEV_MIDIN:
ret = MIDIbuf_read(dev, file, buf, count);
}
unlock_kernel();
return ret;
}
static ssize_t sound_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos)
{
int dev = iminor(file->f_path.dentry->d_inode);
int ret = -EINVAL;
lock_kernel();
DEB(printk("sound_write(dev=%d, count=%d)\n", dev, count));
switch (dev & 0x0f) {
case SND_DEV_SEQ:
case SND_DEV_SEQ2:
ret = sequencer_write(dev, file, buf, count);
break;
case SND_DEV_DSP:
case SND_DEV_DSP16:
case SND_DEV_AUDIO:
ret = audio_write(dev, file, buf, count);
break;
case SND_DEV_MIDIN:
ret = MIDIbuf_write(dev, file, buf, count);
break;
}
unlock_kernel();
return ret;
}
static int sound_open(struct inode *inode, struct file *file)
{
int dev = iminor(inode);
int retval;
DEB(printk("sound_open(dev=%d)\n", dev));
if ((dev >= SND_NDEVS) || (dev < 0)) {
printk(KERN_ERR "Invalid minor device %d\n", dev);
return -ENXIO;
}
switch (dev & 0x0f) {
case SND_DEV_CTL:
dev >>= 4;
if (dev >= 0 && dev < MAX_MIXER_DEV && mixer_devs[dev] == NULL) {
request_module("mixer%d", dev);
}
if (dev && (dev >= num_mixers || mixer_devs[dev] == NULL))
return -ENXIO;
if (!try_module_get(mixer_devs[dev]->owner))
return -ENXIO;
break;
case SND_DEV_SEQ:
case SND_DEV_SEQ2:
if ((retval = sequencer_open(dev, file)) < 0)
return retval;
break;
case SND_DEV_MIDIN:
if ((retval = MIDIbuf_open(dev, file)) < 0)
return retval;
break;
case SND_DEV_DSP:
case SND_DEV_DSP16:
case SND_DEV_AUDIO:
if ((retval = audio_open(dev, file)) < 0)
return retval;
break;
default:
printk(KERN_ERR "Invalid minor device %d\n", dev);
return -ENXIO;
}
return 0;
}
static int sound_release(struct inode *inode, struct file *file)
{
int dev = iminor(inode);
lock_kernel();
DEB(printk("sound_release(dev=%d)\n", dev));
switch (dev & 0x0f) {
case SND_DEV_CTL:
module_put(mixer_devs[dev >> 4]->owner);
break;
case SND_DEV_SEQ:
case SND_DEV_SEQ2:
sequencer_release(dev, file);
break;
case SND_DEV_MIDIN:
MIDIbuf_release(dev, file);
break;
case SND_DEV_DSP:
case SND_DEV_DSP16:
case SND_DEV_AUDIO:
audio_release(dev, file);
break;
default:
printk(KERN_ERR "Sound error: Releasing unknown device 0x%02x\n", dev);
}
unlock_kernel();
return 0;
}
static int get_mixer_info(int dev, void __user *arg)
{
mixer_info info;
memset(&info, 0, sizeof(info));
strlcpy(info.id, mixer_devs[dev]->id, sizeof(info.id));
strlcpy(info.name, mixer_devs[dev]->name, sizeof(info.name));
info.modify_counter = mixer_devs[dev]->modify_counter;
if (__copy_to_user(arg, &info, sizeof(info)))
return -EFAULT;
return 0;
}
static int get_old_mixer_info(int dev, void __user *arg)
{
_old_mixer_info info;
memset(&info, 0, sizeof(info));
strlcpy(info.id, mixer_devs[dev]->id, sizeof(info.id));
strlcpy(info.name, mixer_devs[dev]->name, sizeof(info.name));
if (copy_to_user(arg, &info, sizeof(info)))
return -EFAULT;
return 0;
}
static int sound_mixer_ioctl(int mixdev, unsigned int cmd, void __user *arg)
{
if (mixdev < 0 || mixdev >= MAX_MIXER_DEV)
return -ENXIO;
/* Try to load the mixer... */
if (mixer_devs[mixdev] == NULL) {
request_module("mixer%d", mixdev);
}
if (mixdev >= num_mixers || !mixer_devs[mixdev])
return -ENXIO;
if (cmd == SOUND_MIXER_INFO)
return get_mixer_info(mixdev, arg);
if (cmd == SOUND_OLD_MIXER_INFO)
return get_old_mixer_info(mixdev, arg);
if (_SIOC_DIR(cmd) & _SIOC_WRITE)
mixer_devs[mixdev]->modify_counter++;
if (!mixer_devs[mixdev]->ioctl)
return -EINVAL;
return mixer_devs[mixdev]->ioctl(mixdev, cmd, arg);
}
static long sound_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
int len = 0, dtype;
int dev = iminor(file->f_dentry->d_inode);
long ret = -EINVAL;
void __user *p = (void __user *)arg;
if (_SIOC_DIR(cmd) != _SIOC_NONE && _SIOC_DIR(cmd) != 0) {
/*
* Have to validate the address given by the process.
*/
len = _SIOC_SIZE(cmd);
if (len < 1 || len > 65536 || !p)
return -EFAULT;
if (_SIOC_DIR(cmd) & _SIOC_WRITE)
if (!access_ok(VERIFY_READ, p, len))
return -EFAULT;
if (_SIOC_DIR(cmd) & _SIOC_READ)
if (!access_ok(VERIFY_WRITE, p, len))
return -EFAULT;
}
DEB(printk("sound_ioctl(dev=%d, cmd=0x%x, arg=0x%x)\n", dev, cmd, arg));
if (cmd == OSS_GETVERSION)
return __put_user(SOUND_VERSION, (int __user *)p);
lock_kernel();
if (_IOC_TYPE(cmd) == 'M' && num_mixers > 0 && /* Mixer ioctl */
(dev & 0x0f) != SND_DEV_CTL) {
dtype = dev & 0x0f;
switch (dtype) {
case SND_DEV_DSP:
case SND_DEV_DSP16:
case SND_DEV_AUDIO:
ret = sound_mixer_ioctl(audio_devs[dev >> 4]->mixer_dev,
cmd, p);
break;
default:
ret = sound_mixer_ioctl(dev >> 4, cmd, p);
break;
}
unlock_kernel();
return ret;
}
switch (dev & 0x0f) {
case SND_DEV_CTL:
if (cmd == SOUND_MIXER_GETLEVELS)
ret = get_mixer_levels(p);
else if (cmd == SOUND_MIXER_SETLEVELS)
ret = set_mixer_levels(p);
else
ret = sound_mixer_ioctl(dev >> 4, cmd, p);
break;
case SND_DEV_SEQ:
case SND_DEV_SEQ2:
ret = sequencer_ioctl(dev, file, cmd, p);
break;
case SND_DEV_DSP:
case SND_DEV_DSP16:
case SND_DEV_AUDIO:
return audio_ioctl(dev, file, cmd, p);
break;
case SND_DEV_MIDIN:
return MIDIbuf_ioctl(dev, file, cmd, p);
break;
}
unlock_kernel();
return ret;
}
static unsigned int sound_poll(struct file *file, poll_table * wait)
{
struct inode *inode = file->f_path.dentry->d_inode;
int dev = iminor(inode);
DEB(printk("sound_poll(dev=%d)\n", dev));
switch (dev & 0x0f) {
case SND_DEV_SEQ:
case SND_DEV_SEQ2:
return sequencer_poll(dev, file, wait);
case SND_DEV_MIDIN:
return MIDIbuf_poll(dev, file, wait);
case SND_DEV_DSP:
case SND_DEV_DSP16:
case SND_DEV_AUDIO:
return DMAbuf_poll(file, dev >> 4, wait);
}
return 0;
}
static int sound_mmap(struct file *file, struct vm_area_struct *vma)
{
int dev_class;
unsigned long size;
struct dma_buffparms *dmap = NULL;
int dev = iminor(file->f_path.dentry->d_inode);
dev_class = dev & 0x0f;
dev >>= 4;
if (dev_class != SND_DEV_DSP && dev_class != SND_DEV_DSP16 && dev_class != SND_DEV_AUDIO) {
printk(KERN_ERR "Sound: mmap() not supported for other than audio devices\n");
return -EINVAL;
}
lock_kernel();
if (vma->vm_flags & VM_WRITE) /* Map write and read/write to the output buf */
dmap = audio_devs[dev]->dmap_out;
else if (vma->vm_flags & VM_READ)
dmap = audio_devs[dev]->dmap_in;
else {
printk(KERN_ERR "Sound: Undefined mmap() access\n");
unlock_kernel();
return -EINVAL;
}
if (dmap == NULL) {
printk(KERN_ERR "Sound: mmap() error. dmap == NULL\n");
unlock_kernel();
return -EIO;
}
if (dmap->raw_buf == NULL) {
printk(KERN_ERR "Sound: mmap() called when raw_buf == NULL\n");
unlock_kernel();
return -EIO;
}
if (dmap->mapping_flags) {
printk(KERN_ERR "Sound: mmap() called twice for the same DMA buffer\n");
unlock_kernel();
return -EIO;
}
if (vma->vm_pgoff != 0) {
printk(KERN_ERR "Sound: mmap() offset must be 0.\n");
unlock_kernel();
return -EINVAL;
}
size = vma->vm_end - vma->vm_start;
if (size != dmap->bytes_in_use) {
printk(KERN_WARNING "Sound: mmap() size = %ld. Should be %d\n", size, dmap->bytes_in_use);
}
if (remap_pfn_range(vma, vma->vm_start,
virt_to_phys(dmap->raw_buf) >> PAGE_SHIFT,
vma->vm_end - vma->vm_start, vma->vm_page_prot)) {
unlock_kernel();
return -EAGAIN;
}
dmap->mapping_flags |= DMA_MAP_MAPPED;
if( audio_devs[dev]->d->mmap)
audio_devs[dev]->d->mmap(dev);
memset(dmap->raw_buf,
dmap->neutral_byte,
dmap->bytes_in_use);
unlock_kernel();
return 0;
}
const struct file_operations oss_sound_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.read = sound_read,
.write = sound_write,
.poll = sound_poll,
.unlocked_ioctl = sound_ioctl,
.mmap = sound_mmap,
.open = sound_open,
.release = sound_release,
};
/*
* Create the required special subdevices
*/
static int create_special_devices(void)
{
int seq1,seq2;
seq1=register_sound_special(&oss_sound_fops, 1);
if(seq1==-1)
goto bad;
seq2=register_sound_special(&oss_sound_fops, 8);
if(seq2!=-1)
return 0;
unregister_sound_special(1);
bad:
return -1;
}
/* These device names follow the official Linux device list,
* Documentation/devices.txt. Let us know if there are other
* common names we should support for compatibility.
* Only those devices not created by the generic code in sound_core.c are
* registered here.
*/
static const struct {
unsigned short minor;
char *name;
umode_t mode;
int *num;
} dev_list[] = { /* list of minor devices */
/* seems to be some confusion here -- this device is not in the device list */
{SND_DEV_DSP16, "dspW", S_IWUGO | S_IRUSR | S_IRGRP,
&num_audiodevs},
{SND_DEV_AUDIO, "audio", S_IWUGO | S_IRUSR | S_IRGRP,
&num_audiodevs},
};
static int dmabuf;
static int dmabug;
module_param(dmabuf, int, 0444);
module_param(dmabug, int, 0444);
static int __init oss_init(void)
{
int err;
int i, j;
#ifdef CONFIG_PCI
if(dmabug)
isa_dma_bridge_buggy = dmabug;
#endif
err = create_special_devices();
if (err) {
printk(KERN_ERR "sound: driver already loaded/included in kernel\n");
return err;
}
/* Protecting the innocent */
sound_dmap_flag = (dmabuf > 0 ? 1 : 0);
for (i = 0; i < ARRAY_SIZE(dev_list); i++) {
device_create(sound_class, NULL,
MKDEV(SOUND_MAJOR, dev_list[i].minor), NULL,
"%s", dev_list[i].name);
if (!dev_list[i].num)
continue;
for (j = 1; j < *dev_list[i].num; j++)
device_create(sound_class, NULL,
MKDEV(SOUND_MAJOR,
dev_list[i].minor + (j*0x10)),
NULL, "%s%d", dev_list[i].name, j);
}
if (sound_nblocks >= MAX_MEM_BLOCKS - 1)
printk(KERN_ERR "Sound warning: Deallocation table was too small.\n");
return 0;
}
static void __exit oss_cleanup(void)
{
int i, j;
for (i = 0; i < ARRAY_SIZE(dev_list); i++) {
device_destroy(sound_class, MKDEV(SOUND_MAJOR, dev_list[i].minor));
if (!dev_list[i].num)
continue;
for (j = 1; j < *dev_list[i].num; j++)
device_destroy(sound_class, MKDEV(SOUND_MAJOR, dev_list[i].minor + (j*0x10)));
}
unregister_sound_special(1);
unregister_sound_special(8);
sound_stop_timer();
sequencer_unload();
for (i = 0; i < MAX_DMA_CHANNELS; i++)
if (dma_alloc_map[i] != DMA_MAP_UNAVAIL) {
printk(KERN_ERR "Sound: Hmm, DMA%d was left allocated - fixed\n", i);
sound_free_dma(i);
}
for (i = 0; i < sound_nblocks; i++)
vfree(sound_mem_blocks[i]);
}
module_init(oss_init);
module_exit(oss_cleanup);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("OSS Sound subsystem");
MODULE_AUTHOR("Hannu Savolainen, et al.");
int sound_alloc_dma(int chn, char *deviceID)
{
int err;
if ((err = request_dma(chn, deviceID)) != 0)
return err;
dma_alloc_map[chn] = DMA_MAP_FREE;
return 0;
}
EXPORT_SYMBOL(sound_alloc_dma);
int sound_open_dma(int chn, char *deviceID)
{
if (!valid_dma(chn)) {
printk(KERN_ERR "sound_open_dma: Invalid DMA channel %d\n", chn);
return 1;
}
if (dma_alloc_map[chn] != DMA_MAP_FREE) {
printk("sound_open_dma: DMA channel %d busy or not allocated (%d)\n", chn, dma_alloc_map[chn]);
return 1;
}
dma_alloc_map[chn] = DMA_MAP_BUSY;
return 0;
}
EXPORT_SYMBOL(sound_open_dma);
void sound_free_dma(int chn)
{
if (dma_alloc_map[chn] == DMA_MAP_UNAVAIL) {
/* printk( "sound_free_dma: Bad access to DMA channel %d\n", chn); */
return;
}
free_dma(chn);
dma_alloc_map[chn] = DMA_MAP_UNAVAIL;
}
EXPORT_SYMBOL(sound_free_dma);
void sound_close_dma(int chn)
{
if (dma_alloc_map[chn] != DMA_MAP_BUSY) {
printk(KERN_ERR "sound_close_dma: Bad access to DMA channel %d\n", chn);
return;
}
dma_alloc_map[chn] = DMA_MAP_FREE;
}
EXPORT_SYMBOL(sound_close_dma);
static void do_sequencer_timer(unsigned long dummy)
{
sequencer_timer(0);
}
static DEFINE_TIMER(seq_timer, do_sequencer_timer, 0, 0);
void request_sound_timer(int count)
{
extern unsigned long seq_time;
if (count < 0) {
seq_timer.expires = (-count) + jiffies;
add_timer(&seq_timer);
return;
}
count += seq_time;
count -= jiffies;
if (count < 1)
count = 1;
seq_timer.expires = (count) + jiffies;
add_timer(&seq_timer);
}
void sound_stop_timer(void)
{
del_timer(&seq_timer);
}
void conf_printf(char *name, struct address_info *hw_config)
{
#ifndef CONFIG_SOUND_TRACEINIT
return;
#else
printk("<%s> at 0x%03x", name, hw_config->io_base);
if (hw_config->irq)
printk(" irq %d", (hw_config->irq > 0) ? hw_config->irq : -hw_config->irq);
if (hw_config->dma != -1 || hw_config->dma2 != -1)
{
printk(" dma %d", hw_config->dma);
if (hw_config->dma2 != -1)
printk(",%d", hw_config->dma2);
}
printk("\n");
#endif
}
EXPORT_SYMBOL(conf_printf);
void conf_printf2(char *name, int base, int irq, int dma, int dma2)
{
#ifndef CONFIG_SOUND_TRACEINIT
return;
#else
printk("<%s> at 0x%03x", name, base);
if (irq)
printk(" irq %d", (irq > 0) ? irq : -irq);
if (dma != -1 || dma2 != -1)
{
printk(" dma %d", dma);
if (dma2 != -1)
printk(",%d", dma2);
}
printk("\n");
#endif
}
EXPORT_SYMBOL(conf_printf2);
| gpl-2.0 |
Cpasjuste/android_kernel_lg_p990 | sound/pci/hda/hda_generic.c | 465 | 29041 | /*
* Universal Interface for Intel High Definition Audio Codec
*
* Generic widget tree parser
*
* Copyright (c) 2004 Takashi Iwai <tiwai@suse.de>
*
* This driver 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 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/slab.h>
#include <sound/core.h>
#include "hda_codec.h"
#include "hda_local.h"
/* widget node for parsing */
struct hda_gnode {
hda_nid_t nid; /* NID of this widget */
unsigned short nconns; /* number of input connections */
hda_nid_t *conn_list;
hda_nid_t slist[2]; /* temporay list */
unsigned int wid_caps; /* widget capabilities */
unsigned char type; /* widget type */
unsigned char pin_ctl; /* pin controls */
unsigned char checked; /* the flag indicates that the node is already parsed */
unsigned int pin_caps; /* pin widget capabilities */
unsigned int def_cfg; /* default configuration */
unsigned int amp_out_caps; /* AMP out capabilities */
unsigned int amp_in_caps; /* AMP in capabilities */
struct list_head list;
};
/* patch-specific record */
#define MAX_PCM_VOLS 2
struct pcm_vol {
struct hda_gnode *node; /* Node for PCM volume */
unsigned int index; /* connection of PCM volume */
};
struct hda_gspec {
struct hda_gnode *dac_node[2]; /* DAC node */
struct hda_gnode *out_pin_node[2]; /* Output pin (Line-Out) node */
struct pcm_vol pcm_vol[MAX_PCM_VOLS]; /* PCM volumes */
unsigned int pcm_vol_nodes; /* number of PCM volumes */
struct hda_gnode *adc_node; /* ADC node */
struct hda_gnode *cap_vol_node; /* Node for capture volume */
unsigned int cur_cap_src; /* current capture source */
struct hda_input_mux input_mux;
char cap_labels[HDA_MAX_NUM_INPUTS][16];
unsigned int def_amp_in_caps;
unsigned int def_amp_out_caps;
struct hda_pcm pcm_rec; /* PCM information */
struct list_head nid_list; /* list of widgets */
#ifdef CONFIG_SND_HDA_POWER_SAVE
#define MAX_LOOPBACK_AMPS 7
struct hda_loopback_check loopback;
int num_loopbacks;
struct hda_amp_list loopback_list[MAX_LOOPBACK_AMPS + 1];
#endif
};
/*
* retrieve the default device type from the default config value
*/
#define defcfg_type(node) (((node)->def_cfg & AC_DEFCFG_DEVICE) >> \
AC_DEFCFG_DEVICE_SHIFT)
#define defcfg_location(node) (((node)->def_cfg & AC_DEFCFG_LOCATION) >> \
AC_DEFCFG_LOCATION_SHIFT)
#define defcfg_port_conn(node) (((node)->def_cfg & AC_DEFCFG_PORT_CONN) >> \
AC_DEFCFG_PORT_CONN_SHIFT)
/*
* destructor
*/
static void snd_hda_generic_free(struct hda_codec *codec)
{
struct hda_gspec *spec = codec->spec;
struct hda_gnode *node, *n;
if (! spec)
return;
/* free all widgets */
list_for_each_entry_safe(node, n, &spec->nid_list, list) {
if (node->conn_list != node->slist)
kfree(node->conn_list);
kfree(node);
}
kfree(spec);
}
/*
* add a new widget node and read its attributes
*/
static int add_new_node(struct hda_codec *codec, struct hda_gspec *spec, hda_nid_t nid)
{
struct hda_gnode *node;
int nconns;
hda_nid_t conn_list[HDA_MAX_CONNECTIONS];
node = kzalloc(sizeof(*node), GFP_KERNEL);
if (node == NULL)
return -ENOMEM;
node->nid = nid;
node->wid_caps = get_wcaps(codec, nid);
node->type = get_wcaps_type(node->wid_caps);
if (node->wid_caps & AC_WCAP_CONN_LIST) {
nconns = snd_hda_get_connections(codec, nid, conn_list,
HDA_MAX_CONNECTIONS);
if (nconns < 0) {
kfree(node);
return nconns;
}
} else {
nconns = 0;
}
if (nconns <= ARRAY_SIZE(node->slist))
node->conn_list = node->slist;
else {
node->conn_list = kmalloc(sizeof(hda_nid_t) * nconns,
GFP_KERNEL);
if (! node->conn_list) {
snd_printk(KERN_ERR "hda-generic: cannot malloc\n");
kfree(node);
return -ENOMEM;
}
}
memcpy(node->conn_list, conn_list, nconns * sizeof(hda_nid_t));
node->nconns = nconns;
if (node->type == AC_WID_PIN) {
node->pin_caps = snd_hda_query_pin_caps(codec, node->nid);
node->pin_ctl = snd_hda_codec_read(codec, node->nid, 0, AC_VERB_GET_PIN_WIDGET_CONTROL, 0);
node->def_cfg = snd_hda_codec_get_pincfg(codec, node->nid);
}
if (node->wid_caps & AC_WCAP_OUT_AMP) {
if (node->wid_caps & AC_WCAP_AMP_OVRD)
node->amp_out_caps = snd_hda_param_read(codec, node->nid, AC_PAR_AMP_OUT_CAP);
if (! node->amp_out_caps)
node->amp_out_caps = spec->def_amp_out_caps;
}
if (node->wid_caps & AC_WCAP_IN_AMP) {
if (node->wid_caps & AC_WCAP_AMP_OVRD)
node->amp_in_caps = snd_hda_param_read(codec, node->nid, AC_PAR_AMP_IN_CAP);
if (! node->amp_in_caps)
node->amp_in_caps = spec->def_amp_in_caps;
}
list_add_tail(&node->list, &spec->nid_list);
return 0;
}
/*
* build the AFG subtree
*/
static int build_afg_tree(struct hda_codec *codec)
{
struct hda_gspec *spec = codec->spec;
int i, nodes, err;
hda_nid_t nid;
if (snd_BUG_ON(!spec))
return -EINVAL;
spec->def_amp_out_caps = snd_hda_param_read(codec, codec->afg, AC_PAR_AMP_OUT_CAP);
spec->def_amp_in_caps = snd_hda_param_read(codec, codec->afg, AC_PAR_AMP_IN_CAP);
nodes = snd_hda_get_sub_nodes(codec, codec->afg, &nid);
if (! nid || nodes < 0) {
printk(KERN_ERR "Invalid AFG subtree\n");
return -EINVAL;
}
/* parse all nodes belonging to the AFG */
for (i = 0; i < nodes; i++, nid++) {
if ((err = add_new_node(codec, spec, nid)) < 0)
return err;
}
return 0;
}
/*
* look for the node record for the given NID
*/
/* FIXME: should avoid the braindead linear search */
static struct hda_gnode *hda_get_node(struct hda_gspec *spec, hda_nid_t nid)
{
struct hda_gnode *node;
list_for_each_entry(node, &spec->nid_list, list) {
if (node->nid == nid)
return node;
}
return NULL;
}
/*
* unmute (and set max vol) the output amplifier
*/
static int unmute_output(struct hda_codec *codec, struct hda_gnode *node)
{
unsigned int val, ofs;
snd_printdd("UNMUTE OUT: NID=0x%x\n", node->nid);
val = (node->amp_out_caps & AC_AMPCAP_NUM_STEPS) >> AC_AMPCAP_NUM_STEPS_SHIFT;
ofs = (node->amp_out_caps & AC_AMPCAP_OFFSET) >> AC_AMPCAP_OFFSET_SHIFT;
if (val >= ofs)
val -= ofs;
snd_hda_codec_amp_stereo(codec, node->nid, HDA_OUTPUT, 0, 0xff, val);
return 0;
}
/*
* unmute (and set max vol) the input amplifier
*/
static int unmute_input(struct hda_codec *codec, struct hda_gnode *node, unsigned int index)
{
unsigned int val, ofs;
snd_printdd("UNMUTE IN: NID=0x%x IDX=0x%x\n", node->nid, index);
val = (node->amp_in_caps & AC_AMPCAP_NUM_STEPS) >> AC_AMPCAP_NUM_STEPS_SHIFT;
ofs = (node->amp_in_caps & AC_AMPCAP_OFFSET) >> AC_AMPCAP_OFFSET_SHIFT;
if (val >= ofs)
val -= ofs;
snd_hda_codec_amp_stereo(codec, node->nid, HDA_INPUT, index, 0xff, val);
return 0;
}
/*
* select the input connection of the given node.
*/
static int select_input_connection(struct hda_codec *codec, struct hda_gnode *node,
unsigned int index)
{
snd_printdd("CONNECT: NID=0x%x IDX=0x%x\n", node->nid, index);
return snd_hda_codec_write_cache(codec, node->nid, 0,
AC_VERB_SET_CONNECT_SEL, index);
}
/*
* clear checked flag of each node in the node list
*/
static void clear_check_flags(struct hda_gspec *spec)
{
struct hda_gnode *node;
list_for_each_entry(node, &spec->nid_list, list) {
node->checked = 0;
}
}
/*
* parse the output path recursively until reach to an audio output widget
*
* returns 0 if not found, 1 if found, or a negative error code.
*/
static int parse_output_path(struct hda_codec *codec, struct hda_gspec *spec,
struct hda_gnode *node, int dac_idx)
{
int i, err;
struct hda_gnode *child;
if (node->checked)
return 0;
node->checked = 1;
if (node->type == AC_WID_AUD_OUT) {
if (node->wid_caps & AC_WCAP_DIGITAL) {
snd_printdd("Skip Digital OUT node %x\n", node->nid);
return 0;
}
snd_printdd("AUD_OUT found %x\n", node->nid);
if (spec->dac_node[dac_idx]) {
/* already DAC node is assigned, just unmute & connect */
return node == spec->dac_node[dac_idx];
}
spec->dac_node[dac_idx] = node;
if ((node->wid_caps & AC_WCAP_OUT_AMP) &&
spec->pcm_vol_nodes < MAX_PCM_VOLS) {
spec->pcm_vol[spec->pcm_vol_nodes].node = node;
spec->pcm_vol[spec->pcm_vol_nodes].index = 0;
spec->pcm_vol_nodes++;
}
return 1; /* found */
}
for (i = 0; i < node->nconns; i++) {
child = hda_get_node(spec, node->conn_list[i]);
if (! child)
continue;
err = parse_output_path(codec, spec, child, dac_idx);
if (err < 0)
return err;
else if (err > 0) {
/* found one,
* select the path, unmute both input and output
*/
if (node->nconns > 1)
select_input_connection(codec, node, i);
unmute_input(codec, node, i);
unmute_output(codec, node);
if (spec->dac_node[dac_idx] &&
spec->pcm_vol_nodes < MAX_PCM_VOLS &&
!(spec->dac_node[dac_idx]->wid_caps &
AC_WCAP_OUT_AMP)) {
if ((node->wid_caps & AC_WCAP_IN_AMP) ||
(node->wid_caps & AC_WCAP_OUT_AMP)) {
int n = spec->pcm_vol_nodes;
spec->pcm_vol[n].node = node;
spec->pcm_vol[n].index = i;
spec->pcm_vol_nodes++;
}
}
return 1;
}
}
return 0;
}
/*
* Look for the output PIN widget with the given jack type
* and parse the output path to that PIN.
*
* Returns the PIN node when the path to DAC is established.
*/
static struct hda_gnode *parse_output_jack(struct hda_codec *codec,
struct hda_gspec *spec,
int jack_type)
{
struct hda_gnode *node;
int err;
list_for_each_entry(node, &spec->nid_list, list) {
if (node->type != AC_WID_PIN)
continue;
/* output capable? */
if (! (node->pin_caps & AC_PINCAP_OUT))
continue;
if (defcfg_port_conn(node) == AC_JACK_PORT_NONE)
continue; /* unconnected */
if (jack_type >= 0) {
if (jack_type != defcfg_type(node))
continue;
if (node->wid_caps & AC_WCAP_DIGITAL)
continue; /* skip SPDIF */
} else {
/* output as default? */
if (! (node->pin_ctl & AC_PINCTL_OUT_EN))
continue;
}
clear_check_flags(spec);
err = parse_output_path(codec, spec, node, 0);
if (err < 0)
return NULL;
if (! err && spec->out_pin_node[0]) {
err = parse_output_path(codec, spec, node, 1);
if (err < 0)
return NULL;
}
if (err > 0) {
/* unmute the PIN output */
unmute_output(codec, node);
/* set PIN-Out enable */
snd_hda_codec_write_cache(codec, node->nid, 0,
AC_VERB_SET_PIN_WIDGET_CONTROL,
AC_PINCTL_OUT_EN |
((node->pin_caps & AC_PINCAP_HP_DRV) ?
AC_PINCTL_HP_EN : 0));
return node;
}
}
return NULL;
}
/*
* parse outputs
*/
static int parse_output(struct hda_codec *codec)
{
struct hda_gspec *spec = codec->spec;
struct hda_gnode *node;
/*
* Look for the output PIN widget
*/
/* first, look for the line-out pin */
node = parse_output_jack(codec, spec, AC_JACK_LINE_OUT);
if (node) /* found, remember the PIN node */
spec->out_pin_node[0] = node;
else {
/* if no line-out is found, try speaker out */
node = parse_output_jack(codec, spec, AC_JACK_SPEAKER);
if (node)
spec->out_pin_node[0] = node;
}
/* look for the HP-out pin */
node = parse_output_jack(codec, spec, AC_JACK_HP_OUT);
if (node) {
if (! spec->out_pin_node[0])
spec->out_pin_node[0] = node;
else
spec->out_pin_node[1] = node;
}
if (! spec->out_pin_node[0]) {
/* no line-out or HP pins found,
* then choose for the first output pin
*/
spec->out_pin_node[0] = parse_output_jack(codec, spec, -1);
if (! spec->out_pin_node[0])
snd_printd("hda_generic: no proper output path found\n");
}
return 0;
}
/*
* input MUX
*/
/* control callbacks */
static int capture_source_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct hda_gspec *spec = codec->spec;
return snd_hda_input_mux_info(&spec->input_mux, uinfo);
}
static int capture_source_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct hda_gspec *spec = codec->spec;
ucontrol->value.enumerated.item[0] = spec->cur_cap_src;
return 0;
}
static int capture_source_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct hda_gspec *spec = codec->spec;
return snd_hda_input_mux_put(codec, &spec->input_mux, ucontrol,
spec->adc_node->nid, &spec->cur_cap_src);
}
/*
* return the string name of the given input PIN widget
*/
static const char *get_input_type(struct hda_gnode *node, unsigned int *pinctl)
{
unsigned int location = defcfg_location(node);
switch (defcfg_type(node)) {
case AC_JACK_LINE_IN:
if ((location & 0x0f) == AC_JACK_LOC_FRONT)
return "Front Line";
return "Line";
case AC_JACK_CD:
#if 0
if (pinctl)
*pinctl |= AC_PINCTL_VREF_GRD;
#endif
return "CD";
case AC_JACK_AUX:
if ((location & 0x0f) == AC_JACK_LOC_FRONT)
return "Front Aux";
return "Aux";
case AC_JACK_MIC_IN:
if (pinctl &&
(node->pin_caps &
(AC_PINCAP_VREF_80 << AC_PINCAP_VREF_SHIFT)))
*pinctl |= AC_PINCTL_VREF_80;
if ((location & 0x0f) == AC_JACK_LOC_FRONT)
return "Front Mic";
return "Mic";
case AC_JACK_SPDIF_IN:
return "SPDIF";
case AC_JACK_DIG_OTHER_IN:
return "Digital";
}
return NULL;
}
/*
* parse the nodes recursively until reach to the input PIN
*
* returns 0 if not found, 1 if found, or a negative error code.
*/
static int parse_adc_sub_nodes(struct hda_codec *codec, struct hda_gspec *spec,
struct hda_gnode *node)
{
int i, err;
unsigned int pinctl;
char *label;
const char *type;
if (node->checked)
return 0;
node->checked = 1;
if (node->type != AC_WID_PIN) {
for (i = 0; i < node->nconns; i++) {
struct hda_gnode *child;
child = hda_get_node(spec, node->conn_list[i]);
if (! child)
continue;
err = parse_adc_sub_nodes(codec, spec, child);
if (err < 0)
return err;
if (err > 0) {
/* found one,
* select the path, unmute both input and output
*/
if (node->nconns > 1)
select_input_connection(codec, node, i);
unmute_input(codec, node, i);
unmute_output(codec, node);
return err;
}
}
return 0;
}
/* input capable? */
if (! (node->pin_caps & AC_PINCAP_IN))
return 0;
if (defcfg_port_conn(node) == AC_JACK_PORT_NONE)
return 0; /* unconnected */
if (node->wid_caps & AC_WCAP_DIGITAL)
return 0; /* skip SPDIF */
if (spec->input_mux.num_items >= HDA_MAX_NUM_INPUTS) {
snd_printk(KERN_ERR "hda_generic: Too many items for capture\n");
return -EINVAL;
}
pinctl = AC_PINCTL_IN_EN;
/* create a proper capture source label */
type = get_input_type(node, &pinctl);
if (! type) {
/* input as default? */
if (! (node->pin_ctl & AC_PINCTL_IN_EN))
return 0;
type = "Input";
}
label = spec->cap_labels[spec->input_mux.num_items];
strcpy(label, type);
spec->input_mux.items[spec->input_mux.num_items].label = label;
/* unmute the PIN external input */
unmute_input(codec, node, 0); /* index = 0? */
/* set PIN-In enable */
snd_hda_codec_write_cache(codec, node->nid, 0,
AC_VERB_SET_PIN_WIDGET_CONTROL, pinctl);
return 1; /* found */
}
/* add a capture source element */
static void add_cap_src(struct hda_gspec *spec, int idx)
{
struct hda_input_mux_item *csrc;
char *buf;
int num, ocap;
num = spec->input_mux.num_items;
csrc = &spec->input_mux.items[num];
buf = spec->cap_labels[num];
for (ocap = 0; ocap < num; ocap++) {
if (! strcmp(buf, spec->cap_labels[ocap])) {
/* same label already exists,
* put the index number to be unique
*/
sprintf(buf, "%s %d", spec->cap_labels[ocap], num);
break;
}
}
csrc->index = idx;
spec->input_mux.num_items++;
}
/*
* parse input
*/
static int parse_input_path(struct hda_codec *codec, struct hda_gnode *adc_node)
{
struct hda_gspec *spec = codec->spec;
struct hda_gnode *node;
int i, err;
snd_printdd("AUD_IN = %x\n", adc_node->nid);
clear_check_flags(spec);
// awk added - fixed no recording due to muted widget
unmute_input(codec, adc_node, 0);
/*
* check each connection of the ADC
* if it reaches to a proper input PIN, add the path as the
* input path.
*/
/* first, check the direct connections to PIN widgets */
for (i = 0; i < adc_node->nconns; i++) {
node = hda_get_node(spec, adc_node->conn_list[i]);
if (node && node->type == AC_WID_PIN) {
err = parse_adc_sub_nodes(codec, spec, node);
if (err < 0)
return err;
else if (err > 0)
add_cap_src(spec, i);
}
}
/* ... then check the rests, more complicated connections */
for (i = 0; i < adc_node->nconns; i++) {
node = hda_get_node(spec, adc_node->conn_list[i]);
if (node && node->type != AC_WID_PIN) {
err = parse_adc_sub_nodes(codec, spec, node);
if (err < 0)
return err;
else if (err > 0)
add_cap_src(spec, i);
}
}
if (! spec->input_mux.num_items)
return 0; /* no input path found... */
snd_printdd("[Capture Source] NID=0x%x, #SRC=%d\n", adc_node->nid, spec->input_mux.num_items);
for (i = 0; i < spec->input_mux.num_items; i++)
snd_printdd(" [%s] IDX=0x%x\n", spec->input_mux.items[i].label,
spec->input_mux.items[i].index);
spec->adc_node = adc_node;
return 1;
}
/*
* parse input
*/
static int parse_input(struct hda_codec *codec)
{
struct hda_gspec *spec = codec->spec;
struct hda_gnode *node;
int err;
/*
* At first we look for an audio input widget.
* If it reaches to certain input PINs, we take it as the
* input path.
*/
list_for_each_entry(node, &spec->nid_list, list) {
if (node->wid_caps & AC_WCAP_DIGITAL)
continue; /* skip SPDIF */
if (node->type == AC_WID_AUD_IN) {
err = parse_input_path(codec, node);
if (err < 0)
return err;
else if (err > 0)
return 0;
}
}
snd_printd("hda_generic: no proper input path found\n");
return 0;
}
#ifdef CONFIG_SND_HDA_POWER_SAVE
static void add_input_loopback(struct hda_codec *codec, hda_nid_t nid,
int dir, int idx)
{
struct hda_gspec *spec = codec->spec;
struct hda_amp_list *p;
if (spec->num_loopbacks >= MAX_LOOPBACK_AMPS) {
snd_printk(KERN_ERR "hda_generic: Too many loopback ctls\n");
return;
}
p = &spec->loopback_list[spec->num_loopbacks++];
p->nid = nid;
p->dir = dir;
p->idx = idx;
spec->loopback.amplist = spec->loopback_list;
}
#else
#define add_input_loopback(codec,nid,dir,idx)
#endif
/*
* create mixer controls if possible
*/
static int create_mixer(struct hda_codec *codec, struct hda_gnode *node,
unsigned int index, const char *type,
const char *dir_sfx, int is_loopback)
{
char name[32];
int err;
int created = 0;
struct snd_kcontrol_new knew;
if (type)
sprintf(name, "%s %s Switch", type, dir_sfx);
else
sprintf(name, "%s Switch", dir_sfx);
if ((node->wid_caps & AC_WCAP_IN_AMP) &&
(node->amp_in_caps & AC_AMPCAP_MUTE)) {
knew = (struct snd_kcontrol_new)HDA_CODEC_MUTE(name, node->nid, index, HDA_INPUT);
if (is_loopback)
add_input_loopback(codec, node->nid, HDA_INPUT, index);
snd_printdd("[%s] NID=0x%x, DIR=IN, IDX=0x%x\n", name, node->nid, index);
err = snd_hda_ctl_add(codec, snd_ctl_new1(&knew, codec));
if (err < 0)
return err;
created = 1;
} else if ((node->wid_caps & AC_WCAP_OUT_AMP) &&
(node->amp_out_caps & AC_AMPCAP_MUTE)) {
knew = (struct snd_kcontrol_new)HDA_CODEC_MUTE(name, node->nid, 0, HDA_OUTPUT);
if (is_loopback)
add_input_loopback(codec, node->nid, HDA_OUTPUT, 0);
snd_printdd("[%s] NID=0x%x, DIR=OUT\n", name, node->nid);
err = snd_hda_ctl_add(codec, snd_ctl_new1(&knew, codec));
if (err < 0)
return err;
created = 1;
}
if (type)
sprintf(name, "%s %s Volume", type, dir_sfx);
else
sprintf(name, "%s Volume", dir_sfx);
if ((node->wid_caps & AC_WCAP_IN_AMP) &&
(node->amp_in_caps & AC_AMPCAP_NUM_STEPS)) {
knew = (struct snd_kcontrol_new)HDA_CODEC_VOLUME(name, node->nid, index, HDA_INPUT);
snd_printdd("[%s] NID=0x%x, DIR=IN, IDX=0x%x\n", name, node->nid, index);
err = snd_hda_ctl_add(codec, snd_ctl_new1(&knew, codec));
if (err < 0)
return err;
created = 1;
} else if ((node->wid_caps & AC_WCAP_OUT_AMP) &&
(node->amp_out_caps & AC_AMPCAP_NUM_STEPS)) {
knew = (struct snd_kcontrol_new)HDA_CODEC_VOLUME(name, node->nid, 0, HDA_OUTPUT);
snd_printdd("[%s] NID=0x%x, DIR=OUT\n", name, node->nid);
err = snd_hda_ctl_add(codec, snd_ctl_new1(&knew, codec));
if (err < 0)
return err;
created = 1;
}
return created;
}
/*
* check whether the controls with the given name and direction suffix already exist
*/
static int check_existing_control(struct hda_codec *codec, const char *type, const char *dir)
{
struct snd_ctl_elem_id id;
memset(&id, 0, sizeof(id));
sprintf(id.name, "%s %s Volume", type, dir);
id.iface = SNDRV_CTL_ELEM_IFACE_MIXER;
if (snd_ctl_find_id(codec->bus->card, &id))
return 1;
sprintf(id.name, "%s %s Switch", type, dir);
id.iface = SNDRV_CTL_ELEM_IFACE_MIXER;
if (snd_ctl_find_id(codec->bus->card, &id))
return 1;
return 0;
}
/*
* build output mixer controls
*/
static int create_output_mixers(struct hda_codec *codec, const char **names)
{
struct hda_gspec *spec = codec->spec;
int i, err;
for (i = 0; i < spec->pcm_vol_nodes; i++) {
err = create_mixer(codec, spec->pcm_vol[i].node,
spec->pcm_vol[i].index,
names[i], "Playback", 0);
if (err < 0)
return err;
}
return 0;
}
static int build_output_controls(struct hda_codec *codec)
{
struct hda_gspec *spec = codec->spec;
static const char *types_speaker[] = { "Speaker", "Headphone" };
static const char *types_line[] = { "Front", "Headphone" };
switch (spec->pcm_vol_nodes) {
case 1:
return create_mixer(codec, spec->pcm_vol[0].node,
spec->pcm_vol[0].index,
"Master", "Playback", 0);
case 2:
if (defcfg_type(spec->out_pin_node[0]) == AC_JACK_SPEAKER)
return create_output_mixers(codec, types_speaker);
else
return create_output_mixers(codec, types_line);
}
return 0;
}
/* create capture volume/switch */
static int build_input_controls(struct hda_codec *codec)
{
struct hda_gspec *spec = codec->spec;
struct hda_gnode *adc_node = spec->adc_node;
int i, err;
static struct snd_kcontrol_new cap_sel = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Capture Source",
.info = capture_source_info,
.get = capture_source_get,
.put = capture_source_put,
};
if (! adc_node || ! spec->input_mux.num_items)
return 0; /* not found */
spec->cur_cap_src = 0;
select_input_connection(codec, adc_node,
spec->input_mux.items[0].index);
/* create capture volume and switch controls if the ADC has an amp */
/* do we have only a single item? */
if (spec->input_mux.num_items == 1) {
err = create_mixer(codec, adc_node,
spec->input_mux.items[0].index,
NULL, "Capture", 0);
if (err < 0)
return err;
return 0;
}
/* create input MUX if multiple sources are available */
err = snd_hda_ctl_add(codec, snd_ctl_new1(&cap_sel, codec));
if (err < 0)
return err;
/* no volume control? */
if (! (adc_node->wid_caps & AC_WCAP_IN_AMP) ||
! (adc_node->amp_in_caps & AC_AMPCAP_NUM_STEPS))
return 0;
for (i = 0; i < spec->input_mux.num_items; i++) {
struct snd_kcontrol_new knew;
char name[32];
sprintf(name, "%s Capture Volume",
spec->input_mux.items[i].label);
knew = (struct snd_kcontrol_new)
HDA_CODEC_VOLUME(name, adc_node->nid,
spec->input_mux.items[i].index,
HDA_INPUT);
err = snd_hda_ctl_add(codec, snd_ctl_new1(&knew, codec));
if (err < 0)
return err;
}
return 0;
}
/*
* parse the nodes recursively until reach to the output PIN.
*
* returns 0 - if not found,
* 1 - if found, but no mixer is created
* 2 - if found and mixer was already created, (just skip)
* a negative error code
*/
static int parse_loopback_path(struct hda_codec *codec, struct hda_gspec *spec,
struct hda_gnode *node, struct hda_gnode *dest_node,
const char *type)
{
int i, err;
if (node->checked)
return 0;
node->checked = 1;
if (node == dest_node) {
/* loopback connection found */
return 1;
}
for (i = 0; i < node->nconns; i++) {
struct hda_gnode *child = hda_get_node(spec, node->conn_list[i]);
if (! child)
continue;
err = parse_loopback_path(codec, spec, child, dest_node, type);
if (err < 0)
return err;
else if (err >= 1) {
if (err == 1) {
err = create_mixer(codec, node, i, type,
"Playback", 1);
if (err < 0)
return err;
if (err > 0)
return 2; /* ok, created */
/* not created, maybe in the lower path */
err = 1;
}
/* connect and unmute */
if (node->nconns > 1)
select_input_connection(codec, node, i);
unmute_input(codec, node, i);
unmute_output(codec, node);
return err;
}
}
return 0;
}
/*
* parse the tree and build the loopback controls
*/
static int build_loopback_controls(struct hda_codec *codec)
{
struct hda_gspec *spec = codec->spec;
struct hda_gnode *node;
int err;
const char *type;
if (! spec->out_pin_node[0])
return 0;
list_for_each_entry(node, &spec->nid_list, list) {
if (node->type != AC_WID_PIN)
continue;
/* input capable? */
if (! (node->pin_caps & AC_PINCAP_IN))
return 0;
type = get_input_type(node, NULL);
if (type) {
if (check_existing_control(codec, type, "Playback"))
continue;
clear_check_flags(spec);
err = parse_loopback_path(codec, spec,
spec->out_pin_node[0],
node, type);
if (err < 0)
return err;
if (! err)
continue;
}
}
return 0;
}
/*
* build mixer controls
*/
static int build_generic_controls(struct hda_codec *codec)
{
int err;
if ((err = build_input_controls(codec)) < 0 ||
(err = build_output_controls(codec)) < 0 ||
(err = build_loopback_controls(codec)) < 0)
return err;
return 0;
}
/*
* PCM
*/
static struct hda_pcm_stream generic_pcm_playback = {
.substreams = 1,
.channels_min = 2,
.channels_max = 2,
};
static int generic_pcm2_prepare(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
unsigned int stream_tag,
unsigned int format,
struct snd_pcm_substream *substream)
{
struct hda_gspec *spec = codec->spec;
snd_hda_codec_setup_stream(codec, hinfo->nid, stream_tag, 0, format);
snd_hda_codec_setup_stream(codec, spec->dac_node[1]->nid,
stream_tag, 0, format);
return 0;
}
static int generic_pcm2_cleanup(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct hda_gspec *spec = codec->spec;
snd_hda_codec_cleanup_stream(codec, hinfo->nid);
snd_hda_codec_cleanup_stream(codec, spec->dac_node[1]->nid);
return 0;
}
static int build_generic_pcms(struct hda_codec *codec)
{
struct hda_gspec *spec = codec->spec;
struct hda_pcm *info = &spec->pcm_rec;
if (! spec->dac_node[0] && ! spec->adc_node) {
snd_printd("hda_generic: no PCM found\n");
return 0;
}
codec->num_pcms = 1;
codec->pcm_info = info;
info->name = "HDA Generic";
if (spec->dac_node[0]) {
info->stream[0] = generic_pcm_playback;
info->stream[0].nid = spec->dac_node[0]->nid;
if (spec->dac_node[1]) {
info->stream[0].ops.prepare = generic_pcm2_prepare;
info->stream[0].ops.cleanup = generic_pcm2_cleanup;
}
}
if (spec->adc_node) {
info->stream[1] = generic_pcm_playback;
info->stream[1].nid = spec->adc_node->nid;
}
return 0;
}
#ifdef CONFIG_SND_HDA_POWER_SAVE
static int generic_check_power_status(struct hda_codec *codec, hda_nid_t nid)
{
struct hda_gspec *spec = codec->spec;
return snd_hda_check_amp_list_power(codec, &spec->loopback, nid);
}
#endif
/*
*/
static struct hda_codec_ops generic_patch_ops = {
.build_controls = build_generic_controls,
.build_pcms = build_generic_pcms,
.free = snd_hda_generic_free,
#ifdef CONFIG_SND_HDA_POWER_SAVE
.check_power_status = generic_check_power_status,
#endif
};
/*
* the generic parser
*/
int snd_hda_parse_generic_codec(struct hda_codec *codec)
{
struct hda_gspec *spec;
int err;
if(!codec->afg)
return 0;
spec = kzalloc(sizeof(*spec), GFP_KERNEL);
if (spec == NULL) {
printk(KERN_ERR "hda_generic: can't allocate spec\n");
return -ENOMEM;
}
codec->spec = spec;
INIT_LIST_HEAD(&spec->nid_list);
if ((err = build_afg_tree(codec)) < 0)
goto error;
if ((err = parse_input(codec)) < 0 ||
(err = parse_output(codec)) < 0)
goto error;
codec->patch_ops = generic_patch_ops;
return 0;
error:
snd_hda_generic_free(codec);
return err;
}
EXPORT_SYMBOL(snd_hda_parse_generic_codec);
| gpl-2.0 |
jacobrivers123/kernel-nk1-negalite-lt02ltespr | drivers/gpu/msm/adreno_a3xx_snapshot.c | 465 | 13361 | /* Copyright (c) 2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include "kgsl.h"
#include "adreno.h"
#include "kgsl_snapshot.h"
#include "a3xx_reg.h"
#define DEBUG_SECTION_SZ(_dwords) (((_dwords) * sizeof(unsigned int)) \
+ sizeof(struct kgsl_snapshot_debug))
#define SHADER_MEMORY_SIZE 0x4000
/**
* _rbbm_debug_bus_read - Helper function to read data from the RBBM
* debug bus.
* @device - GPU device to read/write registers
* @block_id - Debug bus block to read from
* @index - Index in the debug bus block to read
* @ret - Value of the register read
*/
static void _rbbm_debug_bus_read(struct kgsl_device *device,
unsigned int block_id, unsigned int index, unsigned int *val)
{
unsigned int block = (block_id << 8) | 1 << 16;
adreno_regwrite(device, A3XX_RBBM_DEBUG_BUS_CTL, block | index);
adreno_regread(device, A3XX_RBBM_DEBUG_BUS_DATA_STATUS, val);
}
static int a3xx_snapshot_shader_memory(struct kgsl_device *device,
void *snapshot, int remain, void *priv)
{
struct kgsl_snapshot_debug *header = snapshot;
unsigned int *data = snapshot + sizeof(*header);
int i;
if (remain < DEBUG_SECTION_SZ(SHADER_MEMORY_SIZE)) {
SNAPSHOT_ERR_NOMEM(device, "SHADER MEMORY");
return 0;
}
header->type = SNAPSHOT_DEBUG_SHADER_MEMORY;
header->size = SHADER_MEMORY_SIZE;
for (i = 0; i < SHADER_MEMORY_SIZE; i++)
adreno_regread(device, 0x4000 + i, &data[i]);
return DEBUG_SECTION_SZ(SHADER_MEMORY_SIZE);
}
#define VPC_MEMORY_BANKS 4
#define VPC_MEMORY_SIZE 512
static int a3xx_snapshot_vpc_memory(struct kgsl_device *device, void *snapshot,
int remain, void *priv)
{
struct kgsl_snapshot_debug *header = snapshot;
unsigned int *data = snapshot + sizeof(*header);
int size = VPC_MEMORY_BANKS * VPC_MEMORY_SIZE;
int bank, addr, i = 0;
if (remain < DEBUG_SECTION_SZ(size)) {
SNAPSHOT_ERR_NOMEM(device, "VPC MEMORY");
return 0;
}
header->type = SNAPSHOT_DEBUG_VPC_MEMORY;
header->size = size;
for (bank = 0; bank < VPC_MEMORY_BANKS; bank++) {
for (addr = 0; addr < VPC_MEMORY_SIZE; addr++) {
unsigned int val = bank | (addr << 4);
adreno_regwrite(device,
A3XX_VPC_VPC_DEBUG_RAM_SEL, val);
adreno_regread(device,
A3XX_VPC_VPC_DEBUG_RAM_READ, &data[i++]);
}
}
return DEBUG_SECTION_SZ(size);
}
#define CP_MEQ_SIZE 16
static int a3xx_snapshot_cp_meq(struct kgsl_device *device, void *snapshot,
int remain, void *priv)
{
struct kgsl_snapshot_debug *header = snapshot;
unsigned int *data = snapshot + sizeof(*header);
int i;
if (remain < DEBUG_SECTION_SZ(CP_MEQ_SIZE)) {
SNAPSHOT_ERR_NOMEM(device, "CP MEQ DEBUG");
return 0;
}
header->type = SNAPSHOT_DEBUG_CP_MEQ;
header->size = CP_MEQ_SIZE;
adreno_regwrite(device, A3XX_CP_MEQ_ADDR, 0x0);
for (i = 0; i < CP_MEQ_SIZE; i++)
adreno_regread(device, A3XX_CP_MEQ_DATA, &data[i]);
return DEBUG_SECTION_SZ(CP_MEQ_SIZE);
}
static int a3xx_snapshot_cp_pm4_ram(struct kgsl_device *device, void *snapshot,
int remain, void *priv)
{
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
struct kgsl_snapshot_debug *header = snapshot;
unsigned int *data = snapshot + sizeof(*header);
int i, size = adreno_dev->pm4_fw_size - 1;
if (remain < DEBUG_SECTION_SZ(size)) {
SNAPSHOT_ERR_NOMEM(device, "CP PM4 RAM DEBUG");
return 0;
}
header->type = SNAPSHOT_DEBUG_CP_PM4_RAM;
header->size = size;
/*
* Read the firmware from the GPU rather than use our cache in order to
* try to catch mis-programming or corruption in the hardware. We do
* use the cached version of the size, however, instead of trying to
* maintain always changing hardcoded constants
*/
adreno_regwrite(device, REG_CP_ME_RAM_RADDR, 0x0);
for (i = 0; i < size; i++)
adreno_regread(device, REG_CP_ME_RAM_DATA, &data[i]);
return DEBUG_SECTION_SZ(size);
}
static int a3xx_snapshot_cp_pfp_ram(struct kgsl_device *device, void *snapshot,
int remain, void *priv)
{
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
struct kgsl_snapshot_debug *header = snapshot;
unsigned int *data = snapshot + sizeof(*header);
int i, size = adreno_dev->pfp_fw_size - 1;
if (remain < DEBUG_SECTION_SZ(size)) {
SNAPSHOT_ERR_NOMEM(device, "CP PFP RAM DEBUG");
return 0;
}
header->type = SNAPSHOT_DEBUG_CP_PFP_RAM;
header->size = size;
/*
* Read the firmware from the GPU rather than use our cache in order to
* try to catch mis-programming or corruption in the hardware. We do
* use the cached version of the size, however, instead of trying to
* maintain always changing hardcoded constants
*/
kgsl_regwrite(device, A3XX_CP_PFP_UCODE_ADDR, 0x0);
for (i = 0; i < size; i++)
adreno_regread(device, A3XX_CP_PFP_UCODE_DATA, &data[i]);
return DEBUG_SECTION_SZ(size);
}
/* This is the ROQ buffer size on both the A305 and A320 */
#define A320_CP_ROQ_SIZE 128
/* This is the ROQ buffer size on the A330 */
#define A330_CP_ROQ_SIZE 512
static int a3xx_snapshot_cp_roq(struct kgsl_device *device, void *snapshot,
int remain, void *priv)
{
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
struct kgsl_snapshot_debug *header = snapshot;
unsigned int *data = snapshot + sizeof(*header);
int i, size;
/* The size of the ROQ buffer is core dependent */
size = adreno_is_a330(adreno_dev) ?
A330_CP_ROQ_SIZE : A320_CP_ROQ_SIZE;
if (remain < DEBUG_SECTION_SZ(size)) {
SNAPSHOT_ERR_NOMEM(device, "CP ROQ DEBUG");
return 0;
}
header->type = SNAPSHOT_DEBUG_CP_ROQ;
header->size = size;
adreno_regwrite(device, A3XX_CP_ROQ_ADDR, 0x0);
for (i = 0; i < size; i++)
adreno_regread(device, A3XX_CP_ROQ_DATA, &data[i]);
return DEBUG_SECTION_SZ(size);
}
#define A330_CP_MERCIU_QUEUE_SIZE 32
static int a330_snapshot_cp_merciu(struct kgsl_device *device, void *snapshot,
int remain, void *priv)
{
struct kgsl_snapshot_debug *header = snapshot;
unsigned int *data = snapshot + sizeof(*header);
int i, size;
/* The MERCIU data is two dwords per entry */
size = A330_CP_MERCIU_QUEUE_SIZE << 1;
if (remain < DEBUG_SECTION_SZ(size)) {
SNAPSHOT_ERR_NOMEM(device, "CP MERCIU DEBUG");
return 0;
}
header->type = SNAPSHOT_DEBUG_CP_MERCIU;
header->size = size;
adreno_regwrite(device, A3XX_CP_MERCIU_ADDR, 0x0);
for (i = 0; i < A330_CP_MERCIU_QUEUE_SIZE; i++) {
adreno_regread(device, A3XX_CP_MERCIU_DATA,
&data[(i * 2)]);
adreno_regread(device, A3XX_CP_MERCIU_DATA2,
&data[(i * 2) + 1]);
}
return DEBUG_SECTION_SZ(size);
}
#define DEBUGFS_BLOCK_SIZE 0x40
static int a3xx_snapshot_debugbus_block(struct kgsl_device *device,
void *snapshot, int remain, void *priv)
{
struct kgsl_snapshot_debugbus *header = snapshot;
unsigned int id = (unsigned int) priv;
unsigned int val;
int i;
unsigned int *data = snapshot + sizeof(*header);
int size =
(DEBUGFS_BLOCK_SIZE * sizeof(unsigned int)) + sizeof(*header);
if (remain < size) {
SNAPSHOT_ERR_NOMEM(device, "DEBUGBUS");
return 0;
}
val = (id << 8) | (1 << 16);
header->id = id;
header->count = DEBUGFS_BLOCK_SIZE;
for (i = 0; i < DEBUGFS_BLOCK_SIZE; i++)
_rbbm_debug_bus_read(device, id, i, &data[i]);
return size;
}
static unsigned int debugbus_blocks[] = {
RBBM_BLOCK_ID_CP,
RBBM_BLOCK_ID_RBBM,
RBBM_BLOCK_ID_VBIF,
RBBM_BLOCK_ID_HLSQ,
RBBM_BLOCK_ID_UCHE,
RBBM_BLOCK_ID_PC,
RBBM_BLOCK_ID_VFD,
RBBM_BLOCK_ID_VPC,
RBBM_BLOCK_ID_TSE,
RBBM_BLOCK_ID_RAS,
RBBM_BLOCK_ID_VSC,
RBBM_BLOCK_ID_SP_0,
RBBM_BLOCK_ID_SP_1,
RBBM_BLOCK_ID_SP_2,
RBBM_BLOCK_ID_SP_3,
RBBM_BLOCK_ID_TPL1_0,
RBBM_BLOCK_ID_TPL1_1,
RBBM_BLOCK_ID_TPL1_2,
RBBM_BLOCK_ID_TPL1_3,
RBBM_BLOCK_ID_RB_0,
RBBM_BLOCK_ID_RB_1,
RBBM_BLOCK_ID_RB_2,
RBBM_BLOCK_ID_RB_3,
RBBM_BLOCK_ID_MARB_0,
RBBM_BLOCK_ID_MARB_1,
RBBM_BLOCK_ID_MARB_2,
RBBM_BLOCK_ID_MARB_3,
};
static void *a3xx_snapshot_debugbus(struct kgsl_device *device,
void *snapshot, int *remain)
{
int i;
for (i = 0; i < ARRAY_SIZE(debugbus_blocks); i++) {
snapshot = kgsl_snapshot_add_section(device,
KGSL_SNAPSHOT_SECTION_DEBUGBUS, snapshot, remain,
a3xx_snapshot_debugbus_block,
(void *) debugbus_blocks[i]);
}
return snapshot;
}
static void _snapshot_a3xx_regs(struct kgsl_snapshot_registers *regs,
struct kgsl_snapshot_registers_list *list)
{
regs[list->count].regs = (unsigned int *) a3xx_registers;
regs[list->count].count = a3xx_registers_count;
list->count++;
}
static void _snapshot_hlsq_regs(struct kgsl_snapshot_registers *regs,
struct kgsl_snapshot_registers_list *list,
struct adreno_device *adreno_dev)
{
struct kgsl_device *device = &adreno_dev->dev;
/*
* Trying to read HLSQ registers when the HLSQ block is busy
* will cause the device to hang. The RBBM_DEBUG_BUS has information
* that will tell us if the HLSQ block is busy or not. Read values
* from the debug bus to ensure the HLSQ block is not busy (this
* is hardware dependent). If the HLSQ block is busy do not
* dump the registers, otherwise dump the HLSQ registers.
*/
if (adreno_is_a330(adreno_dev)) {
/*
* stall_ctxt_full status bit: RBBM_BLOCK_ID_HLSQ index 49 [27]
*
* if (!stall_context_full)
* then dump HLSQ registers
*/
unsigned int stall_context_full = 0;
_rbbm_debug_bus_read(device, RBBM_BLOCK_ID_HLSQ, 49,
&stall_context_full);
stall_context_full &= 0x08000000;
if (stall_context_full)
return;
} else {
/*
* tpif status bits: RBBM_BLOCK_ID_HLSQ index 4 [4:0]
* spif status bits: RBBM_BLOCK_ID_HLSQ index 7 [5:0]
*
* if ((tpif == 0, 1, 28) && (spif == 0, 1, 10))
* then dump HLSQ registers
*/
unsigned int next_pif = 0;
/* check tpif */
_rbbm_debug_bus_read(device, RBBM_BLOCK_ID_HLSQ, 4, &next_pif);
next_pif &= 0x1f;
if (next_pif != 0 && next_pif != 1 && next_pif != 28)
return;
/* check spif */
_rbbm_debug_bus_read(device, RBBM_BLOCK_ID_HLSQ, 7, &next_pif);
next_pif &= 0x3f;
if (next_pif != 0 && next_pif != 1 && next_pif != 10)
return;
}
regs[list->count].regs = (unsigned int *) a3xx_hlsq_registers;
regs[list->count].count = a3xx_hlsq_registers_count;
list->count++;
}
static void _snapshot_a330_regs(struct kgsl_snapshot_registers *regs,
struct kgsl_snapshot_registers_list *list)
{
/* For A330, append the additional list of new registers to grab */
regs[list->count].regs = (unsigned int *) a330_registers;
regs[list->count].count = a330_registers_count;
list->count++;
}
/* A3XX GPU snapshot function - this is where all of the A3XX specific
* bits and pieces are grabbed into the snapshot memory
*/
void *a3xx_snapshot(struct adreno_device *adreno_dev, void *snapshot,
int *remain, int hang)
{
struct kgsl_device *device = &adreno_dev->dev;
struct kgsl_snapshot_registers_list list;
struct kgsl_snapshot_registers regs[5];
list.registers = regs;
list.count = 0;
/* Disable Clock gating temporarily for the debug bus to work */
adreno_regwrite(device, A3XX_RBBM_CLOCK_CTL, 0x00);
/* Store relevant registers in list to snapshot */
_snapshot_a3xx_regs(regs, &list);
_snapshot_hlsq_regs(regs, &list, adreno_dev);
if (adreno_is_a330(adreno_dev))
_snapshot_a330_regs(regs, &list);
/* Master set of (non debug) registers */
snapshot = kgsl_snapshot_add_section(device,
KGSL_SNAPSHOT_SECTION_REGS, snapshot, remain,
kgsl_snapshot_dump_regs, &list);
/* CP_STATE_DEBUG indexed registers */
snapshot = kgsl_snapshot_indexed_registers(device, snapshot,
remain, REG_CP_STATE_DEBUG_INDEX,
REG_CP_STATE_DEBUG_DATA, 0x0, 0x14);
/* CP_ME indexed registers */
snapshot = kgsl_snapshot_indexed_registers(device, snapshot,
remain, REG_CP_ME_CNTL, REG_CP_ME_STATUS,
64, 44);
/* VPC memory */
snapshot = kgsl_snapshot_add_section(device,
KGSL_SNAPSHOT_SECTION_DEBUG, snapshot, remain,
a3xx_snapshot_vpc_memory, NULL);
/* CP MEQ */
snapshot = kgsl_snapshot_add_section(device,
KGSL_SNAPSHOT_SECTION_DEBUG, snapshot, remain,
a3xx_snapshot_cp_meq, NULL);
/* Shader working/shadow memory */
snapshot = kgsl_snapshot_add_section(device,
KGSL_SNAPSHOT_SECTION_DEBUG, snapshot, remain,
a3xx_snapshot_shader_memory, NULL);
/* CP PFP and PM4 */
/* Reading these will hang the GPU if it isn't already hung */
if (hang) {
snapshot = kgsl_snapshot_add_section(device,
KGSL_SNAPSHOT_SECTION_DEBUG, snapshot, remain,
a3xx_snapshot_cp_pfp_ram, NULL);
snapshot = kgsl_snapshot_add_section(device,
KGSL_SNAPSHOT_SECTION_DEBUG, snapshot, remain,
a3xx_snapshot_cp_pm4_ram, NULL);
}
/* CP ROQ */
snapshot = kgsl_snapshot_add_section(device,
KGSL_SNAPSHOT_SECTION_DEBUG, snapshot, remain,
a3xx_snapshot_cp_roq, NULL);
if (adreno_is_a330(adreno_dev)) {
snapshot = kgsl_snapshot_add_section(device,
KGSL_SNAPSHOT_SECTION_DEBUG, snapshot, remain,
a330_snapshot_cp_merciu, NULL);
}
snapshot = a3xx_snapshot_debugbus(device, snapshot, remain);
/* Enable Clock gating */
adreno_regwrite(device, A3XX_RBBM_CLOCK_CTL,
adreno_a3xx_rbbm_clock_ctl_default(adreno_dev));
return snapshot;
}
| gpl-2.0 |
neldar/kernel-2.6.32.9-i9000-bln-only | drivers/media/dvb/frontends/stv6110.c | 465 | 10916 | /*
* stv6110.c
*
* Driver for ST STV6110 satellite tuner IC.
*
* 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 <linux/module.h>
#include <linux/dvb/frontend.h>
#include <linux/types.h>
#include "stv6110.h"
static int debug;
struct stv6110_priv {
int i2c_address;
struct i2c_adapter *i2c;
u32 mclk;
u8 clk_div;
u8 regs[8];
};
#define dprintk(args...) \
do { \
if (debug) \
printk(KERN_DEBUG args); \
} while (0)
static s32 abssub(s32 a, s32 b)
{
if (a > b)
return a - b;
else
return b - a;
};
static int stv6110_release(struct dvb_frontend *fe)
{
kfree(fe->tuner_priv);
fe->tuner_priv = NULL;
return 0;
}
static int stv6110_write_regs(struct dvb_frontend *fe, u8 buf[],
int start, int len)
{
struct stv6110_priv *priv = fe->tuner_priv;
int rc;
u8 cmdbuf[len + 1];
struct i2c_msg msg = {
.addr = priv->i2c_address,
.flags = 0,
.buf = cmdbuf,
.len = len + 1
};
dprintk("%s\n", __func__);
if (start + len > 8)
return -EINVAL;
memcpy(&cmdbuf[1], buf, len);
cmdbuf[0] = start;
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
rc = i2c_transfer(priv->i2c, &msg, 1);
if (rc != 1)
dprintk("%s: i2c error\n", __func__);
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 0);
return 0;
}
static int stv6110_read_regs(struct dvb_frontend *fe, u8 regs[],
int start, int len)
{
struct stv6110_priv *priv = fe->tuner_priv;
int rc;
u8 reg[] = { start };
struct i2c_msg msg[] = {
{
.addr = priv->i2c_address,
.flags = 0,
.buf = reg,
.len = 1,
}, {
.addr = priv->i2c_address,
.flags = I2C_M_RD,
.buf = regs,
.len = len,
},
};
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
rc = i2c_transfer(priv->i2c, msg, 2);
if (rc != 2)
dprintk("%s: i2c error\n", __func__);
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 0);
memcpy(&priv->regs[start], regs, len);
return 0;
}
static int stv6110_read_reg(struct dvb_frontend *fe, int start)
{
u8 buf[] = { 0 };
stv6110_read_regs(fe, buf, start, 1);
return buf[0];
}
static int stv6110_sleep(struct dvb_frontend *fe)
{
u8 reg[] = { 0 };
stv6110_write_regs(fe, reg, 0, 1);
return 0;
}
static u32 carrier_width(u32 symbol_rate, fe_rolloff_t rolloff)
{
u32 rlf;
switch (rolloff) {
case ROLLOFF_20:
rlf = 20;
break;
case ROLLOFF_25:
rlf = 25;
break;
default:
rlf = 35;
break;
}
return symbol_rate + ((symbol_rate * rlf) / 100);
}
static int stv6110_set_bandwidth(struct dvb_frontend *fe, u32 bandwidth)
{
struct stv6110_priv *priv = fe->tuner_priv;
u8 r8, ret = 0x04;
int i;
if ((bandwidth / 2) > 36000000) /*BW/2 max=31+5=36 mhz for r8=31*/
r8 = 31;
else if ((bandwidth / 2) < 5000000) /* BW/2 min=5Mhz for F=0 */
r8 = 0;
else /*if 5 < BW/2 < 36*/
r8 = (bandwidth / 2) / 1000000 - 5;
/* ctrl3, RCCLKOFF = 0 Activate the calibration Clock */
/* ctrl3, CF = r8 Set the LPF value */
priv->regs[RSTV6110_CTRL3] &= ~((1 << 6) | 0x1f);
priv->regs[RSTV6110_CTRL3] |= (r8 & 0x1f);
stv6110_write_regs(fe, &priv->regs[RSTV6110_CTRL3], RSTV6110_CTRL3, 1);
/* stat1, CALRCSTRT = 1 Start LPF auto calibration*/
priv->regs[RSTV6110_STAT1] |= 0x02;
stv6110_write_regs(fe, &priv->regs[RSTV6110_STAT1], RSTV6110_STAT1, 1);
i = 0;
/* Wait for CALRCSTRT == 0 */
while ((i < 10) && (ret != 0)) {
ret = ((stv6110_read_reg(fe, RSTV6110_STAT1)) & 0x02);
mdelay(1); /* wait for LPF auto calibration */
i++;
}
/* RCCLKOFF = 1 calibration done, desactivate the calibration Clock */
priv->regs[RSTV6110_CTRL3] |= (1 << 6);
stv6110_write_regs(fe, &priv->regs[RSTV6110_CTRL3], RSTV6110_CTRL3, 1);
return 0;
}
static int stv6110_init(struct dvb_frontend *fe)
{
struct stv6110_priv *priv = fe->tuner_priv;
u8 buf0[] = { 0x07, 0x11, 0xdc, 0x85, 0x17, 0x01, 0xe6, 0x1e };
memcpy(priv->regs, buf0, 8);
/* K = (Reference / 1000000) - 16 */
priv->regs[RSTV6110_CTRL1] &= ~(0x1f << 3);
priv->regs[RSTV6110_CTRL1] |=
((((priv->mclk / 1000000) - 16) & 0x1f) << 3);
/* divisor value for the output clock */
priv->regs[RSTV6110_CTRL2] &= ~0xc0;
priv->regs[RSTV6110_CTRL2] |= (priv->clk_div << 6);
stv6110_write_regs(fe, &priv->regs[RSTV6110_CTRL1], RSTV6110_CTRL1, 8);
msleep(1);
stv6110_set_bandwidth(fe, 72000000);
return 0;
}
static int stv6110_get_frequency(struct dvb_frontend *fe, u32 *frequency)
{
struct stv6110_priv *priv = fe->tuner_priv;
u32 nbsteps, divider, psd2, freq;
u8 regs[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
stv6110_read_regs(fe, regs, 0, 8);
/*N*/
divider = (priv->regs[RSTV6110_TUNING2] & 0x0f) << 8;
divider += priv->regs[RSTV6110_TUNING1];
/*R*/
nbsteps = (priv->regs[RSTV6110_TUNING2] >> 6) & 3;
/*p*/
psd2 = (priv->regs[RSTV6110_TUNING2] >> 4) & 1;
freq = divider * (priv->mclk / 1000);
freq /= (1 << (nbsteps + psd2));
freq /= 4;
*frequency = freq;
return 0;
}
static int stv6110_set_frequency(struct dvb_frontend *fe, u32 frequency)
{
struct stv6110_priv *priv = fe->tuner_priv;
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
u8 ret = 0x04;
u32 divider, ref, p, presc, i, result_freq, vco_freq;
s32 p_calc, p_calc_opt = 1000, r_div, r_div_opt = 0, p_val;
s32 srate; u8 gain;
dprintk("%s, freq=%d kHz, mclk=%d Hz\n", __func__,
frequency, priv->mclk);
/* K = (Reference / 1000000) - 16 */
priv->regs[RSTV6110_CTRL1] &= ~(0x1f << 3);
priv->regs[RSTV6110_CTRL1] |=
((((priv->mclk / 1000000) - 16) & 0x1f) << 3);
/* BB_GAIN = db/2 */
if (fe->ops.set_property && fe->ops.get_property) {
srate = c->symbol_rate;
dprintk("%s: Get Frontend parameters: srate=%d\n",
__func__, srate);
} else
srate = 15000000;
if (srate >= 15000000)
gain = 3; /* +6 dB */
else if (srate >= 5000000)
gain = 3; /* +6 dB */
else
gain = 3; /* +6 dB */
priv->regs[RSTV6110_CTRL2] &= ~0x0f;
priv->regs[RSTV6110_CTRL2] |= (gain & 0x0f);
if (frequency <= 1023000) {
p = 1;
presc = 0;
} else if (frequency <= 1300000) {
p = 1;
presc = 1;
} else if (frequency <= 2046000) {
p = 0;
presc = 0;
} else {
p = 0;
presc = 1;
}
/* DIV4SEL = p*/
priv->regs[RSTV6110_TUNING2] &= ~(1 << 4);
priv->regs[RSTV6110_TUNING2] |= (p << 4);
/* PRESC32ON = presc */
priv->regs[RSTV6110_TUNING2] &= ~(1 << 5);
priv->regs[RSTV6110_TUNING2] |= (presc << 5);
p_val = (int)(1 << (p + 1)) * 10;/* P = 2 or P = 4 */
for (r_div = 0; r_div <= 3; r_div++) {
p_calc = (priv->mclk / 100000);
p_calc /= (1 << (r_div + 1));
if ((abssub(p_calc, p_val)) < (abssub(p_calc_opt, p_val)))
r_div_opt = r_div;
p_calc_opt = (priv->mclk / 100000);
p_calc_opt /= (1 << (r_div_opt + 1));
}
ref = priv->mclk / ((1 << (r_div_opt + 1)) * (1 << (p + 1)));
divider = (((frequency * 1000) + (ref >> 1)) / ref);
/* RDIV = r_div_opt */
priv->regs[RSTV6110_TUNING2] &= ~(3 << 6);
priv->regs[RSTV6110_TUNING2] |= (((r_div_opt) & 3) << 6);
/* NDIV_MSB = MSB(divider) */
priv->regs[RSTV6110_TUNING2] &= ~0x0f;
priv->regs[RSTV6110_TUNING2] |= (((divider) >> 8) & 0x0f);
/* NDIV_LSB, LSB(divider) */
priv->regs[RSTV6110_TUNING1] = (divider & 0xff);
/* CALVCOSTRT = 1 VCO Auto Calibration */
priv->regs[RSTV6110_STAT1] |= 0x04;
stv6110_write_regs(fe, &priv->regs[RSTV6110_CTRL1],
RSTV6110_CTRL1, 8);
i = 0;
/* Wait for CALVCOSTRT == 0 */
while ((i < 10) && (ret != 0)) {
ret = ((stv6110_read_reg(fe, RSTV6110_STAT1)) & 0x04);
msleep(1); /* wait for VCO auto calibration */
i++;
}
ret = stv6110_read_reg(fe, RSTV6110_STAT1);
stv6110_get_frequency(fe, &result_freq);
vco_freq = divider * ((priv->mclk / 1000) / ((1 << (r_div_opt + 1))));
dprintk("%s, stat1=%x, lo_freq=%d kHz, vco_frec=%d kHz\n", __func__,
ret, result_freq, vco_freq);
return 0;
}
static int stv6110_set_params(struct dvb_frontend *fe,
struct dvb_frontend_parameters *params)
{
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
u32 bandwidth = carrier_width(c->symbol_rate, c->rolloff);
stv6110_set_frequency(fe, c->frequency);
stv6110_set_bandwidth(fe, bandwidth);
return 0;
}
static int stv6110_get_bandwidth(struct dvb_frontend *fe, u32 *bandwidth)
{
struct stv6110_priv *priv = fe->tuner_priv;
u8 r8 = 0;
u8 regs[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
stv6110_read_regs(fe, regs, 0, 8);
/* CF */
r8 = priv->regs[RSTV6110_CTRL3] & 0x1f;
*bandwidth = (r8 + 5) * 2000000;/* x2 for ZIF tuner BW/2 = F+5 Mhz */
return 0;
}
static struct dvb_tuner_ops stv6110_tuner_ops = {
.info = {
.name = "ST STV6110",
.frequency_min = 950000,
.frequency_max = 2150000,
.frequency_step = 1000,
},
.init = stv6110_init,
.release = stv6110_release,
.sleep = stv6110_sleep,
.set_params = stv6110_set_params,
.get_frequency = stv6110_get_frequency,
.set_frequency = stv6110_set_frequency,
.get_bandwidth = stv6110_get_bandwidth,
.set_bandwidth = stv6110_set_bandwidth,
};
struct dvb_frontend *stv6110_attach(struct dvb_frontend *fe,
const struct stv6110_config *config,
struct i2c_adapter *i2c)
{
struct stv6110_priv *priv = NULL;
u8 reg0[] = { 0x00, 0x07, 0x11, 0xdc, 0x85, 0x17, 0x01, 0xe6, 0x1e };
struct i2c_msg msg[] = {
{
.addr = config->i2c_address,
.flags = 0,
.buf = reg0,
.len = 9
}
};
int ret;
/* divisor value for the output clock */
reg0[2] &= ~0xc0;
reg0[2] |= (config->clk_div << 6);
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 1);
ret = i2c_transfer(i2c, msg, 1);
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 0);
if (ret != 1)
return NULL;
priv = kzalloc(sizeof(struct stv6110_priv), GFP_KERNEL);
if (priv == NULL)
return NULL;
priv->i2c_address = config->i2c_address;
priv->i2c = i2c;
priv->mclk = config->mclk;
priv->clk_div = config->clk_div;
memcpy(&priv->regs, ®0[1], 8);
memcpy(&fe->ops.tuner_ops, &stv6110_tuner_ops,
sizeof(struct dvb_tuner_ops));
fe->tuner_priv = priv;
printk(KERN_INFO "STV6110 attached on addr=%x!\n", priv->i2c_address);
return fe;
}
EXPORT_SYMBOL(stv6110_attach);
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Turn on/off frontend debugging (default:off).");
MODULE_DESCRIPTION("ST STV6110 driver");
MODULE_AUTHOR("Igor M. Liplianin");
MODULE_LICENSE("GPL");
| gpl-2.0 |
bananacakes/bravo_2.6.35_gb-mr | arch/powerpc/kernel/machine_kexec.c | 721 | 5648 | /*
* Code to handle transition of Linux booting another kernel.
*
* Copyright (C) 2002-2003 Eric Biederman <ebiederm@xmission.com>
* GameCube/ppc32 port Copyright (C) 2004 Albert Herranz
* Copyright (C) 2005 IBM Corporation.
*
* This source code is licensed under the GNU General Public License,
* Version 2. See the file COPYING for more details.
*/
#include <linux/kexec.h>
#include <linux/reboot.h>
#include <linux/threads.h>
#include <linux/memblock.h>
#include <linux/of.h>
#include <asm/machdep.h>
#include <asm/prom.h>
#include <asm/sections.h>
void machine_crash_shutdown(struct pt_regs *regs)
{
if (ppc_md.machine_crash_shutdown)
ppc_md.machine_crash_shutdown(regs);
else
default_machine_crash_shutdown(regs);
}
/*
* Do what every setup is needed on image and the
* reboot code buffer to allow us to avoid allocations
* later.
*/
int machine_kexec_prepare(struct kimage *image)
{
if (ppc_md.machine_kexec_prepare)
return ppc_md.machine_kexec_prepare(image);
else
return default_machine_kexec_prepare(image);
}
void machine_kexec_cleanup(struct kimage *image)
{
if (ppc_md.machine_kexec_cleanup)
ppc_md.machine_kexec_cleanup(image);
}
/*
* Do not allocate memory (or fail in any way) in machine_kexec().
* We are past the point of no return, committed to rebooting now.
*/
void machine_kexec(struct kimage *image)
{
if (ppc_md.machine_kexec)
ppc_md.machine_kexec(image);
else
default_machine_kexec(image);
/* Fall back to normal restart if we're still alive. */
machine_restart(NULL);
for(;;);
}
void __init reserve_crashkernel(void)
{
unsigned long long crash_size, crash_base;
int ret;
/* this is necessary because of memblock_phys_mem_size() */
memblock_analyze();
/* use common parsing */
ret = parse_crashkernel(boot_command_line, memblock_phys_mem_size(),
&crash_size, &crash_base);
if (ret == 0 && crash_size > 0) {
crashk_res.start = crash_base;
crashk_res.end = crash_base + crash_size - 1;
}
if (crashk_res.end == crashk_res.start) {
crashk_res.start = crashk_res.end = 0;
return;
}
/* We might have got these values via the command line or the
* device tree, either way sanitise them now. */
crash_size = crashk_res.end - crashk_res.start + 1;
#ifndef CONFIG_RELOCATABLE
if (crashk_res.start != KDUMP_KERNELBASE)
printk("Crash kernel location must be 0x%x\n",
KDUMP_KERNELBASE);
crashk_res.start = KDUMP_KERNELBASE;
#else
if (!crashk_res.start) {
/*
* unspecified address, choose a region of specified size
* can overlap with initrd (ignoring corruption when retained)
* ppc64 requires kernel and some stacks to be in first segemnt
*/
crashk_res.start = KDUMP_KERNELBASE;
}
crash_base = PAGE_ALIGN(crashk_res.start);
if (crash_base != crashk_res.start) {
printk("Crash kernel base must be aligned to 0x%lx\n",
PAGE_SIZE);
crashk_res.start = crash_base;
}
#endif
crash_size = PAGE_ALIGN(crash_size);
crashk_res.end = crashk_res.start + crash_size - 1;
/* The crash region must not overlap the current kernel */
if (overlaps_crashkernel(__pa(_stext), _end - _stext)) {
printk(KERN_WARNING
"Crash kernel can not overlap current kernel\n");
crashk_res.start = crashk_res.end = 0;
return;
}
/* Crash kernel trumps memory limit */
if (memory_limit && memory_limit <= crashk_res.end) {
memory_limit = crashk_res.end + 1;
printk("Adjusted memory limit for crashkernel, now 0x%llx\n",
(unsigned long long)memory_limit);
}
printk(KERN_INFO "Reserving %ldMB of memory at %ldMB "
"for crashkernel (System RAM: %ldMB)\n",
(unsigned long)(crash_size >> 20),
(unsigned long)(crashk_res.start >> 20),
(unsigned long)(memblock_phys_mem_size() >> 20));
memblock_reserve(crashk_res.start, crash_size);
}
int overlaps_crashkernel(unsigned long start, unsigned long size)
{
return (start + size) > crashk_res.start && start <= crashk_res.end;
}
/* Values we need to export to the second kernel via the device tree. */
static unsigned long kernel_end;
static unsigned long crashk_size;
static struct property kernel_end_prop = {
.name = "linux,kernel-end",
.length = sizeof(unsigned long),
.value = &kernel_end,
};
static struct property crashk_base_prop = {
.name = "linux,crashkernel-base",
.length = sizeof(unsigned long),
.value = &crashk_res.start,
};
static struct property crashk_size_prop = {
.name = "linux,crashkernel-size",
.length = sizeof(unsigned long),
.value = &crashk_size,
};
static void __init export_crashk_values(struct device_node *node)
{
struct property *prop;
/* There might be existing crash kernel properties, but we can't
* be sure what's in them, so remove them. */
prop = of_find_property(node, "linux,crashkernel-base", NULL);
if (prop)
prom_remove_property(node, prop);
prop = of_find_property(node, "linux,crashkernel-size", NULL);
if (prop)
prom_remove_property(node, prop);
if (crashk_res.start != 0) {
prom_add_property(node, &crashk_base_prop);
crashk_size = crashk_res.end - crashk_res.start + 1;
prom_add_property(node, &crashk_size_prop);
}
}
static int __init kexec_setup(void)
{
struct device_node *node;
struct property *prop;
node = of_find_node_by_path("/chosen");
if (!node)
return -ENOENT;
/* remove any stale properties so ours can be found */
prop = of_find_property(node, kernel_end_prop.name, NULL);
if (prop)
prom_remove_property(node, prop);
/* information needed by userspace when using default_machine_kexec */
kernel_end = __pa(_end);
prom_add_property(node, &kernel_end_prop);
export_crashk_values(node);
of_node_put(node);
return 0;
}
late_initcall(kexec_setup);
| gpl-2.0 |
sq9fk/HamNET-Mesh-SP9PDF | target/linux/at91/image/dfboot/src/main.c | 721 | 22643 | /*----------------------------------------------------------------------------
* ATMEL Microcontroller Software Support - ROUSSET -
*----------------------------------------------------------------------------
* The software is delivered "AS IS" without warranty or condition of any
* kind, either express, implied or statutory. This includes without
* limitation any warranty or condition with respect to merchantability or
* fitness for any particular purpose, or against the infringements of
* intellectual property rights of others.
*----------------------------------------------------------------------------
* File Name : main.c
* Object :
* Creation : HIi 10/10/2003
* Modif : HIi 15/06/2004 : add crc32 to verify the download
* from dataflash
* : HIi 21/09/2004 : Set first PLLA to 180Mhz and MCK to
* 60Mhz to speed up dataflash boot (15Mhz)
* : MLC 12/04/2005 : Modify SetPLL() to avoid errata
* : USA 30/12/2005 : Change to page Size 1056
* Change startaddress to C0008400
* Change SPI Speed to ~4 Mhz
* Add retry on CRC Error
*----------------------------------------------------------------------------
*/
#include "config.h"
#include "stdio.h"
#include "AT91RM9200.h"
#include "lib_AT91RM9200.h"
#include "com.h"
#include "main.h"
#include "dataflash.h"
#include "AT91C_MCI_Device.h"
#define DEBUGOUT
#define XMODEM
#define MEMDISP
#ifdef PAGESZ_1056
#define PAGESIZE 1056
#else
#define PAGESIZE 1024
#endif
#define AT91C_SDRAM_START 0x20000000
#define AT91C_BOOT_ADDR 0x21F00000
#define AT91C_BOOT_SIZE 128*PAGESIZE
#ifdef PAGESZ_1056
#define AT91C_BOOT_DATAFLASH_ADDR 0xC0008400
#else
#define AT91C_BOOT_DATAFLASH_ADDR 0xC0008000
#endif
#define AT91C_PLLA_VALUE 0x237A3E5A // crystal= 18.432MHz - fixes BRG error at 115kbps
//#define AT91C_PLLA_VALUE 0x2026BE04 // crystal= 18.432MHz
//#define AT91C_PLLA_VALUE 0x202CBE01 // crystal= 4MHz
#define DISP_LINE_LEN 16
// Reason for boot failure
#define IMAGE_BAD_SIZE 0
#define IMAGE_READ_FAILURE 1
#define IMAGE_CRC_ERROR 2
#define IMAGE_ERROR 3
#define SUCCESS -1
/* prototypes*/
extern void AT91F_ST_ASM_HANDLER(void);
extern void Jump(unsigned int addr);
const char *menu_dataflash[] = {
#ifdef XMODEM
"1: P DFboot\n",
"2: P U-Boot\n",
#endif
"3: P SDCard\n",
#ifdef PAGESZ_1056
"4: R UBOOT\n",
#else
"4: R UBOOT\n",
#endif
#ifdef XMODEM
"5: P DF [addr]\n",
#endif
"6: RD DF [addr]\n",
"7: E DF\n"
};
#ifdef XMODEM
#define MAXMENU 7
#else
#define MAXMENU 4
#endif
char message[20];
#ifdef XMODEM
volatile char XmodemComplete = 0;
#endif
unsigned int StTick = 0;
AT91S_RomBoot const *pAT91;
#ifdef XMODEM
AT91S_SBuffer sXmBuffer;
AT91S_SvcXmodem svcXmodem;
AT91S_Pipe xmodemPipe;
#endif
AT91S_CtlTempo ctlTempo;
//*--------------------------------------------------------------------------------------
//* Function Name : GetTickCount()
//* Object : Return the number of systimer tick
//* Input Parameters :
//* Output Parameters :
//*--------------------------------------------------------------------------------------
unsigned int GetTickCount(void)
{
return StTick;
}
#ifdef XMODEM
//*--------------------------------------------------------------------------------------
//* Function Name : AT91_XmodemComplete()
//* Object : Perform the remap and jump to appli in RAM
//* Input Parameters :
//* Output Parameters :
//*--------------------------------------------------------------------------------------
static void AT91_XmodemComplete(AT91S_PipeStatus status, void *pVoid)
{
/* stop the Xmodem tempo */
svcXmodem.tempo.Stop(&(svcXmodem.tempo));
XmodemComplete = 1;
}
//*--------------------------------------------------------------------------------------
//* Function Name : AT91F_XmodemProtocol(AT91S_PipeStatus status, void *pVoid)
//* Object : Xmodem dispatcher
//* Input Parameters :
//* Output Parameters :
//*--------------------------------------------------------------------------------------
static void XmodemProtocol(AT91S_PipeStatus status, void *pVoid)
{
AT91PS_SBuffer pSBuffer = (AT91PS_SBuffer) xmodemPipe.pBuffer->pChild;
AT91PS_USART pUsart = svcXmodem.pUsart;
if (pSBuffer->szRdBuffer == 0) {
/* Start a tempo to wait the Xmodem protocol complete */
svcXmodem.tempo.Start(&(svcXmodem.tempo), 10, 0, AT91_XmodemComplete, pUsart);
}
}
#endif
//*--------------------------------------------------------------------------------------
//* Function Name : irq1_c_handler()
//* Object : C Interrupt handler for Interrutp source 1
//* Input Parameters : none
//* Output Parameters : none
//*--------------------------------------------------------------------------------------
void AT91F_ST_HANDLER(void)
{
volatile unsigned int csr = *AT91C_DBGU_CSR;
#ifdef XMODEM
unsigned int error;
#endif
if (AT91C_BASE_ST->ST_SR & 0x01) {
StTick++;
ctlTempo.CtlTempoTick(&ctlTempo);
return;
}
#ifdef XMODEM
error = AT91F_US_Error((AT91PS_USART)AT91C_BASE_DBGU);
if (csr & error) {
/* Stop previous Xmodem transmition*/
*(AT91C_DBGU_CR) = AT91C_US_RSTSTA;
AT91F_US_DisableIt((AT91PS_USART)AT91C_BASE_DBGU, AT91C_US_ENDRX);
AT91F_US_EnableIt((AT91PS_USART)AT91C_BASE_DBGU, AT91C_US_RXRDY);
}
else if (csr & (AT91C_US_TXRDY | AT91C_US_ENDTX | AT91C_US_TXEMPTY |
AT91C_US_RXRDY | AT91C_US_ENDRX | AT91C_US_TIMEOUT |
AT91C_US_RXBUFF)) {
if ( !(svcXmodem.eot) )
svcXmodem.Handler(&svcXmodem, csr);
}
#endif
}
//*-----------------------------------------------------------------------------
//* Function Name : AT91F_DisplayMenu()
//* Object :
//* Input Parameters :
//* Return value :
//*-----------------------------------------------------------------------------
static int AT91F_DisplayMenu(void)
{
int i, mci_present = 0;
printf("\nDF LOADER %s %s %s\n",AT91C_VERSION,__DATE__,__TIME__);
AT91F_DataflashPrintInfo();
mci_present = AT91F_MCI_Init();
for(i = 0; i < MAXMENU; i++) {
puts(menu_dataflash[i]);
}
return mci_present;
}
//*-----------------------------------------------------------------------------
//* Function Name : AsciiToHex()
//* Object : ascii to hexa conversion
//* Input Parameters :
//* Return value :
//*-----------------------------------------------------------------------------
static unsigned int AsciiToHex(char *s, unsigned int *val)
{
int n;
*val=0;
if(s[0] == '0' && ((s[1] == 'x') || (s[1] == 'X')))
s+=2;
n = 0;
while((n < 8) && (s[n] !=0))
{
*val <<= 4;
if ( (s[n] >= '0') && (s[n] <='9'))
*val += (s[n] - '0');
else
if ((s[n] >= 'a') && (s[n] <='f'))
*val += (s[n] - 0x57);
else
if ((s[n] >= 'A') && (s[n] <='F'))
*val += (s[n] - 0x37);
else
return 0;
n++;
}
return 1;
}
#ifdef MEMDISP
//*-----------------------------------------------------------------------------
//* Function Name : AT91F_MemoryDisplay()
//* Object : Display the content of the dataflash
//* Input Parameters :
//* Return value :
//*-----------------------------------------------------------------------------
static int AT91F_MemoryDisplay(unsigned int addr, unsigned int length)
{
unsigned long i, nbytes, linebytes;
char *cp;
// unsigned int *uip;
// unsigned short *usp;
unsigned char *ucp;
char linebuf[DISP_LINE_LEN];
// nbytes = length * size;
nbytes = length;
do
{
// uip = (unsigned int *)linebuf;
// usp = (unsigned short *)linebuf;
ucp = (unsigned char *)linebuf;
printf("%08x:", addr);
linebytes = (nbytes > DISP_LINE_LEN)?DISP_LINE_LEN:nbytes;
if((addr & 0xF0000000) == 0x20000000) {
for(i = 0; i < linebytes; i ++) {
linebuf[i] = *(char *)(addr+i);
}
} else {
read_dataflash(addr, linebytes, linebuf);
}
for (i=0; i<linebytes; i++)
{
/* if (size == 4)
printf(" %08x", *uip++);
else if (size == 2)
printf(" %04x", *usp++);
else
*/
printf(" %02x", *ucp++);
// addr += size;
addr++;
}
printf(" ");
cp = linebuf;
for (i=0; i<linebytes; i++) {
if ((*cp < 0x20) || (*cp > 0x7e))
printf(".");
else
printf("%c", *cp);
cp++;
}
printf("\n");
nbytes -= linebytes;
} while (nbytes > 0);
return 0;
}
#endif
//*--------------------------------------------------------------------------------------
//* Function Name : AT91F_SetPLL
//* Object : Set the PLLA to 180Mhz and Master clock to 60 Mhz
//* Input Parameters :
//* Output Parameters :
//*--------------------------------------------------------------------------------------
static unsigned int AT91F_SetPLL(void)
{
AT91_REG tmp;
AT91PS_PMC pPmc = AT91C_BASE_PMC;
AT91PS_CKGR pCkgr = AT91C_BASE_CKGR;
pPmc->PMC_IDR = 0xFFFFFFFF;
/* -Setup the PLL A */
pCkgr->CKGR_PLLAR = AT91C_PLLA_VALUE;
while (!(*AT91C_PMC_SR & AT91C_PMC_LOCKA));
/* - Switch Master Clock from PLLB to PLLA/3 */
tmp = pPmc->PMC_MCKR;
/* See Atmel Errata #27 and #28 */
if (tmp & 0x0000001C) {
tmp = (tmp & ~0x0000001C);
pPmc->PMC_MCKR = tmp;
while (!(*AT91C_PMC_SR & AT91C_PMC_MCKRDY));
}
if (tmp != 0x00000202) {
pPmc->PMC_MCKR = 0x00000202;
if ((tmp & 0x00000003) != 0x00000002)
while (!(*AT91C_PMC_SR & AT91C_PMC_MCKRDY));
}
return 1;
}
//*--------------------------------------------------------------------------------------
//* Function Name : AT91F_ResetRegisters
//* Object : Restore the initial state to registers
//* Input Parameters :
//* Output Parameters :
//*--------------------------------------------------------------------------------------
static unsigned int AT91F_ResetRegisters(void)
{
volatile int i = 0;
/* set the PIOs in input*/
/* This disables the UART output, so dont execute for now*/
#ifndef DEBUGOUT
*AT91C_PIOA_ODR = 0xFFFFFFFF; /* Disables all the output pins */
*AT91C_PIOA_PER = 0xFFFFFFFF; /* Enables the PIO to control all the pins */
#endif
AT91F_AIC_DisableIt (AT91C_BASE_AIC, AT91C_ID_SYS);
/* close all peripheral clocks */
#ifndef DEBUGOUT
AT91C_BASE_PMC->PMC_PCDR = 0xFFFFFFFC;
#endif
/* Disable core interrupts and set supervisor mode */
__asm__ ("msr CPSR_c, #0xDF"); //* ARM_MODE_SYS(0x1F) | I_BIT(0x80) | F_BIT(0x40)
/* Clear all the interrupts */
*AT91C_AIC_ICCR = 0xffffffff;
/* read the AIC_IVR and AIC_FVR */
i = *AT91C_AIC_IVR;
i = *AT91C_AIC_FVR;
/* write the end of interrupt control register */
*AT91C_AIC_EOICR = 0;
return 1;
}
static int AT91F_LoadBoot(void)
{
// volatile unsigned int crc1 = 0, crc2 = 0;
volatile unsigned int SizeToDownload = 0x21400;
volatile unsigned int AddressToDownload = AT91C_BOOT_ADDR;
#if 0
/* Read vector 6 to extract size to load */
if (read_dataflash(AT91C_BOOT_DATAFLASH_ADDR, 32,
(char *)AddressToDownload) != AT91C_DATAFLASH_OK)
{
printf("Bad Code Size\n");
return IMAGE_BAD_SIZE;
}
/* calculate the size to download */
SizeToDownload = *(int *)(AddressToDownload + AT91C_OFFSET_VECT6);
#endif
// printf("\nLoad UBOOT from dataflash[%x] to SDRAM[%x]\n",
// AT91C_BOOT_DATAFLASH_ADDR, AT91C_BOOT_ADDR);
if (read_dataflash(AT91C_BOOT_DATAFLASH_ADDR, SizeToDownload + 8,
(char *)AddressToDownload) != AT91C_DATAFLASH_OK)
{
printf("F DF RD\n");
return IMAGE_READ_FAILURE;
}
#if 0
pAT91->CRC32((const unsigned char *)AT91C_BOOT_ADDR,
(unsigned int)SizeToDownload , (unsigned int *)&crc2);
crc1 = (int)(*(char *)(AddressToDownload + SizeToDownload)) +
(int)(*(char *)(AddressToDownload + SizeToDownload + 1) << 8) +
(int)(*(char *)(AddressToDownload + SizeToDownload + 2) << 16) +
(int)(*(char *)(AddressToDownload + SizeToDownload + 3) << 24);
/* Restore the value of Vector 6 */
*(int *)(AddressToDownload + AT91C_OFFSET_VECT6) =
*(int *)(AddressToDownload + SizeToDownload + 4);
if (crc1 != crc2) {
printf("DF CRC bad %x != %x\n",crc1,crc2);
return IMAGE_CRC_ERROR;
}
#endif
return SUCCESS;
}
static int AT91F_StartBoot(void)
{
int sts;
if((sts = AT91F_LoadBoot()) != SUCCESS) return sts;
// printf("\n");
// printf("PLLA[180MHz], MCK[60Mhz] ==> Start UBOOT\n");
if (AT91F_ResetRegisters())
{
printf("Jump");
Jump(AT91C_BOOT_ADDR);
// LED_blink(0);
}
return IMAGE_ERROR;
}
#if 0
static void AT91F_RepeatedStartBoot(void)
{
int i;
for(i = 0; i < CRC_RETRIES; i++) {
if(AT91F_StartBoot() != IMAGE_CRC_ERROR){
// LED_blink(1);
return;
}
}
return;
}
#endif
#define TRUE 1
#define FALSE 0
#define TRX_MAGIC 0x30524448 /* "HDR0" */
#define TRX_VERSION 1
struct trx_header {
unsigned int magic;
unsigned int len;
unsigned int crc32;
unsigned int flag_version;
unsigned int offsets[3];
};
#define AT91C_MCI_TIMEOUT 1000000
extern AT91S_MciDevice MCI_Device;
extern void AT91F_MCIDeviceWaitReady(unsigned int);
extern int AT91F_MCI_ReadBlockSwab(AT91PS_MciDevice, int, unsigned int *, int);
int Program_From_MCI(void)
{
int i;
unsigned int Max_Read_DataBlock_Length;
int block = 0;
int buffer = AT91C_DOWNLOAD_BASE_ADDRESS;
int bufpos = AT91C_DOWNLOAD_BASE_ADDRESS;
int NbPage = 0;
struct trx_header *p;
p = (struct trx_header *)bufpos;
Max_Read_DataBlock_Length = MCI_Device.pMCI_DeviceFeatures->Max_Read_DataBlock_Length;
AT91F_MCIDeviceWaitReady(AT91C_MCI_TIMEOUT);
AT91F_MCI_ReadBlockSwab(&MCI_Device, block*Max_Read_DataBlock_Length, (unsigned int *)bufpos, Max_Read_DataBlock_Length);
if (p->magic != TRX_MAGIC) {
printf("Inv IMG 0x%08x\n", p->magic);
return FALSE;
}
printf("RDSD");
AT91C_BASE_PIOC->PIO_CODR = AT91C_PIO_PC7 | AT91C_PIO_PC15 | AT91C_PIO_PC8 | AT91C_PIO_PC14;
for (i=0; i<(p->len/512); i++) {
AT91F_MCI_ReadBlockSwab(&MCI_Device, block*Max_Read_DataBlock_Length, (unsigned int *)bufpos, Max_Read_DataBlock_Length);
block++;
bufpos += Max_Read_DataBlock_Length;
}
NbPage = 0;
i = dataflash_info[0].Device.pages_number;
while(i >>= 1)
NbPage++;
i = ((p->offsets[1] - p->offsets[0])/ 512) + 1 + (NbPage << 13) + (dataflash_info[0].Device.pages_size << 17);
*(int *)(buffer + p->offsets[0] + AT91C_OFFSET_VECT6) = i;
printf(" WDFB");
AT91C_BASE_PIOC->PIO_CODR = AT91C_PIO_PC7 | AT91C_PIO_PC15 | AT91C_PIO_PC14;
AT91C_BASE_PIOC->PIO_SODR = AT91C_PIO_PC8;
write_dataflash(0xc0000000, buffer + p->offsets[0], p->offsets[1] - p->offsets[0]);
printf(" WUB");
AT91C_BASE_PIOC->PIO_CODR = AT91C_PIO_PC7 | AT91C_PIO_PC15;
AT91C_BASE_PIOC->PIO_SODR = AT91C_PIO_PC8 | AT91C_PIO_PC14;
write_dataflash(0xc0008000, buffer + p->offsets[1], p->offsets[2] - p->offsets[1]);
printf(" WKRFS");
AT91C_BASE_PIOC->PIO_CODR = AT91C_PIO_PC8 | AT91C_PIO_PC15;
AT91C_BASE_PIOC->PIO_SODR = AT91C_PIO_PC7 | AT91C_PIO_PC14;
write_dataflash(0xc0042000, buffer + p->offsets[2], p->len - p->offsets[2]);
AT91C_BASE_PIOC->PIO_CODR = AT91C_PIO_PC8 | AT91C_PIO_PC14;
AT91C_BASE_PIOC->PIO_SODR = AT91C_PIO_PC7 | AT91C_PIO_PC15;
return TRUE;
}
//*----------------------------------------------------------------------------
//* Function Name : main
//* Object : Main function
//* Input Parameters : none
//* Output Parameters : True
//*----------------------------------------------------------------------------
int main(void)
{
#ifdef XMODEM
AT91PS_Buffer pXmBuffer;
AT91PS_SvcComm pSvcXmodem;
#endif
AT91S_SvcTempo svcBootTempo; // Link to a AT91S_Tempo object
unsigned int ix;
volatile unsigned int AddressToDownload, SizeToDownload;
unsigned int DeviceAddress = 0;
char command = 0;
#ifdef XMODEM
volatile int i = 0;
unsigned int crc1 = 0, crc2 = 0;
volatile int device;
int NbPage;
#endif
volatile int Nb_Device = 0;
int mci_present = 0;
pAT91 = AT91C_ROM_BOOT_ADDRESS;
if (!AT91F_SetPLL())
{
printf("F SetPLL");
while(1);
}
at91_init_uarts();
/* Tempo Initialisation */
pAT91->OpenCtlTempo(&ctlTempo, (void *) &(pAT91->SYSTIMER_DESC));
ctlTempo.CtlTempoStart((void *) &(pAT91->SYSTIMER_DESC));
// Attach the tempo to a tempo controler
ctlTempo.CtlTempoCreate(&ctlTempo, &svcBootTempo);
// LED_init();
// LED_blink(2);
#ifdef XMODEM
/* Xmodem Initialisation */
pXmBuffer = pAT91->OpenSBuffer(&sXmBuffer);
pSvcXmodem = pAT91->OpenSvcXmodem(&svcXmodem,
(AT91PS_USART)AT91C_BASE_DBGU, &ctlTempo);
pAT91->OpenPipe(&xmodemPipe, pSvcXmodem, pXmBuffer);
#endif
/* System Timer initialization */
AT91F_AIC_ConfigureIt(
AT91C_BASE_AIC, // AIC base address
AT91C_ID_SYS, // System peripheral ID
AT91C_AIC_PRIOR_HIGHEST, // Max priority
AT91C_AIC_SRCTYPE_INT_LEVEL_SENSITIVE, // Level sensitive
AT91F_ST_ASM_HANDLER
);
/* Enable ST interrupt */
AT91F_AIC_EnableIt(AT91C_BASE_AIC, AT91C_ID_SYS);
#ifndef PRODTEST
/* Start tempo to start Boot in a delay of
* AT91C_DELAY_TO_BOOT sec if no key pressed */
svcBootTempo.Start(&svcBootTempo, AT91C_DELAY_TO_BOOT,
0, AT91F_StartBoot, NULL);
#endif
while(1)
{
while(command == 0)
{
AddressToDownload = AT91C_DOWNLOAD_BASE_ADDRESS;
SizeToDownload = AT91C_DOWNLOAD_MAX_SIZE;
DeviceAddress = 0;
/* try to detect Dataflash */
if (!Nb_Device)
Nb_Device = AT91F_DataflashInit();
mci_present = AT91F_DisplayMenu();
#ifdef PRODTEST
if (mci_present) {
if (Program_From_MCI())
AT91F_StartBoot();
}
#endif
message[0] = 0;
AT91F_ReadLine ("Enter: ", message);
#ifndef PRODTEST
/* stop tempo ==> stop autoboot */
svcBootTempo.Stop(&svcBootTempo);
#endif
command = message[0];
for(ix = 1; (message[ix] == ' ') && (ix < 12); ix++); // Skip some whitespace
if(!AsciiToHex(&message[ix], &DeviceAddress) )
DeviceAddress = 0; // Illegal DeviceAddress
switch(command)
{
#ifdef XMODEM
case '1':
case '2':
case '5':
if(command == '1') {
DeviceAddress = 0xC0000000;
// printf("Download DataflashBoot.bin to [0x%x]\n", DeviceAddress);
} else if(command == '2') {
DeviceAddress = AT91C_BOOT_DATAFLASH_ADDR;
// printf("Download u-boot.bin to [0x%x]\n", DeviceAddress);
} else {
// printf("Download Dataflash to [0x%x]\n", DeviceAddress);
}
switch(DeviceAddress & 0xFF000000)
{
case CFG_DATAFLASH_LOGIC_ADDR_CS0:
if (dataflash_info[0].id == 0){
printf("No DF");
AT91F_WaitKeyPressed();
command = 0;
}
device = 0;
break;
case CFG_DATAFLASH_LOGIC_ADDR_CS3:
if (dataflash_info[1].id == 0){
printf("No DF");
AT91F_WaitKeyPressed();
command = 0;
}
device = 1;
break;
default:
command = 0;
break;
}
break;
#endif
case '3':
if (mci_present)
Program_From_MCI();
command = 0;
break;
case '4':
AT91F_StartBoot();
command = 0;
break;
#ifdef MEMDISP
case '6':
do
{
AT91F_MemoryDisplay(DeviceAddress, 256);
AT91F_ReadLine (NULL, message);
DeviceAddress += 0x100;
}
while(message[0] == '\0');
command = 0;
break;
#endif
case '7':
switch(DeviceAddress & 0xFF000000)
{
case CFG_DATAFLASH_LOGIC_ADDR_CS0:
break;
case CFG_DATAFLASH_LOGIC_ADDR_CS3:
break;
default:
command = 0;
break;
}
if (command != 0) {
AT91F_ReadLine ("RDY ERA\nSure?",
message);
if(message[0] == 'Y' || message[0] == 'y') {
erase_dataflash(DeviceAddress & 0xFF000000);
// printf("Erase complete\n\n");
}
// else
// printf("Erase aborted\n");
}
command = 0;
break;
default:
command = 0;
break;
}
}
#ifdef XMODEM
for(i = 0; i <= AT91C_DOWNLOAD_MAX_SIZE; i++)
*(unsigned char *)(AddressToDownload + i) = 0;
xmodemPipe.Read(&xmodemPipe, (char *)AddressToDownload,
SizeToDownload, XmodemProtocol, 0);
while(XmodemComplete !=1);
SizeToDownload = (unsigned int)((svcXmodem.pData) -
(unsigned int)AddressToDownload);
/* Modification of vector 6 */
if ((DeviceAddress == CFG_DATAFLASH_LOGIC_ADDR_CS0)) {
// Vector 6 must be compliant to the BootRom description (ref Datasheet)
NbPage = 0;
i = dataflash_info[device].Device.pages_number;
while(i >>= 1)
NbPage++;
i = (SizeToDownload / 512)+1 + (NbPage << 13) +
(dataflash_info[device].Device.pages_size << 17); //+4 to add crc32
SizeToDownload = 512 * (i &0xFF);
}
else
{
/* Save the contents of vector 6 ==> will be restored
* at boot time (AT91F_StartBoot) */
*(int *)(AddressToDownload + SizeToDownload + 4) =
*(int *)(AddressToDownload + AT91C_OFFSET_VECT6);
/* Modify Vector 6 to contain the size of the
* file to copy (Dataflash -> SDRAM)*/
i = SizeToDownload;
}
*(int *)(AddressToDownload + AT91C_OFFSET_VECT6) = i;
// printf("\nModification of Arm Vector 6 :%x\n", i);
// printf("\nWrite %d bytes in DataFlash [0x%x]\n",SizeToDownload, DeviceAddress);
crc1 = 0;
pAT91->CRC32((const unsigned char *)AddressToDownload, SizeToDownload , &crc1);
/* Add the crc32 at the end of the code */
*(char *)(AddressToDownload + SizeToDownload) = (char)(crc1 & 0x000000FF);
*(char *)(AddressToDownload + SizeToDownload + 1) = (char)((crc1 & 0x0000FF00) >> 8);
*(char *)(AddressToDownload + SizeToDownload + 2) = (char)((crc1 & 0x00FF0000) >> 16);
*(char *)(AddressToDownload + SizeToDownload + 3) = (char)((crc1 & 0xFF000000) >> 24);
/* write dataflash */
write_dataflash (DeviceAddress, AddressToDownload, (SizeToDownload + 8));
/* clear the buffer before read */
for(i=0; i <= SizeToDownload; i++)
*(unsigned char *)(AddressToDownload + i) = 0;
/* Read dataflash to check the validity of the data */
read_dataflash (DeviceAddress, (SizeToDownload + 4), (char *)(AddressToDownload));
printf("VFY: ");
crc2 = 0;
pAT91->CRC32((const unsigned char *)AddressToDownload, SizeToDownload , &crc2);
crc1 = (int)(*(char *)(AddressToDownload + SizeToDownload)) +
(int)(*(char *)(AddressToDownload + SizeToDownload + 1) << 8) +
(int)(*(char *)(AddressToDownload + SizeToDownload + 2) << 16) +
(int)(*(char *)(AddressToDownload + SizeToDownload + 3) << 24);
if (crc1 != crc2)
printf("ERR");
else
printf("OK");
command = 0;
XmodemComplete = 0;
AT91F_WaitKeyPressed();
#endif
}
}
| gpl-2.0 |
ArmyOfPirates/openwrt | target/linux/at91/image/dfboot/src/init.c | 721 | 5014 | //*----------------------------------------------------------------------------
//* ATMEL Microcontroller Software Support - ROUSSET -
//*----------------------------------------------------------------------------
//* The software is delivered "AS IS" without warranty or condition of any
//* kind, either express, implied or statutory. This includes without
//* limitation any warranty or condition with respect to merchantability or
//* fitness for any particular purpose, or against the infringements of
//* intellectual property rights of others.
//*----------------------------------------------------------------------------
//* File Name : init.c
//* Object : Low level initialisations written in C
//* Creation : HIi 10/10/2003
//*
//*----------------------------------------------------------------------------
#include "config.h"
#include "AT91RM9200.h"
#include "lib_AT91RM9200.h"
#include "stdio.h"
//*----------------------------------------------------------------------------
//* \fn AT91F_DataAbort
//* \brief This function reports an Abort
//*----------------------------------------------------------------------------
static void AT91F_SpuriousHandler()
{
puts("ISI");
while (1);
}
//*----------------------------------------------------------------------------
//* \fn AT91F_DataAbort
//* \brief This function reports an Abort
//*----------------------------------------------------------------------------
static void AT91F_DataAbort()
{
puts("IDA");
while (1);
}
//*----------------------------------------------------------------------------
//* \fn AT91F_FetchAbort
//* \brief This function reports an Abort
//*----------------------------------------------------------------------------
static void AT91F_FetchAbort()
{
puts("IFA");
while (1);
}
//*----------------------------------------------------------------------------
//* \fn AT91F_UndefHandler
//* \brief This function reports that no handler have been set for current IT
//*----------------------------------------------------------------------------
static void AT91F_UndefHandler()
{
puts("IUD");
while (1);
}
//*--------------------------------------------------------------------------------------
//* Function Name : AT91F_InitSdram
//* Object : Initialize the SDRAM
//* Input Parameters :
//* Output Parameters :
//*--------------------------------------------------------------------------------------
static void AT91F_InitSdram()
{
int *pRegister;
//* Configure PIOC as peripheral (D16/D31)
AT91F_PIO_CfgPeriph(
AT91C_BASE_PIOC, // PIO controller base address
0xFFFF0030,
0
);
//*Init SDRAM
pRegister = (int *)0xFFFFFF98;
*pRegister = 0x2188c155;
pRegister = (int *)0xFFFFFF90;
*pRegister = 0x2;
pRegister = (int *)0x20000000;
*pRegister = 0;
pRegister = (int *)0xFFFFFF90;
*pRegister = 0x4;
pRegister = (int *)0x20000000;
*pRegister = 0;
*pRegister = 0;
*pRegister = 0;
*pRegister = 0;
*pRegister = 0;
*pRegister = 0;
*pRegister = 0;
*pRegister = 0;
pRegister = (int *)0xFFFFFF90;
*pRegister = 0x3;
pRegister = (int *)0x20000080;
*pRegister = 0;
pRegister = (int *)0xFFFFFF94;
*pRegister = 0x2e0;
pRegister = (int *)0x20000000;
*pRegister = 0;
pRegister = (int *)0xFFFFFF90;
*pRegister = 0x00;
pRegister = (int *)0x20000000;
*pRegister = 0;
}
//*----------------------------------------------------------------------------
//* \fn AT91F_InitFlash
//* \brief This function performs low level HW initialization
//*----------------------------------------------------------------------------
static void AT91F_InitMemories()
{
int *pEbi = (int *)0xFFFFFF60;
//* Setup MEMC to support all connected memories (CS0 = FLASH; CS1=SDRAM)
pEbi = (int *)0xFFFFFF60;
*pEbi = 0x00000002;
//* CS0 cs for flash
pEbi = (int *)0xFFFFFF70;
*pEbi = 0x00003284;
AT91F_InitSdram();
}
//*----------------------------------------------------------------------------
//* \fn AT91F_LowLevelInit
//* \brief This function performs very low level HW initialization
//*----------------------------------------------------------------------------
void AT91F_LowLevelInit(void)
{
int i;
// Init Interrupt Controller
AT91F_AIC_Open(
AT91C_BASE_AIC, // pointer to the AIC registers
AT91C_AIC_BRANCH_OPCODE, // IRQ exception vector
AT91F_UndefHandler, // FIQ exception vector
AT91F_UndefHandler, // AIC default handler
AT91F_SpuriousHandler, // AIC spurious handler
0); // Protect mode
// Perform 8 End Of Interrupt Command to make sýre AIC will not Lock out nIRQ
for(i=0; i<8; i++)
AT91F_AIC_AcknowledgeIt(AT91C_BASE_AIC);
AT91F_AIC_SetExceptionVector((unsigned int *)0x0C, AT91F_FetchAbort);
AT91F_AIC_SetExceptionVector((unsigned int *)0x10, AT91F_DataAbort);
AT91F_AIC_SetExceptionVector((unsigned int *)0x4, AT91F_UndefHandler);
//Initialize SDRAM and Flash
AT91F_InitMemories();
}
| gpl-2.0 |
CandyDevices/kernel_mediatek_sprout | drivers/gpu/drm/vmwgfx/vmwgfx_fb.c | 1489 | 15891 | /**************************************************************************
*
* Copyright © 2007 David Airlie
* Copyright © 2009 VMware, Inc., Palo Alto, CA., USA
* 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.
*
**************************************************************************/
#include <linux/export.h>
#include <drm/drmP.h>
#include "vmwgfx_drv.h"
#include <drm/ttm/ttm_placement.h>
#define VMW_DIRTY_DELAY (HZ / 30)
struct vmw_fb_par {
struct vmw_private *vmw_priv;
void *vmalloc;
struct vmw_dma_buffer *vmw_bo;
struct ttm_bo_kmap_obj map;
u32 pseudo_palette[17];
unsigned depth;
unsigned bpp;
unsigned max_width;
unsigned max_height;
void *bo_ptr;
unsigned bo_size;
bool bo_iowrite;
struct {
spinlock_t lock;
bool active;
unsigned x1;
unsigned y1;
unsigned x2;
unsigned y2;
} dirty;
};
static int vmw_fb_setcolreg(unsigned regno, unsigned red, unsigned green,
unsigned blue, unsigned transp,
struct fb_info *info)
{
struct vmw_fb_par *par = info->par;
u32 *pal = par->pseudo_palette;
if (regno > 15) {
DRM_ERROR("Bad regno %u.\n", regno);
return 1;
}
switch (par->depth) {
case 24:
case 32:
pal[regno] = ((red & 0xff00) << 8) |
(green & 0xff00) |
((blue & 0xff00) >> 8);
break;
default:
DRM_ERROR("Bad depth %u, bpp %u.\n", par->depth, par->bpp);
return 1;
}
return 0;
}
static int vmw_fb_check_var(struct fb_var_screeninfo *var,
struct fb_info *info)
{
int depth = var->bits_per_pixel;
struct vmw_fb_par *par = info->par;
struct vmw_private *vmw_priv = par->vmw_priv;
switch (var->bits_per_pixel) {
case 32:
depth = (var->transp.length > 0) ? 32 : 24;
break;
default:
DRM_ERROR("Bad bpp %u.\n", var->bits_per_pixel);
return -EINVAL;
}
switch (depth) {
case 24:
var->red.offset = 16;
var->green.offset = 8;
var->blue.offset = 0;
var->red.length = 8;
var->green.length = 8;
var->blue.length = 8;
var->transp.length = 0;
var->transp.offset = 0;
break;
case 32:
var->red.offset = 16;
var->green.offset = 8;
var->blue.offset = 0;
var->red.length = 8;
var->green.length = 8;
var->blue.length = 8;
var->transp.length = 8;
var->transp.offset = 24;
break;
default:
DRM_ERROR("Bad depth %u.\n", depth);
return -EINVAL;
}
if (!(vmw_priv->capabilities & SVGA_CAP_DISPLAY_TOPOLOGY) &&
(var->xoffset != 0 || var->yoffset != 0)) {
DRM_ERROR("Can not handle panning without display topology\n");
return -EINVAL;
}
if ((var->xoffset + var->xres) > par->max_width ||
(var->yoffset + var->yres) > par->max_height) {
DRM_ERROR("Requested geom can not fit in framebuffer\n");
return -EINVAL;
}
if (!vmw_kms_validate_mode_vram(vmw_priv,
var->xres * var->bits_per_pixel/8,
var->yoffset + var->yres)) {
DRM_ERROR("Requested geom can not fit in framebuffer\n");
return -EINVAL;
}
return 0;
}
static int vmw_fb_set_par(struct fb_info *info)
{
struct vmw_fb_par *par = info->par;
struct vmw_private *vmw_priv = par->vmw_priv;
int ret;
info->fix.line_length = info->var.xres * info->var.bits_per_pixel/8;
ret = vmw_kms_write_svga(vmw_priv, info->var.xres, info->var.yres,
info->fix.line_length,
par->bpp, par->depth);
if (ret)
return ret;
if (vmw_priv->capabilities & SVGA_CAP_DISPLAY_TOPOLOGY) {
/* TODO check if pitch and offset changes */
vmw_write(vmw_priv, SVGA_REG_NUM_GUEST_DISPLAYS, 1);
vmw_write(vmw_priv, SVGA_REG_DISPLAY_ID, 0);
vmw_write(vmw_priv, SVGA_REG_DISPLAY_IS_PRIMARY, true);
vmw_write(vmw_priv, SVGA_REG_DISPLAY_POSITION_X, info->var.xoffset);
vmw_write(vmw_priv, SVGA_REG_DISPLAY_POSITION_Y, info->var.yoffset);
vmw_write(vmw_priv, SVGA_REG_DISPLAY_WIDTH, info->var.xres);
vmw_write(vmw_priv, SVGA_REG_DISPLAY_HEIGHT, info->var.yres);
vmw_write(vmw_priv, SVGA_REG_DISPLAY_ID, SVGA_ID_INVALID);
}
/* This is really helpful since if this fails the user
* can probably not see anything on the screen.
*/
WARN_ON(vmw_read(vmw_priv, SVGA_REG_FB_OFFSET) != 0);
return 0;
}
static int vmw_fb_pan_display(struct fb_var_screeninfo *var,
struct fb_info *info)
{
return 0;
}
static int vmw_fb_blank(int blank, struct fb_info *info)
{
return 0;
}
/*
* Dirty code
*/
static void vmw_fb_dirty_flush(struct vmw_fb_par *par)
{
struct vmw_private *vmw_priv = par->vmw_priv;
struct fb_info *info = vmw_priv->fb_info;
int stride = (info->fix.line_length / 4);
int *src = (int *)info->screen_base;
__le32 __iomem *vram_mem = par->bo_ptr;
unsigned long flags;
unsigned x, y, w, h;
int i, k;
struct {
uint32_t header;
SVGAFifoCmdUpdate body;
} *cmd;
if (vmw_priv->suspended)
return;
spin_lock_irqsave(&par->dirty.lock, flags);
if (!par->dirty.active) {
spin_unlock_irqrestore(&par->dirty.lock, flags);
return;
}
x = par->dirty.x1;
y = par->dirty.y1;
w = min(par->dirty.x2, info->var.xres) - x;
h = min(par->dirty.y2, info->var.yres) - y;
par->dirty.x1 = par->dirty.x2 = 0;
par->dirty.y1 = par->dirty.y2 = 0;
spin_unlock_irqrestore(&par->dirty.lock, flags);
for (i = y * stride; i < info->fix.smem_len / 4; i += stride) {
for (k = i+x; k < i+x+w && k < info->fix.smem_len / 4; k++)
iowrite32(src[k], vram_mem + k);
}
#if 0
DRM_INFO("%s, (%u, %u) (%ux%u)\n", __func__, x, y, w, h);
#endif
cmd = vmw_fifo_reserve(vmw_priv, sizeof(*cmd));
if (unlikely(cmd == NULL)) {
DRM_ERROR("Fifo reserve failed.\n");
return;
}
cmd->header = cpu_to_le32(SVGA_CMD_UPDATE);
cmd->body.x = cpu_to_le32(x);
cmd->body.y = cpu_to_le32(y);
cmd->body.width = cpu_to_le32(w);
cmd->body.height = cpu_to_le32(h);
vmw_fifo_commit(vmw_priv, sizeof(*cmd));
}
static void vmw_fb_dirty_mark(struct vmw_fb_par *par,
unsigned x1, unsigned y1,
unsigned width, unsigned height)
{
struct fb_info *info = par->vmw_priv->fb_info;
unsigned long flags;
unsigned x2 = x1 + width;
unsigned y2 = y1 + height;
spin_lock_irqsave(&par->dirty.lock, flags);
if (par->dirty.x1 == par->dirty.x2) {
par->dirty.x1 = x1;
par->dirty.y1 = y1;
par->dirty.x2 = x2;
par->dirty.y2 = y2;
/* if we are active start the dirty work
* we share the work with the defio system */
if (par->dirty.active)
schedule_delayed_work(&info->deferred_work, VMW_DIRTY_DELAY);
} else {
if (x1 < par->dirty.x1)
par->dirty.x1 = x1;
if (y1 < par->dirty.y1)
par->dirty.y1 = y1;
if (x2 > par->dirty.x2)
par->dirty.x2 = x2;
if (y2 > par->dirty.y2)
par->dirty.y2 = y2;
}
spin_unlock_irqrestore(&par->dirty.lock, flags);
}
static void vmw_deferred_io(struct fb_info *info,
struct list_head *pagelist)
{
struct vmw_fb_par *par = info->par;
unsigned long start, end, min, max;
unsigned long flags;
struct page *page;
int y1, y2;
min = ULONG_MAX;
max = 0;
list_for_each_entry(page, pagelist, lru) {
start = page->index << PAGE_SHIFT;
end = start + PAGE_SIZE - 1;
min = min(min, start);
max = max(max, end);
}
if (min < max) {
y1 = min / info->fix.line_length;
y2 = (max / info->fix.line_length) + 1;
spin_lock_irqsave(&par->dirty.lock, flags);
par->dirty.x1 = 0;
par->dirty.y1 = y1;
par->dirty.x2 = info->var.xres;
par->dirty.y2 = y2;
spin_unlock_irqrestore(&par->dirty.lock, flags);
}
vmw_fb_dirty_flush(par);
};
struct fb_deferred_io vmw_defio = {
.delay = VMW_DIRTY_DELAY,
.deferred_io = vmw_deferred_io,
};
/*
* Draw code
*/
static void vmw_fb_fillrect(struct fb_info *info, const struct fb_fillrect *rect)
{
cfb_fillrect(info, rect);
vmw_fb_dirty_mark(info->par, rect->dx, rect->dy,
rect->width, rect->height);
}
static void vmw_fb_copyarea(struct fb_info *info, const struct fb_copyarea *region)
{
cfb_copyarea(info, region);
vmw_fb_dirty_mark(info->par, region->dx, region->dy,
region->width, region->height);
}
static void vmw_fb_imageblit(struct fb_info *info, const struct fb_image *image)
{
cfb_imageblit(info, image);
vmw_fb_dirty_mark(info->par, image->dx, image->dy,
image->width, image->height);
}
/*
* Bring up code
*/
static struct fb_ops vmw_fb_ops = {
.owner = THIS_MODULE,
.fb_check_var = vmw_fb_check_var,
.fb_set_par = vmw_fb_set_par,
.fb_setcolreg = vmw_fb_setcolreg,
.fb_fillrect = vmw_fb_fillrect,
.fb_copyarea = vmw_fb_copyarea,
.fb_imageblit = vmw_fb_imageblit,
.fb_pan_display = vmw_fb_pan_display,
.fb_blank = vmw_fb_blank,
};
static int vmw_fb_create_bo(struct vmw_private *vmw_priv,
size_t size, struct vmw_dma_buffer **out)
{
struct vmw_dma_buffer *vmw_bo;
struct ttm_placement ne_placement = vmw_vram_ne_placement;
int ret;
ne_placement.lpfn = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
/* interuptable? */
ret = ttm_write_lock(&vmw_priv->fbdev_master.lock, false);
if (unlikely(ret != 0))
return ret;
vmw_bo = kmalloc(sizeof(*vmw_bo), GFP_KERNEL);
if (!vmw_bo)
goto err_unlock;
ret = vmw_dmabuf_init(vmw_priv, vmw_bo, size,
&ne_placement,
false,
&vmw_dmabuf_bo_free);
if (unlikely(ret != 0))
goto err_unlock; /* init frees the buffer on failure */
*out = vmw_bo;
ttm_write_unlock(&vmw_priv->fbdev_master.lock);
return 0;
err_unlock:
ttm_write_unlock(&vmw_priv->fbdev_master.lock);
return ret;
}
int vmw_fb_init(struct vmw_private *vmw_priv)
{
struct device *device = &vmw_priv->dev->pdev->dev;
struct vmw_fb_par *par;
struct fb_info *info;
unsigned initial_width, initial_height;
unsigned fb_width, fb_height;
unsigned fb_bpp, fb_depth, fb_offset, fb_pitch, fb_size;
int ret;
fb_bpp = 32;
fb_depth = 24;
/* XXX As shouldn't these be as well. */
fb_width = min(vmw_priv->fb_max_width, (unsigned)2048);
fb_height = min(vmw_priv->fb_max_height, (unsigned)2048);
initial_width = min(vmw_priv->initial_width, fb_width);
initial_height = min(vmw_priv->initial_height, fb_height);
fb_pitch = fb_width * fb_bpp / 8;
fb_size = fb_pitch * fb_height;
fb_offset = vmw_read(vmw_priv, SVGA_REG_FB_OFFSET);
info = framebuffer_alloc(sizeof(*par), device);
if (!info)
return -ENOMEM;
/*
* Par
*/
vmw_priv->fb_info = info;
par = info->par;
par->vmw_priv = vmw_priv;
par->depth = fb_depth;
par->bpp = fb_bpp;
par->vmalloc = NULL;
par->max_width = fb_width;
par->max_height = fb_height;
/*
* Create buffers and alloc memory
*/
par->vmalloc = vmalloc(fb_size);
if (unlikely(par->vmalloc == NULL)) {
ret = -ENOMEM;
goto err_free;
}
ret = vmw_fb_create_bo(vmw_priv, fb_size, &par->vmw_bo);
if (unlikely(ret != 0))
goto err_free;
ret = ttm_bo_kmap(&par->vmw_bo->base,
0,
par->vmw_bo->base.num_pages,
&par->map);
if (unlikely(ret != 0))
goto err_unref;
par->bo_ptr = ttm_kmap_obj_virtual(&par->map, &par->bo_iowrite);
par->bo_size = fb_size;
/*
* Fixed and var
*/
strcpy(info->fix.id, "svgadrmfb");
info->fix.type = FB_TYPE_PACKED_PIXELS;
info->fix.visual = FB_VISUAL_TRUECOLOR;
info->fix.type_aux = 0;
info->fix.xpanstep = 1; /* doing it in hw */
info->fix.ypanstep = 1; /* doing it in hw */
info->fix.ywrapstep = 0;
info->fix.accel = FB_ACCEL_NONE;
info->fix.line_length = fb_pitch;
info->fix.smem_start = 0;
info->fix.smem_len = fb_size;
info->pseudo_palette = par->pseudo_palette;
info->screen_base = par->vmalloc;
info->screen_size = fb_size;
info->flags = FBINFO_DEFAULT;
info->fbops = &vmw_fb_ops;
/* 24 depth per default */
info->var.red.offset = 16;
info->var.green.offset = 8;
info->var.blue.offset = 0;
info->var.red.length = 8;
info->var.green.length = 8;
info->var.blue.length = 8;
info->var.transp.offset = 0;
info->var.transp.length = 0;
info->var.xres_virtual = fb_width;
info->var.yres_virtual = fb_height;
info->var.bits_per_pixel = par->bpp;
info->var.xoffset = 0;
info->var.yoffset = 0;
info->var.activate = FB_ACTIVATE_NOW;
info->var.height = -1;
info->var.width = -1;
info->var.xres = initial_width;
info->var.yres = initial_height;
/* Use default scratch pixmap (info->pixmap.flags = FB_PIXMAP_SYSTEM) */
info->apertures = alloc_apertures(1);
if (!info->apertures) {
ret = -ENOMEM;
goto err_aper;
}
info->apertures->ranges[0].base = vmw_priv->vram_start;
info->apertures->ranges[0].size = vmw_priv->vram_size;
/*
* Dirty & Deferred IO
*/
par->dirty.x1 = par->dirty.x2 = 0;
par->dirty.y1 = par->dirty.y2 = 0;
par->dirty.active = true;
spin_lock_init(&par->dirty.lock);
info->fbdefio = &vmw_defio;
fb_deferred_io_init(info);
ret = register_framebuffer(info);
if (unlikely(ret != 0))
goto err_defio;
return 0;
err_defio:
fb_deferred_io_cleanup(info);
err_aper:
ttm_bo_kunmap(&par->map);
err_unref:
ttm_bo_unref((struct ttm_buffer_object **)&par->vmw_bo);
err_free:
vfree(par->vmalloc);
framebuffer_release(info);
vmw_priv->fb_info = NULL;
return ret;
}
int vmw_fb_close(struct vmw_private *vmw_priv)
{
struct fb_info *info;
struct vmw_fb_par *par;
struct ttm_buffer_object *bo;
if (!vmw_priv->fb_info)
return 0;
info = vmw_priv->fb_info;
par = info->par;
bo = &par->vmw_bo->base;
par->vmw_bo = NULL;
/* ??? order */
fb_deferred_io_cleanup(info);
unregister_framebuffer(info);
ttm_bo_kunmap(&par->map);
ttm_bo_unref(&bo);
vfree(par->vmalloc);
framebuffer_release(info);
return 0;
}
int vmw_fb_off(struct vmw_private *vmw_priv)
{
struct fb_info *info;
struct vmw_fb_par *par;
unsigned long flags;
if (!vmw_priv->fb_info)
return -EINVAL;
info = vmw_priv->fb_info;
par = info->par;
spin_lock_irqsave(&par->dirty.lock, flags);
par->dirty.active = false;
spin_unlock_irqrestore(&par->dirty.lock, flags);
flush_delayed_work(&info->deferred_work);
par->bo_ptr = NULL;
ttm_bo_kunmap(&par->map);
vmw_dmabuf_unpin(vmw_priv, par->vmw_bo, false);
return 0;
}
int vmw_fb_on(struct vmw_private *vmw_priv)
{
struct fb_info *info;
struct vmw_fb_par *par;
unsigned long flags;
bool dummy;
int ret;
if (!vmw_priv->fb_info)
return -EINVAL;
info = vmw_priv->fb_info;
par = info->par;
/* we are already active */
if (par->bo_ptr != NULL)
return 0;
/* Make sure that all overlays are stoped when we take over */
vmw_overlay_stop_all(vmw_priv);
ret = vmw_dmabuf_to_start_of_vram(vmw_priv, par->vmw_bo, true, false);
if (unlikely(ret != 0)) {
DRM_ERROR("could not move buffer to start of VRAM\n");
goto err_no_buffer;
}
ret = ttm_bo_kmap(&par->vmw_bo->base,
0,
par->vmw_bo->base.num_pages,
&par->map);
BUG_ON(ret != 0);
par->bo_ptr = ttm_kmap_obj_virtual(&par->map, &dummy);
spin_lock_irqsave(&par->dirty.lock, flags);
par->dirty.active = true;
spin_unlock_irqrestore(&par->dirty.lock, flags);
err_no_buffer:
vmw_fb_set_par(info);
vmw_fb_dirty_mark(par, 0, 0, info->var.xres, info->var.yres);
/* If there already was stuff dirty we wont
* schedule a new work, so lets do it now */
schedule_delayed_work(&info->deferred_work, 0);
return 0;
}
| gpl-2.0 |
yajnab/android_kernel_samsung_msm7x27 | drivers/mtd/maps/edb7312.c | 2001 | 3301 | /*
* Handle mapping of the NOR flash on Cogent EDB7312 boards
*
* Copyright 2002 SYSGO Real-Time Solutions GmbH
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <asm/io.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
#ifdef CONFIG_MTD_PARTITIONS
#include <linux/mtd/partitions.h>
#endif
#define WINDOW_ADDR 0x00000000 /* physical properties of flash */
#define WINDOW_SIZE 0x01000000
#define BUSWIDTH 2
#define FLASH_BLOCKSIZE_MAIN 0x20000
#define FLASH_NUMBLOCKS_MAIN 128
/* can be "cfi_probe", "jedec_probe", "map_rom", NULL }; */
#define PROBETYPES { "cfi_probe", NULL }
#define MSG_PREFIX "EDB7312-NOR:" /* prefix for our printk()'s */
#define MTDID "edb7312-nor" /* for mtdparts= partitioning */
static struct mtd_info *mymtd;
struct map_info edb7312nor_map = {
.name = "NOR flash on EDB7312",
.size = WINDOW_SIZE,
.bankwidth = BUSWIDTH,
.phys = WINDOW_ADDR,
};
#ifdef CONFIG_MTD_PARTITIONS
/*
* MTD partitioning stuff
*/
static struct mtd_partition static_partitions[3] =
{
{
.name = "ARMboot",
.size = 0x40000,
.offset = 0
},
{
.name = "Kernel",
.size = 0x200000,
.offset = 0x40000
},
{
.name = "RootFS",
.size = 0xDC0000,
.offset = 0x240000
},
};
static const char *probes[] = { "RedBoot", "cmdlinepart", NULL };
#endif
static int mtd_parts_nb = 0;
static struct mtd_partition *mtd_parts = 0;
static int __init init_edb7312nor(void)
{
static const char *rom_probe_types[] = PROBETYPES;
const char **type;
const char *part_type = 0;
printk(KERN_NOTICE MSG_PREFIX "0x%08x at 0x%08x\n",
WINDOW_SIZE, WINDOW_ADDR);
edb7312nor_map.virt = ioremap(WINDOW_ADDR, WINDOW_SIZE);
if (!edb7312nor_map.virt) {
printk(MSG_PREFIX "failed to ioremap\n");
return -EIO;
}
simple_map_init(&edb7312nor_map);
mymtd = 0;
type = rom_probe_types;
for(; !mymtd && *type; type++) {
mymtd = do_map_probe(*type, &edb7312nor_map);
}
if (mymtd) {
mymtd->owner = THIS_MODULE;
#ifdef CONFIG_MTD_PARTITIONS
mtd_parts_nb = parse_mtd_partitions(mymtd, probes, &mtd_parts, MTDID);
if (mtd_parts_nb > 0)
part_type = "detected";
if (mtd_parts_nb == 0)
{
mtd_parts = static_partitions;
mtd_parts_nb = ARRAY_SIZE(static_partitions);
part_type = "static";
}
#endif
add_mtd_device(mymtd);
if (mtd_parts_nb == 0)
printk(KERN_NOTICE MSG_PREFIX "no partition info available\n");
else
{
printk(KERN_NOTICE MSG_PREFIX
"using %s partition definition\n", part_type);
add_mtd_partitions(mymtd, mtd_parts, mtd_parts_nb);
}
return 0;
}
iounmap((void *)edb7312nor_map.virt);
return -ENXIO;
}
static void __exit cleanup_edb7312nor(void)
{
if (mymtd) {
del_mtd_device(mymtd);
map_destroy(mymtd);
}
if (edb7312nor_map.virt) {
iounmap((void *)edb7312nor_map.virt);
edb7312nor_map.virt = 0;
}
}
module_init(init_edb7312nor);
module_exit(cleanup_edb7312nor);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Marius Groeger <mag@sysgo.de>");
MODULE_DESCRIPTION("Generic configurable MTD map driver");
| gpl-2.0 |
loglud/acclaim_kernel | drivers/mtd/maps/nettel.c | 2001 | 11658 | /****************************************************************************/
/*
* nettel.c -- mappings for NETtel/SecureEdge/SnapGear (x86) boards.
*
* (C) Copyright 2000-2001, Greg Ungerer (gerg@snapgear.com)
* (C) Copyright 2001-2002, SnapGear (www.snapgear.com)
*/
/****************************************************************************/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/cfi.h>
#include <linux/reboot.h>
#include <linux/err.h>
#include <linux/kdev_t.h>
#include <linux/root_dev.h>
#include <asm/io.h>
/****************************************************************************/
#define INTEL_BUSWIDTH 1
#define AMD_WINDOW_MAXSIZE 0x00200000
#define AMD_BUSWIDTH 1
/*
* PAR masks and shifts, assuming 64K pages.
*/
#define SC520_PAR_ADDR_MASK 0x00003fff
#define SC520_PAR_ADDR_SHIFT 16
#define SC520_PAR_TO_ADDR(par) \
(((par)&SC520_PAR_ADDR_MASK) << SC520_PAR_ADDR_SHIFT)
#define SC520_PAR_SIZE_MASK 0x01ffc000
#define SC520_PAR_SIZE_SHIFT 2
#define SC520_PAR_TO_SIZE(par) \
((((par)&SC520_PAR_SIZE_MASK) << SC520_PAR_SIZE_SHIFT) + (64*1024))
#define SC520_PAR(cs, addr, size) \
((cs) | \
((((size)-(64*1024)) >> SC520_PAR_SIZE_SHIFT) & SC520_PAR_SIZE_MASK) | \
(((addr) >> SC520_PAR_ADDR_SHIFT) & SC520_PAR_ADDR_MASK))
#define SC520_PAR_BOOTCS 0x8a000000
#define SC520_PAR_ROMCS1 0xaa000000
#define SC520_PAR_ROMCS2 0xca000000 /* Cache disabled, 64K page */
static void *nettel_mmcrp = NULL;
#ifdef CONFIG_MTD_CFI_INTELEXT
static struct mtd_info *intel_mtd;
#endif
static struct mtd_info *amd_mtd;
/****************************************************************************/
/****************************************************************************/
#ifdef CONFIG_MTD_CFI_INTELEXT
static struct map_info nettel_intel_map = {
.name = "SnapGear Intel",
.size = 0,
.bankwidth = INTEL_BUSWIDTH,
};
static struct mtd_partition nettel_intel_partitions[] = {
{
.name = "SnapGear kernel",
.offset = 0,
.size = 0x000e0000
},
{
.name = "SnapGear filesystem",
.offset = 0x00100000,
},
{
.name = "SnapGear config",
.offset = 0x000e0000,
.size = 0x00020000
},
{
.name = "SnapGear Intel",
.offset = 0
},
{
.name = "SnapGear BIOS Config",
.offset = 0x007e0000,
.size = 0x00020000
},
{
.name = "SnapGear BIOS",
.offset = 0x007e0000,
.size = 0x00020000
},
};
#endif
static struct map_info nettel_amd_map = {
.name = "SnapGear AMD",
.size = AMD_WINDOW_MAXSIZE,
.bankwidth = AMD_BUSWIDTH,
};
static struct mtd_partition nettel_amd_partitions[] = {
{
.name = "SnapGear BIOS config",
.offset = 0x000e0000,
.size = 0x00010000
},
{
.name = "SnapGear BIOS",
.offset = 0x000f0000,
.size = 0x00010000
},
{
.name = "SnapGear AMD",
.offset = 0
},
{
.name = "SnapGear high BIOS",
.offset = 0x001f0000,
.size = 0x00010000
}
};
#define NUM_AMD_PARTITIONS ARRAY_SIZE(nettel_amd_partitions)
/****************************************************************************/
#ifdef CONFIG_MTD_CFI_INTELEXT
/*
* Set the Intel flash back to read mode since some old boot
* loaders don't.
*/
static int nettel_reboot_notifier(struct notifier_block *nb, unsigned long val, void *v)
{
struct cfi_private *cfi = nettel_intel_map.fldrv_priv;
unsigned long b;
/* Make sure all FLASH chips are put back into read mode */
for (b = 0; (b < nettel_intel_partitions[3].size); b += 0x100000) {
cfi_send_gen_cmd(0xff, 0x55, b, &nettel_intel_map, cfi,
cfi->device_type, NULL);
}
return(NOTIFY_OK);
}
static struct notifier_block nettel_notifier_block = {
nettel_reboot_notifier, NULL, 0
};
#endif
/****************************************************************************/
static int __init nettel_init(void)
{
volatile unsigned long *amdpar;
unsigned long amdaddr, maxsize;
int num_amd_partitions=0;
#ifdef CONFIG_MTD_CFI_INTELEXT
volatile unsigned long *intel0par, *intel1par;
unsigned long orig_bootcspar, orig_romcs1par;
unsigned long intel0addr, intel0size;
unsigned long intel1addr, intel1size;
int intelboot, intel0cs, intel1cs;
int num_intel_partitions;
#endif
int rc = 0;
nettel_mmcrp = (void *) ioremap_nocache(0xfffef000, 4096);
if (nettel_mmcrp == NULL) {
printk("SNAPGEAR: failed to disable MMCR cache??\n");
return(-EIO);
}
/* Set CPU clock to be 33.000MHz */
*((unsigned char *) (nettel_mmcrp + 0xc64)) = 0x01;
amdpar = (volatile unsigned long *) (nettel_mmcrp + 0xc4);
#ifdef CONFIG_MTD_CFI_INTELEXT
intelboot = 0;
intel0cs = SC520_PAR_ROMCS1;
intel0par = (volatile unsigned long *) (nettel_mmcrp + 0xc0);
intel1cs = SC520_PAR_ROMCS2;
intel1par = (volatile unsigned long *) (nettel_mmcrp + 0xbc);
/*
* Save the CS settings then ensure ROMCS1 and ROMCS2 are off,
* otherwise they might clash with where we try to map BOOTCS.
*/
orig_bootcspar = *amdpar;
orig_romcs1par = *intel0par;
*intel0par = 0;
*intel1par = 0;
#endif
/*
* The first thing to do is determine if we have a separate
* boot FLASH device. Typically this is a small (1 to 2MB)
* AMD FLASH part. It seems that device size is about the
* only way to tell if this is the case...
*/
amdaddr = 0x20000000;
maxsize = AMD_WINDOW_MAXSIZE;
*amdpar = SC520_PAR(SC520_PAR_BOOTCS, amdaddr, maxsize);
__asm__ ("wbinvd");
nettel_amd_map.phys = amdaddr;
nettel_amd_map.virt = ioremap_nocache(amdaddr, maxsize);
if (!nettel_amd_map.virt) {
printk("SNAPGEAR: failed to ioremap() BOOTCS\n");
iounmap(nettel_mmcrp);
return(-EIO);
}
simple_map_init(&nettel_amd_map);
if ((amd_mtd = do_map_probe("jedec_probe", &nettel_amd_map))) {
printk(KERN_NOTICE "SNAPGEAR: AMD flash device size = %dK\n",
(int)(amd_mtd->size>>10));
amd_mtd->owner = THIS_MODULE;
/* The high BIOS partition is only present for 2MB units */
num_amd_partitions = NUM_AMD_PARTITIONS;
if (amd_mtd->size < AMD_WINDOW_MAXSIZE)
num_amd_partitions--;
/* Don't add the partition until after the primary INTEL's */
#ifdef CONFIG_MTD_CFI_INTELEXT
/*
* Map the Intel flash into memory after the AMD
* It has to start on a multiple of maxsize.
*/
maxsize = SC520_PAR_TO_SIZE(orig_romcs1par);
if (maxsize < (32 * 1024 * 1024))
maxsize = (32 * 1024 * 1024);
intel0addr = amdaddr + maxsize;
#endif
} else {
#ifdef CONFIG_MTD_CFI_INTELEXT
/* INTEL boot FLASH */
intelboot++;
if (!orig_romcs1par) {
intel0cs = SC520_PAR_BOOTCS;
intel0par = (volatile unsigned long *)
(nettel_mmcrp + 0xc4);
intel1cs = SC520_PAR_ROMCS1;
intel1par = (volatile unsigned long *)
(nettel_mmcrp + 0xc0);
intel0addr = SC520_PAR_TO_ADDR(orig_bootcspar);
maxsize = SC520_PAR_TO_SIZE(orig_bootcspar);
} else {
/* Kernel base is on ROMCS1, not BOOTCS */
intel0cs = SC520_PAR_ROMCS1;
intel0par = (volatile unsigned long *)
(nettel_mmcrp + 0xc0);
intel1cs = SC520_PAR_BOOTCS;
intel1par = (volatile unsigned long *)
(nettel_mmcrp + 0xc4);
intel0addr = SC520_PAR_TO_ADDR(orig_romcs1par);
maxsize = SC520_PAR_TO_SIZE(orig_romcs1par);
}
/* Destroy useless AMD MTD mapping */
amd_mtd = NULL;
iounmap(nettel_amd_map.virt);
nettel_amd_map.virt = NULL;
#else
/* Only AMD flash supported */
rc = -ENXIO;
goto out_unmap2;
#endif
}
#ifdef CONFIG_MTD_CFI_INTELEXT
/*
* We have determined the INTEL FLASH configuration, so lets
* go ahead and probe for them now.
*/
/* Set PAR to the maximum size */
if (maxsize < (32 * 1024 * 1024))
maxsize = (32 * 1024 * 1024);
*intel0par = SC520_PAR(intel0cs, intel0addr, maxsize);
/* Turn other PAR off so the first probe doesn't find it */
*intel1par = 0;
/* Probe for the size of the first Intel flash */
nettel_intel_map.size = maxsize;
nettel_intel_map.phys = intel0addr;
nettel_intel_map.virt = ioremap_nocache(intel0addr, maxsize);
if (!nettel_intel_map.virt) {
printk("SNAPGEAR: failed to ioremap() ROMCS1\n");
rc = -EIO;
goto out_unmap2;
}
simple_map_init(&nettel_intel_map);
intel_mtd = do_map_probe("cfi_probe", &nettel_intel_map);
if (!intel_mtd) {
rc = -ENXIO;
goto out_unmap1;
}
/* Set PAR to the detected size */
intel0size = intel_mtd->size;
*intel0par = SC520_PAR(intel0cs, intel0addr, intel0size);
/*
* Map second Intel FLASH right after first. Set its size to the
* same maxsize used for the first Intel FLASH.
*/
intel1addr = intel0addr + intel0size;
*intel1par = SC520_PAR(intel1cs, intel1addr, maxsize);
__asm__ ("wbinvd");
maxsize += intel0size;
/* Delete the old map and probe again to do both chips */
map_destroy(intel_mtd);
intel_mtd = NULL;
iounmap(nettel_intel_map.virt);
nettel_intel_map.size = maxsize;
nettel_intel_map.virt = ioremap_nocache(intel0addr, maxsize);
if (!nettel_intel_map.virt) {
printk("SNAPGEAR: failed to ioremap() ROMCS1/2\n");
rc = -EIO;
goto out_unmap2;
}
intel_mtd = do_map_probe("cfi_probe", &nettel_intel_map);
if (! intel_mtd) {
rc = -ENXIO;
goto out_unmap1;
}
intel1size = intel_mtd->size - intel0size;
if (intel1size > 0) {
*intel1par = SC520_PAR(intel1cs, intel1addr, intel1size);
__asm__ ("wbinvd");
} else {
*intel1par = 0;
}
printk(KERN_NOTICE "SNAPGEAR: Intel flash device size = %lldKiB\n",
(unsigned long long)(intel_mtd->size >> 10));
intel_mtd->owner = THIS_MODULE;
num_intel_partitions = ARRAY_SIZE(nettel_intel_partitions);
if (intelboot) {
/*
* Adjust offset and size of last boot partition.
* Must allow for BIOS region at end of FLASH.
*/
nettel_intel_partitions[1].size = (intel0size + intel1size) -
(1024*1024 + intel_mtd->erasesize);
nettel_intel_partitions[3].size = intel0size + intel1size;
nettel_intel_partitions[4].offset =
(intel0size + intel1size) - intel_mtd->erasesize;
nettel_intel_partitions[4].size = intel_mtd->erasesize;
nettel_intel_partitions[5].offset =
nettel_intel_partitions[4].offset;
nettel_intel_partitions[5].size =
nettel_intel_partitions[4].size;
} else {
/* No BIOS regions when AMD boot */
num_intel_partitions -= 2;
}
rc = add_mtd_partitions(intel_mtd, nettel_intel_partitions,
num_intel_partitions);
#endif
if (amd_mtd) {
rc = add_mtd_partitions(amd_mtd, nettel_amd_partitions,
num_amd_partitions);
}
#ifdef CONFIG_MTD_CFI_INTELEXT
register_reboot_notifier(&nettel_notifier_block);
#endif
return(rc);
#ifdef CONFIG_MTD_CFI_INTELEXT
out_unmap1:
iounmap(nettel_intel_map.virt);
#endif
out_unmap2:
iounmap(nettel_mmcrp);
iounmap(nettel_amd_map.virt);
return(rc);
}
/****************************************************************************/
static void __exit nettel_cleanup(void)
{
#ifdef CONFIG_MTD_CFI_INTELEXT
unregister_reboot_notifier(&nettel_notifier_block);
#endif
if (amd_mtd) {
del_mtd_partitions(amd_mtd);
map_destroy(amd_mtd);
}
if (nettel_mmcrp) {
iounmap(nettel_mmcrp);
nettel_mmcrp = NULL;
}
if (nettel_amd_map.virt) {
iounmap(nettel_amd_map.virt);
nettel_amd_map.virt = NULL;
}
#ifdef CONFIG_MTD_CFI_INTELEXT
if (intel_mtd) {
del_mtd_partitions(intel_mtd);
map_destroy(intel_mtd);
}
if (nettel_intel_map.virt) {
iounmap(nettel_intel_map.virt);
nettel_intel_map.virt = NULL;
}
#endif
}
/****************************************************************************/
module_init(nettel_init);
module_exit(nettel_cleanup);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Greg Ungerer <gerg@snapgear.com>");
MODULE_DESCRIPTION("SnapGear/SecureEdge FLASH support");
/****************************************************************************/
| gpl-2.0 |
dreikk91/android_kernel_motorola_omap4-common | arch/arm/mach-exynos4/mach-universal_c210.c | 2001 | 15351 | /* linux/arch/arm/mach-exynos4/mach-universal_c210.c
*
* Copyright (c) 2010 Samsung Electronics Co., 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.
*/
#include <linux/platform_device.h>
#include <linux/serial_core.h>
#include <linux/input.h>
#include <linux/i2c.h>
#include <linux/gpio_keys.h>
#include <linux/gpio.h>
#include <linux/mfd/max8998.h>
#include <linux/regulator/machine.h>
#include <linux/regulator/fixed.h>
#include <linux/regulator/max8952.h>
#include <linux/mmc/host.h>
#include <asm/mach/arch.h>
#include <asm/mach-types.h>
#include <plat/regs-serial.h>
#include <plat/exynos4.h>
#include <plat/cpu.h>
#include <plat/devs.h>
#include <plat/iic.h>
#include <plat/sdhci.h>
#include <mach/map.h>
/* Following are default values for UCON, ULCON and UFCON UART registers */
#define UNIVERSAL_UCON_DEFAULT (S3C2410_UCON_TXILEVEL | \
S3C2410_UCON_RXILEVEL | \
S3C2410_UCON_TXIRQMODE | \
S3C2410_UCON_RXIRQMODE | \
S3C2410_UCON_RXFIFO_TOI | \
S3C2443_UCON_RXERR_IRQEN)
#define UNIVERSAL_ULCON_DEFAULT S3C2410_LCON_CS8
#define UNIVERSAL_UFCON_DEFAULT (S3C2410_UFCON_FIFOMODE | \
S5PV210_UFCON_TXTRIG256 | \
S5PV210_UFCON_RXTRIG256)
static struct s3c2410_uartcfg universal_uartcfgs[] __initdata = {
[0] = {
.hwport = 0,
.ucon = UNIVERSAL_UCON_DEFAULT,
.ulcon = UNIVERSAL_ULCON_DEFAULT,
.ufcon = UNIVERSAL_UFCON_DEFAULT,
},
[1] = {
.hwport = 1,
.ucon = UNIVERSAL_UCON_DEFAULT,
.ulcon = UNIVERSAL_ULCON_DEFAULT,
.ufcon = UNIVERSAL_UFCON_DEFAULT,
},
[2] = {
.hwport = 2,
.ucon = UNIVERSAL_UCON_DEFAULT,
.ulcon = UNIVERSAL_ULCON_DEFAULT,
.ufcon = UNIVERSAL_UFCON_DEFAULT,
},
[3] = {
.hwport = 3,
.ucon = UNIVERSAL_UCON_DEFAULT,
.ulcon = UNIVERSAL_ULCON_DEFAULT,
.ufcon = UNIVERSAL_UFCON_DEFAULT,
},
};
static struct regulator_consumer_supply max8952_consumer =
REGULATOR_SUPPLY("vddarm", NULL);
static struct max8952_platform_data universal_max8952_pdata __initdata = {
.gpio_vid0 = EXYNOS4_GPX0(3),
.gpio_vid1 = EXYNOS4_GPX0(4),
.gpio_en = -1, /* Not controllable, set "Always High" */
.default_mode = 0, /* vid0 = 0, vid1 = 0 */
.dvs_mode = { 48, 32, 28, 18 }, /* 1.25, 1.20, 1.05, 0.95V */
.sync_freq = 0, /* default: fastest */
.ramp_speed = 0, /* default: fastest */
.reg_data = {
.constraints = {
.name = "VARM_1.2V",
.min_uV = 770000,
.max_uV = 1400000,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE,
.always_on = 1,
.boot_on = 1,
},
.num_consumer_supplies = 1,
.consumer_supplies = &max8952_consumer,
},
};
static struct regulator_consumer_supply lp3974_buck1_consumer =
REGULATOR_SUPPLY("vddint", NULL);
static struct regulator_consumer_supply lp3974_buck2_consumer =
REGULATOR_SUPPLY("vddg3d", NULL);
static struct regulator_init_data lp3974_buck1_data = {
.constraints = {
.name = "VINT_1.1V",
.min_uV = 750000,
.max_uV = 1500000,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE |
REGULATOR_CHANGE_STATUS,
.boot_on = 1,
.state_mem = {
.disabled = 1,
},
},
.num_consumer_supplies = 1,
.consumer_supplies = &lp3974_buck1_consumer,
};
static struct regulator_init_data lp3974_buck2_data = {
.constraints = {
.name = "VG3D_1.1V",
.min_uV = 750000,
.max_uV = 1500000,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE |
REGULATOR_CHANGE_STATUS,
.boot_on = 1,
.state_mem = {
.disabled = 1,
},
},
.num_consumer_supplies = 1,
.consumer_supplies = &lp3974_buck2_consumer,
};
static struct regulator_init_data lp3974_buck3_data = {
.constraints = {
.name = "VCC_1.8V",
.min_uV = 1800000,
.max_uV = 1800000,
.apply_uV = 1,
.always_on = 1,
.state_mem = {
.enabled = 1,
},
},
};
static struct regulator_init_data lp3974_buck4_data = {
.constraints = {
.name = "VMEM_1.2V",
.min_uV = 1200000,
.max_uV = 1200000,
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
.apply_uV = 1,
.state_mem = {
.disabled = 1,
},
},
};
static struct regulator_init_data lp3974_ldo2_data = {
.constraints = {
.name = "VALIVE_1.2V",
.min_uV = 1200000,
.max_uV = 1200000,
.apply_uV = 1,
.always_on = 1,
.state_mem = {
.enabled = 1,
},
},
};
static struct regulator_init_data lp3974_ldo3_data = {
.constraints = {
.name = "VUSB+MIPI_1.1V",
.min_uV = 1100000,
.max_uV = 1100000,
.apply_uV = 1,
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
.state_mem = {
.disabled = 1,
},
},
};
static struct regulator_init_data lp3974_ldo4_data = {
.constraints = {
.name = "VADC_3.3V",
.min_uV = 3300000,
.max_uV = 3300000,
.apply_uV = 1,
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
.state_mem = {
.disabled = 1,
},
},
};
static struct regulator_init_data lp3974_ldo5_data = {
.constraints = {
.name = "VTF_2.8V",
.min_uV = 2800000,
.max_uV = 2800000,
.apply_uV = 1,
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
.state_mem = {
.disabled = 1,
},
},
};
static struct regulator_init_data lp3974_ldo6_data = {
.constraints = {
.name = "LDO6",
.min_uV = 2000000,
.max_uV = 2000000,
.apply_uV = 1,
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
.state_mem = {
.disabled = 1,
},
},
};
static struct regulator_init_data lp3974_ldo7_data = {
.constraints = {
.name = "VLCD+VMIPI_1.8V",
.min_uV = 1800000,
.max_uV = 1800000,
.apply_uV = 1,
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
.state_mem = {
.disabled = 1,
},
},
};
static struct regulator_init_data lp3974_ldo8_data = {
.constraints = {
.name = "VUSB+VDAC_3.3V",
.min_uV = 3300000,
.max_uV = 3300000,
.apply_uV = 1,
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
.state_mem = {
.disabled = 1,
},
},
};
static struct regulator_init_data lp3974_ldo9_data = {
.constraints = {
.name = "VCC_2.8V",
.min_uV = 2800000,
.max_uV = 2800000,
.apply_uV = 1,
.always_on = 1,
.state_mem = {
.enabled = 1,
},
},
};
static struct regulator_init_data lp3974_ldo10_data = {
.constraints = {
.name = "VPLL_1.1V",
.min_uV = 1100000,
.max_uV = 1100000,
.boot_on = 1,
.apply_uV = 1,
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
.state_mem = {
.disabled = 1,
},
},
};
static struct regulator_init_data lp3974_ldo11_data = {
.constraints = {
.name = "CAM_AF_3.3V",
.min_uV = 3300000,
.max_uV = 3300000,
.apply_uV = 1,
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
.state_mem = {
.disabled = 1,
},
},
};
static struct regulator_init_data lp3974_ldo12_data = {
.constraints = {
.name = "PS_2.8V",
.min_uV = 2800000,
.max_uV = 2800000,
.apply_uV = 1,
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
.state_mem = {
.disabled = 1,
},
},
};
static struct regulator_init_data lp3974_ldo13_data = {
.constraints = {
.name = "VHIC_1.2V",
.min_uV = 1200000,
.max_uV = 1200000,
.apply_uV = 1,
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
.state_mem = {
.disabled = 1,
},
},
};
static struct regulator_init_data lp3974_ldo14_data = {
.constraints = {
.name = "CAM_I_HOST_1.8V",
.min_uV = 1800000,
.max_uV = 1800000,
.apply_uV = 1,
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
.state_mem = {
.disabled = 1,
},
},
};
static struct regulator_init_data lp3974_ldo15_data = {
.constraints = {
.name = "CAM_S_DIG+FM33_CORE_1.2V",
.min_uV = 1200000,
.max_uV = 1200000,
.apply_uV = 1,
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
.state_mem = {
.disabled = 1,
},
},
};
static struct regulator_init_data lp3974_ldo16_data = {
.constraints = {
.name = "CAM_S_ANA_2.8V",
.min_uV = 2800000,
.max_uV = 2800000,
.apply_uV = 1,
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
.state_mem = {
.disabled = 1,
},
},
};
static struct regulator_init_data lp3974_ldo17_data = {
.constraints = {
.name = "VCC_3.0V_LCD",
.min_uV = 3000000,
.max_uV = 3000000,
.apply_uV = 1,
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
.boot_on = 1,
.state_mem = {
.disabled = 1,
},
},
};
static struct regulator_init_data lp3974_32khz_ap_data = {
.constraints = {
.name = "32KHz AP",
.always_on = 1,
.state_mem = {
.enabled = 1,
},
},
};
static struct regulator_init_data lp3974_32khz_cp_data = {
.constraints = {
.name = "32KHz CP",
.state_mem = {
.disabled = 1,
},
},
};
static struct regulator_init_data lp3974_vichg_data = {
.constraints = {
.name = "VICHG",
.state_mem = {
.disabled = 1,
},
},
};
static struct regulator_init_data lp3974_esafeout1_data = {
.constraints = {
.name = "SAFEOUT1",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
.state_mem = {
.enabled = 1,
},
},
};
static struct regulator_init_data lp3974_esafeout2_data = {
.constraints = {
.name = "SAFEOUT2",
.boot_on = 1,
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
.state_mem = {
.enabled = 1,
},
},
};
static struct max8998_regulator_data lp3974_regulators[] = {
{ MAX8998_LDO2, &lp3974_ldo2_data },
{ MAX8998_LDO3, &lp3974_ldo3_data },
{ MAX8998_LDO4, &lp3974_ldo4_data },
{ MAX8998_LDO5, &lp3974_ldo5_data },
{ MAX8998_LDO6, &lp3974_ldo6_data },
{ MAX8998_LDO7, &lp3974_ldo7_data },
{ MAX8998_LDO8, &lp3974_ldo8_data },
{ MAX8998_LDO9, &lp3974_ldo9_data },
{ MAX8998_LDO10, &lp3974_ldo10_data },
{ MAX8998_LDO11, &lp3974_ldo11_data },
{ MAX8998_LDO12, &lp3974_ldo12_data },
{ MAX8998_LDO13, &lp3974_ldo13_data },
{ MAX8998_LDO14, &lp3974_ldo14_data },
{ MAX8998_LDO15, &lp3974_ldo15_data },
{ MAX8998_LDO16, &lp3974_ldo16_data },
{ MAX8998_LDO17, &lp3974_ldo17_data },
{ MAX8998_BUCK1, &lp3974_buck1_data },
{ MAX8998_BUCK2, &lp3974_buck2_data },
{ MAX8998_BUCK3, &lp3974_buck3_data },
{ MAX8998_BUCK4, &lp3974_buck4_data },
{ MAX8998_EN32KHZ_AP, &lp3974_32khz_ap_data },
{ MAX8998_EN32KHZ_CP, &lp3974_32khz_cp_data },
{ MAX8998_ENVICHG, &lp3974_vichg_data },
{ MAX8998_ESAFEOUT1, &lp3974_esafeout1_data },
{ MAX8998_ESAFEOUT2, &lp3974_esafeout2_data },
};
static struct max8998_platform_data universal_lp3974_pdata = {
.num_regulators = ARRAY_SIZE(lp3974_regulators),
.regulators = lp3974_regulators,
.buck1_voltage1 = 1100000, /* INT */
.buck1_voltage2 = 1000000,
.buck1_voltage3 = 1100000,
.buck1_voltage4 = 1000000,
.buck1_set1 = EXYNOS4_GPX0(5),
.buck1_set2 = EXYNOS4_GPX0(6),
.buck2_voltage1 = 1200000, /* G3D */
.buck2_voltage2 = 1100000,
.buck1_default_idx = 0,
.buck2_set3 = EXYNOS4_GPE2(0),
.buck2_default_idx = 0,
.wakeup = true,
};
/* GPIO I2C 5 (PMIC) */
static struct i2c_board_info i2c5_devs[] __initdata = {
{
I2C_BOARD_INFO("max8952", 0xC0 >> 1),
.platform_data = &universal_max8952_pdata,
}, {
I2C_BOARD_INFO("lp3974", 0xCC >> 1),
.platform_data = &universal_lp3974_pdata,
},
};
/* GPIO KEYS */
static struct gpio_keys_button universal_gpio_keys_tables[] = {
{
.code = KEY_VOLUMEUP,
.gpio = EXYNOS4_GPX2(0), /* XEINT16 */
.desc = "gpio-keys: KEY_VOLUMEUP",
.type = EV_KEY,
.active_low = 1,
.debounce_interval = 1,
}, {
.code = KEY_VOLUMEDOWN,
.gpio = EXYNOS4_GPX2(1), /* XEINT17 */
.desc = "gpio-keys: KEY_VOLUMEDOWN",
.type = EV_KEY,
.active_low = 1,
.debounce_interval = 1,
}, {
.code = KEY_CONFIG,
.gpio = EXYNOS4_GPX2(2), /* XEINT18 */
.desc = "gpio-keys: KEY_CONFIG",
.type = EV_KEY,
.active_low = 1,
.debounce_interval = 1,
}, {
.code = KEY_CAMERA,
.gpio = EXYNOS4_GPX2(3), /* XEINT19 */
.desc = "gpio-keys: KEY_CAMERA",
.type = EV_KEY,
.active_low = 1,
.debounce_interval = 1,
}, {
.code = KEY_OK,
.gpio = EXYNOS4_GPX3(5), /* XEINT29 */
.desc = "gpio-keys: KEY_OK",
.type = EV_KEY,
.active_low = 1,
.debounce_interval = 1,
},
};
static struct gpio_keys_platform_data universal_gpio_keys_data = {
.buttons = universal_gpio_keys_tables,
.nbuttons = ARRAY_SIZE(universal_gpio_keys_tables),
};
static struct platform_device universal_gpio_keys = {
.name = "gpio-keys",
.dev = {
.platform_data = &universal_gpio_keys_data,
},
};
/* eMMC */
static struct s3c_sdhci_platdata universal_hsmmc0_data __initdata = {
.max_width = 8,
.host_caps = (MMC_CAP_8_BIT_DATA | MMC_CAP_4_BIT_DATA |
MMC_CAP_MMC_HIGHSPEED | MMC_CAP_SD_HIGHSPEED |
MMC_CAP_DISABLE),
.cd_type = S3C_SDHCI_CD_PERMANENT,
.clk_type = S3C_SDHCI_CLK_DIV_EXTERNAL,
};
static struct regulator_consumer_supply mmc0_supplies[] = {
REGULATOR_SUPPLY("vmmc", "s3c-sdhci.0"),
};
static struct regulator_init_data mmc0_fixed_voltage_init_data = {
.constraints = {
.name = "VMEM_VDD_2.8V",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
.num_consumer_supplies = ARRAY_SIZE(mmc0_supplies),
.consumer_supplies = mmc0_supplies,
};
static struct fixed_voltage_config mmc0_fixed_voltage_config = {
.supply_name = "MASSMEMORY_EN",
.microvolts = 2800000,
.gpio = EXYNOS4_GPE1(3),
.enable_high = true,
.init_data = &mmc0_fixed_voltage_init_data,
};
static struct platform_device mmc0_fixed_voltage = {
.name = "reg-fixed-voltage",
.id = 0,
.dev = {
.platform_data = &mmc0_fixed_voltage_config,
},
};
/* SD */
static struct s3c_sdhci_platdata universal_hsmmc2_data __initdata = {
.max_width = 4,
.host_caps = MMC_CAP_4_BIT_DATA |
MMC_CAP_MMC_HIGHSPEED | MMC_CAP_SD_HIGHSPEED |
MMC_CAP_DISABLE,
.ext_cd_gpio = EXYNOS4_GPX3(4), /* XEINT_28 */
.ext_cd_gpio_invert = 1,
.cd_type = S3C_SDHCI_CD_GPIO,
.clk_type = S3C_SDHCI_CLK_DIV_EXTERNAL,
};
/* WiFi */
static struct s3c_sdhci_platdata universal_hsmmc3_data __initdata = {
.max_width = 4,
.host_caps = MMC_CAP_4_BIT_DATA |
MMC_CAP_MMC_HIGHSPEED | MMC_CAP_SD_HIGHSPEED |
MMC_CAP_DISABLE,
.cd_type = S3C_SDHCI_CD_EXTERNAL,
};
static void __init universal_sdhci_init(void)
{
s3c_sdhci0_set_platdata(&universal_hsmmc0_data);
s3c_sdhci2_set_platdata(&universal_hsmmc2_data);
s3c_sdhci3_set_platdata(&universal_hsmmc3_data);
}
/* I2C0 */
static struct i2c_board_info i2c0_devs[] __initdata = {
/* Camera, To be updated */
};
/* I2C1 */
static struct i2c_board_info i2c1_devs[] __initdata = {
/* Gyro, To be updated */
};
static struct platform_device *universal_devices[] __initdata = {
/* Samsung Platform Devices */
&mmc0_fixed_voltage,
&s3c_device_hsmmc0,
&s3c_device_hsmmc2,
&s3c_device_hsmmc3,
&s3c_device_i2c5,
/* Universal Devices */
&universal_gpio_keys,
&s5p_device_onenand,
};
static void __init universal_map_io(void)
{
s5p_init_io(NULL, 0, S5P_VA_CHIPID);
s3c24xx_init_clocks(24000000);
s3c24xx_init_uarts(universal_uartcfgs, ARRAY_SIZE(universal_uartcfgs));
}
static void __init universal_machine_init(void)
{
universal_sdhci_init();
i2c_register_board_info(0, i2c0_devs, ARRAY_SIZE(i2c0_devs));
i2c_register_board_info(1, i2c1_devs, ARRAY_SIZE(i2c1_devs));
s3c_i2c5_set_platdata(NULL);
i2c_register_board_info(5, i2c5_devs, ARRAY_SIZE(i2c5_devs));
/* Last */
platform_add_devices(universal_devices, ARRAY_SIZE(universal_devices));
}
MACHINE_START(UNIVERSAL_C210, "UNIVERSAL_C210")
/* Maintainer: Kyungmin Park <kyungmin.park@samsung.com> */
.boot_params = S5P_PA_SDRAM + 0x100,
.init_irq = exynos4_init_irq,
.map_io = universal_map_io,
.init_machine = universal_machine_init,
.timer = &exynos4_timer,
MACHINE_END
| gpl-2.0 |
lplachno/mx6-dev | arch/mn10300/mm/pgtable.c | 2257 | 4639 | /* MN10300 Page table management
*
* Copyright (C) 2007 Matsushita Electric Industrial Co., Ltd.
* Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
* Modified by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/gfp.h>
#include <linux/mm.h>
#include <linux/swap.h>
#include <linux/smp.h>
#include <linux/highmem.h>
#include <linux/pagemap.h>
#include <linux/spinlock.h>
#include <linux/quicklist.h>
#include <asm/pgtable.h>
#include <asm/pgalloc.h>
#include <asm/tlb.h>
#include <asm/tlbflush.h>
/*
* Associate a large virtual page frame with a given physical page frame
* and protection flags for that frame. pfn is for the base of the page,
* vaddr is what the page gets mapped to - both must be properly aligned.
* The pmd must already be instantiated. Assumes PAE mode.
*/
void set_pmd_pfn(unsigned long vaddr, unsigned long pfn, pgprot_t flags)
{
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd;
if (vaddr & (PMD_SIZE-1)) { /* vaddr is misaligned */
printk(KERN_ERR "set_pmd_pfn: vaddr misaligned\n");
return; /* BUG(); */
}
if (pfn & (PTRS_PER_PTE-1)) { /* pfn is misaligned */
printk(KERN_ERR "set_pmd_pfn: pfn misaligned\n");
return; /* BUG(); */
}
pgd = swapper_pg_dir + pgd_index(vaddr);
if (pgd_none(*pgd)) {
printk(KERN_ERR "set_pmd_pfn: pgd_none\n");
return; /* BUG(); */
}
pud = pud_offset(pgd, vaddr);
pmd = pmd_offset(pud, vaddr);
set_pmd(pmd, pfn_pmd(pfn, flags));
/*
* It's enough to flush this one mapping.
* (PGE mappings get flushed as well)
*/
local_flush_tlb_one(vaddr);
}
pte_t *pte_alloc_one_kernel(struct mm_struct *mm, unsigned long address)
{
pte_t *pte = (pte_t *)__get_free_page(GFP_KERNEL|__GFP_REPEAT);
if (pte)
clear_page(pte);
return pte;
}
struct page *pte_alloc_one(struct mm_struct *mm, unsigned long address)
{
struct page *pte;
#ifdef CONFIG_HIGHPTE
pte = alloc_pages(GFP_KERNEL|__GFP_HIGHMEM|__GFP_REPEAT, 0);
#else
pte = alloc_pages(GFP_KERNEL|__GFP_REPEAT, 0);
#endif
if (pte)
clear_highpage(pte);
return pte;
}
/*
* List of all pgd's needed for non-PAE so it can invalidate entries
* in both cached and uncached pgd's; not needed for PAE since the
* kernel pmd is shared. If PAE were not to share the pmd a similar
* tactic would be needed. This is essentially codepath-based locking
* against pageattr.c; it is the unique case in which a valid change
* of kernel pagetables can't be lazily synchronized by vmalloc faults.
* vmalloc faults work because attached pagetables are never freed.
* If the locking proves to be non-performant, a ticketing scheme with
* checks at dup_mmap(), exec(), and other mmlist addition points
* could be used. The locking scheme was chosen on the basis of
* manfred's recommendations and having no core impact whatsoever.
* -- nyc
*/
DEFINE_SPINLOCK(pgd_lock);
struct page *pgd_list;
static inline void pgd_list_add(pgd_t *pgd)
{
struct page *page = virt_to_page(pgd);
page->index = (unsigned long) pgd_list;
if (pgd_list)
set_page_private(pgd_list, (unsigned long) &page->index);
pgd_list = page;
set_page_private(page, (unsigned long) &pgd_list);
}
static inline void pgd_list_del(pgd_t *pgd)
{
struct page *next, **pprev, *page = virt_to_page(pgd);
next = (struct page *) page->index;
pprev = (struct page **) page_private(page);
*pprev = next;
if (next)
set_page_private(next, (unsigned long) pprev);
}
void pgd_ctor(void *pgd)
{
unsigned long flags;
if (PTRS_PER_PMD == 1)
spin_lock_irqsave(&pgd_lock, flags);
memcpy((pgd_t *)pgd + USER_PTRS_PER_PGD,
swapper_pg_dir + USER_PTRS_PER_PGD,
(PTRS_PER_PGD - USER_PTRS_PER_PGD) * sizeof(pgd_t));
if (PTRS_PER_PMD > 1)
return;
pgd_list_add(pgd);
spin_unlock_irqrestore(&pgd_lock, flags);
memset(pgd, 0, USER_PTRS_PER_PGD * sizeof(pgd_t));
}
/* never called when PTRS_PER_PMD > 1 */
void pgd_dtor(void *pgd)
{
unsigned long flags; /* can be called from interrupt context */
spin_lock_irqsave(&pgd_lock, flags);
pgd_list_del(pgd);
spin_unlock_irqrestore(&pgd_lock, flags);
}
pgd_t *pgd_alloc(struct mm_struct *mm)
{
return quicklist_alloc(0, GFP_KERNEL, pgd_ctor);
}
void pgd_free(struct mm_struct *mm, pgd_t *pgd)
{
quicklist_free(0, pgd_dtor, pgd);
}
void __init pgtable_cache_init(void)
{
}
void check_pgt_cache(void)
{
quicklist_trim(0, pgd_dtor, 25, 16);
}
| gpl-2.0 |
Team-Blackout/BeastMode-Evita | fs/logfs/journal.c | 3281 | 24303 | /*
* fs/logfs/journal.c - journal handling code
*
* As should be obvious for Linux kernel code, license is GPLv2
*
* Copyright (c) 2005-2008 Joern Engel <joern@logfs.org>
*/
#include "logfs.h"
#include <linux/slab.h>
static void logfs_calc_free(struct super_block *sb)
{
struct logfs_super *super = logfs_super(sb);
u64 reserve, no_segs = super->s_no_segs;
s64 free;
int i;
/* superblock segments */
no_segs -= 2;
super->s_no_journal_segs = 0;
/* journal */
journal_for_each(i)
if (super->s_journal_seg[i]) {
no_segs--;
super->s_no_journal_segs++;
}
/* open segments plus one extra per level for GC */
no_segs -= 2 * super->s_total_levels;
free = no_segs * (super->s_segsize - LOGFS_SEGMENT_RESERVE);
free -= super->s_used_bytes;
/* just a bit extra */
free -= super->s_total_levels * 4096;
/* Bad blocks are 'paid' for with speed reserve - the filesystem
* simply gets slower as bad blocks accumulate. Until the bad blocks
* exceed the speed reserve - then the filesystem gets smaller.
*/
reserve = super->s_bad_segments + super->s_bad_seg_reserve;
reserve *= super->s_segsize - LOGFS_SEGMENT_RESERVE;
reserve = max(reserve, super->s_speed_reserve);
free -= reserve;
if (free < 0)
free = 0;
super->s_free_bytes = free;
}
static void reserve_sb_and_journal(struct super_block *sb)
{
struct logfs_super *super = logfs_super(sb);
struct btree_head32 *head = &super->s_reserved_segments;
int i, err;
err = btree_insert32(head, seg_no(sb, super->s_sb_ofs[0]), (void *)1,
GFP_KERNEL);
BUG_ON(err);
err = btree_insert32(head, seg_no(sb, super->s_sb_ofs[1]), (void *)1,
GFP_KERNEL);
BUG_ON(err);
journal_for_each(i) {
if (!super->s_journal_seg[i])
continue;
err = btree_insert32(head, super->s_journal_seg[i], (void *)1,
GFP_KERNEL);
BUG_ON(err);
}
}
static void read_dynsb(struct super_block *sb,
struct logfs_je_dynsb *dynsb)
{
struct logfs_super *super = logfs_super(sb);
super->s_gec = be64_to_cpu(dynsb->ds_gec);
super->s_sweeper = be64_to_cpu(dynsb->ds_sweeper);
super->s_victim_ino = be64_to_cpu(dynsb->ds_victim_ino);
super->s_rename_dir = be64_to_cpu(dynsb->ds_rename_dir);
super->s_rename_pos = be64_to_cpu(dynsb->ds_rename_pos);
super->s_used_bytes = be64_to_cpu(dynsb->ds_used_bytes);
super->s_generation = be32_to_cpu(dynsb->ds_generation);
}
static void read_anchor(struct super_block *sb,
struct logfs_je_anchor *da)
{
struct logfs_super *super = logfs_super(sb);
struct inode *inode = super->s_master_inode;
struct logfs_inode *li = logfs_inode(inode);
int i;
super->s_last_ino = be64_to_cpu(da->da_last_ino);
li->li_flags = 0;
li->li_height = da->da_height;
i_size_write(inode, be64_to_cpu(da->da_size));
li->li_used_bytes = be64_to_cpu(da->da_used_bytes);
for (i = 0; i < LOGFS_EMBEDDED_FIELDS; i++)
li->li_data[i] = be64_to_cpu(da->da_data[i]);
}
static void read_erasecount(struct super_block *sb,
struct logfs_je_journal_ec *ec)
{
struct logfs_super *super = logfs_super(sb);
int i;
journal_for_each(i)
super->s_journal_ec[i] = be32_to_cpu(ec->ec[i]);
}
static int read_area(struct super_block *sb, struct logfs_je_area *a)
{
struct logfs_super *super = logfs_super(sb);
struct logfs_area *area = super->s_area[a->gc_level];
u64 ofs;
u32 writemask = ~(super->s_writesize - 1);
if (a->gc_level >= LOGFS_NO_AREAS)
return -EIO;
if (a->vim != VIM_DEFAULT)
return -EIO; /* TODO: close area and continue */
area->a_used_bytes = be32_to_cpu(a->used_bytes);
area->a_written_bytes = area->a_used_bytes & writemask;
area->a_segno = be32_to_cpu(a->segno);
if (area->a_segno)
area->a_is_open = 1;
ofs = dev_ofs(sb, area->a_segno, area->a_written_bytes);
if (super->s_writesize > 1)
return logfs_buf_recover(area, ofs, a + 1, super->s_writesize);
else
return logfs_buf_recover(area, ofs, NULL, 0);
}
static void *unpack(void *from, void *to)
{
struct logfs_journal_header *jh = from;
void *data = from + sizeof(struct logfs_journal_header);
int err;
size_t inlen, outlen;
inlen = be16_to_cpu(jh->h_len);
outlen = be16_to_cpu(jh->h_datalen);
if (jh->h_compr == COMPR_NONE)
memcpy(to, data, inlen);
else {
err = logfs_uncompress(data, to, inlen, outlen);
BUG_ON(err);
}
return to;
}
static int __read_je_header(struct super_block *sb, u64 ofs,
struct logfs_journal_header *jh)
{
struct logfs_super *super = logfs_super(sb);
size_t bufsize = max_t(size_t, sb->s_blocksize, super->s_writesize)
+ MAX_JOURNAL_HEADER;
u16 type, len, datalen;
int err;
/* read header only */
err = wbuf_read(sb, ofs, sizeof(*jh), jh);
if (err)
return err;
type = be16_to_cpu(jh->h_type);
len = be16_to_cpu(jh->h_len);
datalen = be16_to_cpu(jh->h_datalen);
if (len > sb->s_blocksize)
return -EIO;
if ((type < JE_FIRST) || (type > JE_LAST))
return -EIO;
if (datalen > bufsize)
return -EIO;
return 0;
}
static int __read_je_payload(struct super_block *sb, u64 ofs,
struct logfs_journal_header *jh)
{
u16 len;
int err;
len = be16_to_cpu(jh->h_len);
err = wbuf_read(sb, ofs + sizeof(*jh), len, jh + 1);
if (err)
return err;
if (jh->h_crc != logfs_crc32(jh, len + sizeof(*jh), 4)) {
/* Old code was confused. It forgot about the header length
* and stopped calculating the crc 16 bytes before the end
* of data - ick!
* FIXME: Remove this hack once the old code is fixed.
*/
if (jh->h_crc == logfs_crc32(jh, len, 4))
WARN_ON_ONCE(1);
else
return -EIO;
}
return 0;
}
/*
* jh needs to be large enough to hold the complete entry, not just the header
*/
static int __read_je(struct super_block *sb, u64 ofs,
struct logfs_journal_header *jh)
{
int err;
err = __read_je_header(sb, ofs, jh);
if (err)
return err;
return __read_je_payload(sb, ofs, jh);
}
static int read_je(struct super_block *sb, u64 ofs)
{
struct logfs_super *super = logfs_super(sb);
struct logfs_journal_header *jh = super->s_compressed_je;
void *scratch = super->s_je;
u16 type, datalen;
int err;
err = __read_je(sb, ofs, jh);
if (err)
return err;
type = be16_to_cpu(jh->h_type);
datalen = be16_to_cpu(jh->h_datalen);
switch (type) {
case JE_DYNSB:
read_dynsb(sb, unpack(jh, scratch));
break;
case JE_ANCHOR:
read_anchor(sb, unpack(jh, scratch));
break;
case JE_ERASECOUNT:
read_erasecount(sb, unpack(jh, scratch));
break;
case JE_AREA:
err = read_area(sb, unpack(jh, scratch));
break;
case JE_OBJ_ALIAS:
err = logfs_load_object_aliases(sb, unpack(jh, scratch),
datalen);
break;
default:
WARN_ON_ONCE(1);
return -EIO;
}
return err;
}
static int logfs_read_segment(struct super_block *sb, u32 segno)
{
struct logfs_super *super = logfs_super(sb);
struct logfs_journal_header *jh = super->s_compressed_je;
u64 ofs, seg_ofs = dev_ofs(sb, segno, 0);
u32 h_ofs, last_ofs = 0;
u16 len, datalen, last_len = 0;
int i, err;
/* search for most recent commit */
for (h_ofs = 0; h_ofs < super->s_segsize; h_ofs += sizeof(*jh)) {
ofs = seg_ofs + h_ofs;
err = __read_je_header(sb, ofs, jh);
if (err)
continue;
if (jh->h_type != cpu_to_be16(JE_COMMIT))
continue;
err = __read_je_payload(sb, ofs, jh);
if (err)
continue;
len = be16_to_cpu(jh->h_len);
datalen = be16_to_cpu(jh->h_datalen);
if ((datalen > sizeof(super->s_je_array)) ||
(datalen % sizeof(__be64)))
continue;
last_ofs = h_ofs;
last_len = datalen;
h_ofs += ALIGN(len, sizeof(*jh)) - sizeof(*jh);
}
/* read commit */
if (last_ofs == 0)
return -ENOENT;
ofs = seg_ofs + last_ofs;
log_journal("Read commit from %llx\n", ofs);
err = __read_je(sb, ofs, jh);
BUG_ON(err); /* We should have caught it in the scan loop already */
if (err)
return err;
/* uncompress */
unpack(jh, super->s_je_array);
super->s_no_je = last_len / sizeof(__be64);
/* iterate over array */
for (i = 0; i < super->s_no_je; i++) {
err = read_je(sb, be64_to_cpu(super->s_je_array[i]));
if (err)
return err;
}
super->s_journal_area->a_segno = segno;
return 0;
}
static u64 read_gec(struct super_block *sb, u32 segno)
{
struct logfs_segment_header sh;
__be32 crc;
int err;
if (!segno)
return 0;
err = wbuf_read(sb, dev_ofs(sb, segno, 0), sizeof(sh), &sh);
if (err)
return 0;
crc = logfs_crc32(&sh, sizeof(sh), 4);
if (crc != sh.crc) {
WARN_ON(sh.gec != cpu_to_be64(0xffffffffffffffffull));
/* Most likely it was just erased */
return 0;
}
return be64_to_cpu(sh.gec);
}
static int logfs_read_journal(struct super_block *sb)
{
struct logfs_super *super = logfs_super(sb);
u64 gec[LOGFS_JOURNAL_SEGS], max;
u32 segno;
int i, max_i;
max = 0;
max_i = -1;
journal_for_each(i) {
segno = super->s_journal_seg[i];
gec[i] = read_gec(sb, super->s_journal_seg[i]);
if (gec[i] > max) {
max = gec[i];
max_i = i;
}
}
if (max_i == -1)
return -EIO;
/* FIXME: Try older segments in case of error */
return logfs_read_segment(sb, super->s_journal_seg[max_i]);
}
/*
* First search the current segment (outer loop), then pick the next segment
* in the array, skipping any zero entries (inner loop).
*/
static void journal_get_free_segment(struct logfs_area *area)
{
struct logfs_super *super = logfs_super(area->a_sb);
int i;
journal_for_each(i) {
if (area->a_segno != super->s_journal_seg[i])
continue;
do {
i++;
if (i == LOGFS_JOURNAL_SEGS)
i = 0;
} while (!super->s_journal_seg[i]);
area->a_segno = super->s_journal_seg[i];
area->a_erase_count = ++(super->s_journal_ec[i]);
log_journal("Journal now at %x (ec %x)\n", area->a_segno,
area->a_erase_count);
return;
}
BUG();
}
static void journal_get_erase_count(struct logfs_area *area)
{
/* erase count is stored globally and incremented in
* journal_get_free_segment() - nothing to do here */
}
static int journal_erase_segment(struct logfs_area *area)
{
struct super_block *sb = area->a_sb;
union {
struct logfs_segment_header sh;
unsigned char c[ALIGN(sizeof(struct logfs_segment_header), 16)];
} u;
u64 ofs;
int err;
err = logfs_erase_segment(sb, area->a_segno, 1);
if (err)
return err;
memset(&u, 0, sizeof(u));
u.sh.pad = 0;
u.sh.type = SEG_JOURNAL;
u.sh.level = 0;
u.sh.segno = cpu_to_be32(area->a_segno);
u.sh.ec = cpu_to_be32(area->a_erase_count);
u.sh.gec = cpu_to_be64(logfs_super(sb)->s_gec);
u.sh.crc = logfs_crc32(&u.sh, sizeof(u.sh), 4);
/* This causes a bug in segment.c. Not yet. */
//logfs_set_segment_erased(sb, area->a_segno, area->a_erase_count, 0);
ofs = dev_ofs(sb, area->a_segno, 0);
area->a_used_bytes = sizeof(u);
logfs_buf_write(area, ofs, &u, sizeof(u));
return 0;
}
static size_t __logfs_write_header(struct logfs_super *super,
struct logfs_journal_header *jh, size_t len, size_t datalen,
u16 type, u8 compr)
{
jh->h_len = cpu_to_be16(len);
jh->h_type = cpu_to_be16(type);
jh->h_datalen = cpu_to_be16(datalen);
jh->h_compr = compr;
jh->h_pad[0] = 'H';
jh->h_pad[1] = 'E';
jh->h_pad[2] = 'A';
jh->h_pad[3] = 'D';
jh->h_pad[4] = 'R';
jh->h_crc = logfs_crc32(jh, len + sizeof(*jh), 4);
return ALIGN(len, 16) + sizeof(*jh);
}
static size_t logfs_write_header(struct logfs_super *super,
struct logfs_journal_header *jh, size_t datalen, u16 type)
{
size_t len = datalen;
return __logfs_write_header(super, jh, len, datalen, type, COMPR_NONE);
}
static inline size_t logfs_journal_erasecount_size(struct logfs_super *super)
{
return LOGFS_JOURNAL_SEGS * sizeof(__be32);
}
static void *logfs_write_erasecount(struct super_block *sb, void *_ec,
u16 *type, size_t *len)
{
struct logfs_super *super = logfs_super(sb);
struct logfs_je_journal_ec *ec = _ec;
int i;
journal_for_each(i)
ec->ec[i] = cpu_to_be32(super->s_journal_ec[i]);
*type = JE_ERASECOUNT;
*len = logfs_journal_erasecount_size(super);
return ec;
}
static void account_shadow(void *_shadow, unsigned long _sb, u64 ignore,
size_t ignore2)
{
struct logfs_shadow *shadow = _shadow;
struct super_block *sb = (void *)_sb;
struct logfs_super *super = logfs_super(sb);
/* consume new space */
super->s_free_bytes -= shadow->new_len;
super->s_used_bytes += shadow->new_len;
super->s_dirty_used_bytes -= shadow->new_len;
/* free up old space */
super->s_free_bytes += shadow->old_len;
super->s_used_bytes -= shadow->old_len;
super->s_dirty_free_bytes -= shadow->old_len;
logfs_set_segment_used(sb, shadow->old_ofs, -shadow->old_len);
logfs_set_segment_used(sb, shadow->new_ofs, shadow->new_len);
log_journal("account_shadow(%llx, %llx, %x) %llx->%llx %x->%x\n",
shadow->ino, shadow->bix, shadow->gc_level,
shadow->old_ofs, shadow->new_ofs,
shadow->old_len, shadow->new_len);
mempool_free(shadow, super->s_shadow_pool);
}
static void account_shadows(struct super_block *sb)
{
struct logfs_super *super = logfs_super(sb);
struct inode *inode = super->s_master_inode;
struct logfs_inode *li = logfs_inode(inode);
struct shadow_tree *tree = &super->s_shadow_tree;
btree_grim_visitor64(&tree->new, (unsigned long)sb, account_shadow);
btree_grim_visitor64(&tree->old, (unsigned long)sb, account_shadow);
btree_grim_visitor32(&tree->segment_map, 0, NULL);
tree->no_shadowed_segments = 0;
if (li->li_block) {
/*
* We never actually use the structure, when attached to the
* master inode. But it is easier to always free it here than
* to have checks in several places elsewhere when allocating
* it.
*/
li->li_block->ops->free_block(sb, li->li_block);
}
BUG_ON((s64)li->li_used_bytes < 0);
}
static void *__logfs_write_anchor(struct super_block *sb, void *_da,
u16 *type, size_t *len)
{
struct logfs_super *super = logfs_super(sb);
struct logfs_je_anchor *da = _da;
struct inode *inode = super->s_master_inode;
struct logfs_inode *li = logfs_inode(inode);
int i;
da->da_height = li->li_height;
da->da_last_ino = cpu_to_be64(super->s_last_ino);
da->da_size = cpu_to_be64(i_size_read(inode));
da->da_used_bytes = cpu_to_be64(li->li_used_bytes);
for (i = 0; i < LOGFS_EMBEDDED_FIELDS; i++)
da->da_data[i] = cpu_to_be64(li->li_data[i]);
*type = JE_ANCHOR;
*len = sizeof(*da);
return da;
}
static void *logfs_write_dynsb(struct super_block *sb, void *_dynsb,
u16 *type, size_t *len)
{
struct logfs_super *super = logfs_super(sb);
struct logfs_je_dynsb *dynsb = _dynsb;
dynsb->ds_gec = cpu_to_be64(super->s_gec);
dynsb->ds_sweeper = cpu_to_be64(super->s_sweeper);
dynsb->ds_victim_ino = cpu_to_be64(super->s_victim_ino);
dynsb->ds_rename_dir = cpu_to_be64(super->s_rename_dir);
dynsb->ds_rename_pos = cpu_to_be64(super->s_rename_pos);
dynsb->ds_used_bytes = cpu_to_be64(super->s_used_bytes);
dynsb->ds_generation = cpu_to_be32(super->s_generation);
*type = JE_DYNSB;
*len = sizeof(*dynsb);
return dynsb;
}
static void write_wbuf(struct super_block *sb, struct logfs_area *area,
void *wbuf)
{
struct logfs_super *super = logfs_super(sb);
struct address_space *mapping = super->s_mapping_inode->i_mapping;
u64 ofs;
pgoff_t index;
int page_ofs;
struct page *page;
ofs = dev_ofs(sb, area->a_segno,
area->a_used_bytes & ~(super->s_writesize - 1));
index = ofs >> PAGE_SHIFT;
page_ofs = ofs & (PAGE_SIZE - 1);
page = find_lock_page(mapping, index);
BUG_ON(!page);
memcpy(wbuf, page_address(page) + page_ofs, super->s_writesize);
unlock_page(page);
}
static void *logfs_write_area(struct super_block *sb, void *_a,
u16 *type, size_t *len)
{
struct logfs_super *super = logfs_super(sb);
struct logfs_area *area = super->s_area[super->s_sum_index];
struct logfs_je_area *a = _a;
a->vim = VIM_DEFAULT;
a->gc_level = super->s_sum_index;
a->used_bytes = cpu_to_be32(area->a_used_bytes);
a->segno = cpu_to_be32(area->a_segno);
if (super->s_writesize > 1)
write_wbuf(sb, area, a + 1);
*type = JE_AREA;
*len = sizeof(*a) + super->s_writesize;
return a;
}
static void *logfs_write_commit(struct super_block *sb, void *h,
u16 *type, size_t *len)
{
struct logfs_super *super = logfs_super(sb);
*type = JE_COMMIT;
*len = super->s_no_je * sizeof(__be64);
return super->s_je_array;
}
static size_t __logfs_write_je(struct super_block *sb, void *buf, u16 type,
size_t len)
{
struct logfs_super *super = logfs_super(sb);
void *header = super->s_compressed_je;
void *data = header + sizeof(struct logfs_journal_header);
ssize_t compr_len, pad_len;
u8 compr = COMPR_ZLIB;
if (len == 0)
return logfs_write_header(super, header, 0, type);
BUG_ON(len > sb->s_blocksize);
compr_len = logfs_compress(buf, data, len, sb->s_blocksize);
if (compr_len < 0 || type == JE_ANCHOR) {
memcpy(data, buf, len);
compr_len = len;
compr = COMPR_NONE;
}
pad_len = ALIGN(compr_len, 16);
memset(data + compr_len, 0, pad_len - compr_len);
return __logfs_write_header(super, header, compr_len, len, type, compr);
}
static s64 logfs_get_free_bytes(struct logfs_area *area, size_t *bytes,
int must_pad)
{
u32 writesize = logfs_super(area->a_sb)->s_writesize;
s32 ofs;
int ret;
ret = logfs_open_area(area, *bytes);
if (ret)
return -EAGAIN;
ofs = area->a_used_bytes;
area->a_used_bytes += *bytes;
if (must_pad) {
area->a_used_bytes = ALIGN(area->a_used_bytes, writesize);
*bytes = area->a_used_bytes - ofs;
}
return dev_ofs(area->a_sb, area->a_segno, ofs);
}
static int logfs_write_je_buf(struct super_block *sb, void *buf, u16 type,
size_t buf_len)
{
struct logfs_super *super = logfs_super(sb);
struct logfs_area *area = super->s_journal_area;
struct logfs_journal_header *jh = super->s_compressed_je;
size_t len;
int must_pad = 0;
s64 ofs;
len = __logfs_write_je(sb, buf, type, buf_len);
if (jh->h_type == cpu_to_be16(JE_COMMIT))
must_pad = 1;
ofs = logfs_get_free_bytes(area, &len, must_pad);
if (ofs < 0)
return ofs;
logfs_buf_write(area, ofs, super->s_compressed_je, len);
BUG_ON(super->s_no_je >= MAX_JOURNAL_ENTRIES);
super->s_je_array[super->s_no_je++] = cpu_to_be64(ofs);
return 0;
}
static int logfs_write_je(struct super_block *sb,
void* (*write)(struct super_block *sb, void *scratch,
u16 *type, size_t *len))
{
void *buf;
size_t len;
u16 type;
buf = write(sb, logfs_super(sb)->s_je, &type, &len);
return logfs_write_je_buf(sb, buf, type, len);
}
int write_alias_journal(struct super_block *sb, u64 ino, u64 bix,
level_t level, int child_no, __be64 val)
{
struct logfs_super *super = logfs_super(sb);
struct logfs_obj_alias *oa = super->s_je;
int err = 0, fill = super->s_je_fill;
log_aliases("logfs_write_obj_aliases #%x(%llx, %llx, %x, %x) %llx\n",
fill, ino, bix, level, child_no, be64_to_cpu(val));
oa[fill].ino = cpu_to_be64(ino);
oa[fill].bix = cpu_to_be64(bix);
oa[fill].val = val;
oa[fill].level = (__force u8)level;
oa[fill].child_no = cpu_to_be16(child_no);
fill++;
if (fill >= sb->s_blocksize / sizeof(*oa)) {
err = logfs_write_je_buf(sb, oa, JE_OBJ_ALIAS, sb->s_blocksize);
fill = 0;
}
super->s_je_fill = fill;
return err;
}
static int logfs_write_obj_aliases(struct super_block *sb)
{
struct logfs_super *super = logfs_super(sb);
int err;
log_journal("logfs_write_obj_aliases: %d aliases to write\n",
super->s_no_object_aliases);
super->s_je_fill = 0;
err = logfs_write_obj_aliases_pagecache(sb);
if (err)
return err;
if (super->s_je_fill)
err = logfs_write_je_buf(sb, super->s_je, JE_OBJ_ALIAS,
super->s_je_fill
* sizeof(struct logfs_obj_alias));
return err;
}
/*
* Write all journal entries. The goto logic ensures that all journal entries
* are written whenever a new segment is used. It is ugly and potentially a
* bit wasteful, but robustness is more important. With this we can *always*
* erase all journal segments except the one containing the most recent commit.
*/
void logfs_write_anchor(struct super_block *sb)
{
struct logfs_super *super = logfs_super(sb);
struct logfs_area *area = super->s_journal_area;
int i, err;
if (!(super->s_flags & LOGFS_SB_FLAG_DIRTY))
return;
super->s_flags &= ~LOGFS_SB_FLAG_DIRTY;
BUG_ON(super->s_flags & LOGFS_SB_FLAG_SHUTDOWN);
mutex_lock(&super->s_journal_mutex);
/* Do this first or suffer corruption */
logfs_sync_segments(sb);
account_shadows(sb);
again:
super->s_no_je = 0;
for_each_area(i) {
if (!super->s_area[i]->a_is_open)
continue;
super->s_sum_index = i;
err = logfs_write_je(sb, logfs_write_area);
if (err)
goto again;
}
err = logfs_write_obj_aliases(sb);
if (err)
goto again;
err = logfs_write_je(sb, logfs_write_erasecount);
if (err)
goto again;
err = logfs_write_je(sb, __logfs_write_anchor);
if (err)
goto again;
err = logfs_write_je(sb, logfs_write_dynsb);
if (err)
goto again;
/*
* Order is imperative. First we sync all writes, including the
* non-committed journal writes. Then we write the final commit and
* sync the current journal segment.
* There is a theoretical bug here. Syncing the journal segment will
* write a number of journal entries and the final commit. All these
* are written in a single operation. If the device layer writes the
* data back-to-front, the commit will precede the other journal
* entries, leaving a race window.
* Two fixes are possible. Preferred is to fix the device layer to
* ensure writes happen front-to-back. Alternatively we can insert
* another logfs_sync_area() super->s_devops->sync() combo before
* writing the commit.
*/
/*
* On another subject, super->s_devops->sync is usually not necessary.
* Unless called from sys_sync or friends, a barrier would suffice.
*/
super->s_devops->sync(sb);
err = logfs_write_je(sb, logfs_write_commit);
if (err)
goto again;
log_journal("Write commit to %llx\n",
be64_to_cpu(super->s_je_array[super->s_no_je - 1]));
logfs_sync_area(area);
BUG_ON(area->a_used_bytes != area->a_written_bytes);
super->s_devops->sync(sb);
mutex_unlock(&super->s_journal_mutex);
return;
}
void do_logfs_journal_wl_pass(struct super_block *sb)
{
struct logfs_super *super = logfs_super(sb);
struct logfs_area *area = super->s_journal_area;
struct btree_head32 *head = &super->s_reserved_segments;
u32 segno, ec;
int i, err;
log_journal("Journal requires wear-leveling.\n");
/* Drop old segments */
journal_for_each(i)
if (super->s_journal_seg[i]) {
btree_remove32(head, super->s_journal_seg[i]);
logfs_set_segment_unreserved(sb,
super->s_journal_seg[i],
super->s_journal_ec[i]);
super->s_journal_seg[i] = 0;
super->s_journal_ec[i] = 0;
}
/* Get new segments */
for (i = 0; i < super->s_no_journal_segs; i++) {
segno = get_best_cand(sb, &super->s_reserve_list, &ec);
super->s_journal_seg[i] = segno;
super->s_journal_ec[i] = ec;
logfs_set_segment_reserved(sb, segno);
err = btree_insert32(head, segno, (void *)1, GFP_NOFS);
BUG_ON(err); /* mempool should prevent this */
err = logfs_erase_segment(sb, segno, 1);
BUG_ON(err); /* FIXME: remount-ro would be nicer */
}
/* Manually move journal_area */
freeseg(sb, area->a_segno);
area->a_segno = super->s_journal_seg[0];
area->a_is_open = 0;
area->a_used_bytes = 0;
/* Write journal */
logfs_write_anchor(sb);
/* Write superblocks */
err = logfs_write_sb(sb);
BUG_ON(err);
}
static const struct logfs_area_ops journal_area_ops = {
.get_free_segment = journal_get_free_segment,
.get_erase_count = journal_get_erase_count,
.erase_segment = journal_erase_segment,
};
int logfs_init_journal(struct super_block *sb)
{
struct logfs_super *super = logfs_super(sb);
size_t bufsize = max_t(size_t, sb->s_blocksize, super->s_writesize)
+ MAX_JOURNAL_HEADER;
int ret = -ENOMEM;
mutex_init(&super->s_journal_mutex);
btree_init_mempool32(&super->s_reserved_segments, super->s_btree_pool);
super->s_je = kzalloc(bufsize, GFP_KERNEL);
if (!super->s_je)
return ret;
super->s_compressed_je = kzalloc(bufsize, GFP_KERNEL);
if (!super->s_compressed_je)
return ret;
super->s_master_inode = logfs_new_meta_inode(sb, LOGFS_INO_MASTER);
if (IS_ERR(super->s_master_inode))
return PTR_ERR(super->s_master_inode);
ret = logfs_read_journal(sb);
if (ret)
return -EIO;
reserve_sb_and_journal(sb);
logfs_calc_free(sb);
super->s_journal_area->a_ops = &journal_area_ops;
return 0;
}
void logfs_cleanup_journal(struct super_block *sb)
{
struct logfs_super *super = logfs_super(sb);
btree_grim_visitor32(&super->s_reserved_segments, 0, NULL);
kfree(super->s_compressed_je);
kfree(super->s_je);
}
| gpl-2.0 |
greg17477/kernel_motley_mako | drivers/mtd/nand/cs553x_nand.c | 3281 | 9816 | /*
* drivers/mtd/nand/cs553x_nand.c
*
* (C) 2005, 2006 Red Hat Inc.
*
* Author: David Woodhouse <dwmw2@infradead.org>
* Tom Sylla <tom.sylla@amd.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.
*
* Overview:
* This is a device driver for the NAND flash controller found on
* the AMD CS5535/CS5536 companion chipsets for the Geode processor.
* mtd-id for command line partitioning is cs553x_nand_cs[0-3]
* where 0-3 reflects the chip select for NAND.
*
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/nand_ecc.h>
#include <linux/mtd/partitions.h>
#include <asm/msr.h>
#include <asm/io.h>
#define NR_CS553X_CONTROLLERS 4
#define MSR_DIVIL_GLD_CAP 0x51400000 /* DIVIL capabilitiies */
#define CAP_CS5535 0x2df000ULL
#define CAP_CS5536 0x5df500ULL
/* NAND Timing MSRs */
#define MSR_NANDF_DATA 0x5140001b /* NAND Flash Data Timing MSR */
#define MSR_NANDF_CTL 0x5140001c /* NAND Flash Control Timing */
#define MSR_NANDF_RSVD 0x5140001d /* Reserved */
/* NAND BAR MSRs */
#define MSR_DIVIL_LBAR_FLSH0 0x51400010 /* Flash Chip Select 0 */
#define MSR_DIVIL_LBAR_FLSH1 0x51400011 /* Flash Chip Select 1 */
#define MSR_DIVIL_LBAR_FLSH2 0x51400012 /* Flash Chip Select 2 */
#define MSR_DIVIL_LBAR_FLSH3 0x51400013 /* Flash Chip Select 3 */
/* Each made up of... */
#define FLSH_LBAR_EN (1ULL<<32)
#define FLSH_NOR_NAND (1ULL<<33) /* 1 for NAND */
#define FLSH_MEM_IO (1ULL<<34) /* 1 for MMIO */
/* I/O BARs have BASE_ADDR in bits 15:4, IO_MASK in 47:36 */
/* MMIO BARs have BASE_ADDR in bits 31:12, MEM_MASK in 63:44 */
/* Pin function selection MSR (IDE vs. flash on the IDE pins) */
#define MSR_DIVIL_BALL_OPTS 0x51400015
#define PIN_OPT_IDE (1<<0) /* 0 for flash, 1 for IDE */
/* Registers within the NAND flash controller BAR -- memory mapped */
#define MM_NAND_DATA 0x00 /* 0 to 0x7ff, in fact */
#define MM_NAND_CTL 0x800 /* Any even address 0x800-0x80e */
#define MM_NAND_IO 0x801 /* Any odd address 0x801-0x80f */
#define MM_NAND_STS 0x810
#define MM_NAND_ECC_LSB 0x811
#define MM_NAND_ECC_MSB 0x812
#define MM_NAND_ECC_COL 0x813
#define MM_NAND_LAC 0x814
#define MM_NAND_ECC_CTL 0x815
/* Registers within the NAND flash controller BAR -- I/O mapped */
#define IO_NAND_DATA 0x00 /* 0 to 3, in fact */
#define IO_NAND_CTL 0x04
#define IO_NAND_IO 0x05
#define IO_NAND_STS 0x06
#define IO_NAND_ECC_CTL 0x08
#define IO_NAND_ECC_LSB 0x09
#define IO_NAND_ECC_MSB 0x0a
#define IO_NAND_ECC_COL 0x0b
#define IO_NAND_LAC 0x0c
#define CS_NAND_CTL_DIST_EN (1<<4) /* Enable NAND Distract interrupt */
#define CS_NAND_CTL_RDY_INT_MASK (1<<3) /* Enable RDY/BUSY# interrupt */
#define CS_NAND_CTL_ALE (1<<2)
#define CS_NAND_CTL_CLE (1<<1)
#define CS_NAND_CTL_CE (1<<0) /* Keep low; 1 to reset */
#define CS_NAND_STS_FLASH_RDY (1<<3)
#define CS_NAND_CTLR_BUSY (1<<2)
#define CS_NAND_CMD_COMP (1<<1)
#define CS_NAND_DIST_ST (1<<0)
#define CS_NAND_ECC_PARITY (1<<2)
#define CS_NAND_ECC_CLRECC (1<<1)
#define CS_NAND_ECC_ENECC (1<<0)
static void cs553x_read_buf(struct mtd_info *mtd, u_char *buf, int len)
{
struct nand_chip *this = mtd->priv;
while (unlikely(len > 0x800)) {
memcpy_fromio(buf, this->IO_ADDR_R, 0x800);
buf += 0x800;
len -= 0x800;
}
memcpy_fromio(buf, this->IO_ADDR_R, len);
}
static void cs553x_write_buf(struct mtd_info *mtd, const u_char *buf, int len)
{
struct nand_chip *this = mtd->priv;
while (unlikely(len > 0x800)) {
memcpy_toio(this->IO_ADDR_R, buf, 0x800);
buf += 0x800;
len -= 0x800;
}
memcpy_toio(this->IO_ADDR_R, buf, len);
}
static unsigned char cs553x_read_byte(struct mtd_info *mtd)
{
struct nand_chip *this = mtd->priv;
return readb(this->IO_ADDR_R);
}
static void cs553x_write_byte(struct mtd_info *mtd, u_char byte)
{
struct nand_chip *this = mtd->priv;
int i = 100000;
while (i && readb(this->IO_ADDR_R + MM_NAND_STS) & CS_NAND_CTLR_BUSY) {
udelay(1);
i--;
}
writeb(byte, this->IO_ADDR_W + 0x801);
}
static void cs553x_hwcontrol(struct mtd_info *mtd, int cmd,
unsigned int ctrl)
{
struct nand_chip *this = mtd->priv;
void __iomem *mmio_base = this->IO_ADDR_R;
if (ctrl & NAND_CTRL_CHANGE) {
unsigned char ctl = (ctrl & ~NAND_CTRL_CHANGE ) ^ 0x01;
writeb(ctl, mmio_base + MM_NAND_CTL);
}
if (cmd != NAND_CMD_NONE)
cs553x_write_byte(mtd, cmd);
}
static int cs553x_device_ready(struct mtd_info *mtd)
{
struct nand_chip *this = mtd->priv;
void __iomem *mmio_base = this->IO_ADDR_R;
unsigned char foo = readb(mmio_base + MM_NAND_STS);
return (foo & CS_NAND_STS_FLASH_RDY) && !(foo & CS_NAND_CTLR_BUSY);
}
static void cs_enable_hwecc(struct mtd_info *mtd, int mode)
{
struct nand_chip *this = mtd->priv;
void __iomem *mmio_base = this->IO_ADDR_R;
writeb(0x07, mmio_base + MM_NAND_ECC_CTL);
}
static int cs_calculate_ecc(struct mtd_info *mtd, const u_char *dat, u_char *ecc_code)
{
uint32_t ecc;
struct nand_chip *this = mtd->priv;
void __iomem *mmio_base = this->IO_ADDR_R;
ecc = readl(mmio_base + MM_NAND_STS);
ecc_code[1] = ecc >> 8;
ecc_code[0] = ecc >> 16;
ecc_code[2] = ecc >> 24;
return 0;
}
static struct mtd_info *cs553x_mtd[4];
static int __init cs553x_init_one(int cs, int mmio, unsigned long adr)
{
int err = 0;
struct nand_chip *this;
struct mtd_info *new_mtd;
printk(KERN_NOTICE "Probing CS553x NAND controller CS#%d at %sIO 0x%08lx\n", cs, mmio?"MM":"P", adr);
if (!mmio) {
printk(KERN_NOTICE "PIO mode not yet implemented for CS553X NAND controller\n");
return -ENXIO;
}
/* Allocate memory for MTD device structure and private data */
new_mtd = kmalloc(sizeof(struct mtd_info) + sizeof(struct nand_chip), GFP_KERNEL);
if (!new_mtd) {
printk(KERN_WARNING "Unable to allocate CS553X NAND MTD device structure.\n");
err = -ENOMEM;
goto out;
}
/* Get pointer to private data */
this = (struct nand_chip *)(&new_mtd[1]);
/* Initialize structures */
memset(new_mtd, 0, sizeof(struct mtd_info));
memset(this, 0, sizeof(struct nand_chip));
/* Link the private data with the MTD structure */
new_mtd->priv = this;
new_mtd->owner = THIS_MODULE;
/* map physical address */
this->IO_ADDR_R = this->IO_ADDR_W = ioremap(adr, 4096);
if (!this->IO_ADDR_R) {
printk(KERN_WARNING "ioremap cs553x NAND @0x%08lx failed\n", adr);
err = -EIO;
goto out_mtd;
}
this->cmd_ctrl = cs553x_hwcontrol;
this->dev_ready = cs553x_device_ready;
this->read_byte = cs553x_read_byte;
this->read_buf = cs553x_read_buf;
this->write_buf = cs553x_write_buf;
this->chip_delay = 0;
this->ecc.mode = NAND_ECC_HW;
this->ecc.size = 256;
this->ecc.bytes = 3;
this->ecc.hwctl = cs_enable_hwecc;
this->ecc.calculate = cs_calculate_ecc;
this->ecc.correct = nand_correct_data;
/* Enable the following for a flash based bad block table */
this->bbt_options = NAND_BBT_USE_FLASH;
this->options = NAND_NO_AUTOINCR;
/* Scan to find existence of the device */
if (nand_scan(new_mtd, 1)) {
err = -ENXIO;
goto out_ior;
}
this->ecc.strength = 1;
new_mtd->name = kasprintf(GFP_KERNEL, "cs553x_nand_cs%d", cs);
cs553x_mtd[cs] = new_mtd;
goto out;
out_ior:
iounmap(this->IO_ADDR_R);
out_mtd:
kfree(new_mtd);
out:
return err;
}
static int is_geode(void)
{
/* These are the CPUs which will have a CS553[56] companion chip */
if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD &&
boot_cpu_data.x86 == 5 &&
boot_cpu_data.x86_model == 10)
return 1; /* Geode LX */
if ((boot_cpu_data.x86_vendor == X86_VENDOR_NSC ||
boot_cpu_data.x86_vendor == X86_VENDOR_CYRIX) &&
boot_cpu_data.x86 == 5 &&
boot_cpu_data.x86_model == 5)
return 1; /* Geode GX (née GX2) */
return 0;
}
static int __init cs553x_init(void)
{
int err = -ENXIO;
int i;
uint64_t val;
/* If the CPU isn't a Geode GX or LX, abort */
if (!is_geode())
return -ENXIO;
/* If it doesn't have the CS553[56], abort */
rdmsrl(MSR_DIVIL_GLD_CAP, val);
val &= ~0xFFULL;
if (val != CAP_CS5535 && val != CAP_CS5536)
return -ENXIO;
/* If it doesn't have the NAND controller enabled, abort */
rdmsrl(MSR_DIVIL_BALL_OPTS, val);
if (val & PIN_OPT_IDE) {
printk(KERN_INFO "CS553x NAND controller: Flash I/O not enabled in MSR_DIVIL_BALL_OPTS.\n");
return -ENXIO;
}
for (i = 0; i < NR_CS553X_CONTROLLERS; i++) {
rdmsrl(MSR_DIVIL_LBAR_FLSH0 + i, val);
if ((val & (FLSH_LBAR_EN|FLSH_NOR_NAND)) == (FLSH_LBAR_EN|FLSH_NOR_NAND))
err = cs553x_init_one(i, !!(val & FLSH_MEM_IO), val & 0xFFFFFFFF);
}
/* Register all devices together here. This means we can easily hack it to
do mtdconcat etc. if we want to. */
for (i = 0; i < NR_CS553X_CONTROLLERS; i++) {
if (cs553x_mtd[i]) {
/* If any devices registered, return success. Else the last error. */
mtd_device_parse_register(cs553x_mtd[i], NULL, NULL,
NULL, 0);
err = 0;
}
}
return err;
}
module_init(cs553x_init);
static void __exit cs553x_cleanup(void)
{
int i;
for (i = 0; i < NR_CS553X_CONTROLLERS; i++) {
struct mtd_info *mtd = cs553x_mtd[i];
struct nand_chip *this;
void __iomem *mmio_base;
if (!mtd)
continue;
this = cs553x_mtd[i]->priv;
mmio_base = this->IO_ADDR_R;
/* Release resources, unregister device */
nand_release(cs553x_mtd[i]);
kfree(cs553x_mtd[i]->name);
cs553x_mtd[i] = NULL;
/* unmap physical address */
iounmap(mmio_base);
/* Free the MTD device structure */
kfree(mtd);
}
}
module_exit(cs553x_cleanup);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("David Woodhouse <dwmw2@infradead.org>");
MODULE_DESCRIPTION("NAND controller driver for AMD CS5535/CS5536 companion chip");
| gpl-2.0 |
friedrich420/Note-3-AEL-Kernel-NEW-NG2-2 | kernel/power/fbearlysuspend.c | 3793 | 4455 | /* kernel/power/fbearlysuspend.c
*
* Copyright (C) 2005-2008 Google, Inc.
*
* 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/earlysuspend.h>
#include <linux/module.h>
#include <linux/wait.h>
#include "power.h"
#define MAX_BUF 100
static wait_queue_head_t fb_state_wq;
static int display = 1;
static DEFINE_SPINLOCK(fb_state_lock);
static enum {
FB_STATE_STOPPED_DRAWING,
FB_STATE_REQUEST_STOP_DRAWING,
FB_STATE_DRAWING_OK,
} fb_state;
/* tell userspace to stop drawing, wait for it to stop */
static void stop_drawing_early_suspend(struct early_suspend *h)
{
int ret;
unsigned long irq_flags;
spin_lock_irqsave(&fb_state_lock, irq_flags);
fb_state = FB_STATE_REQUEST_STOP_DRAWING;
spin_unlock_irqrestore(&fb_state_lock, irq_flags);
wake_up_all(&fb_state_wq);
ret = wait_event_timeout(fb_state_wq,
fb_state == FB_STATE_STOPPED_DRAWING,
HZ);
if (unlikely(fb_state != FB_STATE_STOPPED_DRAWING))
pr_warning("stop_drawing_early_suspend: timeout waiting for "
"userspace to stop drawing\n");
}
/* tell userspace to start drawing */
static void start_drawing_late_resume(struct early_suspend *h)
{
unsigned long irq_flags;
spin_lock_irqsave(&fb_state_lock, irq_flags);
fb_state = FB_STATE_DRAWING_OK;
spin_unlock_irqrestore(&fb_state_lock, irq_flags);
wake_up(&fb_state_wq);
}
static struct early_suspend stop_drawing_early_suspend_desc = {
.level = EARLY_SUSPEND_LEVEL_STOP_DRAWING,
.suspend = stop_drawing_early_suspend,
.resume = start_drawing_late_resume,
};
static ssize_t wait_for_fb_sleep_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
char *s = buf;
int ret;
ret = wait_event_interruptible(fb_state_wq,
fb_state != FB_STATE_DRAWING_OK);
if (ret && fb_state == FB_STATE_DRAWING_OK) {
return ret;
} else {
s += sprintf(buf, "sleeping");
if (display == 1) {
display = 0;
sysfs_notify(power_kobj, NULL, "wait_for_fb_status");
}
}
return s - buf;
}
static ssize_t wait_for_fb_wake_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
char *s = buf;
int ret;
unsigned long irq_flags;
spin_lock_irqsave(&fb_state_lock, irq_flags);
if (fb_state == FB_STATE_REQUEST_STOP_DRAWING) {
fb_state = FB_STATE_STOPPED_DRAWING;
wake_up(&fb_state_wq);
}
spin_unlock_irqrestore(&fb_state_lock, irq_flags);
ret = wait_event_interruptible(fb_state_wq,
fb_state == FB_STATE_DRAWING_OK);
if (ret && fb_state != FB_STATE_DRAWING_OK)
return ret;
else {
s += sprintf(buf, "awake");
if (display == 0) {
display = 1;
sysfs_notify(power_kobj, NULL, "wait_for_fb_status");
}
}
return s - buf;
}
static ssize_t wait_for_fb_status_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
int ret = 0;
if (display == 1)
ret = snprintf(buf, strnlen("on", MAX_BUF) + 1, "on");
else
ret = snprintf(buf, strnlen("off", MAX_BUF) + 1, "off");
return ret;
}
#define power_ro_attr(_name) \
static struct kobj_attribute _name##_attr = { \
.attr = { \
.name = __stringify(_name), \
.mode = 0444, \
}, \
.show = _name##_show, \
.store = NULL, \
}
power_ro_attr(wait_for_fb_sleep);
power_ro_attr(wait_for_fb_wake);
power_ro_attr(wait_for_fb_status);
static struct attribute *g[] = {
&wait_for_fb_sleep_attr.attr,
&wait_for_fb_wake_attr.attr,
&wait_for_fb_status_attr.attr,
NULL,
};
static struct attribute_group attr_group = {
.attrs = g,
};
static int __init android_power_init(void)
{
int ret;
init_waitqueue_head(&fb_state_wq);
fb_state = FB_STATE_DRAWING_OK;
ret = sysfs_create_group(power_kobj, &attr_group);
if (ret) {
pr_err("android_power_init: sysfs_create_group failed\n");
return ret;
}
register_early_suspend(&stop_drawing_early_suspend_desc);
return 0;
}
static void __exit android_power_exit(void)
{
unregister_early_suspend(&stop_drawing_early_suspend_desc);
sysfs_remove_group(power_kobj, &attr_group);
}
module_init(android_power_init);
module_exit(android_power_exit);
| gpl-2.0 |
joni2012/joni | drivers/gpu/drm/radeon/r300.c | 4049 | 43236 | /*
* Copyright 2008 Advanced Micro Devices, Inc.
* Copyright 2008 Red Hat Inc.
* Copyright 2009 Jerome Glisse.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Dave Airlie
* Alex Deucher
* Jerome Glisse
*/
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <drm/drmP.h>
#include <drm/drm.h>
#include <drm/drm_crtc_helper.h>
#include "radeon_reg.h"
#include "radeon.h"
#include "radeon_asic.h"
#include "radeon_drm.h"
#include "r100_track.h"
#include "r300d.h"
#include "rv350d.h"
#include "r300_reg_safe.h"
/* This files gather functions specifics to: r300,r350,rv350,rv370,rv380
*
* GPU Errata:
* - HOST_PATH_CNTL: r300 family seems to dislike write to HOST_PATH_CNTL
* using MMIO to flush host path read cache, this lead to HARDLOCKUP.
* However, scheduling such write to the ring seems harmless, i suspect
* the CP read collide with the flush somehow, or maybe the MC, hard to
* tell. (Jerome Glisse)
*/
/*
* rv370,rv380 PCIE GART
*/
static int rv370_debugfs_pcie_gart_info_init(struct radeon_device *rdev);
void rv370_pcie_gart_tlb_flush(struct radeon_device *rdev)
{
uint32_t tmp;
int i;
/* Workaround HW bug do flush 2 times */
for (i = 0; i < 2; i++) {
tmp = RREG32_PCIE(RADEON_PCIE_TX_GART_CNTL);
WREG32_PCIE(RADEON_PCIE_TX_GART_CNTL, tmp | RADEON_PCIE_TX_GART_INVALIDATE_TLB);
(void)RREG32_PCIE(RADEON_PCIE_TX_GART_CNTL);
WREG32_PCIE(RADEON_PCIE_TX_GART_CNTL, tmp);
}
mb();
}
#define R300_PTE_WRITEABLE (1 << 2)
#define R300_PTE_READABLE (1 << 3)
int rv370_pcie_gart_set_page(struct radeon_device *rdev, int i, uint64_t addr)
{
void __iomem *ptr = rdev->gart.ptr;
if (i < 0 || i > rdev->gart.num_gpu_pages) {
return -EINVAL;
}
addr = (lower_32_bits(addr) >> 8) |
((upper_32_bits(addr) & 0xff) << 24) |
R300_PTE_WRITEABLE | R300_PTE_READABLE;
/* on x86 we want this to be CPU endian, on powerpc
* on powerpc without HW swappers, it'll get swapped on way
* into VRAM - so no need for cpu_to_le32 on VRAM tables */
writel(addr, ((void __iomem *)ptr) + (i * 4));
return 0;
}
int rv370_pcie_gart_init(struct radeon_device *rdev)
{
int r;
if (rdev->gart.robj) {
WARN(1, "RV370 PCIE GART already initialized\n");
return 0;
}
/* Initialize common gart structure */
r = radeon_gart_init(rdev);
if (r)
return r;
r = rv370_debugfs_pcie_gart_info_init(rdev);
if (r)
DRM_ERROR("Failed to register debugfs file for PCIE gart !\n");
rdev->gart.table_size = rdev->gart.num_gpu_pages * 4;
rdev->asic->gart.tlb_flush = &rv370_pcie_gart_tlb_flush;
rdev->asic->gart.set_page = &rv370_pcie_gart_set_page;
return radeon_gart_table_vram_alloc(rdev);
}
int rv370_pcie_gart_enable(struct radeon_device *rdev)
{
uint32_t table_addr;
uint32_t tmp;
int r;
if (rdev->gart.robj == NULL) {
dev_err(rdev->dev, "No VRAM object for PCIE GART.\n");
return -EINVAL;
}
r = radeon_gart_table_vram_pin(rdev);
if (r)
return r;
radeon_gart_restore(rdev);
/* discard memory request outside of configured range */
tmp = RADEON_PCIE_TX_GART_UNMAPPED_ACCESS_DISCARD;
WREG32_PCIE(RADEON_PCIE_TX_GART_CNTL, tmp);
WREG32_PCIE(RADEON_PCIE_TX_GART_START_LO, rdev->mc.gtt_start);
tmp = rdev->mc.gtt_end & ~RADEON_GPU_PAGE_MASK;
WREG32_PCIE(RADEON_PCIE_TX_GART_END_LO, tmp);
WREG32_PCIE(RADEON_PCIE_TX_GART_START_HI, 0);
WREG32_PCIE(RADEON_PCIE_TX_GART_END_HI, 0);
table_addr = rdev->gart.table_addr;
WREG32_PCIE(RADEON_PCIE_TX_GART_BASE, table_addr);
/* FIXME: setup default page */
WREG32_PCIE(RADEON_PCIE_TX_DISCARD_RD_ADDR_LO, rdev->mc.vram_start);
WREG32_PCIE(RADEON_PCIE_TX_DISCARD_RD_ADDR_HI, 0);
/* Clear error */
WREG32_PCIE(RADEON_PCIE_TX_GART_ERROR, 0);
tmp = RREG32_PCIE(RADEON_PCIE_TX_GART_CNTL);
tmp |= RADEON_PCIE_TX_GART_EN;
tmp |= RADEON_PCIE_TX_GART_UNMAPPED_ACCESS_DISCARD;
WREG32_PCIE(RADEON_PCIE_TX_GART_CNTL, tmp);
rv370_pcie_gart_tlb_flush(rdev);
DRM_INFO("PCIE GART of %uM enabled (table at 0x%016llX).\n",
(unsigned)(rdev->mc.gtt_size >> 20),
(unsigned long long)table_addr);
rdev->gart.ready = true;
return 0;
}
void rv370_pcie_gart_disable(struct radeon_device *rdev)
{
u32 tmp;
WREG32_PCIE(RADEON_PCIE_TX_GART_START_LO, 0);
WREG32_PCIE(RADEON_PCIE_TX_GART_END_LO, 0);
WREG32_PCIE(RADEON_PCIE_TX_GART_START_HI, 0);
WREG32_PCIE(RADEON_PCIE_TX_GART_END_HI, 0);
tmp = RREG32_PCIE(RADEON_PCIE_TX_GART_CNTL);
tmp |= RADEON_PCIE_TX_GART_UNMAPPED_ACCESS_DISCARD;
WREG32_PCIE(RADEON_PCIE_TX_GART_CNTL, tmp & ~RADEON_PCIE_TX_GART_EN);
radeon_gart_table_vram_unpin(rdev);
}
void rv370_pcie_gart_fini(struct radeon_device *rdev)
{
radeon_gart_fini(rdev);
rv370_pcie_gart_disable(rdev);
radeon_gart_table_vram_free(rdev);
}
void r300_fence_ring_emit(struct radeon_device *rdev,
struct radeon_fence *fence)
{
struct radeon_ring *ring = &rdev->ring[fence->ring];
/* Who ever call radeon_fence_emit should call ring_lock and ask
* for enough space (today caller are ib schedule and buffer move) */
/* Write SC register so SC & US assert idle */
radeon_ring_write(ring, PACKET0(R300_RE_SCISSORS_TL, 0));
radeon_ring_write(ring, 0);
radeon_ring_write(ring, PACKET0(R300_RE_SCISSORS_BR, 0));
radeon_ring_write(ring, 0);
/* Flush 3D cache */
radeon_ring_write(ring, PACKET0(R300_RB3D_DSTCACHE_CTLSTAT, 0));
radeon_ring_write(ring, R300_RB3D_DC_FLUSH);
radeon_ring_write(ring, PACKET0(R300_RB3D_ZCACHE_CTLSTAT, 0));
radeon_ring_write(ring, R300_ZC_FLUSH);
/* Wait until IDLE & CLEAN */
radeon_ring_write(ring, PACKET0(RADEON_WAIT_UNTIL, 0));
radeon_ring_write(ring, (RADEON_WAIT_3D_IDLECLEAN |
RADEON_WAIT_2D_IDLECLEAN |
RADEON_WAIT_DMA_GUI_IDLE));
radeon_ring_write(ring, PACKET0(RADEON_HOST_PATH_CNTL, 0));
radeon_ring_write(ring, rdev->config.r300.hdp_cntl |
RADEON_HDP_READ_BUFFER_INVALIDATE);
radeon_ring_write(ring, PACKET0(RADEON_HOST_PATH_CNTL, 0));
radeon_ring_write(ring, rdev->config.r300.hdp_cntl);
/* Emit fence sequence & fire IRQ */
radeon_ring_write(ring, PACKET0(rdev->fence_drv[fence->ring].scratch_reg, 0));
radeon_ring_write(ring, fence->seq);
radeon_ring_write(ring, PACKET0(RADEON_GEN_INT_STATUS, 0));
radeon_ring_write(ring, RADEON_SW_INT_FIRE);
}
void r300_ring_start(struct radeon_device *rdev, struct radeon_ring *ring)
{
unsigned gb_tile_config;
int r;
/* Sub pixel 1/12 so we can have 4K rendering according to doc */
gb_tile_config = (R300_ENABLE_TILING | R300_TILE_SIZE_16);
switch(rdev->num_gb_pipes) {
case 2:
gb_tile_config |= R300_PIPE_COUNT_R300;
break;
case 3:
gb_tile_config |= R300_PIPE_COUNT_R420_3P;
break;
case 4:
gb_tile_config |= R300_PIPE_COUNT_R420;
break;
case 1:
default:
gb_tile_config |= R300_PIPE_COUNT_RV350;
break;
}
r = radeon_ring_lock(rdev, ring, 64);
if (r) {
return;
}
radeon_ring_write(ring, PACKET0(RADEON_ISYNC_CNTL, 0));
radeon_ring_write(ring,
RADEON_ISYNC_ANY2D_IDLE3D |
RADEON_ISYNC_ANY3D_IDLE2D |
RADEON_ISYNC_WAIT_IDLEGUI |
RADEON_ISYNC_CPSCRATCH_IDLEGUI);
radeon_ring_write(ring, PACKET0(R300_GB_TILE_CONFIG, 0));
radeon_ring_write(ring, gb_tile_config);
radeon_ring_write(ring, PACKET0(RADEON_WAIT_UNTIL, 0));
radeon_ring_write(ring,
RADEON_WAIT_2D_IDLECLEAN |
RADEON_WAIT_3D_IDLECLEAN);
radeon_ring_write(ring, PACKET0(R300_DST_PIPE_CONFIG, 0));
radeon_ring_write(ring, R300_PIPE_AUTO_CONFIG);
radeon_ring_write(ring, PACKET0(R300_GB_SELECT, 0));
radeon_ring_write(ring, 0);
radeon_ring_write(ring, PACKET0(R300_GB_ENABLE, 0));
radeon_ring_write(ring, 0);
radeon_ring_write(ring, PACKET0(R300_RB3D_DSTCACHE_CTLSTAT, 0));
radeon_ring_write(ring, R300_RB3D_DC_FLUSH | R300_RB3D_DC_FREE);
radeon_ring_write(ring, PACKET0(R300_RB3D_ZCACHE_CTLSTAT, 0));
radeon_ring_write(ring, R300_ZC_FLUSH | R300_ZC_FREE);
radeon_ring_write(ring, PACKET0(RADEON_WAIT_UNTIL, 0));
radeon_ring_write(ring,
RADEON_WAIT_2D_IDLECLEAN |
RADEON_WAIT_3D_IDLECLEAN);
radeon_ring_write(ring, PACKET0(R300_GB_AA_CONFIG, 0));
radeon_ring_write(ring, 0);
radeon_ring_write(ring, PACKET0(R300_RB3D_DSTCACHE_CTLSTAT, 0));
radeon_ring_write(ring, R300_RB3D_DC_FLUSH | R300_RB3D_DC_FREE);
radeon_ring_write(ring, PACKET0(R300_RB3D_ZCACHE_CTLSTAT, 0));
radeon_ring_write(ring, R300_ZC_FLUSH | R300_ZC_FREE);
radeon_ring_write(ring, PACKET0(R300_GB_MSPOS0, 0));
radeon_ring_write(ring,
((6 << R300_MS_X0_SHIFT) |
(6 << R300_MS_Y0_SHIFT) |
(6 << R300_MS_X1_SHIFT) |
(6 << R300_MS_Y1_SHIFT) |
(6 << R300_MS_X2_SHIFT) |
(6 << R300_MS_Y2_SHIFT) |
(6 << R300_MSBD0_Y_SHIFT) |
(6 << R300_MSBD0_X_SHIFT)));
radeon_ring_write(ring, PACKET0(R300_GB_MSPOS1, 0));
radeon_ring_write(ring,
((6 << R300_MS_X3_SHIFT) |
(6 << R300_MS_Y3_SHIFT) |
(6 << R300_MS_X4_SHIFT) |
(6 << R300_MS_Y4_SHIFT) |
(6 << R300_MS_X5_SHIFT) |
(6 << R300_MS_Y5_SHIFT) |
(6 << R300_MSBD1_SHIFT)));
radeon_ring_write(ring, PACKET0(R300_GA_ENHANCE, 0));
radeon_ring_write(ring, R300_GA_DEADLOCK_CNTL | R300_GA_FASTSYNC_CNTL);
radeon_ring_write(ring, PACKET0(R300_GA_POLY_MODE, 0));
radeon_ring_write(ring,
R300_FRONT_PTYPE_TRIANGE | R300_BACK_PTYPE_TRIANGE);
radeon_ring_write(ring, PACKET0(R300_GA_ROUND_MODE, 0));
radeon_ring_write(ring,
R300_GEOMETRY_ROUND_NEAREST |
R300_COLOR_ROUND_NEAREST);
radeon_ring_unlock_commit(rdev, ring);
}
void r300_errata(struct radeon_device *rdev)
{
rdev->pll_errata = 0;
if (rdev->family == CHIP_R300 &&
(RREG32(RADEON_CONFIG_CNTL) & RADEON_CFG_ATI_REV_ID_MASK) == RADEON_CFG_ATI_REV_A11) {
rdev->pll_errata |= CHIP_ERRATA_R300_CG;
}
}
int r300_mc_wait_for_idle(struct radeon_device *rdev)
{
unsigned i;
uint32_t tmp;
for (i = 0; i < rdev->usec_timeout; i++) {
/* read MC_STATUS */
tmp = RREG32(RADEON_MC_STATUS);
if (tmp & R300_MC_IDLE) {
return 0;
}
DRM_UDELAY(1);
}
return -1;
}
void r300_gpu_init(struct radeon_device *rdev)
{
uint32_t gb_tile_config, tmp;
if ((rdev->family == CHIP_R300 && rdev->pdev->device != 0x4144) ||
(rdev->family == CHIP_R350 && rdev->pdev->device != 0x4148)) {
/* r300,r350 */
rdev->num_gb_pipes = 2;
} else {
/* rv350,rv370,rv380,r300 AD, r350 AH */
rdev->num_gb_pipes = 1;
}
rdev->num_z_pipes = 1;
gb_tile_config = (R300_ENABLE_TILING | R300_TILE_SIZE_16);
switch (rdev->num_gb_pipes) {
case 2:
gb_tile_config |= R300_PIPE_COUNT_R300;
break;
case 3:
gb_tile_config |= R300_PIPE_COUNT_R420_3P;
break;
case 4:
gb_tile_config |= R300_PIPE_COUNT_R420;
break;
default:
case 1:
gb_tile_config |= R300_PIPE_COUNT_RV350;
break;
}
WREG32(R300_GB_TILE_CONFIG, gb_tile_config);
if (r100_gui_wait_for_idle(rdev)) {
printk(KERN_WARNING "Failed to wait GUI idle while "
"programming pipes. Bad things might happen.\n");
}
tmp = RREG32(R300_DST_PIPE_CONFIG);
WREG32(R300_DST_PIPE_CONFIG, tmp | R300_PIPE_AUTO_CONFIG);
WREG32(R300_RB2D_DSTCACHE_MODE,
R300_DC_AUTOFLUSH_ENABLE |
R300_DC_DC_DISABLE_IGNORE_PE);
if (r100_gui_wait_for_idle(rdev)) {
printk(KERN_WARNING "Failed to wait GUI idle while "
"programming pipes. Bad things might happen.\n");
}
if (r300_mc_wait_for_idle(rdev)) {
printk(KERN_WARNING "Failed to wait MC idle while "
"programming pipes. Bad things might happen.\n");
}
DRM_INFO("radeon: %d quad pipes, %d Z pipes initialized.\n",
rdev->num_gb_pipes, rdev->num_z_pipes);
}
bool r300_gpu_is_lockup(struct radeon_device *rdev, struct radeon_ring *ring)
{
u32 rbbm_status;
int r;
rbbm_status = RREG32(R_000E40_RBBM_STATUS);
if (!G_000E40_GUI_ACTIVE(rbbm_status)) {
r100_gpu_lockup_update(&rdev->config.r300.lockup, ring);
return false;
}
/* force CP activities */
r = radeon_ring_lock(rdev, ring, 2);
if (!r) {
/* PACKET2 NOP */
radeon_ring_write(ring, 0x80000000);
radeon_ring_write(ring, 0x80000000);
radeon_ring_unlock_commit(rdev, ring);
}
ring->rptr = RREG32(RADEON_CP_RB_RPTR);
return r100_gpu_cp_is_lockup(rdev, &rdev->config.r300.lockup, ring);
}
int r300_asic_reset(struct radeon_device *rdev)
{
struct r100_mc_save save;
u32 status, tmp;
int ret = 0;
status = RREG32(R_000E40_RBBM_STATUS);
if (!G_000E40_GUI_ACTIVE(status)) {
return 0;
}
r100_mc_stop(rdev, &save);
status = RREG32(R_000E40_RBBM_STATUS);
dev_info(rdev->dev, "(%s:%d) RBBM_STATUS=0x%08X\n", __func__, __LINE__, status);
/* stop CP */
WREG32(RADEON_CP_CSQ_CNTL, 0);
tmp = RREG32(RADEON_CP_RB_CNTL);
WREG32(RADEON_CP_RB_CNTL, tmp | RADEON_RB_RPTR_WR_ENA);
WREG32(RADEON_CP_RB_RPTR_WR, 0);
WREG32(RADEON_CP_RB_WPTR, 0);
WREG32(RADEON_CP_RB_CNTL, tmp);
/* save PCI state */
pci_save_state(rdev->pdev);
/* disable bus mastering */
r100_bm_disable(rdev);
WREG32(R_0000F0_RBBM_SOFT_RESET, S_0000F0_SOFT_RESET_VAP(1) |
S_0000F0_SOFT_RESET_GA(1));
RREG32(R_0000F0_RBBM_SOFT_RESET);
mdelay(500);
WREG32(R_0000F0_RBBM_SOFT_RESET, 0);
mdelay(1);
status = RREG32(R_000E40_RBBM_STATUS);
dev_info(rdev->dev, "(%s:%d) RBBM_STATUS=0x%08X\n", __func__, __LINE__, status);
/* resetting the CP seems to be problematic sometimes it end up
* hard locking the computer, but it's necessary for successful
* reset more test & playing is needed on R3XX/R4XX to find a
* reliable (if any solution)
*/
WREG32(R_0000F0_RBBM_SOFT_RESET, S_0000F0_SOFT_RESET_CP(1));
RREG32(R_0000F0_RBBM_SOFT_RESET);
mdelay(500);
WREG32(R_0000F0_RBBM_SOFT_RESET, 0);
mdelay(1);
status = RREG32(R_000E40_RBBM_STATUS);
dev_info(rdev->dev, "(%s:%d) RBBM_STATUS=0x%08X\n", __func__, __LINE__, status);
/* restore PCI & busmastering */
pci_restore_state(rdev->pdev);
r100_enable_bm(rdev);
/* Check if GPU is idle */
if (G_000E40_GA_BUSY(status) || G_000E40_VAP_BUSY(status)) {
dev_err(rdev->dev, "failed to reset GPU\n");
rdev->gpu_lockup = true;
ret = -1;
} else
dev_info(rdev->dev, "GPU reset succeed\n");
r100_mc_resume(rdev, &save);
return ret;
}
/*
* r300,r350,rv350,rv380 VRAM info
*/
void r300_mc_init(struct radeon_device *rdev)
{
u64 base;
u32 tmp;
/* DDR for all card after R300 & IGP */
rdev->mc.vram_is_ddr = true;
tmp = RREG32(RADEON_MEM_CNTL);
tmp &= R300_MEM_NUM_CHANNELS_MASK;
switch (tmp) {
case 0: rdev->mc.vram_width = 64; break;
case 1: rdev->mc.vram_width = 128; break;
case 2: rdev->mc.vram_width = 256; break;
default: rdev->mc.vram_width = 128; break;
}
r100_vram_init_sizes(rdev);
base = rdev->mc.aper_base;
if (rdev->flags & RADEON_IS_IGP)
base = (RREG32(RADEON_NB_TOM) & 0xffff) << 16;
radeon_vram_location(rdev, &rdev->mc, base);
rdev->mc.gtt_base_align = 0;
if (!(rdev->flags & RADEON_IS_AGP))
radeon_gtt_location(rdev, &rdev->mc);
radeon_update_bandwidth_info(rdev);
}
void rv370_set_pcie_lanes(struct radeon_device *rdev, int lanes)
{
uint32_t link_width_cntl, mask;
if (rdev->flags & RADEON_IS_IGP)
return;
if (!(rdev->flags & RADEON_IS_PCIE))
return;
/* FIXME wait for idle */
switch (lanes) {
case 0:
mask = RADEON_PCIE_LC_LINK_WIDTH_X0;
break;
case 1:
mask = RADEON_PCIE_LC_LINK_WIDTH_X1;
break;
case 2:
mask = RADEON_PCIE_LC_LINK_WIDTH_X2;
break;
case 4:
mask = RADEON_PCIE_LC_LINK_WIDTH_X4;
break;
case 8:
mask = RADEON_PCIE_LC_LINK_WIDTH_X8;
break;
case 12:
mask = RADEON_PCIE_LC_LINK_WIDTH_X12;
break;
case 16:
default:
mask = RADEON_PCIE_LC_LINK_WIDTH_X16;
break;
}
link_width_cntl = RREG32_PCIE(RADEON_PCIE_LC_LINK_WIDTH_CNTL);
if ((link_width_cntl & RADEON_PCIE_LC_LINK_WIDTH_RD_MASK) ==
(mask << RADEON_PCIE_LC_LINK_WIDTH_RD_SHIFT))
return;
link_width_cntl &= ~(RADEON_PCIE_LC_LINK_WIDTH_MASK |
RADEON_PCIE_LC_RECONFIG_NOW |
RADEON_PCIE_LC_RECONFIG_LATER |
RADEON_PCIE_LC_SHORT_RECONFIG_EN);
link_width_cntl |= mask;
WREG32_PCIE(RADEON_PCIE_LC_LINK_WIDTH_CNTL, link_width_cntl);
WREG32_PCIE(RADEON_PCIE_LC_LINK_WIDTH_CNTL, (link_width_cntl |
RADEON_PCIE_LC_RECONFIG_NOW));
/* wait for lane set to complete */
link_width_cntl = RREG32_PCIE(RADEON_PCIE_LC_LINK_WIDTH_CNTL);
while (link_width_cntl == 0xffffffff)
link_width_cntl = RREG32_PCIE(RADEON_PCIE_LC_LINK_WIDTH_CNTL);
}
int rv370_get_pcie_lanes(struct radeon_device *rdev)
{
u32 link_width_cntl;
if (rdev->flags & RADEON_IS_IGP)
return 0;
if (!(rdev->flags & RADEON_IS_PCIE))
return 0;
/* FIXME wait for idle */
link_width_cntl = RREG32_PCIE(RADEON_PCIE_LC_LINK_WIDTH_CNTL);
switch ((link_width_cntl & RADEON_PCIE_LC_LINK_WIDTH_RD_MASK) >> RADEON_PCIE_LC_LINK_WIDTH_RD_SHIFT) {
case RADEON_PCIE_LC_LINK_WIDTH_X0:
return 0;
case RADEON_PCIE_LC_LINK_WIDTH_X1:
return 1;
case RADEON_PCIE_LC_LINK_WIDTH_X2:
return 2;
case RADEON_PCIE_LC_LINK_WIDTH_X4:
return 4;
case RADEON_PCIE_LC_LINK_WIDTH_X8:
return 8;
case RADEON_PCIE_LC_LINK_WIDTH_X16:
default:
return 16;
}
}
#if defined(CONFIG_DEBUG_FS)
static int rv370_debugfs_pcie_gart_info(struct seq_file *m, void *data)
{
struct drm_info_node *node = (struct drm_info_node *) m->private;
struct drm_device *dev = node->minor->dev;
struct radeon_device *rdev = dev->dev_private;
uint32_t tmp;
tmp = RREG32_PCIE(RADEON_PCIE_TX_GART_CNTL);
seq_printf(m, "PCIE_TX_GART_CNTL 0x%08x\n", tmp);
tmp = RREG32_PCIE(RADEON_PCIE_TX_GART_BASE);
seq_printf(m, "PCIE_TX_GART_BASE 0x%08x\n", tmp);
tmp = RREG32_PCIE(RADEON_PCIE_TX_GART_START_LO);
seq_printf(m, "PCIE_TX_GART_START_LO 0x%08x\n", tmp);
tmp = RREG32_PCIE(RADEON_PCIE_TX_GART_START_HI);
seq_printf(m, "PCIE_TX_GART_START_HI 0x%08x\n", tmp);
tmp = RREG32_PCIE(RADEON_PCIE_TX_GART_END_LO);
seq_printf(m, "PCIE_TX_GART_END_LO 0x%08x\n", tmp);
tmp = RREG32_PCIE(RADEON_PCIE_TX_GART_END_HI);
seq_printf(m, "PCIE_TX_GART_END_HI 0x%08x\n", tmp);
tmp = RREG32_PCIE(RADEON_PCIE_TX_GART_ERROR);
seq_printf(m, "PCIE_TX_GART_ERROR 0x%08x\n", tmp);
return 0;
}
static struct drm_info_list rv370_pcie_gart_info_list[] = {
{"rv370_pcie_gart_info", rv370_debugfs_pcie_gart_info, 0, NULL},
};
#endif
static int rv370_debugfs_pcie_gart_info_init(struct radeon_device *rdev)
{
#if defined(CONFIG_DEBUG_FS)
return radeon_debugfs_add_files(rdev, rv370_pcie_gart_info_list, 1);
#else
return 0;
#endif
}
static int r300_packet0_check(struct radeon_cs_parser *p,
struct radeon_cs_packet *pkt,
unsigned idx, unsigned reg)
{
struct radeon_cs_reloc *reloc;
struct r100_cs_track *track;
volatile uint32_t *ib;
uint32_t tmp, tile_flags = 0;
unsigned i;
int r;
u32 idx_value;
ib = p->ib->ptr;
track = (struct r100_cs_track *)p->track;
idx_value = radeon_get_ib_value(p, idx);
switch(reg) {
case AVIVO_D1MODE_VLINE_START_END:
case RADEON_CRTC_GUI_TRIG_VLINE:
r = r100_cs_packet_parse_vline(p);
if (r) {
DRM_ERROR("No reloc for ib[%d]=0x%04X\n",
idx, reg);
r100_cs_dump_packet(p, pkt);
return r;
}
break;
case RADEON_DST_PITCH_OFFSET:
case RADEON_SRC_PITCH_OFFSET:
r = r100_reloc_pitch_offset(p, pkt, idx, reg);
if (r)
return r;
break;
case R300_RB3D_COLOROFFSET0:
case R300_RB3D_COLOROFFSET1:
case R300_RB3D_COLOROFFSET2:
case R300_RB3D_COLOROFFSET3:
i = (reg - R300_RB3D_COLOROFFSET0) >> 2;
r = r100_cs_packet_next_reloc(p, &reloc);
if (r) {
DRM_ERROR("No reloc for ib[%d]=0x%04X\n",
idx, reg);
r100_cs_dump_packet(p, pkt);
return r;
}
track->cb[i].robj = reloc->robj;
track->cb[i].offset = idx_value;
track->cb_dirty = true;
ib[idx] = idx_value + ((u32)reloc->lobj.gpu_offset);
break;
case R300_ZB_DEPTHOFFSET:
r = r100_cs_packet_next_reloc(p, &reloc);
if (r) {
DRM_ERROR("No reloc for ib[%d]=0x%04X\n",
idx, reg);
r100_cs_dump_packet(p, pkt);
return r;
}
track->zb.robj = reloc->robj;
track->zb.offset = idx_value;
track->zb_dirty = true;
ib[idx] = idx_value + ((u32)reloc->lobj.gpu_offset);
break;
case R300_TX_OFFSET_0:
case R300_TX_OFFSET_0+4:
case R300_TX_OFFSET_0+8:
case R300_TX_OFFSET_0+12:
case R300_TX_OFFSET_0+16:
case R300_TX_OFFSET_0+20:
case R300_TX_OFFSET_0+24:
case R300_TX_OFFSET_0+28:
case R300_TX_OFFSET_0+32:
case R300_TX_OFFSET_0+36:
case R300_TX_OFFSET_0+40:
case R300_TX_OFFSET_0+44:
case R300_TX_OFFSET_0+48:
case R300_TX_OFFSET_0+52:
case R300_TX_OFFSET_0+56:
case R300_TX_OFFSET_0+60:
i = (reg - R300_TX_OFFSET_0) >> 2;
r = r100_cs_packet_next_reloc(p, &reloc);
if (r) {
DRM_ERROR("No reloc for ib[%d]=0x%04X\n",
idx, reg);
r100_cs_dump_packet(p, pkt);
return r;
}
if (p->cs_flags & RADEON_CS_KEEP_TILING_FLAGS) {
ib[idx] = (idx_value & 31) | /* keep the 1st 5 bits */
((idx_value & ~31) + (u32)reloc->lobj.gpu_offset);
} else {
if (reloc->lobj.tiling_flags & RADEON_TILING_MACRO)
tile_flags |= R300_TXO_MACRO_TILE;
if (reloc->lobj.tiling_flags & RADEON_TILING_MICRO)
tile_flags |= R300_TXO_MICRO_TILE;
else if (reloc->lobj.tiling_flags & RADEON_TILING_MICRO_SQUARE)
tile_flags |= R300_TXO_MICRO_TILE_SQUARE;
tmp = idx_value + ((u32)reloc->lobj.gpu_offset);
tmp |= tile_flags;
ib[idx] = tmp;
}
track->textures[i].robj = reloc->robj;
track->tex_dirty = true;
break;
/* Tracked registers */
case 0x2084:
/* VAP_VF_CNTL */
track->vap_vf_cntl = idx_value;
break;
case 0x20B4:
/* VAP_VTX_SIZE */
track->vtx_size = idx_value & 0x7F;
break;
case 0x2134:
/* VAP_VF_MAX_VTX_INDX */
track->max_indx = idx_value & 0x00FFFFFFUL;
break;
case 0x2088:
/* VAP_ALT_NUM_VERTICES - only valid on r500 */
if (p->rdev->family < CHIP_RV515)
goto fail;
track->vap_alt_nverts = idx_value & 0xFFFFFF;
break;
case 0x43E4:
/* SC_SCISSOR1 */
track->maxy = ((idx_value >> 13) & 0x1FFF) + 1;
if (p->rdev->family < CHIP_RV515) {
track->maxy -= 1440;
}
track->cb_dirty = true;
track->zb_dirty = true;
break;
case 0x4E00:
/* RB3D_CCTL */
if ((idx_value & (1 << 10)) && /* CMASK_ENABLE */
p->rdev->cmask_filp != p->filp) {
DRM_ERROR("Invalid RB3D_CCTL: Cannot enable CMASK.\n");
return -EINVAL;
}
track->num_cb = ((idx_value >> 5) & 0x3) + 1;
track->cb_dirty = true;
break;
case 0x4E38:
case 0x4E3C:
case 0x4E40:
case 0x4E44:
/* RB3D_COLORPITCH0 */
/* RB3D_COLORPITCH1 */
/* RB3D_COLORPITCH2 */
/* RB3D_COLORPITCH3 */
if (!(p->cs_flags & RADEON_CS_KEEP_TILING_FLAGS)) {
r = r100_cs_packet_next_reloc(p, &reloc);
if (r) {
DRM_ERROR("No reloc for ib[%d]=0x%04X\n",
idx, reg);
r100_cs_dump_packet(p, pkt);
return r;
}
if (reloc->lobj.tiling_flags & RADEON_TILING_MACRO)
tile_flags |= R300_COLOR_TILE_ENABLE;
if (reloc->lobj.tiling_flags & RADEON_TILING_MICRO)
tile_flags |= R300_COLOR_MICROTILE_ENABLE;
else if (reloc->lobj.tiling_flags & RADEON_TILING_MICRO_SQUARE)
tile_flags |= R300_COLOR_MICROTILE_SQUARE_ENABLE;
tmp = idx_value & ~(0x7 << 16);
tmp |= tile_flags;
ib[idx] = tmp;
}
i = (reg - 0x4E38) >> 2;
track->cb[i].pitch = idx_value & 0x3FFE;
switch (((idx_value >> 21) & 0xF)) {
case 9:
case 11:
case 12:
track->cb[i].cpp = 1;
break;
case 3:
case 4:
case 13:
case 15:
track->cb[i].cpp = 2;
break;
case 5:
if (p->rdev->family < CHIP_RV515) {
DRM_ERROR("Invalid color buffer format (%d)!\n",
((idx_value >> 21) & 0xF));
return -EINVAL;
}
/* Pass through. */
case 6:
track->cb[i].cpp = 4;
break;
case 10:
track->cb[i].cpp = 8;
break;
case 7:
track->cb[i].cpp = 16;
break;
default:
DRM_ERROR("Invalid color buffer format (%d) !\n",
((idx_value >> 21) & 0xF));
return -EINVAL;
}
track->cb_dirty = true;
break;
case 0x4F00:
/* ZB_CNTL */
if (idx_value & 2) {
track->z_enabled = true;
} else {
track->z_enabled = false;
}
track->zb_dirty = true;
break;
case 0x4F10:
/* ZB_FORMAT */
switch ((idx_value & 0xF)) {
case 0:
case 1:
track->zb.cpp = 2;
break;
case 2:
track->zb.cpp = 4;
break;
default:
DRM_ERROR("Invalid z buffer format (%d) !\n",
(idx_value & 0xF));
return -EINVAL;
}
track->zb_dirty = true;
break;
case 0x4F24:
/* ZB_DEPTHPITCH */
if (!(p->cs_flags & RADEON_CS_KEEP_TILING_FLAGS)) {
r = r100_cs_packet_next_reloc(p, &reloc);
if (r) {
DRM_ERROR("No reloc for ib[%d]=0x%04X\n",
idx, reg);
r100_cs_dump_packet(p, pkt);
return r;
}
if (reloc->lobj.tiling_flags & RADEON_TILING_MACRO)
tile_flags |= R300_DEPTHMACROTILE_ENABLE;
if (reloc->lobj.tiling_flags & RADEON_TILING_MICRO)
tile_flags |= R300_DEPTHMICROTILE_TILED;
else if (reloc->lobj.tiling_flags & RADEON_TILING_MICRO_SQUARE)
tile_flags |= R300_DEPTHMICROTILE_TILED_SQUARE;
tmp = idx_value & ~(0x7 << 16);
tmp |= tile_flags;
ib[idx] = tmp;
}
track->zb.pitch = idx_value & 0x3FFC;
track->zb_dirty = true;
break;
case 0x4104:
/* TX_ENABLE */
for (i = 0; i < 16; i++) {
bool enabled;
enabled = !!(idx_value & (1 << i));
track->textures[i].enabled = enabled;
}
track->tex_dirty = true;
break;
case 0x44C0:
case 0x44C4:
case 0x44C8:
case 0x44CC:
case 0x44D0:
case 0x44D4:
case 0x44D8:
case 0x44DC:
case 0x44E0:
case 0x44E4:
case 0x44E8:
case 0x44EC:
case 0x44F0:
case 0x44F4:
case 0x44F8:
case 0x44FC:
/* TX_FORMAT1_[0-15] */
i = (reg - 0x44C0) >> 2;
tmp = (idx_value >> 25) & 0x3;
track->textures[i].tex_coord_type = tmp;
switch ((idx_value & 0x1F)) {
case R300_TX_FORMAT_X8:
case R300_TX_FORMAT_Y4X4:
case R300_TX_FORMAT_Z3Y3X2:
track->textures[i].cpp = 1;
track->textures[i].compress_format = R100_TRACK_COMP_NONE;
break;
case R300_TX_FORMAT_X16:
case R300_TX_FORMAT_FL_I16:
case R300_TX_FORMAT_Y8X8:
case R300_TX_FORMAT_Z5Y6X5:
case R300_TX_FORMAT_Z6Y5X5:
case R300_TX_FORMAT_W4Z4Y4X4:
case R300_TX_FORMAT_W1Z5Y5X5:
case R300_TX_FORMAT_D3DMFT_CxV8U8:
case R300_TX_FORMAT_B8G8_B8G8:
case R300_TX_FORMAT_G8R8_G8B8:
track->textures[i].cpp = 2;
track->textures[i].compress_format = R100_TRACK_COMP_NONE;
break;
case R300_TX_FORMAT_Y16X16:
case R300_TX_FORMAT_FL_I16A16:
case R300_TX_FORMAT_Z11Y11X10:
case R300_TX_FORMAT_Z10Y11X11:
case R300_TX_FORMAT_W8Z8Y8X8:
case R300_TX_FORMAT_W2Z10Y10X10:
case 0x17:
case R300_TX_FORMAT_FL_I32:
case 0x1e:
track->textures[i].cpp = 4;
track->textures[i].compress_format = R100_TRACK_COMP_NONE;
break;
case R300_TX_FORMAT_W16Z16Y16X16:
case R300_TX_FORMAT_FL_R16G16B16A16:
case R300_TX_FORMAT_FL_I32A32:
track->textures[i].cpp = 8;
track->textures[i].compress_format = R100_TRACK_COMP_NONE;
break;
case R300_TX_FORMAT_FL_R32G32B32A32:
track->textures[i].cpp = 16;
track->textures[i].compress_format = R100_TRACK_COMP_NONE;
break;
case R300_TX_FORMAT_DXT1:
track->textures[i].cpp = 1;
track->textures[i].compress_format = R100_TRACK_COMP_DXT1;
break;
case R300_TX_FORMAT_ATI2N:
if (p->rdev->family < CHIP_R420) {
DRM_ERROR("Invalid texture format %u\n",
(idx_value & 0x1F));
return -EINVAL;
}
/* The same rules apply as for DXT3/5. */
/* Pass through. */
case R300_TX_FORMAT_DXT3:
case R300_TX_FORMAT_DXT5:
track->textures[i].cpp = 1;
track->textures[i].compress_format = R100_TRACK_COMP_DXT35;
break;
default:
DRM_ERROR("Invalid texture format %u\n",
(idx_value & 0x1F));
return -EINVAL;
}
track->tex_dirty = true;
break;
case 0x4400:
case 0x4404:
case 0x4408:
case 0x440C:
case 0x4410:
case 0x4414:
case 0x4418:
case 0x441C:
case 0x4420:
case 0x4424:
case 0x4428:
case 0x442C:
case 0x4430:
case 0x4434:
case 0x4438:
case 0x443C:
/* TX_FILTER0_[0-15] */
i = (reg - 0x4400) >> 2;
tmp = idx_value & 0x7;
if (tmp == 2 || tmp == 4 || tmp == 6) {
track->textures[i].roundup_w = false;
}
tmp = (idx_value >> 3) & 0x7;
if (tmp == 2 || tmp == 4 || tmp == 6) {
track->textures[i].roundup_h = false;
}
track->tex_dirty = true;
break;
case 0x4500:
case 0x4504:
case 0x4508:
case 0x450C:
case 0x4510:
case 0x4514:
case 0x4518:
case 0x451C:
case 0x4520:
case 0x4524:
case 0x4528:
case 0x452C:
case 0x4530:
case 0x4534:
case 0x4538:
case 0x453C:
/* TX_FORMAT2_[0-15] */
i = (reg - 0x4500) >> 2;
tmp = idx_value & 0x3FFF;
track->textures[i].pitch = tmp + 1;
if (p->rdev->family >= CHIP_RV515) {
tmp = ((idx_value >> 15) & 1) << 11;
track->textures[i].width_11 = tmp;
tmp = ((idx_value >> 16) & 1) << 11;
track->textures[i].height_11 = tmp;
/* ATI1N */
if (idx_value & (1 << 14)) {
/* The same rules apply as for DXT1. */
track->textures[i].compress_format =
R100_TRACK_COMP_DXT1;
}
} else if (idx_value & (1 << 14)) {
DRM_ERROR("Forbidden bit TXFORMAT_MSB\n");
return -EINVAL;
}
track->tex_dirty = true;
break;
case 0x4480:
case 0x4484:
case 0x4488:
case 0x448C:
case 0x4490:
case 0x4494:
case 0x4498:
case 0x449C:
case 0x44A0:
case 0x44A4:
case 0x44A8:
case 0x44AC:
case 0x44B0:
case 0x44B4:
case 0x44B8:
case 0x44BC:
/* TX_FORMAT0_[0-15] */
i = (reg - 0x4480) >> 2;
tmp = idx_value & 0x7FF;
track->textures[i].width = tmp + 1;
tmp = (idx_value >> 11) & 0x7FF;
track->textures[i].height = tmp + 1;
tmp = (idx_value >> 26) & 0xF;
track->textures[i].num_levels = tmp;
tmp = idx_value & (1 << 31);
track->textures[i].use_pitch = !!tmp;
tmp = (idx_value >> 22) & 0xF;
track->textures[i].txdepth = tmp;
track->tex_dirty = true;
break;
case R300_ZB_ZPASS_ADDR:
r = r100_cs_packet_next_reloc(p, &reloc);
if (r) {
DRM_ERROR("No reloc for ib[%d]=0x%04X\n",
idx, reg);
r100_cs_dump_packet(p, pkt);
return r;
}
ib[idx] = idx_value + ((u32)reloc->lobj.gpu_offset);
break;
case 0x4e0c:
/* RB3D_COLOR_CHANNEL_MASK */
track->color_channel_mask = idx_value;
track->cb_dirty = true;
break;
case 0x43a4:
/* SC_HYPERZ_EN */
/* r300c emits this register - we need to disable hyperz for it
* without complaining */
if (p->rdev->hyperz_filp != p->filp) {
if (idx_value & 0x1)
ib[idx] = idx_value & ~1;
}
break;
case 0x4f1c:
/* ZB_BW_CNTL */
track->zb_cb_clear = !!(idx_value & (1 << 5));
track->cb_dirty = true;
track->zb_dirty = true;
if (p->rdev->hyperz_filp != p->filp) {
if (idx_value & (R300_HIZ_ENABLE |
R300_RD_COMP_ENABLE |
R300_WR_COMP_ENABLE |
R300_FAST_FILL_ENABLE))
goto fail;
}
break;
case 0x4e04:
/* RB3D_BLENDCNTL */
track->blend_read_enable = !!(idx_value & (1 << 2));
track->cb_dirty = true;
break;
case R300_RB3D_AARESOLVE_OFFSET:
r = r100_cs_packet_next_reloc(p, &reloc);
if (r) {
DRM_ERROR("No reloc for ib[%d]=0x%04X\n",
idx, reg);
r100_cs_dump_packet(p, pkt);
return r;
}
track->aa.robj = reloc->robj;
track->aa.offset = idx_value;
track->aa_dirty = true;
ib[idx] = idx_value + ((u32)reloc->lobj.gpu_offset);
break;
case R300_RB3D_AARESOLVE_PITCH:
track->aa.pitch = idx_value & 0x3FFE;
track->aa_dirty = true;
break;
case R300_RB3D_AARESOLVE_CTL:
track->aaresolve = idx_value & 0x1;
track->aa_dirty = true;
break;
case 0x4f30: /* ZB_MASK_OFFSET */
case 0x4f34: /* ZB_ZMASK_PITCH */
case 0x4f44: /* ZB_HIZ_OFFSET */
case 0x4f54: /* ZB_HIZ_PITCH */
if (idx_value && (p->rdev->hyperz_filp != p->filp))
goto fail;
break;
case 0x4028:
if (idx_value && (p->rdev->hyperz_filp != p->filp))
goto fail;
/* GB_Z_PEQ_CONFIG */
if (p->rdev->family >= CHIP_RV350)
break;
goto fail;
break;
case 0x4be8:
/* valid register only on RV530 */
if (p->rdev->family == CHIP_RV530)
break;
/* fallthrough do not move */
default:
goto fail;
}
return 0;
fail:
printk(KERN_ERR "Forbidden register 0x%04X in cs at %d (val=%08x)\n",
reg, idx, idx_value);
return -EINVAL;
}
static int r300_packet3_check(struct radeon_cs_parser *p,
struct radeon_cs_packet *pkt)
{
struct radeon_cs_reloc *reloc;
struct r100_cs_track *track;
volatile uint32_t *ib;
unsigned idx;
int r;
ib = p->ib->ptr;
idx = pkt->idx + 1;
track = (struct r100_cs_track *)p->track;
switch(pkt->opcode) {
case PACKET3_3D_LOAD_VBPNTR:
r = r100_packet3_load_vbpntr(p, pkt, idx);
if (r)
return r;
break;
case PACKET3_INDX_BUFFER:
r = r100_cs_packet_next_reloc(p, &reloc);
if (r) {
DRM_ERROR("No reloc for packet3 %d\n", pkt->opcode);
r100_cs_dump_packet(p, pkt);
return r;
}
ib[idx+1] = radeon_get_ib_value(p, idx + 1) + ((u32)reloc->lobj.gpu_offset);
r = r100_cs_track_check_pkt3_indx_buffer(p, pkt, reloc->robj);
if (r) {
return r;
}
break;
/* Draw packet */
case PACKET3_3D_DRAW_IMMD:
/* Number of dwords is vtx_size * (num_vertices - 1)
* PRIM_WALK must be equal to 3 vertex data in embedded
* in cmd stream */
if (((radeon_get_ib_value(p, idx + 1) >> 4) & 0x3) != 3) {
DRM_ERROR("PRIM_WALK must be 3 for IMMD draw\n");
return -EINVAL;
}
track->vap_vf_cntl = radeon_get_ib_value(p, idx + 1);
track->immd_dwords = pkt->count - 1;
r = r100_cs_track_check(p->rdev, track);
if (r) {
return r;
}
break;
case PACKET3_3D_DRAW_IMMD_2:
/* Number of dwords is vtx_size * (num_vertices - 1)
* PRIM_WALK must be equal to 3 vertex data in embedded
* in cmd stream */
if (((radeon_get_ib_value(p, idx) >> 4) & 0x3) != 3) {
DRM_ERROR("PRIM_WALK must be 3 for IMMD draw\n");
return -EINVAL;
}
track->vap_vf_cntl = radeon_get_ib_value(p, idx);
track->immd_dwords = pkt->count;
r = r100_cs_track_check(p->rdev, track);
if (r) {
return r;
}
break;
case PACKET3_3D_DRAW_VBUF:
track->vap_vf_cntl = radeon_get_ib_value(p, idx + 1);
r = r100_cs_track_check(p->rdev, track);
if (r) {
return r;
}
break;
case PACKET3_3D_DRAW_VBUF_2:
track->vap_vf_cntl = radeon_get_ib_value(p, idx);
r = r100_cs_track_check(p->rdev, track);
if (r) {
return r;
}
break;
case PACKET3_3D_DRAW_INDX:
track->vap_vf_cntl = radeon_get_ib_value(p, idx + 1);
r = r100_cs_track_check(p->rdev, track);
if (r) {
return r;
}
break;
case PACKET3_3D_DRAW_INDX_2:
track->vap_vf_cntl = radeon_get_ib_value(p, idx);
r = r100_cs_track_check(p->rdev, track);
if (r) {
return r;
}
break;
case PACKET3_3D_CLEAR_HIZ:
case PACKET3_3D_CLEAR_ZMASK:
if (p->rdev->hyperz_filp != p->filp)
return -EINVAL;
break;
case PACKET3_3D_CLEAR_CMASK:
if (p->rdev->cmask_filp != p->filp)
return -EINVAL;
break;
case PACKET3_NOP:
break;
default:
DRM_ERROR("Packet3 opcode %x not supported\n", pkt->opcode);
return -EINVAL;
}
return 0;
}
int r300_cs_parse(struct radeon_cs_parser *p)
{
struct radeon_cs_packet pkt;
struct r100_cs_track *track;
int r;
track = kzalloc(sizeof(*track), GFP_KERNEL);
if (track == NULL)
return -ENOMEM;
r100_cs_track_clear(p->rdev, track);
p->track = track;
do {
r = r100_cs_packet_parse(p, &pkt, p->idx);
if (r) {
return r;
}
p->idx += pkt.count + 2;
switch (pkt.type) {
case PACKET_TYPE0:
r = r100_cs_parse_packet0(p, &pkt,
p->rdev->config.r300.reg_safe_bm,
p->rdev->config.r300.reg_safe_bm_size,
&r300_packet0_check);
break;
case PACKET_TYPE2:
break;
case PACKET_TYPE3:
r = r300_packet3_check(p, &pkt);
break;
default:
DRM_ERROR("Unknown packet type %d !\n", pkt.type);
return -EINVAL;
}
if (r) {
return r;
}
} while (p->idx < p->chunks[p->chunk_ib_idx].length_dw);
return 0;
}
void r300_set_reg_safe(struct radeon_device *rdev)
{
rdev->config.r300.reg_safe_bm = r300_reg_safe_bm;
rdev->config.r300.reg_safe_bm_size = ARRAY_SIZE(r300_reg_safe_bm);
}
void r300_mc_program(struct radeon_device *rdev)
{
struct r100_mc_save save;
int r;
r = r100_debugfs_mc_info_init(rdev);
if (r) {
dev_err(rdev->dev, "Failed to create r100_mc debugfs file.\n");
}
/* Stops all mc clients */
r100_mc_stop(rdev, &save);
if (rdev->flags & RADEON_IS_AGP) {
WREG32(R_00014C_MC_AGP_LOCATION,
S_00014C_MC_AGP_START(rdev->mc.gtt_start >> 16) |
S_00014C_MC_AGP_TOP(rdev->mc.gtt_end >> 16));
WREG32(R_000170_AGP_BASE, lower_32_bits(rdev->mc.agp_base));
WREG32(R_00015C_AGP_BASE_2,
upper_32_bits(rdev->mc.agp_base) & 0xff);
} else {
WREG32(R_00014C_MC_AGP_LOCATION, 0x0FFFFFFF);
WREG32(R_000170_AGP_BASE, 0);
WREG32(R_00015C_AGP_BASE_2, 0);
}
/* Wait for mc idle */
if (r300_mc_wait_for_idle(rdev))
DRM_INFO("Failed to wait MC idle before programming MC.\n");
/* Program MC, should be a 32bits limited address space */
WREG32(R_000148_MC_FB_LOCATION,
S_000148_MC_FB_START(rdev->mc.vram_start >> 16) |
S_000148_MC_FB_TOP(rdev->mc.vram_end >> 16));
r100_mc_resume(rdev, &save);
}
void r300_clock_startup(struct radeon_device *rdev)
{
u32 tmp;
if (radeon_dynclks != -1 && radeon_dynclks)
radeon_legacy_set_clock_gating(rdev, 1);
/* We need to force on some of the block */
tmp = RREG32_PLL(R_00000D_SCLK_CNTL);
tmp |= S_00000D_FORCE_CP(1) | S_00000D_FORCE_VIP(1);
if ((rdev->family == CHIP_RV350) || (rdev->family == CHIP_RV380))
tmp |= S_00000D_FORCE_VAP(1);
WREG32_PLL(R_00000D_SCLK_CNTL, tmp);
}
static int r300_startup(struct radeon_device *rdev)
{
int r;
/* set common regs */
r100_set_common_regs(rdev);
/* program mc */
r300_mc_program(rdev);
/* Resume clock */
r300_clock_startup(rdev);
/* Initialize GPU configuration (# pipes, ...) */
r300_gpu_init(rdev);
/* Initialize GART (initialize after TTM so we can allocate
* memory through TTM but finalize after TTM) */
if (rdev->flags & RADEON_IS_PCIE) {
r = rv370_pcie_gart_enable(rdev);
if (r)
return r;
}
if (rdev->family == CHIP_R300 ||
rdev->family == CHIP_R350 ||
rdev->family == CHIP_RV350)
r100_enable_bm(rdev);
if (rdev->flags & RADEON_IS_PCI) {
r = r100_pci_gart_enable(rdev);
if (r)
return r;
}
/* allocate wb buffer */
r = radeon_wb_init(rdev);
if (r)
return r;
r = radeon_fence_driver_start_ring(rdev, RADEON_RING_TYPE_GFX_INDEX);
if (r) {
dev_err(rdev->dev, "failed initializing CP fences (%d).\n", r);
return r;
}
/* Enable IRQ */
r100_irq_set(rdev);
rdev->config.r300.hdp_cntl = RREG32(RADEON_HOST_PATH_CNTL);
/* 1M ring buffer */
r = r100_cp_init(rdev, 1024 * 1024);
if (r) {
dev_err(rdev->dev, "failed initializing CP (%d).\n", r);
return r;
}
r = radeon_ib_pool_start(rdev);
if (r)
return r;
r = radeon_ib_test(rdev, RADEON_RING_TYPE_GFX_INDEX, &rdev->ring[RADEON_RING_TYPE_GFX_INDEX]);
if (r) {
dev_err(rdev->dev, "failed testing IB (%d).\n", r);
rdev->accel_working = false;
return r;
}
return 0;
}
int r300_resume(struct radeon_device *rdev)
{
int r;
/* Make sur GART are not working */
if (rdev->flags & RADEON_IS_PCIE)
rv370_pcie_gart_disable(rdev);
if (rdev->flags & RADEON_IS_PCI)
r100_pci_gart_disable(rdev);
/* Resume clock before doing reset */
r300_clock_startup(rdev);
/* Reset gpu before posting otherwise ATOM will enter infinite loop */
if (radeon_asic_reset(rdev)) {
dev_warn(rdev->dev, "GPU reset failed ! (0xE40=0x%08X, 0x7C0=0x%08X)\n",
RREG32(R_000E40_RBBM_STATUS),
RREG32(R_0007C0_CP_STAT));
}
/* post */
radeon_combios_asic_init(rdev->ddev);
/* Resume clock after posting */
r300_clock_startup(rdev);
/* Initialize surface registers */
radeon_surface_init(rdev);
rdev->accel_working = true;
r = r300_startup(rdev);
if (r) {
rdev->accel_working = false;
}
return r;
}
int r300_suspend(struct radeon_device *rdev)
{
radeon_ib_pool_suspend(rdev);
r100_cp_disable(rdev);
radeon_wb_disable(rdev);
r100_irq_disable(rdev);
if (rdev->flags & RADEON_IS_PCIE)
rv370_pcie_gart_disable(rdev);
if (rdev->flags & RADEON_IS_PCI)
r100_pci_gart_disable(rdev);
return 0;
}
void r300_fini(struct radeon_device *rdev)
{
r100_cp_fini(rdev);
radeon_wb_fini(rdev);
r100_ib_fini(rdev);
radeon_gem_fini(rdev);
if (rdev->flags & RADEON_IS_PCIE)
rv370_pcie_gart_fini(rdev);
if (rdev->flags & RADEON_IS_PCI)
r100_pci_gart_fini(rdev);
radeon_agp_fini(rdev);
radeon_irq_kms_fini(rdev);
radeon_fence_driver_fini(rdev);
radeon_bo_fini(rdev);
radeon_atombios_fini(rdev);
kfree(rdev->bios);
rdev->bios = NULL;
}
int r300_init(struct radeon_device *rdev)
{
int r;
/* Disable VGA */
r100_vga_render_disable(rdev);
/* Initialize scratch registers */
radeon_scratch_init(rdev);
/* Initialize surface registers */
radeon_surface_init(rdev);
/* TODO: disable VGA need to use VGA request */
/* restore some register to sane defaults */
r100_restore_sanity(rdev);
/* BIOS*/
if (!radeon_get_bios(rdev)) {
if (ASIC_IS_AVIVO(rdev))
return -EINVAL;
}
if (rdev->is_atom_bios) {
dev_err(rdev->dev, "Expecting combios for RS400/RS480 GPU\n");
return -EINVAL;
} else {
r = radeon_combios_init(rdev);
if (r)
return r;
}
/* Reset gpu before posting otherwise ATOM will enter infinite loop */
if (radeon_asic_reset(rdev)) {
dev_warn(rdev->dev,
"GPU reset failed ! (0xE40=0x%08X, 0x7C0=0x%08X)\n",
RREG32(R_000E40_RBBM_STATUS),
RREG32(R_0007C0_CP_STAT));
}
/* check if cards are posted or not */
if (radeon_boot_test_post_card(rdev) == false)
return -EINVAL;
/* Set asic errata */
r300_errata(rdev);
/* Initialize clocks */
radeon_get_clock_info(rdev->ddev);
/* initialize AGP */
if (rdev->flags & RADEON_IS_AGP) {
r = radeon_agp_init(rdev);
if (r) {
radeon_agp_disable(rdev);
}
}
/* initialize memory controller */
r300_mc_init(rdev);
/* Fence driver */
r = radeon_fence_driver_init(rdev);
if (r)
return r;
r = radeon_irq_kms_init(rdev);
if (r)
return r;
/* Memory manager */
r = radeon_bo_init(rdev);
if (r)
return r;
if (rdev->flags & RADEON_IS_PCIE) {
r = rv370_pcie_gart_init(rdev);
if (r)
return r;
}
if (rdev->flags & RADEON_IS_PCI) {
r = r100_pci_gart_init(rdev);
if (r)
return r;
}
r300_set_reg_safe(rdev);
r = radeon_ib_pool_init(rdev);
rdev->accel_working = true;
if (r) {
dev_err(rdev->dev, "IB initialization failed (%d).\n", r);
rdev->accel_working = false;
}
r = r300_startup(rdev);
if (r) {
/* Somethings want wront with the accel init stop accel */
dev_err(rdev->dev, "Disabling GPU acceleration\n");
r100_cp_fini(rdev);
radeon_wb_fini(rdev);
r100_ib_fini(rdev);
radeon_irq_kms_fini(rdev);
if (rdev->flags & RADEON_IS_PCIE)
rv370_pcie_gart_fini(rdev);
if (rdev->flags & RADEON_IS_PCI)
r100_pci_gart_fini(rdev);
radeon_agp_fini(rdev);
rdev->accel_working = false;
}
return 0;
}
| gpl-2.0 |
TeamWin/android_kernel_samsung_zerolte | drivers/input/mouse/hgpk.c | 4561 | 27822 | /*
* OLPC HGPK (XO-1) touchpad PS/2 mouse driver
*
* Copyright (c) 2006-2008 One Laptop Per Child
* Authors:
* Zephaniah E. Hull
* Andres Salomon <dilinger@debian.org>
*
* This driver is partly based on the ALPS driver, which is:
*
* Copyright (c) 2003 Neil Brown <neilb@cse.unsw.edu.au>
* Copyright (c) 2003-2005 Peter Osterlund <petero2@telia.com>
* Copyright (c) 2004 Dmitry Torokhov <dtor@mail.ru>
* Copyright (c) 2005 Vojtech Pavlik <vojtech@suse.cz>
*
* 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.
*/
/*
* The spec from ALPS is available from
* <http://wiki.laptop.org/go/Touch_Pad/Tablet>. It refers to this
* device as HGPK (Hybrid GS, PT, and Keymatrix).
*
* The earliest versions of the device had simultaneous reporting; that
* was removed. After that, the device used the Advanced Mode GS/PT streaming
* stuff. That turned out to be too buggy to support, so we've finally
* switched to Mouse Mode (which utilizes only the center 1/3 of the touchpad).
*/
#define DEBUG
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/module.h>
#include <linux/serio.h>
#include <linux/libps2.h>
#include <linux/delay.h>
#include <asm/olpc.h>
#include "psmouse.h"
#include "hgpk.h"
#define ILLEGAL_XY 999999
static bool tpdebug;
module_param(tpdebug, bool, 0644);
MODULE_PARM_DESC(tpdebug, "enable debugging, dumping packets to KERN_DEBUG.");
static int recalib_delta = 100;
module_param(recalib_delta, int, 0644);
MODULE_PARM_DESC(recalib_delta,
"packets containing a delta this large will be discarded, and a "
"recalibration may be scheduled.");
static int jumpy_delay = 20;
module_param(jumpy_delay, int, 0644);
MODULE_PARM_DESC(jumpy_delay,
"delay (ms) before recal after jumpiness detected");
static int spew_delay = 1;
module_param(spew_delay, int, 0644);
MODULE_PARM_DESC(spew_delay,
"delay (ms) before recal after packet spew detected");
static int recal_guard_time;
module_param(recal_guard_time, int, 0644);
MODULE_PARM_DESC(recal_guard_time,
"interval (ms) during which recal will be restarted if packet received");
static int post_interrupt_delay = 40;
module_param(post_interrupt_delay, int, 0644);
MODULE_PARM_DESC(post_interrupt_delay,
"delay (ms) before recal after recal interrupt detected");
static bool autorecal = true;
module_param(autorecal, bool, 0644);
MODULE_PARM_DESC(autorecal, "enable recalibration in the driver");
static char hgpk_mode_name[16];
module_param_string(hgpk_mode, hgpk_mode_name, sizeof(hgpk_mode_name), 0644);
MODULE_PARM_DESC(hgpk_mode,
"default hgpk mode: mouse, glidesensor or pentablet");
static int hgpk_default_mode = HGPK_MODE_MOUSE;
static const char * const hgpk_mode_names[] = {
[HGPK_MODE_MOUSE] = "Mouse",
[HGPK_MODE_GLIDESENSOR] = "GlideSensor",
[HGPK_MODE_PENTABLET] = "PenTablet",
};
static int hgpk_mode_from_name(const char *buf, int len)
{
int i;
for (i = 0; i < ARRAY_SIZE(hgpk_mode_names); i++) {
const char *name = hgpk_mode_names[i];
if (strlen(name) == len && !strncasecmp(name, buf, len))
return i;
}
return HGPK_MODE_INVALID;
}
/*
* see if new value is within 20% of half of old value
*/
static int approx_half(int curr, int prev)
{
int belowhalf, abovehalf;
if (curr < 5 || prev < 5)
return 0;
belowhalf = (prev * 8) / 20;
abovehalf = (prev * 12) / 20;
return belowhalf < curr && curr <= abovehalf;
}
/*
* Throw out oddly large delta packets, and any that immediately follow whose
* values are each approximately half of the previous. It seems that the ALPS
* firmware emits errant packets, and they get averaged out slowly.
*/
static int hgpk_discard_decay_hack(struct psmouse *psmouse, int x, int y)
{
struct hgpk_data *priv = psmouse->private;
int avx, avy;
bool do_recal = false;
avx = abs(x);
avy = abs(y);
/* discard if too big, or half that but > 4 times the prev delta */
if (avx > recalib_delta ||
(avx > recalib_delta / 2 && ((avx / 4) > priv->xlast))) {
psmouse_warn(psmouse, "detected %dpx jump in x\n", x);
priv->xbigj = avx;
} else if (approx_half(avx, priv->xbigj)) {
psmouse_warn(psmouse, "detected secondary %dpx jump in x\n", x);
priv->xbigj = avx;
priv->xsaw_secondary++;
} else {
if (priv->xbigj && priv->xsaw_secondary > 1)
do_recal = true;
priv->xbigj = 0;
priv->xsaw_secondary = 0;
}
if (avy > recalib_delta ||
(avy > recalib_delta / 2 && ((avy / 4) > priv->ylast))) {
psmouse_warn(psmouse, "detected %dpx jump in y\n", y);
priv->ybigj = avy;
} else if (approx_half(avy, priv->ybigj)) {
psmouse_warn(psmouse, "detected secondary %dpx jump in y\n", y);
priv->ybigj = avy;
priv->ysaw_secondary++;
} else {
if (priv->ybigj && priv->ysaw_secondary > 1)
do_recal = true;
priv->ybigj = 0;
priv->ysaw_secondary = 0;
}
priv->xlast = avx;
priv->ylast = avy;
if (do_recal && jumpy_delay) {
psmouse_warn(psmouse, "scheduling recalibration\n");
psmouse_queue_work(psmouse, &priv->recalib_wq,
msecs_to_jiffies(jumpy_delay));
}
return priv->xbigj || priv->ybigj;
}
static void hgpk_reset_spew_detection(struct hgpk_data *priv)
{
priv->spew_count = 0;
priv->dupe_count = 0;
priv->x_tally = 0;
priv->y_tally = 0;
priv->spew_flag = NO_SPEW;
}
static void hgpk_reset_hack_state(struct psmouse *psmouse)
{
struct hgpk_data *priv = psmouse->private;
priv->abs_x = priv->abs_y = -1;
priv->xlast = priv->ylast = ILLEGAL_XY;
priv->xbigj = priv->ybigj = 0;
priv->xsaw_secondary = priv->ysaw_secondary = 0;
hgpk_reset_spew_detection(priv);
}
/*
* We have no idea why this particular hardware bug occurs. The touchpad
* will randomly start spewing packets without anything touching the
* pad. This wouldn't necessarily be bad, but it's indicative of a
* severely miscalibrated pad; attempting to use the touchpad while it's
* spewing means the cursor will jump all over the place, and act "drunk".
*
* The packets that are spewed tend to all have deltas between -2 and 2, and
* the cursor will move around without really going very far. It will
* tend to end up in the same location; if we tally up the changes over
* 100 packets, we end up w/ a final delta of close to 0. This happens
* pretty regularly when the touchpad is spewing, and is pretty hard to
* manually trigger (at least for *my* fingers). So, it makes a perfect
* scheme for detecting spews.
*/
static void hgpk_spewing_hack(struct psmouse *psmouse,
int l, int r, int x, int y)
{
struct hgpk_data *priv = psmouse->private;
/* ignore button press packets; many in a row could trigger
* a false-positive! */
if (l || r)
return;
/* don't track spew if the workaround feature has been turned off */
if (!spew_delay)
return;
if (abs(x) > 3 || abs(y) > 3) {
/* no spew, or spew ended */
hgpk_reset_spew_detection(priv);
return;
}
/* Keep a tally of the overall delta to the cursor position caused by
* the spew */
priv->x_tally += x;
priv->y_tally += y;
switch (priv->spew_flag) {
case NO_SPEW:
/* we're not spewing, but this packet might be the start */
priv->spew_flag = MAYBE_SPEWING;
/* fall-through */
case MAYBE_SPEWING:
priv->spew_count++;
if (priv->spew_count < SPEW_WATCH_COUNT)
break;
/* excessive spew detected, request recalibration */
priv->spew_flag = SPEW_DETECTED;
/* fall-through */
case SPEW_DETECTED:
/* only recalibrate when the overall delta to the cursor
* is really small. if the spew is causing significant cursor
* movement, it is probably a case of the user moving the
* cursor very slowly across the screen. */
if (abs(priv->x_tally) < 3 && abs(priv->y_tally) < 3) {
psmouse_warn(psmouse, "packet spew detected (%d,%d)\n",
priv->x_tally, priv->y_tally);
priv->spew_flag = RECALIBRATING;
psmouse_queue_work(psmouse, &priv->recalib_wq,
msecs_to_jiffies(spew_delay));
}
break;
case RECALIBRATING:
/* we already detected a spew and requested a recalibration,
* just wait for the queue to kick into action. */
break;
}
}
/*
* HGPK Mouse Mode format (standard mouse format, sans middle button)
*
* byte 0: y-over x-over y-neg x-neg 1 0 swr swl
* byte 1: x7 x6 x5 x4 x3 x2 x1 x0
* byte 2: y7 y6 y5 y4 y3 y2 y1 y0
*
* swr/swl are the left/right buttons.
* x-neg/y-neg are the x and y delta negative bits
* x-over/y-over are the x and y overflow bits
*
* ---
*
* HGPK Advanced Mode - single-mode format
*
* byte 0(PT): 1 1 0 0 1 1 1 1
* byte 0(GS): 1 1 1 1 1 1 1 1
* byte 1: 0 x6 x5 x4 x3 x2 x1 x0
* byte 2(PT): 0 0 x9 x8 x7 ? pt-dsw 0
* byte 2(GS): 0 x10 x9 x8 x7 ? gs-dsw pt-dsw
* byte 3: 0 y9 y8 y7 1 0 swr swl
* byte 4: 0 y6 y5 y4 y3 y2 y1 y0
* byte 5: 0 z6 z5 z4 z3 z2 z1 z0
*
* ?'s are not defined in the protocol spec, may vary between models.
*
* swr/swl are the left/right buttons.
*
* pt-dsw/gs-dsw indicate that the pt/gs sensor is detecting a
* pen/finger
*/
static bool hgpk_is_byte_valid(struct psmouse *psmouse, unsigned char *packet)
{
struct hgpk_data *priv = psmouse->private;
int pktcnt = psmouse->pktcnt;
bool valid;
switch (priv->mode) {
case HGPK_MODE_MOUSE:
valid = (packet[0] & 0x0C) == 0x08;
break;
case HGPK_MODE_GLIDESENSOR:
valid = pktcnt == 1 ?
packet[0] == HGPK_GS : !(packet[pktcnt - 1] & 0x80);
break;
case HGPK_MODE_PENTABLET:
valid = pktcnt == 1 ?
packet[0] == HGPK_PT : !(packet[pktcnt - 1] & 0x80);
break;
default:
valid = false;
break;
}
if (!valid)
psmouse_dbg(psmouse,
"bad data, mode %d (%d) %*ph\n",
priv->mode, pktcnt, 6, psmouse->packet);
return valid;
}
static void hgpk_process_advanced_packet(struct psmouse *psmouse)
{
struct hgpk_data *priv = psmouse->private;
struct input_dev *idev = psmouse->dev;
unsigned char *packet = psmouse->packet;
int down = !!(packet[2] & 2);
int left = !!(packet[3] & 1);
int right = !!(packet[3] & 2);
int x = packet[1] | ((packet[2] & 0x78) << 4);
int y = packet[4] | ((packet[3] & 0x70) << 3);
if (priv->mode == HGPK_MODE_GLIDESENSOR) {
int pt_down = !!(packet[2] & 1);
int finger_down = !!(packet[2] & 2);
int z = packet[5];
input_report_abs(idev, ABS_PRESSURE, z);
if (tpdebug)
psmouse_dbg(psmouse, "pd=%d fd=%d z=%d",
pt_down, finger_down, z);
} else {
/*
* PenTablet mode does not report pressure, so we don't
* report it here
*/
if (tpdebug)
psmouse_dbg(psmouse, "pd=%d ", down);
}
if (tpdebug)
psmouse_dbg(psmouse, "l=%d r=%d x=%d y=%d\n",
left, right, x, y);
input_report_key(idev, BTN_TOUCH, down);
input_report_key(idev, BTN_LEFT, left);
input_report_key(idev, BTN_RIGHT, right);
/*
* If this packet says that the finger was removed, reset our position
* tracking so that we don't erroneously detect a jump on next press.
*/
if (!down) {
hgpk_reset_hack_state(psmouse);
goto done;
}
/*
* Weed out duplicate packets (we get quite a few, and they mess up
* our jump detection)
*/
if (x == priv->abs_x && y == priv->abs_y) {
if (++priv->dupe_count > SPEW_WATCH_COUNT) {
if (tpdebug)
psmouse_dbg(psmouse, "hard spew detected\n");
priv->spew_flag = RECALIBRATING;
psmouse_queue_work(psmouse, &priv->recalib_wq,
msecs_to_jiffies(spew_delay));
}
goto done;
}
/* not a duplicate, continue with position reporting */
priv->dupe_count = 0;
/* Don't apply hacks in PT mode, it seems reliable */
if (priv->mode != HGPK_MODE_PENTABLET && priv->abs_x != -1) {
int x_diff = priv->abs_x - x;
int y_diff = priv->abs_y - y;
if (hgpk_discard_decay_hack(psmouse, x_diff, y_diff)) {
if (tpdebug)
psmouse_dbg(psmouse, "discarding\n");
goto done;
}
hgpk_spewing_hack(psmouse, left, right, x_diff, y_diff);
}
input_report_abs(idev, ABS_X, x);
input_report_abs(idev, ABS_Y, y);
priv->abs_x = x;
priv->abs_y = y;
done:
input_sync(idev);
}
static void hgpk_process_simple_packet(struct psmouse *psmouse)
{
struct input_dev *dev = psmouse->dev;
unsigned char *packet = psmouse->packet;
int left = packet[0] & 1;
int right = (packet[0] >> 1) & 1;
int x = packet[1] - ((packet[0] << 4) & 0x100);
int y = ((packet[0] << 3) & 0x100) - packet[2];
if (packet[0] & 0xc0)
psmouse_dbg(psmouse,
"overflow -- 0x%02x 0x%02x 0x%02x\n",
packet[0], packet[1], packet[2]);
if (hgpk_discard_decay_hack(psmouse, x, y)) {
if (tpdebug)
psmouse_dbg(psmouse, "discarding\n");
return;
}
hgpk_spewing_hack(psmouse, left, right, x, y);
if (tpdebug)
psmouse_dbg(psmouse, "l=%d r=%d x=%d y=%d\n",
left, right, x, y);
input_report_key(dev, BTN_LEFT, left);
input_report_key(dev, BTN_RIGHT, right);
input_report_rel(dev, REL_X, x);
input_report_rel(dev, REL_Y, y);
input_sync(dev);
}
static psmouse_ret_t hgpk_process_byte(struct psmouse *psmouse)
{
struct hgpk_data *priv = psmouse->private;
if (!hgpk_is_byte_valid(psmouse, psmouse->packet))
return PSMOUSE_BAD_DATA;
if (psmouse->pktcnt >= psmouse->pktsize) {
if (priv->mode == HGPK_MODE_MOUSE)
hgpk_process_simple_packet(psmouse);
else
hgpk_process_advanced_packet(psmouse);
return PSMOUSE_FULL_PACKET;
}
if (priv->recalib_window) {
if (time_before(jiffies, priv->recalib_window)) {
/*
* ugh, got a packet inside our recalibration
* window, schedule another recalibration.
*/
psmouse_dbg(psmouse,
"packet inside calibration window, queueing another recalibration\n");
psmouse_queue_work(psmouse, &priv->recalib_wq,
msecs_to_jiffies(post_interrupt_delay));
}
priv->recalib_window = 0;
}
return PSMOUSE_GOOD_DATA;
}
static int hgpk_select_mode(struct psmouse *psmouse)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
struct hgpk_data *priv = psmouse->private;
int i;
int cmd;
/*
* 4 disables to enable advanced mode
* then 3 0xf2 bytes as the preamble for GS/PT selection
*/
const int advanced_init[] = {
PSMOUSE_CMD_DISABLE, PSMOUSE_CMD_DISABLE,
PSMOUSE_CMD_DISABLE, PSMOUSE_CMD_DISABLE,
0xf2, 0xf2, 0xf2,
};
switch (priv->mode) {
case HGPK_MODE_MOUSE:
psmouse->pktsize = 3;
break;
case HGPK_MODE_GLIDESENSOR:
case HGPK_MODE_PENTABLET:
psmouse->pktsize = 6;
/* Switch to 'Advanced mode.', four disables in a row. */
for (i = 0; i < ARRAY_SIZE(advanced_init); i++)
if (ps2_command(ps2dev, NULL, advanced_init[i]))
return -EIO;
/* select between GlideSensor (mouse) or PenTablet */
cmd = priv->mode == HGPK_MODE_GLIDESENSOR ?
PSMOUSE_CMD_SETSCALE11 : PSMOUSE_CMD_SETSCALE21;
if (ps2_command(ps2dev, NULL, cmd))
return -EIO;
break;
default:
return -EINVAL;
}
return 0;
}
static void hgpk_setup_input_device(struct input_dev *input,
struct input_dev *old_input,
enum hgpk_mode mode)
{
if (old_input) {
input->name = old_input->name;
input->phys = old_input->phys;
input->id = old_input->id;
input->dev.parent = old_input->dev.parent;
}
memset(input->evbit, 0, sizeof(input->evbit));
memset(input->relbit, 0, sizeof(input->relbit));
memset(input->keybit, 0, sizeof(input->keybit));
/* All modes report left and right buttons */
__set_bit(EV_KEY, input->evbit);
__set_bit(BTN_LEFT, input->keybit);
__set_bit(BTN_RIGHT, input->keybit);
switch (mode) {
case HGPK_MODE_MOUSE:
__set_bit(EV_REL, input->evbit);
__set_bit(REL_X, input->relbit);
__set_bit(REL_Y, input->relbit);
break;
case HGPK_MODE_GLIDESENSOR:
__set_bit(BTN_TOUCH, input->keybit);
__set_bit(BTN_TOOL_FINGER, input->keybit);
__set_bit(EV_ABS, input->evbit);
/* GlideSensor has pressure sensor, PenTablet does not */
input_set_abs_params(input, ABS_PRESSURE, 0, 15, 0, 0);
/* From device specs */
input_set_abs_params(input, ABS_X, 0, 399, 0, 0);
input_set_abs_params(input, ABS_Y, 0, 290, 0, 0);
/* Calculated by hand based on usable size (52mm x 38mm) */
input_abs_set_res(input, ABS_X, 8);
input_abs_set_res(input, ABS_Y, 8);
break;
case HGPK_MODE_PENTABLET:
__set_bit(BTN_TOUCH, input->keybit);
__set_bit(BTN_TOOL_FINGER, input->keybit);
__set_bit(EV_ABS, input->evbit);
/* From device specs */
input_set_abs_params(input, ABS_X, 0, 999, 0, 0);
input_set_abs_params(input, ABS_Y, 5, 239, 0, 0);
/* Calculated by hand based on usable size (156mm x 38mm) */
input_abs_set_res(input, ABS_X, 6);
input_abs_set_res(input, ABS_Y, 8);
break;
default:
BUG();
}
}
static int hgpk_reset_device(struct psmouse *psmouse, bool recalibrate)
{
int err;
psmouse_reset(psmouse);
if (recalibrate) {
struct ps2dev *ps2dev = &psmouse->ps2dev;
/* send the recalibrate request */
if (ps2_command(ps2dev, NULL, 0xf5) ||
ps2_command(ps2dev, NULL, 0xf5) ||
ps2_command(ps2dev, NULL, 0xe6) ||
ps2_command(ps2dev, NULL, 0xf5)) {
return -1;
}
/* according to ALPS, 150mS is required for recalibration */
msleep(150);
}
err = hgpk_select_mode(psmouse);
if (err) {
psmouse_err(psmouse, "failed to select mode\n");
return err;
}
hgpk_reset_hack_state(psmouse);
return 0;
}
static int hgpk_force_recalibrate(struct psmouse *psmouse)
{
struct hgpk_data *priv = psmouse->private;
int err;
/* C-series touchpads added the recalibrate command */
if (psmouse->model < HGPK_MODEL_C)
return 0;
if (!autorecal) {
psmouse_dbg(psmouse, "recalibration disabled, ignoring\n");
return 0;
}
psmouse_dbg(psmouse, "recalibrating touchpad..\n");
/* we don't want to race with the irq handler, nor with resyncs */
psmouse_set_state(psmouse, PSMOUSE_INITIALIZING);
/* start by resetting the device */
err = hgpk_reset_device(psmouse, true);
if (err)
return err;
/*
* XXX: If a finger is down during this delay, recalibration will
* detect capacitance incorrectly. This is a hardware bug, and
* we don't have a good way to deal with it. The 2s window stuff
* (below) is our best option for now.
*/
if (psmouse_activate(psmouse))
return -1;
if (tpdebug)
psmouse_dbg(psmouse, "touchpad reactivated\n");
/*
* If we get packets right away after recalibrating, it's likely
* that a finger was on the touchpad. If so, it's probably
* miscalibrated, so we optionally schedule another.
*/
if (recal_guard_time)
priv->recalib_window = jiffies +
msecs_to_jiffies(recal_guard_time);
return 0;
}
/*
* This puts the touchpad in a power saving mode; according to ALPS, current
* consumption goes down to 50uA after running this. To turn power back on,
* we drive MS-DAT low. Measuring with a 1mA resolution ammeter says that
* the current on the SUS_3.3V rail drops from 3mA or 4mA to 0 when we do this.
*
* We have no formal spec that details this operation -- the low-power
* sequence came from a long-lost email trail.
*/
static int hgpk_toggle_powersave(struct psmouse *psmouse, int enable)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
int timeo;
int err;
/* Added on D-series touchpads */
if (psmouse->model < HGPK_MODEL_D)
return 0;
if (enable) {
psmouse_set_state(psmouse, PSMOUSE_INITIALIZING);
/*
* Sending a byte will drive MS-DAT low; this will wake up
* the controller. Once we get an ACK back from it, it
* means we can continue with the touchpad re-init. ALPS
* tells us that 1s should be long enough, so set that as
* the upper bound. (in practice, it takes about 3 loops.)
*/
for (timeo = 20; timeo > 0; timeo--) {
if (!ps2_sendbyte(&psmouse->ps2dev,
PSMOUSE_CMD_DISABLE, 20))
break;
msleep(25);
}
err = hgpk_reset_device(psmouse, false);
if (err) {
psmouse_err(psmouse, "Failed to reset device!\n");
return err;
}
/* should be all set, enable the touchpad */
psmouse_activate(psmouse);
psmouse_dbg(psmouse, "Touchpad powered up.\n");
} else {
psmouse_dbg(psmouse, "Powering off touchpad.\n");
if (ps2_command(ps2dev, NULL, 0xec) ||
ps2_command(ps2dev, NULL, 0xec) ||
ps2_command(ps2dev, NULL, 0xea)) {
return -1;
}
psmouse_set_state(psmouse, PSMOUSE_IGNORE);
/* probably won't see an ACK, the touchpad will be off */
ps2_sendbyte(&psmouse->ps2dev, 0xec, 20);
}
return 0;
}
static int hgpk_poll(struct psmouse *psmouse)
{
/* We can't poll, so always return failure. */
return -1;
}
static int hgpk_reconnect(struct psmouse *psmouse)
{
struct hgpk_data *priv = psmouse->private;
/*
* During suspend/resume the ps2 rails remain powered. We don't want
* to do a reset because it's flush data out of buffers; however,
* earlier prototypes (B1) had some brokenness that required a reset.
*/
if (olpc_board_at_least(olpc_board(0xb2)))
if (psmouse->ps2dev.serio->dev.power.power_state.event !=
PM_EVENT_ON)
return 0;
priv->powered = 1;
return hgpk_reset_device(psmouse, false);
}
static ssize_t hgpk_show_powered(struct psmouse *psmouse, void *data, char *buf)
{
struct hgpk_data *priv = psmouse->private;
return sprintf(buf, "%d\n", priv->powered);
}
static ssize_t hgpk_set_powered(struct psmouse *psmouse, void *data,
const char *buf, size_t count)
{
struct hgpk_data *priv = psmouse->private;
unsigned int value;
int err;
err = kstrtouint(buf, 10, &value);
if (err)
return err;
if (value > 1)
return -EINVAL;
if (value != priv->powered) {
/*
* hgpk_toggle_power will deal w/ state so
* we're not racing w/ irq
*/
err = hgpk_toggle_powersave(psmouse, value);
if (!err)
priv->powered = value;
}
return err ? err : count;
}
__PSMOUSE_DEFINE_ATTR(powered, S_IWUSR | S_IRUGO, NULL,
hgpk_show_powered, hgpk_set_powered, false);
static ssize_t attr_show_mode(struct psmouse *psmouse, void *data, char *buf)
{
struct hgpk_data *priv = psmouse->private;
return sprintf(buf, "%s\n", hgpk_mode_names[priv->mode]);
}
static ssize_t attr_set_mode(struct psmouse *psmouse, void *data,
const char *buf, size_t len)
{
struct hgpk_data *priv = psmouse->private;
enum hgpk_mode old_mode = priv->mode;
enum hgpk_mode new_mode = hgpk_mode_from_name(buf, len);
struct input_dev *old_dev = psmouse->dev;
struct input_dev *new_dev;
int err;
if (new_mode == HGPK_MODE_INVALID)
return -EINVAL;
if (old_mode == new_mode)
return len;
new_dev = input_allocate_device();
if (!new_dev)
return -ENOMEM;
psmouse_set_state(psmouse, PSMOUSE_INITIALIZING);
/* Switch device into the new mode */
priv->mode = new_mode;
err = hgpk_reset_device(psmouse, false);
if (err)
goto err_try_restore;
hgpk_setup_input_device(new_dev, old_dev, new_mode);
psmouse_set_state(psmouse, PSMOUSE_CMD_MODE);
err = input_register_device(new_dev);
if (err)
goto err_try_restore;
psmouse->dev = new_dev;
input_unregister_device(old_dev);
return len;
err_try_restore:
input_free_device(new_dev);
priv->mode = old_mode;
hgpk_reset_device(psmouse, false);
return err;
}
PSMOUSE_DEFINE_ATTR(hgpk_mode, S_IWUSR | S_IRUGO, NULL,
attr_show_mode, attr_set_mode);
static ssize_t hgpk_trigger_recal_show(struct psmouse *psmouse,
void *data, char *buf)
{
return -EINVAL;
}
static ssize_t hgpk_trigger_recal(struct psmouse *psmouse, void *data,
const char *buf, size_t count)
{
struct hgpk_data *priv = psmouse->private;
unsigned int value;
int err;
err = kstrtouint(buf, 10, &value);
if (err)
return err;
if (value != 1)
return -EINVAL;
/*
* We queue work instead of doing recalibration right here
* to avoid adding locking to to hgpk_force_recalibrate()
* since workqueue provides serialization.
*/
psmouse_queue_work(psmouse, &priv->recalib_wq, 0);
return count;
}
__PSMOUSE_DEFINE_ATTR(recalibrate, S_IWUSR | S_IRUGO, NULL,
hgpk_trigger_recal_show, hgpk_trigger_recal, false);
static void hgpk_disconnect(struct psmouse *psmouse)
{
struct hgpk_data *priv = psmouse->private;
device_remove_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_powered.dattr);
device_remove_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_hgpk_mode.dattr);
if (psmouse->model >= HGPK_MODEL_C)
device_remove_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_recalibrate.dattr);
psmouse_reset(psmouse);
kfree(priv);
}
static void hgpk_recalib_work(struct work_struct *work)
{
struct delayed_work *w = to_delayed_work(work);
struct hgpk_data *priv = container_of(w, struct hgpk_data, recalib_wq);
struct psmouse *psmouse = priv->psmouse;
if (hgpk_force_recalibrate(psmouse))
psmouse_err(psmouse, "recalibration failed!\n");
}
static int hgpk_register(struct psmouse *psmouse)
{
struct hgpk_data *priv = psmouse->private;
int err;
/* register handlers */
psmouse->protocol_handler = hgpk_process_byte;
psmouse->poll = hgpk_poll;
psmouse->disconnect = hgpk_disconnect;
psmouse->reconnect = hgpk_reconnect;
/* Disable the idle resync. */
psmouse->resync_time = 0;
/* Reset after a lot of bad bytes. */
psmouse->resetafter = 1024;
hgpk_setup_input_device(psmouse->dev, NULL, priv->mode);
err = device_create_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_powered.dattr);
if (err) {
psmouse_err(psmouse, "Failed creating 'powered' sysfs node\n");
return err;
}
err = device_create_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_hgpk_mode.dattr);
if (err) {
psmouse_err(psmouse,
"Failed creating 'hgpk_mode' sysfs node\n");
goto err_remove_powered;
}
/* C-series touchpads added the recalibrate command */
if (psmouse->model >= HGPK_MODEL_C) {
err = device_create_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_recalibrate.dattr);
if (err) {
psmouse_err(psmouse,
"Failed creating 'recalibrate' sysfs node\n");
goto err_remove_mode;
}
}
return 0;
err_remove_mode:
device_remove_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_hgpk_mode.dattr);
err_remove_powered:
device_remove_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_powered.dattr);
return err;
}
int hgpk_init(struct psmouse *psmouse)
{
struct hgpk_data *priv;
int err;
priv = kzalloc(sizeof(struct hgpk_data), GFP_KERNEL);
if (!priv) {
err = -ENOMEM;
goto alloc_fail;
}
psmouse->private = priv;
priv->psmouse = psmouse;
priv->powered = true;
priv->mode = hgpk_default_mode;
INIT_DELAYED_WORK(&priv->recalib_wq, hgpk_recalib_work);
err = hgpk_reset_device(psmouse, false);
if (err)
goto init_fail;
err = hgpk_register(psmouse);
if (err)
goto init_fail;
return 0;
init_fail:
kfree(priv);
alloc_fail:
return err;
}
static enum hgpk_model_t hgpk_get_model(struct psmouse *psmouse)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char param[3];
/* E7, E7, E7, E9 gets us a 3 byte identifier */
if (ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE21) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE21) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE21) ||
ps2_command(ps2dev, param, PSMOUSE_CMD_GETINFO)) {
return -EIO;
}
psmouse_dbg(psmouse, "ID: %*ph\n", 3, param);
/* HGPK signature: 0x67, 0x00, 0x<model> */
if (param[0] != 0x67 || param[1] != 0x00)
return -ENODEV;
psmouse_info(psmouse, "OLPC touchpad revision 0x%x\n", param[2]);
return param[2];
}
int hgpk_detect(struct psmouse *psmouse, bool set_properties)
{
int version;
version = hgpk_get_model(psmouse);
if (version < 0)
return version;
if (set_properties) {
psmouse->vendor = "ALPS";
psmouse->name = "HGPK";
psmouse->model = version;
}
return 0;
}
void hgpk_module_init(void)
{
hgpk_default_mode = hgpk_mode_from_name(hgpk_mode_name,
strlen(hgpk_mode_name));
if (hgpk_default_mode == HGPK_MODE_INVALID) {
hgpk_default_mode = HGPK_MODE_MOUSE;
strlcpy(hgpk_mode_name, hgpk_mode_names[HGPK_MODE_MOUSE],
sizeof(hgpk_mode_name));
}
}
| gpl-2.0 |
Caio99BR/FalconSSKernel | drivers/media/dvb/dm1105/dm1105.c | 5073 | 29946 | /*
* dm1105.c - driver for DVB cards based on SDMC DM1105 PCI chip
*
* Copyright (C) 2008 Igor M. Liplianin <liplianin@me.by>
*
* 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/i2c.h>
#include <linux/i2c-algo-bit.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/pci.h>
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <media/rc-core.h>
#include "demux.h"
#include "dmxdev.h"
#include "dvb_demux.h"
#include "dvb_frontend.h"
#include "dvb_net.h"
#include "dvbdev.h"
#include "dvb-pll.h"
#include "stv0299.h"
#include "stv0288.h"
#include "stb6000.h"
#include "si21xx.h"
#include "cx24116.h"
#include "z0194a.h"
#include "ds3000.h"
#define MODULE_NAME "dm1105"
#define UNSET (-1U)
#define DM1105_BOARD_NOAUTO UNSET
#define DM1105_BOARD_UNKNOWN 0
#define DM1105_BOARD_DVBWORLD_2002 1
#define DM1105_BOARD_DVBWORLD_2004 2
#define DM1105_BOARD_AXESS_DM05 3
#define DM1105_BOARD_UNBRANDED_I2C_ON_GPIO 4
/* ----------------------------------------------- */
/*
* PCI ID's
*/
#ifndef PCI_VENDOR_ID_TRIGEM
#define PCI_VENDOR_ID_TRIGEM 0x109f
#endif
#ifndef PCI_VENDOR_ID_AXESS
#define PCI_VENDOR_ID_AXESS 0x195d
#endif
#ifndef PCI_DEVICE_ID_DM1105
#define PCI_DEVICE_ID_DM1105 0x036f
#endif
#ifndef PCI_DEVICE_ID_DW2002
#define PCI_DEVICE_ID_DW2002 0x2002
#endif
#ifndef PCI_DEVICE_ID_DW2004
#define PCI_DEVICE_ID_DW2004 0x2004
#endif
#ifndef PCI_DEVICE_ID_DM05
#define PCI_DEVICE_ID_DM05 0x1105
#endif
/* ----------------------------------------------- */
/* sdmc dm1105 registers */
/* TS Control */
#define DM1105_TSCTR 0x00
#define DM1105_DTALENTH 0x04
/* GPIO Interface */
#define DM1105_GPIOVAL 0x08
#define DM1105_GPIOCTR 0x0c
/* PID serial number */
#define DM1105_PIDN 0x10
/* Odd-even secret key select */
#define DM1105_CWSEL 0x14
/* Host Command Interface */
#define DM1105_HOST_CTR 0x18
#define DM1105_HOST_AD 0x1c
/* PCI Interface */
#define DM1105_CR 0x30
#define DM1105_RST 0x34
#define DM1105_STADR 0x38
#define DM1105_RLEN 0x3c
#define DM1105_WRP 0x40
#define DM1105_INTCNT 0x44
#define DM1105_INTMAK 0x48
#define DM1105_INTSTS 0x4c
/* CW Value */
#define DM1105_ODD 0x50
#define DM1105_EVEN 0x58
/* PID Value */
#define DM1105_PID 0x60
/* IR Control */
#define DM1105_IRCTR 0x64
#define DM1105_IRMODE 0x68
#define DM1105_SYSTEMCODE 0x6c
#define DM1105_IRCODE 0x70
/* Unknown Values */
#define DM1105_ENCRYPT 0x74
#define DM1105_VER 0x7c
/* I2C Interface */
#define DM1105_I2CCTR 0x80
#define DM1105_I2CSTS 0x81
#define DM1105_I2CDAT 0x82
#define DM1105_I2C_RA 0x83
/* ----------------------------------------------- */
/* Interrupt Mask Bits */
#define INTMAK_TSIRQM 0x01
#define INTMAK_HIRQM 0x04
#define INTMAK_IRM 0x08
#define INTMAK_ALLMASK (INTMAK_TSIRQM | \
INTMAK_HIRQM | \
INTMAK_IRM)
#define INTMAK_NONEMASK 0x00
/* Interrupt Status Bits */
#define INTSTS_TSIRQ 0x01
#define INTSTS_HIRQ 0x04
#define INTSTS_IR 0x08
/* IR Control Bits */
#define DM1105_IR_EN 0x01
#define DM1105_SYS_CHK 0x02
#define DM1105_REP_FLG 0x08
/* EEPROM addr */
#define IIC_24C01_addr 0xa0
/* Max board count */
#define DM1105_MAX 0x04
#define DRIVER_NAME "dm1105"
#define DM1105_I2C_GPIO_NAME "dm1105-gpio"
#define DM1105_DMA_PACKETS 47
#define DM1105_DMA_PACKET_LENGTH (128*4)
#define DM1105_DMA_BYTES (128 * 4 * DM1105_DMA_PACKETS)
/* */
#define GPIO08 (1 << 8)
#define GPIO13 (1 << 13)
#define GPIO14 (1 << 14)
#define GPIO15 (1 << 15)
#define GPIO16 (1 << 16)
#define GPIO17 (1 << 17)
#define GPIO_ALL 0x03ffff
/* GPIO's for LNB power control */
#define DM1105_LNB_MASK (GPIO_ALL & ~(GPIO14 | GPIO13))
#define DM1105_LNB_OFF GPIO17
#define DM1105_LNB_13V (GPIO16 | GPIO08)
#define DM1105_LNB_18V GPIO08
/* GPIO's for LNB power control for Axess DM05 */
#define DM05_LNB_MASK (GPIO_ALL & ~(GPIO14 | GPIO13))
#define DM05_LNB_OFF GPIO17/* actually 13v */
#define DM05_LNB_13V GPIO17
#define DM05_LNB_18V (GPIO17 | GPIO16)
/* GPIO's for LNB power control for unbranded with I2C on GPIO */
#define UNBR_LNB_MASK (GPIO17 | GPIO16)
#define UNBR_LNB_OFF 0
#define UNBR_LNB_13V GPIO17
#define UNBR_LNB_18V (GPIO17 | GPIO16)
static unsigned int card[] = {[0 ... 3] = UNSET };
module_param_array(card, int, NULL, 0444);
MODULE_PARM_DESC(card, "card type");
static int ir_debug;
module_param(ir_debug, int, 0644);
MODULE_PARM_DESC(ir_debug, "enable debugging information for IR decoding");
static unsigned int dm1105_devcount;
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
struct dm1105_board {
char *name;
struct {
u32 mask, off, v13, v18;
} lnb;
u32 gpio_scl, gpio_sda;
};
struct dm1105_subid {
u16 subvendor;
u16 subdevice;
u32 card;
};
static const struct dm1105_board dm1105_boards[] = {
[DM1105_BOARD_UNKNOWN] = {
.name = "UNKNOWN/GENERIC",
.lnb = {
.mask = DM1105_LNB_MASK,
.off = DM1105_LNB_OFF,
.v13 = DM1105_LNB_13V,
.v18 = DM1105_LNB_18V,
},
},
[DM1105_BOARD_DVBWORLD_2002] = {
.name = "DVBWorld PCI 2002",
.lnb = {
.mask = DM1105_LNB_MASK,
.off = DM1105_LNB_OFF,
.v13 = DM1105_LNB_13V,
.v18 = DM1105_LNB_18V,
},
},
[DM1105_BOARD_DVBWORLD_2004] = {
.name = "DVBWorld PCI 2004",
.lnb = {
.mask = DM1105_LNB_MASK,
.off = DM1105_LNB_OFF,
.v13 = DM1105_LNB_13V,
.v18 = DM1105_LNB_18V,
},
},
[DM1105_BOARD_AXESS_DM05] = {
.name = "Axess/EasyTv DM05",
.lnb = {
.mask = DM05_LNB_MASK,
.off = DM05_LNB_OFF,
.v13 = DM05_LNB_13V,
.v18 = DM05_LNB_18V,
},
},
[DM1105_BOARD_UNBRANDED_I2C_ON_GPIO] = {
.name = "Unbranded DM1105 with i2c on GPIOs",
.lnb = {
.mask = UNBR_LNB_MASK,
.off = UNBR_LNB_OFF,
.v13 = UNBR_LNB_13V,
.v18 = UNBR_LNB_18V,
},
.gpio_scl = GPIO14,
.gpio_sda = GPIO13,
},
};
static const struct dm1105_subid dm1105_subids[] = {
{
.subvendor = 0x0000,
.subdevice = 0x2002,
.card = DM1105_BOARD_DVBWORLD_2002,
}, {
.subvendor = 0x0001,
.subdevice = 0x2002,
.card = DM1105_BOARD_DVBWORLD_2002,
}, {
.subvendor = 0x0000,
.subdevice = 0x2004,
.card = DM1105_BOARD_DVBWORLD_2004,
}, {
.subvendor = 0x0001,
.subdevice = 0x2004,
.card = DM1105_BOARD_DVBWORLD_2004,
}, {
.subvendor = 0x195d,
.subdevice = 0x1105,
.card = DM1105_BOARD_AXESS_DM05,
},
};
static void dm1105_card_list(struct pci_dev *pci)
{
int i;
if (0 == pci->subsystem_vendor &&
0 == pci->subsystem_device) {
printk(KERN_ERR
"dm1105: Your board has no valid PCI Subsystem ID\n"
"dm1105: and thus can't be autodetected\n"
"dm1105: Please pass card=<n> insmod option to\n"
"dm1105: workaround that. Redirect complaints to\n"
"dm1105: the vendor of the TV card. Best regards,\n"
"dm1105: -- tux\n");
} else {
printk(KERN_ERR
"dm1105: Your board isn't known (yet) to the driver.\n"
"dm1105: You can try to pick one of the existing\n"
"dm1105: card configs via card=<n> insmod option.\n"
"dm1105: Updating to the latest version might help\n"
"dm1105: as well.\n");
}
printk(KERN_ERR "Here is a list of valid choices for the card=<n> "
"insmod option:\n");
for (i = 0; i < ARRAY_SIZE(dm1105_boards); i++)
printk(KERN_ERR "dm1105: card=%d -> %s\n",
i, dm1105_boards[i].name);
}
/* infrared remote control */
struct infrared {
struct rc_dev *dev;
char input_phys[32];
struct work_struct work;
u32 ir_command;
};
struct dm1105_dev {
/* pci */
struct pci_dev *pdev;
u8 __iomem *io_mem;
/* ir */
struct infrared ir;
/* dvb */
struct dmx_frontend hw_frontend;
struct dmx_frontend mem_frontend;
struct dmxdev dmxdev;
struct dvb_adapter dvb_adapter;
struct dvb_demux demux;
struct dvb_frontend *fe;
struct dvb_net dvbnet;
unsigned int full_ts_users;
unsigned int boardnr;
int nr;
/* i2c */
struct i2c_adapter i2c_adap;
struct i2c_adapter i2c_bb_adap;
struct i2c_algo_bit_data i2c_bit;
/* irq */
struct work_struct work;
struct workqueue_struct *wq;
char wqn[16];
/* dma */
dma_addr_t dma_addr;
unsigned char *ts_buf;
u32 wrp;
u32 nextwrp;
u32 buffer_size;
unsigned int PacketErrorCount;
unsigned int dmarst;
spinlock_t lock;
};
#define dm_io_mem(reg) ((unsigned long)(&dev->io_mem[reg]))
#define dm_readb(reg) inb(dm_io_mem(reg))
#define dm_writeb(reg, value) outb((value), (dm_io_mem(reg)))
#define dm_readw(reg) inw(dm_io_mem(reg))
#define dm_writew(reg, value) outw((value), (dm_io_mem(reg)))
#define dm_readl(reg) inl(dm_io_mem(reg))
#define dm_writel(reg, value) outl((value), (dm_io_mem(reg)))
#define dm_andorl(reg, mask, value) \
outl((inl(dm_io_mem(reg)) & ~(mask)) |\
((value) & (mask)), (dm_io_mem(reg)))
#define dm_setl(reg, bit) dm_andorl((reg), (bit), (bit))
#define dm_clearl(reg, bit) dm_andorl((reg), (bit), 0)
/* The chip has 18 GPIOs. In HOST mode GPIO's used as 15 bit address lines,
so we can use only 3 GPIO's from GPIO15 to GPIO17.
Here I don't check whether HOST is enebled as it is not implemented yet.
*/
static void dm1105_gpio_set(struct dm1105_dev *dev, u32 mask)
{
if (mask & 0xfffc0000)
printk(KERN_ERR "%s: Only 18 GPIO's are allowed\n", __func__);
if (mask & 0x0003ffff)
dm_setl(DM1105_GPIOVAL, mask & 0x0003ffff);
}
static void dm1105_gpio_clear(struct dm1105_dev *dev, u32 mask)
{
if (mask & 0xfffc0000)
printk(KERN_ERR "%s: Only 18 GPIO's are allowed\n", __func__);
if (mask & 0x0003ffff)
dm_clearl(DM1105_GPIOVAL, mask & 0x0003ffff);
}
static void dm1105_gpio_andor(struct dm1105_dev *dev, u32 mask, u32 val)
{
if (mask & 0xfffc0000)
printk(KERN_ERR "%s: Only 18 GPIO's are allowed\n", __func__);
if (mask & 0x0003ffff)
dm_andorl(DM1105_GPIOVAL, mask & 0x0003ffff, val);
}
static u32 dm1105_gpio_get(struct dm1105_dev *dev, u32 mask)
{
if (mask & 0xfffc0000)
printk(KERN_ERR "%s: Only 18 GPIO's are allowed\n", __func__);
if (mask & 0x0003ffff)
return dm_readl(DM1105_GPIOVAL) & mask & 0x0003ffff;
return 0;
}
static void dm1105_gpio_enable(struct dm1105_dev *dev, u32 mask, int asoutput)
{
if (mask & 0xfffc0000)
printk(KERN_ERR "%s: Only 18 GPIO's are allowed\n", __func__);
if ((mask & 0x0003ffff) && asoutput)
dm_clearl(DM1105_GPIOCTR, mask & 0x0003ffff);
else if ((mask & 0x0003ffff) && !asoutput)
dm_setl(DM1105_GPIOCTR, mask & 0x0003ffff);
}
static void dm1105_setline(struct dm1105_dev *dev, u32 line, int state)
{
if (state)
dm1105_gpio_enable(dev, line, 0);
else {
dm1105_gpio_enable(dev, line, 1);
dm1105_gpio_clear(dev, line);
}
}
static void dm1105_setsda(void *data, int state)
{
struct dm1105_dev *dev = data;
dm1105_setline(dev, dm1105_boards[dev->boardnr].gpio_sda, state);
}
static void dm1105_setscl(void *data, int state)
{
struct dm1105_dev *dev = data;
dm1105_setline(dev, dm1105_boards[dev->boardnr].gpio_scl, state);
}
static int dm1105_getsda(void *data)
{
struct dm1105_dev *dev = data;
return dm1105_gpio_get(dev, dm1105_boards[dev->boardnr].gpio_sda)
? 1 : 0;
}
static int dm1105_getscl(void *data)
{
struct dm1105_dev *dev = data;
return dm1105_gpio_get(dev, dm1105_boards[dev->boardnr].gpio_scl)
? 1 : 0;
}
static int dm1105_i2c_xfer(struct i2c_adapter *i2c_adap,
struct i2c_msg *msgs, int num)
{
struct dm1105_dev *dev ;
int addr, rc, i, j, k, len, byte, data;
u8 status;
dev = i2c_adap->algo_data;
for (i = 0; i < num; i++) {
dm_writeb(DM1105_I2CCTR, 0x00);
if (msgs[i].flags & I2C_M_RD) {
/* read bytes */
addr = msgs[i].addr << 1;
addr |= 1;
dm_writeb(DM1105_I2CDAT, addr);
for (byte = 0; byte < msgs[i].len; byte++)
dm_writeb(DM1105_I2CDAT + byte + 1, 0);
dm_writeb(DM1105_I2CCTR, 0x81 + msgs[i].len);
for (j = 0; j < 55; j++) {
mdelay(10);
status = dm_readb(DM1105_I2CSTS);
if ((status & 0xc0) == 0x40)
break;
}
if (j >= 55)
return -1;
for (byte = 0; byte < msgs[i].len; byte++) {
rc = dm_readb(DM1105_I2CDAT + byte + 1);
if (rc < 0)
goto err;
msgs[i].buf[byte] = rc;
}
} else if ((msgs[i].buf[0] == 0xf7) && (msgs[i].addr == 0x55)) {
/* prepaired for cx24116 firmware */
/* Write in small blocks */
len = msgs[i].len - 1;
k = 1;
do {
dm_writeb(DM1105_I2CDAT, msgs[i].addr << 1);
dm_writeb(DM1105_I2CDAT + 1, 0xf7);
for (byte = 0; byte < (len > 48 ? 48 : len); byte++) {
data = msgs[i].buf[k + byte];
dm_writeb(DM1105_I2CDAT + byte + 2, data);
}
dm_writeb(DM1105_I2CCTR, 0x82 + (len > 48 ? 48 : len));
for (j = 0; j < 25; j++) {
mdelay(10);
status = dm_readb(DM1105_I2CSTS);
if ((status & 0xc0) == 0x40)
break;
}
if (j >= 25)
return -1;
k += 48;
len -= 48;
} while (len > 0);
} else {
/* write bytes */
dm_writeb(DM1105_I2CDAT, msgs[i].addr << 1);
for (byte = 0; byte < msgs[i].len; byte++) {
data = msgs[i].buf[byte];
dm_writeb(DM1105_I2CDAT + byte + 1, data);
}
dm_writeb(DM1105_I2CCTR, 0x81 + msgs[i].len);
for (j = 0; j < 25; j++) {
mdelay(10);
status = dm_readb(DM1105_I2CSTS);
if ((status & 0xc0) == 0x40)
break;
}
if (j >= 25)
return -1;
}
}
return num;
err:
return rc;
}
static u32 functionality(struct i2c_adapter *adap)
{
return I2C_FUNC_I2C;
}
static struct i2c_algorithm dm1105_algo = {
.master_xfer = dm1105_i2c_xfer,
.functionality = functionality,
};
static inline struct dm1105_dev *feed_to_dm1105_dev(struct dvb_demux_feed *feed)
{
return container_of(feed->demux, struct dm1105_dev, demux);
}
static inline struct dm1105_dev *frontend_to_dm1105_dev(struct dvb_frontend *fe)
{
return container_of(fe->dvb, struct dm1105_dev, dvb_adapter);
}
static int dm1105_set_voltage(struct dvb_frontend *fe, fe_sec_voltage_t voltage)
{
struct dm1105_dev *dev = frontend_to_dm1105_dev(fe);
dm1105_gpio_enable(dev, dm1105_boards[dev->boardnr].lnb.mask, 1);
if (voltage == SEC_VOLTAGE_18)
dm1105_gpio_andor(dev,
dm1105_boards[dev->boardnr].lnb.mask,
dm1105_boards[dev->boardnr].lnb.v18);
else if (voltage == SEC_VOLTAGE_13)
dm1105_gpio_andor(dev,
dm1105_boards[dev->boardnr].lnb.mask,
dm1105_boards[dev->boardnr].lnb.v13);
else
dm1105_gpio_andor(dev,
dm1105_boards[dev->boardnr].lnb.mask,
dm1105_boards[dev->boardnr].lnb.off);
return 0;
}
static void dm1105_set_dma_addr(struct dm1105_dev *dev)
{
dm_writel(DM1105_STADR, cpu_to_le32(dev->dma_addr));
}
static int __devinit dm1105_dma_map(struct dm1105_dev *dev)
{
dev->ts_buf = pci_alloc_consistent(dev->pdev,
6 * DM1105_DMA_BYTES,
&dev->dma_addr);
return !dev->ts_buf;
}
static void dm1105_dma_unmap(struct dm1105_dev *dev)
{
pci_free_consistent(dev->pdev,
6 * DM1105_DMA_BYTES,
dev->ts_buf,
dev->dma_addr);
}
static void dm1105_enable_irqs(struct dm1105_dev *dev)
{
dm_writeb(DM1105_INTMAK, INTMAK_ALLMASK);
dm_writeb(DM1105_CR, 1);
}
static void dm1105_disable_irqs(struct dm1105_dev *dev)
{
dm_writeb(DM1105_INTMAK, INTMAK_IRM);
dm_writeb(DM1105_CR, 0);
}
static int dm1105_start_feed(struct dvb_demux_feed *f)
{
struct dm1105_dev *dev = feed_to_dm1105_dev(f);
if (dev->full_ts_users++ == 0)
dm1105_enable_irqs(dev);
return 0;
}
static int dm1105_stop_feed(struct dvb_demux_feed *f)
{
struct dm1105_dev *dev = feed_to_dm1105_dev(f);
if (--dev->full_ts_users == 0)
dm1105_disable_irqs(dev);
return 0;
}
/* ir work handler */
static void dm1105_emit_key(struct work_struct *work)
{
struct infrared *ir = container_of(work, struct infrared, work);
u32 ircom = ir->ir_command;
u8 data;
if (ir_debug)
printk(KERN_INFO "%s: received byte 0x%04x\n", __func__, ircom);
data = (ircom >> 8) & 0x7f;
rc_keydown(ir->dev, data, 0);
}
/* work handler */
static void dm1105_dmx_buffer(struct work_struct *work)
{
struct dm1105_dev *dev = container_of(work, struct dm1105_dev, work);
unsigned int nbpackets;
u32 oldwrp = dev->wrp;
u32 nextwrp = dev->nextwrp;
if (!((dev->ts_buf[oldwrp] == 0x47) &&
(dev->ts_buf[oldwrp + 188] == 0x47) &&
(dev->ts_buf[oldwrp + 188 * 2] == 0x47))) {
dev->PacketErrorCount++;
/* bad packet found */
if ((dev->PacketErrorCount >= 2) &&
(dev->dmarst == 0)) {
dm_writeb(DM1105_RST, 1);
dev->wrp = 0;
dev->PacketErrorCount = 0;
dev->dmarst = 0;
return;
}
}
if (nextwrp < oldwrp) {
memcpy(dev->ts_buf + dev->buffer_size, dev->ts_buf, nextwrp);
nbpackets = ((dev->buffer_size - oldwrp) + nextwrp) / 188;
} else
nbpackets = (nextwrp - oldwrp) / 188;
dev->wrp = nextwrp;
dvb_dmx_swfilter_packets(&dev->demux, &dev->ts_buf[oldwrp], nbpackets);
}
static irqreturn_t dm1105_irq(int irq, void *dev_id)
{
struct dm1105_dev *dev = dev_id;
/* Read-Write INSTS Ack's Interrupt for DM1105 chip 16.03.2008 */
unsigned int intsts = dm_readb(DM1105_INTSTS);
dm_writeb(DM1105_INTSTS, intsts);
switch (intsts) {
case INTSTS_TSIRQ:
case (INTSTS_TSIRQ | INTSTS_IR):
dev->nextwrp = dm_readl(DM1105_WRP) - dm_readl(DM1105_STADR);
queue_work(dev->wq, &dev->work);
break;
case INTSTS_IR:
dev->ir.ir_command = dm_readl(DM1105_IRCODE);
schedule_work(&dev->ir.work);
break;
}
return IRQ_HANDLED;
}
int __devinit dm1105_ir_init(struct dm1105_dev *dm1105)
{
struct rc_dev *dev;
int err = -ENOMEM;
dev = rc_allocate_device();
if (!dev)
return -ENOMEM;
snprintf(dm1105->ir.input_phys, sizeof(dm1105->ir.input_phys),
"pci-%s/ir0", pci_name(dm1105->pdev));
dev->driver_name = MODULE_NAME;
dev->map_name = RC_MAP_DM1105_NEC;
dev->driver_type = RC_DRIVER_SCANCODE;
dev->input_name = "DVB on-card IR receiver";
dev->input_phys = dm1105->ir.input_phys;
dev->input_id.bustype = BUS_PCI;
dev->input_id.version = 1;
if (dm1105->pdev->subsystem_vendor) {
dev->input_id.vendor = dm1105->pdev->subsystem_vendor;
dev->input_id.product = dm1105->pdev->subsystem_device;
} else {
dev->input_id.vendor = dm1105->pdev->vendor;
dev->input_id.product = dm1105->pdev->device;
}
dev->dev.parent = &dm1105->pdev->dev;
INIT_WORK(&dm1105->ir.work, dm1105_emit_key);
err = rc_register_device(dev);
if (err < 0) {
rc_free_device(dev);
return err;
}
dm1105->ir.dev = dev;
return 0;
}
void __devexit dm1105_ir_exit(struct dm1105_dev *dm1105)
{
rc_unregister_device(dm1105->ir.dev);
}
static int __devinit dm1105_hw_init(struct dm1105_dev *dev)
{
dm1105_disable_irqs(dev);
dm_writeb(DM1105_HOST_CTR, 0);
/*DATALEN 188,*/
dm_writeb(DM1105_DTALENTH, 188);
/*TS_STRT TS_VALP MSBFIRST TS_MODE ALPAS TSPES*/
dm_writew(DM1105_TSCTR, 0xc10a);
/* map DMA and set address */
dm1105_dma_map(dev);
dm1105_set_dma_addr(dev);
/* big buffer */
dm_writel(DM1105_RLEN, 5 * DM1105_DMA_BYTES);
dm_writeb(DM1105_INTCNT, 47);
/* IR NEC mode enable */
dm_writeb(DM1105_IRCTR, (DM1105_IR_EN | DM1105_SYS_CHK));
dm_writeb(DM1105_IRMODE, 0);
dm_writew(DM1105_SYSTEMCODE, 0);
return 0;
}
static void dm1105_hw_exit(struct dm1105_dev *dev)
{
dm1105_disable_irqs(dev);
/* IR disable */
dm_writeb(DM1105_IRCTR, 0);
dm_writeb(DM1105_INTMAK, INTMAK_NONEMASK);
dm1105_dma_unmap(dev);
}
static struct stv0299_config sharp_z0194a_config = {
.demod_address = 0x68,
.inittab = sharp_z0194a_inittab,
.mclk = 88000000UL,
.invert = 1,
.skip_reinit = 0,
.lock_output = STV0299_LOCKOUTPUT_1,
.volt13_op0_op1 = STV0299_VOLT13_OP1,
.min_delay_ms = 100,
.set_symbol_rate = sharp_z0194a_set_symbol_rate,
};
static struct stv0288_config earda_config = {
.demod_address = 0x68,
.min_delay_ms = 100,
};
static struct si21xx_config serit_config = {
.demod_address = 0x68,
.min_delay_ms = 100,
};
static struct cx24116_config serit_sp2633_config = {
.demod_address = 0x55,
};
static struct ds3000_config dvbworld_ds3000_config = {
.demod_address = 0x68,
};
static int __devinit frontend_init(struct dm1105_dev *dev)
{
int ret;
switch (dev->boardnr) {
case DM1105_BOARD_UNBRANDED_I2C_ON_GPIO:
dm1105_gpio_enable(dev, GPIO15, 1);
dm1105_gpio_clear(dev, GPIO15);
msleep(100);
dm1105_gpio_set(dev, GPIO15);
msleep(200);
dev->fe = dvb_attach(
stv0299_attach, &sharp_z0194a_config,
&dev->i2c_bb_adap);
if (dev->fe) {
dev->fe->ops.set_voltage = dm1105_set_voltage;
dvb_attach(dvb_pll_attach, dev->fe, 0x60,
&dev->i2c_bb_adap, DVB_PLL_OPERA1);
break;
}
dev->fe = dvb_attach(
stv0288_attach, &earda_config,
&dev->i2c_bb_adap);
if (dev->fe) {
dev->fe->ops.set_voltage = dm1105_set_voltage;
dvb_attach(stb6000_attach, dev->fe, 0x61,
&dev->i2c_bb_adap);
break;
}
dev->fe = dvb_attach(
si21xx_attach, &serit_config,
&dev->i2c_bb_adap);
if (dev->fe)
dev->fe->ops.set_voltage = dm1105_set_voltage;
break;
case DM1105_BOARD_DVBWORLD_2004:
dev->fe = dvb_attach(
cx24116_attach, &serit_sp2633_config,
&dev->i2c_adap);
if (dev->fe) {
dev->fe->ops.set_voltage = dm1105_set_voltage;
break;
}
dev->fe = dvb_attach(
ds3000_attach, &dvbworld_ds3000_config,
&dev->i2c_adap);
if (dev->fe)
dev->fe->ops.set_voltage = dm1105_set_voltage;
break;
case DM1105_BOARD_DVBWORLD_2002:
case DM1105_BOARD_AXESS_DM05:
default:
dev->fe = dvb_attach(
stv0299_attach, &sharp_z0194a_config,
&dev->i2c_adap);
if (dev->fe) {
dev->fe->ops.set_voltage = dm1105_set_voltage;
dvb_attach(dvb_pll_attach, dev->fe, 0x60,
&dev->i2c_adap, DVB_PLL_OPERA1);
break;
}
dev->fe = dvb_attach(
stv0288_attach, &earda_config,
&dev->i2c_adap);
if (dev->fe) {
dev->fe->ops.set_voltage = dm1105_set_voltage;
dvb_attach(stb6000_attach, dev->fe, 0x61,
&dev->i2c_adap);
break;
}
dev->fe = dvb_attach(
si21xx_attach, &serit_config,
&dev->i2c_adap);
if (dev->fe)
dev->fe->ops.set_voltage = dm1105_set_voltage;
}
if (!dev->fe) {
dev_err(&dev->pdev->dev, "could not attach frontend\n");
return -ENODEV;
}
ret = dvb_register_frontend(&dev->dvb_adapter, dev->fe);
if (ret < 0) {
if (dev->fe->ops.release)
dev->fe->ops.release(dev->fe);
dev->fe = NULL;
return ret;
}
return 0;
}
static void __devinit dm1105_read_mac(struct dm1105_dev *dev, u8 *mac)
{
static u8 command[1] = { 0x28 };
struct i2c_msg msg[] = {
{
.addr = IIC_24C01_addr >> 1,
.flags = 0,
.buf = command,
.len = 1
}, {
.addr = IIC_24C01_addr >> 1,
.flags = I2C_M_RD,
.buf = mac,
.len = 6
},
};
dm1105_i2c_xfer(&dev->i2c_adap, msg , 2);
dev_info(&dev->pdev->dev, "MAC %pM\n", mac);
}
static int __devinit dm1105_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct dm1105_dev *dev;
struct dvb_adapter *dvb_adapter;
struct dvb_demux *dvbdemux;
struct dmx_demux *dmx;
int ret = -ENOMEM;
int i;
dev = kzalloc(sizeof(struct dm1105_dev), GFP_KERNEL);
if (!dev)
return -ENOMEM;
/* board config */
dev->nr = dm1105_devcount;
dev->boardnr = UNSET;
if (card[dev->nr] < ARRAY_SIZE(dm1105_boards))
dev->boardnr = card[dev->nr];
for (i = 0; UNSET == dev->boardnr &&
i < ARRAY_SIZE(dm1105_subids); i++)
if (pdev->subsystem_vendor ==
dm1105_subids[i].subvendor &&
pdev->subsystem_device ==
dm1105_subids[i].subdevice)
dev->boardnr = dm1105_subids[i].card;
if (UNSET == dev->boardnr) {
dev->boardnr = DM1105_BOARD_UNKNOWN;
dm1105_card_list(pdev);
}
dm1105_devcount++;
dev->pdev = pdev;
dev->buffer_size = 5 * DM1105_DMA_BYTES;
dev->PacketErrorCount = 0;
dev->dmarst = 0;
ret = pci_enable_device(pdev);
if (ret < 0)
goto err_kfree;
ret = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (ret < 0)
goto err_pci_disable_device;
pci_set_master(pdev);
ret = pci_request_regions(pdev, DRIVER_NAME);
if (ret < 0)
goto err_pci_disable_device;
dev->io_mem = pci_iomap(pdev, 0, pci_resource_len(pdev, 0));
if (!dev->io_mem) {
ret = -EIO;
goto err_pci_release_regions;
}
spin_lock_init(&dev->lock);
pci_set_drvdata(pdev, dev);
ret = dm1105_hw_init(dev);
if (ret < 0)
goto err_pci_iounmap;
/* i2c */
i2c_set_adapdata(&dev->i2c_adap, dev);
strcpy(dev->i2c_adap.name, DRIVER_NAME);
dev->i2c_adap.owner = THIS_MODULE;
dev->i2c_adap.dev.parent = &pdev->dev;
dev->i2c_adap.algo = &dm1105_algo;
dev->i2c_adap.algo_data = dev;
ret = i2c_add_adapter(&dev->i2c_adap);
if (ret < 0)
goto err_dm1105_hw_exit;
i2c_set_adapdata(&dev->i2c_bb_adap, dev);
strcpy(dev->i2c_bb_adap.name, DM1105_I2C_GPIO_NAME);
dev->i2c_bb_adap.owner = THIS_MODULE;
dev->i2c_bb_adap.dev.parent = &pdev->dev;
dev->i2c_bb_adap.algo_data = &dev->i2c_bit;
dev->i2c_bit.data = dev;
dev->i2c_bit.setsda = dm1105_setsda;
dev->i2c_bit.setscl = dm1105_setscl;
dev->i2c_bit.getsda = dm1105_getsda;
dev->i2c_bit.getscl = dm1105_getscl;
dev->i2c_bit.udelay = 10;
dev->i2c_bit.timeout = 10;
/* Raise SCL and SDA */
dm1105_setsda(dev, 1);
dm1105_setscl(dev, 1);
ret = i2c_bit_add_bus(&dev->i2c_bb_adap);
if (ret < 0)
goto err_i2c_del_adapter;
/* dvb */
ret = dvb_register_adapter(&dev->dvb_adapter, DRIVER_NAME,
THIS_MODULE, &pdev->dev, adapter_nr);
if (ret < 0)
goto err_i2c_del_adapters;
dvb_adapter = &dev->dvb_adapter;
dm1105_read_mac(dev, dvb_adapter->proposed_mac);
dvbdemux = &dev->demux;
dvbdemux->filternum = 256;
dvbdemux->feednum = 256;
dvbdemux->start_feed = dm1105_start_feed;
dvbdemux->stop_feed = dm1105_stop_feed;
dvbdemux->dmx.capabilities = (DMX_TS_FILTERING |
DMX_SECTION_FILTERING | DMX_MEMORY_BASED_FILTERING);
ret = dvb_dmx_init(dvbdemux);
if (ret < 0)
goto err_dvb_unregister_adapter;
dmx = &dvbdemux->dmx;
dev->dmxdev.filternum = 256;
dev->dmxdev.demux = dmx;
dev->dmxdev.capabilities = 0;
ret = dvb_dmxdev_init(&dev->dmxdev, dvb_adapter);
if (ret < 0)
goto err_dvb_dmx_release;
dev->hw_frontend.source = DMX_FRONTEND_0;
ret = dmx->add_frontend(dmx, &dev->hw_frontend);
if (ret < 0)
goto err_dvb_dmxdev_release;
dev->mem_frontend.source = DMX_MEMORY_FE;
ret = dmx->add_frontend(dmx, &dev->mem_frontend);
if (ret < 0)
goto err_remove_hw_frontend;
ret = dmx->connect_frontend(dmx, &dev->hw_frontend);
if (ret < 0)
goto err_remove_mem_frontend;
ret = dvb_net_init(dvb_adapter, &dev->dvbnet, dmx);
if (ret < 0)
goto err_disconnect_frontend;
ret = frontend_init(dev);
if (ret < 0)
goto err_dvb_net;
dm1105_ir_init(dev);
INIT_WORK(&dev->work, dm1105_dmx_buffer);
sprintf(dev->wqn, "%s/%d", dvb_adapter->name, dvb_adapter->num);
dev->wq = create_singlethread_workqueue(dev->wqn);
if (!dev->wq)
goto err_dvb_net;
ret = request_irq(pdev->irq, dm1105_irq, IRQF_SHARED,
DRIVER_NAME, dev);
if (ret < 0)
goto err_workqueue;
return 0;
err_workqueue:
destroy_workqueue(dev->wq);
err_dvb_net:
dvb_net_release(&dev->dvbnet);
err_disconnect_frontend:
dmx->disconnect_frontend(dmx);
err_remove_mem_frontend:
dmx->remove_frontend(dmx, &dev->mem_frontend);
err_remove_hw_frontend:
dmx->remove_frontend(dmx, &dev->hw_frontend);
err_dvb_dmxdev_release:
dvb_dmxdev_release(&dev->dmxdev);
err_dvb_dmx_release:
dvb_dmx_release(dvbdemux);
err_dvb_unregister_adapter:
dvb_unregister_adapter(dvb_adapter);
err_i2c_del_adapters:
i2c_del_adapter(&dev->i2c_bb_adap);
err_i2c_del_adapter:
i2c_del_adapter(&dev->i2c_adap);
err_dm1105_hw_exit:
dm1105_hw_exit(dev);
err_pci_iounmap:
pci_iounmap(pdev, dev->io_mem);
err_pci_release_regions:
pci_release_regions(pdev);
err_pci_disable_device:
pci_disable_device(pdev);
err_kfree:
pci_set_drvdata(pdev, NULL);
kfree(dev);
return ret;
}
static void __devexit dm1105_remove(struct pci_dev *pdev)
{
struct dm1105_dev *dev = pci_get_drvdata(pdev);
struct dvb_adapter *dvb_adapter = &dev->dvb_adapter;
struct dvb_demux *dvbdemux = &dev->demux;
struct dmx_demux *dmx = &dvbdemux->dmx;
dm1105_ir_exit(dev);
dmx->close(dmx);
dvb_net_release(&dev->dvbnet);
if (dev->fe)
dvb_unregister_frontend(dev->fe);
dmx->disconnect_frontend(dmx);
dmx->remove_frontend(dmx, &dev->mem_frontend);
dmx->remove_frontend(dmx, &dev->hw_frontend);
dvb_dmxdev_release(&dev->dmxdev);
dvb_dmx_release(dvbdemux);
dvb_unregister_adapter(dvb_adapter);
if (&dev->i2c_adap)
i2c_del_adapter(&dev->i2c_adap);
dm1105_hw_exit(dev);
synchronize_irq(pdev->irq);
free_irq(pdev->irq, dev);
pci_iounmap(pdev, dev->io_mem);
pci_release_regions(pdev);
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
dm1105_devcount--;
kfree(dev);
}
static struct pci_device_id dm1105_id_table[] __devinitdata = {
{
.vendor = PCI_VENDOR_ID_TRIGEM,
.device = PCI_DEVICE_ID_DM1105,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
}, {
.vendor = PCI_VENDOR_ID_AXESS,
.device = PCI_DEVICE_ID_DM05,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
}, {
/* empty */
},
};
MODULE_DEVICE_TABLE(pci, dm1105_id_table);
static struct pci_driver dm1105_driver = {
.name = DRIVER_NAME,
.id_table = dm1105_id_table,
.probe = dm1105_probe,
.remove = __devexit_p(dm1105_remove),
};
static int __init dm1105_init(void)
{
return pci_register_driver(&dm1105_driver);
}
static void __exit dm1105_exit(void)
{
pci_unregister_driver(&dm1105_driver);
}
module_init(dm1105_init);
module_exit(dm1105_exit);
MODULE_AUTHOR("Igor M. Liplianin <liplianin@me.by>");
MODULE_DESCRIPTION("SDMC DM1105 DVB driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
BrateloSlava/test-sez-cm-kernel | drivers/hid/hid-gaff.c | 5329 | 4868 | /*
* Force feedback support for GreenAsia (Product ID 0x12) based devices
*
* The devices are distributed under various names and the same USB device ID
* can be used in many game controllers.
*
*
* 0e8f:0012 "GreenAsia Inc. USB Joystick "
* - tested with MANTA Warior MM816 and SpeedLink Strike2 SL-6635.
*
* Copyright (c) 2008 Lukasz Lubojanski <lukasz@lubojanski.info>
*/
/*
* 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/input.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include <linux/hid.h>
#include <linux/module.h>
#include "hid-ids.h"
#ifdef CONFIG_GREENASIA_FF
#include "usbhid/usbhid.h"
struct gaff_device {
struct hid_report *report;
};
static int hid_gaff_play(struct input_dev *dev, void *data,
struct ff_effect *effect)
{
struct hid_device *hid = input_get_drvdata(dev);
struct gaff_device *gaff = data;
int left, right;
left = effect->u.rumble.strong_magnitude;
right = effect->u.rumble.weak_magnitude;
dbg_hid("called with 0x%04x 0x%04x", left, right);
left = left * 0xfe / 0xffff;
right = right * 0xfe / 0xffff;
gaff->report->field[0]->value[0] = 0x51;
gaff->report->field[0]->value[1] = 0x0;
gaff->report->field[0]->value[2] = right;
gaff->report->field[0]->value[3] = 0;
gaff->report->field[0]->value[4] = left;
gaff->report->field[0]->value[5] = 0;
dbg_hid("running with 0x%02x 0x%02x", left, right);
usbhid_submit_report(hid, gaff->report, USB_DIR_OUT);
gaff->report->field[0]->value[0] = 0xfa;
gaff->report->field[0]->value[1] = 0xfe;
gaff->report->field[0]->value[2] = 0x0;
gaff->report->field[0]->value[4] = 0x0;
usbhid_submit_report(hid, gaff->report, USB_DIR_OUT);
return 0;
}
static int gaff_init(struct hid_device *hid)
{
struct gaff_device *gaff;
struct hid_report *report;
struct hid_input *hidinput = list_entry(hid->inputs.next,
struct hid_input, list);
struct list_head *report_list =
&hid->report_enum[HID_OUTPUT_REPORT].report_list;
struct list_head *report_ptr = report_list;
struct input_dev *dev = hidinput->input;
int error;
if (list_empty(report_list)) {
hid_err(hid, "no output reports found\n");
return -ENODEV;
}
report_ptr = report_ptr->next;
report = list_entry(report_ptr, struct hid_report, list);
if (report->maxfield < 1) {
hid_err(hid, "no fields in the report\n");
return -ENODEV;
}
if (report->field[0]->report_count < 6) {
hid_err(hid, "not enough values in the field\n");
return -ENODEV;
}
gaff = kzalloc(sizeof(struct gaff_device), GFP_KERNEL);
if (!gaff)
return -ENOMEM;
set_bit(FF_RUMBLE, dev->ffbit);
error = input_ff_create_memless(dev, gaff, hid_gaff_play);
if (error) {
kfree(gaff);
return error;
}
gaff->report = report;
gaff->report->field[0]->value[0] = 0x51;
gaff->report->field[0]->value[1] = 0x00;
gaff->report->field[0]->value[2] = 0x00;
gaff->report->field[0]->value[3] = 0x00;
usbhid_submit_report(hid, gaff->report, USB_DIR_OUT);
gaff->report->field[0]->value[0] = 0xfa;
gaff->report->field[0]->value[1] = 0xfe;
usbhid_submit_report(hid, gaff->report, USB_DIR_OUT);
hid_info(hid, "Force Feedback for GreenAsia 0x12 devices by Lukasz Lubojanski <lukasz@lubojanski.info>\n");
return 0;
}
#else
static inline int gaff_init(struct hid_device *hdev)
{
return 0;
}
#endif
static int ga_probe(struct hid_device *hdev, const struct hid_device_id *id)
{
int ret;
dev_dbg(&hdev->dev, "Greenasia HID hardware probe...");
ret = hid_parse(hdev);
if (ret) {
hid_err(hdev, "parse failed\n");
goto err;
}
ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT & ~HID_CONNECT_FF);
if (ret) {
hid_err(hdev, "hw start failed\n");
goto err;
}
gaff_init(hdev);
return 0;
err:
return ret;
}
static const struct hid_device_id ga_devices[] = {
{ HID_USB_DEVICE(USB_VENDOR_ID_GREENASIA, 0x0012), },
{ }
};
MODULE_DEVICE_TABLE(hid, ga_devices);
static struct hid_driver ga_driver = {
.name = "greenasia",
.id_table = ga_devices,
.probe = ga_probe,
};
static int __init ga_init(void)
{
return hid_register_driver(&ga_driver);
}
static void __exit ga_exit(void)
{
hid_unregister_driver(&ga_driver);
}
module_init(ga_init);
module_exit(ga_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
mrjaydee82/SinLessKerne1-m8-4.4.4 | drivers/hid/hid-gaff.c | 5329 | 4868 | /*
* Force feedback support for GreenAsia (Product ID 0x12) based devices
*
* The devices are distributed under various names and the same USB device ID
* can be used in many game controllers.
*
*
* 0e8f:0012 "GreenAsia Inc. USB Joystick "
* - tested with MANTA Warior MM816 and SpeedLink Strike2 SL-6635.
*
* Copyright (c) 2008 Lukasz Lubojanski <lukasz@lubojanski.info>
*/
/*
* 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/input.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include <linux/hid.h>
#include <linux/module.h>
#include "hid-ids.h"
#ifdef CONFIG_GREENASIA_FF
#include "usbhid/usbhid.h"
struct gaff_device {
struct hid_report *report;
};
static int hid_gaff_play(struct input_dev *dev, void *data,
struct ff_effect *effect)
{
struct hid_device *hid = input_get_drvdata(dev);
struct gaff_device *gaff = data;
int left, right;
left = effect->u.rumble.strong_magnitude;
right = effect->u.rumble.weak_magnitude;
dbg_hid("called with 0x%04x 0x%04x", left, right);
left = left * 0xfe / 0xffff;
right = right * 0xfe / 0xffff;
gaff->report->field[0]->value[0] = 0x51;
gaff->report->field[0]->value[1] = 0x0;
gaff->report->field[0]->value[2] = right;
gaff->report->field[0]->value[3] = 0;
gaff->report->field[0]->value[4] = left;
gaff->report->field[0]->value[5] = 0;
dbg_hid("running with 0x%02x 0x%02x", left, right);
usbhid_submit_report(hid, gaff->report, USB_DIR_OUT);
gaff->report->field[0]->value[0] = 0xfa;
gaff->report->field[0]->value[1] = 0xfe;
gaff->report->field[0]->value[2] = 0x0;
gaff->report->field[0]->value[4] = 0x0;
usbhid_submit_report(hid, gaff->report, USB_DIR_OUT);
return 0;
}
static int gaff_init(struct hid_device *hid)
{
struct gaff_device *gaff;
struct hid_report *report;
struct hid_input *hidinput = list_entry(hid->inputs.next,
struct hid_input, list);
struct list_head *report_list =
&hid->report_enum[HID_OUTPUT_REPORT].report_list;
struct list_head *report_ptr = report_list;
struct input_dev *dev = hidinput->input;
int error;
if (list_empty(report_list)) {
hid_err(hid, "no output reports found\n");
return -ENODEV;
}
report_ptr = report_ptr->next;
report = list_entry(report_ptr, struct hid_report, list);
if (report->maxfield < 1) {
hid_err(hid, "no fields in the report\n");
return -ENODEV;
}
if (report->field[0]->report_count < 6) {
hid_err(hid, "not enough values in the field\n");
return -ENODEV;
}
gaff = kzalloc(sizeof(struct gaff_device), GFP_KERNEL);
if (!gaff)
return -ENOMEM;
set_bit(FF_RUMBLE, dev->ffbit);
error = input_ff_create_memless(dev, gaff, hid_gaff_play);
if (error) {
kfree(gaff);
return error;
}
gaff->report = report;
gaff->report->field[0]->value[0] = 0x51;
gaff->report->field[0]->value[1] = 0x00;
gaff->report->field[0]->value[2] = 0x00;
gaff->report->field[0]->value[3] = 0x00;
usbhid_submit_report(hid, gaff->report, USB_DIR_OUT);
gaff->report->field[0]->value[0] = 0xfa;
gaff->report->field[0]->value[1] = 0xfe;
usbhid_submit_report(hid, gaff->report, USB_DIR_OUT);
hid_info(hid, "Force Feedback for GreenAsia 0x12 devices by Lukasz Lubojanski <lukasz@lubojanski.info>\n");
return 0;
}
#else
static inline int gaff_init(struct hid_device *hdev)
{
return 0;
}
#endif
static int ga_probe(struct hid_device *hdev, const struct hid_device_id *id)
{
int ret;
dev_dbg(&hdev->dev, "Greenasia HID hardware probe...");
ret = hid_parse(hdev);
if (ret) {
hid_err(hdev, "parse failed\n");
goto err;
}
ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT & ~HID_CONNECT_FF);
if (ret) {
hid_err(hdev, "hw start failed\n");
goto err;
}
gaff_init(hdev);
return 0;
err:
return ret;
}
static const struct hid_device_id ga_devices[] = {
{ HID_USB_DEVICE(USB_VENDOR_ID_GREENASIA, 0x0012), },
{ }
};
MODULE_DEVICE_TABLE(hid, ga_devices);
static struct hid_driver ga_driver = {
.name = "greenasia",
.id_table = ga_devices,
.probe = ga_probe,
};
static int __init ga_init(void)
{
return hid_register_driver(&ga_driver);
}
static void __exit ga_exit(void)
{
hid_unregister_driver(&ga_driver);
}
module_init(ga_init);
module_exit(ga_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
uDude/linux | arch/mips/rb532/time.c | 14033 | 1976 | /*
* Carsten Langgaard, carstenl@mips.com
* Copyright (C) 1999,2000 MIPS Technologies, Inc. All rights reserved.
*
* This program is free software; you can distribute it and/or modify it
* under the terms of the GNU General Public License (Version 2) as
* published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
*
* Setting up the clock on the MIPS boards.
*/
#include <linux/init.h>
#include <linux/kernel_stat.h>
#include <linux/ptrace.h>
#include <linux/sched.h>
#include <linux/spinlock.h>
#include <linux/mc146818rtc.h>
#include <linux/irq.h>
#include <linux/timex.h>
#include <asm/mipsregs.h>
#include <asm/time.h>
#include <asm/mach-rc32434/rc32434.h>
extern unsigned int idt_cpu_freq;
/*
* Figure out the r4k offset, the amount to increment the compare
* register for each time tick. There is no RTC available.
*
* The RC32434 counts at half the CPU *core* speed.
*/
static unsigned long __init cal_r4koff(void)
{
mips_hpt_frequency = idt_cpu_freq * IDT_CLOCK_MULT / 2;
return mips_hpt_frequency / HZ;
}
void __init plat_time_init(void)
{
unsigned int est_freq;
unsigned long flags, r4k_offset;
local_irq_save(flags);
printk(KERN_INFO "calculating r4koff... ");
r4k_offset = cal_r4koff();
printk("%08lx(%d)\n", r4k_offset, (int) r4k_offset);
est_freq = 2 * r4k_offset * HZ;
est_freq += 5000; /* round */
est_freq -= est_freq % 10000;
printk(KERN_INFO "CPU frequency %d.%02d MHz\n", est_freq / 1000000,
(est_freq % 1000000) * 100 / 1000000);
local_irq_restore(flags);
}
| gpl-2.0 |
AnesHadzi/linux-socfpga | drivers/net/ethernet/sfc/mcdi.c | 210 | 56050 | /****************************************************************************
* Driver for Solarflare network controllers and boards
* Copyright 2008-2013 Solarflare Communications Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include <linux/delay.h>
#include <linux/moduleparam.h>
#include <asm/cmpxchg.h>
#include "net_driver.h"
#include "nic.h"
#include "io.h"
#include "farch_regs.h"
#include "mcdi_pcol.h"
#include "phy.h"
/**************************************************************************
*
* Management-Controller-to-Driver Interface
*
**************************************************************************
*/
#define MCDI_RPC_TIMEOUT (10 * HZ)
/* A reboot/assertion causes the MCDI status word to be set after the
* command word is set or a REBOOT event is sent. If we notice a reboot
* via these mechanisms then wait 250ms for the status word to be set.
*/
#define MCDI_STATUS_DELAY_US 100
#define MCDI_STATUS_DELAY_COUNT 2500
#define MCDI_STATUS_SLEEP_MS \
(MCDI_STATUS_DELAY_US * MCDI_STATUS_DELAY_COUNT / 1000)
#define SEQ_MASK \
EFX_MASK32(EFX_WIDTH(MCDI_HEADER_SEQ))
struct efx_mcdi_async_param {
struct list_head list;
unsigned int cmd;
size_t inlen;
size_t outlen;
bool quiet;
efx_mcdi_async_completer *complete;
unsigned long cookie;
/* followed by request/response buffer */
};
static void efx_mcdi_timeout_async(unsigned long context);
static int efx_mcdi_drv_attach(struct efx_nic *efx, bool driver_operating,
bool *was_attached_out);
static bool efx_mcdi_poll_once(struct efx_nic *efx);
static void efx_mcdi_abandon(struct efx_nic *efx);
#ifdef CONFIG_SFC_MCDI_LOGGING
static bool mcdi_logging_default;
module_param(mcdi_logging_default, bool, 0644);
MODULE_PARM_DESC(mcdi_logging_default,
"Enable MCDI logging on newly-probed functions");
#endif
int efx_mcdi_init(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi;
bool already_attached;
int rc = -ENOMEM;
efx->mcdi = kzalloc(sizeof(*efx->mcdi), GFP_KERNEL);
if (!efx->mcdi)
goto fail;
mcdi = efx_mcdi(efx);
mcdi->efx = efx;
#ifdef CONFIG_SFC_MCDI_LOGGING
/* consuming code assumes buffer is page-sized */
mcdi->logging_buffer = (char *)__get_free_page(GFP_KERNEL);
if (!mcdi->logging_buffer)
goto fail1;
mcdi->logging_enabled = mcdi_logging_default;
#endif
init_waitqueue_head(&mcdi->wq);
spin_lock_init(&mcdi->iface_lock);
mcdi->state = MCDI_STATE_QUIESCENT;
mcdi->mode = MCDI_MODE_POLL;
spin_lock_init(&mcdi->async_lock);
INIT_LIST_HEAD(&mcdi->async_list);
setup_timer(&mcdi->async_timer, efx_mcdi_timeout_async,
(unsigned long)mcdi);
(void) efx_mcdi_poll_reboot(efx);
mcdi->new_epoch = true;
/* Recover from a failed assertion before probing */
rc = efx_mcdi_handle_assertion(efx);
if (rc)
goto fail2;
/* Let the MC (and BMC, if this is a LOM) know that the driver
* is loaded. We should do this before we reset the NIC.
*/
rc = efx_mcdi_drv_attach(efx, true, &already_attached);
if (rc) {
netif_err(efx, probe, efx->net_dev,
"Unable to register driver with MCPU\n");
goto fail2;
}
if (already_attached)
/* Not a fatal error */
netif_err(efx, probe, efx->net_dev,
"Host already registered with MCPU\n");
if (efx->mcdi->fn_flags &
(1 << MC_CMD_DRV_ATTACH_EXT_OUT_FLAG_PRIMARY))
efx->primary = efx;
return 0;
fail2:
#ifdef CONFIG_SFC_MCDI_LOGGING
free_page((unsigned long)mcdi->logging_buffer);
fail1:
#endif
kfree(efx->mcdi);
efx->mcdi = NULL;
fail:
return rc;
}
void efx_mcdi_fini(struct efx_nic *efx)
{
if (!efx->mcdi)
return;
BUG_ON(efx->mcdi->iface.state != MCDI_STATE_QUIESCENT);
/* Relinquish the device (back to the BMC, if this is a LOM) */
efx_mcdi_drv_attach(efx, false, NULL);
#ifdef CONFIG_SFC_MCDI_LOGGING
free_page((unsigned long)efx->mcdi->iface.logging_buffer);
#endif
kfree(efx->mcdi);
}
static void efx_mcdi_send_request(struct efx_nic *efx, unsigned cmd,
const efx_dword_t *inbuf, size_t inlen)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
#ifdef CONFIG_SFC_MCDI_LOGGING
char *buf = mcdi->logging_buffer; /* page-sized */
#endif
efx_dword_t hdr[2];
size_t hdr_len;
u32 xflags, seqno;
BUG_ON(mcdi->state == MCDI_STATE_QUIESCENT);
/* Serialise with efx_mcdi_ev_cpl() and efx_mcdi_ev_death() */
spin_lock_bh(&mcdi->iface_lock);
++mcdi->seqno;
spin_unlock_bh(&mcdi->iface_lock);
seqno = mcdi->seqno & SEQ_MASK;
xflags = 0;
if (mcdi->mode == MCDI_MODE_EVENTS)
xflags |= MCDI_HEADER_XFLAGS_EVREQ;
if (efx->type->mcdi_max_ver == 1) {
/* MCDI v1 */
EFX_POPULATE_DWORD_7(hdr[0],
MCDI_HEADER_RESPONSE, 0,
MCDI_HEADER_RESYNC, 1,
MCDI_HEADER_CODE, cmd,
MCDI_HEADER_DATALEN, inlen,
MCDI_HEADER_SEQ, seqno,
MCDI_HEADER_XFLAGS, xflags,
MCDI_HEADER_NOT_EPOCH, !mcdi->new_epoch);
hdr_len = 4;
} else {
/* MCDI v2 */
BUG_ON(inlen > MCDI_CTL_SDU_LEN_MAX_V2);
EFX_POPULATE_DWORD_7(hdr[0],
MCDI_HEADER_RESPONSE, 0,
MCDI_HEADER_RESYNC, 1,
MCDI_HEADER_CODE, MC_CMD_V2_EXTN,
MCDI_HEADER_DATALEN, 0,
MCDI_HEADER_SEQ, seqno,
MCDI_HEADER_XFLAGS, xflags,
MCDI_HEADER_NOT_EPOCH, !mcdi->new_epoch);
EFX_POPULATE_DWORD_2(hdr[1],
MC_CMD_V2_EXTN_IN_EXTENDED_CMD, cmd,
MC_CMD_V2_EXTN_IN_ACTUAL_LEN, inlen);
hdr_len = 8;
}
#ifdef CONFIG_SFC_MCDI_LOGGING
if (mcdi->logging_enabled && !WARN_ON_ONCE(!buf)) {
int bytes = 0;
int i;
/* Lengths should always be a whole number of dwords, so scream
* if they're not.
*/
WARN_ON_ONCE(hdr_len % 4);
WARN_ON_ONCE(inlen % 4);
/* We own the logging buffer, as only one MCDI can be in
* progress on a NIC at any one time. So no need for locking.
*/
for (i = 0; i < hdr_len / 4 && bytes < PAGE_SIZE; i++)
bytes += snprintf(buf + bytes, PAGE_SIZE - bytes,
" %08x", le32_to_cpu(hdr[i].u32[0]));
for (i = 0; i < inlen / 4 && bytes < PAGE_SIZE; i++)
bytes += snprintf(buf + bytes, PAGE_SIZE - bytes,
" %08x", le32_to_cpu(inbuf[i].u32[0]));
netif_info(efx, hw, efx->net_dev, "MCDI RPC REQ:%s\n", buf);
}
#endif
efx->type->mcdi_request(efx, hdr, hdr_len, inbuf, inlen);
mcdi->new_epoch = false;
}
static int efx_mcdi_errno(unsigned int mcdi_err)
{
switch (mcdi_err) {
case 0:
return 0;
#define TRANSLATE_ERROR(name) \
case MC_CMD_ERR_ ## name: \
return -name;
TRANSLATE_ERROR(EPERM);
TRANSLATE_ERROR(ENOENT);
TRANSLATE_ERROR(EINTR);
TRANSLATE_ERROR(EAGAIN);
TRANSLATE_ERROR(EACCES);
TRANSLATE_ERROR(EBUSY);
TRANSLATE_ERROR(EINVAL);
TRANSLATE_ERROR(EDEADLK);
TRANSLATE_ERROR(ENOSYS);
TRANSLATE_ERROR(ETIME);
TRANSLATE_ERROR(EALREADY);
TRANSLATE_ERROR(ENOSPC);
#undef TRANSLATE_ERROR
case MC_CMD_ERR_ENOTSUP:
return -EOPNOTSUPP;
case MC_CMD_ERR_ALLOC_FAIL:
return -ENOBUFS;
case MC_CMD_ERR_MAC_EXIST:
return -EADDRINUSE;
default:
return -EPROTO;
}
}
static void efx_mcdi_read_response_header(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
unsigned int respseq, respcmd, error;
#ifdef CONFIG_SFC_MCDI_LOGGING
char *buf = mcdi->logging_buffer; /* page-sized */
#endif
efx_dword_t hdr;
efx->type->mcdi_read_response(efx, &hdr, 0, 4);
respseq = EFX_DWORD_FIELD(hdr, MCDI_HEADER_SEQ);
respcmd = EFX_DWORD_FIELD(hdr, MCDI_HEADER_CODE);
error = EFX_DWORD_FIELD(hdr, MCDI_HEADER_ERROR);
if (respcmd != MC_CMD_V2_EXTN) {
mcdi->resp_hdr_len = 4;
mcdi->resp_data_len = EFX_DWORD_FIELD(hdr, MCDI_HEADER_DATALEN);
} else {
efx->type->mcdi_read_response(efx, &hdr, 4, 4);
mcdi->resp_hdr_len = 8;
mcdi->resp_data_len =
EFX_DWORD_FIELD(hdr, MC_CMD_V2_EXTN_IN_ACTUAL_LEN);
}
#ifdef CONFIG_SFC_MCDI_LOGGING
if (mcdi->logging_enabled && !WARN_ON_ONCE(!buf)) {
size_t hdr_len, data_len;
int bytes = 0;
int i;
WARN_ON_ONCE(mcdi->resp_hdr_len % 4);
hdr_len = mcdi->resp_hdr_len / 4;
/* MCDI_DECLARE_BUF ensures that underlying buffer is padded
* to dword size, and the MCDI buffer is always dword size
*/
data_len = DIV_ROUND_UP(mcdi->resp_data_len, 4);
/* We own the logging buffer, as only one MCDI can be in
* progress on a NIC at any one time. So no need for locking.
*/
for (i = 0; i < hdr_len && bytes < PAGE_SIZE; i++) {
efx->type->mcdi_read_response(efx, &hdr, (i * 4), 4);
bytes += snprintf(buf + bytes, PAGE_SIZE - bytes,
" %08x", le32_to_cpu(hdr.u32[0]));
}
for (i = 0; i < data_len && bytes < PAGE_SIZE; i++) {
efx->type->mcdi_read_response(efx, &hdr,
mcdi->resp_hdr_len + (i * 4), 4);
bytes += snprintf(buf + bytes, PAGE_SIZE - bytes,
" %08x", le32_to_cpu(hdr.u32[0]));
}
netif_info(efx, hw, efx->net_dev, "MCDI RPC RESP:%s\n", buf);
}
#endif
if (error && mcdi->resp_data_len == 0) {
netif_err(efx, hw, efx->net_dev, "MC rebooted\n");
mcdi->resprc = -EIO;
} else if ((respseq ^ mcdi->seqno) & SEQ_MASK) {
netif_err(efx, hw, efx->net_dev,
"MC response mismatch tx seq 0x%x rx seq 0x%x\n",
respseq, mcdi->seqno);
mcdi->resprc = -EIO;
} else if (error) {
efx->type->mcdi_read_response(efx, &hdr, mcdi->resp_hdr_len, 4);
mcdi->resprc =
efx_mcdi_errno(EFX_DWORD_FIELD(hdr, EFX_DWORD_0));
} else {
mcdi->resprc = 0;
}
}
static bool efx_mcdi_poll_once(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
rmb();
if (!efx->type->mcdi_poll_response(efx))
return false;
spin_lock_bh(&mcdi->iface_lock);
efx_mcdi_read_response_header(efx);
spin_unlock_bh(&mcdi->iface_lock);
return true;
}
static int efx_mcdi_poll(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
unsigned long time, finish;
unsigned int spins;
int rc;
/* Check for a reboot atomically with respect to efx_mcdi_copyout() */
rc = efx_mcdi_poll_reboot(efx);
if (rc) {
spin_lock_bh(&mcdi->iface_lock);
mcdi->resprc = rc;
mcdi->resp_hdr_len = 0;
mcdi->resp_data_len = 0;
spin_unlock_bh(&mcdi->iface_lock);
return 0;
}
/* Poll for completion. Poll quickly (once a us) for the 1st jiffy,
* because generally mcdi responses are fast. After that, back off
* and poll once a jiffy (approximately)
*/
spins = TICK_USEC;
finish = jiffies + MCDI_RPC_TIMEOUT;
while (1) {
if (spins != 0) {
--spins;
udelay(1);
} else {
schedule_timeout_uninterruptible(1);
}
time = jiffies;
if (efx_mcdi_poll_once(efx))
break;
if (time_after(time, finish))
return -ETIMEDOUT;
}
/* Return rc=0 like wait_event_timeout() */
return 0;
}
/* Test and clear MC-rebooted flag for this port/function; reset
* software state as necessary.
*/
int efx_mcdi_poll_reboot(struct efx_nic *efx)
{
if (!efx->mcdi)
return 0;
return efx->type->mcdi_poll_reboot(efx);
}
static bool efx_mcdi_acquire_async(struct efx_mcdi_iface *mcdi)
{
return cmpxchg(&mcdi->state,
MCDI_STATE_QUIESCENT, MCDI_STATE_RUNNING_ASYNC) ==
MCDI_STATE_QUIESCENT;
}
static void efx_mcdi_acquire_sync(struct efx_mcdi_iface *mcdi)
{
/* Wait until the interface becomes QUIESCENT and we win the race
* to mark it RUNNING_SYNC.
*/
wait_event(mcdi->wq,
cmpxchg(&mcdi->state,
MCDI_STATE_QUIESCENT, MCDI_STATE_RUNNING_SYNC) ==
MCDI_STATE_QUIESCENT);
}
static int efx_mcdi_await_completion(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
if (wait_event_timeout(mcdi->wq, mcdi->state == MCDI_STATE_COMPLETED,
MCDI_RPC_TIMEOUT) == 0)
return -ETIMEDOUT;
/* Check if efx_mcdi_set_mode() switched us back to polled completions.
* In which case, poll for completions directly. If efx_mcdi_ev_cpl()
* completed the request first, then we'll just end up completing the
* request again, which is safe.
*
* We need an smp_rmb() to synchronise with efx_mcdi_mode_poll(), which
* wait_event_timeout() implicitly provides.
*/
if (mcdi->mode == MCDI_MODE_POLL)
return efx_mcdi_poll(efx);
return 0;
}
/* If the interface is RUNNING_SYNC, switch to COMPLETED and wake the
* requester. Return whether this was done. Does not take any locks.
*/
static bool efx_mcdi_complete_sync(struct efx_mcdi_iface *mcdi)
{
if (cmpxchg(&mcdi->state,
MCDI_STATE_RUNNING_SYNC, MCDI_STATE_COMPLETED) ==
MCDI_STATE_RUNNING_SYNC) {
wake_up(&mcdi->wq);
return true;
}
return false;
}
static void efx_mcdi_release(struct efx_mcdi_iface *mcdi)
{
if (mcdi->mode == MCDI_MODE_EVENTS) {
struct efx_mcdi_async_param *async;
struct efx_nic *efx = mcdi->efx;
/* Process the asynchronous request queue */
spin_lock_bh(&mcdi->async_lock);
async = list_first_entry_or_null(
&mcdi->async_list, struct efx_mcdi_async_param, list);
if (async) {
mcdi->state = MCDI_STATE_RUNNING_ASYNC;
efx_mcdi_send_request(efx, async->cmd,
(const efx_dword_t *)(async + 1),
async->inlen);
mod_timer(&mcdi->async_timer,
jiffies + MCDI_RPC_TIMEOUT);
}
spin_unlock_bh(&mcdi->async_lock);
if (async)
return;
}
mcdi->state = MCDI_STATE_QUIESCENT;
wake_up(&mcdi->wq);
}
/* If the interface is RUNNING_ASYNC, switch to COMPLETED, call the
* asynchronous completion function, and release the interface.
* Return whether this was done. Must be called in bh-disabled
* context. Will take iface_lock and async_lock.
*/
static bool efx_mcdi_complete_async(struct efx_mcdi_iface *mcdi, bool timeout)
{
struct efx_nic *efx = mcdi->efx;
struct efx_mcdi_async_param *async;
size_t hdr_len, data_len, err_len;
efx_dword_t *outbuf;
MCDI_DECLARE_BUF_ERR(errbuf);
int rc;
if (cmpxchg(&mcdi->state,
MCDI_STATE_RUNNING_ASYNC, MCDI_STATE_COMPLETED) !=
MCDI_STATE_RUNNING_ASYNC)
return false;
spin_lock(&mcdi->iface_lock);
if (timeout) {
/* Ensure that if the completion event arrives later,
* the seqno check in efx_mcdi_ev_cpl() will fail
*/
++mcdi->seqno;
++mcdi->credits;
rc = -ETIMEDOUT;
hdr_len = 0;
data_len = 0;
} else {
rc = mcdi->resprc;
hdr_len = mcdi->resp_hdr_len;
data_len = mcdi->resp_data_len;
}
spin_unlock(&mcdi->iface_lock);
/* Stop the timer. In case the timer function is running, we
* must wait for it to return so that there is no possibility
* of it aborting the next request.
*/
if (!timeout)
del_timer_sync(&mcdi->async_timer);
spin_lock(&mcdi->async_lock);
async = list_first_entry(&mcdi->async_list,
struct efx_mcdi_async_param, list);
list_del(&async->list);
spin_unlock(&mcdi->async_lock);
outbuf = (efx_dword_t *)(async + 1);
efx->type->mcdi_read_response(efx, outbuf, hdr_len,
min(async->outlen, data_len));
if (!timeout && rc && !async->quiet) {
err_len = min(sizeof(errbuf), data_len);
efx->type->mcdi_read_response(efx, errbuf, hdr_len,
sizeof(errbuf));
efx_mcdi_display_error(efx, async->cmd, async->inlen, errbuf,
err_len, rc);
}
async->complete(efx, async->cookie, rc, outbuf, data_len);
kfree(async);
efx_mcdi_release(mcdi);
return true;
}
static void efx_mcdi_ev_cpl(struct efx_nic *efx, unsigned int seqno,
unsigned int datalen, unsigned int mcdi_err)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
bool wake = false;
spin_lock(&mcdi->iface_lock);
if ((seqno ^ mcdi->seqno) & SEQ_MASK) {
if (mcdi->credits)
/* The request has been cancelled */
--mcdi->credits;
else
netif_err(efx, hw, efx->net_dev,
"MC response mismatch tx seq 0x%x rx "
"seq 0x%x\n", seqno, mcdi->seqno);
} else {
if (efx->type->mcdi_max_ver >= 2) {
/* MCDI v2 responses don't fit in an event */
efx_mcdi_read_response_header(efx);
} else {
mcdi->resprc = efx_mcdi_errno(mcdi_err);
mcdi->resp_hdr_len = 4;
mcdi->resp_data_len = datalen;
}
wake = true;
}
spin_unlock(&mcdi->iface_lock);
if (wake) {
if (!efx_mcdi_complete_async(mcdi, false))
(void) efx_mcdi_complete_sync(mcdi);
/* If the interface isn't RUNNING_ASYNC or
* RUNNING_SYNC then we've received a duplicate
* completion after we've already transitioned back to
* QUIESCENT. [A subsequent invocation would increment
* seqno, so would have failed the seqno check].
*/
}
}
static void efx_mcdi_timeout_async(unsigned long context)
{
struct efx_mcdi_iface *mcdi = (struct efx_mcdi_iface *)context;
efx_mcdi_complete_async(mcdi, true);
}
static int
efx_mcdi_check_supported(struct efx_nic *efx, unsigned int cmd, size_t inlen)
{
if (efx->type->mcdi_max_ver < 0 ||
(efx->type->mcdi_max_ver < 2 &&
cmd > MC_CMD_CMD_SPACE_ESCAPE_7))
return -EINVAL;
if (inlen > MCDI_CTL_SDU_LEN_MAX_V2 ||
(efx->type->mcdi_max_ver < 2 &&
inlen > MCDI_CTL_SDU_LEN_MAX_V1))
return -EMSGSIZE;
return 0;
}
static int _efx_mcdi_rpc_finish(struct efx_nic *efx, unsigned cmd, size_t inlen,
efx_dword_t *outbuf, size_t outlen,
size_t *outlen_actual, bool quiet)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
MCDI_DECLARE_BUF_ERR(errbuf);
int rc;
if (mcdi->mode == MCDI_MODE_POLL)
rc = efx_mcdi_poll(efx);
else
rc = efx_mcdi_await_completion(efx);
if (rc != 0) {
netif_err(efx, hw, efx->net_dev,
"MC command 0x%x inlen %d mode %d timed out\n",
cmd, (int)inlen, mcdi->mode);
if (mcdi->mode == MCDI_MODE_EVENTS && efx_mcdi_poll_once(efx)) {
netif_err(efx, hw, efx->net_dev,
"MCDI request was completed without an event\n");
rc = 0;
}
efx_mcdi_abandon(efx);
/* Close the race with efx_mcdi_ev_cpl() executing just too late
* and completing a request we've just cancelled, by ensuring
* that the seqno check therein fails.
*/
spin_lock_bh(&mcdi->iface_lock);
++mcdi->seqno;
++mcdi->credits;
spin_unlock_bh(&mcdi->iface_lock);
}
if (rc != 0) {
if (outlen_actual)
*outlen_actual = 0;
} else {
size_t hdr_len, data_len, err_len;
/* At the very least we need a memory barrier here to ensure
* we pick up changes from efx_mcdi_ev_cpl(). Protect against
* a spurious efx_mcdi_ev_cpl() running concurrently by
* acquiring the iface_lock. */
spin_lock_bh(&mcdi->iface_lock);
rc = mcdi->resprc;
hdr_len = mcdi->resp_hdr_len;
data_len = mcdi->resp_data_len;
err_len = min(sizeof(errbuf), data_len);
spin_unlock_bh(&mcdi->iface_lock);
BUG_ON(rc > 0);
efx->type->mcdi_read_response(efx, outbuf, hdr_len,
min(outlen, data_len));
if (outlen_actual)
*outlen_actual = data_len;
efx->type->mcdi_read_response(efx, errbuf, hdr_len, err_len);
if (cmd == MC_CMD_REBOOT && rc == -EIO) {
/* Don't reset if MC_CMD_REBOOT returns EIO */
} else if (rc == -EIO || rc == -EINTR) {
netif_err(efx, hw, efx->net_dev, "MC fatal error %d\n",
-rc);
efx_schedule_reset(efx, RESET_TYPE_MC_FAILURE);
} else if (rc && !quiet) {
efx_mcdi_display_error(efx, cmd, inlen, errbuf, err_len,
rc);
}
if (rc == -EIO || rc == -EINTR) {
msleep(MCDI_STATUS_SLEEP_MS);
efx_mcdi_poll_reboot(efx);
mcdi->new_epoch = true;
}
}
efx_mcdi_release(mcdi);
return rc;
}
static int _efx_mcdi_rpc(struct efx_nic *efx, unsigned cmd,
const efx_dword_t *inbuf, size_t inlen,
efx_dword_t *outbuf, size_t outlen,
size_t *outlen_actual, bool quiet)
{
int rc;
rc = efx_mcdi_rpc_start(efx, cmd, inbuf, inlen);
if (rc) {
if (outlen_actual)
*outlen_actual = 0;
return rc;
}
return _efx_mcdi_rpc_finish(efx, cmd, inlen, outbuf, outlen,
outlen_actual, quiet);
}
int efx_mcdi_rpc(struct efx_nic *efx, unsigned cmd,
const efx_dword_t *inbuf, size_t inlen,
efx_dword_t *outbuf, size_t outlen,
size_t *outlen_actual)
{
return _efx_mcdi_rpc(efx, cmd, inbuf, inlen, outbuf, outlen,
outlen_actual, false);
}
/* Normally, on receiving an error code in the MCDI response,
* efx_mcdi_rpc will log an error message containing (among other
* things) the raw error code, by means of efx_mcdi_display_error.
* This _quiet version suppresses that; if the caller wishes to log
* the error conditionally on the return code, it should call this
* function and is then responsible for calling efx_mcdi_display_error
* as needed.
*/
int efx_mcdi_rpc_quiet(struct efx_nic *efx, unsigned cmd,
const efx_dword_t *inbuf, size_t inlen,
efx_dword_t *outbuf, size_t outlen,
size_t *outlen_actual)
{
return _efx_mcdi_rpc(efx, cmd, inbuf, inlen, outbuf, outlen,
outlen_actual, true);
}
int efx_mcdi_rpc_start(struct efx_nic *efx, unsigned cmd,
const efx_dword_t *inbuf, size_t inlen)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
int rc;
rc = efx_mcdi_check_supported(efx, cmd, inlen);
if (rc)
return rc;
if (efx->mc_bist_for_other_fn)
return -ENETDOWN;
if (mcdi->mode == MCDI_MODE_FAIL)
return -ENETDOWN;
efx_mcdi_acquire_sync(mcdi);
efx_mcdi_send_request(efx, cmd, inbuf, inlen);
return 0;
}
static int _efx_mcdi_rpc_async(struct efx_nic *efx, unsigned int cmd,
const efx_dword_t *inbuf, size_t inlen,
size_t outlen,
efx_mcdi_async_completer *complete,
unsigned long cookie, bool quiet)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
struct efx_mcdi_async_param *async;
int rc;
rc = efx_mcdi_check_supported(efx, cmd, inlen);
if (rc)
return rc;
if (efx->mc_bist_for_other_fn)
return -ENETDOWN;
async = kmalloc(sizeof(*async) + ALIGN(max(inlen, outlen), 4),
GFP_ATOMIC);
if (!async)
return -ENOMEM;
async->cmd = cmd;
async->inlen = inlen;
async->outlen = outlen;
async->quiet = quiet;
async->complete = complete;
async->cookie = cookie;
memcpy(async + 1, inbuf, inlen);
spin_lock_bh(&mcdi->async_lock);
if (mcdi->mode == MCDI_MODE_EVENTS) {
list_add_tail(&async->list, &mcdi->async_list);
/* If this is at the front of the queue, try to start it
* immediately
*/
if (mcdi->async_list.next == &async->list &&
efx_mcdi_acquire_async(mcdi)) {
efx_mcdi_send_request(efx, cmd, inbuf, inlen);
mod_timer(&mcdi->async_timer,
jiffies + MCDI_RPC_TIMEOUT);
}
} else {
kfree(async);
rc = -ENETDOWN;
}
spin_unlock_bh(&mcdi->async_lock);
return rc;
}
/**
* efx_mcdi_rpc_async - Schedule an MCDI command to run asynchronously
* @efx: NIC through which to issue the command
* @cmd: Command type number
* @inbuf: Command parameters
* @inlen: Length of command parameters, in bytes
* @outlen: Length to allocate for response buffer, in bytes
* @complete: Function to be called on completion or cancellation.
* @cookie: Arbitrary value to be passed to @complete.
*
* This function does not sleep and therefore may be called in atomic
* context. It will fail if event queues are disabled or if MCDI
* event completions have been disabled due to an error.
*
* If it succeeds, the @complete function will be called exactly once
* in atomic context, when one of the following occurs:
* (a) the completion event is received (in NAPI context)
* (b) event queues are disabled (in the process that disables them)
* (c) the request times-out (in timer context)
*/
int
efx_mcdi_rpc_async(struct efx_nic *efx, unsigned int cmd,
const efx_dword_t *inbuf, size_t inlen, size_t outlen,
efx_mcdi_async_completer *complete, unsigned long cookie)
{
return _efx_mcdi_rpc_async(efx, cmd, inbuf, inlen, outlen, complete,
cookie, false);
}
int efx_mcdi_rpc_async_quiet(struct efx_nic *efx, unsigned int cmd,
const efx_dword_t *inbuf, size_t inlen,
size_t outlen, efx_mcdi_async_completer *complete,
unsigned long cookie)
{
return _efx_mcdi_rpc_async(efx, cmd, inbuf, inlen, outlen, complete,
cookie, true);
}
int efx_mcdi_rpc_finish(struct efx_nic *efx, unsigned cmd, size_t inlen,
efx_dword_t *outbuf, size_t outlen,
size_t *outlen_actual)
{
return _efx_mcdi_rpc_finish(efx, cmd, inlen, outbuf, outlen,
outlen_actual, false);
}
int efx_mcdi_rpc_finish_quiet(struct efx_nic *efx, unsigned cmd, size_t inlen,
efx_dword_t *outbuf, size_t outlen,
size_t *outlen_actual)
{
return _efx_mcdi_rpc_finish(efx, cmd, inlen, outbuf, outlen,
outlen_actual, true);
}
void efx_mcdi_display_error(struct efx_nic *efx, unsigned cmd,
size_t inlen, efx_dword_t *outbuf,
size_t outlen, int rc)
{
int code = 0, err_arg = 0;
if (outlen >= MC_CMD_ERR_CODE_OFST + 4)
code = MCDI_DWORD(outbuf, ERR_CODE);
if (outlen >= MC_CMD_ERR_ARG_OFST + 4)
err_arg = MCDI_DWORD(outbuf, ERR_ARG);
netif_err(efx, hw, efx->net_dev,
"MC command 0x%x inlen %d failed rc=%d (raw=%d) arg=%d\n",
cmd, (int)inlen, rc, code, err_arg);
}
/* Switch to polled MCDI completions. This can be called in various
* error conditions with various locks held, so it must be lockless.
* Caller is responsible for flushing asynchronous requests later.
*/
void efx_mcdi_mode_poll(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi;
if (!efx->mcdi)
return;
mcdi = efx_mcdi(efx);
/* If already in polling mode, nothing to do.
* If in fail-fast state, don't switch to polled completion.
* FLR recovery will do that later.
*/
if (mcdi->mode == MCDI_MODE_POLL || mcdi->mode == MCDI_MODE_FAIL)
return;
/* We can switch from event completion to polled completion, because
* mcdi requests are always completed in shared memory. We do this by
* switching the mode to POLL'd then completing the request.
* efx_mcdi_await_completion() will then call efx_mcdi_poll().
*
* We need an smp_wmb() to synchronise with efx_mcdi_await_completion(),
* which efx_mcdi_complete_sync() provides for us.
*/
mcdi->mode = MCDI_MODE_POLL;
efx_mcdi_complete_sync(mcdi);
}
/* Flush any running or queued asynchronous requests, after event processing
* is stopped
*/
void efx_mcdi_flush_async(struct efx_nic *efx)
{
struct efx_mcdi_async_param *async, *next;
struct efx_mcdi_iface *mcdi;
if (!efx->mcdi)
return;
mcdi = efx_mcdi(efx);
/* We must be in poll or fail mode so no more requests can be queued */
BUG_ON(mcdi->mode == MCDI_MODE_EVENTS);
del_timer_sync(&mcdi->async_timer);
/* If a request is still running, make sure we give the MC
* time to complete it so that the response won't overwrite our
* next request.
*/
if (mcdi->state == MCDI_STATE_RUNNING_ASYNC) {
efx_mcdi_poll(efx);
mcdi->state = MCDI_STATE_QUIESCENT;
}
/* Nothing else will access the async list now, so it is safe
* to walk it without holding async_lock. If we hold it while
* calling a completer then lockdep may warn that we have
* acquired locks in the wrong order.
*/
list_for_each_entry_safe(async, next, &mcdi->async_list, list) {
async->complete(efx, async->cookie, -ENETDOWN, NULL, 0);
list_del(&async->list);
kfree(async);
}
}
void efx_mcdi_mode_event(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi;
if (!efx->mcdi)
return;
mcdi = efx_mcdi(efx);
/* If already in event completion mode, nothing to do.
* If in fail-fast state, don't switch to event completion. FLR
* recovery will do that later.
*/
if (mcdi->mode == MCDI_MODE_EVENTS || mcdi->mode == MCDI_MODE_FAIL)
return;
/* We can't switch from polled to event completion in the middle of a
* request, because the completion method is specified in the request.
* So acquire the interface to serialise the requestors. We don't need
* to acquire the iface_lock to change the mode here, but we do need a
* write memory barrier ensure that efx_mcdi_rpc() sees it, which
* efx_mcdi_acquire() provides.
*/
efx_mcdi_acquire_sync(mcdi);
mcdi->mode = MCDI_MODE_EVENTS;
efx_mcdi_release(mcdi);
}
static void efx_mcdi_ev_death(struct efx_nic *efx, int rc)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
/* If there is an outstanding MCDI request, it has been terminated
* either by a BADASSERT or REBOOT event. If the mcdi interface is
* in polled mode, then do nothing because the MC reboot handler will
* set the header correctly. However, if the mcdi interface is waiting
* for a CMDDONE event it won't receive it [and since all MCDI events
* are sent to the same queue, we can't be racing with
* efx_mcdi_ev_cpl()]
*
* If there is an outstanding asynchronous request, we can't
* complete it now (efx_mcdi_complete() would deadlock). The
* reset process will take care of this.
*
* There's a race here with efx_mcdi_send_request(), because
* we might receive a REBOOT event *before* the request has
* been copied out. In polled mode (during startup) this is
* irrelevant, because efx_mcdi_complete_sync() is ignored. In
* event mode, this condition is just an edge-case of
* receiving a REBOOT event after posting the MCDI
* request. Did the mc reboot before or after the copyout? The
* best we can do always is just return failure.
*/
spin_lock(&mcdi->iface_lock);
if (efx_mcdi_complete_sync(mcdi)) {
if (mcdi->mode == MCDI_MODE_EVENTS) {
mcdi->resprc = rc;
mcdi->resp_hdr_len = 0;
mcdi->resp_data_len = 0;
++mcdi->credits;
}
} else {
int count;
/* Consume the status word since efx_mcdi_rpc_finish() won't */
for (count = 0; count < MCDI_STATUS_DELAY_COUNT; ++count) {
if (efx_mcdi_poll_reboot(efx))
break;
udelay(MCDI_STATUS_DELAY_US);
}
mcdi->new_epoch = true;
/* Nobody was waiting for an MCDI request, so trigger a reset */
efx_schedule_reset(efx, RESET_TYPE_MC_FAILURE);
}
spin_unlock(&mcdi->iface_lock);
}
/* The MC is going down in to BIST mode. set the BIST flag to block
* new MCDI, cancel any outstanding MCDI and and schedule a BIST-type reset
* (which doesn't actually execute a reset, it waits for the controlling
* function to reset it).
*/
static void efx_mcdi_ev_bist(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
spin_lock(&mcdi->iface_lock);
efx->mc_bist_for_other_fn = true;
if (efx_mcdi_complete_sync(mcdi)) {
if (mcdi->mode == MCDI_MODE_EVENTS) {
mcdi->resprc = -EIO;
mcdi->resp_hdr_len = 0;
mcdi->resp_data_len = 0;
++mcdi->credits;
}
}
mcdi->new_epoch = true;
efx_schedule_reset(efx, RESET_TYPE_MC_BIST);
spin_unlock(&mcdi->iface_lock);
}
/* MCDI timeouts seen, so make all MCDI calls fail-fast and issue an FLR to try
* to recover.
*/
static void efx_mcdi_abandon(struct efx_nic *efx)
{
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
if (xchg(&mcdi->mode, MCDI_MODE_FAIL) == MCDI_MODE_FAIL)
return; /* it had already been done */
netif_dbg(efx, hw, efx->net_dev, "MCDI is timing out; trying to recover\n");
efx_schedule_reset(efx, RESET_TYPE_MCDI_TIMEOUT);
}
/* Called from falcon_process_eventq for MCDI events */
void efx_mcdi_process_event(struct efx_channel *channel,
efx_qword_t *event)
{
struct efx_nic *efx = channel->efx;
int code = EFX_QWORD_FIELD(*event, MCDI_EVENT_CODE);
u32 data = EFX_QWORD_FIELD(*event, MCDI_EVENT_DATA);
switch (code) {
case MCDI_EVENT_CODE_BADSSERT:
netif_err(efx, hw, efx->net_dev,
"MC watchdog or assertion failure at 0x%x\n", data);
efx_mcdi_ev_death(efx, -EINTR);
break;
case MCDI_EVENT_CODE_PMNOTICE:
netif_info(efx, wol, efx->net_dev, "MCDI PM event.\n");
break;
case MCDI_EVENT_CODE_CMDDONE:
efx_mcdi_ev_cpl(efx,
MCDI_EVENT_FIELD(*event, CMDDONE_SEQ),
MCDI_EVENT_FIELD(*event, CMDDONE_DATALEN),
MCDI_EVENT_FIELD(*event, CMDDONE_ERRNO));
break;
case MCDI_EVENT_CODE_LINKCHANGE:
efx_mcdi_process_link_change(efx, event);
break;
case MCDI_EVENT_CODE_SENSOREVT:
efx_mcdi_sensor_event(efx, event);
break;
case MCDI_EVENT_CODE_SCHEDERR:
netif_dbg(efx, hw, efx->net_dev,
"MC Scheduler alert (0x%x)\n", data);
break;
case MCDI_EVENT_CODE_REBOOT:
case MCDI_EVENT_CODE_MC_REBOOT:
netif_info(efx, hw, efx->net_dev, "MC Reboot\n");
efx_mcdi_ev_death(efx, -EIO);
break;
case MCDI_EVENT_CODE_MC_BIST:
netif_info(efx, hw, efx->net_dev, "MC entered BIST mode\n");
efx_mcdi_ev_bist(efx);
break;
case MCDI_EVENT_CODE_MAC_STATS_DMA:
/* MAC stats are gather lazily. We can ignore this. */
break;
case MCDI_EVENT_CODE_FLR:
if (efx->type->sriov_flr)
efx->type->sriov_flr(efx,
MCDI_EVENT_FIELD(*event, FLR_VF));
break;
case MCDI_EVENT_CODE_PTP_RX:
case MCDI_EVENT_CODE_PTP_FAULT:
case MCDI_EVENT_CODE_PTP_PPS:
efx_ptp_event(efx, event);
break;
case MCDI_EVENT_CODE_PTP_TIME:
efx_time_sync_event(channel, event);
break;
case MCDI_EVENT_CODE_TX_FLUSH:
case MCDI_EVENT_CODE_RX_FLUSH:
/* Two flush events will be sent: one to the same event
* queue as completions, and one to event queue 0.
* In the latter case the {RX,TX}_FLUSH_TO_DRIVER
* flag will be set, and we should ignore the event
* because we want to wait for all completions.
*/
BUILD_BUG_ON(MCDI_EVENT_TX_FLUSH_TO_DRIVER_LBN !=
MCDI_EVENT_RX_FLUSH_TO_DRIVER_LBN);
if (!MCDI_EVENT_FIELD(*event, TX_FLUSH_TO_DRIVER))
efx_ef10_handle_drain_event(efx);
break;
case MCDI_EVENT_CODE_TX_ERR:
case MCDI_EVENT_CODE_RX_ERR:
netif_err(efx, hw, efx->net_dev,
"%s DMA error (event: "EFX_QWORD_FMT")\n",
code == MCDI_EVENT_CODE_TX_ERR ? "TX" : "RX",
EFX_QWORD_VAL(*event));
efx_schedule_reset(efx, RESET_TYPE_DMA_ERROR);
break;
default:
netif_err(efx, hw, efx->net_dev, "Unknown MCDI event 0x%x\n",
code);
}
}
/**************************************************************************
*
* Specific request functions
*
**************************************************************************
*/
void efx_mcdi_print_fwver(struct efx_nic *efx, char *buf, size_t len)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_VERSION_OUT_LEN);
size_t outlength;
const __le16 *ver_words;
size_t offset;
int rc;
BUILD_BUG_ON(MC_CMD_GET_VERSION_IN_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_GET_VERSION, NULL, 0,
outbuf, sizeof(outbuf), &outlength);
if (rc)
goto fail;
if (outlength < MC_CMD_GET_VERSION_OUT_LEN) {
rc = -EIO;
goto fail;
}
ver_words = (__le16 *)MCDI_PTR(outbuf, GET_VERSION_OUT_VERSION);
offset = snprintf(buf, len, "%u.%u.%u.%u",
le16_to_cpu(ver_words[0]), le16_to_cpu(ver_words[1]),
le16_to_cpu(ver_words[2]), le16_to_cpu(ver_words[3]));
/* EF10 may have multiple datapath firmware variants within a
* single version. Report which variants are running.
*/
if (efx_nic_rev(efx) >= EFX_REV_HUNT_A0) {
struct efx_ef10_nic_data *nic_data = efx->nic_data;
offset += snprintf(buf + offset, len - offset, " rx%x tx%x",
nic_data->rx_dpcpu_fw_id,
nic_data->tx_dpcpu_fw_id);
/* It's theoretically possible for the string to exceed 31
* characters, though in practice the first three version
* components are short enough that this doesn't happen.
*/
if (WARN_ON(offset >= len))
buf[0] = 0;
}
return;
fail:
netif_err(efx, probe, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
buf[0] = 0;
}
static int efx_mcdi_drv_attach(struct efx_nic *efx, bool driver_operating,
bool *was_attached)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_DRV_ATTACH_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_DRV_ATTACH_EXT_OUT_LEN);
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, DRV_ATTACH_IN_NEW_STATE,
driver_operating ? 1 : 0);
MCDI_SET_DWORD(inbuf, DRV_ATTACH_IN_UPDATE, 1);
MCDI_SET_DWORD(inbuf, DRV_ATTACH_IN_FIRMWARE_ID, MC_CMD_FW_LOW_LATENCY);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_DRV_ATTACH, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
/* If we're not the primary PF, trying to ATTACH with a FIRMWARE_ID
* specified will fail with EPERM, and we have to tell the MC we don't
* care what firmware we get.
*/
if (rc == -EPERM) {
netif_dbg(efx, probe, efx->net_dev,
"efx_mcdi_drv_attach with fw-variant setting failed EPERM, trying without it\n");
MCDI_SET_DWORD(inbuf, DRV_ATTACH_IN_FIRMWARE_ID,
MC_CMD_FW_DONT_CARE);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_DRV_ATTACH, inbuf,
sizeof(inbuf), outbuf, sizeof(outbuf),
&outlen);
}
if (rc) {
efx_mcdi_display_error(efx, MC_CMD_DRV_ATTACH, sizeof(inbuf),
outbuf, outlen, rc);
goto fail;
}
if (outlen < MC_CMD_DRV_ATTACH_OUT_LEN) {
rc = -EIO;
goto fail;
}
if (driver_operating) {
if (outlen >= MC_CMD_DRV_ATTACH_EXT_OUT_LEN) {
efx->mcdi->fn_flags =
MCDI_DWORD(outbuf,
DRV_ATTACH_EXT_OUT_FUNC_FLAGS);
} else {
/* Synthesise flags for Siena */
efx->mcdi->fn_flags =
1 << MC_CMD_DRV_ATTACH_EXT_OUT_FLAG_LINKCTRL |
1 << MC_CMD_DRV_ATTACH_EXT_OUT_FLAG_TRUSTED |
(efx_port_num(efx) == 0) <<
MC_CMD_DRV_ATTACH_EXT_OUT_FLAG_PRIMARY;
}
}
/* We currently assume we have control of the external link
* and are completely trusted by firmware. Abort probing
* if that's not true for this function.
*/
if (was_attached != NULL)
*was_attached = MCDI_DWORD(outbuf, DRV_ATTACH_OUT_OLD_STATE);
return 0;
fail:
netif_err(efx, probe, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_mcdi_get_board_cfg(struct efx_nic *efx, u8 *mac_address,
u16 *fw_subtype_list, u32 *capabilities)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_BOARD_CFG_OUT_LENMAX);
size_t outlen, i;
int port_num = efx_port_num(efx);
int rc;
BUILD_BUG_ON(MC_CMD_GET_BOARD_CFG_IN_LEN != 0);
/* we need __aligned(2) for ether_addr_copy */
BUILD_BUG_ON(MC_CMD_GET_BOARD_CFG_OUT_MAC_ADDR_BASE_PORT0_OFST & 1);
BUILD_BUG_ON(MC_CMD_GET_BOARD_CFG_OUT_MAC_ADDR_BASE_PORT1_OFST & 1);
rc = efx_mcdi_rpc(efx, MC_CMD_GET_BOARD_CFG, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_GET_BOARD_CFG_OUT_LENMIN) {
rc = -EIO;
goto fail;
}
if (mac_address)
ether_addr_copy(mac_address,
port_num ?
MCDI_PTR(outbuf, GET_BOARD_CFG_OUT_MAC_ADDR_BASE_PORT1) :
MCDI_PTR(outbuf, GET_BOARD_CFG_OUT_MAC_ADDR_BASE_PORT0));
if (fw_subtype_list) {
for (i = 0;
i < MCDI_VAR_ARRAY_LEN(outlen,
GET_BOARD_CFG_OUT_FW_SUBTYPE_LIST);
i++)
fw_subtype_list[i] = MCDI_ARRAY_WORD(
outbuf, GET_BOARD_CFG_OUT_FW_SUBTYPE_LIST, i);
for (; i < MC_CMD_GET_BOARD_CFG_OUT_FW_SUBTYPE_LIST_MAXNUM; i++)
fw_subtype_list[i] = 0;
}
if (capabilities) {
if (port_num)
*capabilities = MCDI_DWORD(outbuf,
GET_BOARD_CFG_OUT_CAPABILITIES_PORT1);
else
*capabilities = MCDI_DWORD(outbuf,
GET_BOARD_CFG_OUT_CAPABILITIES_PORT0);
}
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d len=%d\n",
__func__, rc, (int)outlen);
return rc;
}
int efx_mcdi_log_ctrl(struct efx_nic *efx, bool evq, bool uart, u32 dest_evq)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_LOG_CTRL_IN_LEN);
u32 dest = 0;
int rc;
if (uart)
dest |= MC_CMD_LOG_CTRL_IN_LOG_DEST_UART;
if (evq)
dest |= MC_CMD_LOG_CTRL_IN_LOG_DEST_EVQ;
MCDI_SET_DWORD(inbuf, LOG_CTRL_IN_LOG_DEST, dest);
MCDI_SET_DWORD(inbuf, LOG_CTRL_IN_LOG_DEST_EVQ, dest_evq);
BUILD_BUG_ON(MC_CMD_LOG_CTRL_OUT_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_LOG_CTRL, inbuf, sizeof(inbuf),
NULL, 0, NULL);
return rc;
}
int efx_mcdi_nvram_types(struct efx_nic *efx, u32 *nvram_types_out)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_NVRAM_TYPES_OUT_LEN);
size_t outlen;
int rc;
BUILD_BUG_ON(MC_CMD_NVRAM_TYPES_IN_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_TYPES, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_NVRAM_TYPES_OUT_LEN) {
rc = -EIO;
goto fail;
}
*nvram_types_out = MCDI_DWORD(outbuf, NVRAM_TYPES_OUT_TYPES);
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n",
__func__, rc);
return rc;
}
int efx_mcdi_nvram_info(struct efx_nic *efx, unsigned int type,
size_t *size_out, size_t *erase_size_out,
bool *protected_out)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_NVRAM_INFO_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_NVRAM_INFO_OUT_LEN);
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_INFO_IN_TYPE, type);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_INFO, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_NVRAM_INFO_OUT_LEN) {
rc = -EIO;
goto fail;
}
*size_out = MCDI_DWORD(outbuf, NVRAM_INFO_OUT_SIZE);
*erase_size_out = MCDI_DWORD(outbuf, NVRAM_INFO_OUT_ERASESIZE);
*protected_out = !!(MCDI_DWORD(outbuf, NVRAM_INFO_OUT_FLAGS) &
(1 << MC_CMD_NVRAM_INFO_OUT_PROTECTED_LBN));
return 0;
fail:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
static int efx_mcdi_nvram_test(struct efx_nic *efx, unsigned int type)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_NVRAM_TEST_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_NVRAM_TEST_OUT_LEN);
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_TEST_IN_TYPE, type);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_TEST, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), NULL);
if (rc)
return rc;
switch (MCDI_DWORD(outbuf, NVRAM_TEST_OUT_RESULT)) {
case MC_CMD_NVRAM_TEST_PASS:
case MC_CMD_NVRAM_TEST_NOTSUPP:
return 0;
default:
return -EIO;
}
}
int efx_mcdi_nvram_test_all(struct efx_nic *efx)
{
u32 nvram_types;
unsigned int type;
int rc;
rc = efx_mcdi_nvram_types(efx, &nvram_types);
if (rc)
goto fail1;
type = 0;
while (nvram_types != 0) {
if (nvram_types & 1) {
rc = efx_mcdi_nvram_test(efx, type);
if (rc)
goto fail2;
}
type++;
nvram_types >>= 1;
}
return 0;
fail2:
netif_err(efx, hw, efx->net_dev, "%s: failed type=%u\n",
__func__, type);
fail1:
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
/* Returns 1 if an assertion was read, 0 if no assertion had fired,
* negative on error.
*/
static int efx_mcdi_read_assertion(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_GET_ASSERTS_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_ASSERTS_OUT_LEN);
unsigned int flags, index;
const char *reason;
size_t outlen;
int retry;
int rc;
/* Attempt to read any stored assertion state before we reboot
* the mcfw out of the assertion handler. Retry twice, once
* because a boot-time assertion might cause this command to fail
* with EINTR. And once again because GET_ASSERTS can race with
* MC_CMD_REBOOT running on the other port. */
retry = 2;
do {
MCDI_SET_DWORD(inbuf, GET_ASSERTS_IN_CLEAR, 1);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_GET_ASSERTS,
inbuf, MC_CMD_GET_ASSERTS_IN_LEN,
outbuf, sizeof(outbuf), &outlen);
if (rc == -EPERM)
return 0;
} while ((rc == -EINTR || rc == -EIO) && retry-- > 0);
if (rc) {
efx_mcdi_display_error(efx, MC_CMD_GET_ASSERTS,
MC_CMD_GET_ASSERTS_IN_LEN, outbuf,
outlen, rc);
return rc;
}
if (outlen < MC_CMD_GET_ASSERTS_OUT_LEN)
return -EIO;
/* Print out any recorded assertion state */
flags = MCDI_DWORD(outbuf, GET_ASSERTS_OUT_GLOBAL_FLAGS);
if (flags == MC_CMD_GET_ASSERTS_FLAGS_NO_FAILS)
return 0;
reason = (flags == MC_CMD_GET_ASSERTS_FLAGS_SYS_FAIL)
? "system-level assertion"
: (flags == MC_CMD_GET_ASSERTS_FLAGS_THR_FAIL)
? "thread-level assertion"
: (flags == MC_CMD_GET_ASSERTS_FLAGS_WDOG_FIRED)
? "watchdog reset"
: "unknown assertion";
netif_err(efx, hw, efx->net_dev,
"MCPU %s at PC = 0x%.8x in thread 0x%.8x\n", reason,
MCDI_DWORD(outbuf, GET_ASSERTS_OUT_SAVED_PC_OFFS),
MCDI_DWORD(outbuf, GET_ASSERTS_OUT_THREAD_OFFS));
/* Print out the registers */
for (index = 0;
index < MC_CMD_GET_ASSERTS_OUT_GP_REGS_OFFS_NUM;
index++)
netif_err(efx, hw, efx->net_dev, "R%.2d (?): 0x%.8x\n",
1 + index,
MCDI_ARRAY_DWORD(outbuf, GET_ASSERTS_OUT_GP_REGS_OFFS,
index));
return 1;
}
static int efx_mcdi_exit_assertion(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_REBOOT_IN_LEN);
int rc;
/* If the MC is running debug firmware, it might now be
* waiting for a debugger to attach, but we just want it to
* reboot. We set a flag that makes the command a no-op if it
* has already done so.
* The MCDI will thus return either 0 or -EIO.
*/
BUILD_BUG_ON(MC_CMD_REBOOT_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, REBOOT_IN_FLAGS,
MC_CMD_REBOOT_FLAGS_AFTER_ASSERTION);
rc = efx_mcdi_rpc_quiet(efx, MC_CMD_REBOOT, inbuf, MC_CMD_REBOOT_IN_LEN,
NULL, 0, NULL);
if (rc == -EIO)
rc = 0;
if (rc)
efx_mcdi_display_error(efx, MC_CMD_REBOOT, MC_CMD_REBOOT_IN_LEN,
NULL, 0, rc);
return rc;
}
int efx_mcdi_handle_assertion(struct efx_nic *efx)
{
int rc;
rc = efx_mcdi_read_assertion(efx);
if (rc <= 0)
return rc;
return efx_mcdi_exit_assertion(efx);
}
void efx_mcdi_set_id_led(struct efx_nic *efx, enum efx_led_mode mode)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_SET_ID_LED_IN_LEN);
int rc;
BUILD_BUG_ON(EFX_LED_OFF != MC_CMD_LED_OFF);
BUILD_BUG_ON(EFX_LED_ON != MC_CMD_LED_ON);
BUILD_BUG_ON(EFX_LED_DEFAULT != MC_CMD_LED_DEFAULT);
BUILD_BUG_ON(MC_CMD_SET_ID_LED_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, SET_ID_LED_IN_STATE, mode);
rc = efx_mcdi_rpc(efx, MC_CMD_SET_ID_LED, inbuf, sizeof(inbuf),
NULL, 0, NULL);
}
static int efx_mcdi_reset_func(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_ENTITY_RESET_IN_LEN);
int rc;
BUILD_BUG_ON(MC_CMD_ENTITY_RESET_OUT_LEN != 0);
MCDI_POPULATE_DWORD_1(inbuf, ENTITY_RESET_IN_FLAG,
ENTITY_RESET_IN_FUNCTION_RESOURCE_RESET, 1);
rc = efx_mcdi_rpc(efx, MC_CMD_ENTITY_RESET, inbuf, sizeof(inbuf),
NULL, 0, NULL);
return rc;
}
static int efx_mcdi_reset_mc(struct efx_nic *efx)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_REBOOT_IN_LEN);
int rc;
BUILD_BUG_ON(MC_CMD_REBOOT_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, REBOOT_IN_FLAGS, 0);
rc = efx_mcdi_rpc(efx, MC_CMD_REBOOT, inbuf, sizeof(inbuf),
NULL, 0, NULL);
/* White is black, and up is down */
if (rc == -EIO)
return 0;
if (rc == 0)
rc = -EIO;
return rc;
}
enum reset_type efx_mcdi_map_reset_reason(enum reset_type reason)
{
return RESET_TYPE_RECOVER_OR_ALL;
}
int efx_mcdi_reset(struct efx_nic *efx, enum reset_type method)
{
int rc;
/* If MCDI is down, we can't handle_assertion */
if (method == RESET_TYPE_MCDI_TIMEOUT) {
rc = pci_reset_function(efx->pci_dev);
if (rc)
return rc;
/* Re-enable polled MCDI completion */
if (efx->mcdi) {
struct efx_mcdi_iface *mcdi = efx_mcdi(efx);
mcdi->mode = MCDI_MODE_POLL;
}
return 0;
}
/* Recover from a failed assertion pre-reset */
rc = efx_mcdi_handle_assertion(efx);
if (rc)
return rc;
if (method == RESET_TYPE_DATAPATH)
return 0;
else if (method == RESET_TYPE_WORLD)
return efx_mcdi_reset_mc(efx);
else
return efx_mcdi_reset_func(efx);
}
static int efx_mcdi_wol_filter_set(struct efx_nic *efx, u32 type,
const u8 *mac, int *id_out)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_WOL_FILTER_SET_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_WOL_FILTER_SET_OUT_LEN);
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, WOL_FILTER_SET_IN_WOL_TYPE, type);
MCDI_SET_DWORD(inbuf, WOL_FILTER_SET_IN_FILTER_MODE,
MC_CMD_FILTER_MODE_SIMPLE);
ether_addr_copy(MCDI_PTR(inbuf, WOL_FILTER_SET_IN_MAGIC_MAC), mac);
rc = efx_mcdi_rpc(efx, MC_CMD_WOL_FILTER_SET, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_WOL_FILTER_SET_OUT_LEN) {
rc = -EIO;
goto fail;
}
*id_out = (int)MCDI_DWORD(outbuf, WOL_FILTER_SET_OUT_FILTER_ID);
return 0;
fail:
*id_out = -1;
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int
efx_mcdi_wol_filter_set_magic(struct efx_nic *efx, const u8 *mac, int *id_out)
{
return efx_mcdi_wol_filter_set(efx, MC_CMD_WOL_TYPE_MAGIC, mac, id_out);
}
int efx_mcdi_wol_filter_get_magic(struct efx_nic *efx, int *id_out)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_WOL_FILTER_GET_OUT_LEN);
size_t outlen;
int rc;
rc = efx_mcdi_rpc(efx, MC_CMD_WOL_FILTER_GET, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_WOL_FILTER_GET_OUT_LEN) {
rc = -EIO;
goto fail;
}
*id_out = (int)MCDI_DWORD(outbuf, WOL_FILTER_GET_OUT_FILTER_ID);
return 0;
fail:
*id_out = -1;
netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
int efx_mcdi_wol_filter_remove(struct efx_nic *efx, int id)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_WOL_FILTER_REMOVE_IN_LEN);
int rc;
MCDI_SET_DWORD(inbuf, WOL_FILTER_REMOVE_IN_FILTER_ID, (u32)id);
rc = efx_mcdi_rpc(efx, MC_CMD_WOL_FILTER_REMOVE, inbuf, sizeof(inbuf),
NULL, 0, NULL);
return rc;
}
int efx_mcdi_flush_rxqs(struct efx_nic *efx)
{
struct efx_channel *channel;
struct efx_rx_queue *rx_queue;
MCDI_DECLARE_BUF(inbuf,
MC_CMD_FLUSH_RX_QUEUES_IN_LEN(EFX_MAX_CHANNELS));
int rc, count;
BUILD_BUG_ON(EFX_MAX_CHANNELS >
MC_CMD_FLUSH_RX_QUEUES_IN_QID_OFST_MAXNUM);
count = 0;
efx_for_each_channel(channel, efx) {
efx_for_each_channel_rx_queue(rx_queue, channel) {
if (rx_queue->flush_pending) {
rx_queue->flush_pending = false;
atomic_dec(&efx->rxq_flush_pending);
MCDI_SET_ARRAY_DWORD(
inbuf, FLUSH_RX_QUEUES_IN_QID_OFST,
count, efx_rx_queue_index(rx_queue));
count++;
}
}
}
rc = efx_mcdi_rpc(efx, MC_CMD_FLUSH_RX_QUEUES, inbuf,
MC_CMD_FLUSH_RX_QUEUES_IN_LEN(count), NULL, 0, NULL);
WARN_ON(rc < 0);
return rc;
}
int efx_mcdi_wol_filter_reset(struct efx_nic *efx)
{
int rc;
rc = efx_mcdi_rpc(efx, MC_CMD_WOL_FILTER_RESET, NULL, 0, NULL, 0, NULL);
return rc;
}
int efx_mcdi_set_workaround(struct efx_nic *efx, u32 type, bool enabled,
unsigned int *flags)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_WORKAROUND_IN_LEN);
MCDI_DECLARE_BUF(outbuf, MC_CMD_WORKAROUND_EXT_OUT_LEN);
size_t outlen;
int rc;
BUILD_BUG_ON(MC_CMD_WORKAROUND_OUT_LEN != 0);
MCDI_SET_DWORD(inbuf, WORKAROUND_IN_TYPE, type);
MCDI_SET_DWORD(inbuf, WORKAROUND_IN_ENABLED, enabled);
rc = efx_mcdi_rpc(efx, MC_CMD_WORKAROUND, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
if (!flags)
return 0;
if (outlen >= MC_CMD_WORKAROUND_EXT_OUT_LEN)
*flags = MCDI_DWORD(outbuf, WORKAROUND_EXT_OUT_FLAGS);
else
*flags = 0;
return 0;
}
int efx_mcdi_get_workarounds(struct efx_nic *efx, unsigned int *impl_out,
unsigned int *enabled_out)
{
MCDI_DECLARE_BUF(outbuf, MC_CMD_GET_WORKAROUNDS_OUT_LEN);
size_t outlen;
int rc;
rc = efx_mcdi_rpc(efx, MC_CMD_GET_WORKAROUNDS, NULL, 0,
outbuf, sizeof(outbuf), &outlen);
if (rc)
goto fail;
if (outlen < MC_CMD_GET_WORKAROUNDS_OUT_LEN) {
rc = -EIO;
goto fail;
}
if (impl_out)
*impl_out = MCDI_DWORD(outbuf, GET_WORKAROUNDS_OUT_IMPLEMENTED);
if (enabled_out)
*enabled_out = MCDI_DWORD(outbuf, GET_WORKAROUNDS_OUT_ENABLED);
return 0;
fail:
/* Older firmware lacks GET_WORKAROUNDS and this isn't especially
* terrifying. The call site will have to deal with it though.
*/
netif_printk(efx, hw, rc == -ENOSYS ? KERN_DEBUG : KERN_ERR,
efx->net_dev, "%s: failed rc=%d\n", __func__, rc);
return rc;
}
#ifdef CONFIG_SFC_MTD
#define EFX_MCDI_NVRAM_LEN_MAX 128
static int efx_mcdi_nvram_update_start(struct efx_nic *efx, unsigned int type)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_NVRAM_UPDATE_START_IN_LEN);
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_UPDATE_START_IN_TYPE, type);
BUILD_BUG_ON(MC_CMD_NVRAM_UPDATE_START_OUT_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_UPDATE_START, inbuf, sizeof(inbuf),
NULL, 0, NULL);
return rc;
}
static int efx_mcdi_nvram_read(struct efx_nic *efx, unsigned int type,
loff_t offset, u8 *buffer, size_t length)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_NVRAM_READ_IN_LEN);
MCDI_DECLARE_BUF(outbuf,
MC_CMD_NVRAM_READ_OUT_LEN(EFX_MCDI_NVRAM_LEN_MAX));
size_t outlen;
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_READ_IN_TYPE, type);
MCDI_SET_DWORD(inbuf, NVRAM_READ_IN_OFFSET, offset);
MCDI_SET_DWORD(inbuf, NVRAM_READ_IN_LENGTH, length);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_READ, inbuf, sizeof(inbuf),
outbuf, sizeof(outbuf), &outlen);
if (rc)
return rc;
memcpy(buffer, MCDI_PTR(outbuf, NVRAM_READ_OUT_READ_BUFFER), length);
return 0;
}
static int efx_mcdi_nvram_write(struct efx_nic *efx, unsigned int type,
loff_t offset, const u8 *buffer, size_t length)
{
MCDI_DECLARE_BUF(inbuf,
MC_CMD_NVRAM_WRITE_IN_LEN(EFX_MCDI_NVRAM_LEN_MAX));
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_WRITE_IN_TYPE, type);
MCDI_SET_DWORD(inbuf, NVRAM_WRITE_IN_OFFSET, offset);
MCDI_SET_DWORD(inbuf, NVRAM_WRITE_IN_LENGTH, length);
memcpy(MCDI_PTR(inbuf, NVRAM_WRITE_IN_WRITE_BUFFER), buffer, length);
BUILD_BUG_ON(MC_CMD_NVRAM_WRITE_OUT_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_WRITE, inbuf,
ALIGN(MC_CMD_NVRAM_WRITE_IN_LEN(length), 4),
NULL, 0, NULL);
return rc;
}
static int efx_mcdi_nvram_erase(struct efx_nic *efx, unsigned int type,
loff_t offset, size_t length)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_NVRAM_ERASE_IN_LEN);
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_ERASE_IN_TYPE, type);
MCDI_SET_DWORD(inbuf, NVRAM_ERASE_IN_OFFSET, offset);
MCDI_SET_DWORD(inbuf, NVRAM_ERASE_IN_LENGTH, length);
BUILD_BUG_ON(MC_CMD_NVRAM_ERASE_OUT_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_ERASE, inbuf, sizeof(inbuf),
NULL, 0, NULL);
return rc;
}
static int efx_mcdi_nvram_update_finish(struct efx_nic *efx, unsigned int type)
{
MCDI_DECLARE_BUF(inbuf, MC_CMD_NVRAM_UPDATE_FINISH_IN_LEN);
int rc;
MCDI_SET_DWORD(inbuf, NVRAM_UPDATE_FINISH_IN_TYPE, type);
BUILD_BUG_ON(MC_CMD_NVRAM_UPDATE_FINISH_OUT_LEN != 0);
rc = efx_mcdi_rpc(efx, MC_CMD_NVRAM_UPDATE_FINISH, inbuf, sizeof(inbuf),
NULL, 0, NULL);
return rc;
}
int efx_mcdi_mtd_read(struct mtd_info *mtd, loff_t start,
size_t len, size_t *retlen, u8 *buffer)
{
struct efx_mcdi_mtd_partition *part = to_efx_mcdi_mtd_partition(mtd);
struct efx_nic *efx = mtd->priv;
loff_t offset = start;
loff_t end = min_t(loff_t, start + len, mtd->size);
size_t chunk;
int rc = 0;
while (offset < end) {
chunk = min_t(size_t, end - offset, EFX_MCDI_NVRAM_LEN_MAX);
rc = efx_mcdi_nvram_read(efx, part->nvram_type, offset,
buffer, chunk);
if (rc)
goto out;
offset += chunk;
buffer += chunk;
}
out:
*retlen = offset - start;
return rc;
}
int efx_mcdi_mtd_erase(struct mtd_info *mtd, loff_t start, size_t len)
{
struct efx_mcdi_mtd_partition *part = to_efx_mcdi_mtd_partition(mtd);
struct efx_nic *efx = mtd->priv;
loff_t offset = start & ~((loff_t)(mtd->erasesize - 1));
loff_t end = min_t(loff_t, start + len, mtd->size);
size_t chunk = part->common.mtd.erasesize;
int rc = 0;
if (!part->updating) {
rc = efx_mcdi_nvram_update_start(efx, part->nvram_type);
if (rc)
goto out;
part->updating = true;
}
/* The MCDI interface can in fact do multiple erase blocks at once;
* but erasing may be slow, so we make multiple calls here to avoid
* tripping the MCDI RPC timeout. */
while (offset < end) {
rc = efx_mcdi_nvram_erase(efx, part->nvram_type, offset,
chunk);
if (rc)
goto out;
offset += chunk;
}
out:
return rc;
}
int efx_mcdi_mtd_write(struct mtd_info *mtd, loff_t start,
size_t len, size_t *retlen, const u8 *buffer)
{
struct efx_mcdi_mtd_partition *part = to_efx_mcdi_mtd_partition(mtd);
struct efx_nic *efx = mtd->priv;
loff_t offset = start;
loff_t end = min_t(loff_t, start + len, mtd->size);
size_t chunk;
int rc = 0;
if (!part->updating) {
rc = efx_mcdi_nvram_update_start(efx, part->nvram_type);
if (rc)
goto out;
part->updating = true;
}
while (offset < end) {
chunk = min_t(size_t, end - offset, EFX_MCDI_NVRAM_LEN_MAX);
rc = efx_mcdi_nvram_write(efx, part->nvram_type, offset,
buffer, chunk);
if (rc)
goto out;
offset += chunk;
buffer += chunk;
}
out:
*retlen = offset - start;
return rc;
}
int efx_mcdi_mtd_sync(struct mtd_info *mtd)
{
struct efx_mcdi_mtd_partition *part = to_efx_mcdi_mtd_partition(mtd);
struct efx_nic *efx = mtd->priv;
int rc = 0;
if (part->updating) {
part->updating = false;
rc = efx_mcdi_nvram_update_finish(efx, part->nvram_type);
}
return rc;
}
void efx_mcdi_mtd_rename(struct efx_mtd_partition *part)
{
struct efx_mcdi_mtd_partition *mcdi_part =
container_of(part, struct efx_mcdi_mtd_partition, common);
struct efx_nic *efx = part->mtd.priv;
snprintf(part->name, sizeof(part->name), "%s %s:%02x",
efx->name, part->type_name, mcdi_part->fw_subtype);
}
#endif /* CONFIG_SFC_MTD */
| gpl-2.0 |
helohe/android_kernel_samsung_n7100 | drivers/media/video/samsung/mali_r3p0/common/mali_kernel_utilization.c | 210 | 6027 | /*
* Copyright (C) 2010-2012 ARM Limited. All rights reserved.
*
* This program is free software and is provided to you under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation, and any use by you of this program is subject to the terms of such GNU licence.
*
* A copy of the licence is included with the program, and can also be obtained from Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "mali_kernel_utilization.h"
#include "mali_osk.h"
#include "mali_platform.h"
/* Define how often to calculate and report GPU utilization, in milliseconds */
#define MALI_GPU_UTILIZATION_TIMEOUT 100
static _mali_osk_lock_t *time_data_lock;
static _mali_osk_atomic_t num_running_cores;
static u64 period_start_time = 0;
static u64 work_start_time = 0;
static u64 accumulated_work_time = 0;
static _mali_osk_timer_t *utilization_timer = NULL;
static mali_bool timer_running = MALI_FALSE;
static void calculate_gpu_utilization(void* arg)
{
u64 time_now;
u64 time_period;
u32 leading_zeroes;
u32 shift_val;
u32 work_normalized;
u32 period_normalized;
u32 utilization;
_mali_osk_lock_wait(time_data_lock, _MALI_OSK_LOCKMODE_RW);
if (accumulated_work_time == 0 && work_start_time == 0)
{
/* Don't reschedule timer, this will be started if new work arrives */
timer_running = MALI_FALSE;
_mali_osk_lock_signal(time_data_lock, _MALI_OSK_LOCKMODE_RW);
/* No work done for this period, report zero usage */
mali_gpu_utilization_handler(0);
return;
}
time_now = _mali_osk_time_get_ns();
time_period = time_now - period_start_time;
/* If we are currently busy, update working period up to now */
if (work_start_time != 0)
{
accumulated_work_time += (time_now - work_start_time);
work_start_time = time_now;
}
/*
* We have two 64-bit values, a dividend and a divisor.
* To avoid dependencies to a 64-bit divider, we shift down the two values
* equally first.
* We shift the dividend up and possibly the divisor down, making the result X in 256.
*/
/* Shift the 64-bit values down so they fit inside a 32-bit integer */
leading_zeroes = _mali_osk_clz((u32)(time_period >> 32));
shift_val = 32 - leading_zeroes;
work_normalized = (u32)(accumulated_work_time >> shift_val);
period_normalized = (u32)(time_period >> shift_val);
/*
* Now, we should report the usage in parts of 256
* this means we must shift up the dividend or down the divisor by 8
* (we could do a combination, but we just use one for simplicity,
* but the end result should be good enough anyway)
*/
if (period_normalized > 0x00FFFFFF)
{
/* The divisor is so big that it is safe to shift it down */
period_normalized >>= 8;
}
else
{
/*
* The divisor is so small that we can shift up the dividend, without loosing any data.
* (dividend is always smaller than the divisor)
*/
work_normalized <<= 8;
}
utilization = work_normalized / period_normalized;
accumulated_work_time = 0;
period_start_time = time_now; /* starting a new period */
_mali_osk_lock_signal(time_data_lock, _MALI_OSK_LOCKMODE_RW);
_mali_osk_timer_add(utilization_timer, _mali_osk_time_mstoticks(MALI_GPU_UTILIZATION_TIMEOUT));
mali_gpu_utilization_handler(utilization);
}
_mali_osk_errcode_t mali_utilization_init(void)
{
time_data_lock = _mali_osk_lock_init(_MALI_OSK_LOCKFLAG_ORDERED | _MALI_OSK_LOCKFLAG_SPINLOCK_IRQ |
_MALI_OSK_LOCKFLAG_NONINTERRUPTABLE, 0, _MALI_OSK_LOCK_ORDER_UTILIZATION);
if (NULL == time_data_lock)
{
return _MALI_OSK_ERR_FAULT;
}
_mali_osk_atomic_init(&num_running_cores, 0);
utilization_timer = _mali_osk_timer_init();
if (NULL == utilization_timer)
{
_mali_osk_lock_term(time_data_lock);
return _MALI_OSK_ERR_FAULT;
}
_mali_osk_timer_setcallback(utilization_timer, calculate_gpu_utilization, NULL);
return _MALI_OSK_ERR_OK;
}
void mali_utilization_suspend(void)
{
if (NULL != utilization_timer)
{
_mali_osk_timer_del(utilization_timer);
timer_running = MALI_FALSE;
}
}
void mali_utilization_term(void)
{
if (NULL != utilization_timer)
{
_mali_osk_timer_del(utilization_timer);
timer_running = MALI_FALSE;
_mali_osk_timer_term(utilization_timer);
utilization_timer = NULL;
}
_mali_osk_atomic_term(&num_running_cores);
_mali_osk_lock_term(time_data_lock);
}
void mali_utilization_core_start(u64 time_now)
{
if (_mali_osk_atomic_inc_return(&num_running_cores) == 1)
{
/*
* We went from zero cores working, to one core working,
* we now consider the entire GPU for being busy
*/
_mali_osk_lock_wait(time_data_lock, _MALI_OSK_LOCKMODE_RW);
if (time_now < period_start_time)
{
/*
* This might happen if the calculate_gpu_utilization() was able
* to run between the sampling of time_now and us grabbing the lock above
*/
time_now = period_start_time;
}
work_start_time = time_now;
if (timer_running != MALI_TRUE)
{
timer_running = MALI_TRUE;
period_start_time = work_start_time; /* starting a new period */
_mali_osk_lock_signal(time_data_lock, _MALI_OSK_LOCKMODE_RW);
_mali_osk_timer_del(utilization_timer);
_mali_osk_timer_add(utilization_timer, _mali_osk_time_mstoticks(MALI_GPU_UTILIZATION_TIMEOUT));
}
else
{
_mali_osk_lock_signal(time_data_lock, _MALI_OSK_LOCKMODE_RW);
}
}
}
void mali_utilization_core_end(u64 time_now)
{
if (_mali_osk_atomic_dec_return(&num_running_cores) == 0)
{
/*
* No more cores are working, so accumulate the time we was busy.
*/
_mali_osk_lock_wait(time_data_lock, _MALI_OSK_LOCKMODE_RW);
if (time_now < work_start_time)
{
/*
* This might happen if the calculate_gpu_utilization() was able
* to run between the sampling of time_now and us grabbing the lock above
*/
time_now = work_start_time;
}
accumulated_work_time += (time_now - work_start_time);
work_start_time = 0;
_mali_osk_lock_signal(time_data_lock, _MALI_OSK_LOCKMODE_RW);
}
}
| gpl-2.0 |
dblessing/linux | drivers/edac/xgene_edac.c | 210 | 35117 | /*
* APM X-Gene SoC EDAC (error detection and correction)
*
* Copyright (c) 2015, Applied Micro Circuits Corporation
* Author: Feng Kan <fkan@apm.com>
* Loc Ho <lho@apm.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/ctype.h>
#include <linux/edac.h>
#include <linux/interrupt.h>
#include <linux/mfd/syscon.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/regmap.h>
#include "edac_core.h"
#define EDAC_MOD_STR "xgene_edac"
/* Global error configuration status registers (CSR) */
#define PCPHPERRINTSTS 0x0000
#define PCPHPERRINTMSK 0x0004
#define MCU_CTL_ERR_MASK BIT(12)
#define IOB_PA_ERR_MASK BIT(11)
#define IOB_BA_ERR_MASK BIT(10)
#define IOB_XGIC_ERR_MASK BIT(9)
#define IOB_RB_ERR_MASK BIT(8)
#define L3C_UNCORR_ERR_MASK BIT(5)
#define MCU_UNCORR_ERR_MASK BIT(4)
#define PMD3_MERR_MASK BIT(3)
#define PMD2_MERR_MASK BIT(2)
#define PMD1_MERR_MASK BIT(1)
#define PMD0_MERR_MASK BIT(0)
#define PCPLPERRINTSTS 0x0008
#define PCPLPERRINTMSK 0x000C
#define CSW_SWITCH_TRACE_ERR_MASK BIT(2)
#define L3C_CORR_ERR_MASK BIT(1)
#define MCU_CORR_ERR_MASK BIT(0)
#define MEMERRINTSTS 0x0010
#define MEMERRINTMSK 0x0014
struct xgene_edac {
struct device *dev;
struct regmap *csw_map;
struct regmap *mcba_map;
struct regmap *mcbb_map;
struct regmap *efuse_map;
void __iomem *pcp_csr;
spinlock_t lock;
struct dentry *dfs;
struct list_head mcus;
struct list_head pmds;
struct mutex mc_lock;
int mc_active_mask;
int mc_registered_mask;
};
static void xgene_edac_pcp_rd(struct xgene_edac *edac, u32 reg, u32 *val)
{
*val = readl(edac->pcp_csr + reg);
}
static void xgene_edac_pcp_clrbits(struct xgene_edac *edac, u32 reg,
u32 bits_mask)
{
u32 val;
spin_lock(&edac->lock);
val = readl(edac->pcp_csr + reg);
val &= ~bits_mask;
writel(val, edac->pcp_csr + reg);
spin_unlock(&edac->lock);
}
static void xgene_edac_pcp_setbits(struct xgene_edac *edac, u32 reg,
u32 bits_mask)
{
u32 val;
spin_lock(&edac->lock);
val = readl(edac->pcp_csr + reg);
val |= bits_mask;
writel(val, edac->pcp_csr + reg);
spin_unlock(&edac->lock);
}
/* Memory controller error CSR */
#define MCU_MAX_RANK 8
#define MCU_RANK_STRIDE 0x40
#define MCUGECR 0x0110
#define MCU_GECR_DEMANDUCINTREN_MASK BIT(0)
#define MCU_GECR_BACKUCINTREN_MASK BIT(1)
#define MCU_GECR_CINTREN_MASK BIT(2)
#define MUC_GECR_MCUADDRERREN_MASK BIT(9)
#define MCUGESR 0x0114
#define MCU_GESR_ADDRNOMATCH_ERR_MASK BIT(7)
#define MCU_GESR_ADDRMULTIMATCH_ERR_MASK BIT(6)
#define MCU_GESR_PHYP_ERR_MASK BIT(3)
#define MCUESRR0 0x0314
#define MCU_ESRR_MULTUCERR_MASK BIT(3)
#define MCU_ESRR_BACKUCERR_MASK BIT(2)
#define MCU_ESRR_DEMANDUCERR_MASK BIT(1)
#define MCU_ESRR_CERR_MASK BIT(0)
#define MCUESRRA0 0x0318
#define MCUEBLRR0 0x031c
#define MCU_EBLRR_ERRBANK_RD(src) (((src) & 0x00000007) >> 0)
#define MCUERCRR0 0x0320
#define MCU_ERCRR_ERRROW_RD(src) (((src) & 0xFFFF0000) >> 16)
#define MCU_ERCRR_ERRCOL_RD(src) ((src) & 0x00000FFF)
#define MCUSBECNT0 0x0324
#define MCU_SBECNT_COUNT(src) ((src) & 0xFFFF)
#define CSW_CSWCR 0x0000
#define CSW_CSWCR_DUALMCB_MASK BIT(0)
#define MCBADDRMR 0x0000
#define MCBADDRMR_MCU_INTLV_MODE_MASK BIT(3)
#define MCBADDRMR_DUALMCU_MODE_MASK BIT(2)
#define MCBADDRMR_MCB_INTLV_MODE_MASK BIT(1)
#define MCBADDRMR_ADDRESS_MODE_MASK BIT(0)
struct xgene_edac_mc_ctx {
struct list_head next;
char *name;
struct mem_ctl_info *mci;
struct xgene_edac *edac;
void __iomem *mcu_csr;
u32 mcu_id;
};
static ssize_t xgene_edac_mc_err_inject_write(struct file *file,
const char __user *data,
size_t count, loff_t *ppos)
{
struct mem_ctl_info *mci = file->private_data;
struct xgene_edac_mc_ctx *ctx = mci->pvt_info;
int i;
for (i = 0; i < MCU_MAX_RANK; i++) {
writel(MCU_ESRR_MULTUCERR_MASK | MCU_ESRR_BACKUCERR_MASK |
MCU_ESRR_DEMANDUCERR_MASK | MCU_ESRR_CERR_MASK,
ctx->mcu_csr + MCUESRRA0 + i * MCU_RANK_STRIDE);
}
return count;
}
static const struct file_operations xgene_edac_mc_debug_inject_fops = {
.open = simple_open,
.write = xgene_edac_mc_err_inject_write,
.llseek = generic_file_llseek,
};
static void xgene_edac_mc_create_debugfs_node(struct mem_ctl_info *mci)
{
if (!IS_ENABLED(CONFIG_EDAC_DEBUG))
return;
#ifdef CONFIG_EDAC_DEBUG
if (!mci->debugfs)
return;
debugfs_create_file("inject_ctrl", S_IWUSR, mci->debugfs, mci,
&xgene_edac_mc_debug_inject_fops);
#endif
}
static void xgene_edac_mc_check(struct mem_ctl_info *mci)
{
struct xgene_edac_mc_ctx *ctx = mci->pvt_info;
unsigned int pcp_hp_stat;
unsigned int pcp_lp_stat;
u32 reg;
u32 rank;
u32 bank;
u32 count;
u32 col_row;
xgene_edac_pcp_rd(ctx->edac, PCPHPERRINTSTS, &pcp_hp_stat);
xgene_edac_pcp_rd(ctx->edac, PCPLPERRINTSTS, &pcp_lp_stat);
if (!((MCU_UNCORR_ERR_MASK & pcp_hp_stat) ||
(MCU_CTL_ERR_MASK & pcp_hp_stat) ||
(MCU_CORR_ERR_MASK & pcp_lp_stat)))
return;
for (rank = 0; rank < MCU_MAX_RANK; rank++) {
reg = readl(ctx->mcu_csr + MCUESRR0 + rank * MCU_RANK_STRIDE);
/* Detect uncorrectable memory error */
if (reg & (MCU_ESRR_DEMANDUCERR_MASK |
MCU_ESRR_BACKUCERR_MASK)) {
/* Detected uncorrectable memory error */
edac_mc_chipset_printk(mci, KERN_ERR, "X-Gene",
"MCU uncorrectable error at rank %d\n", rank);
edac_mc_handle_error(HW_EVENT_ERR_UNCORRECTED, mci,
1, 0, 0, 0, 0, 0, -1, mci->ctl_name, "");
}
/* Detect correctable memory error */
if (reg & MCU_ESRR_CERR_MASK) {
bank = readl(ctx->mcu_csr + MCUEBLRR0 +
rank * MCU_RANK_STRIDE);
col_row = readl(ctx->mcu_csr + MCUERCRR0 +
rank * MCU_RANK_STRIDE);
count = readl(ctx->mcu_csr + MCUSBECNT0 +
rank * MCU_RANK_STRIDE);
edac_mc_chipset_printk(mci, KERN_WARNING, "X-Gene",
"MCU correctable error at rank %d bank %d column %d row %d count %d\n",
rank, MCU_EBLRR_ERRBANK_RD(bank),
MCU_ERCRR_ERRCOL_RD(col_row),
MCU_ERCRR_ERRROW_RD(col_row),
MCU_SBECNT_COUNT(count));
edac_mc_handle_error(HW_EVENT_ERR_CORRECTED, mci,
1, 0, 0, 0, 0, 0, -1, mci->ctl_name, "");
}
/* Clear all error registers */
writel(0x0, ctx->mcu_csr + MCUEBLRR0 + rank * MCU_RANK_STRIDE);
writel(0x0, ctx->mcu_csr + MCUERCRR0 + rank * MCU_RANK_STRIDE);
writel(0x0, ctx->mcu_csr + MCUSBECNT0 +
rank * MCU_RANK_STRIDE);
writel(reg, ctx->mcu_csr + MCUESRR0 + rank * MCU_RANK_STRIDE);
}
/* Detect memory controller error */
reg = readl(ctx->mcu_csr + MCUGESR);
if (reg) {
if (reg & MCU_GESR_ADDRNOMATCH_ERR_MASK)
edac_mc_chipset_printk(mci, KERN_WARNING, "X-Gene",
"MCU address miss-match error\n");
if (reg & MCU_GESR_ADDRMULTIMATCH_ERR_MASK)
edac_mc_chipset_printk(mci, KERN_WARNING, "X-Gene",
"MCU address multi-match error\n");
writel(reg, ctx->mcu_csr + MCUGESR);
}
}
static void xgene_edac_mc_irq_ctl(struct mem_ctl_info *mci, bool enable)
{
struct xgene_edac_mc_ctx *ctx = mci->pvt_info;
unsigned int val;
if (edac_op_state != EDAC_OPSTATE_INT)
return;
mutex_lock(&ctx->edac->mc_lock);
/*
* As there is only single bit for enable error and interrupt mask,
* we must only enable top level interrupt after all MCUs are
* registered. Otherwise, if there is an error and the corresponding
* MCU has not registered, the interrupt will never get cleared. To
* determine all MCU have registered, we will keep track of active
* MCUs and registered MCUs.
*/
if (enable) {
/* Set registered MCU bit */
ctx->edac->mc_registered_mask |= 1 << ctx->mcu_id;
/* Enable interrupt after all active MCU registered */
if (ctx->edac->mc_registered_mask ==
ctx->edac->mc_active_mask) {
/* Enable memory controller top level interrupt */
xgene_edac_pcp_clrbits(ctx->edac, PCPHPERRINTMSK,
MCU_UNCORR_ERR_MASK |
MCU_CTL_ERR_MASK);
xgene_edac_pcp_clrbits(ctx->edac, PCPLPERRINTMSK,
MCU_CORR_ERR_MASK);
}
/* Enable MCU interrupt and error reporting */
val = readl(ctx->mcu_csr + MCUGECR);
val |= MCU_GECR_DEMANDUCINTREN_MASK |
MCU_GECR_BACKUCINTREN_MASK |
MCU_GECR_CINTREN_MASK |
MUC_GECR_MCUADDRERREN_MASK;
writel(val, ctx->mcu_csr + MCUGECR);
} else {
/* Disable MCU interrupt */
val = readl(ctx->mcu_csr + MCUGECR);
val &= ~(MCU_GECR_DEMANDUCINTREN_MASK |
MCU_GECR_BACKUCINTREN_MASK |
MCU_GECR_CINTREN_MASK |
MUC_GECR_MCUADDRERREN_MASK);
writel(val, ctx->mcu_csr + MCUGECR);
/* Disable memory controller top level interrupt */
xgene_edac_pcp_setbits(ctx->edac, PCPHPERRINTMSK,
MCU_UNCORR_ERR_MASK | MCU_CTL_ERR_MASK);
xgene_edac_pcp_setbits(ctx->edac, PCPLPERRINTMSK,
MCU_CORR_ERR_MASK);
/* Clear registered MCU bit */
ctx->edac->mc_registered_mask &= ~(1 << ctx->mcu_id);
}
mutex_unlock(&ctx->edac->mc_lock);
}
static int xgene_edac_mc_is_active(struct xgene_edac_mc_ctx *ctx, int mc_idx)
{
unsigned int reg;
u32 mcu_mask;
if (regmap_read(ctx->edac->csw_map, CSW_CSWCR, ®))
return 0;
if (reg & CSW_CSWCR_DUALMCB_MASK) {
/*
* Dual MCB active - Determine if all 4 active or just MCU0
* and MCU2 active
*/
if (regmap_read(ctx->edac->mcbb_map, MCBADDRMR, ®))
return 0;
mcu_mask = (reg & MCBADDRMR_DUALMCU_MODE_MASK) ? 0xF : 0x5;
} else {
/*
* Single MCB active - Determine if MCU0/MCU1 or just MCU0
* active
*/
if (regmap_read(ctx->edac->mcba_map, MCBADDRMR, ®))
return 0;
mcu_mask = (reg & MCBADDRMR_DUALMCU_MODE_MASK) ? 0x3 : 0x1;
}
/* Save active MC mask if hasn't set already */
if (!ctx->edac->mc_active_mask)
ctx->edac->mc_active_mask = mcu_mask;
return (mcu_mask & (1 << mc_idx)) ? 1 : 0;
}
static int xgene_edac_mc_add(struct xgene_edac *edac, struct device_node *np)
{
struct mem_ctl_info *mci;
struct edac_mc_layer layers[2];
struct xgene_edac_mc_ctx tmp_ctx;
struct xgene_edac_mc_ctx *ctx;
struct resource res;
int rc;
memset(&tmp_ctx, 0, sizeof(tmp_ctx));
tmp_ctx.edac = edac;
if (!devres_open_group(edac->dev, xgene_edac_mc_add, GFP_KERNEL))
return -ENOMEM;
rc = of_address_to_resource(np, 0, &res);
if (rc < 0) {
dev_err(edac->dev, "no MCU resource address\n");
goto err_group;
}
tmp_ctx.mcu_csr = devm_ioremap_resource(edac->dev, &res);
if (IS_ERR(tmp_ctx.mcu_csr)) {
dev_err(edac->dev, "unable to map MCU resource\n");
rc = PTR_ERR(tmp_ctx.mcu_csr);
goto err_group;
}
/* Ignore non-active MCU */
if (of_property_read_u32(np, "memory-controller", &tmp_ctx.mcu_id)) {
dev_err(edac->dev, "no memory-controller property\n");
rc = -ENODEV;
goto err_group;
}
if (!xgene_edac_mc_is_active(&tmp_ctx, tmp_ctx.mcu_id)) {
rc = -ENODEV;
goto err_group;
}
layers[0].type = EDAC_MC_LAYER_CHIP_SELECT;
layers[0].size = 4;
layers[0].is_virt_csrow = true;
layers[1].type = EDAC_MC_LAYER_CHANNEL;
layers[1].size = 2;
layers[1].is_virt_csrow = false;
mci = edac_mc_alloc(tmp_ctx.mcu_id, ARRAY_SIZE(layers), layers,
sizeof(*ctx));
if (!mci) {
rc = -ENOMEM;
goto err_group;
}
ctx = mci->pvt_info;
*ctx = tmp_ctx; /* Copy over resource value */
ctx->name = "xgene_edac_mc_err";
ctx->mci = mci;
mci->pdev = &mci->dev;
mci->ctl_name = ctx->name;
mci->dev_name = ctx->name;
mci->mtype_cap = MEM_FLAG_RDDR | MEM_FLAG_RDDR2 | MEM_FLAG_RDDR3 |
MEM_FLAG_DDR | MEM_FLAG_DDR2 | MEM_FLAG_DDR3;
mci->edac_ctl_cap = EDAC_FLAG_SECDED;
mci->edac_cap = EDAC_FLAG_SECDED;
mci->mod_name = EDAC_MOD_STR;
mci->mod_ver = "0.1";
mci->ctl_page_to_phys = NULL;
mci->scrub_cap = SCRUB_FLAG_HW_SRC;
mci->scrub_mode = SCRUB_HW_SRC;
if (edac_op_state == EDAC_OPSTATE_POLL)
mci->edac_check = xgene_edac_mc_check;
if (edac_mc_add_mc(mci)) {
dev_err(edac->dev, "edac_mc_add_mc failed\n");
rc = -EINVAL;
goto err_free;
}
xgene_edac_mc_create_debugfs_node(mci);
list_add(&ctx->next, &edac->mcus);
xgene_edac_mc_irq_ctl(mci, true);
devres_remove_group(edac->dev, xgene_edac_mc_add);
dev_info(edac->dev, "X-Gene EDAC MC registered\n");
return 0;
err_free:
edac_mc_free(mci);
err_group:
devres_release_group(edac->dev, xgene_edac_mc_add);
return rc;
}
static int xgene_edac_mc_remove(struct xgene_edac_mc_ctx *mcu)
{
xgene_edac_mc_irq_ctl(mcu->mci, false);
edac_mc_del_mc(&mcu->mci->dev);
edac_mc_free(mcu->mci);
return 0;
}
/* CPU L1/L2 error CSR */
#define MAX_CPU_PER_PMD 2
#define CPU_CSR_STRIDE 0x00100000
#define CPU_L2C_PAGE 0x000D0000
#define CPU_MEMERR_L2C_PAGE 0x000E0000
#define CPU_MEMERR_CPU_PAGE 0x000F0000
#define MEMERR_CPU_ICFECR_PAGE_OFFSET 0x0000
#define MEMERR_CPU_ICFESR_PAGE_OFFSET 0x0004
#define MEMERR_CPU_ICFESR_ERRWAY_RD(src) (((src) & 0xFF000000) >> 24)
#define MEMERR_CPU_ICFESR_ERRINDEX_RD(src) (((src) & 0x003F0000) >> 16)
#define MEMERR_CPU_ICFESR_ERRINFO_RD(src) (((src) & 0x0000FF00) >> 8)
#define MEMERR_CPU_ICFESR_ERRTYPE_RD(src) (((src) & 0x00000070) >> 4)
#define MEMERR_CPU_ICFESR_MULTCERR_MASK BIT(2)
#define MEMERR_CPU_ICFESR_CERR_MASK BIT(0)
#define MEMERR_CPU_LSUESR_PAGE_OFFSET 0x000c
#define MEMERR_CPU_LSUESR_ERRWAY_RD(src) (((src) & 0xFF000000) >> 24)
#define MEMERR_CPU_LSUESR_ERRINDEX_RD(src) (((src) & 0x003F0000) >> 16)
#define MEMERR_CPU_LSUESR_ERRINFO_RD(src) (((src) & 0x0000FF00) >> 8)
#define MEMERR_CPU_LSUESR_ERRTYPE_RD(src) (((src) & 0x00000070) >> 4)
#define MEMERR_CPU_LSUESR_MULTCERR_MASK BIT(2)
#define MEMERR_CPU_LSUESR_CERR_MASK BIT(0)
#define MEMERR_CPU_LSUECR_PAGE_OFFSET 0x0008
#define MEMERR_CPU_MMUECR_PAGE_OFFSET 0x0010
#define MEMERR_CPU_MMUESR_PAGE_OFFSET 0x0014
#define MEMERR_CPU_MMUESR_ERRWAY_RD(src) (((src) & 0xFF000000) >> 24)
#define MEMERR_CPU_MMUESR_ERRINDEX_RD(src) (((src) & 0x007F0000) >> 16)
#define MEMERR_CPU_MMUESR_ERRINFO_RD(src) (((src) & 0x0000FF00) >> 8)
#define MEMERR_CPU_MMUESR_ERRREQSTR_LSU_MASK BIT(7)
#define MEMERR_CPU_MMUESR_ERRTYPE_RD(src) (((src) & 0x00000070) >> 4)
#define MEMERR_CPU_MMUESR_MULTCERR_MASK BIT(2)
#define MEMERR_CPU_MMUESR_CERR_MASK BIT(0)
#define MEMERR_CPU_ICFESRA_PAGE_OFFSET 0x0804
#define MEMERR_CPU_LSUESRA_PAGE_OFFSET 0x080c
#define MEMERR_CPU_MMUESRA_PAGE_OFFSET 0x0814
#define MEMERR_L2C_L2ECR_PAGE_OFFSET 0x0000
#define MEMERR_L2C_L2ESR_PAGE_OFFSET 0x0004
#define MEMERR_L2C_L2ESR_ERRSYN_RD(src) (((src) & 0xFF000000) >> 24)
#define MEMERR_L2C_L2ESR_ERRWAY_RD(src) (((src) & 0x00FC0000) >> 18)
#define MEMERR_L2C_L2ESR_ERRCPU_RD(src) (((src) & 0x00020000) >> 17)
#define MEMERR_L2C_L2ESR_ERRGROUP_RD(src) (((src) & 0x0000E000) >> 13)
#define MEMERR_L2C_L2ESR_ERRACTION_RD(src) (((src) & 0x00001C00) >> 10)
#define MEMERR_L2C_L2ESR_ERRTYPE_RD(src) (((src) & 0x00000300) >> 8)
#define MEMERR_L2C_L2ESR_MULTUCERR_MASK BIT(3)
#define MEMERR_L2C_L2ESR_MULTICERR_MASK BIT(2)
#define MEMERR_L2C_L2ESR_UCERR_MASK BIT(1)
#define MEMERR_L2C_L2ESR_ERR_MASK BIT(0)
#define MEMERR_L2C_L2EALR_PAGE_OFFSET 0x0008
#define CPUX_L2C_L2RTOCR_PAGE_OFFSET 0x0010
#define MEMERR_L2C_L2EAHR_PAGE_OFFSET 0x000c
#define CPUX_L2C_L2RTOSR_PAGE_OFFSET 0x0014
#define MEMERR_L2C_L2RTOSR_MULTERR_MASK BIT(1)
#define MEMERR_L2C_L2RTOSR_ERR_MASK BIT(0)
#define CPUX_L2C_L2RTOALR_PAGE_OFFSET 0x0018
#define CPUX_L2C_L2RTOAHR_PAGE_OFFSET 0x001c
#define MEMERR_L2C_L2ESRA_PAGE_OFFSET 0x0804
/*
* Processor Module Domain (PMD) context - Context for a pair of processsors.
* Each PMD consists of 2 CPUs and a shared L2 cache. Each CPU consists of
* its own L1 cache.
*/
struct xgene_edac_pmd_ctx {
struct list_head next;
struct device ddev;
char *name;
struct xgene_edac *edac;
struct edac_device_ctl_info *edac_dev;
void __iomem *pmd_csr;
u32 pmd;
int version;
};
static void xgene_edac_pmd_l1_check(struct edac_device_ctl_info *edac_dev,
int cpu_idx)
{
struct xgene_edac_pmd_ctx *ctx = edac_dev->pvt_info;
void __iomem *pg_f;
u32 val;
pg_f = ctx->pmd_csr + cpu_idx * CPU_CSR_STRIDE + CPU_MEMERR_CPU_PAGE;
val = readl(pg_f + MEMERR_CPU_ICFESR_PAGE_OFFSET);
if (val) {
dev_err(edac_dev->dev,
"CPU%d L1 memory error ICF 0x%08X Way 0x%02X Index 0x%02X Info 0x%02X\n",
ctx->pmd * MAX_CPU_PER_PMD + cpu_idx, val,
MEMERR_CPU_ICFESR_ERRWAY_RD(val),
MEMERR_CPU_ICFESR_ERRINDEX_RD(val),
MEMERR_CPU_ICFESR_ERRINFO_RD(val));
if (val & MEMERR_CPU_ICFESR_CERR_MASK)
dev_err(edac_dev->dev,
"One or more correctable error\n");
if (val & MEMERR_CPU_ICFESR_MULTCERR_MASK)
dev_err(edac_dev->dev, "Multiple correctable error\n");
switch (MEMERR_CPU_ICFESR_ERRTYPE_RD(val)) {
case 1:
dev_err(edac_dev->dev, "L1 TLB multiple hit\n");
break;
case 2:
dev_err(edac_dev->dev, "Way select multiple hit\n");
break;
case 3:
dev_err(edac_dev->dev, "Physical tag parity error\n");
break;
case 4:
case 5:
dev_err(edac_dev->dev, "L1 data parity error\n");
break;
case 6:
dev_err(edac_dev->dev, "L1 pre-decode parity error\n");
break;
}
/* Clear any HW errors */
writel(val, pg_f + MEMERR_CPU_ICFESR_PAGE_OFFSET);
if (val & (MEMERR_CPU_ICFESR_CERR_MASK |
MEMERR_CPU_ICFESR_MULTCERR_MASK))
edac_device_handle_ce(edac_dev, 0, 0,
edac_dev->ctl_name);
}
val = readl(pg_f + MEMERR_CPU_LSUESR_PAGE_OFFSET);
if (val) {
dev_err(edac_dev->dev,
"CPU%d memory error LSU 0x%08X Way 0x%02X Index 0x%02X Info 0x%02X\n",
ctx->pmd * MAX_CPU_PER_PMD + cpu_idx, val,
MEMERR_CPU_LSUESR_ERRWAY_RD(val),
MEMERR_CPU_LSUESR_ERRINDEX_RD(val),
MEMERR_CPU_LSUESR_ERRINFO_RD(val));
if (val & MEMERR_CPU_LSUESR_CERR_MASK)
dev_err(edac_dev->dev,
"One or more correctable error\n");
if (val & MEMERR_CPU_LSUESR_MULTCERR_MASK)
dev_err(edac_dev->dev, "Multiple correctable error\n");
switch (MEMERR_CPU_LSUESR_ERRTYPE_RD(val)) {
case 0:
dev_err(edac_dev->dev, "Load tag error\n");
break;
case 1:
dev_err(edac_dev->dev, "Load data error\n");
break;
case 2:
dev_err(edac_dev->dev, "WSL multihit error\n");
break;
case 3:
dev_err(edac_dev->dev, "Store tag error\n");
break;
case 4:
dev_err(edac_dev->dev,
"DTB multihit from load pipeline error\n");
break;
case 5:
dev_err(edac_dev->dev,
"DTB multihit from store pipeline error\n");
break;
}
/* Clear any HW errors */
writel(val, pg_f + MEMERR_CPU_LSUESR_PAGE_OFFSET);
if (val & (MEMERR_CPU_LSUESR_CERR_MASK |
MEMERR_CPU_LSUESR_MULTCERR_MASK))
edac_device_handle_ce(edac_dev, 0, 0,
edac_dev->ctl_name);
}
val = readl(pg_f + MEMERR_CPU_MMUESR_PAGE_OFFSET);
if (val) {
dev_err(edac_dev->dev,
"CPU%d memory error MMU 0x%08X Way 0x%02X Index 0x%02X Info 0x%02X %s\n",
ctx->pmd * MAX_CPU_PER_PMD + cpu_idx, val,
MEMERR_CPU_MMUESR_ERRWAY_RD(val),
MEMERR_CPU_MMUESR_ERRINDEX_RD(val),
MEMERR_CPU_MMUESR_ERRINFO_RD(val),
val & MEMERR_CPU_MMUESR_ERRREQSTR_LSU_MASK ? "LSU" :
"ICF");
if (val & MEMERR_CPU_MMUESR_CERR_MASK)
dev_err(edac_dev->dev,
"One or more correctable error\n");
if (val & MEMERR_CPU_MMUESR_MULTCERR_MASK)
dev_err(edac_dev->dev, "Multiple correctable error\n");
switch (MEMERR_CPU_MMUESR_ERRTYPE_RD(val)) {
case 0:
dev_err(edac_dev->dev, "Stage 1 UTB hit error\n");
break;
case 1:
dev_err(edac_dev->dev, "Stage 1 UTB miss error\n");
break;
case 2:
dev_err(edac_dev->dev, "Stage 1 UTB allocate error\n");
break;
case 3:
dev_err(edac_dev->dev,
"TMO operation single bank error\n");
break;
case 4:
dev_err(edac_dev->dev, "Stage 2 UTB error\n");
break;
case 5:
dev_err(edac_dev->dev, "Stage 2 UTB miss error\n");
break;
case 6:
dev_err(edac_dev->dev, "Stage 2 UTB allocate error\n");
break;
case 7:
dev_err(edac_dev->dev,
"TMO operation multiple bank error\n");
break;
}
/* Clear any HW errors */
writel(val, pg_f + MEMERR_CPU_MMUESR_PAGE_OFFSET);
edac_device_handle_ce(edac_dev, 0, 0, edac_dev->ctl_name);
}
}
static void xgene_edac_pmd_l2_check(struct edac_device_ctl_info *edac_dev)
{
struct xgene_edac_pmd_ctx *ctx = edac_dev->pvt_info;
void __iomem *pg_d;
void __iomem *pg_e;
u32 val_hi;
u32 val_lo;
u32 val;
/* Check L2 */
pg_e = ctx->pmd_csr + CPU_MEMERR_L2C_PAGE;
val = readl(pg_e + MEMERR_L2C_L2ESR_PAGE_OFFSET);
if (val) {
val_lo = readl(pg_e + MEMERR_L2C_L2EALR_PAGE_OFFSET);
val_hi = readl(pg_e + MEMERR_L2C_L2EAHR_PAGE_OFFSET);
dev_err(edac_dev->dev,
"PMD%d memory error L2C L2ESR 0x%08X @ 0x%08X.%08X\n",
ctx->pmd, val, val_hi, val_lo);
dev_err(edac_dev->dev,
"ErrSyndrome 0x%02X ErrWay 0x%02X ErrCpu %d ErrGroup 0x%02X ErrAction 0x%02X\n",
MEMERR_L2C_L2ESR_ERRSYN_RD(val),
MEMERR_L2C_L2ESR_ERRWAY_RD(val),
MEMERR_L2C_L2ESR_ERRCPU_RD(val),
MEMERR_L2C_L2ESR_ERRGROUP_RD(val),
MEMERR_L2C_L2ESR_ERRACTION_RD(val));
if (val & MEMERR_L2C_L2ESR_ERR_MASK)
dev_err(edac_dev->dev,
"One or more correctable error\n");
if (val & MEMERR_L2C_L2ESR_MULTICERR_MASK)
dev_err(edac_dev->dev, "Multiple correctable error\n");
if (val & MEMERR_L2C_L2ESR_UCERR_MASK)
dev_err(edac_dev->dev,
"One or more uncorrectable error\n");
if (val & MEMERR_L2C_L2ESR_MULTUCERR_MASK)
dev_err(edac_dev->dev,
"Multiple uncorrectable error\n");
switch (MEMERR_L2C_L2ESR_ERRTYPE_RD(val)) {
case 0:
dev_err(edac_dev->dev, "Outbound SDB parity error\n");
break;
case 1:
dev_err(edac_dev->dev, "Inbound SDB parity error\n");
break;
case 2:
dev_err(edac_dev->dev, "Tag ECC error\n");
break;
case 3:
dev_err(edac_dev->dev, "Data ECC error\n");
break;
}
/* Clear any HW errors */
writel(val, pg_e + MEMERR_L2C_L2ESR_PAGE_OFFSET);
if (val & (MEMERR_L2C_L2ESR_ERR_MASK |
MEMERR_L2C_L2ESR_MULTICERR_MASK))
edac_device_handle_ce(edac_dev, 0, 0,
edac_dev->ctl_name);
if (val & (MEMERR_L2C_L2ESR_UCERR_MASK |
MEMERR_L2C_L2ESR_MULTUCERR_MASK))
edac_device_handle_ue(edac_dev, 0, 0,
edac_dev->ctl_name);
}
/* Check if any memory request timed out on L2 cache */
pg_d = ctx->pmd_csr + CPU_L2C_PAGE;
val = readl(pg_d + CPUX_L2C_L2RTOSR_PAGE_OFFSET);
if (val) {
val_lo = readl(pg_d + CPUX_L2C_L2RTOALR_PAGE_OFFSET);
val_hi = readl(pg_d + CPUX_L2C_L2RTOAHR_PAGE_OFFSET);
dev_err(edac_dev->dev,
"PMD%d L2C error L2C RTOSR 0x%08X @ 0x%08X.%08X\n",
ctx->pmd, val, val_hi, val_lo);
writel(val, pg_d + CPUX_L2C_L2RTOSR_PAGE_OFFSET);
}
}
static void xgene_edac_pmd_check(struct edac_device_ctl_info *edac_dev)
{
struct xgene_edac_pmd_ctx *ctx = edac_dev->pvt_info;
unsigned int pcp_hp_stat;
int i;
xgene_edac_pcp_rd(ctx->edac, PCPHPERRINTSTS, &pcp_hp_stat);
if (!((PMD0_MERR_MASK << ctx->pmd) & pcp_hp_stat))
return;
/* Check CPU L1 error */
for (i = 0; i < MAX_CPU_PER_PMD; i++)
xgene_edac_pmd_l1_check(edac_dev, i);
/* Check CPU L2 error */
xgene_edac_pmd_l2_check(edac_dev);
}
static void xgene_edac_pmd_cpu_hw_cfg(struct edac_device_ctl_info *edac_dev,
int cpu)
{
struct xgene_edac_pmd_ctx *ctx = edac_dev->pvt_info;
void __iomem *pg_f = ctx->pmd_csr + cpu * CPU_CSR_STRIDE +
CPU_MEMERR_CPU_PAGE;
/*
* Enable CPU memory error:
* MEMERR_CPU_ICFESRA, MEMERR_CPU_LSUESRA, and MEMERR_CPU_MMUESRA
*/
writel(0x00000301, pg_f + MEMERR_CPU_ICFECR_PAGE_OFFSET);
writel(0x00000301, pg_f + MEMERR_CPU_LSUECR_PAGE_OFFSET);
writel(0x00000101, pg_f + MEMERR_CPU_MMUECR_PAGE_OFFSET);
}
static void xgene_edac_pmd_hw_cfg(struct edac_device_ctl_info *edac_dev)
{
struct xgene_edac_pmd_ctx *ctx = edac_dev->pvt_info;
void __iomem *pg_d = ctx->pmd_csr + CPU_L2C_PAGE;
void __iomem *pg_e = ctx->pmd_csr + CPU_MEMERR_L2C_PAGE;
/* Enable PMD memory error - MEMERR_L2C_L2ECR and L2C_L2RTOCR */
writel(0x00000703, pg_e + MEMERR_L2C_L2ECR_PAGE_OFFSET);
/* Configure L2C HW request time out feature if supported */
if (ctx->version > 1)
writel(0x00000119, pg_d + CPUX_L2C_L2RTOCR_PAGE_OFFSET);
}
static void xgene_edac_pmd_hw_ctl(struct edac_device_ctl_info *edac_dev,
bool enable)
{
struct xgene_edac_pmd_ctx *ctx = edac_dev->pvt_info;
int i;
/* Enable PMD error interrupt */
if (edac_dev->op_state == OP_RUNNING_INTERRUPT) {
if (enable)
xgene_edac_pcp_clrbits(ctx->edac, PCPHPERRINTMSK,
PMD0_MERR_MASK << ctx->pmd);
else
xgene_edac_pcp_setbits(ctx->edac, PCPHPERRINTMSK,
PMD0_MERR_MASK << ctx->pmd);
}
if (enable) {
xgene_edac_pmd_hw_cfg(edac_dev);
/* Two CPUs per a PMD */
for (i = 0; i < MAX_CPU_PER_PMD; i++)
xgene_edac_pmd_cpu_hw_cfg(edac_dev, i);
}
}
static ssize_t xgene_edac_pmd_l1_inject_ctrl_write(struct file *file,
const char __user *data,
size_t count, loff_t *ppos)
{
struct edac_device_ctl_info *edac_dev = file->private_data;
struct xgene_edac_pmd_ctx *ctx = edac_dev->pvt_info;
void __iomem *cpux_pg_f;
int i;
for (i = 0; i < MAX_CPU_PER_PMD; i++) {
cpux_pg_f = ctx->pmd_csr + i * CPU_CSR_STRIDE +
CPU_MEMERR_CPU_PAGE;
writel(MEMERR_CPU_ICFESR_MULTCERR_MASK |
MEMERR_CPU_ICFESR_CERR_MASK,
cpux_pg_f + MEMERR_CPU_ICFESRA_PAGE_OFFSET);
writel(MEMERR_CPU_LSUESR_MULTCERR_MASK |
MEMERR_CPU_LSUESR_CERR_MASK,
cpux_pg_f + MEMERR_CPU_LSUESRA_PAGE_OFFSET);
writel(MEMERR_CPU_MMUESR_MULTCERR_MASK |
MEMERR_CPU_MMUESR_CERR_MASK,
cpux_pg_f + MEMERR_CPU_MMUESRA_PAGE_OFFSET);
}
return count;
}
static ssize_t xgene_edac_pmd_l2_inject_ctrl_write(struct file *file,
const char __user *data,
size_t count, loff_t *ppos)
{
struct edac_device_ctl_info *edac_dev = file->private_data;
struct xgene_edac_pmd_ctx *ctx = edac_dev->pvt_info;
void __iomem *pg_e = ctx->pmd_csr + CPU_MEMERR_L2C_PAGE;
writel(MEMERR_L2C_L2ESR_MULTUCERR_MASK |
MEMERR_L2C_L2ESR_MULTICERR_MASK |
MEMERR_L2C_L2ESR_UCERR_MASK |
MEMERR_L2C_L2ESR_ERR_MASK,
pg_e + MEMERR_L2C_L2ESRA_PAGE_OFFSET);
return count;
}
static const struct file_operations xgene_edac_pmd_debug_inject_fops[] = {
{
.open = simple_open,
.write = xgene_edac_pmd_l1_inject_ctrl_write,
.llseek = generic_file_llseek, },
{
.open = simple_open,
.write = xgene_edac_pmd_l2_inject_ctrl_write,
.llseek = generic_file_llseek, },
{ }
};
static void xgene_edac_pmd_create_debugfs_nodes(
struct edac_device_ctl_info *edac_dev)
{
struct xgene_edac_pmd_ctx *ctx = edac_dev->pvt_info;
struct dentry *edac_debugfs;
char name[30];
if (!IS_ENABLED(CONFIG_EDAC_DEBUG))
return;
/*
* Todo: Switch to common EDAC debug file system for edac device
* when available.
*/
if (!ctx->edac->dfs) {
ctx->edac->dfs = debugfs_create_dir(edac_dev->dev->kobj.name,
NULL);
if (!ctx->edac->dfs)
return;
}
sprintf(name, "PMD%d", ctx->pmd);
edac_debugfs = debugfs_create_dir(name, ctx->edac->dfs);
if (!edac_debugfs)
return;
debugfs_create_file("l1_inject_ctrl", S_IWUSR, edac_debugfs, edac_dev,
&xgene_edac_pmd_debug_inject_fops[0]);
debugfs_create_file("l2_inject_ctrl", S_IWUSR, edac_debugfs, edac_dev,
&xgene_edac_pmd_debug_inject_fops[1]);
}
static int xgene_edac_pmd_available(u32 efuse, int pmd)
{
return (efuse & (1 << pmd)) ? 0 : 1;
}
static int xgene_edac_pmd_add(struct xgene_edac *edac, struct device_node *np,
int version)
{
struct edac_device_ctl_info *edac_dev;
struct xgene_edac_pmd_ctx *ctx;
struct resource res;
char edac_name[10];
u32 pmd;
int rc;
u32 val;
if (!devres_open_group(edac->dev, xgene_edac_pmd_add, GFP_KERNEL))
return -ENOMEM;
/* Determine if this PMD is disabled */
if (of_property_read_u32(np, "pmd-controller", &pmd)) {
dev_err(edac->dev, "no pmd-controller property\n");
rc = -ENODEV;
goto err_group;
}
rc = regmap_read(edac->efuse_map, 0, &val);
if (rc)
goto err_group;
if (!xgene_edac_pmd_available(val, pmd)) {
rc = -ENODEV;
goto err_group;
}
sprintf(edac_name, "l2c%d", pmd);
edac_dev = edac_device_alloc_ctl_info(sizeof(*ctx),
edac_name, 1, "l2c", 1, 2, NULL,
0, edac_device_alloc_index());
if (!edac_dev) {
rc = -ENOMEM;
goto err_group;
}
ctx = edac_dev->pvt_info;
ctx->name = "xgene_pmd_err";
ctx->pmd = pmd;
ctx->edac = edac;
ctx->edac_dev = edac_dev;
ctx->ddev = *edac->dev;
ctx->version = version;
edac_dev->dev = &ctx->ddev;
edac_dev->ctl_name = ctx->name;
edac_dev->dev_name = ctx->name;
edac_dev->mod_name = EDAC_MOD_STR;
rc = of_address_to_resource(np, 0, &res);
if (rc < 0) {
dev_err(edac->dev, "no PMD resource address\n");
goto err_free;
}
ctx->pmd_csr = devm_ioremap_resource(edac->dev, &res);
if (IS_ERR(ctx->pmd_csr)) {
dev_err(edac->dev,
"devm_ioremap_resource failed for PMD resource address\n");
rc = PTR_ERR(ctx->pmd_csr);
goto err_free;
}
if (edac_op_state == EDAC_OPSTATE_POLL)
edac_dev->edac_check = xgene_edac_pmd_check;
xgene_edac_pmd_create_debugfs_nodes(edac_dev);
rc = edac_device_add_device(edac_dev);
if (rc > 0) {
dev_err(edac->dev, "edac_device_add_device failed\n");
rc = -ENOMEM;
goto err_free;
}
if (edac_op_state == EDAC_OPSTATE_INT)
edac_dev->op_state = OP_RUNNING_INTERRUPT;
list_add(&ctx->next, &edac->pmds);
xgene_edac_pmd_hw_ctl(edac_dev, 1);
devres_remove_group(edac->dev, xgene_edac_pmd_add);
dev_info(edac->dev, "X-Gene EDAC PMD%d registered\n", ctx->pmd);
return 0;
err_free:
edac_device_free_ctl_info(edac_dev);
err_group:
devres_release_group(edac->dev, xgene_edac_pmd_add);
return rc;
}
static int xgene_edac_pmd_remove(struct xgene_edac_pmd_ctx *pmd)
{
struct edac_device_ctl_info *edac_dev = pmd->edac_dev;
xgene_edac_pmd_hw_ctl(edac_dev, 0);
edac_device_del_device(edac_dev->dev);
edac_device_free_ctl_info(edac_dev);
return 0;
}
static irqreturn_t xgene_edac_isr(int irq, void *dev_id)
{
struct xgene_edac *ctx = dev_id;
struct xgene_edac_pmd_ctx *pmd;
unsigned int pcp_hp_stat;
unsigned int pcp_lp_stat;
xgene_edac_pcp_rd(ctx, PCPHPERRINTSTS, &pcp_hp_stat);
xgene_edac_pcp_rd(ctx, PCPLPERRINTSTS, &pcp_lp_stat);
if ((MCU_UNCORR_ERR_MASK & pcp_hp_stat) ||
(MCU_CTL_ERR_MASK & pcp_hp_stat) ||
(MCU_CORR_ERR_MASK & pcp_lp_stat)) {
struct xgene_edac_mc_ctx *mcu;
list_for_each_entry(mcu, &ctx->mcus, next) {
xgene_edac_mc_check(mcu->mci);
}
}
list_for_each_entry(pmd, &ctx->pmds, next) {
if ((PMD0_MERR_MASK << pmd->pmd) & pcp_hp_stat)
xgene_edac_pmd_check(pmd->edac_dev);
}
return IRQ_HANDLED;
}
static int xgene_edac_probe(struct platform_device *pdev)
{
struct xgene_edac *edac;
struct device_node *child;
struct resource *res;
int rc;
edac = devm_kzalloc(&pdev->dev, sizeof(*edac), GFP_KERNEL);
if (!edac)
return -ENOMEM;
edac->dev = &pdev->dev;
platform_set_drvdata(pdev, edac);
INIT_LIST_HEAD(&edac->mcus);
INIT_LIST_HEAD(&edac->pmds);
spin_lock_init(&edac->lock);
mutex_init(&edac->mc_lock);
edac->csw_map = syscon_regmap_lookup_by_phandle(pdev->dev.of_node,
"regmap-csw");
if (IS_ERR(edac->csw_map)) {
dev_err(edac->dev, "unable to get syscon regmap csw\n");
rc = PTR_ERR(edac->csw_map);
goto out_err;
}
edac->mcba_map = syscon_regmap_lookup_by_phandle(pdev->dev.of_node,
"regmap-mcba");
if (IS_ERR(edac->mcba_map)) {
dev_err(edac->dev, "unable to get syscon regmap mcba\n");
rc = PTR_ERR(edac->mcba_map);
goto out_err;
}
edac->mcbb_map = syscon_regmap_lookup_by_phandle(pdev->dev.of_node,
"regmap-mcbb");
if (IS_ERR(edac->mcbb_map)) {
dev_err(edac->dev, "unable to get syscon regmap mcbb\n");
rc = PTR_ERR(edac->mcbb_map);
goto out_err;
}
edac->efuse_map = syscon_regmap_lookup_by_phandle(pdev->dev.of_node,
"regmap-efuse");
if (IS_ERR(edac->efuse_map)) {
dev_err(edac->dev, "unable to get syscon regmap efuse\n");
rc = PTR_ERR(edac->efuse_map);
goto out_err;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
edac->pcp_csr = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(edac->pcp_csr)) {
dev_err(&pdev->dev, "no PCP resource address\n");
rc = PTR_ERR(edac->pcp_csr);
goto out_err;
}
if (edac_op_state == EDAC_OPSTATE_INT) {
int irq;
int i;
for (i = 0; i < 3; i++) {
irq = platform_get_irq(pdev, i);
if (irq < 0) {
dev_err(&pdev->dev, "No IRQ resource\n");
rc = -EINVAL;
goto out_err;
}
rc = devm_request_irq(&pdev->dev, irq,
xgene_edac_isr, IRQF_SHARED,
dev_name(&pdev->dev), edac);
if (rc) {
dev_err(&pdev->dev,
"Could not request IRQ %d\n", irq);
goto out_err;
}
}
}
for_each_child_of_node(pdev->dev.of_node, child) {
if (!of_device_is_available(child))
continue;
if (of_device_is_compatible(child, "apm,xgene-edac-mc"))
xgene_edac_mc_add(edac, child);
if (of_device_is_compatible(child, "apm,xgene-edac-pmd"))
xgene_edac_pmd_add(edac, child, 1);
if (of_device_is_compatible(child, "apm,xgene-edac-pmd-v2"))
xgene_edac_pmd_add(edac, child, 2);
}
return 0;
out_err:
return rc;
}
static int xgene_edac_remove(struct platform_device *pdev)
{
struct xgene_edac *edac = dev_get_drvdata(&pdev->dev);
struct xgene_edac_mc_ctx *mcu;
struct xgene_edac_mc_ctx *temp_mcu;
struct xgene_edac_pmd_ctx *pmd;
struct xgene_edac_pmd_ctx *temp_pmd;
list_for_each_entry_safe(mcu, temp_mcu, &edac->mcus, next) {
xgene_edac_mc_remove(mcu);
}
list_for_each_entry_safe(pmd, temp_pmd, &edac->pmds, next) {
xgene_edac_pmd_remove(pmd);
}
return 0;
}
static const struct of_device_id xgene_edac_of_match[] = {
{ .compatible = "apm,xgene-edac" },
{},
};
MODULE_DEVICE_TABLE(of, xgene_edac_of_match);
static struct platform_driver xgene_edac_driver = {
.probe = xgene_edac_probe,
.remove = xgene_edac_remove,
.driver = {
.name = "xgene-edac",
.of_match_table = xgene_edac_of_match,
},
};
static int __init xgene_edac_init(void)
{
int rc;
/* Make sure error reporting method is sane */
switch (edac_op_state) {
case EDAC_OPSTATE_POLL:
case EDAC_OPSTATE_INT:
break;
default:
edac_op_state = EDAC_OPSTATE_INT;
break;
}
rc = platform_driver_register(&xgene_edac_driver);
if (rc) {
edac_printk(KERN_ERR, EDAC_MOD_STR,
"EDAC fails to register\n");
goto reg_failed;
}
return 0;
reg_failed:
return rc;
}
module_init(xgene_edac_init);
static void __exit xgene_edac_exit(void)
{
platform_driver_unregister(&xgene_edac_driver);
}
module_exit(xgene_edac_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Feng Kan <fkan@apm.com>");
MODULE_DESCRIPTION("APM X-Gene EDAC driver");
module_param(edac_op_state, int, 0444);
MODULE_PARM_DESC(edac_op_state,
"EDAC error reporting state: 0=Poll, 2=Interrupt");
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.