repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
CyanogenMod/android_kernel_hardkernel_odroidc1 | drivers/staging/vme/devices/vme_pio2_cntr.c | 4402 | 1706 | /*
* GE PIO2 Counter Driver
*
* Author: Martyn Welch <martyn.welch@ge.com>
* Copyright 2009 GE Intelligent Platforms Embedded Systems, 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.
*
* The PIO-2 has 6 counters, currently this code just disables the interrupts
* and leaves them alone.
*
*/
#include <linux/device.h>
#include <linux/types.h>
#include <linux/gpio.h>
#include <linux/vme.h>
#include "vme_pio2.h"
static int pio2_cntr_irq_set(struct pio2_card *card, int id)
{
int retval;
u8 data;
data = PIO2_CNTR_SC_DEV[id] | PIO2_CNTR_RW_BOTH | card->cntr[id].mode;
retval = vme_master_write(card->window, &data, 1, PIO2_CNTR_CTRL[id]);
if (retval < 0)
return retval;
data = card->cntr[id].count & 0xFF;
retval = vme_master_write(card->window, &data, 1, PIO2_CNTR_DATA[id]);
if (retval < 0)
return retval;
data = (card->cntr[id].count >> 8) & 0xFF;
retval = vme_master_write(card->window, &data, 1, PIO2_CNTR_DATA[id]);
if (retval < 0)
return retval;
return 0;
}
int pio2_cntr_reset(struct pio2_card *card)
{
int i, retval = 0;
u8 reg;
/* Clear down all timers */
for (i = 0; i < 6; i++) {
card->cntr[i].mode = PIO2_CNTR_MODE5;
card->cntr[i].count = 0;
retval = pio2_cntr_irq_set(card, i);
if (retval < 0)
return retval;
}
/* Ensure all counter interrupts are cleared */
do {
retval = vme_master_read(card->window, ®, 1,
PIO2_REGS_INT_STAT_CNTR);
if (retval < 0)
return retval;
} while (reg != 0);
return retval;
}
| gpl-2.0 |
LuckJC/cubie-linux | fs/sysfs/inode.c | 4402 | 8451 | /*
* fs/sysfs/inode.c - basic sysfs inode and dentry operations
*
* Copyright (c) 2001-3 Patrick Mochel
* Copyright (c) 2007 SUSE Linux Products GmbH
* Copyright (c) 2007 Tejun Heo <teheo@suse.de>
*
* This file is released under the GPLv2.
*
* Please see Documentation/filesystems/sysfs.txt for more information.
*/
#undef DEBUG
#include <linux/pagemap.h>
#include <linux/namei.h>
#include <linux/backing-dev.h>
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/sysfs.h>
#include <linux/xattr.h>
#include <linux/security.h>
#include "sysfs.h"
extern struct super_block * sysfs_sb;
static const struct address_space_operations sysfs_aops = {
.readpage = simple_readpage,
.write_begin = simple_write_begin,
.write_end = simple_write_end,
};
static struct backing_dev_info sysfs_backing_dev_info = {
.name = "sysfs",
.ra_pages = 0, /* No readahead */
.capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
};
static const struct inode_operations sysfs_inode_operations ={
.permission = sysfs_permission,
.setattr = sysfs_setattr,
.getattr = sysfs_getattr,
.setxattr = sysfs_setxattr,
};
int __init sysfs_inode_init(void)
{
return bdi_init(&sysfs_backing_dev_info);
}
static struct sysfs_inode_attrs *sysfs_init_inode_attrs(struct sysfs_dirent *sd)
{
struct sysfs_inode_attrs *attrs;
struct iattr *iattrs;
attrs = kzalloc(sizeof(struct sysfs_inode_attrs), GFP_KERNEL);
if (!attrs)
return NULL;
iattrs = &attrs->ia_iattr;
/* assign default attributes */
iattrs->ia_mode = sd->s_mode;
iattrs->ia_uid = 0;
iattrs->ia_gid = 0;
iattrs->ia_atime = iattrs->ia_mtime = iattrs->ia_ctime = CURRENT_TIME;
return attrs;
}
int sysfs_sd_setattr(struct sysfs_dirent *sd, struct iattr * iattr)
{
struct sysfs_inode_attrs *sd_attrs;
struct iattr *iattrs;
unsigned int ia_valid = iattr->ia_valid;
sd_attrs = sd->s_iattr;
if (!sd_attrs) {
/* setting attributes for the first time, allocate now */
sd_attrs = sysfs_init_inode_attrs(sd);
if (!sd_attrs)
return -ENOMEM;
sd->s_iattr = sd_attrs;
}
/* attributes were changed at least once in past */
iattrs = &sd_attrs->ia_iattr;
if (ia_valid & ATTR_UID)
iattrs->ia_uid = iattr->ia_uid;
if (ia_valid & ATTR_GID)
iattrs->ia_gid = iattr->ia_gid;
if (ia_valid & ATTR_ATIME)
iattrs->ia_atime = iattr->ia_atime;
if (ia_valid & ATTR_MTIME)
iattrs->ia_mtime = iattr->ia_mtime;
if (ia_valid & ATTR_CTIME)
iattrs->ia_ctime = iattr->ia_ctime;
if (ia_valid & ATTR_MODE) {
umode_t mode = iattr->ia_mode;
iattrs->ia_mode = sd->s_mode = mode;
}
return 0;
}
int sysfs_setattr(struct dentry *dentry, struct iattr *iattr)
{
struct inode *inode = dentry->d_inode;
struct sysfs_dirent *sd = dentry->d_fsdata;
int error;
if (!sd)
return -EINVAL;
mutex_lock(&sysfs_mutex);
error = inode_change_ok(inode, iattr);
if (error)
goto out;
error = sysfs_sd_setattr(sd, iattr);
if (error)
goto out;
/* this ignores size changes */
setattr_copy(inode, iattr);
out:
mutex_unlock(&sysfs_mutex);
return error;
}
static int sysfs_sd_setsecdata(struct sysfs_dirent *sd, void **secdata, u32 *secdata_len)
{
struct sysfs_inode_attrs *iattrs;
void *old_secdata;
size_t old_secdata_len;
if (!sd->s_iattr) {
sd->s_iattr = sysfs_init_inode_attrs(sd);
if (!sd->s_iattr)
return -ENOMEM;
}
iattrs = sd->s_iattr;
old_secdata = iattrs->ia_secdata;
old_secdata_len = iattrs->ia_secdata_len;
iattrs->ia_secdata = *secdata;
iattrs->ia_secdata_len = *secdata_len;
*secdata = old_secdata;
*secdata_len = old_secdata_len;
return 0;
}
int sysfs_setxattr(struct dentry *dentry, const char *name, const void *value,
size_t size, int flags)
{
struct sysfs_dirent *sd = dentry->d_fsdata;
void *secdata;
int error;
u32 secdata_len = 0;
if (!sd)
return -EINVAL;
if (!strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN)) {
const char *suffix = name + XATTR_SECURITY_PREFIX_LEN;
error = security_inode_setsecurity(dentry->d_inode, suffix,
value, size, flags);
if (error)
goto out;
error = security_inode_getsecctx(dentry->d_inode,
&secdata, &secdata_len);
if (error)
goto out;
mutex_lock(&sysfs_mutex);
error = sysfs_sd_setsecdata(sd, &secdata, &secdata_len);
mutex_unlock(&sysfs_mutex);
if (secdata)
security_release_secctx(secdata, secdata_len);
} else
return -EINVAL;
out:
return error;
}
static inline void set_default_inode_attr(struct inode * inode, umode_t mode)
{
inode->i_mode = mode;
inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
}
static inline void set_inode_attr(struct inode * inode, struct iattr * iattr)
{
inode->i_uid = iattr->ia_uid;
inode->i_gid = iattr->ia_gid;
inode->i_atime = iattr->ia_atime;
inode->i_mtime = iattr->ia_mtime;
inode->i_ctime = iattr->ia_ctime;
}
static void sysfs_refresh_inode(struct sysfs_dirent *sd, struct inode *inode)
{
struct sysfs_inode_attrs *iattrs = sd->s_iattr;
inode->i_mode = sd->s_mode;
if (iattrs) {
/* sysfs_dirent has non-default attributes
* get them from persistent copy in sysfs_dirent
*/
set_inode_attr(inode, &iattrs->ia_iattr);
security_inode_notifysecctx(inode,
iattrs->ia_secdata,
iattrs->ia_secdata_len);
}
if (sysfs_type(sd) == SYSFS_DIR)
set_nlink(inode, sd->s_dir.subdirs + 2);
}
int sysfs_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat)
{
struct sysfs_dirent *sd = dentry->d_fsdata;
struct inode *inode = dentry->d_inode;
mutex_lock(&sysfs_mutex);
sysfs_refresh_inode(sd, inode);
mutex_unlock(&sysfs_mutex);
generic_fillattr(inode, stat);
return 0;
}
static void sysfs_init_inode(struct sysfs_dirent *sd, struct inode *inode)
{
struct bin_attribute *bin_attr;
inode->i_private = sysfs_get(sd);
inode->i_mapping->a_ops = &sysfs_aops;
inode->i_mapping->backing_dev_info = &sysfs_backing_dev_info;
inode->i_op = &sysfs_inode_operations;
set_default_inode_attr(inode, sd->s_mode);
sysfs_refresh_inode(sd, inode);
/* initialize inode according to type */
switch (sysfs_type(sd)) {
case SYSFS_DIR:
inode->i_op = &sysfs_dir_inode_operations;
inode->i_fop = &sysfs_dir_operations;
break;
case SYSFS_KOBJ_ATTR:
inode->i_size = PAGE_SIZE;
inode->i_fop = &sysfs_file_operations;
break;
case SYSFS_KOBJ_BIN_ATTR:
bin_attr = sd->s_bin_attr.bin_attr;
inode->i_size = bin_attr->size;
inode->i_fop = &bin_fops;
break;
case SYSFS_KOBJ_LINK:
inode->i_op = &sysfs_symlink_inode_operations;
break;
default:
BUG();
}
unlock_new_inode(inode);
}
/**
* sysfs_get_inode - get inode for sysfs_dirent
* @sb: super block
* @sd: sysfs_dirent to allocate inode for
*
* Get inode for @sd. If such inode doesn't exist, a new inode
* is allocated and basics are initialized. New inode is
* returned locked.
*
* LOCKING:
* Kernel thread context (may sleep).
*
* RETURNS:
* Pointer to allocated inode on success, NULL on failure.
*/
struct inode * sysfs_get_inode(struct super_block *sb, struct sysfs_dirent *sd)
{
struct inode *inode;
inode = iget_locked(sb, sd->s_ino);
if (inode && (inode->i_state & I_NEW))
sysfs_init_inode(sd, inode);
return inode;
}
/*
* The sysfs_dirent serves as both an inode and a directory entry for sysfs.
* To prevent the sysfs inode numbers from being freed prematurely we take a
* reference to sysfs_dirent from the sysfs inode. A
* super_operations.evict_inode() implementation is needed to drop that
* reference upon inode destruction.
*/
void sysfs_evict_inode(struct inode *inode)
{
struct sysfs_dirent *sd = inode->i_private;
truncate_inode_pages(&inode->i_data, 0);
end_writeback(inode);
sysfs_put(sd);
}
int sysfs_hash_and_remove(struct sysfs_dirent *dir_sd, const void *ns, const char *name)
{
struct sysfs_addrm_cxt acxt;
struct sysfs_dirent *sd;
if (!dir_sd) {
WARN(1, KERN_WARNING "sysfs: can not remove '%s', no directory\n",
name);
return -ENOENT;
}
sysfs_addrm_start(&acxt, dir_sd);
sd = sysfs_find_dirent(dir_sd, ns, name);
if (sd)
sysfs_remove_one(&acxt, sd);
sysfs_addrm_finish(&acxt);
if (sd)
return 0;
else
return -ENOENT;
}
int sysfs_permission(struct inode *inode, int mask)
{
struct sysfs_dirent *sd;
if (mask & MAY_NOT_BLOCK)
return -ECHILD;
sd = inode->i_private;
mutex_lock(&sysfs_mutex);
sysfs_refresh_inode(sd, inode);
mutex_unlock(&sysfs_mutex);
return generic_permission(inode, mask);
}
| gpl-2.0 |
showliu/android_kernel_xiaomi_aries-1 | arch/sparc/kernel/traps_32.c | 4402 | 12549 | /*
* arch/sparc/kernel/traps.c
*
* Copyright 1995, 2008 David S. Miller (davem@davemloft.net)
* Copyright 2000 Jakub Jelinek (jakub@redhat.com)
*/
/*
* I hate traps on the sparc, grrr...
*/
#include <linux/sched.h> /* for jiffies */
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/smp.h>
#include <linux/kdebug.h>
#include <linux/export.h>
#include <asm/delay.h>
#include <asm/ptrace.h>
#include <asm/oplib.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/unistd.h>
#include <asm/traps.h>
#include "entry.h"
#include "kernel.h"
/* #define TRAP_DEBUG */
static void instruction_dump(unsigned long *pc)
{
int i;
if((((unsigned long) pc) & 3))
return;
for(i = -3; i < 6; i++)
printk("%c%08lx%c",i?' ':'<',pc[i],i?' ':'>');
printk("\n");
}
#define __SAVE __asm__ __volatile__("save %sp, -0x40, %sp\n\t")
#define __RESTORE __asm__ __volatile__("restore %g0, %g0, %g0\n\t")
void die_if_kernel(char *str, struct pt_regs *regs)
{
static int die_counter;
int count = 0;
/* Amuse the user. */
printk(
" \\|/ ____ \\|/\n"
" \"@'/ ,. \\`@\"\n"
" /_| \\__/ |_\\\n"
" \\__U_/\n");
printk("%s(%d): %s [#%d]\n", current->comm, task_pid_nr(current), str, ++die_counter);
show_regs(regs);
add_taint(TAINT_DIE);
__SAVE; __SAVE; __SAVE; __SAVE;
__SAVE; __SAVE; __SAVE; __SAVE;
__RESTORE; __RESTORE; __RESTORE; __RESTORE;
__RESTORE; __RESTORE; __RESTORE; __RESTORE;
{
struct reg_window32 *rw = (struct reg_window32 *)regs->u_regs[UREG_FP];
/* Stop the back trace when we hit userland or we
* find some badly aligned kernel stack. Set an upper
* bound in case our stack is trashed and we loop.
*/
while(rw &&
count++ < 30 &&
(((unsigned long) rw) >= PAGE_OFFSET) &&
!(((unsigned long) rw) & 0x7)) {
printk("Caller[%08lx]: %pS\n", rw->ins[7],
(void *) rw->ins[7]);
rw = (struct reg_window32 *)rw->ins[6];
}
}
printk("Instruction DUMP:");
instruction_dump ((unsigned long *) regs->pc);
if(regs->psr & PSR_PS)
do_exit(SIGKILL);
do_exit(SIGSEGV);
}
void do_hw_interrupt(struct pt_regs *regs, unsigned long type)
{
siginfo_t info;
if(type < 0x80) {
/* Sun OS's puke from bad traps, Linux survives! */
printk("Unimplemented Sparc TRAP, type = %02lx\n", type);
die_if_kernel("Whee... Hello Mr. Penguin", regs);
}
if(regs->psr & PSR_PS)
die_if_kernel("Kernel bad trap", regs);
info.si_signo = SIGILL;
info.si_errno = 0;
info.si_code = ILL_ILLTRP;
info.si_addr = (void __user *)regs->pc;
info.si_trapno = type - 0x80;
force_sig_info(SIGILL, &info, current);
}
void do_illegal_instruction(struct pt_regs *regs, unsigned long pc, unsigned long npc,
unsigned long psr)
{
siginfo_t info;
if(psr & PSR_PS)
die_if_kernel("Kernel illegal instruction", regs);
#ifdef TRAP_DEBUG
printk("Ill instr. at pc=%08lx instruction is %08lx\n",
regs->pc, *(unsigned long *)regs->pc);
#endif
if (!do_user_muldiv (regs, pc))
return;
info.si_signo = SIGILL;
info.si_errno = 0;
info.si_code = ILL_ILLOPC;
info.si_addr = (void __user *)pc;
info.si_trapno = 0;
send_sig_info(SIGILL, &info, current);
}
void do_priv_instruction(struct pt_regs *regs, unsigned long pc, unsigned long npc,
unsigned long psr)
{
siginfo_t info;
if(psr & PSR_PS)
die_if_kernel("Penguin instruction from Penguin mode??!?!", regs);
info.si_signo = SIGILL;
info.si_errno = 0;
info.si_code = ILL_PRVOPC;
info.si_addr = (void __user *)pc;
info.si_trapno = 0;
send_sig_info(SIGILL, &info, current);
}
/* XXX User may want to be allowed to do this. XXX */
void do_memaccess_unaligned(struct pt_regs *regs, unsigned long pc, unsigned long npc,
unsigned long psr)
{
siginfo_t info;
if(regs->psr & PSR_PS) {
printk("KERNEL MNA at pc %08lx npc %08lx called by %08lx\n", pc, npc,
regs->u_regs[UREG_RETPC]);
die_if_kernel("BOGUS", regs);
/* die_if_kernel("Kernel MNA access", regs); */
}
#if 0
show_regs (regs);
instruction_dump ((unsigned long *) regs->pc);
printk ("do_MNA!\n");
#endif
info.si_signo = SIGBUS;
info.si_errno = 0;
info.si_code = BUS_ADRALN;
info.si_addr = /* FIXME: Should dig out mna address */ (void *)0;
info.si_trapno = 0;
send_sig_info(SIGBUS, &info, current);
}
static unsigned long init_fsr = 0x0UL;
static unsigned long init_fregs[32] __attribute__ ((aligned (8))) =
{ ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL,
~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL,
~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL,
~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL, ~0UL };
void do_fpd_trap(struct pt_regs *regs, unsigned long pc, unsigned long npc,
unsigned long psr)
{
/* Sanity check... */
if(psr & PSR_PS)
die_if_kernel("Kernel gets FloatingPenguinUnit disabled trap", regs);
put_psr(get_psr() | PSR_EF); /* Allow FPU ops. */
regs->psr |= PSR_EF;
#ifndef CONFIG_SMP
if(last_task_used_math == current)
return;
if(last_task_used_math) {
/* Other processes fpu state, save away */
struct task_struct *fptask = last_task_used_math;
fpsave(&fptask->thread.float_regs[0], &fptask->thread.fsr,
&fptask->thread.fpqueue[0], &fptask->thread.fpqdepth);
}
last_task_used_math = current;
if(used_math()) {
fpload(¤t->thread.float_regs[0], ¤t->thread.fsr);
} else {
/* Set initial sane state. */
fpload(&init_fregs[0], &init_fsr);
set_used_math();
}
#else
if(!used_math()) {
fpload(&init_fregs[0], &init_fsr);
set_used_math();
} else {
fpload(¤t->thread.float_regs[0], ¤t->thread.fsr);
}
set_thread_flag(TIF_USEDFPU);
#endif
}
static unsigned long fake_regs[32] __attribute__ ((aligned (8)));
static unsigned long fake_fsr;
static unsigned long fake_queue[32] __attribute__ ((aligned (8)));
static unsigned long fake_depth;
extern int do_mathemu(struct pt_regs *, struct task_struct *);
void do_fpe_trap(struct pt_regs *regs, unsigned long pc, unsigned long npc,
unsigned long psr)
{
static int calls;
siginfo_t info;
unsigned long fsr;
int ret = 0;
#ifndef CONFIG_SMP
struct task_struct *fpt = last_task_used_math;
#else
struct task_struct *fpt = current;
#endif
put_psr(get_psr() | PSR_EF);
/* If nobody owns the fpu right now, just clear the
* error into our fake static buffer and hope it don't
* happen again. Thank you crashme...
*/
#ifndef CONFIG_SMP
if(!fpt) {
#else
if (!test_tsk_thread_flag(fpt, TIF_USEDFPU)) {
#endif
fpsave(&fake_regs[0], &fake_fsr, &fake_queue[0], &fake_depth);
regs->psr &= ~PSR_EF;
return;
}
fpsave(&fpt->thread.float_regs[0], &fpt->thread.fsr,
&fpt->thread.fpqueue[0], &fpt->thread.fpqdepth);
#ifdef DEBUG_FPU
printk("Hmm, FP exception, fsr was %016lx\n", fpt->thread.fsr);
#endif
switch ((fpt->thread.fsr & 0x1c000)) {
/* switch on the contents of the ftt [floating point trap type] field */
#ifdef DEBUG_FPU
case (1 << 14):
printk("IEEE_754_exception\n");
break;
#endif
case (2 << 14): /* unfinished_FPop (underflow & co) */
case (3 << 14): /* unimplemented_FPop (quad stuff, maybe sqrt) */
ret = do_mathemu(regs, fpt);
break;
#ifdef DEBUG_FPU
case (4 << 14):
printk("sequence_error (OS bug...)\n");
break;
case (5 << 14):
printk("hardware_error (uhoh!)\n");
break;
case (6 << 14):
printk("invalid_fp_register (user error)\n");
break;
#endif /* DEBUG_FPU */
}
/* If we successfully emulated the FPop, we pretend the trap never happened :-> */
if (ret) {
fpload(¤t->thread.float_regs[0], ¤t->thread.fsr);
return;
}
/* nope, better SIGFPE the offending process... */
#ifdef CONFIG_SMP
clear_tsk_thread_flag(fpt, TIF_USEDFPU);
#endif
if(psr & PSR_PS) {
/* The first fsr store/load we tried trapped,
* the second one will not (we hope).
*/
printk("WARNING: FPU exception from kernel mode. at pc=%08lx\n",
regs->pc);
regs->pc = regs->npc;
regs->npc += 4;
calls++;
if(calls > 2)
die_if_kernel("Too many Penguin-FPU traps from kernel mode",
regs);
return;
}
fsr = fpt->thread.fsr;
info.si_signo = SIGFPE;
info.si_errno = 0;
info.si_addr = (void __user *)pc;
info.si_trapno = 0;
info.si_code = __SI_FAULT;
if ((fsr & 0x1c000) == (1 << 14)) {
if (fsr & 0x10)
info.si_code = FPE_FLTINV;
else if (fsr & 0x08)
info.si_code = FPE_FLTOVF;
else if (fsr & 0x04)
info.si_code = FPE_FLTUND;
else if (fsr & 0x02)
info.si_code = FPE_FLTDIV;
else if (fsr & 0x01)
info.si_code = FPE_FLTRES;
}
send_sig_info(SIGFPE, &info, fpt);
#ifndef CONFIG_SMP
last_task_used_math = NULL;
#endif
regs->psr &= ~PSR_EF;
if(calls > 0)
calls=0;
}
void handle_tag_overflow(struct pt_regs *regs, unsigned long pc, unsigned long npc,
unsigned long psr)
{
siginfo_t info;
if(psr & PSR_PS)
die_if_kernel("Penguin overflow trap from kernel mode", regs);
info.si_signo = SIGEMT;
info.si_errno = 0;
info.si_code = EMT_TAGOVF;
info.si_addr = (void __user *)pc;
info.si_trapno = 0;
send_sig_info(SIGEMT, &info, current);
}
void handle_watchpoint(struct pt_regs *regs, unsigned long pc, unsigned long npc,
unsigned long psr)
{
#ifdef TRAP_DEBUG
printk("Watchpoint detected at PC %08lx NPC %08lx PSR %08lx\n",
pc, npc, psr);
#endif
if(psr & PSR_PS)
panic("Tell me what a watchpoint trap is, and I'll then deal "
"with such a beast...");
}
void handle_reg_access(struct pt_regs *regs, unsigned long pc, unsigned long npc,
unsigned long psr)
{
siginfo_t info;
#ifdef TRAP_DEBUG
printk("Register Access Exception at PC %08lx NPC %08lx PSR %08lx\n",
pc, npc, psr);
#endif
info.si_signo = SIGBUS;
info.si_errno = 0;
info.si_code = BUS_OBJERR;
info.si_addr = (void __user *)pc;
info.si_trapno = 0;
force_sig_info(SIGBUS, &info, current);
}
void handle_cp_disabled(struct pt_regs *regs, unsigned long pc, unsigned long npc,
unsigned long psr)
{
siginfo_t info;
info.si_signo = SIGILL;
info.si_errno = 0;
info.si_code = ILL_COPROC;
info.si_addr = (void __user *)pc;
info.si_trapno = 0;
send_sig_info(SIGILL, &info, current);
}
void handle_cp_exception(struct pt_regs *regs, unsigned long pc, unsigned long npc,
unsigned long psr)
{
siginfo_t info;
#ifdef TRAP_DEBUG
printk("Co-Processor Exception at PC %08lx NPC %08lx PSR %08lx\n",
pc, npc, psr);
#endif
info.si_signo = SIGILL;
info.si_errno = 0;
info.si_code = ILL_COPROC;
info.si_addr = (void __user *)pc;
info.si_trapno = 0;
send_sig_info(SIGILL, &info, current);
}
void handle_hw_divzero(struct pt_regs *regs, unsigned long pc, unsigned long npc,
unsigned long psr)
{
siginfo_t info;
info.si_signo = SIGFPE;
info.si_errno = 0;
info.si_code = FPE_INTDIV;
info.si_addr = (void __user *)pc;
info.si_trapno = 0;
send_sig_info(SIGFPE, &info, current);
}
#ifdef CONFIG_DEBUG_BUGVERBOSE
void do_BUG(const char *file, int line)
{
// bust_spinlocks(1); XXX Not in our original BUG()
printk("kernel BUG at %s:%d!\n", file, line);
}
EXPORT_SYMBOL(do_BUG);
#endif
/* Since we have our mappings set up, on multiprocessors we can spin them
* up here so that timer interrupts work during initialization.
*/
void trap_init(void)
{
extern void thread_info_offsets_are_bolixed_pete(void);
/* Force linker to barf if mismatched */
if (TI_UWINMASK != offsetof(struct thread_info, uwinmask) ||
TI_TASK != offsetof(struct thread_info, task) ||
TI_EXECDOMAIN != offsetof(struct thread_info, exec_domain) ||
TI_FLAGS != offsetof(struct thread_info, flags) ||
TI_CPU != offsetof(struct thread_info, cpu) ||
TI_PREEMPT != offsetof(struct thread_info, preempt_count) ||
TI_SOFTIRQ != offsetof(struct thread_info, softirq_count) ||
TI_HARDIRQ != offsetof(struct thread_info, hardirq_count) ||
TI_KSP != offsetof(struct thread_info, ksp) ||
TI_KPC != offsetof(struct thread_info, kpc) ||
TI_KPSR != offsetof(struct thread_info, kpsr) ||
TI_KWIM != offsetof(struct thread_info, kwim) ||
TI_REG_WINDOW != offsetof(struct thread_info, reg_window) ||
TI_RWIN_SPTRS != offsetof(struct thread_info, rwbuf_stkptrs) ||
TI_W_SAVED != offsetof(struct thread_info, w_saved))
thread_info_offsets_are_bolixed_pete();
/* Attach to the address space of init_task. */
atomic_inc(&init_mm.mm_count);
current->active_mm = &init_mm;
/* NOTE: Other cpus have this done as they are started
* up on SMP.
*/
}
| gpl-2.0 |
vl197602/htc_msm8960 | fs/jffs2/nodelist.c | 7474 | 22184 | /*
* 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.
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/fs.h>
#include <linux/mtd/mtd.h>
#include <linux/rbtree.h>
#include <linux/crc32.h>
#include <linux/pagemap.h>
#include "nodelist.h"
static void jffs2_obsolete_node_frag(struct jffs2_sb_info *c,
struct jffs2_node_frag *this);
void jffs2_add_fd_to_list(struct jffs2_sb_info *c, struct jffs2_full_dirent *new, struct jffs2_full_dirent **list)
{
struct jffs2_full_dirent **prev = list;
dbg_dentlist("add dirent \"%s\", ino #%u\n", new->name, new->ino);
while ((*prev) && (*prev)->nhash <= new->nhash) {
if ((*prev)->nhash == new->nhash && !strcmp((*prev)->name, new->name)) {
/* Duplicate. Free one */
if (new->version < (*prev)->version) {
dbg_dentlist("Eep! Marking new dirent node obsolete, old is \"%s\", ino #%u\n",
(*prev)->name, (*prev)->ino);
jffs2_mark_node_obsolete(c, new->raw);
jffs2_free_full_dirent(new);
} else {
dbg_dentlist("marking old dirent \"%s\", ino #%u obsolete\n",
(*prev)->name, (*prev)->ino);
new->next = (*prev)->next;
/* It may have been a 'placeholder' deletion dirent,
if jffs2_can_mark_obsolete() (see jffs2_do_unlink()) */
if ((*prev)->raw)
jffs2_mark_node_obsolete(c, ((*prev)->raw));
jffs2_free_full_dirent(*prev);
*prev = new;
}
return;
}
prev = &((*prev)->next);
}
new->next = *prev;
*prev = new;
}
uint32_t jffs2_truncate_fragtree(struct jffs2_sb_info *c, struct rb_root *list, uint32_t size)
{
struct jffs2_node_frag *frag = jffs2_lookup_node_frag(list, size);
dbg_fragtree("truncating fragtree to 0x%08x bytes\n", size);
/* We know frag->ofs <= size. That's what lookup does for us */
if (frag && frag->ofs != size) {
if (frag->ofs+frag->size > size) {
frag->size = size - frag->ofs;
}
frag = frag_next(frag);
}
while (frag && frag->ofs >= size) {
struct jffs2_node_frag *next = frag_next(frag);
frag_erase(frag, list);
jffs2_obsolete_node_frag(c, frag);
frag = next;
}
if (size == 0)
return 0;
frag = frag_last(list);
/* Sanity check for truncation to longer than we started with... */
if (!frag)
return 0;
if (frag->ofs + frag->size < size)
return frag->ofs + frag->size;
/* If the last fragment starts at the RAM page boundary, it is
* REF_PRISTINE irrespective of its size. */
if (frag->node && (frag->ofs & (PAGE_CACHE_SIZE - 1)) == 0) {
dbg_fragtree2("marking the last fragment 0x%08x-0x%08x REF_PRISTINE.\n",
frag->ofs, frag->ofs + frag->size);
frag->node->raw->flash_offset = ref_offset(frag->node->raw) | REF_PRISTINE;
}
return size;
}
static void jffs2_obsolete_node_frag(struct jffs2_sb_info *c,
struct jffs2_node_frag *this)
{
if (this->node) {
this->node->frags--;
if (!this->node->frags) {
/* The node has no valid frags left. It's totally obsoleted */
dbg_fragtree2("marking old node @0x%08x (0x%04x-0x%04x) obsolete\n",
ref_offset(this->node->raw), this->node->ofs, this->node->ofs+this->node->size);
jffs2_mark_node_obsolete(c, this->node->raw);
jffs2_free_full_dnode(this->node);
} else {
dbg_fragtree2("marking old node @0x%08x (0x%04x-0x%04x) REF_NORMAL. frags is %d\n",
ref_offset(this->node->raw), this->node->ofs, this->node->ofs+this->node->size, this->node->frags);
mark_ref_normal(this->node->raw);
}
}
jffs2_free_node_frag(this);
}
static void jffs2_fragtree_insert(struct jffs2_node_frag *newfrag, struct jffs2_node_frag *base)
{
struct rb_node *parent = &base->rb;
struct rb_node **link = &parent;
dbg_fragtree2("insert frag (0x%04x-0x%04x)\n", newfrag->ofs, newfrag->ofs + newfrag->size);
while (*link) {
parent = *link;
base = rb_entry(parent, struct jffs2_node_frag, rb);
if (newfrag->ofs > base->ofs)
link = &base->rb.rb_right;
else if (newfrag->ofs < base->ofs)
link = &base->rb.rb_left;
else {
JFFS2_ERROR("duplicate frag at %08x (%p,%p)\n", newfrag->ofs, newfrag, base);
BUG();
}
}
rb_link_node(&newfrag->rb, &base->rb, link);
}
/*
* Allocate and initializes a new fragment.
*/
static struct jffs2_node_frag * new_fragment(struct jffs2_full_dnode *fn, uint32_t ofs, uint32_t size)
{
struct jffs2_node_frag *newfrag;
newfrag = jffs2_alloc_node_frag();
if (likely(newfrag)) {
newfrag->ofs = ofs;
newfrag->size = size;
newfrag->node = fn;
} else {
JFFS2_ERROR("cannot allocate a jffs2_node_frag object\n");
}
return newfrag;
}
/*
* Called when there is no overlapping fragment exist. Inserts a hole before the new
* fragment and inserts the new fragment to the fragtree.
*/
static int no_overlapping_node(struct jffs2_sb_info *c, struct rb_root *root,
struct jffs2_node_frag *newfrag,
struct jffs2_node_frag *this, uint32_t lastend)
{
if (lastend < newfrag->node->ofs) {
/* put a hole in before the new fragment */
struct jffs2_node_frag *holefrag;
holefrag= new_fragment(NULL, lastend, newfrag->node->ofs - lastend);
if (unlikely(!holefrag)) {
jffs2_free_node_frag(newfrag);
return -ENOMEM;
}
if (this) {
/* By definition, the 'this' node has no right-hand child,
because there are no frags with offset greater than it.
So that's where we want to put the hole */
dbg_fragtree2("add hole frag %#04x-%#04x on the right of the new frag.\n",
holefrag->ofs, holefrag->ofs + holefrag->size);
rb_link_node(&holefrag->rb, &this->rb, &this->rb.rb_right);
} else {
dbg_fragtree2("Add hole frag %#04x-%#04x to the root of the tree.\n",
holefrag->ofs, holefrag->ofs + holefrag->size);
rb_link_node(&holefrag->rb, NULL, &root->rb_node);
}
rb_insert_color(&holefrag->rb, root);
this = holefrag;
}
if (this) {
/* By definition, the 'this' node has no right-hand child,
because there are no frags with offset greater than it.
So that's where we want to put new fragment */
dbg_fragtree2("add the new node at the right\n");
rb_link_node(&newfrag->rb, &this->rb, &this->rb.rb_right);
} else {
dbg_fragtree2("insert the new node at the root of the tree\n");
rb_link_node(&newfrag->rb, NULL, &root->rb_node);
}
rb_insert_color(&newfrag->rb, root);
return 0;
}
/* Doesn't set inode->i_size */
static int jffs2_add_frag_to_fragtree(struct jffs2_sb_info *c, struct rb_root *root, struct jffs2_node_frag *newfrag)
{
struct jffs2_node_frag *this;
uint32_t lastend;
/* Skip all the nodes which are completed before this one starts */
this = jffs2_lookup_node_frag(root, newfrag->node->ofs);
if (this) {
dbg_fragtree2("lookup gave frag 0x%04x-0x%04x; phys 0x%08x (*%p)\n",
this->ofs, this->ofs+this->size, this->node?(ref_offset(this->node->raw)):0xffffffff, this);
lastend = this->ofs + this->size;
} else {
dbg_fragtree2("lookup gave no frag\n");
lastend = 0;
}
/* See if we ran off the end of the fragtree */
if (lastend <= newfrag->ofs) {
/* We did */
/* Check if 'this' node was on the same page as the new node.
If so, both 'this' and the new node get marked REF_NORMAL so
the GC can take a look.
*/
if (lastend && (lastend-1) >> PAGE_CACHE_SHIFT == newfrag->ofs >> PAGE_CACHE_SHIFT) {
if (this->node)
mark_ref_normal(this->node->raw);
mark_ref_normal(newfrag->node->raw);
}
return no_overlapping_node(c, root, newfrag, this, lastend);
}
if (this->node)
dbg_fragtree2("dealing with frag %u-%u, phys %#08x(%d).\n",
this->ofs, this->ofs + this->size,
ref_offset(this->node->raw), ref_flags(this->node->raw));
else
dbg_fragtree2("dealing with hole frag %u-%u.\n",
this->ofs, this->ofs + this->size);
/* OK. 'this' is pointing at the first frag that newfrag->ofs at least partially obsoletes,
* - i.e. newfrag->ofs < this->ofs+this->size && newfrag->ofs >= this->ofs
*/
if (newfrag->ofs > this->ofs) {
/* This node isn't completely obsoleted. The start of it remains valid */
/* Mark the new node and the partially covered node REF_NORMAL -- let
the GC take a look at them */
mark_ref_normal(newfrag->node->raw);
if (this->node)
mark_ref_normal(this->node->raw);
if (this->ofs + this->size > newfrag->ofs + newfrag->size) {
/* The new node splits 'this' frag into two */
struct jffs2_node_frag *newfrag2;
if (this->node)
dbg_fragtree2("split old frag 0x%04x-0x%04x, phys 0x%08x\n",
this->ofs, this->ofs+this->size, ref_offset(this->node->raw));
else
dbg_fragtree2("split old hole frag 0x%04x-0x%04x\n",
this->ofs, this->ofs+this->size);
/* New second frag pointing to this's node */
newfrag2 = new_fragment(this->node, newfrag->ofs + newfrag->size,
this->ofs + this->size - newfrag->ofs - newfrag->size);
if (unlikely(!newfrag2))
return -ENOMEM;
if (this->node)
this->node->frags++;
/* Adjust size of original 'this' */
this->size = newfrag->ofs - this->ofs;
/* Now, we know there's no node with offset
greater than this->ofs but smaller than
newfrag2->ofs or newfrag->ofs, for obvious
reasons. So we can do a tree insert from
'this' to insert newfrag, and a tree insert
from newfrag to insert newfrag2. */
jffs2_fragtree_insert(newfrag, this);
rb_insert_color(&newfrag->rb, root);
jffs2_fragtree_insert(newfrag2, newfrag);
rb_insert_color(&newfrag2->rb, root);
return 0;
}
/* New node just reduces 'this' frag in size, doesn't split it */
this->size = newfrag->ofs - this->ofs;
/* Again, we know it lives down here in the tree */
jffs2_fragtree_insert(newfrag, this);
rb_insert_color(&newfrag->rb, root);
} else {
/* New frag starts at the same point as 'this' used to. Replace
it in the tree without doing a delete and insertion */
dbg_fragtree2("inserting newfrag (*%p),%d-%d in before 'this' (*%p),%d-%d\n",
newfrag, newfrag->ofs, newfrag->ofs+newfrag->size, this, this->ofs, this->ofs+this->size);
rb_replace_node(&this->rb, &newfrag->rb, root);
if (newfrag->ofs + newfrag->size >= this->ofs+this->size) {
dbg_fragtree2("obsoleting node frag %p (%x-%x)\n", this, this->ofs, this->ofs+this->size);
jffs2_obsolete_node_frag(c, this);
} else {
this->ofs += newfrag->size;
this->size -= newfrag->size;
jffs2_fragtree_insert(this, newfrag);
rb_insert_color(&this->rb, root);
return 0;
}
}
/* OK, now we have newfrag added in the correct place in the tree, but
frag_next(newfrag) may be a fragment which is overlapped by it
*/
while ((this = frag_next(newfrag)) && newfrag->ofs + newfrag->size >= this->ofs + this->size) {
/* 'this' frag is obsoleted completely. */
dbg_fragtree2("obsoleting node frag %p (%x-%x) and removing from tree\n",
this, this->ofs, this->ofs+this->size);
rb_erase(&this->rb, root);
jffs2_obsolete_node_frag(c, this);
}
/* Now we're pointing at the first frag which isn't totally obsoleted by
the new frag */
if (!this || newfrag->ofs + newfrag->size == this->ofs)
return 0;
/* Still some overlap but we don't need to move it in the tree */
this->size = (this->ofs + this->size) - (newfrag->ofs + newfrag->size);
this->ofs = newfrag->ofs + newfrag->size;
/* And mark them REF_NORMAL so the GC takes a look at them */
if (this->node)
mark_ref_normal(this->node->raw);
mark_ref_normal(newfrag->node->raw);
return 0;
}
/*
* Given an inode, probably with existing tree of fragments, add the new node
* to the fragment tree.
*/
int jffs2_add_full_dnode_to_inode(struct jffs2_sb_info *c, struct jffs2_inode_info *f, struct jffs2_full_dnode *fn)
{
int ret;
struct jffs2_node_frag *newfrag;
if (unlikely(!fn->size))
return 0;
newfrag = new_fragment(fn, fn->ofs, fn->size);
if (unlikely(!newfrag))
return -ENOMEM;
newfrag->node->frags = 1;
dbg_fragtree("adding node %#04x-%#04x @0x%08x on flash, newfrag *%p\n",
fn->ofs, fn->ofs+fn->size, ref_offset(fn->raw), newfrag);
ret = jffs2_add_frag_to_fragtree(c, &f->fragtree, newfrag);
if (unlikely(ret))
return ret;
/* If we now share a page with other nodes, mark either previous
or next node REF_NORMAL, as appropriate. */
if (newfrag->ofs & (PAGE_CACHE_SIZE-1)) {
struct jffs2_node_frag *prev = frag_prev(newfrag);
mark_ref_normal(fn->raw);
/* If we don't start at zero there's _always_ a previous */
if (prev->node)
mark_ref_normal(prev->node->raw);
}
if ((newfrag->ofs+newfrag->size) & (PAGE_CACHE_SIZE-1)) {
struct jffs2_node_frag *next = frag_next(newfrag);
if (next) {
mark_ref_normal(fn->raw);
if (next->node)
mark_ref_normal(next->node->raw);
}
}
jffs2_dbg_fragtree_paranoia_check_nolock(f);
return 0;
}
void jffs2_set_inocache_state(struct jffs2_sb_info *c, struct jffs2_inode_cache *ic, int state)
{
spin_lock(&c->inocache_lock);
ic->state = state;
wake_up(&c->inocache_wq);
spin_unlock(&c->inocache_lock);
}
/* During mount, this needs no locking. During normal operation, its
callers want to do other stuff while still holding the inocache_lock.
Rather than introducing special case get_ino_cache functions or
callbacks, we just let the caller do the locking itself. */
struct jffs2_inode_cache *jffs2_get_ino_cache(struct jffs2_sb_info *c, uint32_t ino)
{
struct jffs2_inode_cache *ret;
ret = c->inocache_list[ino % c->inocache_hashsize];
while (ret && ret->ino < ino) {
ret = ret->next;
}
if (ret && ret->ino != ino)
ret = NULL;
return ret;
}
void jffs2_add_ino_cache (struct jffs2_sb_info *c, struct jffs2_inode_cache *new)
{
struct jffs2_inode_cache **prev;
spin_lock(&c->inocache_lock);
if (!new->ino)
new->ino = ++c->highest_ino;
dbg_inocache("add %p (ino #%u)\n", new, new->ino);
prev = &c->inocache_list[new->ino % c->inocache_hashsize];
while ((*prev) && (*prev)->ino < new->ino) {
prev = &(*prev)->next;
}
new->next = *prev;
*prev = new;
spin_unlock(&c->inocache_lock);
}
void jffs2_del_ino_cache(struct jffs2_sb_info *c, struct jffs2_inode_cache *old)
{
struct jffs2_inode_cache **prev;
#ifdef CONFIG_JFFS2_FS_XATTR
BUG_ON(old->xref);
#endif
dbg_inocache("del %p (ino #%u)\n", old, old->ino);
spin_lock(&c->inocache_lock);
prev = &c->inocache_list[old->ino % c->inocache_hashsize];
while ((*prev) && (*prev)->ino < old->ino) {
prev = &(*prev)->next;
}
if ((*prev) == old) {
*prev = old->next;
}
/* Free it now unless it's in READING or CLEARING state, which
are the transitions upon read_inode() and clear_inode(). The
rest of the time we know nobody else is looking at it, and
if it's held by read_inode() or clear_inode() they'll free it
for themselves. */
if (old->state != INO_STATE_READING && old->state != INO_STATE_CLEARING)
jffs2_free_inode_cache(old);
spin_unlock(&c->inocache_lock);
}
void jffs2_free_ino_caches(struct jffs2_sb_info *c)
{
int i;
struct jffs2_inode_cache *this, *next;
for (i=0; i < c->inocache_hashsize; i++) {
this = c->inocache_list[i];
while (this) {
next = this->next;
jffs2_xattr_free_inode(c, this);
jffs2_free_inode_cache(this);
this = next;
}
c->inocache_list[i] = NULL;
}
}
void jffs2_free_raw_node_refs(struct jffs2_sb_info *c)
{
int i;
struct jffs2_raw_node_ref *this, *next;
for (i=0; i<c->nr_blocks; i++) {
this = c->blocks[i].first_node;
while (this) {
if (this[REFS_PER_BLOCK].flash_offset == REF_LINK_NODE)
next = this[REFS_PER_BLOCK].next_in_ino;
else
next = NULL;
jffs2_free_refblock(this);
this = next;
}
c->blocks[i].first_node = c->blocks[i].last_node = NULL;
}
}
struct jffs2_node_frag *jffs2_lookup_node_frag(struct rb_root *fragtree, uint32_t offset)
{
/* The common case in lookup is that there will be a node
which precisely matches. So we go looking for that first */
struct rb_node *next;
struct jffs2_node_frag *prev = NULL;
struct jffs2_node_frag *frag = NULL;
dbg_fragtree2("root %p, offset %d\n", fragtree, offset);
next = fragtree->rb_node;
while(next) {
frag = rb_entry(next, struct jffs2_node_frag, rb);
if (frag->ofs + frag->size <= offset) {
/* Remember the closest smaller match on the way down */
if (!prev || frag->ofs > prev->ofs)
prev = frag;
next = frag->rb.rb_right;
} else if (frag->ofs > offset) {
next = frag->rb.rb_left;
} else {
return frag;
}
}
/* Exact match not found. Go back up looking at each parent,
and return the closest smaller one */
if (prev)
dbg_fragtree2("no match. Returning frag %#04x-%#04x, closest previous\n",
prev->ofs, prev->ofs+prev->size);
else
dbg_fragtree2("returning NULL, empty fragtree\n");
return prev;
}
/* Pass 'c' argument to indicate that nodes should be marked obsolete as
they're killed. */
void jffs2_kill_fragtree(struct rb_root *root, struct jffs2_sb_info *c)
{
struct jffs2_node_frag *frag;
struct jffs2_node_frag *parent;
if (!root->rb_node)
return;
dbg_fragtree("killing\n");
frag = (rb_entry(root->rb_node, struct jffs2_node_frag, rb));
while(frag) {
if (frag->rb.rb_left) {
frag = frag_left(frag);
continue;
}
if (frag->rb.rb_right) {
frag = frag_right(frag);
continue;
}
if (frag->node && !(--frag->node->frags)) {
/* Not a hole, and it's the final remaining frag
of this node. Free the node */
if (c)
jffs2_mark_node_obsolete(c, frag->node->raw);
jffs2_free_full_dnode(frag->node);
}
parent = frag_parent(frag);
if (parent) {
if (frag_left(parent) == frag)
parent->rb.rb_left = NULL;
else
parent->rb.rb_right = NULL;
}
jffs2_free_node_frag(frag);
frag = parent;
cond_resched();
}
}
struct jffs2_raw_node_ref *jffs2_link_node_ref(struct jffs2_sb_info *c,
struct jffs2_eraseblock *jeb,
uint32_t ofs, uint32_t len,
struct jffs2_inode_cache *ic)
{
struct jffs2_raw_node_ref *ref;
BUG_ON(!jeb->allocated_refs);
jeb->allocated_refs--;
ref = jeb->last_node;
dbg_noderef("Last node at %p is (%08x,%p)\n", ref, ref->flash_offset,
ref->next_in_ino);
while (ref->flash_offset != REF_EMPTY_NODE) {
if (ref->flash_offset == REF_LINK_NODE)
ref = ref->next_in_ino;
else
ref++;
}
dbg_noderef("New ref is %p (%08x becomes %08x,%p) len 0x%x\n", ref,
ref->flash_offset, ofs, ref->next_in_ino, len);
ref->flash_offset = ofs;
if (!jeb->first_node) {
jeb->first_node = ref;
BUG_ON(ref_offset(ref) != jeb->offset);
} else if (unlikely(ref_offset(ref) != jeb->offset + c->sector_size - jeb->free_size)) {
uint32_t last_len = ref_totlen(c, jeb, jeb->last_node);
JFFS2_ERROR("Adding new ref %p at (0x%08x-0x%08x) not immediately after previous (0x%08x-0x%08x)\n",
ref, ref_offset(ref), ref_offset(ref)+len,
ref_offset(jeb->last_node),
ref_offset(jeb->last_node)+last_len);
BUG();
}
jeb->last_node = ref;
if (ic) {
ref->next_in_ino = ic->nodes;
ic->nodes = ref;
} else {
ref->next_in_ino = NULL;
}
switch(ref_flags(ref)) {
case REF_UNCHECKED:
c->unchecked_size += len;
jeb->unchecked_size += len;
break;
case REF_NORMAL:
case REF_PRISTINE:
c->used_size += len;
jeb->used_size += len;
break;
case REF_OBSOLETE:
c->dirty_size += len;
jeb->dirty_size += len;
break;
}
c->free_size -= len;
jeb->free_size -= len;
#ifdef TEST_TOTLEN
/* Set (and test) __totlen field... for now */
ref->__totlen = len;
ref_totlen(c, jeb, ref);
#endif
return ref;
}
/* No locking, no reservation of 'ref'. Do not use on a live file system */
int jffs2_scan_dirty_space(struct jffs2_sb_info *c, struct jffs2_eraseblock *jeb,
uint32_t size)
{
if (!size)
return 0;
if (unlikely(size > jeb->free_size)) {
pr_crit("Dirty space 0x%x larger then free_size 0x%x (wasted 0x%x)\n",
size, jeb->free_size, jeb->wasted_size);
BUG();
}
/* REF_EMPTY_NODE is !obsolete, so that works OK */
if (jeb->last_node && ref_obsolete(jeb->last_node)) {
#ifdef TEST_TOTLEN
jeb->last_node->__totlen += size;
#endif
c->dirty_size += size;
c->free_size -= size;
jeb->dirty_size += size;
jeb->free_size -= size;
} else {
uint32_t ofs = jeb->offset + c->sector_size - jeb->free_size;
ofs |= REF_OBSOLETE;
jffs2_link_node_ref(c, jeb, ofs, size, NULL);
}
return 0;
}
/* Calculate totlen from surrounding nodes or eraseblock */
static inline uint32_t __ref_totlen(struct jffs2_sb_info *c,
struct jffs2_eraseblock *jeb,
struct jffs2_raw_node_ref *ref)
{
uint32_t ref_end;
struct jffs2_raw_node_ref *next_ref = ref_next(ref);
if (next_ref)
ref_end = ref_offset(next_ref);
else {
if (!jeb)
jeb = &c->blocks[ref->flash_offset / c->sector_size];
/* Last node in block. Use free_space */
if (unlikely(ref != jeb->last_node)) {
pr_crit("ref %p @0x%08x is not jeb->last_node (%p @0x%08x)\n",
ref, ref_offset(ref), jeb->last_node,
jeb->last_node ?
ref_offset(jeb->last_node) : 0);
BUG();
}
ref_end = jeb->offset + c->sector_size - jeb->free_size;
}
return ref_end - ref_offset(ref);
}
uint32_t __jffs2_ref_totlen(struct jffs2_sb_info *c, struct jffs2_eraseblock *jeb,
struct jffs2_raw_node_ref *ref)
{
uint32_t ret;
ret = __ref_totlen(c, jeb, ref);
#ifdef TEST_TOTLEN
if (unlikely(ret != ref->__totlen)) {
if (!jeb)
jeb = &c->blocks[ref->flash_offset / c->sector_size];
pr_crit("Totlen for ref at %p (0x%08x-0x%08x) miscalculated as 0x%x instead of %x\n",
ref, ref_offset(ref), ref_offset(ref) + ref->__totlen,
ret, ref->__totlen);
if (ref_next(ref)) {
pr_crit("next %p (0x%08x-0x%08x)\n",
ref_next(ref), ref_offset(ref_next(ref)),
ref_offset(ref_next(ref)) + ref->__totlen);
} else
pr_crit("No next ref. jeb->last_node is %p\n",
jeb->last_node);
pr_crit("jeb->wasted_size %x, dirty_size %x, used_size %x, free_size %x\n",
jeb->wasted_size, jeb->dirty_size, jeb->used_size,
jeb->free_size);
#if defined(JFFS2_DBG_DUMPS) || defined(JFFS2_DBG_PARANOIA_CHECKS)
__jffs2_dbg_dump_node_refs_nolock(c, jeb);
#endif
WARN_ON(1);
ret = ref->__totlen;
}
#endif /* TEST_TOTLEN */
return ret;
}
| gpl-2.0 |
Team-Hydra/S5-AEL-Kernel | drivers/staging/comedi/drivers/usbduxfast.c | 7986 | 46911 | /*
* Copyright (C) 2004 Bernd Porr, Bernd.Porr@f2s.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* I must give credit here to Chris Baugher who
* wrote the driver for AT-MIO-16d. I used some parts of this
* driver. I also must give credits to David Brownell
* who supported me with the USB development.
*
* Bernd Porr
*
*
* Revision history:
* 0.9: Dropping the first data packet which seems to be from the last transfer.
* Buffer overflows in the FX2 are handed over to comedi.
* 0.92: Dropping now 4 packets. The quad buffer has to be emptied.
* Added insn command basically for testing. Sample rate is
* 1MHz/16ch=62.5kHz
* 0.99: Ian Abbott pointed out a bug which has been corrected. Thanks!
* 0.99a: added external trigger.
* 1.00: added firmware kernel request to the driver which fixed
* udev coldplug problem
*/
#include <linux/kernel.h>
#include <linux/firmware.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/usb.h>
#include <linux/fcntl.h>
#include <linux/compiler.h>
#include "comedi_fc.h"
#include "../comedidev.h"
#define DRIVER_VERSION "v1.0"
#define DRIVER_AUTHOR "Bernd Porr, BerndPorr@f2s.com"
#define DRIVER_DESC "USB-DUXfast, BerndPorr@f2s.com"
#define BOARDNAME "usbduxfast"
/*
* timeout for the USB-transfer
*/
#define EZTIMEOUT 30
/*
* constants for "firmware" upload and download
*/
#define USBDUXFASTSUB_FIRMWARE 0xA0
#define VENDOR_DIR_IN 0xC0
#define VENDOR_DIR_OUT 0x40
/*
* internal addresses of the 8051 processor
*/
#define USBDUXFASTSUB_CPUCS 0xE600
/*
* max lenghth of the transfer-buffer for software upload
*/
#define TB_LEN 0x2000
/*
* input endpoint number
*/
#define BULKINEP 6
/*
* endpoint for the A/D channellist: bulk OUT
*/
#define CHANNELLISTEP 4
/*
* number of channels
*/
#define NUMCHANNELS 32
/*
* size of the waveform descriptor
*/
#define WAVESIZE 0x20
/*
* size of one A/D value
*/
#define SIZEADIN (sizeof(int16_t))
/*
* size of the input-buffer IN BYTES
*/
#define SIZEINBUF 512
/*
* 16 bytes
*/
#define SIZEINSNBUF 512
/*
* size of the buffer for the dux commands in bytes
*/
#define SIZEOFDUXBUFFER 256
/*
* number of in-URBs which receive the data: min=5
*/
#define NUMOFINBUFFERSHIGH 10
/*
* total number of usbduxfast devices
*/
#define NUMUSBDUXFAST 16
/*
* number of subdevices
*/
#define N_SUBDEVICES 1
/*
* analogue in subdevice
*/
#define SUBDEV_AD 0
/*
* min delay steps for more than one channel
* basically when the mux gives up ;-)
*
* steps at 30MHz in the FX2
*/
#define MIN_SAMPLING_PERIOD 9
/*
* max number of 1/30MHz delay steps
*/
#define MAX_SAMPLING_PERIOD 500
/*
* number of received packets to ignore before we start handing data
* over to comedi, it's quad buffering and we have to ignore 4 packets
*/
#define PACKETS_TO_IGNORE 4
/*
* comedi constants
*/
static const struct comedi_lrange range_usbduxfast_ai_range = {
2, {BIP_RANGE(0.75), BIP_RANGE(0.5)}
};
/*
* private structure of one subdevice
*
* this is the structure which holds all the data of this driver
* one sub device just now: A/D
*/
struct usbduxfastsub_s {
int attached; /* is attached? */
int probed; /* is it associated with a subdevice? */
struct usb_device *usbdev; /* pointer to the usb-device */
struct urb *urbIn; /* BULK-transfer handling: urb */
int8_t *transfer_buffer;
int16_t *insnBuffer; /* input buffer for single insn */
int ifnum; /* interface number */
struct usb_interface *interface; /* interface structure */
/* comedi device for the interrupt context */
struct comedi_device *comedidev;
short int ai_cmd_running; /* asynchronous command is running */
short int ai_continous; /* continous acquisition */
long int ai_sample_count; /* number of samples to acquire */
uint8_t *dux_commands; /* commands */
int ignore; /* counter which ignores the first
buffers */
struct semaphore sem;
};
/*
* The pointer to the private usb-data of the driver
* is also the private data for the comedi-device.
* This has to be global as the usb subsystem needs
* global variables. The other reason is that this
* structure must be there _before_ any comedi
* command is issued. The usb subsystem must be
* initialised before comedi can access it.
*/
static struct usbduxfastsub_s usbduxfastsub[NUMUSBDUXFAST];
static DEFINE_SEMAPHORE(start_stop_sem);
/*
* bulk transfers to usbduxfast
*/
#define SENDADCOMMANDS 0
#define SENDINITEP6 1
static int send_dux_commands(struct usbduxfastsub_s *udfs, int cmd_type)
{
int tmp, nsent;
udfs->dux_commands[0] = cmd_type;
#ifdef CONFIG_COMEDI_DEBUG
printk(KERN_DEBUG "comedi%d: usbduxfast: dux_commands: ",
udfs->comedidev->minor);
for (tmp = 0; tmp < SIZEOFDUXBUFFER; tmp++)
printk(" %02x", udfs->dux_commands[tmp]);
printk("\n");
#endif
tmp = usb_bulk_msg(udfs->usbdev,
usb_sndbulkpipe(udfs->usbdev, CHANNELLISTEP),
udfs->dux_commands, SIZEOFDUXBUFFER, &nsent, 10000);
if (tmp < 0)
printk(KERN_ERR "comedi%d: could not transmit dux_commands to"
"the usb-device, err=%d\n", udfs->comedidev->minor, tmp);
return tmp;
}
/*
* Stops the data acquision.
* It should be safe to call this function from any context.
*/
static int usbduxfastsub_unlink_InURBs(struct usbduxfastsub_s *udfs)
{
int j = 0;
int err = 0;
if (udfs && udfs->urbIn) {
udfs->ai_cmd_running = 0;
/* waits until a running transfer is over */
usb_kill_urb(udfs->urbIn);
j = 0;
}
#ifdef CONFIG_COMEDI_DEBUG
printk(KERN_DEBUG "comedi: usbduxfast: unlinked InURB: res=%d\n", j);
#endif
return err;
}
/*
* This will stop a running acquisition operation.
* Is called from within this driver from both the
* interrupt context and from comedi.
*/
static int usbduxfast_ai_stop(struct usbduxfastsub_s *udfs, int do_unlink)
{
int ret = 0;
if (!udfs) {
printk(KERN_ERR "comedi?: usbduxfast_ai_stop: udfs=NULL!\n");
return -EFAULT;
}
#ifdef CONFIG_COMEDI_DEBUG
printk(KERN_DEBUG "comedi: usbduxfast_ai_stop\n");
#endif
udfs->ai_cmd_running = 0;
if (do_unlink)
/* stop aquistion */
ret = usbduxfastsub_unlink_InURBs(udfs);
return ret;
}
/*
* This will cancel a running acquisition operation.
* This is called by comedi but never from inside the driver.
*/
static int usbduxfast_ai_cancel(struct comedi_device *dev,
struct comedi_subdevice *s)
{
struct usbduxfastsub_s *udfs;
int ret;
/* force unlink of all urbs */
#ifdef CONFIG_COMEDI_DEBUG
printk(KERN_DEBUG "comedi: usbduxfast_ai_cancel\n");
#endif
udfs = dev->private;
if (!udfs) {
printk(KERN_ERR "comedi: usbduxfast_ai_cancel: udfs=NULL\n");
return -EFAULT;
}
down(&udfs->sem);
if (!udfs->probed) {
up(&udfs->sem);
return -ENODEV;
}
/* unlink */
ret = usbduxfast_ai_stop(udfs, 1);
up(&udfs->sem);
return ret;
}
/*
* analogue IN
* interrupt service routine
*/
static void usbduxfastsub_ai_Irq(struct urb *urb)
{
int n, err;
struct usbduxfastsub_s *udfs;
struct comedi_device *this_comedidev;
struct comedi_subdevice *s;
uint16_t *p;
/* sanity checks - is the urb there? */
if (!urb) {
printk(KERN_ERR "comedi_: usbduxfast_: ao int-handler called "
"with urb=NULL!\n");
return;
}
/* the context variable points to the subdevice */
this_comedidev = urb->context;
if (!this_comedidev) {
printk(KERN_ERR "comedi_: usbduxfast_: urb context is a NULL "
"pointer!\n");
return;
}
/* the private structure of the subdevice is usbduxfastsub_s */
udfs = this_comedidev->private;
if (!udfs) {
printk(KERN_ERR "comedi_: usbduxfast_: private of comedi "
"subdev is a NULL pointer!\n");
return;
}
/* are we running a command? */
if (unlikely(!udfs->ai_cmd_running)) {
/*
* not running a command
* do not continue execution if no asynchronous command
* is running in particular not resubmit
*/
return;
}
if (unlikely(!udfs->attached)) {
/* no comedi device there */
return;
}
/* subdevice which is the AD converter */
s = this_comedidev->subdevices + SUBDEV_AD;
/* first we test if something unusual has just happened */
switch (urb->status) {
case 0:
break;
/*
* happens after an unlink command or when the device
* is plugged out
*/
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
case -ECONNABORTED:
/* tell this comedi */
s->async->events |= COMEDI_CB_EOA;
s->async->events |= COMEDI_CB_ERROR;
comedi_event(udfs->comedidev, s);
/* stop the transfer w/o unlink */
usbduxfast_ai_stop(udfs, 0);
return;
default:
printk("comedi%d: usbduxfast: non-zero urb status received in "
"ai intr context: %d\n",
udfs->comedidev->minor, urb->status);
s->async->events |= COMEDI_CB_EOA;
s->async->events |= COMEDI_CB_ERROR;
comedi_event(udfs->comedidev, s);
usbduxfast_ai_stop(udfs, 0);
return;
}
p = urb->transfer_buffer;
if (!udfs->ignore) {
if (!udfs->ai_continous) {
/* not continuous, fixed number of samples */
n = urb->actual_length / sizeof(uint16_t);
if (unlikely(udfs->ai_sample_count < n)) {
/*
* we have send only a fraction of the bytes
* received
*/
cfc_write_array_to_buffer(s,
urb->transfer_buffer,
udfs->ai_sample_count
* sizeof(uint16_t));
usbduxfast_ai_stop(udfs, 0);
/* tell comedi that the acquistion is over */
s->async->events |= COMEDI_CB_EOA;
comedi_event(udfs->comedidev, s);
return;
}
udfs->ai_sample_count -= n;
}
/* write the full buffer to comedi */
err = cfc_write_array_to_buffer(s, urb->transfer_buffer,
urb->actual_length);
if (unlikely(err == 0)) {
/* buffer overflow */
usbduxfast_ai_stop(udfs, 0);
return;
}
/* tell comedi that data is there */
comedi_event(udfs->comedidev, s);
} else {
/* ignore this packet */
udfs->ignore--;
}
/*
* command is still running
* resubmit urb for BULK transfer
*/
urb->dev = udfs->usbdev;
urb->status = 0;
err = usb_submit_urb(urb, GFP_ATOMIC);
if (err < 0) {
printk(KERN_ERR "comedi%d: usbduxfast: urb resubm failed: %d",
udfs->comedidev->minor, err);
s->async->events |= COMEDI_CB_EOA;
s->async->events |= COMEDI_CB_ERROR;
comedi_event(udfs->comedidev, s);
usbduxfast_ai_stop(udfs, 0);
}
}
static int usbduxfastsub_start(struct usbduxfastsub_s *udfs)
{
int ret;
unsigned char local_transfer_buffer[16];
/* 7f92 to zero */
local_transfer_buffer[0] = 0;
/* bRequest, "Firmware" */
ret = usb_control_msg(udfs->usbdev, usb_sndctrlpipe(udfs->usbdev, 0), USBDUXFASTSUB_FIRMWARE,
VENDOR_DIR_OUT, /* bmRequestType */
USBDUXFASTSUB_CPUCS, /* Value */
0x0000, /* Index */
/* address of the transfer buffer */
local_transfer_buffer,
1, /* Length */
EZTIMEOUT); /* Timeout */
if (ret < 0) {
printk("comedi_: usbduxfast_: control msg failed (start)\n");
return ret;
}
return 0;
}
static int usbduxfastsub_stop(struct usbduxfastsub_s *udfs)
{
int ret;
unsigned char local_transfer_buffer[16];
/* 7f92 to one */
local_transfer_buffer[0] = 1;
/* bRequest, "Firmware" */
ret = usb_control_msg(udfs->usbdev, usb_sndctrlpipe(udfs->usbdev, 0), USBDUXFASTSUB_FIRMWARE,
VENDOR_DIR_OUT, /* bmRequestType */
USBDUXFASTSUB_CPUCS, /* Value */
0x0000, /* Index */
local_transfer_buffer, 1, /* Length */
EZTIMEOUT); /* Timeout */
if (ret < 0) {
printk(KERN_ERR "comedi_: usbduxfast: control msg failed "
"(stop)\n");
return ret;
}
return 0;
}
static int usbduxfastsub_upload(struct usbduxfastsub_s *udfs,
unsigned char *local_transfer_buffer,
unsigned int startAddr, unsigned int len)
{
int ret;
#ifdef CONFIG_COMEDI_DEBUG
printk(KERN_DEBUG "comedi: usbduxfast: uploading %d bytes", len);
printk(KERN_DEBUG " to addr %d, first byte=%d.\n",
startAddr, local_transfer_buffer[0]);
#endif
/* brequest, firmware */
ret = usb_control_msg(udfs->usbdev, usb_sndctrlpipe(udfs->usbdev, 0), USBDUXFASTSUB_FIRMWARE,
VENDOR_DIR_OUT, /* bmRequestType */
startAddr, /* value */
0x0000, /* index */
/* our local safe buffer */
local_transfer_buffer,
len, /* length */
EZTIMEOUT); /* timeout */
#ifdef CONFIG_COMEDI_DEBUG
printk(KERN_DEBUG "comedi_: usbduxfast: result=%d\n", ret);
#endif
if (ret < 0) {
printk(KERN_ERR "comedi_: usbduxfast: uppload failed\n");
return ret;
}
return 0;
}
static int usbduxfastsub_submit_InURBs(struct usbduxfastsub_s *udfs)
{
int ret;
if (!udfs)
return -EFAULT;
usb_fill_bulk_urb(udfs->urbIn, udfs->usbdev,
usb_rcvbulkpipe(udfs->usbdev, BULKINEP),
udfs->transfer_buffer,
SIZEINBUF, usbduxfastsub_ai_Irq, udfs->comedidev);
#ifdef CONFIG_COMEDI_DEBUG
printk(KERN_DEBUG "comedi%d: usbduxfast: submitting in-urb: "
"0x%p,0x%p\n", udfs->comedidev->minor, udfs->urbIn->context,
udfs->urbIn->dev);
#endif
ret = usb_submit_urb(udfs->urbIn, GFP_ATOMIC);
if (ret) {
printk(KERN_ERR "comedi_: usbduxfast: ai: usb_submit_urb error"
" %d\n", ret);
return ret;
}
return 0;
}
static int usbduxfast_ai_cmdtest(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_cmd *cmd)
{
int err = 0, stop_mask = 0;
long int steps, tmp;
int minSamplPer;
struct usbduxfastsub_s *udfs = dev->private;
if (!udfs->probed)
return -ENODEV;
#ifdef CONFIG_COMEDI_DEBUG
printk(KERN_DEBUG "comedi%d: usbduxfast_ai_cmdtest\n", dev->minor);
printk(KERN_DEBUG "comedi%d: usbduxfast: convert_arg=%u "
"scan_begin_arg=%u\n",
dev->minor, cmd->convert_arg, cmd->scan_begin_arg);
#endif
/* step 1: make sure trigger sources are trivially valid */
tmp = cmd->start_src;
cmd->start_src &= TRIG_NOW | TRIG_EXT | TRIG_INT;
if (!cmd->start_src || tmp != cmd->start_src)
err++;
tmp = cmd->scan_begin_src;
cmd->scan_begin_src &= TRIG_TIMER | TRIG_FOLLOW | TRIG_EXT;
if (!cmd->scan_begin_src || tmp != cmd->scan_begin_src)
err++;
tmp = cmd->convert_src;
cmd->convert_src &= TRIG_TIMER | TRIG_EXT;
if (!cmd->convert_src || tmp != cmd->convert_src)
err++;
tmp = cmd->scan_end_src;
cmd->scan_end_src &= TRIG_COUNT;
if (!cmd->scan_end_src || tmp != cmd->scan_end_src)
err++;
tmp = cmd->stop_src;
stop_mask = TRIG_COUNT | TRIG_NONE;
cmd->stop_src &= stop_mask;
if (!cmd->stop_src || tmp != cmd->stop_src)
err++;
if (err)
return 1;
/*
* step 2: make sure trigger sources are unique and mutually compatible
*/
if (cmd->start_src != TRIG_NOW &&
cmd->start_src != TRIG_EXT && cmd->start_src != TRIG_INT)
err++;
if (cmd->scan_begin_src != TRIG_TIMER &&
cmd->scan_begin_src != TRIG_FOLLOW &&
cmd->scan_begin_src != TRIG_EXT)
err++;
if (cmd->convert_src != TRIG_TIMER && cmd->convert_src != TRIG_EXT)
err++;
if (cmd->stop_src != TRIG_COUNT &&
cmd->stop_src != TRIG_EXT && cmd->stop_src != TRIG_NONE)
err++;
/* can't have external stop and start triggers at once */
if (cmd->start_src == TRIG_EXT && cmd->stop_src == TRIG_EXT)
err++;
if (err)
return 2;
/* step 3: make sure arguments are trivially compatible */
if (cmd->start_src == TRIG_NOW && cmd->start_arg != 0) {
cmd->start_arg = 0;
err++;
}
if (!cmd->chanlist_len)
err++;
if (cmd->scan_end_arg != cmd->chanlist_len) {
cmd->scan_end_arg = cmd->chanlist_len;
err++;
}
if (cmd->chanlist_len == 1)
minSamplPer = 1;
else
minSamplPer = MIN_SAMPLING_PERIOD;
if (cmd->convert_src == TRIG_TIMER) {
steps = cmd->convert_arg * 30;
if (steps < (minSamplPer * 1000))
steps = minSamplPer * 1000;
if (steps > (MAX_SAMPLING_PERIOD * 1000))
steps = MAX_SAMPLING_PERIOD * 1000;
/* calc arg again */
tmp = steps / 30;
if (cmd->convert_arg != tmp) {
cmd->convert_arg = tmp;
err++;
}
}
if (cmd->scan_begin_src == TRIG_TIMER)
err++;
/* stop source */
switch (cmd->stop_src) {
case TRIG_COUNT:
if (!cmd->stop_arg) {
cmd->stop_arg = 1;
err++;
}
break;
case TRIG_NONE:
if (cmd->stop_arg != 0) {
cmd->stop_arg = 0;
err++;
}
break;
/*
* TRIG_EXT doesn't care since it doesn't trigger
* off a numbered channel
*/
default:
break;
}
if (err)
return 3;
/* step 4: fix up any arguments */
return 0;
}
static int usbduxfast_ai_inttrig(struct comedi_device *dev,
struct comedi_subdevice *s,
unsigned int trignum)
{
int ret;
struct usbduxfastsub_s *udfs = dev->private;
if (!udfs)
return -EFAULT;
down(&udfs->sem);
if (!udfs->probed) {
up(&udfs->sem);
return -ENODEV;
}
#ifdef CONFIG_COMEDI_DEBUG
printk(KERN_DEBUG "comedi%d: usbduxfast_ai_inttrig\n", dev->minor);
#endif
if (trignum != 0) {
printk(KERN_ERR "comedi%d: usbduxfast_ai_inttrig: invalid"
" trignum\n", dev->minor);
up(&udfs->sem);
return -EINVAL;
}
if (!udfs->ai_cmd_running) {
udfs->ai_cmd_running = 1;
ret = usbduxfastsub_submit_InURBs(udfs);
if (ret < 0) {
printk(KERN_ERR "comedi%d: usbduxfast_ai_inttrig: "
"urbSubmit: err=%d\n", dev->minor, ret);
udfs->ai_cmd_running = 0;
up(&udfs->sem);
return ret;
}
s->async->inttrig = NULL;
} else {
printk(KERN_ERR "comedi%d: ai_inttrig but acqu is already"
" running\n", dev->minor);
}
up(&udfs->sem);
return 1;
}
/*
* offsets for the GPIF bytes
* the first byte is the command byte
*/
#define LENBASE (1+0x00)
#define OPBASE (1+0x08)
#define OUTBASE (1+0x10)
#define LOGBASE (1+0x18)
static int usbduxfast_ai_cmd(struct comedi_device *dev,
struct comedi_subdevice *s)
{
struct comedi_cmd *cmd = &s->async->cmd;
unsigned int chan, gain, rngmask = 0xff;
int i, j, ret;
struct usbduxfastsub_s *udfs;
int result;
long steps, steps_tmp;
#ifdef CONFIG_COMEDI_DEBUG
printk(KERN_DEBUG "comedi%d: usbduxfast_ai_cmd\n", dev->minor);
#endif
udfs = dev->private;
if (!udfs)
return -EFAULT;
down(&udfs->sem);
if (!udfs->probed) {
up(&udfs->sem);
return -ENODEV;
}
if (udfs->ai_cmd_running) {
printk(KERN_ERR "comedi%d: ai_cmd not possible. Another ai_cmd"
" is running.\n", dev->minor);
up(&udfs->sem);
return -EBUSY;
}
/* set current channel of the running acquisition to zero */
s->async->cur_chan = 0;
/*
* ignore the first buffers from the device if there
* is an error condition
*/
udfs->ignore = PACKETS_TO_IGNORE;
if (cmd->chanlist_len > 0) {
gain = CR_RANGE(cmd->chanlist[0]);
for (i = 0; i < cmd->chanlist_len; ++i) {
chan = CR_CHAN(cmd->chanlist[i]);
if (chan != i) {
printk(KERN_ERR "comedi%d: cmd is accepting "
"only consecutive channels.\n",
dev->minor);
up(&udfs->sem);
return -EINVAL;
}
if ((gain != CR_RANGE(cmd->chanlist[i]))
&& (cmd->chanlist_len > 3)) {
printk(KERN_ERR "comedi%d: the gain must be"
" the same for all channels.\n",
dev->minor);
up(&udfs->sem);
return -EINVAL;
}
if (i >= NUMCHANNELS) {
printk(KERN_ERR "comedi%d: channel list too"
" long\n", dev->minor);
break;
}
}
}
steps = 0;
if (cmd->scan_begin_src == TRIG_TIMER) {
printk(KERN_ERR "comedi%d: usbduxfast: "
"scan_begin_src==TRIG_TIMER not valid.\n", dev->minor);
up(&udfs->sem);
return -EINVAL;
}
if (cmd->convert_src == TRIG_TIMER)
steps = (cmd->convert_arg * 30) / 1000;
if ((steps < MIN_SAMPLING_PERIOD) && (cmd->chanlist_len != 1)) {
printk(KERN_ERR "comedi%d: usbduxfast: ai_cmd: steps=%ld, "
"scan_begin_arg=%d. Not properly tested by cmdtest?\n",
dev->minor, steps, cmd->scan_begin_arg);
up(&udfs->sem);
return -EINVAL;
}
if (steps > MAX_SAMPLING_PERIOD) {
printk(KERN_ERR "comedi%d: usbduxfast: ai_cmd: sampling rate "
"too low.\n", dev->minor);
up(&udfs->sem);
return -EINVAL;
}
if ((cmd->start_src == TRIG_EXT) && (cmd->chanlist_len != 1)
&& (cmd->chanlist_len != 16)) {
printk(KERN_ERR "comedi%d: usbduxfast: ai_cmd: TRIG_EXT only"
" with 1 or 16 channels possible.\n", dev->minor);
up(&udfs->sem);
return -EINVAL;
}
#ifdef CONFIG_COMEDI_DEBUG
printk(KERN_DEBUG "comedi%d: usbduxfast: steps=%ld, convert_arg=%u\n",
dev->minor, steps, cmd->convert_arg);
#endif
switch (cmd->chanlist_len) {
case 1:
/*
* one channel
*/
if (CR_RANGE(cmd->chanlist[0]) > 0)
rngmask = 0xff - 0x04;
else
rngmask = 0xff;
/*
* for external trigger: looping in this state until
* the RDY0 pin becomes zero
*/
/* we loop here until ready has been set */
if (cmd->start_src == TRIG_EXT) {
/* branch back to state 0 */
udfs->dux_commands[LENBASE + 0] = 0x01;
/* deceision state w/o data */
udfs->dux_commands[OPBASE + 0] = 0x01;
udfs->dux_commands[OUTBASE + 0] = 0xFF & rngmask;
/* RDY0 = 0 */
udfs->dux_commands[LOGBASE + 0] = 0x00;
} else { /* we just proceed to state 1 */
udfs->dux_commands[LENBASE + 0] = 1;
udfs->dux_commands[OPBASE + 0] = 0;
udfs->dux_commands[OUTBASE + 0] = 0xFF & rngmask;
udfs->dux_commands[LOGBASE + 0] = 0;
}
if (steps < MIN_SAMPLING_PERIOD) {
/* for fast single channel aqu without mux */
if (steps <= 1) {
/*
* we just stay here at state 1 and rexecute
* the same state this gives us 30MHz sampling
* rate
*/
/* branch back to state 1 */
udfs->dux_commands[LENBASE + 1] = 0x89;
/* deceision state with data */
udfs->dux_commands[OPBASE + 1] = 0x03;
udfs->dux_commands[OUTBASE + 1] =
0xFF & rngmask;
/* doesn't matter */
udfs->dux_commands[LOGBASE + 1] = 0xFF;
} else {
/*
* we loop through two states: data and delay
* max rate is 15MHz
*/
udfs->dux_commands[LENBASE + 1] = steps - 1;
/* data */
udfs->dux_commands[OPBASE + 1] = 0x02;
udfs->dux_commands[OUTBASE + 1] =
0xFF & rngmask;
/* doesn't matter */
udfs->dux_commands[LOGBASE + 1] = 0;
/* branch back to state 1 */
udfs->dux_commands[LENBASE + 2] = 0x09;
/* deceision state w/o data */
udfs->dux_commands[OPBASE + 2] = 0x01;
udfs->dux_commands[OUTBASE + 2] =
0xFF & rngmask;
/* doesn't matter */
udfs->dux_commands[LOGBASE + 2] = 0xFF;
}
} else {
/*
* we loop through 3 states: 2x delay and 1x data
* this gives a min sampling rate of 60kHz
*/
/* we have 1 state with duration 1 */
steps = steps - 1;
/* do the first part of the delay */
udfs->dux_commands[LENBASE + 1] = steps / 2;
udfs->dux_commands[OPBASE + 1] = 0;
udfs->dux_commands[OUTBASE + 1] = 0xFF & rngmask;
udfs->dux_commands[LOGBASE + 1] = 0;
/* and the second part */
udfs->dux_commands[LENBASE + 2] = steps - steps / 2;
udfs->dux_commands[OPBASE + 2] = 0;
udfs->dux_commands[OUTBASE + 2] = 0xFF & rngmask;
udfs->dux_commands[LOGBASE + 2] = 0;
/* get the data and branch back */
/* branch back to state 1 */
udfs->dux_commands[LENBASE + 3] = 0x09;
/* deceision state w data */
udfs->dux_commands[OPBASE + 3] = 0x03;
udfs->dux_commands[OUTBASE + 3] = 0xFF & rngmask;
/* doesn't matter */
udfs->dux_commands[LOGBASE + 3] = 0xFF;
}
break;
case 2:
/*
* two channels
* commit data to the FIFO
*/
if (CR_RANGE(cmd->chanlist[0]) > 0)
rngmask = 0xff - 0x04;
else
rngmask = 0xff;
udfs->dux_commands[LENBASE + 0] = 1;
/* data */
udfs->dux_commands[OPBASE + 0] = 0x02;
udfs->dux_commands[OUTBASE + 0] = 0xFF & rngmask;
udfs->dux_commands[LOGBASE + 0] = 0;
/* we have 1 state with duration 1: state 0 */
steps_tmp = steps - 1;
if (CR_RANGE(cmd->chanlist[1]) > 0)
rngmask = 0xff - 0x04;
else
rngmask = 0xff;
/* do the first part of the delay */
udfs->dux_commands[LENBASE + 1] = steps_tmp / 2;
udfs->dux_commands[OPBASE + 1] = 0;
/* count */
udfs->dux_commands[OUTBASE + 1] = 0xFE & rngmask;
udfs->dux_commands[LOGBASE + 1] = 0;
/* and the second part */
udfs->dux_commands[LENBASE + 2] = steps_tmp - steps_tmp / 2;
udfs->dux_commands[OPBASE + 2] = 0;
udfs->dux_commands[OUTBASE + 2] = 0xFF & rngmask;
udfs->dux_commands[LOGBASE + 2] = 0;
udfs->dux_commands[LENBASE + 3] = 1;
/* data */
udfs->dux_commands[OPBASE + 3] = 0x02;
udfs->dux_commands[OUTBASE + 3] = 0xFF & rngmask;
udfs->dux_commands[LOGBASE + 3] = 0;
/*
* we have 2 states with duration 1: step 6 and
* the IDLE state
*/
steps_tmp = steps - 2;
if (CR_RANGE(cmd->chanlist[0]) > 0)
rngmask = 0xff - 0x04;
else
rngmask = 0xff;
/* do the first part of the delay */
udfs->dux_commands[LENBASE + 4] = steps_tmp / 2;
udfs->dux_commands[OPBASE + 4] = 0;
/* reset */
udfs->dux_commands[OUTBASE + 4] = (0xFF - 0x02) & rngmask;
udfs->dux_commands[LOGBASE + 4] = 0;
/* and the second part */
udfs->dux_commands[LENBASE + 5] = steps_tmp - steps_tmp / 2;
udfs->dux_commands[OPBASE + 5] = 0;
udfs->dux_commands[OUTBASE + 5] = 0xFF & rngmask;
udfs->dux_commands[LOGBASE + 5] = 0;
udfs->dux_commands[LENBASE + 6] = 1;
udfs->dux_commands[OPBASE + 6] = 0;
udfs->dux_commands[OUTBASE + 6] = 0xFF & rngmask;
udfs->dux_commands[LOGBASE + 6] = 0;
break;
case 3:
/*
* three channels
*/
for (j = 0; j < 1; j++) {
if (CR_RANGE(cmd->chanlist[j]) > 0)
rngmask = 0xff - 0x04;
else
rngmask = 0xff;
/*
* commit data to the FIFO and do the first part
* of the delay
*/
udfs->dux_commands[LENBASE + j * 2] = steps / 2;
/* data */
udfs->dux_commands[OPBASE + j * 2] = 0x02;
/* no change */
udfs->dux_commands[OUTBASE + j * 2] = 0xFF & rngmask;
udfs->dux_commands[LOGBASE + j * 2] = 0;
if (CR_RANGE(cmd->chanlist[j + 1]) > 0)
rngmask = 0xff - 0x04;
else
rngmask = 0xff;
/* do the second part of the delay */
udfs->dux_commands[LENBASE + j * 2 + 1] =
steps - steps / 2;
/* no data */
udfs->dux_commands[OPBASE + j * 2 + 1] = 0;
/* count */
udfs->dux_commands[OUTBASE + j * 2 + 1] =
0xFE & rngmask;
udfs->dux_commands[LOGBASE + j * 2 + 1] = 0;
}
/* 2 steps with duration 1: the idele step and step 6: */
steps_tmp = steps - 2;
/* commit data to the FIFO and do the first part of the delay */
udfs->dux_commands[LENBASE + 4] = steps_tmp / 2;
/* data */
udfs->dux_commands[OPBASE + 4] = 0x02;
udfs->dux_commands[OUTBASE + 4] = 0xFF & rngmask;
udfs->dux_commands[LOGBASE + 4] = 0;
if (CR_RANGE(cmd->chanlist[0]) > 0)
rngmask = 0xff - 0x04;
else
rngmask = 0xff;
/* do the second part of the delay */
udfs->dux_commands[LENBASE + 5] = steps_tmp - steps_tmp / 2;
/* no data */
udfs->dux_commands[OPBASE + 5] = 0;
/* reset */
udfs->dux_commands[OUTBASE + 5] = (0xFF - 0x02) & rngmask;
udfs->dux_commands[LOGBASE + 5] = 0;
udfs->dux_commands[LENBASE + 6] = 1;
udfs->dux_commands[OPBASE + 6] = 0;
udfs->dux_commands[OUTBASE + 6] = 0xFF & rngmask;
udfs->dux_commands[LOGBASE + 6] = 0;
case 16:
if (CR_RANGE(cmd->chanlist[0]) > 0)
rngmask = 0xff - 0x04;
else
rngmask = 0xff;
if (cmd->start_src == TRIG_EXT) {
/*
* we loop here until ready has been set
*/
/* branch back to state 0 */
udfs->dux_commands[LENBASE + 0] = 0x01;
/* deceision state w/o data */
udfs->dux_commands[OPBASE + 0] = 0x01;
/* reset */
udfs->dux_commands[OUTBASE + 0] =
(0xFF - 0x02) & rngmask;
/* RDY0 = 0 */
udfs->dux_commands[LOGBASE + 0] = 0x00;
} else {
/*
* we just proceed to state 1
*/
/* 30us reset pulse */
udfs->dux_commands[LENBASE + 0] = 255;
udfs->dux_commands[OPBASE + 0] = 0;
/* reset */
udfs->dux_commands[OUTBASE + 0] =
(0xFF - 0x02) & rngmask;
udfs->dux_commands[LOGBASE + 0] = 0;
}
/* commit data to the FIFO */
udfs->dux_commands[LENBASE + 1] = 1;
/* data */
udfs->dux_commands[OPBASE + 1] = 0x02;
udfs->dux_commands[OUTBASE + 1] = 0xFF & rngmask;
udfs->dux_commands[LOGBASE + 1] = 0;
/* we have 2 states with duration 1 */
steps = steps - 2;
/* do the first part of the delay */
udfs->dux_commands[LENBASE + 2] = steps / 2;
udfs->dux_commands[OPBASE + 2] = 0;
udfs->dux_commands[OUTBASE + 2] = 0xFE & rngmask;
udfs->dux_commands[LOGBASE + 2] = 0;
/* and the second part */
udfs->dux_commands[LENBASE + 3] = steps - steps / 2;
udfs->dux_commands[OPBASE + 3] = 0;
udfs->dux_commands[OUTBASE + 3] = 0xFF & rngmask;
udfs->dux_commands[LOGBASE + 3] = 0;
/* branch back to state 1 */
udfs->dux_commands[LENBASE + 4] = 0x09;
/* deceision state w/o data */
udfs->dux_commands[OPBASE + 4] = 0x01;
udfs->dux_commands[OUTBASE + 4] = 0xFF & rngmask;
/* doesn't matter */
udfs->dux_commands[LOGBASE + 4] = 0xFF;
break;
default:
printk(KERN_ERR "comedi %d: unsupported combination of "
"channels\n", dev->minor);
up(&udfs->sem);
return -EFAULT;
}
#ifdef CONFIG_COMEDI_DEBUG
printk(KERN_DEBUG "comedi %d: sending commands to the usb device\n",
dev->minor);
#endif
/* 0 means that the AD commands are sent */
result = send_dux_commands(udfs, SENDADCOMMANDS);
if (result < 0) {
printk(KERN_ERR "comedi%d: adc command could not be submitted."
"Aborting...\n", dev->minor);
up(&udfs->sem);
return result;
}
if (cmd->stop_src == TRIG_COUNT) {
udfs->ai_sample_count = cmd->stop_arg * cmd->scan_end_arg;
if (udfs->ai_sample_count < 1) {
printk(KERN_ERR "comedi%d: "
"(cmd->stop_arg)*(cmd->scan_end_arg)<1, "
"aborting.\n", dev->minor);
up(&udfs->sem);
return -EFAULT;
}
udfs->ai_continous = 0;
} else {
/* continous acquisition */
udfs->ai_continous = 1;
udfs->ai_sample_count = 0;
}
if ((cmd->start_src == TRIG_NOW) || (cmd->start_src == TRIG_EXT)) {
/* enable this acquisition operation */
udfs->ai_cmd_running = 1;
ret = usbduxfastsub_submit_InURBs(udfs);
if (ret < 0) {
udfs->ai_cmd_running = 0;
/* fixme: unlink here?? */
up(&udfs->sem);
return ret;
}
s->async->inttrig = NULL;
} else {
/*
* TRIG_INT
* don't enable the acquision operation
* wait for an internal signal
*/
s->async->inttrig = usbduxfast_ai_inttrig;
}
up(&udfs->sem);
return 0;
}
/*
* Mode 0 is used to get a single conversion on demand.
*/
static int usbduxfast_ai_insn_read(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int i, j, n, actual_length;
int chan, range, rngmask;
int err;
struct usbduxfastsub_s *udfs;
udfs = dev->private;
if (!udfs) {
printk(KERN_ERR "comedi%d: ai_insn_read: no usb dev.\n",
dev->minor);
return -ENODEV;
}
#ifdef CONFIG_COMEDI_DEBUG
printk(KERN_DEBUG "comedi%d: ai_insn_read, insn->n=%d, "
"insn->subdev=%d\n", dev->minor, insn->n, insn->subdev);
#endif
down(&udfs->sem);
if (!udfs->probed) {
up(&udfs->sem);
return -ENODEV;
}
if (udfs->ai_cmd_running) {
printk(KERN_ERR "comedi%d: ai_insn_read not possible. Async "
"Command is running.\n", dev->minor);
up(&udfs->sem);
return -EBUSY;
}
/* sample one channel */
chan = CR_CHAN(insn->chanspec);
range = CR_RANGE(insn->chanspec);
/* set command for the first channel */
if (range > 0)
rngmask = 0xff - 0x04;
else
rngmask = 0xff;
/* commit data to the FIFO */
udfs->dux_commands[LENBASE + 0] = 1;
/* data */
udfs->dux_commands[OPBASE + 0] = 0x02;
udfs->dux_commands[OUTBASE + 0] = 0xFF & rngmask;
udfs->dux_commands[LOGBASE + 0] = 0;
/* do the first part of the delay */
udfs->dux_commands[LENBASE + 1] = 12;
udfs->dux_commands[OPBASE + 1] = 0;
udfs->dux_commands[OUTBASE + 1] = 0xFE & rngmask;
udfs->dux_commands[LOGBASE + 1] = 0;
udfs->dux_commands[LENBASE + 2] = 1;
udfs->dux_commands[OPBASE + 2] = 0;
udfs->dux_commands[OUTBASE + 2] = 0xFE & rngmask;
udfs->dux_commands[LOGBASE + 2] = 0;
udfs->dux_commands[LENBASE + 3] = 1;
udfs->dux_commands[OPBASE + 3] = 0;
udfs->dux_commands[OUTBASE + 3] = 0xFE & rngmask;
udfs->dux_commands[LOGBASE + 3] = 0;
udfs->dux_commands[LENBASE + 4] = 1;
udfs->dux_commands[OPBASE + 4] = 0;
udfs->dux_commands[OUTBASE + 4] = 0xFE & rngmask;
udfs->dux_commands[LOGBASE + 4] = 0;
/* second part */
udfs->dux_commands[LENBASE + 5] = 12;
udfs->dux_commands[OPBASE + 5] = 0;
udfs->dux_commands[OUTBASE + 5] = 0xFF & rngmask;
udfs->dux_commands[LOGBASE + 5] = 0;
udfs->dux_commands[LENBASE + 6] = 1;
udfs->dux_commands[OPBASE + 6] = 0;
udfs->dux_commands[OUTBASE + 6] = 0xFF & rngmask;
udfs->dux_commands[LOGBASE + 0] = 0;
#ifdef CONFIG_COMEDI_DEBUG
printk(KERN_DEBUG "comedi %d: sending commands to the usb device\n",
dev->minor);
#endif
/* 0 means that the AD commands are sent */
err = send_dux_commands(udfs, SENDADCOMMANDS);
if (err < 0) {
printk(KERN_ERR "comedi%d: adc command could not be submitted."
"Aborting...\n", dev->minor);
up(&udfs->sem);
return err;
}
#ifdef CONFIG_COMEDI_DEBUG
printk(KERN_DEBUG "comedi%d: usbduxfast: submitting in-urb: "
"0x%p,0x%p\n", udfs->comedidev->minor, udfs->urbIn->context,
udfs->urbIn->dev);
#endif
for (i = 0; i < PACKETS_TO_IGNORE; i++) {
err = usb_bulk_msg(udfs->usbdev,
usb_rcvbulkpipe(udfs->usbdev, BULKINEP),
udfs->transfer_buffer, SIZEINBUF,
&actual_length, 10000);
if (err < 0) {
printk(KERN_ERR "comedi%d: insn timeout. No data.\n",
dev->minor);
up(&udfs->sem);
return err;
}
}
/* data points */
for (i = 0; i < insn->n;) {
err = usb_bulk_msg(udfs->usbdev,
usb_rcvbulkpipe(udfs->usbdev, BULKINEP),
udfs->transfer_buffer, SIZEINBUF,
&actual_length, 10000);
if (err < 0) {
printk(KERN_ERR "comedi%d: insn data error: %d\n",
dev->minor, err);
up(&udfs->sem);
return err;
}
n = actual_length / sizeof(uint16_t);
if ((n % 16) != 0) {
printk(KERN_ERR "comedi%d: insn data packet "
"corrupted.\n", dev->minor);
up(&udfs->sem);
return -EINVAL;
}
for (j = chan; (j < n) && (i < insn->n); j = j + 16) {
data[i] = ((uint16_t *) (udfs->transfer_buffer))[j];
i++;
}
}
up(&udfs->sem);
return i;
}
#define FIRMWARE_MAX_LEN 0x2000
static int firmwareUpload(struct usbduxfastsub_s *usbduxfastsub,
const u8 *firmwareBinary, int sizeFirmware)
{
int ret;
uint8_t *fwBuf;
if (!firmwareBinary)
return 0;
if (sizeFirmware > FIRMWARE_MAX_LEN) {
dev_err(&usbduxfastsub->interface->dev,
"comedi_: usbduxfast firmware binary it too large for FX2.\n");
return -ENOMEM;
}
/* we generate a local buffer for the firmware */
fwBuf = kmemdup(firmwareBinary, sizeFirmware, GFP_KERNEL);
if (!fwBuf) {
dev_err(&usbduxfastsub->interface->dev,
"comedi_: mem alloc for firmware failed\n");
return -ENOMEM;
}
ret = usbduxfastsub_stop(usbduxfastsub);
if (ret < 0) {
dev_err(&usbduxfastsub->interface->dev,
"comedi_: can not stop firmware\n");
kfree(fwBuf);
return ret;
}
ret = usbduxfastsub_upload(usbduxfastsub, fwBuf, 0, sizeFirmware);
if (ret < 0) {
dev_err(&usbduxfastsub->interface->dev,
"comedi_: firmware upload failed\n");
kfree(fwBuf);
return ret;
}
ret = usbduxfastsub_start(usbduxfastsub);
if (ret < 0) {
dev_err(&usbduxfastsub->interface->dev,
"comedi_: can not start firmware\n");
kfree(fwBuf);
return ret;
}
kfree(fwBuf);
return 0;
}
static void tidy_up(struct usbduxfastsub_s *udfs)
{
#ifdef CONFIG_COMEDI_DEBUG
printk(KERN_DEBUG "comedi_: usbduxfast: tiding up\n");
#endif
if (!udfs)
return;
/* shows the usb subsystem that the driver is down */
if (udfs->interface)
usb_set_intfdata(udfs->interface, NULL);
udfs->probed = 0;
if (udfs->urbIn) {
/* waits until a running transfer is over */
usb_kill_urb(udfs->urbIn);
kfree(udfs->transfer_buffer);
udfs->transfer_buffer = NULL;
usb_free_urb(udfs->urbIn);
udfs->urbIn = NULL;
}
kfree(udfs->insnBuffer);
udfs->insnBuffer = NULL;
kfree(udfs->dux_commands);
udfs->dux_commands = NULL;
udfs->ai_cmd_running = 0;
}
static void usbduxfast_firmware_request_complete_handler(const struct firmware
*fw, void *context)
{
struct usbduxfastsub_s *usbduxfastsub_tmp = context;
struct usb_device *usbdev = usbduxfastsub_tmp->usbdev;
int ret;
if (fw == NULL)
return;
/*
* we need to upload the firmware here because fw will be
* freed once we've left this function
*/
ret = firmwareUpload(usbduxfastsub_tmp, fw->data, fw->size);
if (ret) {
dev_err(&usbdev->dev,
"Could not upload firmware (err=%d)\n", ret);
goto out;
}
comedi_usb_auto_config(usbdev, BOARDNAME);
out:
release_firmware(fw);
}
/*
* allocate memory for the urbs and initialise them
*/
static int usbduxfastsub_probe(struct usb_interface *uinterf,
const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev(uinterf);
int i;
int index;
int ret;
if (udev->speed != USB_SPEED_HIGH) {
printk(KERN_ERR "comedi_: usbduxfast_: This driver needs"
"USB 2.0 to operate. Aborting...\n");
return -ENODEV;
}
#ifdef CONFIG_COMEDI_DEBUG
printk(KERN_DEBUG "comedi_: usbduxfast_: finding a free structure for "
"the usb-device\n");
#endif
down(&start_stop_sem);
/* look for a free place in the usbduxfast array */
index = -1;
for (i = 0; i < NUMUSBDUXFAST; i++) {
if (!usbduxfastsub[i].probed) {
index = i;
break;
}
}
/* no more space */
if (index == -1) {
printk(KERN_ERR "Too many usbduxfast-devices connected.\n");
up(&start_stop_sem);
return -EMFILE;
}
#ifdef CONFIG_COMEDI_DEBUG
printk(KERN_DEBUG "comedi_: usbduxfast: usbduxfastsub[%d] is ready to "
"connect to comedi.\n", index);
#endif
sema_init(&(usbduxfastsub[index].sem), 1);
/* save a pointer to the usb device */
usbduxfastsub[index].usbdev = udev;
/* save the interface itself */
usbduxfastsub[index].interface = uinterf;
/* get the interface number from the interface */
usbduxfastsub[index].ifnum = uinterf->altsetting->desc.bInterfaceNumber;
/*
* hand the private data over to the usb subsystem
* will be needed for disconnect
*/
usb_set_intfdata(uinterf, &(usbduxfastsub[index]));
#ifdef CONFIG_COMEDI_DEBUG
printk(KERN_DEBUG "comedi_: usbduxfast: ifnum=%d\n",
usbduxfastsub[index].ifnum);
#endif
/* create space for the commands going to the usb device */
usbduxfastsub[index].dux_commands = kmalloc(SIZEOFDUXBUFFER,
GFP_KERNEL);
if (!usbduxfastsub[index].dux_commands) {
printk(KERN_ERR "comedi_: usbduxfast: error alloc space for "
"dac commands\n");
tidy_up(&(usbduxfastsub[index]));
up(&start_stop_sem);
return -ENOMEM;
}
/* create space of the instruction buffer */
usbduxfastsub[index].insnBuffer = kmalloc(SIZEINSNBUF, GFP_KERNEL);
if (!usbduxfastsub[index].insnBuffer) {
printk(KERN_ERR "comedi_: usbduxfast: could not alloc space "
"for insnBuffer\n");
tidy_up(&(usbduxfastsub[index]));
up(&start_stop_sem);
return -ENOMEM;
}
/* setting to alternate setting 1: enabling bulk ep */
i = usb_set_interface(usbduxfastsub[index].usbdev,
usbduxfastsub[index].ifnum, 1);
if (i < 0) {
printk(KERN_ERR "comedi_: usbduxfast%d: could not switch to "
"alternate setting 1.\n", index);
tidy_up(&(usbduxfastsub[index]));
up(&start_stop_sem);
return -ENODEV;
}
usbduxfastsub[index].urbIn = usb_alloc_urb(0, GFP_KERNEL);
if (!usbduxfastsub[index].urbIn) {
printk(KERN_ERR "comedi_: usbduxfast%d: Could not alloc."
"urb\n", index);
tidy_up(&(usbduxfastsub[index]));
up(&start_stop_sem);
return -ENOMEM;
}
usbduxfastsub[index].transfer_buffer = kmalloc(SIZEINBUF, GFP_KERNEL);
if (!usbduxfastsub[index].transfer_buffer) {
printk(KERN_ERR "comedi_: usbduxfast%d: could not alloc. "
"transb.\n", index);
tidy_up(&(usbduxfastsub[index]));
up(&start_stop_sem);
return -ENOMEM;
}
/* we've reached the bottom of the function */
usbduxfastsub[index].probed = 1;
up(&start_stop_sem);
ret = request_firmware_nowait(THIS_MODULE,
FW_ACTION_HOTPLUG,
"usbduxfast_firmware.bin",
&udev->dev,
GFP_KERNEL,
usbduxfastsub + index,
usbduxfast_firmware_request_complete_handler);
if (ret) {
dev_err(&udev->dev, "could not load firmware (err=%d)\n", ret);
return ret;
}
printk(KERN_INFO "comedi_: usbduxfast%d has been successfully "
"initialized.\n", index);
/* success */
return 0;
}
static void usbduxfastsub_disconnect(struct usb_interface *intf)
{
struct usbduxfastsub_s *udfs = usb_get_intfdata(intf);
struct usb_device *udev = interface_to_usbdev(intf);
if (!udfs) {
printk(KERN_ERR "comedi_: usbduxfast: disconnect called with "
"null pointer.\n");
return;
}
if (udfs->usbdev != udev) {
printk(KERN_ERR "comedi_: usbduxfast: BUG! called with wrong "
"ptr!!!\n");
return;
}
comedi_usb_auto_unconfig(udev);
down(&start_stop_sem);
down(&udfs->sem);
tidy_up(udfs);
up(&udfs->sem);
up(&start_stop_sem);
#ifdef CONFIG_COMEDI_DEBUG
printk(KERN_DEBUG "comedi_: usbduxfast: disconnected from the usb\n");
#endif
}
/*
* is called when comedi-config is called
*/
static int usbduxfast_attach(struct comedi_device *dev,
struct comedi_devconfig *it)
{
int ret;
int index;
int i;
struct comedi_subdevice *s = NULL;
dev->private = NULL;
down(&start_stop_sem);
/*
* find a valid device which has been detected by the
* probe function of the usb
*/
index = -1;
for (i = 0; i < NUMUSBDUXFAST; i++) {
if (usbduxfastsub[i].probed && !usbduxfastsub[i].attached) {
index = i;
break;
}
}
if (index < 0) {
printk(KERN_ERR "comedi%d: usbduxfast: error: attach failed, "
"no usbduxfast devs connected to the usb bus.\n",
dev->minor);
up(&start_stop_sem);
return -ENODEV;
}
down(&(usbduxfastsub[index].sem));
/* pointer back to the corresponding comedi device */
usbduxfastsub[index].comedidev = dev;
/* trying to upload the firmware into the chip */
if (comedi_aux_data(it->options, 0) &&
it->options[COMEDI_DEVCONF_AUX_DATA_LENGTH]) {
firmwareUpload(&usbduxfastsub[index],
comedi_aux_data(it->options, 0),
it->options[COMEDI_DEVCONF_AUX_DATA_LENGTH]);
}
dev->board_name = BOARDNAME;
/* set number of subdevices */
dev->n_subdevices = N_SUBDEVICES;
/* allocate space for the subdevices */
ret = alloc_subdevices(dev, N_SUBDEVICES);
if (ret < 0) {
printk(KERN_ERR "comedi%d: usbduxfast: error alloc space for "
"subdev\n", dev->minor);
up(&(usbduxfastsub[index].sem));
up(&start_stop_sem);
return ret;
}
printk(KERN_INFO "comedi%d: usbduxfast: usb-device %d is attached to "
"comedi.\n", dev->minor, index);
/* private structure is also simply the usb-structure */
dev->private = usbduxfastsub + index;
/* the first subdevice is the A/D converter */
s = dev->subdevices + SUBDEV_AD;
/*
* the URBs get the comedi subdevice which is responsible for reading
* this is the subdevice which reads data
*/
dev->read_subdev = s;
/* the subdevice receives as private structure the usb-structure */
s->private = NULL;
/* analog input */
s->type = COMEDI_SUBD_AI;
/* readable and ref is to ground */
s->subdev_flags = SDF_READABLE | SDF_GROUND | SDF_CMD_READ;
/* 16 channels */
s->n_chan = 16;
/* length of the channellist */
s->len_chanlist = 16;
/* callback functions */
s->insn_read = usbduxfast_ai_insn_read;
s->do_cmdtest = usbduxfast_ai_cmdtest;
s->do_cmd = usbduxfast_ai_cmd;
s->cancel = usbduxfast_ai_cancel;
/* max value from the A/D converter (12bit+1 bit for overflow) */
s->maxdata = 0x1000;
/* range table to convert to physical units */
s->range_table = &range_usbduxfast_ai_range;
/* finally decide that it's attached */
usbduxfastsub[index].attached = 1;
up(&(usbduxfastsub[index].sem));
up(&start_stop_sem);
printk(KERN_INFO "comedi%d: successfully attached to usbduxfast.\n",
dev->minor);
return 0;
}
static int usbduxfast_detach(struct comedi_device *dev)
{
struct usbduxfastsub_s *udfs;
if (!dev) {
printk(KERN_ERR "comedi?: usbduxfast: detach without dev "
"variable...\n");
return -EFAULT;
}
#ifdef CONFIG_COMEDI_DEBUG
printk(KERN_DEBUG "comedi%d: usbduxfast: detach usb device\n",
dev->minor);
#endif
udfs = dev->private;
if (!udfs) {
printk(KERN_ERR "comedi?: usbduxfast: detach without ptr to "
"usbduxfastsub[]\n");
return -EFAULT;
}
down(&udfs->sem);
down(&start_stop_sem);
/*
* Don't allow detach to free the private structure
* It's one entry of of usbduxfastsub[]
*/
dev->private = NULL;
udfs->attached = 0;
udfs->comedidev = NULL;
#ifdef CONFIG_COMEDI_DEBUG
printk(KERN_DEBUG "comedi%d: usbduxfast: detach: successfully "
"removed\n", dev->minor);
#endif
up(&start_stop_sem);
up(&udfs->sem);
return 0;
}
/*
* main driver struct
*/
static struct comedi_driver driver_usbduxfast = {
.driver_name = "usbduxfast",
.module = THIS_MODULE,
.attach = usbduxfast_attach,
.detach = usbduxfast_detach
};
/*
* Table with the USB-devices: just now only testing IDs
*/
static const struct usb_device_id usbduxfastsub_table[] = {
/* { USB_DEVICE(0x4b4, 0x8613) }, testing */
{USB_DEVICE(0x13d8, 0x0010)}, /* real ID */
{USB_DEVICE(0x13d8, 0x0011)}, /* real ID */
{} /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, usbduxfastsub_table);
/*
* The usbduxfastsub-driver
*/
static struct usb_driver usbduxfastsub_driver = {
#ifdef COMEDI_HAVE_USB_DRIVER_OWNER
.owner = THIS_MODULE,
#endif
.name = BOARDNAME,
.probe = usbduxfastsub_probe,
.disconnect = usbduxfastsub_disconnect,
.id_table = usbduxfastsub_table
};
/*
* Can't use the nice macro as I have also to initialise the USB subsystem:
* registering the usb-system _and_ the comedi-driver
*/
static int __init init_usbduxfast(void)
{
printk(KERN_INFO
KBUILD_MODNAME ": " DRIVER_VERSION ":" DRIVER_DESC "\n");
usb_register(&usbduxfastsub_driver);
comedi_driver_register(&driver_usbduxfast);
return 0;
}
/*
* deregistering the comedi driver and the usb-subsystem
*/
static void __exit exit_usbduxfast(void)
{
comedi_driver_unregister(&driver_usbduxfast);
usb_deregister(&usbduxfastsub_driver);
}
module_init(init_usbduxfast);
module_exit(exit_usbduxfast);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
| gpl-2.0 |
cm-maya/android_kernel_hp_maya | drivers/staging/comedi/drivers/icp_multi.c | 7986 | 31968 | /*
comedi/drivers/icp_multi.c
COMEDI - Linux Control and Measurement Device Interface
Copyright (C) 1997-2002 David A. Schleef <ds@schleef.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
Driver: icp_multi
Description: Inova ICP_MULTI
Author: Anne Smorthit <anne.smorthit@sfwte.ch>
Devices: [Inova] ICP_MULTI (icp_multi)
Status: works
The driver works for analog input and output and digital input and output.
It does not work with interrupts or with the counters. Currently no support
for DMA.
It has 16 single-ended or 8 differential Analogue Input channels with 12-bit
resolution. Ranges : 5V, 10V, +/-5V, +/-10V, 0..20mA and 4..20mA. Input
ranges can be individually programmed for each channel. Voltage or current
measurement is selected by jumper.
There are 4 x 12-bit Analogue Outputs. Ranges : 5V, 10V, +/-5V, +/-10V
16 x Digital Inputs, 24V
8 x Digital Outputs, 24V, 1A
4 x 16-bit counters
Options:
[0] - PCI bus number - if bus number and slot number are 0,
then driver search for first unused card
[1] - PCI slot number
*/
#include <linux/interrupt.h>
#include "../comedidev.h"
#include <linux/delay.h>
#include <linux/pci.h>
#include "icp_multi.h"
#define DEVICE_ID 0x8000 /* Device ID */
#define ICP_MULTI_EXTDEBUG
/* Hardware types of the cards */
#define TYPE_ICP_MULTI 0
#define IORANGE_ICP_MULTI 32
#define ICP_MULTI_ADC_CSR 0 /* R/W: ADC command/status register */
#define ICP_MULTI_AI 2 /* R: Analogue input data */
#define ICP_MULTI_DAC_CSR 4 /* R/W: DAC command/status register */
#define ICP_MULTI_AO 6 /* R/W: Analogue output data */
#define ICP_MULTI_DI 8 /* R/W: Digital inouts */
#define ICP_MULTI_DO 0x0A /* R/W: Digital outputs */
#define ICP_MULTI_INT_EN 0x0C /* R/W: Interrupt enable register */
#define ICP_MULTI_INT_STAT 0x0E /* R/W: Interrupt status register */
#define ICP_MULTI_CNTR0 0x10 /* R/W: Counter 0 */
#define ICP_MULTI_CNTR1 0x12 /* R/W: counter 1 */
#define ICP_MULTI_CNTR2 0x14 /* R/W: Counter 2 */
#define ICP_MULTI_CNTR3 0x16 /* R/W: Counter 3 */
#define ICP_MULTI_SIZE 0x20 /* 32 bytes */
/* Define bits from ADC command/status register */
#define ADC_ST 0x0001 /* Start ADC */
#define ADC_BSY 0x0001 /* ADC busy */
#define ADC_BI 0x0010 /* Bipolar input range 1 = bipolar */
#define ADC_RA 0x0020 /* Input range 0 = 5V, 1 = 10V */
#define ADC_DI 0x0040 /* Differential input mode 1 = differential */
/* Define bits from DAC command/status register */
#define DAC_ST 0x0001 /* Start DAC */
#define DAC_BSY 0x0001 /* DAC busy */
#define DAC_BI 0x0010 /* Bipolar input range 1 = bipolar */
#define DAC_RA 0x0020 /* Input range 0 = 5V, 1 = 10V */
/* Define bits from interrupt enable/status registers */
#define ADC_READY 0x0001 /* A/d conversion ready interrupt */
#define DAC_READY 0x0002 /* D/a conversion ready interrupt */
#define DOUT_ERROR 0x0004 /* Digital output error interrupt */
#define DIN_STATUS 0x0008 /* Digital input status change interrupt */
#define CIE0 0x0010 /* Counter 0 overrun interrupt */
#define CIE1 0x0020 /* Counter 1 overrun interrupt */
#define CIE2 0x0040 /* Counter 2 overrun interrupt */
#define CIE3 0x0080 /* Counter 3 overrun interrupt */
/* Useful definitions */
#define Status_IRQ 0x00ff /* All interrupts */
/* Define analogue range */
static const struct comedi_lrange range_analog = { 4, {
UNI_RANGE(5),
UNI_RANGE(10),
BIP_RANGE(5),
BIP_RANGE(10)
}
};
static const char range_codes_analog[] = { 0x00, 0x20, 0x10, 0x30 };
/*
==============================================================================
Forward declarations
==============================================================================
*/
static int icp_multi_attach(struct comedi_device *dev,
struct comedi_devconfig *it);
static int icp_multi_detach(struct comedi_device *dev);
/*
==============================================================================
Data & Structure declarations
==============================================================================
*/
static unsigned short pci_list_builded; /*>0 list of card is known */
struct boardtype {
const char *name; /* driver name */
int device_id;
int iorange; /* I/O range len */
char have_irq; /* 1=card support IRQ */
char cardtype; /* 0=ICP Multi */
int n_aichan; /* num of A/D chans */
int n_aichand; /* num of A/D chans in diff mode */
int n_aochan; /* num of D/A chans */
int n_dichan; /* num of DI chans */
int n_dochan; /* num of DO chans */
int n_ctrs; /* num of counters */
int ai_maxdata; /* resolution of A/D */
int ao_maxdata; /* resolution of D/A */
const struct comedi_lrange *rangelist_ai; /* rangelist for A/D */
const char *rangecode; /* range codes for programming */
const struct comedi_lrange *rangelist_ao; /* rangelist for D/A */
};
static const struct boardtype boardtypes[] = {
{"icp_multi", /* Driver name */
DEVICE_ID, /* PCI device ID */
IORANGE_ICP_MULTI, /* I/O range length */
1, /* 1=Card supports interrupts */
TYPE_ICP_MULTI, /* Card type = ICP MULTI */
16, /* Num of A/D channels */
8, /* Num of A/D channels in diff mode */
4, /* Num of D/A channels */
16, /* Num of digital inputs */
8, /* Num of digital outputs */
4, /* Num of counters */
0x0fff, /* Resolution of A/D */
0x0fff, /* Resolution of D/A */
&range_analog, /* Rangelist for A/D */
range_codes_analog, /* Range codes for programming */
&range_analog}, /* Rangelist for D/A */
};
#define n_boardtypes (sizeof(boardtypes)/sizeof(struct boardtype))
static struct comedi_driver driver_icp_multi = {
.driver_name = "icp_multi",
.module = THIS_MODULE,
.attach = icp_multi_attach,
.detach = icp_multi_detach,
.num_names = n_boardtypes,
.board_name = &boardtypes[0].name,
.offset = sizeof(struct boardtype),
};
static int __init driver_icp_multi_init_module(void)
{
return comedi_driver_register(&driver_icp_multi);
}
static void __exit driver_icp_multi_cleanup_module(void)
{
comedi_driver_unregister(&driver_icp_multi);
}
module_init(driver_icp_multi_init_module);
module_exit(driver_icp_multi_cleanup_module);
struct icp_multi_private {
struct pcilst_struct *card; /* pointer to card */
char valid; /* card is usable */
void *io_addr; /* Pointer to mapped io address */
resource_size_t phys_iobase; /* Physical io address */
unsigned int AdcCmdStatus; /* ADC Command/Status register */
unsigned int DacCmdStatus; /* DAC Command/Status register */
unsigned int IntEnable; /* Interrupt Enable register */
unsigned int IntStatus; /* Interrupt Status register */
unsigned int act_chanlist[32]; /* list of scaned channel */
unsigned char act_chanlist_len; /* len of scanlist */
unsigned char act_chanlist_pos; /* actual position in MUX list */
unsigned int *ai_chanlist; /* actaul chanlist */
short *ai_data; /* data buffer */
short ao_data[4]; /* data output buffer */
short di_data; /* Digital input data */
unsigned int do_data; /* Remember digital output data */
};
#define devpriv ((struct icp_multi_private *)dev->private)
#define this_board ((const struct boardtype *)dev->board_ptr)
/*
==============================================================================
More forward declarations
==============================================================================
*/
#if 0
static int check_channel_list(struct comedi_device *dev,
struct comedi_subdevice *s,
unsigned int *chanlist, unsigned int n_chan);
#endif
static void setup_channel_list(struct comedi_device *dev,
struct comedi_subdevice *s,
unsigned int *chanlist, unsigned int n_chan);
static int icp_multi_reset(struct comedi_device *dev);
/*
==============================================================================
Functions
==============================================================================
*/
/*
==============================================================================
Name: icp_multi_insn_read_ai
Description:
This function reads a single analogue input.
Parameters:
struct comedi_device *dev Pointer to current device structure
struct comedi_subdevice *s Pointer to current subdevice structure
struct comedi_insn *insn Pointer to current comedi instruction
unsigned int *data Pointer to analogue input data
Returns:int Nmuber of instructions executed
==============================================================================
*/
static int icp_multi_insn_read_ai(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int n, timeout;
#ifdef ICP_MULTI_EXTDEBUG
printk(KERN_DEBUG "icp multi EDBG: BGN: icp_multi_insn_read_ai(...)\n");
#endif
/* Disable A/D conversion ready interrupt */
devpriv->IntEnable &= ~ADC_READY;
writew(devpriv->IntEnable, devpriv->io_addr + ICP_MULTI_INT_EN);
/* Clear interrupt status */
devpriv->IntStatus |= ADC_READY;
writew(devpriv->IntStatus, devpriv->io_addr + ICP_MULTI_INT_STAT);
/* Set up appropriate channel, mode and range data, for specified ch */
setup_channel_list(dev, s, &insn->chanspec, 1);
#ifdef ICP_MULTI_EXTDEBUG
printk(KERN_DEBUG "icp_multi A ST=%4x IO=%p\n",
readw(devpriv->io_addr + ICP_MULTI_ADC_CSR),
devpriv->io_addr + ICP_MULTI_ADC_CSR);
#endif
for (n = 0; n < insn->n; n++) {
/* Set start ADC bit */
devpriv->AdcCmdStatus |= ADC_ST;
writew(devpriv->AdcCmdStatus,
devpriv->io_addr + ICP_MULTI_ADC_CSR);
devpriv->AdcCmdStatus &= ~ADC_ST;
#ifdef ICP_MULTI_EXTDEBUG
printk(KERN_DEBUG "icp multi B n=%d ST=%4x\n", n,
readw(devpriv->io_addr + ICP_MULTI_ADC_CSR));
#endif
udelay(1);
#ifdef ICP_MULTI_EXTDEBUG
printk(KERN_DEBUG "icp multi C n=%d ST=%4x\n", n,
readw(devpriv->io_addr + ICP_MULTI_ADC_CSR));
#endif
/* Wait for conversion to complete, or get fed up waiting */
timeout = 100;
while (timeout--) {
if (!(readw(devpriv->io_addr +
ICP_MULTI_ADC_CSR) & ADC_BSY))
goto conv_finish;
#ifdef ICP_MULTI_EXTDEBUG
if (!(timeout % 10))
printk(KERN_DEBUG
"icp multi D n=%d tm=%d ST=%4x\n", n,
timeout,
readw(devpriv->io_addr +
ICP_MULTI_ADC_CSR));
#endif
udelay(1);
}
/* If we reach here, a timeout has occurred */
comedi_error(dev, "A/D insn timeout");
/* Disable interrupt */
devpriv->IntEnable &= ~ADC_READY;
writew(devpriv->IntEnable, devpriv->io_addr + ICP_MULTI_INT_EN);
/* Clear interrupt status */
devpriv->IntStatus |= ADC_READY;
writew(devpriv->IntStatus,
devpriv->io_addr + ICP_MULTI_INT_STAT);
/* Clear data received */
data[n] = 0;
#ifdef ICP_MULTI_EXTDEBUG
printk(KERN_DEBUG
"icp multi EDBG: END: icp_multi_insn_read_ai(...) n=%d\n",
n);
#endif
return -ETIME;
conv_finish:
data[n] =
(readw(devpriv->io_addr + ICP_MULTI_AI) >> 4) & 0x0fff;
}
/* Disable interrupt */
devpriv->IntEnable &= ~ADC_READY;
writew(devpriv->IntEnable, devpriv->io_addr + ICP_MULTI_INT_EN);
/* Clear interrupt status */
devpriv->IntStatus |= ADC_READY;
writew(devpriv->IntStatus, devpriv->io_addr + ICP_MULTI_INT_STAT);
#ifdef ICP_MULTI_EXTDEBUG
printk(KERN_DEBUG
"icp multi EDBG: END: icp_multi_insn_read_ai(...) n=%d\n", n);
#endif
return n;
}
/*
==============================================================================
Name: icp_multi_insn_write_ao
Description:
This function writes a single analogue output.
Parameters:
struct comedi_device *dev Pointer to current device structure
struct comedi_subdevice *s Pointer to current subdevice structure
struct comedi_insn *insn Pointer to current comedi instruction
unsigned int *data Pointer to analogue output data
Returns:int Nmuber of instructions executed
==============================================================================
*/
static int icp_multi_insn_write_ao(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int n, chan, range, timeout;
#ifdef ICP_MULTI_EXTDEBUG
printk(KERN_DEBUG
"icp multi EDBG: BGN: icp_multi_insn_write_ao(...)\n");
#endif
/* Disable D/A conversion ready interrupt */
devpriv->IntEnable &= ~DAC_READY;
writew(devpriv->IntEnable, devpriv->io_addr + ICP_MULTI_INT_EN);
/* Clear interrupt status */
devpriv->IntStatus |= DAC_READY;
writew(devpriv->IntStatus, devpriv->io_addr + ICP_MULTI_INT_STAT);
/* Get channel number and range */
chan = CR_CHAN(insn->chanspec);
range = CR_RANGE(insn->chanspec);
/* Set up range and channel data */
/* Bit 4 = 1 : Bipolar */
/* Bit 5 = 0 : 5V */
/* Bit 5 = 1 : 10V */
/* Bits 8-9 : Channel number */
devpriv->DacCmdStatus &= 0xfccf;
devpriv->DacCmdStatus |= this_board->rangecode[range];
devpriv->DacCmdStatus |= (chan << 8);
writew(devpriv->DacCmdStatus, devpriv->io_addr + ICP_MULTI_DAC_CSR);
for (n = 0; n < insn->n; n++) {
/* Wait for analogue output data register to be
* ready for new data, or get fed up waiting */
timeout = 100;
while (timeout--) {
if (!(readw(devpriv->io_addr +
ICP_MULTI_DAC_CSR) & DAC_BSY))
goto dac_ready;
#ifdef ICP_MULTI_EXTDEBUG
if (!(timeout % 10))
printk(KERN_DEBUG
"icp multi A n=%d tm=%d ST=%4x\n", n,
timeout,
readw(devpriv->io_addr +
ICP_MULTI_DAC_CSR));
#endif
udelay(1);
}
/* If we reach here, a timeout has occurred */
comedi_error(dev, "D/A insn timeout");
/* Disable interrupt */
devpriv->IntEnable &= ~DAC_READY;
writew(devpriv->IntEnable, devpriv->io_addr + ICP_MULTI_INT_EN);
/* Clear interrupt status */
devpriv->IntStatus |= DAC_READY;
writew(devpriv->IntStatus,
devpriv->io_addr + ICP_MULTI_INT_STAT);
/* Clear data received */
devpriv->ao_data[chan] = 0;
#ifdef ICP_MULTI_EXTDEBUG
printk(KERN_DEBUG
"icp multi EDBG: END: icp_multi_insn_write_ao(...) n=%d\n",
n);
#endif
return -ETIME;
dac_ready:
/* Write data to analogue output data register */
writew(data[n], devpriv->io_addr + ICP_MULTI_AO);
/* Set DAC_ST bit to write the data to selected channel */
devpriv->DacCmdStatus |= DAC_ST;
writew(devpriv->DacCmdStatus,
devpriv->io_addr + ICP_MULTI_DAC_CSR);
devpriv->DacCmdStatus &= ~DAC_ST;
/* Save analogue output data */
devpriv->ao_data[chan] = data[n];
}
#ifdef ICP_MULTI_EXTDEBUG
printk(KERN_DEBUG
"icp multi EDBG: END: icp_multi_insn_write_ao(...) n=%d\n", n);
#endif
return n;
}
/*
==============================================================================
Name: icp_multi_insn_read_ao
Description:
This function reads a single analogue output.
Parameters:
struct comedi_device *dev Pointer to current device structure
struct comedi_subdevice *s Pointer to current subdevice structure
struct comedi_insn *insn Pointer to current comedi instruction
unsigned int *data Pointer to analogue output data
Returns:int Nmuber of instructions executed
==============================================================================
*/
static int icp_multi_insn_read_ao(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int n, chan;
/* Get channel number */
chan = CR_CHAN(insn->chanspec);
/* Read analogue outputs */
for (n = 0; n < insn->n; n++)
data[n] = devpriv->ao_data[chan];
return n;
}
/*
==============================================================================
Name: icp_multi_insn_bits_di
Description:
This function reads the digital inputs.
Parameters:
struct comedi_device *dev Pointer to current device structure
struct comedi_subdevice *s Pointer to current subdevice structure
struct comedi_insn *insn Pointer to current comedi instruction
unsigned int *data Pointer to analogue output data
Returns:int Nmuber of instructions executed
==============================================================================
*/
static int icp_multi_insn_bits_di(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
data[1] = readw(devpriv->io_addr + ICP_MULTI_DI);
return 2;
}
/*
==============================================================================
Name: icp_multi_insn_bits_do
Description:
This function writes the appropriate digital outputs.
Parameters:
struct comedi_device *dev Pointer to current device structure
struct comedi_subdevice *s Pointer to current subdevice structure
struct comedi_insn *insn Pointer to current comedi instruction
unsigned int *data Pointer to analogue output data
Returns:int Nmuber of instructions executed
==============================================================================
*/
static int icp_multi_insn_bits_do(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
#ifdef ICP_MULTI_EXTDEBUG
printk(KERN_DEBUG "icp multi EDBG: BGN: icp_multi_insn_bits_do(...)\n");
#endif
if (data[0]) {
s->state &= ~data[0];
s->state |= (data[0] & data[1]);
printk(KERN_DEBUG "Digital outputs = %4x \n", s->state);
writew(s->state, devpriv->io_addr + ICP_MULTI_DO);
}
data[1] = readw(devpriv->io_addr + ICP_MULTI_DI);
#ifdef ICP_MULTI_EXTDEBUG
printk(KERN_DEBUG "icp multi EDBG: END: icp_multi_insn_bits_do(...)\n");
#endif
return 2;
}
/*
==============================================================================
Name: icp_multi_insn_read_ctr
Description:
This function reads the specified counter.
Parameters:
struct comedi_device *dev Pointer to current device structure
struct comedi_subdevice *s Pointer to current subdevice structure
struct comedi_insn *insn Pointer to current comedi instruction
unsigned int *data Pointer to counter data
Returns:int Nmuber of instructions executed
==============================================================================
*/
static int icp_multi_insn_read_ctr(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
return 0;
}
/*
==============================================================================
Name: icp_multi_insn_write_ctr
Description:
This function write to the specified counter.
Parameters:
struct comedi_device *dev Pointer to current device structure
struct comedi_subdevice *s Pointer to current subdevice structure
struct comedi_insn *insn Pointer to current comedi instruction
unsigned int *data Pointer to counter data
Returns:int Nmuber of instructions executed
==============================================================================
*/
static int icp_multi_insn_write_ctr(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
return 0;
}
/*
==============================================================================
Name: interrupt_service_icp_multi
Description:
This function is the interrupt service routine for all
interrupts generated by the icp multi board.
Parameters:
int irq
void *d Pointer to current device
==============================================================================
*/
static irqreturn_t interrupt_service_icp_multi(int irq, void *d)
{
struct comedi_device *dev = d;
int int_no;
#ifdef ICP_MULTI_EXTDEBUG
printk(KERN_DEBUG
"icp multi EDBG: BGN: interrupt_service_icp_multi(%d,...)\n",
irq);
#endif
/* Is this interrupt from our board? */
int_no = readw(devpriv->io_addr + ICP_MULTI_INT_STAT) & Status_IRQ;
if (!int_no)
/* No, exit */
return IRQ_NONE;
#ifdef ICP_MULTI_EXTDEBUG
printk(KERN_DEBUG
"icp multi EDBG: interrupt_service_icp_multi() ST: %4x\n",
readw(devpriv->io_addr + ICP_MULTI_INT_STAT));
#endif
/* Determine which interrupt is active & handle it */
switch (int_no) {
case ADC_READY:
break;
case DAC_READY:
break;
case DOUT_ERROR:
break;
case DIN_STATUS:
break;
case CIE0:
break;
case CIE1:
break;
case CIE2:
break;
case CIE3:
break;
default:
break;
}
#ifdef ICP_MULTI_EXTDEBUG
printk(KERN_DEBUG
"icp multi EDBG: END: interrupt_service_icp_multi(...)\n");
#endif
return IRQ_HANDLED;
}
#if 0
/*
==============================================================================
Name: check_channel_list
Description:
This function checks if the channel list, provided by user
is built correctly
Parameters:
struct comedi_device *dev Pointer to current service structure
struct comedi_subdevice *s Pointer to current subdevice structure
unsigned int *chanlist Pointer to packed channel list
unsigned int n_chan Number of channels to scan
Returns:int 0 = failure
1 = success
==============================================================================
*/
static int check_channel_list(struct comedi_device *dev,
struct comedi_subdevice *s,
unsigned int *chanlist, unsigned int n_chan)
{
unsigned int i;
#ifdef ICP_MULTI_EXTDEBUG
printk(KERN_DEBUG
"icp multi EDBG: check_channel_list(...,%d)\n", n_chan);
#endif
/* Check that we at least have one channel to check */
if (n_chan < 1) {
comedi_error(dev, "range/channel list is empty!");
return 0;
}
/* Check all channels */
for (i = 0; i < n_chan; i++) {
/* Check that channel number is < maximum */
if (CR_AREF(chanlist[i]) == AREF_DIFF) {
if (CR_CHAN(chanlist[i]) > this_board->n_aichand) {
comedi_error(dev,
"Incorrect differential ai ch-nr");
return 0;
}
} else {
if (CR_CHAN(chanlist[i]) > this_board->n_aichan) {
comedi_error(dev,
"Incorrect ai channel number");
return 0;
}
}
}
return 1;
}
#endif
/*
==============================================================================
Name: setup_channel_list
Description:
This function sets the appropriate channel selection,
differential input mode and range bits in the ADC Command/
Status register.
Parameters:
struct comedi_device *dev Pointer to current service structure
struct comedi_subdevice *s Pointer to current subdevice structure
unsigned int *chanlist Pointer to packed channel list
unsigned int n_chan Number of channels to scan
Returns:Void
==============================================================================
*/
static void setup_channel_list(struct comedi_device *dev,
struct comedi_subdevice *s,
unsigned int *chanlist, unsigned int n_chan)
{
unsigned int i, range, chanprog;
unsigned int diff;
#ifdef ICP_MULTI_EXTDEBUG
printk(KERN_DEBUG
"icp multi EDBG: setup_channel_list(...,%d)\n", n_chan);
#endif
devpriv->act_chanlist_len = n_chan;
devpriv->act_chanlist_pos = 0;
for (i = 0; i < n_chan; i++) {
/* Get channel */
chanprog = CR_CHAN(chanlist[i]);
/* Determine if it is a differential channel (Bit 15 = 1) */
if (CR_AREF(chanlist[i]) == AREF_DIFF) {
diff = 1;
chanprog &= 0x0007;
} else {
diff = 0;
chanprog &= 0x000f;
}
/* Clear channel, range and input mode bits
* in A/D command/status register */
devpriv->AdcCmdStatus &= 0xf00f;
/* Set channel number and differential mode status bit */
if (diff) {
/* Set channel number, bits 9-11 & mode, bit 6 */
devpriv->AdcCmdStatus |= (chanprog << 9);
devpriv->AdcCmdStatus |= ADC_DI;
} else
/* Set channel number, bits 8-11 */
devpriv->AdcCmdStatus |= (chanprog << 8);
/* Get range for current channel */
range = this_board->rangecode[CR_RANGE(chanlist[i])];
/* Set range. bits 4-5 */
devpriv->AdcCmdStatus |= range;
/* Output channel, range, mode to ICP Multi */
writew(devpriv->AdcCmdStatus,
devpriv->io_addr + ICP_MULTI_ADC_CSR);
#ifdef ICP_MULTI_EXTDEBUG
printk(KERN_DEBUG
"GS: %2d. [%4x]=%4x %4x\n", i, chanprog, range,
devpriv->act_chanlist[i]);
#endif
}
}
/*
==============================================================================
Name: icp_multi_reset
Description:
This function resets the icp multi device to a 'safe' state
Parameters:
struct comedi_device *dev Pointer to current service structure
Returns:int 0 = success
==============================================================================
*/
static int icp_multi_reset(struct comedi_device *dev)
{
unsigned int i;
#ifdef ICP_MULTI_EXTDEBUG
printk(KERN_DEBUG
"icp_multi EDBG: BGN: icp_multi_reset(...)\n");
#endif
/* Clear INT enables and requests */
writew(0, devpriv->io_addr + ICP_MULTI_INT_EN);
writew(0x00ff, devpriv->io_addr + ICP_MULTI_INT_STAT);
if (this_board->n_aochan)
/* Set DACs to 0..5V range and 0V output */
for (i = 0; i < this_board->n_aochan; i++) {
devpriv->DacCmdStatus &= 0xfcce;
/* Set channel number */
devpriv->DacCmdStatus |= (i << 8);
/* Output 0V */
writew(0, devpriv->io_addr + ICP_MULTI_AO);
/* Set start conversion bit */
devpriv->DacCmdStatus |= DAC_ST;
/* Output to command / status register */
writew(devpriv->DacCmdStatus,
devpriv->io_addr + ICP_MULTI_DAC_CSR);
/* Delay to allow DAC time to recover */
udelay(1);
}
/* Digital outputs to 0 */
writew(0, devpriv->io_addr + ICP_MULTI_DO);
#ifdef ICP_MULTI_EXTDEBUG
printk(KERN_DEBUG
"icp multi EDBG: END: icp_multi_reset(...)\n");
#endif
return 0;
}
/*
==============================================================================
Name: icp_multi_attach
Description:
This function sets up all the appropriate data for the current
device.
Parameters:
struct comedi_device *dev Pointer to current device structure
struct comedi_devconfig *it Pointer to current device configuration
Returns:int 0 = success
==============================================================================
*/
static int icp_multi_attach(struct comedi_device *dev,
struct comedi_devconfig *it)
{
struct comedi_subdevice *s;
int ret, subdev, n_subdevices;
unsigned int irq;
struct pcilst_struct *card = NULL;
resource_size_t io_addr[5], iobase;
unsigned char pci_bus, pci_slot, pci_func;
printk(KERN_WARNING
"icp_multi EDBG: BGN: icp_multi_attach(...)\n");
/* Alocate private data storage space */
ret = alloc_private(dev, sizeof(struct icp_multi_private));
if (ret < 0)
return ret;
/* Initialise list of PCI cards in system, if not already done so */
if (pci_list_builded++ == 0) {
pci_card_list_init(PCI_VENDOR_ID_ICP,
#ifdef ICP_MULTI_EXTDEBUG
1
#else
0
#endif
);
}
printk(KERN_WARNING
"Anne's comedi%d: icp_multi: board=%s", dev->minor,
this_board->name);
card = select_and_alloc_pci_card(PCI_VENDOR_ID_ICP,
this_board->device_id, it->options[0],
it->options[1]);
if (card == NULL)
return -EIO;
devpriv->card = card;
if ((pci_card_data(card, &pci_bus, &pci_slot, &pci_func, &io_addr[0],
&irq)) < 0) {
printk(KERN_WARNING " - Can't get configuration data!\n");
return -EIO;
}
iobase = io_addr[2];
devpriv->phys_iobase = iobase;
printk(KERN_WARNING
", b:s:f=%d:%d:%d, io=0x%8llx \n", pci_bus, pci_slot, pci_func,
(unsigned long long)iobase);
devpriv->io_addr = ioremap(iobase, ICP_MULTI_SIZE);
if (devpriv->io_addr == NULL) {
printk(KERN_WARNING "ioremap failed.\n");
return -ENOMEM;
}
#ifdef ICP_MULTI_EXTDEBUG
printk(KERN_DEBUG
"0x%08llx mapped to %p, ", (unsigned long long)iobase,
devpriv->io_addr);
#endif
dev->board_name = this_board->name;
n_subdevices = 0;
if (this_board->n_aichan)
n_subdevices++;
if (this_board->n_aochan)
n_subdevices++;
if (this_board->n_dichan)
n_subdevices++;
if (this_board->n_dochan)
n_subdevices++;
if (this_board->n_ctrs)
n_subdevices++;
ret = alloc_subdevices(dev, n_subdevices);
if (ret < 0)
return ret;
icp_multi_reset(dev);
if (this_board->have_irq) {
if (irq) {
if (request_irq(irq, interrupt_service_icp_multi,
IRQF_SHARED, "Inova Icp Multi", dev)) {
printk(KERN_WARNING
"unable to allocate IRQ %u, DISABLING IT",
irq);
irq = 0; /* Can't use IRQ */
} else
printk(KERN_WARNING ", irq=%u", irq);
} else
printk(KERN_WARNING ", IRQ disabled");
} else
irq = 0;
dev->irq = irq;
printk(KERN_WARNING ".\n");
subdev = 0;
if (this_board->n_aichan) {
s = dev->subdevices + subdev;
dev->read_subdev = s;
s->type = COMEDI_SUBD_AI;
s->subdev_flags = SDF_READABLE | SDF_COMMON | SDF_GROUND;
if (this_board->n_aichand)
s->subdev_flags |= SDF_DIFF;
s->n_chan = this_board->n_aichan;
s->maxdata = this_board->ai_maxdata;
s->len_chanlist = this_board->n_aichan;
s->range_table = this_board->rangelist_ai;
s->insn_read = icp_multi_insn_read_ai;
subdev++;
}
if (this_board->n_aochan) {
s = dev->subdevices + subdev;
s->type = COMEDI_SUBD_AO;
s->subdev_flags = SDF_WRITABLE | SDF_GROUND | SDF_COMMON;
s->n_chan = this_board->n_aochan;
s->maxdata = this_board->ao_maxdata;
s->len_chanlist = this_board->n_aochan;
s->range_table = this_board->rangelist_ao;
s->insn_write = icp_multi_insn_write_ao;
s->insn_read = icp_multi_insn_read_ao;
subdev++;
}
if (this_board->n_dichan) {
s = dev->subdevices + subdev;
s->type = COMEDI_SUBD_DI;
s->subdev_flags = SDF_READABLE;
s->n_chan = this_board->n_dichan;
s->maxdata = 1;
s->len_chanlist = this_board->n_dichan;
s->range_table = &range_digital;
s->io_bits = 0;
s->insn_bits = icp_multi_insn_bits_di;
subdev++;
}
if (this_board->n_dochan) {
s = dev->subdevices + subdev;
s->type = COMEDI_SUBD_DO;
s->subdev_flags = SDF_WRITABLE | SDF_READABLE;
s->n_chan = this_board->n_dochan;
s->maxdata = 1;
s->len_chanlist = this_board->n_dochan;
s->range_table = &range_digital;
s->io_bits = (1 << this_board->n_dochan) - 1;
s->state = 0;
s->insn_bits = icp_multi_insn_bits_do;
subdev++;
}
if (this_board->n_ctrs) {
s = dev->subdevices + subdev;
s->type = COMEDI_SUBD_COUNTER;
s->subdev_flags = SDF_WRITABLE | SDF_GROUND | SDF_COMMON;
s->n_chan = this_board->n_ctrs;
s->maxdata = 0xffff;
s->len_chanlist = this_board->n_ctrs;
s->state = 0;
s->insn_read = icp_multi_insn_read_ctr;
s->insn_write = icp_multi_insn_write_ctr;
subdev++;
}
devpriv->valid = 1;
#ifdef ICP_MULTI_EXTDEBUG
printk(KERN_DEBUG "icp multi EDBG: END: icp_multi_attach(...)\n");
#endif
return 0;
}
/*
==============================================================================
Name: icp_multi_detach
Description:
This function releases all the resources used by the current
device.
Parameters:
struct comedi_device *dev Pointer to current device structure
Returns:int 0 = success
==============================================================================
*/
static int icp_multi_detach(struct comedi_device *dev)
{
if (dev->private)
if (devpriv->valid)
icp_multi_reset(dev);
if (dev->irq)
free_irq(dev->irq, dev);
if (dev->private && devpriv->io_addr)
iounmap(devpriv->io_addr);
if (dev->private && devpriv->card)
pci_card_free(devpriv->card);
if (--pci_list_builded == 0)
pci_card_list_cleanup(PCI_VENDOR_ID_ICP);
return 0;
}
MODULE_AUTHOR("Comedi http://www.comedi.org");
MODULE_DESCRIPTION("Comedi low-level driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
jshafer817/sailfish_kernel_hp_tenderloin30 | drivers/media/video/davinci/vpss.c | 8242 | 12136 | /*
* Copyright (C) 2009 Texas Instruments.
*
* 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.
*
* common vpss system module platform driver for all video drivers.
*/
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/spinlock.h>
#include <linux/compiler.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include <media/davinci/vpss.h>
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("VPSS Driver");
MODULE_AUTHOR("Texas Instruments");
/* DM644x defines */
#define DM644X_SBL_PCR_VPSS (4)
#define DM355_VPSSBL_INTSEL 0x10
#define DM355_VPSSBL_EVTSEL 0x14
/* vpss BL register offsets */
#define DM355_VPSSBL_CCDCMUX 0x1c
/* vpss CLK register offsets */
#define DM355_VPSSCLK_CLKCTRL 0x04
/* masks and shifts */
#define VPSS_HSSISEL_SHIFT 4
/*
* VDINT0 - vpss_int0, VDINT1 - vpss_int1, H3A - vpss_int4,
* IPIPE_INT1_SDR - vpss_int5
*/
#define DM355_VPSSBL_INTSEL_DEFAULT 0xff83ff10
/* VENCINT - vpss_int8 */
#define DM355_VPSSBL_EVTSEL_DEFAULT 0x4
#define DM365_ISP5_PCCR 0x04
#define DM365_ISP5_INTSEL1 0x10
#define DM365_ISP5_INTSEL2 0x14
#define DM365_ISP5_INTSEL3 0x18
#define DM365_ISP5_CCDCMUX 0x20
#define DM365_ISP5_PG_FRAME_SIZE 0x28
#define DM365_VPBE_CLK_CTRL 0x00
/*
* vpss interrupts. VDINT0 - vpss_int0, VDINT1 - vpss_int1,
* AF - vpss_int3
*/
#define DM365_ISP5_INTSEL1_DEFAULT 0x0b1f0100
/* AEW - vpss_int6, RSZ_INT_DMA - vpss_int5 */
#define DM365_ISP5_INTSEL2_DEFAULT 0x1f0a0f1f
/* VENC - vpss_int8 */
#define DM365_ISP5_INTSEL3_DEFAULT 0x00000015
/* masks and shifts for DM365*/
#define DM365_CCDC_PG_VD_POL_SHIFT 0
#define DM365_CCDC_PG_HD_POL_SHIFT 1
#define CCD_SRC_SEL_MASK (BIT_MASK(5) | BIT_MASK(4))
#define CCD_SRC_SEL_SHIFT 4
/* Different SoC platforms supported by this driver */
enum vpss_platform_type {
DM644X,
DM355,
DM365,
};
/*
* vpss operations. Depends on platform. Not all functions are available
* on all platforms. The api, first check if a functio is available before
* invoking it. In the probe, the function ptrs are initialized based on
* vpss name. vpss name can be "dm355_vpss", "dm644x_vpss" etc.
*/
struct vpss_hw_ops {
/* enable clock */
int (*enable_clock)(enum vpss_clock_sel clock_sel, int en);
/* select input to ccdc */
void (*select_ccdc_source)(enum vpss_ccdc_source_sel src_sel);
/* clear wbl overflow bit */
int (*clear_wbl_overflow)(enum vpss_wbl_sel wbl_sel);
};
/* vpss configuration */
struct vpss_oper_config {
__iomem void *vpss_regs_base0;
__iomem void *vpss_regs_base1;
enum vpss_platform_type platform;
spinlock_t vpss_lock;
struct vpss_hw_ops hw_ops;
};
static struct vpss_oper_config oper_cfg;
/* register access routines */
static inline u32 bl_regr(u32 offset)
{
return __raw_readl(oper_cfg.vpss_regs_base0 + offset);
}
static inline void bl_regw(u32 val, u32 offset)
{
__raw_writel(val, oper_cfg.vpss_regs_base0 + offset);
}
static inline u32 vpss_regr(u32 offset)
{
return __raw_readl(oper_cfg.vpss_regs_base1 + offset);
}
static inline void vpss_regw(u32 val, u32 offset)
{
__raw_writel(val, oper_cfg.vpss_regs_base1 + offset);
}
/* For DM365 only */
static inline u32 isp5_read(u32 offset)
{
return __raw_readl(oper_cfg.vpss_regs_base0 + offset);
}
/* For DM365 only */
static inline void isp5_write(u32 val, u32 offset)
{
__raw_writel(val, oper_cfg.vpss_regs_base0 + offset);
}
static void dm365_select_ccdc_source(enum vpss_ccdc_source_sel src_sel)
{
u32 temp = isp5_read(DM365_ISP5_CCDCMUX) & ~CCD_SRC_SEL_MASK;
/* if we are using pattern generator, enable it */
if (src_sel == VPSS_PGLPBK || src_sel == VPSS_CCDCPG)
temp |= 0x08;
temp |= (src_sel << CCD_SRC_SEL_SHIFT);
isp5_write(temp, DM365_ISP5_CCDCMUX);
}
static void dm355_select_ccdc_source(enum vpss_ccdc_source_sel src_sel)
{
bl_regw(src_sel << VPSS_HSSISEL_SHIFT, DM355_VPSSBL_CCDCMUX);
}
int vpss_select_ccdc_source(enum vpss_ccdc_source_sel src_sel)
{
if (!oper_cfg.hw_ops.select_ccdc_source)
return -EINVAL;
oper_cfg.hw_ops.select_ccdc_source(src_sel);
return 0;
}
EXPORT_SYMBOL(vpss_select_ccdc_source);
static int dm644x_clear_wbl_overflow(enum vpss_wbl_sel wbl_sel)
{
u32 mask = 1, val;
if (wbl_sel < VPSS_PCR_AEW_WBL_0 ||
wbl_sel > VPSS_PCR_CCDC_WBL_O)
return -EINVAL;
/* writing a 0 clear the overflow */
mask = ~(mask << wbl_sel);
val = bl_regr(DM644X_SBL_PCR_VPSS) & mask;
bl_regw(val, DM644X_SBL_PCR_VPSS);
return 0;
}
int vpss_clear_wbl_overflow(enum vpss_wbl_sel wbl_sel)
{
if (!oper_cfg.hw_ops.clear_wbl_overflow)
return -EINVAL;
return oper_cfg.hw_ops.clear_wbl_overflow(wbl_sel);
}
EXPORT_SYMBOL(vpss_clear_wbl_overflow);
/*
* dm355_enable_clock - Enable VPSS Clock
* @clock_sel: CLock to be enabled/disabled
* @en: enable/disable flag
*
* This is called to enable or disable a vpss clock
*/
static int dm355_enable_clock(enum vpss_clock_sel clock_sel, int en)
{
unsigned long flags;
u32 utemp, mask = 0x1, shift = 0;
switch (clock_sel) {
case VPSS_VPBE_CLOCK:
/* nothing since lsb */
break;
case VPSS_VENC_CLOCK_SEL:
shift = 2;
break;
case VPSS_CFALD_CLOCK:
shift = 3;
break;
case VPSS_H3A_CLOCK:
shift = 4;
break;
case VPSS_IPIPE_CLOCK:
shift = 5;
break;
case VPSS_CCDC_CLOCK:
shift = 6;
break;
default:
printk(KERN_ERR "dm355_enable_clock:"
" Invalid selector: %d\n", clock_sel);
return -EINVAL;
}
spin_lock_irqsave(&oper_cfg.vpss_lock, flags);
utemp = vpss_regr(DM355_VPSSCLK_CLKCTRL);
if (!en)
utemp &= ~(mask << shift);
else
utemp |= (mask << shift);
vpss_regw(utemp, DM355_VPSSCLK_CLKCTRL);
spin_unlock_irqrestore(&oper_cfg.vpss_lock, flags);
return 0;
}
static int dm365_enable_clock(enum vpss_clock_sel clock_sel, int en)
{
unsigned long flags;
u32 utemp, mask = 0x1, shift = 0, offset = DM365_ISP5_PCCR;
u32 (*read)(u32 offset) = isp5_read;
void(*write)(u32 val, u32 offset) = isp5_write;
switch (clock_sel) {
case VPSS_BL_CLOCK:
break;
case VPSS_CCDC_CLOCK:
shift = 1;
break;
case VPSS_H3A_CLOCK:
shift = 2;
break;
case VPSS_RSZ_CLOCK:
shift = 3;
break;
case VPSS_IPIPE_CLOCK:
shift = 4;
break;
case VPSS_IPIPEIF_CLOCK:
shift = 5;
break;
case VPSS_PCLK_INTERNAL:
shift = 6;
break;
case VPSS_PSYNC_CLOCK_SEL:
shift = 7;
break;
case VPSS_VPBE_CLOCK:
read = vpss_regr;
write = vpss_regw;
offset = DM365_VPBE_CLK_CTRL;
break;
case VPSS_VENC_CLOCK_SEL:
shift = 2;
read = vpss_regr;
write = vpss_regw;
offset = DM365_VPBE_CLK_CTRL;
break;
case VPSS_LDC_CLOCK:
shift = 3;
read = vpss_regr;
write = vpss_regw;
offset = DM365_VPBE_CLK_CTRL;
break;
case VPSS_FDIF_CLOCK:
shift = 4;
read = vpss_regr;
write = vpss_regw;
offset = DM365_VPBE_CLK_CTRL;
break;
case VPSS_OSD_CLOCK_SEL:
shift = 6;
read = vpss_regr;
write = vpss_regw;
offset = DM365_VPBE_CLK_CTRL;
break;
case VPSS_LDC_CLOCK_SEL:
shift = 7;
read = vpss_regr;
write = vpss_regw;
offset = DM365_VPBE_CLK_CTRL;
break;
default:
printk(KERN_ERR "dm365_enable_clock: Invalid selector: %d\n",
clock_sel);
return -1;
}
spin_lock_irqsave(&oper_cfg.vpss_lock, flags);
utemp = read(offset);
if (!en) {
mask = ~mask;
utemp &= (mask << shift);
} else
utemp |= (mask << shift);
write(utemp, offset);
spin_unlock_irqrestore(&oper_cfg.vpss_lock, flags);
return 0;
}
int vpss_enable_clock(enum vpss_clock_sel clock_sel, int en)
{
if (!oper_cfg.hw_ops.enable_clock)
return -EINVAL;
return oper_cfg.hw_ops.enable_clock(clock_sel, en);
}
EXPORT_SYMBOL(vpss_enable_clock);
void dm365_vpss_set_sync_pol(struct vpss_sync_pol sync)
{
int val = 0;
val = isp5_read(DM365_ISP5_CCDCMUX);
val |= (sync.ccdpg_hdpol << DM365_CCDC_PG_HD_POL_SHIFT);
val |= (sync.ccdpg_vdpol << DM365_CCDC_PG_VD_POL_SHIFT);
isp5_write(val, DM365_ISP5_CCDCMUX);
}
EXPORT_SYMBOL(dm365_vpss_set_sync_pol);
void dm365_vpss_set_pg_frame_size(struct vpss_pg_frame_size frame_size)
{
int current_reg = ((frame_size.hlpfr >> 1) - 1) << 16;
current_reg |= (frame_size.pplen - 1);
isp5_write(current_reg, DM365_ISP5_PG_FRAME_SIZE);
}
EXPORT_SYMBOL(dm365_vpss_set_pg_frame_size);
static int __init vpss_probe(struct platform_device *pdev)
{
struct resource *r1, *r2;
char *platform_name;
int status;
if (!pdev->dev.platform_data) {
dev_err(&pdev->dev, "no platform data\n");
return -ENOENT;
}
platform_name = pdev->dev.platform_data;
if (!strcmp(platform_name, "dm355_vpss"))
oper_cfg.platform = DM355;
else if (!strcmp(platform_name, "dm365_vpss"))
oper_cfg.platform = DM365;
else if (!strcmp(platform_name, "dm644x_vpss"))
oper_cfg.platform = DM644X;
else {
dev_err(&pdev->dev, "vpss driver not supported on"
" this platform\n");
return -ENODEV;
}
dev_info(&pdev->dev, "%s vpss probed\n", platform_name);
r1 = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!r1)
return -ENOENT;
r1 = request_mem_region(r1->start, resource_size(r1), r1->name);
if (!r1)
return -EBUSY;
oper_cfg.vpss_regs_base0 = ioremap(r1->start, resource_size(r1));
if (!oper_cfg.vpss_regs_base0) {
status = -EBUSY;
goto fail1;
}
if (oper_cfg.platform == DM355 || oper_cfg.platform == DM365) {
r2 = platform_get_resource(pdev, IORESOURCE_MEM, 1);
if (!r2) {
status = -ENOENT;
goto fail2;
}
r2 = request_mem_region(r2->start, resource_size(r2), r2->name);
if (!r2) {
status = -EBUSY;
goto fail2;
}
oper_cfg.vpss_regs_base1 = ioremap(r2->start,
resource_size(r2));
if (!oper_cfg.vpss_regs_base1) {
status = -EBUSY;
goto fail3;
}
}
if (oper_cfg.platform == DM355) {
oper_cfg.hw_ops.enable_clock = dm355_enable_clock;
oper_cfg.hw_ops.select_ccdc_source = dm355_select_ccdc_source;
/* Setup vpss interrupts */
bl_regw(DM355_VPSSBL_INTSEL_DEFAULT, DM355_VPSSBL_INTSEL);
bl_regw(DM355_VPSSBL_EVTSEL_DEFAULT, DM355_VPSSBL_EVTSEL);
} else if (oper_cfg.platform == DM365) {
oper_cfg.hw_ops.enable_clock = dm365_enable_clock;
oper_cfg.hw_ops.select_ccdc_source = dm365_select_ccdc_source;
/* Setup vpss interrupts */
isp5_write(DM365_ISP5_INTSEL1_DEFAULT, DM365_ISP5_INTSEL1);
isp5_write(DM365_ISP5_INTSEL2_DEFAULT, DM365_ISP5_INTSEL2);
isp5_write(DM365_ISP5_INTSEL3_DEFAULT, DM365_ISP5_INTSEL3);
} else
oper_cfg.hw_ops.clear_wbl_overflow = dm644x_clear_wbl_overflow;
spin_lock_init(&oper_cfg.vpss_lock);
dev_info(&pdev->dev, "%s vpss probe success\n", platform_name);
return 0;
fail3:
release_mem_region(r2->start, resource_size(r2));
fail2:
iounmap(oper_cfg.vpss_regs_base0);
fail1:
release_mem_region(r1->start, resource_size(r1));
return status;
}
static int __devexit vpss_remove(struct platform_device *pdev)
{
struct resource *res;
iounmap(oper_cfg.vpss_regs_base0);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(res->start, resource_size(res));
if (oper_cfg.platform == DM355 || oper_cfg.platform == DM365) {
iounmap(oper_cfg.vpss_regs_base1);
res = platform_get_resource(pdev, IORESOURCE_MEM, 1);
release_mem_region(res->start, resource_size(res));
}
return 0;
}
static struct platform_driver vpss_driver = {
.driver = {
.name = "vpss",
.owner = THIS_MODULE,
},
.remove = __devexit_p(vpss_remove),
.probe = vpss_probe,
};
static void vpss_exit(void)
{
platform_driver_unregister(&vpss_driver);
}
static int __init vpss_init(void)
{
return platform_driver_register(&vpss_driver);
}
subsys_initcall(vpss_init);
module_exit(vpss_exit);
| gpl-2.0 |
davidlt/glibc-slc6 | localedata/tests-mbwc/dat_iswpunct.c | 51 | 5575 | /*
* TEST SUITE FOR MB/WC FUNCTIONS IN C LIBRARY
*
* FILE: dat_iswpunct.c
*
* ISW*: int iswpunct (wint_t wc);
*/
#include "dat_isw-funcs.h"
TST_ISW_LOC (PUNCT, punct) = {
{ TST_ISW_REC (de, punct)
{
{ { 0x0080 }, { 0,1,0 } }, /* CTRL */
{ { 0x009F }, { 0,1,0 } }, /* CTRL */
#ifdef SHOJI_IS_RIGHT
{ { 0x00A0 }, { 0,1,0 } }, /* NB SPACE */
#else
{ { 0x00A0 }, { 0,0,0 } }, /* NB SPACE */
#endif
{ { 0x00A1 }, { 0,0,0 } }, /* UD ! */
{ { 0x00B0 }, { 0,0,0 } }, /* Degree */
{ { 0x00B1 }, { 0,0,0 } }, /* +- sign */
{ { 0x00B2 }, { 0,0,0 } }, /* SUP 2 */
{ { 0x00B3 }, { 0,0,0 } }, /* SUP 3 */
{ { 0x00B4 }, { 0,0,0 } }, /* ACUTE */
{ { 0x00B8 }, { 0,0,0 } }, /* CEDILLA */
{ { 0x00B9 }, { 0,0,0 } }, /* SUP 1 */
{ { 0x00BB }, { 0,0,0 } }, /* >> */
{ { 0x00BC }, { 0,0,0 } }, /* 1/4 */
{ { 0x00BD }, { 0,0,0 } }, /* 1/2 */
{ { 0x00BE }, { 0,0,0 } }, /* 3/4 */
{ { 0x00BF }, { 0,0,0 } }, /* UD ? */
{ { 0x00C0 }, { 0,1,0 } }, /* A Grave */
{ { 0x00D6 }, { 0,1,0 } }, /* O dia */
{ { 0x00D7 }, { 0,0,0 } }, /* multipl. */
{ { 0x00D8 }, { 0,1,0 } }, /* O stroke */
{ { 0x00DF }, { 0,1,0 } }, /* small Sh */
{ { 0x00E0 }, { 0,1,0 } }, /* a grave */
{ { 0x00F6 }, { 0,1,0 } }, /* o dia */
{ { 0x00F7 }, { 0,0,0 } }, /* division */
{ { 0x00F8 }, { 0,1,0 } }, /* o stroke */
{ { 0x00FF }, { 0,1,0 } }, /* y dia */
{ .is_last = 1 } /* Last element. */
}
},
{ TST_ISW_REC (enUS, punct)
{
{ { WEOF }, { 0,1,0 } }, /* 01 */
{ { 0x0000 }, { 0,1,0 } },
{ { 0x001F }, { 0,1,0 } },
{ { 0x0020 }, { 0,1,0 } },
{ { 0x0021 }, { 0,0,0 } },
{ { 0x002F }, { 0,0,0 } },
{ { 0x0030 }, { 0,1,0 } },
{ { 0x0039 }, { 0,1,0 } },
{ { 0x003A }, { 0,0,0 } },
{ { 0x0040 }, { 0,0,0 } },
{ { 0x0041 }, { 0,1,0 } },
{ { 0x005A }, { 0,1,0 } },
{ { 0x005B }, { 0,0,0 } },
{ { 0x0060 }, { 0,0,0 } },
{ { 0x0061 }, { 0,1,0 } },
{ { 0x007A }, { 0,1,0 } },
{ { 0x007B }, { 0,0,0 } },
{ { 0x007E }, { 0,0,0 } },
{ { 0x007F }, { 0,1,0 } },
{ { 0x0080 }, { 0,1,0 } }, /* 20 */
{ .is_last = 1 } /* Last element. */
}
},
{ TST_ISW_REC (eucJP, punct)
{
{ { 0x3000 }, { 0,1,0 } }, /* IDEO. SPACE */
#ifdef SHOJI_IS_RIGHT
{ { 0x3020 }, { 0,1,0 } }, /* POSTAL MARK FACE */
#else
{ { 0x3020 }, { 0,0,0 } }, /* POSTAL MARK FACE */
#endif
{ { 0x3029 }, { 0,1,0 } }, /* Hangzhou NUM9 */
#ifdef SHOJI_IS_RIGHT
{ { 0x302F }, { 0,1,0 } }, /* Diacritics(Hangul) */
{ { 0x3037 }, { 0,1,0 } }, /* Separator Symbol */
{ { 0x303F }, { 0,1,0 } }, /* IDEO. HALF SPACE */
#else
{ { 0x302F }, { 0,0,0 } }, /* Diacritics(Hangul) */
{ { 0x3037 }, { 0,0,0 } }, /* Separator Symbol */
{ { 0x303F }, { 0,0,0 } }, /* IDEO. HALF SPACE */
#endif
{ { 0x3041 }, { 0,1,0 } }, /* HIRAGANA a */
{ { 0x3094 }, { 0,1,0 } }, /* HIRAGANA u" */
#ifdef SHOJI_IS_RIGHT
{ { 0x3099 }, { 0,1,0 } }, /* SOUND MARK */
#else
{ { 0x3099 }, { 0,0,0 } }, /* SOUND MARK */
#endif
{ { 0x309E }, { 0,1,0 } }, /* ITERATION MARK */ /* 10 */
{ { 0x30A1 }, { 0,1,0 } }, /* KATAKANA a */
{ { 0x30FA }, { 0,1,0 } }, /* KATAKANA wo" */
{ { 0x30FB }, { 0,0,0 } }, /* KATAKANA MID.DOT */
{ { 0x30FE }, { 0,1,0 } }, /* KATAKANA ITERATION */
#ifdef SHOJI_IS_RIGHT
{ { 0x3191 }, { 0,1,0 } }, /* KANBUN REV.MARK */
{ { 0x3243 }, { 0,1,0 } }, /* IDEO. MARK (reach) */
{ { 0x32CB }, { 0,1,0 } }, /* IDEO.TEL.SYM.DEC12 */
{ { 0x32FE }, { 0,1,0 } }, /* MARU KATAKANA wo */
{ { 0x33FE }, { 0,1,0 } }, /* CJK IDEO.TEL.31th */
#else
{ { 0x3191 }, { 0,0,0 } }, /* KANBUN REV.MARK */
{ { 0x3243 }, { 0,0,0 } }, /* IDEO. MARK (reach) */
{ { 0x32CB }, { 0,0,0 } }, /* IDEO.TEL.SYM.DEC12 */
{ { 0x32FE }, { 0,0,0 } }, /* MARU KATAKANA wo */
{ { 0x33FE }, { 0,0,0 } }, /* CJK IDEO.TEL.31th */
#endif
{ { 0x4E00 }, { 0,1,0 } }, /* CJK UNI.IDEO. */ /* 20 */
{ { 0x4E05 }, { 0,1,0 } }, /* CJK UNI.IDEO. */
{ { 0x4E06 }, { 0,1,0 } }, /* CJK UNI.IDEO.NON-J */
{ { 0x4E07 }, { 0,1,0 } }, /* CJK UNI.IDEO. */
{ { 0x4FFF }, { 0,1,0 } }, /* CJK UNI.IDEO. */
{ { 0x9000 }, { 0,1,0 } }, /* CJK UNI.IDEO. */
{ { 0x9006 }, { 0,1,0 } }, /* CJK UNI.IDEO. */
{ { 0x9007 }, { 0,1,0 } }, /* CJK UNI.IDEO.NON-J */
{ { 0x9FA4 }, { 0,1,0 } }, /* CJK UNI.IDEO.NON-J */
{ { 0x9FA5 }, { 0,1,0 } }, /* CJK UNI.IDEO. */
#ifdef SHOJI_IS_RIGHT
{ { 0xFE4F }, { 0,1,0 } }, /* CJK UNI.IDEO. */ /* 30 */
#else
{ { 0xFE4F }, { 0,0,0 } }, /* CJK UNI.IDEO. */ /* 30 */
#endif
{ { 0xFF0F }, { 0,0,0 } }, /* FULL SLASH */
{ { 0xFF19 }, { 0,1,0 } }, /* FULL 9 */
{ { 0xFF20 }, { 0,0,0 } }, /* FULL @ */
{ { 0xFF3A }, { 0,1,0 } }, /* FULL Z */
{ { 0xFF40 }, { 0,0,0 } }, /* FULL GRAVE ACC. */
{ { 0xFF5A }, { 0,1,0 } }, /* FULL z */
{ { 0xFF5E }, { 0,0,0 } }, /* FULL ~ (tilde) */
{ { 0xFF61 }, { 0,0,0 } }, /* HALF IDEO.STOP. . */
{ { 0xFF65 }, { 0,0,0 } }, /* HALF KATA MID.DOT */
{ { 0xFF66 }, { 0,1,0 } }, /* HALF KATA WO */ /* 40 */
{ { 0xFF6F }, { 0,1,0 } }, /* HALF KATA tu */
{ { 0xFF70 }, { 0,1,0 } }, /* HALF KATA PL - */
{ { 0xFF71 }, { 0,1,0 } }, /* HALF KATA A */
{ { 0xFF9E }, { 0,1,0 } }, /* HALF KATA MI */
{ .is_last = 1 } /* Last element. */
}
},
{ TST_ISW_REC (end, punct) }
};
| gpl-2.0 |
vishal-android-freak/Super_Fusion | net/bluetooth/hci_conn.c | 51 | 17481 | /*
BlueZ - Bluetooth protocol stack for Linux
Copyright (c) 2000-2001, 2010, Code Aurora Forum. All rights reserved.
Written 2000,2001 by Maxim Krasnyansky <maxk@qualcomm.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;
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 OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
CLAIM, OR 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.
ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
SOFTWARE IS DISCLAIMED.
*/
/* Bluetooth HCI connection handling. */
#include <linux/module.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/poll.h>
#include <linux/fcntl.h>
#include <linux/init.h>
#include <linux/skbuff.h>
#include <linux/interrupt.h>
#include <linux/notifier.h>
#include <net/sock.h>
#include <asm/system.h>
#include <asm/uaccess.h>
#include <asm/unaligned.h>
#include <net/bluetooth/bluetooth.h>
#include <net/bluetooth/hci_core.h>
void hci_acl_connect(struct hci_conn *conn)
{
struct hci_dev *hdev = conn->hdev;
struct inquiry_entry *ie;
struct hci_cp_create_conn cp;
BT_DBG("%p", conn);
conn->state = BT_CONNECT;
conn->out = 1;
conn->link_mode = HCI_LM_MASTER;
conn->attempt++;
conn->link_policy = hdev->link_policy;
memset(&cp, 0, sizeof(cp));
bacpy(&cp.bdaddr, &conn->dst);
cp.pscan_rep_mode = 0x02;
if ((ie = hci_inquiry_cache_lookup(hdev, &conn->dst))) {
if (inquiry_entry_age(ie) <= INQUIRY_ENTRY_AGE_MAX) {
cp.pscan_rep_mode = ie->data.pscan_rep_mode;
cp.pscan_mode = ie->data.pscan_mode;
cp.clock_offset = ie->data.clock_offset |
cpu_to_le16(0x8000);
}
memcpy(conn->dev_class, ie->data.dev_class, 3);
conn->ssp_mode = ie->data.ssp_mode;
}
cp.pkt_type = cpu_to_le16(conn->pkt_type);
if (lmp_rswitch_capable(hdev) && !(hdev->link_mode & HCI_LM_MASTER))
cp.role_switch = 0x01;
else
cp.role_switch = 0x00;
hci_send_cmd(hdev, HCI_OP_CREATE_CONN, sizeof(cp), &cp);
}
static void hci_acl_connect_cancel(struct hci_conn *conn)
{
struct hci_cp_create_conn_cancel cp;
BT_DBG("%p", conn);
if (conn->hdev->hci_ver < 2)
return;
bacpy(&cp.bdaddr, &conn->dst);
hci_send_cmd(conn->hdev, HCI_OP_CREATE_CONN_CANCEL, sizeof(cp), &cp);
}
void hci_acl_disconn(struct hci_conn *conn, __u8 reason)
{
struct hci_cp_disconnect cp;
BT_DBG("%p", conn);
conn->state = BT_DISCONN;
cp.handle = cpu_to_le16(conn->handle);
cp.reason = reason;
hci_send_cmd(conn->hdev, HCI_OP_DISCONNECT, sizeof(cp), &cp);
}
void hci_add_sco(struct hci_conn *conn, __u16 handle)
{
struct hci_dev *hdev = conn->hdev;
struct hci_cp_add_sco cp;
struct hci_conn *acl = conn->link;
BT_DBG("%p", conn);
if (acl->mode == HCI_CM_SNIFF &&
test_bit(HCI_CONN_MODE_CHANGE_PEND, &acl->pend)) {
set_bit(HCI_CONN_SCO_PEND, &conn->pend);
return;
}
clear_bit(HCI_CONN_SCO_PEND, &conn->pend);
conn->state = BT_CONNECT;
conn->out = 1;
conn->attempt++;
cp.handle = cpu_to_le16(handle);
cp.pkt_type = cpu_to_le16(conn->pkt_type);
hci_send_cmd(hdev, HCI_OP_ADD_SCO, sizeof(cp), &cp);
}
void hci_setup_sync(struct hci_conn *conn, __u16 handle)
{
struct hci_dev *hdev = conn->hdev;
struct hci_cp_setup_sync_conn cp;
struct hci_conn *acl = conn->link;
BT_DBG("%p", conn);
if (acl->mode == HCI_CM_SNIFF &&
test_bit(HCI_CONN_MODE_CHANGE_PEND, &acl->pend)) {
set_bit(HCI_CONN_SCO_PEND, &conn->pend);
return;
}
clear_bit(HCI_CONN_SCO_PEND, &conn->pend);
conn->state = BT_CONNECT;
conn->out = 1;
conn->attempt++;
cp.handle = cpu_to_le16(handle);
cp.pkt_type = cpu_to_le16(conn->pkt_type);
cp.tx_bandwidth = cpu_to_le32(0x00001f40);
cp.rx_bandwidth = cpu_to_le32(0x00001f40);
cp.max_latency = cpu_to_le16(0xffff);
cp.voice_setting = cpu_to_le16(hdev->voice_setting);
cp.retrans_effort = 0xff;
hci_send_cmd(hdev, HCI_OP_SETUP_SYNC_CONN, sizeof(cp), &cp);
}
static void hci_conn_timeout(unsigned long arg)
{
struct hci_conn *conn = (void *) arg;
struct hci_dev *hdev = conn->hdev;
__u8 reason;
BT_DBG("conn %p state %d", conn, conn->state);
if (atomic_read(&conn->refcnt))
return;
hci_dev_lock(hdev);
switch (conn->state) {
case BT_CONNECT:
case BT_CONNECT2:
if (conn->type == ACL_LINK && conn->out)
hci_acl_connect_cancel(conn);
break;
case BT_CONFIG:
case BT_CONNECTED:
if (conn->type != ACL_LINK) {
struct hci_conn *acl = conn->link;
if (acl) {
acl->power_save = 1;
hci_conn_enter_active_mode(acl);
}
}
reason = hci_proto_disconn_ind(conn);
hci_acl_disconn(conn, reason);
break;
default:
conn->state = BT_CLOSED;
break;
}
hci_dev_unlock(hdev);
}
static void hci_conn_idle(unsigned long arg)
{
struct hci_conn *conn = (void *) arg;
BT_DBG("conn %p mode %d", conn, conn->mode);
hci_conn_enter_sniff_mode(conn);
}
struct hci_conn *hci_conn_add(struct hci_dev *hdev, int type,
__u16 pkt_type, bdaddr_t *dst)
{
struct hci_conn *conn;
BT_DBG("%s dst %s", hdev->name, batostr(dst));
conn = kzalloc(sizeof(struct hci_conn), GFP_ATOMIC);
if (!conn)
return NULL;
bacpy(&conn->dst, dst);
conn->hdev = hdev;
conn->type = type;
conn->mode = HCI_CM_ACTIVE;
conn->state = BT_OPEN;
conn->auth_type = HCI_AT_GENERAL_BONDING;
conn->power_save = 1;
conn->disc_timeout = HCI_DISCONN_TIMEOUT;
switch (type) {
case ACL_LINK:
conn->pkt_type = hdev->pkt_type & ACL_PTYPE_MASK;
break;
case SCO_LINK:
if (!pkt_type)
pkt_type = SCO_ESCO_MASK;
case ESCO_LINK:
if (!pkt_type)
pkt_type = ALL_ESCO_MASK;
if (lmp_esco_capable(hdev)) {
/* HCI Setup Synchronous Connection Command uses
reverse logic on the EDR_ESCO_MASK bits */
conn->pkt_type = (pkt_type ^ EDR_ESCO_MASK) &
hdev->esco_type;
} else {
/* Legacy HCI Add Sco Connection Command uses a
shifted bitmask */
conn->pkt_type = (pkt_type << 5) & hdev->pkt_type &
SCO_PTYPE_MASK;
}
break;
}
skb_queue_head_init(&conn->data_q);
setup_timer(&conn->disc_timer, hci_conn_timeout, (unsigned long)conn);
setup_timer(&conn->idle_timer, hci_conn_idle, (unsigned long)conn);
atomic_set(&conn->refcnt, 0);
hci_dev_hold(hdev);
tasklet_disable(&hdev->tx_task);
hci_conn_hash_add(hdev, conn);
if (hdev->notify)
hdev->notify(hdev, HCI_NOTIFY_CONN_ADD);
atomic_set(&conn->devref, 0);
hci_conn_init_sysfs(conn);
tasklet_enable(&hdev->tx_task);
return conn;
}
int hci_conn_del(struct hci_conn *conn)
{
struct hci_dev *hdev = conn->hdev;
BT_DBG("%s conn %p handle %d", hdev->name, conn, conn->handle);
del_timer(&conn->idle_timer);
del_timer(&conn->disc_timer);
if (conn->type == ACL_LINK) {
struct hci_conn *sco = conn->link;
if (sco)
sco->link = NULL;
/* Unacked frames */
hdev->acl_cnt += conn->sent;
} else {
struct hci_conn *acl = conn->link;
if (acl) {
acl->link = NULL;
hci_conn_put(acl);
}
}
tasklet_disable(&hdev->tx_task);
hci_conn_hash_del(hdev, conn);
if (hdev->notify)
hdev->notify(hdev, HCI_NOTIFY_CONN_DEL);
tasklet_enable(&hdev->tx_task);
skb_queue_purge(&conn->data_q);
hci_conn_put_device(conn);
hci_dev_put(hdev);
return 0;
}
struct hci_dev *hci_get_route(bdaddr_t *dst, bdaddr_t *src)
{
int use_src = bacmp(src, BDADDR_ANY);
struct hci_dev *hdev = NULL;
struct list_head *p;
BT_DBG("%s -> %s", batostr(src), batostr(dst));
read_lock_bh(&hci_dev_list_lock);
list_for_each(p, &hci_dev_list) {
struct hci_dev *d = list_entry(p, struct hci_dev, list);
if (!test_bit(HCI_UP, &d->flags) || test_bit(HCI_RAW, &d->flags))
continue;
/* Simple routing:
* No source address - find interface with bdaddr != dst
* Source address - find interface with bdaddr == src
*/
if (use_src) {
if (!bacmp(&d->bdaddr, src)) {
hdev = d; break;
}
} else {
if (bacmp(&d->bdaddr, dst)) {
hdev = d; break;
}
}
}
if (hdev)
hdev = hci_dev_hold(hdev);
read_unlock_bh(&hci_dev_list_lock);
return hdev;
}
EXPORT_SYMBOL(hci_get_route);
/* Create SCO or ACL connection.
* Device _must_ be locked */
struct hci_conn *hci_connect(struct hci_dev *hdev, int type,
__u16 pkt_type, bdaddr_t *dst,
__u8 sec_level, __u8 auth_type)
{
struct hci_conn *acl;
struct hci_conn *sco;
BT_DBG("%s dst %s", hdev->name, batostr(dst));
if (!(acl = hci_conn_hash_lookup_ba(hdev, ACL_LINK, dst))) {
if (!(acl = hci_conn_add(hdev, ACL_LINK, 0, dst)))
return NULL;
}
hci_conn_hold(acl);
if (acl->state == BT_OPEN || acl->state == BT_CLOSED) {
acl->sec_level = sec_level;
acl->auth_type = auth_type;
hci_acl_connect(acl);
}
if (type == ACL_LINK)
return acl;
if (!(sco = hci_conn_hash_lookup_ba(hdev, type, dst))) {
if (!(sco = hci_conn_add(hdev, type, pkt_type, dst))) {
hci_conn_put(acl);
return NULL;
}
}
acl->link = sco;
sco->link = acl;
hci_conn_hold(sco);
if (acl->state == BT_CONNECTED &&
(sco->state == BT_OPEN || sco->state == BT_CLOSED)) {
acl->power_save = 1;
hci_conn_enter_active_mode(acl);
if (lmp_esco_capable(hdev))
hci_setup_sync(sco, acl->handle);
else
hci_add_sco(sco, acl->handle);
}
return sco;
}
EXPORT_SYMBOL(hci_connect);
/* Check link security requirement */
int hci_conn_check_link_mode(struct hci_conn *conn)
{
BT_DBG("conn %p", conn);
if (conn->ssp_mode > 0 && conn->hdev->ssp_mode > 0 &&
!(conn->link_mode & HCI_LM_ENCRYPT))
return 0;
return 1;
}
EXPORT_SYMBOL(hci_conn_check_link_mode);
/* Authenticate remote device */
static int hci_conn_auth(struct hci_conn *conn, __u8 sec_level, __u8 auth_type)
{
BT_DBG("conn %p", conn);
if (sec_level > conn->sec_level)
conn->sec_level = sec_level;
else if (conn->link_mode & HCI_LM_AUTH)
return 1;
conn->auth_type = auth_type;
if (!test_and_set_bit(HCI_CONN_AUTH_PEND, &conn->pend)) {
struct hci_cp_auth_requested cp;
cp.handle = cpu_to_le16(conn->handle);
hci_send_cmd(conn->hdev, HCI_OP_AUTH_REQUESTED,
sizeof(cp), &cp);
}
return 0;
}
/* Enable security */
int hci_conn_security(struct hci_conn *conn, __u8 sec_level, __u8 auth_type)
{
BT_DBG("conn %p", conn);
if (sec_level == BT_SECURITY_SDP)
return 1;
if (sec_level == BT_SECURITY_LOW &&
(!conn->ssp_mode || !conn->hdev->ssp_mode))
return 1;
if (conn->link_mode & HCI_LM_ENCRYPT)
return hci_conn_auth(conn, sec_level, auth_type);
if (test_and_set_bit(HCI_CONN_ENCRYPT_PEND, &conn->pend))
return 0;
if (hci_conn_auth(conn, sec_level, auth_type)) {
struct hci_cp_set_conn_encrypt cp;
cp.handle = cpu_to_le16(conn->handle);
cp.encrypt = 1;
hci_send_cmd(conn->hdev, HCI_OP_SET_CONN_ENCRYPT,
sizeof(cp), &cp);
}
return 0;
}
EXPORT_SYMBOL(hci_conn_security);
/* Change link key */
int hci_conn_change_link_key(struct hci_conn *conn)
{
BT_DBG("conn %p", conn);
if (!test_and_set_bit(HCI_CONN_AUTH_PEND, &conn->pend)) {
struct hci_cp_change_conn_link_key cp;
cp.handle = cpu_to_le16(conn->handle);
hci_send_cmd(conn->hdev, HCI_OP_CHANGE_CONN_LINK_KEY,
sizeof(cp), &cp);
}
return 0;
}
EXPORT_SYMBOL(hci_conn_change_link_key);
/* Switch role */
int hci_conn_switch_role(struct hci_conn *conn, __u8 role)
{
BT_DBG("conn %p", conn);
if (!role && conn->link_mode & HCI_LM_MASTER)
return 1;
if (!test_and_set_bit(HCI_CONN_RSWITCH_PEND, &conn->pend)) {
struct hci_cp_switch_role cp;
bacpy(&cp.bdaddr, &conn->dst);
cp.role = role;
hci_send_cmd(conn->hdev, HCI_OP_SWITCH_ROLE, sizeof(cp), &cp);
}
return 0;
}
EXPORT_SYMBOL(hci_conn_switch_role);
/* Enter active mode */
void hci_conn_enter_active_mode(struct hci_conn *conn)
{
struct hci_dev *hdev = conn->hdev;
BT_DBG("conn %p mode %d", conn, conn->mode);
if (test_bit(HCI_RAW, &hdev->flags))
return;
if (conn->mode != HCI_CM_SNIFF /* || !conn->power_save */)
goto timer;
if (!test_and_set_bit(HCI_CONN_MODE_CHANGE_PEND, &conn->pend)) {
struct hci_cp_exit_sniff_mode cp;
cp.handle = cpu_to_le16(conn->handle);
hci_send_cmd(hdev, HCI_OP_EXIT_SNIFF_MODE, sizeof(cp), &cp);
}
timer:
if (hdev->idle_timeout > 0)
mod_timer(&conn->idle_timer,
jiffies + msecs_to_jiffies(hdev->idle_timeout));
}
/* Enter sniff mode */
void hci_conn_enter_sniff_mode(struct hci_conn *conn)
{
struct hci_dev *hdev = conn->hdev;
BT_DBG("conn %p mode %d", conn, conn->mode);
if (test_bit(HCI_RAW, &hdev->flags))
return;
if (!lmp_sniff_capable(hdev) || !lmp_sniff_capable(conn))
return;
if (conn->mode != HCI_CM_ACTIVE || !(conn->link_policy & HCI_LP_SNIFF))
return;
if (lmp_sniffsubr_capable(hdev) && lmp_sniffsubr_capable(conn)) {
struct hci_cp_sniff_subrate cp;
cp.handle = cpu_to_le16(conn->handle);
cp.max_latency = cpu_to_le16(0);
cp.min_remote_timeout = cpu_to_le16(0);
cp.min_local_timeout = cpu_to_le16(0);
hci_send_cmd(hdev, HCI_OP_SNIFF_SUBRATE, sizeof(cp), &cp);
}
if (!test_and_set_bit(HCI_CONN_MODE_CHANGE_PEND, &conn->pend)) {
struct hci_cp_sniff_mode cp;
cp.handle = cpu_to_le16(conn->handle);
cp.max_interval = cpu_to_le16(hdev->sniff_max_interval);
cp.min_interval = cpu_to_le16(hdev->sniff_min_interval);
cp.attempt = cpu_to_le16(4);
cp.timeout = cpu_to_le16(1);
hci_send_cmd(hdev, HCI_OP_SNIFF_MODE, sizeof(cp), &cp);
}
}
/* Drop all connection on the device */
void hci_conn_hash_flush(struct hci_dev *hdev)
{
struct hci_conn_hash *h = &hdev->conn_hash;
struct list_head *p;
BT_DBG("hdev %s", hdev->name);
p = h->list.next;
while (p != &h->list) {
struct hci_conn *c;
c = list_entry(p, struct hci_conn, list);
p = p->next;
c->state = BT_CLOSED;
hci_proto_disconn_cfm(c, 0x16);
hci_conn_del(c);
}
}
/* Check pending connect attempts */
void hci_conn_check_pending(struct hci_dev *hdev)
{
struct hci_conn *conn;
BT_DBG("hdev %s", hdev->name);
hci_dev_lock(hdev);
conn = hci_conn_hash_lookup_state(hdev, ACL_LINK, BT_CONNECT2);
if (conn)
hci_acl_connect(conn);
hci_dev_unlock(hdev);
}
void hci_conn_hold_device(struct hci_conn *conn)
{
atomic_inc(&conn->devref);
}
EXPORT_SYMBOL(hci_conn_hold_device);
void hci_conn_put_device(struct hci_conn *conn)
{
if (atomic_dec_and_test(&conn->devref))
hci_conn_del_sysfs(conn);
}
EXPORT_SYMBOL(hci_conn_put_device);
int hci_get_conn_list(void __user *arg)
{
struct hci_conn_list_req req, *cl;
struct hci_conn_info *ci;
struct hci_dev *hdev;
struct list_head *p;
int n = 0, size, err;
if (copy_from_user(&req, arg, sizeof(req)))
return -EFAULT;
if (!req.conn_num || req.conn_num > (PAGE_SIZE * 2) / sizeof(*ci))
return -EINVAL;
size = sizeof(req) + req.conn_num * sizeof(*ci);
if (!(cl = kmalloc(size, GFP_KERNEL)))
return -ENOMEM;
if (!(hdev = hci_dev_get(req.dev_id))) {
kfree(cl);
return -ENODEV;
}
ci = cl->conn_info;
hci_dev_lock_bh(hdev);
list_for_each(p, &hdev->conn_hash.list) {
register struct hci_conn *c;
c = list_entry(p, struct hci_conn, list);
bacpy(&(ci + n)->bdaddr, &c->dst);
(ci + n)->handle = c->handle;
(ci + n)->type = c->type;
(ci + n)->out = c->out;
(ci + n)->state = c->state;
(ci + n)->link_mode = c->link_mode;
if (c->type == SCO_LINK) {
(ci + n)->mtu = hdev->sco_mtu;
(ci + n)->cnt = hdev->sco_cnt;
(ci + n)->pkts = hdev->sco_pkts;
} else {
(ci + n)->mtu = hdev->acl_mtu;
(ci + n)->cnt = hdev->acl_cnt;
(ci + n)->pkts = hdev->acl_pkts;
}
if (++n >= req.conn_num)
break;
}
hci_dev_unlock_bh(hdev);
cl->dev_id = hdev->id;
cl->conn_num = n;
size = sizeof(req) + n * sizeof(*ci);
hci_dev_put(hdev);
err = copy_to_user(arg, cl, size);
kfree(cl);
return err ? -EFAULT : 0;
}
int hci_get_conn_info(struct hci_dev *hdev, void __user *arg)
{
struct hci_conn_info_req req;
struct hci_conn_info ci;
struct hci_conn *conn;
char __user *ptr = arg + sizeof(req);
if (copy_from_user(&req, arg, sizeof(req)))
return -EFAULT;
hci_dev_lock_bh(hdev);
conn = hci_conn_hash_lookup_ba(hdev, req.type, &req.bdaddr);
if (conn) {
bacpy(&ci.bdaddr, &conn->dst);
ci.handle = conn->handle;
ci.type = conn->type;
ci.out = conn->out;
ci.state = conn->state;
ci.link_mode = conn->link_mode;
if (req.type == SCO_LINK) {
ci.mtu = hdev->sco_mtu;
ci.cnt = hdev->sco_cnt;
ci.pkts = hdev->sco_pkts;
} else {
ci.mtu = hdev->acl_mtu;
ci.cnt = hdev->acl_cnt;
ci.pkts = hdev->acl_pkts;
}
}
hci_dev_unlock_bh(hdev);
if (!conn)
return -ENOENT;
return copy_to_user(ptr, &ci, sizeof(ci)) ? -EFAULT : 0;
}
int hci_get_auth_info(struct hci_dev *hdev, void __user *arg)
{
struct hci_auth_info_req req;
struct hci_conn *conn;
if (copy_from_user(&req, arg, sizeof(req)))
return -EFAULT;
hci_dev_lock_bh(hdev);
conn = hci_conn_hash_lookup_ba(hdev, ACL_LINK, &req.bdaddr);
if (conn)
req.type = conn->auth_type;
hci_dev_unlock_bh(hdev);
if (!conn)
return -ENOENT;
return copy_to_user(arg, &req, sizeof(req)) ? -EFAULT : 0;
}
| gpl-2.0 |
steppnasty/platform_kernel_msm7x30 | drivers/scsi/fcoe/fcoe.c | 51 | 73630 | /*
* Copyright(c) 2007 - 2009 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
* Maintained at www.Open-FCoE.org
*/
#include <linux/module.h>
#include <linux/version.h>
#include <linux/spinlock.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/if_ether.h>
#include <linux/if_vlan.h>
#include <linux/crc32.h>
#include <linux/slab.h>
#include <linux/cpu.h>
#include <linux/fs.h>
#include <linux/sysfs.h>
#include <linux/ctype.h>
#include <scsi/scsi_tcq.h>
#include <scsi/scsicam.h>
#include <scsi/scsi_transport.h>
#include <scsi/scsi_transport_fc.h>
#include <net/rtnetlink.h>
#include <scsi/fc/fc_encaps.h>
#include <scsi/fc/fc_fip.h>
#include <scsi/libfc.h>
#include <scsi/fc_frame.h>
#include <scsi/libfcoe.h>
#include "fcoe.h"
MODULE_AUTHOR("Open-FCoE.org");
MODULE_DESCRIPTION("FCoE");
MODULE_LICENSE("GPL v2");
/* Performance tuning parameters for fcoe */
static unsigned int fcoe_ddp_min;
module_param_named(ddp_min, fcoe_ddp_min, uint, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(ddp_min, "Minimum I/O size in bytes for " \
"Direct Data Placement (DDP).");
DEFINE_MUTEX(fcoe_config_mutex);
/* fcoe_percpu_clean completion. Waiter protected by fcoe_create_mutex */
static DECLARE_COMPLETION(fcoe_flush_completion);
/* fcoe host list */
/* must only by accessed under the RTNL mutex */
LIST_HEAD(fcoe_hostlist);
DEFINE_PER_CPU(struct fcoe_percpu_s, fcoe_percpu);
/* Function Prototypes */
static int fcoe_reset(struct Scsi_Host *);
static int fcoe_xmit(struct fc_lport *, struct fc_frame *);
static int fcoe_rcv(struct sk_buff *, struct net_device *,
struct packet_type *, struct net_device *);
static int fcoe_percpu_receive_thread(void *);
static void fcoe_clean_pending_queue(struct fc_lport *);
static void fcoe_percpu_clean(struct fc_lport *);
static int fcoe_link_speed_update(struct fc_lport *);
static int fcoe_link_ok(struct fc_lport *);
static struct fc_lport *fcoe_hostlist_lookup(const struct net_device *);
static int fcoe_hostlist_add(const struct fc_lport *);
static void fcoe_check_wait_queue(struct fc_lport *, struct sk_buff *);
static int fcoe_device_notification(struct notifier_block *, ulong, void *);
static void fcoe_dev_setup(void);
static void fcoe_dev_cleanup(void);
static struct fcoe_interface
*fcoe_hostlist_lookup_port(const struct net_device *);
static int fcoe_fip_recv(struct sk_buff *, struct net_device *,
struct packet_type *, struct net_device *);
static void fcoe_fip_send(struct fcoe_ctlr *, struct sk_buff *);
static void fcoe_update_src_mac(struct fc_lport *, u8 *);
static u8 *fcoe_get_src_mac(struct fc_lport *);
static void fcoe_destroy_work(struct work_struct *);
static int fcoe_ddp_setup(struct fc_lport *, u16, struct scatterlist *,
unsigned int);
static int fcoe_ddp_done(struct fc_lport *, u16);
static int fcoe_cpu_callback(struct notifier_block *, unsigned long, void *);
static int fcoe_create(const char *, struct kernel_param *);
static int fcoe_destroy(const char *, struct kernel_param *);
static int fcoe_enable(const char *, struct kernel_param *);
static int fcoe_disable(const char *, struct kernel_param *);
static struct fc_seq *fcoe_elsct_send(struct fc_lport *,
u32 did, struct fc_frame *,
unsigned int op,
void (*resp)(struct fc_seq *,
struct fc_frame *,
void *),
void *, u32 timeout);
static void fcoe_recv_frame(struct sk_buff *skb);
static void fcoe_get_lesb(struct fc_lport *, struct fc_els_lesb *);
module_param_call(create, fcoe_create, NULL, (void *)FIP_MODE_FABRIC, S_IWUSR);
__MODULE_PARM_TYPE(create, "string");
MODULE_PARM_DESC(create, " Creates fcoe instance on a ethernet interface");
module_param_call(create_vn2vn, fcoe_create, NULL,
(void *)FIP_MODE_VN2VN, S_IWUSR);
__MODULE_PARM_TYPE(create_vn2vn, "string");
MODULE_PARM_DESC(create_vn2vn, " Creates a VN_node to VN_node FCoE instance "
"on an Ethernet interface");
module_param_call(destroy, fcoe_destroy, NULL, NULL, S_IWUSR);
__MODULE_PARM_TYPE(destroy, "string");
MODULE_PARM_DESC(destroy, " Destroys fcoe instance on a ethernet interface");
module_param_call(enable, fcoe_enable, NULL, NULL, S_IWUSR);
__MODULE_PARM_TYPE(enable, "string");
MODULE_PARM_DESC(enable, " Enables fcoe on a ethernet interface.");
module_param_call(disable, fcoe_disable, NULL, NULL, S_IWUSR);
__MODULE_PARM_TYPE(disable, "string");
MODULE_PARM_DESC(disable, " Disables fcoe on a ethernet interface.");
/* notification function for packets from net device */
static struct notifier_block fcoe_notifier = {
.notifier_call = fcoe_device_notification,
};
/* notification function for CPU hotplug events */
static struct notifier_block fcoe_cpu_notifier = {
.notifier_call = fcoe_cpu_callback,
};
static struct scsi_transport_template *fcoe_transport_template;
static struct scsi_transport_template *fcoe_vport_transport_template;
static int fcoe_vport_destroy(struct fc_vport *);
static int fcoe_vport_create(struct fc_vport *, bool disabled);
static int fcoe_vport_disable(struct fc_vport *, bool disable);
static void fcoe_set_vport_symbolic_name(struct fc_vport *);
static void fcoe_set_port_id(struct fc_lport *, u32, struct fc_frame *);
static struct libfc_function_template fcoe_libfc_fcn_templ = {
.frame_send = fcoe_xmit,
.ddp_setup = fcoe_ddp_setup,
.ddp_done = fcoe_ddp_done,
.elsct_send = fcoe_elsct_send,
.get_lesb = fcoe_get_lesb,
.lport_set_port_id = fcoe_set_port_id,
};
struct fc_function_template fcoe_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),
.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 = fcoe_reset,
.terminate_rport_io = fc_rport_terminate_io,
.vport_create = fcoe_vport_create,
.vport_delete = fcoe_vport_destroy,
.vport_disable = fcoe_vport_disable,
.set_vport_symbolic_name = fcoe_set_vport_symbolic_name,
.bsg_request = fc_lport_bsg_request,
};
struct fc_function_template fcoe_vport_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),
.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 = fcoe_reset,
.terminate_rport_io = fc_rport_terminate_io,
.bsg_request = fc_lport_bsg_request,
};
static struct scsi_host_template fcoe_shost_template = {
.module = THIS_MODULE,
.name = "FCoE Driver",
.proc_name = FCOE_NAME,
.queuecommand = fc_queuecommand,
.eh_abort_handler = fc_eh_abort,
.eh_device_reset_handler = fc_eh_device_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 = FCOE_MAX_OUTSTANDING_COMMANDS,
.use_clustering = ENABLE_CLUSTERING,
.sg_tablesize = SG_ALL,
.max_sectors = 0xffff,
};
/**
* fcoe_interface_setup() - Setup a FCoE interface
* @fcoe: The new FCoE interface
* @netdev: The net device that the fcoe interface is on
*
* Returns : 0 for success
* Locking: must be called with the RTNL mutex held
*/
static int fcoe_interface_setup(struct fcoe_interface *fcoe,
struct net_device *netdev)
{
struct fcoe_ctlr *fip = &fcoe->ctlr;
struct netdev_hw_addr *ha;
struct net_device *real_dev;
u8 flogi_maddr[ETH_ALEN];
const struct net_device_ops *ops;
fcoe->netdev = netdev;
/* Let LLD initialize for FCoE */
ops = netdev->netdev_ops;
if (ops->ndo_fcoe_enable) {
if (ops->ndo_fcoe_enable(netdev))
FCOE_NETDEV_DBG(netdev, "Failed to enable FCoE"
" specific feature for LLD.\n");
}
/* Do not support for bonding device */
if ((netdev->priv_flags & IFF_MASTER_ALB) ||
(netdev->priv_flags & IFF_SLAVE_INACTIVE) ||
(netdev->priv_flags & IFF_MASTER_8023AD)) {
FCOE_NETDEV_DBG(netdev, "Bonded interfaces not supported\n");
return -EOPNOTSUPP;
}
/* look for SAN MAC address, if multiple SAN MACs exist, only
* use the first one for SPMA */
real_dev = (netdev->priv_flags & IFF_802_1Q_VLAN) ?
vlan_dev_real_dev(netdev) : netdev;
rcu_read_lock();
for_each_dev_addr(real_dev, ha) {
if ((ha->type == NETDEV_HW_ADDR_T_SAN) &&
(is_valid_ether_addr(ha->addr))) {
memcpy(fip->ctl_src_addr, ha->addr, ETH_ALEN);
fip->spma = 1;
break;
}
}
rcu_read_unlock();
/* setup Source Mac Address */
if (!fip->spma)
memcpy(fip->ctl_src_addr, netdev->dev_addr, netdev->addr_len);
/*
* Add FCoE MAC address as second unicast MAC address
* or enter promiscuous mode if not capable of listening
* for multiple unicast MACs.
*/
memcpy(flogi_maddr, (u8[6]) FC_FCOE_FLOGI_MAC, ETH_ALEN);
dev_uc_add(netdev, flogi_maddr);
if (fip->spma)
dev_uc_add(netdev, fip->ctl_src_addr);
if (fip->mode == FIP_MODE_VN2VN) {
dev_mc_add(netdev, FIP_ALL_VN2VN_MACS);
dev_mc_add(netdev, FIP_ALL_P2P_MACS);
} else
dev_mc_add(netdev, FIP_ALL_ENODE_MACS);
/*
* setup the receive function from ethernet driver
* on the ethertype for the given device
*/
fcoe->fcoe_packet_type.func = fcoe_rcv;
fcoe->fcoe_packet_type.type = __constant_htons(ETH_P_FCOE);
fcoe->fcoe_packet_type.dev = netdev;
dev_add_pack(&fcoe->fcoe_packet_type);
fcoe->fip_packet_type.func = fcoe_fip_recv;
fcoe->fip_packet_type.type = htons(ETH_P_FIP);
fcoe->fip_packet_type.dev = netdev;
dev_add_pack(&fcoe->fip_packet_type);
return 0;
}
/**
* fcoe_interface_create() - Create a FCoE interface on a net device
* @netdev: The net device to create the FCoE interface on
* @fip_mode: The mode to use for FIP
*
* Returns: pointer to a struct fcoe_interface or NULL on error
*/
static struct fcoe_interface *fcoe_interface_create(struct net_device *netdev,
enum fip_state fip_mode)
{
struct fcoe_interface *fcoe;
int err;
fcoe = kzalloc(sizeof(*fcoe), GFP_KERNEL);
if (!fcoe) {
FCOE_NETDEV_DBG(netdev, "Could not allocate fcoe structure\n");
return NULL;
}
dev_hold(netdev);
kref_init(&fcoe->kref);
/*
* Initialize FIP.
*/
fcoe_ctlr_init(&fcoe->ctlr, fip_mode);
fcoe->ctlr.send = fcoe_fip_send;
fcoe->ctlr.update_mac = fcoe_update_src_mac;
fcoe->ctlr.get_src_addr = fcoe_get_src_mac;
err = fcoe_interface_setup(fcoe, netdev);
if (err) {
fcoe_ctlr_destroy(&fcoe->ctlr);
kfree(fcoe);
dev_put(netdev);
return NULL;
}
return fcoe;
}
/**
* fcoe_interface_cleanup() - Clean up a FCoE interface
* @fcoe: The FCoE interface to be cleaned up
*
* Caller must be holding the RTNL mutex
*/
void fcoe_interface_cleanup(struct fcoe_interface *fcoe)
{
struct net_device *netdev = fcoe->netdev;
struct fcoe_ctlr *fip = &fcoe->ctlr;
u8 flogi_maddr[ETH_ALEN];
const struct net_device_ops *ops;
/*
* Don't listen for Ethernet packets anymore.
* synchronize_net() ensures that the packet handlers are not running
* on another CPU. dev_remove_pack() would do that, this calls the
* unsyncronized version __dev_remove_pack() to avoid multiple delays.
*/
__dev_remove_pack(&fcoe->fcoe_packet_type);
__dev_remove_pack(&fcoe->fip_packet_type);
synchronize_net();
/* Delete secondary MAC addresses */
memcpy(flogi_maddr, (u8[6]) FC_FCOE_FLOGI_MAC, ETH_ALEN);
dev_uc_del(netdev, flogi_maddr);
if (fip->spma)
dev_uc_del(netdev, fip->ctl_src_addr);
if (fip->mode == FIP_MODE_VN2VN) {
dev_mc_del(netdev, FIP_ALL_VN2VN_MACS);
dev_mc_del(netdev, FIP_ALL_P2P_MACS);
} else
dev_mc_del(netdev, FIP_ALL_ENODE_MACS);
/* Tell the LLD we are done w/ FCoE */
ops = netdev->netdev_ops;
if (ops->ndo_fcoe_disable) {
if (ops->ndo_fcoe_disable(netdev))
FCOE_NETDEV_DBG(netdev, "Failed to disable FCoE"
" specific feature for LLD.\n");
}
}
/**
* fcoe_interface_release() - fcoe_port kref release function
* @kref: Embedded reference count in an fcoe_interface struct
*/
static void fcoe_interface_release(struct kref *kref)
{
struct fcoe_interface *fcoe;
struct net_device *netdev;
fcoe = container_of(kref, struct fcoe_interface, kref);
netdev = fcoe->netdev;
/* tear-down the FCoE controller */
fcoe_ctlr_destroy(&fcoe->ctlr);
kfree(fcoe);
dev_put(netdev);
}
/**
* fcoe_interface_get() - Get a reference to a FCoE interface
* @fcoe: The FCoE interface to be held
*/
static inline void fcoe_interface_get(struct fcoe_interface *fcoe)
{
kref_get(&fcoe->kref);
}
/**
* fcoe_interface_put() - Put a reference to a FCoE interface
* @fcoe: The FCoE interface to be released
*/
static inline void fcoe_interface_put(struct fcoe_interface *fcoe)
{
kref_put(&fcoe->kref, fcoe_interface_release);
}
/**
* fcoe_fip_recv() - Handler for received FIP frames
* @skb: The receive skb
* @netdev: The associated net device
* @ptype: The packet_type structure which was used to register this handler
* @orig_dev: The original net_device the the skb was received on.
* (in case dev is a bond)
*
* Returns: 0 for success
*/
static int fcoe_fip_recv(struct sk_buff *skb, struct net_device *netdev,
struct packet_type *ptype,
struct net_device *orig_dev)
{
struct fcoe_interface *fcoe;
fcoe = container_of(ptype, struct fcoe_interface, fip_packet_type);
fcoe_ctlr_recv(&fcoe->ctlr, skb);
return 0;
}
/**
* fcoe_fip_send() - Send an Ethernet-encapsulated FIP frame
* @fip: The FCoE controller
* @skb: The FIP packet to be sent
*/
static void fcoe_fip_send(struct fcoe_ctlr *fip, struct sk_buff *skb)
{
skb->dev = fcoe_from_ctlr(fip)->netdev;
dev_queue_xmit(skb);
}
/**
* fcoe_update_src_mac() - Update the Ethernet MAC filters
* @lport: The local port to update the source MAC on
* @addr: Unicast MAC address to add
*
* Remove any previously-set unicast MAC filter.
* Add secondary FCoE MAC address filter for our OUI.
*/
static void fcoe_update_src_mac(struct fc_lport *lport, u8 *addr)
{
struct fcoe_port *port = lport_priv(lport);
struct fcoe_interface *fcoe = port->fcoe;
rtnl_lock();
if (!is_zero_ether_addr(port->data_src_addr))
dev_uc_del(fcoe->netdev, port->data_src_addr);
if (!is_zero_ether_addr(addr))
dev_uc_add(fcoe->netdev, addr);
memcpy(port->data_src_addr, addr, ETH_ALEN);
rtnl_unlock();
}
/**
* fcoe_get_src_mac() - return the Ethernet source address for an lport
* @lport: libfc lport
*/
static u8 *fcoe_get_src_mac(struct fc_lport *lport)
{
struct fcoe_port *port = lport_priv(lport);
return port->data_src_addr;
}
/**
* fcoe_lport_config() - Set up a local port
* @lport: The local port to be setup
*
* Returns: 0 for success
*/
static int fcoe_lport_config(struct fc_lport *lport)
{
lport->link_up = 0;
lport->qfull = 0;
lport->max_retry_count = 3;
lport->max_rport_retry_count = 3;
lport->e_d_tov = 2 * 1000; /* FC-FS default */
lport->r_a_tov = 2 * 2 * 1000;
lport->service_params = (FCP_SPPF_INIT_FCN | FCP_SPPF_RD_XRDY_DIS |
FCP_SPPF_RETRY | FCP_SPPF_CONF_COMPL);
lport->does_npiv = 1;
fc_lport_init_stats(lport);
/* lport fc_lport related configuration */
fc_lport_config(lport);
/* offload related configuration */
lport->crc_offload = 0;
lport->seq_offload = 0;
lport->lro_enabled = 0;
lport->lro_xid = 0;
lport->lso_max = 0;
return 0;
}
/**
* fcoe_queue_timer() - The fcoe queue timer
* @lport: The local port
*
* Calls fcoe_check_wait_queue on timeout
*/
static void fcoe_queue_timer(ulong lport)
{
fcoe_check_wait_queue((struct fc_lport *)lport, NULL);
}
/**
* fcoe_get_wwn() - Get the world wide name from LLD if it supports it
* @netdev: the associated net device
* @wwn: the output WWN
* @type: the type of WWN (WWPN or WWNN)
*
* Returns: 0 for success
*/
static int fcoe_get_wwn(struct net_device *netdev, u64 *wwn, int type)
{
const struct net_device_ops *ops = netdev->netdev_ops;
if (ops->ndo_fcoe_get_wwn)
return ops->ndo_fcoe_get_wwn(netdev, wwn, type);
return -EINVAL;
}
/**
* fcoe_netdev_features_change - Updates the lport's offload flags based
* on the LLD netdev's FCoE feature flags
*/
static void fcoe_netdev_features_change(struct fc_lport *lport,
struct net_device *netdev)
{
mutex_lock(&lport->lp_mutex);
if (netdev->features & NETIF_F_SG)
lport->sg_supp = 1;
else
lport->sg_supp = 0;
if (netdev->features & NETIF_F_FCOE_CRC) {
lport->crc_offload = 1;
FCOE_NETDEV_DBG(netdev, "Supports FCCRC offload\n");
} else {
lport->crc_offload = 0;
}
if (netdev->features & NETIF_F_FSO) {
lport->seq_offload = 1;
lport->lso_max = netdev->gso_max_size;
FCOE_NETDEV_DBG(netdev, "Supports LSO for max len 0x%x\n",
lport->lso_max);
} else {
lport->seq_offload = 0;
lport->lso_max = 0;
}
if (netdev->fcoe_ddp_xid) {
lport->lro_enabled = 1;
lport->lro_xid = netdev->fcoe_ddp_xid;
FCOE_NETDEV_DBG(netdev, "Supports LRO for max xid 0x%x\n",
lport->lro_xid);
} else {
lport->lro_enabled = 0;
lport->lro_xid = 0;
}
mutex_unlock(&lport->lp_mutex);
}
/**
* fcoe_netdev_config() - Set up net devive for SW FCoE
* @lport: The local port that is associated with the net device
* @netdev: The associated net device
*
* Must be called after fcoe_lport_config() as it will use local port mutex
*
* Returns: 0 for success
*/
static int fcoe_netdev_config(struct fc_lport *lport, struct net_device *netdev)
{
u32 mfs;
u64 wwnn, wwpn;
struct fcoe_interface *fcoe;
struct fcoe_port *port;
/* Setup lport private data to point to fcoe softc */
port = lport_priv(lport);
fcoe = port->fcoe;
/*
* Determine max frame size based on underlying device and optional
* user-configured limit. If the MFS is too low, fcoe_link_ok()
* will return 0, so do this first.
*/
mfs = netdev->mtu;
if (netdev->features & NETIF_F_FCOE_MTU) {
mfs = FCOE_MTU;
FCOE_NETDEV_DBG(netdev, "Supports FCOE_MTU of %d bytes\n", mfs);
}
mfs -= (sizeof(struct fcoe_hdr) + sizeof(struct fcoe_crc_eof));
if (fc_set_mfs(lport, mfs))
return -EINVAL;
/* offload features support */
fcoe_netdev_features_change(lport, netdev);
skb_queue_head_init(&port->fcoe_pending_queue);
port->fcoe_pending_queue_active = 0;
setup_timer(&port->timer, fcoe_queue_timer, (unsigned long)lport);
fcoe_link_speed_update(lport);
if (!lport->vport) {
if (fcoe_get_wwn(netdev, &wwnn, NETDEV_FCOE_WWNN))
wwnn = fcoe_wwn_from_mac(fcoe->ctlr.ctl_src_addr, 1, 0);
fc_set_wwnn(lport, wwnn);
if (fcoe_get_wwn(netdev, &wwpn, NETDEV_FCOE_WWPN))
wwpn = fcoe_wwn_from_mac(fcoe->ctlr.ctl_src_addr,
2, 0);
fc_set_wwpn(lport, wwpn);
}
return 0;
}
/**
* fcoe_shost_config() - Set up the SCSI host associated with a local port
* @lport: The local port
* @dev: The device associated with the SCSI host
*
* Must be called after fcoe_lport_config() and fcoe_netdev_config()
*
* Returns: 0 for success
*/
static int fcoe_shost_config(struct fc_lport *lport, struct device *dev)
{
int rc = 0;
/* lport scsi host config */
lport->host->max_lun = FCOE_MAX_LUN;
lport->host->max_id = FCOE_MAX_FCP_TARGET;
lport->host->max_channel = 0;
lport->host->max_cmd_len = FCOE_MAX_CMD_LEN;
if (lport->vport)
lport->host->transportt = fcoe_vport_transport_template;
else
lport->host->transportt = fcoe_transport_template;
/* add the new host to the SCSI-ml */
rc = scsi_add_host(lport->host, dev);
if (rc) {
FCOE_NETDEV_DBG(fcoe_netdev(lport), "fcoe_shost_config: "
"error on scsi_add_host\n");
return rc;
}
if (!lport->vport)
fc_host_max_npiv_vports(lport->host) = USHRT_MAX;
snprintf(fc_host_symbolic_name(lport->host), FC_SYMBOLIC_NAME_SIZE,
"%s v%s over %s", FCOE_NAME, FCOE_VERSION,
fcoe_netdev(lport)->name);
return 0;
}
/**
* fcoe_oem_match() - The match routine for the offloaded exchange manager
* @fp: The I/O frame
*
* This routine will be associated with an exchange manager (EM). When
* the libfc exchange handling code is looking for an EM to use it will
* call this routine and pass it the frame that it wishes to send. This
* routine will return True if the associated EM is to be used and False
* if the echange code should continue looking for an EM.
*
* The offload EM that this routine is associated with will handle any
* packets that are for SCSI read requests.
*
* Returns: True for read types I/O, otherwise returns false.
*/
bool fcoe_oem_match(struct fc_frame *fp)
{
return fc_fcp_is_read(fr_fsp(fp)) &&
(fr_fsp(fp)->data_len > fcoe_ddp_min);
}
/**
* fcoe_em_config() - Allocate and configure an exchange manager
* @lport: The local port that the new EM will be associated with
*
* Returns: 0 on success
*/
static inline int fcoe_em_config(struct fc_lport *lport)
{
struct fcoe_port *port = lport_priv(lport);
struct fcoe_interface *fcoe = port->fcoe;
struct fcoe_interface *oldfcoe = NULL;
struct net_device *old_real_dev, *cur_real_dev;
u16 min_xid = FCOE_MIN_XID;
u16 max_xid = FCOE_MAX_XID;
/*
* Check if need to allocate an em instance for
* offload exchange ids to be shared across all VN_PORTs/lport.
*/
if (!lport->lro_enabled || !lport->lro_xid ||
(lport->lro_xid >= max_xid)) {
lport->lro_xid = 0;
goto skip_oem;
}
/*
* Reuse existing offload em instance in case
* it is already allocated on real eth device
*/
if (fcoe->netdev->priv_flags & IFF_802_1Q_VLAN)
cur_real_dev = vlan_dev_real_dev(fcoe->netdev);
else
cur_real_dev = fcoe->netdev;
list_for_each_entry(oldfcoe, &fcoe_hostlist, list) {
if (oldfcoe->netdev->priv_flags & IFF_802_1Q_VLAN)
old_real_dev = vlan_dev_real_dev(oldfcoe->netdev);
else
old_real_dev = oldfcoe->netdev;
if (cur_real_dev == old_real_dev) {
fcoe->oem = oldfcoe->oem;
break;
}
}
if (fcoe->oem) {
if (!fc_exch_mgr_add(lport, fcoe->oem, fcoe_oem_match)) {
printk(KERN_ERR "fcoe_em_config: failed to add "
"offload em:%p on interface:%s\n",
fcoe->oem, fcoe->netdev->name);
return -ENOMEM;
}
} else {
fcoe->oem = fc_exch_mgr_alloc(lport, FC_CLASS_3,
FCOE_MIN_XID, lport->lro_xid,
fcoe_oem_match);
if (!fcoe->oem) {
printk(KERN_ERR "fcoe_em_config: failed to allocate "
"em for offload exches on interface:%s\n",
fcoe->netdev->name);
return -ENOMEM;
}
}
/*
* Exclude offload EM xid range from next EM xid range.
*/
min_xid += lport->lro_xid + 1;
skip_oem:
if (!fc_exch_mgr_alloc(lport, FC_CLASS_3, min_xid, max_xid, NULL)) {
printk(KERN_ERR "fcoe_em_config: failed to "
"allocate em on interface %s\n", fcoe->netdev->name);
return -ENOMEM;
}
return 0;
}
/**
* fcoe_if_destroy() - Tear down a SW FCoE instance
* @lport: The local port to be destroyed
*
* Locking: must be called with the RTNL mutex held and RTNL mutex
* needed to be dropped by this function since not dropping RTNL
* would cause circular locking warning on synchronous fip worker
* cancelling thru fcoe_interface_put invoked by this function.
*
*/
static void fcoe_if_destroy(struct fc_lport *lport)
{
struct fcoe_port *port = lport_priv(lport);
struct fcoe_interface *fcoe = port->fcoe;
struct net_device *netdev = fcoe->netdev;
FCOE_NETDEV_DBG(netdev, "Destroying interface\n");
/* Logout of the fabric */
fc_fabric_logoff(lport);
/* Cleanup the fc_lport */
fc_lport_destroy(lport);
fc_fcp_destroy(lport);
/* Stop the transmit retry timer */
del_timer_sync(&port->timer);
/* Free existing transmit skbs */
fcoe_clean_pending_queue(lport);
if (!is_zero_ether_addr(port->data_src_addr))
dev_uc_del(netdev, port->data_src_addr);
rtnl_unlock();
/* receives may not be stopped until after this */
fcoe_interface_put(fcoe);
/* Free queued packets for the per-CPU receive threads */
fcoe_percpu_clean(lport);
/* Detach from the scsi-ml */
fc_remove_host(lport->host);
scsi_remove_host(lport->host);
/* There are no more rports or I/O, free the EM */
fc_exch_mgr_free(lport);
/* Free memory used by statistical counters */
fc_lport_free_stats(lport);
/* Release the Scsi_Host */
scsi_host_put(lport->host);
module_put(THIS_MODULE);
}
/**
* fcoe_ddp_setup() - Call a LLD's ddp_setup through the net device
* @lport: The local port to setup DDP for
* @xid: The exchange ID for this DDP transfer
* @sgl: The scatterlist describing this transfer
* @sgc: The number of sg items
*
* Returns: 0 if the DDP context was not configured
*/
static int fcoe_ddp_setup(struct fc_lport *lport, u16 xid,
struct scatterlist *sgl, unsigned int sgc)
{
struct net_device *netdev = fcoe_netdev(lport);
if (netdev->netdev_ops->ndo_fcoe_ddp_setup)
return netdev->netdev_ops->ndo_fcoe_ddp_setup(netdev,
xid, sgl,
sgc);
return 0;
}
/**
* fcoe_ddp_done() - Call a LLD's ddp_done through the net device
* @lport: The local port to complete DDP on
* @xid: The exchange ID for this DDP transfer
*
* Returns: the length of data that have been completed by DDP
*/
static int fcoe_ddp_done(struct fc_lport *lport, u16 xid)
{
struct net_device *netdev = fcoe_netdev(lport);
if (netdev->netdev_ops->ndo_fcoe_ddp_done)
return netdev->netdev_ops->ndo_fcoe_ddp_done(netdev, xid);
return 0;
}
/**
* fcoe_if_create() - Create a FCoE instance on an interface
* @fcoe: The FCoE interface to create a local port on
* @parent: The device pointer to be the parent in sysfs for the SCSI host
* @npiv: Indicates if the port is a vport or not
*
* Creates a fc_lport instance and a Scsi_Host instance and configure them.
*
* Returns: The allocated fc_lport or an error pointer
*/
static struct fc_lport *fcoe_if_create(struct fcoe_interface *fcoe,
struct device *parent, int npiv)
{
struct net_device *netdev = fcoe->netdev;
struct fc_lport *lport = NULL;
struct fcoe_port *port;
int rc;
/*
* parent is only a vport if npiv is 1,
* but we'll only use vport in that case so go ahead and set it
*/
struct fc_vport *vport = dev_to_vport(parent);
FCOE_NETDEV_DBG(netdev, "Create Interface\n");
if (!npiv) {
lport = libfc_host_alloc(&fcoe_shost_template,
sizeof(struct fcoe_port));
} else {
lport = libfc_vport_create(vport,
sizeof(struct fcoe_port));
}
if (!lport) {
FCOE_NETDEV_DBG(netdev, "Could not allocate host structure\n");
rc = -ENOMEM;
goto out;
}
port = lport_priv(lport);
port->lport = lport;
port->fcoe = fcoe;
INIT_WORK(&port->destroy_work, fcoe_destroy_work);
/* configure a fc_lport including the exchange manager */
rc = fcoe_lport_config(lport);
if (rc) {
FCOE_NETDEV_DBG(netdev, "Could not configure lport for the "
"interface\n");
goto out_host_put;
}
if (npiv) {
FCOE_NETDEV_DBG(netdev, "Setting vport names, "
"%16.16llx %16.16llx\n",
vport->node_name, vport->port_name);
fc_set_wwnn(lport, vport->node_name);
fc_set_wwpn(lport, vport->port_name);
}
/* configure lport network properties */
rc = fcoe_netdev_config(lport, netdev);
if (rc) {
FCOE_NETDEV_DBG(netdev, "Could not configure netdev for the "
"interface\n");
goto out_lp_destroy;
}
/* configure lport scsi host properties */
rc = fcoe_shost_config(lport, parent);
if (rc) {
FCOE_NETDEV_DBG(netdev, "Could not configure shost for the "
"interface\n");
goto out_lp_destroy;
}
/* Initialize the library */
rc = fcoe_libfc_config(lport, &fcoe->ctlr, &fcoe_libfc_fcn_templ, 1);
if (rc) {
FCOE_NETDEV_DBG(netdev, "Could not configure libfc for the "
"interface\n");
goto out_lp_destroy;
}
if (!npiv) {
/*
* fcoe_em_alloc() and fcoe_hostlist_add() both
* need to be atomic with respect to other changes to the
* hostlist since fcoe_em_alloc() looks for an existing EM
* instance on host list updated by fcoe_hostlist_add().
*
* This is currently handled through the fcoe_config_mutex
* begin held.
*/
/* lport exch manager allocation */
rc = fcoe_em_config(lport);
if (rc) {
FCOE_NETDEV_DBG(netdev, "Could not configure the EM "
"for the interface\n");
goto out_lp_destroy;
}
}
fcoe_interface_get(fcoe);
return lport;
out_lp_destroy:
fc_exch_mgr_free(lport);
out_host_put:
scsi_host_put(lport->host);
out:
return ERR_PTR(rc);
}
/**
* fcoe_if_init() - Initialization routine for fcoe.ko
*
* Attaches the SW FCoE transport to the FC transport
*
* Returns: 0 on success
*/
static int __init fcoe_if_init(void)
{
/* attach to scsi transport */
fcoe_transport_template = fc_attach_transport(&fcoe_transport_function);
fcoe_vport_transport_template =
fc_attach_transport(&fcoe_vport_transport_function);
if (!fcoe_transport_template) {
printk(KERN_ERR "fcoe: Failed to attach to the FC transport\n");
return -ENODEV;
}
return 0;
}
/**
* fcoe_if_exit() - Tear down fcoe.ko
*
* Detaches the SW FCoE transport from the FC transport
*
* Returns: 0 on success
*/
int __exit fcoe_if_exit(void)
{
fc_release_transport(fcoe_transport_template);
fc_release_transport(fcoe_vport_transport_template);
fcoe_transport_template = NULL;
fcoe_vport_transport_template = NULL;
return 0;
}
/**
* fcoe_percpu_thread_create() - Create a receive thread for an online CPU
* @cpu: The CPU index of the CPU to create a receive thread for
*/
static void fcoe_percpu_thread_create(unsigned int cpu)
{
struct fcoe_percpu_s *p;
struct task_struct *thread;
p = &per_cpu(fcoe_percpu, cpu);
thread = kthread_create(fcoe_percpu_receive_thread,
(void *)p, "fcoethread/%d", cpu);
if (likely(!IS_ERR(thread))) {
kthread_bind(thread, cpu);
wake_up_process(thread);
spin_lock_bh(&p->fcoe_rx_list.lock);
p->thread = thread;
spin_unlock_bh(&p->fcoe_rx_list.lock);
}
}
/**
* fcoe_percpu_thread_destroy() - Remove the receive thread of a CPU
* @cpu: The CPU index of the CPU whose receive thread is to be destroyed
*
* Destroys a per-CPU Rx thread. Any pending skbs are moved to the
* current CPU's Rx thread. If the thread being destroyed is bound to
* the CPU processing this context the skbs will be freed.
*/
static void fcoe_percpu_thread_destroy(unsigned int cpu)
{
struct fcoe_percpu_s *p;
struct task_struct *thread;
struct page *crc_eof;
struct sk_buff *skb;
#ifdef CONFIG_SMP
struct fcoe_percpu_s *p0;
unsigned targ_cpu = get_cpu();
#endif /* CONFIG_SMP */
FCOE_DBG("Destroying receive thread for CPU %d\n", cpu);
/* Prevent any new skbs from being queued for this CPU. */
p = &per_cpu(fcoe_percpu, cpu);
spin_lock_bh(&p->fcoe_rx_list.lock);
thread = p->thread;
p->thread = NULL;
crc_eof = p->crc_eof_page;
p->crc_eof_page = NULL;
p->crc_eof_offset = 0;
spin_unlock_bh(&p->fcoe_rx_list.lock);
#ifdef CONFIG_SMP
/*
* Don't bother moving the skb's if this context is running
* on the same CPU that is having its thread destroyed. This
* can easily happen when the module is removed.
*/
if (cpu != targ_cpu) {
p0 = &per_cpu(fcoe_percpu, targ_cpu);
spin_lock_bh(&p0->fcoe_rx_list.lock);
if (p0->thread) {
FCOE_DBG("Moving frames from CPU %d to CPU %d\n",
cpu, targ_cpu);
while ((skb = __skb_dequeue(&p->fcoe_rx_list)) != NULL)
__skb_queue_tail(&p0->fcoe_rx_list, skb);
spin_unlock_bh(&p0->fcoe_rx_list.lock);
} else {
/*
* The targeted CPU is not initialized and cannot accept
* new skbs. Unlock the targeted CPU and drop the skbs
* on the CPU that is going offline.
*/
while ((skb = __skb_dequeue(&p->fcoe_rx_list)) != NULL)
kfree_skb(skb);
spin_unlock_bh(&p0->fcoe_rx_list.lock);
}
} else {
/*
* This scenario occurs when the module is being removed
* and all threads are being destroyed. skbs will continue
* to be shifted from the CPU thread that is being removed
* to the CPU thread associated with the CPU that is processing
* the module removal. Once there is only one CPU Rx thread it
* will reach this case and we will drop all skbs and later
* stop the thread.
*/
spin_lock_bh(&p->fcoe_rx_list.lock);
while ((skb = __skb_dequeue(&p->fcoe_rx_list)) != NULL)
kfree_skb(skb);
spin_unlock_bh(&p->fcoe_rx_list.lock);
}
put_cpu();
#else
/*
* This a non-SMP scenario where the singular Rx thread is
* being removed. Free all skbs and stop the thread.
*/
spin_lock_bh(&p->fcoe_rx_list.lock);
while ((skb = __skb_dequeue(&p->fcoe_rx_list)) != NULL)
kfree_skb(skb);
spin_unlock_bh(&p->fcoe_rx_list.lock);
#endif
if (thread)
kthread_stop(thread);
if (crc_eof)
put_page(crc_eof);
}
/**
* fcoe_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 fcoe_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:
FCOE_DBG("CPU %x online: Create Rx thread\n", cpu);
fcoe_percpu_thread_create(cpu);
break;
case CPU_DEAD:
case CPU_DEAD_FROZEN:
FCOE_DBG("CPU %x offline: Remove Rx thread\n", cpu);
fcoe_percpu_thread_destroy(cpu);
break;
default:
break;
}
return NOTIFY_OK;
}
/**
* fcoe_rcv() - Receive packets from a net device
* @skb: The received packet
* @netdev: The net device that the packet was received on
* @ptype: The packet type context
* @olddev: The last device net device
*
* This routine is called by NET_RX_SOFTIRQ. It receives a packet, builds a
* FC frame and passes the frame to libfc.
*
* Returns: 0 for success
*/
int fcoe_rcv(struct sk_buff *skb, struct net_device *netdev,
struct packet_type *ptype, struct net_device *olddev)
{
struct fc_lport *lport;
struct fcoe_rcv_info *fr;
struct fcoe_interface *fcoe;
struct fc_frame_header *fh;
struct fcoe_percpu_s *fps;
struct ethhdr *eh;
unsigned int cpu;
fcoe = container_of(ptype, struct fcoe_interface, fcoe_packet_type);
lport = fcoe->ctlr.lp;
if (unlikely(!lport)) {
FCOE_NETDEV_DBG(netdev, "Cannot find hba structure");
goto err2;
}
if (!lport->link_up)
goto err2;
FCOE_NETDEV_DBG(netdev, "skb_info: len:%d data_len:%d head:%p "
"data:%p tail:%p end:%p sum:%d dev:%s",
skb->len, skb->data_len, skb->head, skb->data,
skb_tail_pointer(skb), skb_end_pointer(skb),
skb->csum, skb->dev ? skb->dev->name : "<NULL>");
eh = eth_hdr(skb);
if (is_fip_mode(&fcoe->ctlr) &&
compare_ether_addr(eh->h_source, fcoe->ctlr.dest_addr)) {
FCOE_NETDEV_DBG(netdev, "wrong source mac address:%pM\n",
eh->h_source);
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);
if (ntoh24(&eh->h_dest[3]) != ntoh24(fh->fh_d_id)) {
FCOE_NETDEV_DBG(netdev, "FC frame d_id mismatch with MAC:%pM\n",
eh->h_dest);
goto err;
}
fr = fcoe_dev_from_skb(skb);
fr->fr_dev = lport;
fr->ptype = ptype;
/*
* In case the incoming frame's exchange is originated from
* the initiator, then received frame's exchange id is ANDed
* with fc_cpu_mask bits to get the same cpu on which exchange
* was originated, otherwise just use the current cpu.
*/
if (ntoh24(fh->fh_f_ctl) & FC_FC_EX_CTX)
cpu = ntohs(fh->fh_ox_id) & fc_cpu_mask;
else
cpu = smp_processor_id();
fps = &per_cpu(fcoe_percpu, cpu);
spin_lock_bh(&fps->fcoe_rx_list.lock);
if (unlikely(!fps->thread)) {
/*
* The targeted CPU is not ready, let's target
* the first CPU now. For non-SMP systems this
* will check the same CPU twice.
*/
FCOE_NETDEV_DBG(netdev, "CPU is online, but no receive thread "
"ready for incoming skb- using first online "
"CPU.\n");
spin_unlock_bh(&fps->fcoe_rx_list.lock);
cpu = cpumask_first(cpu_online_mask);
fps = &per_cpu(fcoe_percpu, cpu);
spin_lock_bh(&fps->fcoe_rx_list.lock);
if (!fps->thread) {
spin_unlock_bh(&fps->fcoe_rx_list.lock);
goto err;
}
}
/*
* We now have a valid CPU that we're targeting for
* this skb. We also have this receive thread locked,
* so we're free to queue skbs into it's queue.
*/
/* If this is a SCSI-FCP frame, and this is already executing on the
* correct CPU, and the queue for this CPU is empty, then go ahead
* and process the frame directly in the softirq context.
* This lets us process completions without context switching from the
* NET_RX softirq, to our receive processing thread, and then back to
* BLOCK softirq context.
*/
if (fh->fh_type == FC_TYPE_FCP &&
cpu == smp_processor_id() &&
skb_queue_empty(&fps->fcoe_rx_list)) {
spin_unlock_bh(&fps->fcoe_rx_list.lock);
fcoe_recv_frame(skb);
} else {
__skb_queue_tail(&fps->fcoe_rx_list, skb);
if (fps->fcoe_rx_list.qlen == 1)
wake_up_process(fps->thread);
spin_unlock_bh(&fps->fcoe_rx_list.lock);
}
return 0;
err:
per_cpu_ptr(lport->dev_stats, get_cpu())->ErrorFrames++;
put_cpu();
err2:
kfree_skb(skb);
return -1;
}
/**
* fcoe_start_io() - Start FCoE I/O
* @skb: The packet to be transmitted
*
* This routine is called from the net device to start transmitting
* FCoE packets.
*
* Returns: 0 for success
*/
static inline int fcoe_start_io(struct sk_buff *skb)
{
struct sk_buff *nskb;
int rc;
nskb = skb_clone(skb, GFP_ATOMIC);
rc = dev_queue_xmit(nskb);
if (rc != 0)
return rc;
kfree_skb(skb);
return 0;
}
/**
* fcoe_get_paged_crc_eof() - Allocate a page to be used for the trailer CRC
* @skb: The packet to be transmitted
* @tlen: The total length of the trailer
*
* This routine allocates a page for frame trailers. The page is re-used if
* there is enough room left on it for the current trailer. If there isn't
* enough buffer left a new page is allocated for the trailer. Reference to
* the page from this function as well as the skbs using the page fragments
* ensure that the page is freed at the appropriate time.
*
* Returns: 0 for success
*/
static int fcoe_get_paged_crc_eof(struct sk_buff *skb, int tlen)
{
struct fcoe_percpu_s *fps;
struct page *page;
fps = &get_cpu_var(fcoe_percpu);
page = fps->crc_eof_page;
if (!page) {
page = alloc_page(GFP_ATOMIC);
if (!page) {
put_cpu_var(fcoe_percpu);
return -ENOMEM;
}
fps->crc_eof_page = page;
fps->crc_eof_offset = 0;
}
get_page(page);
skb_fill_page_desc(skb, skb_shinfo(skb)->nr_frags, page,
fps->crc_eof_offset, tlen);
skb->len += tlen;
skb->data_len += tlen;
skb->truesize += tlen;
fps->crc_eof_offset += sizeof(struct fcoe_crc_eof);
if (fps->crc_eof_offset >= PAGE_SIZE) {
fps->crc_eof_page = NULL;
fps->crc_eof_offset = 0;
put_page(page);
}
put_cpu_var(fcoe_percpu);
return 0;
}
/**
* fcoe_fc_crc() - Calculates the CRC for a given frame
* @fp: The frame to be checksumed
*
* This uses crc32() routine to calculate the CRC for a frame
*
* Return: The 32 bit CRC value
*/
u32 fcoe_fc_crc(struct fc_frame *fp)
{
struct sk_buff *skb = fp_skb(fp);
struct skb_frag_struct *frag;
unsigned char *data;
unsigned long off, len, clen;
u32 crc;
unsigned i;
crc = crc32(~0, skb->data, skb_headlen(skb));
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
frag = &skb_shinfo(skb)->frags[i];
off = frag->page_offset;
len = frag->size;
while (len > 0) {
clen = min(len, PAGE_SIZE - (off & ~PAGE_MASK));
data = kmap_atomic(frag->page + (off >> PAGE_SHIFT),
KM_SKB_DATA_SOFTIRQ);
crc = crc32(crc, data + (off & ~PAGE_MASK), clen);
kunmap_atomic(data, KM_SKB_DATA_SOFTIRQ);
off += clen;
len -= clen;
}
}
return crc;
}
/**
* fcoe_xmit() - Transmit a FCoE frame
* @lport: The local port that the frame is to be transmitted for
* @fp: The frame to be transmitted
*
* Return: 0 for success
*/
int fcoe_xmit(struct fc_lport *lport, struct fc_frame *fp)
{
int wlen;
u32 crc;
struct ethhdr *eh;
struct fcoe_crc_eof *cp;
struct sk_buff *skb;
struct fcoe_dev_stats *stats;
struct fc_frame_header *fh;
unsigned int hlen; /* header length implies the version */
unsigned int tlen; /* trailer length */
unsigned int elen; /* eth header, may include vlan */
struct fcoe_port *port = lport_priv(lport);
struct fcoe_interface *fcoe = port->fcoe;
u8 sof, eof;
struct fcoe_hdr *hp;
WARN_ON((fr_len(fp) % sizeof(u32)) != 0);
fh = fc_frame_header_get(fp);
skb = fp_skb(fp);
wlen = skb->len / FCOE_WORD_TO_BYTE;
if (!lport->link_up) {
kfree_skb(skb);
return 0;
}
if (unlikely(fh->fh_type == FC_TYPE_ELS) &&
fcoe_ctlr_els_send(&fcoe->ctlr, lport, skb))
return 0;
sof = fr_sof(fp);
eof = fr_eof(fp);
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;
/* crc offload */
if (likely(lport->crc_offload)) {
skb->ip_summed = CHECKSUM_PARTIAL;
skb->csum_start = skb_headroom(skb);
skb->csum_offset = skb->len;
crc = 0;
} else {
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 (fcoe_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(frag->page, KM_SKB_DATA_SOFTIRQ)
+ 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, KM_SKB_DATA_SOFTIRQ);
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 = fcoe->netdev;
/* fill up mac and fcoe headers */
eh = eth_hdr(skb);
eh->h_proto = htons(ETH_P_FCOE);
memcpy(eh->h_dest, fcoe->ctlr.dest_addr, ETH_ALEN);
if (fcoe->ctlr.map_dest)
memcpy(eh->h_dest + 3, fh->fh_d_id, 3);
if (unlikely(fcoe->ctlr.flogi_oxid != FC_XID_UNKNOWN))
memcpy(eh->h_source, fcoe->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: regardless if LLD fails */
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;
}
/**
* fcoe_percpu_flush_done() - Indicate per-CPU queue flush completion
* @skb: The completed skb (argument required by destructor)
*/
static void fcoe_percpu_flush_done(struct sk_buff *skb)
{
complete(&fcoe_flush_completion);
}
/**
* fcoe_recv_frame() - process a single received frame
* @skb: frame to process
*/
static void fcoe_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 fcoe_port *port;
struct fcoe_hdr *hp;
fr = fcoe_dev_from_skb(skb);
lport = fr->fr_dev;
if (unlikely(!lport)) {
if (skb->destructor != fcoe_percpu_flush_done)
FCOE_NETDEV_DBG(skb->dev, "NULL lport in skb");
kfree_skb(skb);
return;
}
FCOE_NETDEV_DBG(skb->dev, "skb_info: len:%d data_len:%d "
"head:%p data:%p tail:%p end:%p sum:%d dev:%s",
skb->len, skb->data_len,
skb->head, skb->data, skb_tail_pointer(skb),
skb_end_pointer(skb), skb->csum,
skb->dev ? skb->dev->name : "<NULL>");
port = lport_priv(lport);
if (skb_is_nonlinear(skb))
skb_linearize(skb); /* not ideal */
/*
* Frame length checks and setting up the header pointers
* was done in fcoe_rcv already.
*/
hp = (struct fcoe_hdr *) skb_network_header(skb);
fh = (struct fc_frame_header *) skb_transport_header(skb);
stats = per_cpu_ptr(lport->dev_stats, get_cpu());
if (unlikely(FC_FCOE_DECAPS_VER(hp) != FC_FCOE_VER)) {
if (stats->ErrorFrames < 5)
printk(KERN_WARNING "fcoe: FCoE version "
"mismatch: The frame has "
"version %x, but the "
"initiator supports version "
"%x\n", FC_FCOE_DECAPS_VER(hp),
FC_FCOE_VER);
goto drop;
}
skb_pull(skb, sizeof(struct fcoe_hdr));
fr_len = skb->len - sizeof(struct fcoe_crc_eof);
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;
/* Copy out the CRC and EOF trailer for access */
if (skb_copy_bits(skb, fr_len, &crc_eof, sizeof(crc_eof)))
goto drop;
fr_eof(fp) = crc_eof.fcoe_eof;
fr_crc(fp) = crc_eof.fcoe_crc32;
if (pskb_trim(skb, fr_len))
goto drop;
/*
* We only check CRC if no offload is available and if it is
* it's solicited data, in which case, the FCP layer would
* check it during the copy.
*/
if (lport->crc_offload &&
skb->ip_summed == CHECKSUM_UNNECESSARY)
fr_flags(fp) &= ~FCPHF_CRC_UNCHECKED;
else
fr_flags(fp) |= FCPHF_CRC_UNCHECKED;
fh = fc_frame_header_get(fp);
if ((fh->fh_r_ctl != FC_RCTL_DD_SOL_DATA ||
fh->fh_type != FC_TYPE_FCP) &&
(fr_flags(fp) & FCPHF_CRC_UNCHECKED)) {
if (le32_to_cpu(fr_crc(fp)) !=
~crc32(~0, skb->data, fr_len)) {
if (stats->InvalidCRCCount < 5)
printk(KERN_WARNING "fcoe: dropping "
"frame with CRC error\n");
stats->InvalidCRCCount++;
goto drop;
}
fr_flags(fp) &= ~FCPHF_CRC_UNCHECKED;
}
put_cpu();
fc_exch_recv(lport, fp);
return;
drop:
stats->ErrorFrames++;
put_cpu();
kfree_skb(skb);
}
/**
* fcoe_percpu_receive_thread() - The per-CPU packet receive thread
* @arg: The per-CPU context
*
* Return: 0 for success
*/
int fcoe_percpu_receive_thread(void *arg)
{
struct fcoe_percpu_s *p = arg;
struct sk_buff *skb;
set_user_nice(current, -20);
while (!kthread_should_stop()) {
spin_lock_bh(&p->fcoe_rx_list.lock);
while ((skb = __skb_dequeue(&p->fcoe_rx_list)) == NULL) {
set_current_state(TASK_INTERRUPTIBLE);
spin_unlock_bh(&p->fcoe_rx_list.lock);
schedule();
set_current_state(TASK_RUNNING);
if (kthread_should_stop())
return 0;
spin_lock_bh(&p->fcoe_rx_list.lock);
}
spin_unlock_bh(&p->fcoe_rx_list.lock);
fcoe_recv_frame(skb);
}
return 0;
}
/**
* fcoe_check_wait_queue() - Attempt to clear the transmit backlog
* @lport: The local port whose backlog is to be cleared
*
* This empties the wait_queue, dequeues the head of the wait_queue queue
* and calls fcoe_start_io() for each packet. If all skb have been
* transmitted it returns the qlen. If an error occurs it restores
* wait_queue (to try again later) and returns -1.
*
* The wait_queue is used when the skb transmit fails. The failed skb
* will go in the wait_queue which will be emptied by the timer function or
* by the next skb transmit.
*/
static void fcoe_check_wait_queue(struct fc_lport *lport, struct sk_buff *skb)
{
struct fcoe_port *port = lport_priv(lport);
int rc;
spin_lock_bh(&port->fcoe_pending_queue.lock);
if (skb)
__skb_queue_tail(&port->fcoe_pending_queue, skb);
if (port->fcoe_pending_queue_active)
goto out;
port->fcoe_pending_queue_active = 1;
while (port->fcoe_pending_queue.qlen) {
/* keep qlen > 0 until fcoe_start_io succeeds */
port->fcoe_pending_queue.qlen++;
skb = __skb_dequeue(&port->fcoe_pending_queue);
spin_unlock_bh(&port->fcoe_pending_queue.lock);
rc = fcoe_start_io(skb);
spin_lock_bh(&port->fcoe_pending_queue.lock);
if (rc) {
__skb_queue_head(&port->fcoe_pending_queue, skb);
/* undo temporary increment above */
port->fcoe_pending_queue.qlen--;
break;
}
/* undo temporary increment above */
port->fcoe_pending_queue.qlen--;
}
if (port->fcoe_pending_queue.qlen < FCOE_LOW_QUEUE_DEPTH)
lport->qfull = 0;
if (port->fcoe_pending_queue.qlen && !timer_pending(&port->timer))
mod_timer(&port->timer, jiffies + 2);
port->fcoe_pending_queue_active = 0;
out:
if (port->fcoe_pending_queue.qlen > FCOE_MAX_QUEUE_DEPTH)
lport->qfull = 1;
spin_unlock_bh(&port->fcoe_pending_queue.lock);
return;
}
/**
* fcoe_dev_setup() - Setup the link change notification interface
*/
static void fcoe_dev_setup(void)
{
register_netdevice_notifier(&fcoe_notifier);
}
/**
* fcoe_dev_cleanup() - Cleanup the link change notification interface
*/
static void fcoe_dev_cleanup(void)
{
unregister_netdevice_notifier(&fcoe_notifier);
}
/**
* fcoe_device_notification() - Handler for net device events
* @notifier: The context of the notification
* @event: The type of event
* @ptr: The net device that the event was on
*
* This function is called by the Ethernet driver in case of link change event.
*
* Returns: 0 for success
*/
static int fcoe_device_notification(struct notifier_block *notifier,
ulong event, void *ptr)
{
struct fc_lport *lport = NULL;
struct net_device *netdev = ptr;
struct fcoe_interface *fcoe;
struct fcoe_port *port;
struct fcoe_dev_stats *stats;
u32 link_possible = 1;
u32 mfs;
int rc = NOTIFY_OK;
list_for_each_entry(fcoe, &fcoe_hostlist, list) {
if (fcoe->netdev == netdev) {
lport = fcoe->ctlr.lp;
break;
}
}
if (!lport) {
rc = NOTIFY_DONE;
goto out;
}
switch (event) {
case NETDEV_DOWN:
case NETDEV_GOING_DOWN:
link_possible = 0;
break;
case NETDEV_UP:
case NETDEV_CHANGE:
break;
case NETDEV_CHANGEMTU:
if (netdev->features & NETIF_F_FCOE_MTU)
break;
mfs = netdev->mtu - (sizeof(struct fcoe_hdr) +
sizeof(struct fcoe_crc_eof));
if (mfs >= FC_MIN_MAX_FRAME)
fc_set_mfs(lport, mfs);
break;
case NETDEV_REGISTER:
break;
case NETDEV_UNREGISTER:
list_del(&fcoe->list);
port = lport_priv(fcoe->ctlr.lp);
fcoe_interface_cleanup(fcoe);
schedule_work(&port->destroy_work);
goto out;
break;
case NETDEV_FEAT_CHANGE:
fcoe_netdev_features_change(lport, netdev);
break;
default:
FCOE_NETDEV_DBG(netdev, "Unknown event %ld "
"from netdev netlink\n", event);
}
fcoe_link_speed_update(lport);
if (link_possible && !fcoe_link_ok(lport))
fcoe_ctlr_link_up(&fcoe->ctlr);
else if (fcoe_ctlr_link_down(&fcoe->ctlr)) {
stats = per_cpu_ptr(lport->dev_stats, get_cpu());
stats->LinkFailureCount++;
put_cpu();
fcoe_clean_pending_queue(lport);
}
out:
return rc;
}
/**
* fcoe_if_to_netdev() - Parse a name buffer to get a net device
* @buffer: The name of the net device
*
* Returns: NULL or a ptr to net_device
*/
static struct net_device *fcoe_if_to_netdev(const char *buffer)
{
char *cp;
char ifname[IFNAMSIZ + 2];
if (buffer) {
strlcpy(ifname, buffer, IFNAMSIZ);
cp = ifname + strlen(ifname);
while (--cp >= ifname && *cp == '\n')
*cp = '\0';
return dev_get_by_name(&init_net, ifname);
}
return NULL;
}
/**
* fcoe_disable() - Disables a FCoE interface
* @buffer: The name of the Ethernet interface to be disabled
* @kp: The associated kernel parameter
*
* Called from sysfs.
*
* Returns: 0 for success
*/
static int fcoe_disable(const char *buffer, struct kernel_param *kp)
{
struct fcoe_interface *fcoe;
struct net_device *netdev;
int rc = 0;
mutex_lock(&fcoe_config_mutex);
#ifdef CONFIG_FCOE_MODULE
/*
* Make sure the module has been initialized, and is not about to be
* removed. Module paramter sysfs files are writable before the
* module_init function is called and after module_exit.
*/
if (THIS_MODULE->state != MODULE_STATE_LIVE) {
rc = -ENODEV;
goto out_nodev;
}
#endif
netdev = fcoe_if_to_netdev(buffer);
if (!netdev) {
rc = -ENODEV;
goto out_nodev;
}
if (!rtnl_trylock()) {
dev_put(netdev);
mutex_unlock(&fcoe_config_mutex);
return restart_syscall();
}
fcoe = fcoe_hostlist_lookup_port(netdev);
rtnl_unlock();
if (fcoe) {
fcoe_ctlr_link_down(&fcoe->ctlr);
fcoe_clean_pending_queue(fcoe->ctlr.lp);
} else
rc = -ENODEV;
dev_put(netdev);
out_nodev:
mutex_unlock(&fcoe_config_mutex);
return rc;
}
/**
* fcoe_enable() - Enables a FCoE interface
* @buffer: The name of the Ethernet interface to be enabled
* @kp: The associated kernel parameter
*
* Called from sysfs.
*
* Returns: 0 for success
*/
static int fcoe_enable(const char *buffer, struct kernel_param *kp)
{
struct fcoe_interface *fcoe;
struct net_device *netdev;
int rc = 0;
mutex_lock(&fcoe_config_mutex);
#ifdef CONFIG_FCOE_MODULE
/*
* Make sure the module has been initialized, and is not about to be
* removed. Module paramter sysfs files are writable before the
* module_init function is called and after module_exit.
*/
if (THIS_MODULE->state != MODULE_STATE_LIVE) {
rc = -ENODEV;
goto out_nodev;
}
#endif
netdev = fcoe_if_to_netdev(buffer);
if (!netdev) {
rc = -ENODEV;
goto out_nodev;
}
if (!rtnl_trylock()) {
dev_put(netdev);
mutex_unlock(&fcoe_config_mutex);
return restart_syscall();
}
fcoe = fcoe_hostlist_lookup_port(netdev);
rtnl_unlock();
if (!fcoe)
rc = -ENODEV;
else if (!fcoe_link_ok(fcoe->ctlr.lp))
fcoe_ctlr_link_up(&fcoe->ctlr);
dev_put(netdev);
out_nodev:
mutex_unlock(&fcoe_config_mutex);
return rc;
}
/**
* fcoe_destroy() - Destroy a 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 fcoe_destroy(const char *buffer, struct kernel_param *kp)
{
struct fcoe_interface *fcoe;
struct net_device *netdev;
int rc = 0;
mutex_lock(&fcoe_config_mutex);
#ifdef CONFIG_FCOE_MODULE
/*
* Make sure the module has been initialized, and is not about to be
* removed. Module paramter sysfs files are writable before the
* module_init function is called and after module_exit.
*/
if (THIS_MODULE->state != MODULE_STATE_LIVE) {
rc = -ENODEV;
goto out_nodev;
}
#endif
netdev = fcoe_if_to_netdev(buffer);
if (!netdev) {
rc = -ENODEV;
goto out_nodev;
}
if (!rtnl_trylock()) {
dev_put(netdev);
mutex_unlock(&fcoe_config_mutex);
return restart_syscall();
}
fcoe = fcoe_hostlist_lookup_port(netdev);
if (!fcoe) {
rtnl_unlock();
rc = -ENODEV;
goto out_putdev;
}
fcoe_interface_cleanup(fcoe);
list_del(&fcoe->list);
/* RTNL mutex is dropped by fcoe_if_destroy */
fcoe_if_destroy(fcoe->ctlr.lp);
out_putdev:
dev_put(netdev);
out_nodev:
mutex_unlock(&fcoe_config_mutex);
return rc;
}
/**
* fcoe_destroy_work() - Destroy a FCoE port in a deferred work context
* @work: Handle to the FCoE port to be destroyed
*/
static void fcoe_destroy_work(struct work_struct *work)
{
struct fcoe_port *port;
port = container_of(work, struct fcoe_port, destroy_work);
mutex_lock(&fcoe_config_mutex);
rtnl_lock();
/* RTNL mutex is dropped by fcoe_if_destroy */
fcoe_if_destroy(port->lport);
mutex_unlock(&fcoe_config_mutex);
}
/**
* fcoe_create() - Create a fcoe interface
* @buffer: The name of the Ethernet interface to create on
* @kp: The associated kernel param
*
* Called from sysfs.
*
* Returns: 0 for success
*/
static int fcoe_create(const char *buffer, struct kernel_param *kp)
{
enum fip_state fip_mode = (enum fip_state)(long)kp->arg;
int rc;
struct fcoe_interface *fcoe;
struct fc_lport *lport;
struct net_device *netdev;
mutex_lock(&fcoe_config_mutex);
if (!rtnl_trylock()) {
mutex_unlock(&fcoe_config_mutex);
return restart_syscall();
}
#ifdef CONFIG_FCOE_MODULE
/*
* Make sure the module has been initialized, and is not about to be
* removed. Module paramter sysfs files are writable before the
* module_init function is called and after module_exit.
*/
if (THIS_MODULE->state != MODULE_STATE_LIVE) {
rc = -ENODEV;
goto out_nomod;
}
#endif
if (!try_module_get(THIS_MODULE)) {
rc = -EINVAL;
goto out_nomod;
}
netdev = fcoe_if_to_netdev(buffer);
if (!netdev) {
rc = -ENODEV;
goto out_nodev;
}
/* look for existing lport */
if (fcoe_hostlist_lookup(netdev)) {
rc = -EEXIST;
goto out_putdev;
}
fcoe = fcoe_interface_create(netdev, fip_mode);
if (!fcoe) {
rc = -ENOMEM;
goto out_putdev;
}
lport = fcoe_if_create(fcoe, &netdev->dev, 0);
if (IS_ERR(lport)) {
printk(KERN_ERR "fcoe: Failed to create interface (%s)\n",
netdev->name);
rc = -EIO;
fcoe_interface_cleanup(fcoe);
goto out_free;
}
/* Make this the "master" N_Port */
fcoe->ctlr.lp = lport;
/* add to lports list */
fcoe_hostlist_add(lport);
/* start FIP Discovery and FLOGI */
lport->boot_time = jiffies;
fc_fabric_login(lport);
if (!fcoe_link_ok(lport))
fcoe_ctlr_link_up(&fcoe->ctlr);
/*
* Release from init in fcoe_interface_create(), on success lport
* should be holding a reference taken in fcoe_if_create().
*/
fcoe_interface_put(fcoe);
dev_put(netdev);
rtnl_unlock();
mutex_unlock(&fcoe_config_mutex);
return 0;
out_free:
fcoe_interface_put(fcoe);
out_putdev:
dev_put(netdev);
out_nodev:
module_put(THIS_MODULE);
out_nomod:
rtnl_unlock();
mutex_unlock(&fcoe_config_mutex);
return rc;
}
/**
* fcoe_link_speed_update() - Update the supported and actual link speeds
* @lport: The local port to update speeds for
*
* Returns: 0 if the ethtool query was successful
* -1 if the ethtool query failed
*/
int fcoe_link_speed_update(struct fc_lport *lport)
{
struct fcoe_port *port = lport_priv(lport);
struct net_device *netdev = port->fcoe->netdev;
struct ethtool_cmd ecmd = { ETHTOOL_GSET };
if (!dev_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;
if (ecmd.speed == SPEED_1000)
lport->link_speed = FC_PORTSPEED_1GBIT;
if (ecmd.speed == SPEED_10000)
lport->link_speed = FC_PORTSPEED_10GBIT;
return 0;
}
return -1;
}
/**
* fcoe_link_ok() - Check if the link is OK for a local port
* @lport: The local port to check link on
*
* Returns: 0 if link is UP and OK, -1 if not
*
*/
int fcoe_link_ok(struct fc_lport *lport)
{
struct fcoe_port *port = lport_priv(lport);
struct net_device *netdev = port->fcoe->netdev;
if (netif_oper_up(netdev))
return 0;
return -1;
}
/**
* fcoe_percpu_clean() - Clear all pending skbs for an local port
* @lport: The local port whose skbs are to be cleared
*
* Must be called with fcoe_create_mutex held to single-thread completion.
*
* This flushes the pending skbs by adding a new skb to each queue and
* waiting until they are all freed. This assures us that not only are
* there no packets that will be handled by the lport, but also that any
* threads already handling packet have returned.
*/
void fcoe_percpu_clean(struct fc_lport *lport)
{
struct fcoe_percpu_s *pp;
struct fcoe_rcv_info *fr;
struct sk_buff_head *list;
struct sk_buff *skb, *next;
struct sk_buff *head;
unsigned int cpu;
for_each_possible_cpu(cpu) {
pp = &per_cpu(fcoe_percpu, cpu);
spin_lock_bh(&pp->fcoe_rx_list.lock);
list = &pp->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 == lport) {
__skb_unlink(skb, list);
kfree_skb(skb);
}
}
if (!pp->thread || !cpu_online(cpu)) {
spin_unlock_bh(&pp->fcoe_rx_list.lock);
continue;
}
skb = dev_alloc_skb(0);
if (!skb) {
spin_unlock_bh(&pp->fcoe_rx_list.lock);
continue;
}
skb->destructor = fcoe_percpu_flush_done;
__skb_queue_tail(&pp->fcoe_rx_list, skb);
if (pp->fcoe_rx_list.qlen == 1)
wake_up_process(pp->thread);
spin_unlock_bh(&pp->fcoe_rx_list.lock);
wait_for_completion(&fcoe_flush_completion);
}
}
/**
* fcoe_clean_pending_queue() - Dequeue a skb and free it
* @lport: The local port to dequeue a skb on
*/
void fcoe_clean_pending_queue(struct fc_lport *lport)
{
struct fcoe_port *port = lport_priv(lport);
struct sk_buff *skb;
spin_lock_bh(&port->fcoe_pending_queue.lock);
while ((skb = __skb_dequeue(&port->fcoe_pending_queue)) != NULL) {
spin_unlock_bh(&port->fcoe_pending_queue.lock);
kfree_skb(skb);
spin_lock_bh(&port->fcoe_pending_queue.lock);
}
spin_unlock_bh(&port->fcoe_pending_queue.lock);
}
/**
* fcoe_reset() - Reset a local port
* @shost: The SCSI host associated with the local port to be reset
*
* Returns: Always 0 (return value required by FC transport template)
*/
int fcoe_reset(struct Scsi_Host *shost)
{
struct fc_lport *lport = shost_priv(shost);
fc_lport_reset(lport);
return 0;
}
/**
* fcoe_hostlist_lookup_port() - Find the FCoE interface associated with a net device
* @netdev: The net device used as a key
*
* Locking: Must be called with the RNL mutex held.
*
* Returns: NULL or the FCoE interface
*/
static struct fcoe_interface *
fcoe_hostlist_lookup_port(const struct net_device *netdev)
{
struct fcoe_interface *fcoe;
list_for_each_entry(fcoe, &fcoe_hostlist, list) {
if (fcoe->netdev == netdev)
return fcoe;
}
return NULL;
}
/**
* fcoe_hostlist_lookup() - Find the local port associated with a
* given net device
* @netdev: The netdevice used as a key
*
* Locking: Must be called with the RTNL mutex held
*
* Returns: NULL or the local port
*/
static struct fc_lport *fcoe_hostlist_lookup(const struct net_device *netdev)
{
struct fcoe_interface *fcoe;
fcoe = fcoe_hostlist_lookup_port(netdev);
return (fcoe) ? fcoe->ctlr.lp : NULL;
}
/**
* fcoe_hostlist_add() - Add the FCoE interface identified by a local
* port to the hostlist
* @lport: The local port that identifies the FCoE interface to be added
*
* Locking: must be called with the RTNL mutex held
*
* Returns: 0 for success
*/
static int fcoe_hostlist_add(const struct fc_lport *lport)
{
struct fcoe_interface *fcoe;
struct fcoe_port *port;
fcoe = fcoe_hostlist_lookup_port(fcoe_netdev(lport));
if (!fcoe) {
port = lport_priv(lport);
fcoe = port->fcoe;
list_add_tail(&fcoe->list, &fcoe_hostlist);
}
return 0;
}
/**
* fcoe_init() - Initialize fcoe.ko
*
* Returns: 0 on success, or a negative value on failure
*/
static int __init fcoe_init(void)
{
struct fcoe_percpu_s *p;
unsigned int cpu;
int rc = 0;
mutex_lock(&fcoe_config_mutex);
for_each_possible_cpu(cpu) {
p = &per_cpu(fcoe_percpu, cpu);
skb_queue_head_init(&p->fcoe_rx_list);
}
for_each_online_cpu(cpu)
fcoe_percpu_thread_create(cpu);
/* Initialize per CPU interrupt thread */
rc = register_hotcpu_notifier(&fcoe_cpu_notifier);
if (rc)
goto out_free;
/* Setup link change notification */
fcoe_dev_setup();
rc = fcoe_if_init();
if (rc)
goto out_free;
mutex_unlock(&fcoe_config_mutex);
return 0;
out_free:
for_each_online_cpu(cpu) {
fcoe_percpu_thread_destroy(cpu);
}
mutex_unlock(&fcoe_config_mutex);
return rc;
}
module_init(fcoe_init);
/**
* fcoe_exit() - Clean up fcoe.ko
*
* Returns: 0 on success or a negative value on failure
*/
static void __exit fcoe_exit(void)
{
struct fcoe_interface *fcoe, *tmp;
struct fcoe_port *port;
unsigned int cpu;
mutex_lock(&fcoe_config_mutex);
fcoe_dev_cleanup();
/* releases the associated fcoe hosts */
rtnl_lock();
list_for_each_entry_safe(fcoe, tmp, &fcoe_hostlist, list) {
list_del(&fcoe->list);
port = lport_priv(fcoe->ctlr.lp);
fcoe_interface_cleanup(fcoe);
schedule_work(&port->destroy_work);
}
rtnl_unlock();
unregister_hotcpu_notifier(&fcoe_cpu_notifier);
for_each_online_cpu(cpu)
fcoe_percpu_thread_destroy(cpu);
mutex_unlock(&fcoe_config_mutex);
/* flush any asyncronous interface destroys,
* this should happen after the netdev notifier is unregistered */
flush_scheduled_work();
/* That will flush out all the N_Ports on the hostlist, but now we
* may have NPIV VN_Ports scheduled for destruction */
flush_scheduled_work();
/* detach from scsi transport
* must happen after all destroys are done, therefor after the flush */
fcoe_if_exit();
}
module_exit(fcoe_exit);
/**
* fcoe_flogi_resp() - FCoE specific FLOGI and FDISC response handler
* @seq: active sequence in the FLOGI or FDISC exchange
* @fp: response frame, or error encoded in a pointer (timeout)
* @arg: pointer the the fcoe_ctlr structure
*
* This handles MAC address management for FCoE, then passes control on to
* the libfc FLOGI response handler.
*/
static void fcoe_flogi_resp(struct fc_seq *seq, struct fc_frame *fp, void *arg)
{
struct fcoe_ctlr *fip = arg;
struct fc_exch *exch = fc_seq_exch(seq);
struct fc_lport *lport = exch->lp;
u8 *mac;
if (IS_ERR(fp))
goto done;
mac = fr_cb(fp)->granted_mac;
if (is_zero_ether_addr(mac)) {
/* pre-FIP */
if (fcoe_ctlr_recv_flogi(fip, lport, fp)) {
fc_frame_free(fp);
return;
}
}
fcoe_update_src_mac(lport, mac);
done:
fc_lport_flogi_resp(seq, fp, lport);
}
/**
* fcoe_logo_resp() - FCoE specific LOGO response handler
* @seq: active sequence in the LOGO exchange
* @fp: response frame, or error encoded in a pointer (timeout)
* @arg: pointer the the fcoe_ctlr structure
*
* This handles MAC address management for FCoE, then passes control on to
* the libfc LOGO response handler.
*/
static void fcoe_logo_resp(struct fc_seq *seq, struct fc_frame *fp, void *arg)
{
struct fc_lport *lport = arg;
static u8 zero_mac[ETH_ALEN] = { 0 };
if (!IS_ERR(fp))
fcoe_update_src_mac(lport, zero_mac);
fc_lport_logo_resp(seq, fp, lport);
}
/**
* fcoe_elsct_send - FCoE specific ELS handler
*
* This does special case handling of FIP encapsualted ELS exchanges for FCoE,
* using FCoE specific response handlers and passing the FIP controller as
* the argument (the lport is still available from the exchange).
*
* Most of the work here is just handed off to the libfc routine.
*/
static struct fc_seq *fcoe_elsct_send(struct fc_lport *lport, u32 did,
struct fc_frame *fp, unsigned int op,
void (*resp)(struct fc_seq *,
struct fc_frame *,
void *),
void *arg, u32 timeout)
{
struct fcoe_port *port = lport_priv(lport);
struct fcoe_interface *fcoe = port->fcoe;
struct fcoe_ctlr *fip = &fcoe->ctlr;
struct fc_frame_header *fh = fc_frame_header_get(fp);
switch (op) {
case ELS_FLOGI:
case ELS_FDISC:
if (lport->point_to_multipoint)
break;
return fc_elsct_send(lport, did, fp, op, fcoe_flogi_resp,
fip, timeout);
case ELS_LOGO:
/* only hook onto fabric logouts, not port logouts */
if (ntoh24(fh->fh_d_id) != FC_FID_FLOGI)
break;
return fc_elsct_send(lport, did, fp, op, fcoe_logo_resp,
lport, timeout);
}
return fc_elsct_send(lport, did, fp, op, resp, arg, timeout);
}
/**
* fcoe_vport_create() - create an fc_host/scsi_host for a vport
* @vport: fc_vport object to create a new fc_host for
* @disabled: start the new fc_host in a disabled state by default?
*
* Returns: 0 for success
*/
static int fcoe_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 fcoe_interface *fcoe = port->fcoe;
struct net_device *netdev = fcoe->netdev;
struct fc_lport *vn_port;
mutex_lock(&fcoe_config_mutex);
vn_port = fcoe_if_create(fcoe, &vport->dev, 1);
mutex_unlock(&fcoe_config_mutex);
if (IS_ERR(vn_port)) {
printk(KERN_ERR "fcoe: fcoe_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_fabric_login(vn_port);
fc_vport_setlink(vn_port);
}
return 0;
}
/**
* fcoe_vport_destroy() - destroy the fc_host/scsi_host for a vport
* @vport: fc_vport object that is being destroyed
*
* Returns: 0 for success
*/
static int fcoe_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);
mutex_lock(&n_port->lp_mutex);
list_del(&vn_port->list);
mutex_unlock(&n_port->lp_mutex);
schedule_work(&port->destroy_work);
return 0;
}
/**
* fcoe_vport_disable() - change vport state
* @vport: vport to bring online/offline
* @disable: should the vport be disabled?
*/
static int fcoe_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;
}
/**
* fcoe_vport_set_symbolic_name() - append vport string to symbolic name
* @vport: fc_vport with a new symbolic name string
*
* After generating a new symbolic name string, a new RSPN_ID request is
* sent to the name server. There is no response handler, so if it fails
* for some reason it will not be retried.
*/
static void fcoe_set_vport_symbolic_name(struct fc_vport *vport)
{
struct fc_lport *lport = vport->dd_data;
struct fc_frame *fp;
size_t len;
snprintf(fc_host_symbolic_name(lport->host), FC_SYMBOLIC_NAME_SIZE,
"%s v%s over %s : %s", FCOE_NAME, FCOE_VERSION,
fcoe_netdev(lport)->name, vport->symbolic_name);
if (lport->state != LPORT_ST_READY)
return;
len = strnlen(fc_host_symbolic_name(lport->host), 255);
fp = fc_frame_alloc(lport,
sizeof(struct fc_ct_hdr) +
sizeof(struct fc_ns_rspn) + len);
if (!fp)
return;
lport->tt.elsct_send(lport, FC_FID_DIR_SERV, fp, FC_NS_RSPN_ID,
NULL, NULL, 3 * lport->r_a_tov);
}
/**
* fcoe_get_lesb() - Fill the FCoE Link Error Status Block
* @lport: the local port
* @fc_lesb: the link error status block
*/
static void fcoe_get_lesb(struct fc_lport *lport,
struct fc_els_lesb *fc_lesb)
{
unsigned int cpu;
u32 lfc, vlfc, mdac;
struct fcoe_dev_stats *devst;
struct fcoe_fc_els_lesb *lesb;
struct rtnl_link_stats64 temp;
struct net_device *netdev = fcoe_netdev(lport);
lfc = 0;
vlfc = 0;
mdac = 0;
lesb = (struct fcoe_fc_els_lesb *)fc_lesb;
memset(lesb, 0, sizeof(*lesb));
for_each_possible_cpu(cpu) {
devst = per_cpu_ptr(lport->dev_stats, cpu);
lfc += devst->LinkFailureCount;
vlfc += devst->VLinkFailureCount;
mdac += devst->MissDiscAdvCount;
}
lesb->lesb_link_fail = htonl(lfc);
lesb->lesb_vlink_fail = htonl(vlfc);
lesb->lesb_miss_fka = htonl(mdac);
lesb->lesb_fcs_error = htonl(dev_get_stats(netdev, &temp)->rx_crc_errors);
}
/**
* fcoe_set_port_id() - Callback from libfc when Port_ID is set.
* @lport: the local port
* @port_id: the port ID
* @fp: the received frame, if any, that caused the port_id to be set.
*
* This routine handles the case where we received a FLOGI and are
* entering point-to-point mode. We need to call fcoe_ctlr_recv_flogi()
* so it can set the non-mapped mode and gateway address.
*
* The FLOGI LS_ACC is handled by fcoe_flogi_resp().
*/
static void fcoe_set_port_id(struct fc_lport *lport,
u32 port_id, struct fc_frame *fp)
{
struct fcoe_port *port = lport_priv(lport);
struct fcoe_interface *fcoe = port->fcoe;
if (fp && fc_frame_payload_op(fp) == ELS_FLOGI)
fcoe_ctlr_recv_flogi(&fcoe->ctlr, lport, fp);
}
| gpl-2.0 |
Linhu86/mylinux | fs/hfsplus/attributes.c | 51 | 9326 | /*
* linux/fs/hfsplus/attributes.c
*
* Vyacheslav Dubeyko <slava@dubeyko.com>
*
* Handling of records in attributes tree
*/
#include "hfsplus_fs.h"
#include "hfsplus_raw.h"
static struct kmem_cache *hfsplus_attr_tree_cachep;
int __init hfsplus_create_attr_tree_cache(void)
{
if (hfsplus_attr_tree_cachep)
return -EEXIST;
hfsplus_attr_tree_cachep =
kmem_cache_create("hfsplus_attr_cache",
sizeof(hfsplus_attr_entry), 0,
SLAB_HWCACHE_ALIGN, NULL);
if (!hfsplus_attr_tree_cachep)
return -ENOMEM;
return 0;
}
void hfsplus_destroy_attr_tree_cache(void)
{
kmem_cache_destroy(hfsplus_attr_tree_cachep);
}
int hfsplus_attr_bin_cmp_key(const hfsplus_btree_key *k1,
const hfsplus_btree_key *k2)
{
__be32 k1_cnid, k2_cnid;
k1_cnid = k1->attr.cnid;
k2_cnid = k2->attr.cnid;
if (k1_cnid != k2_cnid)
return be32_to_cpu(k1_cnid) < be32_to_cpu(k2_cnid) ? -1 : 1;
return hfsplus_strcmp(
(const struct hfsplus_unistr *)&k1->attr.key_name,
(const struct hfsplus_unistr *)&k2->attr.key_name);
}
int hfsplus_attr_build_key(struct super_block *sb, hfsplus_btree_key *key,
u32 cnid, const char *name)
{
int len;
memset(key, 0, sizeof(struct hfsplus_attr_key));
key->attr.cnid = cpu_to_be32(cnid);
if (name) {
len = strlen(name);
if (len > HFSPLUS_ATTR_MAX_STRLEN) {
pr_err("invalid xattr name's length\n");
return -EINVAL;
}
hfsplus_asc2uni(sb,
(struct hfsplus_unistr *)&key->attr.key_name,
HFSPLUS_ATTR_MAX_STRLEN, name, len);
len = be16_to_cpu(key->attr.key_name.length);
} else {
key->attr.key_name.length = 0;
len = 0;
}
/* The length of the key, as stored in key_len field, does not include
* the size of the key_len field itself.
* So, offsetof(hfsplus_attr_key, key_name) is a trick because
* it takes into consideration key_len field (__be16) of
* hfsplus_attr_key structure instead of length field (__be16) of
* hfsplus_attr_unistr structure.
*/
key->key_len =
cpu_to_be16(offsetof(struct hfsplus_attr_key, key_name) +
2 * len);
return 0;
}
void hfsplus_attr_build_key_uni(hfsplus_btree_key *key,
u32 cnid,
struct hfsplus_attr_unistr *name)
{
int ustrlen;
memset(key, 0, sizeof(struct hfsplus_attr_key));
ustrlen = be16_to_cpu(name->length);
key->attr.cnid = cpu_to_be32(cnid);
key->attr.key_name.length = cpu_to_be16(ustrlen);
ustrlen *= 2;
memcpy(key->attr.key_name.unicode, name->unicode, ustrlen);
/* The length of the key, as stored in key_len field, does not include
* the size of the key_len field itself.
* So, offsetof(hfsplus_attr_key, key_name) is a trick because
* it takes into consideration key_len field (__be16) of
* hfsplus_attr_key structure instead of length field (__be16) of
* hfsplus_attr_unistr structure.
*/
key->key_len =
cpu_to_be16(offsetof(struct hfsplus_attr_key, key_name) +
ustrlen);
}
hfsplus_attr_entry *hfsplus_alloc_attr_entry(void)
{
return kmem_cache_alloc(hfsplus_attr_tree_cachep, GFP_KERNEL);
}
void hfsplus_destroy_attr_entry(hfsplus_attr_entry *entry)
{
if (entry)
kmem_cache_free(hfsplus_attr_tree_cachep, entry);
}
#define HFSPLUS_INVALID_ATTR_RECORD -1
static int hfsplus_attr_build_record(hfsplus_attr_entry *entry, int record_type,
u32 cnid, const void *value, size_t size)
{
if (record_type == HFSPLUS_ATTR_FORK_DATA) {
/*
* Mac OS X supports only inline data attributes.
* Do nothing
*/
memset(entry, 0, sizeof(*entry));
return sizeof(struct hfsplus_attr_fork_data);
} else if (record_type == HFSPLUS_ATTR_EXTENTS) {
/*
* Mac OS X supports only inline data attributes.
* Do nothing.
*/
memset(entry, 0, sizeof(*entry));
return sizeof(struct hfsplus_attr_extents);
} else if (record_type == HFSPLUS_ATTR_INLINE_DATA) {
u16 len;
memset(entry, 0, sizeof(struct hfsplus_attr_inline_data));
entry->inline_data.record_type = cpu_to_be32(record_type);
if (size <= HFSPLUS_MAX_INLINE_DATA_SIZE)
len = size;
else
return HFSPLUS_INVALID_ATTR_RECORD;
entry->inline_data.length = cpu_to_be16(len);
memcpy(entry->inline_data.raw_bytes, value, len);
/*
* Align len on two-byte boundary.
* It needs to add pad byte if we have odd len.
*/
len = round_up(len, 2);
return offsetof(struct hfsplus_attr_inline_data, raw_bytes) +
len;
} else /* invalid input */
memset(entry, 0, sizeof(*entry));
return HFSPLUS_INVALID_ATTR_RECORD;
}
int hfsplus_find_attr(struct super_block *sb, u32 cnid,
const char *name, struct hfs_find_data *fd)
{
int err = 0;
hfs_dbg(ATTR_MOD, "find_attr: %s,%d\n", name ? name : NULL, cnid);
if (!HFSPLUS_SB(sb)->attr_tree) {
pr_err("attributes file doesn't exist\n");
return -EINVAL;
}
if (name) {
err = hfsplus_attr_build_key(sb, fd->search_key, cnid, name);
if (err)
goto failed_find_attr;
err = hfs_brec_find(fd, hfs_find_rec_by_key);
if (err)
goto failed_find_attr;
} else {
err = hfsplus_attr_build_key(sb, fd->search_key, cnid, NULL);
if (err)
goto failed_find_attr;
err = hfs_brec_find(fd, hfs_find_1st_rec_by_cnid);
if (err)
goto failed_find_attr;
}
failed_find_attr:
return err;
}
int hfsplus_attr_exists(struct inode *inode, const char *name)
{
int err = 0;
struct super_block *sb = inode->i_sb;
struct hfs_find_data fd;
if (!HFSPLUS_SB(sb)->attr_tree)
return 0;
err = hfs_find_init(HFSPLUS_SB(sb)->attr_tree, &fd);
if (err)
return 0;
err = hfsplus_find_attr(sb, inode->i_ino, name, &fd);
if (err)
goto attr_not_found;
hfs_find_exit(&fd);
return 1;
attr_not_found:
hfs_find_exit(&fd);
return 0;
}
int hfsplus_create_attr(struct inode *inode,
const char *name,
const void *value, size_t size)
{
struct super_block *sb = inode->i_sb;
struct hfs_find_data fd;
hfsplus_attr_entry *entry_ptr;
int entry_size;
int err;
hfs_dbg(ATTR_MOD, "create_attr: %s,%ld\n",
name ? name : NULL, inode->i_ino);
if (!HFSPLUS_SB(sb)->attr_tree) {
pr_err("attributes file doesn't exist\n");
return -EINVAL;
}
entry_ptr = hfsplus_alloc_attr_entry();
if (!entry_ptr)
return -ENOMEM;
err = hfs_find_init(HFSPLUS_SB(sb)->attr_tree, &fd);
if (err)
goto failed_init_create_attr;
if (name) {
err = hfsplus_attr_build_key(sb, fd.search_key,
inode->i_ino, name);
if (err)
goto failed_create_attr;
} else {
err = -EINVAL;
goto failed_create_attr;
}
/* Mac OS X supports only inline data attributes. */
entry_size = hfsplus_attr_build_record(entry_ptr,
HFSPLUS_ATTR_INLINE_DATA,
inode->i_ino,
value, size);
if (entry_size == HFSPLUS_INVALID_ATTR_RECORD) {
err = -EINVAL;
goto failed_create_attr;
}
err = hfs_brec_find(&fd, hfs_find_rec_by_key);
if (err != -ENOENT) {
if (!err)
err = -EEXIST;
goto failed_create_attr;
}
err = hfs_brec_insert(&fd, entry_ptr, entry_size);
if (err)
goto failed_create_attr;
hfsplus_mark_inode_dirty(inode, HFSPLUS_I_ATTR_DIRTY);
failed_create_attr:
hfs_find_exit(&fd);
failed_init_create_attr:
hfsplus_destroy_attr_entry(entry_ptr);
return err;
}
static int __hfsplus_delete_attr(struct inode *inode, u32 cnid,
struct hfs_find_data *fd)
{
int err = 0;
__be32 found_cnid, record_type;
hfs_bnode_read(fd->bnode, &found_cnid,
fd->keyoffset +
offsetof(struct hfsplus_attr_key, cnid),
sizeof(__be32));
if (cnid != be32_to_cpu(found_cnid))
return -ENOENT;
hfs_bnode_read(fd->bnode, &record_type,
fd->entryoffset, sizeof(record_type));
switch (be32_to_cpu(record_type)) {
case HFSPLUS_ATTR_INLINE_DATA:
/* All is OK. Do nothing. */
break;
case HFSPLUS_ATTR_FORK_DATA:
case HFSPLUS_ATTR_EXTENTS:
pr_err("only inline data xattr are supported\n");
return -EOPNOTSUPP;
default:
pr_err("invalid extended attribute record\n");
return -ENOENT;
}
err = hfs_brec_remove(fd);
if (err)
return err;
hfsplus_mark_inode_dirty(inode, HFSPLUS_I_ATTR_DIRTY);
return err;
}
int hfsplus_delete_attr(struct inode *inode, const char *name)
{
int err = 0;
struct super_block *sb = inode->i_sb;
struct hfs_find_data fd;
hfs_dbg(ATTR_MOD, "delete_attr: %s,%ld\n",
name ? name : NULL, inode->i_ino);
if (!HFSPLUS_SB(sb)->attr_tree) {
pr_err("attributes file doesn't exist\n");
return -EINVAL;
}
err = hfs_find_init(HFSPLUS_SB(sb)->attr_tree, &fd);
if (err)
return err;
if (name) {
err = hfsplus_attr_build_key(sb, fd.search_key,
inode->i_ino, name);
if (err)
goto out;
} else {
pr_err("invalid extended attribute name\n");
err = -EINVAL;
goto out;
}
err = hfs_brec_find(&fd, hfs_find_rec_by_key);
if (err)
goto out;
err = __hfsplus_delete_attr(inode, inode->i_ino, &fd);
if (err)
goto out;
out:
hfs_find_exit(&fd);
return err;
}
int hfsplus_delete_all_attrs(struct inode *dir, u32 cnid)
{
int err = 0;
struct hfs_find_data fd;
hfs_dbg(ATTR_MOD, "delete_all_attrs: %d\n", cnid);
if (!HFSPLUS_SB(dir->i_sb)->attr_tree) {
pr_err("attributes file doesn't exist\n");
return -EINVAL;
}
err = hfs_find_init(HFSPLUS_SB(dir->i_sb)->attr_tree, &fd);
if (err)
return err;
for (;;) {
err = hfsplus_find_attr(dir->i_sb, cnid, NULL, &fd);
if (err) {
if (err != -ENOENT)
pr_err("xattr search failed\n");
goto end_delete_all;
}
err = __hfsplus_delete_attr(dir, cnid, &fd);
if (err)
goto end_delete_all;
}
end_delete_all:
hfs_find_exit(&fd);
return err;
}
| gpl-2.0 |
Savaged-Zen/Savaged-Zen-Speedy | arch/arm/mach-mx5/board-mx51_babbage.c | 51 | 9802 | /*
* Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved.
* Copyright (C) 2009-2010 Amit Kucheria <amit.kucheria@canonical.com>
*
* The code contained herein is licensed under the GNU General Public
* License. You may obtain a copy of the GNU General Public License
* Version 2 or later at the following locations:
*
* http://www.opensource.org/licenses/gpl-license.html
* http://www.gnu.org/copyleft/gpl.html
*/
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/i2c.h>
#include <linux/gpio.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/fsl_devices.h>
#include <linux/fec.h>
#include <linux/gpio_keys.h>
#include <linux/input.h>
#include <mach/common.h>
#include <mach/hardware.h>
#include <mach/iomux-mx51.h>
#include <mach/mxc_ehci.h>
#include <asm/irq.h>
#include <asm/setup.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/time.h>
#include "devices-imx51.h"
#include "devices.h"
#include "cpu_op-mx51.h"
#define BABBAGE_USB_HUB_RESET (0*32 + 7) /* GPIO_1_7 */
#define BABBAGE_USBH1_STP (0*32 + 27) /* GPIO_1_27 */
#define BABBAGE_PHY_RESET (1*32 + 5) /* GPIO_2_5 */
#define BABBAGE_FEC_PHY_RESET (1*32 + 14) /* GPIO_2_14 */
#define BABBAGE_POWER_KEY (1*32 + 21) /* GPIO_2_21 */
/* USB_CTRL_1 */
#define MX51_USB_CTRL_1_OFFSET 0x10
#define MX51_USB_CTRL_UH1_EXT_CLK_EN (1 << 25)
#define MX51_USB_PLLDIV_12_MHZ 0x00
#define MX51_USB_PLL_DIV_19_2_MHZ 0x01
#define MX51_USB_PLL_DIV_24_MHZ 0x02
static struct gpio_keys_button babbage_buttons[] = {
{
.gpio = BABBAGE_POWER_KEY,
.code = BTN_0,
.desc = "PWR",
.active_low = 1,
.wakeup = 1,
},
};
static const struct gpio_keys_platform_data imx_button_data __initconst = {
.buttons = babbage_buttons,
.nbuttons = ARRAY_SIZE(babbage_buttons),
};
static struct pad_desc mx51babbage_pads[] = {
/* UART1 */
MX51_PAD_UART1_RXD__UART1_RXD,
MX51_PAD_UART1_TXD__UART1_TXD,
MX51_PAD_UART1_RTS__UART1_RTS,
MX51_PAD_UART1_CTS__UART1_CTS,
/* UART2 */
MX51_PAD_UART2_RXD__UART2_RXD,
MX51_PAD_UART2_TXD__UART2_TXD,
/* UART3 */
MX51_PAD_EIM_D25__UART3_RXD,
MX51_PAD_EIM_D26__UART3_TXD,
MX51_PAD_EIM_D27__UART3_RTS,
MX51_PAD_EIM_D24__UART3_CTS,
/* I2C1 */
MX51_PAD_EIM_D16__I2C1_SDA,
MX51_PAD_EIM_D19__I2C1_SCL,
/* I2C2 */
MX51_PAD_KEY_COL4__I2C2_SCL,
MX51_PAD_KEY_COL5__I2C2_SDA,
/* HSI2C */
MX51_PAD_I2C1_CLK__HSI2C_CLK,
MX51_PAD_I2C1_DAT__HSI2C_DAT,
/* USB HOST1 */
MX51_PAD_USBH1_CLK__USBH1_CLK,
MX51_PAD_USBH1_DIR__USBH1_DIR,
MX51_PAD_USBH1_NXT__USBH1_NXT,
MX51_PAD_USBH1_DATA0__USBH1_DATA0,
MX51_PAD_USBH1_DATA1__USBH1_DATA1,
MX51_PAD_USBH1_DATA2__USBH1_DATA2,
MX51_PAD_USBH1_DATA3__USBH1_DATA3,
MX51_PAD_USBH1_DATA4__USBH1_DATA4,
MX51_PAD_USBH1_DATA5__USBH1_DATA5,
MX51_PAD_USBH1_DATA6__USBH1_DATA6,
MX51_PAD_USBH1_DATA7__USBH1_DATA7,
/* USB HUB reset line*/
MX51_PAD_GPIO_1_7__GPIO_1_7,
/* FEC */
MX51_PAD_EIM_EB2__FEC_MDIO,
MX51_PAD_EIM_EB3__FEC_RDAT1,
MX51_PAD_EIM_CS2__FEC_RDAT2,
MX51_PAD_EIM_CS3__FEC_RDAT3,
MX51_PAD_EIM_CS4__FEC_RX_ER,
MX51_PAD_EIM_CS5__FEC_CRS,
MX51_PAD_NANDF_RB2__FEC_COL,
MX51_PAD_NANDF_RB3__FEC_RXCLK,
MX51_PAD_NANDF_RB6__FEC_RDAT0,
MX51_PAD_NANDF_RB7__FEC_TDAT0,
MX51_PAD_NANDF_CS2__FEC_TX_ER,
MX51_PAD_NANDF_CS3__FEC_MDC,
MX51_PAD_NANDF_CS4__FEC_TDAT1,
MX51_PAD_NANDF_CS5__FEC_TDAT2,
MX51_PAD_NANDF_CS6__FEC_TDAT3,
MX51_PAD_NANDF_CS7__FEC_TX_EN,
MX51_PAD_NANDF_RDY_INT__FEC_TX_CLK,
/* FEC PHY reset line */
MX51_PAD_EIM_A20__GPIO_2_14,
/* SD 1 */
MX51_PAD_SD1_CMD__SD1_CMD,
MX51_PAD_SD1_CLK__SD1_CLK,
MX51_PAD_SD1_DATA0__SD1_DATA0,
MX51_PAD_SD1_DATA1__SD1_DATA1,
MX51_PAD_SD1_DATA2__SD1_DATA2,
MX51_PAD_SD1_DATA3__SD1_DATA3,
/* SD 2 */
MX51_PAD_SD2_CMD__SD2_CMD,
MX51_PAD_SD2_CLK__SD2_CLK,
MX51_PAD_SD2_DATA0__SD2_DATA0,
MX51_PAD_SD2_DATA1__SD2_DATA1,
MX51_PAD_SD2_DATA2__SD2_DATA2,
MX51_PAD_SD2_DATA3__SD2_DATA3,
};
/* Serial ports */
#if defined(CONFIG_SERIAL_IMX) || defined(CONFIG_SERIAL_IMX_MODULE)
static const struct imxuart_platform_data uart_pdata __initconst = {
.flags = IMXUART_HAVE_RTSCTS,
};
static inline void mxc_init_imx_uart(void)
{
imx51_add_imx_uart(0, &uart_pdata);
imx51_add_imx_uart(1, &uart_pdata);
imx51_add_imx_uart(2, &uart_pdata);
}
#else /* !SERIAL_IMX */
static inline void mxc_init_imx_uart(void)
{
}
#endif /* SERIAL_IMX */
static const struct imxi2c_platform_data babbage_i2c_data __initconst = {
.bitrate = 100000,
};
static struct imxi2c_platform_data babbage_hsi2c_data = {
.bitrate = 400000,
};
static int gpio_usbh1_active(void)
{
struct pad_desc usbh1stp_gpio = MX51_PAD_USBH1_STP__GPIO_1_27;
struct pad_desc phyreset_gpio = MX51_PAD_EIM_D21__GPIO_2_5;
int ret;
/* Set USBH1_STP to GPIO and toggle it */
mxc_iomux_v3_setup_pad(&usbh1stp_gpio);
ret = gpio_request(BABBAGE_USBH1_STP, "usbh1_stp");
if (ret) {
pr_debug("failed to get MX51_PAD_USBH1_STP__GPIO_1_27: %d\n", ret);
return ret;
}
gpio_direction_output(BABBAGE_USBH1_STP, 0);
gpio_set_value(BABBAGE_USBH1_STP, 1);
msleep(100);
gpio_free(BABBAGE_USBH1_STP);
/* De-assert USB PHY RESETB */
mxc_iomux_v3_setup_pad(&phyreset_gpio);
ret = gpio_request(BABBAGE_PHY_RESET, "phy_reset");
if (ret) {
pr_debug("failed to get MX51_PAD_EIM_D21__GPIO_2_5: %d\n", ret);
return ret;
}
gpio_direction_output(BABBAGE_PHY_RESET, 1);
return 0;
}
static inline void babbage_usbhub_reset(void)
{
int ret;
/* Bring USB hub out of reset */
ret = gpio_request(BABBAGE_USB_HUB_RESET, "GPIO1_7");
if (ret) {
printk(KERN_ERR"failed to get GPIO_USB_HUB_RESET: %d\n", ret);
return;
}
gpio_direction_output(BABBAGE_USB_HUB_RESET, 0);
/* USB HUB RESET - De-assert USB HUB RESET_N */
msleep(1);
gpio_set_value(BABBAGE_USB_HUB_RESET, 0);
msleep(1);
gpio_set_value(BABBAGE_USB_HUB_RESET, 1);
}
static inline void babbage_fec_reset(void)
{
int ret;
/* reset FEC PHY */
ret = gpio_request(BABBAGE_FEC_PHY_RESET, "fec-phy-reset");
if (ret) {
printk(KERN_ERR"failed to get GPIO_FEC_PHY_RESET: %d\n", ret);
return;
}
gpio_direction_output(BABBAGE_FEC_PHY_RESET, 0);
gpio_set_value(BABBAGE_FEC_PHY_RESET, 0);
msleep(1);
gpio_set_value(BABBAGE_FEC_PHY_RESET, 1);
}
/* This function is board specific as the bit mask for the plldiv will also
be different for other Freescale SoCs, thus a common bitmask is not
possible and cannot get place in /plat-mxc/ehci.c.*/
static int initialize_otg_port(struct platform_device *pdev)
{
u32 v;
void __iomem *usb_base;
void __iomem *usbother_base;
usb_base = ioremap(MX51_OTG_BASE_ADDR, SZ_4K);
usbother_base = usb_base + MX5_USBOTHER_REGS_OFFSET;
/* Set the PHY clock to 19.2MHz */
v = __raw_readl(usbother_base + MXC_USB_PHY_CTR_FUNC2_OFFSET);
v &= ~MX5_USB_UTMI_PHYCTRL1_PLLDIV_MASK;
v |= MX51_USB_PLL_DIV_19_2_MHZ;
__raw_writel(v, usbother_base + MXC_USB_PHY_CTR_FUNC2_OFFSET);
iounmap(usb_base);
return 0;
}
static int initialize_usbh1_port(struct platform_device *pdev)
{
u32 v;
void __iomem *usb_base;
void __iomem *usbother_base;
usb_base = ioremap(MX51_OTG_BASE_ADDR, SZ_4K);
usbother_base = usb_base + MX5_USBOTHER_REGS_OFFSET;
/* The clock for the USBH1 ULPI port will come externally from the PHY. */
v = __raw_readl(usbother_base + MX51_USB_CTRL_1_OFFSET);
__raw_writel(v | MX51_USB_CTRL_UH1_EXT_CLK_EN, usbother_base + MX51_USB_CTRL_1_OFFSET);
iounmap(usb_base);
return 0;
}
static struct mxc_usbh_platform_data dr_utmi_config = {
.init = initialize_otg_port,
.portsc = MXC_EHCI_UTMI_16BIT,
.flags = MXC_EHCI_INTERNAL_PHY,
};
static struct fsl_usb2_platform_data usb_pdata = {
.operating_mode = FSL_USB2_DR_DEVICE,
.phy_mode = FSL_USB2_PHY_UTMI_WIDE,
};
static struct mxc_usbh_platform_data usbh1_config = {
.init = initialize_usbh1_port,
.portsc = MXC_EHCI_MODE_ULPI,
.flags = (MXC_EHCI_POWER_PINS_ENABLED | MXC_EHCI_ITC_NO_THRESHOLD),
};
static int otg_mode_host;
static int __init babbage_otg_mode(char *options)
{
if (!strcmp(options, "host"))
otg_mode_host = 1;
else if (!strcmp(options, "device"))
otg_mode_host = 0;
else
pr_info("otg_mode neither \"host\" nor \"device\". "
"Defaulting to device\n");
return 0;
}
__setup("otg_mode=", babbage_otg_mode);
/*
* Board specific initialization.
*/
static void __init mxc_board_init(void)
{
struct pad_desc usbh1stp = MX51_PAD_USBH1_STP__USBH1_STP;
struct pad_desc power_key = MX51_PAD_EIM_A27__GPIO_2_21;
#if defined(CONFIG_CPU_FREQ_IMX)
get_cpu_op = mx51_get_cpu_op;
#endif
mxc_iomux_v3_setup_multiple_pads(mx51babbage_pads,
ARRAY_SIZE(mx51babbage_pads));
mxc_init_imx_uart();
babbage_fec_reset();
imx51_add_fec(NULL);
/* Set the PAD settings for the pwr key. */
power_key.pad_ctrl = MX51_GPIO_PAD_CTRL_2;
mxc_iomux_v3_setup_pad(&power_key);
imx51_add_gpio_keys(&imx_button_data);
imx51_add_imx_i2c(0, &babbage_i2c_data);
imx51_add_imx_i2c(1, &babbage_i2c_data);
mxc_register_device(&mxc_hsi2c_device, &babbage_hsi2c_data);
if (otg_mode_host)
mxc_register_device(&mxc_usbdr_host_device, &dr_utmi_config);
else {
initialize_otg_port(NULL);
mxc_register_device(&mxc_usbdr_udc_device, &usb_pdata);
}
gpio_usbh1_active();
mxc_register_device(&mxc_usbh1_device, &usbh1_config);
/* setback USBH1_STP to be function */
mxc_iomux_v3_setup_pad(&usbh1stp);
babbage_usbhub_reset();
imx51_add_esdhc(0, NULL);
imx51_add_esdhc(1, NULL);
}
static void __init mx51_babbage_timer_init(void)
{
mx51_clocks_init(32768, 24000000, 22579200, 0);
}
static struct sys_timer mxc_timer = {
.init = mx51_babbage_timer_init,
};
MACHINE_START(MX51_BABBAGE, "Freescale MX51 Babbage Board")
/* Maintainer: Amit Kucheria <amit.kucheria@canonical.com> */
.boot_params = MX51_PHYS_OFFSET + 0x100,
.map_io = mx51_map_io,
.init_irq = mx51_init_irq,
.init_machine = mxc_board_init,
.timer = &mxc_timer,
MACHINE_END
| gpl-2.0 |
ivanich/android_kernel_oneplus_msm8996 | drivers/platform/msm/ipa/ipa_v3/ipa_flt.c | 51 | 51625 | /* Copyright (c) 2012-2016, 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 "ipa_i.h"
#include "ipahal/ipahal.h"
#define IPA_FLT_TABLE_INDEX_NOT_FOUND (-1)
#define IPA_FLT_STATUS_OF_ADD_FAILED (-1)
#define IPA_FLT_STATUS_OF_DEL_FAILED (-1)
#define IPA_FLT_STATUS_OF_MDFY_FAILED (-1)
#define IPA_FLT_GET_RULE_TYPE(__entry) \
( \
((__entry)->rule.hashable) ? \
(IPA_RULE_HASHABLE):(IPA_RULE_NON_HASHABLE) \
)
static int ipa3_generate_hw_rule_from_eq(
const struct ipa_ipfltri_rule_eq *attrib, u8 **buf)
{
int num_offset_meq_32 = attrib->num_offset_meq_32;
int num_ihl_offset_range_16 = attrib->num_ihl_offset_range_16;
int num_ihl_offset_meq_32 = attrib->num_ihl_offset_meq_32;
int num_offset_meq_128 = attrib->num_offset_meq_128;
int i;
int extra_bytes;
u8 *extra;
u8 *rest;
extra_bytes = ipa3_calc_extra_wrd_bytes(attrib);
/* only 3 eq does not have extra word param, 13 out of 16 is the number
* of equations that needs extra word param*/
if (extra_bytes > 13) {
IPAERR("too much extra bytes\n");
return -EPERM;
} else if (extra_bytes > IPA_HW_TBL_HDR_WIDTH) {
/* two extra words */
extra = *buf;
rest = *buf + IPA_HW_TBL_HDR_WIDTH * 2;
} else if (extra_bytes > 0) {
/* single exra word */
extra = *buf;
rest = *buf + IPA_HW_TBL_HDR_WIDTH;
} else {
/* no extra words */
extra = NULL;
rest = *buf;
}
if (attrib->tos_eq_present)
extra = ipa3_write_8(attrib->tos_eq, extra);
if (attrib->protocol_eq_present)
extra = ipa3_write_8(attrib->protocol_eq, extra);
if (attrib->tc_eq_present)
extra = ipa3_write_8(attrib->tc_eq, extra);
if (num_offset_meq_128) {
extra = ipa3_write_8(attrib->offset_meq_128[0].offset, extra);
for (i = 0; i < 8; i++)
rest = ipa3_write_8(attrib->offset_meq_128[0].mask[i],
rest);
for (i = 0; i < 8; i++)
rest = ipa3_write_8(attrib->offset_meq_128[0].value[i],
rest);
for (i = 8; i < 16; i++)
rest = ipa3_write_8(attrib->offset_meq_128[0].mask[i],
rest);
for (i = 8; i < 16; i++)
rest = ipa3_write_8(attrib->offset_meq_128[0].value[i],
rest);
num_offset_meq_128--;
}
if (num_offset_meq_128) {
extra = ipa3_write_8(attrib->offset_meq_128[1].offset, extra);
for (i = 0; i < 8; i++)
rest = ipa3_write_8(attrib->offset_meq_128[1].mask[i],
rest);
for (i = 0; i < 8; i++)
rest = ipa3_write_8(attrib->offset_meq_128[1].value[i],
rest);
for (i = 8; i < 16; i++)
rest = ipa3_write_8(attrib->offset_meq_128[1].mask[i],
rest);
for (i = 8; i < 16; i++)
rest = ipa3_write_8(attrib->offset_meq_128[1].value[i],
rest);
num_offset_meq_128--;
}
if (num_offset_meq_32) {
extra = ipa3_write_8(attrib->offset_meq_32[0].offset, extra);
rest = ipa3_write_32(attrib->offset_meq_32[0].mask, rest);
rest = ipa3_write_32(attrib->offset_meq_32[0].value, rest);
num_offset_meq_32--;
}
if (num_offset_meq_32) {
extra = ipa3_write_8(attrib->offset_meq_32[1].offset, extra);
rest = ipa3_write_32(attrib->offset_meq_32[1].mask, rest);
rest = ipa3_write_32(attrib->offset_meq_32[1].value, rest);
num_offset_meq_32--;
}
if (num_ihl_offset_meq_32) {
extra = ipa3_write_8(attrib->ihl_offset_meq_32[0].offset,
extra);
rest = ipa3_write_32(attrib->ihl_offset_meq_32[0].mask, rest);
rest = ipa3_write_32(attrib->ihl_offset_meq_32[0].value, rest);
num_ihl_offset_meq_32--;
}
if (num_ihl_offset_meq_32) {
extra = ipa3_write_8(attrib->ihl_offset_meq_32[1].offset,
extra);
rest = ipa3_write_32(attrib->ihl_offset_meq_32[1].mask, rest);
rest = ipa3_write_32(attrib->ihl_offset_meq_32[1].value, rest);
num_ihl_offset_meq_32--;
}
if (attrib->metadata_meq32_present) {
rest = ipa3_write_32(attrib->metadata_meq32.mask, rest);
rest = ipa3_write_32(attrib->metadata_meq32.value, rest);
}
if (num_ihl_offset_range_16) {
extra = ipa3_write_8(attrib->ihl_offset_range_16[0].offset,
extra);
rest = ipa3_write_16(attrib->ihl_offset_range_16[0].range_high,
rest);
rest = ipa3_write_16(attrib->ihl_offset_range_16[0].range_low,
rest);
num_ihl_offset_range_16--;
}
if (num_ihl_offset_range_16) {
extra = ipa3_write_8(attrib->ihl_offset_range_16[1].offset,
extra);
rest = ipa3_write_16(attrib->ihl_offset_range_16[1].range_high,
rest);
rest = ipa3_write_16(attrib->ihl_offset_range_16[1].range_low,
rest);
num_ihl_offset_range_16--;
}
if (attrib->ihl_offset_eq_32_present) {
extra = ipa3_write_8(attrib->ihl_offset_eq_32.offset, extra);
rest = ipa3_write_32(attrib->ihl_offset_eq_32.value, rest);
}
if (attrib->ihl_offset_eq_16_present) {
extra = ipa3_write_8(attrib->ihl_offset_eq_16.offset, extra);
rest = ipa3_write_16(attrib->ihl_offset_eq_16.value, rest);
rest = ipa3_write_16(0, rest);
}
if (attrib->fl_eq_present)
rest = ipa3_write_32(attrib->fl_eq & 0xFFFFF, rest);
extra = ipa3_pad_to_64(extra);
rest = ipa3_pad_to_64(rest);
*buf = rest;
return 0;
}
/**
* ipa3_generate_flt_hw_rule() - generates the filtering hardware rule
* @ip: the ip address family type
* @entry: filtering entry
* @buf: output buffer, buf == NULL means
* caller wants to know the size of the rule as seen
* by HW so they did not pass a valid buffer, we will use a
* scratch buffer instead.
* With this scheme we are going to
* generate the rule twice, once to know size using scratch
* buffer and second to write the rule to the actual caller
* supplied buffer which is of required size
*
* Returns: 0 on success, negative on failure
*
* caller needs to hold any needed locks to ensure integrity
*
*/
static int ipa3_generate_flt_hw_rule(enum ipa_ip_type ip,
struct ipa3_flt_entry *entry, u8 *buf)
{
struct ipa3_flt_rule_hw_hdr *hdr;
const struct ipa_flt_rule *rule =
(const struct ipa_flt_rule *)&entry->rule;
u16 en_rule = 0;
u32 tmp[IPA_RT_FLT_HW_RULE_BUF_SIZE/4];
u8 *start;
if (buf == NULL) {
memset(tmp, 0, IPA_RT_FLT_HW_RULE_BUF_SIZE);
buf = (u8 *)tmp;
} else {
if ((long)buf & IPA_HW_RULE_START_ALIGNMENT) {
IPAERR("buff is not rule start aligned\n");
return -EPERM;
}
}
start = buf;
hdr = (struct ipa3_flt_rule_hw_hdr *)buf;
hdr->u.hdr.action = entry->rule.action;
hdr->u.hdr.retain_hdr = entry->rule.retain_hdr;
if (entry->rt_tbl)
hdr->u.hdr.rt_tbl_idx = entry->rt_tbl->idx;
else
hdr->u.hdr.rt_tbl_idx = entry->rule.rt_tbl_idx;
hdr->u.hdr.rsvd1 = 0;
hdr->u.hdr.rsvd2 = 0;
hdr->u.hdr.rsvd3 = 0;
BUG_ON(entry->prio & ~0x3FF);
hdr->u.hdr.priority = entry->prio;
BUG_ON(entry->rule_id & ~0x3FF);
hdr->u.hdr.rule_id = entry->rule_id;
buf += sizeof(struct ipa3_flt_rule_hw_hdr);
if (rule->eq_attrib_type) {
if (ipa3_generate_hw_rule_from_eq(&rule->eq_attrib, &buf)) {
IPAERR("fail to generate hw rule from eq\n");
return -EPERM;
}
en_rule = rule->eq_attrib.rule_eq_bitmap;
} else {
if (ipa3_generate_hw_rule(ip, &rule->attrib, &buf, &en_rule)) {
IPAERR("fail to generate hw rule\n");
return -EPERM;
}
}
IPADBG_LOW("en_rule=0x%x, action=%d, rt_idx=%d, retain_hdr=%d\n",
en_rule,
hdr->u.hdr.action,
hdr->u.hdr.rt_tbl_idx,
hdr->u.hdr.retain_hdr);
IPADBG_LOW("priority=%d, rule_id=%d\n",
hdr->u.hdr.priority,
hdr->u.hdr.rule_id);
hdr->u.hdr.en_rule = en_rule;
ipa3_write_64(hdr->u.word, (u8 *)hdr);
if (entry->hw_len == 0) {
entry->hw_len = buf - start;
} else if (entry->hw_len != (buf - start)) {
IPAERR("hw_len differs b/w passes passed=0x%x calc=0x%td\n",
entry->hw_len, (buf - start));
return -EPERM;
}
return 0;
}
static void __ipa_reap_sys_flt_tbls(enum ipa_ip_type ip, enum ipa_rule_type rlt)
{
struct ipa3_flt_tbl *tbl;
int i;
IPADBG_LOW("reaping sys flt tbls ip=%d rlt=%d\n", ip, rlt);
for (i = 0; i < ipa3_ctx->ipa_num_pipes; i++) {
if (!ipa_is_ep_support_flt(i))
continue;
tbl = &ipa3_ctx->flt_tbl[i][ip];
if (tbl->prev_mem[rlt].phys_base) {
IPADBG_LOW("reaping flt tbl (prev) pipe=%d\n", i);
dma_free_coherent(ipa3_ctx->pdev,
tbl->prev_mem[rlt].size,
tbl->prev_mem[rlt].base,
tbl->prev_mem[rlt].phys_base);
memset(&tbl->prev_mem[rlt], 0,
sizeof(tbl->prev_mem[rlt]));
}
if (list_empty(&tbl->head_flt_rule_list)) {
if (tbl->curr_mem[rlt].phys_base) {
IPADBG_LOW("reaping flt tbl (curr) pipe=%d\n",
i);
dma_free_coherent(ipa3_ctx->pdev,
tbl->curr_mem[rlt].size,
tbl->curr_mem[rlt].base,
tbl->curr_mem[rlt].phys_base);
memset(&tbl->curr_mem[rlt], 0,
sizeof(tbl->curr_mem[rlt]));
}
}
}
}
/**
* ipa_alloc_init_flt_tbl_hdr() - allocate and initialize buffers for
* flt tables headers to be filled into sram
* @ip: the ip address family type
* @hash_hdr: address of the dma buffer for the hashable flt tbl header
* @nhash_hdr: address of the dma buffer for the non-hashable flt tbl header
*
* Return: 0 on success, negative on failure
*/
static int ipa_alloc_init_flt_tbl_hdr(enum ipa_ip_type ip,
struct ipa_mem_buffer *hash_hdr, struct ipa_mem_buffer *nhash_hdr)
{
int num_hdrs;
u64 *hash_entr;
u64 *nhash_entr;
int i;
num_hdrs = ipa3_ctx->ep_flt_num;
hash_hdr->size = num_hdrs * IPA_HW_TBL_HDR_WIDTH;
hash_hdr->base = dma_alloc_coherent(ipa3_ctx->pdev, hash_hdr->size,
&hash_hdr->phys_base, GFP_KERNEL);
if (!hash_hdr->base) {
IPAERR("fail to alloc DMA buff of size %d\n", hash_hdr->size);
goto err;
}
nhash_hdr->size = num_hdrs * IPA_HW_TBL_HDR_WIDTH;
nhash_hdr->base = dma_alloc_coherent(ipa3_ctx->pdev, nhash_hdr->size,
&nhash_hdr->phys_base, GFP_KERNEL);
if (!nhash_hdr->base) {
IPAERR("fail to alloc DMA buff of size %d\n", nhash_hdr->size);
goto nhash_alloc_fail;
}
hash_entr = (u64 *)hash_hdr->base;
nhash_entr = (u64 *)nhash_hdr->base;
for (i = 0; i < num_hdrs; i++) {
*hash_entr = ipa3_ctx->empty_rt_tbl_mem.phys_base;
*nhash_entr = ipa3_ctx->empty_rt_tbl_mem.phys_base;
hash_entr++;
nhash_entr++;
}
return 0;
nhash_alloc_fail:
dma_free_coherent(ipa3_ctx->pdev, hash_hdr->size,
hash_hdr->base, hash_hdr->phys_base);
err:
return -ENOMEM;
}
/**
* ipa_prep_flt_tbl_for_cmt() - preparing the flt table for commit
* assign priorities to the rules, calculate their sizes and calculate
* the overall table size
* @ip: the ip address family type
* @tbl: the flt tbl to be prepared
* @pipe_idx: the ep pipe appropriate for the given tbl
*
* Return: 0 on success, negative on failure
*/
static int ipa_prep_flt_tbl_for_cmt(enum ipa_ip_type ip,
struct ipa3_flt_tbl *tbl, int pipe_idx)
{
struct ipa3_flt_entry *entry;
u16 prio_i = 1;
tbl->sz[IPA_RULE_HASHABLE] = 0;
tbl->sz[IPA_RULE_NON_HASHABLE] = 0;
list_for_each_entry(entry, &tbl->head_flt_rule_list, link) {
entry->prio = entry->rule.max_prio ?
IPA_RULE_MAX_PRIORITY : prio_i++;
if (entry->prio > IPA_RULE_MIN_PRIORITY) {
IPAERR("cannot allocate new priority for flt rule\n");
return -EPERM;
}
if (ipa3_generate_flt_hw_rule(ip, entry, NULL)) {
IPAERR("failed to calculate HW FLT rule size\n");
return -EPERM;
}
IPADBG_LOW("pipe %d hw_len %d priority %u\n",
pipe_idx, entry->hw_len, entry->prio);
if (entry->rule.hashable)
tbl->sz[IPA_RULE_HASHABLE] += entry->hw_len;
else
tbl->sz[IPA_RULE_NON_HASHABLE] += entry->hw_len;
}
if ((tbl->sz[IPA_RULE_HASHABLE] +
tbl->sz[IPA_RULE_NON_HASHABLE]) == 0) {
IPADBG_LOW("flt tbl pipe %d is with zero total size\n",
pipe_idx);
return 0;
}
/* for the header word */
if (tbl->sz[IPA_RULE_HASHABLE])
tbl->sz[IPA_RULE_HASHABLE] += IPA_HW_TBL_HDR_WIDTH;
if (tbl->sz[IPA_RULE_NON_HASHABLE])
tbl->sz[IPA_RULE_NON_HASHABLE] += IPA_HW_TBL_HDR_WIDTH;
IPADBG_LOW("FLT tbl pipe idx %d hash sz %u non-hash sz %u\n", pipe_idx,
tbl->sz[IPA_RULE_HASHABLE], tbl->sz[IPA_RULE_NON_HASHABLE]);
return 0;
}
/**
* ipa_get_flt_tbl_lcl_bdy_size() - calc the overall memory needed on sram
* to hold the hashable and non-hashable flt rules tables bodies
* @ip: the ip address family type
* @hash_bdy_sz[OUT]: size on local sram for all tbls hashable rules
* @nhash_bdy_sz[OUT]: size on local sram for all tbls non-hashable rules
*
* Return: none
*/
static void ipa_get_flt_tbl_lcl_bdy_size(enum ipa_ip_type ip,
u32 *hash_bdy_sz, u32 *nhash_bdy_sz)
{
struct ipa3_flt_tbl *tbl;
int i;
*hash_bdy_sz = 0;
*nhash_bdy_sz = 0;
for (i = 0; i < ipa3_ctx->ipa_num_pipes; i++) {
if (!ipa_is_ep_support_flt(i))
continue;
tbl = &ipa3_ctx->flt_tbl[i][ip];
if (!tbl->in_sys[IPA_RULE_HASHABLE] &&
tbl->sz[IPA_RULE_HASHABLE]) {
*hash_bdy_sz += tbl->sz[IPA_RULE_HASHABLE];
*hash_bdy_sz -= IPA_HW_TBL_HDR_WIDTH;
/* for table terminator */
*hash_bdy_sz += IPA_HW_TBL_WIDTH;
/* align the start of local rule-set */
*hash_bdy_sz += IPA_HW_TBL_LCLADDR_ALIGNMENT;
*hash_bdy_sz &= ~IPA_HW_TBL_LCLADDR_ALIGNMENT;
}
if (!tbl->in_sys[IPA_RULE_NON_HASHABLE] &&
tbl->sz[IPA_RULE_NON_HASHABLE]) {
*nhash_bdy_sz += tbl->sz[IPA_RULE_NON_HASHABLE];
*nhash_bdy_sz -= IPA_HW_TBL_HDR_WIDTH;
/* for table terminator */
*nhash_bdy_sz += IPA_HW_TBL_WIDTH;
/* align the start of local rule-set */
*nhash_bdy_sz += IPA_HW_TBL_LCLADDR_ALIGNMENT;
*nhash_bdy_sz &= ~IPA_HW_TBL_LCLADDR_ALIGNMENT;
}
}
}
/**
* ipa_translate_flt_tbl_to_hw_fmt() - translate the flt driver structures
* (rules and tables) to HW format and fill it in the given buffers
* @ip: the ip address family type
* @rlt: the type of the rules to translate (hashable or non-hashable)
* @base: the rules body buffer to be filled
* @hdr: the rules header (addresses/offsets) buffer to be filled
* @body_ofst: the offset of the rules body from the rules header at
* ipa sram
*
* Returns: 0 on success, negative on failure
*
* caller needs to hold any needed locks to ensure integrity
*
*/
static int ipa_translate_flt_tbl_to_hw_fmt(enum ipa_ip_type ip,
enum ipa_rule_type rlt, u8 *base, u8 *hdr, u32 body_ofst)
{
u64 offset;
u8 *body_i;
int res;
struct ipa3_flt_entry *entry;
u8 *tbl_mem_buf;
struct ipa_mem_buffer tbl_mem;
struct ipa3_flt_tbl *tbl;
int i;
int hdr_idx = 0;
body_i = base;
for (i = 0; i < ipa3_ctx->ipa_num_pipes; i++) {
if (!ipa_is_ep_support_flt(i))
continue;
tbl = &ipa3_ctx->flt_tbl[i][ip];
if (tbl->sz[rlt] == 0) {
hdr_idx++;
continue;
}
if (tbl->in_sys[rlt]) {
/* only body (no header) with rule-set terminator */
tbl_mem.size = tbl->sz[rlt] -
IPA_HW_TBL_HDR_WIDTH + IPA_HW_TBL_WIDTH;
tbl_mem.base =
dma_alloc_coherent(ipa3_ctx->pdev, tbl_mem.size,
&tbl_mem.phys_base, GFP_KERNEL);
if (!tbl_mem.base) {
IPAERR("fail to alloc DMA buf of size %d\n",
tbl_mem.size);
goto err;
}
if (tbl_mem.phys_base & IPA_HW_TBL_SYSADDR_ALIGNMENT) {
IPAERR("sys rt tbl address is not aligned\n");
goto align_err;
}
/* update the hdr at the right index */
ipa3_write_64(tbl_mem.phys_base, hdr +
hdr_idx * IPA_HW_TBL_HDR_WIDTH);
tbl_mem_buf = tbl_mem.base;
memset(tbl_mem_buf, 0, tbl_mem.size);
/* generate the rule-set */
list_for_each_entry(entry, &tbl->head_flt_rule_list,
link) {
if (IPA_FLT_GET_RULE_TYPE(entry) != rlt)
continue;
res = ipa3_generate_flt_hw_rule(
ip, entry, tbl_mem_buf);
if (res) {
IPAERR("failed to gen HW FLT rule\n");
goto align_err;
}
tbl_mem_buf += entry->hw_len;
}
/* write the rule-set terminator */
tbl_mem_buf = ipa3_write_64(0, tbl_mem_buf);
if (tbl->curr_mem[rlt].phys_base) {
WARN_ON(tbl->prev_mem[rlt].phys_base);
tbl->prev_mem[rlt] = tbl->curr_mem[rlt];
}
tbl->curr_mem[rlt] = tbl_mem;
} else {
offset = body_i - base + body_ofst;
if (offset & IPA_HW_TBL_LCLADDR_ALIGNMENT) {
IPAERR("ofst isn't lcl addr aligned %llu\n",
offset);
goto err;
}
/* update the hdr at the right index */
ipa3_write_64(IPA_HW_TBL_OFSET_TO_LCLADDR(offset),
hdr + hdr_idx * IPA_HW_TBL_HDR_WIDTH);
/* generate the rule-set */
list_for_each_entry(entry, &tbl->head_flt_rule_list,
link) {
if (IPA_FLT_GET_RULE_TYPE(entry) != rlt)
continue;
res = ipa3_generate_flt_hw_rule(
ip, entry, body_i);
if (res) {
IPAERR("failed to gen HW FLT rule\n");
goto err;
}
body_i += entry->hw_len;
}
/* write the rule-set terminator */
body_i = ipa3_write_64(0, body_i);
/**
* advance body_i to next table alignment as local tables
* are order back-to-back
*/
body_i += IPA_HW_TBL_LCLADDR_ALIGNMENT;
body_i = (u8 *)((long)body_i &
~IPA_HW_TBL_LCLADDR_ALIGNMENT);
}
hdr_idx++;
}
return 0;
align_err:
dma_free_coherent(ipa3_ctx->pdev, tbl_mem.size,
tbl_mem.base, tbl_mem.phys_base);
err:
return -EPERM;
}
/**
* ipa_generate_flt_hw_tbl_img() - generates the flt hw tbls.
* headers and bodies are being created into buffers that will be filled into
* the local memory (sram)
* @ip: the ip address family type
* @hash_hdr: address of the dma buffer containing hashable rules tbl headers
* @nhash_hdr: address of the dma buffer containing
* non-hashable rules tbl headers
* @hash_bdy: address of the dma buffer containing hashable local rules
* @nhash_bdy: address of the dma buffer containing non-hashable local rules
*
* Return: 0 on success, negative on failure
*/
static int ipa_generate_flt_hw_tbl_img(enum ipa_ip_type ip,
struct ipa_mem_buffer *hash_hdr, struct ipa_mem_buffer *nhash_hdr,
struct ipa_mem_buffer *hash_bdy, struct ipa_mem_buffer *nhash_bdy)
{
u32 hash_bdy_start_ofst, nhash_bdy_start_ofst;
u32 hash_bdy_sz;
u32 nhash_bdy_sz;
struct ipa3_flt_tbl *tbl;
int rc = 0;
int i;
if (ip == IPA_IP_v4) {
nhash_bdy_start_ofst = IPA_MEM_PART(apps_v4_flt_nhash_ofst) -
IPA_MEM_PART(v4_flt_nhash_ofst);
hash_bdy_start_ofst = IPA_MEM_PART(apps_v4_flt_hash_ofst) -
IPA_MEM_PART(v4_flt_hash_ofst);
} else {
nhash_bdy_start_ofst = IPA_MEM_PART(apps_v6_flt_nhash_ofst) -
IPA_MEM_PART(v6_flt_nhash_ofst);
hash_bdy_start_ofst = IPA_MEM_PART(apps_v6_flt_hash_ofst) -
IPA_MEM_PART(v6_flt_hash_ofst);
}
if (ipa_alloc_init_flt_tbl_hdr(ip, hash_hdr, nhash_hdr)) {
IPAERR("fail to alloc and init flt tbl hdr\n");
rc = -ENOMEM;
goto no_flt_tbls;
}
for (i = 0; i < ipa3_ctx->ipa_num_pipes; i++) {
if (!ipa_is_ep_support_flt(i))
continue;
tbl = &ipa3_ctx->flt_tbl[i][ip];
if (ipa_prep_flt_tbl_for_cmt(ip, tbl, i)) {
rc = -EPERM;
goto prep_failed;
}
}
ipa_get_flt_tbl_lcl_bdy_size(ip, &hash_bdy_sz, &nhash_bdy_sz);
IPADBG_LOW("total flt tbl local body sizes: hash %u nhash %u\n",
hash_bdy_sz, nhash_bdy_sz);
hash_bdy->size = hash_bdy_sz + IPA_HW_TBL_BLK_SIZE_ALIGNMENT;
hash_bdy->size &= ~IPA_HW_TBL_BLK_SIZE_ALIGNMENT;
nhash_bdy->size = nhash_bdy_sz + IPA_HW_TBL_BLK_SIZE_ALIGNMENT;
nhash_bdy->size &= ~IPA_HW_TBL_BLK_SIZE_ALIGNMENT;
if (hash_bdy->size) {
hash_bdy->base = dma_alloc_coherent(ipa3_ctx->pdev,
hash_bdy->size, &hash_bdy->phys_base, GFP_KERNEL);
if (!hash_bdy->base) {
IPAERR("fail to alloc DMA buff of size %d\n",
hash_bdy->size);
rc = -ENOMEM;
goto prep_failed;
}
memset(hash_bdy->base, 0, hash_bdy->size);
}
if (nhash_bdy->size) {
nhash_bdy->base = dma_alloc_coherent(ipa3_ctx->pdev,
nhash_bdy->size, &nhash_bdy->phys_base, GFP_KERNEL);
if (!nhash_bdy->base) {
IPAERR("fail to alloc DMA buff of size %d\n",
hash_bdy->size);
rc = -ENOMEM;
goto nhash_bdy_fail;
}
memset(nhash_bdy->base, 0, nhash_bdy->size);
}
if (ipa_translate_flt_tbl_to_hw_fmt(ip, IPA_RULE_HASHABLE,
hash_bdy->base, hash_hdr->base, hash_bdy_start_ofst)) {
IPAERR("fail to translate hashable flt tbls to hw format\n");
rc = -EPERM;
goto translate_fail;
}
if (ipa_translate_flt_tbl_to_hw_fmt(ip, IPA_RULE_NON_HASHABLE,
nhash_bdy->base, nhash_hdr->base, nhash_bdy_start_ofst)) {
IPAERR("fail to translate non-hash flt tbls to hw format\n");
rc = -EPERM;
goto translate_fail;
}
return rc;
translate_fail:
if (nhash_bdy->size)
dma_free_coherent(ipa3_ctx->pdev, nhash_bdy->size,
nhash_bdy->base, nhash_bdy->phys_base);
nhash_bdy_fail:
if (hash_bdy->size)
dma_free_coherent(ipa3_ctx->pdev, hash_bdy->size,
hash_bdy->base, hash_bdy->phys_base);
prep_failed:
dma_free_coherent(ipa3_ctx->pdev, hash_hdr->size,
hash_hdr->base, hash_hdr->phys_base);
dma_free_coherent(ipa3_ctx->pdev, nhash_hdr->size,
nhash_hdr->base, nhash_hdr->phys_base);
no_flt_tbls:
return rc;
}
/**
* ipa_flt_valid_lcl_tbl_size() - validate if the space allocated for flt
* tbl bodies at the sram is enough for the commit
* @ipt: the ip address family type
* @rlt: the rule type (hashable or non-hashable)
*
* Return: true if enough space available or false in other cases
*/
static bool ipa_flt_valid_lcl_tbl_size(enum ipa_ip_type ipt,
enum ipa_rule_type rlt, struct ipa_mem_buffer *bdy)
{
u16 avail;
if (!bdy) {
IPAERR("Bad parameters, bdy = NULL\n");
return false;
}
if (ipt == IPA_IP_v4)
avail = (rlt == IPA_RULE_HASHABLE) ?
IPA_MEM_PART(apps_v4_flt_hash_size) :
IPA_MEM_PART(apps_v4_flt_nhash_size);
else
avail = (rlt == IPA_RULE_HASHABLE) ?
IPA_MEM_PART(apps_v6_flt_hash_size) :
IPA_MEM_PART(apps_v6_flt_nhash_size);
if (bdy->size <= avail)
return true;
IPAERR("tbl too big, needed %d avail %d ipt %d rlt %d\n",
bdy->size, avail, ipt, rlt);
return false;
}
/**
* ipa_flt_alloc_cmd_buffers() - alloc descriptors and imm cmds
* payload pointers buffers for headers and bodies of flt structure
* as well as place for flush imm.
* @ipt: the ip address family type
* @desc: [OUT] descriptor buffer
* @cmd: [OUT] imm commands payload pointers buffer
*
* Return: 0 on success, negative on failure
*/
static int ipa_flt_alloc_cmd_buffers(enum ipa_ip_type ip,
struct ipa3_desc **desc, struct ipahal_imm_cmd_pyld ***cmd_pyld)
{
u16 entries;
/* +3: 2 for bodies (hashable and non-hashable) and 1 for flushing */
entries = (ipa3_ctx->ep_flt_num) * 2 + 3;
*desc = kcalloc(entries, sizeof(**desc), GFP_ATOMIC);
if (*desc == NULL) {
IPAERR("fail to alloc desc blob ip %d\n", ip);
goto fail_desc_alloc;
}
*cmd_pyld = kcalloc(entries, sizeof(**cmd_pyld), GFP_ATOMIC);
if (*cmd_pyld == NULL) {
IPAERR("fail to alloc cmd pyld blob ip %d\n", ip);
goto fail_cmd_alloc;
}
return 0;
fail_cmd_alloc:
kfree(*desc);
fail_desc_alloc:
return -ENOMEM;
}
/**
* ipa_flt_skip_pipe_config() - skip ep flt configuration or not?
* will skip according to pre-configuration or modem pipes
* @pipe: the EP pipe index
*
* Return: true if to skip, false otherwize
*/
static bool ipa_flt_skip_pipe_config(int pipe)
{
if (ipa_is_modem_pipe(pipe)) {
IPADBG_LOW("skip %d - modem owned pipe\n", pipe);
return true;
}
if (ipa3_ctx->skip_ep_cfg_shadow[pipe]) {
IPADBG_LOW("skip %d\n", pipe);
return true;
}
if ((ipa3_get_ep_mapping(IPA_CLIENT_APPS_LAN_WAN_PROD) == pipe
&& ipa3_ctx->modem_cfg_emb_pipe_flt)) {
IPADBG_LOW("skip %d\n", pipe);
return true;
}
return false;
}
/**
* __ipa_commit_flt_v3() - commit flt tables to the hw
* commit the headers and the bodies if are local with internal cache flushing.
* The headers (and local bodies) will first be created into dma buffers and
* then written via IC to the SRAM
* @ipt: the ip address family type
*
* Return: 0 on success, negative on failure
*/
int __ipa_commit_flt_v3(enum ipa_ip_type ip)
{
struct ipa_mem_buffer hash_bdy, nhash_bdy;
struct ipa_mem_buffer hash_hdr, nhash_hdr;
int rc = 0;
struct ipa3_desc *desc;
struct ipahal_imm_cmd_register_write reg_write_cmd = {0};
struct ipahal_imm_cmd_dma_shared_mem mem_cmd = {0};
struct ipahal_imm_cmd_pyld **cmd_pyld;
int num_cmd = 0;
int i;
int hdr_idx;
u32 lcl_hash_hdr, lcl_nhash_hdr;
u32 lcl_hash_bdy, lcl_nhash_bdy;
bool lcl_hash, lcl_nhash;
struct ipahal_reg_fltrt_hash_flush flush;
struct ipahal_reg_valmask valmask;
if (ip == IPA_IP_v4) {
lcl_hash_hdr = ipa3_ctx->smem_restricted_bytes +
IPA_MEM_PART(v4_flt_hash_ofst) +
IPA_HW_TBL_HDR_WIDTH; /* to skip the bitmap */
lcl_nhash_hdr = ipa3_ctx->smem_restricted_bytes +
IPA_MEM_PART(v4_flt_nhash_ofst) +
IPA_HW_TBL_HDR_WIDTH; /* to skip the bitmap */
lcl_hash_bdy = ipa3_ctx->smem_restricted_bytes +
IPA_MEM_PART(apps_v4_flt_hash_ofst);
lcl_nhash_bdy = ipa3_ctx->smem_restricted_bytes +
IPA_MEM_PART(apps_v4_flt_nhash_ofst);
lcl_hash = ipa3_ctx->ip4_flt_tbl_hash_lcl;
lcl_nhash = ipa3_ctx->ip4_flt_tbl_nhash_lcl;
} else {
lcl_hash_hdr = ipa3_ctx->smem_restricted_bytes +
IPA_MEM_PART(v6_flt_hash_ofst) +
IPA_HW_TBL_HDR_WIDTH; /* to skip the bitmap */
lcl_nhash_hdr = ipa3_ctx->smem_restricted_bytes +
IPA_MEM_PART(v6_flt_nhash_ofst) +
IPA_HW_TBL_HDR_WIDTH; /* to skip the bitmap */
lcl_hash_bdy = ipa3_ctx->smem_restricted_bytes +
IPA_MEM_PART(apps_v6_flt_hash_ofst);
lcl_nhash_bdy = ipa3_ctx->smem_restricted_bytes +
IPA_MEM_PART(apps_v6_flt_nhash_ofst);
lcl_hash = ipa3_ctx->ip6_flt_tbl_hash_lcl;
lcl_nhash = ipa3_ctx->ip6_flt_tbl_nhash_lcl;
}
if (ipa_generate_flt_hw_tbl_img(ip,
&hash_hdr, &nhash_hdr, &hash_bdy, &nhash_bdy)) {
IPAERR("fail to generate FLT HW TBL image. IP %d\n", ip);
rc = -EFAULT;
goto fail_gen;
}
if (!ipa_flt_valid_lcl_tbl_size(ip, IPA_RULE_HASHABLE, &hash_bdy)) {
rc = -EFAULT;
goto fail_size_valid;
}
if (!ipa_flt_valid_lcl_tbl_size(ip, IPA_RULE_NON_HASHABLE,
&nhash_bdy)) {
rc = -EFAULT;
goto fail_size_valid;
}
if (ipa_flt_alloc_cmd_buffers(ip, &desc, &cmd_pyld)) {
rc = -ENOMEM;
goto fail_size_valid;
}
/* flushing ipa internal hashable flt rules cache */
memset(&flush, 0, sizeof(flush));
if (ip == IPA_IP_v4)
flush.v4_flt = true;
else
flush.v6_flt = true;
ipahal_get_fltrt_hash_flush_valmask(&flush, &valmask);
reg_write_cmd.skip_pipeline_clear = false;
reg_write_cmd.pipeline_clear_options = IPAHAL_HPS_CLEAR;
reg_write_cmd.offset = ipahal_get_reg_ofst(IPA_FILT_ROUT_HASH_FLUSH);
reg_write_cmd.value = valmask.val;
reg_write_cmd.value_mask = valmask.mask;
cmd_pyld[0] = ipahal_construct_imm_cmd(
IPA_IMM_CMD_REGISTER_WRITE, ®_write_cmd, false);
if (!cmd_pyld[0]) {
IPAERR("fail construct register_write imm cmd: IP %d\n", ip);
rc = -EFAULT;
goto fail_reg_write_construct;
}
desc[0].opcode = ipahal_imm_cmd_get_opcode(IPA_IMM_CMD_REGISTER_WRITE);
desc[0].pyld = cmd_pyld[0]->data;
desc[0].len = cmd_pyld[0]->len;
desc[0].type = IPA_IMM_CMD_DESC;
num_cmd++;
hdr_idx = 0;
for (i = 0; i < ipa3_ctx->ipa_num_pipes; i++) {
if (!ipa_is_ep_support_flt(i)) {
IPADBG_LOW("skip %d - not filtering pipe\n", i);
continue;
}
if (ipa_flt_skip_pipe_config(i)) {
hdr_idx++;
continue;
}
IPADBG_LOW("Prepare imm cmd for hdr at index %d for pipe %d\n",
hdr_idx, i);
mem_cmd.is_read = false;
mem_cmd.skip_pipeline_clear = false;
mem_cmd.pipeline_clear_options = IPAHAL_HPS_CLEAR;
mem_cmd.size = IPA_HW_TBL_HDR_WIDTH;
mem_cmd.system_addr = nhash_hdr.phys_base +
hdr_idx * IPA_HW_TBL_HDR_WIDTH;
mem_cmd.local_addr = lcl_nhash_hdr +
hdr_idx * IPA_HW_TBL_HDR_WIDTH;
cmd_pyld[num_cmd] = ipahal_construct_imm_cmd(
IPA_IMM_CMD_DMA_SHARED_MEM, &mem_cmd, false);
if (!cmd_pyld[num_cmd]) {
IPAERR("fail construct dma_shared_mem cmd: IP = %d\n",
ip);
goto fail_imm_cmd_construct;
}
desc[num_cmd].opcode =
ipahal_imm_cmd_get_opcode(IPA_IMM_CMD_DMA_SHARED_MEM);
desc[num_cmd].pyld = cmd_pyld[num_cmd]->data;
desc[num_cmd].len = cmd_pyld[num_cmd]->len;
desc[num_cmd++].type = IPA_IMM_CMD_DESC;
mem_cmd.is_read = false;
mem_cmd.skip_pipeline_clear = false;
mem_cmd.pipeline_clear_options = IPAHAL_HPS_CLEAR;
mem_cmd.size = IPA_HW_TBL_HDR_WIDTH;
mem_cmd.system_addr = hash_hdr.phys_base +
hdr_idx * IPA_HW_TBL_HDR_WIDTH;
mem_cmd.local_addr = lcl_hash_hdr +
hdr_idx * IPA_HW_TBL_HDR_WIDTH;
cmd_pyld[num_cmd] = ipahal_construct_imm_cmd(
IPA_IMM_CMD_DMA_SHARED_MEM, &mem_cmd, false);
if (!cmd_pyld[num_cmd]) {
IPAERR("fail construct dma_shared_mem cmd: IP = %d\n",
ip);
goto fail_imm_cmd_construct;
}
desc[num_cmd].opcode =
ipahal_imm_cmd_get_opcode(IPA_IMM_CMD_DMA_SHARED_MEM);
desc[num_cmd].pyld = cmd_pyld[num_cmd]->data;
desc[num_cmd].len = cmd_pyld[num_cmd]->len;
desc[num_cmd++].type = IPA_IMM_CMD_DESC;
hdr_idx++;
}
if (lcl_nhash) {
mem_cmd.is_read = false;
mem_cmd.skip_pipeline_clear = false;
mem_cmd.pipeline_clear_options = IPAHAL_HPS_CLEAR;
mem_cmd.size = nhash_bdy.size;
mem_cmd.system_addr = nhash_bdy.phys_base;
mem_cmd.local_addr = lcl_nhash_bdy;
cmd_pyld[num_cmd] = ipahal_construct_imm_cmd(
IPA_IMM_CMD_DMA_SHARED_MEM, &mem_cmd, false);
if (!cmd_pyld[num_cmd]) {
IPAERR("fail construct dma_shared_mem cmd: IP = %d\n",
ip);
goto fail_imm_cmd_construct;
}
desc[num_cmd].opcode =
ipahal_imm_cmd_get_opcode(IPA_IMM_CMD_DMA_SHARED_MEM);
desc[num_cmd].pyld = cmd_pyld[num_cmd]->data;
desc[num_cmd].len = cmd_pyld[num_cmd]->len;
desc[num_cmd++].type = IPA_IMM_CMD_DESC;
}
if (lcl_hash) {
mem_cmd.is_read = false;
mem_cmd.skip_pipeline_clear = false;
mem_cmd.pipeline_clear_options = IPAHAL_HPS_CLEAR;
mem_cmd.size = hash_bdy.size;
mem_cmd.system_addr = hash_bdy.phys_base;
mem_cmd.local_addr = lcl_hash_bdy;
cmd_pyld[num_cmd] = ipahal_construct_imm_cmd(
IPA_IMM_CMD_DMA_SHARED_MEM, &mem_cmd, false);
if (!cmd_pyld[num_cmd]) {
IPAERR("fail construct dma_shared_mem cmd: IP = %d\n",
ip);
goto fail_imm_cmd_construct;
}
desc[num_cmd].opcode =
ipahal_imm_cmd_get_opcode(IPA_IMM_CMD_DMA_SHARED_MEM);
desc[num_cmd].pyld = cmd_pyld[num_cmd]->data;
desc[num_cmd].len = cmd_pyld[num_cmd]->len;
desc[num_cmd++].type = IPA_IMM_CMD_DESC;
}
if (ipa3_send_cmd(num_cmd, desc)) {
IPAERR("fail to send immediate command\n");
rc = -EFAULT;
goto fail_imm_cmd_construct;
}
IPADBG_LOW("Hashable HEAD\n");
IPA_DUMP_BUFF(hash_hdr.base, hash_hdr.phys_base, hash_hdr.size);
IPADBG_LOW("Non-Hashable HEAD\n");
IPA_DUMP_BUFF(nhash_hdr.base, nhash_hdr.phys_base, nhash_hdr.size);
if (hash_bdy.size) {
IPADBG_LOW("Hashable BODY\n");
IPA_DUMP_BUFF(hash_bdy.base,
hash_bdy.phys_base, hash_bdy.size);
}
if (nhash_bdy.size) {
IPADBG_LOW("Non-Hashable BODY\n");
IPA_DUMP_BUFF(nhash_bdy.base,
nhash_bdy.phys_base, nhash_bdy.size);
}
__ipa_reap_sys_flt_tbls(ip, IPA_RULE_HASHABLE);
__ipa_reap_sys_flt_tbls(ip, IPA_RULE_NON_HASHABLE);
fail_imm_cmd_construct:
for (i = 0 ; i < num_cmd ; i++)
ipahal_destroy_imm_cmd(cmd_pyld[i]);
fail_reg_write_construct:
kfree(desc);
kfree(cmd_pyld);
fail_size_valid:
dma_free_coherent(ipa3_ctx->pdev, hash_hdr.size,
hash_hdr.base, hash_hdr.phys_base);
dma_free_coherent(ipa3_ctx->pdev, nhash_hdr.size,
nhash_hdr.base, nhash_hdr.phys_base);
if (hash_bdy.size)
dma_free_coherent(ipa3_ctx->pdev, hash_bdy.size,
hash_bdy.base, hash_bdy.phys_base);
if (nhash_bdy.size)
dma_free_coherent(ipa3_ctx->pdev, nhash_bdy.size,
nhash_bdy.base, nhash_bdy.phys_base);
fail_gen:
return rc;
}
static int __ipa_validate_flt_rule(const struct ipa_flt_rule *rule,
struct ipa3_rt_tbl **rt_tbl, enum ipa_ip_type ip)
{
if (rule->action != IPA_PASS_TO_EXCEPTION) {
if (!rule->eq_attrib_type) {
if (!rule->rt_tbl_hdl) {
IPAERR("invalid RT tbl\n");
goto error;
}
*rt_tbl = ipa3_id_find(rule->rt_tbl_hdl);
if (*rt_tbl == NULL) {
IPAERR("RT tbl not found\n");
goto error;
}
if ((*rt_tbl)->cookie != IPA_COOKIE) {
IPAERR("RT table cookie is invalid\n");
goto error;
}
} else {
if (rule->rt_tbl_idx > ((ip == IPA_IP_v4) ?
IPA_MEM_PART(v4_modem_rt_index_hi) :
IPA_MEM_PART(v6_modem_rt_index_hi))) {
IPAERR("invalid RT tbl\n");
goto error;
}
}
}
if (rule->rule_id) {
if (rule->rule_id >= IPA_RULE_ID_MIN_VAL &&
rule->rule_id <= IPA_RULE_ID_MAX_VAL) {
IPAERR("invalid rule_id provided 0x%x\n"
"rule_id 0x%x - 0x%x are auto generated\n",
rule->rule_id,
IPA_RULE_ID_MIN_VAL,
IPA_RULE_ID_MAX_VAL);
goto error;
}
}
return 0;
error:
return -EPERM;
}
static int __ipa_create_flt_entry(struct ipa3_flt_entry **entry,
const struct ipa_flt_rule *rule, struct ipa3_rt_tbl *rt_tbl,
struct ipa3_flt_tbl *tbl)
{
int id;
*entry = kmem_cache_zalloc(ipa3_ctx->flt_rule_cache, GFP_KERNEL);
if (!*entry) {
IPAERR("failed to alloc FLT rule object\n");
goto error;
}
INIT_LIST_HEAD(&((*entry)->link));
(*entry)->rule = *rule;
(*entry)->cookie = IPA_COOKIE;
(*entry)->rt_tbl = rt_tbl;
(*entry)->tbl = tbl;
if (rule->rule_id) {
id = rule->rule_id;
} else {
id = ipa3_alloc_rule_id(&tbl->rule_ids);
if (id < 0) {
IPAERR("failed to allocate rule id\n");
WARN_ON(1);
goto rule_id_fail;
}
}
(*entry)->rule_id = id;
return 0;
rule_id_fail:
kmem_cache_free(ipa3_ctx->flt_rule_cache, *entry);
error:
return -EPERM;
}
static int __ipa_finish_flt_rule_add(struct ipa3_flt_tbl *tbl,
struct ipa3_flt_entry *entry, u32 *rule_hdl)
{
int id;
tbl->rule_cnt++;
if (entry->rt_tbl)
entry->rt_tbl->ref_cnt++;
id = ipa3_id_alloc(entry);
if (id < 0) {
IPAERR("failed to add to tree\n");
WARN_ON(1);
}
*rule_hdl = id;
entry->id = id;
IPADBG_LOW("add flt rule rule_cnt=%d\n", tbl->rule_cnt);
return 0;
}
static int __ipa_add_flt_rule(struct ipa3_flt_tbl *tbl, enum ipa_ip_type ip,
const struct ipa_flt_rule *rule, u8 add_rear,
u32 *rule_hdl)
{
struct ipa3_flt_entry *entry;
struct ipa3_rt_tbl *rt_tbl = NULL;
if (__ipa_validate_flt_rule(rule, &rt_tbl, ip))
goto error;
if (__ipa_create_flt_entry(&entry, rule, rt_tbl, tbl))
goto error;
if (add_rear) {
if (tbl->sticky_rear)
list_add_tail(&entry->link,
tbl->head_flt_rule_list.prev);
else
list_add_tail(&entry->link, &tbl->head_flt_rule_list);
} else {
list_add(&entry->link, &tbl->head_flt_rule_list);
}
__ipa_finish_flt_rule_add(tbl, entry, rule_hdl);
return 0;
error:
return -EPERM;
}
static int __ipa_add_flt_rule_after(struct ipa3_flt_tbl *tbl,
const struct ipa_flt_rule *rule,
u32 *rule_hdl,
enum ipa_ip_type ip,
struct ipa3_flt_entry **add_after_entry)
{
struct ipa3_flt_entry *entry;
struct ipa3_rt_tbl *rt_tbl = NULL;
if (!*add_after_entry)
goto error;
if (rule == NULL || rule_hdl == NULL) {
IPAERR("bad parms rule=%p rule_hdl=%p\n", rule,
rule_hdl);
goto error;
}
if (__ipa_validate_flt_rule(rule, &rt_tbl, ip))
goto error;
if (__ipa_create_flt_entry(&entry, rule, rt_tbl, tbl))
goto error;
list_add(&entry->link, &((*add_after_entry)->link));
__ipa_finish_flt_rule_add(tbl, entry, rule_hdl);
/*
* prepare for next insertion
*/
*add_after_entry = entry;
return 0;
error:
*add_after_entry = NULL;
return -EPERM;
}
static int __ipa_del_flt_rule(u32 rule_hdl)
{
struct ipa3_flt_entry *entry;
int id;
entry = ipa3_id_find(rule_hdl);
if (entry == NULL) {
IPAERR("lookup failed\n");
return -EINVAL;
}
if (entry->cookie != IPA_COOKIE) {
IPAERR("bad params\n");
return -EINVAL;
}
id = entry->id;
list_del(&entry->link);
entry->tbl->rule_cnt--;
if (entry->rt_tbl)
entry->rt_tbl->ref_cnt--;
IPADBG("del flt rule rule_cnt=%d rule_id=%d\n",
entry->tbl->rule_cnt, entry->rule_id);
entry->cookie = 0;
/* if rule id was allocated from idr, remove it */
if (entry->rule_id >= IPA_RULE_ID_MIN_VAL &&
entry->rule_id <= IPA_RULE_ID_MAX_VAL)
idr_remove(&entry->tbl->rule_ids, entry->rule_id);
kmem_cache_free(ipa3_ctx->flt_rule_cache, entry);
/* remove the handle from the database */
ipa3_id_remove(id);
return 0;
}
static int __ipa_mdfy_flt_rule(struct ipa_flt_rule_mdfy *frule,
enum ipa_ip_type ip)
{
struct ipa3_flt_entry *entry;
struct ipa3_rt_tbl *rt_tbl = NULL;
entry = ipa3_id_find(frule->rule_hdl);
if (entry == NULL) {
IPAERR("lookup failed\n");
goto error;
}
if (entry->cookie != IPA_COOKIE) {
IPAERR("bad params\n");
goto error;
}
if (entry->rt_tbl)
entry->rt_tbl->ref_cnt--;
if (frule->rule.action != IPA_PASS_TO_EXCEPTION) {
if (!frule->rule.eq_attrib_type) {
if (!frule->rule.rt_tbl_hdl) {
IPAERR("invalid RT tbl\n");
goto error;
}
rt_tbl = ipa3_id_find(frule->rule.rt_tbl_hdl);
if (rt_tbl == NULL) {
IPAERR("RT tbl not found\n");
goto error;
}
if (rt_tbl->cookie != IPA_COOKIE) {
IPAERR("RT table cookie is invalid\n");
goto error;
}
} else {
if (frule->rule.rt_tbl_idx > ((ip == IPA_IP_v4) ?
IPA_MEM_PART(v4_modem_rt_index_hi) :
IPA_MEM_PART(v6_modem_rt_index_hi))) {
IPAERR("invalid RT tbl\n");
goto error;
}
}
}
entry->rule = frule->rule;
entry->rt_tbl = rt_tbl;
if (entry->rt_tbl)
entry->rt_tbl->ref_cnt++;
entry->hw_len = 0;
entry->prio = 0;
return 0;
error:
return -EPERM;
}
static int __ipa_add_flt_get_ep_idx(enum ipa_client_type ep, int *ipa_ep_idx)
{
*ipa_ep_idx = ipa3_get_ep_mapping(ep);
if (*ipa_ep_idx == IPA_FLT_TABLE_INDEX_NOT_FOUND) {
IPAERR("ep not valid ep=%d\n", ep);
return -EINVAL;
}
if (ipa3_ctx->ep[*ipa_ep_idx].valid == 0)
IPADBG("ep not connected ep_idx=%d\n", *ipa_ep_idx);
if (!ipa_is_ep_support_flt(*ipa_ep_idx)) {
IPAERR("ep do not support filtering ep=%d\n", ep);
return -EINVAL;
}
return 0;
}
static int __ipa_add_ep_flt_rule(enum ipa_ip_type ip, enum ipa_client_type ep,
const struct ipa_flt_rule *rule, u8 add_rear,
u32 *rule_hdl)
{
struct ipa3_flt_tbl *tbl;
int ipa_ep_idx;
if (rule == NULL || rule_hdl == NULL || ep >= IPA_CLIENT_MAX) {
IPAERR("bad parms rule=%p rule_hdl=%p ep=%d\n", rule,
rule_hdl, ep);
return -EINVAL;
}
if (__ipa_add_flt_get_ep_idx(ep, &ipa_ep_idx))
return -EINVAL;
tbl = &ipa3_ctx->flt_tbl[ipa_ep_idx][ip];
IPADBG_LOW("add ep flt rule ip=%d ep=%d\n", ip, ep);
return __ipa_add_flt_rule(tbl, ip, rule, add_rear, rule_hdl);
}
/**
* ipa3_add_flt_rule() - Add the specified filtering rules to SW and optionally
* commit to IPA HW
*
* Returns: 0 on success, negative on failure
*
* Note: Should not be called from atomic context
*/
int ipa3_add_flt_rule(struct ipa_ioc_add_flt_rule *rules)
{
int i;
int result;
if (rules == NULL || rules->num_rules == 0 ||
rules->ip >= IPA_IP_MAX) {
IPAERR("bad parm\n");
return -EINVAL;
}
mutex_lock(&ipa3_ctx->lock);
for (i = 0; i < rules->num_rules; i++) {
if (!rules->global)
result = __ipa_add_ep_flt_rule(rules->ip, rules->ep,
&rules->rules[i].rule,
rules->rules[i].at_rear,
&rules->rules[i].flt_rule_hdl);
else
result = -1;
if (result) {
IPAERR("failed to add flt rule %d\n", i);
rules->rules[i].status = IPA_FLT_STATUS_OF_ADD_FAILED;
} else {
rules->rules[i].status = 0;
}
}
if (rules->global) {
IPAERR("no support for global filter rules\n");
result = -EPERM;
goto bail;
}
if (rules->commit)
if (ipa3_ctx->ctrl->ipa3_commit_flt(rules->ip)) {
result = -EPERM;
goto bail;
}
result = 0;
bail:
mutex_unlock(&ipa3_ctx->lock);
return result;
}
/**
* ipa3_add_flt_rule_after() - Add the specified filtering rules to SW after
* the rule which its handle is given and optionally commit to IPA HW
*
* Returns: 0 on success, negative on failure
*
* Note: Should not be called from atomic context
*/
int ipa3_add_flt_rule_after(struct ipa_ioc_add_flt_rule_after *rules)
{
int i;
int result;
struct ipa3_flt_tbl *tbl;
int ipa_ep_idx;
struct ipa3_flt_entry *entry;
if (rules == NULL || rules->num_rules == 0 ||
rules->ip >= IPA_IP_MAX) {
IPAERR("bad parm\n");
return -EINVAL;
}
if (rules->ep >= IPA_CLIENT_MAX) {
IPAERR("bad parms ep=%d\n", rules->ep);
return -EINVAL;
}
mutex_lock(&ipa3_ctx->lock);
if (__ipa_add_flt_get_ep_idx(rules->ep, &ipa_ep_idx)) {
result = -EINVAL;
goto bail;
}
tbl = &ipa3_ctx->flt_tbl[ipa_ep_idx][rules->ip];
entry = ipa3_id_find(rules->add_after_hdl);
if (entry == NULL) {
IPAERR("lookup failed\n");
result = -EINVAL;
goto bail;
}
if (entry->tbl != tbl) {
IPAERR("given entry does not match the table\n");
result = -EINVAL;
goto bail;
}
if (tbl->sticky_rear)
if (&entry->link == tbl->head_flt_rule_list.prev) {
IPAERR("cannot add rule at end of a sticky table");
result = -EINVAL;
goto bail;
}
IPADBG("add ep flt rule ip=%d ep=%d after hdl %d\n",
rules->ip, rules->ep, rules->add_after_hdl);
/*
* we add all rules one after the other, if one insertion fails, it cuts
* the chain (all following will receive fail status) following calls to
* __ipa_add_flt_rule_after will fail (entry == NULL)
*/
for (i = 0; i < rules->num_rules; i++) {
result = __ipa_add_flt_rule_after(tbl,
&rules->rules[i].rule,
&rules->rules[i].flt_rule_hdl,
rules->ip,
&entry);
if (result) {
IPAERR("failed to add flt rule %d\n", i);
rules->rules[i].status = IPA_FLT_STATUS_OF_ADD_FAILED;
} else {
rules->rules[i].status = 0;
}
}
if (rules->commit)
if (ipa3_ctx->ctrl->ipa3_commit_flt(rules->ip)) {
IPAERR("failed to commit flt rules\n");
result = -EPERM;
goto bail;
}
result = 0;
bail:
mutex_unlock(&ipa3_ctx->lock);
return result;
}
/**
* ipa3_del_flt_rule() - Remove the specified filtering rules from SW and
* optionally commit to IPA HW
*
* Returns: 0 on success, negative on failure
*
* Note: Should not be called from atomic context
*/
int ipa3_del_flt_rule(struct ipa_ioc_del_flt_rule *hdls)
{
int i;
int result;
if (hdls == NULL || hdls->num_hdls == 0 || hdls->ip >= IPA_IP_MAX) {
IPAERR("bad parm\n");
return -EINVAL;
}
mutex_lock(&ipa3_ctx->lock);
for (i = 0; i < hdls->num_hdls; i++) {
if (__ipa_del_flt_rule(hdls->hdl[i].hdl)) {
IPAERR("failed to del flt rule %i\n", i);
hdls->hdl[i].status = IPA_FLT_STATUS_OF_DEL_FAILED;
} else {
hdls->hdl[i].status = 0;
}
}
if (hdls->commit)
if (ipa3_ctx->ctrl->ipa3_commit_flt(hdls->ip)) {
result = -EPERM;
goto bail;
}
result = 0;
bail:
mutex_unlock(&ipa3_ctx->lock);
return result;
}
/**
* ipa3_mdfy_flt_rule() - Modify the specified filtering rules in SW and optionally
* commit to IPA HW
*
* Returns: 0 on success, negative on failure
*
* Note: Should not be called from atomic context
*/
int ipa3_mdfy_flt_rule(struct ipa_ioc_mdfy_flt_rule *hdls)
{
int i;
int result;
if (hdls == NULL || hdls->num_rules == 0 || hdls->ip >= IPA_IP_MAX) {
IPAERR("bad parm\n");
return -EINVAL;
}
mutex_lock(&ipa3_ctx->lock);
for (i = 0; i < hdls->num_rules; i++) {
if (__ipa_mdfy_flt_rule(&hdls->rules[i], hdls->ip)) {
IPAERR("failed to mdfy flt rule %i\n", i);
hdls->rules[i].status = IPA_FLT_STATUS_OF_MDFY_FAILED;
} else {
hdls->rules[i].status = 0;
}
}
if (hdls->commit)
if (ipa3_ctx->ctrl->ipa3_commit_flt(hdls->ip)) {
result = -EPERM;
goto bail;
}
result = 0;
bail:
mutex_unlock(&ipa3_ctx->lock);
return result;
}
/**
* ipa3_commit_flt() - Commit the current SW filtering table of specified type to
* IPA HW
* @ip: [in] the family of routing tables
*
* Returns: 0 on success, negative on failure
*
* Note: Should not be called from atomic context
*/
int ipa3_commit_flt(enum ipa_ip_type ip)
{
int result;
if (ip >= IPA_IP_MAX) {
IPAERR("bad parm\n");
return -EINVAL;
}
mutex_lock(&ipa3_ctx->lock);
if (ipa3_ctx->ctrl->ipa3_commit_flt(ip)) {
result = -EPERM;
goto bail;
}
result = 0;
bail:
mutex_unlock(&ipa3_ctx->lock);
return result;
}
/**
* ipa3_reset_flt() - Reset the current SW filtering table of specified type
* (does not commit to HW)
* @ip: [in] the family of routing tables
*
* Returns: 0 on success, negative on failure
*
* Note: Should not be called from atomic context
*/
int ipa3_reset_flt(enum ipa_ip_type ip)
{
struct ipa3_flt_tbl *tbl;
struct ipa3_flt_entry *entry;
struct ipa3_flt_entry *next;
int i;
int id;
if (ip >= IPA_IP_MAX) {
IPAERR("bad parm\n");
return -EINVAL;
}
mutex_lock(&ipa3_ctx->lock);
for (i = 0; i < ipa3_ctx->ipa_num_pipes; i++) {
if (!ipa_is_ep_support_flt(i))
continue;
tbl = &ipa3_ctx->flt_tbl[i][ip];
list_for_each_entry_safe(entry, next, &tbl->head_flt_rule_list,
link) {
if (ipa3_id_find(entry->id) == NULL) {
WARN_ON(1);
mutex_unlock(&ipa3_ctx->lock);
return -EFAULT;
}
list_del(&entry->link);
entry->tbl->rule_cnt--;
if (entry->rt_tbl)
entry->rt_tbl->ref_cnt--;
/* if rule id was allocated from idr, remove it */
if (entry->rule_id >= IPA_RULE_ID_MIN_VAL &&
entry->rule_id <= IPA_RULE_ID_MAX_VAL)
idr_remove(&entry->tbl->rule_ids,
entry->rule_id);
entry->cookie = 0;
id = entry->id;
kmem_cache_free(ipa3_ctx->flt_rule_cache, entry);
/* remove the handle from the database */
ipa3_id_remove(id);
}
}
mutex_unlock(&ipa3_ctx->lock);
return 0;
}
void ipa3_install_dflt_flt_rules(u32 ipa_ep_idx)
{
struct ipa3_flt_tbl *tbl;
struct ipa3_ep_context *ep = &ipa3_ctx->ep[ipa_ep_idx];
struct ipa_flt_rule rule;
if (!ipa_is_ep_support_flt(ipa_ep_idx)) {
IPADBG("cannot add flt rules to non filtering pipe num %d\n",
ipa_ep_idx);
return;
}
memset(&rule, 0, sizeof(rule));
mutex_lock(&ipa3_ctx->lock);
tbl = &ipa3_ctx->flt_tbl[ipa_ep_idx][IPA_IP_v4];
tbl->sticky_rear = true;
rule.action = IPA_PASS_TO_EXCEPTION;
__ipa_add_flt_rule(tbl, IPA_IP_v4, &rule, false,
&ep->dflt_flt4_rule_hdl);
ipa3_ctx->ctrl->ipa3_commit_flt(IPA_IP_v4);
tbl = &ipa3_ctx->flt_tbl[ipa_ep_idx][IPA_IP_v6];
tbl->sticky_rear = true;
rule.action = IPA_PASS_TO_EXCEPTION;
__ipa_add_flt_rule(tbl, IPA_IP_v6, &rule, false,
&ep->dflt_flt6_rule_hdl);
ipa3_ctx->ctrl->ipa3_commit_flt(IPA_IP_v6);
mutex_unlock(&ipa3_ctx->lock);
}
void ipa3_delete_dflt_flt_rules(u32 ipa_ep_idx)
{
struct ipa3_ep_context *ep = &ipa3_ctx->ep[ipa_ep_idx];
mutex_lock(&ipa3_ctx->lock);
if (ep->dflt_flt4_rule_hdl) {
__ipa_del_flt_rule(ep->dflt_flt4_rule_hdl);
ipa3_ctx->ctrl->ipa3_commit_flt(IPA_IP_v4);
ep->dflt_flt4_rule_hdl = 0;
}
if (ep->dflt_flt6_rule_hdl) {
__ipa_del_flt_rule(ep->dflt_flt6_rule_hdl);
ipa3_ctx->ctrl->ipa3_commit_flt(IPA_IP_v6);
ep->dflt_flt6_rule_hdl = 0;
}
mutex_unlock(&ipa3_ctx->lock);
}
/**
* ipa3_set_flt_tuple_mask() - Sets the flt tuple masking for the given pipe
* Pipe must be for AP EP (not modem) and support filtering
* updates the the filtering masking values without changing the rt ones.
*
* @pipe_idx: filter pipe index to configure the tuple masking
* @tuple: the tuple members masking
* Returns: 0 on success, negative on failure
*
*/
int ipa3_set_flt_tuple_mask(int pipe_idx, struct ipahal_reg_hash_tuple *tuple)
{
struct ipahal_reg_fltrt_hash_tuple fltrt_tuple;
if (!tuple) {
IPAERR("bad tuple\n");
return -EINVAL;
}
if (pipe_idx >= ipa3_ctx->ipa_num_pipes || pipe_idx < 0) {
IPAERR("bad pipe index!\n");
return -EINVAL;
}
if (!ipa_is_ep_support_flt(pipe_idx)) {
IPAERR("pipe %d not filtering pipe\n", pipe_idx);
return -EINVAL;
}
if (ipa_is_modem_pipe(pipe_idx)) {
IPAERR("modem pipe tuple is not configured by AP\n");
return -EINVAL;
}
ipahal_read_reg_n_fields(IPA_ENDP_FILTER_ROUTER_HSH_CFG_n,
pipe_idx, &fltrt_tuple);
fltrt_tuple.flt = *tuple;
ipahal_write_reg_n_fields(IPA_ENDP_FILTER_ROUTER_HSH_CFG_n,
pipe_idx, &fltrt_tuple);
return 0;
}
/**
* ipa3_flt_read_tbl_from_hw() -Read filtering table from IPA HW
* @pipe_idx: IPA endpoint index
* @ip_type: IPv4 or IPv6 table
* @hashable: hashable or non-hashable table
* @entry: array to fill the table entries
* @num_entry: number of entries in entry array. set by the caller to indicate
* entry array size. Then set by this function as an output parameter to
* indicate the number of entries in the array
*
* This function reads the filtering table from IPA SRAM and prepares an array
* of entries. This function is mainly used for debugging purposes.
* Returns: 0 on success, negative on failure
*/
int ipa3_flt_read_tbl_from_hw(u32 pipe_idx,
enum ipa_ip_type ip_type,
bool hashable,
struct ipa3_flt_entry entry[],
int *num_entry)
{
int tbl_entry_idx;
u64 tbl_entry_in_hdr_ofst;
u64 *tbl_entry_in_hdr;
struct ipa3_flt_rule_hw_hdr *hdr;
u8 *buf;
int rule_idx;
u8 rule_size;
int i;
void *ipa_sram_mmio;
IPADBG("pipe_idx=%d ip_type=%d hashable=%d\n",
pipe_idx, ip_type, hashable);
if (pipe_idx >= ipa3_ctx->ipa_num_pipes ||
ip_type >= IPA_IP_MAX ||
!entry || !num_entry) {
IPAERR("Invalid params\n");
return -EFAULT;
}
if (!ipa_is_ep_support_flt(pipe_idx)) {
IPAERR("pipe %d does not support filtering\n", pipe_idx);
return -EINVAL;
}
/* map IPA SRAM */
ipa_sram_mmio = ioremap(ipa3_ctx->ipa_wrapper_base +
ipa3_ctx->ctrl->ipa_reg_base_ofst +
ipahal_get_reg_n_ofst(
IPA_SRAM_DIRECT_ACCESS_n,
0),
ipa3_ctx->smem_sz);
if (!ipa_sram_mmio) {
IPAERR("fail to ioremap IPA SRAM\n");
return -ENOMEM;
}
memset(entry, 0, sizeof(*entry) * (*num_entry));
/* calculate the offset of the tbl entry */
tbl_entry_idx = 1; /* to skip the bitmap */
for (i = 0; i < pipe_idx; i++)
if (ipa3_ctx->ep_flt_bitmap & (1 << i))
tbl_entry_idx++;
if (hashable) {
if (ip_type == IPA_IP_v4)
tbl_entry_in_hdr_ofst =
ipa3_ctx->smem_restricted_bytes +
IPA_MEM_PART(v4_flt_hash_ofst) +
tbl_entry_idx * IPA_HW_TBL_HDR_WIDTH;
else
tbl_entry_in_hdr_ofst =
ipa3_ctx->smem_restricted_bytes +
IPA_MEM_PART(v6_flt_hash_ofst) +
tbl_entry_idx * IPA_HW_TBL_HDR_WIDTH;
} else {
if (ip_type == IPA_IP_v4)
tbl_entry_in_hdr_ofst =
ipa3_ctx->smem_restricted_bytes +
IPA_MEM_PART(v4_flt_nhash_ofst) +
tbl_entry_idx * IPA_HW_TBL_HDR_WIDTH;
else
tbl_entry_in_hdr_ofst =
ipa3_ctx->smem_restricted_bytes +
IPA_MEM_PART(v6_flt_nhash_ofst) +
tbl_entry_idx * IPA_HW_TBL_HDR_WIDTH;
}
IPADBG("tbl_entry_in_hdr_ofst=0x%llx\n", tbl_entry_in_hdr_ofst);
tbl_entry_in_hdr = ipa_sram_mmio + tbl_entry_in_hdr_ofst;
/* for tables resides in DDR access it from the virtual memory */
if (*tbl_entry_in_hdr & 0x1) {
/* local */
hdr = (void *)((u8 *)tbl_entry_in_hdr -
tbl_entry_idx * IPA_HW_TBL_HDR_WIDTH +
(*tbl_entry_in_hdr - 1) / 16);
} else {
/* system */
if (hashable)
hdr = ipa3_ctx->flt_tbl[pipe_idx][ip_type].
curr_mem[IPA_RULE_HASHABLE].base;
else
hdr = ipa3_ctx->flt_tbl[pipe_idx][ip_type].
curr_mem[IPA_RULE_NON_HASHABLE].base;
if (!hdr)
hdr = ipa3_ctx->empty_rt_tbl_mem.base;
}
IPADBG("*tbl_entry_in_hdr=0x%llx\n", *tbl_entry_in_hdr);
IPADBG("hdr=0x%p\n", hdr);
rule_idx = 0;
while (rule_idx < *num_entry) {
IPADBG("*((u64 *)hdr)=0x%llx\n", *((u64 *)hdr));
if (*((u64 *)hdr) == 0)
break;
entry[rule_idx].rule.eq_attrib_type = true;
entry[rule_idx].rule.eq_attrib.rule_eq_bitmap =
hdr->u.hdr.en_rule;
entry[rule_idx].rule.action = hdr->u.hdr.action;
entry[rule_idx].rule.retain_hdr = hdr->u.hdr.retain_hdr;
entry[rule_idx].rule.rt_tbl_idx = hdr->u.hdr.rt_tbl_idx;
entry[rule_idx].prio = hdr->u.hdr.priority;
entry[rule_idx].rule_id = entry->rule.rule_id =
hdr->u.hdr.rule_id;
buf = (u8 *)(hdr + 1);
IPADBG("buf=0x%p\n", buf);
ipa3_generate_eq_from_hw_rule(&entry[rule_idx].rule.eq_attrib,
buf, &rule_size);
IPADBG("rule_size=%d\n", rule_size);
hdr = (void *)(buf + rule_size);
IPADBG("hdr=0x%p\n", hdr);
rule_idx++;
}
*num_entry = rule_idx;
iounmap(ipa_sram_mmio);
return 0;
}
| gpl-2.0 |
tinyclub/preempt-rt-linux | drivers/media/dvb/dvb-usb/dtt200u.c | 563 | 9776 | /* DVB USB library compliant Linux driver for the WideView/ Yakumo/ Hama/
* Typhoon/ Yuan/ Miglia DVB-T USB2.0 receiver.
*
* Copyright (C) 2004-5 Patrick Boettcher (patrick.boettcher@desy.de)
*
* Thanks to Steve Chang from WideView for providing support for the WT-220U.
*
* 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.
*
* see Documentation/dvb/README.dvb-usb for more information
*/
#include "dtt200u.h"
/* debug */
int dvb_usb_dtt200u_debug;
module_param_named(debug,dvb_usb_dtt200u_debug, int, 0644);
MODULE_PARM_DESC(debug, "set debugging level (1=info,xfer=2 (or-able))." DVB_USB_DEBUG_STATUS);
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
static int dtt200u_power_ctrl(struct dvb_usb_device *d, int onoff)
{
u8 b = SET_INIT;
if (onoff)
dvb_usb_generic_write(d,&b,2);
return 0;
}
static int dtt200u_streaming_ctrl(struct dvb_usb_adapter *adap, int onoff)
{
u8 b_streaming[2] = { SET_STREAMING, onoff };
u8 b_rst_pid = RESET_PID_FILTER;
dvb_usb_generic_write(adap->dev, b_streaming, 2);
if (onoff == 0)
dvb_usb_generic_write(adap->dev, &b_rst_pid, 1);
return 0;
}
static int dtt200u_pid_filter(struct dvb_usb_adapter *adap, int index, u16 pid, int onoff)
{
u8 b_pid[4];
pid = onoff ? pid : 0;
b_pid[0] = SET_PID_FILTER;
b_pid[1] = index;
b_pid[2] = pid & 0xff;
b_pid[3] = (pid >> 8) & 0x1f;
return dvb_usb_generic_write(adap->dev, b_pid, 4);
}
/* remote control */
/* key list for the tiny remote control (Yakumo, don't know about the others) */
static struct dvb_usb_rc_key dtt200u_rc_keys[] = {
{ 0x8001, KEY_MUTE },
{ 0x8002, KEY_CHANNELDOWN },
{ 0x8003, KEY_VOLUMEDOWN },
{ 0x8004, KEY_1 },
{ 0x8005, KEY_2 },
{ 0x8006, KEY_3 },
{ 0x8007, KEY_4 },
{ 0x8008, KEY_5 },
{ 0x8009, KEY_6 },
{ 0x800a, KEY_7 },
{ 0x800c, KEY_ZOOM },
{ 0x800d, KEY_0 },
{ 0x800e, KEY_SELECT },
{ 0x8012, KEY_POWER },
{ 0x801a, KEY_CHANNELUP },
{ 0x801b, KEY_8 },
{ 0x801e, KEY_VOLUMEUP },
{ 0x801f, KEY_9 },
};
static int dtt200u_rc_query(struct dvb_usb_device *d, u32 *event, int *state)
{
u8 key[5],cmd = GET_RC_CODE;
dvb_usb_generic_rw(d,&cmd,1,key,5,0);
dvb_usb_nec_rc_key_to_event(d,key,event,state);
if (key[0] != 0)
deb_info("key: %x %x %x %x %x\n",key[0],key[1],key[2],key[3],key[4]);
return 0;
}
static int dtt200u_frontend_attach(struct dvb_usb_adapter *adap)
{
adap->fe = dtt200u_fe_attach(adap->dev);
return 0;
}
static struct dvb_usb_device_properties dtt200u_properties;
static struct dvb_usb_device_properties wt220u_fc_properties;
static struct dvb_usb_device_properties wt220u_properties;
static struct dvb_usb_device_properties wt220u_zl0353_properties;
static struct dvb_usb_device_properties wt220u_miglia_properties;
static int dtt200u_usb_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
if (0 == dvb_usb_device_init(intf, &dtt200u_properties,
THIS_MODULE, NULL, adapter_nr) ||
0 == dvb_usb_device_init(intf, &wt220u_properties,
THIS_MODULE, NULL, adapter_nr) ||
0 == dvb_usb_device_init(intf, &wt220u_fc_properties,
THIS_MODULE, NULL, adapter_nr) ||
0 == dvb_usb_device_init(intf, &wt220u_zl0353_properties,
THIS_MODULE, NULL, adapter_nr) ||
0 == dvb_usb_device_init(intf, &wt220u_miglia_properties,
THIS_MODULE, NULL, adapter_nr))
return 0;
return -ENODEV;
}
static struct usb_device_id dtt200u_usb_table [] = {
{ USB_DEVICE(USB_VID_WIDEVIEW, USB_PID_DTT200U_COLD) },
{ USB_DEVICE(USB_VID_WIDEVIEW, USB_PID_DTT200U_WARM) },
{ USB_DEVICE(USB_VID_WIDEVIEW, USB_PID_WT220U_COLD) },
{ USB_DEVICE(USB_VID_WIDEVIEW, USB_PID_WT220U_WARM) },
{ USB_DEVICE(USB_VID_WIDEVIEW, USB_PID_WT220U_ZL0353_COLD) },
{ USB_DEVICE(USB_VID_WIDEVIEW, USB_PID_WT220U_ZL0353_WARM) },
{ USB_DEVICE(USB_VID_WIDEVIEW, USB_PID_WT220U_FC_COLD) },
{ USB_DEVICE(USB_VID_WIDEVIEW, USB_PID_WT220U_FC_WARM) },
{ USB_DEVICE(USB_VID_WIDEVIEW, USB_PID_WT220U_ZAP250_COLD) },
{ USB_DEVICE(USB_VID_MIGLIA, USB_PID_WT220U_ZAP250_COLD) },
{ 0 },
};
MODULE_DEVICE_TABLE(usb, dtt200u_usb_table);
static struct dvb_usb_device_properties dtt200u_properties = {
.usb_ctrl = CYPRESS_FX2,
.firmware = "dvb-usb-dtt200u-01.fw",
.num_adapters = 1,
.adapter = {
{
.caps = DVB_USB_ADAP_HAS_PID_FILTER | DVB_USB_ADAP_NEED_PID_FILTERING,
.pid_filter_count = 15,
.streaming_ctrl = dtt200u_streaming_ctrl,
.pid_filter = dtt200u_pid_filter,
.frontend_attach = dtt200u_frontend_attach,
/* parameter for the MPEG2-data transfer */
.stream = {
.type = USB_BULK,
.count = 7,
.endpoint = 0x02,
.u = {
.bulk = {
.buffersize = 4096,
}
}
},
}
},
.power_ctrl = dtt200u_power_ctrl,
.rc_interval = 300,
.rc_key_map = dtt200u_rc_keys,
.rc_key_map_size = ARRAY_SIZE(dtt200u_rc_keys),
.rc_query = dtt200u_rc_query,
.generic_bulk_ctrl_endpoint = 0x01,
.num_device_descs = 1,
.devices = {
{ .name = "WideView/Yuan/Yakumo/Hama/Typhoon DVB-T USB2.0 (WT-200U)",
.cold_ids = { &dtt200u_usb_table[0], NULL },
.warm_ids = { &dtt200u_usb_table[1], NULL },
},
{ NULL },
}
};
static struct dvb_usb_device_properties wt220u_properties = {
.usb_ctrl = CYPRESS_FX2,
.firmware = "dvb-usb-wt220u-02.fw",
.num_adapters = 1,
.adapter = {
{
.caps = DVB_USB_ADAP_HAS_PID_FILTER | DVB_USB_ADAP_NEED_PID_FILTERING,
.pid_filter_count = 15,
.streaming_ctrl = dtt200u_streaming_ctrl,
.pid_filter = dtt200u_pid_filter,
.frontend_attach = dtt200u_frontend_attach,
/* parameter for the MPEG2-data transfer */
.stream = {
.type = USB_BULK,
.count = 7,
.endpoint = 0x02,
.u = {
.bulk = {
.buffersize = 4096,
}
}
},
}
},
.power_ctrl = dtt200u_power_ctrl,
.rc_interval = 300,
.rc_key_map = dtt200u_rc_keys,
.rc_key_map_size = ARRAY_SIZE(dtt200u_rc_keys),
.rc_query = dtt200u_rc_query,
.generic_bulk_ctrl_endpoint = 0x01,
.num_device_descs = 1,
.devices = {
{ .name = "WideView WT-220U PenType Receiver (Typhoon/Freecom)",
.cold_ids = { &dtt200u_usb_table[2], &dtt200u_usb_table[8], NULL },
.warm_ids = { &dtt200u_usb_table[3], NULL },
},
{ NULL },
}
};
static struct dvb_usb_device_properties wt220u_fc_properties = {
.usb_ctrl = CYPRESS_FX2,
.firmware = "dvb-usb-wt220u-fc03.fw",
.num_adapters = 1,
.adapter = {
{
.caps = DVB_USB_ADAP_HAS_PID_FILTER | DVB_USB_ADAP_NEED_PID_FILTERING,
.pid_filter_count = 15,
.streaming_ctrl = dtt200u_streaming_ctrl,
.pid_filter = dtt200u_pid_filter,
.frontend_attach = dtt200u_frontend_attach,
/* parameter for the MPEG2-data transfer */
.stream = {
.type = USB_BULK,
.count = 7,
.endpoint = 0x06,
.u = {
.bulk = {
.buffersize = 4096,
}
}
},
}
},
.power_ctrl = dtt200u_power_ctrl,
.rc_interval = 300,
.rc_key_map = dtt200u_rc_keys,
.rc_key_map_size = ARRAY_SIZE(dtt200u_rc_keys),
.rc_query = dtt200u_rc_query,
.generic_bulk_ctrl_endpoint = 0x01,
.num_device_descs = 1,
.devices = {
{ .name = "WideView WT-220U PenType Receiver (Typhoon/Freecom)",
.cold_ids = { &dtt200u_usb_table[6], NULL },
.warm_ids = { &dtt200u_usb_table[7], NULL },
},
{ NULL },
}
};
static struct dvb_usb_device_properties wt220u_zl0353_properties = {
.usb_ctrl = CYPRESS_FX2,
.firmware = "dvb-usb-wt220u-zl0353-01.fw",
.num_adapters = 1,
.adapter = {
{
.caps = DVB_USB_ADAP_HAS_PID_FILTER | DVB_USB_ADAP_NEED_PID_FILTERING,
.pid_filter_count = 15,
.streaming_ctrl = dtt200u_streaming_ctrl,
.pid_filter = dtt200u_pid_filter,
.frontend_attach = dtt200u_frontend_attach,
/* parameter for the MPEG2-data transfer */
.stream = {
.type = USB_BULK,
.count = 7,
.endpoint = 0x02,
.u = {
.bulk = {
.buffersize = 4096,
}
}
},
}
},
.power_ctrl = dtt200u_power_ctrl,
.rc_interval = 300,
.rc_key_map = dtt200u_rc_keys,
.rc_key_map_size = ARRAY_SIZE(dtt200u_rc_keys),
.rc_query = dtt200u_rc_query,
.generic_bulk_ctrl_endpoint = 0x01,
.num_device_descs = 1,
.devices = {
{ .name = "WideView WT-220U PenType Receiver (based on ZL353)",
.cold_ids = { &dtt200u_usb_table[4], NULL },
.warm_ids = { &dtt200u_usb_table[5], NULL },
},
{ NULL },
}
};
static struct dvb_usb_device_properties wt220u_miglia_properties = {
.usb_ctrl = CYPRESS_FX2,
.firmware = "dvb-usb-wt220u-miglia-01.fw",
.num_adapters = 1,
.generic_bulk_ctrl_endpoint = 0x01,
.num_device_descs = 1,
.devices = {
{ .name = "WideView WT-220U PenType Receiver (Miglia)",
.cold_ids = { &dtt200u_usb_table[9], NULL },
/* This device turns into WT220U_ZL0353_WARM when fw
has been uploaded */
.warm_ids = { NULL },
},
{ NULL },
}
};
/* usb specific object needed to register this driver with the usb subsystem */
static struct usb_driver dtt200u_usb_driver = {
.name = "dvb_usb_dtt200u",
.probe = dtt200u_usb_probe,
.disconnect = dvb_usb_device_exit,
.id_table = dtt200u_usb_table,
};
/* module stuff */
static int __init dtt200u_usb_module_init(void)
{
int result;
if ((result = usb_register(&dtt200u_usb_driver))) {
err("usb_register failed. (%d)",result);
return result;
}
return 0;
}
static void __exit dtt200u_usb_module_exit(void)
{
/* deregister this driver from the USB subsystem */
usb_deregister(&dtt200u_usb_driver);
}
module_init(dtt200u_usb_module_init);
module_exit(dtt200u_usb_module_exit);
MODULE_AUTHOR("Patrick Boettcher <patrick.boettcher@desy.de>");
MODULE_DESCRIPTION("Driver for the WideView/Yakumo/Hama/Typhoon/Club3D/Miglia DVB-T USB2.0 devices");
MODULE_VERSION("1.0");
MODULE_LICENSE("GPL");
| gpl-2.0 |
HRTKernel/Hacker-Kernel-H850 | drivers/gpu/drm/nouveau/core/subdev/i2c/anx9805.c | 563 | 7643 | /*
* Copyright 2013 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Ben Skeggs <bskeggs@redhat.com>
*/
#include "port.h"
struct anx9805_i2c_port {
struct nouveau_i2c_port base;
u32 addr;
u32 ctrl;
};
static int
anx9805_train(struct nouveau_i2c_port *port, int link_nr, int link_bw, bool enh)
{
struct anx9805_i2c_port *chan = (void *)port;
struct nouveau_i2c_port *mast = (void *)nv_object(chan)->parent;
u8 tmp, i;
DBG("ANX9805 train %d 0x%02x %d\n", link_nr, link_bw, enh);
nv_wri2cr(mast, chan->addr, 0xa0, link_bw);
nv_wri2cr(mast, chan->addr, 0xa1, link_nr | (enh ? 0x80 : 0x00));
nv_wri2cr(mast, chan->addr, 0xa2, 0x01);
nv_wri2cr(mast, chan->addr, 0xa8, 0x01);
i = 0;
while ((tmp = nv_rdi2cr(mast, chan->addr, 0xa8)) & 0x01) {
mdelay(5);
if (i++ == 100) {
nv_error(port, "link training timed out\n");
return -ETIMEDOUT;
}
}
if (tmp & 0x70) {
nv_error(port, "link training failed: 0x%02x\n", tmp);
return -EIO;
}
return 1;
}
static int
anx9805_aux(struct nouveau_i2c_port *port, bool retry,
u8 type, u32 addr, u8 *data, u8 size)
{
struct anx9805_i2c_port *chan = (void *)port;
struct nouveau_i2c_port *mast = (void *)nv_object(chan)->parent;
int i, ret = -ETIMEDOUT;
u8 buf[16] = {};
u8 tmp;
DBG("%02x %05x %d\n", type, addr, size);
tmp = nv_rdi2cr(mast, chan->ctrl, 0x07) & ~0x04;
nv_wri2cr(mast, chan->ctrl, 0x07, tmp | 0x04);
nv_wri2cr(mast, chan->ctrl, 0x07, tmp);
nv_wri2cr(mast, chan->ctrl, 0xf7, 0x01);
nv_wri2cr(mast, chan->addr, 0xe4, 0x80);
if (!(type & 1)) {
memcpy(buf, data, size);
DBG("%16ph", buf);
for (i = 0; i < size; i++)
nv_wri2cr(mast, chan->addr, 0xf0 + i, buf[i]);
}
nv_wri2cr(mast, chan->addr, 0xe5, ((size - 1) << 4) | type);
nv_wri2cr(mast, chan->addr, 0xe6, (addr & 0x000ff) >> 0);
nv_wri2cr(mast, chan->addr, 0xe7, (addr & 0x0ff00) >> 8);
nv_wri2cr(mast, chan->addr, 0xe8, (addr & 0xf0000) >> 16);
nv_wri2cr(mast, chan->addr, 0xe9, 0x01);
i = 0;
while ((tmp = nv_rdi2cr(mast, chan->addr, 0xe9)) & 0x01) {
mdelay(5);
if (i++ == 32)
goto done;
}
if ((tmp = nv_rdi2cr(mast, chan->ctrl, 0xf7)) & 0x01) {
ret = -EIO;
goto done;
}
if (type & 1) {
for (i = 0; i < size; i++)
buf[i] = nv_rdi2cr(mast, chan->addr, 0xf0 + i);
DBG("%16ph", buf);
memcpy(data, buf, size);
}
ret = 0;
done:
nv_wri2cr(mast, chan->ctrl, 0xf7, 0x01);
return ret;
}
static const struct nouveau_i2c_func
anx9805_aux_func = {
.aux = anx9805_aux,
.lnk_ctl = anx9805_train,
};
static int
anx9805_aux_chan_ctor(struct nouveau_object *parent,
struct nouveau_object *engine,
struct nouveau_oclass *oclass, void *data, u32 index,
struct nouveau_object **pobject)
{
struct nouveau_i2c_port *mast = (void *)parent;
struct anx9805_i2c_port *chan;
int ret;
ret = nouveau_i2c_port_create(parent, engine, oclass, index,
&nouveau_i2c_aux_algo, &anx9805_aux_func,
&chan);
*pobject = nv_object(chan);
if (ret)
return ret;
switch ((oclass->handle & 0xff00) >> 8) {
case 0x0d:
chan->addr = 0x38;
chan->ctrl = 0x39;
break;
case 0x0e:
chan->addr = 0x3c;
chan->ctrl = 0x3b;
break;
default:
BUG_ON(1);
}
if (mast->adapter.algo == &i2c_bit_algo) {
struct i2c_algo_bit_data *algo = mast->adapter.algo_data;
algo->udelay = max(algo->udelay, 40);
}
return 0;
}
static struct nouveau_ofuncs
anx9805_aux_ofuncs = {
.ctor = anx9805_aux_chan_ctor,
.dtor = _nouveau_i2c_port_dtor,
.init = _nouveau_i2c_port_init,
.fini = _nouveau_i2c_port_fini,
};
static int
anx9805_xfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
{
struct anx9805_i2c_port *port = adap->algo_data;
struct nouveau_i2c_port *mast = (void *)nv_object(port)->parent;
struct i2c_msg *msg = msgs;
int ret = -ETIMEDOUT;
int i, j, cnt = num;
u8 seg = 0x00, off = 0x00, tmp;
tmp = nv_rdi2cr(mast, port->ctrl, 0x07) & ~0x10;
nv_wri2cr(mast, port->ctrl, 0x07, tmp | 0x10);
nv_wri2cr(mast, port->ctrl, 0x07, tmp);
nv_wri2cr(mast, port->addr, 0x43, 0x05);
mdelay(5);
while (cnt--) {
if ( (msg->flags & I2C_M_RD) && msg->addr == 0x50) {
nv_wri2cr(mast, port->addr, 0x40, msg->addr << 1);
nv_wri2cr(mast, port->addr, 0x41, seg);
nv_wri2cr(mast, port->addr, 0x42, off);
nv_wri2cr(mast, port->addr, 0x44, msg->len);
nv_wri2cr(mast, port->addr, 0x45, 0x00);
nv_wri2cr(mast, port->addr, 0x43, 0x01);
for (i = 0; i < msg->len; i++) {
j = 0;
while (nv_rdi2cr(mast, port->addr, 0x46) & 0x10) {
mdelay(5);
if (j++ == 32)
goto done;
}
msg->buf[i] = nv_rdi2cr(mast, port->addr, 0x47);
}
} else
if (!(msg->flags & I2C_M_RD)) {
if (msg->addr == 0x50 && msg->len == 0x01) {
off = msg->buf[0];
} else
if (msg->addr == 0x30 && msg->len == 0x01) {
seg = msg->buf[0];
} else
goto done;
} else {
goto done;
}
msg++;
}
ret = num;
done:
nv_wri2cr(mast, port->addr, 0x43, 0x00);
return ret;
}
static u32
anx9805_func(struct i2c_adapter *adap)
{
return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
}
static const struct i2c_algorithm
anx9805_i2c_algo = {
.master_xfer = anx9805_xfer,
.functionality = anx9805_func
};
static const struct nouveau_i2c_func
anx9805_i2c_func = {
};
static int
anx9805_ddc_port_ctor(struct nouveau_object *parent,
struct nouveau_object *engine,
struct nouveau_oclass *oclass, void *data, u32 index,
struct nouveau_object **pobject)
{
struct nouveau_i2c_port *mast = (void *)parent;
struct anx9805_i2c_port *port;
int ret;
ret = nouveau_i2c_port_create(parent, engine, oclass, index,
&anx9805_i2c_algo, &anx9805_i2c_func,
&port);
*pobject = nv_object(port);
if (ret)
return ret;
switch ((oclass->handle & 0xff00) >> 8) {
case 0x0d:
port->addr = 0x3d;
port->ctrl = 0x39;
break;
case 0x0e:
port->addr = 0x3f;
port->ctrl = 0x3b;
break;
default:
BUG_ON(1);
}
if (mast->adapter.algo == &i2c_bit_algo) {
struct i2c_algo_bit_data *algo = mast->adapter.algo_data;
algo->udelay = max(algo->udelay, 40);
}
return 0;
}
static struct nouveau_ofuncs
anx9805_ddc_ofuncs = {
.ctor = anx9805_ddc_port_ctor,
.dtor = _nouveau_i2c_port_dtor,
.init = _nouveau_i2c_port_init,
.fini = _nouveau_i2c_port_fini,
};
struct nouveau_oclass
nouveau_anx9805_sclass[] = {
{ .handle = NV_I2C_TYPE_EXTDDC(0x0d), .ofuncs = &anx9805_ddc_ofuncs },
{ .handle = NV_I2C_TYPE_EXTAUX(0x0d), .ofuncs = &anx9805_aux_ofuncs },
{ .handle = NV_I2C_TYPE_EXTDDC(0x0e), .ofuncs = &anx9805_ddc_ofuncs },
{ .handle = NV_I2C_TYPE_EXTAUX(0x0e), .ofuncs = &anx9805_aux_ofuncs },
{}
};
| gpl-2.0 |
cattleprod/XCeLL-XV | sound/pci/hda/hda_hwdep.c | 819 | 20219 | /*
* HWDEP Interface for HD-audio codec
*
* Copyright (c) 2007 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 <linux/pci.h>
#include <linux/compat.h>
#include <linux/mutex.h>
#include <linux/ctype.h>
#include <linux/string.h>
#include <linux/firmware.h>
#include <sound/core.h>
#include "hda_codec.h"
#include "hda_local.h"
#include <sound/hda_hwdep.h>
#include <sound/minors.h>
/* hint string pair */
struct hda_hint {
const char *key;
const char *val; /* contained in the same alloc as key */
};
/*
* write/read an out-of-bound verb
*/
static int verb_write_ioctl(struct hda_codec *codec,
struct hda_verb_ioctl __user *arg)
{
u32 verb, res;
if (get_user(verb, &arg->verb))
return -EFAULT;
res = snd_hda_codec_read(codec, verb >> 24, 0,
(verb >> 8) & 0xffff, verb & 0xff);
if (put_user(res, &arg->res))
return -EFAULT;
return 0;
}
static int get_wcap_ioctl(struct hda_codec *codec,
struct hda_verb_ioctl __user *arg)
{
u32 verb, res;
if (get_user(verb, &arg->verb))
return -EFAULT;
res = get_wcaps(codec, verb >> 24);
if (put_user(res, &arg->res))
return -EFAULT;
return 0;
}
/*
*/
static int hda_hwdep_ioctl(struct snd_hwdep *hw, struct file *file,
unsigned int cmd, unsigned long arg)
{
struct hda_codec *codec = hw->private_data;
void __user *argp = (void __user *)arg;
switch (cmd) {
case HDA_IOCTL_PVERSION:
return put_user(HDA_HWDEP_VERSION, (int __user *)argp);
case HDA_IOCTL_VERB_WRITE:
return verb_write_ioctl(codec, argp);
case HDA_IOCTL_GET_WCAP:
return get_wcap_ioctl(codec, argp);
}
return -ENOIOCTLCMD;
}
#ifdef CONFIG_COMPAT
static int hda_hwdep_ioctl_compat(struct snd_hwdep *hw, struct file *file,
unsigned int cmd, unsigned long arg)
{
return hda_hwdep_ioctl(hw, file, cmd, (unsigned long)compat_ptr(arg));
}
#endif
static int hda_hwdep_open(struct snd_hwdep *hw, struct file *file)
{
#ifndef CONFIG_SND_DEBUG_VERBOSE
if (!capable(CAP_SYS_RAWIO))
return -EACCES;
#endif
return 0;
}
static void clear_hwdep_elements(struct hda_codec *codec)
{
int i;
/* clear init verbs */
snd_array_free(&codec->init_verbs);
/* clear hints */
for (i = 0; i < codec->hints.used; i++) {
struct hda_hint *hint = snd_array_elem(&codec->hints, i);
kfree(hint->key); /* we don't need to free hint->val */
}
snd_array_free(&codec->hints);
snd_array_free(&codec->user_pins);
}
static void hwdep_free(struct snd_hwdep *hwdep)
{
clear_hwdep_elements(hwdep->private_data);
}
int /*__devinit*/ snd_hda_create_hwdep(struct hda_codec *codec)
{
char hwname[16];
struct snd_hwdep *hwdep;
int err;
sprintf(hwname, "HDA Codec %d", codec->addr);
err = snd_hwdep_new(codec->bus->card, hwname, codec->addr, &hwdep);
if (err < 0)
return err;
codec->hwdep = hwdep;
sprintf(hwdep->name, "HDA Codec %d", codec->addr);
hwdep->iface = SNDRV_HWDEP_IFACE_HDA;
hwdep->private_data = codec;
hwdep->private_free = hwdep_free;
hwdep->exclusive = 1;
hwdep->ops.open = hda_hwdep_open;
hwdep->ops.ioctl = hda_hwdep_ioctl;
#ifdef CONFIG_COMPAT
hwdep->ops.ioctl_compat = hda_hwdep_ioctl_compat;
#endif
snd_array_init(&codec->init_verbs, sizeof(struct hda_verb), 32);
snd_array_init(&codec->hints, sizeof(struct hda_hint), 32);
snd_array_init(&codec->user_pins, sizeof(struct hda_pincfg), 16);
return 0;
}
#ifdef CONFIG_SND_HDA_POWER_SAVE
static ssize_t power_on_acct_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct snd_hwdep *hwdep = dev_get_drvdata(dev);
struct hda_codec *codec = hwdep->private_data;
snd_hda_update_power_acct(codec);
return sprintf(buf, "%u\n", jiffies_to_msecs(codec->power_on_acct));
}
static ssize_t power_off_acct_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct snd_hwdep *hwdep = dev_get_drvdata(dev);
struct hda_codec *codec = hwdep->private_data;
snd_hda_update_power_acct(codec);
return sprintf(buf, "%u\n", jiffies_to_msecs(codec->power_off_acct));
}
static struct device_attribute power_attrs[] = {
__ATTR_RO(power_on_acct),
__ATTR_RO(power_off_acct),
};
int snd_hda_hwdep_add_power_sysfs(struct hda_codec *codec)
{
struct snd_hwdep *hwdep = codec->hwdep;
int i;
for (i = 0; i < ARRAY_SIZE(power_attrs); i++)
snd_add_device_sysfs_file(SNDRV_DEVICE_TYPE_HWDEP, hwdep->card,
hwdep->device, &power_attrs[i]);
return 0;
}
#endif /* CONFIG_SND_HDA_POWER_SAVE */
#ifdef CONFIG_SND_HDA_RECONFIG
/*
* sysfs interface
*/
static int clear_codec(struct hda_codec *codec)
{
int err;
err = snd_hda_codec_reset(codec);
if (err < 0) {
snd_printk(KERN_ERR "The codec is being used, can't free.\n");
return err;
}
clear_hwdep_elements(codec);
return 0;
}
static int reconfig_codec(struct hda_codec *codec)
{
int err;
snd_hda_power_up(codec);
snd_printk(KERN_INFO "hda-codec: reconfiguring\n");
err = snd_hda_codec_reset(codec);
if (err < 0) {
snd_printk(KERN_ERR
"The codec is being used, can't reconfigure.\n");
goto error;
}
err = snd_hda_codec_configure(codec);
if (err < 0)
goto error;
/* rebuild PCMs */
err = snd_hda_codec_build_pcms(codec);
if (err < 0)
goto error;
/* rebuild mixers */
err = snd_hda_codec_build_controls(codec);
if (err < 0)
goto error;
err = snd_card_register(codec->bus->card);
error:
snd_hda_power_down(codec);
return err;
}
/*
* allocate a string at most len chars, and remove the trailing EOL
*/
static char *kstrndup_noeol(const char *src, size_t len)
{
char *s = kstrndup(src, len, GFP_KERNEL);
char *p;
if (!s)
return NULL;
p = strchr(s, '\n');
if (p)
*p = 0;
return s;
}
#define CODEC_INFO_SHOW(type) \
static ssize_t type##_show(struct device *dev, \
struct device_attribute *attr, \
char *buf) \
{ \
struct snd_hwdep *hwdep = dev_get_drvdata(dev); \
struct hda_codec *codec = hwdep->private_data; \
return sprintf(buf, "0x%x\n", codec->type); \
}
#define CODEC_INFO_STR_SHOW(type) \
static ssize_t type##_show(struct device *dev, \
struct device_attribute *attr, \
char *buf) \
{ \
struct snd_hwdep *hwdep = dev_get_drvdata(dev); \
struct hda_codec *codec = hwdep->private_data; \
return sprintf(buf, "%s\n", \
codec->type ? codec->type : ""); \
}
CODEC_INFO_SHOW(vendor_id);
CODEC_INFO_SHOW(subsystem_id);
CODEC_INFO_SHOW(revision_id);
CODEC_INFO_SHOW(afg);
CODEC_INFO_SHOW(mfg);
CODEC_INFO_STR_SHOW(vendor_name);
CODEC_INFO_STR_SHOW(chip_name);
CODEC_INFO_STR_SHOW(modelname);
#define CODEC_INFO_STORE(type) \
static ssize_t type##_store(struct device *dev, \
struct device_attribute *attr, \
const char *buf, size_t count) \
{ \
struct snd_hwdep *hwdep = dev_get_drvdata(dev); \
struct hda_codec *codec = hwdep->private_data; \
unsigned long val; \
int err = strict_strtoul(buf, 0, &val); \
if (err < 0) \
return err; \
codec->type = val; \
return count; \
}
#define CODEC_INFO_STR_STORE(type) \
static ssize_t type##_store(struct device *dev, \
struct device_attribute *attr, \
const char *buf, size_t count) \
{ \
struct snd_hwdep *hwdep = dev_get_drvdata(dev); \
struct hda_codec *codec = hwdep->private_data; \
char *s = kstrndup_noeol(buf, 64); \
if (!s) \
return -ENOMEM; \
kfree(codec->type); \
codec->type = s; \
return count; \
}
CODEC_INFO_STORE(vendor_id);
CODEC_INFO_STORE(subsystem_id);
CODEC_INFO_STORE(revision_id);
CODEC_INFO_STR_STORE(vendor_name);
CODEC_INFO_STR_STORE(chip_name);
CODEC_INFO_STR_STORE(modelname);
#define CODEC_ACTION_STORE(type) \
static ssize_t type##_store(struct device *dev, \
struct device_attribute *attr, \
const char *buf, size_t count) \
{ \
struct snd_hwdep *hwdep = dev_get_drvdata(dev); \
struct hda_codec *codec = hwdep->private_data; \
int err = 0; \
if (*buf) \
err = type##_codec(codec); \
return err < 0 ? err : count; \
}
CODEC_ACTION_STORE(reconfig);
CODEC_ACTION_STORE(clear);
static ssize_t init_verbs_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct snd_hwdep *hwdep = dev_get_drvdata(dev);
struct hda_codec *codec = hwdep->private_data;
int i, len = 0;
for (i = 0; i < codec->init_verbs.used; i++) {
struct hda_verb *v = snd_array_elem(&codec->init_verbs, i);
len += snprintf(buf + len, PAGE_SIZE - len,
"0x%02x 0x%03x 0x%04x\n",
v->nid, v->verb, v->param);
}
return len;
}
static int parse_init_verbs(struct hda_codec *codec, const char *buf)
{
struct hda_verb *v;
int nid, verb, param;
if (sscanf(buf, "%i %i %i", &nid, &verb, ¶m) != 3)
return -EINVAL;
if (!nid || !verb)
return -EINVAL;
v = snd_array_new(&codec->init_verbs);
if (!v)
return -ENOMEM;
v->nid = nid;
v->verb = verb;
v->param = param;
return 0;
}
static ssize_t init_verbs_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct snd_hwdep *hwdep = dev_get_drvdata(dev);
struct hda_codec *codec = hwdep->private_data;
int err = parse_init_verbs(codec, buf);
if (err < 0)
return err;
return count;
}
static ssize_t hints_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct snd_hwdep *hwdep = dev_get_drvdata(dev);
struct hda_codec *codec = hwdep->private_data;
int i, len = 0;
for (i = 0; i < codec->hints.used; i++) {
struct hda_hint *hint = snd_array_elem(&codec->hints, i);
len += snprintf(buf + len, PAGE_SIZE - len,
"%s = %s\n", hint->key, hint->val);
}
return len;
}
static struct hda_hint *get_hint(struct hda_codec *codec, const char *key)
{
int i;
for (i = 0; i < codec->hints.used; i++) {
struct hda_hint *hint = snd_array_elem(&codec->hints, i);
if (!strcmp(hint->key, key))
return hint;
}
return NULL;
}
static void remove_trail_spaces(char *str)
{
char *p;
if (!*str)
return;
p = str + strlen(str) - 1;
for (; isspace(*p); p--) {
*p = 0;
if (p == str)
return;
}
}
#define MAX_HINTS 1024
static int parse_hints(struct hda_codec *codec, const char *buf)
{
char *key, *val;
struct hda_hint *hint;
buf = skip_spaces(buf);
if (!*buf || *buf == '#' || *buf == '\n')
return 0;
if (*buf == '=')
return -EINVAL;
key = kstrndup_noeol(buf, 1024);
if (!key)
return -ENOMEM;
/* extract key and val */
val = strchr(key, '=');
if (!val) {
kfree(key);
return -EINVAL;
}
*val++ = 0;
val = skip_spaces(val);
remove_trail_spaces(key);
remove_trail_spaces(val);
hint = get_hint(codec, key);
if (hint) {
/* replace */
kfree(hint->key);
hint->key = key;
hint->val = val;
return 0;
}
/* allocate a new hint entry */
if (codec->hints.used >= MAX_HINTS)
hint = NULL;
else
hint = snd_array_new(&codec->hints);
if (!hint) {
kfree(key);
return -ENOMEM;
}
hint->key = key;
hint->val = val;
return 0;
}
static ssize_t hints_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct snd_hwdep *hwdep = dev_get_drvdata(dev);
struct hda_codec *codec = hwdep->private_data;
int err = parse_hints(codec, buf);
if (err < 0)
return err;
return count;
}
static ssize_t pin_configs_show(struct hda_codec *codec,
struct snd_array *list,
char *buf)
{
int i, len = 0;
for (i = 0; i < list->used; i++) {
struct hda_pincfg *pin = snd_array_elem(list, i);
len += sprintf(buf + len, "0x%02x 0x%08x\n",
pin->nid, pin->cfg);
}
return len;
}
static ssize_t init_pin_configs_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct snd_hwdep *hwdep = dev_get_drvdata(dev);
struct hda_codec *codec = hwdep->private_data;
return pin_configs_show(codec, &codec->init_pins, buf);
}
static ssize_t user_pin_configs_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct snd_hwdep *hwdep = dev_get_drvdata(dev);
struct hda_codec *codec = hwdep->private_data;
return pin_configs_show(codec, &codec->user_pins, buf);
}
static ssize_t driver_pin_configs_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct snd_hwdep *hwdep = dev_get_drvdata(dev);
struct hda_codec *codec = hwdep->private_data;
return pin_configs_show(codec, &codec->driver_pins, buf);
}
#define MAX_PIN_CONFIGS 32
static int parse_user_pin_configs(struct hda_codec *codec, const char *buf)
{
int nid, cfg;
if (sscanf(buf, "%i %i", &nid, &cfg) != 2)
return -EINVAL;
if (!nid)
return -EINVAL;
return snd_hda_add_pincfg(codec, &codec->user_pins, nid, cfg);
}
static ssize_t user_pin_configs_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct snd_hwdep *hwdep = dev_get_drvdata(dev);
struct hda_codec *codec = hwdep->private_data;
int err = parse_user_pin_configs(codec, buf);
if (err < 0)
return err;
return count;
}
#define CODEC_ATTR_RW(type) \
__ATTR(type, 0644, type##_show, type##_store)
#define CODEC_ATTR_RO(type) \
__ATTR_RO(type)
#define CODEC_ATTR_WO(type) \
__ATTR(type, 0200, NULL, type##_store)
static struct device_attribute codec_attrs[] = {
CODEC_ATTR_RW(vendor_id),
CODEC_ATTR_RW(subsystem_id),
CODEC_ATTR_RW(revision_id),
CODEC_ATTR_RO(afg),
CODEC_ATTR_RO(mfg),
CODEC_ATTR_RW(vendor_name),
CODEC_ATTR_RW(chip_name),
CODEC_ATTR_RW(modelname),
CODEC_ATTR_RW(init_verbs),
CODEC_ATTR_RW(hints),
CODEC_ATTR_RO(init_pin_configs),
CODEC_ATTR_RW(user_pin_configs),
CODEC_ATTR_RO(driver_pin_configs),
CODEC_ATTR_WO(reconfig),
CODEC_ATTR_WO(clear),
};
/*
* create sysfs files on hwdep directory
*/
int snd_hda_hwdep_add_sysfs(struct hda_codec *codec)
{
struct snd_hwdep *hwdep = codec->hwdep;
int i;
for (i = 0; i < ARRAY_SIZE(codec_attrs); i++)
snd_add_device_sysfs_file(SNDRV_DEVICE_TYPE_HWDEP, hwdep->card,
hwdep->device, &codec_attrs[i]);
return 0;
}
/*
* Look for hint string
*/
const char *snd_hda_get_hint(struct hda_codec *codec, const char *key)
{
struct hda_hint *hint = get_hint(codec, key);
return hint ? hint->val : NULL;
}
EXPORT_SYMBOL_HDA(snd_hda_get_hint);
int snd_hda_get_bool_hint(struct hda_codec *codec, const char *key)
{
const char *p = snd_hda_get_hint(codec, key);
if (!p || !*p)
return -ENOENT;
switch (toupper(*p)) {
case 'T': /* true */
case 'Y': /* yes */
case '1':
return 1;
}
return 0;
}
EXPORT_SYMBOL_HDA(snd_hda_get_bool_hint);
#endif /* CONFIG_SND_HDA_RECONFIG */
#ifdef CONFIG_SND_HDA_PATCH_LOADER
/* parser mode */
enum {
LINE_MODE_NONE,
LINE_MODE_CODEC,
LINE_MODE_MODEL,
LINE_MODE_PINCFG,
LINE_MODE_VERB,
LINE_MODE_HINT,
LINE_MODE_VENDOR_ID,
LINE_MODE_SUBSYSTEM_ID,
LINE_MODE_REVISION_ID,
LINE_MODE_CHIP_NAME,
NUM_LINE_MODES,
};
static inline int strmatch(const char *a, const char *b)
{
return strnicmp(a, b, strlen(b)) == 0;
}
/* parse the contents after the line "[codec]"
* accept only the line with three numbers, and assign the current codec
*/
static void parse_codec_mode(char *buf, struct hda_bus *bus,
struct hda_codec **codecp)
{
unsigned int vendorid, subid, caddr;
struct hda_codec *codec;
*codecp = NULL;
if (sscanf(buf, "%i %i %i", &vendorid, &subid, &caddr) == 3) {
list_for_each_entry(codec, &bus->codec_list, list) {
if (codec->addr == caddr) {
*codecp = codec;
break;
}
}
}
}
/* parse the contents after the other command tags, [pincfg], [verb],
* [vendor_id], [subsystem_id], [revision_id], [chip_name], [hint] and [model]
* just pass to the sysfs helper (only when any codec was specified)
*/
static void parse_pincfg_mode(char *buf, struct hda_bus *bus,
struct hda_codec **codecp)
{
parse_user_pin_configs(*codecp, buf);
}
static void parse_verb_mode(char *buf, struct hda_bus *bus,
struct hda_codec **codecp)
{
parse_init_verbs(*codecp, buf);
}
static void parse_hint_mode(char *buf, struct hda_bus *bus,
struct hda_codec **codecp)
{
parse_hints(*codecp, buf);
}
static void parse_model_mode(char *buf, struct hda_bus *bus,
struct hda_codec **codecp)
{
kfree((*codecp)->modelname);
(*codecp)->modelname = kstrdup(buf, GFP_KERNEL);
}
static void parse_chip_name_mode(char *buf, struct hda_bus *bus,
struct hda_codec **codecp)
{
kfree((*codecp)->chip_name);
(*codecp)->chip_name = kstrdup(buf, GFP_KERNEL);
}
#define DEFINE_PARSE_ID_MODE(name) \
static void parse_##name##_mode(char *buf, struct hda_bus *bus, \
struct hda_codec **codecp) \
{ \
unsigned long val; \
if (!strict_strtoul(buf, 0, &val)) \
(*codecp)->name = val; \
}
DEFINE_PARSE_ID_MODE(vendor_id);
DEFINE_PARSE_ID_MODE(subsystem_id);
DEFINE_PARSE_ID_MODE(revision_id);
struct hda_patch_item {
const char *tag;
void (*parser)(char *buf, struct hda_bus *bus, struct hda_codec **retc);
int need_codec;
};
static struct hda_patch_item patch_items[NUM_LINE_MODES] = {
[LINE_MODE_CODEC] = { "[codec]", parse_codec_mode, 0 },
[LINE_MODE_MODEL] = { "[model]", parse_model_mode, 1 },
[LINE_MODE_VERB] = { "[verb]", parse_verb_mode, 1 },
[LINE_MODE_PINCFG] = { "[pincfg]", parse_pincfg_mode, 1 },
[LINE_MODE_HINT] = { "[hint]", parse_hint_mode, 1 },
[LINE_MODE_VENDOR_ID] = { "[vendor_id]", parse_vendor_id_mode, 1 },
[LINE_MODE_SUBSYSTEM_ID] = { "[subsystem_id]", parse_subsystem_id_mode, 1 },
[LINE_MODE_REVISION_ID] = { "[revision_id]", parse_revision_id_mode, 1 },
[LINE_MODE_CHIP_NAME] = { "[chip_name]", parse_chip_name_mode, 1 },
};
/* check the line starting with '[' -- change the parser mode accodingly */
static int parse_line_mode(char *buf, struct hda_bus *bus)
{
int i;
for (i = 0; i < ARRAY_SIZE(patch_items); i++) {
if (!patch_items[i].tag)
continue;
if (strmatch(buf, patch_items[i].tag))
return i;
}
return LINE_MODE_NONE;
}
/* copy one line from the buffer in fw, and update the fields in fw
* return zero if it reaches to the end of the buffer, or non-zero
* if successfully copied a line
*
* the spaces at the beginning and the end of the line are stripped
*/
static int get_line_from_fw(char *buf, int size, struct firmware *fw)
{
int len;
const char *p = fw->data;
while (isspace(*p) && fw->size) {
p++;
fw->size--;
}
if (!fw->size)
return 0;
if (size < fw->size)
size = fw->size;
for (len = 0; len < fw->size; len++) {
if (!*p)
break;
if (*p == '\n') {
p++;
len++;
break;
}
if (len < size)
*buf++ = *p++;
}
*buf = 0;
fw->size -= len;
fw->data = p;
remove_trail_spaces(buf);
return 1;
}
/*
* load a "patch" firmware file and parse it
*/
int snd_hda_load_patch(struct hda_bus *bus, const char *patch)
{
int err;
const struct firmware *fw;
struct firmware tmp;
char buf[128];
struct hda_codec *codec;
int line_mode;
struct device *dev = bus->card->dev;
if (snd_BUG_ON(!dev))
return -ENODEV;
err = request_firmware(&fw, patch, dev);
if (err < 0) {
printk(KERN_ERR "hda-codec: Cannot load the patch '%s'\n",
patch);
return err;
}
tmp = *fw;
line_mode = LINE_MODE_NONE;
codec = NULL;
while (get_line_from_fw(buf, sizeof(buf) - 1, &tmp)) {
if (!*buf || *buf == '#' || *buf == '\n')
continue;
if (*buf == '[')
line_mode = parse_line_mode(buf, bus);
else if (patch_items[line_mode].parser &&
(codec || !patch_items[line_mode].need_codec))
patch_items[line_mode].parser(buf, bus, &codec);
}
release_firmware(fw);
return 0;
}
EXPORT_SYMBOL_HDA(snd_hda_load_patch);
#endif /* CONFIG_SND_HDA_PATCH_LOADER */
| gpl-2.0 |
sonndinh/litmus-rt | drivers/firewire/net.c | 819 | 42618 | /*
* IPv4 over IEEE 1394, per RFC 2734
* IPv6 over IEEE 1394, per RFC 3146
*
* Copyright (C) 2009 Jay Fenlason <fenlason@redhat.com>
*
* based on eth1394 by Ben Collins et al
*/
#include <linux/bug.h>
#include <linux/compiler.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/ethtool.h>
#include <linux/firewire.h>
#include <linux/firewire-constants.h>
#include <linux/highmem.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/jiffies.h>
#include <linux/mod_devicetable.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/mutex.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <asm/unaligned.h>
#include <net/arp.h>
#include <net/firewire.h>
/* rx limits */
#define FWNET_MAX_FRAGMENTS 30 /* arbitrary, > TX queue depth */
#define FWNET_ISO_PAGE_COUNT (PAGE_SIZE < 16*1024 ? 4 : 2)
/* tx limits */
#define FWNET_MAX_QUEUED_DATAGRAMS 20 /* < 64 = number of tlabels */
#define FWNET_MIN_QUEUED_DATAGRAMS 10 /* should keep AT DMA busy enough */
#define FWNET_TX_QUEUE_LEN FWNET_MAX_QUEUED_DATAGRAMS /* ? */
#define IEEE1394_BROADCAST_CHANNEL 31
#define IEEE1394_ALL_NODES (0xffc0 | 0x003f)
#define IEEE1394_MAX_PAYLOAD_S100 512
#define FWNET_NO_FIFO_ADDR (~0ULL)
#define IANA_SPECIFIER_ID 0x00005eU
#define RFC2734_SW_VERSION 0x000001U
#define RFC3146_SW_VERSION 0x000002U
#define IEEE1394_GASP_HDR_SIZE 8
#define RFC2374_UNFRAG_HDR_SIZE 4
#define RFC2374_FRAG_HDR_SIZE 8
#define RFC2374_FRAG_OVERHEAD 4
#define RFC2374_HDR_UNFRAG 0 /* unfragmented */
#define RFC2374_HDR_FIRSTFRAG 1 /* first fragment */
#define RFC2374_HDR_LASTFRAG 2 /* last fragment */
#define RFC2374_HDR_INTFRAG 3 /* interior fragment */
static bool fwnet_hwaddr_is_multicast(u8 *ha)
{
return !!(*ha & 1);
}
/* IPv4 and IPv6 encapsulation header */
struct rfc2734_header {
u32 w0;
u32 w1;
};
#define fwnet_get_hdr_lf(h) (((h)->w0 & 0xc0000000) >> 30)
#define fwnet_get_hdr_ether_type(h) (((h)->w0 & 0x0000ffff))
#define fwnet_get_hdr_dg_size(h) (((h)->w0 & 0x0fff0000) >> 16)
#define fwnet_get_hdr_fg_off(h) (((h)->w0 & 0x00000fff))
#define fwnet_get_hdr_dgl(h) (((h)->w1 & 0xffff0000) >> 16)
#define fwnet_set_hdr_lf(lf) ((lf) << 30)
#define fwnet_set_hdr_ether_type(et) (et)
#define fwnet_set_hdr_dg_size(dgs) ((dgs) << 16)
#define fwnet_set_hdr_fg_off(fgo) (fgo)
#define fwnet_set_hdr_dgl(dgl) ((dgl) << 16)
static inline void fwnet_make_uf_hdr(struct rfc2734_header *hdr,
unsigned ether_type)
{
hdr->w0 = fwnet_set_hdr_lf(RFC2374_HDR_UNFRAG)
| fwnet_set_hdr_ether_type(ether_type);
}
static inline void fwnet_make_ff_hdr(struct rfc2734_header *hdr,
unsigned ether_type, unsigned dg_size, unsigned dgl)
{
hdr->w0 = fwnet_set_hdr_lf(RFC2374_HDR_FIRSTFRAG)
| fwnet_set_hdr_dg_size(dg_size)
| fwnet_set_hdr_ether_type(ether_type);
hdr->w1 = fwnet_set_hdr_dgl(dgl);
}
static inline void fwnet_make_sf_hdr(struct rfc2734_header *hdr,
unsigned lf, unsigned dg_size, unsigned fg_off, unsigned dgl)
{
hdr->w0 = fwnet_set_hdr_lf(lf)
| fwnet_set_hdr_dg_size(dg_size)
| fwnet_set_hdr_fg_off(fg_off);
hdr->w1 = fwnet_set_hdr_dgl(dgl);
}
/* This list keeps track of what parts of the datagram have been filled in */
struct fwnet_fragment_info {
struct list_head fi_link;
u16 offset;
u16 len;
};
struct fwnet_partial_datagram {
struct list_head pd_link;
struct list_head fi_list;
struct sk_buff *skb;
/* FIXME Why not use skb->data? */
char *pbuf;
u16 datagram_label;
u16 ether_type;
u16 datagram_size;
};
static DEFINE_MUTEX(fwnet_device_mutex);
static LIST_HEAD(fwnet_device_list);
struct fwnet_device {
struct list_head dev_link;
spinlock_t lock;
enum {
FWNET_BROADCAST_ERROR,
FWNET_BROADCAST_RUNNING,
FWNET_BROADCAST_STOPPED,
} broadcast_state;
struct fw_iso_context *broadcast_rcv_context;
struct fw_iso_buffer broadcast_rcv_buffer;
void **broadcast_rcv_buffer_ptrs;
unsigned broadcast_rcv_next_ptr;
unsigned num_broadcast_rcv_ptrs;
unsigned rcv_buffer_size;
/*
* This value is the maximum unfragmented datagram size that can be
* sent by the hardware. It already has the GASP overhead and the
* unfragmented datagram header overhead calculated into it.
*/
unsigned broadcast_xmt_max_payload;
u16 broadcast_xmt_datagramlabel;
/*
* The CSR address that remote nodes must send datagrams to for us to
* receive them.
*/
struct fw_address_handler handler;
u64 local_fifo;
/* Number of tx datagrams that have been queued but not yet acked */
int queued_datagrams;
int peer_count;
struct list_head peer_list;
struct fw_card *card;
struct net_device *netdev;
};
struct fwnet_peer {
struct list_head peer_link;
struct fwnet_device *dev;
u64 guid;
/* guarded by dev->lock */
struct list_head pd_list; /* received partial datagrams */
unsigned pdg_size; /* pd_list size */
u16 datagram_label; /* outgoing datagram label */
u16 max_payload; /* includes RFC2374_FRAG_HDR_SIZE overhead */
int node_id;
int generation;
unsigned speed;
};
/* This is our task struct. It's used for the packet complete callback. */
struct fwnet_packet_task {
struct fw_transaction transaction;
struct rfc2734_header hdr;
struct sk_buff *skb;
struct fwnet_device *dev;
int outstanding_pkts;
u64 fifo_addr;
u16 dest_node;
u16 max_payload;
u8 generation;
u8 speed;
u8 enqueued;
};
/*
* Get fifo address embedded in hwaddr
*/
static __u64 fwnet_hwaddr_fifo(union fwnet_hwaddr *ha)
{
return (u64)get_unaligned_be16(&ha->uc.fifo_hi) << 32
| get_unaligned_be32(&ha->uc.fifo_lo);
}
/*
* saddr == NULL means use device source address.
* daddr == NULL means leave destination address (eg unresolved arp).
*/
static int fwnet_header_create(struct sk_buff *skb, struct net_device *net,
unsigned short type, const void *daddr,
const void *saddr, unsigned len)
{
struct fwnet_header *h;
h = (struct fwnet_header *)skb_push(skb, sizeof(*h));
put_unaligned_be16(type, &h->h_proto);
if (net->flags & (IFF_LOOPBACK | IFF_NOARP)) {
memset(h->h_dest, 0, net->addr_len);
return net->hard_header_len;
}
if (daddr) {
memcpy(h->h_dest, daddr, net->addr_len);
return net->hard_header_len;
}
return -net->hard_header_len;
}
static int fwnet_header_cache(const struct neighbour *neigh,
struct hh_cache *hh, __be16 type)
{
struct net_device *net;
struct fwnet_header *h;
if (type == cpu_to_be16(ETH_P_802_3))
return -1;
net = neigh->dev;
h = (struct fwnet_header *)((u8 *)hh->hh_data + HH_DATA_OFF(sizeof(*h)));
h->h_proto = type;
memcpy(h->h_dest, neigh->ha, net->addr_len);
hh->hh_len = FWNET_HLEN;
return 0;
}
/* Called by Address Resolution module to notify changes in address. */
static void fwnet_header_cache_update(struct hh_cache *hh,
const struct net_device *net, const unsigned char *haddr)
{
memcpy((u8 *)hh->hh_data + HH_DATA_OFF(FWNET_HLEN), haddr, net->addr_len);
}
static int fwnet_header_parse(const struct sk_buff *skb, unsigned char *haddr)
{
memcpy(haddr, skb->dev->dev_addr, FWNET_ALEN);
return FWNET_ALEN;
}
static const struct header_ops fwnet_header_ops = {
.create = fwnet_header_create,
.cache = fwnet_header_cache,
.cache_update = fwnet_header_cache_update,
.parse = fwnet_header_parse,
};
/* FIXME: is this correct for all cases? */
static bool fwnet_frag_overlap(struct fwnet_partial_datagram *pd,
unsigned offset, unsigned len)
{
struct fwnet_fragment_info *fi;
unsigned end = offset + len;
list_for_each_entry(fi, &pd->fi_list, fi_link)
if (offset < fi->offset + fi->len && end > fi->offset)
return true;
return false;
}
/* Assumes that new fragment does not overlap any existing fragments */
static struct fwnet_fragment_info *fwnet_frag_new(
struct fwnet_partial_datagram *pd, unsigned offset, unsigned len)
{
struct fwnet_fragment_info *fi, *fi2, *new;
struct list_head *list;
list = &pd->fi_list;
list_for_each_entry(fi, &pd->fi_list, fi_link) {
if (fi->offset + fi->len == offset) {
/* The new fragment can be tacked on to the end */
/* Did the new fragment plug a hole? */
fi2 = list_entry(fi->fi_link.next,
struct fwnet_fragment_info, fi_link);
if (fi->offset + fi->len == fi2->offset) {
/* glue fragments together */
fi->len += len + fi2->len;
list_del(&fi2->fi_link);
kfree(fi2);
} else {
fi->len += len;
}
return fi;
}
if (offset + len == fi->offset) {
/* The new fragment can be tacked on to the beginning */
/* Did the new fragment plug a hole? */
fi2 = list_entry(fi->fi_link.prev,
struct fwnet_fragment_info, fi_link);
if (fi2->offset + fi2->len == fi->offset) {
/* glue fragments together */
fi2->len += fi->len + len;
list_del(&fi->fi_link);
kfree(fi);
return fi2;
}
fi->offset = offset;
fi->len += len;
return fi;
}
if (offset > fi->offset + fi->len) {
list = &fi->fi_link;
break;
}
if (offset + len < fi->offset) {
list = fi->fi_link.prev;
break;
}
}
new = kmalloc(sizeof(*new), GFP_ATOMIC);
if (!new)
return NULL;
new->offset = offset;
new->len = len;
list_add(&new->fi_link, list);
return new;
}
static struct fwnet_partial_datagram *fwnet_pd_new(struct net_device *net,
struct fwnet_peer *peer, u16 datagram_label, unsigned dg_size,
void *frag_buf, unsigned frag_off, unsigned frag_len)
{
struct fwnet_partial_datagram *new;
struct fwnet_fragment_info *fi;
new = kmalloc(sizeof(*new), GFP_ATOMIC);
if (!new)
goto fail;
INIT_LIST_HEAD(&new->fi_list);
fi = fwnet_frag_new(new, frag_off, frag_len);
if (fi == NULL)
goto fail_w_new;
new->datagram_label = datagram_label;
new->datagram_size = dg_size;
new->skb = dev_alloc_skb(dg_size + LL_RESERVED_SPACE(net));
if (new->skb == NULL)
goto fail_w_fi;
skb_reserve(new->skb, LL_RESERVED_SPACE(net));
new->pbuf = skb_put(new->skb, dg_size);
memcpy(new->pbuf + frag_off, frag_buf, frag_len);
list_add_tail(&new->pd_link, &peer->pd_list);
return new;
fail_w_fi:
kfree(fi);
fail_w_new:
kfree(new);
fail:
return NULL;
}
static struct fwnet_partial_datagram *fwnet_pd_find(struct fwnet_peer *peer,
u16 datagram_label)
{
struct fwnet_partial_datagram *pd;
list_for_each_entry(pd, &peer->pd_list, pd_link)
if (pd->datagram_label == datagram_label)
return pd;
return NULL;
}
static void fwnet_pd_delete(struct fwnet_partial_datagram *old)
{
struct fwnet_fragment_info *fi, *n;
list_for_each_entry_safe(fi, n, &old->fi_list, fi_link)
kfree(fi);
list_del(&old->pd_link);
dev_kfree_skb_any(old->skb);
kfree(old);
}
static bool fwnet_pd_update(struct fwnet_peer *peer,
struct fwnet_partial_datagram *pd, void *frag_buf,
unsigned frag_off, unsigned frag_len)
{
if (fwnet_frag_new(pd, frag_off, frag_len) == NULL)
return false;
memcpy(pd->pbuf + frag_off, frag_buf, frag_len);
/*
* Move list entry to beginning of list so that oldest partial
* datagrams percolate to the end of the list
*/
list_move_tail(&pd->pd_link, &peer->pd_list);
return true;
}
static bool fwnet_pd_is_complete(struct fwnet_partial_datagram *pd)
{
struct fwnet_fragment_info *fi;
fi = list_entry(pd->fi_list.next, struct fwnet_fragment_info, fi_link);
return fi->len == pd->datagram_size;
}
/* caller must hold dev->lock */
static struct fwnet_peer *fwnet_peer_find_by_guid(struct fwnet_device *dev,
u64 guid)
{
struct fwnet_peer *peer;
list_for_each_entry(peer, &dev->peer_list, peer_link)
if (peer->guid == guid)
return peer;
return NULL;
}
/* caller must hold dev->lock */
static struct fwnet_peer *fwnet_peer_find_by_node_id(struct fwnet_device *dev,
int node_id, int generation)
{
struct fwnet_peer *peer;
list_for_each_entry(peer, &dev->peer_list, peer_link)
if (peer->node_id == node_id &&
peer->generation == generation)
return peer;
return NULL;
}
/* See IEEE 1394-2008 table 6-4, table 8-8, table 16-18. */
static unsigned fwnet_max_payload(unsigned max_rec, unsigned speed)
{
max_rec = min(max_rec, speed + 8);
max_rec = clamp(max_rec, 8U, 11U); /* 512...4096 */
return (1 << (max_rec + 1)) - RFC2374_FRAG_HDR_SIZE;
}
static int fwnet_finish_incoming_packet(struct net_device *net,
struct sk_buff *skb, u16 source_node_id,
bool is_broadcast, u16 ether_type)
{
struct fwnet_device *dev;
int status;
__be64 guid;
switch (ether_type) {
case ETH_P_ARP:
case ETH_P_IP:
#if IS_ENABLED(CONFIG_IPV6)
case ETH_P_IPV6:
#endif
break;
default:
goto err;
}
dev = netdev_priv(net);
/* Write metadata, and then pass to the receive level */
skb->dev = net;
skb->ip_summed = CHECKSUM_NONE;
/*
* Parse the encapsulation header. This actually does the job of
* converting to an ethernet-like pseudo frame header.
*/
guid = cpu_to_be64(dev->card->guid);
if (dev_hard_header(skb, net, ether_type,
is_broadcast ? net->broadcast : net->dev_addr,
NULL, skb->len) >= 0) {
struct fwnet_header *eth;
u16 *rawp;
__be16 protocol;
skb_reset_mac_header(skb);
skb_pull(skb, sizeof(*eth));
eth = (struct fwnet_header *)skb_mac_header(skb);
if (fwnet_hwaddr_is_multicast(eth->h_dest)) {
if (memcmp(eth->h_dest, net->broadcast,
net->addr_len) == 0)
skb->pkt_type = PACKET_BROADCAST;
#if 0
else
skb->pkt_type = PACKET_MULTICAST;
#endif
} else {
if (memcmp(eth->h_dest, net->dev_addr, net->addr_len))
skb->pkt_type = PACKET_OTHERHOST;
}
if (ntohs(eth->h_proto) >= ETH_P_802_3_MIN) {
protocol = eth->h_proto;
} else {
rawp = (u16 *)skb->data;
if (*rawp == 0xffff)
protocol = htons(ETH_P_802_3);
else
protocol = htons(ETH_P_802_2);
}
skb->protocol = protocol;
}
status = netif_rx(skb);
if (status == NET_RX_DROP) {
net->stats.rx_errors++;
net->stats.rx_dropped++;
} else {
net->stats.rx_packets++;
net->stats.rx_bytes += skb->len;
}
return 0;
err:
net->stats.rx_errors++;
net->stats.rx_dropped++;
dev_kfree_skb_any(skb);
return -ENOENT;
}
static int fwnet_incoming_packet(struct fwnet_device *dev, __be32 *buf, int len,
int source_node_id, int generation,
bool is_broadcast)
{
struct sk_buff *skb;
struct net_device *net = dev->netdev;
struct rfc2734_header hdr;
unsigned lf;
unsigned long flags;
struct fwnet_peer *peer;
struct fwnet_partial_datagram *pd;
int fg_off;
int dg_size;
u16 datagram_label;
int retval;
u16 ether_type;
hdr.w0 = be32_to_cpu(buf[0]);
lf = fwnet_get_hdr_lf(&hdr);
if (lf == RFC2374_HDR_UNFRAG) {
/*
* An unfragmented datagram has been received by the ieee1394
* bus. Build an skbuff around it so we can pass it to the
* high level network layer.
*/
ether_type = fwnet_get_hdr_ether_type(&hdr);
buf++;
len -= RFC2374_UNFRAG_HDR_SIZE;
skb = dev_alloc_skb(len + LL_RESERVED_SPACE(net));
if (unlikely(!skb)) {
net->stats.rx_dropped++;
return -ENOMEM;
}
skb_reserve(skb, LL_RESERVED_SPACE(net));
memcpy(skb_put(skb, len), buf, len);
return fwnet_finish_incoming_packet(net, skb, source_node_id,
is_broadcast, ether_type);
}
/* A datagram fragment has been received, now the fun begins. */
hdr.w1 = ntohl(buf[1]);
buf += 2;
len -= RFC2374_FRAG_HDR_SIZE;
if (lf == RFC2374_HDR_FIRSTFRAG) {
ether_type = fwnet_get_hdr_ether_type(&hdr);
fg_off = 0;
} else {
ether_type = 0;
fg_off = fwnet_get_hdr_fg_off(&hdr);
}
datagram_label = fwnet_get_hdr_dgl(&hdr);
dg_size = fwnet_get_hdr_dg_size(&hdr); /* ??? + 1 */
spin_lock_irqsave(&dev->lock, flags);
peer = fwnet_peer_find_by_node_id(dev, source_node_id, generation);
if (!peer) {
retval = -ENOENT;
goto fail;
}
pd = fwnet_pd_find(peer, datagram_label);
if (pd == NULL) {
while (peer->pdg_size >= FWNET_MAX_FRAGMENTS) {
/* remove the oldest */
fwnet_pd_delete(list_first_entry(&peer->pd_list,
struct fwnet_partial_datagram, pd_link));
peer->pdg_size--;
}
pd = fwnet_pd_new(net, peer, datagram_label,
dg_size, buf, fg_off, len);
if (pd == NULL) {
retval = -ENOMEM;
goto fail;
}
peer->pdg_size++;
} else {
if (fwnet_frag_overlap(pd, fg_off, len) ||
pd->datagram_size != dg_size) {
/*
* Differing datagram sizes or overlapping fragments,
* discard old datagram and start a new one.
*/
fwnet_pd_delete(pd);
pd = fwnet_pd_new(net, peer, datagram_label,
dg_size, buf, fg_off, len);
if (pd == NULL) {
peer->pdg_size--;
retval = -ENOMEM;
goto fail;
}
} else {
if (!fwnet_pd_update(peer, pd, buf, fg_off, len)) {
/*
* Couldn't save off fragment anyway
* so might as well obliterate the
* datagram now.
*/
fwnet_pd_delete(pd);
peer->pdg_size--;
retval = -ENOMEM;
goto fail;
}
}
} /* new datagram or add to existing one */
if (lf == RFC2374_HDR_FIRSTFRAG)
pd->ether_type = ether_type;
if (fwnet_pd_is_complete(pd)) {
ether_type = pd->ether_type;
peer->pdg_size--;
skb = skb_get(pd->skb);
fwnet_pd_delete(pd);
spin_unlock_irqrestore(&dev->lock, flags);
return fwnet_finish_incoming_packet(net, skb, source_node_id,
false, ether_type);
}
/*
* Datagram is not complete, we're done for the
* moment.
*/
retval = 0;
fail:
spin_unlock_irqrestore(&dev->lock, flags);
return retval;
}
static void fwnet_receive_packet(struct fw_card *card, struct fw_request *r,
int tcode, int destination, int source, int generation,
unsigned long long offset, void *payload, size_t length,
void *callback_data)
{
struct fwnet_device *dev = callback_data;
int rcode;
if (destination == IEEE1394_ALL_NODES) {
kfree(r);
return;
}
if (offset != dev->handler.offset)
rcode = RCODE_ADDRESS_ERROR;
else if (tcode != TCODE_WRITE_BLOCK_REQUEST)
rcode = RCODE_TYPE_ERROR;
else if (fwnet_incoming_packet(dev, payload, length,
source, generation, false) != 0) {
dev_err(&dev->netdev->dev, "incoming packet failure\n");
rcode = RCODE_CONFLICT_ERROR;
} else
rcode = RCODE_COMPLETE;
fw_send_response(card, r, rcode);
}
static void fwnet_receive_broadcast(struct fw_iso_context *context,
u32 cycle, size_t header_length, void *header, void *data)
{
struct fwnet_device *dev;
struct fw_iso_packet packet;
__be16 *hdr_ptr;
__be32 *buf_ptr;
int retval;
u32 length;
u16 source_node_id;
u32 specifier_id;
u32 ver;
unsigned long offset;
unsigned long flags;
dev = data;
hdr_ptr = header;
length = be16_to_cpup(hdr_ptr);
spin_lock_irqsave(&dev->lock, flags);
offset = dev->rcv_buffer_size * dev->broadcast_rcv_next_ptr;
buf_ptr = dev->broadcast_rcv_buffer_ptrs[dev->broadcast_rcv_next_ptr++];
if (dev->broadcast_rcv_next_ptr == dev->num_broadcast_rcv_ptrs)
dev->broadcast_rcv_next_ptr = 0;
spin_unlock_irqrestore(&dev->lock, flags);
specifier_id = (be32_to_cpu(buf_ptr[0]) & 0xffff) << 8
| (be32_to_cpu(buf_ptr[1]) & 0xff000000) >> 24;
ver = be32_to_cpu(buf_ptr[1]) & 0xffffff;
source_node_id = be32_to_cpu(buf_ptr[0]) >> 16;
if (specifier_id == IANA_SPECIFIER_ID &&
(ver == RFC2734_SW_VERSION
#if IS_ENABLED(CONFIG_IPV6)
|| ver == RFC3146_SW_VERSION
#endif
)) {
buf_ptr += 2;
length -= IEEE1394_GASP_HDR_SIZE;
fwnet_incoming_packet(dev, buf_ptr, length, source_node_id,
context->card->generation, true);
}
packet.payload_length = dev->rcv_buffer_size;
packet.interrupt = 1;
packet.skip = 0;
packet.tag = 3;
packet.sy = 0;
packet.header_length = IEEE1394_GASP_HDR_SIZE;
spin_lock_irqsave(&dev->lock, flags);
retval = fw_iso_context_queue(dev->broadcast_rcv_context, &packet,
&dev->broadcast_rcv_buffer, offset);
spin_unlock_irqrestore(&dev->lock, flags);
if (retval >= 0)
fw_iso_context_queue_flush(dev->broadcast_rcv_context);
else
dev_err(&dev->netdev->dev, "requeue failed\n");
}
static struct kmem_cache *fwnet_packet_task_cache;
static void fwnet_free_ptask(struct fwnet_packet_task *ptask)
{
dev_kfree_skb_any(ptask->skb);
kmem_cache_free(fwnet_packet_task_cache, ptask);
}
/* Caller must hold dev->lock. */
static void dec_queued_datagrams(struct fwnet_device *dev)
{
if (--dev->queued_datagrams == FWNET_MIN_QUEUED_DATAGRAMS)
netif_wake_queue(dev->netdev);
}
static int fwnet_send_packet(struct fwnet_packet_task *ptask);
static void fwnet_transmit_packet_done(struct fwnet_packet_task *ptask)
{
struct fwnet_device *dev = ptask->dev;
struct sk_buff *skb = ptask->skb;
unsigned long flags;
bool free;
spin_lock_irqsave(&dev->lock, flags);
ptask->outstanding_pkts--;
/* Check whether we or the networking TX soft-IRQ is last user. */
free = (ptask->outstanding_pkts == 0 && ptask->enqueued);
if (free)
dec_queued_datagrams(dev);
if (ptask->outstanding_pkts == 0) {
dev->netdev->stats.tx_packets++;
dev->netdev->stats.tx_bytes += skb->len;
}
spin_unlock_irqrestore(&dev->lock, flags);
if (ptask->outstanding_pkts > 0) {
u16 dg_size;
u16 fg_off;
u16 datagram_label;
u16 lf;
/* Update the ptask to point to the next fragment and send it */
lf = fwnet_get_hdr_lf(&ptask->hdr);
switch (lf) {
case RFC2374_HDR_LASTFRAG:
case RFC2374_HDR_UNFRAG:
default:
dev_err(&dev->netdev->dev,
"outstanding packet %x lf %x, header %x,%x\n",
ptask->outstanding_pkts, lf, ptask->hdr.w0,
ptask->hdr.w1);
BUG();
case RFC2374_HDR_FIRSTFRAG:
/* Set frag type here for future interior fragments */
dg_size = fwnet_get_hdr_dg_size(&ptask->hdr);
fg_off = ptask->max_payload - RFC2374_FRAG_HDR_SIZE;
datagram_label = fwnet_get_hdr_dgl(&ptask->hdr);
break;
case RFC2374_HDR_INTFRAG:
dg_size = fwnet_get_hdr_dg_size(&ptask->hdr);
fg_off = fwnet_get_hdr_fg_off(&ptask->hdr)
+ ptask->max_payload - RFC2374_FRAG_HDR_SIZE;
datagram_label = fwnet_get_hdr_dgl(&ptask->hdr);
break;
}
if (ptask->dest_node == IEEE1394_ALL_NODES) {
skb_pull(skb,
ptask->max_payload + IEEE1394_GASP_HDR_SIZE);
} else {
skb_pull(skb, ptask->max_payload);
}
if (ptask->outstanding_pkts > 1) {
fwnet_make_sf_hdr(&ptask->hdr, RFC2374_HDR_INTFRAG,
dg_size, fg_off, datagram_label);
} else {
fwnet_make_sf_hdr(&ptask->hdr, RFC2374_HDR_LASTFRAG,
dg_size, fg_off, datagram_label);
ptask->max_payload = skb->len + RFC2374_FRAG_HDR_SIZE;
}
fwnet_send_packet(ptask);
}
if (free)
fwnet_free_ptask(ptask);
}
static void fwnet_transmit_packet_failed(struct fwnet_packet_task *ptask)
{
struct fwnet_device *dev = ptask->dev;
unsigned long flags;
bool free;
spin_lock_irqsave(&dev->lock, flags);
/* One fragment failed; don't try to send remaining fragments. */
ptask->outstanding_pkts = 0;
/* Check whether we or the networking TX soft-IRQ is last user. */
free = ptask->enqueued;
if (free)
dec_queued_datagrams(dev);
dev->netdev->stats.tx_dropped++;
dev->netdev->stats.tx_errors++;
spin_unlock_irqrestore(&dev->lock, flags);
if (free)
fwnet_free_ptask(ptask);
}
static void fwnet_write_complete(struct fw_card *card, int rcode,
void *payload, size_t length, void *data)
{
struct fwnet_packet_task *ptask = data;
static unsigned long j;
static int last_rcode, errors_skipped;
if (rcode == RCODE_COMPLETE) {
fwnet_transmit_packet_done(ptask);
} else {
if (printk_timed_ratelimit(&j, 1000) || rcode != last_rcode) {
dev_err(&ptask->dev->netdev->dev,
"fwnet_write_complete failed: %x (skipped %d)\n",
rcode, errors_skipped);
errors_skipped = 0;
last_rcode = rcode;
} else {
errors_skipped++;
}
fwnet_transmit_packet_failed(ptask);
}
}
static int fwnet_send_packet(struct fwnet_packet_task *ptask)
{
struct fwnet_device *dev;
unsigned tx_len;
struct rfc2734_header *bufhdr;
unsigned long flags;
bool free;
dev = ptask->dev;
tx_len = ptask->max_payload;
switch (fwnet_get_hdr_lf(&ptask->hdr)) {
case RFC2374_HDR_UNFRAG:
bufhdr = (struct rfc2734_header *)
skb_push(ptask->skb, RFC2374_UNFRAG_HDR_SIZE);
put_unaligned_be32(ptask->hdr.w0, &bufhdr->w0);
break;
case RFC2374_HDR_FIRSTFRAG:
case RFC2374_HDR_INTFRAG:
case RFC2374_HDR_LASTFRAG:
bufhdr = (struct rfc2734_header *)
skb_push(ptask->skb, RFC2374_FRAG_HDR_SIZE);
put_unaligned_be32(ptask->hdr.w0, &bufhdr->w0);
put_unaligned_be32(ptask->hdr.w1, &bufhdr->w1);
break;
default:
BUG();
}
if (ptask->dest_node == IEEE1394_ALL_NODES) {
u8 *p;
int generation;
int node_id;
unsigned int sw_version;
/* ptask->generation may not have been set yet */
generation = dev->card->generation;
smp_rmb();
node_id = dev->card->node_id;
switch (ptask->skb->protocol) {
default:
sw_version = RFC2734_SW_VERSION;
break;
#if IS_ENABLED(CONFIG_IPV6)
case htons(ETH_P_IPV6):
sw_version = RFC3146_SW_VERSION;
#endif
}
p = skb_push(ptask->skb, IEEE1394_GASP_HDR_SIZE);
put_unaligned_be32(node_id << 16 | IANA_SPECIFIER_ID >> 8, p);
put_unaligned_be32((IANA_SPECIFIER_ID & 0xff) << 24
| sw_version, &p[4]);
/* We should not transmit if broadcast_channel.valid == 0. */
fw_send_request(dev->card, &ptask->transaction,
TCODE_STREAM_DATA,
fw_stream_packet_destination_id(3,
IEEE1394_BROADCAST_CHANNEL, 0),
generation, SCODE_100, 0ULL, ptask->skb->data,
tx_len + 8, fwnet_write_complete, ptask);
spin_lock_irqsave(&dev->lock, flags);
/* If the AT tasklet already ran, we may be last user. */
free = (ptask->outstanding_pkts == 0 && !ptask->enqueued);
if (!free)
ptask->enqueued = true;
else
dec_queued_datagrams(dev);
spin_unlock_irqrestore(&dev->lock, flags);
goto out;
}
fw_send_request(dev->card, &ptask->transaction,
TCODE_WRITE_BLOCK_REQUEST, ptask->dest_node,
ptask->generation, ptask->speed, ptask->fifo_addr,
ptask->skb->data, tx_len, fwnet_write_complete, ptask);
spin_lock_irqsave(&dev->lock, flags);
/* If the AT tasklet already ran, we may be last user. */
free = (ptask->outstanding_pkts == 0 && !ptask->enqueued);
if (!free)
ptask->enqueued = true;
else
dec_queued_datagrams(dev);
spin_unlock_irqrestore(&dev->lock, flags);
dev->netdev->trans_start = jiffies;
out:
if (free)
fwnet_free_ptask(ptask);
return 0;
}
static void fwnet_fifo_stop(struct fwnet_device *dev)
{
if (dev->local_fifo == FWNET_NO_FIFO_ADDR)
return;
fw_core_remove_address_handler(&dev->handler);
dev->local_fifo = FWNET_NO_FIFO_ADDR;
}
static int fwnet_fifo_start(struct fwnet_device *dev)
{
int retval;
if (dev->local_fifo != FWNET_NO_FIFO_ADDR)
return 0;
dev->handler.length = 4096;
dev->handler.address_callback = fwnet_receive_packet;
dev->handler.callback_data = dev;
retval = fw_core_add_address_handler(&dev->handler,
&fw_high_memory_region);
if (retval < 0)
return retval;
dev->local_fifo = dev->handler.offset;
return 0;
}
static void __fwnet_broadcast_stop(struct fwnet_device *dev)
{
unsigned u;
if (dev->broadcast_state != FWNET_BROADCAST_ERROR) {
for (u = 0; u < FWNET_ISO_PAGE_COUNT; u++)
kunmap(dev->broadcast_rcv_buffer.pages[u]);
fw_iso_buffer_destroy(&dev->broadcast_rcv_buffer, dev->card);
}
if (dev->broadcast_rcv_context) {
fw_iso_context_destroy(dev->broadcast_rcv_context);
dev->broadcast_rcv_context = NULL;
}
kfree(dev->broadcast_rcv_buffer_ptrs);
dev->broadcast_rcv_buffer_ptrs = NULL;
dev->broadcast_state = FWNET_BROADCAST_ERROR;
}
static void fwnet_broadcast_stop(struct fwnet_device *dev)
{
if (dev->broadcast_state == FWNET_BROADCAST_ERROR)
return;
fw_iso_context_stop(dev->broadcast_rcv_context);
__fwnet_broadcast_stop(dev);
}
static int fwnet_broadcast_start(struct fwnet_device *dev)
{
struct fw_iso_context *context;
int retval;
unsigned num_packets;
unsigned max_receive;
struct fw_iso_packet packet;
unsigned long offset;
void **ptrptr;
unsigned u;
if (dev->broadcast_state != FWNET_BROADCAST_ERROR)
return 0;
max_receive = 1U << (dev->card->max_receive + 1);
num_packets = (FWNET_ISO_PAGE_COUNT * PAGE_SIZE) / max_receive;
ptrptr = kmalloc(sizeof(void *) * num_packets, GFP_KERNEL);
if (!ptrptr) {
retval = -ENOMEM;
goto failed;
}
dev->broadcast_rcv_buffer_ptrs = ptrptr;
context = fw_iso_context_create(dev->card, FW_ISO_CONTEXT_RECEIVE,
IEEE1394_BROADCAST_CHANNEL,
dev->card->link_speed, 8,
fwnet_receive_broadcast, dev);
if (IS_ERR(context)) {
retval = PTR_ERR(context);
goto failed;
}
retval = fw_iso_buffer_init(&dev->broadcast_rcv_buffer, dev->card,
FWNET_ISO_PAGE_COUNT, DMA_FROM_DEVICE);
if (retval < 0)
goto failed;
dev->broadcast_state = FWNET_BROADCAST_STOPPED;
for (u = 0; u < FWNET_ISO_PAGE_COUNT; u++) {
void *ptr;
unsigned v;
ptr = kmap(dev->broadcast_rcv_buffer.pages[u]);
for (v = 0; v < num_packets / FWNET_ISO_PAGE_COUNT; v++)
*ptrptr++ = (void *) ((char *)ptr + v * max_receive);
}
dev->broadcast_rcv_context = context;
packet.payload_length = max_receive;
packet.interrupt = 1;
packet.skip = 0;
packet.tag = 3;
packet.sy = 0;
packet.header_length = IEEE1394_GASP_HDR_SIZE;
offset = 0;
for (u = 0; u < num_packets; u++) {
retval = fw_iso_context_queue(context, &packet,
&dev->broadcast_rcv_buffer, offset);
if (retval < 0)
goto failed;
offset += max_receive;
}
dev->num_broadcast_rcv_ptrs = num_packets;
dev->rcv_buffer_size = max_receive;
dev->broadcast_rcv_next_ptr = 0U;
retval = fw_iso_context_start(context, -1, 0,
FW_ISO_CONTEXT_MATCH_ALL_TAGS); /* ??? sync */
if (retval < 0)
goto failed;
/* FIXME: adjust it according to the min. speed of all known peers? */
dev->broadcast_xmt_max_payload = IEEE1394_MAX_PAYLOAD_S100
- IEEE1394_GASP_HDR_SIZE - RFC2374_UNFRAG_HDR_SIZE;
dev->broadcast_state = FWNET_BROADCAST_RUNNING;
return 0;
failed:
__fwnet_broadcast_stop(dev);
return retval;
}
static void set_carrier_state(struct fwnet_device *dev)
{
if (dev->peer_count > 1)
netif_carrier_on(dev->netdev);
else
netif_carrier_off(dev->netdev);
}
/* ifup */
static int fwnet_open(struct net_device *net)
{
struct fwnet_device *dev = netdev_priv(net);
int ret;
ret = fwnet_broadcast_start(dev);
if (ret)
return ret;
netif_start_queue(net);
spin_lock_irq(&dev->lock);
set_carrier_state(dev);
spin_unlock_irq(&dev->lock);
return 0;
}
/* ifdown */
static int fwnet_stop(struct net_device *net)
{
struct fwnet_device *dev = netdev_priv(net);
netif_stop_queue(net);
fwnet_broadcast_stop(dev);
return 0;
}
static netdev_tx_t fwnet_tx(struct sk_buff *skb, struct net_device *net)
{
struct fwnet_header hdr_buf;
struct fwnet_device *dev = netdev_priv(net);
__be16 proto;
u16 dest_node;
unsigned max_payload;
u16 dg_size;
u16 *datagram_label_ptr;
struct fwnet_packet_task *ptask;
struct fwnet_peer *peer;
unsigned long flags;
spin_lock_irqsave(&dev->lock, flags);
/* Can this happen? */
if (netif_queue_stopped(dev->netdev)) {
spin_unlock_irqrestore(&dev->lock, flags);
return NETDEV_TX_BUSY;
}
ptask = kmem_cache_alloc(fwnet_packet_task_cache, GFP_ATOMIC);
if (ptask == NULL)
goto fail;
skb = skb_share_check(skb, GFP_ATOMIC);
if (!skb)
goto fail;
/*
* Make a copy of the driver-specific header.
* We might need to rebuild the header on tx failure.
*/
memcpy(&hdr_buf, skb->data, sizeof(hdr_buf));
proto = hdr_buf.h_proto;
switch (proto) {
case htons(ETH_P_ARP):
case htons(ETH_P_IP):
#if IS_ENABLED(CONFIG_IPV6)
case htons(ETH_P_IPV6):
#endif
break;
default:
goto fail;
}
skb_pull(skb, sizeof(hdr_buf));
dg_size = skb->len;
/*
* Set the transmission type for the packet. ARP packets and IP
* broadcast packets are sent via GASP.
*/
if (fwnet_hwaddr_is_multicast(hdr_buf.h_dest)) {
max_payload = dev->broadcast_xmt_max_payload;
datagram_label_ptr = &dev->broadcast_xmt_datagramlabel;
ptask->fifo_addr = FWNET_NO_FIFO_ADDR;
ptask->generation = 0;
ptask->dest_node = IEEE1394_ALL_NODES;
ptask->speed = SCODE_100;
} else {
union fwnet_hwaddr *ha = (union fwnet_hwaddr *)hdr_buf.h_dest;
__be64 guid = get_unaligned(&ha->uc.uniq_id);
u8 generation;
peer = fwnet_peer_find_by_guid(dev, be64_to_cpu(guid));
if (!peer)
goto fail;
generation = peer->generation;
dest_node = peer->node_id;
max_payload = peer->max_payload;
datagram_label_ptr = &peer->datagram_label;
ptask->fifo_addr = fwnet_hwaddr_fifo(ha);
ptask->generation = generation;
ptask->dest_node = dest_node;
ptask->speed = peer->speed;
}
ptask->hdr.w0 = 0;
ptask->hdr.w1 = 0;
ptask->skb = skb;
ptask->dev = dev;
/* Does it all fit in one packet? */
if (dg_size <= max_payload) {
fwnet_make_uf_hdr(&ptask->hdr, ntohs(proto));
ptask->outstanding_pkts = 1;
max_payload = dg_size + RFC2374_UNFRAG_HDR_SIZE;
} else {
u16 datagram_label;
max_payload -= RFC2374_FRAG_OVERHEAD;
datagram_label = (*datagram_label_ptr)++;
fwnet_make_ff_hdr(&ptask->hdr, ntohs(proto), dg_size,
datagram_label);
ptask->outstanding_pkts = DIV_ROUND_UP(dg_size, max_payload);
max_payload += RFC2374_FRAG_HDR_SIZE;
}
if (++dev->queued_datagrams == FWNET_MAX_QUEUED_DATAGRAMS)
netif_stop_queue(dev->netdev);
spin_unlock_irqrestore(&dev->lock, flags);
ptask->max_payload = max_payload;
ptask->enqueued = 0;
fwnet_send_packet(ptask);
return NETDEV_TX_OK;
fail:
spin_unlock_irqrestore(&dev->lock, flags);
if (ptask)
kmem_cache_free(fwnet_packet_task_cache, ptask);
if (skb != NULL)
dev_kfree_skb(skb);
net->stats.tx_dropped++;
net->stats.tx_errors++;
/*
* FIXME: According to a patch from 2003-02-26, "returning non-zero
* causes serious problems" here, allegedly. Before that patch,
* -ERRNO was returned which is not appropriate under Linux 2.6.
* Perhaps more needs to be done? Stop the queue in serious
* conditions and restart it elsewhere?
*/
return NETDEV_TX_OK;
}
static int fwnet_change_mtu(struct net_device *net, int new_mtu)
{
if (new_mtu < 68)
return -EINVAL;
net->mtu = new_mtu;
return 0;
}
static const struct ethtool_ops fwnet_ethtool_ops = {
.get_link = ethtool_op_get_link,
};
static const struct net_device_ops fwnet_netdev_ops = {
.ndo_open = fwnet_open,
.ndo_stop = fwnet_stop,
.ndo_start_xmit = fwnet_tx,
.ndo_change_mtu = fwnet_change_mtu,
};
static void fwnet_init_dev(struct net_device *net)
{
net->header_ops = &fwnet_header_ops;
net->netdev_ops = &fwnet_netdev_ops;
net->watchdog_timeo = 2 * HZ;
net->flags = IFF_BROADCAST | IFF_MULTICAST;
net->features = NETIF_F_HIGHDMA;
net->addr_len = FWNET_ALEN;
net->hard_header_len = FWNET_HLEN;
net->type = ARPHRD_IEEE1394;
net->tx_queue_len = FWNET_TX_QUEUE_LEN;
net->ethtool_ops = &fwnet_ethtool_ops;
}
/* caller must hold fwnet_device_mutex */
static struct fwnet_device *fwnet_dev_find(struct fw_card *card)
{
struct fwnet_device *dev;
list_for_each_entry(dev, &fwnet_device_list, dev_link)
if (dev->card == card)
return dev;
return NULL;
}
static int fwnet_add_peer(struct fwnet_device *dev,
struct fw_unit *unit, struct fw_device *device)
{
struct fwnet_peer *peer;
peer = kmalloc(sizeof(*peer), GFP_KERNEL);
if (!peer)
return -ENOMEM;
dev_set_drvdata(&unit->device, peer);
peer->dev = dev;
peer->guid = (u64)device->config_rom[3] << 32 | device->config_rom[4];
INIT_LIST_HEAD(&peer->pd_list);
peer->pdg_size = 0;
peer->datagram_label = 0;
peer->speed = device->max_speed;
peer->max_payload = fwnet_max_payload(device->max_rec, peer->speed);
peer->generation = device->generation;
smp_rmb();
peer->node_id = device->node_id;
spin_lock_irq(&dev->lock);
list_add_tail(&peer->peer_link, &dev->peer_list);
dev->peer_count++;
set_carrier_state(dev);
spin_unlock_irq(&dev->lock);
return 0;
}
static int fwnet_probe(struct fw_unit *unit,
const struct ieee1394_device_id *id)
{
struct fw_device *device = fw_parent_device(unit);
struct fw_card *card = device->card;
struct net_device *net;
bool allocated_netdev = false;
struct fwnet_device *dev;
unsigned max_mtu;
int ret;
union fwnet_hwaddr *ha;
mutex_lock(&fwnet_device_mutex);
dev = fwnet_dev_find(card);
if (dev) {
net = dev->netdev;
goto have_dev;
}
net = alloc_netdev(sizeof(*dev), "firewire%d", NET_NAME_UNKNOWN,
fwnet_init_dev);
if (net == NULL) {
mutex_unlock(&fwnet_device_mutex);
return -ENOMEM;
}
allocated_netdev = true;
SET_NETDEV_DEV(net, card->device);
dev = netdev_priv(net);
spin_lock_init(&dev->lock);
dev->broadcast_state = FWNET_BROADCAST_ERROR;
dev->broadcast_rcv_context = NULL;
dev->broadcast_xmt_max_payload = 0;
dev->broadcast_xmt_datagramlabel = 0;
dev->local_fifo = FWNET_NO_FIFO_ADDR;
dev->queued_datagrams = 0;
INIT_LIST_HEAD(&dev->peer_list);
dev->card = card;
dev->netdev = net;
ret = fwnet_fifo_start(dev);
if (ret < 0)
goto out;
dev->local_fifo = dev->handler.offset;
/*
* Use the RFC 2734 default 1500 octets or the maximum payload
* as initial MTU
*/
max_mtu = (1 << (card->max_receive + 1))
- sizeof(struct rfc2734_header) - IEEE1394_GASP_HDR_SIZE;
net->mtu = min(1500U, max_mtu);
/* Set our hardware address while we're at it */
ha = (union fwnet_hwaddr *)net->dev_addr;
put_unaligned_be64(card->guid, &ha->uc.uniq_id);
ha->uc.max_rec = dev->card->max_receive;
ha->uc.sspd = dev->card->link_speed;
put_unaligned_be16(dev->local_fifo >> 32, &ha->uc.fifo_hi);
put_unaligned_be32(dev->local_fifo & 0xffffffff, &ha->uc.fifo_lo);
memset(net->broadcast, -1, net->addr_len);
ret = register_netdev(net);
if (ret)
goto out;
list_add_tail(&dev->dev_link, &fwnet_device_list);
dev_notice(&net->dev, "IP over IEEE 1394 on card %s\n",
dev_name(card->device));
have_dev:
ret = fwnet_add_peer(dev, unit, device);
if (ret && allocated_netdev) {
unregister_netdev(net);
list_del(&dev->dev_link);
out:
fwnet_fifo_stop(dev);
free_netdev(net);
}
mutex_unlock(&fwnet_device_mutex);
return ret;
}
/*
* FIXME abort partially sent fragmented datagrams,
* discard partially received fragmented datagrams
*/
static void fwnet_update(struct fw_unit *unit)
{
struct fw_device *device = fw_parent_device(unit);
struct fwnet_peer *peer = dev_get_drvdata(&unit->device);
int generation;
generation = device->generation;
spin_lock_irq(&peer->dev->lock);
peer->node_id = device->node_id;
peer->generation = generation;
spin_unlock_irq(&peer->dev->lock);
}
static void fwnet_remove_peer(struct fwnet_peer *peer, struct fwnet_device *dev)
{
struct fwnet_partial_datagram *pd, *pd_next;
spin_lock_irq(&dev->lock);
list_del(&peer->peer_link);
dev->peer_count--;
set_carrier_state(dev);
spin_unlock_irq(&dev->lock);
list_for_each_entry_safe(pd, pd_next, &peer->pd_list, pd_link)
fwnet_pd_delete(pd);
kfree(peer);
}
static void fwnet_remove(struct fw_unit *unit)
{
struct fwnet_peer *peer = dev_get_drvdata(&unit->device);
struct fwnet_device *dev = peer->dev;
struct net_device *net;
int i;
mutex_lock(&fwnet_device_mutex);
net = dev->netdev;
fwnet_remove_peer(peer, dev);
if (list_empty(&dev->peer_list)) {
unregister_netdev(net);
fwnet_fifo_stop(dev);
for (i = 0; dev->queued_datagrams && i < 5; i++)
ssleep(1);
WARN_ON(dev->queued_datagrams);
list_del(&dev->dev_link);
free_netdev(net);
}
mutex_unlock(&fwnet_device_mutex);
}
static const struct ieee1394_device_id fwnet_id_table[] = {
{
.match_flags = IEEE1394_MATCH_SPECIFIER_ID |
IEEE1394_MATCH_VERSION,
.specifier_id = IANA_SPECIFIER_ID,
.version = RFC2734_SW_VERSION,
},
#if IS_ENABLED(CONFIG_IPV6)
{
.match_flags = IEEE1394_MATCH_SPECIFIER_ID |
IEEE1394_MATCH_VERSION,
.specifier_id = IANA_SPECIFIER_ID,
.version = RFC3146_SW_VERSION,
},
#endif
{ }
};
static struct fw_driver fwnet_driver = {
.driver = {
.owner = THIS_MODULE,
.name = KBUILD_MODNAME,
.bus = &fw_bus_type,
},
.probe = fwnet_probe,
.update = fwnet_update,
.remove = fwnet_remove,
.id_table = fwnet_id_table,
};
static const u32 rfc2374_unit_directory_data[] = {
0x00040000, /* directory_length */
0x1200005e, /* unit_specifier_id: IANA */
0x81000003, /* textual descriptor offset */
0x13000001, /* unit_sw_version: RFC 2734 */
0x81000005, /* textual descriptor offset */
0x00030000, /* descriptor_length */
0x00000000, /* text */
0x00000000, /* minimal ASCII, en */
0x49414e41, /* I A N A */
0x00030000, /* descriptor_length */
0x00000000, /* text */
0x00000000, /* minimal ASCII, en */
0x49507634, /* I P v 4 */
};
static struct fw_descriptor rfc2374_unit_directory = {
.length = ARRAY_SIZE(rfc2374_unit_directory_data),
.key = (CSR_DIRECTORY | CSR_UNIT) << 24,
.data = rfc2374_unit_directory_data
};
#if IS_ENABLED(CONFIG_IPV6)
static const u32 rfc3146_unit_directory_data[] = {
0x00040000, /* directory_length */
0x1200005e, /* unit_specifier_id: IANA */
0x81000003, /* textual descriptor offset */
0x13000002, /* unit_sw_version: RFC 3146 */
0x81000005, /* textual descriptor offset */
0x00030000, /* descriptor_length */
0x00000000, /* text */
0x00000000, /* minimal ASCII, en */
0x49414e41, /* I A N A */
0x00030000, /* descriptor_length */
0x00000000, /* text */
0x00000000, /* minimal ASCII, en */
0x49507636, /* I P v 6 */
};
static struct fw_descriptor rfc3146_unit_directory = {
.length = ARRAY_SIZE(rfc3146_unit_directory_data),
.key = (CSR_DIRECTORY | CSR_UNIT) << 24,
.data = rfc3146_unit_directory_data
};
#endif
static int __init fwnet_init(void)
{
int err;
err = fw_core_add_descriptor(&rfc2374_unit_directory);
if (err)
return err;
#if IS_ENABLED(CONFIG_IPV6)
err = fw_core_add_descriptor(&rfc3146_unit_directory);
if (err)
goto out;
#endif
fwnet_packet_task_cache = kmem_cache_create("packet_task",
sizeof(struct fwnet_packet_task), 0, 0, NULL);
if (!fwnet_packet_task_cache) {
err = -ENOMEM;
goto out2;
}
err = driver_register(&fwnet_driver.driver);
if (!err)
return 0;
kmem_cache_destroy(fwnet_packet_task_cache);
out2:
#if IS_ENABLED(CONFIG_IPV6)
fw_core_remove_descriptor(&rfc3146_unit_directory);
out:
#endif
fw_core_remove_descriptor(&rfc2374_unit_directory);
return err;
}
module_init(fwnet_init);
static void __exit fwnet_cleanup(void)
{
driver_unregister(&fwnet_driver.driver);
kmem_cache_destroy(fwnet_packet_task_cache);
#if IS_ENABLED(CONFIG_IPV6)
fw_core_remove_descriptor(&rfc3146_unit_directory);
#endif
fw_core_remove_descriptor(&rfc2374_unit_directory);
}
module_exit(fwnet_cleanup);
MODULE_AUTHOR("Jay Fenlason <fenlason@redhat.com>");
MODULE_DESCRIPTION("IP over IEEE1394 as per RFC 2734/3146");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(ieee1394, fwnet_id_table);
| gpl-2.0 |
bmsitech/linux-imx6 | arch/arm/mach-pxa/palmt5.c | 2099 | 5662 | /*
* Hardware definitions for Palm Tungsten|T5
*
* Author: Marek Vasut <marek.vasut@gmail.com>
*
* Based on work of:
* Ales Snuparek <snuparek@atlas.cz>
* Justin Kendrick <twilightsentry@gmail.com>
* RichardT5 <richard_t5@users.sourceforge.net>
*
* 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.
*
* (find more info at www.hackndev.com)
*
*/
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/irq.h>
#include <linux/gpio_keys.h>
#include <linux/input.h>
#include <linux/memblock.h>
#include <linux/pda_power.h>
#include <linux/pwm_backlight.h>
#include <linux/gpio.h>
#include <linux/wm97xx.h>
#include <linux/power_supply.h>
#include <linux/usb/gpio_vbus.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <mach/pxa27x.h>
#include <mach/audio.h>
#include <mach/palmt5.h>
#include <linux/platform_data/mmc-pxamci.h>
#include <linux/platform_data/video-pxafb.h>
#include <linux/platform_data/irda-pxaficp.h>
#include <linux/platform_data/keypad-pxa27x.h>
#include <mach/udc.h>
#include <linux/platform_data/asoc-palm27x.h>
#include <mach/palm27x.h>
#include "generic.h"
#include "devices.h"
/******************************************************************************
* Pin configuration
******************************************************************************/
static unsigned long palmt5_pin_config[] __initdata = {
/* MMC */
GPIO32_MMC_CLK,
GPIO92_MMC_DAT_0,
GPIO109_MMC_DAT_1,
GPIO110_MMC_DAT_2,
GPIO111_MMC_DAT_3,
GPIO112_MMC_CMD,
GPIO14_GPIO, /* SD detect */
GPIO114_GPIO, /* SD power */
GPIO115_GPIO, /* SD r/o switch */
/* AC97 */
GPIO28_AC97_BITCLK,
GPIO29_AC97_SDATA_IN_0,
GPIO30_AC97_SDATA_OUT,
GPIO31_AC97_SYNC,
GPIO89_AC97_SYSCLK,
GPIO95_AC97_nRESET,
/* IrDA */
GPIO40_GPIO, /* ir disable */
GPIO46_FICP_RXD,
GPIO47_FICP_TXD,
/* USB */
GPIO15_GPIO, /* usb detect */
GPIO93_GPIO, /* usb power */
/* MATRIX KEYPAD */
GPIO100_KP_MKIN_0 | WAKEUP_ON_LEVEL_HIGH,
GPIO101_KP_MKIN_1 | WAKEUP_ON_LEVEL_HIGH,
GPIO102_KP_MKIN_2 | WAKEUP_ON_LEVEL_HIGH,
GPIO97_KP_MKIN_3 | WAKEUP_ON_LEVEL_HIGH,
GPIO103_KP_MKOUT_0,
GPIO104_KP_MKOUT_1,
GPIO105_KP_MKOUT_2,
/* LCD */
GPIOxx_LCD_TFT_16BPP,
/* PWM */
GPIO16_PWM0_OUT,
/* FFUART */
GPIO34_FFUART_RXD,
GPIO39_FFUART_TXD,
/* MISC */
GPIO10_GPIO, /* hotsync button */
GPIO90_GPIO, /* power detect */
GPIO107_GPIO, /* earphone detect */
};
/******************************************************************************
* GPIO keyboard
******************************************************************************/
#if defined(CONFIG_KEYBOARD_PXA27x) || defined(CONFIG_KEYBOARD_PXA27x_MODULE)
static unsigned int palmt5_matrix_keys[] = {
KEY(0, 0, KEY_POWER),
KEY(0, 1, KEY_F1),
KEY(0, 2, KEY_ENTER),
KEY(1, 0, KEY_F2),
KEY(1, 1, KEY_F3),
KEY(1, 2, KEY_F4),
KEY(2, 0, KEY_UP),
KEY(2, 2, KEY_DOWN),
KEY(3, 0, KEY_RIGHT),
KEY(3, 2, KEY_LEFT),
};
static struct pxa27x_keypad_platform_data palmt5_keypad_platform_data = {
.matrix_key_rows = 4,
.matrix_key_cols = 3,
.matrix_key_map = palmt5_matrix_keys,
.matrix_key_map_size = ARRAY_SIZE(palmt5_matrix_keys),
.debounce_interval = 30,
};
static void __init palmt5_kpc_init(void)
{
pxa_set_keypad_info(&palmt5_keypad_platform_data);
}
#else
static inline void palmt5_kpc_init(void) {}
#endif
/******************************************************************************
* GPIO keys
******************************************************************************/
#if defined(CONFIG_KEYBOARD_GPIO) || defined(CONFIG_KEYBOARD_GPIO_MODULE)
static struct gpio_keys_button palmt5_pxa_buttons[] = {
{KEY_F8, GPIO_NR_PALMT5_HOTSYNC_BUTTON_N, 1, "HotSync Button" },
};
static struct gpio_keys_platform_data palmt5_pxa_keys_data = {
.buttons = palmt5_pxa_buttons,
.nbuttons = ARRAY_SIZE(palmt5_pxa_buttons),
};
static struct platform_device palmt5_pxa_keys = {
.name = "gpio-keys",
.id = -1,
.dev = {
.platform_data = &palmt5_pxa_keys_data,
},
};
static void __init palmt5_keys_init(void)
{
platform_device_register(&palmt5_pxa_keys);
}
#else
static inline void palmt5_keys_init(void) {}
#endif
/******************************************************************************
* Machine init
******************************************************************************/
static void __init palmt5_reserve(void)
{
memblock_reserve(0xa0200000, 0x1000);
}
static void __init palmt5_init(void)
{
pxa2xx_mfp_config(ARRAY_AND_SIZE(palmt5_pin_config));
pxa_set_ffuart_info(NULL);
pxa_set_btuart_info(NULL);
pxa_set_stuart_info(NULL);
palm27x_mmc_init(GPIO_NR_PALMT5_SD_DETECT_N, GPIO_NR_PALMT5_SD_READONLY,
GPIO_NR_PALMT5_SD_POWER, 0);
palm27x_pm_init(PALMT5_STR_BASE);
palm27x_lcd_init(-1, &palm_320x480_lcd_mode);
palm27x_udc_init(GPIO_NR_PALMT5_USB_DETECT_N,
GPIO_NR_PALMT5_USB_PULLUP, 1);
palm27x_irda_init(GPIO_NR_PALMT5_IR_DISABLE);
palm27x_ac97_init(PALMT5_BAT_MIN_VOLTAGE, PALMT5_BAT_MAX_VOLTAGE,
GPIO_NR_PALMT5_EARPHONE_DETECT, 95);
palm27x_pwm_init(GPIO_NR_PALMT5_BL_POWER, GPIO_NR_PALMT5_LCD_POWER);
palm27x_power_init(GPIO_NR_PALMT5_POWER_DETECT, -1);
palm27x_pmic_init();
palmt5_kpc_init();
palmt5_keys_init();
}
MACHINE_START(PALMT5, "Palm Tungsten|T5")
.atag_offset = 0x100,
.map_io = pxa27x_map_io,
.reserve = palmt5_reserve,
.nr_irqs = PXA_NR_IRQS,
.init_irq = pxa27x_init_irq,
.handle_irq = pxa27x_handle_irq,
.init_time = pxa_timer_init,
.init_machine = palmt5_init,
.restart = pxa_restart,
MACHINE_END
| gpl-2.0 |
TheTypoMaster/yotrino-linux-kernel | arch/arm/mach-pxa/em-x270.c | 2099 | 30548 | /*
* Support for CompuLab EM-X270 platform
*
* Copyright (C) 2007, 2008 CompuLab, Ltd.
* Author: Mike Rapoport <mike@compulab.co.il>
*
* 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/irq.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/dm9000.h>
#include <linux/rtc-v3020.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/physmap.h>
#include <linux/input.h>
#include <linux/gpio_keys.h>
#include <linux/gpio.h>
#include <linux/mfd/da903x.h>
#include <linux/regulator/machine.h>
#include <linux/spi/spi.h>
#include <linux/spi/tdo24m.h>
#include <linux/spi/libertas_spi.h>
#include <linux/spi/pxa2xx_spi.h>
#include <linux/power_supply.h>
#include <linux/apm-emulation.h>
#include <linux/i2c.h>
#include <linux/i2c/pca953x.h>
#include <linux/i2c/pxa-i2c.h>
#include <linux/regulator/userspace-consumer.h>
#include <media/soc_camera.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <mach/pxa27x.h>
#include <mach/pxa27x-udc.h>
#include <mach/audio.h>
#include <linux/platform_data/video-pxafb.h>
#include <linux/platform_data/usb-ohci-pxa27x.h>
#include <linux/platform_data/mmc-pxamci.h>
#include <linux/platform_data/keypad-pxa27x.h>
#include <linux/platform_data/camera-pxa.h>
#include "generic.h"
#include "devices.h"
/* EM-X270 specific GPIOs */
#define GPIO13_MMC_CD (13)
#define GPIO95_MMC_WP (95)
#define GPIO56_NAND_RB (56)
#define GPIO93_CAM_RESET (93)
#define GPIO16_USB_HUB_RESET (16)
/* eXeda specific GPIOs */
#define GPIO114_MMC_CD (114)
#define GPIO20_NAND_RB (20)
#define GPIO38_SD_PWEN (38)
#define GPIO37_WLAN_RST (37)
#define GPIO95_TOUCHPAD_INT (95)
#define GPIO130_CAM_RESET (130)
#define GPIO10_USB_HUB_RESET (10)
/* common GPIOs */
#define GPIO11_NAND_CS (11)
#define GPIO41_ETHIRQ (41)
#define EM_X270_ETHIRQ PXA_GPIO_TO_IRQ(GPIO41_ETHIRQ)
#define GPIO115_WLAN_PWEN (115)
#define GPIO19_WLAN_STRAP (19)
#define GPIO9_USB_VBUS_EN (9)
static int mmc_cd;
static int nand_rb;
static int dm9000_flags;
static int cam_reset;
static int usb_hub_reset;
static unsigned long common_pin_config[] = {
/* AC'97 */
GPIO28_AC97_BITCLK,
GPIO29_AC97_SDATA_IN_0,
GPIO30_AC97_SDATA_OUT,
GPIO31_AC97_SYNC,
GPIO98_AC97_SYSCLK,
GPIO113_AC97_nRESET,
/* BTUART */
GPIO42_BTUART_RXD,
GPIO43_BTUART_TXD,
GPIO44_BTUART_CTS,
GPIO45_BTUART_RTS,
/* STUART */
GPIO46_STUART_RXD,
GPIO47_STUART_TXD,
/* MCI controller */
GPIO32_MMC_CLK,
GPIO112_MMC_CMD,
GPIO92_MMC_DAT_0,
GPIO109_MMC_DAT_1,
GPIO110_MMC_DAT_2,
GPIO111_MMC_DAT_3,
/* LCD */
GPIOxx_LCD_TFT_16BPP,
/* QCI */
GPIO84_CIF_FV,
GPIO25_CIF_LV,
GPIO53_CIF_MCLK,
GPIO54_CIF_PCLK,
GPIO81_CIF_DD_0,
GPIO55_CIF_DD_1,
GPIO51_CIF_DD_2,
GPIO50_CIF_DD_3,
GPIO52_CIF_DD_4,
GPIO48_CIF_DD_5,
GPIO17_CIF_DD_6,
GPIO12_CIF_DD_7,
/* I2C */
GPIO117_I2C_SCL,
GPIO118_I2C_SDA,
/* Keypad */
GPIO100_KP_MKIN_0 | WAKEUP_ON_LEVEL_HIGH,
GPIO101_KP_MKIN_1 | WAKEUP_ON_LEVEL_HIGH,
GPIO102_KP_MKIN_2 | WAKEUP_ON_LEVEL_HIGH,
GPIO34_KP_MKIN_3 | WAKEUP_ON_LEVEL_HIGH,
GPIO39_KP_MKIN_4 | WAKEUP_ON_LEVEL_HIGH,
GPIO99_KP_MKIN_5 | WAKEUP_ON_LEVEL_HIGH,
GPIO91_KP_MKIN_6 | WAKEUP_ON_LEVEL_HIGH,
GPIO36_KP_MKIN_7 | WAKEUP_ON_LEVEL_HIGH,
GPIO103_KP_MKOUT_0,
GPIO104_KP_MKOUT_1,
GPIO105_KP_MKOUT_2,
GPIO106_KP_MKOUT_3,
GPIO107_KP_MKOUT_4,
GPIO108_KP_MKOUT_5,
GPIO96_KP_MKOUT_6,
GPIO22_KP_MKOUT_7,
/* SSP1 */
GPIO26_SSP1_RXD,
GPIO23_SSP1_SCLK,
GPIO24_SSP1_SFRM,
GPIO57_SSP1_TXD,
/* SSP2 */
GPIO19_GPIO, /* SSP2 clock is used as GPIO for Libertas pin-strap */
GPIO14_GPIO,
GPIO89_SSP2_TXD,
GPIO88_SSP2_RXD,
/* SDRAM and local bus */
GPIO15_nCS_1,
GPIO78_nCS_2,
GPIO79_nCS_3,
GPIO80_nCS_4,
GPIO49_nPWE,
GPIO18_RDY,
/* GPIO */
GPIO1_GPIO | WAKEUP_ON_EDGE_BOTH, /* sleep/resume button */
/* power controls */
GPIO20_GPIO | MFP_LPM_DRIVE_LOW, /* GPRS_PWEN */
GPIO115_GPIO | MFP_LPM_DRIVE_LOW, /* WLAN_PWEN */
/* NAND controls */
GPIO11_GPIO | MFP_LPM_DRIVE_HIGH, /* NAND CE# */
/* interrupts */
GPIO41_GPIO, /* DM9000 interrupt */
};
static unsigned long em_x270_pin_config[] = {
GPIO13_GPIO, /* MMC card detect */
GPIO16_GPIO, /* USB hub reset */
GPIO56_GPIO, /* NAND Ready/Busy */
GPIO93_GPIO | MFP_LPM_DRIVE_LOW, /* Camera reset */
GPIO95_GPIO, /* MMC Write protect */
};
static unsigned long exeda_pin_config[] = {
GPIO10_GPIO, /* USB hub reset */
GPIO20_GPIO, /* NAND Ready/Busy */
GPIO38_GPIO | MFP_LPM_DRIVE_LOW, /* SD slot power */
GPIO95_GPIO, /* touchpad IRQ */
GPIO114_GPIO, /* MMC card detect */
};
#if defined(CONFIG_DM9000) || defined(CONFIG_DM9000_MODULE)
static struct resource em_x270_dm9000_resource[] = {
[0] = {
.start = PXA_CS2_PHYS,
.end = PXA_CS2_PHYS + 3,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = PXA_CS2_PHYS + 8,
.end = PXA_CS2_PHYS + 8 + 0x3f,
.flags = IORESOURCE_MEM,
},
[2] = {
.start = EM_X270_ETHIRQ,
.end = EM_X270_ETHIRQ,
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHEDGE,
}
};
static struct dm9000_plat_data em_x270_dm9000_platdata = {
.flags = DM9000_PLATF_NO_EEPROM,
};
static struct platform_device em_x270_dm9000 = {
.name = "dm9000",
.id = 0,
.num_resources = ARRAY_SIZE(em_x270_dm9000_resource),
.resource = em_x270_dm9000_resource,
.dev = {
.platform_data = &em_x270_dm9000_platdata,
}
};
static void __init em_x270_init_dm9000(void)
{
em_x270_dm9000_platdata.flags |= dm9000_flags;
platform_device_register(&em_x270_dm9000);
}
#else
static inline void em_x270_init_dm9000(void) {}
#endif
/* V3020 RTC */
#if defined(CONFIG_RTC_DRV_V3020) || defined(CONFIG_RTC_DRV_V3020_MODULE)
static struct resource em_x270_v3020_resource[] = {
[0] = {
.start = PXA_CS4_PHYS,
.end = PXA_CS4_PHYS + 3,
.flags = IORESOURCE_MEM,
},
};
static struct v3020_platform_data em_x270_v3020_platdata = {
.leftshift = 0,
};
static struct platform_device em_x270_rtc = {
.name = "v3020",
.num_resources = ARRAY_SIZE(em_x270_v3020_resource),
.resource = em_x270_v3020_resource,
.id = -1,
.dev = {
.platform_data = &em_x270_v3020_platdata,
}
};
static void __init em_x270_init_rtc(void)
{
platform_device_register(&em_x270_rtc);
}
#else
static inline void em_x270_init_rtc(void) {}
#endif
/* NAND flash */
#if defined(CONFIG_MTD_NAND_PLATFORM) || defined(CONFIG_MTD_NAND_PLATFORM_MODULE)
static inline void nand_cs_on(void)
{
gpio_set_value(GPIO11_NAND_CS, 0);
}
static void nand_cs_off(void)
{
dsb();
gpio_set_value(GPIO11_NAND_CS, 1);
}
/* hardware specific access to control-lines */
static void em_x270_nand_cmd_ctl(struct mtd_info *mtd, int dat,
unsigned int ctrl)
{
struct nand_chip *this = mtd->priv;
unsigned long nandaddr = (unsigned long)this->IO_ADDR_W;
dsb();
if (ctrl & NAND_CTRL_CHANGE) {
if (ctrl & NAND_ALE)
nandaddr |= (1 << 3);
else
nandaddr &= ~(1 << 3);
if (ctrl & NAND_CLE)
nandaddr |= (1 << 2);
else
nandaddr &= ~(1 << 2);
if (ctrl & NAND_NCE)
nand_cs_on();
else
nand_cs_off();
}
dsb();
this->IO_ADDR_W = (void __iomem *)nandaddr;
if (dat != NAND_CMD_NONE)
writel(dat, this->IO_ADDR_W);
dsb();
}
/* read device ready pin */
static int em_x270_nand_device_ready(struct mtd_info *mtd)
{
dsb();
return gpio_get_value(nand_rb);
}
static struct mtd_partition em_x270_partition_info[] = {
[0] = {
.name = "em_x270-0",
.offset = 0,
.size = SZ_4M,
},
[1] = {
.name = "em_x270-1",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL
},
};
struct platform_nand_data em_x270_nand_platdata = {
.chip = {
.nr_chips = 1,
.chip_offset = 0,
.nr_partitions = ARRAY_SIZE(em_x270_partition_info),
.partitions = em_x270_partition_info,
.chip_delay = 20,
},
.ctrl = {
.hwcontrol = 0,
.dev_ready = em_x270_nand_device_ready,
.select_chip = 0,
.cmd_ctrl = em_x270_nand_cmd_ctl,
},
};
static struct resource em_x270_nand_resource[] = {
[0] = {
.start = PXA_CS1_PHYS,
.end = PXA_CS1_PHYS + 12,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device em_x270_nand = {
.name = "gen_nand",
.num_resources = ARRAY_SIZE(em_x270_nand_resource),
.resource = em_x270_nand_resource,
.id = -1,
.dev = {
.platform_data = &em_x270_nand_platdata,
}
};
static void __init em_x270_init_nand(void)
{
int err;
err = gpio_request(GPIO11_NAND_CS, "NAND CS");
if (err) {
pr_warning("EM-X270: failed to request NAND CS gpio\n");
return;
}
gpio_direction_output(GPIO11_NAND_CS, 1);
err = gpio_request(nand_rb, "NAND R/B");
if (err) {
pr_warning("EM-X270: failed to request NAND R/B gpio\n");
gpio_free(GPIO11_NAND_CS);
return;
}
gpio_direction_input(nand_rb);
platform_device_register(&em_x270_nand);
}
#else
static inline void em_x270_init_nand(void) {}
#endif
#if defined(CONFIG_MTD_PHYSMAP) || defined(CONFIG_MTD_PHYSMAP_MODULE)
static struct mtd_partition em_x270_nor_parts[] = {
{
.name = "Bootloader",
.offset = 0x00000000,
.size = 0x00050000,
.mask_flags = MTD_WRITEABLE /* force read-only */
}, {
.name = "Environment",
.offset = 0x00050000,
.size = 0x00010000,
}, {
.name = "Reserved",
.offset = 0x00060000,
.size = 0x00050000,
.mask_flags = MTD_WRITEABLE /* force read-only */
}, {
.name = "Splashscreen",
.offset = 0x000b0000,
.size = 0x00050000,
}
};
static struct physmap_flash_data em_x270_nor_data[] = {
[0] = {
.width = 2,
.parts = em_x270_nor_parts,
.nr_parts = ARRAY_SIZE(em_x270_nor_parts),
},
};
static struct resource em_x270_nor_flash_resource = {
.start = PXA_CS0_PHYS,
.end = PXA_CS0_PHYS + SZ_1M - 1,
.flags = IORESOURCE_MEM,
};
static struct platform_device em_x270_physmap_flash = {
.name = "physmap-flash",
.id = 0,
.num_resources = 1,
.resource = &em_x270_nor_flash_resource,
.dev = {
.platform_data = &em_x270_nor_data,
},
};
static void __init em_x270_init_nor(void)
{
platform_device_register(&em_x270_physmap_flash);
}
#else
static inline void em_x270_init_nor(void) {}
#endif
/* PXA27x OHCI controller setup */
#if defined(CONFIG_USB_OHCI_HCD) || defined(CONFIG_USB_OHCI_HCD_MODULE)
static struct regulator *em_x270_usb_ldo;
static int em_x270_usb_hub_init(void)
{
int err;
em_x270_usb_ldo = regulator_get(NULL, "vcc usb");
if (IS_ERR(em_x270_usb_ldo))
return PTR_ERR(em_x270_usb_ldo);
err = gpio_request(GPIO9_USB_VBUS_EN, "vbus en");
if (err)
goto err_free_usb_ldo;
err = gpio_request(usb_hub_reset, "hub rst");
if (err)
goto err_free_vbus_gpio;
/* USB Hub power-on and reset */
gpio_direction_output(usb_hub_reset, 1);
gpio_direction_output(GPIO9_USB_VBUS_EN, 0);
regulator_enable(em_x270_usb_ldo);
gpio_set_value(usb_hub_reset, 0);
gpio_set_value(usb_hub_reset, 1);
regulator_disable(em_x270_usb_ldo);
regulator_enable(em_x270_usb_ldo);
gpio_set_value(usb_hub_reset, 0);
gpio_set_value(GPIO9_USB_VBUS_EN, 1);
return 0;
err_free_vbus_gpio:
gpio_free(GPIO9_USB_VBUS_EN);
err_free_usb_ldo:
regulator_put(em_x270_usb_ldo);
return err;
}
static int em_x270_ohci_init(struct device *dev)
{
int err;
/* we don't want to entirely disable USB if the HUB init failed */
err = em_x270_usb_hub_init();
if (err)
pr_err("USB Hub initialization failed: %d\n", err);
/* enable port 2 transiever */
UP2OCR = UP2OCR_HXS | UP2OCR_HXOE;
return 0;
}
static void em_x270_ohci_exit(struct device *dev)
{
gpio_free(usb_hub_reset);
gpio_free(GPIO9_USB_VBUS_EN);
if (!IS_ERR(em_x270_usb_ldo)) {
if (regulator_is_enabled(em_x270_usb_ldo))
regulator_disable(em_x270_usb_ldo);
regulator_put(em_x270_usb_ldo);
}
}
static struct pxaohci_platform_data em_x270_ohci_platform_data = {
.port_mode = PMM_PERPORT_MODE,
.flags = ENABLE_PORT1 | ENABLE_PORT2 | POWER_CONTROL_LOW,
.init = em_x270_ohci_init,
.exit = em_x270_ohci_exit,
};
static void __init em_x270_init_ohci(void)
{
pxa_set_ohci_info(&em_x270_ohci_platform_data);
}
#else
static inline void em_x270_init_ohci(void) {}
#endif
/* MCI controller setup */
#if defined(CONFIG_MMC) || defined(CONFIG_MMC_MODULE)
static struct regulator *em_x270_sdio_ldo;
static int em_x270_mci_init(struct device *dev,
irq_handler_t em_x270_detect_int,
void *data)
{
int err;
em_x270_sdio_ldo = regulator_get(dev, "vcc sdio");
if (IS_ERR(em_x270_sdio_ldo)) {
dev_err(dev, "can't request SDIO power supply: %ld\n",
PTR_ERR(em_x270_sdio_ldo));
return PTR_ERR(em_x270_sdio_ldo);
}
err = request_irq(gpio_to_irq(mmc_cd), em_x270_detect_int,
IRQF_DISABLED | IRQF_TRIGGER_RISING |
IRQF_TRIGGER_FALLING,
"MMC card detect", data);
if (err) {
dev_err(dev, "can't request MMC card detect IRQ: %d\n", err);
goto err_irq;
}
if (machine_is_em_x270()) {
err = gpio_request(GPIO95_MMC_WP, "MMC WP");
if (err) {
dev_err(dev, "can't request MMC write protect: %d\n",
err);
goto err_gpio_wp;
}
gpio_direction_input(GPIO95_MMC_WP);
} else {
err = gpio_request(GPIO38_SD_PWEN, "sdio power");
if (err) {
dev_err(dev, "can't request MMC power control : %d\n",
err);
goto err_gpio_wp;
}
gpio_direction_output(GPIO38_SD_PWEN, 1);
}
return 0;
err_gpio_wp:
free_irq(gpio_to_irq(mmc_cd), data);
err_irq:
regulator_put(em_x270_sdio_ldo);
return err;
}
static void em_x270_mci_setpower(struct device *dev, unsigned int vdd)
{
struct pxamci_platform_data* p_d = dev->platform_data;
if ((1 << vdd) & p_d->ocr_mask) {
int vdd_uV = (2000 + (vdd - __ffs(MMC_VDD_20_21)) * 100) * 1000;
regulator_set_voltage(em_x270_sdio_ldo, vdd_uV, vdd_uV);
regulator_enable(em_x270_sdio_ldo);
} else {
regulator_disable(em_x270_sdio_ldo);
}
}
static void em_x270_mci_exit(struct device *dev, void *data)
{
free_irq(gpio_to_irq(mmc_cd), data);
regulator_put(em_x270_sdio_ldo);
if (machine_is_em_x270())
gpio_free(GPIO95_MMC_WP);
else
gpio_free(GPIO38_SD_PWEN);
}
static int em_x270_mci_get_ro(struct device *dev)
{
return gpio_get_value(GPIO95_MMC_WP);
}
static struct pxamci_platform_data em_x270_mci_platform_data = {
.detect_delay_ms = 250,
.ocr_mask = MMC_VDD_20_21|MMC_VDD_21_22|MMC_VDD_22_23|
MMC_VDD_24_25|MMC_VDD_25_26|MMC_VDD_26_27|
MMC_VDD_27_28|MMC_VDD_28_29|MMC_VDD_29_30|
MMC_VDD_30_31|MMC_VDD_31_32,
.init = em_x270_mci_init,
.setpower = em_x270_mci_setpower,
.exit = em_x270_mci_exit,
.gpio_card_detect = -1,
.gpio_card_ro = -1,
.gpio_power = -1,
};
static void __init em_x270_init_mmc(void)
{
if (machine_is_em_x270())
em_x270_mci_platform_data.get_ro = em_x270_mci_get_ro;
pxa_set_mci_info(&em_x270_mci_platform_data);
}
#else
static inline void em_x270_init_mmc(void) {}
#endif
/* LCD */
#if defined(CONFIG_FB_PXA) || defined(CONFIG_FB_PXA_MODULE)
static struct pxafb_mode_info em_x270_lcd_modes[] = {
[0] = {
.pixclock = 38250,
.bpp = 16,
.xres = 480,
.yres = 640,
.hsync_len = 8,
.vsync_len = 2,
.left_margin = 8,
.upper_margin = 2,
.right_margin = 24,
.lower_margin = 4,
.sync = 0,
},
[1] = {
.pixclock = 153800,
.bpp = 16,
.xres = 240,
.yres = 320,
.hsync_len = 8,
.vsync_len = 2,
.left_margin = 8,
.upper_margin = 2,
.right_margin = 88,
.lower_margin = 2,
.sync = 0,
},
};
static struct pxafb_mach_info em_x270_lcd = {
.modes = em_x270_lcd_modes,
.num_modes = 2,
.lcd_conn = LCD_COLOR_TFT_16BPP,
};
static void __init em_x270_init_lcd(void)
{
pxa_set_fb_info(NULL, &em_x270_lcd);
}
#else
static inline void em_x270_init_lcd(void) {}
#endif
#if defined(CONFIG_SPI_PXA2XX) || defined(CONFIG_SPI_PXA2XX_MODULE)
static struct pxa2xx_spi_master em_x270_spi_info = {
.num_chipselect = 1,
};
static struct pxa2xx_spi_chip em_x270_tdo24m_chip = {
.rx_threshold = 1,
.tx_threshold = 1,
.gpio_cs = -1,
};
static struct tdo24m_platform_data em_x270_tdo24m_pdata = {
.model = TDO35S,
};
static struct pxa2xx_spi_master em_x270_spi_2_info = {
.num_chipselect = 1,
.enable_dma = 1,
};
static struct pxa2xx_spi_chip em_x270_libertas_chip = {
.rx_threshold = 1,
.tx_threshold = 1,
.timeout = 1000,
.gpio_cs = 14,
};
static unsigned long em_x270_libertas_pin_config[] = {
/* SSP2 */
GPIO19_SSP2_SCLK,
GPIO14_GPIO,
GPIO89_SSP2_TXD,
GPIO88_SSP2_RXD,
};
static int em_x270_libertas_setup(struct spi_device *spi)
{
int err = gpio_request(GPIO115_WLAN_PWEN, "WLAN PWEN");
if (err)
return err;
err = gpio_request(GPIO19_WLAN_STRAP, "WLAN STRAP");
if (err)
goto err_free_pwen;
if (machine_is_exeda()) {
err = gpio_request(GPIO37_WLAN_RST, "WLAN RST");
if (err)
goto err_free_strap;
gpio_direction_output(GPIO37_WLAN_RST, 1);
msleep(100);
}
gpio_direction_output(GPIO19_WLAN_STRAP, 1);
msleep(100);
pxa2xx_mfp_config(ARRAY_AND_SIZE(em_x270_libertas_pin_config));
gpio_direction_output(GPIO115_WLAN_PWEN, 0);
msleep(100);
gpio_set_value(GPIO115_WLAN_PWEN, 1);
msleep(100);
spi->bits_per_word = 16;
spi_setup(spi);
return 0;
err_free_strap:
gpio_free(GPIO19_WLAN_STRAP);
err_free_pwen:
gpio_free(GPIO115_WLAN_PWEN);
return err;
}
static int em_x270_libertas_teardown(struct spi_device *spi)
{
gpio_set_value(GPIO115_WLAN_PWEN, 0);
gpio_free(GPIO115_WLAN_PWEN);
gpio_free(GPIO19_WLAN_STRAP);
if (machine_is_exeda()) {
gpio_set_value(GPIO37_WLAN_RST, 0);
gpio_free(GPIO37_WLAN_RST);
}
return 0;
}
struct libertas_spi_platform_data em_x270_libertas_pdata = {
.use_dummy_writes = 1,
.setup = em_x270_libertas_setup,
.teardown = em_x270_libertas_teardown,
};
static struct spi_board_info em_x270_spi_devices[] __initdata = {
{
.modalias = "tdo24m",
.max_speed_hz = 1000000,
.bus_num = 1,
.chip_select = 0,
.controller_data = &em_x270_tdo24m_chip,
.platform_data = &em_x270_tdo24m_pdata,
},
{
.modalias = "libertas_spi",
.max_speed_hz = 13000000,
.bus_num = 2,
.irq = PXA_GPIO_TO_IRQ(116),
.chip_select = 0,
.controller_data = &em_x270_libertas_chip,
.platform_data = &em_x270_libertas_pdata,
},
};
static void __init em_x270_init_spi(void)
{
pxa2xx_set_spi_info(1, &em_x270_spi_info);
pxa2xx_set_spi_info(2, &em_x270_spi_2_info);
spi_register_board_info(ARRAY_AND_SIZE(em_x270_spi_devices));
}
#else
static inline void em_x270_init_spi(void) {}
#endif
#if defined(CONFIG_SND_PXA2XX_LIB_AC97)
static pxa2xx_audio_ops_t em_x270_ac97_info = {
.reset_gpio = 113,
};
static void __init em_x270_init_ac97(void)
{
pxa_set_ac97_info(&em_x270_ac97_info);
}
#else
static inline void em_x270_init_ac97(void) {}
#endif
#if defined(CONFIG_KEYBOARD_PXA27x) || defined(CONFIG_KEYBOARD_PXA27x_MODULE)
static unsigned int em_x270_module_matrix_keys[] = {
KEY(0, 0, KEY_A), KEY(1, 0, KEY_UP), KEY(2, 1, KEY_B),
KEY(0, 2, KEY_LEFT), KEY(1, 1, KEY_ENTER), KEY(2, 0, KEY_RIGHT),
KEY(0, 1, KEY_C), KEY(1, 2, KEY_DOWN), KEY(2, 2, KEY_D),
};
struct pxa27x_keypad_platform_data em_x270_module_keypad_info = {
/* code map for the matrix keys */
.matrix_key_rows = 3,
.matrix_key_cols = 3,
.matrix_key_map = em_x270_module_matrix_keys,
.matrix_key_map_size = ARRAY_SIZE(em_x270_module_matrix_keys),
};
static unsigned int em_x270_exeda_matrix_keys[] = {
KEY(0, 0, KEY_RIGHTSHIFT), KEY(0, 1, KEY_RIGHTCTRL),
KEY(0, 2, KEY_RIGHTALT), KEY(0, 3, KEY_SPACE),
KEY(0, 4, KEY_LEFTALT), KEY(0, 5, KEY_LEFTCTRL),
KEY(0, 6, KEY_ENTER), KEY(0, 7, KEY_SLASH),
KEY(1, 0, KEY_DOT), KEY(1, 1, KEY_M),
KEY(1, 2, KEY_N), KEY(1, 3, KEY_B),
KEY(1, 4, KEY_V), KEY(1, 5, KEY_C),
KEY(1, 6, KEY_X), KEY(1, 7, KEY_Z),
KEY(2, 0, KEY_LEFTSHIFT), KEY(2, 1, KEY_SEMICOLON),
KEY(2, 2, KEY_L), KEY(2, 3, KEY_K),
KEY(2, 4, KEY_J), KEY(2, 5, KEY_H),
KEY(2, 6, KEY_G), KEY(2, 7, KEY_F),
KEY(3, 0, KEY_D), KEY(3, 1, KEY_S),
KEY(3, 2, KEY_A), KEY(3, 3, KEY_TAB),
KEY(3, 4, KEY_BACKSPACE), KEY(3, 5, KEY_P),
KEY(3, 6, KEY_O), KEY(3, 7, KEY_I),
KEY(4, 0, KEY_U), KEY(4, 1, KEY_Y),
KEY(4, 2, KEY_T), KEY(4, 3, KEY_R),
KEY(4, 4, KEY_E), KEY(4, 5, KEY_W),
KEY(4, 6, KEY_Q), KEY(4, 7, KEY_MINUS),
KEY(5, 0, KEY_0), KEY(5, 1, KEY_9),
KEY(5, 2, KEY_8), KEY(5, 3, KEY_7),
KEY(5, 4, KEY_6), KEY(5, 5, KEY_5),
KEY(5, 6, KEY_4), KEY(5, 7, KEY_3),
KEY(6, 0, KEY_2), KEY(6, 1, KEY_1),
KEY(6, 2, KEY_ENTER), KEY(6, 3, KEY_END),
KEY(6, 4, KEY_DOWN), KEY(6, 5, KEY_UP),
KEY(6, 6, KEY_MENU), KEY(6, 7, KEY_F1),
KEY(7, 0, KEY_LEFT), KEY(7, 1, KEY_RIGHT),
KEY(7, 2, KEY_BACK), KEY(7, 3, KEY_HOME),
KEY(7, 4, 0), KEY(7, 5, 0),
KEY(7, 6, 0), KEY(7, 7, 0),
};
struct pxa27x_keypad_platform_data em_x270_exeda_keypad_info = {
/* code map for the matrix keys */
.matrix_key_rows = 8,
.matrix_key_cols = 8,
.matrix_key_map = em_x270_exeda_matrix_keys,
.matrix_key_map_size = ARRAY_SIZE(em_x270_exeda_matrix_keys),
};
static void __init em_x270_init_keypad(void)
{
if (machine_is_em_x270())
pxa_set_keypad_info(&em_x270_module_keypad_info);
else
pxa_set_keypad_info(&em_x270_exeda_keypad_info);
}
#else
static inline void em_x270_init_keypad(void) {}
#endif
#if defined(CONFIG_KEYBOARD_GPIO) || defined(CONFIG_KEYBOARD_GPIO_MODULE)
static struct gpio_keys_button gpio_keys_button[] = {
[0] = {
.desc = "sleep/wakeup",
.code = KEY_SUSPEND,
.type = EV_PWR,
.gpio = 1,
.wakeup = 1,
},
};
static struct gpio_keys_platform_data em_x270_gpio_keys_data = {
.buttons = gpio_keys_button,
.nbuttons = 1,
};
static struct platform_device em_x270_gpio_keys = {
.name = "gpio-keys",
.id = -1,
.dev = {
.platform_data = &em_x270_gpio_keys_data,
},
};
static void __init em_x270_init_gpio_keys(void)
{
platform_device_register(&em_x270_gpio_keys);
}
#else
static inline void em_x270_init_gpio_keys(void) {}
#endif
/* Quick Capture Interface and sensor setup */
#if defined(CONFIG_VIDEO_PXA27x) || defined(CONFIG_VIDEO_PXA27x_MODULE)
static struct regulator *em_x270_camera_ldo;
static int em_x270_sensor_init(void)
{
int ret;
ret = gpio_request(cam_reset, "camera reset");
if (ret)
return ret;
gpio_direction_output(cam_reset, 0);
em_x270_camera_ldo = regulator_get(NULL, "vcc cam");
if (em_x270_camera_ldo == NULL) {
gpio_free(cam_reset);
return -ENODEV;
}
ret = regulator_enable(em_x270_camera_ldo);
if (ret) {
regulator_put(em_x270_camera_ldo);
gpio_free(cam_reset);
return ret;
}
gpio_set_value(cam_reset, 1);
return 0;
}
struct pxacamera_platform_data em_x270_camera_platform_data = {
.flags = PXA_CAMERA_MASTER | PXA_CAMERA_DATAWIDTH_8 |
PXA_CAMERA_PCLK_EN | PXA_CAMERA_MCLK_EN,
.mclk_10khz = 2600,
};
static int em_x270_sensor_power(struct device *dev, int on)
{
int ret;
int is_on = regulator_is_enabled(em_x270_camera_ldo);
if (on == is_on)
return 0;
gpio_set_value(cam_reset, !on);
if (on)
ret = regulator_enable(em_x270_camera_ldo);
else
ret = regulator_disable(em_x270_camera_ldo);
if (ret)
return ret;
gpio_set_value(cam_reset, on);
return 0;
}
static struct i2c_board_info em_x270_i2c_cam_info[] = {
{
I2C_BOARD_INFO("mt9m111", 0x48),
},
};
static struct soc_camera_link iclink = {
.bus_id = 0,
.power = em_x270_sensor_power,
.board_info = &em_x270_i2c_cam_info[0],
.i2c_adapter_id = 0,
};
static struct platform_device em_x270_camera = {
.name = "soc-camera-pdrv",
.id = -1,
.dev = {
.platform_data = &iclink,
},
};
static void __init em_x270_init_camera(void)
{
if (em_x270_sensor_init() == 0) {
pxa_set_camera_info(&em_x270_camera_platform_data);
platform_device_register(&em_x270_camera);
}
}
#else
static inline void em_x270_init_camera(void) {}
#endif
static struct regulator_bulk_data em_x270_gps_consumer_supply = {
.supply = "vcc gps",
};
static struct regulator_userspace_consumer_data em_x270_gps_consumer_data = {
.name = "vcc gps",
.num_supplies = 1,
.supplies = &em_x270_gps_consumer_supply,
};
static struct platform_device em_x270_gps_userspace_consumer = {
.name = "reg-userspace-consumer",
.id = 0,
.dev = {
.platform_data = &em_x270_gps_consumer_data,
},
};
static struct regulator_bulk_data em_x270_gprs_consumer_supply = {
.supply = "vcc gprs",
};
static struct regulator_userspace_consumer_data em_x270_gprs_consumer_data = {
.name = "vcc gprs",
.num_supplies = 1,
.supplies = &em_x270_gprs_consumer_supply
};
static struct platform_device em_x270_gprs_userspace_consumer = {
.name = "reg-userspace-consumer",
.id = 1,
.dev = {
.platform_data = &em_x270_gprs_consumer_data,
}
};
static struct platform_device *em_x270_userspace_consumers[] = {
&em_x270_gps_userspace_consumer,
&em_x270_gprs_userspace_consumer,
};
static void __init em_x270_userspace_consumers_init(void)
{
platform_add_devices(ARRAY_AND_SIZE(em_x270_userspace_consumers));
}
/* DA9030 related initializations */
#define REGULATOR_CONSUMER(_name, _dev_name, _supply) \
static struct regulator_consumer_supply _name##_consumers[] = { \
REGULATOR_SUPPLY(_supply, _dev_name), \
}
REGULATOR_CONSUMER(ldo3, "reg-userspace-consumer.0", "vcc gps");
REGULATOR_CONSUMER(ldo5, NULL, "vcc cam");
REGULATOR_CONSUMER(ldo10, "pxa2xx-mci", "vcc sdio");
REGULATOR_CONSUMER(ldo12, NULL, "vcc usb");
REGULATOR_CONSUMER(ldo19, "reg-userspace-consumer.1", "vcc gprs");
REGULATOR_CONSUMER(buck2, NULL, "vcc_core");
#define REGULATOR_INIT(_ldo, _min_uV, _max_uV, _ops_mask) \
static struct regulator_init_data _ldo##_data = { \
.constraints = { \
.min_uV = _min_uV, \
.max_uV = _max_uV, \
.state_mem = { \
.enabled = 0, \
}, \
.valid_ops_mask = _ops_mask, \
.apply_uV = 1, \
}, \
.num_consumer_supplies = ARRAY_SIZE(_ldo##_consumers), \
.consumer_supplies = _ldo##_consumers, \
};
REGULATOR_INIT(ldo3, 3200000, 3200000, REGULATOR_CHANGE_STATUS);
REGULATOR_INIT(ldo5, 3000000, 3000000, REGULATOR_CHANGE_STATUS);
REGULATOR_INIT(ldo10, 2000000, 3200000,
REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE);
REGULATOR_INIT(ldo12, 3000000, 3000000, REGULATOR_CHANGE_STATUS);
REGULATOR_INIT(ldo19, 3200000, 3200000, REGULATOR_CHANGE_STATUS);
REGULATOR_INIT(buck2, 1000000, 1650000, REGULATOR_CHANGE_VOLTAGE);
struct led_info em_x270_led_info = {
.name = "em-x270:orange",
.default_trigger = "battery-charging-or-full",
};
struct power_supply_info em_x270_psy_info = {
.name = "battery",
.technology = POWER_SUPPLY_TECHNOLOGY_LIPO,
.voltage_max_design = 4200000,
.voltage_min_design = 3000000,
.use_for_apm = 1,
};
static void em_x270_battery_low(void)
{
#if defined(CONFIG_APM_EMULATION)
apm_queue_event(APM_LOW_BATTERY);
#endif
}
static void em_x270_battery_critical(void)
{
#if defined(CONFIG_APM_EMULATION)
apm_queue_event(APM_CRITICAL_SUSPEND);
#endif
}
struct da9030_battery_info em_x270_batterty_info = {
.battery_info = &em_x270_psy_info,
.charge_milliamp = 1000,
.charge_millivolt = 4200,
.vbat_low = 3600,
.vbat_crit = 3400,
.vbat_charge_start = 4100,
.vbat_charge_stop = 4200,
.vbat_charge_restart = 4000,
.vcharge_min = 3200,
.vcharge_max = 5500,
.tbat_low = 197,
.tbat_high = 78,
.tbat_restart = 100,
.batmon_interval = 0,
.battery_low = em_x270_battery_low,
.battery_critical = em_x270_battery_critical,
};
#define DA9030_SUBDEV(_name, _id, _pdata) \
{ \
.name = "da903x-" #_name, \
.id = DA9030_ID_##_id, \
.platform_data = _pdata, \
}
#define DA9030_LDO(num) DA9030_SUBDEV(regulator, LDO##num, &ldo##num##_data)
struct da903x_subdev_info em_x270_da9030_subdevs[] = {
DA9030_LDO(3),
DA9030_LDO(5),
DA9030_LDO(10),
DA9030_LDO(12),
DA9030_LDO(19),
DA9030_SUBDEV(regulator, BUCK2, &buck2_data),
DA9030_SUBDEV(led, LED_PC, &em_x270_led_info),
DA9030_SUBDEV(backlight, WLED, &em_x270_led_info),
DA9030_SUBDEV(battery, BAT, &em_x270_batterty_info),
};
static struct da903x_platform_data em_x270_da9030_info = {
.num_subdevs = ARRAY_SIZE(em_x270_da9030_subdevs),
.subdevs = em_x270_da9030_subdevs,
};
static struct i2c_board_info em_x270_i2c_pmic_info = {
I2C_BOARD_INFO("da9030", 0x49),
.irq = PXA_GPIO_TO_IRQ(0),
.platform_data = &em_x270_da9030_info,
};
static struct i2c_pxa_platform_data em_x270_pwr_i2c_info = {
.use_pio = 1,
};
static void __init em_x270_init_da9030(void)
{
pxa27x_set_i2c_power_info(&em_x270_pwr_i2c_info);
i2c_register_board_info(1, &em_x270_i2c_pmic_info, 1);
}
static struct pca953x_platform_data exeda_gpio_ext_pdata = {
.gpio_base = 128,
};
static struct i2c_board_info exeda_i2c_info[] = {
{
I2C_BOARD_INFO("pca9555", 0x21),
.platform_data = &exeda_gpio_ext_pdata,
},
};
static struct i2c_pxa_platform_data em_x270_i2c_info = {
.fast_mode = 1,
};
static void __init em_x270_init_i2c(void)
{
pxa_set_i2c_info(&em_x270_i2c_info);
if (machine_is_exeda())
i2c_register_board_info(0, ARRAY_AND_SIZE(exeda_i2c_info));
}
static void __init em_x270_module_init(void)
{
pxa2xx_mfp_config(ARRAY_AND_SIZE(em_x270_pin_config));
mmc_cd = GPIO13_MMC_CD;
nand_rb = GPIO56_NAND_RB;
dm9000_flags = DM9000_PLATF_32BITONLY;
cam_reset = GPIO93_CAM_RESET;
usb_hub_reset = GPIO16_USB_HUB_RESET;
}
static void __init em_x270_exeda_init(void)
{
pxa2xx_mfp_config(ARRAY_AND_SIZE(exeda_pin_config));
mmc_cd = GPIO114_MMC_CD;
nand_rb = GPIO20_NAND_RB;
dm9000_flags = DM9000_PLATF_16BITONLY;
cam_reset = GPIO130_CAM_RESET;
usb_hub_reset = GPIO10_USB_HUB_RESET;
}
static void __init em_x270_init(void)
{
pxa2xx_mfp_config(ARRAY_AND_SIZE(common_pin_config));
pxa_set_ffuart_info(NULL);
pxa_set_btuart_info(NULL);
pxa_set_stuart_info(NULL);
#ifdef CONFIG_PM
pxa27x_set_pwrmode(PWRMODE_DEEPSLEEP);
#endif
if (machine_is_em_x270())
em_x270_module_init();
else if (machine_is_exeda())
em_x270_exeda_init();
else
panic("Unsupported machine: %d\n", machine_arch_type);
em_x270_init_da9030();
em_x270_init_dm9000();
em_x270_init_rtc();
em_x270_init_nand();
em_x270_init_nor();
em_x270_init_lcd();
em_x270_init_mmc();
em_x270_init_ohci();
em_x270_init_keypad();
em_x270_init_gpio_keys();
em_x270_init_ac97();
em_x270_init_spi();
em_x270_init_i2c();
em_x270_init_camera();
em_x270_userspace_consumers_init();
}
MACHINE_START(EM_X270, "Compulab EM-X270")
.atag_offset = 0x100,
.map_io = pxa27x_map_io,
.nr_irqs = PXA_NR_IRQS,
.init_irq = pxa27x_init_irq,
.handle_irq = pxa27x_handle_irq,
.init_time = pxa_timer_init,
.init_machine = em_x270_init,
.restart = pxa_restart,
MACHINE_END
MACHINE_START(EXEDA, "Compulab eXeda")
.atag_offset = 0x100,
.map_io = pxa27x_map_io,
.nr_irqs = PXA_NR_IRQS,
.init_irq = pxa27x_init_irq,
.handle_irq = pxa27x_handle_irq,
.init_time = pxa_timer_init,
.init_machine = em_x270_init,
.restart = pxa_restart,
MACHINE_END
| gpl-2.0 |
ImYeol/linux_fbtft | arch/mips/pci/pci-bcm63xx.c | 2611 | 9896 | /*
* 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) 2008 Maxime Bizon <mbizon@freebox.fr>
*/
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/clk.h>
#include <asm/bootinfo.h>
#include <bcm63xx_reset.h>
#include "pci-bcm63xx.h"
/*
* Allow PCI to be disabled at runtime depending on board nvram
* configuration
*/
int bcm63xx_pci_enabled;
static struct resource bcm_pci_mem_resource = {
.name = "bcm63xx PCI memory space",
.start = BCM_PCI_MEM_BASE_PA,
.end = BCM_PCI_MEM_END_PA,
.flags = IORESOURCE_MEM
};
static struct resource bcm_pci_io_resource = {
.name = "bcm63xx PCI IO space",
.start = BCM_PCI_IO_BASE_PA,
#ifdef CONFIG_CARDBUS
.end = BCM_PCI_IO_HALF_PA,
#else
.end = BCM_PCI_IO_END_PA,
#endif
.flags = IORESOURCE_IO
};
struct pci_controller bcm63xx_controller = {
.pci_ops = &bcm63xx_pci_ops,
.io_resource = &bcm_pci_io_resource,
.mem_resource = &bcm_pci_mem_resource,
};
/*
* We handle cardbus via a fake Cardbus bridge, memory and io spaces
* have to be clearly separated from PCI one since we have different
* memory decoder.
*/
#ifdef CONFIG_CARDBUS
static struct resource bcm_cb_mem_resource = {
.name = "bcm63xx Cardbus memory space",
.start = BCM_CB_MEM_BASE_PA,
.end = BCM_CB_MEM_END_PA,
.flags = IORESOURCE_MEM
};
static struct resource bcm_cb_io_resource = {
.name = "bcm63xx Cardbus IO space",
.start = BCM_PCI_IO_HALF_PA + 1,
.end = BCM_PCI_IO_END_PA,
.flags = IORESOURCE_IO
};
struct pci_controller bcm63xx_cb_controller = {
.pci_ops = &bcm63xx_cb_ops,
.io_resource = &bcm_cb_io_resource,
.mem_resource = &bcm_cb_mem_resource,
};
#endif
static struct resource bcm_pcie_mem_resource = {
.name = "bcm63xx PCIe memory space",
.start = BCM_PCIE_MEM_BASE_PA,
.end = BCM_PCIE_MEM_END_PA,
.flags = IORESOURCE_MEM,
};
static struct resource bcm_pcie_io_resource = {
.name = "bcm63xx PCIe IO space",
.start = 0,
.end = 0,
.flags = 0,
};
struct pci_controller bcm63xx_pcie_controller = {
.pci_ops = &bcm63xx_pcie_ops,
.io_resource = &bcm_pcie_io_resource,
.mem_resource = &bcm_pcie_mem_resource,
};
static u32 bcm63xx_int_cfg_readl(u32 reg)
{
u32 tmp;
tmp = reg & MPI_PCICFGCTL_CFGADDR_MASK;
tmp |= MPI_PCICFGCTL_WRITEEN_MASK;
bcm_mpi_writel(tmp, MPI_PCICFGCTL_REG);
iob();
return bcm_mpi_readl(MPI_PCICFGDATA_REG);
}
static void bcm63xx_int_cfg_writel(u32 val, u32 reg)
{
u32 tmp;
tmp = reg & MPI_PCICFGCTL_CFGADDR_MASK;
tmp |= MPI_PCICFGCTL_WRITEEN_MASK;
bcm_mpi_writel(tmp, MPI_PCICFGCTL_REG);
bcm_mpi_writel(val, MPI_PCICFGDATA_REG);
}
void __iomem *pci_iospace_start;
static void __init bcm63xx_reset_pcie(void)
{
u32 val;
u32 reg;
/* enable SERDES */
if (BCMCPU_IS_6328())
reg = MISC_SERDES_CTRL_6328_REG;
else
reg = MISC_SERDES_CTRL_6362_REG;
val = bcm_misc_readl(reg);
val |= SERDES_PCIE_EN | SERDES_PCIE_EXD_EN;
bcm_misc_writel(val, reg);
/* reset the PCIe core */
bcm63xx_core_set_reset(BCM63XX_RESET_PCIE, 1);
bcm63xx_core_set_reset(BCM63XX_RESET_PCIE_EXT, 1);
mdelay(10);
bcm63xx_core_set_reset(BCM63XX_RESET_PCIE, 0);
mdelay(10);
bcm63xx_core_set_reset(BCM63XX_RESET_PCIE_EXT, 0);
mdelay(200);
}
static struct clk *pcie_clk;
static int __init bcm63xx_register_pcie(void)
{
u32 val;
/* enable clock */
pcie_clk = clk_get(NULL, "pcie");
if (IS_ERR_OR_NULL(pcie_clk))
return -ENODEV;
clk_prepare_enable(pcie_clk);
bcm63xx_reset_pcie();
/* configure the PCIe bridge */
val = bcm_pcie_readl(PCIE_BRIDGE_OPT1_REG);
val |= OPT1_RD_BE_OPT_EN;
val |= OPT1_RD_REPLY_BE_FIX_EN;
val |= OPT1_PCIE_BRIDGE_HOLE_DET_EN;
val |= OPT1_L1_INT_STATUS_MASK_POL;
bcm_pcie_writel(val, PCIE_BRIDGE_OPT1_REG);
/* setup the interrupts */
val = bcm_pcie_readl(PCIE_BRIDGE_RC_INT_MASK_REG);
val |= PCIE_RC_INT_A | PCIE_RC_INT_B | PCIE_RC_INT_C | PCIE_RC_INT_D;
bcm_pcie_writel(val, PCIE_BRIDGE_RC_INT_MASK_REG);
val = bcm_pcie_readl(PCIE_BRIDGE_OPT2_REG);
/* enable credit checking and error checking */
val |= OPT2_TX_CREDIT_CHK_EN;
val |= OPT2_UBUS_UR_DECODE_DIS;
/* set device bus/func for the pcie device */
val |= (PCIE_BUS_DEVICE << OPT2_CFG_TYPE1_BUS_NO_SHIFT);
val |= OPT2_CFG_TYPE1_BD_SEL;
bcm_pcie_writel(val, PCIE_BRIDGE_OPT2_REG);
/* setup class code as bridge */
val = bcm_pcie_readl(PCIE_IDVAL3_REG);
val &= ~IDVAL3_CLASS_CODE_MASK;
val |= (PCI_CLASS_BRIDGE_PCI << IDVAL3_SUBCLASS_SHIFT);
bcm_pcie_writel(val, PCIE_IDVAL3_REG);
/* disable bar1 size */
val = bcm_pcie_readl(PCIE_CONFIG2_REG);
val &= ~CONFIG2_BAR1_SIZE_MASK;
bcm_pcie_writel(val, PCIE_CONFIG2_REG);
/* set bar0 to little endian */
val = (BCM_PCIE_MEM_BASE_PA >> 20) << BASEMASK_BASE_SHIFT;
val |= (BCM_PCIE_MEM_BASE_PA >> 20) << BASEMASK_MASK_SHIFT;
val |= BASEMASK_REMAP_EN;
bcm_pcie_writel(val, PCIE_BRIDGE_BAR0_BASEMASK_REG);
val = (BCM_PCIE_MEM_BASE_PA >> 20) << REBASE_ADDR_BASE_SHIFT;
bcm_pcie_writel(val, PCIE_BRIDGE_BAR0_REBASE_ADDR_REG);
register_pci_controller(&bcm63xx_pcie_controller);
return 0;
}
static int __init bcm63xx_register_pci(void)
{
unsigned int mem_size;
u32 val;
/*
* configuration access are done through IO space, remap 4
* first bytes to access it from CPU.
*
* this means that no io access from CPU should happen while
* we do a configuration cycle, but there's no way we can add
* a spinlock for each io access, so this is currently kind of
* broken on SMP.
*/
pci_iospace_start = ioremap_nocache(BCM_PCI_IO_BASE_PA, 4);
if (!pci_iospace_start)
return -ENOMEM;
/* setup local bus to PCI access (PCI memory) */
val = BCM_PCI_MEM_BASE_PA & MPI_L2P_BASE_MASK;
bcm_mpi_writel(val, MPI_L2PMEMBASE1_REG);
bcm_mpi_writel(~(BCM_PCI_MEM_SIZE - 1), MPI_L2PMEMRANGE1_REG);
bcm_mpi_writel(val | MPI_L2PREMAP_ENABLED_MASK, MPI_L2PMEMREMAP1_REG);
/* set Cardbus IDSEL (type 0 cfg access on primary bus for
* this IDSEL will be done on Cardbus instead) */
val = bcm_pcmcia_readl(PCMCIA_C1_REG);
val &= ~PCMCIA_C1_CBIDSEL_MASK;
val |= (CARDBUS_PCI_IDSEL << PCMCIA_C1_CBIDSEL_SHIFT);
bcm_pcmcia_writel(val, PCMCIA_C1_REG);
#ifdef CONFIG_CARDBUS
/* setup local bus to PCI access (Cardbus memory) */
val = BCM_CB_MEM_BASE_PA & MPI_L2P_BASE_MASK;
bcm_mpi_writel(val, MPI_L2PMEMBASE2_REG);
bcm_mpi_writel(~(BCM_CB_MEM_SIZE - 1), MPI_L2PMEMRANGE2_REG);
val |= MPI_L2PREMAP_ENABLED_MASK | MPI_L2PREMAP_IS_CARDBUS_MASK;
bcm_mpi_writel(val, MPI_L2PMEMREMAP2_REG);
#else
/* disable second access windows */
bcm_mpi_writel(0, MPI_L2PMEMREMAP2_REG);
#endif
/* setup local bus to PCI access (IO memory), we have only 1
* IO window for both PCI and cardbus, but it cannot handle
* both at the same time, assume standard PCI for now, if
* cardbus card has IO zone, PCI fixup will change window to
* cardbus */
val = BCM_PCI_IO_BASE_PA & MPI_L2P_BASE_MASK;
bcm_mpi_writel(val, MPI_L2PIOBASE_REG);
bcm_mpi_writel(~(BCM_PCI_IO_SIZE - 1), MPI_L2PIORANGE_REG);
bcm_mpi_writel(val | MPI_L2PREMAP_ENABLED_MASK, MPI_L2PIOREMAP_REG);
/* enable PCI related GPIO pins */
bcm_mpi_writel(MPI_LOCBUSCTL_EN_PCI_GPIO_MASK, MPI_LOCBUSCTL_REG);
/* setup PCI to local bus access, used by PCI device to target
* local RAM while bus mastering */
bcm63xx_int_cfg_writel(0, PCI_BASE_ADDRESS_3);
if (BCMCPU_IS_3368() || BCMCPU_IS_6358() || BCMCPU_IS_6368())
val = MPI_SP0_REMAP_ENABLE_MASK;
else
val = 0;
bcm_mpi_writel(val, MPI_SP0_REMAP_REG);
bcm63xx_int_cfg_writel(0x0, PCI_BASE_ADDRESS_4);
bcm_mpi_writel(0, MPI_SP1_REMAP_REG);
mem_size = bcm63xx_get_memory_size();
/* 6348 before rev b0 exposes only 16 MB of RAM memory through
* PCI, throw a warning if we have more memory */
if (BCMCPU_IS_6348() && (bcm63xx_get_cpu_rev() & 0xf0) == 0xa0) {
if (mem_size > (16 * 1024 * 1024))
printk(KERN_WARNING "bcm63xx: this CPU "
"revision cannot handle more than 16MB "
"of RAM for PCI bus mastering\n");
} else {
/* setup sp0 range to local RAM size */
bcm_mpi_writel(~(mem_size - 1), MPI_SP0_RANGE_REG);
bcm_mpi_writel(0, MPI_SP1_RANGE_REG);
}
/* change host bridge retry counter to infinite number of
* retry, needed for some broadcom wifi cards with Silicon
* Backplane bus where access to srom seems very slow */
val = bcm63xx_int_cfg_readl(BCMPCI_REG_TIMERS);
val &= ~REG_TIMER_RETRY_MASK;
bcm63xx_int_cfg_writel(val, BCMPCI_REG_TIMERS);
/* enable memory decoder and bus mastering */
val = bcm63xx_int_cfg_readl(PCI_COMMAND);
val |= (PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER);
bcm63xx_int_cfg_writel(val, PCI_COMMAND);
/* enable read prefetching & disable byte swapping for bus
* mastering transfers */
val = bcm_mpi_readl(MPI_PCIMODESEL_REG);
val &= ~MPI_PCIMODESEL_BAR1_NOSWAP_MASK;
val &= ~MPI_PCIMODESEL_BAR2_NOSWAP_MASK;
val &= ~MPI_PCIMODESEL_PREFETCH_MASK;
val |= (8 << MPI_PCIMODESEL_PREFETCH_SHIFT);
bcm_mpi_writel(val, MPI_PCIMODESEL_REG);
/* enable pci interrupt */
val = bcm_mpi_readl(MPI_LOCINT_REG);
val |= MPI_LOCINT_MASK(MPI_LOCINT_EXT_PCI_INT);
bcm_mpi_writel(val, MPI_LOCINT_REG);
register_pci_controller(&bcm63xx_controller);
#ifdef CONFIG_CARDBUS
register_pci_controller(&bcm63xx_cb_controller);
#endif
/* mark memory space used for IO mapping as reserved */
request_mem_region(BCM_PCI_IO_BASE_PA, BCM_PCI_IO_SIZE,
"bcm63xx PCI IO space");
return 0;
}
static int __init bcm63xx_pci_init(void)
{
if (!bcm63xx_pci_enabled)
return -ENODEV;
switch (bcm63xx_get_cpu_id()) {
case BCM6328_CPU_ID:
case BCM6362_CPU_ID:
return bcm63xx_register_pcie();
case BCM3368_CPU_ID:
case BCM6348_CPU_ID:
case BCM6358_CPU_ID:
case BCM6368_CPU_ID:
return bcm63xx_register_pci();
default:
return -ENODEV;
}
}
arch_initcall(bcm63xx_pci_init);
| gpl-2.0 |
CyanogenMod/android_kernel_motorola_ghost | drivers/net/virtio_net.c | 2611 | 32403 | /* A network driver using virtio.
*
* Copyright 2007 Rusty Russell <rusty@rustcorp.com.au> IBM Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
//#define DEBUG
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/module.h>
#include <linux/virtio.h>
#include <linux/virtio_net.h>
#include <linux/scatterlist.h>
#include <linux/if_vlan.h>
#include <linux/slab.h>
static int napi_weight = 128;
module_param(napi_weight, int, 0444);
static bool csum = true, gso = true;
module_param(csum, bool, 0444);
module_param(gso, bool, 0444);
/* FIXME: MTU in config. */
#define MAX_PACKET_LEN (ETH_HLEN + VLAN_HLEN + ETH_DATA_LEN)
#define GOOD_COPY_LEN 128
#define VIRTNET_SEND_COMMAND_SG_MAX 2
#define VIRTNET_DRIVER_VERSION "1.0.0"
struct virtnet_stats {
struct u64_stats_sync syncp;
u64 tx_bytes;
u64 tx_packets;
u64 rx_bytes;
u64 rx_packets;
};
struct virtnet_info {
struct virtio_device *vdev;
struct virtqueue *rvq, *svq, *cvq;
struct net_device *dev;
struct napi_struct napi;
unsigned int status;
/* Number of input buffers, and max we've ever had. */
unsigned int num, max;
/* I like... big packets and I cannot lie! */
bool big_packets;
/* Host will merge rx buffers for big packets (shake it! shake it!) */
bool mergeable_rx_bufs;
/* Active statistics */
struct virtnet_stats __percpu *stats;
/* Work struct for refilling if we run low on memory. */
struct delayed_work refill;
/* Chain pages by the private ptr. */
struct page *pages;
/* fragments + linear part + virtio header */
struct scatterlist rx_sg[MAX_SKB_FRAGS + 2];
struct scatterlist tx_sg[MAX_SKB_FRAGS + 2];
};
struct skb_vnet_hdr {
union {
struct virtio_net_hdr hdr;
struct virtio_net_hdr_mrg_rxbuf mhdr;
};
unsigned int num_sg;
};
struct padded_vnet_hdr {
struct virtio_net_hdr hdr;
/*
* virtio_net_hdr should be in a separated sg buffer because of a
* QEMU bug, and data sg buffer shares same page with this header sg.
* This padding makes next sg 16 byte aligned after virtio_net_hdr.
*/
char padding[6];
};
static inline struct skb_vnet_hdr *skb_vnet_hdr(struct sk_buff *skb)
{
return (struct skb_vnet_hdr *)skb->cb;
}
/*
* private is used to chain pages for big packets, put the whole
* most recent used list in the beginning for reuse
*/
static void give_pages(struct virtnet_info *vi, struct page *page)
{
struct page *end;
/* Find end of list, sew whole thing into vi->pages. */
for (end = page; end->private; end = (struct page *)end->private);
end->private = (unsigned long)vi->pages;
vi->pages = page;
}
static struct page *get_a_page(struct virtnet_info *vi, gfp_t gfp_mask)
{
struct page *p = vi->pages;
if (p) {
vi->pages = (struct page *)p->private;
/* clear private here, it is used to chain pages */
p->private = 0;
} else
p = alloc_page(gfp_mask);
return p;
}
static void skb_xmit_done(struct virtqueue *svq)
{
struct virtnet_info *vi = svq->vdev->priv;
/* Suppress further interrupts. */
virtqueue_disable_cb(svq);
/* We were probably waiting for more output buffers. */
netif_wake_queue(vi->dev);
}
static void set_skb_frag(struct sk_buff *skb, struct page *page,
unsigned int offset, unsigned int *len)
{
int size = min((unsigned)PAGE_SIZE - offset, *len);
int i = skb_shinfo(skb)->nr_frags;
__skb_fill_page_desc(skb, i, page, offset, size);
skb->data_len += size;
skb->len += size;
skb->truesize += PAGE_SIZE;
skb_shinfo(skb)->nr_frags++;
*len -= size;
}
/* Called from bottom half context */
static struct sk_buff *page_to_skb(struct virtnet_info *vi,
struct page *page, unsigned int len)
{
struct sk_buff *skb;
struct skb_vnet_hdr *hdr;
unsigned int copy, hdr_len, offset;
char *p;
p = page_address(page);
/* copy small packet so we can reuse these pages for small data */
skb = netdev_alloc_skb_ip_align(vi->dev, GOOD_COPY_LEN);
if (unlikely(!skb))
return NULL;
hdr = skb_vnet_hdr(skb);
if (vi->mergeable_rx_bufs) {
hdr_len = sizeof hdr->mhdr;
offset = hdr_len;
} else {
hdr_len = sizeof hdr->hdr;
offset = sizeof(struct padded_vnet_hdr);
}
memcpy(hdr, p, hdr_len);
len -= hdr_len;
p += offset;
copy = len;
if (copy > skb_tailroom(skb))
copy = skb_tailroom(skb);
memcpy(skb_put(skb, copy), p, copy);
len -= copy;
offset += copy;
/*
* Verify that we can indeed put this data into a skb.
* This is here to handle cases when the device erroneously
* tries to receive more than is possible. This is usually
* the case of a broken device.
*/
if (unlikely(len > MAX_SKB_FRAGS * PAGE_SIZE)) {
if (net_ratelimit())
pr_debug("%s: too much data\n", skb->dev->name);
dev_kfree_skb(skb);
return NULL;
}
while (len) {
set_skb_frag(skb, page, offset, &len);
page = (struct page *)page->private;
offset = 0;
}
if (page)
give_pages(vi, page);
return skb;
}
static int receive_mergeable(struct virtnet_info *vi, struct sk_buff *skb)
{
struct skb_vnet_hdr *hdr = skb_vnet_hdr(skb);
struct page *page;
int num_buf, i, len;
num_buf = hdr->mhdr.num_buffers;
while (--num_buf) {
i = skb_shinfo(skb)->nr_frags;
if (i >= MAX_SKB_FRAGS) {
pr_debug("%s: packet too long\n", skb->dev->name);
skb->dev->stats.rx_length_errors++;
return -EINVAL;
}
page = virtqueue_get_buf(vi->rvq, &len);
if (!page) {
pr_debug("%s: rx error: %d buffers missing\n",
skb->dev->name, hdr->mhdr.num_buffers);
skb->dev->stats.rx_length_errors++;
return -EINVAL;
}
if (len > PAGE_SIZE)
len = PAGE_SIZE;
set_skb_frag(skb, page, 0, &len);
--vi->num;
}
return 0;
}
static void receive_buf(struct net_device *dev, void *buf, unsigned int len)
{
struct virtnet_info *vi = netdev_priv(dev);
struct virtnet_stats *stats = this_cpu_ptr(vi->stats);
struct sk_buff *skb;
struct page *page;
struct skb_vnet_hdr *hdr;
if (unlikely(len < sizeof(struct virtio_net_hdr) + ETH_HLEN)) {
pr_debug("%s: short packet %i\n", dev->name, len);
dev->stats.rx_length_errors++;
if (vi->mergeable_rx_bufs || vi->big_packets)
give_pages(vi, buf);
else
dev_kfree_skb(buf);
return;
}
if (!vi->mergeable_rx_bufs && !vi->big_packets) {
skb = buf;
len -= sizeof(struct virtio_net_hdr);
skb_trim(skb, len);
} else {
page = buf;
skb = page_to_skb(vi, page, len);
if (unlikely(!skb)) {
dev->stats.rx_dropped++;
give_pages(vi, page);
return;
}
if (vi->mergeable_rx_bufs)
if (receive_mergeable(vi, skb)) {
dev_kfree_skb(skb);
return;
}
}
hdr = skb_vnet_hdr(skb);
u64_stats_update_begin(&stats->syncp);
stats->rx_bytes += skb->len;
stats->rx_packets++;
u64_stats_update_end(&stats->syncp);
if (hdr->hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
pr_debug("Needs csum!\n");
if (!skb_partial_csum_set(skb,
hdr->hdr.csum_start,
hdr->hdr.csum_offset))
goto frame_err;
} else if (hdr->hdr.flags & VIRTIO_NET_HDR_F_DATA_VALID) {
skb->ip_summed = CHECKSUM_UNNECESSARY;
}
skb->protocol = eth_type_trans(skb, dev);
pr_debug("Receiving skb proto 0x%04x len %i type %i\n",
ntohs(skb->protocol), skb->len, skb->pkt_type);
if (hdr->hdr.gso_type != VIRTIO_NET_HDR_GSO_NONE) {
pr_debug("GSO!\n");
switch (hdr->hdr.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
case VIRTIO_NET_HDR_GSO_TCPV4:
skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
break;
case VIRTIO_NET_HDR_GSO_UDP:
skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
break;
case VIRTIO_NET_HDR_GSO_TCPV6:
skb_shinfo(skb)->gso_type = SKB_GSO_TCPV6;
break;
default:
if (net_ratelimit())
printk(KERN_WARNING "%s: bad gso type %u.\n",
dev->name, hdr->hdr.gso_type);
goto frame_err;
}
if (hdr->hdr.gso_type & VIRTIO_NET_HDR_GSO_ECN)
skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN;
skb_shinfo(skb)->gso_size = hdr->hdr.gso_size;
if (skb_shinfo(skb)->gso_size == 0) {
if (net_ratelimit())
printk(KERN_WARNING "%s: zero gso size.\n",
dev->name);
goto frame_err;
}
/* Header must be checked, and gso_segs computed. */
skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
skb_shinfo(skb)->gso_segs = 0;
}
netif_receive_skb(skb);
return;
frame_err:
dev->stats.rx_frame_errors++;
dev_kfree_skb(skb);
}
static int add_recvbuf_small(struct virtnet_info *vi, gfp_t gfp)
{
struct sk_buff *skb;
struct skb_vnet_hdr *hdr;
int err;
skb = __netdev_alloc_skb_ip_align(vi->dev, MAX_PACKET_LEN, gfp);
if (unlikely(!skb))
return -ENOMEM;
skb_put(skb, MAX_PACKET_LEN);
hdr = skb_vnet_hdr(skb);
sg_set_buf(vi->rx_sg, &hdr->hdr, sizeof hdr->hdr);
skb_to_sgvec(skb, vi->rx_sg + 1, 0, skb->len);
err = virtqueue_add_buf(vi->rvq, vi->rx_sg, 0, 2, skb, gfp);
if (err < 0)
dev_kfree_skb(skb);
return err;
}
static int add_recvbuf_big(struct virtnet_info *vi, gfp_t gfp)
{
struct page *first, *list = NULL;
char *p;
int i, err, offset;
/* page in vi->rx_sg[MAX_SKB_FRAGS + 1] is list tail */
for (i = MAX_SKB_FRAGS + 1; i > 1; --i) {
first = get_a_page(vi, gfp);
if (!first) {
if (list)
give_pages(vi, list);
return -ENOMEM;
}
sg_set_buf(&vi->rx_sg[i], page_address(first), PAGE_SIZE);
/* chain new page in list head to match sg */
first->private = (unsigned long)list;
list = first;
}
first = get_a_page(vi, gfp);
if (!first) {
give_pages(vi, list);
return -ENOMEM;
}
p = page_address(first);
/* vi->rx_sg[0], vi->rx_sg[1] share the same page */
/* a separated vi->rx_sg[0] for virtio_net_hdr only due to QEMU bug */
sg_set_buf(&vi->rx_sg[0], p, sizeof(struct virtio_net_hdr));
/* vi->rx_sg[1] for data packet, from offset */
offset = sizeof(struct padded_vnet_hdr);
sg_set_buf(&vi->rx_sg[1], p + offset, PAGE_SIZE - offset);
/* chain first in list head */
first->private = (unsigned long)list;
err = virtqueue_add_buf(vi->rvq, vi->rx_sg, 0, MAX_SKB_FRAGS + 2,
first, gfp);
if (err < 0)
give_pages(vi, first);
return err;
}
static int add_recvbuf_mergeable(struct virtnet_info *vi, gfp_t gfp)
{
struct page *page;
int err;
page = get_a_page(vi, gfp);
if (!page)
return -ENOMEM;
sg_init_one(vi->rx_sg, page_address(page), PAGE_SIZE);
err = virtqueue_add_buf(vi->rvq, vi->rx_sg, 0, 1, page, gfp);
if (err < 0)
give_pages(vi, page);
return err;
}
/*
* Returns false if we couldn't fill entirely (OOM).
*
* Normally run in the receive path, but can also be run from ndo_open
* before we're receiving packets, or from refill_work which is
* careful to disable receiving (using napi_disable).
*/
static bool try_fill_recv(struct virtnet_info *vi, gfp_t gfp)
{
int err;
bool oom;
do {
if (vi->mergeable_rx_bufs)
err = add_recvbuf_mergeable(vi, gfp);
else if (vi->big_packets)
err = add_recvbuf_big(vi, gfp);
else
err = add_recvbuf_small(vi, gfp);
oom = err == -ENOMEM;
if (err < 0)
break;
++vi->num;
} while (err > 0);
if (unlikely(vi->num > vi->max))
vi->max = vi->num;
virtqueue_kick(vi->rvq);
return !oom;
}
static void skb_recv_done(struct virtqueue *rvq)
{
struct virtnet_info *vi = rvq->vdev->priv;
/* Schedule NAPI, Suppress further interrupts if successful. */
if (napi_schedule_prep(&vi->napi)) {
virtqueue_disable_cb(rvq);
__napi_schedule(&vi->napi);
}
}
static void virtnet_napi_enable(struct virtnet_info *vi)
{
napi_enable(&vi->napi);
/* If all buffers were filled by other side before we napi_enabled, we
* won't get another interrupt, so process any outstanding packets
* now. virtnet_poll wants re-enable the queue, so we disable here.
* We synchronize against interrupts via NAPI_STATE_SCHED */
if (napi_schedule_prep(&vi->napi)) {
virtqueue_disable_cb(vi->rvq);
local_bh_disable();
__napi_schedule(&vi->napi);
local_bh_enable();
}
}
static void refill_work(struct work_struct *work)
{
struct virtnet_info *vi;
bool still_empty;
vi = container_of(work, struct virtnet_info, refill.work);
napi_disable(&vi->napi);
still_empty = !try_fill_recv(vi, GFP_KERNEL);
virtnet_napi_enable(vi);
/* In theory, this can happen: if we don't get any buffers in
* we will *never* try to fill again. */
if (still_empty)
queue_delayed_work(system_nrt_wq, &vi->refill, HZ/2);
}
static int virtnet_poll(struct napi_struct *napi, int budget)
{
struct virtnet_info *vi = container_of(napi, struct virtnet_info, napi);
void *buf;
unsigned int len, received = 0;
again:
while (received < budget &&
(buf = virtqueue_get_buf(vi->rvq, &len)) != NULL) {
receive_buf(vi->dev, buf, len);
--vi->num;
received++;
}
if (vi->num < vi->max / 2) {
if (!try_fill_recv(vi, GFP_ATOMIC))
queue_delayed_work(system_nrt_wq, &vi->refill, 0);
}
/* Out of packets? */
if (received < budget) {
napi_complete(napi);
if (unlikely(!virtqueue_enable_cb(vi->rvq)) &&
napi_schedule_prep(napi)) {
virtqueue_disable_cb(vi->rvq);
__napi_schedule(napi);
goto again;
}
}
return received;
}
static unsigned int free_old_xmit_skbs(struct virtnet_info *vi)
{
struct sk_buff *skb;
unsigned int len, tot_sgs = 0;
struct virtnet_stats *stats = this_cpu_ptr(vi->stats);
while ((skb = virtqueue_get_buf(vi->svq, &len)) != NULL) {
pr_debug("Sent skb %p\n", skb);
u64_stats_update_begin(&stats->syncp);
stats->tx_bytes += skb->len;
stats->tx_packets++;
u64_stats_update_end(&stats->syncp);
tot_sgs += skb_vnet_hdr(skb)->num_sg;
dev_kfree_skb_any(skb);
}
return tot_sgs;
}
static int xmit_skb(struct virtnet_info *vi, struct sk_buff *skb)
{
struct skb_vnet_hdr *hdr = skb_vnet_hdr(skb);
const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest;
pr_debug("%s: xmit %p %pM\n", vi->dev->name, skb, dest);
if (skb->ip_summed == CHECKSUM_PARTIAL) {
hdr->hdr.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
hdr->hdr.csum_start = skb_checksum_start_offset(skb);
hdr->hdr.csum_offset = skb->csum_offset;
} else {
hdr->hdr.flags = 0;
hdr->hdr.csum_offset = hdr->hdr.csum_start = 0;
}
if (skb_is_gso(skb)) {
hdr->hdr.hdr_len = skb_headlen(skb);
hdr->hdr.gso_size = skb_shinfo(skb)->gso_size;
if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4)
hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
else if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6)
hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
else if (skb_shinfo(skb)->gso_type & SKB_GSO_UDP)
hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_UDP;
else
BUG();
if (skb_shinfo(skb)->gso_type & SKB_GSO_TCP_ECN)
hdr->hdr.gso_type |= VIRTIO_NET_HDR_GSO_ECN;
} else {
hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE;
hdr->hdr.gso_size = hdr->hdr.hdr_len = 0;
}
hdr->mhdr.num_buffers = 0;
/* Encode metadata header at front. */
if (vi->mergeable_rx_bufs)
sg_set_buf(vi->tx_sg, &hdr->mhdr, sizeof hdr->mhdr);
else
sg_set_buf(vi->tx_sg, &hdr->hdr, sizeof hdr->hdr);
hdr->num_sg = skb_to_sgvec(skb, vi->tx_sg + 1, 0, skb->len) + 1;
return virtqueue_add_buf(vi->svq, vi->tx_sg, hdr->num_sg,
0, skb, GFP_ATOMIC);
}
static netdev_tx_t start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct virtnet_info *vi = netdev_priv(dev);
int capacity;
/* Free up any pending old buffers before queueing new ones. */
free_old_xmit_skbs(vi);
/* Try to transmit */
capacity = xmit_skb(vi, skb);
/* This can happen with OOM and indirect buffers. */
if (unlikely(capacity < 0)) {
if (likely(capacity == -ENOMEM)) {
if (net_ratelimit())
dev_warn(&dev->dev,
"TX queue failure: out of memory\n");
} else {
dev->stats.tx_fifo_errors++;
if (net_ratelimit())
dev_warn(&dev->dev,
"Unexpected TX queue failure: %d\n",
capacity);
}
dev->stats.tx_dropped++;
kfree_skb(skb);
return NETDEV_TX_OK;
}
virtqueue_kick(vi->svq);
/* Don't wait up for transmitted skbs to be freed. */
skb_orphan(skb);
nf_reset(skb);
/* Apparently nice girls don't return TX_BUSY; stop the queue
* before it gets out of hand. Naturally, this wastes entries. */
if (capacity < 2+MAX_SKB_FRAGS) {
netif_stop_queue(dev);
if (unlikely(!virtqueue_enable_cb_delayed(vi->svq))) {
/* More just got used, free them then recheck. */
capacity += free_old_xmit_skbs(vi);
if (capacity >= 2+MAX_SKB_FRAGS) {
netif_start_queue(dev);
virtqueue_disable_cb(vi->svq);
}
}
}
return NETDEV_TX_OK;
}
static int virtnet_set_mac_address(struct net_device *dev, void *p)
{
struct virtnet_info *vi = netdev_priv(dev);
struct virtio_device *vdev = vi->vdev;
int ret;
ret = eth_mac_addr(dev, p);
if (ret)
return ret;
if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC))
vdev->config->set(vdev, offsetof(struct virtio_net_config, mac),
dev->dev_addr, dev->addr_len);
return 0;
}
static struct rtnl_link_stats64 *virtnet_stats(struct net_device *dev,
struct rtnl_link_stats64 *tot)
{
struct virtnet_info *vi = netdev_priv(dev);
int cpu;
unsigned int start;
for_each_possible_cpu(cpu) {
struct virtnet_stats *stats = per_cpu_ptr(vi->stats, cpu);
u64 tpackets, tbytes, rpackets, rbytes;
do {
start = u64_stats_fetch_begin(&stats->syncp);
tpackets = stats->tx_packets;
tbytes = stats->tx_bytes;
rpackets = stats->rx_packets;
rbytes = stats->rx_bytes;
} while (u64_stats_fetch_retry(&stats->syncp, start));
tot->rx_packets += rpackets;
tot->tx_packets += tpackets;
tot->rx_bytes += rbytes;
tot->tx_bytes += tbytes;
}
tot->tx_dropped = dev->stats.tx_dropped;
tot->tx_fifo_errors = dev->stats.tx_fifo_errors;
tot->rx_dropped = dev->stats.rx_dropped;
tot->rx_length_errors = dev->stats.rx_length_errors;
tot->rx_frame_errors = dev->stats.rx_frame_errors;
return tot;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void virtnet_netpoll(struct net_device *dev)
{
struct virtnet_info *vi = netdev_priv(dev);
napi_schedule(&vi->napi);
}
#endif
static int virtnet_open(struct net_device *dev)
{
struct virtnet_info *vi = netdev_priv(dev);
/* Make sure we have some buffers: if oom use wq. */
if (!try_fill_recv(vi, GFP_KERNEL))
queue_delayed_work(system_nrt_wq, &vi->refill, 0);
virtnet_napi_enable(vi);
return 0;
}
/*
* Send command via the control virtqueue and check status. Commands
* supported by the hypervisor, as indicated by feature bits, should
* never fail unless improperly formated.
*/
static bool virtnet_send_command(struct virtnet_info *vi, u8 class, u8 cmd,
struct scatterlist *data, int out, int in)
{
struct scatterlist *s, sg[VIRTNET_SEND_COMMAND_SG_MAX + 2];
struct virtio_net_ctrl_hdr ctrl;
virtio_net_ctrl_ack status = ~0;
unsigned int tmp;
int i;
/* Caller should know better */
BUG_ON(!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ) ||
(out + in > VIRTNET_SEND_COMMAND_SG_MAX));
out++; /* Add header */
in++; /* Add return status */
ctrl.class = class;
ctrl.cmd = cmd;
sg_init_table(sg, out + in);
sg_set_buf(&sg[0], &ctrl, sizeof(ctrl));
for_each_sg(data, s, out + in - 2, i)
sg_set_buf(&sg[i + 1], sg_virt(s), s->length);
sg_set_buf(&sg[out + in - 1], &status, sizeof(status));
BUG_ON(virtqueue_add_buf(vi->cvq, sg, out, in, vi, GFP_ATOMIC) < 0);
virtqueue_kick(vi->cvq);
/*
* Spin for a response, the kick causes an ioport write, trapping
* into the hypervisor, so the request should be handled immediately.
*/
while (!virtqueue_get_buf(vi->cvq, &tmp))
cpu_relax();
return status == VIRTIO_NET_OK;
}
static int virtnet_close(struct net_device *dev)
{
struct virtnet_info *vi = netdev_priv(dev);
/* Make sure refill_work doesn't re-enable napi! */
cancel_delayed_work_sync(&vi->refill);
napi_disable(&vi->napi);
return 0;
}
static void virtnet_set_rx_mode(struct net_device *dev)
{
struct virtnet_info *vi = netdev_priv(dev);
struct scatterlist sg[2];
u8 promisc, allmulti;
struct virtio_net_ctrl_mac *mac_data;
struct netdev_hw_addr *ha;
int uc_count;
int mc_count;
void *buf;
int i;
/* We can't dynamicaly set ndo_set_rx_mode, so return gracefully */
if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_RX))
return;
promisc = ((dev->flags & IFF_PROMISC) != 0);
allmulti = ((dev->flags & IFF_ALLMULTI) != 0);
sg_init_one(sg, &promisc, sizeof(promisc));
if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
VIRTIO_NET_CTRL_RX_PROMISC,
sg, 1, 0))
dev_warn(&dev->dev, "Failed to %sable promisc mode.\n",
promisc ? "en" : "dis");
sg_init_one(sg, &allmulti, sizeof(allmulti));
if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
VIRTIO_NET_CTRL_RX_ALLMULTI,
sg, 1, 0))
dev_warn(&dev->dev, "Failed to %sable allmulti mode.\n",
allmulti ? "en" : "dis");
uc_count = netdev_uc_count(dev);
mc_count = netdev_mc_count(dev);
/* MAC filter - use one buffer for both lists */
buf = kzalloc(((uc_count + mc_count) * ETH_ALEN) +
(2 * sizeof(mac_data->entries)), GFP_ATOMIC);
mac_data = buf;
if (!buf) {
dev_warn(&dev->dev, "No memory for MAC address buffer\n");
return;
}
sg_init_table(sg, 2);
/* Store the unicast list and count in the front of the buffer */
mac_data->entries = uc_count;
i = 0;
netdev_for_each_uc_addr(ha, dev)
memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
sg_set_buf(&sg[0], mac_data,
sizeof(mac_data->entries) + (uc_count * ETH_ALEN));
/* multicast list and count fill the end */
mac_data = (void *)&mac_data->macs[uc_count][0];
mac_data->entries = mc_count;
i = 0;
netdev_for_each_mc_addr(ha, dev)
memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
sg_set_buf(&sg[1], mac_data,
sizeof(mac_data->entries) + (mc_count * ETH_ALEN));
if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
VIRTIO_NET_CTRL_MAC_TABLE_SET,
sg, 2, 0))
dev_warn(&dev->dev, "Failed to set MAC fitler table.\n");
kfree(buf);
}
static int virtnet_vlan_rx_add_vid(struct net_device *dev, u16 vid)
{
struct virtnet_info *vi = netdev_priv(dev);
struct scatterlist sg;
sg_init_one(&sg, &vid, sizeof(vid));
if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
VIRTIO_NET_CTRL_VLAN_ADD, &sg, 1, 0))
dev_warn(&dev->dev, "Failed to add VLAN ID %d.\n", vid);
return 0;
}
static int virtnet_vlan_rx_kill_vid(struct net_device *dev, u16 vid)
{
struct virtnet_info *vi = netdev_priv(dev);
struct scatterlist sg;
sg_init_one(&sg, &vid, sizeof(vid));
if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
VIRTIO_NET_CTRL_VLAN_DEL, &sg, 1, 0))
dev_warn(&dev->dev, "Failed to kill VLAN ID %d.\n", vid);
return 0;
}
static void virtnet_get_ringparam(struct net_device *dev,
struct ethtool_ringparam *ring)
{
struct virtnet_info *vi = netdev_priv(dev);
ring->rx_max_pending = virtqueue_get_impl_size(vi->rvq);
ring->tx_max_pending = virtqueue_get_impl_size(vi->svq);
ring->rx_pending = ring->rx_max_pending;
ring->tx_pending = ring->tx_max_pending;
}
static void virtnet_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
struct virtnet_info *vi = netdev_priv(dev);
struct virtio_device *vdev = vi->vdev;
strlcpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
strlcpy(info->version, VIRTNET_DRIVER_VERSION, sizeof(info->version));
strlcpy(info->bus_info, virtio_bus_name(vdev), sizeof(info->bus_info));
}
static const struct ethtool_ops virtnet_ethtool_ops = {
.get_drvinfo = virtnet_get_drvinfo,
.get_link = ethtool_op_get_link,
.get_ringparam = virtnet_get_ringparam,
};
#define MIN_MTU 68
#define MAX_MTU 65535
static int virtnet_change_mtu(struct net_device *dev, int new_mtu)
{
if (new_mtu < MIN_MTU || new_mtu > MAX_MTU)
return -EINVAL;
dev->mtu = new_mtu;
return 0;
}
static const struct net_device_ops virtnet_netdev = {
.ndo_open = virtnet_open,
.ndo_stop = virtnet_close,
.ndo_start_xmit = start_xmit,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = virtnet_set_mac_address,
.ndo_set_rx_mode = virtnet_set_rx_mode,
.ndo_change_mtu = virtnet_change_mtu,
.ndo_get_stats64 = virtnet_stats,
.ndo_vlan_rx_add_vid = virtnet_vlan_rx_add_vid,
.ndo_vlan_rx_kill_vid = virtnet_vlan_rx_kill_vid,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = virtnet_netpoll,
#endif
};
static void virtnet_update_status(struct virtnet_info *vi)
{
u16 v;
if (virtio_config_val(vi->vdev, VIRTIO_NET_F_STATUS,
offsetof(struct virtio_net_config, status),
&v) < 0)
return;
/* Ignore unknown (future) status bits */
v &= VIRTIO_NET_S_LINK_UP;
if (vi->status == v)
return;
vi->status = v;
if (vi->status & VIRTIO_NET_S_LINK_UP) {
netif_carrier_on(vi->dev);
netif_wake_queue(vi->dev);
} else {
netif_carrier_off(vi->dev);
netif_stop_queue(vi->dev);
}
}
static void virtnet_config_changed(struct virtio_device *vdev)
{
struct virtnet_info *vi = vdev->priv;
virtnet_update_status(vi);
}
static int init_vqs(struct virtnet_info *vi)
{
struct virtqueue *vqs[3];
vq_callback_t *callbacks[] = { skb_recv_done, skb_xmit_done, NULL};
const char *names[] = { "input", "output", "control" };
int nvqs, err;
/* We expect two virtqueues, receive then send,
* and optionally control. */
nvqs = virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ) ? 3 : 2;
err = vi->vdev->config->find_vqs(vi->vdev, nvqs, vqs, callbacks, names);
if (err)
return err;
vi->rvq = vqs[0];
vi->svq = vqs[1];
if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ)) {
vi->cvq = vqs[2];
if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VLAN))
vi->dev->features |= NETIF_F_HW_VLAN_FILTER;
}
return 0;
}
static int virtnet_probe(struct virtio_device *vdev)
{
int err;
struct net_device *dev;
struct virtnet_info *vi;
/* Allocate ourselves a network device with room for our info */
dev = alloc_etherdev(sizeof(struct virtnet_info));
if (!dev)
return -ENOMEM;
/* Set up network device as normal. */
dev->priv_flags |= IFF_UNICAST_FLT;
dev->netdev_ops = &virtnet_netdev;
dev->features = NETIF_F_HIGHDMA;
SET_ETHTOOL_OPS(dev, &virtnet_ethtool_ops);
SET_NETDEV_DEV(dev, &vdev->dev);
/* Do we support "hardware" checksums? */
if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
/* This opens up the world of extra features. */
dev->hw_features |= NETIF_F_HW_CSUM|NETIF_F_SG|NETIF_F_FRAGLIST;
if (csum)
dev->features |= NETIF_F_HW_CSUM|NETIF_F_SG|NETIF_F_FRAGLIST;
if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
dev->hw_features |= NETIF_F_TSO | NETIF_F_UFO
| NETIF_F_TSO_ECN | NETIF_F_TSO6;
}
/* Individual feature bits: what can host handle? */
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
dev->hw_features |= NETIF_F_TSO;
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
dev->hw_features |= NETIF_F_TSO6;
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
dev->hw_features |= NETIF_F_TSO_ECN;
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_UFO))
dev->hw_features |= NETIF_F_UFO;
if (gso)
dev->features |= dev->hw_features & (NETIF_F_ALL_TSO|NETIF_F_UFO);
/* (!csum && gso) case will be fixed by register_netdev() */
}
/* Configuration may specify what MAC to use. Otherwise random. */
if (virtio_config_val_len(vdev, VIRTIO_NET_F_MAC,
offsetof(struct virtio_net_config, mac),
dev->dev_addr, dev->addr_len) < 0)
eth_hw_addr_random(dev);
/* Set up our device-specific information */
vi = netdev_priv(dev);
netif_napi_add(dev, &vi->napi, virtnet_poll, napi_weight);
vi->dev = dev;
vi->vdev = vdev;
vdev->priv = vi;
vi->pages = NULL;
vi->stats = alloc_percpu(struct virtnet_stats);
err = -ENOMEM;
if (vi->stats == NULL)
goto free;
INIT_DELAYED_WORK(&vi->refill, refill_work);
sg_init_table(vi->rx_sg, ARRAY_SIZE(vi->rx_sg));
sg_init_table(vi->tx_sg, ARRAY_SIZE(vi->tx_sg));
/* If we can receive ANY GSO packets, we must allocate large ones. */
if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6) ||
virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_ECN))
vi->big_packets = true;
if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF))
vi->mergeable_rx_bufs = true;
err = init_vqs(vi);
if (err)
goto free_stats;
err = register_netdev(dev);
if (err) {
pr_debug("virtio_net: registering device failed\n");
goto free_vqs;
}
/* Last of all, set up some receive buffers. */
try_fill_recv(vi, GFP_KERNEL);
/* If we didn't even get one input buffer, we're useless. */
if (vi->num == 0) {
err = -ENOMEM;
goto unregister;
}
/* Assume link up if device can't report link status,
otherwise get link status from config. */
if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
netif_carrier_off(dev);
virtnet_update_status(vi);
} else {
vi->status = VIRTIO_NET_S_LINK_UP;
netif_carrier_on(dev);
}
pr_debug("virtnet: registered device %s\n", dev->name);
return 0;
unregister:
unregister_netdev(dev);
free_vqs:
vdev->config->del_vqs(vdev);
free_stats:
free_percpu(vi->stats);
free:
free_netdev(dev);
return err;
}
static void free_unused_bufs(struct virtnet_info *vi)
{
void *buf;
while (1) {
buf = virtqueue_detach_unused_buf(vi->svq);
if (!buf)
break;
dev_kfree_skb(buf);
}
while (1) {
buf = virtqueue_detach_unused_buf(vi->rvq);
if (!buf)
break;
if (vi->mergeable_rx_bufs || vi->big_packets)
give_pages(vi, buf);
else
dev_kfree_skb(buf);
--vi->num;
}
BUG_ON(vi->num != 0);
}
static void remove_vq_common(struct virtnet_info *vi)
{
vi->vdev->config->reset(vi->vdev);
/* Free unused buffers in both send and recv, if any. */
free_unused_bufs(vi);
vi->vdev->config->del_vqs(vi->vdev);
while (vi->pages)
__free_pages(get_a_page(vi, GFP_KERNEL), 0);
}
static void __devexit virtnet_remove(struct virtio_device *vdev)
{
struct virtnet_info *vi = vdev->priv;
unregister_netdev(vi->dev);
remove_vq_common(vi);
free_percpu(vi->stats);
free_netdev(vi->dev);
}
#ifdef CONFIG_PM
static int virtnet_freeze(struct virtio_device *vdev)
{
struct virtnet_info *vi = vdev->priv;
virtqueue_disable_cb(vi->rvq);
virtqueue_disable_cb(vi->svq);
if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ))
virtqueue_disable_cb(vi->cvq);
netif_device_detach(vi->dev);
cancel_delayed_work_sync(&vi->refill);
if (netif_running(vi->dev))
napi_disable(&vi->napi);
remove_vq_common(vi);
return 0;
}
static int virtnet_restore(struct virtio_device *vdev)
{
struct virtnet_info *vi = vdev->priv;
int err;
err = init_vqs(vi);
if (err)
return err;
if (netif_running(vi->dev))
virtnet_napi_enable(vi);
netif_device_attach(vi->dev);
if (!try_fill_recv(vi, GFP_KERNEL))
queue_delayed_work(system_nrt_wq, &vi->refill, 0);
return 0;
}
#endif
static struct virtio_device_id id_table[] = {
{ VIRTIO_ID_NET, VIRTIO_DEV_ANY_ID },
{ 0 },
};
static unsigned int features[] = {
VIRTIO_NET_F_CSUM, VIRTIO_NET_F_GUEST_CSUM,
VIRTIO_NET_F_GSO, VIRTIO_NET_F_MAC,
VIRTIO_NET_F_HOST_TSO4, VIRTIO_NET_F_HOST_UFO, VIRTIO_NET_F_HOST_TSO6,
VIRTIO_NET_F_HOST_ECN, VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6,
VIRTIO_NET_F_GUEST_ECN, VIRTIO_NET_F_GUEST_UFO,
VIRTIO_NET_F_MRG_RXBUF, VIRTIO_NET_F_STATUS, VIRTIO_NET_F_CTRL_VQ,
VIRTIO_NET_F_CTRL_RX, VIRTIO_NET_F_CTRL_VLAN,
};
static struct virtio_driver virtio_net_driver = {
.feature_table = features,
.feature_table_size = ARRAY_SIZE(features),
.driver.name = KBUILD_MODNAME,
.driver.owner = THIS_MODULE,
.id_table = id_table,
.probe = virtnet_probe,
.remove = __devexit_p(virtnet_remove),
.config_changed = virtnet_config_changed,
#ifdef CONFIG_PM
.freeze = virtnet_freeze,
.restore = virtnet_restore,
#endif
};
static int __init init(void)
{
return register_virtio_driver(&virtio_net_driver);
}
static void __exit fini(void)
{
unregister_virtio_driver(&virtio_net_driver);
}
module_init(init);
module_exit(fini);
MODULE_DEVICE_TABLE(virtio, id_table);
MODULE_DESCRIPTION("Virtio network driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
templetontsai/nexus7-grouper-kernel | drivers/net/wireless/at76c50x-usb.c | 2867 | 70438 | /*
* at76c503/at76c505 USB driver
*
* Copyright (c) 2002 - 2003 Oliver Kurth
* Copyright (c) 2004 Joerg Albert <joerg.albert@gmx.de>
* Copyright (c) 2004 Nick Jones
* Copyright (c) 2004 Balint Seeber <n0_5p4m_p13453@hotmail.com>
* Copyright (c) 2007 Guido Guenther <agx@sigxcpu.org>
* Copyright (c) 2007 Kalle Valo <kalle.valo@iki.fi>
* Copyright (c) 2010 Sebastian Smolorz <sesmo@gmx.net>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This file is part of the Berlios driver for WLAN USB devices based on the
* Atmel AT76C503A/505/505A.
*
* Some iw_handler code was taken from airo.c, (C) 1999 Benjamin Reed
*
* TODO list is at the wiki:
*
* http://wireless.kernel.org/en/users/Drivers/at76c50x-usb#TODO
*
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/list.h>
#include <linux/usb.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/wireless.h>
#include <net/iw_handler.h>
#include <net/ieee80211_radiotap.h>
#include <linux/firmware.h>
#include <linux/leds.h>
#include <net/mac80211.h>
#include "at76c50x-usb.h"
/* Version information */
#define DRIVER_NAME "at76c50x-usb"
#define DRIVER_VERSION "0.17"
#define DRIVER_DESC "Atmel at76x USB Wireless LAN Driver"
/* at76_debug bits */
#define DBG_PROGRESS 0x00000001 /* authentication/accociation */
#define DBG_BSS_TABLE 0x00000002 /* show BSS table after scans */
#define DBG_IOCTL 0x00000004 /* ioctl calls / settings */
#define DBG_MAC_STATE 0x00000008 /* MAC state transitions */
#define DBG_TX_DATA 0x00000010 /* tx header */
#define DBG_TX_DATA_CONTENT 0x00000020 /* tx content */
#define DBG_TX_MGMT 0x00000040 /* tx management */
#define DBG_RX_DATA 0x00000080 /* rx data header */
#define DBG_RX_DATA_CONTENT 0x00000100 /* rx data content */
#define DBG_RX_MGMT 0x00000200 /* rx mgmt frame headers */
#define DBG_RX_BEACON 0x00000400 /* rx beacon */
#define DBG_RX_CTRL 0x00000800 /* rx control */
#define DBG_RX_MGMT_CONTENT 0x00001000 /* rx mgmt content */
#define DBG_RX_FRAGS 0x00002000 /* rx data fragment handling */
#define DBG_DEVSTART 0x00004000 /* fw download, device start */
#define DBG_URB 0x00008000 /* rx urb status, ... */
#define DBG_RX_ATMEL_HDR 0x00010000 /* Atmel-specific Rx headers */
#define DBG_PROC_ENTRY 0x00020000 /* procedure entries/exits */
#define DBG_PM 0x00040000 /* power management settings */
#define DBG_BSS_MATCH 0x00080000 /* BSS match failures */
#define DBG_PARAMS 0x00100000 /* show configured parameters */
#define DBG_WAIT_COMPLETE 0x00200000 /* command completion */
#define DBG_RX_FRAGS_SKB 0x00400000 /* skb header of Rx fragments */
#define DBG_BSS_TABLE_RM 0x00800000 /* purging bss table entries */
#define DBG_MONITOR_MODE 0x01000000 /* monitor mode */
#define DBG_MIB 0x02000000 /* dump all MIBs on startup */
#define DBG_MGMT_TIMER 0x04000000 /* dump mgmt_timer ops */
#define DBG_WE_EVENTS 0x08000000 /* dump wireless events */
#define DBG_FW 0x10000000 /* firmware download */
#define DBG_DFU 0x20000000 /* device firmware upgrade */
#define DBG_CMD 0x40000000
#define DBG_MAC80211 0x80000000
#define DBG_DEFAULTS 0
/* Use our own dbg macro */
#define at76_dbg(bits, format, arg...) \
do { \
if (at76_debug & (bits)) \
printk(KERN_DEBUG DRIVER_NAME ": " format "\n", ##arg); \
} while (0)
#define at76_dbg_dump(bits, buf, len, format, arg...) \
do { \
if (at76_debug & (bits)) { \
printk(KERN_DEBUG DRIVER_NAME ": " format "\n", ##arg); \
print_hex_dump_bytes("", DUMP_PREFIX_OFFSET, buf, len); \
} \
} while (0)
static uint at76_debug = DBG_DEFAULTS;
/* Protect against concurrent firmware loading and parsing */
static struct mutex fw_mutex;
static struct fwentry firmwares[] = {
[0] = { "" },
[BOARD_503_ISL3861] = { "atmel_at76c503-i3861.bin" },
[BOARD_503_ISL3863] = { "atmel_at76c503-i3863.bin" },
[BOARD_503] = { "atmel_at76c503-rfmd.bin" },
[BOARD_503_ACC] = { "atmel_at76c503-rfmd-acc.bin" },
[BOARD_505] = { "atmel_at76c505-rfmd.bin" },
[BOARD_505_2958] = { "atmel_at76c505-rfmd2958.bin" },
[BOARD_505A] = { "atmel_at76c505a-rfmd2958.bin" },
[BOARD_505AMX] = { "atmel_at76c505amx-rfmd.bin" },
};
MODULE_FIRMWARE("atmel_at76c503-i3861.bin");
MODULE_FIRMWARE("atmel_at76c503-i3863.bin");
MODULE_FIRMWARE("atmel_at76c503-rfmd.bin");
MODULE_FIRMWARE("atmel_at76c503-rfmd-acc.bin");
MODULE_FIRMWARE("atmel_at76c505-rfmd.bin");
MODULE_FIRMWARE("atmel_at76c505-rfmd2958.bin");
MODULE_FIRMWARE("atmel_at76c505a-rfmd2958.bin");
MODULE_FIRMWARE("atmel_at76c505amx-rfmd.bin");
#define USB_DEVICE_DATA(__ops) .driver_info = (kernel_ulong_t)(__ops)
static struct usb_device_id dev_table[] = {
/*
* at76c503-i3861
*/
/* Generic AT76C503/3861 device */
{ USB_DEVICE(0x03eb, 0x7603), USB_DEVICE_DATA(BOARD_503_ISL3861) },
/* Linksys WUSB11 v2.1/v2.6 */
{ USB_DEVICE(0x066b, 0x2211), USB_DEVICE_DATA(BOARD_503_ISL3861) },
/* Netgear MA101 rev. A */
{ USB_DEVICE(0x0864, 0x4100), USB_DEVICE_DATA(BOARD_503_ISL3861) },
/* Tekram U300C / Allnet ALL0193 */
{ USB_DEVICE(0x0b3b, 0x1612), USB_DEVICE_DATA(BOARD_503_ISL3861) },
/* HP HN210W J7801A */
{ USB_DEVICE(0x03f0, 0x011c), USB_DEVICE_DATA(BOARD_503_ISL3861) },
/* Sitecom/Z-Com/Zyxel M4Y-750 */
{ USB_DEVICE(0x0cde, 0x0001), USB_DEVICE_DATA(BOARD_503_ISL3861) },
/* Dynalink/Askey WLL013 (intersil) */
{ USB_DEVICE(0x069a, 0x0320), USB_DEVICE_DATA(BOARD_503_ISL3861) },
/* EZ connect 11Mpbs Wireless USB Adapter SMC2662W v1 */
{ USB_DEVICE(0x0d5c, 0xa001), USB_DEVICE_DATA(BOARD_503_ISL3861) },
/* BenQ AWL300 */
{ USB_DEVICE(0x04a5, 0x9000), USB_DEVICE_DATA(BOARD_503_ISL3861) },
/* Addtron AWU-120, Compex WLU11 */
{ USB_DEVICE(0x05dd, 0xff31), USB_DEVICE_DATA(BOARD_503_ISL3861) },
/* Intel AP310 AnyPoint II USB */
{ USB_DEVICE(0x8086, 0x0200), USB_DEVICE_DATA(BOARD_503_ISL3861) },
/* Dynalink L11U */
{ USB_DEVICE(0x0d8e, 0x7100), USB_DEVICE_DATA(BOARD_503_ISL3861) },
/* Arescom WL-210, FCC id 07J-GL2411USB */
{ USB_DEVICE(0x0d8e, 0x7110), USB_DEVICE_DATA(BOARD_503_ISL3861) },
/* I-O DATA WN-B11/USB */
{ USB_DEVICE(0x04bb, 0x0919), USB_DEVICE_DATA(BOARD_503_ISL3861) },
/* BT Voyager 1010 */
{ USB_DEVICE(0x069a, 0x0821), USB_DEVICE_DATA(BOARD_503_ISL3861) },
/*
* at76c503-i3863
*/
/* Generic AT76C503/3863 device */
{ USB_DEVICE(0x03eb, 0x7604), USB_DEVICE_DATA(BOARD_503_ISL3863) },
/* Samsung SWL-2100U */
{ USB_DEVICE(0x055d, 0xa000), USB_DEVICE_DATA(BOARD_503_ISL3863) },
/*
* at76c503-rfmd
*/
/* Generic AT76C503/RFMD device */
{ USB_DEVICE(0x03eb, 0x7605), USB_DEVICE_DATA(BOARD_503) },
/* Dynalink/Askey WLL013 (rfmd) */
{ USB_DEVICE(0x069a, 0x0321), USB_DEVICE_DATA(BOARD_503) },
/* Linksys WUSB11 v2.6 */
{ USB_DEVICE(0x077b, 0x2219), USB_DEVICE_DATA(BOARD_503) },
/* Network Everywhere NWU11B */
{ USB_DEVICE(0x077b, 0x2227), USB_DEVICE_DATA(BOARD_503) },
/* Netgear MA101 rev. B */
{ USB_DEVICE(0x0864, 0x4102), USB_DEVICE_DATA(BOARD_503) },
/* D-Link DWL-120 rev. E */
{ USB_DEVICE(0x2001, 0x3200), USB_DEVICE_DATA(BOARD_503) },
/* Actiontec 802UAT1, HWU01150-01UK */
{ USB_DEVICE(0x1668, 0x7605), USB_DEVICE_DATA(BOARD_503) },
/* AirVast W-Buddie WN210 */
{ USB_DEVICE(0x03eb, 0x4102), USB_DEVICE_DATA(BOARD_503) },
/* Dick Smith Electronics XH1153 802.11b USB adapter */
{ USB_DEVICE(0x1371, 0x5743), USB_DEVICE_DATA(BOARD_503) },
/* CNet CNUSB611 */
{ USB_DEVICE(0x1371, 0x0001), USB_DEVICE_DATA(BOARD_503) },
/* FiberLine FL-WL200U */
{ USB_DEVICE(0x1371, 0x0002), USB_DEVICE_DATA(BOARD_503) },
/* BenQ AWL400 USB stick */
{ USB_DEVICE(0x04a5, 0x9001), USB_DEVICE_DATA(BOARD_503) },
/* 3Com 3CRSHEW696 */
{ USB_DEVICE(0x0506, 0x0a01), USB_DEVICE_DATA(BOARD_503) },
/* Siemens Santis ADSL WLAN USB adapter WLL 013 */
{ USB_DEVICE(0x0681, 0x001b), USB_DEVICE_DATA(BOARD_503) },
/* Belkin F5D6050, version 2 */
{ USB_DEVICE(0x050d, 0x0050), USB_DEVICE_DATA(BOARD_503) },
/* iBlitzz, BWU613 (not *B or *SB) */
{ USB_DEVICE(0x07b8, 0xb000), USB_DEVICE_DATA(BOARD_503) },
/* Gigabyte GN-WLBM101 */
{ USB_DEVICE(0x1044, 0x8003), USB_DEVICE_DATA(BOARD_503) },
/* Planex GW-US11S */
{ USB_DEVICE(0x2019, 0x3220), USB_DEVICE_DATA(BOARD_503) },
/* Internal WLAN adapter in h5[4,5]xx series iPAQs */
{ USB_DEVICE(0x049f, 0x0032), USB_DEVICE_DATA(BOARD_503) },
/* Corega Wireless LAN USB-11 mini */
{ USB_DEVICE(0x07aa, 0x0011), USB_DEVICE_DATA(BOARD_503) },
/* Corega Wireless LAN USB-11 mini2 */
{ USB_DEVICE(0x07aa, 0x0018), USB_DEVICE_DATA(BOARD_503) },
/* Uniden PCW100 */
{ USB_DEVICE(0x05dd, 0xff35), USB_DEVICE_DATA(BOARD_503) },
/*
* at76c503-rfmd-acc
*/
/* SMC2664W */
{ USB_DEVICE(0x083a, 0x3501), USB_DEVICE_DATA(BOARD_503_ACC) },
/* Belkin F5D6050, SMC2662W v2, SMC2662W-AR */
{ USB_DEVICE(0x0d5c, 0xa002), USB_DEVICE_DATA(BOARD_503_ACC) },
/*
* at76c505-rfmd
*/
/* Generic AT76C505/RFMD */
{ USB_DEVICE(0x03eb, 0x7606), USB_DEVICE_DATA(BOARD_505) },
/*
* at76c505-rfmd2958
*/
/* Generic AT76C505/RFMD, OvisLink WL-1130USB */
{ USB_DEVICE(0x03eb, 0x7613), USB_DEVICE_DATA(BOARD_505_2958) },
/* Fiberline FL-WL240U */
{ USB_DEVICE(0x1371, 0x0014), USB_DEVICE_DATA(BOARD_505_2958) },
/* CNet CNUSB-611G */
{ USB_DEVICE(0x1371, 0x0013), USB_DEVICE_DATA(BOARD_505_2958) },
/* Linksys WUSB11 v2.8 */
{ USB_DEVICE(0x1915, 0x2233), USB_DEVICE_DATA(BOARD_505_2958) },
/* Xterasys XN-2122B, IBlitzz BWU613B/BWU613SB */
{ USB_DEVICE(0x12fd, 0x1001), USB_DEVICE_DATA(BOARD_505_2958) },
/* Corega WLAN USB Stick 11 */
{ USB_DEVICE(0x07aa, 0x7613), USB_DEVICE_DATA(BOARD_505_2958) },
/* Microstar MSI Box MS6978 */
{ USB_DEVICE(0x0db0, 0x1020), USB_DEVICE_DATA(BOARD_505_2958) },
/*
* at76c505a-rfmd2958
*/
/* Generic AT76C505A device */
{ USB_DEVICE(0x03eb, 0x7614), USB_DEVICE_DATA(BOARD_505A) },
/* Generic AT76C505AS device */
{ USB_DEVICE(0x03eb, 0x7617), USB_DEVICE_DATA(BOARD_505A) },
/* Siemens Gigaset USB WLAN Adapter 11 */
{ USB_DEVICE(0x1690, 0x0701), USB_DEVICE_DATA(BOARD_505A) },
/* OQO Model 01+ Internal Wi-Fi */
{ USB_DEVICE(0x1557, 0x0002), USB_DEVICE_DATA(BOARD_505A) },
/*
* at76c505amx-rfmd
*/
/* Generic AT76C505AMX device */
{ USB_DEVICE(0x03eb, 0x7615), USB_DEVICE_DATA(BOARD_505AMX) },
{ }
};
MODULE_DEVICE_TABLE(usb, dev_table);
/* Supported rates of this hardware, bit 7 marks basic rates */
static const u8 hw_rates[] = { 0x82, 0x84, 0x0b, 0x16 };
static const char *const preambles[] = { "long", "short", "auto" };
/* Firmware download */
/* DFU states */
#define STATE_IDLE 0x00
#define STATE_DETACH 0x01
#define STATE_DFU_IDLE 0x02
#define STATE_DFU_DOWNLOAD_SYNC 0x03
#define STATE_DFU_DOWNLOAD_BUSY 0x04
#define STATE_DFU_DOWNLOAD_IDLE 0x05
#define STATE_DFU_MANIFEST_SYNC 0x06
#define STATE_DFU_MANIFEST 0x07
#define STATE_DFU_MANIFEST_WAIT_RESET 0x08
#define STATE_DFU_UPLOAD_IDLE 0x09
#define STATE_DFU_ERROR 0x0a
/* DFU commands */
#define DFU_DETACH 0
#define DFU_DNLOAD 1
#define DFU_UPLOAD 2
#define DFU_GETSTATUS 3
#define DFU_CLRSTATUS 4
#define DFU_GETSTATE 5
#define DFU_ABORT 6
#define FW_BLOCK_SIZE 1024
struct dfu_status {
unsigned char status;
unsigned char poll_timeout[3];
unsigned char state;
unsigned char string;
} __packed;
static inline int at76_is_intersil(enum board_type board)
{
return (board == BOARD_503_ISL3861 || board == BOARD_503_ISL3863);
}
static inline int at76_is_503rfmd(enum board_type board)
{
return (board == BOARD_503 || board == BOARD_503_ACC);
}
static inline int at76_is_505a(enum board_type board)
{
return (board == BOARD_505A || board == BOARD_505AMX);
}
/* Load a block of the first (internal) part of the firmware */
static int at76_load_int_fw_block(struct usb_device *udev, int blockno,
void *block, int size)
{
return usb_control_msg(udev, usb_sndctrlpipe(udev, 0), DFU_DNLOAD,
USB_TYPE_CLASS | USB_DIR_OUT |
USB_RECIP_INTERFACE, blockno, 0, block, size,
USB_CTRL_GET_TIMEOUT);
}
static int at76_dfu_get_status(struct usb_device *udev,
struct dfu_status *status)
{
int ret;
ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), DFU_GETSTATUS,
USB_TYPE_CLASS | USB_DIR_IN | USB_RECIP_INTERFACE,
0, 0, status, sizeof(struct dfu_status),
USB_CTRL_GET_TIMEOUT);
return ret;
}
static u8 at76_dfu_get_state(struct usb_device *udev, u8 *state)
{
int ret;
ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), DFU_GETSTATE,
USB_TYPE_CLASS | USB_DIR_IN | USB_RECIP_INTERFACE,
0, 0, state, 1, USB_CTRL_GET_TIMEOUT);
return ret;
}
/* Convert timeout from the DFU status to jiffies */
static inline unsigned long at76_get_timeout(struct dfu_status *s)
{
return msecs_to_jiffies((s->poll_timeout[2] << 16)
| (s->poll_timeout[1] << 8)
| (s->poll_timeout[0]));
}
/* Load internal firmware from the buffer. If manifest_sync_timeout > 0, use
* its value in jiffies in the MANIFEST_SYNC state. */
static int at76_usbdfu_download(struct usb_device *udev, u8 *buf, u32 size,
int manifest_sync_timeout)
{
u8 *block;
struct dfu_status dfu_stat_buf;
int ret = 0;
int need_dfu_state = 1;
int is_done = 0;
u8 dfu_state = 0;
u32 dfu_timeout = 0;
int bsize = 0;
int blockno = 0;
at76_dbg(DBG_DFU, "%s( %p, %u, %d)", __func__, buf, size,
manifest_sync_timeout);
if (!size) {
dev_printk(KERN_ERR, &udev->dev, "FW buffer length invalid!\n");
return -EINVAL;
}
block = kmalloc(FW_BLOCK_SIZE, GFP_KERNEL);
if (!block)
return -ENOMEM;
do {
if (need_dfu_state) {
ret = at76_dfu_get_state(udev, &dfu_state);
if (ret < 0) {
dev_printk(KERN_ERR, &udev->dev,
"cannot get DFU state: %d\n", ret);
goto exit;
}
need_dfu_state = 0;
}
switch (dfu_state) {
case STATE_DFU_DOWNLOAD_SYNC:
at76_dbg(DBG_DFU, "STATE_DFU_DOWNLOAD_SYNC");
ret = at76_dfu_get_status(udev, &dfu_stat_buf);
if (ret >= 0) {
dfu_state = dfu_stat_buf.state;
dfu_timeout = at76_get_timeout(&dfu_stat_buf);
need_dfu_state = 0;
} else
dev_printk(KERN_ERR, &udev->dev,
"at76_dfu_get_status returned %d\n",
ret);
break;
case STATE_DFU_DOWNLOAD_BUSY:
at76_dbg(DBG_DFU, "STATE_DFU_DOWNLOAD_BUSY");
need_dfu_state = 1;
at76_dbg(DBG_DFU, "DFU: Resetting device");
schedule_timeout_interruptible(dfu_timeout);
break;
case STATE_DFU_DOWNLOAD_IDLE:
at76_dbg(DBG_DFU, "DOWNLOAD...");
/* fall through */
case STATE_DFU_IDLE:
at76_dbg(DBG_DFU, "DFU IDLE");
bsize = min_t(int, size, FW_BLOCK_SIZE);
memcpy(block, buf, bsize);
at76_dbg(DBG_DFU, "int fw, size left = %5d, "
"bsize = %4d, blockno = %2d", size, bsize,
blockno);
ret =
at76_load_int_fw_block(udev, blockno, block, bsize);
buf += bsize;
size -= bsize;
blockno++;
if (ret != bsize)
dev_printk(KERN_ERR, &udev->dev,
"at76_load_int_fw_block "
"returned %d\n", ret);
need_dfu_state = 1;
break;
case STATE_DFU_MANIFEST_SYNC:
at76_dbg(DBG_DFU, "STATE_DFU_MANIFEST_SYNC");
ret = at76_dfu_get_status(udev, &dfu_stat_buf);
if (ret < 0)
break;
dfu_state = dfu_stat_buf.state;
dfu_timeout = at76_get_timeout(&dfu_stat_buf);
need_dfu_state = 0;
/* override the timeout from the status response,
needed for AT76C505A */
if (manifest_sync_timeout > 0)
dfu_timeout = manifest_sync_timeout;
at76_dbg(DBG_DFU, "DFU: Waiting for manifest phase");
schedule_timeout_interruptible(dfu_timeout);
break;
case STATE_DFU_MANIFEST:
at76_dbg(DBG_DFU, "STATE_DFU_MANIFEST");
is_done = 1;
break;
case STATE_DFU_MANIFEST_WAIT_RESET:
at76_dbg(DBG_DFU, "STATE_DFU_MANIFEST_WAIT_RESET");
is_done = 1;
break;
case STATE_DFU_UPLOAD_IDLE:
at76_dbg(DBG_DFU, "STATE_DFU_UPLOAD_IDLE");
break;
case STATE_DFU_ERROR:
at76_dbg(DBG_DFU, "STATE_DFU_ERROR");
ret = -EPIPE;
break;
default:
at76_dbg(DBG_DFU, "DFU UNKNOWN STATE (%d)", dfu_state);
ret = -EINVAL;
break;
}
} while (!is_done && (ret >= 0));
exit:
kfree(block);
if (ret >= 0)
ret = 0;
return ret;
}
#define HEX2STR_BUFFERS 4
#define HEX2STR_MAX_LEN 64
#define BIN2HEX(x) ((x) < 10 ? '0' + (x) : (x) + 'A' - 10)
/* Convert binary data into hex string */
static char *hex2str(void *buf, int len)
{
static atomic_t a = ATOMIC_INIT(0);
static char bufs[HEX2STR_BUFFERS][3 * HEX2STR_MAX_LEN + 1];
char *ret = bufs[atomic_inc_return(&a) & (HEX2STR_BUFFERS - 1)];
char *obuf = ret;
u8 *ibuf = buf;
if (len > HEX2STR_MAX_LEN)
len = HEX2STR_MAX_LEN;
if (len <= 0) {
ret[0] = '\0';
return ret;
}
while (len--) {
*obuf++ = BIN2HEX(*ibuf >> 4);
*obuf++ = BIN2HEX(*ibuf & 0xf);
*obuf++ = '-';
ibuf++;
}
*(--obuf) = '\0';
return ret;
}
/* LED trigger */
static int tx_activity;
static void at76_ledtrig_tx_timerfunc(unsigned long data);
static DEFINE_TIMER(ledtrig_tx_timer, at76_ledtrig_tx_timerfunc, 0, 0);
DEFINE_LED_TRIGGER(ledtrig_tx);
static void at76_ledtrig_tx_timerfunc(unsigned long data)
{
static int tx_lastactivity;
if (tx_lastactivity != tx_activity) {
tx_lastactivity = tx_activity;
led_trigger_event(ledtrig_tx, LED_FULL);
mod_timer(&ledtrig_tx_timer, jiffies + HZ / 4);
} else
led_trigger_event(ledtrig_tx, LED_OFF);
}
static void at76_ledtrig_tx_activity(void)
{
tx_activity++;
if (!timer_pending(&ledtrig_tx_timer))
mod_timer(&ledtrig_tx_timer, jiffies + HZ / 4);
}
static int at76_remap(struct usb_device *udev)
{
int ret;
ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x0a,
USB_TYPE_VENDOR | USB_DIR_OUT |
USB_RECIP_INTERFACE, 0, 0, NULL, 0,
USB_CTRL_GET_TIMEOUT);
if (ret < 0)
return ret;
return 0;
}
static int at76_get_op_mode(struct usb_device *udev)
{
int ret;
u8 saved;
u8 *op_mode;
op_mode = kmalloc(1, GFP_NOIO);
if (!op_mode)
return -ENOMEM;
ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x33,
USB_TYPE_VENDOR | USB_DIR_IN |
USB_RECIP_INTERFACE, 0x01, 0, op_mode, 1,
USB_CTRL_GET_TIMEOUT);
saved = *op_mode;
kfree(op_mode);
if (ret < 0)
return ret;
else if (ret < 1)
return -EIO;
else
return saved;
}
/* Load a block of the second ("external") part of the firmware */
static inline int at76_load_ext_fw_block(struct usb_device *udev, int blockno,
void *block, int size)
{
return usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x0e,
USB_TYPE_VENDOR | USB_DIR_OUT | USB_RECIP_DEVICE,
0x0802, blockno, block, size,
USB_CTRL_GET_TIMEOUT);
}
static inline int at76_get_hw_cfg(struct usb_device *udev,
union at76_hwcfg *buf, int buf_size)
{
return usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x33,
USB_TYPE_VENDOR | USB_DIR_IN |
USB_RECIP_INTERFACE, 0x0a02, 0,
buf, buf_size, USB_CTRL_GET_TIMEOUT);
}
/* Intersil boards use a different "value" for GetHWConfig requests */
static inline int at76_get_hw_cfg_intersil(struct usb_device *udev,
union at76_hwcfg *buf, int buf_size)
{
return usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x33,
USB_TYPE_VENDOR | USB_DIR_IN |
USB_RECIP_INTERFACE, 0x0902, 0,
buf, buf_size, USB_CTRL_GET_TIMEOUT);
}
/* Get the hardware configuration for the adapter and put it to the appropriate
* fields of 'priv' (the GetHWConfig request and interpretation of the result
* depends on the board type) */
static int at76_get_hw_config(struct at76_priv *priv)
{
int ret;
union at76_hwcfg *hwcfg = kmalloc(sizeof(*hwcfg), GFP_KERNEL);
if (!hwcfg)
return -ENOMEM;
if (at76_is_intersil(priv->board_type)) {
ret = at76_get_hw_cfg_intersil(priv->udev, hwcfg,
sizeof(hwcfg->i));
if (ret < 0)
goto exit;
memcpy(priv->mac_addr, hwcfg->i.mac_addr, ETH_ALEN);
priv->regulatory_domain = hwcfg->i.regulatory_domain;
} else if (at76_is_503rfmd(priv->board_type)) {
ret = at76_get_hw_cfg(priv->udev, hwcfg, sizeof(hwcfg->r3));
if (ret < 0)
goto exit;
memcpy(priv->mac_addr, hwcfg->r3.mac_addr, ETH_ALEN);
priv->regulatory_domain = hwcfg->r3.regulatory_domain;
} else {
ret = at76_get_hw_cfg(priv->udev, hwcfg, sizeof(hwcfg->r5));
if (ret < 0)
goto exit;
memcpy(priv->mac_addr, hwcfg->r5.mac_addr, ETH_ALEN);
priv->regulatory_domain = hwcfg->r5.regulatory_domain;
}
exit:
kfree(hwcfg);
if (ret < 0)
wiphy_err(priv->hw->wiphy, "cannot get HW Config (error %d)\n",
ret);
return ret;
}
static struct reg_domain const *at76_get_reg_domain(u16 code)
{
int i;
static struct reg_domain const fd_tab[] = {
{ 0x10, "FCC (USA)", 0x7ff }, /* ch 1-11 */
{ 0x20, "IC (Canada)", 0x7ff }, /* ch 1-11 */
{ 0x30, "ETSI (most of Europe)", 0x1fff }, /* ch 1-13 */
{ 0x31, "Spain", 0x600 }, /* ch 10-11 */
{ 0x32, "France", 0x1e00 }, /* ch 10-13 */
{ 0x40, "MKK (Japan)", 0x2000 }, /* ch 14 */
{ 0x41, "MKK1 (Japan)", 0x3fff }, /* ch 1-14 */
{ 0x50, "Israel", 0x3fc }, /* ch 3-9 */
{ 0x00, "<unknown>", 0xffffffff } /* ch 1-32 */
};
/* Last entry is fallback for unknown domain code */
for (i = 0; i < ARRAY_SIZE(fd_tab) - 1; i++)
if (code == fd_tab[i].code)
break;
return &fd_tab[i];
}
static inline int at76_get_mib(struct usb_device *udev, u16 mib, void *buf,
int buf_size)
{
int ret;
ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x33,
USB_TYPE_VENDOR | USB_DIR_IN |
USB_RECIP_INTERFACE, mib << 8, 0, buf, buf_size,
USB_CTRL_GET_TIMEOUT);
if (ret >= 0 && ret != buf_size)
return -EIO;
return ret;
}
/* Return positive number for status, negative for an error */
static inline int at76_get_cmd_status(struct usb_device *udev, u8 cmd)
{
u8 *stat_buf;
int ret;
stat_buf = kmalloc(40, GFP_NOIO);
if (!stat_buf)
return -ENOMEM;
ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x22,
USB_TYPE_VENDOR | USB_DIR_IN |
USB_RECIP_INTERFACE, cmd, 0, stat_buf,
40, USB_CTRL_GET_TIMEOUT);
if (ret >= 0)
ret = stat_buf[5];
kfree(stat_buf);
return ret;
}
#define MAKE_CMD_CASE(c) case (c): return #c
static const char *at76_get_cmd_string(u8 cmd_status)
{
switch (cmd_status) {
MAKE_CMD_CASE(CMD_SET_MIB);
MAKE_CMD_CASE(CMD_GET_MIB);
MAKE_CMD_CASE(CMD_SCAN);
MAKE_CMD_CASE(CMD_JOIN);
MAKE_CMD_CASE(CMD_START_IBSS);
MAKE_CMD_CASE(CMD_RADIO_ON);
MAKE_CMD_CASE(CMD_RADIO_OFF);
MAKE_CMD_CASE(CMD_STARTUP);
}
return "UNKNOWN";
}
static int at76_set_card_command(struct usb_device *udev, u8 cmd, void *buf,
int buf_size)
{
int ret;
struct at76_command *cmd_buf = kmalloc(sizeof(struct at76_command) +
buf_size, GFP_KERNEL);
if (!cmd_buf)
return -ENOMEM;
cmd_buf->cmd = cmd;
cmd_buf->reserved = 0;
cmd_buf->size = cpu_to_le16(buf_size);
memcpy(cmd_buf->data, buf, buf_size);
at76_dbg_dump(DBG_CMD, cmd_buf, sizeof(struct at76_command) + buf_size,
"issuing command %s (0x%02x)",
at76_get_cmd_string(cmd), cmd);
ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x0e,
USB_TYPE_VENDOR | USB_DIR_OUT | USB_RECIP_DEVICE,
0, 0, cmd_buf,
sizeof(struct at76_command) + buf_size,
USB_CTRL_GET_TIMEOUT);
kfree(cmd_buf);
return ret;
}
#define MAKE_CMD_STATUS_CASE(c) case (c): return #c
static const char *at76_get_cmd_status_string(u8 cmd_status)
{
switch (cmd_status) {
MAKE_CMD_STATUS_CASE(CMD_STATUS_IDLE);
MAKE_CMD_STATUS_CASE(CMD_STATUS_COMPLETE);
MAKE_CMD_STATUS_CASE(CMD_STATUS_UNKNOWN);
MAKE_CMD_STATUS_CASE(CMD_STATUS_INVALID_PARAMETER);
MAKE_CMD_STATUS_CASE(CMD_STATUS_FUNCTION_NOT_SUPPORTED);
MAKE_CMD_STATUS_CASE(CMD_STATUS_TIME_OUT);
MAKE_CMD_STATUS_CASE(CMD_STATUS_IN_PROGRESS);
MAKE_CMD_STATUS_CASE(CMD_STATUS_HOST_FAILURE);
MAKE_CMD_STATUS_CASE(CMD_STATUS_SCAN_FAILED);
}
return "UNKNOWN";
}
/* Wait until the command is completed */
static int at76_wait_completion(struct at76_priv *priv, int cmd)
{
int status = 0;
unsigned long timeout = jiffies + CMD_COMPLETION_TIMEOUT;
do {
status = at76_get_cmd_status(priv->udev, cmd);
if (status < 0) {
wiphy_err(priv->hw->wiphy,
"at76_get_cmd_status failed: %d\n",
status);
break;
}
at76_dbg(DBG_WAIT_COMPLETE,
"%s: Waiting on cmd %d, status = %d (%s)",
wiphy_name(priv->hw->wiphy), cmd, status,
at76_get_cmd_status_string(status));
if (status != CMD_STATUS_IN_PROGRESS
&& status != CMD_STATUS_IDLE)
break;
schedule_timeout_interruptible(HZ / 10); /* 100 ms */
if (time_after(jiffies, timeout)) {
wiphy_err(priv->hw->wiphy,
"completion timeout for command %d\n", cmd);
status = -ETIMEDOUT;
break;
}
} while (1);
return status;
}
static int at76_set_mib(struct at76_priv *priv, struct set_mib_buffer *buf)
{
int ret;
ret = at76_set_card_command(priv->udev, CMD_SET_MIB, buf,
offsetof(struct set_mib_buffer,
data) + buf->size);
if (ret < 0)
return ret;
ret = at76_wait_completion(priv, CMD_SET_MIB);
if (ret != CMD_STATUS_COMPLETE) {
wiphy_info(priv->hw->wiphy,
"set_mib: at76_wait_completion failed with %d\n",
ret);
ret = -EIO;
}
return ret;
}
/* Return < 0 on error, == 0 if no command sent, == 1 if cmd sent */
static int at76_set_radio(struct at76_priv *priv, int enable)
{
int ret;
int cmd;
if (priv->radio_on == enable)
return 0;
cmd = enable ? CMD_RADIO_ON : CMD_RADIO_OFF;
ret = at76_set_card_command(priv->udev, cmd, NULL, 0);
if (ret < 0)
wiphy_err(priv->hw->wiphy,
"at76_set_card_command(%d) failed: %d\n", cmd, ret);
else
ret = 1;
priv->radio_on = enable;
return ret;
}
/* Set current power save mode (AT76_PM_OFF/AT76_PM_ON/AT76_PM_SMART) */
static int at76_set_pm_mode(struct at76_priv *priv)
{
int ret = 0;
priv->mib_buf.type = MIB_MAC_MGMT;
priv->mib_buf.size = 1;
priv->mib_buf.index = offsetof(struct mib_mac_mgmt, power_mgmt_mode);
priv->mib_buf.data.byte = priv->pm_mode;
ret = at76_set_mib(priv, &priv->mib_buf);
if (ret < 0)
wiphy_err(priv->hw->wiphy, "set_mib (pm_mode) failed: %d\n",
ret);
return ret;
}
static int at76_set_preamble(struct at76_priv *priv, u8 type)
{
int ret = 0;
priv->mib_buf.type = MIB_LOCAL;
priv->mib_buf.size = 1;
priv->mib_buf.index = offsetof(struct mib_local, preamble_type);
priv->mib_buf.data.byte = type;
ret = at76_set_mib(priv, &priv->mib_buf);
if (ret < 0)
wiphy_err(priv->hw->wiphy, "set_mib (preamble) failed: %d\n",
ret);
return ret;
}
static int at76_set_frag(struct at76_priv *priv, u16 size)
{
int ret = 0;
priv->mib_buf.type = MIB_MAC;
priv->mib_buf.size = 2;
priv->mib_buf.index = offsetof(struct mib_mac, frag_threshold);
priv->mib_buf.data.word = cpu_to_le16(size);
ret = at76_set_mib(priv, &priv->mib_buf);
if (ret < 0)
wiphy_err(priv->hw->wiphy,
"set_mib (frag threshold) failed: %d\n", ret);
return ret;
}
static int at76_set_rts(struct at76_priv *priv, u16 size)
{
int ret = 0;
priv->mib_buf.type = MIB_MAC;
priv->mib_buf.size = 2;
priv->mib_buf.index = offsetof(struct mib_mac, rts_threshold);
priv->mib_buf.data.word = cpu_to_le16(size);
ret = at76_set_mib(priv, &priv->mib_buf);
if (ret < 0)
wiphy_err(priv->hw->wiphy, "set_mib (rts) failed: %d\n", ret);
return ret;
}
static int at76_set_autorate_fallback(struct at76_priv *priv, int onoff)
{
int ret = 0;
priv->mib_buf.type = MIB_LOCAL;
priv->mib_buf.size = 1;
priv->mib_buf.index = offsetof(struct mib_local, txautorate_fallback);
priv->mib_buf.data.byte = onoff;
ret = at76_set_mib(priv, &priv->mib_buf);
if (ret < 0)
wiphy_err(priv->hw->wiphy,
"set_mib (autorate fallback) failed: %d\n", ret);
return ret;
}
static void at76_dump_mib_mac_addr(struct at76_priv *priv)
{
int i;
int ret;
struct mib_mac_addr *m = kmalloc(sizeof(struct mib_mac_addr),
GFP_KERNEL);
if (!m)
return;
ret = at76_get_mib(priv->udev, MIB_MAC_ADDR, m,
sizeof(struct mib_mac_addr));
if (ret < 0) {
wiphy_err(priv->hw->wiphy,
"at76_get_mib (MAC_ADDR) failed: %d\n", ret);
goto exit;
}
at76_dbg(DBG_MIB, "%s: MIB MAC_ADDR: mac_addr %pM res 0x%x 0x%x",
wiphy_name(priv->hw->wiphy),
m->mac_addr, m->res[0], m->res[1]);
for (i = 0; i < ARRAY_SIZE(m->group_addr); i++)
at76_dbg(DBG_MIB, "%s: MIB MAC_ADDR: group addr %d: %pM, "
"status %d", wiphy_name(priv->hw->wiphy), i,
m->group_addr[i], m->group_addr_status[i]);
exit:
kfree(m);
}
static void at76_dump_mib_mac_wep(struct at76_priv *priv)
{
int i;
int ret;
int key_len;
struct mib_mac_wep *m = kmalloc(sizeof(struct mib_mac_wep), GFP_KERNEL);
if (!m)
return;
ret = at76_get_mib(priv->udev, MIB_MAC_WEP, m,
sizeof(struct mib_mac_wep));
if (ret < 0) {
wiphy_err(priv->hw->wiphy,
"at76_get_mib (MAC_WEP) failed: %d\n", ret);
goto exit;
}
at76_dbg(DBG_MIB, "%s: MIB MAC_WEP: priv_invoked %u def_key_id %u "
"key_len %u excl_unencr %u wep_icv_err %u wep_excluded %u "
"encr_level %u key %d", wiphy_name(priv->hw->wiphy),
m->privacy_invoked, m->wep_default_key_id,
m->wep_key_mapping_len, m->exclude_unencrypted,
le32_to_cpu(m->wep_icv_error_count),
le32_to_cpu(m->wep_excluded_count), m->encryption_level,
m->wep_default_key_id);
key_len = (m->encryption_level == 1) ?
WEP_SMALL_KEY_LEN : WEP_LARGE_KEY_LEN;
for (i = 0; i < WEP_KEYS; i++)
at76_dbg(DBG_MIB, "%s: MIB MAC_WEP: key %d: %s",
wiphy_name(priv->hw->wiphy), i,
hex2str(m->wep_default_keyvalue[i], key_len));
exit:
kfree(m);
}
static void at76_dump_mib_mac_mgmt(struct at76_priv *priv)
{
int ret;
struct mib_mac_mgmt *m = kmalloc(sizeof(struct mib_mac_mgmt),
GFP_KERNEL);
if (!m)
return;
ret = at76_get_mib(priv->udev, MIB_MAC_MGMT, m,
sizeof(struct mib_mac_mgmt));
if (ret < 0) {
wiphy_err(priv->hw->wiphy,
"at76_get_mib (MAC_MGMT) failed: %d\n", ret);
goto exit;
}
at76_dbg(DBG_MIB, "%s: MIB MAC_MGMT: beacon_period %d CFP_max_duration "
"%d medium_occupancy_limit %d station_id 0x%x ATIM_window %d "
"CFP_mode %d privacy_opt_impl %d DTIM_period %d CFP_period %d "
"current_bssid %pM current_essid %s current_bss_type %d "
"pm_mode %d ibss_change %d res %d "
"multi_domain_capability_implemented %d "
"international_roaming %d country_string %.3s",
wiphy_name(priv->hw->wiphy), le16_to_cpu(m->beacon_period),
le16_to_cpu(m->CFP_max_duration),
le16_to_cpu(m->medium_occupancy_limit),
le16_to_cpu(m->station_id), le16_to_cpu(m->ATIM_window),
m->CFP_mode, m->privacy_option_implemented, m->DTIM_period,
m->CFP_period, m->current_bssid,
hex2str(m->current_essid, IW_ESSID_MAX_SIZE),
m->current_bss_type, m->power_mgmt_mode, m->ibss_change,
m->res, m->multi_domain_capability_implemented,
m->multi_domain_capability_enabled, m->country_string);
exit:
kfree(m);
}
static void at76_dump_mib_mac(struct at76_priv *priv)
{
int ret;
struct mib_mac *m = kmalloc(sizeof(struct mib_mac), GFP_KERNEL);
if (!m)
return;
ret = at76_get_mib(priv->udev, MIB_MAC, m, sizeof(struct mib_mac));
if (ret < 0) {
wiphy_err(priv->hw->wiphy,
"at76_get_mib (MAC) failed: %d\n", ret);
goto exit;
}
at76_dbg(DBG_MIB, "%s: MIB MAC: max_tx_msdu_lifetime %d "
"max_rx_lifetime %d frag_threshold %d rts_threshold %d "
"cwmin %d cwmax %d short_retry_time %d long_retry_time %d "
"scan_type %d scan_channel %d probe_delay %u "
"min_channel_time %d max_channel_time %d listen_int %d "
"desired_ssid %s desired_bssid %pM desired_bsstype %d",
wiphy_name(priv->hw->wiphy),
le32_to_cpu(m->max_tx_msdu_lifetime),
le32_to_cpu(m->max_rx_lifetime),
le16_to_cpu(m->frag_threshold), le16_to_cpu(m->rts_threshold),
le16_to_cpu(m->cwmin), le16_to_cpu(m->cwmax),
m->short_retry_time, m->long_retry_time, m->scan_type,
m->scan_channel, le16_to_cpu(m->probe_delay),
le16_to_cpu(m->min_channel_time),
le16_to_cpu(m->max_channel_time),
le16_to_cpu(m->listen_interval),
hex2str(m->desired_ssid, IW_ESSID_MAX_SIZE),
m->desired_bssid, m->desired_bsstype);
exit:
kfree(m);
}
static void at76_dump_mib_phy(struct at76_priv *priv)
{
int ret;
struct mib_phy *m = kmalloc(sizeof(struct mib_phy), GFP_KERNEL);
if (!m)
return;
ret = at76_get_mib(priv->udev, MIB_PHY, m, sizeof(struct mib_phy));
if (ret < 0) {
wiphy_err(priv->hw->wiphy,
"at76_get_mib (PHY) failed: %d\n", ret);
goto exit;
}
at76_dbg(DBG_MIB, "%s: MIB PHY: ed_threshold %d slot_time %d "
"sifs_time %d preamble_length %d plcp_header_length %d "
"mpdu_max_length %d cca_mode_supported %d operation_rate_set "
"0x%x 0x%x 0x%x 0x%x channel_id %d current_cca_mode %d "
"phy_type %d current_reg_domain %d",
wiphy_name(priv->hw->wiphy), le32_to_cpu(m->ed_threshold),
le16_to_cpu(m->slot_time), le16_to_cpu(m->sifs_time),
le16_to_cpu(m->preamble_length),
le16_to_cpu(m->plcp_header_length),
le16_to_cpu(m->mpdu_max_length),
le16_to_cpu(m->cca_mode_supported), m->operation_rate_set[0],
m->operation_rate_set[1], m->operation_rate_set[2],
m->operation_rate_set[3], m->channel_id, m->current_cca_mode,
m->phy_type, m->current_reg_domain);
exit:
kfree(m);
}
static void at76_dump_mib_local(struct at76_priv *priv)
{
int ret;
struct mib_local *m = kmalloc(sizeof(struct mib_phy), GFP_KERNEL);
if (!m)
return;
ret = at76_get_mib(priv->udev, MIB_LOCAL, m, sizeof(struct mib_local));
if (ret < 0) {
wiphy_err(priv->hw->wiphy,
"at76_get_mib (LOCAL) failed: %d\n", ret);
goto exit;
}
at76_dbg(DBG_MIB, "%s: MIB LOCAL: beacon_enable %d "
"txautorate_fallback %d ssid_size %d promiscuous_mode %d "
"preamble_type %d", wiphy_name(priv->hw->wiphy),
m->beacon_enable,
m->txautorate_fallback, m->ssid_size, m->promiscuous_mode,
m->preamble_type);
exit:
kfree(m);
}
static void at76_dump_mib_mdomain(struct at76_priv *priv)
{
int ret;
struct mib_mdomain *m = kmalloc(sizeof(struct mib_mdomain), GFP_KERNEL);
if (!m)
return;
ret = at76_get_mib(priv->udev, MIB_MDOMAIN, m,
sizeof(struct mib_mdomain));
if (ret < 0) {
wiphy_err(priv->hw->wiphy,
"at76_get_mib (MDOMAIN) failed: %d\n", ret);
goto exit;
}
at76_dbg(DBG_MIB, "%s: MIB MDOMAIN: channel_list %s",
wiphy_name(priv->hw->wiphy),
hex2str(m->channel_list, sizeof(m->channel_list)));
at76_dbg(DBG_MIB, "%s: MIB MDOMAIN: tx_powerlevel %s",
wiphy_name(priv->hw->wiphy),
hex2str(m->tx_powerlevel, sizeof(m->tx_powerlevel)));
exit:
kfree(m);
}
/* Enable monitor mode */
static int at76_start_monitor(struct at76_priv *priv)
{
struct at76_req_scan scan;
int ret;
memset(&scan, 0, sizeof(struct at76_req_scan));
memset(scan.bssid, 0xff, ETH_ALEN);
scan.channel = priv->channel;
scan.scan_type = SCAN_TYPE_PASSIVE;
scan.international_scan = 0;
scan.min_channel_time = cpu_to_le16(priv->scan_min_time);
scan.max_channel_time = cpu_to_le16(priv->scan_max_time);
scan.probe_delay = cpu_to_le16(0);
ret = at76_set_card_command(priv->udev, CMD_SCAN, &scan, sizeof(scan));
if (ret >= 0)
ret = at76_get_cmd_status(priv->udev, CMD_SCAN);
return ret;
}
/* Calculate padding from txbuf->wlength (which excludes the USB TX header),
likely to compensate a flaw in the AT76C503A USB part ... */
static inline int at76_calc_padding(int wlen)
{
/* add the USB TX header */
wlen += AT76_TX_HDRLEN;
wlen = wlen % 64;
if (wlen < 50)
return 50 - wlen;
if (wlen >= 61)
return 64 + 50 - wlen;
return 0;
}
static void at76_rx_callback(struct urb *urb)
{
struct at76_priv *priv = urb->context;
priv->rx_tasklet.data = (unsigned long)urb;
tasklet_schedule(&priv->rx_tasklet);
}
static int at76_submit_rx_urb(struct at76_priv *priv)
{
int ret;
int size;
struct sk_buff *skb = priv->rx_skb;
if (!priv->rx_urb) {
wiphy_err(priv->hw->wiphy, "%s: priv->rx_urb is NULL\n",
__func__);
return -EFAULT;
}
if (!skb) {
skb = dev_alloc_skb(sizeof(struct at76_rx_buffer));
if (!skb) {
wiphy_err(priv->hw->wiphy,
"cannot allocate rx skbuff\n");
ret = -ENOMEM;
goto exit;
}
priv->rx_skb = skb;
} else {
skb_push(skb, skb_headroom(skb));
skb_trim(skb, 0);
}
size = skb_tailroom(skb);
usb_fill_bulk_urb(priv->rx_urb, priv->udev, priv->rx_pipe,
skb_put(skb, size), size, at76_rx_callback, priv);
ret = usb_submit_urb(priv->rx_urb, GFP_ATOMIC);
if (ret < 0) {
if (ret == -ENODEV)
at76_dbg(DBG_DEVSTART,
"usb_submit_urb returned -ENODEV");
else
wiphy_err(priv->hw->wiphy,
"rx, usb_submit_urb failed: %d\n", ret);
}
exit:
if (ret < 0 && ret != -ENODEV)
wiphy_err(priv->hw->wiphy,
"cannot submit rx urb - please unload the driver and/or power cycle the device\n");
return ret;
}
/* Download external firmware */
static int at76_load_external_fw(struct usb_device *udev, struct fwentry *fwe)
{
int ret;
int op_mode;
int blockno = 0;
int bsize;
u8 *block;
u8 *buf = fwe->extfw;
int size = fwe->extfw_size;
if (!buf || !size)
return -ENOENT;
op_mode = at76_get_op_mode(udev);
at76_dbg(DBG_DEVSTART, "opmode %d", op_mode);
if (op_mode != OPMODE_NORMAL_NIC_WITHOUT_FLASH) {
dev_printk(KERN_ERR, &udev->dev, "unexpected opmode %d\n",
op_mode);
return -EINVAL;
}
block = kmalloc(FW_BLOCK_SIZE, GFP_KERNEL);
if (!block)
return -ENOMEM;
at76_dbg(DBG_DEVSTART, "downloading external firmware");
/* for fw >= 0.100, the device needs an extra empty block */
do {
bsize = min_t(int, size, FW_BLOCK_SIZE);
memcpy(block, buf, bsize);
at76_dbg(DBG_DEVSTART,
"ext fw, size left = %5d, bsize = %4d, blockno = %2d",
size, bsize, blockno);
ret = at76_load_ext_fw_block(udev, blockno, block, bsize);
if (ret != bsize) {
dev_printk(KERN_ERR, &udev->dev,
"loading %dth firmware block failed: %d\n",
blockno, ret);
goto exit;
}
buf += bsize;
size -= bsize;
blockno++;
} while (bsize > 0);
if (at76_is_505a(fwe->board_type)) {
at76_dbg(DBG_DEVSTART, "200 ms delay for 505a");
schedule_timeout_interruptible(HZ / 5 + 1);
}
exit:
kfree(block);
if (ret < 0)
dev_printk(KERN_ERR, &udev->dev,
"downloading external firmware failed: %d\n", ret);
return ret;
}
/* Download internal firmware */
static int at76_load_internal_fw(struct usb_device *udev, struct fwentry *fwe)
{
int ret;
int need_remap = !at76_is_505a(fwe->board_type);
ret = at76_usbdfu_download(udev, fwe->intfw, fwe->intfw_size,
need_remap ? 0 : 2 * HZ);
if (ret < 0) {
dev_printk(KERN_ERR, &udev->dev,
"downloading internal fw failed with %d\n", ret);
goto exit;
}
at76_dbg(DBG_DEVSTART, "sending REMAP");
/* no REMAP for 505A (see SF driver) */
if (need_remap) {
ret = at76_remap(udev);
if (ret < 0) {
dev_printk(KERN_ERR, &udev->dev,
"sending REMAP failed with %d\n", ret);
goto exit;
}
}
at76_dbg(DBG_DEVSTART, "sleeping for 2 seconds");
schedule_timeout_interruptible(2 * HZ + 1);
usb_reset_device(udev);
exit:
return ret;
}
static int at76_startup_device(struct at76_priv *priv)
{
struct at76_card_config *ccfg = &priv->card_config;
int ret;
at76_dbg(DBG_PARAMS,
"%s param: ssid %.*s (%s) mode %s ch %d wep %s key %d "
"keylen %d", wiphy_name(priv->hw->wiphy), priv->essid_size,
priv->essid, hex2str(priv->essid, IW_ESSID_MAX_SIZE),
priv->iw_mode == IW_MODE_ADHOC ? "adhoc" : "infra",
priv->channel, priv->wep_enabled ? "enabled" : "disabled",
priv->wep_key_id, priv->wep_keys_len[priv->wep_key_id]);
at76_dbg(DBG_PARAMS,
"%s param: preamble %s rts %d retry %d frag %d "
"txrate %s auth_mode %d", wiphy_name(priv->hw->wiphy),
preambles[priv->preamble_type], priv->rts_threshold,
priv->short_retry_limit, priv->frag_threshold,
priv->txrate == TX_RATE_1MBIT ? "1MBit" : priv->txrate ==
TX_RATE_2MBIT ? "2MBit" : priv->txrate ==
TX_RATE_5_5MBIT ? "5.5MBit" : priv->txrate ==
TX_RATE_11MBIT ? "11MBit" : priv->txrate ==
TX_RATE_AUTO ? "auto" : "<invalid>", priv->auth_mode);
at76_dbg(DBG_PARAMS,
"%s param: pm_mode %d pm_period %d auth_mode %s "
"scan_times %d %d scan_mode %s",
wiphy_name(priv->hw->wiphy), priv->pm_mode, priv->pm_period,
priv->auth_mode == WLAN_AUTH_OPEN ? "open" : "shared_secret",
priv->scan_min_time, priv->scan_max_time,
priv->scan_mode == SCAN_TYPE_ACTIVE ? "active" : "passive");
memset(ccfg, 0, sizeof(struct at76_card_config));
ccfg->promiscuous_mode = 0;
ccfg->short_retry_limit = priv->short_retry_limit;
if (priv->wep_enabled) {
if (priv->wep_keys_len[priv->wep_key_id] > WEP_SMALL_KEY_LEN)
ccfg->encryption_type = 2;
else
ccfg->encryption_type = 1;
/* jal: always exclude unencrypted if WEP is active */
ccfg->exclude_unencrypted = 1;
} else {
ccfg->exclude_unencrypted = 0;
ccfg->encryption_type = 0;
}
ccfg->rts_threshold = cpu_to_le16(priv->rts_threshold);
ccfg->fragmentation_threshold = cpu_to_le16(priv->frag_threshold);
memcpy(ccfg->basic_rate_set, hw_rates, 4);
/* jal: really needed, we do a set_mib for autorate later ??? */
ccfg->auto_rate_fallback = (priv->txrate == TX_RATE_AUTO ? 1 : 0);
ccfg->channel = priv->channel;
ccfg->privacy_invoked = priv->wep_enabled;
memcpy(ccfg->current_ssid, priv->essid, IW_ESSID_MAX_SIZE);
ccfg->ssid_len = priv->essid_size;
ccfg->wep_default_key_id = priv->wep_key_id;
memcpy(ccfg->wep_default_key_value, priv->wep_keys,
sizeof(priv->wep_keys));
ccfg->short_preamble = priv->preamble_type;
ccfg->beacon_period = cpu_to_le16(priv->beacon_period);
ret = at76_set_card_command(priv->udev, CMD_STARTUP, &priv->card_config,
sizeof(struct at76_card_config));
if (ret < 0) {
wiphy_err(priv->hw->wiphy, "at76_set_card_command failed: %d\n",
ret);
return ret;
}
at76_wait_completion(priv, CMD_STARTUP);
/* remove BSSID from previous run */
memset(priv->bssid, 0, ETH_ALEN);
if (at76_set_radio(priv, 1) == 1)
at76_wait_completion(priv, CMD_RADIO_ON);
ret = at76_set_preamble(priv, priv->preamble_type);
if (ret < 0)
return ret;
ret = at76_set_frag(priv, priv->frag_threshold);
if (ret < 0)
return ret;
ret = at76_set_rts(priv, priv->rts_threshold);
if (ret < 0)
return ret;
ret = at76_set_autorate_fallback(priv,
priv->txrate == TX_RATE_AUTO ? 1 : 0);
if (ret < 0)
return ret;
ret = at76_set_pm_mode(priv);
if (ret < 0)
return ret;
if (at76_debug & DBG_MIB) {
at76_dump_mib_mac(priv);
at76_dump_mib_mac_addr(priv);
at76_dump_mib_mac_mgmt(priv);
at76_dump_mib_mac_wep(priv);
at76_dump_mib_mdomain(priv);
at76_dump_mib_phy(priv);
at76_dump_mib_local(priv);
}
return 0;
}
/* Enable or disable promiscuous mode */
static void at76_work_set_promisc(struct work_struct *work)
{
struct at76_priv *priv = container_of(work, struct at76_priv,
work_set_promisc);
int ret = 0;
if (priv->device_unplugged)
return;
mutex_lock(&priv->mtx);
priv->mib_buf.type = MIB_LOCAL;
priv->mib_buf.size = 1;
priv->mib_buf.index = offsetof(struct mib_local, promiscuous_mode);
priv->mib_buf.data.byte = priv->promisc ? 1 : 0;
ret = at76_set_mib(priv, &priv->mib_buf);
if (ret < 0)
wiphy_err(priv->hw->wiphy,
"set_mib (promiscuous_mode) failed: %d\n", ret);
mutex_unlock(&priv->mtx);
}
/* Submit Rx urb back to the device */
static void at76_work_submit_rx(struct work_struct *work)
{
struct at76_priv *priv = container_of(work, struct at76_priv,
work_submit_rx);
mutex_lock(&priv->mtx);
at76_submit_rx_urb(priv);
mutex_unlock(&priv->mtx);
}
static void at76_rx_tasklet(unsigned long param)
{
struct urb *urb = (struct urb *)param;
struct at76_priv *priv = urb->context;
struct at76_rx_buffer *buf;
struct ieee80211_rx_status rx_status = { 0 };
if (priv->device_unplugged) {
at76_dbg(DBG_DEVSTART, "device unplugged");
at76_dbg(DBG_DEVSTART, "urb status %d", urb->status);
return;
}
if (!priv->rx_skb || !priv->rx_skb->data)
return;
buf = (struct at76_rx_buffer *)priv->rx_skb->data;
if (urb->status != 0) {
if (urb->status != -ENOENT && urb->status != -ECONNRESET)
at76_dbg(DBG_URB,
"%s %s: - nonzero Rx bulk status received: %d",
__func__, wiphy_name(priv->hw->wiphy),
urb->status);
return;
}
at76_dbg(DBG_RX_ATMEL_HDR,
"%s: rx frame: rate %d rssi %d noise %d link %d",
wiphy_name(priv->hw->wiphy), buf->rx_rate, buf->rssi,
buf->noise_level, buf->link_quality);
skb_pull(priv->rx_skb, AT76_RX_HDRLEN);
skb_trim(priv->rx_skb, le16_to_cpu(buf->wlength));
at76_dbg_dump(DBG_RX_DATA, priv->rx_skb->data,
priv->rx_skb->len, "RX: len=%d", priv->rx_skb->len);
rx_status.signal = buf->rssi;
rx_status.flag |= RX_FLAG_DECRYPTED;
rx_status.flag |= RX_FLAG_IV_STRIPPED;
at76_dbg(DBG_MAC80211, "calling ieee80211_rx_irqsafe(): %d/%d",
priv->rx_skb->len, priv->rx_skb->data_len);
memcpy(IEEE80211_SKB_RXCB(priv->rx_skb), &rx_status, sizeof(rx_status));
ieee80211_rx_irqsafe(priv->hw, priv->rx_skb);
/* Use a new skb for the next receive */
priv->rx_skb = NULL;
at76_submit_rx_urb(priv);
}
/* Load firmware into kernel memory and parse it */
static struct fwentry *at76_load_firmware(struct usb_device *udev,
enum board_type board_type)
{
int ret;
char *str;
struct at76_fw_header *fwh;
struct fwentry *fwe = &firmwares[board_type];
mutex_lock(&fw_mutex);
if (fwe->loaded) {
at76_dbg(DBG_FW, "re-using previously loaded fw");
goto exit;
}
at76_dbg(DBG_FW, "downloading firmware %s", fwe->fwname);
ret = request_firmware(&fwe->fw, fwe->fwname, &udev->dev);
if (ret < 0) {
dev_printk(KERN_ERR, &udev->dev, "firmware %s not found!\n",
fwe->fwname);
dev_printk(KERN_ERR, &udev->dev,
"you may need to download the firmware from "
"http://developer.berlios.de/projects/at76c503a/\n");
goto exit;
}
at76_dbg(DBG_FW, "got it.");
fwh = (struct at76_fw_header *)(fwe->fw->data);
if (fwe->fw->size <= sizeof(*fwh)) {
dev_printk(KERN_ERR, &udev->dev,
"firmware is too short (0x%zx)\n", fwe->fw->size);
goto exit;
}
/* CRC currently not checked */
fwe->board_type = le32_to_cpu(fwh->board_type);
if (fwe->board_type != board_type) {
dev_printk(KERN_ERR, &udev->dev,
"board type mismatch, requested %u, got %u\n",
board_type, fwe->board_type);
goto exit;
}
fwe->fw_version.major = fwh->major;
fwe->fw_version.minor = fwh->minor;
fwe->fw_version.patch = fwh->patch;
fwe->fw_version.build = fwh->build;
str = (char *)fwh + le32_to_cpu(fwh->str_offset);
fwe->intfw = (u8 *)fwh + le32_to_cpu(fwh->int_fw_offset);
fwe->intfw_size = le32_to_cpu(fwh->int_fw_len);
fwe->extfw = (u8 *)fwh + le32_to_cpu(fwh->ext_fw_offset);
fwe->extfw_size = le32_to_cpu(fwh->ext_fw_len);
fwe->loaded = 1;
dev_printk(KERN_DEBUG, &udev->dev,
"using firmware %s (version %d.%d.%d-%d)\n",
fwe->fwname, fwh->major, fwh->minor, fwh->patch, fwh->build);
at76_dbg(DBG_DEVSTART, "board %u, int %d:%d, ext %d:%d", board_type,
le32_to_cpu(fwh->int_fw_offset), le32_to_cpu(fwh->int_fw_len),
le32_to_cpu(fwh->ext_fw_offset), le32_to_cpu(fwh->ext_fw_len));
at76_dbg(DBG_DEVSTART, "firmware id %s", str);
exit:
mutex_unlock(&fw_mutex);
if (fwe->loaded)
return fwe;
else
return NULL;
}
static int at76_join(struct at76_priv *priv)
{
struct at76_req_join join;
int ret;
memset(&join, 0, sizeof(struct at76_req_join));
memcpy(join.essid, priv->essid, priv->essid_size);
join.essid_size = priv->essid_size;
memcpy(join.bssid, priv->bssid, ETH_ALEN);
join.bss_type = INFRASTRUCTURE_MODE;
join.channel = priv->channel;
join.timeout = cpu_to_le16(2000);
at76_dbg(DBG_MAC80211, "%s: sending CMD_JOIN", __func__);
ret = at76_set_card_command(priv->udev, CMD_JOIN, &join,
sizeof(struct at76_req_join));
if (ret < 0) {
wiphy_err(priv->hw->wiphy, "at76_set_card_command failed: %d\n",
ret);
return 0;
}
ret = at76_wait_completion(priv, CMD_JOIN);
at76_dbg(DBG_MAC80211, "%s: CMD_JOIN returned: 0x%02x", __func__, ret);
if (ret != CMD_STATUS_COMPLETE) {
wiphy_err(priv->hw->wiphy, "at76_wait_completion failed: %d\n",
ret);
return 0;
}
at76_set_pm_mode(priv);
return 0;
}
static void at76_work_join_bssid(struct work_struct *work)
{
struct at76_priv *priv = container_of(work, struct at76_priv,
work_join_bssid);
if (priv->device_unplugged)
return;
mutex_lock(&priv->mtx);
if (is_valid_ether_addr(priv->bssid))
at76_join(priv);
mutex_unlock(&priv->mtx);
}
static void at76_mac80211_tx_callback(struct urb *urb)
{
struct at76_priv *priv = urb->context;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(priv->tx_skb);
at76_dbg(DBG_MAC80211, "%s()", __func__);
switch (urb->status) {
case 0:
/* success */
info->flags |= IEEE80211_TX_STAT_ACK;
break;
case -ENOENT:
case -ECONNRESET:
/* fail, urb has been unlinked */
/* FIXME: add error message */
break;
default:
at76_dbg(DBG_URB, "%s - nonzero tx status received: %d",
__func__, urb->status);
break;
}
memset(&info->status, 0, sizeof(info->status));
ieee80211_tx_status_irqsafe(priv->hw, priv->tx_skb);
priv->tx_skb = NULL;
ieee80211_wake_queues(priv->hw);
}
static void at76_mac80211_tx(struct ieee80211_hw *hw, struct sk_buff *skb)
{
struct at76_priv *priv = hw->priv;
struct at76_tx_buffer *tx_buffer = priv->bulk_out_buffer;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct ieee80211_mgmt *mgmt = (struct ieee80211_mgmt *)skb->data;
int padding, submit_len, ret;
at76_dbg(DBG_MAC80211, "%s()", __func__);
if (priv->tx_urb->status == -EINPROGRESS) {
wiphy_err(priv->hw->wiphy,
"%s called while tx urb is pending\n", __func__);
dev_kfree_skb_any(skb);
return;
}
/* The following code lines are important when the device is going to
* authenticate with a new bssid. The driver must send CMD_JOIN before
* an authentication frame is transmitted. For this to succeed, the
* correct bssid of the AP must be known. As mac80211 does not inform
* drivers about the bssid prior to the authentication process the
* following workaround is necessary. If the TX frame is an
* authentication frame extract the bssid and send the CMD_JOIN. */
if (mgmt->frame_control & cpu_to_le16(IEEE80211_STYPE_AUTH)) {
if (compare_ether_addr(priv->bssid, mgmt->bssid)) {
memcpy(priv->bssid, mgmt->bssid, ETH_ALEN);
ieee80211_queue_work(hw, &priv->work_join_bssid);
dev_kfree_skb_any(skb);
return;
}
}
ieee80211_stop_queues(hw);
at76_ledtrig_tx_activity(); /* tell ledtrigger we send a packet */
WARN_ON(priv->tx_skb != NULL);
priv->tx_skb = skb;
padding = at76_calc_padding(skb->len);
submit_len = AT76_TX_HDRLEN + skb->len + padding;
/* setup 'Atmel' header */
memset(tx_buffer, 0, sizeof(*tx_buffer));
tx_buffer->padding = padding;
tx_buffer->wlength = cpu_to_le16(skb->len);
tx_buffer->tx_rate = ieee80211_get_tx_rate(hw, info)->hw_value;
memset(tx_buffer->reserved, 0, sizeof(tx_buffer->reserved));
memcpy(tx_buffer->packet, skb->data, skb->len);
at76_dbg(DBG_TX_DATA, "%s tx: wlen 0x%x pad 0x%x rate %d hdr",
wiphy_name(priv->hw->wiphy), le16_to_cpu(tx_buffer->wlength),
tx_buffer->padding, tx_buffer->tx_rate);
/* send stuff */
at76_dbg_dump(DBG_TX_DATA_CONTENT, tx_buffer, submit_len,
"%s(): tx_buffer %d bytes:", __func__, submit_len);
usb_fill_bulk_urb(priv->tx_urb, priv->udev, priv->tx_pipe, tx_buffer,
submit_len, at76_mac80211_tx_callback, priv);
ret = usb_submit_urb(priv->tx_urb, GFP_ATOMIC);
if (ret) {
wiphy_err(priv->hw->wiphy, "error in tx submit urb: %d\n", ret);
if (ret == -EINVAL)
wiphy_err(priv->hw->wiphy,
"-EINVAL: tx urb %p hcpriv %p complete %p\n",
priv->tx_urb,
priv->tx_urb->hcpriv, priv->tx_urb->complete);
}
}
static int at76_mac80211_start(struct ieee80211_hw *hw)
{
struct at76_priv *priv = hw->priv;
int ret;
at76_dbg(DBG_MAC80211, "%s()", __func__);
mutex_lock(&priv->mtx);
ret = at76_submit_rx_urb(priv);
if (ret < 0) {
wiphy_err(priv->hw->wiphy, "open: submit_rx_urb failed: %d\n",
ret);
goto error;
}
at76_startup_device(priv);
at76_start_monitor(priv);
error:
mutex_unlock(&priv->mtx);
return 0;
}
static void at76_mac80211_stop(struct ieee80211_hw *hw)
{
struct at76_priv *priv = hw->priv;
at76_dbg(DBG_MAC80211, "%s()", __func__);
cancel_delayed_work(&priv->dwork_hw_scan);
cancel_work_sync(&priv->work_join_bssid);
cancel_work_sync(&priv->work_set_promisc);
mutex_lock(&priv->mtx);
if (!priv->device_unplugged) {
/* We are called by "ifconfig ethX down", not because the
* device is not available anymore. */
at76_set_radio(priv, 0);
/* We unlink rx_urb because at76_open() re-submits it.
* If unplugged, at76_delete_device() takes care of it. */
usb_kill_urb(priv->rx_urb);
}
mutex_unlock(&priv->mtx);
}
static int at76_add_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct at76_priv *priv = hw->priv;
int ret = 0;
at76_dbg(DBG_MAC80211, "%s()", __func__);
mutex_lock(&priv->mtx);
switch (vif->type) {
case NL80211_IFTYPE_STATION:
priv->iw_mode = IW_MODE_INFRA;
break;
default:
ret = -EOPNOTSUPP;
goto exit;
}
exit:
mutex_unlock(&priv->mtx);
return ret;
}
static void at76_remove_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
at76_dbg(DBG_MAC80211, "%s()", __func__);
}
static void at76_dwork_hw_scan(struct work_struct *work)
{
struct at76_priv *priv = container_of(work, struct at76_priv,
dwork_hw_scan.work);
int ret;
if (priv->device_unplugged)
return;
mutex_lock(&priv->mtx);
ret = at76_get_cmd_status(priv->udev, CMD_SCAN);
at76_dbg(DBG_MAC80211, "%s: CMD_SCAN status 0x%02x", __func__, ret);
/* FIXME: add maximum time for scan to complete */
if (ret != CMD_STATUS_COMPLETE) {
ieee80211_queue_delayed_work(priv->hw, &priv->dwork_hw_scan,
SCAN_POLL_INTERVAL);
mutex_unlock(&priv->mtx);
return;
}
if (is_valid_ether_addr(priv->bssid))
at76_join(priv);
mutex_unlock(&priv->mtx);
ieee80211_scan_completed(priv->hw, false);
ieee80211_wake_queues(priv->hw);
}
static int at76_hw_scan(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct cfg80211_scan_request *req)
{
struct at76_priv *priv = hw->priv;
struct at76_req_scan scan;
u8 *ssid = NULL;
int ret, len = 0;
at76_dbg(DBG_MAC80211, "%s():", __func__);
if (priv->device_unplugged)
return 0;
mutex_lock(&priv->mtx);
ieee80211_stop_queues(hw);
memset(&scan, 0, sizeof(struct at76_req_scan));
memset(scan.bssid, 0xFF, ETH_ALEN);
if (req->n_ssids) {
scan.scan_type = SCAN_TYPE_ACTIVE;
ssid = req->ssids[0].ssid;
len = req->ssids[0].ssid_len;
} else {
scan.scan_type = SCAN_TYPE_PASSIVE;
}
if (len) {
memcpy(scan.essid, ssid, len);
scan.essid_size = len;
}
scan.min_channel_time = cpu_to_le16(priv->scan_min_time);
scan.max_channel_time = cpu_to_le16(priv->scan_max_time);
scan.probe_delay = cpu_to_le16(priv->scan_min_time * 1000);
scan.international_scan = 0;
at76_dbg(DBG_MAC80211, "%s: sending CMD_SCAN", __func__);
ret = at76_set_card_command(priv->udev, CMD_SCAN, &scan, sizeof(scan));
if (ret < 0) {
err("CMD_SCAN failed: %d", ret);
goto exit;
}
ieee80211_queue_delayed_work(priv->hw, &priv->dwork_hw_scan,
SCAN_POLL_INTERVAL);
exit:
mutex_unlock(&priv->mtx);
return 0;
}
static int at76_config(struct ieee80211_hw *hw, u32 changed)
{
struct at76_priv *priv = hw->priv;
at76_dbg(DBG_MAC80211, "%s(): channel %d",
__func__, hw->conf.channel->hw_value);
at76_dbg_dump(DBG_MAC80211, priv->bssid, ETH_ALEN, "bssid:");
mutex_lock(&priv->mtx);
priv->channel = hw->conf.channel->hw_value;
if (is_valid_ether_addr(priv->bssid))
at76_join(priv);
else
at76_start_monitor(priv);
mutex_unlock(&priv->mtx);
return 0;
}
static void at76_bss_info_changed(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *conf,
u32 changed)
{
struct at76_priv *priv = hw->priv;
at76_dbg(DBG_MAC80211, "%s():", __func__);
if (!(changed & BSS_CHANGED_BSSID))
return;
at76_dbg_dump(DBG_MAC80211, conf->bssid, ETH_ALEN, "bssid:");
mutex_lock(&priv->mtx);
memcpy(priv->bssid, conf->bssid, ETH_ALEN);
if (is_valid_ether_addr(priv->bssid))
/* mac80211 is joining a bss */
at76_join(priv);
mutex_unlock(&priv->mtx);
}
/* must be atomic */
static void at76_configure_filter(struct ieee80211_hw *hw,
unsigned int changed_flags,
unsigned int *total_flags, u64 multicast)
{
struct at76_priv *priv = hw->priv;
int flags;
at76_dbg(DBG_MAC80211, "%s(): changed_flags=0x%08x "
"total_flags=0x%08x",
__func__, changed_flags, *total_flags);
flags = changed_flags & AT76_SUPPORTED_FILTERS;
*total_flags = AT76_SUPPORTED_FILTERS;
/* Bail out after updating flags to prevent a WARN_ON in mac80211. */
if (priv->device_unplugged)
return;
/* FIXME: access to priv->promisc should be protected with
* priv->mtx, but it's impossible because this function needs to be
* atomic */
if (flags && !priv->promisc) {
/* mac80211 wants us to enable promiscuous mode */
priv->promisc = 1;
} else if (!flags && priv->promisc) {
/* we need to disable promiscuous mode */
priv->promisc = 0;
} else
return;
ieee80211_queue_work(hw, &priv->work_set_promisc);
}
static int at76_set_key(struct ieee80211_hw *hw, enum set_key_cmd cmd,
struct ieee80211_vif *vif, struct ieee80211_sta *sta,
struct ieee80211_key_conf *key)
{
struct at76_priv *priv = hw->priv;
int i;
at76_dbg(DBG_MAC80211, "%s(): cmd %d key->cipher %d key->keyidx %d "
"key->keylen %d",
__func__, cmd, key->cipher, key->keyidx, key->keylen);
if ((key->cipher != WLAN_CIPHER_SUITE_WEP40) &&
(key->cipher != WLAN_CIPHER_SUITE_WEP104))
return -EOPNOTSUPP;
key->hw_key_idx = key->keyidx;
mutex_lock(&priv->mtx);
switch (cmd) {
case SET_KEY:
memcpy(priv->wep_keys[key->keyidx], key->key, key->keylen);
priv->wep_keys_len[key->keyidx] = key->keylen;
/* FIXME: find out how to do this properly */
priv->wep_key_id = key->keyidx;
break;
case DISABLE_KEY:
default:
priv->wep_keys_len[key->keyidx] = 0;
break;
}
priv->wep_enabled = 0;
for (i = 0; i < WEP_KEYS; i++) {
if (priv->wep_keys_len[i] != 0)
priv->wep_enabled = 1;
}
at76_startup_device(priv);
mutex_unlock(&priv->mtx);
return 0;
}
static const struct ieee80211_ops at76_ops = {
.tx = at76_mac80211_tx,
.add_interface = at76_add_interface,
.remove_interface = at76_remove_interface,
.config = at76_config,
.bss_info_changed = at76_bss_info_changed,
.configure_filter = at76_configure_filter,
.start = at76_mac80211_start,
.stop = at76_mac80211_stop,
.hw_scan = at76_hw_scan,
.set_key = at76_set_key,
};
/* Allocate network device and initialize private data */
static struct at76_priv *at76_alloc_new_device(struct usb_device *udev)
{
struct ieee80211_hw *hw;
struct at76_priv *priv;
hw = ieee80211_alloc_hw(sizeof(struct at76_priv), &at76_ops);
if (!hw) {
printk(KERN_ERR DRIVER_NAME ": could not register"
" ieee80211_hw\n");
return NULL;
}
priv = hw->priv;
priv->hw = hw;
priv->udev = udev;
mutex_init(&priv->mtx);
INIT_WORK(&priv->work_set_promisc, at76_work_set_promisc);
INIT_WORK(&priv->work_submit_rx, at76_work_submit_rx);
INIT_WORK(&priv->work_join_bssid, at76_work_join_bssid);
INIT_DELAYED_WORK(&priv->dwork_hw_scan, at76_dwork_hw_scan);
tasklet_init(&priv->rx_tasklet, at76_rx_tasklet, 0);
priv->pm_mode = AT76_PM_OFF;
priv->pm_period = 0;
/* unit us */
priv->hw->channel_change_time = 100000;
return priv;
}
static int at76_alloc_urbs(struct at76_priv *priv,
struct usb_interface *interface)
{
struct usb_endpoint_descriptor *endpoint, *ep_in, *ep_out;
int i;
int buffer_size;
struct usb_host_interface *iface_desc;
at76_dbg(DBG_PROC_ENTRY, "%s: ENTER", __func__);
at76_dbg(DBG_URB, "%s: NumEndpoints %d ", __func__,
interface->altsetting[0].desc.bNumEndpoints);
ep_in = NULL;
ep_out = NULL;
iface_desc = interface->cur_altsetting;
for (i = 0; i < iface_desc->desc.bNumEndpoints; i++) {
endpoint = &iface_desc->endpoint[i].desc;
at76_dbg(DBG_URB, "%s: %d. endpoint: addr 0x%x attr 0x%x",
__func__, i, endpoint->bEndpointAddress,
endpoint->bmAttributes);
if (!ep_in && usb_endpoint_is_bulk_in(endpoint))
ep_in = endpoint;
if (!ep_out && usb_endpoint_is_bulk_out(endpoint))
ep_out = endpoint;
}
if (!ep_in || !ep_out) {
dev_printk(KERN_ERR, &interface->dev,
"bulk endpoints missing\n");
return -ENXIO;
}
priv->rx_pipe = usb_rcvbulkpipe(priv->udev, ep_in->bEndpointAddress);
priv->tx_pipe = usb_sndbulkpipe(priv->udev, ep_out->bEndpointAddress);
priv->rx_urb = usb_alloc_urb(0, GFP_KERNEL);
priv->tx_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!priv->rx_urb || !priv->tx_urb) {
dev_printk(KERN_ERR, &interface->dev, "cannot allocate URB\n");
return -ENOMEM;
}
buffer_size = sizeof(struct at76_tx_buffer) + MAX_PADDING_SIZE;
priv->bulk_out_buffer = kmalloc(buffer_size, GFP_KERNEL);
if (!priv->bulk_out_buffer) {
dev_printk(KERN_ERR, &interface->dev,
"cannot allocate output buffer\n");
return -ENOMEM;
}
at76_dbg(DBG_PROC_ENTRY, "%s: EXIT", __func__);
return 0;
}
static struct ieee80211_rate at76_rates[] = {
{ .bitrate = 10, .hw_value = TX_RATE_1MBIT, },
{ .bitrate = 20, .hw_value = TX_RATE_2MBIT, },
{ .bitrate = 55, .hw_value = TX_RATE_5_5MBIT, },
{ .bitrate = 110, .hw_value = TX_RATE_11MBIT, },
};
static struct ieee80211_channel at76_channels[] = {
{ .center_freq = 2412, .hw_value = 1 },
{ .center_freq = 2417, .hw_value = 2 },
{ .center_freq = 2422, .hw_value = 3 },
{ .center_freq = 2427, .hw_value = 4 },
{ .center_freq = 2432, .hw_value = 5 },
{ .center_freq = 2437, .hw_value = 6 },
{ .center_freq = 2442, .hw_value = 7 },
{ .center_freq = 2447, .hw_value = 8 },
{ .center_freq = 2452, .hw_value = 9 },
{ .center_freq = 2457, .hw_value = 10 },
{ .center_freq = 2462, .hw_value = 11 },
{ .center_freq = 2467, .hw_value = 12 },
{ .center_freq = 2472, .hw_value = 13 },
{ .center_freq = 2484, .hw_value = 14 }
};
static struct ieee80211_supported_band at76_supported_band = {
.channels = at76_channels,
.n_channels = ARRAY_SIZE(at76_channels),
.bitrates = at76_rates,
.n_bitrates = ARRAY_SIZE(at76_rates),
};
/* Register network device and initialize the hardware */
static int at76_init_new_device(struct at76_priv *priv,
struct usb_interface *interface)
{
struct wiphy *wiphy;
size_t len;
int ret;
/* set up the endpoint information */
/* check out the endpoints */
at76_dbg(DBG_DEVSTART, "USB interface: %d endpoints",
interface->cur_altsetting->desc.bNumEndpoints);
ret = at76_alloc_urbs(priv, interface);
if (ret < 0)
goto exit;
/* MAC address */
ret = at76_get_hw_config(priv);
if (ret < 0) {
dev_printk(KERN_ERR, &interface->dev,
"cannot get MAC address\n");
goto exit;
}
priv->domain = at76_get_reg_domain(priv->regulatory_domain);
priv->channel = DEF_CHANNEL;
priv->iw_mode = IW_MODE_INFRA;
priv->rts_threshold = DEF_RTS_THRESHOLD;
priv->frag_threshold = DEF_FRAG_THRESHOLD;
priv->short_retry_limit = DEF_SHORT_RETRY_LIMIT;
priv->txrate = TX_RATE_AUTO;
priv->preamble_type = PREAMBLE_TYPE_LONG;
priv->beacon_period = 100;
priv->auth_mode = WLAN_AUTH_OPEN;
priv->scan_min_time = DEF_SCAN_MIN_TIME;
priv->scan_max_time = DEF_SCAN_MAX_TIME;
priv->scan_mode = SCAN_TYPE_ACTIVE;
priv->device_unplugged = 0;
/* mac80211 initialisation */
wiphy = priv->hw->wiphy;
priv->hw->wiphy->max_scan_ssids = 1;
priv->hw->wiphy->max_scan_ie_len = 0;
priv->hw->wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION);
priv->hw->wiphy->bands[IEEE80211_BAND_2GHZ] = &at76_supported_band;
priv->hw->flags = IEEE80211_HW_RX_INCLUDES_FCS |
IEEE80211_HW_SIGNAL_UNSPEC;
priv->hw->max_signal = 100;
SET_IEEE80211_DEV(priv->hw, &interface->dev);
SET_IEEE80211_PERM_ADDR(priv->hw, priv->mac_addr);
len = sizeof(wiphy->fw_version);
snprintf(wiphy->fw_version, len, "%d.%d.%d-%d",
priv->fw_version.major, priv->fw_version.minor,
priv->fw_version.patch, priv->fw_version.build);
wiphy->hw_version = priv->board_type;
ret = ieee80211_register_hw(priv->hw);
if (ret) {
printk(KERN_ERR "cannot register mac80211 hw (status %d)!\n",
ret);
goto exit;
}
priv->mac80211_registered = 1;
wiphy_info(priv->hw->wiphy, "USB %s, MAC %pM, firmware %d.%d.%d-%d\n",
dev_name(&interface->dev), priv->mac_addr,
priv->fw_version.major, priv->fw_version.minor,
priv->fw_version.patch, priv->fw_version.build);
wiphy_info(priv->hw->wiphy, "regulatory domain 0x%02x: %s\n",
priv->regulatory_domain, priv->domain->name);
exit:
return ret;
}
static void at76_delete_device(struct at76_priv *priv)
{
at76_dbg(DBG_PROC_ENTRY, "%s: ENTER", __func__);
/* The device is gone, don't bother turning it off */
priv->device_unplugged = 1;
tasklet_kill(&priv->rx_tasklet);
if (priv->mac80211_registered)
ieee80211_unregister_hw(priv->hw);
if (priv->tx_urb) {
usb_kill_urb(priv->tx_urb);
usb_free_urb(priv->tx_urb);
}
if (priv->rx_urb) {
usb_kill_urb(priv->rx_urb);
usb_free_urb(priv->rx_urb);
}
at76_dbg(DBG_PROC_ENTRY, "%s: unlinked urbs", __func__);
kfree(priv->bulk_out_buffer);
del_timer_sync(&ledtrig_tx_timer);
kfree_skb(priv->rx_skb);
usb_put_dev(priv->udev);
at76_dbg(DBG_PROC_ENTRY, "%s: before freeing priv/ieee80211_hw",
__func__);
ieee80211_free_hw(priv->hw);
at76_dbg(DBG_PROC_ENTRY, "%s: EXIT", __func__);
}
static int at76_probe(struct usb_interface *interface,
const struct usb_device_id *id)
{
int ret;
struct at76_priv *priv;
struct fwentry *fwe;
struct usb_device *udev;
int op_mode;
int need_ext_fw = 0;
struct mib_fw_version fwv;
int board_type = (int)id->driver_info;
udev = usb_get_dev(interface_to_usbdev(interface));
/* Load firmware into kernel memory */
fwe = at76_load_firmware(udev, board_type);
if (!fwe) {
ret = -ENOENT;
goto error;
}
op_mode = at76_get_op_mode(udev);
at76_dbg(DBG_DEVSTART, "opmode %d", op_mode);
/* we get OPMODE_NONE with 2.4.23, SMC2662W-AR ???
we get 204 with 2.4.23, Fiberline FL-WL240u (505A+RFMD2958) ??? */
if (op_mode == OPMODE_HW_CONFIG_MODE) {
dev_printk(KERN_ERR, &interface->dev,
"cannot handle a device in HW_CONFIG_MODE\n");
ret = -EBUSY;
goto error;
}
if (op_mode != OPMODE_NORMAL_NIC_WITH_FLASH
&& op_mode != OPMODE_NORMAL_NIC_WITHOUT_FLASH) {
/* download internal firmware part */
dev_printk(KERN_DEBUG, &interface->dev,
"downloading internal firmware\n");
ret = at76_load_internal_fw(udev, fwe);
if (ret < 0) {
dev_printk(KERN_ERR, &interface->dev,
"error %d downloading internal firmware\n",
ret);
goto error;
}
usb_put_dev(udev);
return ret;
}
/* Internal firmware already inside the device. Get firmware
* version to test if external firmware is loaded.
* This works only for newer firmware, e.g. the Intersil 0.90.x
* says "control timeout on ep0in" and subsequent
* at76_get_op_mode() fail too :-( */
/* if version >= 0.100.x.y or device with built-in flash we can
* query the device for the fw version */
if ((fwe->fw_version.major > 0 || fwe->fw_version.minor >= 100)
|| (op_mode == OPMODE_NORMAL_NIC_WITH_FLASH)) {
ret = at76_get_mib(udev, MIB_FW_VERSION, &fwv, sizeof(fwv));
if (ret < 0 || (fwv.major | fwv.minor) == 0)
need_ext_fw = 1;
} else
/* No way to check firmware version, reload to be sure */
need_ext_fw = 1;
if (need_ext_fw) {
dev_printk(KERN_DEBUG, &interface->dev,
"downloading external firmware\n");
ret = at76_load_external_fw(udev, fwe);
if (ret)
goto error;
/* Re-check firmware version */
ret = at76_get_mib(udev, MIB_FW_VERSION, &fwv, sizeof(fwv));
if (ret < 0) {
dev_printk(KERN_ERR, &interface->dev,
"error %d getting firmware version\n", ret);
goto error;
}
}
priv = at76_alloc_new_device(udev);
if (!priv) {
ret = -ENOMEM;
goto error;
}
usb_set_intfdata(interface, priv);
memcpy(&priv->fw_version, &fwv, sizeof(struct mib_fw_version));
priv->board_type = board_type;
ret = at76_init_new_device(priv, interface);
if (ret < 0)
at76_delete_device(priv);
return ret;
error:
usb_put_dev(udev);
return ret;
}
static void at76_disconnect(struct usb_interface *interface)
{
struct at76_priv *priv;
priv = usb_get_intfdata(interface);
usb_set_intfdata(interface, NULL);
/* Disconnect after loading internal firmware */
if (!priv)
return;
wiphy_info(priv->hw->wiphy, "disconnecting\n");
at76_delete_device(priv);
dev_printk(KERN_INFO, &interface->dev, "disconnected\n");
}
/* Structure for registering this driver with the USB subsystem */
static struct usb_driver at76_driver = {
.name = DRIVER_NAME,
.probe = at76_probe,
.disconnect = at76_disconnect,
.id_table = dev_table,
};
static int __init at76_mod_init(void)
{
int result;
printk(KERN_INFO DRIVER_DESC " " DRIVER_VERSION " loading\n");
mutex_init(&fw_mutex);
/* register this driver with the USB subsystem */
result = usb_register(&at76_driver);
if (result < 0)
printk(KERN_ERR DRIVER_NAME
": usb_register failed (status %d)\n", result);
led_trigger_register_simple("at76_usb-tx", &ledtrig_tx);
return result;
}
static void __exit at76_mod_exit(void)
{
int i;
printk(KERN_INFO DRIVER_DESC " " DRIVER_VERSION " unloading\n");
usb_deregister(&at76_driver);
for (i = 0; i < ARRAY_SIZE(firmwares); i++) {
if (firmwares[i].fw)
release_firmware(firmwares[i].fw);
}
led_trigger_unregister_simple(ledtrig_tx);
}
module_param_named(debug, at76_debug, uint, 0600);
MODULE_PARM_DESC(debug, "Debugging level");
module_init(at76_mod_init);
module_exit(at76_mod_exit);
MODULE_AUTHOR("Oliver Kurth <oku@masqmail.cx>");
MODULE_AUTHOR("Joerg Albert <joerg.albert@gmx.de>");
MODULE_AUTHOR("Alex <alex@foogod.com>");
MODULE_AUTHOR("Nick Jones");
MODULE_AUTHOR("Balint Seeber <n0_5p4m_p13453@hotmail.com>");
MODULE_AUTHOR("Pavel Roskin <proski@gnu.org>");
MODULE_AUTHOR("Guido Guenther <agx@sigxcpu.org>");
MODULE_AUTHOR("Kalle Valo <kalle.valo@iki.fi>");
MODULE_AUTHOR("Sebastian Smolorz <sesmo@gmx.net>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
| gpl-2.0 |
garyclee/android_kernel_samsung_klte | drivers/net/wireless/b43/phy_n.c | 3379 | 148197 | /*
Broadcom B43 wireless driver
IEEE 802.11n PHY support
Copyright (c) 2008 Michael Buesch <m@bues.ch>
Copyright (c) 2010-2011 Rafał Miłecki <zajec5@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Steet, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/types.h>
#include "b43.h"
#include "phy_n.h"
#include "tables_nphy.h"
#include "radio_2055.h"
#include "radio_2056.h"
#include "main.h"
struct nphy_txgains {
u16 txgm[2];
u16 pga[2];
u16 pad[2];
u16 ipa[2];
};
struct nphy_iqcal_params {
u16 txgm;
u16 pga;
u16 pad;
u16 ipa;
u16 cal_gain;
u16 ncorr[5];
};
struct nphy_iq_est {
s32 iq0_prod;
u32 i0_pwr;
u32 q0_pwr;
s32 iq1_prod;
u32 i1_pwr;
u32 q1_pwr;
};
enum b43_nphy_rf_sequence {
B43_RFSEQ_RX2TX,
B43_RFSEQ_TX2RX,
B43_RFSEQ_RESET2RX,
B43_RFSEQ_UPDATE_GAINH,
B43_RFSEQ_UPDATE_GAINL,
B43_RFSEQ_UPDATE_GAINU,
};
enum b43_nphy_rssi_type {
B43_NPHY_RSSI_X = 0,
B43_NPHY_RSSI_Y,
B43_NPHY_RSSI_Z,
B43_NPHY_RSSI_PWRDET,
B43_NPHY_RSSI_TSSI_I,
B43_NPHY_RSSI_TSSI_Q,
B43_NPHY_RSSI_TBD,
};
static inline bool b43_nphy_ipa(struct b43_wldev *dev)
{
enum ieee80211_band band = b43_current_band(dev->wl);
return ((dev->phy.n->ipa2g_on && band == IEEE80211_BAND_2GHZ) ||
(dev->phy.n->ipa5g_on && band == IEEE80211_BAND_5GHZ));
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/RxCoreGetState */
static u8 b43_nphy_get_rx_core_state(struct b43_wldev *dev)
{
return (b43_phy_read(dev, B43_NPHY_RFSEQCA) & B43_NPHY_RFSEQCA_RXEN) >>
B43_NPHY_RFSEQCA_RXEN_SHIFT;
}
/**************************************************
* RF (just without b43_nphy_rf_control_intc_override)
**************************************************/
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/ForceRFSeq */
static void b43_nphy_force_rf_sequence(struct b43_wldev *dev,
enum b43_nphy_rf_sequence seq)
{
static const u16 trigger[] = {
[B43_RFSEQ_RX2TX] = B43_NPHY_RFSEQTR_RX2TX,
[B43_RFSEQ_TX2RX] = B43_NPHY_RFSEQTR_TX2RX,
[B43_RFSEQ_RESET2RX] = B43_NPHY_RFSEQTR_RST2RX,
[B43_RFSEQ_UPDATE_GAINH] = B43_NPHY_RFSEQTR_UPGH,
[B43_RFSEQ_UPDATE_GAINL] = B43_NPHY_RFSEQTR_UPGL,
[B43_RFSEQ_UPDATE_GAINU] = B43_NPHY_RFSEQTR_UPGU,
};
int i;
u16 seq_mode = b43_phy_read(dev, B43_NPHY_RFSEQMODE);
B43_WARN_ON(seq >= ARRAY_SIZE(trigger));
b43_phy_set(dev, B43_NPHY_RFSEQMODE,
B43_NPHY_RFSEQMODE_CAOVER | B43_NPHY_RFSEQMODE_TROVER);
b43_phy_set(dev, B43_NPHY_RFSEQTR, trigger[seq]);
for (i = 0; i < 200; i++) {
if (!(b43_phy_read(dev, B43_NPHY_RFSEQST) & trigger[seq]))
goto ok;
msleep(1);
}
b43err(dev->wl, "RF sequence status timeout\n");
ok:
b43_phy_write(dev, B43_NPHY_RFSEQMODE, seq_mode);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/RFCtrlOverride */
static void b43_nphy_rf_control_override(struct b43_wldev *dev, u16 field,
u16 value, u8 core, bool off)
{
int i;
u8 index = fls(field);
u8 addr, en_addr, val_addr;
/* we expect only one bit set */
B43_WARN_ON(field & (~(1 << (index - 1))));
if (dev->phy.rev >= 3) {
const struct nphy_rf_control_override_rev3 *rf_ctrl;
for (i = 0; i < 2; i++) {
if (index == 0 || index == 16) {
b43err(dev->wl,
"Unsupported RF Ctrl Override call\n");
return;
}
rf_ctrl = &tbl_rf_control_override_rev3[index - 1];
en_addr = B43_PHY_N((i == 0) ?
rf_ctrl->en_addr0 : rf_ctrl->en_addr1);
val_addr = B43_PHY_N((i == 0) ?
rf_ctrl->val_addr0 : rf_ctrl->val_addr1);
if (off) {
b43_phy_mask(dev, en_addr, ~(field));
b43_phy_mask(dev, val_addr,
~(rf_ctrl->val_mask));
} else {
if (core == 0 || ((1 << i) & core)) {
b43_phy_set(dev, en_addr, field);
b43_phy_maskset(dev, val_addr,
~(rf_ctrl->val_mask),
(value << rf_ctrl->val_shift));
}
}
}
} else {
const struct nphy_rf_control_override_rev2 *rf_ctrl;
if (off) {
b43_phy_mask(dev, B43_NPHY_RFCTL_OVER, ~(field));
value = 0;
} else {
b43_phy_set(dev, B43_NPHY_RFCTL_OVER, field);
}
for (i = 0; i < 2; i++) {
if (index <= 1 || index == 16) {
b43err(dev->wl,
"Unsupported RF Ctrl Override call\n");
return;
}
if (index == 2 || index == 10 ||
(index >= 13 && index <= 15)) {
core = 1;
}
rf_ctrl = &tbl_rf_control_override_rev2[index - 2];
addr = B43_PHY_N((i == 0) ?
rf_ctrl->addr0 : rf_ctrl->addr1);
if ((1 << i) & core)
b43_phy_maskset(dev, addr, ~(rf_ctrl->bmask),
(value << rf_ctrl->shift));
b43_phy_set(dev, B43_NPHY_RFCTL_OVER, 0x1);
b43_phy_set(dev, B43_NPHY_RFCTL_CMD,
B43_NPHY_RFCTL_CMD_START);
udelay(1);
b43_phy_mask(dev, B43_NPHY_RFCTL_OVER, 0xFFFE);
}
}
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/RFCtrlIntcOverride */
static void b43_nphy_rf_control_intc_override(struct b43_wldev *dev, u8 field,
u16 value, u8 core)
{
u8 i, j;
u16 reg, tmp, val;
B43_WARN_ON(dev->phy.rev < 3);
B43_WARN_ON(field > 4);
for (i = 0; i < 2; i++) {
if ((core == 1 && i == 1) || (core == 2 && !i))
continue;
reg = (i == 0) ?
B43_NPHY_RFCTL_INTC1 : B43_NPHY_RFCTL_INTC2;
b43_phy_set(dev, reg, 0x400);
switch (field) {
case 0:
b43_phy_write(dev, reg, 0);
b43_nphy_force_rf_sequence(dev, B43_RFSEQ_RESET2RX);
break;
case 1:
if (!i) {
b43_phy_maskset(dev, B43_NPHY_RFCTL_INTC1,
0xFC3F, (value << 6));
b43_phy_maskset(dev, B43_NPHY_TXF_40CO_B1S1,
0xFFFE, 1);
b43_phy_set(dev, B43_NPHY_RFCTL_CMD,
B43_NPHY_RFCTL_CMD_START);
for (j = 0; j < 100; j++) {
if (!(b43_phy_read(dev, B43_NPHY_RFCTL_CMD) & B43_NPHY_RFCTL_CMD_START)) {
j = 0;
break;
}
udelay(10);
}
if (j)
b43err(dev->wl,
"intc override timeout\n");
b43_phy_mask(dev, B43_NPHY_TXF_40CO_B1S1,
0xFFFE);
} else {
b43_phy_maskset(dev, B43_NPHY_RFCTL_INTC2,
0xFC3F, (value << 6));
b43_phy_maskset(dev, B43_NPHY_RFCTL_OVER,
0xFFFE, 1);
b43_phy_set(dev, B43_NPHY_RFCTL_CMD,
B43_NPHY_RFCTL_CMD_RXTX);
for (j = 0; j < 100; j++) {
if (!(b43_phy_read(dev, B43_NPHY_RFCTL_CMD) & B43_NPHY_RFCTL_CMD_RXTX)) {
j = 0;
break;
}
udelay(10);
}
if (j)
b43err(dev->wl,
"intc override timeout\n");
b43_phy_mask(dev, B43_NPHY_RFCTL_OVER,
0xFFFE);
}
break;
case 2:
if (b43_current_band(dev->wl) == IEEE80211_BAND_5GHZ) {
tmp = 0x0020;
val = value << 5;
} else {
tmp = 0x0010;
val = value << 4;
}
b43_phy_maskset(dev, reg, ~tmp, val);
break;
case 3:
if (b43_current_band(dev->wl) == IEEE80211_BAND_5GHZ) {
tmp = 0x0001;
val = value;
} else {
tmp = 0x0004;
val = value << 2;
}
b43_phy_maskset(dev, reg, ~tmp, val);
break;
case 4:
if (b43_current_band(dev->wl) == IEEE80211_BAND_5GHZ) {
tmp = 0x0002;
val = value << 1;
} else {
tmp = 0x0008;
val = value << 3;
}
b43_phy_maskset(dev, reg, ~tmp, val);
break;
}
}
}
/**************************************************
* Various PHY ops
**************************************************/
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/clip-detection */
static void b43_nphy_write_clip_detection(struct b43_wldev *dev,
const u16 *clip_st)
{
b43_phy_write(dev, B43_NPHY_C1_CLIP1THRES, clip_st[0]);
b43_phy_write(dev, B43_NPHY_C2_CLIP1THRES, clip_st[1]);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/clip-detection */
static void b43_nphy_read_clip_detection(struct b43_wldev *dev, u16 *clip_st)
{
clip_st[0] = b43_phy_read(dev, B43_NPHY_C1_CLIP1THRES);
clip_st[1] = b43_phy_read(dev, B43_NPHY_C2_CLIP1THRES);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/classifier */
static u16 b43_nphy_classifier(struct b43_wldev *dev, u16 mask, u16 val)
{
u16 tmp;
if (dev->dev->core_rev == 16)
b43_mac_suspend(dev);
tmp = b43_phy_read(dev, B43_NPHY_CLASSCTL);
tmp &= (B43_NPHY_CLASSCTL_CCKEN | B43_NPHY_CLASSCTL_OFDMEN |
B43_NPHY_CLASSCTL_WAITEDEN);
tmp &= ~mask;
tmp |= (val & mask);
b43_phy_maskset(dev, B43_NPHY_CLASSCTL, 0xFFF8, tmp);
if (dev->dev->core_rev == 16)
b43_mac_enable(dev);
return tmp;
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/CCA */
static void b43_nphy_reset_cca(struct b43_wldev *dev)
{
u16 bbcfg;
b43_phy_force_clock(dev, 1);
bbcfg = b43_phy_read(dev, B43_NPHY_BBCFG);
b43_phy_write(dev, B43_NPHY_BBCFG, bbcfg | B43_NPHY_BBCFG_RSTCCA);
udelay(1);
b43_phy_write(dev, B43_NPHY_BBCFG, bbcfg & ~B43_NPHY_BBCFG_RSTCCA);
b43_phy_force_clock(dev, 0);
b43_nphy_force_rf_sequence(dev, B43_RFSEQ_RESET2RX);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/carriersearch */
static void b43_nphy_stay_in_carrier_search(struct b43_wldev *dev, bool enable)
{
struct b43_phy *phy = &dev->phy;
struct b43_phy_n *nphy = phy->n;
if (enable) {
static const u16 clip[] = { 0xFFFF, 0xFFFF };
if (nphy->deaf_count++ == 0) {
nphy->classifier_state = b43_nphy_classifier(dev, 0, 0);
b43_nphy_classifier(dev, 0x7, 0);
b43_nphy_read_clip_detection(dev, nphy->clip_state);
b43_nphy_write_clip_detection(dev, clip);
}
b43_nphy_reset_cca(dev);
} else {
if (--nphy->deaf_count == 0) {
b43_nphy_classifier(dev, 0x7, nphy->classifier_state);
b43_nphy_write_clip_detection(dev, nphy->clip_state);
}
}
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/AdjustLnaGainTbl */
static void b43_nphy_adjust_lna_gain_table(struct b43_wldev *dev)
{
struct b43_phy_n *nphy = dev->phy.n;
u8 i;
s16 tmp;
u16 data[4];
s16 gain[2];
u16 minmax[2];
static const u16 lna_gain[4] = { -2, 10, 19, 25 };
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, 1);
if (nphy->gain_boost) {
if (b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ) {
gain[0] = 6;
gain[1] = 6;
} else {
tmp = 40370 - 315 * dev->phy.channel;
gain[0] = ((tmp >> 13) + ((tmp >> 12) & 1));
tmp = 23242 - 224 * dev->phy.channel;
gain[1] = ((tmp >> 13) + ((tmp >> 12) & 1));
}
} else {
gain[0] = 0;
gain[1] = 0;
}
for (i = 0; i < 2; i++) {
if (nphy->elna_gain_config) {
data[0] = 19 + gain[i];
data[1] = 25 + gain[i];
data[2] = 25 + gain[i];
data[3] = 25 + gain[i];
} else {
data[0] = lna_gain[0] + gain[i];
data[1] = lna_gain[1] + gain[i];
data[2] = lna_gain[2] + gain[i];
data[3] = lna_gain[3] + gain[i];
}
b43_ntab_write_bulk(dev, B43_NTAB16(i, 8), 4, data);
minmax[i] = 23 + gain[i];
}
b43_phy_maskset(dev, B43_NPHY_C1_MINMAX_GAIN, ~B43_NPHY_C1_MINGAIN,
minmax[0] << B43_NPHY_C1_MINGAIN_SHIFT);
b43_phy_maskset(dev, B43_NPHY_C2_MINMAX_GAIN, ~B43_NPHY_C2_MINGAIN,
minmax[1] << B43_NPHY_C2_MINGAIN_SHIFT);
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, 0);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/SetRfSeq */
static void b43_nphy_set_rf_sequence(struct b43_wldev *dev, u8 cmd,
u8 *events, u8 *delays, u8 length)
{
struct b43_phy_n *nphy = dev->phy.n;
u8 i;
u8 end = (dev->phy.rev >= 3) ? 0x1F : 0x0F;
u16 offset1 = cmd << 4;
u16 offset2 = offset1 + 0x80;
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, true);
b43_ntab_write_bulk(dev, B43_NTAB8(7, offset1), length, events);
b43_ntab_write_bulk(dev, B43_NTAB8(7, offset2), length, delays);
for (i = length; i < 16; i++) {
b43_ntab_write(dev, B43_NTAB8(7, offset1 + i), end);
b43_ntab_write(dev, B43_NTAB8(7, offset2 + i), 1);
}
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, false);
}
/**************************************************
* Radio 0x2056
**************************************************/
static void b43_chantab_radio_2056_upload(struct b43_wldev *dev,
const struct b43_nphy_channeltab_entry_rev3 *e)
{
b43_radio_write(dev, B2056_SYN_PLL_VCOCAL1, e->radio_syn_pll_vcocal1);
b43_radio_write(dev, B2056_SYN_PLL_VCOCAL2, e->radio_syn_pll_vcocal2);
b43_radio_write(dev, B2056_SYN_PLL_REFDIV, e->radio_syn_pll_refdiv);
b43_radio_write(dev, B2056_SYN_PLL_MMD2, e->radio_syn_pll_mmd2);
b43_radio_write(dev, B2056_SYN_PLL_MMD1, e->radio_syn_pll_mmd1);
b43_radio_write(dev, B2056_SYN_PLL_LOOPFILTER1,
e->radio_syn_pll_loopfilter1);
b43_radio_write(dev, B2056_SYN_PLL_LOOPFILTER2,
e->radio_syn_pll_loopfilter2);
b43_radio_write(dev, B2056_SYN_PLL_LOOPFILTER3,
e->radio_syn_pll_loopfilter3);
b43_radio_write(dev, B2056_SYN_PLL_LOOPFILTER4,
e->radio_syn_pll_loopfilter4);
b43_radio_write(dev, B2056_SYN_PLL_LOOPFILTER5,
e->radio_syn_pll_loopfilter5);
b43_radio_write(dev, B2056_SYN_RESERVED_ADDR27,
e->radio_syn_reserved_addr27);
b43_radio_write(dev, B2056_SYN_RESERVED_ADDR28,
e->radio_syn_reserved_addr28);
b43_radio_write(dev, B2056_SYN_RESERVED_ADDR29,
e->radio_syn_reserved_addr29);
b43_radio_write(dev, B2056_SYN_LOGEN_VCOBUF1,
e->radio_syn_logen_vcobuf1);
b43_radio_write(dev, B2056_SYN_LOGEN_MIXER2, e->radio_syn_logen_mixer2);
b43_radio_write(dev, B2056_SYN_LOGEN_BUF3, e->radio_syn_logen_buf3);
b43_radio_write(dev, B2056_SYN_LOGEN_BUF4, e->radio_syn_logen_buf4);
b43_radio_write(dev, B2056_RX0 | B2056_RX_LNAA_TUNE,
e->radio_rx0_lnaa_tune);
b43_radio_write(dev, B2056_RX0 | B2056_RX_LNAG_TUNE,
e->radio_rx0_lnag_tune);
b43_radio_write(dev, B2056_TX0 | B2056_TX_INTPAA_BOOST_TUNE,
e->radio_tx0_intpaa_boost_tune);
b43_radio_write(dev, B2056_TX0 | B2056_TX_INTPAG_BOOST_TUNE,
e->radio_tx0_intpag_boost_tune);
b43_radio_write(dev, B2056_TX0 | B2056_TX_PADA_BOOST_TUNE,
e->radio_tx0_pada_boost_tune);
b43_radio_write(dev, B2056_TX0 | B2056_TX_PADG_BOOST_TUNE,
e->radio_tx0_padg_boost_tune);
b43_radio_write(dev, B2056_TX0 | B2056_TX_PGAA_BOOST_TUNE,
e->radio_tx0_pgaa_boost_tune);
b43_radio_write(dev, B2056_TX0 | B2056_TX_PGAG_BOOST_TUNE,
e->radio_tx0_pgag_boost_tune);
b43_radio_write(dev, B2056_TX0 | B2056_TX_MIXA_BOOST_TUNE,
e->radio_tx0_mixa_boost_tune);
b43_radio_write(dev, B2056_TX0 | B2056_TX_MIXG_BOOST_TUNE,
e->radio_tx0_mixg_boost_tune);
b43_radio_write(dev, B2056_RX1 | B2056_RX_LNAA_TUNE,
e->radio_rx1_lnaa_tune);
b43_radio_write(dev, B2056_RX1 | B2056_RX_LNAG_TUNE,
e->radio_rx1_lnag_tune);
b43_radio_write(dev, B2056_TX1 | B2056_TX_INTPAA_BOOST_TUNE,
e->radio_tx1_intpaa_boost_tune);
b43_radio_write(dev, B2056_TX1 | B2056_TX_INTPAG_BOOST_TUNE,
e->radio_tx1_intpag_boost_tune);
b43_radio_write(dev, B2056_TX1 | B2056_TX_PADA_BOOST_TUNE,
e->radio_tx1_pada_boost_tune);
b43_radio_write(dev, B2056_TX1 | B2056_TX_PADG_BOOST_TUNE,
e->radio_tx1_padg_boost_tune);
b43_radio_write(dev, B2056_TX1 | B2056_TX_PGAA_BOOST_TUNE,
e->radio_tx1_pgaa_boost_tune);
b43_radio_write(dev, B2056_TX1 | B2056_TX_PGAG_BOOST_TUNE,
e->radio_tx1_pgag_boost_tune);
b43_radio_write(dev, B2056_TX1 | B2056_TX_MIXA_BOOST_TUNE,
e->radio_tx1_mixa_boost_tune);
b43_radio_write(dev, B2056_TX1 | B2056_TX_MIXG_BOOST_TUNE,
e->radio_tx1_mixg_boost_tune);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/Radio/2056Setup */
static void b43_radio_2056_setup(struct b43_wldev *dev,
const struct b43_nphy_channeltab_entry_rev3 *e)
{
struct ssb_sprom *sprom = dev->dev->bus_sprom;
enum ieee80211_band band = b43_current_band(dev->wl);
u16 offset;
u8 i;
u16 bias, cbias, pag_boost, pgag_boost, mixg_boost, padg_boost;
B43_WARN_ON(dev->phy.rev < 3);
b43_chantab_radio_2056_upload(dev, e);
b2056_upload_syn_pll_cp2(dev, band == IEEE80211_BAND_5GHZ);
if (sprom->boardflags2_lo & B43_BFL2_GPLL_WAR &&
b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ) {
b43_radio_write(dev, B2056_SYN_PLL_LOOPFILTER1, 0x1F);
b43_radio_write(dev, B2056_SYN_PLL_LOOPFILTER2, 0x1F);
if (dev->dev->chip_id == 0x4716) {
b43_radio_write(dev, B2056_SYN_PLL_LOOPFILTER4, 0x14);
b43_radio_write(dev, B2056_SYN_PLL_CP2, 0);
} else {
b43_radio_write(dev, B2056_SYN_PLL_LOOPFILTER4, 0x0B);
b43_radio_write(dev, B2056_SYN_PLL_CP2, 0x14);
}
}
if (sprom->boardflags2_lo & B43_BFL2_APLL_WAR &&
b43_current_band(dev->wl) == IEEE80211_BAND_5GHZ) {
b43_radio_write(dev, B2056_SYN_PLL_LOOPFILTER1, 0x1F);
b43_radio_write(dev, B2056_SYN_PLL_LOOPFILTER2, 0x1F);
b43_radio_write(dev, B2056_SYN_PLL_LOOPFILTER4, 0x05);
b43_radio_write(dev, B2056_SYN_PLL_CP2, 0x0C);
}
if (dev->phy.n->ipa2g_on && band == IEEE80211_BAND_2GHZ) {
for (i = 0; i < 2; i++) {
offset = i ? B2056_TX1 : B2056_TX0;
if (dev->phy.rev >= 5) {
b43_radio_write(dev,
offset | B2056_TX_PADG_IDAC, 0xcc);
if (dev->dev->chip_id == 0x4716) {
bias = 0x40;
cbias = 0x45;
pag_boost = 0x5;
pgag_boost = 0x33;
mixg_boost = 0x55;
} else {
bias = 0x25;
cbias = 0x20;
pag_boost = 0x4;
pgag_boost = 0x03;
mixg_boost = 0x65;
}
padg_boost = 0x77;
b43_radio_write(dev,
offset | B2056_TX_INTPAG_IMAIN_STAT,
bias);
b43_radio_write(dev,
offset | B2056_TX_INTPAG_IAUX_STAT,
bias);
b43_radio_write(dev,
offset | B2056_TX_INTPAG_CASCBIAS,
cbias);
b43_radio_write(dev,
offset | B2056_TX_INTPAG_BOOST_TUNE,
pag_boost);
b43_radio_write(dev,
offset | B2056_TX_PGAG_BOOST_TUNE,
pgag_boost);
b43_radio_write(dev,
offset | B2056_TX_PADG_BOOST_TUNE,
padg_boost);
b43_radio_write(dev,
offset | B2056_TX_MIXG_BOOST_TUNE,
mixg_boost);
} else {
bias = dev->phy.is_40mhz ? 0x40 : 0x20;
b43_radio_write(dev,
offset | B2056_TX_INTPAG_IMAIN_STAT,
bias);
b43_radio_write(dev,
offset | B2056_TX_INTPAG_IAUX_STAT,
bias);
b43_radio_write(dev,
offset | B2056_TX_INTPAG_CASCBIAS,
0x30);
}
b43_radio_write(dev, offset | B2056_TX_PA_SPARE1, 0xee);
}
} else if (dev->phy.n->ipa5g_on && band == IEEE80211_BAND_5GHZ) {
/* TODO */
}
udelay(50);
/* VCO calibration */
b43_radio_write(dev, B2056_SYN_PLL_VCOCAL12, 0x00);
b43_radio_write(dev, B2056_TX_INTPAA_PA_MISC, 0x38);
b43_radio_write(dev, B2056_TX_INTPAA_PA_MISC, 0x18);
b43_radio_write(dev, B2056_TX_INTPAA_PA_MISC, 0x38);
b43_radio_write(dev, B2056_TX_INTPAA_PA_MISC, 0x39);
udelay(300);
}
static void b43_radio_init2056_pre(struct b43_wldev *dev)
{
b43_phy_mask(dev, B43_NPHY_RFCTL_CMD,
~B43_NPHY_RFCTL_CMD_CHIP0PU);
/* Maybe wl meant to reset and set (order?) RFCTL_CMD_OEPORFORCE? */
b43_phy_mask(dev, B43_NPHY_RFCTL_CMD,
B43_NPHY_RFCTL_CMD_OEPORFORCE);
b43_phy_set(dev, B43_NPHY_RFCTL_CMD,
~B43_NPHY_RFCTL_CMD_OEPORFORCE);
b43_phy_set(dev, B43_NPHY_RFCTL_CMD,
B43_NPHY_RFCTL_CMD_CHIP0PU);
}
static void b43_radio_init2056_post(struct b43_wldev *dev)
{
b43_radio_set(dev, B2056_SYN_COM_CTRL, 0xB);
b43_radio_set(dev, B2056_SYN_COM_PU, 0x2);
b43_radio_set(dev, B2056_SYN_COM_RESET, 0x2);
msleep(1);
b43_radio_mask(dev, B2056_SYN_COM_RESET, ~0x2);
b43_radio_mask(dev, B2056_SYN_PLL_MAST2, ~0xFC);
b43_radio_mask(dev, B2056_SYN_RCCAL_CTRL0, ~0x1);
/*
if (nphy->init_por)
Call Radio 2056 Recalibrate
*/
}
/*
* Initialize a Broadcom 2056 N-radio
* http://bcm-v4.sipsolutions.net/802.11/Radio/2056/Init
*/
static void b43_radio_init2056(struct b43_wldev *dev)
{
b43_radio_init2056_pre(dev);
b2056_upload_inittabs(dev, 0, 0);
b43_radio_init2056_post(dev);
}
/**************************************************
* Radio 0x2055
**************************************************/
static void b43_chantab_radio_upload(struct b43_wldev *dev,
const struct b43_nphy_channeltab_entry_rev2 *e)
{
b43_radio_write(dev, B2055_PLL_REF, e->radio_pll_ref);
b43_radio_write(dev, B2055_RF_PLLMOD0, e->radio_rf_pllmod0);
b43_radio_write(dev, B2055_RF_PLLMOD1, e->radio_rf_pllmod1);
b43_radio_write(dev, B2055_VCO_CAPTAIL, e->radio_vco_captail);
b43_read32(dev, B43_MMIO_MACCTL); /* flush writes */
b43_radio_write(dev, B2055_VCO_CAL1, e->radio_vco_cal1);
b43_radio_write(dev, B2055_VCO_CAL2, e->radio_vco_cal2);
b43_radio_write(dev, B2055_PLL_LFC1, e->radio_pll_lfc1);
b43_radio_write(dev, B2055_PLL_LFR1, e->radio_pll_lfr1);
b43_read32(dev, B43_MMIO_MACCTL); /* flush writes */
b43_radio_write(dev, B2055_PLL_LFC2, e->radio_pll_lfc2);
b43_radio_write(dev, B2055_LGBUF_CENBUF, e->radio_lgbuf_cenbuf);
b43_radio_write(dev, B2055_LGEN_TUNE1, e->radio_lgen_tune1);
b43_radio_write(dev, B2055_LGEN_TUNE2, e->radio_lgen_tune2);
b43_read32(dev, B43_MMIO_MACCTL); /* flush writes */
b43_radio_write(dev, B2055_C1_LGBUF_ATUNE, e->radio_c1_lgbuf_atune);
b43_radio_write(dev, B2055_C1_LGBUF_GTUNE, e->radio_c1_lgbuf_gtune);
b43_radio_write(dev, B2055_C1_RX_RFR1, e->radio_c1_rx_rfr1);
b43_radio_write(dev, B2055_C1_TX_PGAPADTN, e->radio_c1_tx_pgapadtn);
b43_read32(dev, B43_MMIO_MACCTL); /* flush writes */
b43_radio_write(dev, B2055_C1_TX_MXBGTRIM, e->radio_c1_tx_mxbgtrim);
b43_radio_write(dev, B2055_C2_LGBUF_ATUNE, e->radio_c2_lgbuf_atune);
b43_radio_write(dev, B2055_C2_LGBUF_GTUNE, e->radio_c2_lgbuf_gtune);
b43_radio_write(dev, B2055_C2_RX_RFR1, e->radio_c2_rx_rfr1);
b43_read32(dev, B43_MMIO_MACCTL); /* flush writes */
b43_radio_write(dev, B2055_C2_TX_PGAPADTN, e->radio_c2_tx_pgapadtn);
b43_radio_write(dev, B2055_C2_TX_MXBGTRIM, e->radio_c2_tx_mxbgtrim);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/Radio/2055Setup */
static void b43_radio_2055_setup(struct b43_wldev *dev,
const struct b43_nphy_channeltab_entry_rev2 *e)
{
B43_WARN_ON(dev->phy.rev >= 3);
b43_chantab_radio_upload(dev, e);
udelay(50);
b43_radio_write(dev, B2055_VCO_CAL10, 0x05);
b43_radio_write(dev, B2055_VCO_CAL10, 0x45);
b43_read32(dev, B43_MMIO_MACCTL); /* flush writes */
b43_radio_write(dev, B2055_VCO_CAL10, 0x65);
udelay(300);
}
static void b43_radio_init2055_pre(struct b43_wldev *dev)
{
b43_phy_mask(dev, B43_NPHY_RFCTL_CMD,
~B43_NPHY_RFCTL_CMD_PORFORCE);
b43_phy_set(dev, B43_NPHY_RFCTL_CMD,
B43_NPHY_RFCTL_CMD_CHIP0PU |
B43_NPHY_RFCTL_CMD_OEPORFORCE);
b43_phy_set(dev, B43_NPHY_RFCTL_CMD,
B43_NPHY_RFCTL_CMD_PORFORCE);
}
static void b43_radio_init2055_post(struct b43_wldev *dev)
{
struct b43_phy_n *nphy = dev->phy.n;
struct ssb_sprom *sprom = dev->dev->bus_sprom;
int i;
u16 val;
bool workaround = false;
if (sprom->revision < 4)
workaround = (dev->dev->board_vendor != PCI_VENDOR_ID_BROADCOM
&& dev->dev->board_type == 0x46D
&& dev->dev->board_rev >= 0x41);
else
workaround =
!(sprom->boardflags2_lo & B43_BFL2_RXBB_INT_REG_DIS);
b43_radio_mask(dev, B2055_MASTER1, 0xFFF3);
if (workaround) {
b43_radio_mask(dev, B2055_C1_RX_BB_REG, 0x7F);
b43_radio_mask(dev, B2055_C2_RX_BB_REG, 0x7F);
}
b43_radio_maskset(dev, B2055_RRCCAL_NOPTSEL, 0xFFC0, 0x2C);
b43_radio_write(dev, B2055_CAL_MISC, 0x3C);
b43_radio_mask(dev, B2055_CAL_MISC, 0xFFBE);
b43_radio_set(dev, B2055_CAL_LPOCTL, 0x80);
b43_radio_set(dev, B2055_CAL_MISC, 0x1);
msleep(1);
b43_radio_set(dev, B2055_CAL_MISC, 0x40);
for (i = 0; i < 200; i++) {
val = b43_radio_read(dev, B2055_CAL_COUT2);
if (val & 0x80) {
i = 0;
break;
}
udelay(10);
}
if (i)
b43err(dev->wl, "radio post init timeout\n");
b43_radio_mask(dev, B2055_CAL_LPOCTL, 0xFF7F);
b43_switch_channel(dev, dev->phy.channel);
b43_radio_write(dev, B2055_C1_RX_BB_LPF, 0x9);
b43_radio_write(dev, B2055_C2_RX_BB_LPF, 0x9);
b43_radio_write(dev, B2055_C1_RX_BB_MIDACHP, 0x83);
b43_radio_write(dev, B2055_C2_RX_BB_MIDACHP, 0x83);
b43_radio_maskset(dev, B2055_C1_LNA_GAINBST, 0xFFF8, 0x6);
b43_radio_maskset(dev, B2055_C2_LNA_GAINBST, 0xFFF8, 0x6);
if (!nphy->gain_boost) {
b43_radio_set(dev, B2055_C1_RX_RFSPC1, 0x2);
b43_radio_set(dev, B2055_C2_RX_RFSPC1, 0x2);
} else {
b43_radio_mask(dev, B2055_C1_RX_RFSPC1, 0xFFFD);
b43_radio_mask(dev, B2055_C2_RX_RFSPC1, 0xFFFD);
}
udelay(2);
}
/*
* Initialize a Broadcom 2055 N-radio
* http://bcm-v4.sipsolutions.net/802.11/Radio/2055/Init
*/
static void b43_radio_init2055(struct b43_wldev *dev)
{
b43_radio_init2055_pre(dev);
if (b43_status(dev) < B43_STAT_INITIALIZED) {
/* Follow wl, not specs. Do not force uploading all regs */
b2055_upload_inittab(dev, 0, 0);
} else {
bool ghz5 = b43_current_band(dev->wl) == IEEE80211_BAND_5GHZ;
b2055_upload_inittab(dev, ghz5, 0);
}
b43_radio_init2055_post(dev);
}
/**************************************************
* Samples
**************************************************/
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/LoadSampleTable */
static int b43_nphy_load_samples(struct b43_wldev *dev,
struct b43_c32 *samples, u16 len) {
struct b43_phy_n *nphy = dev->phy.n;
u16 i;
u32 *data;
data = kzalloc(len * sizeof(u32), GFP_KERNEL);
if (!data) {
b43err(dev->wl, "allocation for samples loading failed\n");
return -ENOMEM;
}
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, 1);
for (i = 0; i < len; i++) {
data[i] = (samples[i].i & 0x3FF << 10);
data[i] |= samples[i].q & 0x3FF;
}
b43_ntab_write_bulk(dev, B43_NTAB32(17, 0), len, data);
kfree(data);
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, 0);
return 0;
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/GenLoadSamples */
static u16 b43_nphy_gen_load_samples(struct b43_wldev *dev, u32 freq, u16 max,
bool test)
{
int i;
u16 bw, len, rot, angle;
struct b43_c32 *samples;
bw = (dev->phy.is_40mhz) ? 40 : 20;
len = bw << 3;
if (test) {
if (b43_phy_read(dev, B43_NPHY_BBCFG) & B43_NPHY_BBCFG_RSTRX)
bw = 82;
else
bw = 80;
if (dev->phy.is_40mhz)
bw <<= 1;
len = bw << 1;
}
samples = kcalloc(len, sizeof(struct b43_c32), GFP_KERNEL);
if (!samples) {
b43err(dev->wl, "allocation for samples generation failed\n");
return 0;
}
rot = (((freq * 36) / bw) << 16) / 100;
angle = 0;
for (i = 0; i < len; i++) {
samples[i] = b43_cordic(angle);
angle += rot;
samples[i].q = CORDIC_CONVERT(samples[i].q * max);
samples[i].i = CORDIC_CONVERT(samples[i].i * max);
}
i = b43_nphy_load_samples(dev, samples, len);
kfree(samples);
return (i < 0) ? 0 : len;
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/RunSamples */
static void b43_nphy_run_samples(struct b43_wldev *dev, u16 samps, u16 loops,
u16 wait, bool iqmode, bool dac_test)
{
struct b43_phy_n *nphy = dev->phy.n;
int i;
u16 seq_mode;
u32 tmp;
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, true);
if ((nphy->bb_mult_save & 0x80000000) == 0) {
tmp = b43_ntab_read(dev, B43_NTAB16(15, 87));
nphy->bb_mult_save = (tmp & 0xFFFF) | 0x80000000;
}
if (!dev->phy.is_40mhz)
tmp = 0x6464;
else
tmp = 0x4747;
b43_ntab_write(dev, B43_NTAB16(15, 87), tmp);
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, false);
b43_phy_write(dev, B43_NPHY_SAMP_DEPCNT, (samps - 1));
if (loops != 0xFFFF)
b43_phy_write(dev, B43_NPHY_SAMP_LOOPCNT, (loops - 1));
else
b43_phy_write(dev, B43_NPHY_SAMP_LOOPCNT, loops);
b43_phy_write(dev, B43_NPHY_SAMP_WAITCNT, wait);
seq_mode = b43_phy_read(dev, B43_NPHY_RFSEQMODE);
b43_phy_set(dev, B43_NPHY_RFSEQMODE, B43_NPHY_RFSEQMODE_CAOVER);
if (iqmode) {
b43_phy_mask(dev, B43_NPHY_IQLOCAL_CMDGCTL, 0x7FFF);
b43_phy_set(dev, B43_NPHY_IQLOCAL_CMDGCTL, 0x8000);
} else {
if (dac_test)
b43_phy_write(dev, B43_NPHY_SAMP_CMD, 5);
else
b43_phy_write(dev, B43_NPHY_SAMP_CMD, 1);
}
for (i = 0; i < 100; i++) {
if (!(b43_phy_read(dev, B43_NPHY_RFSEQST) & 1)) {
i = 0;
break;
}
udelay(10);
}
if (i)
b43err(dev->wl, "run samples timeout\n");
b43_phy_write(dev, B43_NPHY_RFSEQMODE, seq_mode);
}
/**************************************************
* RSSI
**************************************************/
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/ScaleOffsetRssi */
static void b43_nphy_scale_offset_rssi(struct b43_wldev *dev, u16 scale,
s8 offset, u8 core, u8 rail,
enum b43_nphy_rssi_type type)
{
u16 tmp;
bool core1or5 = (core == 1) || (core == 5);
bool core2or5 = (core == 2) || (core == 5);
offset = clamp_val(offset, -32, 31);
tmp = ((scale & 0x3F) << 8) | (offset & 0x3F);
if (core1or5 && (rail == 0) && (type == B43_NPHY_RSSI_Z))
b43_phy_write(dev, B43_NPHY_RSSIMC_0I_RSSI_Z, tmp);
if (core1or5 && (rail == 1) && (type == B43_NPHY_RSSI_Z))
b43_phy_write(dev, B43_NPHY_RSSIMC_0Q_RSSI_Z, tmp);
if (core2or5 && (rail == 0) && (type == B43_NPHY_RSSI_Z))
b43_phy_write(dev, B43_NPHY_RSSIMC_1I_RSSI_Z, tmp);
if (core2or5 && (rail == 1) && (type == B43_NPHY_RSSI_Z))
b43_phy_write(dev, B43_NPHY_RSSIMC_1Q_RSSI_Z, tmp);
if (core1or5 && (rail == 0) && (type == B43_NPHY_RSSI_X))
b43_phy_write(dev, B43_NPHY_RSSIMC_0I_RSSI_X, tmp);
if (core1or5 && (rail == 1) && (type == B43_NPHY_RSSI_X))
b43_phy_write(dev, B43_NPHY_RSSIMC_0Q_RSSI_X, tmp);
if (core2or5 && (rail == 0) && (type == B43_NPHY_RSSI_X))
b43_phy_write(dev, B43_NPHY_RSSIMC_1I_RSSI_X, tmp);
if (core2or5 && (rail == 1) && (type == B43_NPHY_RSSI_X))
b43_phy_write(dev, B43_NPHY_RSSIMC_1Q_RSSI_X, tmp);
if (core1or5 && (rail == 0) && (type == B43_NPHY_RSSI_Y))
b43_phy_write(dev, B43_NPHY_RSSIMC_0I_RSSI_Y, tmp);
if (core1or5 && (rail == 1) && (type == B43_NPHY_RSSI_Y))
b43_phy_write(dev, B43_NPHY_RSSIMC_0Q_RSSI_Y, tmp);
if (core2or5 && (rail == 0) && (type == B43_NPHY_RSSI_Y))
b43_phy_write(dev, B43_NPHY_RSSIMC_1I_RSSI_Y, tmp);
if (core2or5 && (rail == 1) && (type == B43_NPHY_RSSI_Y))
b43_phy_write(dev, B43_NPHY_RSSIMC_1Q_RSSI_Y, tmp);
if (core1or5 && (rail == 0) && (type == B43_NPHY_RSSI_TBD))
b43_phy_write(dev, B43_NPHY_RSSIMC_0I_TBD, tmp);
if (core1or5 && (rail == 1) && (type == B43_NPHY_RSSI_TBD))
b43_phy_write(dev, B43_NPHY_RSSIMC_0Q_TBD, tmp);
if (core2or5 && (rail == 0) && (type == B43_NPHY_RSSI_TBD))
b43_phy_write(dev, B43_NPHY_RSSIMC_1I_TBD, tmp);
if (core2or5 && (rail == 1) && (type == B43_NPHY_RSSI_TBD))
b43_phy_write(dev, B43_NPHY_RSSIMC_1Q_TBD, tmp);
if (core1or5 && (rail == 0) && (type == B43_NPHY_RSSI_PWRDET))
b43_phy_write(dev, B43_NPHY_RSSIMC_0I_PWRDET, tmp);
if (core1or5 && (rail == 1) && (type == B43_NPHY_RSSI_PWRDET))
b43_phy_write(dev, B43_NPHY_RSSIMC_0Q_PWRDET, tmp);
if (core2or5 && (rail == 0) && (type == B43_NPHY_RSSI_PWRDET))
b43_phy_write(dev, B43_NPHY_RSSIMC_1I_PWRDET, tmp);
if (core2or5 && (rail == 1) && (type == B43_NPHY_RSSI_PWRDET))
b43_phy_write(dev, B43_NPHY_RSSIMC_1Q_PWRDET, tmp);
if (core1or5 && (type == B43_NPHY_RSSI_TSSI_I))
b43_phy_write(dev, B43_NPHY_RSSIMC_0I_TSSI, tmp);
if (core2or5 && (type == B43_NPHY_RSSI_TSSI_I))
b43_phy_write(dev, B43_NPHY_RSSIMC_1I_TSSI, tmp);
if (core1or5 && (type == B43_NPHY_RSSI_TSSI_Q))
b43_phy_write(dev, B43_NPHY_RSSIMC_0Q_TSSI, tmp);
if (core2or5 && (type == B43_NPHY_RSSI_TSSI_Q))
b43_phy_write(dev, B43_NPHY_RSSIMC_1Q_TSSI, tmp);
}
static void b43_nphy_rev3_rssi_select(struct b43_wldev *dev, u8 code, u8 type)
{
u8 i;
u16 reg, val;
if (code == 0) {
b43_phy_mask(dev, B43_NPHY_AFECTL_OVER1, 0xFDFF);
b43_phy_mask(dev, B43_NPHY_AFECTL_OVER, 0xFDFF);
b43_phy_mask(dev, B43_NPHY_AFECTL_C1, 0xFCFF);
b43_phy_mask(dev, B43_NPHY_AFECTL_C2, 0xFCFF);
b43_phy_mask(dev, B43_NPHY_TXF_40CO_B1S0, 0xFFDF);
b43_phy_mask(dev, B43_NPHY_TXF_40CO_B32S1, 0xFFDF);
b43_phy_mask(dev, B43_NPHY_RFCTL_LUT_TRSW_UP1, 0xFFC3);
b43_phy_mask(dev, B43_NPHY_RFCTL_LUT_TRSW_UP2, 0xFFC3);
} else {
for (i = 0; i < 2; i++) {
if ((code == 1 && i == 1) || (code == 2 && !i))
continue;
reg = (i == 0) ?
B43_NPHY_AFECTL_OVER1 : B43_NPHY_AFECTL_OVER;
b43_phy_maskset(dev, reg, 0xFDFF, 0x0200);
if (type < 3) {
reg = (i == 0) ?
B43_NPHY_AFECTL_C1 :
B43_NPHY_AFECTL_C2;
b43_phy_maskset(dev, reg, 0xFCFF, 0);
reg = (i == 0) ?
B43_NPHY_RFCTL_LUT_TRSW_UP1 :
B43_NPHY_RFCTL_LUT_TRSW_UP2;
b43_phy_maskset(dev, reg, 0xFFC3, 0);
if (type == 0)
val = (b43_current_band(dev->wl) == IEEE80211_BAND_5GHZ) ? 4 : 8;
else if (type == 1)
val = 16;
else
val = 32;
b43_phy_set(dev, reg, val);
reg = (i == 0) ?
B43_NPHY_TXF_40CO_B1S0 :
B43_NPHY_TXF_40CO_B32S1;
b43_phy_set(dev, reg, 0x0020);
} else {
if (type == 6)
val = 0x0100;
else if (type == 3)
val = 0x0200;
else
val = 0x0300;
reg = (i == 0) ?
B43_NPHY_AFECTL_C1 :
B43_NPHY_AFECTL_C2;
b43_phy_maskset(dev, reg, 0xFCFF, val);
b43_phy_maskset(dev, reg, 0xF3FF, val << 2);
if (type != 3 && type != 6) {
enum ieee80211_band band =
b43_current_band(dev->wl);
if (b43_nphy_ipa(dev))
val = (band == IEEE80211_BAND_5GHZ) ? 0xC : 0xE;
else
val = 0x11;
reg = (i == 0) ? 0x2000 : 0x3000;
reg |= B2055_PADDRV;
b43_radio_write16(dev, reg, val);
reg = (i == 0) ?
B43_NPHY_AFECTL_OVER1 :
B43_NPHY_AFECTL_OVER;
b43_phy_set(dev, reg, 0x0200);
}
}
}
}
}
static void b43_nphy_rev2_rssi_select(struct b43_wldev *dev, u8 code, u8 type)
{
u16 val;
if (type < 3)
val = 0;
else if (type == 6)
val = 1;
else if (type == 3)
val = 2;
else
val = 3;
val = (val << 12) | (val << 14);
b43_phy_maskset(dev, B43_NPHY_AFECTL_C1, 0x0FFF, val);
b43_phy_maskset(dev, B43_NPHY_AFECTL_C2, 0x0FFF, val);
if (type < 3) {
b43_phy_maskset(dev, B43_NPHY_RFCTL_RSSIO1, 0xFFCF,
(type + 1) << 4);
b43_phy_maskset(dev, B43_NPHY_RFCTL_RSSIO2, 0xFFCF,
(type + 1) << 4);
}
if (code == 0) {
b43_phy_mask(dev, B43_NPHY_AFECTL_OVER, ~0x3000);
if (type < 3) {
b43_phy_mask(dev, B43_NPHY_RFCTL_CMD,
~(B43_NPHY_RFCTL_CMD_RXEN |
B43_NPHY_RFCTL_CMD_CORESEL));
b43_phy_mask(dev, B43_NPHY_RFCTL_OVER,
~(0x1 << 12 |
0x1 << 5 |
0x1 << 1 |
0x1));
b43_phy_mask(dev, B43_NPHY_RFCTL_CMD,
~B43_NPHY_RFCTL_CMD_START);
udelay(20);
b43_phy_mask(dev, B43_NPHY_RFCTL_OVER, ~0x1);
}
} else {
b43_phy_set(dev, B43_NPHY_AFECTL_OVER, 0x3000);
if (type < 3) {
b43_phy_maskset(dev, B43_NPHY_RFCTL_CMD,
~(B43_NPHY_RFCTL_CMD_RXEN |
B43_NPHY_RFCTL_CMD_CORESEL),
(B43_NPHY_RFCTL_CMD_RXEN |
code << B43_NPHY_RFCTL_CMD_CORESEL_SHIFT));
b43_phy_set(dev, B43_NPHY_RFCTL_OVER,
(0x1 << 12 |
0x1 << 5 |
0x1 << 1 |
0x1));
b43_phy_set(dev, B43_NPHY_RFCTL_CMD,
B43_NPHY_RFCTL_CMD_START);
udelay(20);
b43_phy_mask(dev, B43_NPHY_RFCTL_OVER, ~0x1);
}
}
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/RSSISel */
static void b43_nphy_rssi_select(struct b43_wldev *dev, u8 code, u8 type)
{
if (dev->phy.rev >= 3)
b43_nphy_rev3_rssi_select(dev, code, type);
else
b43_nphy_rev2_rssi_select(dev, code, type);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/SetRssi2055Vcm */
static void b43_nphy_set_rssi_2055_vcm(struct b43_wldev *dev, u8 type, u8 *buf)
{
int i;
for (i = 0; i < 2; i++) {
if (type == 2) {
if (i == 0) {
b43_radio_maskset(dev, B2055_C1_B0NB_RSSIVCM,
0xFC, buf[0]);
b43_radio_maskset(dev, B2055_C1_RX_BB_RSSICTL5,
0xFC, buf[1]);
} else {
b43_radio_maskset(dev, B2055_C2_B0NB_RSSIVCM,
0xFC, buf[2 * i]);
b43_radio_maskset(dev, B2055_C2_RX_BB_RSSICTL5,
0xFC, buf[2 * i + 1]);
}
} else {
if (i == 0)
b43_radio_maskset(dev, B2055_C1_RX_BB_RSSICTL5,
0xF3, buf[0] << 2);
else
b43_radio_maskset(dev, B2055_C2_RX_BB_RSSICTL5,
0xF3, buf[2 * i + 1] << 2);
}
}
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/PollRssi */
static int b43_nphy_poll_rssi(struct b43_wldev *dev, u8 type, s32 *buf,
u8 nsamp)
{
int i;
int out;
u16 save_regs_phy[9];
u16 s[2];
if (dev->phy.rev >= 3) {
save_regs_phy[0] = b43_phy_read(dev, B43_NPHY_AFECTL_C1);
save_regs_phy[1] = b43_phy_read(dev, B43_NPHY_AFECTL_C2);
save_regs_phy[2] = b43_phy_read(dev,
B43_NPHY_RFCTL_LUT_TRSW_UP1);
save_regs_phy[3] = b43_phy_read(dev,
B43_NPHY_RFCTL_LUT_TRSW_UP2);
save_regs_phy[4] = b43_phy_read(dev, B43_NPHY_AFECTL_OVER1);
save_regs_phy[5] = b43_phy_read(dev, B43_NPHY_AFECTL_OVER);
save_regs_phy[6] = b43_phy_read(dev, B43_NPHY_TXF_40CO_B1S0);
save_regs_phy[7] = b43_phy_read(dev, B43_NPHY_TXF_40CO_B32S1);
save_regs_phy[8] = 0;
} else {
save_regs_phy[0] = b43_phy_read(dev, B43_NPHY_AFECTL_C1);
save_regs_phy[1] = b43_phy_read(dev, B43_NPHY_AFECTL_C2);
save_regs_phy[2] = b43_phy_read(dev, B43_NPHY_AFECTL_OVER);
save_regs_phy[3] = b43_phy_read(dev, B43_NPHY_RFCTL_CMD);
save_regs_phy[4] = b43_phy_read(dev, B43_NPHY_RFCTL_OVER);
save_regs_phy[5] = b43_phy_read(dev, B43_NPHY_RFCTL_RSSIO1);
save_regs_phy[6] = b43_phy_read(dev, B43_NPHY_RFCTL_RSSIO2);
save_regs_phy[7] = 0;
save_regs_phy[8] = 0;
}
b43_nphy_rssi_select(dev, 5, type);
if (dev->phy.rev < 2) {
save_regs_phy[8] = b43_phy_read(dev, B43_NPHY_GPIO_SEL);
b43_phy_write(dev, B43_NPHY_GPIO_SEL, 5);
}
for (i = 0; i < 4; i++)
buf[i] = 0;
for (i = 0; i < nsamp; i++) {
if (dev->phy.rev < 2) {
s[0] = b43_phy_read(dev, B43_NPHY_GPIO_LOOUT);
s[1] = b43_phy_read(dev, B43_NPHY_GPIO_HIOUT);
} else {
s[0] = b43_phy_read(dev, B43_NPHY_RSSI1);
s[1] = b43_phy_read(dev, B43_NPHY_RSSI2);
}
buf[0] += ((s8)((s[0] & 0x3F) << 2)) >> 2;
buf[1] += ((s8)(((s[0] >> 8) & 0x3F) << 2)) >> 2;
buf[2] += ((s8)((s[1] & 0x3F) << 2)) >> 2;
buf[3] += ((s8)(((s[1] >> 8) & 0x3F) << 2)) >> 2;
}
out = (buf[0] & 0xFF) << 24 | (buf[1] & 0xFF) << 16 |
(buf[2] & 0xFF) << 8 | (buf[3] & 0xFF);
if (dev->phy.rev < 2)
b43_phy_write(dev, B43_NPHY_GPIO_SEL, save_regs_phy[8]);
if (dev->phy.rev >= 3) {
b43_phy_write(dev, B43_NPHY_AFECTL_C1, save_regs_phy[0]);
b43_phy_write(dev, B43_NPHY_AFECTL_C2, save_regs_phy[1]);
b43_phy_write(dev, B43_NPHY_RFCTL_LUT_TRSW_UP1,
save_regs_phy[2]);
b43_phy_write(dev, B43_NPHY_RFCTL_LUT_TRSW_UP2,
save_regs_phy[3]);
b43_phy_write(dev, B43_NPHY_AFECTL_OVER1, save_regs_phy[4]);
b43_phy_write(dev, B43_NPHY_AFECTL_OVER, save_regs_phy[5]);
b43_phy_write(dev, B43_NPHY_TXF_40CO_B1S0, save_regs_phy[6]);
b43_phy_write(dev, B43_NPHY_TXF_40CO_B32S1, save_regs_phy[7]);
} else {
b43_phy_write(dev, B43_NPHY_AFECTL_C1, save_regs_phy[0]);
b43_phy_write(dev, B43_NPHY_AFECTL_C2, save_regs_phy[1]);
b43_phy_write(dev, B43_NPHY_AFECTL_OVER, save_regs_phy[2]);
b43_phy_write(dev, B43_NPHY_RFCTL_CMD, save_regs_phy[3]);
b43_phy_write(dev, B43_NPHY_RFCTL_OVER, save_regs_phy[4]);
b43_phy_write(dev, B43_NPHY_RFCTL_RSSIO1, save_regs_phy[5]);
b43_phy_write(dev, B43_NPHY_RFCTL_RSSIO2, save_regs_phy[6]);
}
return out;
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/RSSICalRev3 */
static void b43_nphy_rev3_rssi_cal(struct b43_wldev *dev)
{
struct b43_phy_n *nphy = dev->phy.n;
u16 saved_regs_phy_rfctl[2];
u16 saved_regs_phy[13];
u16 regs_to_store[] = {
B43_NPHY_AFECTL_OVER1, B43_NPHY_AFECTL_OVER,
B43_NPHY_AFECTL_C1, B43_NPHY_AFECTL_C2,
B43_NPHY_TXF_40CO_B1S1, B43_NPHY_RFCTL_OVER,
B43_NPHY_TXF_40CO_B1S0, B43_NPHY_TXF_40CO_B32S1,
B43_NPHY_RFCTL_CMD,
B43_NPHY_RFCTL_LUT_TRSW_UP1, B43_NPHY_RFCTL_LUT_TRSW_UP2,
B43_NPHY_RFCTL_RSSIO1, B43_NPHY_RFCTL_RSSIO2
};
u16 class;
u16 clip_state[2];
u16 clip_off[2] = { 0xFFFF, 0xFFFF };
u8 vcm_final = 0;
s8 offset[4];
s32 results[8][4] = { };
s32 results_min[4] = { };
s32 poll_results[4] = { };
u16 *rssical_radio_regs = NULL;
u16 *rssical_phy_regs = NULL;
u16 r; /* routing */
u8 rx_core_state;
u8 core, i, j;
class = b43_nphy_classifier(dev, 0, 0);
b43_nphy_classifier(dev, 7, 4);
b43_nphy_read_clip_detection(dev, clip_state);
b43_nphy_write_clip_detection(dev, clip_off);
saved_regs_phy_rfctl[0] = b43_phy_read(dev, B43_NPHY_RFCTL_INTC1);
saved_regs_phy_rfctl[1] = b43_phy_read(dev, B43_NPHY_RFCTL_INTC2);
for (i = 0; i < ARRAY_SIZE(regs_to_store); i++)
saved_regs_phy[i] = b43_phy_read(dev, regs_to_store[i]);
b43_nphy_rf_control_intc_override(dev, 0, 0, 7);
b43_nphy_rf_control_intc_override(dev, 1, 1, 7);
b43_nphy_rf_control_override(dev, 0x1, 0, 0, false);
b43_nphy_rf_control_override(dev, 0x2, 1, 0, false);
b43_nphy_rf_control_override(dev, 0x80, 1, 0, false);
b43_nphy_rf_control_override(dev, 0x40, 1, 0, false);
if (b43_current_band(dev->wl) == IEEE80211_BAND_5GHZ) {
b43_nphy_rf_control_override(dev, 0x20, 0, 0, false);
b43_nphy_rf_control_override(dev, 0x10, 1, 0, false);
} else {
b43_nphy_rf_control_override(dev, 0x10, 0, 0, false);
b43_nphy_rf_control_override(dev, 0x20, 1, 0, false);
}
rx_core_state = b43_nphy_get_rx_core_state(dev);
for (core = 0; core < 2; core++) {
if (!(rx_core_state & (1 << core)))
continue;
r = core ? B2056_RX1 : B2056_RX0;
b43_nphy_scale_offset_rssi(dev, 0, 0, core + 1, 0, 2);
b43_nphy_scale_offset_rssi(dev, 0, 0, core + 1, 1, 2);
for (i = 0; i < 8; i++) {
b43_radio_maskset(dev, r | B2056_RX_RSSI_MISC, 0xE3,
i << 2);
b43_nphy_poll_rssi(dev, 2, results[i], 8);
}
for (i = 0; i < 4; i++) {
s32 curr;
s32 mind = 40;
s32 minpoll = 249;
u8 minvcm = 0;
if (2 * core != i)
continue;
for (j = 0; j < 8; j++) {
curr = results[j][i] * results[j][i] +
results[j][i + 1] * results[j][i];
if (curr < mind) {
mind = curr;
minvcm = j;
}
if (results[j][i] < minpoll)
minpoll = results[j][i];
}
vcm_final = minvcm;
results_min[i] = minpoll;
}
b43_radio_maskset(dev, r | B2056_RX_RSSI_MISC, 0xE3,
vcm_final << 2);
for (i = 0; i < 4; i++) {
if (core != i / 2)
continue;
offset[i] = -results[vcm_final][i];
if (offset[i] < 0)
offset[i] = -((abs(offset[i]) + 4) / 8);
else
offset[i] = (offset[i] + 4) / 8;
if (results_min[i] == 248)
offset[i] = -32;
b43_nphy_scale_offset_rssi(dev, 0, offset[i],
(i / 2 == 0) ? 1 : 2,
(i % 2 == 0) ? 0 : 1,
2);
}
}
for (core = 0; core < 2; core++) {
if (!(rx_core_state & (1 << core)))
continue;
for (i = 0; i < 2; i++) {
b43_nphy_scale_offset_rssi(dev, 0, 0, core + 1, 0, i);
b43_nphy_scale_offset_rssi(dev, 0, 0, core + 1, 1, i);
b43_nphy_poll_rssi(dev, i, poll_results, 8);
for (j = 0; j < 4; j++) {
if (j / 2 == core)
offset[j] = 232 - poll_results[j];
if (offset[j] < 0)
offset[j] = -(abs(offset[j] + 4) / 8);
else
offset[j] = (offset[j] + 4) / 8;
b43_nphy_scale_offset_rssi(dev, 0,
offset[2 * core], core + 1, j % 2, i);
}
}
}
b43_phy_write(dev, B43_NPHY_RFCTL_INTC1, saved_regs_phy_rfctl[0]);
b43_phy_write(dev, B43_NPHY_RFCTL_INTC2, saved_regs_phy_rfctl[1]);
b43_nphy_force_rf_sequence(dev, B43_RFSEQ_RESET2RX);
b43_phy_set(dev, B43_NPHY_TXF_40CO_B1S1, 0x1);
b43_phy_set(dev, B43_NPHY_RFCTL_CMD, B43_NPHY_RFCTL_CMD_START);
b43_phy_mask(dev, B43_NPHY_TXF_40CO_B1S1, ~0x1);
b43_phy_set(dev, B43_NPHY_RFCTL_OVER, 0x1);
b43_phy_set(dev, B43_NPHY_RFCTL_CMD, B43_NPHY_RFCTL_CMD_RXTX);
b43_phy_mask(dev, B43_NPHY_TXF_40CO_B1S1, ~0x1);
for (i = 0; i < ARRAY_SIZE(regs_to_store); i++)
b43_phy_write(dev, regs_to_store[i], saved_regs_phy[i]);
/* Store for future configuration */
if (b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ) {
rssical_radio_regs = nphy->rssical_cache.rssical_radio_regs_2G;
rssical_phy_regs = nphy->rssical_cache.rssical_phy_regs_2G;
} else {
rssical_radio_regs = nphy->rssical_cache.rssical_radio_regs_5G;
rssical_phy_regs = nphy->rssical_cache.rssical_phy_regs_5G;
}
rssical_radio_regs[0] = b43_radio_read(dev, 0x602B);
rssical_radio_regs[0] = b43_radio_read(dev, 0x702B);
rssical_phy_regs[0] = b43_phy_read(dev, B43_NPHY_RSSIMC_0I_RSSI_Z);
rssical_phy_regs[1] = b43_phy_read(dev, B43_NPHY_RSSIMC_0Q_RSSI_Z);
rssical_phy_regs[2] = b43_phy_read(dev, B43_NPHY_RSSIMC_1I_RSSI_Z);
rssical_phy_regs[3] = b43_phy_read(dev, B43_NPHY_RSSIMC_1Q_RSSI_Z);
rssical_phy_regs[4] = b43_phy_read(dev, B43_NPHY_RSSIMC_0I_RSSI_X);
rssical_phy_regs[5] = b43_phy_read(dev, B43_NPHY_RSSIMC_0Q_RSSI_X);
rssical_phy_regs[6] = b43_phy_read(dev, B43_NPHY_RSSIMC_1I_RSSI_X);
rssical_phy_regs[7] = b43_phy_read(dev, B43_NPHY_RSSIMC_1Q_RSSI_X);
rssical_phy_regs[8] = b43_phy_read(dev, B43_NPHY_RSSIMC_0I_RSSI_Y);
rssical_phy_regs[9] = b43_phy_read(dev, B43_NPHY_RSSIMC_0Q_RSSI_Y);
rssical_phy_regs[10] = b43_phy_read(dev, B43_NPHY_RSSIMC_1I_RSSI_Y);
rssical_phy_regs[11] = b43_phy_read(dev, B43_NPHY_RSSIMC_1Q_RSSI_Y);
/* Remember for which channel we store configuration */
if (b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ)
nphy->rssical_chanspec_2G.center_freq = dev->phy.channel_freq;
else
nphy->rssical_chanspec_5G.center_freq = dev->phy.channel_freq;
/* End of calibration, restore configuration */
b43_nphy_classifier(dev, 7, class);
b43_nphy_write_clip_detection(dev, clip_state);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/RSSICal */
static void b43_nphy_rev2_rssi_cal(struct b43_wldev *dev, u8 type)
{
int i, j;
u8 state[4];
u8 code, val;
u16 class, override;
u8 regs_save_radio[2];
u16 regs_save_phy[2];
s8 offset[4];
u8 core;
u8 rail;
u16 clip_state[2];
u16 clip_off[2] = { 0xFFFF, 0xFFFF };
s32 results_min[4] = { };
u8 vcm_final[4] = { };
s32 results[4][4] = { };
s32 miniq[4][2] = { };
if (type == 2) {
code = 0;
val = 6;
} else if (type < 2) {
code = 25;
val = 4;
} else {
B43_WARN_ON(1);
return;
}
class = b43_nphy_classifier(dev, 0, 0);
b43_nphy_classifier(dev, 7, 4);
b43_nphy_read_clip_detection(dev, clip_state);
b43_nphy_write_clip_detection(dev, clip_off);
if (b43_current_band(dev->wl) == IEEE80211_BAND_5GHZ)
override = 0x140;
else
override = 0x110;
regs_save_phy[0] = b43_phy_read(dev, B43_NPHY_RFCTL_INTC1);
regs_save_radio[0] = b43_radio_read16(dev, B2055_C1_PD_RXTX);
b43_phy_write(dev, B43_NPHY_RFCTL_INTC1, override);
b43_radio_write16(dev, B2055_C1_PD_RXTX, val);
regs_save_phy[1] = b43_phy_read(dev, B43_NPHY_RFCTL_INTC2);
regs_save_radio[1] = b43_radio_read16(dev, B2055_C2_PD_RXTX);
b43_phy_write(dev, B43_NPHY_RFCTL_INTC2, override);
b43_radio_write16(dev, B2055_C2_PD_RXTX, val);
state[0] = b43_radio_read16(dev, B2055_C1_PD_RSSIMISC) & 0x07;
state[1] = b43_radio_read16(dev, B2055_C2_PD_RSSIMISC) & 0x07;
b43_radio_mask(dev, B2055_C1_PD_RSSIMISC, 0xF8);
b43_radio_mask(dev, B2055_C2_PD_RSSIMISC, 0xF8);
state[2] = b43_radio_read16(dev, B2055_C1_SP_RSSI) & 0x07;
state[3] = b43_radio_read16(dev, B2055_C2_SP_RSSI) & 0x07;
b43_nphy_rssi_select(dev, 5, type);
b43_nphy_scale_offset_rssi(dev, 0, 0, 5, 0, type);
b43_nphy_scale_offset_rssi(dev, 0, 0, 5, 1, type);
for (i = 0; i < 4; i++) {
u8 tmp[4];
for (j = 0; j < 4; j++)
tmp[j] = i;
if (type != 1)
b43_nphy_set_rssi_2055_vcm(dev, type, tmp);
b43_nphy_poll_rssi(dev, type, results[i], 8);
if (type < 2)
for (j = 0; j < 2; j++)
miniq[i][j] = min(results[i][2 * j],
results[i][2 * j + 1]);
}
for (i = 0; i < 4; i++) {
s32 mind = 40;
u8 minvcm = 0;
s32 minpoll = 249;
s32 curr;
for (j = 0; j < 4; j++) {
if (type == 2)
curr = abs(results[j][i]);
else
curr = abs(miniq[j][i / 2] - code * 8);
if (curr < mind) {
mind = curr;
minvcm = j;
}
if (results[j][i] < minpoll)
minpoll = results[j][i];
}
results_min[i] = minpoll;
vcm_final[i] = minvcm;
}
if (type != 1)
b43_nphy_set_rssi_2055_vcm(dev, type, vcm_final);
for (i = 0; i < 4; i++) {
offset[i] = (code * 8) - results[vcm_final[i]][i];
if (offset[i] < 0)
offset[i] = -((abs(offset[i]) + 4) / 8);
else
offset[i] = (offset[i] + 4) / 8;
if (results_min[i] == 248)
offset[i] = code - 32;
core = (i / 2) ? 2 : 1;
rail = (i % 2) ? 1 : 0;
b43_nphy_scale_offset_rssi(dev, 0, offset[i], core, rail,
type);
}
b43_radio_maskset(dev, B2055_C1_PD_RSSIMISC, 0xF8, state[0]);
b43_radio_maskset(dev, B2055_C2_PD_RSSIMISC, 0xF8, state[1]);
switch (state[2]) {
case 1:
b43_nphy_rssi_select(dev, 1, 2);
break;
case 4:
b43_nphy_rssi_select(dev, 1, 0);
break;
case 2:
b43_nphy_rssi_select(dev, 1, 1);
break;
default:
b43_nphy_rssi_select(dev, 1, 1);
break;
}
switch (state[3]) {
case 1:
b43_nphy_rssi_select(dev, 2, 2);
break;
case 4:
b43_nphy_rssi_select(dev, 2, 0);
break;
default:
b43_nphy_rssi_select(dev, 2, 1);
break;
}
b43_nphy_rssi_select(dev, 0, type);
b43_phy_write(dev, B43_NPHY_RFCTL_INTC1, regs_save_phy[0]);
b43_radio_write16(dev, B2055_C1_PD_RXTX, regs_save_radio[0]);
b43_phy_write(dev, B43_NPHY_RFCTL_INTC2, regs_save_phy[1]);
b43_radio_write16(dev, B2055_C2_PD_RXTX, regs_save_radio[1]);
b43_nphy_classifier(dev, 7, class);
b43_nphy_write_clip_detection(dev, clip_state);
/* Specs don't say about reset here, but it makes wl and b43 dumps
identical, it really seems wl performs this */
b43_nphy_reset_cca(dev);
}
/*
* RSSI Calibration
* http://bcm-v4.sipsolutions.net/802.11/PHY/N/RSSICal
*/
static void b43_nphy_rssi_cal(struct b43_wldev *dev)
{
if (dev->phy.rev >= 3) {
b43_nphy_rev3_rssi_cal(dev);
} else {
b43_nphy_rev2_rssi_cal(dev, B43_NPHY_RSSI_Z);
b43_nphy_rev2_rssi_cal(dev, B43_NPHY_RSSI_X);
b43_nphy_rev2_rssi_cal(dev, B43_NPHY_RSSI_Y);
}
}
/**************************************************
* Workarounds
**************************************************/
static void b43_nphy_gain_ctl_workarounds_rev3plus(struct b43_wldev *dev)
{
struct ssb_sprom *sprom = dev->dev->bus_sprom;
bool ghz5;
bool ext_lna;
u16 rssi_gain;
struct nphy_gain_ctl_workaround_entry *e;
u8 lpf_gain[6] = { 0x00, 0x06, 0x0C, 0x12, 0x12, 0x12 };
u8 lpf_bits[6] = { 0, 1, 2, 3, 3, 3 };
/* Prepare values */
ghz5 = b43_phy_read(dev, B43_NPHY_BANDCTL)
& B43_NPHY_BANDCTL_5GHZ;
ext_lna = ghz5 ? sprom->boardflags_hi & B43_BFH_EXTLNA_5GHZ :
sprom->boardflags_lo & B43_BFL_EXTLNA;
e = b43_nphy_get_gain_ctl_workaround_ent(dev, ghz5, ext_lna);
if (ghz5 && dev->phy.rev >= 5)
rssi_gain = 0x90;
else
rssi_gain = 0x50;
b43_phy_set(dev, B43_NPHY_RXCTL, 0x0040);
/* Set Clip 2 detect */
b43_phy_set(dev, B43_NPHY_C1_CGAINI,
B43_NPHY_C1_CGAINI_CL2DETECT);
b43_phy_set(dev, B43_NPHY_C2_CGAINI,
B43_NPHY_C2_CGAINI_CL2DETECT);
b43_radio_write(dev, B2056_RX0 | B2056_RX_BIASPOLE_LNAG1_IDAC,
0x17);
b43_radio_write(dev, B2056_RX1 | B2056_RX_BIASPOLE_LNAG1_IDAC,
0x17);
b43_radio_write(dev, B2056_RX0 | B2056_RX_LNAG2_IDAC, 0xF0);
b43_radio_write(dev, B2056_RX1 | B2056_RX_LNAG2_IDAC, 0xF0);
b43_radio_write(dev, B2056_RX0 | B2056_RX_RSSI_POLE, 0x00);
b43_radio_write(dev, B2056_RX1 | B2056_RX_RSSI_POLE, 0x00);
b43_radio_write(dev, B2056_RX0 | B2056_RX_RSSI_GAIN,
rssi_gain);
b43_radio_write(dev, B2056_RX1 | B2056_RX_RSSI_GAIN,
rssi_gain);
b43_radio_write(dev, B2056_RX0 | B2056_RX_BIASPOLE_LNAA1_IDAC,
0x17);
b43_radio_write(dev, B2056_RX1 | B2056_RX_BIASPOLE_LNAA1_IDAC,
0x17);
b43_radio_write(dev, B2056_RX0 | B2056_RX_LNAA2_IDAC, 0xFF);
b43_radio_write(dev, B2056_RX1 | B2056_RX_LNAA2_IDAC, 0xFF);
b43_ntab_write_bulk(dev, B43_NTAB8(0, 8), 4, e->lna1_gain);
b43_ntab_write_bulk(dev, B43_NTAB8(1, 8), 4, e->lna1_gain);
b43_ntab_write_bulk(dev, B43_NTAB8(0, 16), 4, e->lna2_gain);
b43_ntab_write_bulk(dev, B43_NTAB8(1, 16), 4, e->lna2_gain);
b43_ntab_write_bulk(dev, B43_NTAB8(0, 32), 10, e->gain_db);
b43_ntab_write_bulk(dev, B43_NTAB8(1, 32), 10, e->gain_db);
b43_ntab_write_bulk(dev, B43_NTAB8(2, 32), 10, e->gain_bits);
b43_ntab_write_bulk(dev, B43_NTAB8(3, 32), 10, e->gain_bits);
b43_ntab_write_bulk(dev, B43_NTAB8(0, 0x40), 6, lpf_gain);
b43_ntab_write_bulk(dev, B43_NTAB8(1, 0x40), 6, lpf_gain);
b43_ntab_write_bulk(dev, B43_NTAB8(2, 0x40), 6, lpf_bits);
b43_ntab_write_bulk(dev, B43_NTAB8(3, 0x40), 6, lpf_bits);
b43_phy_write(dev, B43_NPHY_C1_INITGAIN, e->init_gain);
b43_phy_write(dev, 0x2A7, e->init_gain);
b43_ntab_write_bulk(dev, B43_NTAB16(7, 0x106), 2,
e->rfseq_init);
/* TODO: check defines. Do not match variables names */
b43_phy_write(dev, B43_NPHY_C1_CLIP1_MEDGAIN, e->cliphi_gain);
b43_phy_write(dev, 0x2A9, e->cliphi_gain);
b43_phy_write(dev, B43_NPHY_C1_CLIP2_GAIN, e->clipmd_gain);
b43_phy_write(dev, 0x2AB, e->clipmd_gain);
b43_phy_write(dev, B43_NPHY_C2_CLIP1_HIGAIN, e->cliplo_gain);
b43_phy_write(dev, 0x2AD, e->cliplo_gain);
b43_phy_maskset(dev, 0x27D, 0xFF00, e->crsmin);
b43_phy_maskset(dev, 0x280, 0xFF00, e->crsminl);
b43_phy_maskset(dev, 0x283, 0xFF00, e->crsminu);
b43_phy_write(dev, B43_NPHY_C1_NBCLIPTHRES, e->nbclip);
b43_phy_write(dev, B43_NPHY_C2_NBCLIPTHRES, e->nbclip);
b43_phy_maskset(dev, B43_NPHY_C1_CLIPWBTHRES,
~B43_NPHY_C1_CLIPWBTHRES_CLIP2, e->wlclip);
b43_phy_maskset(dev, B43_NPHY_C2_CLIPWBTHRES,
~B43_NPHY_C2_CLIPWBTHRES_CLIP2, e->wlclip);
b43_phy_write(dev, B43_NPHY_CCK_SHIFTB_REF, 0x809C);
}
static void b43_nphy_gain_ctl_workarounds_rev1_2(struct b43_wldev *dev)
{
struct b43_phy_n *nphy = dev->phy.n;
u8 i, j;
u8 code;
u16 tmp;
u8 rfseq_events[3] = { 6, 8, 7 };
u8 rfseq_delays[3] = { 10, 30, 1 };
/* Set Clip 2 detect */
b43_phy_set(dev, B43_NPHY_C1_CGAINI, B43_NPHY_C1_CGAINI_CL2DETECT);
b43_phy_set(dev, B43_NPHY_C2_CGAINI, B43_NPHY_C2_CGAINI_CL2DETECT);
/* Set narrowband clip threshold */
b43_phy_write(dev, B43_NPHY_C1_NBCLIPTHRES, 0x84);
b43_phy_write(dev, B43_NPHY_C2_NBCLIPTHRES, 0x84);
if (!dev->phy.is_40mhz) {
/* Set dwell lengths */
b43_phy_write(dev, B43_NPHY_CLIP1_NBDWELL_LEN, 0x002B);
b43_phy_write(dev, B43_NPHY_CLIP2_NBDWELL_LEN, 0x002B);
b43_phy_write(dev, B43_NPHY_W1CLIP1_DWELL_LEN, 0x0009);
b43_phy_write(dev, B43_NPHY_W1CLIP2_DWELL_LEN, 0x0009);
}
/* Set wideband clip 2 threshold */
b43_phy_maskset(dev, B43_NPHY_C1_CLIPWBTHRES,
~B43_NPHY_C1_CLIPWBTHRES_CLIP2, 21);
b43_phy_maskset(dev, B43_NPHY_C2_CLIPWBTHRES,
~B43_NPHY_C2_CLIPWBTHRES_CLIP2, 21);
if (!dev->phy.is_40mhz) {
b43_phy_maskset(dev, B43_NPHY_C1_CGAINI,
~B43_NPHY_C1_CGAINI_GAINBKOFF, 0x1);
b43_phy_maskset(dev, B43_NPHY_C2_CGAINI,
~B43_NPHY_C2_CGAINI_GAINBKOFF, 0x1);
b43_phy_maskset(dev, B43_NPHY_C1_CCK_CGAINI,
~B43_NPHY_C1_CCK_CGAINI_GAINBKOFF, 0x1);
b43_phy_maskset(dev, B43_NPHY_C2_CCK_CGAINI,
~B43_NPHY_C2_CCK_CGAINI_GAINBKOFF, 0x1);
}
b43_phy_write(dev, B43_NPHY_CCK_SHIFTB_REF, 0x809C);
if (nphy->gain_boost) {
if (b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ &&
dev->phy.is_40mhz)
code = 4;
else
code = 5;
} else {
code = dev->phy.is_40mhz ? 6 : 7;
}
/* Set HPVGA2 index */
b43_phy_maskset(dev, B43_NPHY_C1_INITGAIN, ~B43_NPHY_C1_INITGAIN_HPVGA2,
code << B43_NPHY_C1_INITGAIN_HPVGA2_SHIFT);
b43_phy_maskset(dev, B43_NPHY_C2_INITGAIN, ~B43_NPHY_C2_INITGAIN_HPVGA2,
code << B43_NPHY_C2_INITGAIN_HPVGA2_SHIFT);
b43_phy_write(dev, B43_NPHY_TABLE_ADDR, 0x1D06);
/* specs say about 2 loops, but wl does 4 */
for (i = 0; i < 4; i++)
b43_phy_write(dev, B43_NPHY_TABLE_DATALO, (code << 8 | 0x7C));
b43_nphy_adjust_lna_gain_table(dev);
if (nphy->elna_gain_config) {
b43_phy_write(dev, B43_NPHY_TABLE_ADDR, 0x0808);
b43_phy_write(dev, B43_NPHY_TABLE_DATALO, 0x0);
b43_phy_write(dev, B43_NPHY_TABLE_DATALO, 0x1);
b43_phy_write(dev, B43_NPHY_TABLE_DATALO, 0x1);
b43_phy_write(dev, B43_NPHY_TABLE_DATALO, 0x1);
b43_phy_write(dev, B43_NPHY_TABLE_ADDR, 0x0C08);
b43_phy_write(dev, B43_NPHY_TABLE_DATALO, 0x0);
b43_phy_write(dev, B43_NPHY_TABLE_DATALO, 0x1);
b43_phy_write(dev, B43_NPHY_TABLE_DATALO, 0x1);
b43_phy_write(dev, B43_NPHY_TABLE_DATALO, 0x1);
b43_phy_write(dev, B43_NPHY_TABLE_ADDR, 0x1D06);
/* specs say about 2 loops, but wl does 4 */
for (i = 0; i < 4; i++)
b43_phy_write(dev, B43_NPHY_TABLE_DATALO,
(code << 8 | 0x74));
}
if (dev->phy.rev == 2) {
for (i = 0; i < 4; i++) {
b43_phy_write(dev, B43_NPHY_TABLE_ADDR,
(0x0400 * i) + 0x0020);
for (j = 0; j < 21; j++) {
tmp = j * (i < 2 ? 3 : 1);
b43_phy_write(dev,
B43_NPHY_TABLE_DATALO, tmp);
}
}
}
b43_nphy_set_rf_sequence(dev, 5, rfseq_events, rfseq_delays, 3);
b43_phy_maskset(dev, B43_NPHY_OVER_DGAIN1,
~B43_NPHY_OVER_DGAIN_CCKDGECV & 0xFFFF,
0x5A << B43_NPHY_OVER_DGAIN_CCKDGECV_SHIFT);
if (b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ)
b43_phy_maskset(dev, B43_PHY_N(0xC5D), 0xFF80, 4);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/WorkaroundsGainCtrl */
static void b43_nphy_gain_ctl_workarounds(struct b43_wldev *dev)
{
if (dev->phy.rev >= 3)
b43_nphy_gain_ctl_workarounds_rev3plus(dev);
else
b43_nphy_gain_ctl_workarounds_rev1_2(dev);
}
static void b43_nphy_workarounds_rev3plus(struct b43_wldev *dev)
{
struct b43_phy_n *nphy = dev->phy.n;
struct ssb_sprom *sprom = dev->dev->bus_sprom;
/* TX to RX */
u8 tx2rx_events[8] = { 0x4, 0x3, 0x6, 0x5, 0x2, 0x1, 0x8, 0x1F };
u8 tx2rx_delays[8] = { 8, 4, 2, 2, 4, 4, 6, 1 };
/* RX to TX */
u8 rx2tx_events_ipa[9] = { 0x0, 0x1, 0x2, 0x8, 0x5, 0x6, 0xF, 0x3,
0x1F };
u8 rx2tx_delays_ipa[9] = { 8, 6, 6, 4, 4, 16, 43, 1, 1 };
u8 rx2tx_events[9] = { 0x0, 0x1, 0x2, 0x8, 0x5, 0x6, 0x3, 0x4, 0x1F };
u8 rx2tx_delays[9] = { 8, 6, 6, 4, 4, 18, 42, 1, 1 };
u16 tmp16;
u32 tmp32;
b43_phy_write(dev, 0x23f, 0x1f8);
b43_phy_write(dev, 0x240, 0x1f8);
tmp32 = b43_ntab_read(dev, B43_NTAB32(30, 0));
tmp32 &= 0xffffff;
b43_ntab_write(dev, B43_NTAB32(30, 0), tmp32);
b43_phy_write(dev, B43_NPHY_PHASETR_A0, 0x0125);
b43_phy_write(dev, B43_NPHY_PHASETR_A1, 0x01B3);
b43_phy_write(dev, B43_NPHY_PHASETR_A2, 0x0105);
b43_phy_write(dev, B43_NPHY_PHASETR_B0, 0x016E);
b43_phy_write(dev, B43_NPHY_PHASETR_B1, 0x00CD);
b43_phy_write(dev, B43_NPHY_PHASETR_B2, 0x0020);
b43_phy_write(dev, B43_NPHY_C2_CLIP1_MEDGAIN, 0x000C);
b43_phy_write(dev, 0x2AE, 0x000C);
/* TX to RX */
b43_nphy_set_rf_sequence(dev, 1, tx2rx_events, tx2rx_delays,
ARRAY_SIZE(tx2rx_events));
/* RX to TX */
if (b43_nphy_ipa(dev))
b43_nphy_set_rf_sequence(dev, 0, rx2tx_events_ipa,
rx2tx_delays_ipa, ARRAY_SIZE(rx2tx_events_ipa));
if (nphy->hw_phyrxchain != 3 &&
nphy->hw_phyrxchain != nphy->hw_phytxchain) {
if (b43_nphy_ipa(dev)) {
rx2tx_delays[5] = 59;
rx2tx_delays[6] = 1;
rx2tx_events[7] = 0x1F;
}
b43_nphy_set_rf_sequence(dev, 1, rx2tx_events, rx2tx_delays,
ARRAY_SIZE(rx2tx_events));
}
tmp16 = (b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ) ?
0x2 : 0x9C40;
b43_phy_write(dev, B43_NPHY_ENDROP_TLEN, tmp16);
b43_phy_maskset(dev, 0x294, 0xF0FF, 0x0700);
b43_ntab_write(dev, B43_NTAB32(16, 3), 0x18D);
b43_ntab_write(dev, B43_NTAB32(16, 127), 0x18D);
b43_nphy_gain_ctl_workarounds(dev);
b43_ntab_write(dev, B43_NTAB16(8, 0), 2);
b43_ntab_write(dev, B43_NTAB16(8, 16), 2);
/* TODO */
b43_radio_write(dev, B2056_RX0 | B2056_RX_MIXA_MAST_BIAS, 0x00);
b43_radio_write(dev, B2056_RX1 | B2056_RX_MIXA_MAST_BIAS, 0x00);
b43_radio_write(dev, B2056_RX0 | B2056_RX_MIXA_BIAS_MAIN, 0x06);
b43_radio_write(dev, B2056_RX1 | B2056_RX_MIXA_BIAS_MAIN, 0x06);
b43_radio_write(dev, B2056_RX0 | B2056_RX_MIXA_BIAS_AUX, 0x07);
b43_radio_write(dev, B2056_RX1 | B2056_RX_MIXA_BIAS_AUX, 0x07);
b43_radio_write(dev, B2056_RX0 | B2056_RX_MIXA_LOB_BIAS, 0x88);
b43_radio_write(dev, B2056_RX1 | B2056_RX_MIXA_LOB_BIAS, 0x88);
b43_radio_write(dev, B2056_RX0 | B2056_RX_MIXA_CMFB_IDAC, 0x00);
b43_radio_write(dev, B2056_RX1 | B2056_RX_MIXA_CMFB_IDAC, 0x00);
b43_radio_write(dev, B2056_RX0 | B2056_RX_MIXG_CMFB_IDAC, 0x00);
b43_radio_write(dev, B2056_RX1 | B2056_RX_MIXG_CMFB_IDAC, 0x00);
/* N PHY WAR TX Chain Update with hw_phytxchain as argument */
if ((sprom->boardflags2_lo & B43_BFL2_APLL_WAR &&
b43_current_band(dev->wl) == IEEE80211_BAND_5GHZ) ||
(sprom->boardflags2_lo & B43_BFL2_GPLL_WAR &&
b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ))
tmp32 = 0x00088888;
else
tmp32 = 0x88888888;
b43_ntab_write(dev, B43_NTAB32(30, 1), tmp32);
b43_ntab_write(dev, B43_NTAB32(30, 2), tmp32);
b43_ntab_write(dev, B43_NTAB32(30, 3), tmp32);
if (dev->phy.rev == 4 &&
b43_current_band(dev->wl) == IEEE80211_BAND_5GHZ) {
b43_radio_write(dev, B2056_TX0 | B2056_TX_GMBB_IDAC,
0x70);
b43_radio_write(dev, B2056_TX1 | B2056_TX_GMBB_IDAC,
0x70);
}
b43_phy_write(dev, 0x224, 0x03eb);
b43_phy_write(dev, 0x225, 0x03eb);
b43_phy_write(dev, 0x226, 0x0341);
b43_phy_write(dev, 0x227, 0x0341);
b43_phy_write(dev, 0x228, 0x042b);
b43_phy_write(dev, 0x229, 0x042b);
b43_phy_write(dev, 0x22a, 0x0381);
b43_phy_write(dev, 0x22b, 0x0381);
b43_phy_write(dev, 0x22c, 0x042b);
b43_phy_write(dev, 0x22d, 0x042b);
b43_phy_write(dev, 0x22e, 0x0381);
b43_phy_write(dev, 0x22f, 0x0381);
}
static void b43_nphy_workarounds_rev1_2(struct b43_wldev *dev)
{
struct ssb_sprom *sprom = dev->dev->bus_sprom;
struct b43_phy *phy = &dev->phy;
struct b43_phy_n *nphy = phy->n;
u8 events1[7] = { 0x0, 0x1, 0x2, 0x8, 0x4, 0x5, 0x3 };
u8 delays1[7] = { 0x8, 0x6, 0x6, 0x2, 0x4, 0x3C, 0x1 };
u8 events2[7] = { 0x0, 0x3, 0x5, 0x4, 0x2, 0x1, 0x8 };
u8 delays2[7] = { 0x8, 0x6, 0x2, 0x4, 0x4, 0x6, 0x1 };
if (b43_current_band(dev->wl) == IEEE80211_BAND_5GHZ &&
nphy->band5g_pwrgain) {
b43_radio_mask(dev, B2055_C1_TX_RF_SPARE, ~0x8);
b43_radio_mask(dev, B2055_C2_TX_RF_SPARE, ~0x8);
} else {
b43_radio_set(dev, B2055_C1_TX_RF_SPARE, 0x8);
b43_radio_set(dev, B2055_C2_TX_RF_SPARE, 0x8);
}
b43_ntab_write(dev, B43_NTAB16(8, 0x00), 0x000A);
b43_ntab_write(dev, B43_NTAB16(8, 0x10), 0x000A);
b43_ntab_write(dev, B43_NTAB16(8, 0x02), 0xCDAA);
b43_ntab_write(dev, B43_NTAB16(8, 0x12), 0xCDAA);
if (dev->phy.rev < 2) {
b43_ntab_write(dev, B43_NTAB16(8, 0x08), 0x0000);
b43_ntab_write(dev, B43_NTAB16(8, 0x18), 0x0000);
b43_ntab_write(dev, B43_NTAB16(8, 0x07), 0x7AAB);
b43_ntab_write(dev, B43_NTAB16(8, 0x17), 0x7AAB);
b43_ntab_write(dev, B43_NTAB16(8, 0x06), 0x0800);
b43_ntab_write(dev, B43_NTAB16(8, 0x16), 0x0800);
}
b43_phy_write(dev, B43_NPHY_RFCTL_LUT_TRSW_LO1, 0x2D8);
b43_phy_write(dev, B43_NPHY_RFCTL_LUT_TRSW_UP1, 0x301);
b43_phy_write(dev, B43_NPHY_RFCTL_LUT_TRSW_LO2, 0x2D8);
b43_phy_write(dev, B43_NPHY_RFCTL_LUT_TRSW_UP2, 0x301);
if (sprom->boardflags2_lo & B43_BFL2_SKWRKFEM_BRD &&
dev->dev->board_type == 0x8B) {
delays1[0] = 0x1;
delays1[5] = 0x14;
}
b43_nphy_set_rf_sequence(dev, 0, events1, delays1, 7);
b43_nphy_set_rf_sequence(dev, 1, events2, delays2, 7);
b43_nphy_gain_ctl_workarounds(dev);
if (dev->phy.rev < 2) {
if (b43_phy_read(dev, B43_NPHY_RXCTL) & 0x2)
b43_hf_write(dev, b43_hf_read(dev) |
B43_HF_MLADVW);
} else if (dev->phy.rev == 2) {
b43_phy_write(dev, B43_NPHY_CRSCHECK2, 0);
b43_phy_write(dev, B43_NPHY_CRSCHECK3, 0);
}
if (dev->phy.rev < 2)
b43_phy_mask(dev, B43_NPHY_SCRAM_SIGCTL,
~B43_NPHY_SCRAM_SIGCTL_SCM);
/* Set phase track alpha and beta */
b43_phy_write(dev, B43_NPHY_PHASETR_A0, 0x125);
b43_phy_write(dev, B43_NPHY_PHASETR_A1, 0x1B3);
b43_phy_write(dev, B43_NPHY_PHASETR_A2, 0x105);
b43_phy_write(dev, B43_NPHY_PHASETR_B0, 0x16E);
b43_phy_write(dev, B43_NPHY_PHASETR_B1, 0xCD);
b43_phy_write(dev, B43_NPHY_PHASETR_B2, 0x20);
b43_phy_mask(dev, B43_NPHY_PIL_DW1,
~B43_NPHY_PIL_DW_64QAM & 0xFFFF);
b43_phy_write(dev, B43_NPHY_TXF_20CO_S2B1, 0xB5);
b43_phy_write(dev, B43_NPHY_TXF_20CO_S2B2, 0xA4);
b43_phy_write(dev, B43_NPHY_TXF_20CO_S2B3, 0x00);
if (dev->phy.rev == 2)
b43_phy_set(dev, B43_NPHY_FINERX2_CGC,
B43_NPHY_FINERX2_CGC_DECGC);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/Workarounds */
static void b43_nphy_workarounds(struct b43_wldev *dev)
{
struct b43_phy *phy = &dev->phy;
struct b43_phy_n *nphy = phy->n;
if (b43_current_band(dev->wl) == IEEE80211_BAND_5GHZ)
b43_nphy_classifier(dev, 1, 0);
else
b43_nphy_classifier(dev, 1, 1);
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, 1);
b43_phy_set(dev, B43_NPHY_IQFLIP,
B43_NPHY_IQFLIP_ADC1 | B43_NPHY_IQFLIP_ADC2);
if (dev->phy.rev >= 3)
b43_nphy_workarounds_rev3plus(dev);
else
b43_nphy_workarounds_rev1_2(dev);
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, 0);
}
/**************************************************
* Tx/Rx common
**************************************************/
/*
* Transmits a known value for LO calibration
* http://bcm-v4.sipsolutions.net/802.11/PHY/N/TXTone
*/
static int b43_nphy_tx_tone(struct b43_wldev *dev, u32 freq, u16 max_val,
bool iqmode, bool dac_test)
{
u16 samp = b43_nphy_gen_load_samples(dev, freq, max_val, dac_test);
if (samp == 0)
return -1;
b43_nphy_run_samples(dev, samp, 0xFFFF, 0, iqmode, dac_test);
return 0;
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/Chains */
static void b43_nphy_update_txrx_chain(struct b43_wldev *dev)
{
struct b43_phy_n *nphy = dev->phy.n;
bool override = false;
u16 chain = 0x33;
if (nphy->txrx_chain == 0) {
chain = 0x11;
override = true;
} else if (nphy->txrx_chain == 1) {
chain = 0x22;
override = true;
}
b43_phy_maskset(dev, B43_NPHY_RFSEQCA,
~(B43_NPHY_RFSEQCA_TXEN | B43_NPHY_RFSEQCA_RXEN),
chain);
if (override)
b43_phy_set(dev, B43_NPHY_RFSEQMODE,
B43_NPHY_RFSEQMODE_CAOVER);
else
b43_phy_mask(dev, B43_NPHY_RFSEQMODE,
~B43_NPHY_RFSEQMODE_CAOVER);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/stop-playback */
static void b43_nphy_stop_playback(struct b43_wldev *dev)
{
struct b43_phy_n *nphy = dev->phy.n;
u16 tmp;
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, 1);
tmp = b43_phy_read(dev, B43_NPHY_SAMP_STAT);
if (tmp & 0x1)
b43_phy_set(dev, B43_NPHY_SAMP_CMD, B43_NPHY_SAMP_CMD_STOP);
else if (tmp & 0x2)
b43_phy_mask(dev, B43_NPHY_IQLOCAL_CMDGCTL, 0x7FFF);
b43_phy_mask(dev, B43_NPHY_SAMP_CMD, ~0x0004);
if (nphy->bb_mult_save & 0x80000000) {
tmp = nphy->bb_mult_save & 0xFFFF;
b43_ntab_write(dev, B43_NTAB16(15, 87), tmp);
nphy->bb_mult_save = 0;
}
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, 0);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/IqCalGainParams */
static void b43_nphy_iq_cal_gain_params(struct b43_wldev *dev, u16 core,
struct nphy_txgains target,
struct nphy_iqcal_params *params)
{
int i, j, indx;
u16 gain;
if (dev->phy.rev >= 3) {
params->txgm = target.txgm[core];
params->pga = target.pga[core];
params->pad = target.pad[core];
params->ipa = target.ipa[core];
params->cal_gain = (params->txgm << 12) | (params->pga << 8) |
(params->pad << 4) | (params->ipa);
for (j = 0; j < 5; j++)
params->ncorr[j] = 0x79;
} else {
gain = (target.pad[core]) | (target.pga[core] << 4) |
(target.txgm[core] << 8);
indx = (b43_current_band(dev->wl) == IEEE80211_BAND_5GHZ) ?
1 : 0;
for (i = 0; i < 9; i++)
if (tbl_iqcal_gainparams[indx][i][0] == gain)
break;
i = min(i, 8);
params->txgm = tbl_iqcal_gainparams[indx][i][1];
params->pga = tbl_iqcal_gainparams[indx][i][2];
params->pad = tbl_iqcal_gainparams[indx][i][3];
params->cal_gain = (params->txgm << 7) | (params->pga << 4) |
(params->pad << 2);
for (j = 0; j < 4; j++)
params->ncorr[j] = tbl_iqcal_gainparams[indx][i][4 + j];
}
}
/**************************************************
* Tx and Rx
**************************************************/
void b43_nphy_set_rxantenna(struct b43_wldev *dev, int antenna)
{//TODO
}
static void b43_nphy_op_adjust_txpower(struct b43_wldev *dev)
{//TODO
}
static enum b43_txpwr_result b43_nphy_op_recalc_txpower(struct b43_wldev *dev,
bool ignore_tssi)
{//TODO
return B43_TXPWR_RES_DONE;
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/TxPwrCtrlEnable */
static void b43_nphy_tx_power_ctrl(struct b43_wldev *dev, bool enable)
{
struct b43_phy_n *nphy = dev->phy.n;
u8 i;
u16 bmask, val, tmp;
enum ieee80211_band band = b43_current_band(dev->wl);
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, 1);
nphy->txpwrctrl = enable;
if (!enable) {
if (dev->phy.rev >= 3 &&
(b43_phy_read(dev, B43_NPHY_TXPCTL_CMD) &
(B43_NPHY_TXPCTL_CMD_COEFF |
B43_NPHY_TXPCTL_CMD_HWPCTLEN |
B43_NPHY_TXPCTL_CMD_PCTLEN))) {
/* We disable enabled TX pwr ctl, save it's state */
nphy->tx_pwr_idx[0] = b43_phy_read(dev,
B43_NPHY_C1_TXPCTL_STAT) & 0x7f;
nphy->tx_pwr_idx[1] = b43_phy_read(dev,
B43_NPHY_C2_TXPCTL_STAT) & 0x7f;
}
b43_phy_write(dev, B43_NPHY_TABLE_ADDR, 0x6840);
for (i = 0; i < 84; i++)
b43_phy_write(dev, B43_NPHY_TABLE_DATALO, 0);
b43_phy_write(dev, B43_NPHY_TABLE_ADDR, 0x6C40);
for (i = 0; i < 84; i++)
b43_phy_write(dev, B43_NPHY_TABLE_DATALO, 0);
tmp = B43_NPHY_TXPCTL_CMD_COEFF | B43_NPHY_TXPCTL_CMD_HWPCTLEN;
if (dev->phy.rev >= 3)
tmp |= B43_NPHY_TXPCTL_CMD_PCTLEN;
b43_phy_mask(dev, B43_NPHY_TXPCTL_CMD, ~tmp);
if (dev->phy.rev >= 3) {
b43_phy_set(dev, B43_NPHY_AFECTL_OVER1, 0x0100);
b43_phy_set(dev, B43_NPHY_AFECTL_OVER, 0x0100);
} else {
b43_phy_set(dev, B43_NPHY_AFECTL_OVER, 0x4000);
}
if (dev->phy.rev == 2)
b43_phy_maskset(dev, B43_NPHY_BPHY_CTL3,
~B43_NPHY_BPHY_CTL3_SCALE, 0x53);
else if (dev->phy.rev < 2)
b43_phy_maskset(dev, B43_NPHY_BPHY_CTL3,
~B43_NPHY_BPHY_CTL3_SCALE, 0x5A);
if (dev->phy.rev < 2 && dev->phy.is_40mhz)
b43_hf_write(dev, b43_hf_read(dev) | B43_HF_TSSIRPSMW);
} else {
b43_ntab_write_bulk(dev, B43_NTAB16(26, 64), 84,
nphy->adj_pwr_tbl);
b43_ntab_write_bulk(dev, B43_NTAB16(27, 64), 84,
nphy->adj_pwr_tbl);
bmask = B43_NPHY_TXPCTL_CMD_COEFF |
B43_NPHY_TXPCTL_CMD_HWPCTLEN;
/* wl does useless check for "enable" param here */
val = B43_NPHY_TXPCTL_CMD_COEFF | B43_NPHY_TXPCTL_CMD_HWPCTLEN;
if (dev->phy.rev >= 3) {
bmask |= B43_NPHY_TXPCTL_CMD_PCTLEN;
if (val)
val |= B43_NPHY_TXPCTL_CMD_PCTLEN;
}
b43_phy_maskset(dev, B43_NPHY_TXPCTL_CMD, ~(bmask), val);
if (band == IEEE80211_BAND_5GHZ) {
b43_phy_maskset(dev, B43_NPHY_TXPCTL_CMD,
~B43_NPHY_TXPCTL_CMD_INIT, 0x64);
if (dev->phy.rev > 1)
b43_phy_maskset(dev, B43_NPHY_TXPCTL_INIT,
~B43_NPHY_TXPCTL_INIT_PIDXI1,
0x64);
}
if (dev->phy.rev >= 3) {
if (nphy->tx_pwr_idx[0] != 128 &&
nphy->tx_pwr_idx[1] != 128) {
/* Recover TX pwr ctl state */
b43_phy_maskset(dev, B43_NPHY_TXPCTL_CMD,
~B43_NPHY_TXPCTL_CMD_INIT,
nphy->tx_pwr_idx[0]);
if (dev->phy.rev > 1)
b43_phy_maskset(dev,
B43_NPHY_TXPCTL_INIT,
~0xff, nphy->tx_pwr_idx[1]);
}
}
if (dev->phy.rev >= 3) {
b43_phy_mask(dev, B43_NPHY_AFECTL_OVER1, ~0x100);
b43_phy_mask(dev, B43_NPHY_AFECTL_OVER, ~0x100);
} else {
b43_phy_mask(dev, B43_NPHY_AFECTL_OVER, ~0x4000);
}
if (dev->phy.rev == 2)
b43_phy_maskset(dev, B43_NPHY_BPHY_CTL3, ~0xFF, 0x3b);
else if (dev->phy.rev < 2)
b43_phy_maskset(dev, B43_NPHY_BPHY_CTL3, ~0xFF, 0x40);
if (dev->phy.rev < 2 && dev->phy.is_40mhz)
b43_hf_write(dev, b43_hf_read(dev) & ~B43_HF_TSSIRPSMW);
if (b43_nphy_ipa(dev)) {
b43_phy_mask(dev, B43_NPHY_PAPD_EN0, ~0x4);
b43_phy_mask(dev, B43_NPHY_PAPD_EN1, ~0x4);
}
}
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, 0);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/TxPwrFix */
static void b43_nphy_tx_power_fix(struct b43_wldev *dev)
{
struct b43_phy_n *nphy = dev->phy.n;
struct ssb_sprom *sprom = dev->dev->bus_sprom;
u8 txpi[2], bbmult, i;
u16 tmp, radio_gain, dac_gain;
u16 freq = dev->phy.channel_freq;
u32 txgain;
/* u32 gaintbl; rev3+ */
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, 1);
if (dev->phy.rev >= 7) {
txpi[0] = txpi[1] = 30;
} else if (dev->phy.rev >= 3) {
txpi[0] = 40;
txpi[1] = 40;
} else if (sprom->revision < 4) {
txpi[0] = 72;
txpi[1] = 72;
} else {
if (b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ) {
txpi[0] = sprom->txpid2g[0];
txpi[1] = sprom->txpid2g[1];
} else if (freq >= 4900 && freq < 5100) {
txpi[0] = sprom->txpid5gl[0];
txpi[1] = sprom->txpid5gl[1];
} else if (freq >= 5100 && freq < 5500) {
txpi[0] = sprom->txpid5g[0];
txpi[1] = sprom->txpid5g[1];
} else if (freq >= 5500) {
txpi[0] = sprom->txpid5gh[0];
txpi[1] = sprom->txpid5gh[1];
} else {
txpi[0] = 91;
txpi[1] = 91;
}
}
if (dev->phy.rev < 7 &&
(txpi[0] < 40 || txpi[0] > 100 || txpi[1] < 40 || txpi[1] > 100))
txpi[0] = txpi[1] = 91;
/*
for (i = 0; i < 2; i++) {
nphy->txpwrindex[i].index_internal = txpi[i];
nphy->txpwrindex[i].index_internal_save = txpi[i];
}
*/
for (i = 0; i < 2; i++) {
txgain = *(b43_nphy_get_tx_gain_table(dev) + txpi[i]);
if (dev->phy.rev >= 3)
radio_gain = (txgain >> 16) & 0x1FFFF;
else
radio_gain = (txgain >> 16) & 0x1FFF;
if (dev->phy.rev >= 7)
dac_gain = (txgain >> 8) & 0x7;
else
dac_gain = (txgain >> 8) & 0x3F;
bbmult = txgain & 0xFF;
if (dev->phy.rev >= 3) {
if (i == 0)
b43_phy_set(dev, B43_NPHY_AFECTL_OVER1, 0x0100);
else
b43_phy_set(dev, B43_NPHY_AFECTL_OVER, 0x0100);
} else {
b43_phy_set(dev, B43_NPHY_AFECTL_OVER, 0x4000);
}
if (i == 0)
b43_phy_write(dev, B43_NPHY_AFECTL_DACGAIN1, dac_gain);
else
b43_phy_write(dev, B43_NPHY_AFECTL_DACGAIN2, dac_gain);
b43_ntab_write(dev, B43_NTAB16(0x7, 0x110 + i), radio_gain);
tmp = b43_ntab_read(dev, B43_NTAB16(0xF, 0x57));
if (i == 0)
tmp = (tmp & 0x00FF) | (bbmult << 8);
else
tmp = (tmp & 0xFF00) | bbmult;
b43_ntab_write(dev, B43_NTAB16(0xF, 0x57), tmp);
if (b43_nphy_ipa(dev)) {
u32 tmp32;
u16 reg = (i == 0) ?
B43_NPHY_PAPD_EN0 : B43_NPHY_PAPD_EN1;
tmp32 = b43_ntab_read(dev, B43_NTAB32(26 + i,
576 + txpi[i]));
b43_phy_maskset(dev, reg, 0xE00F, (u32) tmp32 << 4);
b43_phy_set(dev, reg, 0x4);
}
}
b43_phy_mask(dev, B43_NPHY_BPHY_CTL2, ~B43_NPHY_BPHY_CTL2_LUT);
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, 0);
}
static void b43_nphy_ipa_internal_tssi_setup(struct b43_wldev *dev)
{
struct b43_phy *phy = &dev->phy;
u8 core;
u16 r; /* routing */
if (phy->rev >= 7) {
for (core = 0; core < 2; core++) {
r = core ? 0x190 : 0x170;
if (b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ) {
b43_radio_write(dev, r + 0x5, 0x5);
b43_radio_write(dev, r + 0x9, 0xE);
if (phy->rev != 5)
b43_radio_write(dev, r + 0xA, 0);
if (phy->rev != 7)
b43_radio_write(dev, r + 0xB, 1);
else
b43_radio_write(dev, r + 0xB, 0x31);
} else {
b43_radio_write(dev, r + 0x5, 0x9);
b43_radio_write(dev, r + 0x9, 0xC);
b43_radio_write(dev, r + 0xB, 0x0);
if (phy->rev != 5)
b43_radio_write(dev, r + 0xA, 1);
else
b43_radio_write(dev, r + 0xA, 0x31);
}
b43_radio_write(dev, r + 0x6, 0);
b43_radio_write(dev, r + 0x7, 0);
b43_radio_write(dev, r + 0x8, 3);
b43_radio_write(dev, r + 0xC, 0);
}
} else {
if (b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ)
b43_radio_write(dev, B2056_SYN_RESERVED_ADDR31, 0x128);
else
b43_radio_write(dev, B2056_SYN_RESERVED_ADDR31, 0x80);
b43_radio_write(dev, B2056_SYN_RESERVED_ADDR30, 0);
b43_radio_write(dev, B2056_SYN_GPIO_MASTER1, 0x29);
for (core = 0; core < 2; core++) {
r = core ? B2056_TX1 : B2056_TX0;
b43_radio_write(dev, r | B2056_TX_IQCAL_VCM_HG, 0);
b43_radio_write(dev, r | B2056_TX_IQCAL_IDAC, 0);
b43_radio_write(dev, r | B2056_TX_TSSI_VCM, 3);
b43_radio_write(dev, r | B2056_TX_TX_AMP_DET, 0);
b43_radio_write(dev, r | B2056_TX_TSSI_MISC1, 8);
b43_radio_write(dev, r | B2056_TX_TSSI_MISC2, 0);
b43_radio_write(dev, r | B2056_TX_TSSI_MISC3, 0);
if (b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ) {
b43_radio_write(dev, r | B2056_TX_TX_SSI_MASTER,
0x5);
if (phy->rev != 5)
b43_radio_write(dev, r | B2056_TX_TSSIA,
0x00);
if (phy->rev >= 5)
b43_radio_write(dev, r | B2056_TX_TSSIG,
0x31);
else
b43_radio_write(dev, r | B2056_TX_TSSIG,
0x11);
b43_radio_write(dev, r | B2056_TX_TX_SSI_MUX,
0xE);
} else {
b43_radio_write(dev, r | B2056_TX_TX_SSI_MASTER,
0x9);
b43_radio_write(dev, r | B2056_TX_TSSIA, 0x31);
b43_radio_write(dev, r | B2056_TX_TSSIG, 0x0);
b43_radio_write(dev, r | B2056_TX_TX_SSI_MUX,
0xC);
}
}
}
}
/*
* Stop radio and transmit known signal. Then check received signal strength to
* get TSSI (Transmit Signal Strength Indicator).
* http://bcm-v4.sipsolutions.net/802.11/PHY/N/TxPwrCtrlIdleTssi
*/
static void b43_nphy_tx_power_ctl_idle_tssi(struct b43_wldev *dev)
{
struct b43_phy *phy = &dev->phy;
struct b43_phy_n *nphy = dev->phy.n;
u32 tmp;
s32 rssi[4] = { };
/* TODO: check if we can transmit */
if (b43_nphy_ipa(dev))
b43_nphy_ipa_internal_tssi_setup(dev);
if (phy->rev >= 7)
; /* TODO: Override Rev7 with 0x2000, 0, 3, 0, 0 as arguments */
else if (phy->rev >= 3)
b43_nphy_rf_control_override(dev, 0x2000, 0, 3, false);
b43_nphy_stop_playback(dev);
b43_nphy_tx_tone(dev, 0xFA0, 0, false, false);
udelay(20);
tmp = b43_nphy_poll_rssi(dev, 4, rssi, 1);
b43_nphy_stop_playback(dev);
b43_nphy_rssi_select(dev, 0, 0);
if (phy->rev >= 7)
; /* TODO: Override Rev7 with 0x2000, 0, 3, 1, 0 as arguments */
else if (phy->rev >= 3)
b43_nphy_rf_control_override(dev, 0x2000, 0, 3, true);
if (phy->rev >= 3) {
nphy->pwr_ctl_info[0].idle_tssi_5g = (tmp >> 24) & 0xFF;
nphy->pwr_ctl_info[1].idle_tssi_5g = (tmp >> 8) & 0xFF;
} else {
nphy->pwr_ctl_info[0].idle_tssi_5g = (tmp >> 16) & 0xFF;
nphy->pwr_ctl_info[1].idle_tssi_5g = tmp & 0xFF;
}
nphy->pwr_ctl_info[0].idle_tssi_2g = (tmp >> 24) & 0xFF;
nphy->pwr_ctl_info[1].idle_tssi_2g = (tmp >> 8) & 0xFF;
}
/* http://bcm-v4.sipsolutions.net/PHY/N/TxPwrLimitToTbl */
static void b43_nphy_tx_prepare_adjusted_power_table(struct b43_wldev *dev)
{
struct b43_phy_n *nphy = dev->phy.n;
u8 idx, delta;
u8 i, stf_mode;
for (i = 0; i < 4; i++)
nphy->adj_pwr_tbl[i] = nphy->tx_power_offset[i];
for (stf_mode = 0; stf_mode < 4; stf_mode++) {
delta = 0;
switch (stf_mode) {
case 0:
if (dev->phy.is_40mhz && dev->phy.rev >= 5) {
idx = 68;
} else {
delta = 1;
idx = dev->phy.is_40mhz ? 52 : 4;
}
break;
case 1:
idx = dev->phy.is_40mhz ? 76 : 28;
break;
case 2:
idx = dev->phy.is_40mhz ? 84 : 36;
break;
case 3:
idx = dev->phy.is_40mhz ? 92 : 44;
break;
}
for (i = 0; i < 20; i++) {
nphy->adj_pwr_tbl[4 + 4 * i + stf_mode] =
nphy->tx_power_offset[idx];
if (i == 0)
idx += delta;
if (i == 14)
idx += 1 - delta;
if (i == 3 || i == 4 || i == 7 || i == 8 || i == 11 ||
i == 13)
idx += 1;
}
}
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/TxPwrCtrlSetup */
static void b43_nphy_tx_power_ctl_setup(struct b43_wldev *dev)
{
struct b43_phy_n *nphy = dev->phy.n;
struct ssb_sprom *sprom = dev->dev->bus_sprom;
s16 a1[2], b0[2], b1[2];
u8 idle[2];
s8 target[2];
s32 num, den, pwr;
u32 regval[64];
u16 freq = dev->phy.channel_freq;
u16 tmp;
u16 r; /* routing */
u8 i, c;
if (dev->dev->core_rev == 11 || dev->dev->core_rev == 12) {
b43_maskset32(dev, B43_MMIO_MACCTL, ~0, 0x200000);
b43_read32(dev, B43_MMIO_MACCTL);
udelay(1);
}
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, true);
b43_phy_set(dev, B43_NPHY_TSSIMODE, B43_NPHY_TSSIMODE_EN);
if (dev->phy.rev >= 3)
b43_phy_mask(dev, B43_NPHY_TXPCTL_CMD,
~B43_NPHY_TXPCTL_CMD_PCTLEN & 0xFFFF);
else
b43_phy_set(dev, B43_NPHY_TXPCTL_CMD,
B43_NPHY_TXPCTL_CMD_PCTLEN);
if (dev->dev->core_rev == 11 || dev->dev->core_rev == 12)
b43_maskset32(dev, B43_MMIO_MACCTL, ~0x200000, 0);
if (sprom->revision < 4) {
idle[0] = nphy->pwr_ctl_info[0].idle_tssi_2g;
idle[1] = nphy->pwr_ctl_info[1].idle_tssi_2g;
target[0] = target[1] = 52;
a1[0] = a1[1] = -424;
b0[0] = b0[1] = 5612;
b1[0] = b1[1] = -1393;
} else {
if (b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ) {
for (c = 0; c < 2; c++) {
idle[c] = nphy->pwr_ctl_info[c].idle_tssi_2g;
target[c] = sprom->core_pwr_info[c].maxpwr_2g;
a1[c] = sprom->core_pwr_info[c].pa_2g[0];
b0[c] = sprom->core_pwr_info[c].pa_2g[1];
b1[c] = sprom->core_pwr_info[c].pa_2g[2];
}
} else if (freq >= 4900 && freq < 5100) {
for (c = 0; c < 2; c++) {
idle[c] = nphy->pwr_ctl_info[c].idle_tssi_5g;
target[c] = sprom->core_pwr_info[c].maxpwr_5gl;
a1[c] = sprom->core_pwr_info[c].pa_5gl[0];
b0[c] = sprom->core_pwr_info[c].pa_5gl[1];
b1[c] = sprom->core_pwr_info[c].pa_5gl[2];
}
} else if (freq >= 5100 && freq < 5500) {
for (c = 0; c < 2; c++) {
idle[c] = nphy->pwr_ctl_info[c].idle_tssi_5g;
target[c] = sprom->core_pwr_info[c].maxpwr_5g;
a1[c] = sprom->core_pwr_info[c].pa_5g[0];
b0[c] = sprom->core_pwr_info[c].pa_5g[1];
b1[c] = sprom->core_pwr_info[c].pa_5g[2];
}
} else if (freq >= 5500) {
for (c = 0; c < 2; c++) {
idle[c] = nphy->pwr_ctl_info[c].idle_tssi_5g;
target[c] = sprom->core_pwr_info[c].maxpwr_5gh;
a1[c] = sprom->core_pwr_info[c].pa_5gh[0];
b0[c] = sprom->core_pwr_info[c].pa_5gh[1];
b1[c] = sprom->core_pwr_info[c].pa_5gh[2];
}
} else {
idle[0] = nphy->pwr_ctl_info[0].idle_tssi_5g;
idle[1] = nphy->pwr_ctl_info[1].idle_tssi_5g;
target[0] = target[1] = 52;
a1[0] = a1[1] = -424;
b0[0] = b0[1] = 5612;
b1[0] = b1[1] = -1393;
}
}
/* target[0] = target[1] = nphy->tx_power_max; */
if (dev->phy.rev >= 3) {
if (sprom->fem.ghz2.tssipos)
b43_phy_set(dev, B43_NPHY_TXPCTL_ITSSI, 0x4000);
if (dev->phy.rev >= 7) {
for (c = 0; c < 2; c++) {
r = c ? 0x190 : 0x170;
if (b43_nphy_ipa(dev))
b43_radio_write(dev, r + 0x9, (b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ) ? 0xE : 0xC);
}
} else {
if (b43_nphy_ipa(dev)) {
tmp = (b43_current_band(dev->wl) == IEEE80211_BAND_5GHZ) ? 0xC : 0xE;
b43_radio_write(dev,
B2056_TX0 | B2056_TX_TX_SSI_MUX, tmp);
b43_radio_write(dev,
B2056_TX1 | B2056_TX_TX_SSI_MUX, tmp);
} else {
b43_radio_write(dev,
B2056_TX0 | B2056_TX_TX_SSI_MUX, 0x11);
b43_radio_write(dev,
B2056_TX1 | B2056_TX_TX_SSI_MUX, 0x11);
}
}
}
if (dev->dev->core_rev == 11 || dev->dev->core_rev == 12) {
b43_maskset32(dev, B43_MMIO_MACCTL, ~0, 0x200000);
b43_read32(dev, B43_MMIO_MACCTL);
udelay(1);
}
if (dev->phy.rev >= 7) {
b43_phy_maskset(dev, B43_NPHY_TXPCTL_CMD,
~B43_NPHY_TXPCTL_CMD_INIT, 0x19);
b43_phy_maskset(dev, B43_NPHY_TXPCTL_INIT,
~B43_NPHY_TXPCTL_INIT_PIDXI1, 0x19);
} else {
b43_phy_maskset(dev, B43_NPHY_TXPCTL_CMD,
~B43_NPHY_TXPCTL_CMD_INIT, 0x40);
if (dev->phy.rev > 1)
b43_phy_maskset(dev, B43_NPHY_TXPCTL_INIT,
~B43_NPHY_TXPCTL_INIT_PIDXI1, 0x40);
}
if (dev->dev->core_rev == 11 || dev->dev->core_rev == 12)
b43_maskset32(dev, B43_MMIO_MACCTL, ~0x200000, 0);
b43_phy_write(dev, B43_NPHY_TXPCTL_N,
0xF0 << B43_NPHY_TXPCTL_N_TSSID_SHIFT |
3 << B43_NPHY_TXPCTL_N_NPTIL2_SHIFT);
b43_phy_write(dev, B43_NPHY_TXPCTL_ITSSI,
idle[0] << B43_NPHY_TXPCTL_ITSSI_0_SHIFT |
idle[1] << B43_NPHY_TXPCTL_ITSSI_1_SHIFT |
B43_NPHY_TXPCTL_ITSSI_BINF);
b43_phy_write(dev, B43_NPHY_TXPCTL_TPWR,
target[0] << B43_NPHY_TXPCTL_TPWR_0_SHIFT |
target[1] << B43_NPHY_TXPCTL_TPWR_1_SHIFT);
for (c = 0; c < 2; c++) {
for (i = 0; i < 64; i++) {
num = 8 * (16 * b0[c] + b1[c] * i);
den = 32768 + a1[c] * i;
pwr = max((4 * num + den / 2) / den, -8);
if (dev->phy.rev < 3 && (i <= (31 - idle[c] + 1)))
pwr = max(pwr, target[c] + 1);
regval[i] = pwr;
}
b43_ntab_write_bulk(dev, B43_NTAB32(26 + c, 0), 64, regval);
}
b43_nphy_tx_prepare_adjusted_power_table(dev);
/*
b43_ntab_write_bulk(dev, B43_NTAB16(26, 64), 84, nphy->adj_pwr_tbl);
b43_ntab_write_bulk(dev, B43_NTAB16(27, 64), 84, nphy->adj_pwr_tbl);
*/
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, false);
}
static void b43_nphy_tx_gain_table_upload(struct b43_wldev *dev)
{
struct b43_phy *phy = &dev->phy;
const u32 *table = NULL;
u32 rfpwr_offset;
u8 pga_gain;
int i;
table = b43_nphy_get_tx_gain_table(dev);
b43_ntab_write_bulk(dev, B43_NTAB32(26, 192), 128, table);
b43_ntab_write_bulk(dev, B43_NTAB32(27, 192), 128, table);
if (phy->rev >= 3) {
#if 0
nphy->gmval = (table[0] >> 16) & 0x7000;
#endif
for (i = 0; i < 128; i++) {
pga_gain = (table[i] >> 24) & 0xF;
if (b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ)
rfpwr_offset =
b43_ntab_papd_pga_gain_delta_ipa_2g[pga_gain];
else
rfpwr_offset =
0; /* FIXME */
b43_ntab_write(dev, B43_NTAB32(26, 576 + i),
rfpwr_offset);
b43_ntab_write(dev, B43_NTAB32(27, 576 + i),
rfpwr_offset);
}
}
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/PA%20override */
static void b43_nphy_pa_override(struct b43_wldev *dev, bool enable)
{
struct b43_phy_n *nphy = dev->phy.n;
enum ieee80211_band band;
u16 tmp;
if (!enable) {
nphy->rfctrl_intc1_save = b43_phy_read(dev,
B43_NPHY_RFCTL_INTC1);
nphy->rfctrl_intc2_save = b43_phy_read(dev,
B43_NPHY_RFCTL_INTC2);
band = b43_current_band(dev->wl);
if (dev->phy.rev >= 3) {
if (band == IEEE80211_BAND_5GHZ)
tmp = 0x600;
else
tmp = 0x480;
} else {
if (band == IEEE80211_BAND_5GHZ)
tmp = 0x180;
else
tmp = 0x120;
}
b43_phy_write(dev, B43_NPHY_RFCTL_INTC1, tmp);
b43_phy_write(dev, B43_NPHY_RFCTL_INTC2, tmp);
} else {
b43_phy_write(dev, B43_NPHY_RFCTL_INTC1,
nphy->rfctrl_intc1_save);
b43_phy_write(dev, B43_NPHY_RFCTL_INTC2,
nphy->rfctrl_intc2_save);
}
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/TxLpFbw */
static void b43_nphy_tx_lp_fbw(struct b43_wldev *dev)
{
u16 tmp;
if (dev->phy.rev >= 3) {
if (b43_nphy_ipa(dev)) {
tmp = 4;
b43_phy_write(dev, B43_NPHY_TXF_40CO_B32S2,
(((((tmp << 3) | tmp) << 3) | tmp) << 3) | tmp);
}
tmp = 1;
b43_phy_write(dev, B43_NPHY_TXF_40CO_B1S2,
(((((tmp << 3) | tmp) << 3) | tmp) << 3) | tmp);
}
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/RxIqEst */
static void b43_nphy_rx_iq_est(struct b43_wldev *dev, struct nphy_iq_est *est,
u16 samps, u8 time, bool wait)
{
int i;
u16 tmp;
b43_phy_write(dev, B43_NPHY_IQEST_SAMCNT, samps);
b43_phy_maskset(dev, B43_NPHY_IQEST_WT, ~B43_NPHY_IQEST_WT_VAL, time);
if (wait)
b43_phy_set(dev, B43_NPHY_IQEST_CMD, B43_NPHY_IQEST_CMD_MODE);
else
b43_phy_mask(dev, B43_NPHY_IQEST_CMD, ~B43_NPHY_IQEST_CMD_MODE);
b43_phy_set(dev, B43_NPHY_IQEST_CMD, B43_NPHY_IQEST_CMD_START);
for (i = 1000; i; i--) {
tmp = b43_phy_read(dev, B43_NPHY_IQEST_CMD);
if (!(tmp & B43_NPHY_IQEST_CMD_START)) {
est->i0_pwr = (b43_phy_read(dev, B43_NPHY_IQEST_IPACC_HI0) << 16) |
b43_phy_read(dev, B43_NPHY_IQEST_IPACC_LO0);
est->q0_pwr = (b43_phy_read(dev, B43_NPHY_IQEST_QPACC_HI0) << 16) |
b43_phy_read(dev, B43_NPHY_IQEST_QPACC_LO0);
est->iq0_prod = (b43_phy_read(dev, B43_NPHY_IQEST_IQACC_HI0) << 16) |
b43_phy_read(dev, B43_NPHY_IQEST_IQACC_LO0);
est->i1_pwr = (b43_phy_read(dev, B43_NPHY_IQEST_IPACC_HI1) << 16) |
b43_phy_read(dev, B43_NPHY_IQEST_IPACC_LO1);
est->q1_pwr = (b43_phy_read(dev, B43_NPHY_IQEST_QPACC_HI1) << 16) |
b43_phy_read(dev, B43_NPHY_IQEST_QPACC_LO1);
est->iq1_prod = (b43_phy_read(dev, B43_NPHY_IQEST_IQACC_HI1) << 16) |
b43_phy_read(dev, B43_NPHY_IQEST_IQACC_LO1);
return;
}
udelay(10);
}
memset(est, 0, sizeof(*est));
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/RxIqCoeffs */
static void b43_nphy_rx_iq_coeffs(struct b43_wldev *dev, bool write,
struct b43_phy_n_iq_comp *pcomp)
{
if (write) {
b43_phy_write(dev, B43_NPHY_C1_RXIQ_COMPA0, pcomp->a0);
b43_phy_write(dev, B43_NPHY_C1_RXIQ_COMPB0, pcomp->b0);
b43_phy_write(dev, B43_NPHY_C2_RXIQ_COMPA1, pcomp->a1);
b43_phy_write(dev, B43_NPHY_C2_RXIQ_COMPB1, pcomp->b1);
} else {
pcomp->a0 = b43_phy_read(dev, B43_NPHY_C1_RXIQ_COMPA0);
pcomp->b0 = b43_phy_read(dev, B43_NPHY_C1_RXIQ_COMPB0);
pcomp->a1 = b43_phy_read(dev, B43_NPHY_C2_RXIQ_COMPA1);
pcomp->b1 = b43_phy_read(dev, B43_NPHY_C2_RXIQ_COMPB1);
}
}
#if 0
/* Ready but not used anywhere */
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/RxCalPhyCleanup */
static void b43_nphy_rx_cal_phy_cleanup(struct b43_wldev *dev, u8 core)
{
u16 *regs = dev->phy.n->tx_rx_cal_phy_saveregs;
b43_phy_write(dev, B43_NPHY_RFSEQCA, regs[0]);
if (core == 0) {
b43_phy_write(dev, B43_NPHY_AFECTL_C1, regs[1]);
b43_phy_write(dev, B43_NPHY_AFECTL_OVER1, regs[2]);
} else {
b43_phy_write(dev, B43_NPHY_AFECTL_C2, regs[1]);
b43_phy_write(dev, B43_NPHY_AFECTL_OVER, regs[2]);
}
b43_phy_write(dev, B43_NPHY_RFCTL_INTC1, regs[3]);
b43_phy_write(dev, B43_NPHY_RFCTL_INTC2, regs[4]);
b43_phy_write(dev, B43_NPHY_RFCTL_RSSIO1, regs[5]);
b43_phy_write(dev, B43_NPHY_RFCTL_RSSIO2, regs[6]);
b43_phy_write(dev, B43_NPHY_TXF_40CO_B1S1, regs[7]);
b43_phy_write(dev, B43_NPHY_RFCTL_OVER, regs[8]);
b43_phy_write(dev, B43_NPHY_PAPD_EN0, regs[9]);
b43_phy_write(dev, B43_NPHY_PAPD_EN1, regs[10]);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/RxCalPhySetup */
static void b43_nphy_rx_cal_phy_setup(struct b43_wldev *dev, u8 core)
{
u8 rxval, txval;
u16 *regs = dev->phy.n->tx_rx_cal_phy_saveregs;
regs[0] = b43_phy_read(dev, B43_NPHY_RFSEQCA);
if (core == 0) {
regs[1] = b43_phy_read(dev, B43_NPHY_AFECTL_C1);
regs[2] = b43_phy_read(dev, B43_NPHY_AFECTL_OVER1);
} else {
regs[1] = b43_phy_read(dev, B43_NPHY_AFECTL_C2);
regs[2] = b43_phy_read(dev, B43_NPHY_AFECTL_OVER);
}
regs[3] = b43_phy_read(dev, B43_NPHY_RFCTL_INTC1);
regs[4] = b43_phy_read(dev, B43_NPHY_RFCTL_INTC2);
regs[5] = b43_phy_read(dev, B43_NPHY_RFCTL_RSSIO1);
regs[6] = b43_phy_read(dev, B43_NPHY_RFCTL_RSSIO2);
regs[7] = b43_phy_read(dev, B43_NPHY_TXF_40CO_B1S1);
regs[8] = b43_phy_read(dev, B43_NPHY_RFCTL_OVER);
regs[9] = b43_phy_read(dev, B43_NPHY_PAPD_EN0);
regs[10] = b43_phy_read(dev, B43_NPHY_PAPD_EN1);
b43_phy_mask(dev, B43_NPHY_PAPD_EN0, ~0x0001);
b43_phy_mask(dev, B43_NPHY_PAPD_EN1, ~0x0001);
b43_phy_maskset(dev, B43_NPHY_RFSEQCA,
~B43_NPHY_RFSEQCA_RXDIS & 0xFFFF,
((1 - core) << B43_NPHY_RFSEQCA_RXDIS_SHIFT));
b43_phy_maskset(dev, B43_NPHY_RFSEQCA, ~B43_NPHY_RFSEQCA_TXEN,
((1 - core) << B43_NPHY_RFSEQCA_TXEN_SHIFT));
b43_phy_maskset(dev, B43_NPHY_RFSEQCA, ~B43_NPHY_RFSEQCA_RXEN,
(core << B43_NPHY_RFSEQCA_RXEN_SHIFT));
b43_phy_maskset(dev, B43_NPHY_RFSEQCA, ~B43_NPHY_RFSEQCA_TXDIS,
(core << B43_NPHY_RFSEQCA_TXDIS_SHIFT));
if (core == 0) {
b43_phy_mask(dev, B43_NPHY_AFECTL_C1, ~0x0007);
b43_phy_set(dev, B43_NPHY_AFECTL_OVER1, 0x0007);
} else {
b43_phy_mask(dev, B43_NPHY_AFECTL_C2, ~0x0007);
b43_phy_set(dev, B43_NPHY_AFECTL_OVER, 0x0007);
}
b43_nphy_rf_control_intc_override(dev, 2, 0, 3);
b43_nphy_rf_control_override(dev, 8, 0, 3, false);
b43_nphy_force_rf_sequence(dev, B43_RFSEQ_RX2TX);
if (core == 0) {
rxval = 1;
txval = 8;
} else {
rxval = 4;
txval = 2;
}
b43_nphy_rf_control_intc_override(dev, 1, rxval, (core + 1));
b43_nphy_rf_control_intc_override(dev, 1, txval, (2 - core));
}
#endif
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/CalcRxIqComp */
static void b43_nphy_calc_rx_iq_comp(struct b43_wldev *dev, u8 mask)
{
int i;
s32 iq;
u32 ii;
u32 qq;
int iq_nbits, qq_nbits;
int arsh, brsh;
u16 tmp, a, b;
struct nphy_iq_est est;
struct b43_phy_n_iq_comp old;
struct b43_phy_n_iq_comp new = { };
bool error = false;
if (mask == 0)
return;
b43_nphy_rx_iq_coeffs(dev, false, &old);
b43_nphy_rx_iq_coeffs(dev, true, &new);
b43_nphy_rx_iq_est(dev, &est, 0x4000, 32, false);
new = old;
for (i = 0; i < 2; i++) {
if (i == 0 && (mask & 1)) {
iq = est.iq0_prod;
ii = est.i0_pwr;
qq = est.q0_pwr;
} else if (i == 1 && (mask & 2)) {
iq = est.iq1_prod;
ii = est.i1_pwr;
qq = est.q1_pwr;
} else {
continue;
}
if (ii + qq < 2) {
error = true;
break;
}
iq_nbits = fls(abs(iq));
qq_nbits = fls(qq);
arsh = iq_nbits - 20;
if (arsh >= 0) {
a = -((iq << (30 - iq_nbits)) + (ii >> (1 + arsh)));
tmp = ii >> arsh;
} else {
a = -((iq << (30 - iq_nbits)) + (ii << (-1 - arsh)));
tmp = ii << -arsh;
}
if (tmp == 0) {
error = true;
break;
}
a /= tmp;
brsh = qq_nbits - 11;
if (brsh >= 0) {
b = (qq << (31 - qq_nbits));
tmp = ii >> brsh;
} else {
b = (qq << (31 - qq_nbits));
tmp = ii << -brsh;
}
if (tmp == 0) {
error = true;
break;
}
b = int_sqrt(b / tmp - a * a) - (1 << 10);
if (i == 0 && (mask & 0x1)) {
if (dev->phy.rev >= 3) {
new.a0 = a & 0x3FF;
new.b0 = b & 0x3FF;
} else {
new.a0 = b & 0x3FF;
new.b0 = a & 0x3FF;
}
} else if (i == 1 && (mask & 0x2)) {
if (dev->phy.rev >= 3) {
new.a1 = a & 0x3FF;
new.b1 = b & 0x3FF;
} else {
new.a1 = b & 0x3FF;
new.b1 = a & 0x3FF;
}
}
}
if (error)
new = old;
b43_nphy_rx_iq_coeffs(dev, true, &new);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/TxIqWar */
static void b43_nphy_tx_iq_workaround(struct b43_wldev *dev)
{
u16 array[4];
b43_ntab_read_bulk(dev, B43_NTAB16(0xF, 0x50), 4, array);
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_NPHY_TXIQW0, array[0]);
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_NPHY_TXIQW1, array[1]);
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_NPHY_TXIQW2, array[2]);
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_NPHY_TXIQW3, array[3]);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/SpurWar */
static void b43_nphy_spur_workaround(struct b43_wldev *dev)
{
struct b43_phy_n *nphy = dev->phy.n;
u8 channel = dev->phy.channel;
int tone[2] = { 57, 58 };
u32 noise[2] = { 0x3FF, 0x3FF };
B43_WARN_ON(dev->phy.rev < 3);
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, 1);
if (nphy->gband_spurwar_en) {
/* TODO: N PHY Adjust Analog Pfbw (7) */
if (channel == 11 && dev->phy.is_40mhz)
; /* TODO: N PHY Adjust Min Noise Var(2, tone, noise)*/
else
; /* TODO: N PHY Adjust Min Noise Var(0, NULL, NULL)*/
/* TODO: N PHY Adjust CRS Min Power (0x1E) */
}
if (nphy->aband_spurwar_en) {
if (channel == 54) {
tone[0] = 0x20;
noise[0] = 0x25F;
} else if (channel == 38 || channel == 102 || channel == 118) {
if (0 /* FIXME */) {
tone[0] = 0x20;
noise[0] = 0x21F;
} else {
tone[0] = 0;
noise[0] = 0;
}
} else if (channel == 134) {
tone[0] = 0x20;
noise[0] = 0x21F;
} else if (channel == 151) {
tone[0] = 0x10;
noise[0] = 0x23F;
} else if (channel == 153 || channel == 161) {
tone[0] = 0x30;
noise[0] = 0x23F;
} else {
tone[0] = 0;
noise[0] = 0;
}
if (!tone[0] && !noise[0])
; /* TODO: N PHY Adjust Min Noise Var(1, tone, noise)*/
else
; /* TODO: N PHY Adjust Min Noise Var(0, NULL, NULL)*/
}
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, 0);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/TxPwrCtrlCoefSetup */
static void b43_nphy_tx_pwr_ctrl_coef_setup(struct b43_wldev *dev)
{
struct b43_phy_n *nphy = dev->phy.n;
int i, j;
u32 tmp;
u32 cur_real, cur_imag, real_part, imag_part;
u16 buffer[7];
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, true);
b43_ntab_read_bulk(dev, B43_NTAB16(15, 80), 7, buffer);
for (i = 0; i < 2; i++) {
tmp = ((buffer[i * 2] & 0x3FF) << 10) |
(buffer[i * 2 + 1] & 0x3FF);
b43_phy_write(dev, B43_NPHY_TABLE_ADDR,
(((i + 26) << 10) | 320));
for (j = 0; j < 128; j++) {
b43_phy_write(dev, B43_NPHY_TABLE_DATAHI,
((tmp >> 16) & 0xFFFF));
b43_phy_write(dev, B43_NPHY_TABLE_DATALO,
(tmp & 0xFFFF));
}
}
for (i = 0; i < 2; i++) {
tmp = buffer[5 + i];
real_part = (tmp >> 8) & 0xFF;
imag_part = (tmp & 0xFF);
b43_phy_write(dev, B43_NPHY_TABLE_ADDR,
(((i + 26) << 10) | 448));
if (dev->phy.rev >= 3) {
cur_real = real_part;
cur_imag = imag_part;
tmp = ((cur_real & 0xFF) << 8) | (cur_imag & 0xFF);
}
for (j = 0; j < 128; j++) {
if (dev->phy.rev < 3) {
cur_real = (real_part * loscale[j] + 128) >> 8;
cur_imag = (imag_part * loscale[j] + 128) >> 8;
tmp = ((cur_real & 0xFF) << 8) |
(cur_imag & 0xFF);
}
b43_phy_write(dev, B43_NPHY_TABLE_DATAHI,
((tmp >> 16) & 0xFFFF));
b43_phy_write(dev, B43_NPHY_TABLE_DATALO,
(tmp & 0xFFFF));
}
}
if (dev->phy.rev >= 3) {
b43_shm_write16(dev, B43_SHM_SHARED,
B43_SHM_SH_NPHY_TXPWR_INDX0, 0xFFFF);
b43_shm_write16(dev, B43_SHM_SHARED,
B43_SHM_SH_NPHY_TXPWR_INDX1, 0xFFFF);
}
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, false);
}
/*
* Restore RSSI Calibration
* http://bcm-v4.sipsolutions.net/802.11/PHY/N/RestoreRssiCal
*/
static void b43_nphy_restore_rssi_cal(struct b43_wldev *dev)
{
struct b43_phy_n *nphy = dev->phy.n;
u16 *rssical_radio_regs = NULL;
u16 *rssical_phy_regs = NULL;
if (b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ) {
if (!nphy->rssical_chanspec_2G.center_freq)
return;
rssical_radio_regs = nphy->rssical_cache.rssical_radio_regs_2G;
rssical_phy_regs = nphy->rssical_cache.rssical_phy_regs_2G;
} else {
if (!nphy->rssical_chanspec_5G.center_freq)
return;
rssical_radio_regs = nphy->rssical_cache.rssical_radio_regs_5G;
rssical_phy_regs = nphy->rssical_cache.rssical_phy_regs_5G;
}
/* TODO use some definitions */
b43_radio_maskset(dev, 0x602B, 0xE3, rssical_radio_regs[0]);
b43_radio_maskset(dev, 0x702B, 0xE3, rssical_radio_regs[1]);
b43_phy_write(dev, B43_NPHY_RSSIMC_0I_RSSI_Z, rssical_phy_regs[0]);
b43_phy_write(dev, B43_NPHY_RSSIMC_0Q_RSSI_Z, rssical_phy_regs[1]);
b43_phy_write(dev, B43_NPHY_RSSIMC_1I_RSSI_Z, rssical_phy_regs[2]);
b43_phy_write(dev, B43_NPHY_RSSIMC_1Q_RSSI_Z, rssical_phy_regs[3]);
b43_phy_write(dev, B43_NPHY_RSSIMC_0I_RSSI_X, rssical_phy_regs[4]);
b43_phy_write(dev, B43_NPHY_RSSIMC_0Q_RSSI_X, rssical_phy_regs[5]);
b43_phy_write(dev, B43_NPHY_RSSIMC_1I_RSSI_X, rssical_phy_regs[6]);
b43_phy_write(dev, B43_NPHY_RSSIMC_1Q_RSSI_X, rssical_phy_regs[7]);
b43_phy_write(dev, B43_NPHY_RSSIMC_0I_RSSI_Y, rssical_phy_regs[8]);
b43_phy_write(dev, B43_NPHY_RSSIMC_0Q_RSSI_Y, rssical_phy_regs[9]);
b43_phy_write(dev, B43_NPHY_RSSIMC_1I_RSSI_Y, rssical_phy_regs[10]);
b43_phy_write(dev, B43_NPHY_RSSIMC_1Q_RSSI_Y, rssical_phy_regs[11]);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/TxCalRadioSetup */
static void b43_nphy_tx_cal_radio_setup(struct b43_wldev *dev)
{
struct b43_phy_n *nphy = dev->phy.n;
u16 *save = nphy->tx_rx_cal_radio_saveregs;
u16 tmp;
u8 offset, i;
if (dev->phy.rev >= 3) {
for (i = 0; i < 2; i++) {
tmp = (i == 0) ? 0x2000 : 0x3000;
offset = i * 11;
save[offset + 0] = b43_radio_read16(dev, B2055_CAL_RVARCTL);
save[offset + 1] = b43_radio_read16(dev, B2055_CAL_LPOCTL);
save[offset + 2] = b43_radio_read16(dev, B2055_CAL_TS);
save[offset + 3] = b43_radio_read16(dev, B2055_CAL_RCCALRTS);
save[offset + 4] = b43_radio_read16(dev, B2055_CAL_RCALRTS);
save[offset + 5] = b43_radio_read16(dev, B2055_PADDRV);
save[offset + 6] = b43_radio_read16(dev, B2055_XOCTL1);
save[offset + 7] = b43_radio_read16(dev, B2055_XOCTL2);
save[offset + 8] = b43_radio_read16(dev, B2055_XOREGUL);
save[offset + 9] = b43_radio_read16(dev, B2055_XOMISC);
save[offset + 10] = b43_radio_read16(dev, B2055_PLL_LFC1);
if (b43_current_band(dev->wl) == IEEE80211_BAND_5GHZ) {
b43_radio_write16(dev, tmp | B2055_CAL_RVARCTL, 0x0A);
b43_radio_write16(dev, tmp | B2055_CAL_LPOCTL, 0x40);
b43_radio_write16(dev, tmp | B2055_CAL_TS, 0x55);
b43_radio_write16(dev, tmp | B2055_CAL_RCCALRTS, 0);
b43_radio_write16(dev, tmp | B2055_CAL_RCALRTS, 0);
if (nphy->ipa5g_on) {
b43_radio_write16(dev, tmp | B2055_PADDRV, 4);
b43_radio_write16(dev, tmp | B2055_XOCTL1, 1);
} else {
b43_radio_write16(dev, tmp | B2055_PADDRV, 0);
b43_radio_write16(dev, tmp | B2055_XOCTL1, 0x2F);
}
b43_radio_write16(dev, tmp | B2055_XOCTL2, 0);
} else {
b43_radio_write16(dev, tmp | B2055_CAL_RVARCTL, 0x06);
b43_radio_write16(dev, tmp | B2055_CAL_LPOCTL, 0x40);
b43_radio_write16(dev, tmp | B2055_CAL_TS, 0x55);
b43_radio_write16(dev, tmp | B2055_CAL_RCCALRTS, 0);
b43_radio_write16(dev, tmp | B2055_CAL_RCALRTS, 0);
b43_radio_write16(dev, tmp | B2055_XOCTL1, 0);
if (nphy->ipa2g_on) {
b43_radio_write16(dev, tmp | B2055_PADDRV, 6);
b43_radio_write16(dev, tmp | B2055_XOCTL2,
(dev->phy.rev < 5) ? 0x11 : 0x01);
} else {
b43_radio_write16(dev, tmp | B2055_PADDRV, 0);
b43_radio_write16(dev, tmp | B2055_XOCTL2, 0);
}
}
b43_radio_write16(dev, tmp | B2055_XOREGUL, 0);
b43_radio_write16(dev, tmp | B2055_XOMISC, 0);
b43_radio_write16(dev, tmp | B2055_PLL_LFC1, 0);
}
} else {
save[0] = b43_radio_read16(dev, B2055_C1_TX_RF_IQCAL1);
b43_radio_write16(dev, B2055_C1_TX_RF_IQCAL1, 0x29);
save[1] = b43_radio_read16(dev, B2055_C1_TX_RF_IQCAL2);
b43_radio_write16(dev, B2055_C1_TX_RF_IQCAL2, 0x54);
save[2] = b43_radio_read16(dev, B2055_C2_TX_RF_IQCAL1);
b43_radio_write16(dev, B2055_C2_TX_RF_IQCAL1, 0x29);
save[3] = b43_radio_read16(dev, B2055_C2_TX_RF_IQCAL2);
b43_radio_write16(dev, B2055_C2_TX_RF_IQCAL2, 0x54);
save[3] = b43_radio_read16(dev, B2055_C1_PWRDET_RXTX);
save[4] = b43_radio_read16(dev, B2055_C2_PWRDET_RXTX);
if (!(b43_phy_read(dev, B43_NPHY_BANDCTL) &
B43_NPHY_BANDCTL_5GHZ)) {
b43_radio_write16(dev, B2055_C1_PWRDET_RXTX, 0x04);
b43_radio_write16(dev, B2055_C2_PWRDET_RXTX, 0x04);
} else {
b43_radio_write16(dev, B2055_C1_PWRDET_RXTX, 0x20);
b43_radio_write16(dev, B2055_C2_PWRDET_RXTX, 0x20);
}
if (dev->phy.rev < 2) {
b43_radio_set(dev, B2055_C1_TX_BB_MXGM, 0x20);
b43_radio_set(dev, B2055_C2_TX_BB_MXGM, 0x20);
} else {
b43_radio_mask(dev, B2055_C1_TX_BB_MXGM, ~0x20);
b43_radio_mask(dev, B2055_C2_TX_BB_MXGM, ~0x20);
}
}
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/UpdateTxCalLadder */
static void b43_nphy_update_tx_cal_ladder(struct b43_wldev *dev, u16 core)
{
struct b43_phy_n *nphy = dev->phy.n;
int i;
u16 scale, entry;
u16 tmp = nphy->txcal_bbmult;
if (core == 0)
tmp >>= 8;
tmp &= 0xff;
for (i = 0; i < 18; i++) {
scale = (ladder_lo[i].percent * tmp) / 100;
entry = ((scale & 0xFF) << 8) | ladder_lo[i].g_env;
b43_ntab_write(dev, B43_NTAB16(15, i), entry);
scale = (ladder_iq[i].percent * tmp) / 100;
entry = ((scale & 0xFF) << 8) | ladder_iq[i].g_env;
b43_ntab_write(dev, B43_NTAB16(15, i + 32), entry);
}
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/ExtPaSetTxDigiFilts */
static void b43_nphy_ext_pa_set_tx_dig_filters(struct b43_wldev *dev)
{
int i;
for (i = 0; i < 15; i++)
b43_phy_write(dev, B43_PHY_N(0x2C5 + i),
tbl_tx_filter_coef_rev4[2][i]);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/IpaSetTxDigiFilts */
static void b43_nphy_int_pa_set_tx_dig_filters(struct b43_wldev *dev)
{
int i, j;
/* B43_NPHY_TXF_20CO_S0A1, B43_NPHY_TXF_40CO_S0A1, unknown */
static const u16 offset[] = { 0x186, 0x195, 0x2C5 };
for (i = 0; i < 3; i++)
for (j = 0; j < 15; j++)
b43_phy_write(dev, B43_PHY_N(offset[i] + j),
tbl_tx_filter_coef_rev4[i][j]);
if (dev->phy.is_40mhz) {
for (j = 0; j < 15; j++)
b43_phy_write(dev, B43_PHY_N(offset[0] + j),
tbl_tx_filter_coef_rev4[3][j]);
} else if (b43_current_band(dev->wl) == IEEE80211_BAND_5GHZ) {
for (j = 0; j < 15; j++)
b43_phy_write(dev, B43_PHY_N(offset[0] + j),
tbl_tx_filter_coef_rev4[5][j]);
}
if (dev->phy.channel == 14)
for (j = 0; j < 15; j++)
b43_phy_write(dev, B43_PHY_N(offset[0] + j),
tbl_tx_filter_coef_rev4[6][j]);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/GetTxGain */
static struct nphy_txgains b43_nphy_get_tx_gains(struct b43_wldev *dev)
{
struct b43_phy_n *nphy = dev->phy.n;
u16 curr_gain[2];
struct nphy_txgains target;
const u32 *table = NULL;
if (!nphy->txpwrctrl) {
int i;
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, true);
b43_ntab_read_bulk(dev, B43_NTAB16(7, 0x110), 2, curr_gain);
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, false);
for (i = 0; i < 2; ++i) {
if (dev->phy.rev >= 3) {
target.ipa[i] = curr_gain[i] & 0x000F;
target.pad[i] = (curr_gain[i] & 0x00F0) >> 4;
target.pga[i] = (curr_gain[i] & 0x0F00) >> 8;
target.txgm[i] = (curr_gain[i] & 0x7000) >> 12;
} else {
target.ipa[i] = curr_gain[i] & 0x0003;
target.pad[i] = (curr_gain[i] & 0x000C) >> 2;
target.pga[i] = (curr_gain[i] & 0x0070) >> 4;
target.txgm[i] = (curr_gain[i] & 0x0380) >> 7;
}
}
} else {
int i;
u16 index[2];
index[0] = (b43_phy_read(dev, B43_NPHY_C1_TXPCTL_STAT) &
B43_NPHY_TXPCTL_STAT_BIDX) >>
B43_NPHY_TXPCTL_STAT_BIDX_SHIFT;
index[1] = (b43_phy_read(dev, B43_NPHY_C2_TXPCTL_STAT) &
B43_NPHY_TXPCTL_STAT_BIDX) >>
B43_NPHY_TXPCTL_STAT_BIDX_SHIFT;
for (i = 0; i < 2; ++i) {
table = b43_nphy_get_tx_gain_table(dev);
if (dev->phy.rev >= 3) {
target.ipa[i] = (table[index[i]] >> 16) & 0xF;
target.pad[i] = (table[index[i]] >> 20) & 0xF;
target.pga[i] = (table[index[i]] >> 24) & 0xF;
target.txgm[i] = (table[index[i]] >> 28) & 0xF;
} else {
target.ipa[i] = (table[index[i]] >> 16) & 0x3;
target.pad[i] = (table[index[i]] >> 18) & 0x3;
target.pga[i] = (table[index[i]] >> 20) & 0x7;
target.txgm[i] = (table[index[i]] >> 23) & 0x7;
}
}
}
return target;
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/TxCalPhyCleanup */
static void b43_nphy_tx_cal_phy_cleanup(struct b43_wldev *dev)
{
u16 *regs = dev->phy.n->tx_rx_cal_phy_saveregs;
if (dev->phy.rev >= 3) {
b43_phy_write(dev, B43_NPHY_AFECTL_C1, regs[0]);
b43_phy_write(dev, B43_NPHY_AFECTL_C2, regs[1]);
b43_phy_write(dev, B43_NPHY_AFECTL_OVER1, regs[2]);
b43_phy_write(dev, B43_NPHY_AFECTL_OVER, regs[3]);
b43_phy_write(dev, B43_NPHY_BBCFG, regs[4]);
b43_ntab_write(dev, B43_NTAB16(8, 3), regs[5]);
b43_ntab_write(dev, B43_NTAB16(8, 19), regs[6]);
b43_phy_write(dev, B43_NPHY_RFCTL_INTC1, regs[7]);
b43_phy_write(dev, B43_NPHY_RFCTL_INTC2, regs[8]);
b43_phy_write(dev, B43_NPHY_PAPD_EN0, regs[9]);
b43_phy_write(dev, B43_NPHY_PAPD_EN1, regs[10]);
b43_nphy_reset_cca(dev);
} else {
b43_phy_maskset(dev, B43_NPHY_AFECTL_C1, 0x0FFF, regs[0]);
b43_phy_maskset(dev, B43_NPHY_AFECTL_C2, 0x0FFF, regs[1]);
b43_phy_write(dev, B43_NPHY_AFECTL_OVER, regs[2]);
b43_ntab_write(dev, B43_NTAB16(8, 2), regs[3]);
b43_ntab_write(dev, B43_NTAB16(8, 18), regs[4]);
b43_phy_write(dev, B43_NPHY_RFCTL_INTC1, regs[5]);
b43_phy_write(dev, B43_NPHY_RFCTL_INTC2, regs[6]);
}
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/TxCalPhySetup */
static void b43_nphy_tx_cal_phy_setup(struct b43_wldev *dev)
{
u16 *regs = dev->phy.n->tx_rx_cal_phy_saveregs;
u16 tmp;
regs[0] = b43_phy_read(dev, B43_NPHY_AFECTL_C1);
regs[1] = b43_phy_read(dev, B43_NPHY_AFECTL_C2);
if (dev->phy.rev >= 3) {
b43_phy_maskset(dev, B43_NPHY_AFECTL_C1, 0xF0FF, 0x0A00);
b43_phy_maskset(dev, B43_NPHY_AFECTL_C2, 0xF0FF, 0x0A00);
tmp = b43_phy_read(dev, B43_NPHY_AFECTL_OVER1);
regs[2] = tmp;
b43_phy_write(dev, B43_NPHY_AFECTL_OVER1, tmp | 0x0600);
tmp = b43_phy_read(dev, B43_NPHY_AFECTL_OVER);
regs[3] = tmp;
b43_phy_write(dev, B43_NPHY_AFECTL_OVER, tmp | 0x0600);
regs[4] = b43_phy_read(dev, B43_NPHY_BBCFG);
b43_phy_mask(dev, B43_NPHY_BBCFG,
~B43_NPHY_BBCFG_RSTRX & 0xFFFF);
tmp = b43_ntab_read(dev, B43_NTAB16(8, 3));
regs[5] = tmp;
b43_ntab_write(dev, B43_NTAB16(8, 3), 0);
tmp = b43_ntab_read(dev, B43_NTAB16(8, 19));
regs[6] = tmp;
b43_ntab_write(dev, B43_NTAB16(8, 19), 0);
regs[7] = b43_phy_read(dev, B43_NPHY_RFCTL_INTC1);
regs[8] = b43_phy_read(dev, B43_NPHY_RFCTL_INTC2);
b43_nphy_rf_control_intc_override(dev, 2, 1, 3);
b43_nphy_rf_control_intc_override(dev, 1, 2, 1);
b43_nphy_rf_control_intc_override(dev, 1, 8, 2);
regs[9] = b43_phy_read(dev, B43_NPHY_PAPD_EN0);
regs[10] = b43_phy_read(dev, B43_NPHY_PAPD_EN1);
b43_phy_mask(dev, B43_NPHY_PAPD_EN0, ~0x0001);
b43_phy_mask(dev, B43_NPHY_PAPD_EN1, ~0x0001);
} else {
b43_phy_maskset(dev, B43_NPHY_AFECTL_C1, 0x0FFF, 0xA000);
b43_phy_maskset(dev, B43_NPHY_AFECTL_C2, 0x0FFF, 0xA000);
tmp = b43_phy_read(dev, B43_NPHY_AFECTL_OVER);
regs[2] = tmp;
b43_phy_write(dev, B43_NPHY_AFECTL_OVER, tmp | 0x3000);
tmp = b43_ntab_read(dev, B43_NTAB16(8, 2));
regs[3] = tmp;
tmp |= 0x2000;
b43_ntab_write(dev, B43_NTAB16(8, 2), tmp);
tmp = b43_ntab_read(dev, B43_NTAB16(8, 18));
regs[4] = tmp;
tmp |= 0x2000;
b43_ntab_write(dev, B43_NTAB16(8, 18), tmp);
regs[5] = b43_phy_read(dev, B43_NPHY_RFCTL_INTC1);
regs[6] = b43_phy_read(dev, B43_NPHY_RFCTL_INTC2);
if (b43_current_band(dev->wl) == IEEE80211_BAND_5GHZ)
tmp = 0x0180;
else
tmp = 0x0120;
b43_phy_write(dev, B43_NPHY_RFCTL_INTC1, tmp);
b43_phy_write(dev, B43_NPHY_RFCTL_INTC2, tmp);
}
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/SaveCal */
static void b43_nphy_save_cal(struct b43_wldev *dev)
{
struct b43_phy_n *nphy = dev->phy.n;
struct b43_phy_n_iq_comp *rxcal_coeffs = NULL;
u16 *txcal_radio_regs = NULL;
struct b43_chanspec *iqcal_chanspec;
u16 *table = NULL;
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, 1);
if (b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ) {
rxcal_coeffs = &nphy->cal_cache.rxcal_coeffs_2G;
txcal_radio_regs = nphy->cal_cache.txcal_radio_regs_2G;
iqcal_chanspec = &nphy->iqcal_chanspec_2G;
table = nphy->cal_cache.txcal_coeffs_2G;
} else {
rxcal_coeffs = &nphy->cal_cache.rxcal_coeffs_5G;
txcal_radio_regs = nphy->cal_cache.txcal_radio_regs_5G;
iqcal_chanspec = &nphy->iqcal_chanspec_5G;
table = nphy->cal_cache.txcal_coeffs_5G;
}
b43_nphy_rx_iq_coeffs(dev, false, rxcal_coeffs);
/* TODO use some definitions */
if (dev->phy.rev >= 3) {
txcal_radio_regs[0] = b43_radio_read(dev, 0x2021);
txcal_radio_regs[1] = b43_radio_read(dev, 0x2022);
txcal_radio_regs[2] = b43_radio_read(dev, 0x3021);
txcal_radio_regs[3] = b43_radio_read(dev, 0x3022);
txcal_radio_regs[4] = b43_radio_read(dev, 0x2023);
txcal_radio_regs[5] = b43_radio_read(dev, 0x2024);
txcal_radio_regs[6] = b43_radio_read(dev, 0x3023);
txcal_radio_regs[7] = b43_radio_read(dev, 0x3024);
} else {
txcal_radio_regs[0] = b43_radio_read(dev, 0x8B);
txcal_radio_regs[1] = b43_radio_read(dev, 0xBA);
txcal_radio_regs[2] = b43_radio_read(dev, 0x8D);
txcal_radio_regs[3] = b43_radio_read(dev, 0xBC);
}
iqcal_chanspec->center_freq = dev->phy.channel_freq;
iqcal_chanspec->channel_type = dev->phy.channel_type;
b43_ntab_read_bulk(dev, B43_NTAB16(15, 80), 8, table);
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, 0);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/RestoreCal */
static void b43_nphy_restore_cal(struct b43_wldev *dev)
{
struct b43_phy_n *nphy = dev->phy.n;
u16 coef[4];
u16 *loft = NULL;
u16 *table = NULL;
int i;
u16 *txcal_radio_regs = NULL;
struct b43_phy_n_iq_comp *rxcal_coeffs = NULL;
if (b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ) {
if (!nphy->iqcal_chanspec_2G.center_freq)
return;
table = nphy->cal_cache.txcal_coeffs_2G;
loft = &nphy->cal_cache.txcal_coeffs_2G[5];
} else {
if (!nphy->iqcal_chanspec_5G.center_freq)
return;
table = nphy->cal_cache.txcal_coeffs_5G;
loft = &nphy->cal_cache.txcal_coeffs_5G[5];
}
b43_ntab_write_bulk(dev, B43_NTAB16(15, 80), 4, table);
for (i = 0; i < 4; i++) {
if (dev->phy.rev >= 3)
table[i] = coef[i];
else
coef[i] = 0;
}
b43_ntab_write_bulk(dev, B43_NTAB16(15, 88), 4, coef);
b43_ntab_write_bulk(dev, B43_NTAB16(15, 85), 2, loft);
b43_ntab_write_bulk(dev, B43_NTAB16(15, 93), 2, loft);
if (dev->phy.rev < 2)
b43_nphy_tx_iq_workaround(dev);
if (b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ) {
txcal_radio_regs = nphy->cal_cache.txcal_radio_regs_2G;
rxcal_coeffs = &nphy->cal_cache.rxcal_coeffs_2G;
} else {
txcal_radio_regs = nphy->cal_cache.txcal_radio_regs_5G;
rxcal_coeffs = &nphy->cal_cache.rxcal_coeffs_5G;
}
/* TODO use some definitions */
if (dev->phy.rev >= 3) {
b43_radio_write(dev, 0x2021, txcal_radio_regs[0]);
b43_radio_write(dev, 0x2022, txcal_radio_regs[1]);
b43_radio_write(dev, 0x3021, txcal_radio_regs[2]);
b43_radio_write(dev, 0x3022, txcal_radio_regs[3]);
b43_radio_write(dev, 0x2023, txcal_radio_regs[4]);
b43_radio_write(dev, 0x2024, txcal_radio_regs[5]);
b43_radio_write(dev, 0x3023, txcal_radio_regs[6]);
b43_radio_write(dev, 0x3024, txcal_radio_regs[7]);
} else {
b43_radio_write(dev, 0x8B, txcal_radio_regs[0]);
b43_radio_write(dev, 0xBA, txcal_radio_regs[1]);
b43_radio_write(dev, 0x8D, txcal_radio_regs[2]);
b43_radio_write(dev, 0xBC, txcal_radio_regs[3]);
}
b43_nphy_rx_iq_coeffs(dev, true, rxcal_coeffs);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/CalTxIqlo */
static int b43_nphy_cal_tx_iq_lo(struct b43_wldev *dev,
struct nphy_txgains target,
bool full, bool mphase)
{
struct b43_phy_n *nphy = dev->phy.n;
int i;
int error = 0;
int freq;
bool avoid = false;
u8 length;
u16 tmp, core, type, count, max, numb, last = 0, cmd;
const u16 *table;
bool phy6or5x;
u16 buffer[11];
u16 diq_start = 0;
u16 save[2];
u16 gain[2];
struct nphy_iqcal_params params[2];
bool updated[2] = { };
b43_nphy_stay_in_carrier_search(dev, true);
if (dev->phy.rev >= 4) {
avoid = nphy->hang_avoid;
nphy->hang_avoid = false;
}
b43_ntab_read_bulk(dev, B43_NTAB16(7, 0x110), 2, save);
for (i = 0; i < 2; i++) {
b43_nphy_iq_cal_gain_params(dev, i, target, ¶ms[i]);
gain[i] = params[i].cal_gain;
}
b43_ntab_write_bulk(dev, B43_NTAB16(7, 0x110), 2, gain);
b43_nphy_tx_cal_radio_setup(dev);
b43_nphy_tx_cal_phy_setup(dev);
phy6or5x = dev->phy.rev >= 6 ||
(dev->phy.rev == 5 && nphy->ipa2g_on &&
b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ);
if (phy6or5x) {
if (dev->phy.is_40mhz) {
b43_ntab_write_bulk(dev, B43_NTAB16(15, 0), 18,
tbl_tx_iqlo_cal_loft_ladder_40);
b43_ntab_write_bulk(dev, B43_NTAB16(15, 32), 18,
tbl_tx_iqlo_cal_iqimb_ladder_40);
} else {
b43_ntab_write_bulk(dev, B43_NTAB16(15, 0), 18,
tbl_tx_iqlo_cal_loft_ladder_20);
b43_ntab_write_bulk(dev, B43_NTAB16(15, 32), 18,
tbl_tx_iqlo_cal_iqimb_ladder_20);
}
}
b43_phy_write(dev, B43_NPHY_IQLOCAL_CMDGCTL, 0x8AA9);
if (!dev->phy.is_40mhz)
freq = 2500;
else
freq = 5000;
if (nphy->mphase_cal_phase_id > 2)
b43_nphy_run_samples(dev, (dev->phy.is_40mhz ? 40 : 20) * 8,
0xFFFF, 0, true, false);
else
error = b43_nphy_tx_tone(dev, freq, 250, true, false);
if (error == 0) {
if (nphy->mphase_cal_phase_id > 2) {
table = nphy->mphase_txcal_bestcoeffs;
length = 11;
if (dev->phy.rev < 3)
length -= 2;
} else {
if (!full && nphy->txiqlocal_coeffsvalid) {
table = nphy->txiqlocal_bestc;
length = 11;
if (dev->phy.rev < 3)
length -= 2;
} else {
full = true;
if (dev->phy.rev >= 3) {
table = tbl_tx_iqlo_cal_startcoefs_nphyrev3;
length = B43_NTAB_TX_IQLO_CAL_STARTCOEFS_REV3;
} else {
table = tbl_tx_iqlo_cal_startcoefs;
length = B43_NTAB_TX_IQLO_CAL_STARTCOEFS;
}
}
}
b43_ntab_write_bulk(dev, B43_NTAB16(15, 64), length, table);
if (full) {
if (dev->phy.rev >= 3)
max = B43_NTAB_TX_IQLO_CAL_CMDS_FULLCAL_REV3;
else
max = B43_NTAB_TX_IQLO_CAL_CMDS_FULLCAL;
} else {
if (dev->phy.rev >= 3)
max = B43_NTAB_TX_IQLO_CAL_CMDS_RECAL_REV3;
else
max = B43_NTAB_TX_IQLO_CAL_CMDS_RECAL;
}
if (mphase) {
count = nphy->mphase_txcal_cmdidx;
numb = min(max,
(u16)(count + nphy->mphase_txcal_numcmds));
} else {
count = 0;
numb = max;
}
for (; count < numb; count++) {
if (full) {
if (dev->phy.rev >= 3)
cmd = tbl_tx_iqlo_cal_cmds_fullcal_nphyrev3[count];
else
cmd = tbl_tx_iqlo_cal_cmds_fullcal[count];
} else {
if (dev->phy.rev >= 3)
cmd = tbl_tx_iqlo_cal_cmds_recal_nphyrev3[count];
else
cmd = tbl_tx_iqlo_cal_cmds_recal[count];
}
core = (cmd & 0x3000) >> 12;
type = (cmd & 0x0F00) >> 8;
if (phy6or5x && updated[core] == 0) {
b43_nphy_update_tx_cal_ladder(dev, core);
updated[core] = true;
}
tmp = (params[core].ncorr[type] << 8) | 0x66;
b43_phy_write(dev, B43_NPHY_IQLOCAL_CMDNNUM, tmp);
if (type == 1 || type == 3 || type == 4) {
buffer[0] = b43_ntab_read(dev,
B43_NTAB16(15, 69 + core));
diq_start = buffer[0];
buffer[0] = 0;
b43_ntab_write(dev, B43_NTAB16(15, 69 + core),
0);
}
b43_phy_write(dev, B43_NPHY_IQLOCAL_CMD, cmd);
for (i = 0; i < 2000; i++) {
tmp = b43_phy_read(dev, B43_NPHY_IQLOCAL_CMD);
if (tmp & 0xC000)
break;
udelay(10);
}
b43_ntab_read_bulk(dev, B43_NTAB16(15, 96), length,
buffer);
b43_ntab_write_bulk(dev, B43_NTAB16(15, 64), length,
buffer);
if (type == 1 || type == 3 || type == 4)
buffer[0] = diq_start;
}
if (mphase)
nphy->mphase_txcal_cmdidx = (numb >= max) ? 0 : numb;
last = (dev->phy.rev < 3) ? 6 : 7;
if (!mphase || nphy->mphase_cal_phase_id == last) {
b43_ntab_write_bulk(dev, B43_NTAB16(15, 96), 4, buffer);
b43_ntab_read_bulk(dev, B43_NTAB16(15, 80), 4, buffer);
if (dev->phy.rev < 3) {
buffer[0] = 0;
buffer[1] = 0;
buffer[2] = 0;
buffer[3] = 0;
}
b43_ntab_write_bulk(dev, B43_NTAB16(15, 88), 4,
buffer);
b43_ntab_read_bulk(dev, B43_NTAB16(15, 101), 2,
buffer);
b43_ntab_write_bulk(dev, B43_NTAB16(15, 85), 2,
buffer);
b43_ntab_write_bulk(dev, B43_NTAB16(15, 93), 2,
buffer);
length = 11;
if (dev->phy.rev < 3)
length -= 2;
b43_ntab_read_bulk(dev, B43_NTAB16(15, 96), length,
nphy->txiqlocal_bestc);
nphy->txiqlocal_coeffsvalid = true;
nphy->txiqlocal_chanspec.center_freq =
dev->phy.channel_freq;
nphy->txiqlocal_chanspec.channel_type =
dev->phy.channel_type;
} else {
length = 11;
if (dev->phy.rev < 3)
length -= 2;
b43_ntab_read_bulk(dev, B43_NTAB16(15, 96), length,
nphy->mphase_txcal_bestcoeffs);
}
b43_nphy_stop_playback(dev);
b43_phy_write(dev, B43_NPHY_IQLOCAL_CMDGCTL, 0);
}
b43_nphy_tx_cal_phy_cleanup(dev);
b43_ntab_write_bulk(dev, B43_NTAB16(7, 0x110), 2, save);
if (dev->phy.rev < 2 && (!mphase || nphy->mphase_cal_phase_id == last))
b43_nphy_tx_iq_workaround(dev);
if (dev->phy.rev >= 4)
nphy->hang_avoid = avoid;
b43_nphy_stay_in_carrier_search(dev, false);
return error;
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/ReapplyTxCalCoeffs */
static void b43_nphy_reapply_tx_cal_coeffs(struct b43_wldev *dev)
{
struct b43_phy_n *nphy = dev->phy.n;
u8 i;
u16 buffer[7];
bool equal = true;
if (!nphy->txiqlocal_coeffsvalid ||
nphy->txiqlocal_chanspec.center_freq != dev->phy.channel_freq ||
nphy->txiqlocal_chanspec.channel_type != dev->phy.channel_type)
return;
b43_ntab_read_bulk(dev, B43_NTAB16(15, 80), 7, buffer);
for (i = 0; i < 4; i++) {
if (buffer[i] != nphy->txiqlocal_bestc[i]) {
equal = false;
break;
}
}
if (!equal) {
b43_ntab_write_bulk(dev, B43_NTAB16(15, 80), 4,
nphy->txiqlocal_bestc);
for (i = 0; i < 4; i++)
buffer[i] = 0;
b43_ntab_write_bulk(dev, B43_NTAB16(15, 88), 4,
buffer);
b43_ntab_write_bulk(dev, B43_NTAB16(15, 85), 2,
&nphy->txiqlocal_bestc[5]);
b43_ntab_write_bulk(dev, B43_NTAB16(15, 93), 2,
&nphy->txiqlocal_bestc[5]);
}
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/CalRxIqRev2 */
static int b43_nphy_rev2_cal_rx_iq(struct b43_wldev *dev,
struct nphy_txgains target, u8 type, bool debug)
{
struct b43_phy_n *nphy = dev->phy.n;
int i, j, index;
u8 rfctl[2];
u8 afectl_core;
u16 tmp[6];
u16 uninitialized_var(cur_hpf1), uninitialized_var(cur_hpf2), cur_lna;
u32 real, imag;
enum ieee80211_band band;
u8 use;
u16 cur_hpf;
u16 lna[3] = { 3, 3, 1 };
u16 hpf1[3] = { 7, 2, 0 };
u16 hpf2[3] = { 2, 0, 0 };
u32 power[3] = { };
u16 gain_save[2];
u16 cal_gain[2];
struct nphy_iqcal_params cal_params[2];
struct nphy_iq_est est;
int ret = 0;
bool playtone = true;
int desired = 13;
b43_nphy_stay_in_carrier_search(dev, 1);
if (dev->phy.rev < 2)
b43_nphy_reapply_tx_cal_coeffs(dev);
b43_ntab_read_bulk(dev, B43_NTAB16(7, 0x110), 2, gain_save);
for (i = 0; i < 2; i++) {
b43_nphy_iq_cal_gain_params(dev, i, target, &cal_params[i]);
cal_gain[i] = cal_params[i].cal_gain;
}
b43_ntab_write_bulk(dev, B43_NTAB16(7, 0x110), 2, cal_gain);
for (i = 0; i < 2; i++) {
if (i == 0) {
rfctl[0] = B43_NPHY_RFCTL_INTC1;
rfctl[1] = B43_NPHY_RFCTL_INTC2;
afectl_core = B43_NPHY_AFECTL_C1;
} else {
rfctl[0] = B43_NPHY_RFCTL_INTC2;
rfctl[1] = B43_NPHY_RFCTL_INTC1;
afectl_core = B43_NPHY_AFECTL_C2;
}
tmp[1] = b43_phy_read(dev, B43_NPHY_RFSEQCA);
tmp[2] = b43_phy_read(dev, afectl_core);
tmp[3] = b43_phy_read(dev, B43_NPHY_AFECTL_OVER);
tmp[4] = b43_phy_read(dev, rfctl[0]);
tmp[5] = b43_phy_read(dev, rfctl[1]);
b43_phy_maskset(dev, B43_NPHY_RFSEQCA,
~B43_NPHY_RFSEQCA_RXDIS & 0xFFFF,
((1 - i) << B43_NPHY_RFSEQCA_RXDIS_SHIFT));
b43_phy_maskset(dev, B43_NPHY_RFSEQCA, ~B43_NPHY_RFSEQCA_TXEN,
(1 - i));
b43_phy_set(dev, afectl_core, 0x0006);
b43_phy_set(dev, B43_NPHY_AFECTL_OVER, 0x0006);
band = b43_current_band(dev->wl);
if (nphy->rxcalparams & 0xFF000000) {
if (band == IEEE80211_BAND_5GHZ)
b43_phy_write(dev, rfctl[0], 0x140);
else
b43_phy_write(dev, rfctl[0], 0x110);
} else {
if (band == IEEE80211_BAND_5GHZ)
b43_phy_write(dev, rfctl[0], 0x180);
else
b43_phy_write(dev, rfctl[0], 0x120);
}
if (band == IEEE80211_BAND_5GHZ)
b43_phy_write(dev, rfctl[1], 0x148);
else
b43_phy_write(dev, rfctl[1], 0x114);
if (nphy->rxcalparams & 0x10000) {
b43_radio_maskset(dev, B2055_C1_GENSPARE2, 0xFC,
(i + 1));
b43_radio_maskset(dev, B2055_C2_GENSPARE2, 0xFC,
(2 - i));
}
for (j = 0; j < 4; j++) {
if (j < 3) {
cur_lna = lna[j];
cur_hpf1 = hpf1[j];
cur_hpf2 = hpf2[j];
} else {
if (power[1] > 10000) {
use = 1;
cur_hpf = cur_hpf1;
index = 2;
} else {
if (power[0] > 10000) {
use = 1;
cur_hpf = cur_hpf1;
index = 1;
} else {
index = 0;
use = 2;
cur_hpf = cur_hpf2;
}
}
cur_lna = lna[index];
cur_hpf1 = hpf1[index];
cur_hpf2 = hpf2[index];
cur_hpf += desired - hweight32(power[index]);
cur_hpf = clamp_val(cur_hpf, 0, 10);
if (use == 1)
cur_hpf1 = cur_hpf;
else
cur_hpf2 = cur_hpf;
}
tmp[0] = ((cur_hpf2 << 8) | (cur_hpf1 << 4) |
(cur_lna << 2));
b43_nphy_rf_control_override(dev, 0x400, tmp[0], 3,
false);
b43_nphy_force_rf_sequence(dev, B43_RFSEQ_RESET2RX);
b43_nphy_stop_playback(dev);
if (playtone) {
ret = b43_nphy_tx_tone(dev, 4000,
(nphy->rxcalparams & 0xFFFF),
false, false);
playtone = false;
} else {
b43_nphy_run_samples(dev, 160, 0xFFFF, 0,
false, false);
}
if (ret == 0) {
if (j < 3) {
b43_nphy_rx_iq_est(dev, &est, 1024, 32,
false);
if (i == 0) {
real = est.i0_pwr;
imag = est.q0_pwr;
} else {
real = est.i1_pwr;
imag = est.q1_pwr;
}
power[i] = ((real + imag) / 1024) + 1;
} else {
b43_nphy_calc_rx_iq_comp(dev, 1 << i);
}
b43_nphy_stop_playback(dev);
}
if (ret != 0)
break;
}
b43_radio_mask(dev, B2055_C1_GENSPARE2, 0xFC);
b43_radio_mask(dev, B2055_C2_GENSPARE2, 0xFC);
b43_phy_write(dev, rfctl[1], tmp[5]);
b43_phy_write(dev, rfctl[0], tmp[4]);
b43_phy_write(dev, B43_NPHY_AFECTL_OVER, tmp[3]);
b43_phy_write(dev, afectl_core, tmp[2]);
b43_phy_write(dev, B43_NPHY_RFSEQCA, tmp[1]);
if (ret != 0)
break;
}
b43_nphy_rf_control_override(dev, 0x400, 0, 3, true);
b43_nphy_force_rf_sequence(dev, B43_RFSEQ_RESET2RX);
b43_ntab_write_bulk(dev, B43_NTAB16(7, 0x110), 2, gain_save);
b43_nphy_stay_in_carrier_search(dev, 0);
return ret;
}
static int b43_nphy_rev3_cal_rx_iq(struct b43_wldev *dev,
struct nphy_txgains target, u8 type, bool debug)
{
return -1;
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/CalRxIq */
static int b43_nphy_cal_rx_iq(struct b43_wldev *dev,
struct nphy_txgains target, u8 type, bool debug)
{
if (dev->phy.rev >= 3)
return b43_nphy_rev3_cal_rx_iq(dev, target, type, debug);
else
return b43_nphy_rev2_cal_rx_iq(dev, target, type, debug);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/RxCoreSetState */
static void b43_nphy_set_rx_core_state(struct b43_wldev *dev, u8 mask)
{
struct b43_phy *phy = &dev->phy;
struct b43_phy_n *nphy = phy->n;
/* u16 buf[16]; it's rev3+ */
nphy->phyrxchain = mask;
if (0 /* FIXME clk */)
return;
b43_mac_suspend(dev);
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, true);
b43_phy_maskset(dev, B43_NPHY_RFSEQCA, ~B43_NPHY_RFSEQCA_RXEN,
(mask & 0x3) << B43_NPHY_RFSEQCA_RXEN_SHIFT);
if ((mask & 0x3) != 0x3) {
b43_phy_write(dev, B43_NPHY_HPANT_SWTHRES, 1);
if (dev->phy.rev >= 3) {
/* TODO */
}
} else {
b43_phy_write(dev, B43_NPHY_HPANT_SWTHRES, 0x1E);
if (dev->phy.rev >= 3) {
/* TODO */
}
}
b43_nphy_force_rf_sequence(dev, B43_RFSEQ_RESET2RX);
if (nphy->hang_avoid)
b43_nphy_stay_in_carrier_search(dev, false);
b43_mac_enable(dev);
}
/**************************************************
* N-PHY init
**************************************************/
/*
* Upload the N-PHY tables.
* http://bcm-v4.sipsolutions.net/802.11/PHY/N/InitTables
*/
static void b43_nphy_tables_init(struct b43_wldev *dev)
{
if (dev->phy.rev < 3)
b43_nphy_rev0_1_2_tables_init(dev);
else
b43_nphy_rev3plus_tables_init(dev);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/MIMOConfig */
static void b43_nphy_update_mimo_config(struct b43_wldev *dev, s32 preamble)
{
u16 mimocfg = b43_phy_read(dev, B43_NPHY_MIMOCFG);
mimocfg |= B43_NPHY_MIMOCFG_AUTO;
if (preamble == 1)
mimocfg |= B43_NPHY_MIMOCFG_GFMIX;
else
mimocfg &= ~B43_NPHY_MIMOCFG_GFMIX;
b43_phy_write(dev, B43_NPHY_MIMOCFG, mimocfg);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/BPHYInit */
static void b43_nphy_bphy_init(struct b43_wldev *dev)
{
unsigned int i;
u16 val;
val = 0x1E1F;
for (i = 0; i < 16; i++) {
b43_phy_write(dev, B43_PHY_N_BMODE(0x88 + i), val);
val -= 0x202;
}
val = 0x3E3F;
for (i = 0; i < 16; i++) {
b43_phy_write(dev, B43_PHY_N_BMODE(0x98 + i), val);
val -= 0x202;
}
b43_phy_write(dev, B43_PHY_N_BMODE(0x38), 0x668);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/SuperSwitchInit */
static void b43_nphy_superswitch_init(struct b43_wldev *dev, bool init)
{
if (dev->phy.rev >= 3) {
if (!init)
return;
if (0 /* FIXME */) {
b43_ntab_write(dev, B43_NTAB16(9, 2), 0x211);
b43_ntab_write(dev, B43_NTAB16(9, 3), 0x222);
b43_ntab_write(dev, B43_NTAB16(9, 8), 0x144);
b43_ntab_write(dev, B43_NTAB16(9, 12), 0x188);
}
} else {
b43_phy_write(dev, B43_NPHY_GPIO_LOOEN, 0);
b43_phy_write(dev, B43_NPHY_GPIO_HIOEN, 0);
switch (dev->dev->bus_type) {
#ifdef CONFIG_B43_BCMA
case B43_BUS_BCMA:
bcma_chipco_gpio_control(&dev->dev->bdev->bus->drv_cc,
0xFC00, 0xFC00);
break;
#endif
#ifdef CONFIG_B43_SSB
case B43_BUS_SSB:
ssb_chipco_gpio_control(&dev->dev->sdev->bus->chipco,
0xFC00, 0xFC00);
break;
#endif
}
b43_maskset32(dev, B43_MMIO_MACCTL, ~B43_MACCTL_GPOUTSMSK, 0);
b43_maskset16(dev, B43_MMIO_GPIO_MASK, ~0, 0xFC00);
b43_maskset16(dev, B43_MMIO_GPIO_CONTROL, (~0xFC00 & 0xFFFF),
0);
if (init) {
b43_phy_write(dev, B43_NPHY_RFCTL_LUT_TRSW_LO1, 0x2D8);
b43_phy_write(dev, B43_NPHY_RFCTL_LUT_TRSW_UP1, 0x301);
b43_phy_write(dev, B43_NPHY_RFCTL_LUT_TRSW_LO2, 0x2D8);
b43_phy_write(dev, B43_NPHY_RFCTL_LUT_TRSW_UP2, 0x301);
}
}
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/Init/N */
int b43_phy_initn(struct b43_wldev *dev)
{
struct ssb_sprom *sprom = dev->dev->bus_sprom;
struct b43_phy *phy = &dev->phy;
struct b43_phy_n *nphy = phy->n;
u8 tx_pwr_state;
struct nphy_txgains target;
u16 tmp;
enum ieee80211_band tmp2;
bool do_rssi_cal;
u16 clip[2];
bool do_cal = false;
if ((dev->phy.rev >= 3) &&
(sprom->boardflags_lo & B43_BFL_EXTLNA) &&
(b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ)) {
switch (dev->dev->bus_type) {
#ifdef CONFIG_B43_BCMA
case B43_BUS_BCMA:
bcma_cc_set32(&dev->dev->bdev->bus->drv_cc,
BCMA_CC_CHIPCTL, 0x40);
break;
#endif
#ifdef CONFIG_B43_SSB
case B43_BUS_SSB:
chipco_set32(&dev->dev->sdev->bus->chipco,
SSB_CHIPCO_CHIPCTL, 0x40);
break;
#endif
}
}
nphy->deaf_count = 0;
b43_nphy_tables_init(dev);
nphy->crsminpwr_adjusted = false;
nphy->noisevars_adjusted = false;
/* Clear all overrides */
if (dev->phy.rev >= 3) {
b43_phy_write(dev, B43_NPHY_TXF_40CO_B1S1, 0);
b43_phy_write(dev, B43_NPHY_RFCTL_OVER, 0);
b43_phy_write(dev, B43_NPHY_TXF_40CO_B1S0, 0);
b43_phy_write(dev, B43_NPHY_TXF_40CO_B32S1, 0);
} else {
b43_phy_write(dev, B43_NPHY_RFCTL_OVER, 0);
}
b43_phy_write(dev, B43_NPHY_RFCTL_INTC1, 0);
b43_phy_write(dev, B43_NPHY_RFCTL_INTC2, 0);
if (dev->phy.rev < 6) {
b43_phy_write(dev, B43_NPHY_RFCTL_INTC3, 0);
b43_phy_write(dev, B43_NPHY_RFCTL_INTC4, 0);
}
b43_phy_mask(dev, B43_NPHY_RFSEQMODE,
~(B43_NPHY_RFSEQMODE_CAOVER |
B43_NPHY_RFSEQMODE_TROVER));
if (dev->phy.rev >= 3)
b43_phy_write(dev, B43_NPHY_AFECTL_OVER1, 0);
b43_phy_write(dev, B43_NPHY_AFECTL_OVER, 0);
if (dev->phy.rev <= 2) {
tmp = (dev->phy.rev == 2) ? 0x3B : 0x40;
b43_phy_maskset(dev, B43_NPHY_BPHY_CTL3,
~B43_NPHY_BPHY_CTL3_SCALE,
tmp << B43_NPHY_BPHY_CTL3_SCALE_SHIFT);
}
b43_phy_write(dev, B43_NPHY_AFESEQ_TX2RX_PUD_20M, 0x20);
b43_phy_write(dev, B43_NPHY_AFESEQ_TX2RX_PUD_40M, 0x20);
if (sprom->boardflags2_lo & B43_BFL2_SKWRKFEM_BRD ||
(dev->dev->board_vendor == PCI_VENDOR_ID_APPLE &&
dev->dev->board_type == 0x8B))
b43_phy_write(dev, B43_NPHY_TXREALFD, 0xA0);
else
b43_phy_write(dev, B43_NPHY_TXREALFD, 0xB8);
b43_phy_write(dev, B43_NPHY_MIMO_CRSTXEXT, 0xC8);
b43_phy_write(dev, B43_NPHY_PLOAD_CSENSE_EXTLEN, 0x50);
b43_phy_write(dev, B43_NPHY_TXRIFS_FRDEL, 0x30);
b43_nphy_update_mimo_config(dev, nphy->preamble_override);
b43_nphy_update_txrx_chain(dev);
if (phy->rev < 2) {
b43_phy_write(dev, B43_NPHY_DUP40_GFBL, 0xAA8);
b43_phy_write(dev, B43_NPHY_DUP40_BL, 0x9A4);
}
tmp2 = b43_current_band(dev->wl);
if (b43_nphy_ipa(dev)) {
b43_phy_set(dev, B43_NPHY_PAPD_EN0, 0x1);
b43_phy_maskset(dev, B43_NPHY_EPS_TABLE_ADJ0, 0x007F,
nphy->papd_epsilon_offset[0] << 7);
b43_phy_set(dev, B43_NPHY_PAPD_EN1, 0x1);
b43_phy_maskset(dev, B43_NPHY_EPS_TABLE_ADJ1, 0x007F,
nphy->papd_epsilon_offset[1] << 7);
b43_nphy_int_pa_set_tx_dig_filters(dev);
} else if (phy->rev >= 5) {
b43_nphy_ext_pa_set_tx_dig_filters(dev);
}
b43_nphy_workarounds(dev);
/* Reset CCA, in init code it differs a little from standard way */
b43_phy_force_clock(dev, 1);
tmp = b43_phy_read(dev, B43_NPHY_BBCFG);
b43_phy_write(dev, B43_NPHY_BBCFG, tmp | B43_NPHY_BBCFG_RSTCCA);
b43_phy_write(dev, B43_NPHY_BBCFG, tmp & ~B43_NPHY_BBCFG_RSTCCA);
b43_phy_force_clock(dev, 0);
b43_mac_phy_clock_set(dev, true);
b43_nphy_pa_override(dev, false);
b43_nphy_force_rf_sequence(dev, B43_RFSEQ_RX2TX);
b43_nphy_force_rf_sequence(dev, B43_RFSEQ_RESET2RX);
b43_nphy_pa_override(dev, true);
b43_nphy_classifier(dev, 0, 0);
b43_nphy_read_clip_detection(dev, clip);
if (b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ)
b43_nphy_bphy_init(dev);
tx_pwr_state = nphy->txpwrctrl;
b43_nphy_tx_power_ctrl(dev, false);
b43_nphy_tx_power_fix(dev);
b43_nphy_tx_power_ctl_idle_tssi(dev);
b43_nphy_tx_power_ctl_setup(dev);
b43_nphy_tx_gain_table_upload(dev);
if (nphy->phyrxchain != 3)
b43_nphy_set_rx_core_state(dev, nphy->phyrxchain);
if (nphy->mphase_cal_phase_id > 0)
;/* TODO PHY Periodic Calibration Multi-Phase Restart */
do_rssi_cal = false;
if (phy->rev >= 3) {
if (b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ)
do_rssi_cal = !nphy->rssical_chanspec_2G.center_freq;
else
do_rssi_cal = !nphy->rssical_chanspec_5G.center_freq;
if (do_rssi_cal)
b43_nphy_rssi_cal(dev);
else
b43_nphy_restore_rssi_cal(dev);
} else {
b43_nphy_rssi_cal(dev);
}
if (!((nphy->measure_hold & 0x6) != 0)) {
if (b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ)
do_cal = !nphy->iqcal_chanspec_2G.center_freq;
else
do_cal = !nphy->iqcal_chanspec_5G.center_freq;
if (nphy->mute)
do_cal = false;
if (do_cal) {
target = b43_nphy_get_tx_gains(dev);
if (nphy->antsel_type == 2)
b43_nphy_superswitch_init(dev, true);
if (nphy->perical != 2) {
b43_nphy_rssi_cal(dev);
if (phy->rev >= 3) {
nphy->cal_orig_pwr_idx[0] =
nphy->txpwrindex[0].index_internal;
nphy->cal_orig_pwr_idx[1] =
nphy->txpwrindex[1].index_internal;
/* TODO N PHY Pre Calibrate TX Gain */
target = b43_nphy_get_tx_gains(dev);
}
if (!b43_nphy_cal_tx_iq_lo(dev, target, true, false))
if (b43_nphy_cal_rx_iq(dev, target, 2, 0) == 0)
b43_nphy_save_cal(dev);
} else if (nphy->mphase_cal_phase_id == 0)
;/* N PHY Periodic Calibration with arg 3 */
} else {
b43_nphy_restore_cal(dev);
}
}
b43_nphy_tx_pwr_ctrl_coef_setup(dev);
b43_nphy_tx_power_ctrl(dev, tx_pwr_state);
b43_phy_write(dev, B43_NPHY_TXMACIF_HOLDOFF, 0x0015);
b43_phy_write(dev, B43_NPHY_TXMACDELAY, 0x0320);
if (phy->rev >= 3 && phy->rev <= 6)
b43_phy_write(dev, B43_NPHY_PLOAD_CSENSE_EXTLEN, 0x0014);
b43_nphy_tx_lp_fbw(dev);
if (phy->rev >= 3)
b43_nphy_spur_workaround(dev);
return 0;
}
/**************************************************
* Channel switching ops.
**************************************************/
static void b43_chantab_phy_upload(struct b43_wldev *dev,
const struct b43_phy_n_sfo_cfg *e)
{
b43_phy_write(dev, B43_NPHY_BW1A, e->phy_bw1a);
b43_phy_write(dev, B43_NPHY_BW2, e->phy_bw2);
b43_phy_write(dev, B43_NPHY_BW3, e->phy_bw3);
b43_phy_write(dev, B43_NPHY_BW4, e->phy_bw4);
b43_phy_write(dev, B43_NPHY_BW5, e->phy_bw5);
b43_phy_write(dev, B43_NPHY_BW6, e->phy_bw6);
}
/* http://bcm-v4.sipsolutions.net/802.11/PmuSpurAvoid */
static void b43_nphy_pmu_spur_avoid(struct b43_wldev *dev, bool avoid)
{
struct bcma_drv_cc __maybe_unused *cc;
u32 __maybe_unused pmu_ctl;
switch (dev->dev->bus_type) {
#ifdef CONFIG_B43_BCMA
case B43_BUS_BCMA:
cc = &dev->dev->bdev->bus->drv_cc;
if (dev->dev->chip_id == 43224 || dev->dev->chip_id == 43225) {
if (avoid) {
bcma_chipco_pll_write(cc, 0x0, 0x11500010);
bcma_chipco_pll_write(cc, 0x1, 0x000C0C06);
bcma_chipco_pll_write(cc, 0x2, 0x0F600a08);
bcma_chipco_pll_write(cc, 0x3, 0x00000000);
bcma_chipco_pll_write(cc, 0x4, 0x2001E920);
bcma_chipco_pll_write(cc, 0x5, 0x88888815);
} else {
bcma_chipco_pll_write(cc, 0x0, 0x11100010);
bcma_chipco_pll_write(cc, 0x1, 0x000c0c06);
bcma_chipco_pll_write(cc, 0x2, 0x03000a08);
bcma_chipco_pll_write(cc, 0x3, 0x00000000);
bcma_chipco_pll_write(cc, 0x4, 0x200005c0);
bcma_chipco_pll_write(cc, 0x5, 0x88888815);
}
pmu_ctl = BCMA_CC_PMU_CTL_PLL_UPD;
} else if (dev->dev->chip_id == 0x4716) {
if (avoid) {
bcma_chipco_pll_write(cc, 0x0, 0x11500060);
bcma_chipco_pll_write(cc, 0x1, 0x080C0C06);
bcma_chipco_pll_write(cc, 0x2, 0x0F600000);
bcma_chipco_pll_write(cc, 0x3, 0x00000000);
bcma_chipco_pll_write(cc, 0x4, 0x2001E924);
bcma_chipco_pll_write(cc, 0x5, 0x88888815);
} else {
bcma_chipco_pll_write(cc, 0x0, 0x11100060);
bcma_chipco_pll_write(cc, 0x1, 0x080c0c06);
bcma_chipco_pll_write(cc, 0x2, 0x03000000);
bcma_chipco_pll_write(cc, 0x3, 0x00000000);
bcma_chipco_pll_write(cc, 0x4, 0x200005c0);
bcma_chipco_pll_write(cc, 0x5, 0x88888815);
}
pmu_ctl = BCMA_CC_PMU_CTL_PLL_UPD |
BCMA_CC_PMU_CTL_NOILPONW;
} else if (dev->dev->chip_id == 0x4322 ||
dev->dev->chip_id == 0x4340 ||
dev->dev->chip_id == 0x4341) {
bcma_chipco_pll_write(cc, 0x0, 0x11100070);
bcma_chipco_pll_write(cc, 0x1, 0x1014140a);
bcma_chipco_pll_write(cc, 0x5, 0x88888854);
if (avoid)
bcma_chipco_pll_write(cc, 0x2, 0x05201828);
else
bcma_chipco_pll_write(cc, 0x2, 0x05001828);
pmu_ctl = BCMA_CC_PMU_CTL_PLL_UPD;
} else {
return;
}
bcma_cc_set32(cc, BCMA_CC_PMU_CTL, pmu_ctl);
break;
#endif
#ifdef CONFIG_B43_SSB
case B43_BUS_SSB:
/* FIXME */
break;
#endif
}
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/ChanspecSetup */
static void b43_nphy_channel_setup(struct b43_wldev *dev,
const struct b43_phy_n_sfo_cfg *e,
struct ieee80211_channel *new_channel)
{
struct b43_phy *phy = &dev->phy;
struct b43_phy_n *nphy = dev->phy.n;
int ch = new_channel->hw_value;
u16 old_band_5ghz;
u32 tmp32;
old_band_5ghz =
b43_phy_read(dev, B43_NPHY_BANDCTL) & B43_NPHY_BANDCTL_5GHZ;
if (new_channel->band == IEEE80211_BAND_5GHZ && !old_band_5ghz) {
tmp32 = b43_read32(dev, B43_MMIO_PSM_PHY_HDR);
b43_write32(dev, B43_MMIO_PSM_PHY_HDR, tmp32 | 4);
b43_phy_set(dev, B43_PHY_B_BBCFG, 0xC000);
b43_write32(dev, B43_MMIO_PSM_PHY_HDR, tmp32);
b43_phy_set(dev, B43_NPHY_BANDCTL, B43_NPHY_BANDCTL_5GHZ);
} else if (new_channel->band == IEEE80211_BAND_2GHZ && old_band_5ghz) {
b43_phy_mask(dev, B43_NPHY_BANDCTL, ~B43_NPHY_BANDCTL_5GHZ);
tmp32 = b43_read32(dev, B43_MMIO_PSM_PHY_HDR);
b43_write32(dev, B43_MMIO_PSM_PHY_HDR, tmp32 | 4);
b43_phy_mask(dev, B43_PHY_B_BBCFG, 0x3FFF);
b43_write32(dev, B43_MMIO_PSM_PHY_HDR, tmp32);
}
b43_chantab_phy_upload(dev, e);
if (new_channel->hw_value == 14) {
b43_nphy_classifier(dev, 2, 0);
b43_phy_set(dev, B43_PHY_B_TEST, 0x0800);
} else {
b43_nphy_classifier(dev, 2, 2);
if (new_channel->band == IEEE80211_BAND_2GHZ)
b43_phy_mask(dev, B43_PHY_B_TEST, ~0x840);
}
if (!nphy->txpwrctrl)
b43_nphy_tx_power_fix(dev);
if (dev->phy.rev < 3)
b43_nphy_adjust_lna_gain_table(dev);
b43_nphy_tx_lp_fbw(dev);
if (dev->phy.rev >= 3 &&
dev->phy.n->spur_avoid != B43_SPUR_AVOID_DISABLE) {
bool avoid = false;
if (dev->phy.n->spur_avoid == B43_SPUR_AVOID_FORCE) {
avoid = true;
} else if (!b43_channel_type_is_40mhz(phy->channel_type)) {
if ((ch >= 5 && ch <= 8) || ch == 13 || ch == 14)
avoid = true;
} else { /* 40MHz */
if (nphy->aband_spurwar_en &&
(ch == 38 || ch == 102 || ch == 118))
avoid = dev->dev->chip_id == 0x4716;
}
b43_nphy_pmu_spur_avoid(dev, avoid);
if (dev->dev->chip_id == 43222 || dev->dev->chip_id == 43224 ||
dev->dev->chip_id == 43225) {
b43_write16(dev, B43_MMIO_TSF_CLK_FRAC_LOW,
avoid ? 0x5341 : 0x8889);
b43_write16(dev, B43_MMIO_TSF_CLK_FRAC_HIGH, 0x8);
}
if (dev->phy.rev == 3 || dev->phy.rev == 4)
; /* TODO: reset PLL */
if (avoid)
b43_phy_set(dev, B43_NPHY_BBCFG, B43_NPHY_BBCFG_RSTRX);
else
b43_phy_mask(dev, B43_NPHY_BBCFG,
~B43_NPHY_BBCFG_RSTRX & 0xFFFF);
b43_nphy_reset_cca(dev);
/* wl sets useless phy_isspuravoid here */
}
b43_phy_write(dev, B43_NPHY_NDATAT_DUP40, 0x3830);
if (phy->rev >= 3)
b43_nphy_spur_workaround(dev);
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/SetChanspec */
static int b43_nphy_set_channel(struct b43_wldev *dev,
struct ieee80211_channel *channel,
enum nl80211_channel_type channel_type)
{
struct b43_phy *phy = &dev->phy;
const struct b43_nphy_channeltab_entry_rev2 *tabent_r2 = NULL;
const struct b43_nphy_channeltab_entry_rev3 *tabent_r3 = NULL;
u8 tmp;
if (dev->phy.rev >= 3) {
tabent_r3 = b43_nphy_get_chantabent_rev3(dev,
channel->center_freq);
if (!tabent_r3)
return -ESRCH;
} else {
tabent_r2 = b43_nphy_get_chantabent_rev2(dev,
channel->hw_value);
if (!tabent_r2)
return -ESRCH;
}
/* Channel is set later in common code, but we need to set it on our
own to let this function's subcalls work properly. */
phy->channel = channel->hw_value;
phy->channel_freq = channel->center_freq;
if (b43_channel_type_is_40mhz(phy->channel_type) !=
b43_channel_type_is_40mhz(channel_type))
; /* TODO: BMAC BW Set (channel_type) */
if (channel_type == NL80211_CHAN_HT40PLUS)
b43_phy_set(dev, B43_NPHY_RXCTL,
B43_NPHY_RXCTL_BSELU20);
else if (channel_type == NL80211_CHAN_HT40MINUS)
b43_phy_mask(dev, B43_NPHY_RXCTL,
~B43_NPHY_RXCTL_BSELU20);
if (dev->phy.rev >= 3) {
tmp = (channel->band == IEEE80211_BAND_5GHZ) ? 4 : 0;
b43_radio_maskset(dev, 0x08, 0xFFFB, tmp);
b43_radio_2056_setup(dev, tabent_r3);
b43_nphy_channel_setup(dev, &(tabent_r3->phy_regs), channel);
} else {
tmp = (channel->band == IEEE80211_BAND_5GHZ) ? 0x0020 : 0x0050;
b43_radio_maskset(dev, B2055_MASTER1, 0xFF8F, tmp);
b43_radio_2055_setup(dev, tabent_r2);
b43_nphy_channel_setup(dev, &(tabent_r2->phy_regs), channel);
}
return 0;
}
/**************************************************
* Basic PHY ops.
**************************************************/
static int b43_nphy_op_allocate(struct b43_wldev *dev)
{
struct b43_phy_n *nphy;
nphy = kzalloc(sizeof(*nphy), GFP_KERNEL);
if (!nphy)
return -ENOMEM;
dev->phy.n = nphy;
return 0;
}
static void b43_nphy_op_prepare_structs(struct b43_wldev *dev)
{
struct b43_phy *phy = &dev->phy;
struct b43_phy_n *nphy = phy->n;
struct ssb_sprom *sprom = dev->dev->bus_sprom;
memset(nphy, 0, sizeof(*nphy));
nphy->hang_avoid = (phy->rev == 3 || phy->rev == 4);
nphy->spur_avoid = (phy->rev >= 3) ?
B43_SPUR_AVOID_AUTO : B43_SPUR_AVOID_DISABLE;
nphy->gain_boost = true; /* this way we follow wl, assume it is true */
nphy->txrx_chain = 2; /* sth different than 0 and 1 for now */
nphy->phyrxchain = 3; /* to avoid b43_nphy_set_rx_core_state like wl */
nphy->perical = 2; /* avoid additional rssi cal on init (like wl) */
/* 128 can mean disabled-by-default state of TX pwr ctl. Max value is
* 0x7f == 127 and we check for 128 when restoring TX pwr ctl. */
nphy->tx_pwr_idx[0] = 128;
nphy->tx_pwr_idx[1] = 128;
/* Hardware TX power control and 5GHz power gain */
nphy->txpwrctrl = false;
nphy->pwg_gain_5ghz = false;
if (dev->phy.rev >= 3 ||
(dev->dev->board_vendor == PCI_VENDOR_ID_APPLE &&
(dev->dev->core_rev == 11 || dev->dev->core_rev == 12))) {
nphy->txpwrctrl = true;
nphy->pwg_gain_5ghz = true;
} else if (sprom->revision >= 4) {
if (dev->phy.rev >= 2 &&
(sprom->boardflags2_lo & B43_BFL2_TXPWRCTRL_EN)) {
nphy->txpwrctrl = true;
#ifdef CONFIG_B43_SSB
if (dev->dev->bus_type == B43_BUS_SSB &&
dev->dev->sdev->bus->bustype == SSB_BUSTYPE_PCI) {
struct pci_dev *pdev =
dev->dev->sdev->bus->host_pci;
if (pdev->device == 0x4328 ||
pdev->device == 0x432a)
nphy->pwg_gain_5ghz = true;
}
#endif
} else if (sprom->boardflags2_lo & B43_BFL2_5G_PWRGAIN) {
nphy->pwg_gain_5ghz = true;
}
}
if (dev->phy.rev >= 3) {
nphy->ipa2g_on = sprom->fem.ghz2.extpa_gain == 2;
nphy->ipa5g_on = sprom->fem.ghz5.extpa_gain == 2;
}
}
static void b43_nphy_op_free(struct b43_wldev *dev)
{
struct b43_phy *phy = &dev->phy;
struct b43_phy_n *nphy = phy->n;
kfree(nphy);
phy->n = NULL;
}
static int b43_nphy_op_init(struct b43_wldev *dev)
{
return b43_phy_initn(dev);
}
static inline void check_phyreg(struct b43_wldev *dev, u16 offset)
{
#if B43_DEBUG
if ((offset & B43_PHYROUTE) == B43_PHYROUTE_OFDM_GPHY) {
/* OFDM registers are onnly available on A/G-PHYs */
b43err(dev->wl, "Invalid OFDM PHY access at "
"0x%04X on N-PHY\n", offset);
dump_stack();
}
if ((offset & B43_PHYROUTE) == B43_PHYROUTE_EXT_GPHY) {
/* Ext-G registers are only available on G-PHYs */
b43err(dev->wl, "Invalid EXT-G PHY access at "
"0x%04X on N-PHY\n", offset);
dump_stack();
}
#endif /* B43_DEBUG */
}
static u16 b43_nphy_op_read(struct b43_wldev *dev, u16 reg)
{
check_phyreg(dev, reg);
b43_write16(dev, B43_MMIO_PHY_CONTROL, reg);
return b43_read16(dev, B43_MMIO_PHY_DATA);
}
static void b43_nphy_op_write(struct b43_wldev *dev, u16 reg, u16 value)
{
check_phyreg(dev, reg);
b43_write16(dev, B43_MMIO_PHY_CONTROL, reg);
b43_write16(dev, B43_MMIO_PHY_DATA, value);
}
static void b43_nphy_op_maskset(struct b43_wldev *dev, u16 reg, u16 mask,
u16 set)
{
check_phyreg(dev, reg);
b43_write16(dev, B43_MMIO_PHY_CONTROL, reg);
b43_maskset16(dev, B43_MMIO_PHY_DATA, mask, set);
}
static u16 b43_nphy_op_radio_read(struct b43_wldev *dev, u16 reg)
{
/* Register 1 is a 32-bit register. */
B43_WARN_ON(reg == 1);
/* N-PHY needs 0x100 for read access */
reg |= 0x100;
b43_write16(dev, B43_MMIO_RADIO_CONTROL, reg);
return b43_read16(dev, B43_MMIO_RADIO_DATA_LOW);
}
static void b43_nphy_op_radio_write(struct b43_wldev *dev, u16 reg, u16 value)
{
/* Register 1 is a 32-bit register. */
B43_WARN_ON(reg == 1);
b43_write16(dev, B43_MMIO_RADIO_CONTROL, reg);
b43_write16(dev, B43_MMIO_RADIO_DATA_LOW, value);
}
/* http://bcm-v4.sipsolutions.net/802.11/Radio/Switch%20Radio */
static void b43_nphy_op_software_rfkill(struct b43_wldev *dev,
bool blocked)
{
if (b43_read32(dev, B43_MMIO_MACCTL) & B43_MACCTL_ENABLED)
b43err(dev->wl, "MAC not suspended\n");
if (blocked) {
b43_phy_mask(dev, B43_NPHY_RFCTL_CMD,
~B43_NPHY_RFCTL_CMD_CHIP0PU);
if (dev->phy.rev >= 3) {
b43_radio_mask(dev, 0x09, ~0x2);
b43_radio_write(dev, 0x204D, 0);
b43_radio_write(dev, 0x2053, 0);
b43_radio_write(dev, 0x2058, 0);
b43_radio_write(dev, 0x205E, 0);
b43_radio_mask(dev, 0x2062, ~0xF0);
b43_radio_write(dev, 0x2064, 0);
b43_radio_write(dev, 0x304D, 0);
b43_radio_write(dev, 0x3053, 0);
b43_radio_write(dev, 0x3058, 0);
b43_radio_write(dev, 0x305E, 0);
b43_radio_mask(dev, 0x3062, ~0xF0);
b43_radio_write(dev, 0x3064, 0);
}
} else {
if (dev->phy.rev >= 3) {
b43_radio_init2056(dev);
b43_switch_channel(dev, dev->phy.channel);
} else {
b43_radio_init2055(dev);
}
}
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/Anacore */
static void b43_nphy_op_switch_analog(struct b43_wldev *dev, bool on)
{
u16 override = on ? 0x0 : 0x7FFF;
u16 core = on ? 0xD : 0x00FD;
if (dev->phy.rev >= 3) {
if (on) {
b43_phy_write(dev, B43_NPHY_AFECTL_C1, core);
b43_phy_write(dev, B43_NPHY_AFECTL_OVER1, override);
b43_phy_write(dev, B43_NPHY_AFECTL_C2, core);
b43_phy_write(dev, B43_NPHY_AFECTL_OVER, override);
} else {
b43_phy_write(dev, B43_NPHY_AFECTL_OVER1, override);
b43_phy_write(dev, B43_NPHY_AFECTL_C1, core);
b43_phy_write(dev, B43_NPHY_AFECTL_OVER, override);
b43_phy_write(dev, B43_NPHY_AFECTL_C2, core);
}
} else {
b43_phy_write(dev, B43_NPHY_AFECTL_OVER, override);
}
}
static int b43_nphy_op_switch_channel(struct b43_wldev *dev,
unsigned int new_channel)
{
struct ieee80211_channel *channel = dev->wl->hw->conf.channel;
enum nl80211_channel_type channel_type = dev->wl->hw->conf.channel_type;
if (b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ) {
if ((new_channel < 1) || (new_channel > 14))
return -EINVAL;
} else {
if (new_channel > 200)
return -EINVAL;
}
return b43_nphy_set_channel(dev, channel, channel_type);
}
static unsigned int b43_nphy_op_get_default_chan(struct b43_wldev *dev)
{
if (b43_current_band(dev->wl) == IEEE80211_BAND_2GHZ)
return 1;
return 36;
}
const struct b43_phy_operations b43_phyops_n = {
.allocate = b43_nphy_op_allocate,
.free = b43_nphy_op_free,
.prepare_structs = b43_nphy_op_prepare_structs,
.init = b43_nphy_op_init,
.phy_read = b43_nphy_op_read,
.phy_write = b43_nphy_op_write,
.phy_maskset = b43_nphy_op_maskset,
.radio_read = b43_nphy_op_radio_read,
.radio_write = b43_nphy_op_radio_write,
.software_rfkill = b43_nphy_op_software_rfkill,
.switch_analog = b43_nphy_op_switch_analog,
.switch_channel = b43_nphy_op_switch_channel,
.get_default_chan = b43_nphy_op_get_default_chan,
.recalc_txpower = b43_nphy_op_recalc_txpower,
.adjust_txpower = b43_nphy_op_adjust_txpower,
};
| gpl-2.0 |
1nv4d3r5/linux | drivers/power/smb347-charger.c | 3379 | 32450 | /*
* Summit Microelectronics SMB347 Battery Charger Driver
*
* Copyright (C) 2011, Intel Corporation
*
* Authors: Bruce E. Robertson <bruce.e.robertson@intel.com>
* Mika Westerberg <mika.westerberg@linux.intel.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/err.h>
#include <linux/gpio.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/i2c.h>
#include <linux/mutex.h>
#include <linux/power_supply.h>
#include <linux/power/smb347-charger.h>
#include <linux/regmap.h>
/*
* Configuration registers. These are mirrored to volatile RAM and can be
* written once %CMD_A_ALLOW_WRITE is set in %CMD_A register. They will be
* reloaded from non-volatile registers after POR.
*/
#define CFG_CHARGE_CURRENT 0x00
#define CFG_CHARGE_CURRENT_FCC_MASK 0xe0
#define CFG_CHARGE_CURRENT_FCC_SHIFT 5
#define CFG_CHARGE_CURRENT_PCC_MASK 0x18
#define CFG_CHARGE_CURRENT_PCC_SHIFT 3
#define CFG_CHARGE_CURRENT_TC_MASK 0x07
#define CFG_CURRENT_LIMIT 0x01
#define CFG_CURRENT_LIMIT_DC_MASK 0xf0
#define CFG_CURRENT_LIMIT_DC_SHIFT 4
#define CFG_CURRENT_LIMIT_USB_MASK 0x0f
#define CFG_FLOAT_VOLTAGE 0x03
#define CFG_FLOAT_VOLTAGE_FLOAT_MASK 0x3f
#define CFG_FLOAT_VOLTAGE_THRESHOLD_MASK 0xc0
#define CFG_FLOAT_VOLTAGE_THRESHOLD_SHIFT 6
#define CFG_STAT 0x05
#define CFG_STAT_DISABLED BIT(5)
#define CFG_STAT_ACTIVE_HIGH BIT(7)
#define CFG_PIN 0x06
#define CFG_PIN_EN_CTRL_MASK 0x60
#define CFG_PIN_EN_CTRL_ACTIVE_HIGH 0x40
#define CFG_PIN_EN_CTRL_ACTIVE_LOW 0x60
#define CFG_PIN_EN_APSD_IRQ BIT(1)
#define CFG_PIN_EN_CHARGER_ERROR BIT(2)
#define CFG_THERM 0x07
#define CFG_THERM_SOFT_HOT_COMPENSATION_MASK 0x03
#define CFG_THERM_SOFT_HOT_COMPENSATION_SHIFT 0
#define CFG_THERM_SOFT_COLD_COMPENSATION_MASK 0x0c
#define CFG_THERM_SOFT_COLD_COMPENSATION_SHIFT 2
#define CFG_THERM_MONITOR_DISABLED BIT(4)
#define CFG_SYSOK 0x08
#define CFG_SYSOK_SUSPEND_HARD_LIMIT_DISABLED BIT(2)
#define CFG_OTHER 0x09
#define CFG_OTHER_RID_MASK 0xc0
#define CFG_OTHER_RID_ENABLED_AUTO_OTG 0xc0
#define CFG_OTG 0x0a
#define CFG_OTG_TEMP_THRESHOLD_MASK 0x30
#define CFG_OTG_TEMP_THRESHOLD_SHIFT 4
#define CFG_OTG_CC_COMPENSATION_MASK 0xc0
#define CFG_OTG_CC_COMPENSATION_SHIFT 6
#define CFG_TEMP_LIMIT 0x0b
#define CFG_TEMP_LIMIT_SOFT_HOT_MASK 0x03
#define CFG_TEMP_LIMIT_SOFT_HOT_SHIFT 0
#define CFG_TEMP_LIMIT_SOFT_COLD_MASK 0x0c
#define CFG_TEMP_LIMIT_SOFT_COLD_SHIFT 2
#define CFG_TEMP_LIMIT_HARD_HOT_MASK 0x30
#define CFG_TEMP_LIMIT_HARD_HOT_SHIFT 4
#define CFG_TEMP_LIMIT_HARD_COLD_MASK 0xc0
#define CFG_TEMP_LIMIT_HARD_COLD_SHIFT 6
#define CFG_FAULT_IRQ 0x0c
#define CFG_FAULT_IRQ_DCIN_UV BIT(2)
#define CFG_STATUS_IRQ 0x0d
#define CFG_STATUS_IRQ_TERMINATION_OR_TAPER BIT(4)
#define CFG_STATUS_IRQ_CHARGE_TIMEOUT BIT(7)
#define CFG_ADDRESS 0x0e
/* Command registers */
#define CMD_A 0x30
#define CMD_A_CHG_ENABLED BIT(1)
#define CMD_A_SUSPEND_ENABLED BIT(2)
#define CMD_A_ALLOW_WRITE BIT(7)
#define CMD_B 0x31
#define CMD_C 0x33
/* Interrupt Status registers */
#define IRQSTAT_A 0x35
#define IRQSTAT_C 0x37
#define IRQSTAT_C_TERMINATION_STAT BIT(0)
#define IRQSTAT_C_TERMINATION_IRQ BIT(1)
#define IRQSTAT_C_TAPER_IRQ BIT(3)
#define IRQSTAT_D 0x38
#define IRQSTAT_D_CHARGE_TIMEOUT_STAT BIT(2)
#define IRQSTAT_D_CHARGE_TIMEOUT_IRQ BIT(3)
#define IRQSTAT_E 0x39
#define IRQSTAT_E_USBIN_UV_STAT BIT(0)
#define IRQSTAT_E_USBIN_UV_IRQ BIT(1)
#define IRQSTAT_E_DCIN_UV_STAT BIT(4)
#define IRQSTAT_E_DCIN_UV_IRQ BIT(5)
#define IRQSTAT_F 0x3a
/* Status registers */
#define STAT_A 0x3b
#define STAT_A_FLOAT_VOLTAGE_MASK 0x3f
#define STAT_B 0x3c
#define STAT_C 0x3d
#define STAT_C_CHG_ENABLED BIT(0)
#define STAT_C_HOLDOFF_STAT BIT(3)
#define STAT_C_CHG_MASK 0x06
#define STAT_C_CHG_SHIFT 1
#define STAT_C_CHG_TERM BIT(5)
#define STAT_C_CHARGER_ERROR BIT(6)
#define STAT_E 0x3f
#define SMB347_MAX_REGISTER 0x3f
/**
* struct smb347_charger - smb347 charger instance
* @lock: protects concurrent access to online variables
* @dev: pointer to device
* @regmap: pointer to driver regmap
* @mains: power_supply instance for AC/DC power
* @usb: power_supply instance for USB power
* @battery: power_supply instance for battery
* @mains_online: is AC/DC input connected
* @usb_online: is USB input connected
* @charging_enabled: is charging enabled
* @pdata: pointer to platform data
*/
struct smb347_charger {
struct mutex lock;
struct device *dev;
struct regmap *regmap;
struct power_supply mains;
struct power_supply usb;
struct power_supply battery;
bool mains_online;
bool usb_online;
bool charging_enabled;
const struct smb347_charger_platform_data *pdata;
};
/* Fast charge current in uA */
static const unsigned int fcc_tbl[] = {
700000,
900000,
1200000,
1500000,
1800000,
2000000,
2200000,
2500000,
};
/* Pre-charge current in uA */
static const unsigned int pcc_tbl[] = {
100000,
150000,
200000,
250000,
};
/* Termination current in uA */
static const unsigned int tc_tbl[] = {
37500,
50000,
100000,
150000,
200000,
250000,
500000,
600000,
};
/* Input current limit in uA */
static const unsigned int icl_tbl[] = {
300000,
500000,
700000,
900000,
1200000,
1500000,
1800000,
2000000,
2200000,
2500000,
};
/* Charge current compensation in uA */
static const unsigned int ccc_tbl[] = {
250000,
700000,
900000,
1200000,
};
/* Convert register value to current using lookup table */
static int hw_to_current(const unsigned int *tbl, size_t size, unsigned int val)
{
if (val >= size)
return -EINVAL;
return tbl[val];
}
/* Convert current to register value using lookup table */
static int current_to_hw(const unsigned int *tbl, size_t size, unsigned int val)
{
size_t i;
for (i = 0; i < size; i++)
if (val < tbl[i])
break;
return i > 0 ? i - 1 : -EINVAL;
}
/**
* smb347_update_ps_status - refreshes the power source status
* @smb: pointer to smb347 charger instance
*
* Function checks whether any power source is connected to the charger and
* updates internal state accordingly. If there is a change to previous state
* function returns %1, otherwise %0 and negative errno in case of errror.
*/
static int smb347_update_ps_status(struct smb347_charger *smb)
{
bool usb = false;
bool dc = false;
unsigned int val;
int ret;
ret = regmap_read(smb->regmap, IRQSTAT_E, &val);
if (ret < 0)
return ret;
/*
* Dc and usb are set depending on whether they are enabled in
* platform data _and_ whether corresponding undervoltage is set.
*/
if (smb->pdata->use_mains)
dc = !(val & IRQSTAT_E_DCIN_UV_STAT);
if (smb->pdata->use_usb)
usb = !(val & IRQSTAT_E_USBIN_UV_STAT);
mutex_lock(&smb->lock);
ret = smb->mains_online != dc || smb->usb_online != usb;
smb->mains_online = dc;
smb->usb_online = usb;
mutex_unlock(&smb->lock);
return ret;
}
/*
* smb347_is_ps_online - returns whether input power source is connected
* @smb: pointer to smb347 charger instance
*
* Returns %true if input power source is connected. Note that this is
* dependent on what platform has configured for usable power sources. For
* example if USB is disabled, this will return %false even if the USB cable
* is connected.
*/
static bool smb347_is_ps_online(struct smb347_charger *smb)
{
bool ret;
mutex_lock(&smb->lock);
ret = smb->usb_online || smb->mains_online;
mutex_unlock(&smb->lock);
return ret;
}
/**
* smb347_charging_status - returns status of charging
* @smb: pointer to smb347 charger instance
*
* Function returns charging status. %0 means no charging is in progress,
* %1 means pre-charging, %2 fast-charging and %3 taper-charging.
*/
static int smb347_charging_status(struct smb347_charger *smb)
{
unsigned int val;
int ret;
if (!smb347_is_ps_online(smb))
return 0;
ret = regmap_read(smb->regmap, STAT_C, &val);
if (ret < 0)
return 0;
return (val & STAT_C_CHG_MASK) >> STAT_C_CHG_SHIFT;
}
static int smb347_charging_set(struct smb347_charger *smb, bool enable)
{
int ret = 0;
if (smb->pdata->enable_control != SMB347_CHG_ENABLE_SW) {
dev_dbg(smb->dev, "charging enable/disable in SW disabled\n");
return 0;
}
mutex_lock(&smb->lock);
if (smb->charging_enabled != enable) {
ret = regmap_update_bits(smb->regmap, CMD_A, CMD_A_CHG_ENABLED,
enable ? CMD_A_CHG_ENABLED : 0);
if (!ret)
smb->charging_enabled = enable;
}
mutex_unlock(&smb->lock);
return ret;
}
static inline int smb347_charging_enable(struct smb347_charger *smb)
{
return smb347_charging_set(smb, true);
}
static inline int smb347_charging_disable(struct smb347_charger *smb)
{
return smb347_charging_set(smb, false);
}
static int smb347_start_stop_charging(struct smb347_charger *smb)
{
int ret;
/*
* Depending on whether valid power source is connected or not, we
* disable or enable the charging. We do it manually because it
* depends on how the platform has configured the valid inputs.
*/
if (smb347_is_ps_online(smb)) {
ret = smb347_charging_enable(smb);
if (ret < 0)
dev_err(smb->dev, "failed to enable charging\n");
} else {
ret = smb347_charging_disable(smb);
if (ret < 0)
dev_err(smb->dev, "failed to disable charging\n");
}
return ret;
}
static int smb347_set_charge_current(struct smb347_charger *smb)
{
int ret;
if (smb->pdata->max_charge_current) {
ret = current_to_hw(fcc_tbl, ARRAY_SIZE(fcc_tbl),
smb->pdata->max_charge_current);
if (ret < 0)
return ret;
ret = regmap_update_bits(smb->regmap, CFG_CHARGE_CURRENT,
CFG_CHARGE_CURRENT_FCC_MASK,
ret << CFG_CHARGE_CURRENT_FCC_SHIFT);
if (ret < 0)
return ret;
}
if (smb->pdata->pre_charge_current) {
ret = current_to_hw(pcc_tbl, ARRAY_SIZE(pcc_tbl),
smb->pdata->pre_charge_current);
if (ret < 0)
return ret;
ret = regmap_update_bits(smb->regmap, CFG_CHARGE_CURRENT,
CFG_CHARGE_CURRENT_PCC_MASK,
ret << CFG_CHARGE_CURRENT_PCC_SHIFT);
if (ret < 0)
return ret;
}
if (smb->pdata->termination_current) {
ret = current_to_hw(tc_tbl, ARRAY_SIZE(tc_tbl),
smb->pdata->termination_current);
if (ret < 0)
return ret;
ret = regmap_update_bits(smb->regmap, CFG_CHARGE_CURRENT,
CFG_CHARGE_CURRENT_TC_MASK, ret);
if (ret < 0)
return ret;
}
return 0;
}
static int smb347_set_current_limits(struct smb347_charger *smb)
{
int ret;
if (smb->pdata->mains_current_limit) {
ret = current_to_hw(icl_tbl, ARRAY_SIZE(icl_tbl),
smb->pdata->mains_current_limit);
if (ret < 0)
return ret;
ret = regmap_update_bits(smb->regmap, CFG_CURRENT_LIMIT,
CFG_CURRENT_LIMIT_DC_MASK,
ret << CFG_CURRENT_LIMIT_DC_SHIFT);
if (ret < 0)
return ret;
}
if (smb->pdata->usb_hc_current_limit) {
ret = current_to_hw(icl_tbl, ARRAY_SIZE(icl_tbl),
smb->pdata->usb_hc_current_limit);
if (ret < 0)
return ret;
ret = regmap_update_bits(smb->regmap, CFG_CURRENT_LIMIT,
CFG_CURRENT_LIMIT_USB_MASK, ret);
if (ret < 0)
return ret;
}
return 0;
}
static int smb347_set_voltage_limits(struct smb347_charger *smb)
{
int ret;
if (smb->pdata->pre_to_fast_voltage) {
ret = smb->pdata->pre_to_fast_voltage;
/* uV */
ret = clamp_val(ret, 2400000, 3000000) - 2400000;
ret /= 200000;
ret = regmap_update_bits(smb->regmap, CFG_FLOAT_VOLTAGE,
CFG_FLOAT_VOLTAGE_THRESHOLD_MASK,
ret << CFG_FLOAT_VOLTAGE_THRESHOLD_SHIFT);
if (ret < 0)
return ret;
}
if (smb->pdata->max_charge_voltage) {
ret = smb->pdata->max_charge_voltage;
/* uV */
ret = clamp_val(ret, 3500000, 4500000) - 3500000;
ret /= 20000;
ret = regmap_update_bits(smb->regmap, CFG_FLOAT_VOLTAGE,
CFG_FLOAT_VOLTAGE_FLOAT_MASK, ret);
if (ret < 0)
return ret;
}
return 0;
}
static int smb347_set_temp_limits(struct smb347_charger *smb)
{
bool enable_therm_monitor = false;
int ret = 0;
int val;
if (smb->pdata->chip_temp_threshold) {
val = smb->pdata->chip_temp_threshold;
/* degree C */
val = clamp_val(val, 100, 130) - 100;
val /= 10;
ret = regmap_update_bits(smb->regmap, CFG_OTG,
CFG_OTG_TEMP_THRESHOLD_MASK,
val << CFG_OTG_TEMP_THRESHOLD_SHIFT);
if (ret < 0)
return ret;
}
if (smb->pdata->soft_cold_temp_limit != SMB347_TEMP_USE_DEFAULT) {
val = smb->pdata->soft_cold_temp_limit;
val = clamp_val(val, 0, 15);
val /= 5;
/* this goes from higher to lower so invert the value */
val = ~val & 0x3;
ret = regmap_update_bits(smb->regmap, CFG_TEMP_LIMIT,
CFG_TEMP_LIMIT_SOFT_COLD_MASK,
val << CFG_TEMP_LIMIT_SOFT_COLD_SHIFT);
if (ret < 0)
return ret;
enable_therm_monitor = true;
}
if (smb->pdata->soft_hot_temp_limit != SMB347_TEMP_USE_DEFAULT) {
val = smb->pdata->soft_hot_temp_limit;
val = clamp_val(val, 40, 55) - 40;
val /= 5;
ret = regmap_update_bits(smb->regmap, CFG_TEMP_LIMIT,
CFG_TEMP_LIMIT_SOFT_HOT_MASK,
val << CFG_TEMP_LIMIT_SOFT_HOT_SHIFT);
if (ret < 0)
return ret;
enable_therm_monitor = true;
}
if (smb->pdata->hard_cold_temp_limit != SMB347_TEMP_USE_DEFAULT) {
val = smb->pdata->hard_cold_temp_limit;
val = clamp_val(val, -5, 10) + 5;
val /= 5;
/* this goes from higher to lower so invert the value */
val = ~val & 0x3;
ret = regmap_update_bits(smb->regmap, CFG_TEMP_LIMIT,
CFG_TEMP_LIMIT_HARD_COLD_MASK,
val << CFG_TEMP_LIMIT_HARD_COLD_SHIFT);
if (ret < 0)
return ret;
enable_therm_monitor = true;
}
if (smb->pdata->hard_hot_temp_limit != SMB347_TEMP_USE_DEFAULT) {
val = smb->pdata->hard_hot_temp_limit;
val = clamp_val(val, 50, 65) - 50;
val /= 5;
ret = regmap_update_bits(smb->regmap, CFG_TEMP_LIMIT,
CFG_TEMP_LIMIT_HARD_HOT_MASK,
val << CFG_TEMP_LIMIT_HARD_HOT_SHIFT);
if (ret < 0)
return ret;
enable_therm_monitor = true;
}
/*
* If any of the temperature limits are set, we also enable the
* thermistor monitoring.
*
* When soft limits are hit, the device will start to compensate
* current and/or voltage depending on the configuration.
*
* When hard limit is hit, the device will suspend charging
* depending on the configuration.
*/
if (enable_therm_monitor) {
ret = regmap_update_bits(smb->regmap, CFG_THERM,
CFG_THERM_MONITOR_DISABLED, 0);
if (ret < 0)
return ret;
}
if (smb->pdata->suspend_on_hard_temp_limit) {
ret = regmap_update_bits(smb->regmap, CFG_SYSOK,
CFG_SYSOK_SUSPEND_HARD_LIMIT_DISABLED, 0);
if (ret < 0)
return ret;
}
if (smb->pdata->soft_temp_limit_compensation !=
SMB347_SOFT_TEMP_COMPENSATE_DEFAULT) {
val = smb->pdata->soft_temp_limit_compensation & 0x3;
ret = regmap_update_bits(smb->regmap, CFG_THERM,
CFG_THERM_SOFT_HOT_COMPENSATION_MASK,
val << CFG_THERM_SOFT_HOT_COMPENSATION_SHIFT);
if (ret < 0)
return ret;
ret = regmap_update_bits(smb->regmap, CFG_THERM,
CFG_THERM_SOFT_COLD_COMPENSATION_MASK,
val << CFG_THERM_SOFT_COLD_COMPENSATION_SHIFT);
if (ret < 0)
return ret;
}
if (smb->pdata->charge_current_compensation) {
val = current_to_hw(ccc_tbl, ARRAY_SIZE(ccc_tbl),
smb->pdata->charge_current_compensation);
if (val < 0)
return val;
ret = regmap_update_bits(smb->regmap, CFG_OTG,
CFG_OTG_CC_COMPENSATION_MASK,
(val & 0x3) << CFG_OTG_CC_COMPENSATION_SHIFT);
if (ret < 0)
return ret;
}
return ret;
}
/*
* smb347_set_writable - enables/disables writing to non-volatile registers
* @smb: pointer to smb347 charger instance
*
* You can enable/disable writing to the non-volatile configuration
* registers by calling this function.
*
* Returns %0 on success and negative errno in case of failure.
*/
static int smb347_set_writable(struct smb347_charger *smb, bool writable)
{
return regmap_update_bits(smb->regmap, CMD_A, CMD_A_ALLOW_WRITE,
writable ? CMD_A_ALLOW_WRITE : 0);
}
static int smb347_hw_init(struct smb347_charger *smb)
{
unsigned int val;
int ret;
ret = smb347_set_writable(smb, true);
if (ret < 0)
return ret;
/*
* Program the platform specific configuration values to the device
* first.
*/
ret = smb347_set_charge_current(smb);
if (ret < 0)
goto fail;
ret = smb347_set_current_limits(smb);
if (ret < 0)
goto fail;
ret = smb347_set_voltage_limits(smb);
if (ret < 0)
goto fail;
ret = smb347_set_temp_limits(smb);
if (ret < 0)
goto fail;
/* If USB charging is disabled we put the USB in suspend mode */
if (!smb->pdata->use_usb) {
ret = regmap_update_bits(smb->regmap, CMD_A,
CMD_A_SUSPEND_ENABLED,
CMD_A_SUSPEND_ENABLED);
if (ret < 0)
goto fail;
}
/*
* If configured by platform data, we enable hardware Auto-OTG
* support for driving VBUS. Otherwise we disable it.
*/
ret = regmap_update_bits(smb->regmap, CFG_OTHER, CFG_OTHER_RID_MASK,
smb->pdata->use_usb_otg ? CFG_OTHER_RID_ENABLED_AUTO_OTG : 0);
if (ret < 0)
goto fail;
/*
* Make the charging functionality controllable by a write to the
* command register unless pin control is specified in the platform
* data.
*/
switch (smb->pdata->enable_control) {
case SMB347_CHG_ENABLE_PIN_ACTIVE_LOW:
val = CFG_PIN_EN_CTRL_ACTIVE_LOW;
break;
case SMB347_CHG_ENABLE_PIN_ACTIVE_HIGH:
val = CFG_PIN_EN_CTRL_ACTIVE_HIGH;
break;
default:
val = 0;
break;
}
ret = regmap_update_bits(smb->regmap, CFG_PIN, CFG_PIN_EN_CTRL_MASK,
val);
if (ret < 0)
goto fail;
/* Disable Automatic Power Source Detection (APSD) interrupt. */
ret = regmap_update_bits(smb->regmap, CFG_PIN, CFG_PIN_EN_APSD_IRQ, 0);
if (ret < 0)
goto fail;
ret = smb347_update_ps_status(smb);
if (ret < 0)
goto fail;
ret = smb347_start_stop_charging(smb);
fail:
smb347_set_writable(smb, false);
return ret;
}
static irqreturn_t smb347_interrupt(int irq, void *data)
{
struct smb347_charger *smb = data;
unsigned int stat_c, irqstat_c, irqstat_d, irqstat_e;
bool handled = false;
int ret;
ret = regmap_read(smb->regmap, STAT_C, &stat_c);
if (ret < 0) {
dev_warn(smb->dev, "reading STAT_C failed\n");
return IRQ_NONE;
}
ret = regmap_read(smb->regmap, IRQSTAT_C, &irqstat_c);
if (ret < 0) {
dev_warn(smb->dev, "reading IRQSTAT_C failed\n");
return IRQ_NONE;
}
ret = regmap_read(smb->regmap, IRQSTAT_D, &irqstat_d);
if (ret < 0) {
dev_warn(smb->dev, "reading IRQSTAT_D failed\n");
return IRQ_NONE;
}
ret = regmap_read(smb->regmap, IRQSTAT_E, &irqstat_e);
if (ret < 0) {
dev_warn(smb->dev, "reading IRQSTAT_E failed\n");
return IRQ_NONE;
}
/*
* If we get charger error we report the error back to user.
* If the error is recovered charging will resume again.
*/
if (stat_c & STAT_C_CHARGER_ERROR) {
dev_err(smb->dev, "charging stopped due to charger error\n");
power_supply_changed(&smb->battery);
handled = true;
}
/*
* If we reached the termination current the battery is charged and
* we can update the status now. Charging is automatically
* disabled by the hardware.
*/
if (irqstat_c & (IRQSTAT_C_TERMINATION_IRQ | IRQSTAT_C_TAPER_IRQ)) {
if (irqstat_c & IRQSTAT_C_TERMINATION_STAT)
power_supply_changed(&smb->battery);
dev_dbg(smb->dev, "going to HW maintenance mode\n");
handled = true;
}
/*
* If we got a charger timeout INT that means the charge
* full is not detected with in charge timeout value.
*/
if (irqstat_d & IRQSTAT_D_CHARGE_TIMEOUT_IRQ) {
dev_dbg(smb->dev, "total Charge Timeout INT received\n");
if (irqstat_d & IRQSTAT_D_CHARGE_TIMEOUT_STAT)
dev_warn(smb->dev, "charging stopped due to timeout\n");
power_supply_changed(&smb->battery);
handled = true;
}
/*
* If we got an under voltage interrupt it means that AC/USB input
* was connected or disconnected.
*/
if (irqstat_e & (IRQSTAT_E_USBIN_UV_IRQ | IRQSTAT_E_DCIN_UV_IRQ)) {
if (smb347_update_ps_status(smb) > 0) {
smb347_start_stop_charging(smb);
if (smb->pdata->use_mains)
power_supply_changed(&smb->mains);
if (smb->pdata->use_usb)
power_supply_changed(&smb->usb);
}
handled = true;
}
return handled ? IRQ_HANDLED : IRQ_NONE;
}
static int smb347_irq_set(struct smb347_charger *smb, bool enable)
{
int ret;
ret = smb347_set_writable(smb, true);
if (ret < 0)
return ret;
/*
* Enable/disable interrupts for:
* - under voltage
* - termination current reached
* - charger timeout
* - charger error
*/
ret = regmap_update_bits(smb->regmap, CFG_FAULT_IRQ, 0xff,
enable ? CFG_FAULT_IRQ_DCIN_UV : 0);
if (ret < 0)
goto fail;
ret = regmap_update_bits(smb->regmap, CFG_STATUS_IRQ, 0xff,
enable ? (CFG_STATUS_IRQ_TERMINATION_OR_TAPER |
CFG_STATUS_IRQ_CHARGE_TIMEOUT) : 0);
if (ret < 0)
goto fail;
ret = regmap_update_bits(smb->regmap, CFG_PIN, CFG_PIN_EN_CHARGER_ERROR,
enable ? CFG_PIN_EN_CHARGER_ERROR : 0);
fail:
smb347_set_writable(smb, false);
return ret;
}
static inline int smb347_irq_enable(struct smb347_charger *smb)
{
return smb347_irq_set(smb, true);
}
static inline int smb347_irq_disable(struct smb347_charger *smb)
{
return smb347_irq_set(smb, false);
}
static int smb347_irq_init(struct smb347_charger *smb,
struct i2c_client *client)
{
const struct smb347_charger_platform_data *pdata = smb->pdata;
int ret, irq = gpio_to_irq(pdata->irq_gpio);
ret = gpio_request_one(pdata->irq_gpio, GPIOF_IN, client->name);
if (ret < 0)
goto fail;
ret = request_threaded_irq(irq, NULL, smb347_interrupt,
IRQF_TRIGGER_FALLING, client->name, smb);
if (ret < 0)
goto fail_gpio;
ret = smb347_set_writable(smb, true);
if (ret < 0)
goto fail_irq;
/*
* Configure the STAT output to be suitable for interrupts: disable
* all other output (except interrupts) and make it active low.
*/
ret = regmap_update_bits(smb->regmap, CFG_STAT,
CFG_STAT_ACTIVE_HIGH | CFG_STAT_DISABLED,
CFG_STAT_DISABLED);
if (ret < 0)
goto fail_readonly;
smb347_set_writable(smb, false);
client->irq = irq;
return 0;
fail_readonly:
smb347_set_writable(smb, false);
fail_irq:
free_irq(irq, smb);
fail_gpio:
gpio_free(pdata->irq_gpio);
fail:
client->irq = 0;
return ret;
}
/*
* Returns the constant charge current programmed
* into the charger in uA.
*/
static int get_const_charge_current(struct smb347_charger *smb)
{
int ret, intval;
unsigned int v;
if (!smb347_is_ps_online(smb))
return -ENODATA;
ret = regmap_read(smb->regmap, STAT_B, &v);
if (ret < 0)
return ret;
/*
* The current value is composition of FCC and PCC values
* and we can detect which table to use from bit 5.
*/
if (v & 0x20) {
intval = hw_to_current(fcc_tbl, ARRAY_SIZE(fcc_tbl), v & 7);
} else {
v >>= 3;
intval = hw_to_current(pcc_tbl, ARRAY_SIZE(pcc_tbl), v & 7);
}
return intval;
}
/*
* Returns the constant charge voltage programmed
* into the charger in uV.
*/
static int get_const_charge_voltage(struct smb347_charger *smb)
{
int ret, intval;
unsigned int v;
if (!smb347_is_ps_online(smb))
return -ENODATA;
ret = regmap_read(smb->regmap, STAT_A, &v);
if (ret < 0)
return ret;
v &= STAT_A_FLOAT_VOLTAGE_MASK;
if (v > 0x3d)
v = 0x3d;
intval = 3500000 + v * 20000;
return intval;
}
static int smb347_mains_get_property(struct power_supply *psy,
enum power_supply_property prop,
union power_supply_propval *val)
{
struct smb347_charger *smb =
container_of(psy, struct smb347_charger, mains);
int ret;
switch (prop) {
case POWER_SUPPLY_PROP_ONLINE:
val->intval = smb->mains_online;
break;
case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE:
ret = get_const_charge_voltage(smb);
if (ret < 0)
return ret;
else
val->intval = ret;
break;
case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT:
ret = get_const_charge_current(smb);
if (ret < 0)
return ret;
else
val->intval = ret;
break;
default:
return -EINVAL;
}
return 0;
}
static enum power_supply_property smb347_mains_properties[] = {
POWER_SUPPLY_PROP_ONLINE,
POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT,
POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE,
};
static int smb347_usb_get_property(struct power_supply *psy,
enum power_supply_property prop,
union power_supply_propval *val)
{
struct smb347_charger *smb =
container_of(psy, struct smb347_charger, usb);
int ret;
switch (prop) {
case POWER_SUPPLY_PROP_ONLINE:
val->intval = smb->usb_online;
break;
case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE:
ret = get_const_charge_voltage(smb);
if (ret < 0)
return ret;
else
val->intval = ret;
break;
case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT:
ret = get_const_charge_current(smb);
if (ret < 0)
return ret;
else
val->intval = ret;
break;
default:
return -EINVAL;
}
return 0;
}
static enum power_supply_property smb347_usb_properties[] = {
POWER_SUPPLY_PROP_ONLINE,
POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT,
POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE,
};
static int smb347_get_charging_status(struct smb347_charger *smb)
{
int ret, status;
unsigned int val;
if (!smb347_is_ps_online(smb))
return POWER_SUPPLY_STATUS_DISCHARGING;
ret = regmap_read(smb->regmap, STAT_C, &val);
if (ret < 0)
return ret;
if ((val & STAT_C_CHARGER_ERROR) ||
(val & STAT_C_HOLDOFF_STAT)) {
/*
* set to NOT CHARGING upon charger error
* or charging has stopped.
*/
status = POWER_SUPPLY_STATUS_NOT_CHARGING;
} else {
if ((val & STAT_C_CHG_MASK) >> STAT_C_CHG_SHIFT) {
/*
* set to charging if battery is in pre-charge,
* fast charge or taper charging mode.
*/
status = POWER_SUPPLY_STATUS_CHARGING;
} else if (val & STAT_C_CHG_TERM) {
/*
* set the status to FULL if battery is not in pre
* charge, fast charge or taper charging mode AND
* charging is terminated at least once.
*/
status = POWER_SUPPLY_STATUS_FULL;
} else {
/*
* in this case no charger error or termination
* occured but charging is not in progress!!!
*/
status = POWER_SUPPLY_STATUS_NOT_CHARGING;
}
}
return status;
}
static int smb347_battery_get_property(struct power_supply *psy,
enum power_supply_property prop,
union power_supply_propval *val)
{
struct smb347_charger *smb =
container_of(psy, struct smb347_charger, battery);
const struct smb347_charger_platform_data *pdata = smb->pdata;
int ret;
ret = smb347_update_ps_status(smb);
if (ret < 0)
return ret;
switch (prop) {
case POWER_SUPPLY_PROP_STATUS:
ret = smb347_get_charging_status(smb);
if (ret < 0)
return ret;
val->intval = ret;
break;
case POWER_SUPPLY_PROP_CHARGE_TYPE:
if (!smb347_is_ps_online(smb))
return -ENODATA;
/*
* We handle trickle and pre-charging the same, and taper
* and none the same.
*/
switch (smb347_charging_status(smb)) {
case 1:
val->intval = POWER_SUPPLY_CHARGE_TYPE_TRICKLE;
break;
case 2:
val->intval = POWER_SUPPLY_CHARGE_TYPE_FAST;
break;
default:
val->intval = POWER_SUPPLY_CHARGE_TYPE_NONE;
break;
}
break;
case POWER_SUPPLY_PROP_TECHNOLOGY:
val->intval = pdata->battery_info.technology;
break;
case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
val->intval = pdata->battery_info.voltage_min_design;
break;
case POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN:
val->intval = pdata->battery_info.voltage_max_design;
break;
case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
val->intval = pdata->battery_info.charge_full_design;
break;
case POWER_SUPPLY_PROP_MODEL_NAME:
val->strval = pdata->battery_info.name;
break;
default:
return -EINVAL;
}
return 0;
}
static enum power_supply_property smb347_battery_properties[] = {
POWER_SUPPLY_PROP_STATUS,
POWER_SUPPLY_PROP_CHARGE_TYPE,
POWER_SUPPLY_PROP_TECHNOLOGY,
POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN,
POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
POWER_SUPPLY_PROP_MODEL_NAME,
};
static bool smb347_volatile_reg(struct device *dev, unsigned int reg)
{
switch (reg) {
case IRQSTAT_A:
case IRQSTAT_C:
case IRQSTAT_E:
case IRQSTAT_F:
case STAT_A:
case STAT_B:
case STAT_C:
case STAT_E:
return true;
}
return false;
}
static bool smb347_readable_reg(struct device *dev, unsigned int reg)
{
switch (reg) {
case CFG_CHARGE_CURRENT:
case CFG_CURRENT_LIMIT:
case CFG_FLOAT_VOLTAGE:
case CFG_STAT:
case CFG_PIN:
case CFG_THERM:
case CFG_SYSOK:
case CFG_OTHER:
case CFG_OTG:
case CFG_TEMP_LIMIT:
case CFG_FAULT_IRQ:
case CFG_STATUS_IRQ:
case CFG_ADDRESS:
case CMD_A:
case CMD_B:
case CMD_C:
return true;
}
return smb347_volatile_reg(dev, reg);
}
static const struct regmap_config smb347_regmap = {
.reg_bits = 8,
.val_bits = 8,
.max_register = SMB347_MAX_REGISTER,
.volatile_reg = smb347_volatile_reg,
.readable_reg = smb347_readable_reg,
};
static int smb347_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
static char *battery[] = { "smb347-battery" };
const struct smb347_charger_platform_data *pdata;
struct device *dev = &client->dev;
struct smb347_charger *smb;
int ret;
pdata = dev->platform_data;
if (!pdata)
return -EINVAL;
if (!pdata->use_mains && !pdata->use_usb)
return -EINVAL;
smb = devm_kzalloc(dev, sizeof(*smb), GFP_KERNEL);
if (!smb)
return -ENOMEM;
i2c_set_clientdata(client, smb);
mutex_init(&smb->lock);
smb->dev = &client->dev;
smb->pdata = pdata;
smb->regmap = devm_regmap_init_i2c(client, &smb347_regmap);
if (IS_ERR(smb->regmap))
return PTR_ERR(smb->regmap);
ret = smb347_hw_init(smb);
if (ret < 0)
return ret;
if (smb->pdata->use_mains) {
smb->mains.name = "smb347-mains";
smb->mains.type = POWER_SUPPLY_TYPE_MAINS;
smb->mains.get_property = smb347_mains_get_property;
smb->mains.properties = smb347_mains_properties;
smb->mains.num_properties = ARRAY_SIZE(smb347_mains_properties);
smb->mains.supplied_to = battery;
smb->mains.num_supplicants = ARRAY_SIZE(battery);
ret = power_supply_register(dev, &smb->mains);
if (ret < 0)
return ret;
}
if (smb->pdata->use_usb) {
smb->usb.name = "smb347-usb";
smb->usb.type = POWER_SUPPLY_TYPE_USB;
smb->usb.get_property = smb347_usb_get_property;
smb->usb.properties = smb347_usb_properties;
smb->usb.num_properties = ARRAY_SIZE(smb347_usb_properties);
smb->usb.supplied_to = battery;
smb->usb.num_supplicants = ARRAY_SIZE(battery);
ret = power_supply_register(dev, &smb->usb);
if (ret < 0) {
if (smb->pdata->use_mains)
power_supply_unregister(&smb->mains);
return ret;
}
}
smb->battery.name = "smb347-battery";
smb->battery.type = POWER_SUPPLY_TYPE_BATTERY;
smb->battery.get_property = smb347_battery_get_property;
smb->battery.properties = smb347_battery_properties;
smb->battery.num_properties = ARRAY_SIZE(smb347_battery_properties);
ret = power_supply_register(dev, &smb->battery);
if (ret < 0) {
if (smb->pdata->use_usb)
power_supply_unregister(&smb->usb);
if (smb->pdata->use_mains)
power_supply_unregister(&smb->mains);
return ret;
}
/*
* Interrupt pin is optional. If it is connected, we setup the
* interrupt support here.
*/
if (pdata->irq_gpio >= 0) {
ret = smb347_irq_init(smb, client);
if (ret < 0) {
dev_warn(dev, "failed to initialize IRQ: %d\n", ret);
dev_warn(dev, "disabling IRQ support\n");
} else {
smb347_irq_enable(smb);
}
}
return 0;
}
static int smb347_remove(struct i2c_client *client)
{
struct smb347_charger *smb = i2c_get_clientdata(client);
if (client->irq) {
smb347_irq_disable(smb);
free_irq(client->irq, smb);
gpio_free(smb->pdata->irq_gpio);
}
power_supply_unregister(&smb->battery);
if (smb->pdata->use_usb)
power_supply_unregister(&smb->usb);
if (smb->pdata->use_mains)
power_supply_unregister(&smb->mains);
return 0;
}
static const struct i2c_device_id smb347_id[] = {
{ "smb347", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, smb347_id);
static struct i2c_driver smb347_driver = {
.driver = {
.name = "smb347",
},
.probe = smb347_probe,
.remove = smb347_remove,
.id_table = smb347_id,
};
module_i2c_driver(smb347_driver);
MODULE_AUTHOR("Bruce E. Robertson <bruce.e.robertson@intel.com>");
MODULE_AUTHOR("Mika Westerberg <mika.westerberg@linux.intel.com>");
MODULE_DESCRIPTION("SMB347 battery charger driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("i2c:smb347");
| gpl-2.0 |
edoko/Air_Kernel-POP | drivers/watchdog/wm8350_wdt.c | 4147 | 6980 | /*
* Watchdog driver for the wm8350
*
* Copyright (C) 2007, 2008 Wolfson Microelectronics <linux@wolfsonmicro.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
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/miscdevice.h>
#include <linux/platform_device.h>
#include <linux/watchdog.h>
#include <linux/uaccess.h>
#include <linux/mfd/wm8350/core.h>
static int nowayout = WATCHDOG_NOWAYOUT;
module_param(nowayout, int, 0);
MODULE_PARM_DESC(nowayout,
"Watchdog cannot be stopped once started (default="
__MODULE_STRING(WATCHDOG_NOWAYOUT) ")");
static unsigned long wm8350_wdt_users;
static struct miscdevice wm8350_wdt_miscdev;
static int wm8350_wdt_expect_close;
static DEFINE_MUTEX(wdt_mutex);
static struct {
int time; /* Seconds */
u16 val; /* To be set in WM8350_SYSTEM_CONTROL_2 */
} wm8350_wdt_cfgs[] = {
{ 1, 0x02 },
{ 2, 0x04 },
{ 4, 0x05 },
};
static struct wm8350 *get_wm8350(void)
{
return dev_get_drvdata(wm8350_wdt_miscdev.parent);
}
static int wm8350_wdt_set_timeout(struct wm8350 *wm8350, u16 value)
{
int ret;
u16 reg;
mutex_lock(&wdt_mutex);
wm8350_reg_unlock(wm8350);
reg = wm8350_reg_read(wm8350, WM8350_SYSTEM_CONTROL_2);
reg &= ~WM8350_WDOG_TO_MASK;
reg |= value;
ret = wm8350_reg_write(wm8350, WM8350_SYSTEM_CONTROL_2, reg);
wm8350_reg_lock(wm8350);
mutex_unlock(&wdt_mutex);
return ret;
}
static int wm8350_wdt_start(struct wm8350 *wm8350)
{
int ret;
u16 reg;
mutex_lock(&wdt_mutex);
wm8350_reg_unlock(wm8350);
reg = wm8350_reg_read(wm8350, WM8350_SYSTEM_CONTROL_2);
reg &= ~WM8350_WDOG_MODE_MASK;
reg |= 0x20;
ret = wm8350_reg_write(wm8350, WM8350_SYSTEM_CONTROL_2, reg);
wm8350_reg_lock(wm8350);
mutex_unlock(&wdt_mutex);
return ret;
}
static int wm8350_wdt_stop(struct wm8350 *wm8350)
{
int ret;
u16 reg;
mutex_lock(&wdt_mutex);
wm8350_reg_unlock(wm8350);
reg = wm8350_reg_read(wm8350, WM8350_SYSTEM_CONTROL_2);
reg &= ~WM8350_WDOG_MODE_MASK;
ret = wm8350_reg_write(wm8350, WM8350_SYSTEM_CONTROL_2, reg);
wm8350_reg_lock(wm8350);
mutex_unlock(&wdt_mutex);
return ret;
}
static int wm8350_wdt_kick(struct wm8350 *wm8350)
{
int ret;
u16 reg;
mutex_lock(&wdt_mutex);
reg = wm8350_reg_read(wm8350, WM8350_SYSTEM_CONTROL_2);
ret = wm8350_reg_write(wm8350, WM8350_SYSTEM_CONTROL_2, reg);
mutex_unlock(&wdt_mutex);
return ret;
}
static int wm8350_wdt_open(struct inode *inode, struct file *file)
{
struct wm8350 *wm8350 = get_wm8350();
int ret;
if (!wm8350)
return -ENODEV;
if (test_and_set_bit(0, &wm8350_wdt_users))
return -EBUSY;
ret = wm8350_wdt_start(wm8350);
if (ret != 0)
return ret;
return nonseekable_open(inode, file);
}
static int wm8350_wdt_release(struct inode *inode, struct file *file)
{
struct wm8350 *wm8350 = get_wm8350();
if (wm8350_wdt_expect_close)
wm8350_wdt_stop(wm8350);
else {
dev_warn(wm8350->dev, "Watchdog device closed uncleanly\n");
wm8350_wdt_kick(wm8350);
}
clear_bit(0, &wm8350_wdt_users);
return 0;
}
static ssize_t wm8350_wdt_write(struct file *file,
const char __user *data, size_t count,
loff_t *ppos)
{
struct wm8350 *wm8350 = get_wm8350();
size_t i;
if (count) {
wm8350_wdt_kick(wm8350);
if (!nowayout) {
/* In case it was set long ago */
wm8350_wdt_expect_close = 0;
/* scan to see whether or not we got the magic
character */
for (i = 0; i != count; i++) {
char c;
if (get_user(c, data + i))
return -EFAULT;
if (c == 'V')
wm8350_wdt_expect_close = 42;
}
}
}
return count;
}
static const struct watchdog_info ident = {
.options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING | WDIOF_MAGICCLOSE,
.identity = "WM8350 Watchdog",
};
static long wm8350_wdt_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
struct wm8350 *wm8350 = get_wm8350();
int ret = -ENOTTY, time, i;
void __user *argp = (void __user *)arg;
int __user *p = argp;
u16 reg;
switch (cmd) {
case WDIOC_GETSUPPORT:
ret = copy_to_user(argp, &ident, sizeof(ident)) ? -EFAULT : 0;
break;
case WDIOC_GETSTATUS:
case WDIOC_GETBOOTSTATUS:
ret = put_user(0, p);
break;
case WDIOC_SETOPTIONS:
{
int options;
if (get_user(options, p))
return -EFAULT;
ret = -EINVAL;
/* Setting both simultaneously means at least one must fail */
if (options == WDIOS_DISABLECARD)
ret = wm8350_wdt_start(wm8350);
if (options == WDIOS_ENABLECARD)
ret = wm8350_wdt_stop(wm8350);
break;
}
case WDIOC_KEEPALIVE:
ret = wm8350_wdt_kick(wm8350);
break;
case WDIOC_SETTIMEOUT:
ret = get_user(time, p);
if (ret)
break;
if (time == 0) {
if (nowayout)
ret = -EINVAL;
else
wm8350_wdt_stop(wm8350);
break;
}
for (i = 0; i < ARRAY_SIZE(wm8350_wdt_cfgs); i++)
if (wm8350_wdt_cfgs[i].time == time)
break;
if (i == ARRAY_SIZE(wm8350_wdt_cfgs))
ret = -EINVAL;
else
ret = wm8350_wdt_set_timeout(wm8350,
wm8350_wdt_cfgs[i].val);
break;
case WDIOC_GETTIMEOUT:
reg = wm8350_reg_read(wm8350, WM8350_SYSTEM_CONTROL_2);
reg &= WM8350_WDOG_TO_MASK;
for (i = 0; i < ARRAY_SIZE(wm8350_wdt_cfgs); i++)
if (wm8350_wdt_cfgs[i].val == reg)
break;
if (i == ARRAY_SIZE(wm8350_wdt_cfgs)) {
dev_warn(wm8350->dev,
"Unknown watchdog configuration: %x\n", reg);
ret = -EINVAL;
} else
ret = put_user(wm8350_wdt_cfgs[i].time, p);
}
return ret;
}
static const struct file_operations wm8350_wdt_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.write = wm8350_wdt_write,
.unlocked_ioctl = wm8350_wdt_ioctl,
.open = wm8350_wdt_open,
.release = wm8350_wdt_release,
};
static struct miscdevice wm8350_wdt_miscdev = {
.minor = WATCHDOG_MINOR,
.name = "watchdog",
.fops = &wm8350_wdt_fops,
};
static int __devinit wm8350_wdt_probe(struct platform_device *pdev)
{
struct wm8350 *wm8350 = platform_get_drvdata(pdev);
if (!wm8350) {
pr_err("No driver data supplied\n");
return -ENODEV;
}
/* Default to 4s timeout */
wm8350_wdt_set_timeout(wm8350, 0x05);
wm8350_wdt_miscdev.parent = &pdev->dev;
return misc_register(&wm8350_wdt_miscdev);
}
static int __devexit wm8350_wdt_remove(struct platform_device *pdev)
{
misc_deregister(&wm8350_wdt_miscdev);
return 0;
}
static struct platform_driver wm8350_wdt_driver = {
.probe = wm8350_wdt_probe,
.remove = __devexit_p(wm8350_wdt_remove),
.driver = {
.name = "wm8350-wdt",
},
};
static int __init wm8350_wdt_init(void)
{
return platform_driver_register(&wm8350_wdt_driver);
}
module_init(wm8350_wdt_init);
static void __exit wm8350_wdt_exit(void)
{
platform_driver_unregister(&wm8350_wdt_driver);
}
module_exit(wm8350_wdt_exit);
MODULE_AUTHOR("Mark Brown");
MODULE_DESCRIPTION("WM8350 Watchdog");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:wm8350-wdt");
| gpl-2.0 |
rex-xxx/iq442_kernel | drivers/staging/bcm/IPv6Protocol.c | 7987 | 12961 | #include "headers.h"
static BOOLEAN MatchSrcIpv6Address(S_CLASSIFIER_RULE *pstClassifierRule,IPV6Header *pstIpv6Header);
static BOOLEAN MatchDestIpv6Address(S_CLASSIFIER_RULE *pstClassifierRule,IPV6Header *pstIpv6Header);
static VOID DumpIpv6Header(IPV6Header *pstIpv6Header);
static UCHAR * GetNextIPV6ChainedHeader(UCHAR **ppucPayload,UCHAR *pucNextHeader,BOOLEAN *bParseDone,USHORT *pusPayloadLength)
{
UCHAR *pucRetHeaderPtr = NULL;
UCHAR *pucPayloadPtr = NULL;
USHORT usNextHeaderOffset = 0 ;
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
if((NULL == ppucPayload) || (*pusPayloadLength == 0) || (*bParseDone))
{
*bParseDone = TRUE;
return NULL;
}
pucRetHeaderPtr = *ppucPayload;
pucPayloadPtr = *ppucPayload;
if(!pucRetHeaderPtr || !pucPayloadPtr)
{
*bParseDone = TRUE;
return NULL;
}
//Get the Nextt Header Type
*bParseDone = FALSE;
switch(*pucNextHeader)
{
case IPV6HDR_TYPE_HOPBYHOP:
{
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\nIPv6 HopByHop Header");
usNextHeaderOffset+=sizeof(IPV6HopByHopOptionsHeader);
}
break;
case IPV6HDR_TYPE_ROUTING:
{
IPV6RoutingHeader *pstIpv6RoutingHeader;
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\nIPv6 Routing Header");
pstIpv6RoutingHeader = (IPV6RoutingHeader *)pucPayloadPtr;
usNextHeaderOffset += sizeof(IPV6RoutingHeader);
usNextHeaderOffset += pstIpv6RoutingHeader->ucNumAddresses * IPV6_ADDRESS_SIZEINBYTES;
}
break;
case IPV6HDR_TYPE_FRAGMENTATION:
{
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\nIPv6 Fragmentation Header");
usNextHeaderOffset+= sizeof(IPV6FragmentHeader);
}
break;
case IPV6HDR_TYPE_DESTOPTS:
{
IPV6DestOptionsHeader *pstIpv6DestOptsHdr = (IPV6DestOptionsHeader *)pucPayloadPtr;
int nTotalOptions = pstIpv6DestOptsHdr->ucHdrExtLen;
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\nIPv6 DestOpts Header Header");
usNextHeaderOffset+= sizeof(IPV6DestOptionsHeader);
usNextHeaderOffset+= nTotalOptions * IPV6_DESTOPTS_HDR_OPTIONSIZE ;
}
break;
case IPV6HDR_TYPE_AUTHENTICATION:
{
IPV6AuthenticationHeader *pstIpv6AuthHdr = (IPV6AuthenticationHeader *)pucPayloadPtr;
int nHdrLen = pstIpv6AuthHdr->ucLength;
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\nIPv6 Authentication Header");
usNextHeaderOffset+= nHdrLen * 4;
}
break;
case IPV6HDR_TYPE_ENCRYPTEDSECURITYPAYLOAD:
{
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\nIPv6 Encrypted Security Payload Header");
*bParseDone = TRUE;
}
break;
case IPV6_ICMP_HDR_TYPE:
{
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, " ICMP Header");
*bParseDone = TRUE;
}
break;
case TCP_HEADER_TYPE:
{
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, " \nTCP Header");
*bParseDone = TRUE;
}
break;
case UDP_HEADER_TYPE:
{
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, " \nUDP Header");
*bParseDone = TRUE;
}
break;
default :
{
*bParseDone = TRUE;
}
break;
}
if(*bParseDone == FALSE)
{
if(*pusPayloadLength <= usNextHeaderOffset)
{
*bParseDone = TRUE;
}
else
{
*pucNextHeader = *pucPayloadPtr;
pucPayloadPtr+=usNextHeaderOffset;
(*pusPayloadLength)-=usNextHeaderOffset;
}
}
*ppucPayload = pucPayloadPtr;
return pucRetHeaderPtr;
}
static UCHAR GetIpv6ProtocolPorts(UCHAR *pucPayload,USHORT *pusSrcPort,USHORT *pusDestPort,USHORT usPayloadLength,UCHAR ucNextHeader)
{
UCHAR *pIpv6HdrScanContext = pucPayload;
BOOLEAN bDone = FALSE;
UCHAR ucHeaderType =0;
UCHAR *pucNextHeader = NULL;
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
if( !pucPayload || (usPayloadLength == 0))
{
return 0;
}
*pusSrcPort = *pusDestPort = 0;
ucHeaderType = ucNextHeader;
while(!bDone)
{
pucNextHeader = GetNextIPV6ChainedHeader(&pIpv6HdrScanContext,&ucHeaderType,&bDone,&usPayloadLength);
if(bDone)
{
if((ucHeaderType==TCP_HEADER_TYPE) || (ucHeaderType == UDP_HEADER_TYPE))
{
*pusSrcPort=*((PUSHORT)(pucNextHeader));
*pusDestPort=*((PUSHORT)(pucNextHeader+2));
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, " \nProtocol Ports - Src Port :0x%x Dest Port : 0x%x",ntohs(*pusSrcPort),ntohs(*pusDestPort));
}
break;
}
}
return ucHeaderType;
}
USHORT IpVersion6(PMINI_ADAPTER Adapter, /**< Pointer to the driver control structure */
PVOID pcIpHeader, /**<Pointer to the IP Hdr of the packet*/
S_CLASSIFIER_RULE *pstClassifierRule )
{
USHORT ushDestPort = 0;
USHORT ushSrcPort = 0;
UCHAR ucNextProtocolAboveIP =0;
IPV6Header *pstIpv6Header = NULL;
BOOLEAN bClassificationSucceed = FALSE;
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "IpVersion6 ==========>\n");
pstIpv6Header = (IPV6Header *)pcIpHeader;
DumpIpv6Header(pstIpv6Header);
//Try to get the next higher layer protocol and the Ports Nos if TCP or UDP
ucNextProtocolAboveIP = GetIpv6ProtocolPorts((UCHAR *)(pcIpHeader + sizeof(IPV6Header)),
&ushSrcPort,
&ushDestPort,
pstIpv6Header->usPayloadLength,
pstIpv6Header->ucNextHeader);
do
{
if(0 == pstClassifierRule->ucDirection)
{
//cannot be processed for classification.
// it is a down link connection
break;
}
if(!pstClassifierRule->bIpv6Protocol)
{
//We are looking for Ipv6 Classifiers . Lets ignore this classifier and try the next one.
break;
}
bClassificationSucceed=MatchSrcIpv6Address(pstClassifierRule,pstIpv6Header);
if(!bClassificationSucceed)
break;
bClassificationSucceed=MatchDestIpv6Address(pstClassifierRule,pstIpv6Header);
if(!bClassificationSucceed)
break;
//Match the protocol type.For IPv6 the next protocol at end of Chain of IPv6 prot headers
bClassificationSucceed=MatchProtocol(pstClassifierRule,ucNextProtocolAboveIP);
if(!bClassificationSucceed)
break;
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\nIPv6 Protocol Matched");
if((ucNextProtocolAboveIP == TCP_HEADER_TYPE) || (ucNextProtocolAboveIP == UDP_HEADER_TYPE))
{
//Match Src Port
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\nIPv6 Source Port:%x\n",ntohs(ushSrcPort));
bClassificationSucceed=MatchSrcPort(pstClassifierRule,ntohs(ushSrcPort));
if(!bClassificationSucceed)
break;
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\nIPv6 Src Port Matched");
//Match Dest Port
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\nIPv6 Destination Port:%x\n",ntohs(ushDestPort));
bClassificationSucceed=MatchDestPort(pstClassifierRule,ntohs(ushDestPort));
if(!bClassificationSucceed)
break;
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\nIPv6 Dest Port Matched");
}
}while(0);
if(TRUE==bClassificationSucceed)
{
INT iMatchedSFQueueIndex = 0;
iMatchedSFQueueIndex = SearchSfid(Adapter,pstClassifierRule->ulSFID);
if(iMatchedSFQueueIndex >= NO_OF_QUEUES)
{
bClassificationSucceed = FALSE;
}
else
{
if(FALSE == Adapter->PackInfo[iMatchedSFQueueIndex].bActive)
{
bClassificationSucceed = FALSE;
}
}
}
return bClassificationSucceed;
}
static BOOLEAN MatchSrcIpv6Address(S_CLASSIFIER_RULE *pstClassifierRule,IPV6Header *pstIpv6Header)
{
UINT uiLoopIndex=0;
UINT uiIpv6AddIndex=0;
UINT uiIpv6AddrNoLongWords = 4;
ULONG aulSrcIP[4];
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
/*
//This is the no. of Src Addresses ie Range of IP Addresses contained
//in the classifier rule for which we need to match
*/
UINT uiCountIPSrcAddresses = (UINT)pstClassifierRule->ucIPSourceAddressLength;
if(0 == uiCountIPSrcAddresses)
return TRUE;
//First Convert the Ip Address in the packet to Host Endian order
for(uiIpv6AddIndex=0;uiIpv6AddIndex<uiIpv6AddrNoLongWords;uiIpv6AddIndex++)
{
aulSrcIP[uiIpv6AddIndex]=ntohl(pstIpv6Header->ulSrcIpAddress[uiIpv6AddIndex]);
}
for(uiLoopIndex=0;uiLoopIndex<uiCountIPSrcAddresses;uiLoopIndex+=uiIpv6AddrNoLongWords)
{
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\n Src Ipv6 Address In Received Packet : \n ");
DumpIpv6Address(aulSrcIP);
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\n Src Ipv6 Mask In Classifier Rule: \n");
DumpIpv6Address(&pstClassifierRule->stSrcIpAddress.ulIpv6Mask[uiLoopIndex]);
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\n Src Ipv6 Address In Classifier Rule : \n");
DumpIpv6Address(&pstClassifierRule->stSrcIpAddress.ulIpv6Addr[uiLoopIndex]);
for(uiIpv6AddIndex=0;uiIpv6AddIndex<uiIpv6AddrNoLongWords;uiIpv6AddIndex++)
{
if((pstClassifierRule->stSrcIpAddress.ulIpv6Mask[uiLoopIndex+uiIpv6AddIndex] & aulSrcIP[uiIpv6AddIndex])
!= pstClassifierRule->stSrcIpAddress.ulIpv6Addr[uiLoopIndex+uiIpv6AddIndex])
{
//Match failed for current Ipv6 Address.Try next Ipv6 Address
break;
}
if(uiIpv6AddIndex == uiIpv6AddrNoLongWords-1)
{
//Match Found
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "Ipv6 Src Ip Address Matched\n");
return TRUE;
}
}
}
return FALSE;
}
static BOOLEAN MatchDestIpv6Address(S_CLASSIFIER_RULE *pstClassifierRule,IPV6Header *pstIpv6Header)
{
UINT uiLoopIndex=0;
UINT uiIpv6AddIndex=0;
UINT uiIpv6AddrNoLongWords = 4;
ULONG aulDestIP[4];
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
/*
//This is the no. of Destination Addresses ie Range of IP Addresses contained
//in the classifier rule for which we need to match
*/
UINT uiCountIPDestinationAddresses = (UINT)pstClassifierRule->ucIPDestinationAddressLength;
if(0 == uiCountIPDestinationAddresses)
return TRUE;
//First Convert the Ip Address in the packet to Host Endian order
for(uiIpv6AddIndex=0;uiIpv6AddIndex<uiIpv6AddrNoLongWords;uiIpv6AddIndex++)
{
aulDestIP[uiIpv6AddIndex]=ntohl(pstIpv6Header->ulDestIpAddress[uiIpv6AddIndex]);
}
for(uiLoopIndex=0;uiLoopIndex<uiCountIPDestinationAddresses;uiLoopIndex+=uiIpv6AddrNoLongWords)
{
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\n Destination Ipv6 Address In Received Packet : \n ");
DumpIpv6Address(aulDestIP);
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\n Destination Ipv6 Mask In Classifier Rule: \n");
DumpIpv6Address(&pstClassifierRule->stDestIpAddress.ulIpv6Mask[uiLoopIndex]);
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\n Destination Ipv6 Address In Classifier Rule : \n");
DumpIpv6Address(&pstClassifierRule->stDestIpAddress.ulIpv6Addr[uiLoopIndex]);
for(uiIpv6AddIndex=0;uiIpv6AddIndex<uiIpv6AddrNoLongWords;uiIpv6AddIndex++)
{
if((pstClassifierRule->stDestIpAddress.ulIpv6Mask[uiLoopIndex+uiIpv6AddIndex] & aulDestIP[uiIpv6AddIndex])
!= pstClassifierRule->stDestIpAddress.ulIpv6Addr[uiLoopIndex+uiIpv6AddIndex])
{
//Match failed for current Ipv6 Address.Try next Ipv6 Address
break;
}
if(uiIpv6AddIndex == uiIpv6AddrNoLongWords-1)
{
//Match Found
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "Ipv6 Destination Ip Address Matched\n");
return TRUE;
}
}
}
return FALSE;
}
VOID DumpIpv6Address(ULONG *puIpv6Address)
{
UINT uiIpv6AddrNoLongWords = 4;
UINT uiIpv6AddIndex=0;
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
for(uiIpv6AddIndex=0;uiIpv6AddIndex<uiIpv6AddrNoLongWords;uiIpv6AddIndex++)
{
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, ":%lx",puIpv6Address[uiIpv6AddIndex]);
}
}
static VOID DumpIpv6Header(IPV6Header *pstIpv6Header)
{
UCHAR ucVersion;
UCHAR ucPrio ;
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "----Ipv6 Header---");
ucVersion = pstIpv6Header->ucVersionPrio & 0xf0;
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "Version : %x \n",ucVersion);
ucPrio = pstIpv6Header->ucVersionPrio & 0x0f;
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "Priority : %x \n",ucPrio);
//BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "Flow Label : %x \n",(pstIpv6Header->ucVersionPrio &0xf0);
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "Payload Length : %x \n",ntohs(pstIpv6Header->usPayloadLength));
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "Next Header : %x \n",pstIpv6Header->ucNextHeader);
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "Hop Limit : %x \n",pstIpv6Header->ucHopLimit);
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "Src Address :\n");
DumpIpv6Address(pstIpv6Header->ulSrcIpAddress);
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "Dest Address :\n");
DumpIpv6Address(pstIpv6Header->ulDestIpAddress);
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "----Ipv6 Header End---");
}
| gpl-2.0 |
iodak/p920-ICS-kernel | drivers/staging/bcm/IPv6Protocol.c | 7987 | 12961 | #include "headers.h"
static BOOLEAN MatchSrcIpv6Address(S_CLASSIFIER_RULE *pstClassifierRule,IPV6Header *pstIpv6Header);
static BOOLEAN MatchDestIpv6Address(S_CLASSIFIER_RULE *pstClassifierRule,IPV6Header *pstIpv6Header);
static VOID DumpIpv6Header(IPV6Header *pstIpv6Header);
static UCHAR * GetNextIPV6ChainedHeader(UCHAR **ppucPayload,UCHAR *pucNextHeader,BOOLEAN *bParseDone,USHORT *pusPayloadLength)
{
UCHAR *pucRetHeaderPtr = NULL;
UCHAR *pucPayloadPtr = NULL;
USHORT usNextHeaderOffset = 0 ;
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
if((NULL == ppucPayload) || (*pusPayloadLength == 0) || (*bParseDone))
{
*bParseDone = TRUE;
return NULL;
}
pucRetHeaderPtr = *ppucPayload;
pucPayloadPtr = *ppucPayload;
if(!pucRetHeaderPtr || !pucPayloadPtr)
{
*bParseDone = TRUE;
return NULL;
}
//Get the Nextt Header Type
*bParseDone = FALSE;
switch(*pucNextHeader)
{
case IPV6HDR_TYPE_HOPBYHOP:
{
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\nIPv6 HopByHop Header");
usNextHeaderOffset+=sizeof(IPV6HopByHopOptionsHeader);
}
break;
case IPV6HDR_TYPE_ROUTING:
{
IPV6RoutingHeader *pstIpv6RoutingHeader;
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\nIPv6 Routing Header");
pstIpv6RoutingHeader = (IPV6RoutingHeader *)pucPayloadPtr;
usNextHeaderOffset += sizeof(IPV6RoutingHeader);
usNextHeaderOffset += pstIpv6RoutingHeader->ucNumAddresses * IPV6_ADDRESS_SIZEINBYTES;
}
break;
case IPV6HDR_TYPE_FRAGMENTATION:
{
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\nIPv6 Fragmentation Header");
usNextHeaderOffset+= sizeof(IPV6FragmentHeader);
}
break;
case IPV6HDR_TYPE_DESTOPTS:
{
IPV6DestOptionsHeader *pstIpv6DestOptsHdr = (IPV6DestOptionsHeader *)pucPayloadPtr;
int nTotalOptions = pstIpv6DestOptsHdr->ucHdrExtLen;
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\nIPv6 DestOpts Header Header");
usNextHeaderOffset+= sizeof(IPV6DestOptionsHeader);
usNextHeaderOffset+= nTotalOptions * IPV6_DESTOPTS_HDR_OPTIONSIZE ;
}
break;
case IPV6HDR_TYPE_AUTHENTICATION:
{
IPV6AuthenticationHeader *pstIpv6AuthHdr = (IPV6AuthenticationHeader *)pucPayloadPtr;
int nHdrLen = pstIpv6AuthHdr->ucLength;
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\nIPv6 Authentication Header");
usNextHeaderOffset+= nHdrLen * 4;
}
break;
case IPV6HDR_TYPE_ENCRYPTEDSECURITYPAYLOAD:
{
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\nIPv6 Encrypted Security Payload Header");
*bParseDone = TRUE;
}
break;
case IPV6_ICMP_HDR_TYPE:
{
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, " ICMP Header");
*bParseDone = TRUE;
}
break;
case TCP_HEADER_TYPE:
{
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, " \nTCP Header");
*bParseDone = TRUE;
}
break;
case UDP_HEADER_TYPE:
{
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, " \nUDP Header");
*bParseDone = TRUE;
}
break;
default :
{
*bParseDone = TRUE;
}
break;
}
if(*bParseDone == FALSE)
{
if(*pusPayloadLength <= usNextHeaderOffset)
{
*bParseDone = TRUE;
}
else
{
*pucNextHeader = *pucPayloadPtr;
pucPayloadPtr+=usNextHeaderOffset;
(*pusPayloadLength)-=usNextHeaderOffset;
}
}
*ppucPayload = pucPayloadPtr;
return pucRetHeaderPtr;
}
static UCHAR GetIpv6ProtocolPorts(UCHAR *pucPayload,USHORT *pusSrcPort,USHORT *pusDestPort,USHORT usPayloadLength,UCHAR ucNextHeader)
{
UCHAR *pIpv6HdrScanContext = pucPayload;
BOOLEAN bDone = FALSE;
UCHAR ucHeaderType =0;
UCHAR *pucNextHeader = NULL;
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
if( !pucPayload || (usPayloadLength == 0))
{
return 0;
}
*pusSrcPort = *pusDestPort = 0;
ucHeaderType = ucNextHeader;
while(!bDone)
{
pucNextHeader = GetNextIPV6ChainedHeader(&pIpv6HdrScanContext,&ucHeaderType,&bDone,&usPayloadLength);
if(bDone)
{
if((ucHeaderType==TCP_HEADER_TYPE) || (ucHeaderType == UDP_HEADER_TYPE))
{
*pusSrcPort=*((PUSHORT)(pucNextHeader));
*pusDestPort=*((PUSHORT)(pucNextHeader+2));
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, " \nProtocol Ports - Src Port :0x%x Dest Port : 0x%x",ntohs(*pusSrcPort),ntohs(*pusDestPort));
}
break;
}
}
return ucHeaderType;
}
USHORT IpVersion6(PMINI_ADAPTER Adapter, /**< Pointer to the driver control structure */
PVOID pcIpHeader, /**<Pointer to the IP Hdr of the packet*/
S_CLASSIFIER_RULE *pstClassifierRule )
{
USHORT ushDestPort = 0;
USHORT ushSrcPort = 0;
UCHAR ucNextProtocolAboveIP =0;
IPV6Header *pstIpv6Header = NULL;
BOOLEAN bClassificationSucceed = FALSE;
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "IpVersion6 ==========>\n");
pstIpv6Header = (IPV6Header *)pcIpHeader;
DumpIpv6Header(pstIpv6Header);
//Try to get the next higher layer protocol and the Ports Nos if TCP or UDP
ucNextProtocolAboveIP = GetIpv6ProtocolPorts((UCHAR *)(pcIpHeader + sizeof(IPV6Header)),
&ushSrcPort,
&ushDestPort,
pstIpv6Header->usPayloadLength,
pstIpv6Header->ucNextHeader);
do
{
if(0 == pstClassifierRule->ucDirection)
{
//cannot be processed for classification.
// it is a down link connection
break;
}
if(!pstClassifierRule->bIpv6Protocol)
{
//We are looking for Ipv6 Classifiers . Lets ignore this classifier and try the next one.
break;
}
bClassificationSucceed=MatchSrcIpv6Address(pstClassifierRule,pstIpv6Header);
if(!bClassificationSucceed)
break;
bClassificationSucceed=MatchDestIpv6Address(pstClassifierRule,pstIpv6Header);
if(!bClassificationSucceed)
break;
//Match the protocol type.For IPv6 the next protocol at end of Chain of IPv6 prot headers
bClassificationSucceed=MatchProtocol(pstClassifierRule,ucNextProtocolAboveIP);
if(!bClassificationSucceed)
break;
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\nIPv6 Protocol Matched");
if((ucNextProtocolAboveIP == TCP_HEADER_TYPE) || (ucNextProtocolAboveIP == UDP_HEADER_TYPE))
{
//Match Src Port
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\nIPv6 Source Port:%x\n",ntohs(ushSrcPort));
bClassificationSucceed=MatchSrcPort(pstClassifierRule,ntohs(ushSrcPort));
if(!bClassificationSucceed)
break;
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\nIPv6 Src Port Matched");
//Match Dest Port
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\nIPv6 Destination Port:%x\n",ntohs(ushDestPort));
bClassificationSucceed=MatchDestPort(pstClassifierRule,ntohs(ushDestPort));
if(!bClassificationSucceed)
break;
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\nIPv6 Dest Port Matched");
}
}while(0);
if(TRUE==bClassificationSucceed)
{
INT iMatchedSFQueueIndex = 0;
iMatchedSFQueueIndex = SearchSfid(Adapter,pstClassifierRule->ulSFID);
if(iMatchedSFQueueIndex >= NO_OF_QUEUES)
{
bClassificationSucceed = FALSE;
}
else
{
if(FALSE == Adapter->PackInfo[iMatchedSFQueueIndex].bActive)
{
bClassificationSucceed = FALSE;
}
}
}
return bClassificationSucceed;
}
static BOOLEAN MatchSrcIpv6Address(S_CLASSIFIER_RULE *pstClassifierRule,IPV6Header *pstIpv6Header)
{
UINT uiLoopIndex=0;
UINT uiIpv6AddIndex=0;
UINT uiIpv6AddrNoLongWords = 4;
ULONG aulSrcIP[4];
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
/*
//This is the no. of Src Addresses ie Range of IP Addresses contained
//in the classifier rule for which we need to match
*/
UINT uiCountIPSrcAddresses = (UINT)pstClassifierRule->ucIPSourceAddressLength;
if(0 == uiCountIPSrcAddresses)
return TRUE;
//First Convert the Ip Address in the packet to Host Endian order
for(uiIpv6AddIndex=0;uiIpv6AddIndex<uiIpv6AddrNoLongWords;uiIpv6AddIndex++)
{
aulSrcIP[uiIpv6AddIndex]=ntohl(pstIpv6Header->ulSrcIpAddress[uiIpv6AddIndex]);
}
for(uiLoopIndex=0;uiLoopIndex<uiCountIPSrcAddresses;uiLoopIndex+=uiIpv6AddrNoLongWords)
{
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\n Src Ipv6 Address In Received Packet : \n ");
DumpIpv6Address(aulSrcIP);
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\n Src Ipv6 Mask In Classifier Rule: \n");
DumpIpv6Address(&pstClassifierRule->stSrcIpAddress.ulIpv6Mask[uiLoopIndex]);
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\n Src Ipv6 Address In Classifier Rule : \n");
DumpIpv6Address(&pstClassifierRule->stSrcIpAddress.ulIpv6Addr[uiLoopIndex]);
for(uiIpv6AddIndex=0;uiIpv6AddIndex<uiIpv6AddrNoLongWords;uiIpv6AddIndex++)
{
if((pstClassifierRule->stSrcIpAddress.ulIpv6Mask[uiLoopIndex+uiIpv6AddIndex] & aulSrcIP[uiIpv6AddIndex])
!= pstClassifierRule->stSrcIpAddress.ulIpv6Addr[uiLoopIndex+uiIpv6AddIndex])
{
//Match failed for current Ipv6 Address.Try next Ipv6 Address
break;
}
if(uiIpv6AddIndex == uiIpv6AddrNoLongWords-1)
{
//Match Found
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "Ipv6 Src Ip Address Matched\n");
return TRUE;
}
}
}
return FALSE;
}
static BOOLEAN MatchDestIpv6Address(S_CLASSIFIER_RULE *pstClassifierRule,IPV6Header *pstIpv6Header)
{
UINT uiLoopIndex=0;
UINT uiIpv6AddIndex=0;
UINT uiIpv6AddrNoLongWords = 4;
ULONG aulDestIP[4];
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
/*
//This is the no. of Destination Addresses ie Range of IP Addresses contained
//in the classifier rule for which we need to match
*/
UINT uiCountIPDestinationAddresses = (UINT)pstClassifierRule->ucIPDestinationAddressLength;
if(0 == uiCountIPDestinationAddresses)
return TRUE;
//First Convert the Ip Address in the packet to Host Endian order
for(uiIpv6AddIndex=0;uiIpv6AddIndex<uiIpv6AddrNoLongWords;uiIpv6AddIndex++)
{
aulDestIP[uiIpv6AddIndex]=ntohl(pstIpv6Header->ulDestIpAddress[uiIpv6AddIndex]);
}
for(uiLoopIndex=0;uiLoopIndex<uiCountIPDestinationAddresses;uiLoopIndex+=uiIpv6AddrNoLongWords)
{
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\n Destination Ipv6 Address In Received Packet : \n ");
DumpIpv6Address(aulDestIP);
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\n Destination Ipv6 Mask In Classifier Rule: \n");
DumpIpv6Address(&pstClassifierRule->stDestIpAddress.ulIpv6Mask[uiLoopIndex]);
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "\n Destination Ipv6 Address In Classifier Rule : \n");
DumpIpv6Address(&pstClassifierRule->stDestIpAddress.ulIpv6Addr[uiLoopIndex]);
for(uiIpv6AddIndex=0;uiIpv6AddIndex<uiIpv6AddrNoLongWords;uiIpv6AddIndex++)
{
if((pstClassifierRule->stDestIpAddress.ulIpv6Mask[uiLoopIndex+uiIpv6AddIndex] & aulDestIP[uiIpv6AddIndex])
!= pstClassifierRule->stDestIpAddress.ulIpv6Addr[uiLoopIndex+uiIpv6AddIndex])
{
//Match failed for current Ipv6 Address.Try next Ipv6 Address
break;
}
if(uiIpv6AddIndex == uiIpv6AddrNoLongWords-1)
{
//Match Found
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "Ipv6 Destination Ip Address Matched\n");
return TRUE;
}
}
}
return FALSE;
}
VOID DumpIpv6Address(ULONG *puIpv6Address)
{
UINT uiIpv6AddrNoLongWords = 4;
UINT uiIpv6AddIndex=0;
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
for(uiIpv6AddIndex=0;uiIpv6AddIndex<uiIpv6AddrNoLongWords;uiIpv6AddIndex++)
{
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, ":%lx",puIpv6Address[uiIpv6AddIndex]);
}
}
static VOID DumpIpv6Header(IPV6Header *pstIpv6Header)
{
UCHAR ucVersion;
UCHAR ucPrio ;
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "----Ipv6 Header---");
ucVersion = pstIpv6Header->ucVersionPrio & 0xf0;
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "Version : %x \n",ucVersion);
ucPrio = pstIpv6Header->ucVersionPrio & 0x0f;
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "Priority : %x \n",ucPrio);
//BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "Flow Label : %x \n",(pstIpv6Header->ucVersionPrio &0xf0);
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "Payload Length : %x \n",ntohs(pstIpv6Header->usPayloadLength));
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "Next Header : %x \n",pstIpv6Header->ucNextHeader);
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "Hop Limit : %x \n",pstIpv6Header->ucHopLimit);
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "Src Address :\n");
DumpIpv6Address(pstIpv6Header->ulSrcIpAddress);
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "Dest Address :\n");
DumpIpv6Address(pstIpv6Header->ulDestIpAddress);
BCM_DEBUG_PRINT( Adapter,DBG_TYPE_TX, IPV6_DBG, DBG_LVL_ALL, "----Ipv6 Header End---");
}
| gpl-2.0 |
Advael/fjord-kernel | drivers/video/via/via_aux_vt1621.c | 9779 | 1224 | /*
* Copyright 2011 Florian Tobias Schandinat <FlorianSchandinat@gmx.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, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTIES OR REPRESENTATIONS; 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.
*/
/*
* driver for VIA VT1621(M) TV Encoder
*/
#include <linux/slab.h>
#include "via_aux.h"
static const char *name = "VT1621(M) TV Encoder";
void via_aux_vt1621_probe(struct via_aux_bus *bus)
{
struct via_aux_drv drv = {
.bus = bus,
.addr = 0x20,
.name = name};
u8 tmp;
if (!via_aux_read(&drv, 0x1B, &tmp, 1) || tmp != 0x02)
return;
printk(KERN_INFO "viafb: Found %s\n", name);
via_aux_add(&drv);
}
| gpl-2.0 |
davidmueller13/f2fs-backport | arch/blackfin/mach-common/cache-c.c | 11059 | 1798 | /*
* Blackfin cache control code (simpler control-style functions)
*
* Copyright 2004-2009 Analog Devices Inc.
*
* Licensed under the GPL-2 or later.
*/
#include <linux/init.h>
#include <asm/blackfin.h>
#include <asm/cplbinit.h>
/* Invalidate the Entire Data cache by
* clearing DMC[1:0] bits
*/
void blackfin_invalidate_entire_dcache(void)
{
u32 dmem = bfin_read_DMEM_CONTROL();
bfin_write_DMEM_CONTROL(dmem & ~0xc);
SSYNC();
bfin_write_DMEM_CONTROL(dmem);
SSYNC();
}
/* Invalidate the Entire Instruction cache by
* clearing IMC bit
*/
void blackfin_invalidate_entire_icache(void)
{
u32 imem = bfin_read_IMEM_CONTROL();
bfin_write_IMEM_CONTROL(imem & ~0x4);
SSYNC();
bfin_write_IMEM_CONTROL(imem);
SSYNC();
}
#if defined(CONFIG_BFIN_ICACHE) || defined(CONFIG_BFIN_DCACHE)
static void
bfin_cache_init(struct cplb_entry *cplb_tbl, unsigned long cplb_addr,
unsigned long cplb_data, unsigned long mem_control,
unsigned long mem_mask)
{
int i;
for (i = 0; i < MAX_CPLBS; i++) {
bfin_write32(cplb_addr + i * 4, cplb_tbl[i].addr);
bfin_write32(cplb_data + i * 4, cplb_tbl[i].data);
}
_enable_cplb(mem_control, mem_mask);
}
#ifdef CONFIG_BFIN_ICACHE
void __cpuinit bfin_icache_init(struct cplb_entry *icplb_tbl)
{
bfin_cache_init(icplb_tbl, ICPLB_ADDR0, ICPLB_DATA0, IMEM_CONTROL,
(IMC | ENICPLB));
}
#endif
#ifdef CONFIG_BFIN_DCACHE
void __cpuinit bfin_dcache_init(struct cplb_entry *dcplb_tbl)
{
/*
* Anomaly notes:
* 05000287 - We implement workaround #2 - Change the DMEM_CONTROL
* register, so that the port preferences for DAG0 and DAG1 are set
* to port B
*/
bfin_cache_init(dcplb_tbl, DCPLB_ADDR0, DCPLB_DATA0, DMEM_CONTROL,
(DMEM_CNTR | PORT_PREF0 | (ANOMALY_05000287 ? PORT_PREF1 : 0)));
}
#endif
#endif
| gpl-2.0 |
MyAOSP/external_blktrace | btt/trace_plug.c | 52 | 1419 | /*
* blktrace output analysis: generate a timeline & gather statistics
*
* Copyright (C) 2007 Alan D. Brunelle <Alan.Brunelle@hp.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "globals.h"
static __u64 get_nio_up(struct io *u_iop)
{
__u64 *val = u_iop->pdu;
return be64_to_cpu(*val);
}
void trace_unplug_io(struct io *u_iop)
{
unplug_hist_add(u_iop);
dip_unplug(u_iop->t.device, BIT_TIME(u_iop->t.time), get_nio_up(u_iop));
io_release(u_iop);
}
void trace_unplug_timer(struct io *ut_iop)
{
dip_unplug_tm(ut_iop->t.device, BIT_TIME(ut_iop->t.time),
get_nio_up(ut_iop));
io_release(ut_iop);
}
void trace_plug(struct io *p_iop)
{
dip_plug(p_iop->t.device, BIT_TIME(p_iop->t.time));
io_release(p_iop);
}
| gpl-2.0 |
keshwans/vlc | modules/control/netsync.c | 52 | 9527 | /*****************************************************************************
* netsync.c: synchronization between several network clients.
*****************************************************************************
* Copyright (C) 2004-2009 the VideoLAN team
* $Id$
*
* Authors: Gildas Bazin <gbazin@videolan.org>
* Jean-Paul Saman <jpsaman@videolan.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.
*****************************************************************************/
/*****************************************************************************
* Preamble
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <assert.h>
#define VLC_MODULE_LICENSE VLC_LICENSE_GPL_2_PLUS
#include <vlc_common.h>
#include <vlc_plugin.h>
#include <vlc_interface.h>
#include <vlc_input.h>
#include <vlc_playlist.h>
#include <sys/types.h>
#include <unistd.h>
#ifdef HAVE_POLL
# include <poll.h>
#endif
#include <vlc_network.h>
#define NETSYNC_PORT 9875
/*****************************************************************************
* Module descriptor
*****************************************************************************/
static int Open (vlc_object_t *);
static void Close(vlc_object_t *);
#define NETSYNC_TEXT N_("Network master clock")
#define NETSYNC_LONGTEXT N_("When set, " \
"this VLC instance will act as the master clock for synchronization " \
"for clients listening")
#define MIP_TEXT N_("Master server IP address")
#define MIP_LONGTEXT N_("The IP address of " \
"the network master clock to use for clock synchronization.")
#define NETSYNC_TIMEOUT_TEXT N_("UDP timeout (in ms)")
#define NETSYNC_TIMEOUT_LONGTEXT N_("Length of time (in ms) " \
"until aborting data reception.")
vlc_module_begin()
set_shortname(N_("Network Sync"))
set_description(N_("Network synchronization"))
set_category(CAT_ADVANCED)
set_subcategory(SUBCAT_ADVANCED_MISC)
add_bool("netsync-master", false,
NETSYNC_TEXT, NETSYNC_LONGTEXT, true)
add_string("netsync-master-ip", NULL, MIP_TEXT, MIP_LONGTEXT,
true)
add_integer("netsync-timeout", 500,
NETSYNC_TIMEOUT_TEXT, NETSYNC_TIMEOUT_LONGTEXT, true)
set_capability("interface", 0)
set_callbacks(Open, Close)
vlc_module_end()
/*****************************************************************************
* Local prototypes
*****************************************************************************/
struct intf_sys_t {
int fd;
int timeout;
bool is_master;
playlist_t *playlist;
/* */
input_thread_t *input;
vlc_thread_t thread;
};
static int PlaylistEvent(vlc_object_t *, char const *cmd,
vlc_value_t oldval, vlc_value_t newval, void *data);
/*****************************************************************************
* Activate: initialize and create stuff
*****************************************************************************/
static int Open(vlc_object_t *object)
{
intf_thread_t *intf = (intf_thread_t*)object;
intf_sys_t *sys;
int fd;
if (!var_InheritBool(intf, "netsync-master")) {
char *psz_master = var_InheritString(intf, "netsync-master-ip");
if (psz_master == NULL) {
msg_Err(intf, "master address not specified");
return VLC_EGENERIC;
}
fd = net_ConnectUDP(VLC_OBJECT(intf), psz_master, NETSYNC_PORT, -1);
free(psz_master);
} else {
fd = net_ListenUDP1(VLC_OBJECT(intf), NULL, NETSYNC_PORT);
}
if (fd == -1) {
msg_Err(intf, "Netsync socket failure");
return VLC_EGENERIC;
}
intf->p_sys = sys = malloc(sizeof(*sys));
if (!sys) {
net_Close(fd);
return VLC_ENOMEM;
}
sys->fd = fd;
sys->is_master = var_InheritBool(intf, "netsync-master");
sys->timeout = var_InheritInteger(intf, "netsync-timeout");
if (sys->timeout < 500)
sys->timeout = 500;
sys->playlist = pl_Get(intf);
sys->input = NULL;
var_AddCallback(sys->playlist, "input-current", PlaylistEvent, intf);
return VLC_SUCCESS;
}
/*****************************************************************************
* Close: destroy interface
*****************************************************************************/
void Close(vlc_object_t *object)
{
intf_thread_t *intf = (intf_thread_t*)object;
intf_sys_t *sys = intf->p_sys;
var_DelCallback(sys->playlist, "input-current", PlaylistEvent, intf);
if (sys->input != NULL) {
vlc_cancel(sys->thread);
vlc_join(sys->thread, NULL);
}
net_Close(sys->fd);
free(sys);
}
static mtime_t GetPcrSystem(input_thread_t *input)
{
int canc = vlc_savecancel();
/* TODO use the delay */
mtime_t system;
if (input_GetPcrSystem(input, &system, NULL))
system = -1;
vlc_restorecancel(canc);
return system;
}
static void *Master(void *handle)
{
intf_thread_t *intf = handle;
intf_sys_t *sys = intf->p_sys;
for (;;) {
struct pollfd ufd = { .fd = sys->fd, .events = POLLIN, };
uint64_t data[2];
if (poll(&ufd, 1, -1) < 0)
continue;
/* We received something */
struct sockaddr_storage from;
socklen_t fromlen = sizeof (from);
if (recvfrom(sys->fd, data, 8, 0,
(struct sockaddr *)&from, &fromlen) < 8)
continue;
mtime_t master_system = GetPcrSystem(sys->input);
if (master_system < 0)
continue;
data[0] = hton64(mdate());
data[1] = hton64(master_system);
/* Reply to the sender */
sendto(sys->fd, data, 16, 0,
(struct sockaddr *)&from, fromlen);
#if 0
/* not sure we need the client information to sync,
since we are the master anyway */
mtime_t client_system = ntoh64(data[0]);
msg_Dbg(intf, "Master clockref: %"PRId64" -> %"PRId64", from %s "
"(date: %"PRId64")", client_system, master_system,
(from.ss_family == AF_INET) ? inet_ntoa(((struct sockaddr_in *)&from)->sin_addr)
: "non-IPv4", /*date*/ 0);
#endif
}
return NULL;
}
static void *Slave(void *handle)
{
intf_thread_t *intf = handle;
intf_sys_t *sys = intf->p_sys;
for (;;) {
struct pollfd ufd = { .fd = sys->fd, .events = POLLIN, };
uint64_t data[2];
mtime_t system = GetPcrSystem(sys->input);
if (system < 0)
goto wait;
/* Send clock request to the master */
const mtime_t send_date = mdate();
data[0] = hton64(system);
send(sys->fd, data, 8, 0);
/* Don't block */
if (poll(&ufd, 1, sys->timeout) <= 0)
continue;
const mtime_t receive_date = mdate();
if (recv(sys->fd, data, 16, 0) < 16)
goto wait;
const mtime_t master_date = ntoh64(data[0]);
const mtime_t master_system = ntoh64(data[1]);
const mtime_t diff_date = receive_date -
((receive_date - send_date) / 2 + master_date);
if (master_system > 0) {
int canc = vlc_savecancel();
mtime_t client_system;
if (!input_GetPcrSystem(sys->input, &client_system, NULL)) {
const mtime_t diff_system = client_system - master_system - diff_date;
if (diff_system != 0) {
input_ModifyPcrSystem(sys->input, true, master_system - diff_date);
#if 0
msg_Dbg(intf, "Slave clockref: %"PRId64" -> %"PRId64" -> %"PRId64","
" clock diff: %"PRId64", diff: %"PRId64"",
system, master_system, client_system,
diff_system, diff_date);
#endif
}
}
vlc_restorecancel(canc);
}
wait:
msleep(INTF_IDLE_SLEEP);
}
return NULL;
}
static int PlaylistEvent(vlc_object_t *object, char const *cmd,
vlc_value_t oldval, vlc_value_t newval, void *data)
{
VLC_UNUSED(cmd); VLC_UNUSED(object);
intf_thread_t *intf = data;
intf_sys_t *sys = intf->p_sys;
input_thread_t *input = newval.p_address;
if (sys->input != NULL) {
msg_Err(intf, "InputEvent DEAD");
assert(oldval.p_address == sys->input);
vlc_cancel(sys->thread);
vlc_join(sys->thread, NULL);
}
sys->input = input;
if (input != NULL) {
if (vlc_clone(&sys->thread, sys->is_master ? Master : Slave, intf,
VLC_THREAD_PRIORITY_INPUT))
sys->input = NULL;
}
return VLC_SUCCESS;
}
| gpl-2.0 |
MoKee/android_kernel_lge_msm8992 | drivers/devfreq/governor_cache_hwmon.c | 308 | 10286 | /*
* Copyright (c) 2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#define pr_fmt(fmt) "cache-hwmon: " fmt
#include <linux/kernel.h>
#include <linux/sizes.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <linux/ktime.h>
#include <linux/time.h>
#include <linux/err.h>
#include <linux/errno.h>
#include <linux/mutex.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/of.h>
#include <linux/devfreq.h>
#include "governor.h"
#include "governor_cache_hwmon.h"
struct cache_hwmon_node {
unsigned int cycles_per_low_req;
unsigned int cycles_per_med_req;
unsigned int cycles_per_high_req;
unsigned int min_busy;
unsigned int max_busy;
unsigned int tolerance_mrps;
unsigned int guard_band_mhz;
unsigned int decay_rate;
unsigned long prev_mhz;
ktime_t prev_ts;
bool mon_started;
struct list_head list;
void *orig_data;
struct cache_hwmon *hw;
struct attribute_group *attr_grp;
};
static LIST_HEAD(cache_hwmon_list);
static DEFINE_MUTEX(list_lock);
static int use_cnt;
static DEFINE_MUTEX(state_lock);
#define show_attr(name) \
static ssize_t show_##name(struct device *dev, \
struct device_attribute *attr, char *buf) \
{ \
struct devfreq *df = to_devfreq(dev); \
struct cache_hwmon_node *hw = df->data; \
return snprintf(buf, PAGE_SIZE, "%u\n", hw->name); \
}
#define store_attr(name, _min, _max) \
static ssize_t store_##name(struct device *dev, \
struct device_attribute *attr, const char *buf, \
size_t count) \
{ \
int ret; \
unsigned int val; \
struct devfreq *df = to_devfreq(dev); \
struct cache_hwmon_node *hw = df->data; \
ret = sscanf(buf, "%u", &val); \
if (ret != 1) \
return -EINVAL; \
val = max(val, _min); \
val = min(val, _max); \
hw->name = val; \
return count; \
}
#define gov_attr(__attr, min, max) \
show_attr(__attr) \
store_attr(__attr, min, max) \
static DEVICE_ATTR(__attr, 0644, show_##__attr, store_##__attr)
#define MIN_MS 10U
#define MAX_MS 500U
static struct cache_hwmon_node *find_hwmon_node(struct devfreq *df)
{
struct cache_hwmon_node *node, *found = NULL;
mutex_lock(&list_lock);
list_for_each_entry(node, &cache_hwmon_list, list)
if (node->hw->dev == df->dev.parent ||
node->hw->of_node == df->dev.parent->of_node) {
found = node;
break;
}
mutex_unlock(&list_lock);
return found;
}
static unsigned long measure_mrps_and_set_irq(struct cache_hwmon_node *node,
struct mrps_stats *stat)
{
ktime_t ts;
unsigned int us;
struct cache_hwmon *hw = node->hw;
/*
* Since we are stopping the counters, we don't want this short work
* to be interrupted by other tasks and cause the measurements to be
* wrong. Not blocking interrupts to avoid affecting interrupt
* latency and since they should be short anyway because they run in
* atomic context.
*/
preempt_disable();
ts = ktime_get();
us = ktime_to_us(ktime_sub(ts, node->prev_ts));
if (!us)
us = 1;
hw->meas_mrps_and_set_irq(hw, node->tolerance_mrps, us, stat);
node->prev_ts = ts;
preempt_enable();
dev_dbg(hw->df->dev.parent,
"stat H=%3lu, M=%3lu, L=%3lu, T=%3lu, b=%3u, f=%4lu, us=%d\n",
stat->mrps[HIGH], stat->mrps[MED], stat->mrps[LOW],
stat->mrps[HIGH] + stat->mrps[MED] + stat->mrps[LOW],
stat->busy_percent, hw->df->previous_freq / 1000, us);
return 0;
}
static void compute_cache_freq(struct cache_hwmon_node *node,
struct mrps_stats *mrps, unsigned long *freq)
{
unsigned long new_mhz;
unsigned int busy;
new_mhz = mrps->mrps[HIGH] * node->cycles_per_high_req
+ mrps->mrps[MED] * node->cycles_per_med_req
+ mrps->mrps[LOW] * node->cycles_per_low_req;
busy = max(node->min_busy, mrps->busy_percent);
busy = min(node->max_busy, busy);
new_mhz *= 100;
new_mhz /= busy;
if (new_mhz < node->prev_mhz) {
new_mhz = new_mhz * node->decay_rate + node->prev_mhz
* (100 - node->decay_rate);
new_mhz /= 100;
}
node->prev_mhz = new_mhz;
new_mhz += node->guard_band_mhz;
*freq = new_mhz * 1000;
}
#define TOO_SOON_US (1 * USEC_PER_MSEC)
int update_cache_hwmon(struct cache_hwmon *hwmon)
{
struct cache_hwmon_node *node;
struct devfreq *df;
ktime_t ts;
unsigned int us;
int ret;
if (!hwmon)
return -EINVAL;
df = hwmon->df;
if (!df)
return -ENODEV;
node = df->data;
if (!node)
return -ENODEV;
if (!node->mon_started)
return -EBUSY;
dev_dbg(df->dev.parent, "Got update request\n");
devfreq_monitor_stop(df);
/*
* Don't recalc cache freq if the interrupt comes right after a
* previous cache freq calculation. This is done for two reasons:
*
* 1. Sampling the cache request during a very short duration can
* result in a very inaccurate measurement due to very short
* bursts.
* 2. This can only happen if the limit was hit very close to the end
* of the previous sample period. Which means the current cache
* request estimate is not very off and doesn't need to be
* readjusted.
*/
ts = ktime_get();
us = ktime_to_us(ktime_sub(ts, node->prev_ts));
if (us > TOO_SOON_US) {
mutex_lock(&df->lock);
ret = update_devfreq(df);
if (ret)
dev_err(df->dev.parent,
"Unable to update freq on request!\n");
mutex_unlock(&df->lock);
}
devfreq_monitor_start(df);
return 0;
}
static int devfreq_cache_hwmon_get_freq(struct devfreq *df,
unsigned long *freq,
u32 *flag)
{
struct mrps_stats stat;
struct cache_hwmon_node *node = df->data;
memset(&stat, 0, sizeof(stat));
measure_mrps_and_set_irq(node, &stat);
compute_cache_freq(node, &stat, freq);
return 0;
}
gov_attr(cycles_per_low_req, 1U, 100U);
gov_attr(cycles_per_med_req, 1U, 100U);
gov_attr(cycles_per_high_req, 1U, 100U);
gov_attr(min_busy, 1U, 100U);
gov_attr(max_busy, 1U, 100U);
gov_attr(tolerance_mrps, 0U, 100U);
gov_attr(guard_band_mhz, 0U, 500U);
gov_attr(decay_rate, 0U, 100U);
static struct attribute *dev_attr[] = {
&dev_attr_cycles_per_low_req.attr,
&dev_attr_cycles_per_med_req.attr,
&dev_attr_cycles_per_high_req.attr,
&dev_attr_min_busy.attr,
&dev_attr_max_busy.attr,
&dev_attr_tolerance_mrps.attr,
&dev_attr_guard_band_mhz.attr,
&dev_attr_decay_rate.attr,
NULL,
};
static struct attribute_group dev_attr_group = {
.name = "cache_hwmon",
.attrs = dev_attr,
};
static int start_monitoring(struct devfreq *df)
{
int ret;
struct mrps_stats mrps;
struct device *dev = df->dev.parent;
struct cache_hwmon_node *node;
struct cache_hwmon *hw;
node = find_hwmon_node(df);
if (!node) {
dev_err(dev, "Unable to find HW monitor!\n");
return -ENODEV;
}
hw = node->hw;
hw->df = df;
node->orig_data = df->data;
df->data = node;
node->prev_ts = ktime_get();
node->prev_mhz = 0;
mrps.mrps[HIGH] = (df->previous_freq / 1000) - node->guard_band_mhz;
mrps.mrps[HIGH] /= node->cycles_per_high_req;
mrps.mrps[MED] = mrps.mrps[LOW] = 0;
ret = hw->start_hwmon(hw, &mrps);
if (ret) {
dev_err(dev, "Unable to start HW monitor!\n");
goto err_start;
}
devfreq_monitor_start(df);
node->mon_started = true;
ret = sysfs_create_group(&df->dev.kobj, &dev_attr_group);
if (ret) {
dev_err(dev, "Error creating sys entries!\n");
goto sysfs_fail;
}
return 0;
sysfs_fail:
node->mon_started = false;
devfreq_monitor_stop(df);
hw->stop_hwmon(hw);
err_start:
df->data = node->orig_data;
node->orig_data = NULL;
hw->df = NULL;
return ret;
}
static void stop_monitoring(struct devfreq *df)
{
struct cache_hwmon_node *node = df->data;
struct cache_hwmon *hw = node->hw;
sysfs_remove_group(&df->dev.kobj, &dev_attr_group);
node->mon_started = false;
devfreq_monitor_stop(df);
hw->stop_hwmon(hw);
df->data = node->orig_data;
node->orig_data = NULL;
hw->df = NULL;
}
static int devfreq_cache_hwmon_ev_handler(struct devfreq *df,
unsigned int event, void *data)
{
int ret;
unsigned int sample_ms;
switch (event) {
case DEVFREQ_GOV_START:
sample_ms = df->profile->polling_ms;
sample_ms = max(MIN_MS, sample_ms);
sample_ms = min(MAX_MS, sample_ms);
df->profile->polling_ms = sample_ms;
ret = start_monitoring(df);
if (ret)
return ret;
dev_dbg(df->dev.parent, "Enabled Cache HW monitor governor\n");
break;
case DEVFREQ_GOV_STOP:
stop_monitoring(df);
dev_dbg(df->dev.parent, "Disabled Cache HW monitor governor\n");
break;
case DEVFREQ_GOV_INTERVAL:
sample_ms = *(unsigned int *)data;
sample_ms = max(MIN_MS, sample_ms);
sample_ms = min(MAX_MS, sample_ms);
devfreq_interval_update(df, &sample_ms);
break;
}
return 0;
}
static struct devfreq_governor devfreq_cache_hwmon = {
.name = "cache_hwmon",
.get_target_freq = devfreq_cache_hwmon_get_freq,
.event_handler = devfreq_cache_hwmon_ev_handler,
};
int register_cache_hwmon(struct device *dev, struct cache_hwmon *hwmon)
{
int ret = 0;
struct cache_hwmon_node *node;
if (!hwmon->dev && !hwmon->of_node)
return -EINVAL;
node = devm_kzalloc(dev, sizeof(*node), GFP_KERNEL);
if (!node) {
dev_err(dev, "Unable to register gov. Out of memory!\n");
return -ENOMEM;
}
node->cycles_per_med_req = 20;
node->cycles_per_high_req = 35;
node->min_busy = 100;
node->max_busy = 100;
node->tolerance_mrps = 5;
node->guard_band_mhz = 100;
node->decay_rate = 90;
node->hw = hwmon;
node->attr_grp = &dev_attr_group;
mutex_lock(&state_lock);
if (!use_cnt) {
ret = devfreq_add_governor(&devfreq_cache_hwmon);
if (!ret)
use_cnt++;
}
mutex_unlock(&state_lock);
if (!ret) {
dev_info(dev, "Cache HWmon governor registered.\n");
} else {
dev_err(dev, "Failed to add Cache HWmon governor\n");
return ret;
}
mutex_lock(&list_lock);
list_add_tail(&node->list, &cache_hwmon_list);
mutex_unlock(&list_lock);
return ret;
}
MODULE_DESCRIPTION("HW monitor based cache freq driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
KingLiuDao/linux | sound/usb/line6/capture.c | 1076 | 6871 | /*
* Line 6 Linux USB driver
*
* Copyright (C) 2004-2010 Markus Grabner (grabner@icg.tugraz.at)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 2.
*
*/
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include "capture.h"
#include "driver.h"
#include "pcm.h"
/*
Find a free URB and submit it.
must be called in line6pcm->in.lock context
*/
static int submit_audio_in_urb(struct snd_line6_pcm *line6pcm)
{
int index;
int i, urb_size;
int ret;
struct urb *urb_in;
index =
find_first_zero_bit(&line6pcm->in.active_urbs, LINE6_ISO_BUFFERS);
if (index < 0 || index >= LINE6_ISO_BUFFERS) {
dev_err(line6pcm->line6->ifcdev, "no free URB found\n");
return -EINVAL;
}
urb_in = line6pcm->in.urbs[index];
urb_size = 0;
for (i = 0; i < LINE6_ISO_PACKETS; ++i) {
struct usb_iso_packet_descriptor *fin =
&urb_in->iso_frame_desc[i];
fin->offset = urb_size;
fin->length = line6pcm->max_packet_size;
urb_size += line6pcm->max_packet_size;
}
urb_in->transfer_buffer =
line6pcm->in.buffer +
index * LINE6_ISO_PACKETS * line6pcm->max_packet_size;
urb_in->transfer_buffer_length = urb_size;
urb_in->context = line6pcm;
ret = usb_submit_urb(urb_in, GFP_ATOMIC);
if (ret == 0)
set_bit(index, &line6pcm->in.active_urbs);
else
dev_err(line6pcm->line6->ifcdev,
"URB in #%d submission failed (%d)\n", index, ret);
return 0;
}
/*
Submit all currently available capture URBs.
must be called in line6pcm->in.lock context
*/
int line6_submit_audio_in_all_urbs(struct snd_line6_pcm *line6pcm)
{
int ret = 0, i;
for (i = 0; i < LINE6_ISO_BUFFERS; ++i) {
ret = submit_audio_in_urb(line6pcm);
if (ret < 0)
break;
}
return ret;
}
/*
Copy data into ALSA capture buffer.
*/
void line6_capture_copy(struct snd_line6_pcm *line6pcm, char *fbuf, int fsize)
{
struct snd_pcm_substream *substream =
get_substream(line6pcm, SNDRV_PCM_STREAM_CAPTURE);
struct snd_pcm_runtime *runtime = substream->runtime;
const int bytes_per_frame = line6pcm->properties->bytes_per_frame;
int frames = fsize / bytes_per_frame;
if (runtime == NULL)
return;
if (line6pcm->in.pos_done + frames > runtime->buffer_size) {
/*
The transferred area goes over buffer boundary,
copy two separate chunks.
*/
int len;
len = runtime->buffer_size - line6pcm->in.pos_done;
if (len > 0) {
memcpy(runtime->dma_area +
line6pcm->in.pos_done * bytes_per_frame, fbuf,
len * bytes_per_frame);
memcpy(runtime->dma_area, fbuf + len * bytes_per_frame,
(frames - len) * bytes_per_frame);
} else {
/* this is somewhat paranoid */
dev_err(line6pcm->line6->ifcdev,
"driver bug: len = %d\n", len);
}
} else {
/* copy single chunk */
memcpy(runtime->dma_area +
line6pcm->in.pos_done * bytes_per_frame, fbuf, fsize);
}
line6pcm->in.pos_done += frames;
if (line6pcm->in.pos_done >= runtime->buffer_size)
line6pcm->in.pos_done -= runtime->buffer_size;
}
void line6_capture_check_period(struct snd_line6_pcm *line6pcm, int length)
{
struct snd_pcm_substream *substream =
get_substream(line6pcm, SNDRV_PCM_STREAM_CAPTURE);
line6pcm->in.bytes += length;
if (line6pcm->in.bytes >= line6pcm->in.period) {
line6pcm->in.bytes %= line6pcm->in.period;
spin_unlock(&line6pcm->in.lock);
snd_pcm_period_elapsed(substream);
spin_lock(&line6pcm->in.lock);
}
}
/*
* Callback for completed capture URB.
*/
static void audio_in_callback(struct urb *urb)
{
int i, index, length = 0, shutdown = 0;
unsigned long flags;
struct snd_line6_pcm *line6pcm = (struct snd_line6_pcm *)urb->context;
line6pcm->in.last_frame = urb->start_frame;
/* find index of URB */
for (index = 0; index < LINE6_ISO_BUFFERS; ++index)
if (urb == line6pcm->in.urbs[index])
break;
spin_lock_irqsave(&line6pcm->in.lock, flags);
for (i = 0; i < LINE6_ISO_PACKETS; ++i) {
char *fbuf;
int fsize;
struct usb_iso_packet_descriptor *fin = &urb->iso_frame_desc[i];
if (fin->status == -EXDEV) {
shutdown = 1;
break;
}
fbuf = urb->transfer_buffer + fin->offset;
fsize = fin->actual_length;
if (fsize > line6pcm->max_packet_size) {
dev_err(line6pcm->line6->ifcdev,
"driver and/or device bug: packet too large (%d > %d)\n",
fsize, line6pcm->max_packet_size);
}
length += fsize;
/* the following assumes LINE6_ISO_PACKETS == 1: */
line6pcm->prev_fbuf = fbuf;
line6pcm->prev_fsize = fsize;
if (!test_bit(LINE6_STREAM_IMPULSE, &line6pcm->in.running) &&
test_bit(LINE6_STREAM_PCM, &line6pcm->in.running) &&
fsize > 0)
line6_capture_copy(line6pcm, fbuf, fsize);
}
clear_bit(index, &line6pcm->in.active_urbs);
if (test_and_clear_bit(index, &line6pcm->in.unlink_urbs))
shutdown = 1;
if (!shutdown) {
submit_audio_in_urb(line6pcm);
if (!test_bit(LINE6_STREAM_IMPULSE, &line6pcm->in.running) &&
test_bit(LINE6_STREAM_PCM, &line6pcm->in.running))
line6_capture_check_period(line6pcm, length);
}
spin_unlock_irqrestore(&line6pcm->in.lock, flags);
}
/* open capture callback */
static int snd_line6_capture_open(struct snd_pcm_substream *substream)
{
int err;
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_line6_pcm *line6pcm = snd_pcm_substream_chip(substream);
err = snd_pcm_hw_constraint_ratdens(runtime, 0,
SNDRV_PCM_HW_PARAM_RATE,
&line6pcm->properties->rates);
if (err < 0)
return err;
runtime->hw = line6pcm->properties->capture_hw;
return 0;
}
/* close capture callback */
static int snd_line6_capture_close(struct snd_pcm_substream *substream)
{
return 0;
}
/* capture operators */
struct snd_pcm_ops snd_line6_capture_ops = {
.open = snd_line6_capture_open,
.close = snd_line6_capture_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_line6_hw_params,
.hw_free = snd_line6_hw_free,
.prepare = snd_line6_prepare,
.trigger = snd_line6_trigger,
.pointer = snd_line6_pointer,
};
int line6_create_audio_in_urbs(struct snd_line6_pcm *line6pcm)
{
struct usb_line6 *line6 = line6pcm->line6;
int i;
/* create audio URBs and fill in constant values: */
for (i = 0; i < LINE6_ISO_BUFFERS; ++i) {
struct urb *urb;
/* URB for audio in: */
urb = line6pcm->in.urbs[i] =
usb_alloc_urb(LINE6_ISO_PACKETS, GFP_KERNEL);
if (urb == NULL)
return -ENOMEM;
urb->dev = line6->usbdev;
urb->pipe =
usb_rcvisocpipe(line6->usbdev,
line6->properties->ep_audio_r &
USB_ENDPOINT_NUMBER_MASK);
urb->transfer_flags = URB_ISO_ASAP;
urb->start_frame = -1;
urb->number_of_packets = LINE6_ISO_PACKETS;
urb->interval = LINE6_ISO_INTERVAL;
urb->error_count = 0;
urb->complete = audio_in_callback;
}
return 0;
}
| gpl-2.0 |
motoTurboZ/kernel-msm | arch/x86/lib/usercopy_64.c | 1076 | 2181 | /*
* User address space access functions.
*
* Copyright 1997 Andi Kleen <ak@muc.de>
* Copyright 1997 Linus Torvalds
* Copyright 2002 Andi Kleen <ak@suse.de>
*/
#include <linux/module.h>
#include <asm/uaccess.h>
/*
* Zero Userspace
*/
unsigned long __clear_user(void __user *addr, unsigned long size)
{
long __d0;
might_fault();
/* no memory constraint because it doesn't change any memory gcc knows
about */
stac();
asm volatile(
" testq %[size8],%[size8]\n"
" jz 4f\n"
"0: movq %[zero],(%[dst])\n"
" addq %[eight],%[dst]\n"
" decl %%ecx ; jnz 0b\n"
"4: movq %[size1],%%rcx\n"
" testl %%ecx,%%ecx\n"
" jz 2f\n"
"1: movb %b[zero],(%[dst])\n"
" incq %[dst]\n"
" decl %%ecx ; jnz 1b\n"
"2:\n"
".section .fixup,\"ax\"\n"
"3: lea 0(%[size1],%[size8],8),%[size8]\n"
" jmp 2b\n"
".previous\n"
_ASM_EXTABLE(0b,3b)
_ASM_EXTABLE(1b,2b)
: [size8] "=&c"(size), [dst] "=&D" (__d0)
: [size1] "r"(size & 7), "[size8]" (size / 8), "[dst]"(addr),
[zero] "r" (0UL), [eight] "r" (8UL));
clac();
return size;
}
EXPORT_SYMBOL(__clear_user);
unsigned long clear_user(void __user *to, unsigned long n)
{
if (access_ok(VERIFY_WRITE, to, n))
return __clear_user(to, n);
return n;
}
EXPORT_SYMBOL(clear_user);
unsigned long copy_in_user(void __user *to, const void __user *from, unsigned len)
{
if (access_ok(VERIFY_WRITE, to, len) && access_ok(VERIFY_READ, from, len)) {
return copy_user_generic((__force void *)to, (__force void *)from, len);
}
return len;
}
EXPORT_SYMBOL(copy_in_user);
/*
* Try to copy last bytes and clear the rest if needed.
* Since protection fault in copy_from/to_user is not a normal situation,
* it is not necessary to optimize tail handling.
*/
__visible unsigned long
copy_user_handle_tail(char *to, char *from, unsigned len, unsigned zerorest)
{
char c;
unsigned zero_len;
for (; len; --len, to++) {
if (__get_user_nocheck(c, from++, sizeof(char)))
break;
if (__put_user_nocheck(c, to, sizeof(char)))
break;
}
for (c = 0, zero_len = len; zerorest && zero_len; --zero_len)
if (__put_user_nocheck(c, to++, sizeof(char)))
break;
clac();
return len;
}
| gpl-2.0 |
DC07/spirit_msm8916 | drivers/switch/switch_class.c | 1332 | 4373 | /*
* drivers/switch/switch_class.c
*
* Copyright (C) 2008 Google, Inc.
* Author: Mike Lockwood <lockwood@android.com>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/fs.h>
#include <linux/err.h>
#include <linux/switch.h>
struct class *switch_class;
static atomic_t device_count;
static ssize_t state_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct switch_dev *sdev = (struct switch_dev *)
dev_get_drvdata(dev);
if (sdev->print_state) {
int ret = sdev->print_state(sdev, buf);
if (ret >= 0)
return ret;
}
return sprintf(buf, "%d\n", sdev->state);
}
static ssize_t name_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct switch_dev *sdev = (struct switch_dev *)
dev_get_drvdata(dev);
if (sdev->print_name) {
int ret = sdev->print_name(sdev, buf);
if (ret >= 0)
return ret;
}
return sprintf(buf, "%s\n", sdev->name);
}
static DEVICE_ATTR(state, S_IRUGO, state_show, NULL);
static DEVICE_ATTR(name, S_IRUGO, name_show, NULL);
void switch_set_state(struct switch_dev *sdev, int state)
{
char name_buf[120];
char state_buf[120];
char *prop_buf;
char *envp[3];
int env_offset = 0;
int length;
if (sdev->state != state) {
sdev->state = state;
prop_buf = (char *)get_zeroed_page(GFP_KERNEL);
if (prop_buf) {
length = name_show(sdev->dev, NULL, prop_buf);
if (length > 0) {
if (prop_buf[length - 1] == '\n')
prop_buf[length - 1] = 0;
snprintf(name_buf, sizeof(name_buf),
"SWITCH_NAME=%s", prop_buf);
envp[env_offset++] = name_buf;
}
length = state_show(sdev->dev, NULL, prop_buf);
if (length > 0) {
if (prop_buf[length - 1] == '\n')
prop_buf[length - 1] = 0;
snprintf(state_buf, sizeof(state_buf),
"SWITCH_STATE=%s", prop_buf);
envp[env_offset++] = state_buf;
}
envp[env_offset] = NULL;
kobject_uevent_env(&sdev->dev->kobj, KOBJ_CHANGE, envp);
free_page((unsigned long)prop_buf);
} else {
printk(KERN_ERR "out of memory in switch_set_state\n");
kobject_uevent(&sdev->dev->kobj, KOBJ_CHANGE);
}
}
}
EXPORT_SYMBOL_GPL(switch_set_state);
static int create_switch_class(void)
{
if (!switch_class) {
switch_class = class_create(THIS_MODULE, "switch");
if (IS_ERR(switch_class))
return PTR_ERR(switch_class);
atomic_set(&device_count, 0);
}
return 0;
}
int switch_dev_register(struct switch_dev *sdev)
{
int ret;
if (!switch_class) {
ret = create_switch_class();
if (ret < 0)
return ret;
}
sdev->index = atomic_inc_return(&device_count);
sdev->dev = device_create(switch_class, NULL,
MKDEV(0, sdev->index), NULL, sdev->name);
if (IS_ERR(sdev->dev))
return PTR_ERR(sdev->dev);
ret = device_create_file(sdev->dev, &dev_attr_state);
if (ret < 0)
goto err_create_file_1;
ret = device_create_file(sdev->dev, &dev_attr_name);
if (ret < 0)
goto err_create_file_2;
dev_set_drvdata(sdev->dev, sdev);
sdev->state = 0;
return 0;
err_create_file_2:
device_remove_file(sdev->dev, &dev_attr_state);
err_create_file_1:
device_destroy(switch_class, MKDEV(0, sdev->index));
printk(KERN_ERR "switch: Failed to register driver %s\n", sdev->name);
return ret;
}
EXPORT_SYMBOL_GPL(switch_dev_register);
void switch_dev_unregister(struct switch_dev *sdev)
{
device_remove_file(sdev->dev, &dev_attr_name);
device_remove_file(sdev->dev, &dev_attr_state);
dev_set_drvdata(sdev->dev, NULL);
device_destroy(switch_class, MKDEV(0, sdev->index));
}
EXPORT_SYMBOL_GPL(switch_dev_unregister);
static int __init switch_class_init(void)
{
return create_switch_class();
}
static void __exit switch_class_exit(void)
{
class_destroy(switch_class);
}
module_init(switch_class_init);
module_exit(switch_class_exit);
MODULE_AUTHOR("Mike Lockwood <lockwood@android.com>");
MODULE_DESCRIPTION("Switch class driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
allanm84/linux-imx | drivers/iio/adc/ad7266.c | 1588 | 13306 | /*
* AD7266/65 SPI ADC driver
*
* Copyright 2012 Analog Devices Inc.
*
* Licensed under the GPL-2.
*/
#include <linux/device.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/spi/spi.h>
#include <linux/regulator/consumer.h>
#include <linux/err.h>
#include <linux/gpio.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/iio/iio.h>
#include <linux/iio/buffer.h>
#include <linux/iio/trigger_consumer.h>
#include <linux/iio/triggered_buffer.h>
#include <linux/platform_data/ad7266.h>
struct ad7266_state {
struct spi_device *spi;
struct regulator *reg;
unsigned long vref_mv;
struct spi_transfer single_xfer[3];
struct spi_message single_msg;
enum ad7266_range range;
enum ad7266_mode mode;
bool fixed_addr;
struct gpio gpios[3];
/*
* DMA (thus cache coherency maintenance) requires the
* transfer buffers to live in their own cache lines.
* The buffer needs to be large enough to hold two samples (4 bytes) and
* the naturally aligned timestamp (8 bytes).
*/
struct {
__be16 sample[2];
s64 timestamp;
} data ____cacheline_aligned;
};
static int ad7266_wakeup(struct ad7266_state *st)
{
/* Any read with >= 2 bytes will wake the device */
return spi_read(st->spi, &st->data.sample[0], 2);
}
static int ad7266_powerdown(struct ad7266_state *st)
{
/* Any read with < 2 bytes will powerdown the device */
return spi_read(st->spi, &st->data.sample[0], 1);
}
static int ad7266_preenable(struct iio_dev *indio_dev)
{
struct ad7266_state *st = iio_priv(indio_dev);
return ad7266_wakeup(st);
}
static int ad7266_postdisable(struct iio_dev *indio_dev)
{
struct ad7266_state *st = iio_priv(indio_dev);
return ad7266_powerdown(st);
}
static const struct iio_buffer_setup_ops iio_triggered_buffer_setup_ops = {
.preenable = &ad7266_preenable,
.postenable = &iio_triggered_buffer_postenable,
.predisable = &iio_triggered_buffer_predisable,
.postdisable = &ad7266_postdisable,
};
static irqreturn_t ad7266_trigger_handler(int irq, void *p)
{
struct iio_poll_func *pf = p;
struct iio_dev *indio_dev = pf->indio_dev;
struct ad7266_state *st = iio_priv(indio_dev);
int ret;
ret = spi_read(st->spi, st->data.sample, 4);
if (ret == 0) {
iio_push_to_buffers_with_timestamp(indio_dev, &st->data,
pf->timestamp);
}
iio_trigger_notify_done(indio_dev->trig);
return IRQ_HANDLED;
}
static void ad7266_select_input(struct ad7266_state *st, unsigned int nr)
{
unsigned int i;
if (st->fixed_addr)
return;
switch (st->mode) {
case AD7266_MODE_SINGLE_ENDED:
nr >>= 1;
break;
case AD7266_MODE_PSEUDO_DIFF:
nr |= 1;
break;
case AD7266_MODE_DIFF:
nr &= ~1;
break;
}
for (i = 0; i < 3; ++i)
gpio_set_value(st->gpios[i].gpio, (bool)(nr & BIT(i)));
}
static int ad7266_update_scan_mode(struct iio_dev *indio_dev,
const unsigned long *scan_mask)
{
struct ad7266_state *st = iio_priv(indio_dev);
unsigned int nr = find_first_bit(scan_mask, indio_dev->masklength);
ad7266_select_input(st, nr);
return 0;
}
static int ad7266_read_single(struct ad7266_state *st, int *val,
unsigned int address)
{
int ret;
ad7266_select_input(st, address);
ret = spi_sync(st->spi, &st->single_msg);
*val = be16_to_cpu(st->data.sample[address % 2]);
return ret;
}
static int ad7266_read_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan, int *val, int *val2, long m)
{
struct ad7266_state *st = iio_priv(indio_dev);
unsigned long scale_mv;
int ret;
switch (m) {
case IIO_CHAN_INFO_RAW:
if (iio_buffer_enabled(indio_dev))
return -EBUSY;
ret = ad7266_read_single(st, val, chan->address);
if (ret)
return ret;
*val = (*val >> 2) & 0xfff;
if (chan->scan_type.sign == 's')
*val = sign_extend32(*val, 11);
return IIO_VAL_INT;
case IIO_CHAN_INFO_SCALE:
scale_mv = st->vref_mv;
if (st->mode == AD7266_MODE_DIFF)
scale_mv *= 2;
if (st->range == AD7266_RANGE_2VREF)
scale_mv *= 2;
*val = scale_mv;
*val2 = chan->scan_type.realbits;
return IIO_VAL_FRACTIONAL_LOG2;
case IIO_CHAN_INFO_OFFSET:
if (st->range == AD7266_RANGE_2VREF &&
st->mode != AD7266_MODE_DIFF)
*val = 2048;
else
*val = 0;
return IIO_VAL_INT;
}
return -EINVAL;
}
#define AD7266_CHAN(_chan, _sign) { \
.type = IIO_VOLTAGE, \
.indexed = 1, \
.channel = (_chan), \
.address = (_chan), \
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW), \
.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE) \
| BIT(IIO_CHAN_INFO_OFFSET), \
.scan_index = (_chan), \
.scan_type = { \
.sign = (_sign), \
.realbits = 12, \
.storagebits = 16, \
.shift = 2, \
.endianness = IIO_BE, \
}, \
}
#define AD7266_DECLARE_SINGLE_ENDED_CHANNELS(_name, _sign) \
const struct iio_chan_spec ad7266_channels_##_name[] = { \
AD7266_CHAN(0, (_sign)), \
AD7266_CHAN(1, (_sign)), \
AD7266_CHAN(2, (_sign)), \
AD7266_CHAN(3, (_sign)), \
AD7266_CHAN(4, (_sign)), \
AD7266_CHAN(5, (_sign)), \
AD7266_CHAN(6, (_sign)), \
AD7266_CHAN(7, (_sign)), \
AD7266_CHAN(8, (_sign)), \
AD7266_CHAN(9, (_sign)), \
AD7266_CHAN(10, (_sign)), \
AD7266_CHAN(11, (_sign)), \
IIO_CHAN_SOFT_TIMESTAMP(13), \
}
#define AD7266_DECLARE_SINGLE_ENDED_CHANNELS_FIXED(_name, _sign) \
const struct iio_chan_spec ad7266_channels_##_name##_fixed[] = { \
AD7266_CHAN(0, (_sign)), \
AD7266_CHAN(1, (_sign)), \
IIO_CHAN_SOFT_TIMESTAMP(2), \
}
static AD7266_DECLARE_SINGLE_ENDED_CHANNELS(u, 'u');
static AD7266_DECLARE_SINGLE_ENDED_CHANNELS(s, 's');
static AD7266_DECLARE_SINGLE_ENDED_CHANNELS_FIXED(u, 'u');
static AD7266_DECLARE_SINGLE_ENDED_CHANNELS_FIXED(s, 's');
#define AD7266_CHAN_DIFF(_chan, _sign) { \
.type = IIO_VOLTAGE, \
.indexed = 1, \
.channel = (_chan) * 2, \
.channel2 = (_chan) * 2 + 1, \
.address = (_chan), \
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW), \
.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE) \
| BIT(IIO_CHAN_INFO_OFFSET), \
.scan_index = (_chan), \
.scan_type = { \
.sign = _sign, \
.realbits = 12, \
.storagebits = 16, \
.shift = 2, \
.endianness = IIO_BE, \
}, \
.differential = 1, \
}
#define AD7266_DECLARE_DIFF_CHANNELS(_name, _sign) \
const struct iio_chan_spec ad7266_channels_diff_##_name[] = { \
AD7266_CHAN_DIFF(0, (_sign)), \
AD7266_CHAN_DIFF(1, (_sign)), \
AD7266_CHAN_DIFF(2, (_sign)), \
AD7266_CHAN_DIFF(3, (_sign)), \
AD7266_CHAN_DIFF(4, (_sign)), \
AD7266_CHAN_DIFF(5, (_sign)), \
IIO_CHAN_SOFT_TIMESTAMP(6), \
}
static AD7266_DECLARE_DIFF_CHANNELS(s, 's');
static AD7266_DECLARE_DIFF_CHANNELS(u, 'u');
#define AD7266_DECLARE_DIFF_CHANNELS_FIXED(_name, _sign) \
const struct iio_chan_spec ad7266_channels_diff_fixed_##_name[] = { \
AD7266_CHAN_DIFF(0, (_sign)), \
AD7266_CHAN_DIFF(1, (_sign)), \
IIO_CHAN_SOFT_TIMESTAMP(2), \
}
static AD7266_DECLARE_DIFF_CHANNELS_FIXED(s, 's');
static AD7266_DECLARE_DIFF_CHANNELS_FIXED(u, 'u');
static const struct iio_info ad7266_info = {
.read_raw = &ad7266_read_raw,
.update_scan_mode = &ad7266_update_scan_mode,
.driver_module = THIS_MODULE,
};
static const unsigned long ad7266_available_scan_masks[] = {
0x003,
0x00c,
0x030,
0x0c0,
0x300,
0xc00,
0x000,
};
static const unsigned long ad7266_available_scan_masks_diff[] = {
0x003,
0x00c,
0x030,
0x000,
};
static const unsigned long ad7266_available_scan_masks_fixed[] = {
0x003,
0x000,
};
struct ad7266_chan_info {
const struct iio_chan_spec *channels;
unsigned int num_channels;
const unsigned long *scan_masks;
};
#define AD7266_CHAN_INFO_INDEX(_differential, _signed, _fixed) \
(((_differential) << 2) | ((_signed) << 1) | ((_fixed) << 0))
static const struct ad7266_chan_info ad7266_chan_infos[] = {
[AD7266_CHAN_INFO_INDEX(0, 0, 0)] = {
.channels = ad7266_channels_u,
.num_channels = ARRAY_SIZE(ad7266_channels_u),
.scan_masks = ad7266_available_scan_masks,
},
[AD7266_CHAN_INFO_INDEX(0, 0, 1)] = {
.channels = ad7266_channels_u_fixed,
.num_channels = ARRAY_SIZE(ad7266_channels_u_fixed),
.scan_masks = ad7266_available_scan_masks_fixed,
},
[AD7266_CHAN_INFO_INDEX(0, 1, 0)] = {
.channels = ad7266_channels_s,
.num_channels = ARRAY_SIZE(ad7266_channels_s),
.scan_masks = ad7266_available_scan_masks,
},
[AD7266_CHAN_INFO_INDEX(0, 1, 1)] = {
.channels = ad7266_channels_s_fixed,
.num_channels = ARRAY_SIZE(ad7266_channels_s_fixed),
.scan_masks = ad7266_available_scan_masks_fixed,
},
[AD7266_CHAN_INFO_INDEX(1, 0, 0)] = {
.channels = ad7266_channels_diff_u,
.num_channels = ARRAY_SIZE(ad7266_channels_diff_u),
.scan_masks = ad7266_available_scan_masks_diff,
},
[AD7266_CHAN_INFO_INDEX(1, 0, 1)] = {
.channels = ad7266_channels_diff_fixed_u,
.num_channels = ARRAY_SIZE(ad7266_channels_diff_fixed_u),
.scan_masks = ad7266_available_scan_masks_fixed,
},
[AD7266_CHAN_INFO_INDEX(1, 1, 0)] = {
.channels = ad7266_channels_diff_s,
.num_channels = ARRAY_SIZE(ad7266_channels_diff_s),
.scan_masks = ad7266_available_scan_masks_diff,
},
[AD7266_CHAN_INFO_INDEX(1, 1, 1)] = {
.channels = ad7266_channels_diff_fixed_s,
.num_channels = ARRAY_SIZE(ad7266_channels_diff_fixed_s),
.scan_masks = ad7266_available_scan_masks_fixed,
},
};
static void ad7266_init_channels(struct iio_dev *indio_dev)
{
struct ad7266_state *st = iio_priv(indio_dev);
bool is_differential, is_signed;
const struct ad7266_chan_info *chan_info;
int i;
is_differential = st->mode != AD7266_MODE_SINGLE_ENDED;
is_signed = (st->range == AD7266_RANGE_2VREF) |
(st->mode == AD7266_MODE_DIFF);
i = AD7266_CHAN_INFO_INDEX(is_differential, is_signed, st->fixed_addr);
chan_info = &ad7266_chan_infos[i];
indio_dev->channels = chan_info->channels;
indio_dev->num_channels = chan_info->num_channels;
indio_dev->available_scan_masks = chan_info->scan_masks;
indio_dev->masklength = chan_info->num_channels - 1;
}
static const char * const ad7266_gpio_labels[] = {
"AD0", "AD1", "AD2",
};
static int ad7266_probe(struct spi_device *spi)
{
struct ad7266_platform_data *pdata = spi->dev.platform_data;
struct iio_dev *indio_dev;
struct ad7266_state *st;
unsigned int i;
int ret;
indio_dev = devm_iio_device_alloc(&spi->dev, sizeof(*st));
if (indio_dev == NULL)
return -ENOMEM;
st = iio_priv(indio_dev);
st->reg = devm_regulator_get(&spi->dev, "vref");
if (!IS_ERR_OR_NULL(st->reg)) {
ret = regulator_enable(st->reg);
if (ret)
return ret;
ret = regulator_get_voltage(st->reg);
if (ret < 0)
goto error_disable_reg;
st->vref_mv = ret / 1000;
} else {
/* Use internal reference */
st->vref_mv = 2500;
}
if (pdata) {
st->fixed_addr = pdata->fixed_addr;
st->mode = pdata->mode;
st->range = pdata->range;
if (!st->fixed_addr) {
for (i = 0; i < ARRAY_SIZE(st->gpios); ++i) {
st->gpios[i].gpio = pdata->addr_gpios[i];
st->gpios[i].flags = GPIOF_OUT_INIT_LOW;
st->gpios[i].label = ad7266_gpio_labels[i];
}
ret = gpio_request_array(st->gpios,
ARRAY_SIZE(st->gpios));
if (ret)
goto error_disable_reg;
}
} else {
st->fixed_addr = true;
st->range = AD7266_RANGE_VREF;
st->mode = AD7266_MODE_DIFF;
}
spi_set_drvdata(spi, indio_dev);
st->spi = spi;
indio_dev->dev.parent = &spi->dev;
indio_dev->name = spi_get_device_id(spi)->name;
indio_dev->modes = INDIO_DIRECT_MODE;
indio_dev->info = &ad7266_info;
ad7266_init_channels(indio_dev);
/* wakeup */
st->single_xfer[0].rx_buf = &st->data.sample[0];
st->single_xfer[0].len = 2;
st->single_xfer[0].cs_change = 1;
/* conversion */
st->single_xfer[1].rx_buf = st->data.sample;
st->single_xfer[1].len = 4;
st->single_xfer[1].cs_change = 1;
/* powerdown */
st->single_xfer[2].tx_buf = &st->data.sample[0];
st->single_xfer[2].len = 1;
spi_message_init(&st->single_msg);
spi_message_add_tail(&st->single_xfer[0], &st->single_msg);
spi_message_add_tail(&st->single_xfer[1], &st->single_msg);
spi_message_add_tail(&st->single_xfer[2], &st->single_msg);
ret = iio_triggered_buffer_setup(indio_dev, &iio_pollfunc_store_time,
&ad7266_trigger_handler, &iio_triggered_buffer_setup_ops);
if (ret)
goto error_free_gpios;
ret = iio_device_register(indio_dev);
if (ret)
goto error_buffer_cleanup;
return 0;
error_buffer_cleanup:
iio_triggered_buffer_cleanup(indio_dev);
error_free_gpios:
if (!st->fixed_addr)
gpio_free_array(st->gpios, ARRAY_SIZE(st->gpios));
error_disable_reg:
if (!IS_ERR_OR_NULL(st->reg))
regulator_disable(st->reg);
return ret;
}
static int ad7266_remove(struct spi_device *spi)
{
struct iio_dev *indio_dev = spi_get_drvdata(spi);
struct ad7266_state *st = iio_priv(indio_dev);
iio_device_unregister(indio_dev);
iio_triggered_buffer_cleanup(indio_dev);
if (!st->fixed_addr)
gpio_free_array(st->gpios, ARRAY_SIZE(st->gpios));
if (!IS_ERR_OR_NULL(st->reg))
regulator_disable(st->reg);
return 0;
}
static const struct spi_device_id ad7266_id[] = {
{"ad7265", 0},
{"ad7266", 0},
{ }
};
MODULE_DEVICE_TABLE(spi, ad7266_id);
static struct spi_driver ad7266_driver = {
.driver = {
.name = "ad7266",
.owner = THIS_MODULE,
},
.probe = ad7266_probe,
.remove = ad7266_remove,
.id_table = ad7266_id,
};
module_spi_driver(ad7266_driver);
MODULE_AUTHOR("Lars-Peter Clausen <lars@metafoo.de>");
MODULE_DESCRIPTION("Analog Devices AD7266/65 ADC");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
darknighte/linux | crypto/cast5_generic.c | 2356 | 21383 | /* Kernel cryptographic api.
* cast5.c - Cast5 cipher algorithm (rfc2144).
*
* Derived from GnuPG implementation of cast5.
*
* Major Changes.
* Complete conformance to rfc2144.
* Supports key size from 40 to 128 bits.
*
* Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
* Copyright (C) 2003 Kartikey Mahendra Bhatt <kartik_me@hotmail.com>.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#include <asm/byteorder.h>
#include <linux/init.h>
#include <linux/crypto.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/types.h>
#include <crypto/cast5.h>
static const u32 s5[256] = {
0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff,
0x1dd358f5, 0x44dd9d44, 0x1731167f,
0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8,
0x386381cb, 0xacf6243a, 0x69befd7a,
0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640,
0x15b0a848, 0xe68b18cb, 0x4caadeff,
0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d,
0x248eb6fb, 0x8dba1cfe, 0x41a99b02,
0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7,
0x97a5980a, 0xc539b9aa, 0x4d79fe6a,
0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88,
0x8709e6b0, 0xd7e07156, 0x4e29fea7,
0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a,
0x578535f2, 0x2261be02, 0xd642a0c9,
0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8,
0xc8adedb3, 0x28a87fc9, 0x3d959981,
0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1,
0x4fb96976, 0x90c79505, 0xb0a8a774,
0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f,
0x0ec50966, 0xdfdd55bc, 0x29de0655,
0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980,
0x524755f4, 0x03b63cc9, 0x0cc844b2,
0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449,
0x64ee2d7e, 0xcddbb1da, 0x01c94910,
0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6,
0x50f5b616, 0xf24766e3, 0x8eca36c1,
0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9,
0x3063fcdf, 0xb6f589de, 0xec2941da,
0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401,
0xc1bacb7f, 0xe5ff550f, 0xb6083049,
0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd,
0x9e0885f9, 0x68cb3e47, 0x086c010f,
0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3,
0xcbb3d550, 0x1793084d, 0xb0d70eba,
0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56,
0x0f5755d1, 0xe0e1e56e, 0x6184b5be,
0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280,
0x05687715, 0x646c6bd7, 0x44904db3,
0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f,
0x2cb6356a, 0x85808573, 0x4991f840,
0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8,
0xc1092910, 0x8bc95fc6, 0x7d869cf4,
0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717,
0x7d161bba, 0x9cad9010, 0xaf462ba2,
0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e,
0x176d486f, 0x097c13ea, 0x631da5c7,
0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72,
0x6e5dd2f3, 0x20936079, 0x459b80a5,
0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572,
0xf6721b2c, 0x1ad2fff3, 0x8c25404e,
0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e,
0x75922283, 0x784d6b17, 0x58ebb16e,
0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf,
0xaaf47556, 0x5f46b02a, 0x2b092801,
0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874,
0x95055110, 0x1b5ad7a8, 0xf61ed5ad,
0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826,
0x0ff6f8f3, 0xa09c7f70, 0x5346aba0,
0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9,
0x17e3fe2a, 0x24b79767, 0xf5a96b20,
0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a,
0xeeb9491d, 0x34010718, 0xbb30cab8,
0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8,
0xb1534546, 0x6d47de08, 0xefe9e7d4
};
static const u32 s6[256] = {
0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7,
0x016843b4, 0xeced5cbc, 0x325553ac,
0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8,
0xde5ebe39, 0xf38ff732, 0x8989b138,
0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99,
0x4e23e33c, 0x79cbd7cc, 0x48a14367,
0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d,
0x09a8486f, 0xa888614a, 0x2900af98,
0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932,
0xcf0fec14, 0xf7ca07d2, 0xd0a82072,
0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c,
0x4c7f4448, 0xdab5d440, 0x6dba0ec3,
0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01,
0x64bdb941, 0x2c0e636a, 0xba7dd9cd,
0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c,
0xb88153e2, 0x08a19866, 0x1ae2eac8,
0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3,
0x9aea3906, 0xefe8c36e, 0xf890cdd9,
0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc,
0x221db3a6, 0x9a69a02f, 0x68818a54,
0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc,
0xcf222ebf, 0x25ac6f48, 0xa9a99387,
0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1,
0xe8a11be9, 0x4980740d, 0xc8087dfc,
0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f,
0x9528cd89, 0xfd339fed, 0xb87834bf,
0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa,
0x57f55ec5, 0xe2220abe, 0xd2916ebf,
0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff,
0xa8dc8af0, 0x7345c106, 0xf41e232f,
0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af,
0x692573e4, 0xe9a9d848, 0xf3160289,
0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063,
0x4576698d, 0xb6fad407, 0x592af950,
0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8,
0xc50dfe5d, 0xfcd707ab, 0x0921c42f,
0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d,
0x48b9d585, 0xdc049441, 0xc8098f9b,
0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6,
0x890072d6, 0x28207682, 0xa9a9f7be,
0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a,
0x1f8fb214, 0xd372cf08, 0xcc3c4a13,
0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a,
0xb6c85283, 0x3cc2acfb, 0x3fc06976,
0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0,
0x513021a5, 0x6c5b68b7, 0x822f8aa0,
0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9,
0x0c5ec241, 0x8809286c, 0xf592d891,
0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98,
0xb173ecc0, 0xbc60b42a, 0x953498da,
0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123,
0x257f0c3d, 0x9348af49, 0x361400bc,
0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57,
0xda41e7f9, 0xc25ad33a, 0x54f4a084,
0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5,
0xb6f6deaf, 0x3a479c3a, 0x5302da25,
0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88,
0x44136c76, 0x0404a8c8, 0xb8e5a121,
0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913,
0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5,
0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1,
0xf544edeb, 0xb0e93524, 0xbebb8fbd,
0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905,
0xa65b1db8, 0x851c97bd, 0xd675cf2f
};
static const u32 s7[256] = {
0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f,
0xab9bc912, 0xde6008a1, 0x2028da1f,
0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11,
0xb232e75c, 0x4b3695f2, 0xb28707de,
0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381,
0xfde4e789, 0x5c79b0d8, 0x1e8bfd43,
0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be,
0xbaeeadf4, 0x1286becf, 0xb6eacb19,
0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66,
0x28136086, 0x0bd8dfa8, 0x356d1cf2,
0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a,
0xeb12ff82, 0xe3486911, 0xd34d7516,
0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce,
0x8c9341b7, 0xd0d854c0, 0xcb3a6c88,
0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa,
0x4437f107, 0xb6e79962, 0x42d2d816,
0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7,
0xf9583745, 0xcf19df58, 0xbec3f756,
0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511,
0x38bc46e9, 0xc6e6fa14, 0xbae8584a,
0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f,
0xaff60ff4, 0xea2c4e6d, 0x16e39264,
0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a,
0xb2856e6e, 0x1aec3ca9, 0xbe838688,
0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85,
0x61fe033c, 0x16746233, 0x3c034c28,
0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a,
0x1626a49f, 0xeed82b29, 0x1d382fe3,
0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c,
0xd45230c7, 0x2bd1408b, 0x60c03eb7,
0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32,
0xebd4e7be, 0xbe8b9d2d, 0x7979fb06,
0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f,
0x5a6317a6, 0xfa5cf7a0, 0x5dda0033,
0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0,
0x79d34217, 0x021a718d, 0x9ac6336a,
0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef,
0x4eeb8476, 0x488dcf25, 0x36c9d566,
0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6,
0x92aeaf64, 0x3ac7d5e6, 0x9ea80509,
0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887,
0x2b9f4fd5, 0x625aba82, 0x6a017962,
0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22,
0xe32dbf9a, 0x058745b9, 0x3453dc1e,
0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1,
0x19de7eae, 0x053e561a, 0x15ad6f8c,
0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0,
0x58d4f2ae, 0x9ea294fb, 0x52cf564c,
0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108,
0xa1e7160e, 0xe4f2dfa6, 0x693ed285,
0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f,
0x3d321c5d, 0xc3f5e194, 0x4b269301,
0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e,
0x296693f4, 0x3d1fce6f, 0xc61e45be,
0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d,
0xb5229301, 0xcfd2a87f, 0x60aeb767,
0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b,
0x589dd390, 0x5479f8e6, 0x1cb8d647,
0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad,
0x462e1b78, 0x6580f87e, 0xf3817914,
0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc,
0x3d40f021, 0xc3c0bdae, 0x4958c24c,
0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7,
0x94e01be8, 0x90716f4b, 0x954b8aa3
};
static const u32 sb8[256] = {
0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7,
0xe6c1121b, 0x0e241600, 0x052ce8b5,
0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c,
0x76e38111, 0xb12def3a, 0x37ddddfc,
0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f,
0xb4d137cf, 0xb44e79f0, 0x049eedfd,
0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831,
0x3f8f95e7, 0x72df191b, 0x7580330d,
0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a,
0x02e7d1ca, 0x53571dae, 0x7a3182a2,
0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022,
0xce949ad4, 0xb84769ad, 0x965bd862,
0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f,
0xc28ec4b8, 0x57e8726e, 0x647a78fc,
0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3,
0xae63aff2, 0x7e8bd632, 0x70108c0c,
0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53,
0x06918548, 0x58cb7e07, 0x3b74ef2e,
0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2,
0x19b47a38, 0x424f7618, 0x35856039,
0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd,
0xc18910b1, 0xe11dbf7b, 0x06cd1af8,
0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c,
0x3dd00db3, 0x708f8f34, 0x77d51b42,
0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e,
0x3e378160, 0x7895cda5, 0x859c15a5,
0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e,
0x31842e7b, 0x24259fd7, 0xf8bef472,
0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c,
0xe2506d3d, 0x4f9b12ea, 0xf215f225,
0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187,
0xea7a6e98, 0x7cd16efc, 0x1436876c,
0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899,
0x92ecbae6, 0xdd67016d, 0x151682eb,
0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e,
0xe139673b, 0xefa63fb8, 0x71873054,
0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d,
0x844a1be5, 0xbae7dfdc, 0x42cbda70,
0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428,
0x79d130a4, 0x3486ebfb, 0x33d3cddc,
0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4,
0xc5c8b37e, 0x0d809ea2, 0x398feb7c,
0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2,
0x37df932b, 0xc4248289, 0xacf3ebc3,
0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e,
0x5e410fab, 0xb48a2465, 0x2eda7fa4,
0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b,
0xdb485694, 0x38d7e5b2, 0x57720101,
0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282,
0x7523d24a, 0xe0779695, 0xf9c17a8f,
0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f,
0xad1163ed, 0xea7b5965, 0x1a00726e,
0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0,
0x9eedc364, 0x22ebe6a8, 0xcee7d28a,
0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca,
0x8951570f, 0xdf09822b, 0xbd691a6c,
0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f,
0x0d771c2b, 0x67cdb156, 0x350d8384,
0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61,
0x8360d87b, 0x1fa98b0c, 0x1149382c,
0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82,
0x0d2059d1, 0xa466bb1e, 0xf8da0a82,
0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80,
0xeaee6801, 0x8db2a283, 0xea8bf59e
};
#define s1 cast_s1
#define s2 cast_s2
#define s3 cast_s3
#define s4 cast_s4
#define F1(D, m, r) ((I = ((m) + (D))), (I = rol32(I, (r))), \
(((s1[I >> 24] ^ s2[(I>>16)&0xff]) - s3[(I>>8)&0xff]) + s4[I&0xff]))
#define F2(D, m, r) ((I = ((m) ^ (D))), (I = rol32(I, (r))), \
(((s1[I >> 24] - s2[(I>>16)&0xff]) + s3[(I>>8)&0xff]) ^ s4[I&0xff]))
#define F3(D, m, r) ((I = ((m) - (D))), (I = rol32(I, (r))), \
(((s1[I >> 24] + s2[(I>>16)&0xff]) ^ s3[(I>>8)&0xff]) - s4[I&0xff]))
void __cast5_encrypt(struct cast5_ctx *c, u8 *outbuf, const u8 *inbuf)
{
const __be32 *src = (const __be32 *)inbuf;
__be32 *dst = (__be32 *)outbuf;
u32 l, r, t;
u32 I; /* used by the Fx macros */
u32 *Km;
u8 *Kr;
Km = c->Km;
Kr = c->Kr;
/* (L0,R0) <-- (m1...m64). (Split the plaintext into left and
* right 32-bit halves L0 = m1...m32 and R0 = m33...m64.)
*/
l = be32_to_cpu(src[0]);
r = be32_to_cpu(src[1]);
/* (16 rounds) for i from 1 to 16, compute Li and Ri as follows:
* Li = Ri-1;
* Ri = Li-1 ^ f(Ri-1,Kmi,Kri), where f is defined in Section 2.2
* Rounds 1, 4, 7, 10, 13, and 16 use f function Type 1.
* Rounds 2, 5, 8, 11, and 14 use f function Type 2.
* Rounds 3, 6, 9, 12, and 15 use f function Type 3.
*/
t = l; l = r; r = t ^ F1(r, Km[0], Kr[0]);
t = l; l = r; r = t ^ F2(r, Km[1], Kr[1]);
t = l; l = r; r = t ^ F3(r, Km[2], Kr[2]);
t = l; l = r; r = t ^ F1(r, Km[3], Kr[3]);
t = l; l = r; r = t ^ F2(r, Km[4], Kr[4]);
t = l; l = r; r = t ^ F3(r, Km[5], Kr[5]);
t = l; l = r; r = t ^ F1(r, Km[6], Kr[6]);
t = l; l = r; r = t ^ F2(r, Km[7], Kr[7]);
t = l; l = r; r = t ^ F3(r, Km[8], Kr[8]);
t = l; l = r; r = t ^ F1(r, Km[9], Kr[9]);
t = l; l = r; r = t ^ F2(r, Km[10], Kr[10]);
t = l; l = r; r = t ^ F3(r, Km[11], Kr[11]);
if (!(c->rr)) {
t = l; l = r; r = t ^ F1(r, Km[12], Kr[12]);
t = l; l = r; r = t ^ F2(r, Km[13], Kr[13]);
t = l; l = r; r = t ^ F3(r, Km[14], Kr[14]);
t = l; l = r; r = t ^ F1(r, Km[15], Kr[15]);
}
/* c1...c64 <-- (R16,L16). (Exchange final blocks L16, R16 and
* concatenate to form the ciphertext.) */
dst[0] = cpu_to_be32(r);
dst[1] = cpu_to_be32(l);
}
EXPORT_SYMBOL_GPL(__cast5_encrypt);
static void cast5_encrypt(struct crypto_tfm *tfm, u8 *outbuf, const u8 *inbuf)
{
__cast5_encrypt(crypto_tfm_ctx(tfm), outbuf, inbuf);
}
void __cast5_decrypt(struct cast5_ctx *c, u8 *outbuf, const u8 *inbuf)
{
const __be32 *src = (const __be32 *)inbuf;
__be32 *dst = (__be32 *)outbuf;
u32 l, r, t;
u32 I;
u32 *Km;
u8 *Kr;
Km = c->Km;
Kr = c->Kr;
l = be32_to_cpu(src[0]);
r = be32_to_cpu(src[1]);
if (!(c->rr)) {
t = l; l = r; r = t ^ F1(r, Km[15], Kr[15]);
t = l; l = r; r = t ^ F3(r, Km[14], Kr[14]);
t = l; l = r; r = t ^ F2(r, Km[13], Kr[13]);
t = l; l = r; r = t ^ F1(r, Km[12], Kr[12]);
}
t = l; l = r; r = t ^ F3(r, Km[11], Kr[11]);
t = l; l = r; r = t ^ F2(r, Km[10], Kr[10]);
t = l; l = r; r = t ^ F1(r, Km[9], Kr[9]);
t = l; l = r; r = t ^ F3(r, Km[8], Kr[8]);
t = l; l = r; r = t ^ F2(r, Km[7], Kr[7]);
t = l; l = r; r = t ^ F1(r, Km[6], Kr[6]);
t = l; l = r; r = t ^ F3(r, Km[5], Kr[5]);
t = l; l = r; r = t ^ F2(r, Km[4], Kr[4]);
t = l; l = r; r = t ^ F1(r, Km[3], Kr[3]);
t = l; l = r; r = t ^ F3(r, Km[2], Kr[2]);
t = l; l = r; r = t ^ F2(r, Km[1], Kr[1]);
t = l; l = r; r = t ^ F1(r, Km[0], Kr[0]);
dst[0] = cpu_to_be32(r);
dst[1] = cpu_to_be32(l);
}
EXPORT_SYMBOL_GPL(__cast5_decrypt);
static void cast5_decrypt(struct crypto_tfm *tfm, u8 *outbuf, const u8 *inbuf)
{
__cast5_decrypt(crypto_tfm_ctx(tfm), outbuf, inbuf);
}
static void key_schedule(u32 *x, u32 *z, u32 *k)
{
#define xi(i) ((x[(i)/4] >> (8*(3-((i)%4)))) & 0xff)
#define zi(i) ((z[(i)/4] >> (8*(3-((i)%4)))) & 0xff)
z[0] = x[0] ^ s5[xi(13)] ^ s6[xi(15)] ^ s7[xi(12)] ^ sb8[xi(14)] ^
s7[xi(8)];
z[1] = x[2] ^ s5[zi(0)] ^ s6[zi(2)] ^ s7[zi(1)] ^ sb8[zi(3)] ^
sb8[xi(10)];
z[2] = x[3] ^ s5[zi(7)] ^ s6[zi(6)] ^ s7[zi(5)] ^ sb8[zi(4)] ^
s5[xi(9)];
z[3] = x[1] ^ s5[zi(10)] ^ s6[zi(9)] ^ s7[zi(11)] ^ sb8[zi(8)] ^
s6[xi(11)];
k[0] = s5[zi(8)] ^ s6[zi(9)] ^ s7[zi(7)] ^ sb8[zi(6)] ^ s5[zi(2)];
k[1] = s5[zi(10)] ^ s6[zi(11)] ^ s7[zi(5)] ^ sb8[zi(4)] ^
s6[zi(6)];
k[2] = s5[zi(12)] ^ s6[zi(13)] ^ s7[zi(3)] ^ sb8[zi(2)] ^
s7[zi(9)];
k[3] = s5[zi(14)] ^ s6[zi(15)] ^ s7[zi(1)] ^ sb8[zi(0)] ^
sb8[zi(12)];
x[0] = z[2] ^ s5[zi(5)] ^ s6[zi(7)] ^ s7[zi(4)] ^ sb8[zi(6)] ^
s7[zi(0)];
x[1] = z[0] ^ s5[xi(0)] ^ s6[xi(2)] ^ s7[xi(1)] ^ sb8[xi(3)] ^
sb8[zi(2)];
x[2] = z[1] ^ s5[xi(7)] ^ s6[xi(6)] ^ s7[xi(5)] ^ sb8[xi(4)] ^
s5[zi(1)];
x[3] = z[3] ^ s5[xi(10)] ^ s6[xi(9)] ^ s7[xi(11)] ^ sb8[xi(8)] ^
s6[zi(3)];
k[4] = s5[xi(3)] ^ s6[xi(2)] ^ s7[xi(12)] ^ sb8[xi(13)] ^
s5[xi(8)];
k[5] = s5[xi(1)] ^ s6[xi(0)] ^ s7[xi(14)] ^ sb8[xi(15)] ^
s6[xi(13)];
k[6] = s5[xi(7)] ^ s6[xi(6)] ^ s7[xi(8)] ^ sb8[xi(9)] ^ s7[xi(3)];
k[7] = s5[xi(5)] ^ s6[xi(4)] ^ s7[xi(10)] ^ sb8[xi(11)] ^
sb8[xi(7)];
z[0] = x[0] ^ s5[xi(13)] ^ s6[xi(15)] ^ s7[xi(12)] ^ sb8[xi(14)] ^
s7[xi(8)];
z[1] = x[2] ^ s5[zi(0)] ^ s6[zi(2)] ^ s7[zi(1)] ^ sb8[zi(3)] ^
sb8[xi(10)];
z[2] = x[3] ^ s5[zi(7)] ^ s6[zi(6)] ^ s7[zi(5)] ^ sb8[zi(4)] ^
s5[xi(9)];
z[3] = x[1] ^ s5[zi(10)] ^ s6[zi(9)] ^ s7[zi(11)] ^ sb8[zi(8)] ^
s6[xi(11)];
k[8] = s5[zi(3)] ^ s6[zi(2)] ^ s7[zi(12)] ^ sb8[zi(13)] ^
s5[zi(9)];
k[9] = s5[zi(1)] ^ s6[zi(0)] ^ s7[zi(14)] ^ sb8[zi(15)] ^
s6[zi(12)];
k[10] = s5[zi(7)] ^ s6[zi(6)] ^ s7[zi(8)] ^ sb8[zi(9)] ^ s7[zi(2)];
k[11] = s5[zi(5)] ^ s6[zi(4)] ^ s7[zi(10)] ^ sb8[zi(11)] ^
sb8[zi(6)];
x[0] = z[2] ^ s5[zi(5)] ^ s6[zi(7)] ^ s7[zi(4)] ^ sb8[zi(6)] ^
s7[zi(0)];
x[1] = z[0] ^ s5[xi(0)] ^ s6[xi(2)] ^ s7[xi(1)] ^ sb8[xi(3)] ^
sb8[zi(2)];
x[2] = z[1] ^ s5[xi(7)] ^ s6[xi(6)] ^ s7[xi(5)] ^ sb8[xi(4)] ^
s5[zi(1)];
x[3] = z[3] ^ s5[xi(10)] ^ s6[xi(9)] ^ s7[xi(11)] ^ sb8[xi(8)] ^
s6[zi(3)];
k[12] = s5[xi(8)] ^ s6[xi(9)] ^ s7[xi(7)] ^ sb8[xi(6)] ^ s5[xi(3)];
k[13] = s5[xi(10)] ^ s6[xi(11)] ^ s7[xi(5)] ^ sb8[xi(4)] ^
s6[xi(7)];
k[14] = s5[xi(12)] ^ s6[xi(13)] ^ s7[xi(3)] ^ sb8[xi(2)] ^
s7[xi(8)];
k[15] = s5[xi(14)] ^ s6[xi(15)] ^ s7[xi(1)] ^ sb8[xi(0)] ^
sb8[xi(13)];
#undef xi
#undef zi
}
int cast5_setkey(struct crypto_tfm *tfm, const u8 *key, unsigned int key_len)
{
struct cast5_ctx *c = crypto_tfm_ctx(tfm);
int i;
u32 x[4];
u32 z[4];
u32 k[16];
__be32 p_key[4];
c->rr = key_len <= 10 ? 1 : 0;
memset(p_key, 0, 16);
memcpy(p_key, key, key_len);
x[0] = be32_to_cpu(p_key[0]);
x[1] = be32_to_cpu(p_key[1]);
x[2] = be32_to_cpu(p_key[2]);
x[3] = be32_to_cpu(p_key[3]);
key_schedule(x, z, k);
for (i = 0; i < 16; i++)
c->Km[i] = k[i];
key_schedule(x, z, k);
for (i = 0; i < 16; i++)
c->Kr[i] = k[i] & 0x1f;
return 0;
}
EXPORT_SYMBOL_GPL(cast5_setkey);
static struct crypto_alg alg = {
.cra_name = "cast5",
.cra_driver_name = "cast5-generic",
.cra_priority = 100,
.cra_flags = CRYPTO_ALG_TYPE_CIPHER,
.cra_blocksize = CAST5_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct cast5_ctx),
.cra_alignmask = 3,
.cra_module = THIS_MODULE,
.cra_u = {
.cipher = {
.cia_min_keysize = CAST5_MIN_KEY_SIZE,
.cia_max_keysize = CAST5_MAX_KEY_SIZE,
.cia_setkey = cast5_setkey,
.cia_encrypt = cast5_encrypt,
.cia_decrypt = cast5_decrypt
}
}
};
static int __init cast5_mod_init(void)
{
return crypto_register_alg(&alg);
}
static void __exit cast5_mod_fini(void)
{
crypto_unregister_alg(&alg);
}
module_init(cast5_mod_init);
module_exit(cast5_mod_fini);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Cast5 Cipher Algorithm");
MODULE_ALIAS_CRYPTO("cast5");
MODULE_ALIAS_CRYPTO("cast5-generic");
| gpl-2.0 |
russelldias98/Omega-Kernel | fs/btrfs/extent_io.c | 2356 | 96304 | #include <linux/bitops.h>
#include <linux/slab.h>
#include <linux/bio.h>
#include <linux/mm.h>
#include <linux/pagemap.h>
#include <linux/page-flags.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/blkdev.h>
#include <linux/swap.h>
#include <linux/writeback.h>
#include <linux/pagevec.h>
#include <linux/prefetch.h>
#include <linux/cleancache.h>
#include "extent_io.h"
#include "extent_map.h"
#include "compat.h"
#include "ctree.h"
#include "btrfs_inode.h"
static struct kmem_cache *extent_state_cache;
static struct kmem_cache *extent_buffer_cache;
static LIST_HEAD(buffers);
static LIST_HEAD(states);
#define LEAK_DEBUG 0
#if LEAK_DEBUG
static DEFINE_SPINLOCK(leak_lock);
#endif
#define BUFFER_LRU_MAX 64
struct tree_entry {
u64 start;
u64 end;
struct rb_node rb_node;
};
struct extent_page_data {
struct bio *bio;
struct extent_io_tree *tree;
get_extent_t *get_extent;
/* tells writepage not to lock the state bits for this range
* it still does the unlocking
*/
unsigned int extent_locked:1;
/* tells the submit_bio code to use a WRITE_SYNC */
unsigned int sync_io:1;
};
int __init extent_io_init(void)
{
extent_state_cache = kmem_cache_create("extent_state",
sizeof(struct extent_state), 0,
SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
if (!extent_state_cache)
return -ENOMEM;
extent_buffer_cache = kmem_cache_create("extent_buffers",
sizeof(struct extent_buffer), 0,
SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
if (!extent_buffer_cache)
goto free_state_cache;
return 0;
free_state_cache:
kmem_cache_destroy(extent_state_cache);
return -ENOMEM;
}
void extent_io_exit(void)
{
struct extent_state *state;
struct extent_buffer *eb;
while (!list_empty(&states)) {
state = list_entry(states.next, struct extent_state, leak_list);
printk(KERN_ERR "btrfs state leak: start %llu end %llu "
"state %lu in tree %p refs %d\n",
(unsigned long long)state->start,
(unsigned long long)state->end,
state->state, state->tree, atomic_read(&state->refs));
list_del(&state->leak_list);
kmem_cache_free(extent_state_cache, state);
}
while (!list_empty(&buffers)) {
eb = list_entry(buffers.next, struct extent_buffer, leak_list);
printk(KERN_ERR "btrfs buffer leak start %llu len %lu "
"refs %d\n", (unsigned long long)eb->start,
eb->len, atomic_read(&eb->refs));
list_del(&eb->leak_list);
kmem_cache_free(extent_buffer_cache, eb);
}
if (extent_state_cache)
kmem_cache_destroy(extent_state_cache);
if (extent_buffer_cache)
kmem_cache_destroy(extent_buffer_cache);
}
void extent_io_tree_init(struct extent_io_tree *tree,
struct address_space *mapping)
{
tree->state = RB_ROOT;
INIT_RADIX_TREE(&tree->buffer, GFP_ATOMIC);
tree->ops = NULL;
tree->dirty_bytes = 0;
spin_lock_init(&tree->lock);
spin_lock_init(&tree->buffer_lock);
tree->mapping = mapping;
}
static struct extent_state *alloc_extent_state(gfp_t mask)
{
struct extent_state *state;
#if LEAK_DEBUG
unsigned long flags;
#endif
state = kmem_cache_alloc(extent_state_cache, mask);
if (!state)
return state;
state->state = 0;
state->private = 0;
state->tree = NULL;
#if LEAK_DEBUG
spin_lock_irqsave(&leak_lock, flags);
list_add(&state->leak_list, &states);
spin_unlock_irqrestore(&leak_lock, flags);
#endif
atomic_set(&state->refs, 1);
init_waitqueue_head(&state->wq);
return state;
}
void free_extent_state(struct extent_state *state)
{
if (!state)
return;
if (atomic_dec_and_test(&state->refs)) {
#if LEAK_DEBUG
unsigned long flags;
#endif
WARN_ON(state->tree);
#if LEAK_DEBUG
spin_lock_irqsave(&leak_lock, flags);
list_del(&state->leak_list);
spin_unlock_irqrestore(&leak_lock, flags);
#endif
kmem_cache_free(extent_state_cache, state);
}
}
static struct rb_node *tree_insert(struct rb_root *root, u64 offset,
struct rb_node *node)
{
struct rb_node **p = &root->rb_node;
struct rb_node *parent = NULL;
struct tree_entry *entry;
while (*p) {
parent = *p;
entry = rb_entry(parent, struct tree_entry, rb_node);
if (offset < entry->start)
p = &(*p)->rb_left;
else if (offset > entry->end)
p = &(*p)->rb_right;
else
return parent;
}
entry = rb_entry(node, struct tree_entry, rb_node);
rb_link_node(node, parent, p);
rb_insert_color(node, root);
return NULL;
}
static struct rb_node *__etree_search(struct extent_io_tree *tree, u64 offset,
struct rb_node **prev_ret,
struct rb_node **next_ret)
{
struct rb_root *root = &tree->state;
struct rb_node *n = root->rb_node;
struct rb_node *prev = NULL;
struct rb_node *orig_prev = NULL;
struct tree_entry *entry;
struct tree_entry *prev_entry = NULL;
while (n) {
entry = rb_entry(n, struct tree_entry, rb_node);
prev = n;
prev_entry = entry;
if (offset < entry->start)
n = n->rb_left;
else if (offset > entry->end)
n = n->rb_right;
else
return n;
}
if (prev_ret) {
orig_prev = prev;
while (prev && offset > prev_entry->end) {
prev = rb_next(prev);
prev_entry = rb_entry(prev, struct tree_entry, rb_node);
}
*prev_ret = prev;
prev = orig_prev;
}
if (next_ret) {
prev_entry = rb_entry(prev, struct tree_entry, rb_node);
while (prev && offset < prev_entry->start) {
prev = rb_prev(prev);
prev_entry = rb_entry(prev, struct tree_entry, rb_node);
}
*next_ret = prev;
}
return NULL;
}
static inline struct rb_node *tree_search(struct extent_io_tree *tree,
u64 offset)
{
struct rb_node *prev = NULL;
struct rb_node *ret;
ret = __etree_search(tree, offset, &prev, NULL);
if (!ret)
return prev;
return ret;
}
static void merge_cb(struct extent_io_tree *tree, struct extent_state *new,
struct extent_state *other)
{
if (tree->ops && tree->ops->merge_extent_hook)
tree->ops->merge_extent_hook(tree->mapping->host, new,
other);
}
/*
* utility function to look for merge candidates inside a given range.
* Any extents with matching state are merged together into a single
* extent in the tree. Extents with EXTENT_IO in their state field
* are not merged because the end_io handlers need to be able to do
* operations on them without sleeping (or doing allocations/splits).
*
* This should be called with the tree lock held.
*/
static int merge_state(struct extent_io_tree *tree,
struct extent_state *state)
{
struct extent_state *other;
struct rb_node *other_node;
if (state->state & (EXTENT_IOBITS | EXTENT_BOUNDARY))
return 0;
other_node = rb_prev(&state->rb_node);
if (other_node) {
other = rb_entry(other_node, struct extent_state, rb_node);
if (other->end == state->start - 1 &&
other->state == state->state) {
merge_cb(tree, state, other);
state->start = other->start;
other->tree = NULL;
rb_erase(&other->rb_node, &tree->state);
free_extent_state(other);
}
}
other_node = rb_next(&state->rb_node);
if (other_node) {
other = rb_entry(other_node, struct extent_state, rb_node);
if (other->start == state->end + 1 &&
other->state == state->state) {
merge_cb(tree, state, other);
other->start = state->start;
state->tree = NULL;
rb_erase(&state->rb_node, &tree->state);
free_extent_state(state);
state = NULL;
}
}
return 0;
}
static int set_state_cb(struct extent_io_tree *tree,
struct extent_state *state, int *bits)
{
if (tree->ops && tree->ops->set_bit_hook) {
return tree->ops->set_bit_hook(tree->mapping->host,
state, bits);
}
return 0;
}
static void clear_state_cb(struct extent_io_tree *tree,
struct extent_state *state, int *bits)
{
if (tree->ops && tree->ops->clear_bit_hook)
tree->ops->clear_bit_hook(tree->mapping->host, state, bits);
}
/*
* insert an extent_state struct into the tree. 'bits' are set on the
* struct before it is inserted.
*
* This may return -EEXIST if the extent is already there, in which case the
* state struct is freed.
*
* The tree lock is not taken internally. This is a utility function and
* probably isn't what you want to call (see set/clear_extent_bit).
*/
static int insert_state(struct extent_io_tree *tree,
struct extent_state *state, u64 start, u64 end,
int *bits)
{
struct rb_node *node;
int bits_to_set = *bits & ~EXTENT_CTLBITS;
int ret;
if (end < start) {
printk(KERN_ERR "btrfs end < start %llu %llu\n",
(unsigned long long)end,
(unsigned long long)start);
WARN_ON(1);
}
state->start = start;
state->end = end;
ret = set_state_cb(tree, state, bits);
if (ret)
return ret;
if (bits_to_set & EXTENT_DIRTY)
tree->dirty_bytes += end - start + 1;
state->state |= bits_to_set;
node = tree_insert(&tree->state, end, &state->rb_node);
if (node) {
struct extent_state *found;
found = rb_entry(node, struct extent_state, rb_node);
printk(KERN_ERR "btrfs found node %llu %llu on insert of "
"%llu %llu\n", (unsigned long long)found->start,
(unsigned long long)found->end,
(unsigned long long)start, (unsigned long long)end);
free_extent_state(state);
return -EEXIST;
}
state->tree = tree;
merge_state(tree, state);
return 0;
}
static int split_cb(struct extent_io_tree *tree, struct extent_state *orig,
u64 split)
{
if (tree->ops && tree->ops->split_extent_hook)
return tree->ops->split_extent_hook(tree->mapping->host,
orig, split);
return 0;
}
/*
* split a given extent state struct in two, inserting the preallocated
* struct 'prealloc' as the newly created second half. 'split' indicates an
* offset inside 'orig' where it should be split.
*
* Before calling,
* the tree has 'orig' at [orig->start, orig->end]. After calling, there
* are two extent state structs in the tree:
* prealloc: [orig->start, split - 1]
* orig: [ split, orig->end ]
*
* The tree locks are not taken by this function. They need to be held
* by the caller.
*/
static int split_state(struct extent_io_tree *tree, struct extent_state *orig,
struct extent_state *prealloc, u64 split)
{
struct rb_node *node;
split_cb(tree, orig, split);
prealloc->start = orig->start;
prealloc->end = split - 1;
prealloc->state = orig->state;
orig->start = split;
node = tree_insert(&tree->state, prealloc->end, &prealloc->rb_node);
if (node) {
free_extent_state(prealloc);
return -EEXIST;
}
prealloc->tree = tree;
return 0;
}
/*
* utility function to clear some bits in an extent state struct.
* it will optionally wake up any one waiting on this state (wake == 1), or
* forcibly remove the state from the tree (delete == 1).
*
* If no bits are set on the state struct after clearing things, the
* struct is freed and removed from the tree
*/
static int clear_state_bit(struct extent_io_tree *tree,
struct extent_state *state,
int *bits, int wake)
{
int bits_to_clear = *bits & ~EXTENT_CTLBITS;
int ret = state->state & bits_to_clear;
if ((bits_to_clear & EXTENT_DIRTY) && (state->state & EXTENT_DIRTY)) {
u64 range = state->end - state->start + 1;
WARN_ON(range > tree->dirty_bytes);
tree->dirty_bytes -= range;
}
clear_state_cb(tree, state, bits);
state->state &= ~bits_to_clear;
if (wake)
wake_up(&state->wq);
if (state->state == 0) {
if (state->tree) {
rb_erase(&state->rb_node, &tree->state);
state->tree = NULL;
free_extent_state(state);
} else {
WARN_ON(1);
}
} else {
merge_state(tree, state);
}
return ret;
}
static struct extent_state *
alloc_extent_state_atomic(struct extent_state *prealloc)
{
if (!prealloc)
prealloc = alloc_extent_state(GFP_ATOMIC);
return prealloc;
}
/*
* clear some bits on a range in the tree. This may require splitting
* or inserting elements in the tree, so the gfp mask is used to
* indicate which allocations or sleeping are allowed.
*
* pass 'wake' == 1 to kick any sleepers, and 'delete' == 1 to remove
* the given range from the tree regardless of state (ie for truncate).
*
* the range [start, end] is inclusive.
*
* This takes the tree lock, and returns < 0 on error, > 0 if any of the
* bits were already set, or zero if none of the bits were already set.
*/
int clear_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
int bits, int wake, int delete,
struct extent_state **cached_state,
gfp_t mask)
{
struct extent_state *state;
struct extent_state *cached;
struct extent_state *prealloc = NULL;
struct rb_node *next_node;
struct rb_node *node;
u64 last_end;
int err;
int set = 0;
int clear = 0;
if (delete)
bits |= ~EXTENT_CTLBITS;
bits |= EXTENT_FIRST_DELALLOC;
if (bits & (EXTENT_IOBITS | EXTENT_BOUNDARY))
clear = 1;
again:
if (!prealloc && (mask & __GFP_WAIT)) {
prealloc = alloc_extent_state(mask);
if (!prealloc)
return -ENOMEM;
}
spin_lock(&tree->lock);
if (cached_state) {
cached = *cached_state;
if (clear) {
*cached_state = NULL;
cached_state = NULL;
}
if (cached && cached->tree && cached->start == start) {
if (clear)
atomic_dec(&cached->refs);
state = cached;
goto hit_next;
}
if (clear)
free_extent_state(cached);
}
/*
* this search will find the extents that end after
* our range starts
*/
node = tree_search(tree, start);
if (!node)
goto out;
state = rb_entry(node, struct extent_state, rb_node);
hit_next:
if (state->start > end)
goto out;
WARN_ON(state->end < start);
last_end = state->end;
/*
* | ---- desired range ---- |
* | state | or
* | ------------- state -------------- |
*
* We need to split the extent we found, and may flip
* bits on second half.
*
* If the extent we found extends past our range, we
* just split and search again. It'll get split again
* the next time though.
*
* If the extent we found is inside our range, we clear
* the desired bit on it.
*/
if (state->start < start) {
prealloc = alloc_extent_state_atomic(prealloc);
BUG_ON(!prealloc);
err = split_state(tree, state, prealloc, start);
BUG_ON(err == -EEXIST);
prealloc = NULL;
if (err)
goto out;
if (state->end <= end) {
set |= clear_state_bit(tree, state, &bits, wake);
if (last_end == (u64)-1)
goto out;
start = last_end + 1;
}
goto search_again;
}
/*
* | ---- desired range ---- |
* | state |
* We need to split the extent, and clear the bit
* on the first half
*/
if (state->start <= end && state->end > end) {
prealloc = alloc_extent_state_atomic(prealloc);
BUG_ON(!prealloc);
err = split_state(tree, state, prealloc, end + 1);
BUG_ON(err == -EEXIST);
if (wake)
wake_up(&state->wq);
set |= clear_state_bit(tree, prealloc, &bits, wake);
prealloc = NULL;
goto out;
}
if (state->end < end && prealloc && !need_resched())
next_node = rb_next(&state->rb_node);
else
next_node = NULL;
set |= clear_state_bit(tree, state, &bits, wake);
if (last_end == (u64)-1)
goto out;
start = last_end + 1;
if (start <= end && next_node) {
state = rb_entry(next_node, struct extent_state,
rb_node);
if (state->start == start)
goto hit_next;
}
goto search_again;
out:
spin_unlock(&tree->lock);
if (prealloc)
free_extent_state(prealloc);
return set;
search_again:
if (start > end)
goto out;
spin_unlock(&tree->lock);
if (mask & __GFP_WAIT)
cond_resched();
goto again;
}
static int wait_on_state(struct extent_io_tree *tree,
struct extent_state *state)
__releases(tree->lock)
__acquires(tree->lock)
{
DEFINE_WAIT(wait);
prepare_to_wait(&state->wq, &wait, TASK_UNINTERRUPTIBLE);
spin_unlock(&tree->lock);
schedule();
spin_lock(&tree->lock);
finish_wait(&state->wq, &wait);
return 0;
}
/*
* waits for one or more bits to clear on a range in the state tree.
* The range [start, end] is inclusive.
* The tree lock is taken by this function
*/
int wait_extent_bit(struct extent_io_tree *tree, u64 start, u64 end, int bits)
{
struct extent_state *state;
struct rb_node *node;
spin_lock(&tree->lock);
again:
while (1) {
/*
* this search will find all the extents that end after
* our range starts
*/
node = tree_search(tree, start);
if (!node)
break;
state = rb_entry(node, struct extent_state, rb_node);
if (state->start > end)
goto out;
if (state->state & bits) {
start = state->start;
atomic_inc(&state->refs);
wait_on_state(tree, state);
free_extent_state(state);
goto again;
}
start = state->end + 1;
if (start > end)
break;
if (need_resched()) {
spin_unlock(&tree->lock);
cond_resched();
spin_lock(&tree->lock);
}
}
out:
spin_unlock(&tree->lock);
return 0;
}
static int set_state_bits(struct extent_io_tree *tree,
struct extent_state *state,
int *bits)
{
int ret;
int bits_to_set = *bits & ~EXTENT_CTLBITS;
ret = set_state_cb(tree, state, bits);
if (ret)
return ret;
if ((bits_to_set & EXTENT_DIRTY) && !(state->state & EXTENT_DIRTY)) {
u64 range = state->end - state->start + 1;
tree->dirty_bytes += range;
}
state->state |= bits_to_set;
return 0;
}
static void cache_state(struct extent_state *state,
struct extent_state **cached_ptr)
{
if (cached_ptr && !(*cached_ptr)) {
if (state->state & (EXTENT_IOBITS | EXTENT_BOUNDARY)) {
*cached_ptr = state;
atomic_inc(&state->refs);
}
}
}
static void uncache_state(struct extent_state **cached_ptr)
{
if (cached_ptr && (*cached_ptr)) {
struct extent_state *state = *cached_ptr;
*cached_ptr = NULL;
free_extent_state(state);
}
}
/*
* set some bits on a range in the tree. This may require allocations or
* sleeping, so the gfp mask is used to indicate what is allowed.
*
* If any of the exclusive bits are set, this will fail with -EEXIST if some
* part of the range already has the desired bits set. The start of the
* existing range is returned in failed_start in this case.
*
* [start, end] is inclusive This takes the tree lock.
*/
int set_extent_bit(struct extent_io_tree *tree, u64 start, u64 end,
int bits, int exclusive_bits, u64 *failed_start,
struct extent_state **cached_state, gfp_t mask)
{
struct extent_state *state;
struct extent_state *prealloc = NULL;
struct rb_node *node;
int err = 0;
u64 last_start;
u64 last_end;
bits |= EXTENT_FIRST_DELALLOC;
again:
if (!prealloc && (mask & __GFP_WAIT)) {
prealloc = alloc_extent_state(mask);
BUG_ON(!prealloc);
}
spin_lock(&tree->lock);
if (cached_state && *cached_state) {
state = *cached_state;
if (state->start == start && state->tree) {
node = &state->rb_node;
goto hit_next;
}
}
/*
* this search will find all the extents that end after
* our range starts.
*/
node = tree_search(tree, start);
if (!node) {
prealloc = alloc_extent_state_atomic(prealloc);
BUG_ON(!prealloc);
err = insert_state(tree, prealloc, start, end, &bits);
prealloc = NULL;
BUG_ON(err == -EEXIST);
goto out;
}
state = rb_entry(node, struct extent_state, rb_node);
hit_next:
last_start = state->start;
last_end = state->end;
/*
* | ---- desired range ---- |
* | state |
*
* Just lock what we found and keep going
*/
if (state->start == start && state->end <= end) {
struct rb_node *next_node;
if (state->state & exclusive_bits) {
*failed_start = state->start;
err = -EEXIST;
goto out;
}
err = set_state_bits(tree, state, &bits);
if (err)
goto out;
next_node = rb_next(node);
cache_state(state, cached_state);
merge_state(tree, state);
if (last_end == (u64)-1)
goto out;
start = last_end + 1;
if (next_node && start < end && prealloc && !need_resched()) {
state = rb_entry(next_node, struct extent_state,
rb_node);
if (state->start == start)
goto hit_next;
}
goto search_again;
}
/*
* | ---- desired range ---- |
* | state |
* or
* | ------------- state -------------- |
*
* We need to split the extent we found, and may flip bits on
* second half.
*
* If the extent we found extends past our
* range, we just split and search again. It'll get split
* again the next time though.
*
* If the extent we found is inside our range, we set the
* desired bit on it.
*/
if (state->start < start) {
if (state->state & exclusive_bits) {
*failed_start = start;
err = -EEXIST;
goto out;
}
prealloc = alloc_extent_state_atomic(prealloc);
BUG_ON(!prealloc);
err = split_state(tree, state, prealloc, start);
BUG_ON(err == -EEXIST);
prealloc = NULL;
if (err)
goto out;
if (state->end <= end) {
err = set_state_bits(tree, state, &bits);
if (err)
goto out;
cache_state(state, cached_state);
merge_state(tree, state);
if (last_end == (u64)-1)
goto out;
start = last_end + 1;
}
goto search_again;
}
/*
* | ---- desired range ---- |
* | state | or | state |
*
* There's a hole, we need to insert something in it and
* ignore the extent we found.
*/
if (state->start > start) {
u64 this_end;
if (end < last_start)
this_end = end;
else
this_end = last_start - 1;
prealloc = alloc_extent_state_atomic(prealloc);
BUG_ON(!prealloc);
/*
* Avoid to free 'prealloc' if it can be merged with
* the later extent.
*/
atomic_inc(&prealloc->refs);
err = insert_state(tree, prealloc, start, this_end,
&bits);
BUG_ON(err == -EEXIST);
if (err) {
free_extent_state(prealloc);
prealloc = NULL;
goto out;
}
cache_state(prealloc, cached_state);
free_extent_state(prealloc);
prealloc = NULL;
start = this_end + 1;
goto search_again;
}
/*
* | ---- desired range ---- |
* | state |
* We need to split the extent, and set the bit
* on the first half
*/
if (state->start <= end && state->end > end) {
if (state->state & exclusive_bits) {
*failed_start = start;
err = -EEXIST;
goto out;
}
prealloc = alloc_extent_state_atomic(prealloc);
BUG_ON(!prealloc);
err = split_state(tree, state, prealloc, end + 1);
BUG_ON(err == -EEXIST);
err = set_state_bits(tree, prealloc, &bits);
if (err) {
prealloc = NULL;
goto out;
}
cache_state(prealloc, cached_state);
merge_state(tree, prealloc);
prealloc = NULL;
goto out;
}
goto search_again;
out:
spin_unlock(&tree->lock);
if (prealloc)
free_extent_state(prealloc);
return err;
search_again:
if (start > end)
goto out;
spin_unlock(&tree->lock);
if (mask & __GFP_WAIT)
cond_resched();
goto again;
}
/* wrappers around set/clear extent bit */
int set_extent_dirty(struct extent_io_tree *tree, u64 start, u64 end,
gfp_t mask)
{
return set_extent_bit(tree, start, end, EXTENT_DIRTY, 0, NULL,
NULL, mask);
}
int set_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
int bits, gfp_t mask)
{
return set_extent_bit(tree, start, end, bits, 0, NULL,
NULL, mask);
}
int clear_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
int bits, gfp_t mask)
{
return clear_extent_bit(tree, start, end, bits, 0, 0, NULL, mask);
}
int set_extent_delalloc(struct extent_io_tree *tree, u64 start, u64 end,
struct extent_state **cached_state, gfp_t mask)
{
return set_extent_bit(tree, start, end,
EXTENT_DELALLOC | EXTENT_DIRTY | EXTENT_UPTODATE,
0, NULL, cached_state, mask);
}
int clear_extent_dirty(struct extent_io_tree *tree, u64 start, u64 end,
gfp_t mask)
{
return clear_extent_bit(tree, start, end,
EXTENT_DIRTY | EXTENT_DELALLOC |
EXTENT_DO_ACCOUNTING, 0, 0, NULL, mask);
}
int set_extent_new(struct extent_io_tree *tree, u64 start, u64 end,
gfp_t mask)
{
return set_extent_bit(tree, start, end, EXTENT_NEW, 0, NULL,
NULL, mask);
}
int set_extent_uptodate(struct extent_io_tree *tree, u64 start, u64 end,
struct extent_state **cached_state, gfp_t mask)
{
return set_extent_bit(tree, start, end, EXTENT_UPTODATE, 0,
NULL, cached_state, mask);
}
static int clear_extent_uptodate(struct extent_io_tree *tree, u64 start,
u64 end, struct extent_state **cached_state,
gfp_t mask)
{
return clear_extent_bit(tree, start, end, EXTENT_UPTODATE, 0, 0,
cached_state, mask);
}
/*
* either insert or lock state struct between start and end use mask to tell
* us if waiting is desired.
*/
int lock_extent_bits(struct extent_io_tree *tree, u64 start, u64 end,
int bits, struct extent_state **cached_state, gfp_t mask)
{
int err;
u64 failed_start;
while (1) {
err = set_extent_bit(tree, start, end, EXTENT_LOCKED | bits,
EXTENT_LOCKED, &failed_start,
cached_state, mask);
if (err == -EEXIST && (mask & __GFP_WAIT)) {
wait_extent_bit(tree, failed_start, end, EXTENT_LOCKED);
start = failed_start;
} else {
break;
}
WARN_ON(start > end);
}
return err;
}
int lock_extent(struct extent_io_tree *tree, u64 start, u64 end, gfp_t mask)
{
return lock_extent_bits(tree, start, end, 0, NULL, mask);
}
int try_lock_extent(struct extent_io_tree *tree, u64 start, u64 end,
gfp_t mask)
{
int err;
u64 failed_start;
err = set_extent_bit(tree, start, end, EXTENT_LOCKED, EXTENT_LOCKED,
&failed_start, NULL, mask);
if (err == -EEXIST) {
if (failed_start > start)
clear_extent_bit(tree, start, failed_start - 1,
EXTENT_LOCKED, 1, 0, NULL, mask);
return 0;
}
return 1;
}
int unlock_extent_cached(struct extent_io_tree *tree, u64 start, u64 end,
struct extent_state **cached, gfp_t mask)
{
return clear_extent_bit(tree, start, end, EXTENT_LOCKED, 1, 0, cached,
mask);
}
int unlock_extent(struct extent_io_tree *tree, u64 start, u64 end, gfp_t mask)
{
return clear_extent_bit(tree, start, end, EXTENT_LOCKED, 1, 0, NULL,
mask);
}
/*
* helper function to set both pages and extents in the tree writeback
*/
static int set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
{
unsigned long index = start >> PAGE_CACHE_SHIFT;
unsigned long end_index = end >> PAGE_CACHE_SHIFT;
struct page *page;
while (index <= end_index) {
page = find_get_page(tree->mapping, index);
BUG_ON(!page);
set_page_writeback(page);
page_cache_release(page);
index++;
}
return 0;
}
/*
* find the first offset in the io tree with 'bits' set. zero is
* returned if we find something, and *start_ret and *end_ret are
* set to reflect the state struct that was found.
*
* If nothing was found, 1 is returned, < 0 on error
*/
int find_first_extent_bit(struct extent_io_tree *tree, u64 start,
u64 *start_ret, u64 *end_ret, int bits)
{
struct rb_node *node;
struct extent_state *state;
int ret = 1;
spin_lock(&tree->lock);
/*
* this search will find all the extents that end after
* our range starts.
*/
node = tree_search(tree, start);
if (!node)
goto out;
while (1) {
state = rb_entry(node, struct extent_state, rb_node);
if (state->end >= start && (state->state & bits)) {
*start_ret = state->start;
*end_ret = state->end;
ret = 0;
break;
}
node = rb_next(node);
if (!node)
break;
}
out:
spin_unlock(&tree->lock);
return ret;
}
/* find the first state struct with 'bits' set after 'start', and
* return it. tree->lock must be held. NULL will returned if
* nothing was found after 'start'
*/
struct extent_state *find_first_extent_bit_state(struct extent_io_tree *tree,
u64 start, int bits)
{
struct rb_node *node;
struct extent_state *state;
/*
* this search will find all the extents that end after
* our range starts.
*/
node = tree_search(tree, start);
if (!node)
goto out;
while (1) {
state = rb_entry(node, struct extent_state, rb_node);
if (state->end >= start && (state->state & bits))
return state;
node = rb_next(node);
if (!node)
break;
}
out:
return NULL;
}
/*
* find a contiguous range of bytes in the file marked as delalloc, not
* more than 'max_bytes'. start and end are used to return the range,
*
* 1 is returned if we find something, 0 if nothing was in the tree
*/
static noinline u64 find_delalloc_range(struct extent_io_tree *tree,
u64 *start, u64 *end, u64 max_bytes,
struct extent_state **cached_state)
{
struct rb_node *node;
struct extent_state *state;
u64 cur_start = *start;
u64 found = 0;
u64 total_bytes = 0;
spin_lock(&tree->lock);
/*
* this search will find all the extents that end after
* our range starts.
*/
node = tree_search(tree, cur_start);
if (!node) {
if (!found)
*end = (u64)-1;
goto out;
}
while (1) {
state = rb_entry(node, struct extent_state, rb_node);
if (found && (state->start != cur_start ||
(state->state & EXTENT_BOUNDARY))) {
goto out;
}
if (!(state->state & EXTENT_DELALLOC)) {
if (!found)
*end = state->end;
goto out;
}
if (!found) {
*start = state->start;
*cached_state = state;
atomic_inc(&state->refs);
}
found++;
*end = state->end;
cur_start = state->end + 1;
node = rb_next(node);
if (!node)
break;
total_bytes += state->end - state->start + 1;
if (total_bytes >= max_bytes)
break;
}
out:
spin_unlock(&tree->lock);
return found;
}
static noinline int __unlock_for_delalloc(struct inode *inode,
struct page *locked_page,
u64 start, u64 end)
{
int ret;
struct page *pages[16];
unsigned long index = start >> PAGE_CACHE_SHIFT;
unsigned long end_index = end >> PAGE_CACHE_SHIFT;
unsigned long nr_pages = end_index - index + 1;
int i;
if (index == locked_page->index && end_index == index)
return 0;
while (nr_pages > 0) {
ret = find_get_pages_contig(inode->i_mapping, index,
min_t(unsigned long, nr_pages,
ARRAY_SIZE(pages)), pages);
for (i = 0; i < ret; i++) {
if (pages[i] != locked_page)
unlock_page(pages[i]);
page_cache_release(pages[i]);
}
nr_pages -= ret;
index += ret;
cond_resched();
}
return 0;
}
static noinline int lock_delalloc_pages(struct inode *inode,
struct page *locked_page,
u64 delalloc_start,
u64 delalloc_end)
{
unsigned long index = delalloc_start >> PAGE_CACHE_SHIFT;
unsigned long start_index = index;
unsigned long end_index = delalloc_end >> PAGE_CACHE_SHIFT;
unsigned long pages_locked = 0;
struct page *pages[16];
unsigned long nrpages;
int ret;
int i;
/* the caller is responsible for locking the start index */
if (index == locked_page->index && index == end_index)
return 0;
/* skip the page at the start index */
nrpages = end_index - index + 1;
while (nrpages > 0) {
ret = find_get_pages_contig(inode->i_mapping, index,
min_t(unsigned long,
nrpages, ARRAY_SIZE(pages)), pages);
if (ret == 0) {
ret = -EAGAIN;
goto done;
}
/* now we have an array of pages, lock them all */
for (i = 0; i < ret; i++) {
/*
* the caller is taking responsibility for
* locked_page
*/
if (pages[i] != locked_page) {
lock_page(pages[i]);
if (!PageDirty(pages[i]) ||
pages[i]->mapping != inode->i_mapping) {
ret = -EAGAIN;
unlock_page(pages[i]);
page_cache_release(pages[i]);
goto done;
}
}
page_cache_release(pages[i]);
pages_locked++;
}
nrpages -= ret;
index += ret;
cond_resched();
}
ret = 0;
done:
if (ret && pages_locked) {
__unlock_for_delalloc(inode, locked_page,
delalloc_start,
((u64)(start_index + pages_locked - 1)) <<
PAGE_CACHE_SHIFT);
}
return ret;
}
/*
* find a contiguous range of bytes in the file marked as delalloc, not
* more than 'max_bytes'. start and end are used to return the range,
*
* 1 is returned if we find something, 0 if nothing was in the tree
*/
static noinline u64 find_lock_delalloc_range(struct inode *inode,
struct extent_io_tree *tree,
struct page *locked_page,
u64 *start, u64 *end,
u64 max_bytes)
{
u64 delalloc_start;
u64 delalloc_end;
u64 found;
struct extent_state *cached_state = NULL;
int ret;
int loops = 0;
again:
/* step one, find a bunch of delalloc bytes starting at start */
delalloc_start = *start;
delalloc_end = 0;
found = find_delalloc_range(tree, &delalloc_start, &delalloc_end,
max_bytes, &cached_state);
if (!found || delalloc_end <= *start) {
*start = delalloc_start;
*end = delalloc_end;
free_extent_state(cached_state);
return found;
}
/*
* start comes from the offset of locked_page. We have to lock
* pages in order, so we can't process delalloc bytes before
* locked_page
*/
if (delalloc_start < *start)
delalloc_start = *start;
/*
* make sure to limit the number of pages we try to lock down
* if we're looping.
*/
if (delalloc_end + 1 - delalloc_start > max_bytes && loops)
delalloc_end = delalloc_start + PAGE_CACHE_SIZE - 1;
/* step two, lock all the pages after the page that has start */
ret = lock_delalloc_pages(inode, locked_page,
delalloc_start, delalloc_end);
if (ret == -EAGAIN) {
/* some of the pages are gone, lets avoid looping by
* shortening the size of the delalloc range we're searching
*/
free_extent_state(cached_state);
if (!loops) {
unsigned long offset = (*start) & (PAGE_CACHE_SIZE - 1);
max_bytes = PAGE_CACHE_SIZE - offset;
loops = 1;
goto again;
} else {
found = 0;
goto out_failed;
}
}
BUG_ON(ret);
/* step three, lock the state bits for the whole range */
lock_extent_bits(tree, delalloc_start, delalloc_end,
0, &cached_state, GFP_NOFS);
/* then test to make sure it is all still delalloc */
ret = test_range_bit(tree, delalloc_start, delalloc_end,
EXTENT_DELALLOC, 1, cached_state);
if (!ret) {
unlock_extent_cached(tree, delalloc_start, delalloc_end,
&cached_state, GFP_NOFS);
__unlock_for_delalloc(inode, locked_page,
delalloc_start, delalloc_end);
cond_resched();
goto again;
}
free_extent_state(cached_state);
*start = delalloc_start;
*end = delalloc_end;
out_failed:
return found;
}
int extent_clear_unlock_delalloc(struct inode *inode,
struct extent_io_tree *tree,
u64 start, u64 end, struct page *locked_page,
unsigned long op)
{
int ret;
struct page *pages[16];
unsigned long index = start >> PAGE_CACHE_SHIFT;
unsigned long end_index = end >> PAGE_CACHE_SHIFT;
unsigned long nr_pages = end_index - index + 1;
int i;
int clear_bits = 0;
if (op & EXTENT_CLEAR_UNLOCK)
clear_bits |= EXTENT_LOCKED;
if (op & EXTENT_CLEAR_DIRTY)
clear_bits |= EXTENT_DIRTY;
if (op & EXTENT_CLEAR_DELALLOC)
clear_bits |= EXTENT_DELALLOC;
clear_extent_bit(tree, start, end, clear_bits, 1, 0, NULL, GFP_NOFS);
if (!(op & (EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK |
EXTENT_SET_PRIVATE2)))
return 0;
while (nr_pages > 0) {
ret = find_get_pages_contig(inode->i_mapping, index,
min_t(unsigned long,
nr_pages, ARRAY_SIZE(pages)), pages);
for (i = 0; i < ret; i++) {
if (op & EXTENT_SET_PRIVATE2)
SetPagePrivate2(pages[i]);
if (pages[i] == locked_page) {
page_cache_release(pages[i]);
continue;
}
if (op & EXTENT_CLEAR_DIRTY)
clear_page_dirty_for_io(pages[i]);
if (op & EXTENT_SET_WRITEBACK)
set_page_writeback(pages[i]);
if (op & EXTENT_END_WRITEBACK)
end_page_writeback(pages[i]);
if (op & EXTENT_CLEAR_UNLOCK_PAGE)
unlock_page(pages[i]);
page_cache_release(pages[i]);
}
nr_pages -= ret;
index += ret;
cond_resched();
}
return 0;
}
/*
* count the number of bytes in the tree that have a given bit(s)
* set. This can be fairly slow, except for EXTENT_DIRTY which is
* cached. The total number found is returned.
*/
u64 count_range_bits(struct extent_io_tree *tree,
u64 *start, u64 search_end, u64 max_bytes,
unsigned long bits, int contig)
{
struct rb_node *node;
struct extent_state *state;
u64 cur_start = *start;
u64 total_bytes = 0;
u64 last = 0;
int found = 0;
if (search_end <= cur_start) {
WARN_ON(1);
return 0;
}
spin_lock(&tree->lock);
if (cur_start == 0 && bits == EXTENT_DIRTY) {
total_bytes = tree->dirty_bytes;
goto out;
}
/*
* this search will find all the extents that end after
* our range starts.
*/
node = tree_search(tree, cur_start);
if (!node)
goto out;
while (1) {
state = rb_entry(node, struct extent_state, rb_node);
if (state->start > search_end)
break;
if (contig && found && state->start > last + 1)
break;
if (state->end >= cur_start && (state->state & bits) == bits) {
total_bytes += min(search_end, state->end) + 1 -
max(cur_start, state->start);
if (total_bytes >= max_bytes)
break;
if (!found) {
*start = max(cur_start, state->start);
found = 1;
}
last = state->end;
} else if (contig && found) {
break;
}
node = rb_next(node);
if (!node)
break;
}
out:
spin_unlock(&tree->lock);
return total_bytes;
}
/*
* set the private field for a given byte offset in the tree. If there isn't
* an extent_state there already, this does nothing.
*/
int set_state_private(struct extent_io_tree *tree, u64 start, u64 private)
{
struct rb_node *node;
struct extent_state *state;
int ret = 0;
spin_lock(&tree->lock);
/*
* this search will find all the extents that end after
* our range starts.
*/
node = tree_search(tree, start);
if (!node) {
ret = -ENOENT;
goto out;
}
state = rb_entry(node, struct extent_state, rb_node);
if (state->start != start) {
ret = -ENOENT;
goto out;
}
state->private = private;
out:
spin_unlock(&tree->lock);
return ret;
}
int get_state_private(struct extent_io_tree *tree, u64 start, u64 *private)
{
struct rb_node *node;
struct extent_state *state;
int ret = 0;
spin_lock(&tree->lock);
/*
* this search will find all the extents that end after
* our range starts.
*/
node = tree_search(tree, start);
if (!node) {
ret = -ENOENT;
goto out;
}
state = rb_entry(node, struct extent_state, rb_node);
if (state->start != start) {
ret = -ENOENT;
goto out;
}
*private = state->private;
out:
spin_unlock(&tree->lock);
return ret;
}
/*
* searches a range in the state tree for a given mask.
* If 'filled' == 1, this returns 1 only if every extent in the tree
* has the bits set. Otherwise, 1 is returned if any bit in the
* range is found set.
*/
int test_range_bit(struct extent_io_tree *tree, u64 start, u64 end,
int bits, int filled, struct extent_state *cached)
{
struct extent_state *state = NULL;
struct rb_node *node;
int bitset = 0;
spin_lock(&tree->lock);
if (cached && cached->tree && cached->start == start)
node = &cached->rb_node;
else
node = tree_search(tree, start);
while (node && start <= end) {
state = rb_entry(node, struct extent_state, rb_node);
if (filled && state->start > start) {
bitset = 0;
break;
}
if (state->start > end)
break;
if (state->state & bits) {
bitset = 1;
if (!filled)
break;
} else if (filled) {
bitset = 0;
break;
}
if (state->end == (u64)-1)
break;
start = state->end + 1;
if (start > end)
break;
node = rb_next(node);
if (!node) {
if (filled)
bitset = 0;
break;
}
}
spin_unlock(&tree->lock);
return bitset;
}
/*
* helper function to set a given page up to date if all the
* extents in the tree for that page are up to date
*/
static int check_page_uptodate(struct extent_io_tree *tree,
struct page *page)
{
u64 start = (u64)page->index << PAGE_CACHE_SHIFT;
u64 end = start + PAGE_CACHE_SIZE - 1;
if (test_range_bit(tree, start, end, EXTENT_UPTODATE, 1, NULL))
SetPageUptodate(page);
return 0;
}
/*
* helper function to unlock a page if all the extents in the tree
* for that page are unlocked
*/
static int check_page_locked(struct extent_io_tree *tree,
struct page *page)
{
u64 start = (u64)page->index << PAGE_CACHE_SHIFT;
u64 end = start + PAGE_CACHE_SIZE - 1;
if (!test_range_bit(tree, start, end, EXTENT_LOCKED, 0, NULL))
unlock_page(page);
return 0;
}
/*
* helper function to end page writeback if all the extents
* in the tree for that page are done with writeback
*/
static int check_page_writeback(struct extent_io_tree *tree,
struct page *page)
{
end_page_writeback(page);
return 0;
}
/* lots and lots of room for performance fixes in the end_bio funcs */
/*
* after a writepage IO is done, we need to:
* clear the uptodate bits on error
* clear the writeback bits in the extent tree for this IO
* end_page_writeback if the page has no more pending IO
*
* Scheduling is not allowed, so the extent state tree is expected
* to have one and only one object corresponding to this IO.
*/
static void end_bio_extent_writepage(struct bio *bio, int err)
{
int uptodate = err == 0;
struct bio_vec *bvec = bio->bi_io_vec + bio->bi_vcnt - 1;
struct extent_io_tree *tree;
u64 start;
u64 end;
int whole_page;
int ret;
do {
struct page *page = bvec->bv_page;
tree = &BTRFS_I(page->mapping->host)->io_tree;
start = ((u64)page->index << PAGE_CACHE_SHIFT) +
bvec->bv_offset;
end = start + bvec->bv_len - 1;
if (bvec->bv_offset == 0 && bvec->bv_len == PAGE_CACHE_SIZE)
whole_page = 1;
else
whole_page = 0;
if (--bvec >= bio->bi_io_vec)
prefetchw(&bvec->bv_page->flags);
if (tree->ops && tree->ops->writepage_end_io_hook) {
ret = tree->ops->writepage_end_io_hook(page, start,
end, NULL, uptodate);
if (ret)
uptodate = 0;
}
if (!uptodate && tree->ops &&
tree->ops->writepage_io_failed_hook) {
ret = tree->ops->writepage_io_failed_hook(bio, page,
start, end, NULL);
if (ret == 0) {
uptodate = (err == 0);
continue;
}
}
if (!uptodate) {
clear_extent_uptodate(tree, start, end, NULL, GFP_NOFS);
ClearPageUptodate(page);
SetPageError(page);
}
if (whole_page)
end_page_writeback(page);
else
check_page_writeback(tree, page);
} while (bvec >= bio->bi_io_vec);
bio_put(bio);
}
/*
* after a readpage IO is done, we need to:
* clear the uptodate bits on error
* set the uptodate bits if things worked
* set the page up to date if all extents in the tree are uptodate
* clear the lock bit in the extent tree
* unlock the page if there are no other extents locked for it
*
* Scheduling is not allowed, so the extent state tree is expected
* to have one and only one object corresponding to this IO.
*/
static void end_bio_extent_readpage(struct bio *bio, int err)
{
int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
struct bio_vec *bvec = bio->bi_io_vec;
struct extent_io_tree *tree;
u64 start;
u64 end;
int whole_page;
int ret;
if (err)
uptodate = 0;
do {
struct page *page = bvec->bv_page;
struct extent_state *cached = NULL;
struct extent_state *state;
tree = &BTRFS_I(page->mapping->host)->io_tree;
start = ((u64)page->index << PAGE_CACHE_SHIFT) +
bvec->bv_offset;
end = start + bvec->bv_len - 1;
if (bvec->bv_offset == 0 && bvec->bv_len == PAGE_CACHE_SIZE)
whole_page = 1;
else
whole_page = 0;
if (++bvec <= bvec_end)
prefetchw(&bvec->bv_page->flags);
spin_lock(&tree->lock);
state = find_first_extent_bit_state(tree, start, EXTENT_LOCKED);
if (state && state->start == start) {
/*
* take a reference on the state, unlock will drop
* the ref
*/
cache_state(state, &cached);
}
spin_unlock(&tree->lock);
if (uptodate && tree->ops && tree->ops->readpage_end_io_hook) {
ret = tree->ops->readpage_end_io_hook(page, start, end,
state);
if (ret)
uptodate = 0;
}
if (!uptodate && tree->ops &&
tree->ops->readpage_io_failed_hook) {
ret = tree->ops->readpage_io_failed_hook(bio, page,
start, end, NULL);
if (ret == 0) {
uptodate =
test_bit(BIO_UPTODATE, &bio->bi_flags);
if (err)
uptodate = 0;
uncache_state(&cached);
continue;
}
}
if (uptodate) {
set_extent_uptodate(tree, start, end, &cached,
GFP_ATOMIC);
}
unlock_extent_cached(tree, start, end, &cached, GFP_ATOMIC);
if (whole_page) {
if (uptodate) {
SetPageUptodate(page);
} else {
ClearPageUptodate(page);
SetPageError(page);
}
unlock_page(page);
} else {
if (uptodate) {
check_page_uptodate(tree, page);
} else {
ClearPageUptodate(page);
SetPageError(page);
}
check_page_locked(tree, page);
}
} while (bvec <= bvec_end);
bio_put(bio);
}
struct bio *
btrfs_bio_alloc(struct block_device *bdev, u64 first_sector, int nr_vecs,
gfp_t gfp_flags)
{
struct bio *bio;
bio = bio_alloc(gfp_flags, nr_vecs);
if (bio == NULL && (current->flags & PF_MEMALLOC)) {
while (!bio && (nr_vecs /= 2))
bio = bio_alloc(gfp_flags, nr_vecs);
}
if (bio) {
bio->bi_size = 0;
bio->bi_bdev = bdev;
bio->bi_sector = first_sector;
}
return bio;
}
static int submit_one_bio(int rw, struct bio *bio, int mirror_num,
unsigned long bio_flags)
{
int ret = 0;
struct bio_vec *bvec = bio->bi_io_vec + bio->bi_vcnt - 1;
struct page *page = bvec->bv_page;
struct extent_io_tree *tree = bio->bi_private;
u64 start;
start = ((u64)page->index << PAGE_CACHE_SHIFT) + bvec->bv_offset;
bio->bi_private = NULL;
bio_get(bio);
if (tree->ops && tree->ops->submit_bio_hook)
ret = tree->ops->submit_bio_hook(page->mapping->host, rw, bio,
mirror_num, bio_flags, start);
else
submit_bio(rw, bio);
if (bio_flagged(bio, BIO_EOPNOTSUPP))
ret = -EOPNOTSUPP;
bio_put(bio);
return ret;
}
static int submit_extent_page(int rw, struct extent_io_tree *tree,
struct page *page, sector_t sector,
size_t size, unsigned long offset,
struct block_device *bdev,
struct bio **bio_ret,
unsigned long max_pages,
bio_end_io_t end_io_func,
int mirror_num,
unsigned long prev_bio_flags,
unsigned long bio_flags)
{
int ret = 0;
struct bio *bio;
int nr;
int contig = 0;
int this_compressed = bio_flags & EXTENT_BIO_COMPRESSED;
int old_compressed = prev_bio_flags & EXTENT_BIO_COMPRESSED;
size_t page_size = min_t(size_t, size, PAGE_CACHE_SIZE);
if (bio_ret && *bio_ret) {
bio = *bio_ret;
if (old_compressed)
contig = bio->bi_sector == sector;
else
contig = bio->bi_sector + (bio->bi_size >> 9) ==
sector;
if (prev_bio_flags != bio_flags || !contig ||
(tree->ops && tree->ops->merge_bio_hook &&
tree->ops->merge_bio_hook(page, offset, page_size, bio,
bio_flags)) ||
bio_add_page(bio, page, page_size, offset) < page_size) {
ret = submit_one_bio(rw, bio, mirror_num,
prev_bio_flags);
bio = NULL;
} else {
return 0;
}
}
if (this_compressed)
nr = BIO_MAX_PAGES;
else
nr = bio_get_nr_vecs(bdev);
bio = btrfs_bio_alloc(bdev, sector, nr, GFP_NOFS | __GFP_HIGH);
if (!bio)
return -ENOMEM;
bio_add_page(bio, page, page_size, offset);
bio->bi_end_io = end_io_func;
bio->bi_private = tree;
if (bio_ret)
*bio_ret = bio;
else
ret = submit_one_bio(rw, bio, mirror_num, bio_flags);
return ret;
}
void set_page_extent_mapped(struct page *page)
{
if (!PagePrivate(page)) {
SetPagePrivate(page);
page_cache_get(page);
set_page_private(page, EXTENT_PAGE_PRIVATE);
}
}
static void set_page_extent_head(struct page *page, unsigned long len)
{
WARN_ON(!PagePrivate(page));
set_page_private(page, EXTENT_PAGE_PRIVATE_FIRST_PAGE | len << 2);
}
/*
* basic readpage implementation. Locked extent state structs are inserted
* into the tree that are removed when the IO is done (by the end_io
* handlers)
*/
static int __extent_read_full_page(struct extent_io_tree *tree,
struct page *page,
get_extent_t *get_extent,
struct bio **bio, int mirror_num,
unsigned long *bio_flags)
{
struct inode *inode = page->mapping->host;
u64 start = (u64)page->index << PAGE_CACHE_SHIFT;
u64 page_end = start + PAGE_CACHE_SIZE - 1;
u64 end;
u64 cur = start;
u64 extent_offset;
u64 last_byte = i_size_read(inode);
u64 block_start;
u64 cur_end;
sector_t sector;
struct extent_map *em;
struct block_device *bdev;
struct btrfs_ordered_extent *ordered;
int ret;
int nr = 0;
size_t pg_offset = 0;
size_t iosize;
size_t disk_io_size;
size_t blocksize = inode->i_sb->s_blocksize;
unsigned long this_bio_flag = 0;
set_page_extent_mapped(page);
if (!PageUptodate(page)) {
if (cleancache_get_page(page) == 0) {
BUG_ON(blocksize != PAGE_SIZE);
goto out;
}
}
end = page_end;
while (1) {
lock_extent(tree, start, end, GFP_NOFS);
ordered = btrfs_lookup_ordered_extent(inode, start);
if (!ordered)
break;
unlock_extent(tree, start, end, GFP_NOFS);
btrfs_start_ordered_extent(inode, ordered, 1);
btrfs_put_ordered_extent(ordered);
}
if (page->index == last_byte >> PAGE_CACHE_SHIFT) {
char *userpage;
size_t zero_offset = last_byte & (PAGE_CACHE_SIZE - 1);
if (zero_offset) {
iosize = PAGE_CACHE_SIZE - zero_offset;
userpage = kmap_atomic(page, KM_USER0);
memset(userpage + zero_offset, 0, iosize);
flush_dcache_page(page);
kunmap_atomic(userpage, KM_USER0);
}
}
while (cur <= end) {
if (cur >= last_byte) {
char *userpage;
struct extent_state *cached = NULL;
iosize = PAGE_CACHE_SIZE - pg_offset;
userpage = kmap_atomic(page, KM_USER0);
memset(userpage + pg_offset, 0, iosize);
flush_dcache_page(page);
kunmap_atomic(userpage, KM_USER0);
set_extent_uptodate(tree, cur, cur + iosize - 1,
&cached, GFP_NOFS);
unlock_extent_cached(tree, cur, cur + iosize - 1,
&cached, GFP_NOFS);
break;
}
em = get_extent(inode, page, pg_offset, cur,
end - cur + 1, 0);
if (IS_ERR_OR_NULL(em)) {
SetPageError(page);
unlock_extent(tree, cur, end, GFP_NOFS);
break;
}
extent_offset = cur - em->start;
BUG_ON(extent_map_end(em) <= cur);
BUG_ON(end < cur);
if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
this_bio_flag = EXTENT_BIO_COMPRESSED;
extent_set_compress_type(&this_bio_flag,
em->compress_type);
}
iosize = min(extent_map_end(em) - cur, end - cur + 1);
cur_end = min(extent_map_end(em) - 1, end);
iosize = (iosize + blocksize - 1) & ~((u64)blocksize - 1);
if (this_bio_flag & EXTENT_BIO_COMPRESSED) {
disk_io_size = em->block_len;
sector = em->block_start >> 9;
} else {
sector = (em->block_start + extent_offset) >> 9;
disk_io_size = iosize;
}
bdev = em->bdev;
block_start = em->block_start;
if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
block_start = EXTENT_MAP_HOLE;
free_extent_map(em);
em = NULL;
/* we've found a hole, just zero and go on */
if (block_start == EXTENT_MAP_HOLE) {
char *userpage;
struct extent_state *cached = NULL;
userpage = kmap_atomic(page, KM_USER0);
memset(userpage + pg_offset, 0, iosize);
flush_dcache_page(page);
kunmap_atomic(userpage, KM_USER0);
set_extent_uptodate(tree, cur, cur + iosize - 1,
&cached, GFP_NOFS);
unlock_extent_cached(tree, cur, cur + iosize - 1,
&cached, GFP_NOFS);
cur = cur + iosize;
pg_offset += iosize;
continue;
}
/* the get_extent function already copied into the page */
if (test_range_bit(tree, cur, cur_end,
EXTENT_UPTODATE, 1, NULL)) {
check_page_uptodate(tree, page);
unlock_extent(tree, cur, cur + iosize - 1, GFP_NOFS);
cur = cur + iosize;
pg_offset += iosize;
continue;
}
/* we have an inline extent but it didn't get marked up
* to date. Error out
*/
if (block_start == EXTENT_MAP_INLINE) {
SetPageError(page);
unlock_extent(tree, cur, cur + iosize - 1, GFP_NOFS);
cur = cur + iosize;
pg_offset += iosize;
continue;
}
ret = 0;
if (tree->ops && tree->ops->readpage_io_hook) {
ret = tree->ops->readpage_io_hook(page, cur,
cur + iosize - 1);
}
if (!ret) {
unsigned long pnr = (last_byte >> PAGE_CACHE_SHIFT) + 1;
pnr -= page->index;
ret = submit_extent_page(READ, tree, page,
sector, disk_io_size, pg_offset,
bdev, bio, pnr,
end_bio_extent_readpage, mirror_num,
*bio_flags,
this_bio_flag);
nr++;
*bio_flags = this_bio_flag;
}
if (ret)
SetPageError(page);
cur = cur + iosize;
pg_offset += iosize;
}
out:
if (!nr) {
if (!PageError(page))
SetPageUptodate(page);
unlock_page(page);
}
return 0;
}
int extent_read_full_page(struct extent_io_tree *tree, struct page *page,
get_extent_t *get_extent)
{
struct bio *bio = NULL;
unsigned long bio_flags = 0;
int ret;
ret = __extent_read_full_page(tree, page, get_extent, &bio, 0,
&bio_flags);
if (bio)
ret = submit_one_bio(READ, bio, 0, bio_flags);
return ret;
}
static noinline void update_nr_written(struct page *page,
struct writeback_control *wbc,
unsigned long nr_written)
{
wbc->nr_to_write -= nr_written;
if (wbc->range_cyclic || (wbc->nr_to_write > 0 &&
wbc->range_start == 0 && wbc->range_end == LLONG_MAX))
page->mapping->writeback_index = page->index + nr_written;
}
/*
* the writepage semantics are similar to regular writepage. extent
* records are inserted to lock ranges in the tree, and as dirty areas
* are found, they are marked writeback. Then the lock bits are removed
* and the end_io handler clears the writeback ranges
*/
static int __extent_writepage(struct page *page, struct writeback_control *wbc,
void *data)
{
struct inode *inode = page->mapping->host;
struct extent_page_data *epd = data;
struct extent_io_tree *tree = epd->tree;
u64 start = (u64)page->index << PAGE_CACHE_SHIFT;
u64 delalloc_start;
u64 page_end = start + PAGE_CACHE_SIZE - 1;
u64 end;
u64 cur = start;
u64 extent_offset;
u64 last_byte = i_size_read(inode);
u64 block_start;
u64 iosize;
sector_t sector;
struct extent_state *cached_state = NULL;
struct extent_map *em;
struct block_device *bdev;
int ret;
int nr = 0;
size_t pg_offset = 0;
size_t blocksize;
loff_t i_size = i_size_read(inode);
unsigned long end_index = i_size >> PAGE_CACHE_SHIFT;
u64 nr_delalloc;
u64 delalloc_end;
int page_started;
int compressed;
int write_flags;
unsigned long nr_written = 0;
if (wbc->sync_mode == WB_SYNC_ALL)
write_flags = WRITE_SYNC;
else
write_flags = WRITE;
trace___extent_writepage(page, inode, wbc);
WARN_ON(!PageLocked(page));
pg_offset = i_size & (PAGE_CACHE_SIZE - 1);
if (page->index > end_index ||
(page->index == end_index && !pg_offset)) {
page->mapping->a_ops->invalidatepage(page, 0);
unlock_page(page);
return 0;
}
if (page->index == end_index) {
char *userpage;
userpage = kmap_atomic(page, KM_USER0);
memset(userpage + pg_offset, 0,
PAGE_CACHE_SIZE - pg_offset);
kunmap_atomic(userpage, KM_USER0);
flush_dcache_page(page);
}
pg_offset = 0;
set_page_extent_mapped(page);
delalloc_start = start;
delalloc_end = 0;
page_started = 0;
if (!epd->extent_locked) {
u64 delalloc_to_write = 0;
/*
* make sure the wbc mapping index is at least updated
* to this page.
*/
update_nr_written(page, wbc, 0);
while (delalloc_end < page_end) {
nr_delalloc = find_lock_delalloc_range(inode, tree,
page,
&delalloc_start,
&delalloc_end,
128 * 1024 * 1024);
if (nr_delalloc == 0) {
delalloc_start = delalloc_end + 1;
continue;
}
tree->ops->fill_delalloc(inode, page, delalloc_start,
delalloc_end, &page_started,
&nr_written);
/*
* delalloc_end is already one less than the total
* length, so we don't subtract one from
* PAGE_CACHE_SIZE
*/
delalloc_to_write += (delalloc_end - delalloc_start +
PAGE_CACHE_SIZE) >>
PAGE_CACHE_SHIFT;
delalloc_start = delalloc_end + 1;
}
if (wbc->nr_to_write < delalloc_to_write) {
int thresh = 8192;
if (delalloc_to_write < thresh * 2)
thresh = delalloc_to_write;
wbc->nr_to_write = min_t(u64, delalloc_to_write,
thresh);
}
/* did the fill delalloc function already unlock and start
* the IO?
*/
if (page_started) {
ret = 0;
/*
* we've unlocked the page, so we can't update
* the mapping's writeback index, just update
* nr_to_write.
*/
wbc->nr_to_write -= nr_written;
goto done_unlocked;
}
}
if (tree->ops && tree->ops->writepage_start_hook) {
ret = tree->ops->writepage_start_hook(page, start,
page_end);
if (ret == -EAGAIN) {
redirty_page_for_writepage(wbc, page);
update_nr_written(page, wbc, nr_written);
unlock_page(page);
ret = 0;
goto done_unlocked;
}
}
/*
* we don't want to touch the inode after unlocking the page,
* so we update the mapping writeback index now
*/
update_nr_written(page, wbc, nr_written + 1);
end = page_end;
if (last_byte <= start) {
if (tree->ops && tree->ops->writepage_end_io_hook)
tree->ops->writepage_end_io_hook(page, start,
page_end, NULL, 1);
goto done;
}
blocksize = inode->i_sb->s_blocksize;
while (cur <= end) {
if (cur >= last_byte) {
if (tree->ops && tree->ops->writepage_end_io_hook)
tree->ops->writepage_end_io_hook(page, cur,
page_end, NULL, 1);
break;
}
em = epd->get_extent(inode, page, pg_offset, cur,
end - cur + 1, 1);
if (IS_ERR_OR_NULL(em)) {
SetPageError(page);
break;
}
extent_offset = cur - em->start;
BUG_ON(extent_map_end(em) <= cur);
BUG_ON(end < cur);
iosize = min(extent_map_end(em) - cur, end - cur + 1);
iosize = (iosize + blocksize - 1) & ~((u64)blocksize - 1);
sector = (em->block_start + extent_offset) >> 9;
bdev = em->bdev;
block_start = em->block_start;
compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
free_extent_map(em);
em = NULL;
/*
* compressed and inline extents are written through other
* paths in the FS
*/
if (compressed || block_start == EXTENT_MAP_HOLE ||
block_start == EXTENT_MAP_INLINE) {
/*
* end_io notification does not happen here for
* compressed extents
*/
if (!compressed && tree->ops &&
tree->ops->writepage_end_io_hook)
tree->ops->writepage_end_io_hook(page, cur,
cur + iosize - 1,
NULL, 1);
else if (compressed) {
/* we don't want to end_page_writeback on
* a compressed extent. this happens
* elsewhere
*/
nr++;
}
cur += iosize;
pg_offset += iosize;
continue;
}
/* leave this out until we have a page_mkwrite call */
if (0 && !test_range_bit(tree, cur, cur + iosize - 1,
EXTENT_DIRTY, 0, NULL)) {
cur = cur + iosize;
pg_offset += iosize;
continue;
}
if (tree->ops && tree->ops->writepage_io_hook) {
ret = tree->ops->writepage_io_hook(page, cur,
cur + iosize - 1);
} else {
ret = 0;
}
if (ret) {
SetPageError(page);
} else {
unsigned long max_nr = end_index + 1;
set_range_writeback(tree, cur, cur + iosize - 1);
if (!PageWriteback(page)) {
printk(KERN_ERR "btrfs warning page %lu not "
"writeback, cur %llu end %llu\n",
page->index, (unsigned long long)cur,
(unsigned long long)end);
}
ret = submit_extent_page(write_flags, tree, page,
sector, iosize, pg_offset,
bdev, &epd->bio, max_nr,
end_bio_extent_writepage,
0, 0, 0);
if (ret)
SetPageError(page);
}
cur = cur + iosize;
pg_offset += iosize;
nr++;
}
done:
if (nr == 0) {
/* make sure the mapping tag for page dirty gets cleared */
set_page_writeback(page);
end_page_writeback(page);
}
unlock_page(page);
done_unlocked:
/* drop our reference on any cached states */
free_extent_state(cached_state);
return 0;
}
/**
* write_cache_pages - walk the list of dirty pages of the given address space and write all of them.
* @mapping: address space structure to write
* @wbc: subtract the number of written pages from *@wbc->nr_to_write
* @writepage: function called for each page
* @data: data passed to writepage function
*
* If a page is already under I/O, write_cache_pages() skips it, even
* if it's dirty. This is desirable behaviour for memory-cleaning writeback,
* but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
* and msync() need to guarantee that all the data which was dirty at the time
* the call was made get new I/O started against them. If wbc->sync_mode is
* WB_SYNC_ALL then we were called for data integrity and we must wait for
* existing IO to complete.
*/
static int extent_write_cache_pages(struct extent_io_tree *tree,
struct address_space *mapping,
struct writeback_control *wbc,
writepage_t writepage, void *data,
void (*flush_fn)(void *))
{
int ret = 0;
int done = 0;
int nr_to_write_done = 0;
struct pagevec pvec;
int nr_pages;
pgoff_t index;
pgoff_t end; /* Inclusive */
int scanned = 0;
pagevec_init(&pvec, 0);
if (wbc->range_cyclic) {
index = mapping->writeback_index; /* Start from prev offset */
end = -1;
} else {
index = wbc->range_start >> PAGE_CACHE_SHIFT;
end = wbc->range_end >> PAGE_CACHE_SHIFT;
scanned = 1;
}
retry:
while (!done && !nr_to_write_done && (index <= end) &&
(nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
PAGECACHE_TAG_DIRTY, min(end - index,
(pgoff_t)PAGEVEC_SIZE-1) + 1))) {
unsigned i;
scanned = 1;
for (i = 0; i < nr_pages; i++) {
struct page *page = pvec.pages[i];
/*
* At this point we hold neither mapping->tree_lock nor
* lock on the page itself: the page may be truncated or
* invalidated (changing page->mapping to NULL), or even
* swizzled back from swapper_space to tmpfs file
* mapping
*/
if (tree->ops && tree->ops->write_cache_pages_lock_hook)
tree->ops->write_cache_pages_lock_hook(page);
else
lock_page(page);
if (unlikely(page->mapping != mapping)) {
unlock_page(page);
continue;
}
if (!wbc->range_cyclic && page->index > end) {
done = 1;
unlock_page(page);
continue;
}
if (wbc->sync_mode != WB_SYNC_NONE) {
if (PageWriteback(page))
flush_fn(data);
wait_on_page_writeback(page);
}
if (PageWriteback(page) ||
!clear_page_dirty_for_io(page)) {
unlock_page(page);
continue;
}
ret = (*writepage)(page, wbc, data);
if (unlikely(ret == AOP_WRITEPAGE_ACTIVATE)) {
unlock_page(page);
ret = 0;
}
if (ret)
done = 1;
/*
* the filesystem may choose to bump up nr_to_write.
* We have to make sure to honor the new nr_to_write
* at any time
*/
nr_to_write_done = wbc->nr_to_write <= 0;
}
pagevec_release(&pvec);
cond_resched();
}
if (!scanned && !done) {
/*
* We hit the last page and there is more work to be done: wrap
* back to the start of the file
*/
scanned = 1;
index = 0;
goto retry;
}
return ret;
}
static void flush_epd_write_bio(struct extent_page_data *epd)
{
if (epd->bio) {
if (epd->sync_io)
submit_one_bio(WRITE_SYNC, epd->bio, 0, 0);
else
submit_one_bio(WRITE, epd->bio, 0, 0);
epd->bio = NULL;
}
}
static noinline void flush_write_bio(void *data)
{
struct extent_page_data *epd = data;
flush_epd_write_bio(epd);
}
int extent_write_full_page(struct extent_io_tree *tree, struct page *page,
get_extent_t *get_extent,
struct writeback_control *wbc)
{
int ret;
struct address_space *mapping = page->mapping;
struct extent_page_data epd = {
.bio = NULL,
.tree = tree,
.get_extent = get_extent,
.extent_locked = 0,
.sync_io = wbc->sync_mode == WB_SYNC_ALL,
};
struct writeback_control wbc_writepages = {
.sync_mode = wbc->sync_mode,
.older_than_this = NULL,
.nr_to_write = 64,
.range_start = page_offset(page) + PAGE_CACHE_SIZE,
.range_end = (loff_t)-1,
};
ret = __extent_writepage(page, wbc, &epd);
extent_write_cache_pages(tree, mapping, &wbc_writepages,
__extent_writepage, &epd, flush_write_bio);
flush_epd_write_bio(&epd);
return ret;
}
int extent_write_locked_range(struct extent_io_tree *tree, struct inode *inode,
u64 start, u64 end, get_extent_t *get_extent,
int mode)
{
int ret = 0;
struct address_space *mapping = inode->i_mapping;
struct page *page;
unsigned long nr_pages = (end - start + PAGE_CACHE_SIZE) >>
PAGE_CACHE_SHIFT;
struct extent_page_data epd = {
.bio = NULL,
.tree = tree,
.get_extent = get_extent,
.extent_locked = 1,
.sync_io = mode == WB_SYNC_ALL,
};
struct writeback_control wbc_writepages = {
.sync_mode = mode,
.older_than_this = NULL,
.nr_to_write = nr_pages * 2,
.range_start = start,
.range_end = end + 1,
};
while (start <= end) {
page = find_get_page(mapping, start >> PAGE_CACHE_SHIFT);
if (clear_page_dirty_for_io(page))
ret = __extent_writepage(page, &wbc_writepages, &epd);
else {
if (tree->ops && tree->ops->writepage_end_io_hook)
tree->ops->writepage_end_io_hook(page, start,
start + PAGE_CACHE_SIZE - 1,
NULL, 1);
unlock_page(page);
}
page_cache_release(page);
start += PAGE_CACHE_SIZE;
}
flush_epd_write_bio(&epd);
return ret;
}
int extent_writepages(struct extent_io_tree *tree,
struct address_space *mapping,
get_extent_t *get_extent,
struct writeback_control *wbc)
{
int ret = 0;
struct extent_page_data epd = {
.bio = NULL,
.tree = tree,
.get_extent = get_extent,
.extent_locked = 0,
.sync_io = wbc->sync_mode == WB_SYNC_ALL,
};
ret = extent_write_cache_pages(tree, mapping, wbc,
__extent_writepage, &epd,
flush_write_bio);
flush_epd_write_bio(&epd);
return ret;
}
int extent_readpages(struct extent_io_tree *tree,
struct address_space *mapping,
struct list_head *pages, unsigned nr_pages,
get_extent_t get_extent)
{
struct bio *bio = NULL;
unsigned page_idx;
unsigned long bio_flags = 0;
for (page_idx = 0; page_idx < nr_pages; page_idx++) {
struct page *page = list_entry(pages->prev, struct page, lru);
prefetchw(&page->flags);
list_del(&page->lru);
if (!add_to_page_cache_lru(page, mapping,
page->index, GFP_NOFS)) {
__extent_read_full_page(tree, page, get_extent,
&bio, 0, &bio_flags);
}
page_cache_release(page);
}
BUG_ON(!list_empty(pages));
if (bio)
submit_one_bio(READ, bio, 0, bio_flags);
return 0;
}
/*
* basic invalidatepage code, this waits on any locked or writeback
* ranges corresponding to the page, and then deletes any extent state
* records from the tree
*/
int extent_invalidatepage(struct extent_io_tree *tree,
struct page *page, unsigned long offset)
{
struct extent_state *cached_state = NULL;
u64 start = ((u64)page->index << PAGE_CACHE_SHIFT);
u64 end = start + PAGE_CACHE_SIZE - 1;
size_t blocksize = page->mapping->host->i_sb->s_blocksize;
start += (offset + blocksize - 1) & ~(blocksize - 1);
if (start > end)
return 0;
lock_extent_bits(tree, start, end, 0, &cached_state, GFP_NOFS);
wait_on_page_writeback(page);
clear_extent_bit(tree, start, end,
EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
EXTENT_DO_ACCOUNTING,
1, 1, &cached_state, GFP_NOFS);
return 0;
}
/*
* a helper for releasepage, this tests for areas of the page that
* are locked or under IO and drops the related state bits if it is safe
* to drop the page.
*/
int try_release_extent_state(struct extent_map_tree *map,
struct extent_io_tree *tree, struct page *page,
gfp_t mask)
{
u64 start = (u64)page->index << PAGE_CACHE_SHIFT;
u64 end = start + PAGE_CACHE_SIZE - 1;
int ret = 1;
if (test_range_bit(tree, start, end,
EXTENT_IOBITS, 0, NULL))
ret = 0;
else {
if ((mask & GFP_NOFS) == GFP_NOFS)
mask = GFP_NOFS;
/*
* at this point we can safely clear everything except the
* locked bit and the nodatasum bit
*/
ret = clear_extent_bit(tree, start, end,
~(EXTENT_LOCKED | EXTENT_NODATASUM),
0, 0, NULL, mask);
/* if clear_extent_bit failed for enomem reasons,
* we can't allow the release to continue.
*/
if (ret < 0)
ret = 0;
else
ret = 1;
}
return ret;
}
/*
* a helper for releasepage. As long as there are no locked extents
* in the range corresponding to the page, both state records and extent
* map records are removed
*/
int try_release_extent_mapping(struct extent_map_tree *map,
struct extent_io_tree *tree, struct page *page,
gfp_t mask)
{
struct extent_map *em;
u64 start = (u64)page->index << PAGE_CACHE_SHIFT;
u64 end = start + PAGE_CACHE_SIZE - 1;
if ((mask & __GFP_WAIT) &&
page->mapping->host->i_size > 16 * 1024 * 1024) {
u64 len;
while (start <= end) {
len = end - start + 1;
write_lock(&map->lock);
em = lookup_extent_mapping(map, start, len);
if (IS_ERR_OR_NULL(em)) {
write_unlock(&map->lock);
break;
}
if (test_bit(EXTENT_FLAG_PINNED, &em->flags) ||
em->start != start) {
write_unlock(&map->lock);
free_extent_map(em);
break;
}
if (!test_range_bit(tree, em->start,
extent_map_end(em) - 1,
EXTENT_LOCKED | EXTENT_WRITEBACK,
0, NULL)) {
remove_extent_mapping(map, em);
/* once for the rb tree */
free_extent_map(em);
}
start = extent_map_end(em);
write_unlock(&map->lock);
/* once for us */
free_extent_map(em);
}
}
return try_release_extent_state(map, tree, page, mask);
}
/*
* helper function for fiemap, which doesn't want to see any holes.
* This maps until we find something past 'last'
*/
static struct extent_map *get_extent_skip_holes(struct inode *inode,
u64 offset,
u64 last,
get_extent_t *get_extent)
{
u64 sectorsize = BTRFS_I(inode)->root->sectorsize;
struct extent_map *em;
u64 len;
if (offset >= last)
return NULL;
while(1) {
len = last - offset;
if (len == 0)
break;
len = (len + sectorsize - 1) & ~(sectorsize - 1);
em = get_extent(inode, NULL, 0, offset, len, 0);
if (IS_ERR_OR_NULL(em))
return em;
/* if this isn't a hole return it */
if (!test_bit(EXTENT_FLAG_VACANCY, &em->flags) &&
em->block_start != EXTENT_MAP_HOLE) {
return em;
}
/* this is a hole, advance to the next extent */
offset = extent_map_end(em);
free_extent_map(em);
if (offset >= last)
break;
}
return NULL;
}
int extent_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
__u64 start, __u64 len, get_extent_t *get_extent)
{
int ret = 0;
u64 off = start;
u64 max = start + len;
u32 flags = 0;
u32 found_type;
u64 last;
u64 last_for_get_extent = 0;
u64 disko = 0;
u64 isize = i_size_read(inode);
struct btrfs_key found_key;
struct extent_map *em = NULL;
struct extent_state *cached_state = NULL;
struct btrfs_path *path;
struct btrfs_file_extent_item *item;
int end = 0;
u64 em_start = 0;
u64 em_len = 0;
u64 em_end = 0;
unsigned long emflags;
if (len == 0)
return -EINVAL;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
path->leave_spinning = 1;
/*
* lookup the last file extent. We're not using i_size here
* because there might be preallocation past i_size
*/
ret = btrfs_lookup_file_extent(NULL, BTRFS_I(inode)->root,
path, btrfs_ino(inode), -1, 0);
if (ret < 0) {
btrfs_free_path(path);
return ret;
}
WARN_ON(!ret);
path->slots[0]--;
item = btrfs_item_ptr(path->nodes[0], path->slots[0],
struct btrfs_file_extent_item);
btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
found_type = btrfs_key_type(&found_key);
/* No extents, but there might be delalloc bits */
if (found_key.objectid != btrfs_ino(inode) ||
found_type != BTRFS_EXTENT_DATA_KEY) {
/* have to trust i_size as the end */
last = (u64)-1;
last_for_get_extent = isize;
} else {
/*
* remember the start of the last extent. There are a
* bunch of different factors that go into the length of the
* extent, so its much less complex to remember where it started
*/
last = found_key.offset;
last_for_get_extent = last + 1;
}
btrfs_free_path(path);
/*
* we might have some extents allocated but more delalloc past those
* extents. so, we trust isize unless the start of the last extent is
* beyond isize
*/
if (last < isize) {
last = (u64)-1;
last_for_get_extent = isize;
}
lock_extent_bits(&BTRFS_I(inode)->io_tree, start, start + len, 0,
&cached_state, GFP_NOFS);
em = get_extent_skip_holes(inode, off, last_for_get_extent,
get_extent);
if (!em)
goto out;
if (IS_ERR(em)) {
ret = PTR_ERR(em);
goto out;
}
while (!end) {
u64 offset_in_extent;
/* break if the extent we found is outside the range */
if (em->start >= max || extent_map_end(em) < off)
break;
/*
* get_extent may return an extent that starts before our
* requested range. We have to make sure the ranges
* we return to fiemap always move forward and don't
* overlap, so adjust the offsets here
*/
em_start = max(em->start, off);
/*
* record the offset from the start of the extent
* for adjusting the disk offset below
*/
offset_in_extent = em_start - em->start;
em_end = extent_map_end(em);
em_len = em_end - em_start;
emflags = em->flags;
disko = 0;
flags = 0;
/*
* bump off for our next call to get_extent
*/
off = extent_map_end(em);
if (off >= max)
end = 1;
if (em->block_start == EXTENT_MAP_LAST_BYTE) {
end = 1;
flags |= FIEMAP_EXTENT_LAST;
} else if (em->block_start == EXTENT_MAP_INLINE) {
flags |= (FIEMAP_EXTENT_DATA_INLINE |
FIEMAP_EXTENT_NOT_ALIGNED);
} else if (em->block_start == EXTENT_MAP_DELALLOC) {
flags |= (FIEMAP_EXTENT_DELALLOC |
FIEMAP_EXTENT_UNKNOWN);
} else {
disko = em->block_start + offset_in_extent;
}
if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags))
flags |= FIEMAP_EXTENT_ENCODED;
free_extent_map(em);
em = NULL;
if ((em_start >= last) || em_len == (u64)-1 ||
(last == (u64)-1 && isize <= em_end)) {
flags |= FIEMAP_EXTENT_LAST;
end = 1;
}
/* now scan forward to see if this is really the last extent. */
em = get_extent_skip_holes(inode, off, last_for_get_extent,
get_extent);
if (IS_ERR(em)) {
ret = PTR_ERR(em);
goto out;
}
if (!em) {
flags |= FIEMAP_EXTENT_LAST;
end = 1;
}
ret = fiemap_fill_next_extent(fieinfo, em_start, disko,
em_len, flags);
if (ret)
goto out_free;
}
out_free:
free_extent_map(em);
out:
unlock_extent_cached(&BTRFS_I(inode)->io_tree, start, start + len,
&cached_state, GFP_NOFS);
return ret;
}
static inline struct page *extent_buffer_page(struct extent_buffer *eb,
unsigned long i)
{
struct page *p;
struct address_space *mapping;
if (i == 0)
return eb->first_page;
i += eb->start >> PAGE_CACHE_SHIFT;
mapping = eb->first_page->mapping;
if (!mapping)
return NULL;
/*
* extent_buffer_page is only called after pinning the page
* by increasing the reference count. So we know the page must
* be in the radix tree.
*/
rcu_read_lock();
p = radix_tree_lookup(&mapping->page_tree, i);
rcu_read_unlock();
return p;
}
static inline unsigned long num_extent_pages(u64 start, u64 len)
{
return ((start + len + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT) -
(start >> PAGE_CACHE_SHIFT);
}
static struct extent_buffer *__alloc_extent_buffer(struct extent_io_tree *tree,
u64 start,
unsigned long len,
gfp_t mask)
{
struct extent_buffer *eb = NULL;
#if LEAK_DEBUG
unsigned long flags;
#endif
eb = kmem_cache_zalloc(extent_buffer_cache, mask);
if (eb == NULL)
return NULL;
eb->start = start;
eb->len = len;
spin_lock_init(&eb->lock);
init_waitqueue_head(&eb->lock_wq);
#if LEAK_DEBUG
spin_lock_irqsave(&leak_lock, flags);
list_add(&eb->leak_list, &buffers);
spin_unlock_irqrestore(&leak_lock, flags);
#endif
atomic_set(&eb->refs, 1);
return eb;
}
static void __free_extent_buffer(struct extent_buffer *eb)
{
#if LEAK_DEBUG
unsigned long flags;
spin_lock_irqsave(&leak_lock, flags);
list_del(&eb->leak_list);
spin_unlock_irqrestore(&leak_lock, flags);
#endif
kmem_cache_free(extent_buffer_cache, eb);
}
/*
* Helper for releasing extent buffer page.
*/
static void btrfs_release_extent_buffer_page(struct extent_buffer *eb,
unsigned long start_idx)
{
unsigned long index;
struct page *page;
if (!eb->first_page)
return;
index = num_extent_pages(eb->start, eb->len);
if (start_idx >= index)
return;
do {
index--;
page = extent_buffer_page(eb, index);
if (page)
page_cache_release(page);
} while (index != start_idx);
}
/*
* Helper for releasing the extent buffer.
*/
static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
{
btrfs_release_extent_buffer_page(eb, 0);
__free_extent_buffer(eb);
}
struct extent_buffer *alloc_extent_buffer(struct extent_io_tree *tree,
u64 start, unsigned long len,
struct page *page0)
{
unsigned long num_pages = num_extent_pages(start, len);
unsigned long i;
unsigned long index = start >> PAGE_CACHE_SHIFT;
struct extent_buffer *eb;
struct extent_buffer *exists = NULL;
struct page *p;
struct address_space *mapping = tree->mapping;
int uptodate = 1;
int ret;
rcu_read_lock();
eb = radix_tree_lookup(&tree->buffer, start >> PAGE_CACHE_SHIFT);
if (eb && atomic_inc_not_zero(&eb->refs)) {
rcu_read_unlock();
mark_page_accessed(eb->first_page);
return eb;
}
rcu_read_unlock();
eb = __alloc_extent_buffer(tree, start, len, GFP_NOFS);
if (!eb)
return NULL;
if (page0) {
eb->first_page = page0;
i = 1;
index++;
page_cache_get(page0);
mark_page_accessed(page0);
set_page_extent_mapped(page0);
set_page_extent_head(page0, len);
uptodate = PageUptodate(page0);
} else {
i = 0;
}
for (; i < num_pages; i++, index++) {
p = find_or_create_page(mapping, index, GFP_NOFS | __GFP_HIGHMEM);
if (!p) {
WARN_ON(1);
goto free_eb;
}
set_page_extent_mapped(p);
mark_page_accessed(p);
if (i == 0) {
eb->first_page = p;
set_page_extent_head(p, len);
} else {
set_page_private(p, EXTENT_PAGE_PRIVATE);
}
if (!PageUptodate(p))
uptodate = 0;
/*
* see below about how we avoid a nasty race with release page
* and why we unlock later
*/
if (i != 0)
unlock_page(p);
}
if (uptodate)
set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
ret = radix_tree_preload(GFP_NOFS & ~__GFP_HIGHMEM);
if (ret)
goto free_eb;
spin_lock(&tree->buffer_lock);
ret = radix_tree_insert(&tree->buffer, start >> PAGE_CACHE_SHIFT, eb);
if (ret == -EEXIST) {
exists = radix_tree_lookup(&tree->buffer,
start >> PAGE_CACHE_SHIFT);
/* add one reference for the caller */
atomic_inc(&exists->refs);
spin_unlock(&tree->buffer_lock);
radix_tree_preload_end();
goto free_eb;
}
/* add one reference for the tree */
atomic_inc(&eb->refs);
spin_unlock(&tree->buffer_lock);
radix_tree_preload_end();
/*
* there is a race where release page may have
* tried to find this extent buffer in the radix
* but failed. It will tell the VM it is safe to
* reclaim the, and it will clear the page private bit.
* We must make sure to set the page private bit properly
* after the extent buffer is in the radix tree so
* it doesn't get lost
*/
set_page_extent_mapped(eb->first_page);
set_page_extent_head(eb->first_page, eb->len);
if (!page0)
unlock_page(eb->first_page);
return eb;
free_eb:
if (eb->first_page && !page0)
unlock_page(eb->first_page);
if (!atomic_dec_and_test(&eb->refs))
return exists;
btrfs_release_extent_buffer(eb);
return exists;
}
struct extent_buffer *find_extent_buffer(struct extent_io_tree *tree,
u64 start, unsigned long len)
{
struct extent_buffer *eb;
rcu_read_lock();
eb = radix_tree_lookup(&tree->buffer, start >> PAGE_CACHE_SHIFT);
if (eb && atomic_inc_not_zero(&eb->refs)) {
rcu_read_unlock();
mark_page_accessed(eb->first_page);
return eb;
}
rcu_read_unlock();
return NULL;
}
void free_extent_buffer(struct extent_buffer *eb)
{
if (!eb)
return;
if (!atomic_dec_and_test(&eb->refs))
return;
WARN_ON(1);
}
int clear_extent_buffer_dirty(struct extent_io_tree *tree,
struct extent_buffer *eb)
{
unsigned long i;
unsigned long num_pages;
struct page *page;
num_pages = num_extent_pages(eb->start, eb->len);
for (i = 0; i < num_pages; i++) {
page = extent_buffer_page(eb, i);
if (!PageDirty(page))
continue;
lock_page(page);
WARN_ON(!PagePrivate(page));
set_page_extent_mapped(page);
if (i == 0)
set_page_extent_head(page, eb->len);
clear_page_dirty_for_io(page);
spin_lock_irq(&page->mapping->tree_lock);
if (!PageDirty(page)) {
radix_tree_tag_clear(&page->mapping->page_tree,
page_index(page),
PAGECACHE_TAG_DIRTY);
}
spin_unlock_irq(&page->mapping->tree_lock);
unlock_page(page);
}
return 0;
}
int set_extent_buffer_dirty(struct extent_io_tree *tree,
struct extent_buffer *eb)
{
unsigned long i;
unsigned long num_pages;
int was_dirty = 0;
was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
num_pages = num_extent_pages(eb->start, eb->len);
for (i = 0; i < num_pages; i++)
__set_page_dirty_nobuffers(extent_buffer_page(eb, i));
return was_dirty;
}
int clear_extent_buffer_uptodate(struct extent_io_tree *tree,
struct extent_buffer *eb,
struct extent_state **cached_state)
{
unsigned long i;
struct page *page;
unsigned long num_pages;
num_pages = num_extent_pages(eb->start, eb->len);
clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
clear_extent_uptodate(tree, eb->start, eb->start + eb->len - 1,
cached_state, GFP_NOFS);
for (i = 0; i < num_pages; i++) {
page = extent_buffer_page(eb, i);
if (page)
ClearPageUptodate(page);
}
return 0;
}
int set_extent_buffer_uptodate(struct extent_io_tree *tree,
struct extent_buffer *eb)
{
unsigned long i;
struct page *page;
unsigned long num_pages;
num_pages = num_extent_pages(eb->start, eb->len);
set_extent_uptodate(tree, eb->start, eb->start + eb->len - 1,
NULL, GFP_NOFS);
for (i = 0; i < num_pages; i++) {
page = extent_buffer_page(eb, i);
if ((i == 0 && (eb->start & (PAGE_CACHE_SIZE - 1))) ||
((i == num_pages - 1) &&
((eb->start + eb->len) & (PAGE_CACHE_SIZE - 1)))) {
check_page_uptodate(tree, page);
continue;
}
SetPageUptodate(page);
}
return 0;
}
int extent_range_uptodate(struct extent_io_tree *tree,
u64 start, u64 end)
{
struct page *page;
int ret;
int pg_uptodate = 1;
int uptodate;
unsigned long index;
ret = test_range_bit(tree, start, end, EXTENT_UPTODATE, 1, NULL);
if (ret)
return 1;
while (start <= end) {
index = start >> PAGE_CACHE_SHIFT;
page = find_get_page(tree->mapping, index);
uptodate = PageUptodate(page);
page_cache_release(page);
if (!uptodate) {
pg_uptodate = 0;
break;
}
start += PAGE_CACHE_SIZE;
}
return pg_uptodate;
}
int extent_buffer_uptodate(struct extent_io_tree *tree,
struct extent_buffer *eb,
struct extent_state *cached_state)
{
int ret = 0;
unsigned long num_pages;
unsigned long i;
struct page *page;
int pg_uptodate = 1;
if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
return 1;
ret = test_range_bit(tree, eb->start, eb->start + eb->len - 1,
EXTENT_UPTODATE, 1, cached_state);
if (ret)
return ret;
num_pages = num_extent_pages(eb->start, eb->len);
for (i = 0; i < num_pages; i++) {
page = extent_buffer_page(eb, i);
if (!PageUptodate(page)) {
pg_uptodate = 0;
break;
}
}
return pg_uptodate;
}
int read_extent_buffer_pages(struct extent_io_tree *tree,
struct extent_buffer *eb,
u64 start, int wait,
get_extent_t *get_extent, int mirror_num)
{
unsigned long i;
unsigned long start_i;
struct page *page;
int err;
int ret = 0;
int locked_pages = 0;
int all_uptodate = 1;
int inc_all_pages = 0;
unsigned long num_pages;
struct bio *bio = NULL;
unsigned long bio_flags = 0;
if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
return 0;
if (test_range_bit(tree, eb->start, eb->start + eb->len - 1,
EXTENT_UPTODATE, 1, NULL)) {
return 0;
}
if (start) {
WARN_ON(start < eb->start);
start_i = (start >> PAGE_CACHE_SHIFT) -
(eb->start >> PAGE_CACHE_SHIFT);
} else {
start_i = 0;
}
num_pages = num_extent_pages(eb->start, eb->len);
for (i = start_i; i < num_pages; i++) {
page = extent_buffer_page(eb, i);
if (!wait) {
if (!trylock_page(page))
goto unlock_exit;
} else {
lock_page(page);
}
locked_pages++;
if (!PageUptodate(page))
all_uptodate = 0;
}
if (all_uptodate) {
if (start_i == 0)
set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
goto unlock_exit;
}
for (i = start_i; i < num_pages; i++) {
page = extent_buffer_page(eb, i);
WARN_ON(!PagePrivate(page));
set_page_extent_mapped(page);
if (i == 0)
set_page_extent_head(page, eb->len);
if (inc_all_pages)
page_cache_get(page);
if (!PageUptodate(page)) {
if (start_i == 0)
inc_all_pages = 1;
ClearPageError(page);
err = __extent_read_full_page(tree, page,
get_extent, &bio,
mirror_num, &bio_flags);
if (err)
ret = err;
} else {
unlock_page(page);
}
}
if (bio)
submit_one_bio(READ, bio, mirror_num, bio_flags);
if (ret || !wait)
return ret;
for (i = start_i; i < num_pages; i++) {
page = extent_buffer_page(eb, i);
wait_on_page_locked(page);
if (!PageUptodate(page))
ret = -EIO;
}
if (!ret)
set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
return ret;
unlock_exit:
i = start_i;
while (locked_pages > 0) {
page = extent_buffer_page(eb, i);
i++;
unlock_page(page);
locked_pages--;
}
return ret;
}
void read_extent_buffer(struct extent_buffer *eb, void *dstv,
unsigned long start,
unsigned long len)
{
size_t cur;
size_t offset;
struct page *page;
char *kaddr;
char *dst = (char *)dstv;
size_t start_offset = eb->start & ((u64)PAGE_CACHE_SIZE - 1);
unsigned long i = (start_offset + start) >> PAGE_CACHE_SHIFT;
WARN_ON(start > eb->len);
WARN_ON(start + len > eb->start + eb->len);
offset = (start_offset + start) & ((unsigned long)PAGE_CACHE_SIZE - 1);
while (len > 0) {
page = extent_buffer_page(eb, i);
cur = min(len, (PAGE_CACHE_SIZE - offset));
kaddr = kmap_atomic(page, KM_USER1);
memcpy(dst, kaddr + offset, cur);
kunmap_atomic(kaddr, KM_USER1);
dst += cur;
len -= cur;
offset = 0;
i++;
}
}
int map_private_extent_buffer(struct extent_buffer *eb, unsigned long start,
unsigned long min_len, char **token, char **map,
unsigned long *map_start,
unsigned long *map_len, int km)
{
size_t offset = start & (PAGE_CACHE_SIZE - 1);
char *kaddr;
struct page *p;
size_t start_offset = eb->start & ((u64)PAGE_CACHE_SIZE - 1);
unsigned long i = (start_offset + start) >> PAGE_CACHE_SHIFT;
unsigned long end_i = (start_offset + start + min_len - 1) >>
PAGE_CACHE_SHIFT;
if (i != end_i)
return -EINVAL;
if (i == 0) {
offset = start_offset;
*map_start = 0;
} else {
offset = 0;
*map_start = ((u64)i << PAGE_CACHE_SHIFT) - start_offset;
}
if (start + min_len > eb->len) {
printk(KERN_ERR "btrfs bad mapping eb start %llu len %lu, "
"wanted %lu %lu\n", (unsigned long long)eb->start,
eb->len, start, min_len);
WARN_ON(1);
return -EINVAL;
}
p = extent_buffer_page(eb, i);
kaddr = kmap_atomic(p, km);
*token = kaddr;
*map = kaddr + offset;
*map_len = PAGE_CACHE_SIZE - offset;
return 0;
}
int map_extent_buffer(struct extent_buffer *eb, unsigned long start,
unsigned long min_len,
char **token, char **map,
unsigned long *map_start,
unsigned long *map_len, int km)
{
int err;
int save = 0;
if (eb->map_token) {
unmap_extent_buffer(eb, eb->map_token, km);
eb->map_token = NULL;
save = 1;
}
err = map_private_extent_buffer(eb, start, min_len, token, map,
map_start, map_len, km);
if (!err && save) {
eb->map_token = *token;
eb->kaddr = *map;
eb->map_start = *map_start;
eb->map_len = *map_len;
}
return err;
}
void unmap_extent_buffer(struct extent_buffer *eb, char *token, int km)
{
kunmap_atomic(token, km);
}
int memcmp_extent_buffer(struct extent_buffer *eb, const void *ptrv,
unsigned long start,
unsigned long len)
{
size_t cur;
size_t offset;
struct page *page;
char *kaddr;
char *ptr = (char *)ptrv;
size_t start_offset = eb->start & ((u64)PAGE_CACHE_SIZE - 1);
unsigned long i = (start_offset + start) >> PAGE_CACHE_SHIFT;
int ret = 0;
WARN_ON(start > eb->len);
WARN_ON(start + len > eb->start + eb->len);
offset = (start_offset + start) & ((unsigned long)PAGE_CACHE_SIZE - 1);
while (len > 0) {
page = extent_buffer_page(eb, i);
cur = min(len, (PAGE_CACHE_SIZE - offset));
kaddr = kmap_atomic(page, KM_USER0);
ret = memcmp(ptr, kaddr + offset, cur);
kunmap_atomic(kaddr, KM_USER0);
if (ret)
break;
ptr += cur;
len -= cur;
offset = 0;
i++;
}
return ret;
}
void write_extent_buffer(struct extent_buffer *eb, const void *srcv,
unsigned long start, unsigned long len)
{
size_t cur;
size_t offset;
struct page *page;
char *kaddr;
char *src = (char *)srcv;
size_t start_offset = eb->start & ((u64)PAGE_CACHE_SIZE - 1);
unsigned long i = (start_offset + start) >> PAGE_CACHE_SHIFT;
WARN_ON(start > eb->len);
WARN_ON(start + len > eb->start + eb->len);
offset = (start_offset + start) & ((unsigned long)PAGE_CACHE_SIZE - 1);
while (len > 0) {
page = extent_buffer_page(eb, i);
WARN_ON(!PageUptodate(page));
cur = min(len, PAGE_CACHE_SIZE - offset);
kaddr = kmap_atomic(page, KM_USER1);
memcpy(kaddr + offset, src, cur);
kunmap_atomic(kaddr, KM_USER1);
src += cur;
len -= cur;
offset = 0;
i++;
}
}
void memset_extent_buffer(struct extent_buffer *eb, char c,
unsigned long start, unsigned long len)
{
size_t cur;
size_t offset;
struct page *page;
char *kaddr;
size_t start_offset = eb->start & ((u64)PAGE_CACHE_SIZE - 1);
unsigned long i = (start_offset + start) >> PAGE_CACHE_SHIFT;
WARN_ON(start > eb->len);
WARN_ON(start + len > eb->start + eb->len);
offset = (start_offset + start) & ((unsigned long)PAGE_CACHE_SIZE - 1);
while (len > 0) {
page = extent_buffer_page(eb, i);
WARN_ON(!PageUptodate(page));
cur = min(len, PAGE_CACHE_SIZE - offset);
kaddr = kmap_atomic(page, KM_USER0);
memset(kaddr + offset, c, cur);
kunmap_atomic(kaddr, KM_USER0);
len -= cur;
offset = 0;
i++;
}
}
void copy_extent_buffer(struct extent_buffer *dst, struct extent_buffer *src,
unsigned long dst_offset, unsigned long src_offset,
unsigned long len)
{
u64 dst_len = dst->len;
size_t cur;
size_t offset;
struct page *page;
char *kaddr;
size_t start_offset = dst->start & ((u64)PAGE_CACHE_SIZE - 1);
unsigned long i = (start_offset + dst_offset) >> PAGE_CACHE_SHIFT;
WARN_ON(src->len != dst_len);
offset = (start_offset + dst_offset) &
((unsigned long)PAGE_CACHE_SIZE - 1);
while (len > 0) {
page = extent_buffer_page(dst, i);
WARN_ON(!PageUptodate(page));
cur = min(len, (unsigned long)(PAGE_CACHE_SIZE - offset));
kaddr = kmap_atomic(page, KM_USER0);
read_extent_buffer(src, kaddr + offset, src_offset, cur);
kunmap_atomic(kaddr, KM_USER0);
src_offset += cur;
len -= cur;
offset = 0;
i++;
}
}
static void move_pages(struct page *dst_page, struct page *src_page,
unsigned long dst_off, unsigned long src_off,
unsigned long len)
{
char *dst_kaddr = kmap_atomic(dst_page, KM_USER0);
if (dst_page == src_page) {
memmove(dst_kaddr + dst_off, dst_kaddr + src_off, len);
} else {
char *src_kaddr = kmap_atomic(src_page, KM_USER1);
char *p = dst_kaddr + dst_off + len;
char *s = src_kaddr + src_off + len;
while (len--)
*--p = *--s;
kunmap_atomic(src_kaddr, KM_USER1);
}
kunmap_atomic(dst_kaddr, KM_USER0);
}
static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
{
unsigned long distance = (src > dst) ? src - dst : dst - src;
return distance < len;
}
static void copy_pages(struct page *dst_page, struct page *src_page,
unsigned long dst_off, unsigned long src_off,
unsigned long len)
{
char *dst_kaddr = kmap_atomic(dst_page, KM_USER0);
char *src_kaddr;
if (dst_page != src_page) {
src_kaddr = kmap_atomic(src_page, KM_USER1);
} else {
src_kaddr = dst_kaddr;
BUG_ON(areas_overlap(src_off, dst_off, len));
}
memcpy(dst_kaddr + dst_off, src_kaddr + src_off, len);
kunmap_atomic(dst_kaddr, KM_USER0);
if (dst_page != src_page)
kunmap_atomic(src_kaddr, KM_USER1);
}
void memcpy_extent_buffer(struct extent_buffer *dst, unsigned long dst_offset,
unsigned long src_offset, unsigned long len)
{
size_t cur;
size_t dst_off_in_page;
size_t src_off_in_page;
size_t start_offset = dst->start & ((u64)PAGE_CACHE_SIZE - 1);
unsigned long dst_i;
unsigned long src_i;
if (src_offset + len > dst->len) {
printk(KERN_ERR "btrfs memmove bogus src_offset %lu move "
"len %lu dst len %lu\n", src_offset, len, dst->len);
BUG_ON(1);
}
if (dst_offset + len > dst->len) {
printk(KERN_ERR "btrfs memmove bogus dst_offset %lu move "
"len %lu dst len %lu\n", dst_offset, len, dst->len);
BUG_ON(1);
}
while (len > 0) {
dst_off_in_page = (start_offset + dst_offset) &
((unsigned long)PAGE_CACHE_SIZE - 1);
src_off_in_page = (start_offset + src_offset) &
((unsigned long)PAGE_CACHE_SIZE - 1);
dst_i = (start_offset + dst_offset) >> PAGE_CACHE_SHIFT;
src_i = (start_offset + src_offset) >> PAGE_CACHE_SHIFT;
cur = min(len, (unsigned long)(PAGE_CACHE_SIZE -
src_off_in_page));
cur = min_t(unsigned long, cur,
(unsigned long)(PAGE_CACHE_SIZE - dst_off_in_page));
copy_pages(extent_buffer_page(dst, dst_i),
extent_buffer_page(dst, src_i),
dst_off_in_page, src_off_in_page, cur);
src_offset += cur;
dst_offset += cur;
len -= cur;
}
}
void memmove_extent_buffer(struct extent_buffer *dst, unsigned long dst_offset,
unsigned long src_offset, unsigned long len)
{
size_t cur;
size_t dst_off_in_page;
size_t src_off_in_page;
unsigned long dst_end = dst_offset + len - 1;
unsigned long src_end = src_offset + len - 1;
size_t start_offset = dst->start & ((u64)PAGE_CACHE_SIZE - 1);
unsigned long dst_i;
unsigned long src_i;
if (src_offset + len > dst->len) {
printk(KERN_ERR "btrfs memmove bogus src_offset %lu move "
"len %lu len %lu\n", src_offset, len, dst->len);
BUG_ON(1);
}
if (dst_offset + len > dst->len) {
printk(KERN_ERR "btrfs memmove bogus dst_offset %lu move "
"len %lu len %lu\n", dst_offset, len, dst->len);
BUG_ON(1);
}
if (!areas_overlap(src_offset, dst_offset, len)) {
memcpy_extent_buffer(dst, dst_offset, src_offset, len);
return;
}
while (len > 0) {
dst_i = (start_offset + dst_end) >> PAGE_CACHE_SHIFT;
src_i = (start_offset + src_end) >> PAGE_CACHE_SHIFT;
dst_off_in_page = (start_offset + dst_end) &
((unsigned long)PAGE_CACHE_SIZE - 1);
src_off_in_page = (start_offset + src_end) &
((unsigned long)PAGE_CACHE_SIZE - 1);
cur = min_t(unsigned long, len, src_off_in_page + 1);
cur = min(cur, dst_off_in_page + 1);
move_pages(extent_buffer_page(dst, dst_i),
extent_buffer_page(dst, src_i),
dst_off_in_page - cur + 1,
src_off_in_page - cur + 1, cur);
dst_end -= cur;
src_end -= cur;
len -= cur;
}
}
static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
{
struct extent_buffer *eb =
container_of(head, struct extent_buffer, rcu_head);
btrfs_release_extent_buffer(eb);
}
int try_release_extent_buffer(struct extent_io_tree *tree, struct page *page)
{
u64 start = page_offset(page);
struct extent_buffer *eb;
int ret = 1;
spin_lock(&tree->buffer_lock);
eb = radix_tree_lookup(&tree->buffer, start >> PAGE_CACHE_SHIFT);
if (!eb) {
spin_unlock(&tree->buffer_lock);
return ret;
}
if (test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
ret = 0;
goto out;
}
/*
* set @eb->refs to 0 if it is already 1, and then release the @eb.
* Or go back.
*/
if (atomic_cmpxchg(&eb->refs, 1, 0) != 1) {
ret = 0;
goto out;
}
radix_tree_delete(&tree->buffer, start >> PAGE_CACHE_SHIFT);
out:
spin_unlock(&tree->buffer_lock);
/* at this point we can safely release the extent buffer */
if (atomic_read(&eb->refs) == 0)
call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
return ret;
}
| gpl-2.0 |
AOSP-ZEUS/android_kernel_samsung_n1 | arch/x86/mm/memblock.c | 2868 | 8652 | #include <linux/kernel.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/bitops.h>
#include <linux/memblock.h>
#include <linux/bootmem.h>
#include <linux/mm.h>
#include <linux/range.h>
/* Check for already reserved areas */
bool __init memblock_x86_check_reserved_size(u64 *addrp, u64 *sizep, u64 align)
{
struct memblock_region *r;
u64 addr = *addrp, last;
u64 size = *sizep;
bool changed = false;
again:
last = addr + size;
for_each_memblock(reserved, r) {
if (last > r->base && addr < r->base) {
size = r->base - addr;
changed = true;
goto again;
}
if (last > (r->base + r->size) && addr < (r->base + r->size)) {
addr = round_up(r->base + r->size, align);
size = last - addr;
changed = true;
goto again;
}
if (last <= (r->base + r->size) && addr >= r->base) {
*sizep = 0;
return false;
}
}
if (changed) {
*addrp = addr;
*sizep = size;
}
return changed;
}
/*
* Find next free range after start, and size is returned in *sizep
*/
u64 __init memblock_x86_find_in_range_size(u64 start, u64 *sizep, u64 align)
{
struct memblock_region *r;
for_each_memblock(memory, r) {
u64 ei_start = r->base;
u64 ei_last = ei_start + r->size;
u64 addr;
addr = round_up(ei_start, align);
if (addr < start)
addr = round_up(start, align);
if (addr >= ei_last)
continue;
*sizep = ei_last - addr;
while (memblock_x86_check_reserved_size(&addr, sizep, align))
;
if (*sizep)
return addr;
}
return MEMBLOCK_ERROR;
}
static __init struct range *find_range_array(int count)
{
u64 end, size, mem;
struct range *range;
size = sizeof(struct range) * count;
end = memblock.current_limit;
mem = memblock_find_in_range(0, end, size, sizeof(struct range));
if (mem == MEMBLOCK_ERROR)
panic("can not find more space for range array");
/*
* This range is tempoaray, so don't reserve it, it will not be
* overlapped because We will not alloccate new buffer before
* We discard this one
*/
range = __va(mem);
memset(range, 0, size);
return range;
}
static void __init memblock_x86_subtract_reserved(struct range *range, int az)
{
u64 final_start, final_end;
struct memblock_region *r;
/* Take out region array itself at first*/
memblock_free_reserved_regions();
memblock_dbg("Subtract (%ld early reservations)\n", memblock.reserved.cnt);
for_each_memblock(reserved, r) {
memblock_dbg(" [%010llx-%010llx]\n", (u64)r->base, (u64)r->base + r->size - 1);
final_start = PFN_DOWN(r->base);
final_end = PFN_UP(r->base + r->size);
if (final_start >= final_end)
continue;
subtract_range(range, az, final_start, final_end);
}
/* Put region array back ? */
memblock_reserve_reserved_regions();
}
struct count_data {
int nr;
};
static int __init count_work_fn(unsigned long start_pfn,
unsigned long end_pfn, void *datax)
{
struct count_data *data = datax;
data->nr++;
return 0;
}
static int __init count_early_node_map(int nodeid)
{
struct count_data data;
data.nr = 0;
work_with_active_regions(nodeid, count_work_fn, &data);
return data.nr;
}
int __init __get_free_all_memory_range(struct range **rangep, int nodeid,
unsigned long start_pfn, unsigned long end_pfn)
{
int count;
struct range *range;
int nr_range;
count = (memblock.reserved.cnt + count_early_node_map(nodeid)) * 2;
range = find_range_array(count);
nr_range = 0;
/*
* Use early_node_map[] and memblock.reserved.region to get range array
* at first
*/
nr_range = add_from_early_node_map(range, count, nr_range, nodeid);
subtract_range(range, count, 0, start_pfn);
subtract_range(range, count, end_pfn, -1ULL);
memblock_x86_subtract_reserved(range, count);
nr_range = clean_sort_range(range, count);
*rangep = range;
return nr_range;
}
int __init get_free_all_memory_range(struct range **rangep, int nodeid)
{
unsigned long end_pfn = -1UL;
#ifdef CONFIG_X86_32
end_pfn = max_low_pfn;
#endif
return __get_free_all_memory_range(rangep, nodeid, 0, end_pfn);
}
static u64 __init __memblock_x86_memory_in_range(u64 addr, u64 limit, bool get_free)
{
int i, count;
struct range *range;
int nr_range;
u64 final_start, final_end;
u64 free_size;
struct memblock_region *r;
count = (memblock.reserved.cnt + memblock.memory.cnt) * 2;
range = find_range_array(count);
nr_range = 0;
addr = PFN_UP(addr);
limit = PFN_DOWN(limit);
for_each_memblock(memory, r) {
final_start = PFN_UP(r->base);
final_end = PFN_DOWN(r->base + r->size);
if (final_start >= final_end)
continue;
if (final_start >= limit || final_end <= addr)
continue;
nr_range = add_range(range, count, nr_range, final_start, final_end);
}
subtract_range(range, count, 0, addr);
subtract_range(range, count, limit, -1ULL);
/* Subtract memblock.reserved.region in range ? */
if (!get_free)
goto sort_and_count_them;
for_each_memblock(reserved, r) {
final_start = PFN_DOWN(r->base);
final_end = PFN_UP(r->base + r->size);
if (final_start >= final_end)
continue;
if (final_start >= limit || final_end <= addr)
continue;
subtract_range(range, count, final_start, final_end);
}
sort_and_count_them:
nr_range = clean_sort_range(range, count);
free_size = 0;
for (i = 0; i < nr_range; i++)
free_size += range[i].end - range[i].start;
return free_size << PAGE_SHIFT;
}
u64 __init memblock_x86_free_memory_in_range(u64 addr, u64 limit)
{
return __memblock_x86_memory_in_range(addr, limit, true);
}
u64 __init memblock_x86_memory_in_range(u64 addr, u64 limit)
{
return __memblock_x86_memory_in_range(addr, limit, false);
}
void __init memblock_x86_reserve_range(u64 start, u64 end, char *name)
{
if (start == end)
return;
if (WARN_ONCE(start > end, "memblock_x86_reserve_range: wrong range [%#llx, %#llx)\n", start, end))
return;
memblock_dbg(" memblock_x86_reserve_range: [%#010llx-%#010llx] %16s\n", start, end - 1, name);
memblock_reserve(start, end - start);
}
void __init memblock_x86_free_range(u64 start, u64 end)
{
if (start == end)
return;
if (WARN_ONCE(start > end, "memblock_x86_free_range: wrong range [%#llx, %#llx)\n", start, end))
return;
memblock_dbg(" memblock_x86_free_range: [%#010llx-%#010llx]\n", start, end - 1);
memblock_free(start, end - start);
}
/*
* Need to call this function after memblock_x86_register_active_regions,
* so early_node_map[] is filled already.
*/
u64 __init memblock_x86_find_in_range_node(int nid, u64 start, u64 end, u64 size, u64 align)
{
u64 addr;
addr = find_memory_core_early(nid, size, align, start, end);
if (addr != MEMBLOCK_ERROR)
return addr;
/* Fallback, should already have start end within node range */
return memblock_find_in_range(start, end, size, align);
}
/*
* Finds an active region in the address range from start_pfn to last_pfn and
* returns its range in ei_startpfn and ei_endpfn for the memblock entry.
*/
static int __init memblock_x86_find_active_region(const struct memblock_region *ei,
unsigned long start_pfn,
unsigned long last_pfn,
unsigned long *ei_startpfn,
unsigned long *ei_endpfn)
{
u64 align = PAGE_SIZE;
*ei_startpfn = round_up(ei->base, align) >> PAGE_SHIFT;
*ei_endpfn = round_down(ei->base + ei->size, align) >> PAGE_SHIFT;
/* Skip map entries smaller than a page */
if (*ei_startpfn >= *ei_endpfn)
return 0;
/* Skip if map is outside the node */
if (*ei_endpfn <= start_pfn || *ei_startpfn >= last_pfn)
return 0;
/* Check for overlaps */
if (*ei_startpfn < start_pfn)
*ei_startpfn = start_pfn;
if (*ei_endpfn > last_pfn)
*ei_endpfn = last_pfn;
return 1;
}
/* Walk the memblock.memory map and register active regions within a node */
void __init memblock_x86_register_active_regions(int nid, unsigned long start_pfn,
unsigned long last_pfn)
{
unsigned long ei_startpfn;
unsigned long ei_endpfn;
struct memblock_region *r;
for_each_memblock(memory, r)
if (memblock_x86_find_active_region(r, start_pfn, last_pfn,
&ei_startpfn, &ei_endpfn))
add_active_range(nid, ei_startpfn, ei_endpfn);
}
/*
* Find the hole size (in bytes) in the memory range.
* @start: starting address of the memory range to scan
* @end: ending address of the memory range to scan
*/
u64 __init memblock_x86_hole_size(u64 start, u64 end)
{
unsigned long start_pfn = start >> PAGE_SHIFT;
unsigned long last_pfn = end >> PAGE_SHIFT;
unsigned long ei_startpfn, ei_endpfn, ram = 0;
struct memblock_region *r;
for_each_memblock(memory, r)
if (memblock_x86_find_active_region(r, start_pfn, last_pfn,
&ei_startpfn, &ei_endpfn))
ram += ei_endpfn - ei_startpfn;
return end - start - ((u64)ram << PAGE_SHIFT);
}
| gpl-2.0 |
zozo123/boeffla-kernel-jb-u6-s3 | security/integrity/ima/ima_policy.c | 3636 | 12687 | /*
* Copyright (C) 2008 IBM Corporation
* Author: Mimi Zohar <zohar@us.ibm.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 2 of the License.
*
* ima_policy.c
* - initialize default measure policy rules
*
*/
#include <linux/module.h>
#include <linux/list.h>
#include <linux/security.h>
#include <linux/magic.h>
#include <linux/parser.h>
#include <linux/slab.h>
#include "ima.h"
/* flags definitions */
#define IMA_FUNC 0x0001
#define IMA_MASK 0x0002
#define IMA_FSMAGIC 0x0004
#define IMA_UID 0x0008
enum ima_action { UNKNOWN = -1, DONT_MEASURE = 0, MEASURE };
#define MAX_LSM_RULES 6
enum lsm_rule_types { LSM_OBJ_USER, LSM_OBJ_ROLE, LSM_OBJ_TYPE,
LSM_SUBJ_USER, LSM_SUBJ_ROLE, LSM_SUBJ_TYPE
};
struct ima_measure_rule_entry {
struct list_head list;
enum ima_action action;
unsigned int flags;
enum ima_hooks func;
int mask;
unsigned long fsmagic;
uid_t uid;
struct {
void *rule; /* LSM file metadata specific */
int type; /* audit type */
} lsm[MAX_LSM_RULES];
};
/*
* Without LSM specific knowledge, the default policy can only be
* written in terms of .action, .func, .mask, .fsmagic, and .uid
*/
/*
* The minimum rule set to allow for full TCB coverage. Measures all files
* opened or mmap for exec and everything read by root. Dangerous because
* normal users can easily run the machine out of memory simply building
* and running executables.
*/
static struct ima_measure_rule_entry default_rules[] = {
{.action = DONT_MEASURE,.fsmagic = PROC_SUPER_MAGIC,.flags = IMA_FSMAGIC},
{.action = DONT_MEASURE,.fsmagic = SYSFS_MAGIC,.flags = IMA_FSMAGIC},
{.action = DONT_MEASURE,.fsmagic = DEBUGFS_MAGIC,.flags = IMA_FSMAGIC},
{.action = DONT_MEASURE,.fsmagic = TMPFS_MAGIC,.flags = IMA_FSMAGIC},
{.action = DONT_MEASURE,.fsmagic = SECURITYFS_MAGIC,.flags = IMA_FSMAGIC},
{.action = DONT_MEASURE,.fsmagic = SELINUX_MAGIC,.flags = IMA_FSMAGIC},
{.action = MEASURE,.func = FILE_MMAP,.mask = MAY_EXEC,
.flags = IMA_FUNC | IMA_MASK},
{.action = MEASURE,.func = BPRM_CHECK,.mask = MAY_EXEC,
.flags = IMA_FUNC | IMA_MASK},
{.action = MEASURE,.func = FILE_CHECK,.mask = MAY_READ,.uid = 0,
.flags = IMA_FUNC | IMA_MASK | IMA_UID},
};
static LIST_HEAD(measure_default_rules);
static LIST_HEAD(measure_policy_rules);
static struct list_head *ima_measure;
static DEFINE_MUTEX(ima_measure_mutex);
static bool ima_use_tcb __initdata;
static int __init default_policy_setup(char *str)
{
ima_use_tcb = 1;
return 1;
}
__setup("ima_tcb", default_policy_setup);
/**
* ima_match_rules - determine whether an inode matches the measure rule.
* @rule: a pointer to a rule
* @inode: a pointer to an inode
* @func: LIM hook identifier
* @mask: requested action (MAY_READ | MAY_WRITE | MAY_APPEND | MAY_EXEC)
*
* Returns true on rule match, false on failure.
*/
static bool ima_match_rules(struct ima_measure_rule_entry *rule,
struct inode *inode, enum ima_hooks func, int mask)
{
struct task_struct *tsk = current;
int i;
if ((rule->flags & IMA_FUNC) && rule->func != func)
return false;
if ((rule->flags & IMA_MASK) && rule->mask != mask)
return false;
if ((rule->flags & IMA_FSMAGIC)
&& rule->fsmagic != inode->i_sb->s_magic)
return false;
if ((rule->flags & IMA_UID) && rule->uid != tsk->cred->uid)
return false;
for (i = 0; i < MAX_LSM_RULES; i++) {
int rc = 0;
u32 osid, sid;
if (!rule->lsm[i].rule)
continue;
switch (i) {
case LSM_OBJ_USER:
case LSM_OBJ_ROLE:
case LSM_OBJ_TYPE:
security_inode_getsecid(inode, &osid);
rc = security_filter_rule_match(osid,
rule->lsm[i].type,
Audit_equal,
rule->lsm[i].rule,
NULL);
break;
case LSM_SUBJ_USER:
case LSM_SUBJ_ROLE:
case LSM_SUBJ_TYPE:
security_task_getsecid(tsk, &sid);
rc = security_filter_rule_match(sid,
rule->lsm[i].type,
Audit_equal,
rule->lsm[i].rule,
NULL);
default:
break;
}
if (!rc)
return false;
}
return true;
}
/**
* ima_match_policy - decision based on LSM and other conditions
* @inode: pointer to an inode for which the policy decision is being made
* @func: IMA hook identifier
* @mask: requested action (MAY_READ | MAY_WRITE | MAY_APPEND | MAY_EXEC)
*
* Measure decision based on func/mask/fsmagic and LSM(subj/obj/type)
* conditions.
*
* (There is no need for locking when walking the policy list,
* as elements in the list are never deleted, nor does the list
* change.)
*/
int ima_match_policy(struct inode *inode, enum ima_hooks func, int mask)
{
struct ima_measure_rule_entry *entry;
list_for_each_entry(entry, ima_measure, list) {
bool rc;
rc = ima_match_rules(entry, inode, func, mask);
if (rc)
return entry->action;
}
return 0;
}
/**
* ima_init_policy - initialize the default measure rules.
*
* ima_measure points to either the measure_default_rules or the
* the new measure_policy_rules.
*/
void __init ima_init_policy(void)
{
int i, entries;
/* if !ima_use_tcb set entries = 0 so we load NO default rules */
if (ima_use_tcb)
entries = ARRAY_SIZE(default_rules);
else
entries = 0;
for (i = 0; i < entries; i++)
list_add_tail(&default_rules[i].list, &measure_default_rules);
ima_measure = &measure_default_rules;
}
/**
* ima_update_policy - update default_rules with new measure rules
*
* Called on file .release to update the default rules with a complete new
* policy. Once updated, the policy is locked, no additional rules can be
* added to the policy.
*/
void ima_update_policy(void)
{
const char *op = "policy_update";
const char *cause = "already exists";
int result = 1;
int audit_info = 0;
if (ima_measure == &measure_default_rules) {
ima_measure = &measure_policy_rules;
cause = "complete";
result = 0;
}
integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL,
NULL, op, cause, result, audit_info);
}
enum {
Opt_err = -1,
Opt_measure = 1, Opt_dont_measure,
Opt_obj_user, Opt_obj_role, Opt_obj_type,
Opt_subj_user, Opt_subj_role, Opt_subj_type,
Opt_func, Opt_mask, Opt_fsmagic, Opt_uid
};
static match_table_t policy_tokens = {
{Opt_measure, "measure"},
{Opt_dont_measure, "dont_measure"},
{Opt_obj_user, "obj_user=%s"},
{Opt_obj_role, "obj_role=%s"},
{Opt_obj_type, "obj_type=%s"},
{Opt_subj_user, "subj_user=%s"},
{Opt_subj_role, "subj_role=%s"},
{Opt_subj_type, "subj_type=%s"},
{Opt_func, "func=%s"},
{Opt_mask, "mask=%s"},
{Opt_fsmagic, "fsmagic=%s"},
{Opt_uid, "uid=%s"},
{Opt_err, NULL}
};
static int ima_lsm_rule_init(struct ima_measure_rule_entry *entry,
char *args, int lsm_rule, int audit_type)
{
int result;
if (entry->lsm[lsm_rule].rule)
return -EINVAL;
entry->lsm[lsm_rule].type = audit_type;
result = security_filter_rule_init(entry->lsm[lsm_rule].type,
Audit_equal, args,
&entry->lsm[lsm_rule].rule);
if (!entry->lsm[lsm_rule].rule)
return -EINVAL;
return result;
}
static void ima_log_string(struct audit_buffer *ab, char *key, char *value)
{
audit_log_format(ab, "%s=", key);
audit_log_untrustedstring(ab, value);
audit_log_format(ab, " ");
}
static int ima_parse_rule(char *rule, struct ima_measure_rule_entry *entry)
{
struct audit_buffer *ab;
char *p;
int result = 0;
ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_INTEGRITY_RULE);
entry->uid = -1;
entry->action = UNKNOWN;
while ((p = strsep(&rule, " \t")) != NULL) {
substring_t args[MAX_OPT_ARGS];
int token;
unsigned long lnum;
if (result < 0)
break;
if ((*p == '\0') || (*p == ' ') || (*p == '\t'))
continue;
token = match_token(p, policy_tokens, args);
switch (token) {
case Opt_measure:
ima_log_string(ab, "action", "measure");
if (entry->action != UNKNOWN)
result = -EINVAL;
entry->action = MEASURE;
break;
case Opt_dont_measure:
ima_log_string(ab, "action", "dont_measure");
if (entry->action != UNKNOWN)
result = -EINVAL;
entry->action = DONT_MEASURE;
break;
case Opt_func:
ima_log_string(ab, "func", args[0].from);
if (entry->func)
result = -EINVAL;
if (strcmp(args[0].from, "FILE_CHECK") == 0)
entry->func = FILE_CHECK;
/* PATH_CHECK is for backwards compat */
else if (strcmp(args[0].from, "PATH_CHECK") == 0)
entry->func = FILE_CHECK;
else if (strcmp(args[0].from, "FILE_MMAP") == 0)
entry->func = FILE_MMAP;
else if (strcmp(args[0].from, "BPRM_CHECK") == 0)
entry->func = BPRM_CHECK;
else
result = -EINVAL;
if (!result)
entry->flags |= IMA_FUNC;
break;
case Opt_mask:
ima_log_string(ab, "mask", args[0].from);
if (entry->mask)
result = -EINVAL;
if ((strcmp(args[0].from, "MAY_EXEC")) == 0)
entry->mask = MAY_EXEC;
else if (strcmp(args[0].from, "MAY_WRITE") == 0)
entry->mask = MAY_WRITE;
else if (strcmp(args[0].from, "MAY_READ") == 0)
entry->mask = MAY_READ;
else if (strcmp(args[0].from, "MAY_APPEND") == 0)
entry->mask = MAY_APPEND;
else
result = -EINVAL;
if (!result)
entry->flags |= IMA_MASK;
break;
case Opt_fsmagic:
ima_log_string(ab, "fsmagic", args[0].from);
if (entry->fsmagic) {
result = -EINVAL;
break;
}
result = strict_strtoul(args[0].from, 16,
&entry->fsmagic);
if (!result)
entry->flags |= IMA_FSMAGIC;
break;
case Opt_uid:
ima_log_string(ab, "uid", args[0].from);
if (entry->uid != -1) {
result = -EINVAL;
break;
}
result = strict_strtoul(args[0].from, 10, &lnum);
if (!result) {
entry->uid = (uid_t) lnum;
if (entry->uid != lnum)
result = -EINVAL;
else
entry->flags |= IMA_UID;
}
break;
case Opt_obj_user:
ima_log_string(ab, "obj_user", args[0].from);
result = ima_lsm_rule_init(entry, args[0].from,
LSM_OBJ_USER,
AUDIT_OBJ_USER);
break;
case Opt_obj_role:
ima_log_string(ab, "obj_role", args[0].from);
result = ima_lsm_rule_init(entry, args[0].from,
LSM_OBJ_ROLE,
AUDIT_OBJ_ROLE);
break;
case Opt_obj_type:
ima_log_string(ab, "obj_type", args[0].from);
result = ima_lsm_rule_init(entry, args[0].from,
LSM_OBJ_TYPE,
AUDIT_OBJ_TYPE);
break;
case Opt_subj_user:
ima_log_string(ab, "subj_user", args[0].from);
result = ima_lsm_rule_init(entry, args[0].from,
LSM_SUBJ_USER,
AUDIT_SUBJ_USER);
break;
case Opt_subj_role:
ima_log_string(ab, "subj_role", args[0].from);
result = ima_lsm_rule_init(entry, args[0].from,
LSM_SUBJ_ROLE,
AUDIT_SUBJ_ROLE);
break;
case Opt_subj_type:
ima_log_string(ab, "subj_type", args[0].from);
result = ima_lsm_rule_init(entry, args[0].from,
LSM_SUBJ_TYPE,
AUDIT_SUBJ_TYPE);
break;
case Opt_err:
ima_log_string(ab, "UNKNOWN", p);
result = -EINVAL;
break;
}
}
if (!result && (entry->action == UNKNOWN))
result = -EINVAL;
audit_log_format(ab, "res=%d", !!result);
audit_log_end(ab);
return result;
}
/**
* ima_parse_add_rule - add a rule to measure_policy_rules
* @rule - ima measurement policy rule
*
* Uses a mutex to protect the policy list from multiple concurrent writers.
* Returns the length of the rule parsed, an error code on failure
*/
ssize_t ima_parse_add_rule(char *rule)
{
const char *op = "update_policy";
char *p;
struct ima_measure_rule_entry *entry;
ssize_t result, len;
int audit_info = 0;
/* Prevent installed policy from changing */
if (ima_measure != &measure_default_rules) {
integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL,
NULL, op, "already exists",
-EACCES, audit_info);
return -EACCES;
}
entry = kzalloc(sizeof(*entry), GFP_KERNEL);
if (!entry) {
integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL,
NULL, op, "-ENOMEM", -ENOMEM, audit_info);
return -ENOMEM;
}
INIT_LIST_HEAD(&entry->list);
p = strsep(&rule, "\n");
len = strlen(p) + 1;
if (*p == '#') {
kfree(entry);
return len;
}
result = ima_parse_rule(p, entry);
if (result) {
kfree(entry);
integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL,
NULL, op, "invalid policy", result,
audit_info);
return result;
}
mutex_lock(&ima_measure_mutex);
list_add_tail(&entry->list, &measure_policy_rules);
mutex_unlock(&ima_measure_mutex);
return len;
}
/* ima_delete_rules called to cleanup invalid policy */
void ima_delete_rules(void)
{
struct ima_measure_rule_entry *entry, *tmp;
mutex_lock(&ima_measure_mutex);
list_for_each_entry_safe(entry, tmp, &measure_policy_rules, list) {
list_del(&entry->list);
kfree(entry);
}
mutex_unlock(&ima_measure_mutex);
}
| gpl-2.0 |
KonstaT/zte-turies-35 | drivers/input/serio/at32psif.c | 3636 | 8585 | /*
* Copyright (C) 2007 Atmel Corporation
*
* Driver for the AT32AP700X PS/2 controller (PSIF).
*
* 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/device.h>
#include <linux/init.h>
#include <linux/serio.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/io.h>
#include <linux/clk.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
/* PSIF register offsets */
#define PSIF_CR 0x00
#define PSIF_RHR 0x04
#define PSIF_THR 0x08
#define PSIF_SR 0x10
#define PSIF_IER 0x14
#define PSIF_IDR 0x18
#define PSIF_IMR 0x1c
#define PSIF_PSR 0x24
/* Bitfields in control register. */
#define PSIF_CR_RXDIS_OFFSET 1
#define PSIF_CR_RXDIS_SIZE 1
#define PSIF_CR_RXEN_OFFSET 0
#define PSIF_CR_RXEN_SIZE 1
#define PSIF_CR_SWRST_OFFSET 15
#define PSIF_CR_SWRST_SIZE 1
#define PSIF_CR_TXDIS_OFFSET 9
#define PSIF_CR_TXDIS_SIZE 1
#define PSIF_CR_TXEN_OFFSET 8
#define PSIF_CR_TXEN_SIZE 1
/* Bitfields in interrupt disable, enable, mask and status register. */
#define PSIF_NACK_OFFSET 8
#define PSIF_NACK_SIZE 1
#define PSIF_OVRUN_OFFSET 5
#define PSIF_OVRUN_SIZE 1
#define PSIF_PARITY_OFFSET 9
#define PSIF_PARITY_SIZE 1
#define PSIF_RXRDY_OFFSET 4
#define PSIF_RXRDY_SIZE 1
#define PSIF_TXEMPTY_OFFSET 1
#define PSIF_TXEMPTY_SIZE 1
#define PSIF_TXRDY_OFFSET 0
#define PSIF_TXRDY_SIZE 1
/* Bitfields in prescale register. */
#define PSIF_PSR_PRSCV_OFFSET 0
#define PSIF_PSR_PRSCV_SIZE 12
/* Bitfields in receive hold register. */
#define PSIF_RHR_RXDATA_OFFSET 0
#define PSIF_RHR_RXDATA_SIZE 8
/* Bitfields in transmit hold register. */
#define PSIF_THR_TXDATA_OFFSET 0
#define PSIF_THR_TXDATA_SIZE 8
/* Bit manipulation macros */
#define PSIF_BIT(name) \
(1 << PSIF_##name##_OFFSET)
#define PSIF_BF(name, value) \
(((value) & ((1 << PSIF_##name##_SIZE) - 1)) \
<< PSIF_##name##_OFFSET)
#define PSIF_BFEXT(name, value) \
(((value) >> PSIF_##name##_OFFSET) \
& ((1 << PSIF_##name##_SIZE) - 1))
#define PSIF_BFINS(name, value, old) \
(((old) & ~(((1 << PSIF_##name##_SIZE) - 1) \
<< PSIF_##name##_OFFSET)) \
| PSIF_BF(name, value))
/* Register access macros */
#define psif_readl(port, reg) \
__raw_readl((port)->regs + PSIF_##reg)
#define psif_writel(port, reg, value) \
__raw_writel((value), (port)->regs + PSIF_##reg)
struct psif {
struct platform_device *pdev;
struct clk *pclk;
struct serio *io;
void __iomem *regs;
unsigned int irq;
unsigned int open;
/* Prevent concurrent writes to PSIF THR. */
spinlock_t lock;
};
static irqreturn_t psif_interrupt(int irq, void *_ptr)
{
struct psif *psif = _ptr;
int retval = IRQ_NONE;
unsigned int io_flags = 0;
unsigned long status;
status = psif_readl(psif, SR);
if (status & PSIF_BIT(RXRDY)) {
unsigned char val = (unsigned char) psif_readl(psif, RHR);
if (status & PSIF_BIT(PARITY))
io_flags |= SERIO_PARITY;
if (status & PSIF_BIT(OVRUN))
dev_err(&psif->pdev->dev, "overrun read error\n");
serio_interrupt(psif->io, val, io_flags);
retval = IRQ_HANDLED;
}
return retval;
}
static int psif_write(struct serio *io, unsigned char val)
{
struct psif *psif = io->port_data;
unsigned long flags;
int timeout = 10;
int retval = 0;
spin_lock_irqsave(&psif->lock, flags);
while (!(psif_readl(psif, SR) & PSIF_BIT(TXEMPTY)) && timeout--)
udelay(50);
if (timeout >= 0) {
psif_writel(psif, THR, val);
} else {
dev_dbg(&psif->pdev->dev, "timeout writing to THR\n");
retval = -EBUSY;
}
spin_unlock_irqrestore(&psif->lock, flags);
return retval;
}
static int psif_open(struct serio *io)
{
struct psif *psif = io->port_data;
int retval;
retval = clk_enable(psif->pclk);
if (retval)
goto out;
psif_writel(psif, CR, PSIF_BIT(CR_TXEN) | PSIF_BIT(CR_RXEN));
psif_writel(psif, IER, PSIF_BIT(RXRDY));
psif->open = 1;
out:
return retval;
}
static void psif_close(struct serio *io)
{
struct psif *psif = io->port_data;
psif->open = 0;
psif_writel(psif, IDR, ~0UL);
psif_writel(psif, CR, PSIF_BIT(CR_TXDIS) | PSIF_BIT(CR_RXDIS));
clk_disable(psif->pclk);
}
static void psif_set_prescaler(struct psif *psif)
{
unsigned long prscv;
unsigned long rate = clk_get_rate(psif->pclk);
/* PRSCV = Pulse length (100 us) * PSIF module frequency. */
prscv = 100 * (rate / 1000000UL);
if (prscv > ((1<<PSIF_PSR_PRSCV_SIZE) - 1)) {
prscv = (1<<PSIF_PSR_PRSCV_SIZE) - 1;
dev_dbg(&psif->pdev->dev, "pclk too fast, "
"prescaler set to max\n");
}
clk_enable(psif->pclk);
psif_writel(psif, PSR, prscv);
clk_disable(psif->pclk);
}
static int __init psif_probe(struct platform_device *pdev)
{
struct resource *regs;
struct psif *psif;
struct serio *io;
struct clk *pclk;
int irq;
int ret;
psif = kzalloc(sizeof(struct psif), GFP_KERNEL);
if (!psif) {
dev_dbg(&pdev->dev, "out of memory\n");
ret = -ENOMEM;
goto out;
}
psif->pdev = pdev;
io = kzalloc(sizeof(struct serio), GFP_KERNEL);
if (!io) {
dev_dbg(&pdev->dev, "out of memory\n");
ret = -ENOMEM;
goto out_free_psif;
}
psif->io = io;
regs = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!regs) {
dev_dbg(&pdev->dev, "no mmio resources defined\n");
ret = -ENOMEM;
goto out_free_io;
}
psif->regs = ioremap(regs->start, resource_size(regs));
if (!psif->regs) {
ret = -ENOMEM;
dev_dbg(&pdev->dev, "could not map I/O memory\n");
goto out_free_io;
}
pclk = clk_get(&pdev->dev, "pclk");
if (IS_ERR(pclk)) {
dev_dbg(&pdev->dev, "could not get peripheral clock\n");
ret = PTR_ERR(pclk);
goto out_iounmap;
}
psif->pclk = pclk;
/* Reset the PSIF to enter at a known state. */
ret = clk_enable(pclk);
if (ret) {
dev_dbg(&pdev->dev, "could not enable pclk\n");
goto out_put_clk;
}
psif_writel(psif, CR, PSIF_BIT(CR_SWRST));
clk_disable(pclk);
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
dev_dbg(&pdev->dev, "could not get irq\n");
ret = -ENXIO;
goto out_put_clk;
}
ret = request_irq(irq, psif_interrupt, IRQF_SHARED, "at32psif", psif);
if (ret) {
dev_dbg(&pdev->dev, "could not request irq %d\n", irq);
goto out_put_clk;
}
psif->irq = irq;
io->id.type = SERIO_8042;
io->write = psif_write;
io->open = psif_open;
io->close = psif_close;
snprintf(io->name, sizeof(io->name), "AVR32 PS/2 port%d", pdev->id);
snprintf(io->phys, sizeof(io->phys), "at32psif/serio%d", pdev->id);
io->port_data = psif;
io->dev.parent = &pdev->dev;
psif_set_prescaler(psif);
spin_lock_init(&psif->lock);
serio_register_port(psif->io);
platform_set_drvdata(pdev, psif);
dev_info(&pdev->dev, "Atmel AVR32 PSIF PS/2 driver on 0x%08x irq %d\n",
(int)psif->regs, psif->irq);
return 0;
out_put_clk:
clk_put(psif->pclk);
out_iounmap:
iounmap(psif->regs);
out_free_io:
kfree(io);
out_free_psif:
kfree(psif);
out:
return ret;
}
static int __exit psif_remove(struct platform_device *pdev)
{
struct psif *psif = platform_get_drvdata(pdev);
psif_writel(psif, IDR, ~0UL);
psif_writel(psif, CR, PSIF_BIT(CR_TXDIS) | PSIF_BIT(CR_RXDIS));
serio_unregister_port(psif->io);
iounmap(psif->regs);
free_irq(psif->irq, psif);
clk_put(psif->pclk);
kfree(psif);
platform_set_drvdata(pdev, NULL);
return 0;
}
#ifdef CONFIG_PM
static int psif_suspend(struct platform_device *pdev, pm_message_t state)
{
struct psif *psif = platform_get_drvdata(pdev);
if (psif->open) {
psif_writel(psif, CR, PSIF_BIT(CR_RXDIS) | PSIF_BIT(CR_TXDIS));
clk_disable(psif->pclk);
}
return 0;
}
static int psif_resume(struct platform_device *pdev)
{
struct psif *psif = platform_get_drvdata(pdev);
if (psif->open) {
clk_enable(psif->pclk);
psif_set_prescaler(psif);
psif_writel(psif, CR, PSIF_BIT(CR_RXEN) | PSIF_BIT(CR_TXEN));
}
return 0;
}
#else
#define psif_suspend NULL
#define psif_resume NULL
#endif
static struct platform_driver psif_driver = {
.remove = __exit_p(psif_remove),
.driver = {
.name = "atmel_psif",
.owner = THIS_MODULE,
},
.suspend = psif_suspend,
.resume = psif_resume,
};
static int __init psif_init(void)
{
return platform_driver_probe(&psif_driver, psif_probe);
}
static void __exit psif_exit(void)
{
platform_driver_unregister(&psif_driver);
}
module_init(psif_init);
module_exit(psif_exit);
MODULE_AUTHOR("Hans-Christian Egtvedt <hans-christian.egtvedt@atmel.com>");
MODULE_DESCRIPTION("Atmel AVR32 PSIF PS/2 driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
AndrewDB/rk3066-kernel | arch/arm/mach-footbridge/personal-pci.c | 4404 | 1400 | /*
* linux/arch/arm/mach-footbridge/personal-pci.c
*
* PCI bios-type initialisation for PCI machines
*
* Bits taken from various places.
*/
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <asm/irq.h>
#include <asm/mach/pci.h>
#include <asm/mach-types.h>
static int irqmap_personal_server[] __initdata = {
IRQ_IN0, IRQ_IN1, IRQ_IN2, IRQ_IN3, 0, 0, 0,
IRQ_DOORBELLHOST, IRQ_DMA1, IRQ_DMA2, IRQ_PCI
};
static int __init personal_server_map_irq(struct pci_dev *dev, u8 slot, u8 pin)
{
unsigned char line;
pci_read_config_byte(dev, PCI_INTERRUPT_LINE, &line);
if (line > 0x40 && line <= 0x5f) {
/* line corresponds to the bit controlling this interrupt
* in the footbridge. Ignore the first 8 interrupt bits,
* look up the rest in the map. IN0 is bit number 8
*/
return irqmap_personal_server[(line & 0x1f) - 8];
} else if (line == 0) {
/* no interrupt */
return 0;
} else
return irqmap_personal_server[(line - 1) & 3];
}
static struct hw_pci personal_server_pci __initdata = {
.map_irq = personal_server_map_irq,
.nr_controllers = 1,
.setup = dc21285_setup,
.scan = dc21285_scan_bus,
.preinit = dc21285_preinit,
.postinit = dc21285_postinit,
};
static int __init personal_pci_init(void)
{
if (machine_is_personal_server())
pci_common_init(&personal_server_pci);
return 0;
}
subsys_initcall(personal_pci_init);
| gpl-2.0 |
Phreya/phreya_kernel_onyx_cm | drivers/media/video/zoran/zoran_device.c | 4916 | 43455 | /*
* Zoran zr36057/zr36067 PCI controller driver, for the
* Pinnacle/Miro DC10/DC10+/DC30/DC30+, Iomega Buz, Linux
* Media Labs LML33/LML33R10.
*
* This part handles device access (PCI/I2C/codec/...)
*
* Copyright (C) 2000 Serguei Miridonov <mirsev@cicese.mx>
*
* Currently maintained by:
* Ronald Bultje <rbultje@ronald.bitfreak.net>
* Laurent Pinchart <laurent.pinchart@skynet.be>
* Mailinglist <mjpeg-users@lists.sf.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <linux/interrupt.h>
#include <linux/proc_fs.h>
#include <linux/i2c.h>
#include <linux/i2c-algo-bit.h>
#include <linux/videodev2.h>
#include <media/v4l2-common.h>
#include <linux/spinlock.h>
#include <linux/sem.h>
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/wait.h>
#include <asm/byteorder.h>
#include <asm/io.h>
#include "videocodec.h"
#include "zoran.h"
#include "zoran_device.h"
#include "zoran_card.h"
#define IRQ_MASK ( ZR36057_ISR_GIRQ0 | \
ZR36057_ISR_GIRQ1 | \
ZR36057_ISR_JPEGRepIRQ )
static bool lml33dpath; /* default = 0
* 1 will use digital path in capture
* mode instead of analog. It can be
* used for picture adjustments using
* tool like xawtv while watching image
* on TV monitor connected to the output.
* However, due to absence of 75 Ohm
* load on Bt819 input, there will be
* some image imperfections */
module_param(lml33dpath, bool, 0644);
MODULE_PARM_DESC(lml33dpath,
"Use digital path capture mode (on LML33 cards)");
static void
zr36057_init_vfe (struct zoran *zr);
/*
* General Purpose I/O and Guest bus access
*/
/*
* This is a bit tricky. When a board lacks a GPIO function, the corresponding
* GPIO bit number in the card_info structure is set to 0.
*/
void
GPIO (struct zoran *zr,
int bit,
unsigned int value)
{
u32 reg;
u32 mask;
/* Make sure the bit number is legal
* A bit number of -1 (lacking) gives a mask of 0,
* making it harmless */
mask = (1 << (24 + bit)) & 0xff000000;
reg = btread(ZR36057_GPPGCR1) & ~mask;
if (value) {
reg |= mask;
}
btwrite(reg, ZR36057_GPPGCR1);
udelay(1);
}
/*
* Wait til post office is no longer busy
*/
int
post_office_wait (struct zoran *zr)
{
u32 por;
// while (((por = btread(ZR36057_POR)) & (ZR36057_POR_POPen | ZR36057_POR_POTime)) == ZR36057_POR_POPen) {
while ((por = btread(ZR36057_POR)) & ZR36057_POR_POPen) {
/* wait for something to happen */
}
if ((por & ZR36057_POR_POTime) && !zr->card.gws_not_connected) {
/* In LML33/BUZ \GWS line is not connected, so it has always timeout set */
dprintk(1, KERN_INFO "%s: pop timeout %08x\n", ZR_DEVNAME(zr),
por);
return -1;
}
return 0;
}
int
post_office_write (struct zoran *zr,
unsigned int guest,
unsigned int reg,
unsigned int value)
{
u32 por;
por =
ZR36057_POR_PODir | ZR36057_POR_POTime | ((guest & 7) << 20) |
((reg & 7) << 16) | (value & 0xFF);
btwrite(por, ZR36057_POR);
return post_office_wait(zr);
}
int
post_office_read (struct zoran *zr,
unsigned int guest,
unsigned int reg)
{
u32 por;
por = ZR36057_POR_POTime | ((guest & 7) << 20) | ((reg & 7) << 16);
btwrite(por, ZR36057_POR);
if (post_office_wait(zr) < 0) {
return -1;
}
return btread(ZR36057_POR) & 0xFF;
}
/*
* detect guests
*/
static void
dump_guests (struct zoran *zr)
{
if (zr36067_debug > 2) {
int i, guest[8];
for (i = 1; i < 8; i++) { // Don't read jpeg codec here
guest[i] = post_office_read(zr, i, 0);
}
printk(KERN_INFO "%s: Guests:", ZR_DEVNAME(zr));
for (i = 1; i < 8; i++) {
printk(" 0x%02x", guest[i]);
}
printk("\n");
}
}
static inline unsigned long
get_time (void)
{
struct timeval tv;
do_gettimeofday(&tv);
return (1000000 * tv.tv_sec + tv.tv_usec);
}
void
detect_guest_activity (struct zoran *zr)
{
int timeout, i, j, res, guest[8], guest0[8], change[8][3];
unsigned long t0, t1;
dump_guests(zr);
printk(KERN_INFO "%s: Detecting guests activity, please wait...\n",
ZR_DEVNAME(zr));
for (i = 1; i < 8; i++) { // Don't read jpeg codec here
guest0[i] = guest[i] = post_office_read(zr, i, 0);
}
timeout = 0;
j = 0;
t0 = get_time();
while (timeout < 10000) {
udelay(10);
timeout++;
for (i = 1; (i < 8) && (j < 8); i++) {
res = post_office_read(zr, i, 0);
if (res != guest[i]) {
t1 = get_time();
change[j][0] = (t1 - t0);
t0 = t1;
change[j][1] = i;
change[j][2] = res;
j++;
guest[i] = res;
}
}
if (j >= 8)
break;
}
printk(KERN_INFO "%s: Guests:", ZR_DEVNAME(zr));
for (i = 1; i < 8; i++) {
printk(" 0x%02x", guest0[i]);
}
printk("\n");
if (j == 0) {
printk(KERN_INFO "%s: No activity detected.\n", ZR_DEVNAME(zr));
return;
}
for (i = 0; i < j; i++) {
printk(KERN_INFO "%s: %6d: %d => 0x%02x\n", ZR_DEVNAME(zr),
change[i][0], change[i][1], change[i][2]);
}
}
/*
* JPEG Codec access
*/
void
jpeg_codec_sleep (struct zoran *zr,
int sleep)
{
GPIO(zr, zr->card.gpio[ZR_GPIO_JPEG_SLEEP], !sleep);
if (!sleep) {
dprintk(3,
KERN_DEBUG
"%s: jpeg_codec_sleep() - wake GPIO=0x%08x\n",
ZR_DEVNAME(zr), btread(ZR36057_GPPGCR1));
udelay(500);
} else {
dprintk(3,
KERN_DEBUG
"%s: jpeg_codec_sleep() - sleep GPIO=0x%08x\n",
ZR_DEVNAME(zr), btread(ZR36057_GPPGCR1));
udelay(2);
}
}
int
jpeg_codec_reset (struct zoran *zr)
{
/* Take the codec out of sleep */
jpeg_codec_sleep(zr, 0);
if (zr->card.gpcs[GPCS_JPEG_RESET] != 0xff) {
post_office_write(zr, zr->card.gpcs[GPCS_JPEG_RESET], 0,
0);
udelay(2);
} else {
GPIO(zr, zr->card.gpio[ZR_GPIO_JPEG_RESET], 0);
udelay(2);
GPIO(zr, zr->card.gpio[ZR_GPIO_JPEG_RESET], 1);
udelay(2);
}
return 0;
}
/*
* Set the registers for the size we have specified. Don't bother
* trying to understand this without the ZR36057 manual in front of
* you [AC].
*
* PS: The manual is free for download in .pdf format from
* www.zoran.com - nicely done those folks.
*/
static void
zr36057_adjust_vfe (struct zoran *zr,
enum zoran_codec_mode mode)
{
u32 reg;
switch (mode) {
case BUZ_MODE_MOTION_DECOMPRESS:
btand(~ZR36057_VFESPFR_ExtFl, ZR36057_VFESPFR);
reg = btread(ZR36057_VFEHCR);
if ((reg & (1 << 10)) && zr->card.type != LML33R10) {
reg += ((1 << 10) | 1);
}
btwrite(reg, ZR36057_VFEHCR);
break;
case BUZ_MODE_MOTION_COMPRESS:
case BUZ_MODE_IDLE:
default:
if ((zr->norm & V4L2_STD_NTSC) ||
(zr->card.type == LML33R10 &&
(zr->norm & V4L2_STD_PAL)))
btand(~ZR36057_VFESPFR_ExtFl, ZR36057_VFESPFR);
else
btor(ZR36057_VFESPFR_ExtFl, ZR36057_VFESPFR);
reg = btread(ZR36057_VFEHCR);
if (!(reg & (1 << 10)) && zr->card.type != LML33R10) {
reg -= ((1 << 10) | 1);
}
btwrite(reg, ZR36057_VFEHCR);
break;
}
}
/*
* set geometry
*/
static void
zr36057_set_vfe (struct zoran *zr,
int video_width,
int video_height,
const struct zoran_format *format)
{
struct tvnorm *tvn;
unsigned HStart, HEnd, VStart, VEnd;
unsigned DispMode;
unsigned VidWinWid, VidWinHt;
unsigned hcrop1, hcrop2, vcrop1, vcrop2;
unsigned Wa, We, Ha, He;
unsigned X, Y, HorDcm, VerDcm;
u32 reg;
unsigned mask_line_size;
tvn = zr->timing;
Wa = tvn->Wa;
Ha = tvn->Ha;
dprintk(2, KERN_INFO "%s: set_vfe() - width = %d, height = %d\n",
ZR_DEVNAME(zr), video_width, video_height);
if (video_width < BUZ_MIN_WIDTH ||
video_height < BUZ_MIN_HEIGHT ||
video_width > Wa || video_height > Ha) {
dprintk(1, KERN_ERR "%s: set_vfe: w=%d h=%d not valid\n",
ZR_DEVNAME(zr), video_width, video_height);
return;
}
/**** zr36057 ****/
/* horizontal */
VidWinWid = video_width;
X = DIV_ROUND_UP(VidWinWid * 64, tvn->Wa);
We = (VidWinWid * 64) / X;
HorDcm = 64 - X;
hcrop1 = 2 * ((tvn->Wa - We) / 4);
hcrop2 = tvn->Wa - We - hcrop1;
HStart = tvn->HStart ? tvn->HStart : 1;
/* (Ronald) Original comment:
* "| 1 Doesn't have any effect, tested on both a DC10 and a DC10+"
* this is false. It inverses chroma values on the LML33R10 (so Cr
* suddenly is shown as Cb and reverse, really cool effect if you
* want to see blue faces, not useful otherwise). So don't use |1.
* However, the DC10 has '0' as HStart, but does need |1, so we
* use a dirty check...
*/
HEnd = HStart + tvn->Wa - 1;
HStart += hcrop1;
HEnd -= hcrop2;
reg = ((HStart & ZR36057_VFEHCR_Hmask) << ZR36057_VFEHCR_HStart)
| ((HEnd & ZR36057_VFEHCR_Hmask) << ZR36057_VFEHCR_HEnd);
if (zr->card.vfe_pol.hsync_pol)
reg |= ZR36057_VFEHCR_HSPol;
btwrite(reg, ZR36057_VFEHCR);
/* Vertical */
DispMode = !(video_height > BUZ_MAX_HEIGHT / 2);
VidWinHt = DispMode ? video_height : video_height / 2;
Y = DIV_ROUND_UP(VidWinHt * 64 * 2, tvn->Ha);
He = (VidWinHt * 64) / Y;
VerDcm = 64 - Y;
vcrop1 = (tvn->Ha / 2 - He) / 2;
vcrop2 = tvn->Ha / 2 - He - vcrop1;
VStart = tvn->VStart;
VEnd = VStart + tvn->Ha / 2; // - 1; FIXME SnapShot times out with -1 in 768*576 on the DC10 - LP
VStart += vcrop1;
VEnd -= vcrop2;
reg = ((VStart & ZR36057_VFEVCR_Vmask) << ZR36057_VFEVCR_VStart)
| ((VEnd & ZR36057_VFEVCR_Vmask) << ZR36057_VFEVCR_VEnd);
if (zr->card.vfe_pol.vsync_pol)
reg |= ZR36057_VFEVCR_VSPol;
btwrite(reg, ZR36057_VFEVCR);
/* scaler and pixel format */
reg = 0;
reg |= (HorDcm << ZR36057_VFESPFR_HorDcm);
reg |= (VerDcm << ZR36057_VFESPFR_VerDcm);
reg |= (DispMode << ZR36057_VFESPFR_DispMode);
/* RJ: I don't know, why the following has to be the opposite
* of the corresponding ZR36060 setting, but only this way
* we get the correct colors when uncompressing to the screen */
//reg |= ZR36057_VFESPFR_VCLKPol; /**/
/* RJ: Don't know if that is needed for NTSC also */
if (!(zr->norm & V4L2_STD_NTSC))
reg |= ZR36057_VFESPFR_ExtFl; // NEEDED!!!!!!! Wolfgang
reg |= ZR36057_VFESPFR_TopField;
if (HorDcm >= 48) {
reg |= 3 << ZR36057_VFESPFR_HFilter; /* 5 tap filter */
} else if (HorDcm >= 32) {
reg |= 2 << ZR36057_VFESPFR_HFilter; /* 4 tap filter */
} else if (HorDcm >= 16) {
reg |= 1 << ZR36057_VFESPFR_HFilter; /* 3 tap filter */
}
reg |= format->vfespfr;
btwrite(reg, ZR36057_VFESPFR);
/* display configuration */
reg = (16 << ZR36057_VDCR_MinPix)
| (VidWinHt << ZR36057_VDCR_VidWinHt)
| (VidWinWid << ZR36057_VDCR_VidWinWid);
if (pci_pci_problems & PCIPCI_TRITON)
// || zr->revision < 1) // Revision 1 has also Triton support
reg &= ~ZR36057_VDCR_Triton;
else
reg |= ZR36057_VDCR_Triton;
btwrite(reg, ZR36057_VDCR);
/* (Ronald) don't write this if overlay_mask = NULL */
if (zr->overlay_mask) {
/* Write overlay clipping mask data, but don't enable overlay clipping */
/* RJ: since this makes only sense on the screen, we use
* zr->overlay_settings.width instead of video_width */
mask_line_size = (BUZ_MAX_WIDTH + 31) / 32;
reg = virt_to_bus(zr->overlay_mask);
btwrite(reg, ZR36057_MMTR);
reg = virt_to_bus(zr->overlay_mask + mask_line_size);
btwrite(reg, ZR36057_MMBR);
reg =
mask_line_size - (zr->overlay_settings.width +
31) / 32;
if (DispMode == 0)
reg += mask_line_size;
reg <<= ZR36057_OCR_MaskStride;
btwrite(reg, ZR36057_OCR);
}
zr36057_adjust_vfe(zr, zr->codec_mode);
}
/*
* Switch overlay on or off
*/
void
zr36057_overlay (struct zoran *zr,
int on)
{
u32 reg;
if (on) {
/* do the necessary settings ... */
btand(~ZR36057_VDCR_VidEn, ZR36057_VDCR); /* switch it off first */
zr36057_set_vfe(zr,
zr->overlay_settings.width,
zr->overlay_settings.height,
zr->overlay_settings.format);
/* Start and length of each line MUST be 4-byte aligned.
* This should be already checked before the call to this routine.
* All error messages are internal driver checking only! */
/* video display top and bottom registers */
reg = (long) zr->vbuf_base +
zr->overlay_settings.x *
((zr->overlay_settings.format->depth + 7) / 8) +
zr->overlay_settings.y *
zr->vbuf_bytesperline;
btwrite(reg, ZR36057_VDTR);
if (reg & 3)
dprintk(1,
KERN_ERR
"%s: zr36057_overlay() - video_address not aligned\n",
ZR_DEVNAME(zr));
if (zr->overlay_settings.height > BUZ_MAX_HEIGHT / 2)
reg += zr->vbuf_bytesperline;
btwrite(reg, ZR36057_VDBR);
/* video stride, status, and frame grab register */
reg = zr->vbuf_bytesperline -
zr->overlay_settings.width *
((zr->overlay_settings.format->depth + 7) / 8);
if (zr->overlay_settings.height > BUZ_MAX_HEIGHT / 2)
reg += zr->vbuf_bytesperline;
if (reg & 3)
dprintk(1,
KERN_ERR
"%s: zr36057_overlay() - video_stride not aligned\n",
ZR_DEVNAME(zr));
reg = (reg << ZR36057_VSSFGR_DispStride);
reg |= ZR36057_VSSFGR_VidOvf; /* clear overflow status */
btwrite(reg, ZR36057_VSSFGR);
/* Set overlay clipping */
if (zr->overlay_settings.clipcount > 0)
btor(ZR36057_OCR_OvlEnable, ZR36057_OCR);
/* ... and switch it on */
btor(ZR36057_VDCR_VidEn, ZR36057_VDCR);
} else {
/* Switch it off */
btand(~ZR36057_VDCR_VidEn, ZR36057_VDCR);
}
}
/*
* The overlay mask has one bit for each pixel on a scan line,
* and the maximum window size is BUZ_MAX_WIDTH * BUZ_MAX_HEIGHT pixels.
*/
void write_overlay_mask(struct zoran_fh *fh, struct v4l2_clip *vp, int count)
{
struct zoran *zr = fh->zr;
unsigned mask_line_size = (BUZ_MAX_WIDTH + 31) / 32;
u32 *mask;
int x, y, width, height;
unsigned i, j, k;
u32 reg;
/* fill mask with one bits */
memset(fh->overlay_mask, ~0, mask_line_size * 4 * BUZ_MAX_HEIGHT);
reg = 0;
for (i = 0; i < count; ++i) {
/* pick up local copy of clip */
x = vp[i].c.left;
y = vp[i].c.top;
width = vp[i].c.width;
height = vp[i].c.height;
/* trim clips that extend beyond the window */
if (x < 0) {
width += x;
x = 0;
}
if (y < 0) {
height += y;
y = 0;
}
if (x + width > fh->overlay_settings.width) {
width = fh->overlay_settings.width - x;
}
if (y + height > fh->overlay_settings.height) {
height = fh->overlay_settings.height - y;
}
/* ignore degenerate clips */
if (height <= 0) {
continue;
}
if (width <= 0) {
continue;
}
/* apply clip for each scan line */
for (j = 0; j < height; ++j) {
/* reset bit for each pixel */
/* this can be optimized later if need be */
mask = fh->overlay_mask + (y + j) * mask_line_size;
for (k = 0; k < width; ++k) {
mask[(x + k) / 32] &=
~((u32) 1 << (x + k) % 32);
}
}
}
}
/* Enable/Disable uncompressed memory grabbing of the 36057 */
void
zr36057_set_memgrab (struct zoran *zr,
int mode)
{
if (mode) {
/* We only check SnapShot and not FrameGrab here. SnapShot==1
* means a capture is already in progress, but FrameGrab==1
* doesn't necessary mean that. It's more correct to say a 1
* to 0 transition indicates a capture completed. If a
* capture is pending when capturing is tuned off, FrameGrab
* will be stuck at 1 until capturing is turned back on.
*/
if (btread(ZR36057_VSSFGR) & ZR36057_VSSFGR_SnapShot)
dprintk(1,
KERN_WARNING
"%s: zr36057_set_memgrab(1) with SnapShot on!?\n",
ZR_DEVNAME(zr));
/* switch on VSync interrupts */
btwrite(IRQ_MASK, ZR36057_ISR); // Clear Interrupts
btor(zr->card.vsync_int, ZR36057_ICR); // SW
/* enable SnapShot */
btor(ZR36057_VSSFGR_SnapShot, ZR36057_VSSFGR);
/* Set zr36057 video front end and enable video */
zr36057_set_vfe(zr, zr->v4l_settings.width,
zr->v4l_settings.height,
zr->v4l_settings.format);
zr->v4l_memgrab_active = 1;
} else {
/* switch off VSync interrupts */
btand(~zr->card.vsync_int, ZR36057_ICR); // SW
zr->v4l_memgrab_active = 0;
zr->v4l_grab_frame = NO_GRAB_ACTIVE;
/* reenable grabbing to screen if it was running */
if (zr->v4l_overlay_active) {
zr36057_overlay(zr, 1);
} else {
btand(~ZR36057_VDCR_VidEn, ZR36057_VDCR);
btand(~ZR36057_VSSFGR_SnapShot, ZR36057_VSSFGR);
}
}
}
int
wait_grab_pending (struct zoran *zr)
{
unsigned long flags;
/* wait until all pending grabs are finished */
if (!zr->v4l_memgrab_active)
return 0;
wait_event_interruptible(zr->v4l_capq,
(zr->v4l_pend_tail == zr->v4l_pend_head));
if (signal_pending(current))
return -ERESTARTSYS;
spin_lock_irqsave(&zr->spinlock, flags);
zr36057_set_memgrab(zr, 0);
spin_unlock_irqrestore(&zr->spinlock, flags);
return 0;
}
/*****************************************************************************
* *
* Set up the Buz-specific MJPEG part *
* *
*****************************************************************************/
static inline void
set_frame (struct zoran *zr,
int val)
{
GPIO(zr, zr->card.gpio[ZR_GPIO_JPEG_FRAME], val);
}
static void
set_videobus_dir (struct zoran *zr,
int val)
{
switch (zr->card.type) {
case LML33:
case LML33R10:
if (lml33dpath == 0)
GPIO(zr, 5, val);
else
GPIO(zr, 5, 1);
break;
default:
GPIO(zr, zr->card.gpio[ZR_GPIO_VID_DIR],
zr->card.gpio_pol[ZR_GPIO_VID_DIR] ? !val : val);
break;
}
}
static void
init_jpeg_queue (struct zoran *zr)
{
int i;
/* re-initialize DMA ring stuff */
zr->jpg_que_head = 0;
zr->jpg_dma_head = 0;
zr->jpg_dma_tail = 0;
zr->jpg_que_tail = 0;
zr->jpg_seq_num = 0;
zr->JPEG_error = 0;
zr->num_errors = 0;
zr->jpg_err_seq = 0;
zr->jpg_err_shift = 0;
zr->jpg_queued_num = 0;
for (i = 0; i < zr->jpg_buffers.num_buffers; i++) {
zr->jpg_buffers.buffer[i].state = BUZ_STATE_USER; /* nothing going on */
}
for (i = 0; i < BUZ_NUM_STAT_COM; i++) {
zr->stat_com[i] = cpu_to_le32(1); /* mark as unavailable to zr36057 */
}
}
static void
zr36057_set_jpg (struct zoran *zr,
enum zoran_codec_mode mode)
{
struct tvnorm *tvn;
u32 reg;
tvn = zr->timing;
/* assert P_Reset, disable code transfer, deassert Active */
btwrite(0, ZR36057_JPC);
/* MJPEG compression mode */
switch (mode) {
case BUZ_MODE_MOTION_COMPRESS:
default:
reg = ZR36057_JMC_MJPGCmpMode;
break;
case BUZ_MODE_MOTION_DECOMPRESS:
reg = ZR36057_JMC_MJPGExpMode;
reg |= ZR36057_JMC_SyncMstr;
/* RJ: The following is experimental - improves the output to screen */
//if(zr->jpg_settings.VFIFO_FB) reg |= ZR36057_JMC_VFIFO_FB; // No, it doesn't. SM
break;
case BUZ_MODE_STILL_COMPRESS:
reg = ZR36057_JMC_JPGCmpMode;
break;
case BUZ_MODE_STILL_DECOMPRESS:
reg = ZR36057_JMC_JPGExpMode;
break;
}
reg |= ZR36057_JMC_JPG;
if (zr->jpg_settings.field_per_buff == 1)
reg |= ZR36057_JMC_Fld_per_buff;
btwrite(reg, ZR36057_JMC);
/* vertical */
btor(ZR36057_VFEVCR_VSPol, ZR36057_VFEVCR);
reg = (6 << ZR36057_VSP_VsyncSize) |
(tvn->Ht << ZR36057_VSP_FrmTot);
btwrite(reg, ZR36057_VSP);
reg = ((zr->jpg_settings.img_y + tvn->VStart) << ZR36057_FVAP_NAY) |
(zr->jpg_settings.img_height << ZR36057_FVAP_PAY);
btwrite(reg, ZR36057_FVAP);
/* horizontal */
if (zr->card.vfe_pol.hsync_pol)
btor(ZR36057_VFEHCR_HSPol, ZR36057_VFEHCR);
else
btand(~ZR36057_VFEHCR_HSPol, ZR36057_VFEHCR);
reg = ((tvn->HSyncStart) << ZR36057_HSP_HsyncStart) |
(tvn->Wt << ZR36057_HSP_LineTot);
btwrite(reg, ZR36057_HSP);
reg = ((zr->jpg_settings.img_x +
tvn->HStart + 4) << ZR36057_FHAP_NAX) |
(zr->jpg_settings.img_width << ZR36057_FHAP_PAX);
btwrite(reg, ZR36057_FHAP);
/* field process parameters */
if (zr->jpg_settings.odd_even)
reg = ZR36057_FPP_Odd_Even;
else
reg = 0;
btwrite(reg, ZR36057_FPP);
/* Set proper VCLK Polarity, else colors will be wrong during playback */
//btor(ZR36057_VFESPFR_VCLKPol, ZR36057_VFESPFR);
/* code base address */
reg = virt_to_bus(zr->stat_com);
btwrite(reg, ZR36057_JCBA);
/* FIFO threshold (FIFO is 160. double words) */
/* NOTE: decimal values here */
switch (mode) {
case BUZ_MODE_STILL_COMPRESS:
case BUZ_MODE_MOTION_COMPRESS:
if (zr->card.type != BUZ)
reg = 140;
else
reg = 60;
break;
case BUZ_MODE_STILL_DECOMPRESS:
case BUZ_MODE_MOTION_DECOMPRESS:
reg = 20;
break;
default:
reg = 80;
break;
}
btwrite(reg, ZR36057_JCFT);
zr36057_adjust_vfe(zr, mode);
}
void
print_interrupts (struct zoran *zr)
{
int res, noerr = 0;
printk(KERN_INFO "%s: interrupts received:", ZR_DEVNAME(zr));
if ((res = zr->field_counter) < -1 || res > 1) {
printk(" FD:%d", res);
}
if ((res = zr->intr_counter_GIRQ1) != 0) {
printk(" GIRQ1:%d", res);
noerr++;
}
if ((res = zr->intr_counter_GIRQ0) != 0) {
printk(" GIRQ0:%d", res);
noerr++;
}
if ((res = zr->intr_counter_CodRepIRQ) != 0) {
printk(" CodRepIRQ:%d", res);
noerr++;
}
if ((res = zr->intr_counter_JPEGRepIRQ) != 0) {
printk(" JPEGRepIRQ:%d", res);
noerr++;
}
if (zr->JPEG_max_missed) {
printk(" JPEG delays: max=%d min=%d", zr->JPEG_max_missed,
zr->JPEG_min_missed);
}
if (zr->END_event_missed) {
printk(" ENDs missed: %d", zr->END_event_missed);
}
//if (zr->jpg_queued_num) {
printk(" queue_state=%ld/%ld/%ld/%ld", zr->jpg_que_tail,
zr->jpg_dma_tail, zr->jpg_dma_head, zr->jpg_que_head);
//}
if (!noerr) {
printk(": no interrupts detected.");
}
printk("\n");
}
void
clear_interrupt_counters (struct zoran *zr)
{
zr->intr_counter_GIRQ1 = 0;
zr->intr_counter_GIRQ0 = 0;
zr->intr_counter_CodRepIRQ = 0;
zr->intr_counter_JPEGRepIRQ = 0;
zr->field_counter = 0;
zr->IRQ1_in = 0;
zr->IRQ1_out = 0;
zr->JPEG_in = 0;
zr->JPEG_out = 0;
zr->JPEG_0 = 0;
zr->JPEG_1 = 0;
zr->END_event_missed = 0;
zr->JPEG_missed = 0;
zr->JPEG_max_missed = 0;
zr->JPEG_min_missed = 0x7fffffff;
}
static u32
count_reset_interrupt (struct zoran *zr)
{
u32 isr;
if ((isr = btread(ZR36057_ISR) & 0x78000000)) {
if (isr & ZR36057_ISR_GIRQ1) {
btwrite(ZR36057_ISR_GIRQ1, ZR36057_ISR);
zr->intr_counter_GIRQ1++;
}
if (isr & ZR36057_ISR_GIRQ0) {
btwrite(ZR36057_ISR_GIRQ0, ZR36057_ISR);
zr->intr_counter_GIRQ0++;
}
if (isr & ZR36057_ISR_CodRepIRQ) {
btwrite(ZR36057_ISR_CodRepIRQ, ZR36057_ISR);
zr->intr_counter_CodRepIRQ++;
}
if (isr & ZR36057_ISR_JPEGRepIRQ) {
btwrite(ZR36057_ISR_JPEGRepIRQ, ZR36057_ISR);
zr->intr_counter_JPEGRepIRQ++;
}
}
return isr;
}
void
jpeg_start (struct zoran *zr)
{
int reg;
zr->frame_num = 0;
/* deassert P_reset, disable code transfer, deassert Active */
btwrite(ZR36057_JPC_P_Reset, ZR36057_JPC);
/* stop flushing the internal code buffer */
btand(~ZR36057_MCTCR_CFlush, ZR36057_MCTCR);
/* enable code transfer */
btor(ZR36057_JPC_CodTrnsEn, ZR36057_JPC);
/* clear IRQs */
btwrite(IRQ_MASK, ZR36057_ISR);
/* enable the JPEG IRQs */
btwrite(zr->card.jpeg_int |
ZR36057_ICR_JPEGRepIRQ |
ZR36057_ICR_IntPinEn,
ZR36057_ICR);
set_frame(zr, 0); // \FRAME
/* set the JPEG codec guest ID */
reg = (zr->card.gpcs[1] << ZR36057_JCGI_JPEGuestID) |
(0 << ZR36057_JCGI_JPEGuestReg);
btwrite(reg, ZR36057_JCGI);
if (zr->card.video_vfe == CODEC_TYPE_ZR36016 &&
zr->card.video_codec == CODEC_TYPE_ZR36050) {
/* Enable processing on the ZR36016 */
if (zr->vfe)
zr36016_write(zr->vfe, 0, 1);
/* load the address of the GO register in the ZR36050 latch */
post_office_write(zr, 0, 0, 0);
}
/* assert Active */
btor(ZR36057_JPC_Active, ZR36057_JPC);
/* enable the Go generation */
btor(ZR36057_JMC_Go_en, ZR36057_JMC);
udelay(30);
set_frame(zr, 1); // /FRAME
dprintk(3, KERN_DEBUG "%s: jpeg_start\n", ZR_DEVNAME(zr));
}
void
zr36057_enable_jpg (struct zoran *zr,
enum zoran_codec_mode mode)
{
struct vfe_settings cap;
int field_size =
zr->jpg_buffers.buffer_size / zr->jpg_settings.field_per_buff;
zr->codec_mode = mode;
cap.x = zr->jpg_settings.img_x;
cap.y = zr->jpg_settings.img_y;
cap.width = zr->jpg_settings.img_width;
cap.height = zr->jpg_settings.img_height;
cap.decimation =
zr->jpg_settings.HorDcm | (zr->jpg_settings.VerDcm << 8);
cap.quality = zr->jpg_settings.jpg_comp.quality;
switch (mode) {
case BUZ_MODE_MOTION_COMPRESS: {
struct jpeg_app_marker app;
struct jpeg_com_marker com;
/* In motion compress mode, the decoder output must be enabled, and
* the video bus direction set to input.
*/
set_videobus_dir(zr, 0);
decoder_call(zr, video, s_stream, 1);
encoder_call(zr, video, s_routing, 0, 0, 0);
/* Take the JPEG codec and the VFE out of sleep */
jpeg_codec_sleep(zr, 0);
/* set JPEG app/com marker */
app.appn = zr->jpg_settings.jpg_comp.APPn;
app.len = zr->jpg_settings.jpg_comp.APP_len;
memcpy(app.data, zr->jpg_settings.jpg_comp.APP_data, 60);
zr->codec->control(zr->codec, CODEC_S_JPEG_APP_DATA,
sizeof(struct jpeg_app_marker), &app);
com.len = zr->jpg_settings.jpg_comp.COM_len;
memcpy(com.data, zr->jpg_settings.jpg_comp.COM_data, 60);
zr->codec->control(zr->codec, CODEC_S_JPEG_COM_DATA,
sizeof(struct jpeg_com_marker), &com);
/* Setup the JPEG codec */
zr->codec->control(zr->codec, CODEC_S_JPEG_TDS_BYTE,
sizeof(int), &field_size);
zr->codec->set_video(zr->codec, zr->timing, &cap,
&zr->card.vfe_pol);
zr->codec->set_mode(zr->codec, CODEC_DO_COMPRESSION);
/* Setup the VFE */
if (zr->vfe) {
zr->vfe->control(zr->vfe, CODEC_S_JPEG_TDS_BYTE,
sizeof(int), &field_size);
zr->vfe->set_video(zr->vfe, zr->timing, &cap,
&zr->card.vfe_pol);
zr->vfe->set_mode(zr->vfe, CODEC_DO_COMPRESSION);
}
init_jpeg_queue(zr);
zr36057_set_jpg(zr, mode); // \P_Reset, ... Video param, FIFO
clear_interrupt_counters(zr);
dprintk(2, KERN_INFO "%s: enable_jpg(MOTION_COMPRESS)\n",
ZR_DEVNAME(zr));
break;
}
case BUZ_MODE_MOTION_DECOMPRESS:
/* In motion decompression mode, the decoder output must be disabled, and
* the video bus direction set to output.
*/
decoder_call(zr, video, s_stream, 0);
set_videobus_dir(zr, 1);
encoder_call(zr, video, s_routing, 1, 0, 0);
/* Take the JPEG codec and the VFE out of sleep */
jpeg_codec_sleep(zr, 0);
/* Setup the VFE */
if (zr->vfe) {
zr->vfe->set_video(zr->vfe, zr->timing, &cap,
&zr->card.vfe_pol);
zr->vfe->set_mode(zr->vfe, CODEC_DO_EXPANSION);
}
/* Setup the JPEG codec */
zr->codec->set_video(zr->codec, zr->timing, &cap,
&zr->card.vfe_pol);
zr->codec->set_mode(zr->codec, CODEC_DO_EXPANSION);
init_jpeg_queue(zr);
zr36057_set_jpg(zr, mode); // \P_Reset, ... Video param, FIFO
clear_interrupt_counters(zr);
dprintk(2, KERN_INFO "%s: enable_jpg(MOTION_DECOMPRESS)\n",
ZR_DEVNAME(zr));
break;
case BUZ_MODE_IDLE:
default:
/* shut down processing */
btand(~(zr->card.jpeg_int | ZR36057_ICR_JPEGRepIRQ),
ZR36057_ICR);
btwrite(zr->card.jpeg_int | ZR36057_ICR_JPEGRepIRQ,
ZR36057_ISR);
btand(~ZR36057_JMC_Go_en, ZR36057_JMC); // \Go_en
msleep(50);
set_videobus_dir(zr, 0);
set_frame(zr, 1); // /FRAME
btor(ZR36057_MCTCR_CFlush, ZR36057_MCTCR); // /CFlush
btwrite(0, ZR36057_JPC); // \P_Reset,\CodTrnsEn,\Active
btand(~ZR36057_JMC_VFIFO_FB, ZR36057_JMC);
btand(~ZR36057_JMC_SyncMstr, ZR36057_JMC);
jpeg_codec_reset(zr);
jpeg_codec_sleep(zr, 1);
zr36057_adjust_vfe(zr, mode);
decoder_call(zr, video, s_stream, 1);
encoder_call(zr, video, s_routing, 0, 0, 0);
dprintk(2, KERN_INFO "%s: enable_jpg(IDLE)\n", ZR_DEVNAME(zr));
break;
}
}
/* when this is called the spinlock must be held */
void
zoran_feed_stat_com (struct zoran *zr)
{
/* move frames from pending queue to DMA */
int frame, i, max_stat_com;
max_stat_com =
(zr->jpg_settings.TmpDcm ==
1) ? BUZ_NUM_STAT_COM : (BUZ_NUM_STAT_COM >> 1);
while ((zr->jpg_dma_head - zr->jpg_dma_tail) < max_stat_com &&
zr->jpg_dma_head < zr->jpg_que_head) {
frame = zr->jpg_pend[zr->jpg_dma_head & BUZ_MASK_FRAME];
if (zr->jpg_settings.TmpDcm == 1) {
/* fill 1 stat_com entry */
i = (zr->jpg_dma_head -
zr->jpg_err_shift) & BUZ_MASK_STAT_COM;
if (!(zr->stat_com[i] & cpu_to_le32(1)))
break;
zr->stat_com[i] =
cpu_to_le32(zr->jpg_buffers.buffer[frame].jpg.frag_tab_bus);
} else {
/* fill 2 stat_com entries */
i = ((zr->jpg_dma_head -
zr->jpg_err_shift) & 1) * 2;
if (!(zr->stat_com[i] & cpu_to_le32(1)))
break;
zr->stat_com[i] =
cpu_to_le32(zr->jpg_buffers.buffer[frame].jpg.frag_tab_bus);
zr->stat_com[i + 1] =
cpu_to_le32(zr->jpg_buffers.buffer[frame].jpg.frag_tab_bus);
}
zr->jpg_buffers.buffer[frame].state = BUZ_STATE_DMA;
zr->jpg_dma_head++;
}
if (zr->codec_mode == BUZ_MODE_MOTION_DECOMPRESS)
zr->jpg_queued_num++;
}
/* when this is called the spinlock must be held */
static void
zoran_reap_stat_com (struct zoran *zr)
{
/* move frames from DMA queue to done queue */
int i;
u32 stat_com;
unsigned int seq;
unsigned int dif;
struct zoran_buffer *buffer;
int frame;
/* In motion decompress we don't have a hardware frame counter,
* we just count the interrupts here */
if (zr->codec_mode == BUZ_MODE_MOTION_DECOMPRESS) {
zr->jpg_seq_num++;
}
while (zr->jpg_dma_tail < zr->jpg_dma_head) {
if (zr->jpg_settings.TmpDcm == 1)
i = (zr->jpg_dma_tail -
zr->jpg_err_shift) & BUZ_MASK_STAT_COM;
else
i = ((zr->jpg_dma_tail -
zr->jpg_err_shift) & 1) * 2 + 1;
stat_com = le32_to_cpu(zr->stat_com[i]);
if ((stat_com & 1) == 0) {
return;
}
frame = zr->jpg_pend[zr->jpg_dma_tail & BUZ_MASK_FRAME];
buffer = &zr->jpg_buffers.buffer[frame];
do_gettimeofday(&buffer->bs.timestamp);
if (zr->codec_mode == BUZ_MODE_MOTION_COMPRESS) {
buffer->bs.length = (stat_com & 0x7fffff) >> 1;
/* update sequence number with the help of the counter in stat_com */
seq = ((stat_com >> 24) + zr->jpg_err_seq) & 0xff;
dif = (seq - zr->jpg_seq_num) & 0xff;
zr->jpg_seq_num += dif;
} else {
buffer->bs.length = 0;
}
buffer->bs.seq =
zr->jpg_settings.TmpDcm ==
2 ? (zr->jpg_seq_num >> 1) : zr->jpg_seq_num;
buffer->state = BUZ_STATE_DONE;
zr->jpg_dma_tail++;
}
}
static void zoran_restart(struct zoran *zr)
{
/* Now the stat_comm buffer is ready for restart */
unsigned int status = 0;
int mode;
if (zr->codec_mode == BUZ_MODE_MOTION_COMPRESS) {
decoder_call(zr, video, g_input_status, &status);
mode = CODEC_DO_COMPRESSION;
} else {
status = V4L2_IN_ST_NO_SIGNAL;
mode = CODEC_DO_EXPANSION;
}
if (zr->codec_mode == BUZ_MODE_MOTION_DECOMPRESS ||
!(status & V4L2_IN_ST_NO_SIGNAL)) {
/********** RESTART code *************/
jpeg_codec_reset(zr);
zr->codec->set_mode(zr->codec, mode);
zr36057_set_jpg(zr, zr->codec_mode);
jpeg_start(zr);
if (zr->num_errors <= 8)
dprintk(2, KERN_INFO "%s: Restart\n",
ZR_DEVNAME(zr));
zr->JPEG_missed = 0;
zr->JPEG_error = 2;
/********** End RESTART code ***********/
}
}
static void
error_handler (struct zoran *zr,
u32 astat,
u32 stat)
{
int i;
/* This is JPEG error handling part */
if (zr->codec_mode != BUZ_MODE_MOTION_COMPRESS &&
zr->codec_mode != BUZ_MODE_MOTION_DECOMPRESS) {
return;
}
if ((stat & 1) == 0 &&
zr->codec_mode == BUZ_MODE_MOTION_COMPRESS &&
zr->jpg_dma_tail - zr->jpg_que_tail >= zr->jpg_buffers.num_buffers) {
/* No free buffers... */
zoran_reap_stat_com(zr);
zoran_feed_stat_com(zr);
wake_up_interruptible(&zr->jpg_capq);
zr->JPEG_missed = 0;
return;
}
if (zr->JPEG_error == 1) {
zoran_restart(zr);
return;
}
/*
* First entry: error just happened during normal operation
*
* In BUZ_MODE_MOTION_COMPRESS:
*
* Possible glitch in TV signal. In this case we should
* stop the codec and wait for good quality signal before
* restarting it to avoid further problems
*
* In BUZ_MODE_MOTION_DECOMPRESS:
*
* Bad JPEG frame: we have to mark it as processed (codec crashed
* and was not able to do it itself), and to remove it from queue.
*/
btand(~ZR36057_JMC_Go_en, ZR36057_JMC);
udelay(1);
stat = stat | (post_office_read(zr, 7, 0) & 3) << 8;
btwrite(0, ZR36057_JPC);
btor(ZR36057_MCTCR_CFlush, ZR36057_MCTCR);
jpeg_codec_reset(zr);
jpeg_codec_sleep(zr, 1);
zr->JPEG_error = 1;
zr->num_errors++;
/* Report error */
if (zr36067_debug > 1 && zr->num_errors <= 8) {
long frame;
int j;
frame = zr->jpg_pend[zr->jpg_dma_tail & BUZ_MASK_FRAME];
printk(KERN_ERR
"%s: JPEG error stat=0x%08x(0x%08x) queue_state=%ld/%ld/%ld/%ld seq=%ld frame=%ld. Codec stopped. ",
ZR_DEVNAME(zr), stat, zr->last_isr,
zr->jpg_que_tail, zr->jpg_dma_tail,
zr->jpg_dma_head, zr->jpg_que_head,
zr->jpg_seq_num, frame);
printk(KERN_INFO "stat_com frames:");
for (j = 0; j < BUZ_NUM_STAT_COM; j++) {
for (i = 0; i < zr->jpg_buffers.num_buffers; i++) {
if (le32_to_cpu(zr->stat_com[j]) == zr->jpg_buffers.buffer[i].jpg.frag_tab_bus)
printk(KERN_CONT "% d->%d", j, i);
}
}
printk(KERN_CONT "\n");
}
/* Find an entry in stat_com and rotate contents */
if (zr->jpg_settings.TmpDcm == 1)
i = (zr->jpg_dma_tail - zr->jpg_err_shift) & BUZ_MASK_STAT_COM;
else
i = ((zr->jpg_dma_tail - zr->jpg_err_shift) & 1) * 2;
if (zr->codec_mode == BUZ_MODE_MOTION_DECOMPRESS) {
/* Mimic zr36067 operation */
zr->stat_com[i] |= cpu_to_le32(1);
if (zr->jpg_settings.TmpDcm != 1)
zr->stat_com[i + 1] |= cpu_to_le32(1);
/* Refill */
zoran_reap_stat_com(zr);
zoran_feed_stat_com(zr);
wake_up_interruptible(&zr->jpg_capq);
/* Find an entry in stat_com again after refill */
if (zr->jpg_settings.TmpDcm == 1)
i = (zr->jpg_dma_tail - zr->jpg_err_shift) & BUZ_MASK_STAT_COM;
else
i = ((zr->jpg_dma_tail - zr->jpg_err_shift) & 1) * 2;
}
if (i) {
/* Rotate stat_comm entries to make current entry first */
int j;
__le32 bus_addr[BUZ_NUM_STAT_COM];
/* Here we are copying the stat_com array, which
* is already in little endian format, so
* no endian conversions here
*/
memcpy(bus_addr, zr->stat_com, sizeof(bus_addr));
for (j = 0; j < BUZ_NUM_STAT_COM; j++)
zr->stat_com[j] = bus_addr[(i + j) & BUZ_MASK_STAT_COM];
zr->jpg_err_shift += i;
zr->jpg_err_shift &= BUZ_MASK_STAT_COM;
}
if (zr->codec_mode == BUZ_MODE_MOTION_COMPRESS)
zr->jpg_err_seq = zr->jpg_seq_num; /* + 1; */
zoran_restart(zr);
}
irqreturn_t
zoran_irq (int irq,
void *dev_id)
{
u32 stat, astat;
int count;
struct zoran *zr;
unsigned long flags;
zr = dev_id;
count = 0;
if (zr->testing) {
/* Testing interrupts */
spin_lock_irqsave(&zr->spinlock, flags);
while ((stat = count_reset_interrupt(zr))) {
if (count++ > 100) {
btand(~ZR36057_ICR_IntPinEn, ZR36057_ICR);
dprintk(1,
KERN_ERR
"%s: IRQ lockup while testing, isr=0x%08x, cleared int mask\n",
ZR_DEVNAME(zr), stat);
wake_up_interruptible(&zr->test_q);
}
}
zr->last_isr = stat;
spin_unlock_irqrestore(&zr->spinlock, flags);
return IRQ_HANDLED;
}
spin_lock_irqsave(&zr->spinlock, flags);
while (1) {
/* get/clear interrupt status bits */
stat = count_reset_interrupt(zr);
astat = stat & IRQ_MASK;
if (!astat) {
break;
}
dprintk(4,
KERN_DEBUG
"zoran_irq: astat: 0x%08x, mask: 0x%08x\n",
astat, btread(ZR36057_ICR));
if (astat & zr->card.vsync_int) { // SW
if (zr->codec_mode == BUZ_MODE_MOTION_DECOMPRESS ||
zr->codec_mode == BUZ_MODE_MOTION_COMPRESS) {
/* count missed interrupts */
zr->JPEG_missed++;
}
//post_office_read(zr,1,0);
/* Interrupts may still happen when
* zr->v4l_memgrab_active is switched off.
* We simply ignore them */
if (zr->v4l_memgrab_active) {
/* A lot more checks should be here ... */
if ((btread(ZR36057_VSSFGR) & ZR36057_VSSFGR_SnapShot) == 0)
dprintk(1,
KERN_WARNING
"%s: BuzIRQ with SnapShot off ???\n",
ZR_DEVNAME(zr));
if (zr->v4l_grab_frame != NO_GRAB_ACTIVE) {
/* There is a grab on a frame going on, check if it has finished */
if ((btread(ZR36057_VSSFGR) & ZR36057_VSSFGR_FrameGrab) == 0) {
/* it is finished, notify the user */
zr->v4l_buffers.buffer[zr->v4l_grab_frame].state = BUZ_STATE_DONE;
zr->v4l_buffers.buffer[zr->v4l_grab_frame].bs.seq = zr->v4l_grab_seq;
do_gettimeofday(&zr->v4l_buffers.buffer[zr->v4l_grab_frame].bs.timestamp);
zr->v4l_grab_frame = NO_GRAB_ACTIVE;
zr->v4l_pend_tail++;
}
}
if (zr->v4l_grab_frame == NO_GRAB_ACTIVE)
wake_up_interruptible(&zr->v4l_capq);
/* Check if there is another grab queued */
if (zr->v4l_grab_frame == NO_GRAB_ACTIVE &&
zr->v4l_pend_tail != zr->v4l_pend_head) {
int frame = zr->v4l_pend[zr->v4l_pend_tail & V4L_MASK_FRAME];
u32 reg;
zr->v4l_grab_frame = frame;
/* Set zr36057 video front end and enable video */
/* Buffer address */
reg = zr->v4l_buffers.buffer[frame].v4l.fbuffer_bus;
btwrite(reg, ZR36057_VDTR);
if (zr->v4l_settings.height > BUZ_MAX_HEIGHT / 2)
reg += zr->v4l_settings.bytesperline;
btwrite(reg, ZR36057_VDBR);
/* video stride, status, and frame grab register */
reg = 0;
if (zr->v4l_settings.height > BUZ_MAX_HEIGHT / 2)
reg += zr->v4l_settings.bytesperline;
reg = (reg << ZR36057_VSSFGR_DispStride);
reg |= ZR36057_VSSFGR_VidOvf;
reg |= ZR36057_VSSFGR_SnapShot;
reg |= ZR36057_VSSFGR_FrameGrab;
btwrite(reg, ZR36057_VSSFGR);
btor(ZR36057_VDCR_VidEn,
ZR36057_VDCR);
}
}
/* even if we don't grab, we do want to increment
* the sequence counter to see lost frames */
zr->v4l_grab_seq++;
}
#if (IRQ_MASK & ZR36057_ISR_CodRepIRQ)
if (astat & ZR36057_ISR_CodRepIRQ) {
zr->intr_counter_CodRepIRQ++;
IDEBUG(printk(KERN_DEBUG "%s: ZR36057_ISR_CodRepIRQ\n",
ZR_DEVNAME(zr)));
btand(~ZR36057_ICR_CodRepIRQ, ZR36057_ICR);
}
#endif /* (IRQ_MASK & ZR36057_ISR_CodRepIRQ) */
#if (IRQ_MASK & ZR36057_ISR_JPEGRepIRQ)
if ((astat & ZR36057_ISR_JPEGRepIRQ) &&
(zr->codec_mode == BUZ_MODE_MOTION_DECOMPRESS ||
zr->codec_mode == BUZ_MODE_MOTION_COMPRESS)) {
if (zr36067_debug > 1 && (!zr->frame_num || zr->JPEG_error)) {
char sv[BUZ_NUM_STAT_COM + 1];
int i;
printk(KERN_INFO
"%s: first frame ready: state=0x%08x odd_even=%d field_per_buff=%d delay=%d\n",
ZR_DEVNAME(zr), stat,
zr->jpg_settings.odd_even,
zr->jpg_settings.field_per_buff,
zr->JPEG_missed);
for (i = 0; i < BUZ_NUM_STAT_COM; i++)
sv[i] = le32_to_cpu(zr->stat_com[i]) & 1 ? '1' : '0';
sv[BUZ_NUM_STAT_COM] = 0;
printk(KERN_INFO
"%s: stat_com=%s queue_state=%ld/%ld/%ld/%ld\n",
ZR_DEVNAME(zr), sv,
zr->jpg_que_tail,
zr->jpg_dma_tail,
zr->jpg_dma_head,
zr->jpg_que_head);
} else {
/* Get statistics */
if (zr->JPEG_missed > zr->JPEG_max_missed)
zr->JPEG_max_missed = zr->JPEG_missed;
if (zr->JPEG_missed < zr->JPEG_min_missed)
zr->JPEG_min_missed = zr->JPEG_missed;
}
if (zr36067_debug > 2 && zr->frame_num < 6) {
int i;
printk(KERN_INFO "%s: seq=%ld stat_com:",
ZR_DEVNAME(zr), zr->jpg_seq_num);
for (i = 0; i < 4; i++) {
printk(KERN_CONT " %08x",
le32_to_cpu(zr->stat_com[i]));
}
printk(KERN_CONT "\n");
}
zr->frame_num++;
zr->JPEG_missed = 0;
zr->JPEG_error = 0;
zoran_reap_stat_com(zr);
zoran_feed_stat_com(zr);
wake_up_interruptible(&zr->jpg_capq);
}
#endif /* (IRQ_MASK & ZR36057_ISR_JPEGRepIRQ) */
/* DATERR, too many fields missed, error processing */
if ((astat & zr->card.jpeg_int) ||
zr->JPEG_missed > 25 ||
zr->JPEG_error == 1 ||
((zr->codec_mode == BUZ_MODE_MOTION_DECOMPRESS) &&
(zr->frame_num && (zr->JPEG_missed > zr->jpg_settings.field_per_buff)))) {
error_handler(zr, astat, stat);
}
count++;
if (count > 10) {
dprintk(2, KERN_WARNING "%s: irq loop %d\n",
ZR_DEVNAME(zr), count);
if (count > 20) {
btand(~ZR36057_ICR_IntPinEn, ZR36057_ICR);
dprintk(2,
KERN_ERR
"%s: IRQ lockup, cleared int mask\n",
ZR_DEVNAME(zr));
break;
}
}
zr->last_isr = stat;
}
spin_unlock_irqrestore(&zr->spinlock, flags);
return IRQ_HANDLED;
}
void
zoran_set_pci_master (struct zoran *zr,
int set_master)
{
if (set_master) {
pci_set_master(zr->pci_dev);
} else {
u16 command;
pci_read_config_word(zr->pci_dev, PCI_COMMAND, &command);
command &= ~PCI_COMMAND_MASTER;
pci_write_config_word(zr->pci_dev, PCI_COMMAND, command);
}
}
void
zoran_init_hardware (struct zoran *zr)
{
/* Enable bus-mastering */
zoran_set_pci_master(zr, 1);
/* Initialize the board */
if (zr->card.init) {
zr->card.init(zr);
}
decoder_call(zr, core, init, 0);
decoder_call(zr, core, s_std, zr->norm);
decoder_call(zr, video, s_routing,
zr->card.input[zr->input].muxsel, 0, 0);
encoder_call(zr, core, init, 0);
encoder_call(zr, video, s_std_output, zr->norm);
encoder_call(zr, video, s_routing, 0, 0, 0);
/* toggle JPEG codec sleep to sync PLL */
jpeg_codec_sleep(zr, 1);
jpeg_codec_sleep(zr, 0);
/* set individual interrupt enables (without GIRQ1)
* but don't global enable until zoran_open() */
//btwrite(IRQ_MASK & ~ZR36057_ISR_GIRQ1, ZR36057_ICR); // SW
// It looks like using only JPEGRepIRQEn is not always reliable,
// may be when JPEG codec crashes it won't generate IRQ? So,
/*CP*/ // btwrite(IRQ_MASK, ZR36057_ICR); // Enable Vsync interrupts too. SM WHY ? LP
zr36057_init_vfe(zr);
zr36057_enable_jpg(zr, BUZ_MODE_IDLE);
btwrite(IRQ_MASK, ZR36057_ISR); // Clears interrupts
}
void
zr36057_restart (struct zoran *zr)
{
btwrite(0, ZR36057_SPGPPCR);
mdelay(1);
btor(ZR36057_SPGPPCR_SoftReset, ZR36057_SPGPPCR);
mdelay(1);
/* assert P_Reset */
btwrite(0, ZR36057_JPC);
/* set up GPIO direction - all output */
btwrite(ZR36057_SPGPPCR_SoftReset | 0, ZR36057_SPGPPCR);
/* set up GPIO pins and guest bus timing */
btwrite((0x81 << 24) | 0x8888, ZR36057_GPPGCR1);
}
/*
* initialize video front end
*/
static void
zr36057_init_vfe (struct zoran *zr)
{
u32 reg;
reg = btread(ZR36057_VFESPFR);
reg |= ZR36057_VFESPFR_LittleEndian;
reg &= ~ZR36057_VFESPFR_VCLKPol;
reg |= ZR36057_VFESPFR_ExtFl;
reg |= ZR36057_VFESPFR_TopField;
btwrite(reg, ZR36057_VFESPFR);
reg = btread(ZR36057_VDCR);
if (pci_pci_problems & PCIPCI_TRITON)
// || zr->revision < 1) // Revision 1 has also Triton support
reg &= ~ZR36057_VDCR_Triton;
else
reg |= ZR36057_VDCR_Triton;
btwrite(reg, ZR36057_VDCR);
}
| gpl-2.0 |
flar2/ElementalX-evita-8.0 | drivers/platform/x86/wmi.c | 5172 | 23589 | /*
* ACPI-WMI mapping driver
*
* Copyright (C) 2007-2008 Carlos Corbacho <carlos@strangeworlds.co.uk>
*
* GUID parsing code from ldm.c is:
* Copyright (C) 2001,2002 Richard Russon <ldm@flatcap.org>
* Copyright (c) 2001-2007 Anton Altaparmakov
* Copyright (C) 2001,2002 Jakob Kemi <jakob.kemi@telia.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.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/device.h>
#include <linux/list.h>
#include <linux/acpi.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <acpi/acpi_bus.h>
#include <acpi/acpi_drivers.h>
ACPI_MODULE_NAME("wmi");
MODULE_AUTHOR("Carlos Corbacho");
MODULE_DESCRIPTION("ACPI-WMI Mapping Driver");
MODULE_LICENSE("GPL");
#define ACPI_WMI_CLASS "wmi"
static DEFINE_MUTEX(wmi_data_lock);
static LIST_HEAD(wmi_block_list);
struct guid_block {
char guid[16];
union {
char object_id[2];
struct {
unsigned char notify_id;
unsigned char reserved;
};
};
u8 instance_count;
u8 flags;
};
struct wmi_block {
struct list_head list;
struct guid_block gblock;
acpi_handle handle;
wmi_notify_handler handler;
void *handler_data;
struct device dev;
};
/*
* If the GUID data block is marked as expensive, we must enable and
* explicitily disable data collection.
*/
#define ACPI_WMI_EXPENSIVE 0x1
#define ACPI_WMI_METHOD 0x2 /* GUID is a method */
#define ACPI_WMI_STRING 0x4 /* GUID takes & returns a string */
#define ACPI_WMI_EVENT 0x8 /* GUID is an event */
static bool debug_event;
module_param(debug_event, bool, 0444);
MODULE_PARM_DESC(debug_event,
"Log WMI Events [0/1]");
static bool debug_dump_wdg;
module_param(debug_dump_wdg, bool, 0444);
MODULE_PARM_DESC(debug_dump_wdg,
"Dump available WMI interfaces [0/1]");
static int acpi_wmi_remove(struct acpi_device *device, int type);
static int acpi_wmi_add(struct acpi_device *device);
static void acpi_wmi_notify(struct acpi_device *device, u32 event);
static const struct acpi_device_id wmi_device_ids[] = {
{"PNP0C14", 0},
{"pnp0c14", 0},
{"", 0},
};
MODULE_DEVICE_TABLE(acpi, wmi_device_ids);
static struct acpi_driver acpi_wmi_driver = {
.name = "wmi",
.class = ACPI_WMI_CLASS,
.ids = wmi_device_ids,
.ops = {
.add = acpi_wmi_add,
.remove = acpi_wmi_remove,
.notify = acpi_wmi_notify,
},
};
/*
* GUID parsing functions
*/
/**
* wmi_parse_hexbyte - Convert a ASCII hex number to a byte
* @src: Pointer to at least 2 characters to convert.
*
* Convert a two character ASCII hex string to a number.
*
* Return: 0-255 Success, the byte was parsed correctly
* -1 Error, an invalid character was supplied
*/
static int wmi_parse_hexbyte(const u8 *src)
{
int h;
int value;
/* high part */
h = value = hex_to_bin(src[0]);
if (value < 0)
return -1;
/* low part */
value = hex_to_bin(src[1]);
if (value >= 0)
return (h << 4) | value;
return -1;
}
/**
* wmi_swap_bytes - Rearrange GUID bytes to match GUID binary
* @src: Memory block holding binary GUID (16 bytes)
* @dest: Memory block to hold byte swapped binary GUID (16 bytes)
*
* Byte swap a binary GUID to match it's real GUID value
*/
static void wmi_swap_bytes(u8 *src, u8 *dest)
{
int i;
for (i = 0; i <= 3; i++)
memcpy(dest + i, src + (3 - i), 1);
for (i = 0; i <= 1; i++)
memcpy(dest + 4 + i, src + (5 - i), 1);
for (i = 0; i <= 1; i++)
memcpy(dest + 6 + i, src + (7 - i), 1);
memcpy(dest + 8, src + 8, 8);
}
/**
* wmi_parse_guid - Convert GUID from ASCII to binary
* @src: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba
* @dest: Memory block to hold binary GUID (16 bytes)
*
* N.B. The GUID need not be NULL terminated.
*
* Return: 'true' @dest contains binary GUID
* 'false' @dest contents are undefined
*/
static bool wmi_parse_guid(const u8 *src, u8 *dest)
{
static const int size[] = { 4, 2, 2, 2, 6 };
int i, j, v;
if (src[8] != '-' || src[13] != '-' ||
src[18] != '-' || src[23] != '-')
return false;
for (j = 0; j < 5; j++, src++) {
for (i = 0; i < size[j]; i++, src += 2, *dest++ = v) {
v = wmi_parse_hexbyte(src);
if (v < 0)
return false;
}
}
return true;
}
/*
* Convert a raw GUID to the ACII string representation
*/
static int wmi_gtoa(const char *in, char *out)
{
int i;
for (i = 3; i >= 0; i--)
out += sprintf(out, "%02X", in[i] & 0xFF);
out += sprintf(out, "-");
out += sprintf(out, "%02X", in[5] & 0xFF);
out += sprintf(out, "%02X", in[4] & 0xFF);
out += sprintf(out, "-");
out += sprintf(out, "%02X", in[7] & 0xFF);
out += sprintf(out, "%02X", in[6] & 0xFF);
out += sprintf(out, "-");
out += sprintf(out, "%02X", in[8] & 0xFF);
out += sprintf(out, "%02X", in[9] & 0xFF);
out += sprintf(out, "-");
for (i = 10; i <= 15; i++)
out += sprintf(out, "%02X", in[i] & 0xFF);
*out = '\0';
return 0;
}
static bool find_guid(const char *guid_string, struct wmi_block **out)
{
char tmp[16], guid_input[16];
struct wmi_block *wblock;
struct guid_block *block;
struct list_head *p;
wmi_parse_guid(guid_string, tmp);
wmi_swap_bytes(tmp, guid_input);
list_for_each(p, &wmi_block_list) {
wblock = list_entry(p, struct wmi_block, list);
block = &wblock->gblock;
if (memcmp(block->guid, guid_input, 16) == 0) {
if (out)
*out = wblock;
return 1;
}
}
return 0;
}
static acpi_status wmi_method_enable(struct wmi_block *wblock, int enable)
{
struct guid_block *block = NULL;
char method[5];
struct acpi_object_list input;
union acpi_object params[1];
acpi_status status;
acpi_handle handle;
block = &wblock->gblock;
handle = wblock->handle;
if (!block)
return AE_NOT_EXIST;
input.count = 1;
input.pointer = params;
params[0].type = ACPI_TYPE_INTEGER;
params[0].integer.value = enable;
snprintf(method, 5, "WE%02X", block->notify_id);
status = acpi_evaluate_object(handle, method, &input, NULL);
if (status != AE_OK && status != AE_NOT_FOUND)
return status;
else
return AE_OK;
}
/*
* Exported WMI functions
*/
/**
* wmi_evaluate_method - Evaluate a WMI method
* @guid_string: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba
* @instance: Instance index
* @method_id: Method ID to call
* &in: Buffer containing input for the method call
* &out: Empty buffer to return the method results
*
* Call an ACPI-WMI method
*/
acpi_status wmi_evaluate_method(const char *guid_string, u8 instance,
u32 method_id, const struct acpi_buffer *in, struct acpi_buffer *out)
{
struct guid_block *block = NULL;
struct wmi_block *wblock = NULL;
acpi_handle handle;
acpi_status status;
struct acpi_object_list input;
union acpi_object params[3];
char method[5] = "WM";
if (!find_guid(guid_string, &wblock))
return AE_ERROR;
block = &wblock->gblock;
handle = wblock->handle;
if (!(block->flags & ACPI_WMI_METHOD))
return AE_BAD_DATA;
if (block->instance_count < instance)
return AE_BAD_PARAMETER;
input.count = 2;
input.pointer = params;
params[0].type = ACPI_TYPE_INTEGER;
params[0].integer.value = instance;
params[1].type = ACPI_TYPE_INTEGER;
params[1].integer.value = method_id;
if (in) {
input.count = 3;
if (block->flags & ACPI_WMI_STRING) {
params[2].type = ACPI_TYPE_STRING;
} else {
params[2].type = ACPI_TYPE_BUFFER;
}
params[2].buffer.length = in->length;
params[2].buffer.pointer = in->pointer;
}
strncat(method, block->object_id, 2);
status = acpi_evaluate_object(handle, method, &input, out);
return status;
}
EXPORT_SYMBOL_GPL(wmi_evaluate_method);
/**
* wmi_query_block - Return contents of a WMI block
* @guid_string: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba
* @instance: Instance index
* &out: Empty buffer to return the contents of the data block to
*
* Return the contents of an ACPI-WMI data block to a buffer
*/
acpi_status wmi_query_block(const char *guid_string, u8 instance,
struct acpi_buffer *out)
{
struct guid_block *block = NULL;
struct wmi_block *wblock = NULL;
acpi_handle handle, wc_handle;
acpi_status status, wc_status = AE_ERROR;
struct acpi_object_list input, wc_input;
union acpi_object wc_params[1], wq_params[1];
char method[5];
char wc_method[5] = "WC";
if (!guid_string || !out)
return AE_BAD_PARAMETER;
if (!find_guid(guid_string, &wblock))
return AE_ERROR;
block = &wblock->gblock;
handle = wblock->handle;
if (block->instance_count < instance)
return AE_BAD_PARAMETER;
/* Check GUID is a data block */
if (block->flags & (ACPI_WMI_EVENT | ACPI_WMI_METHOD))
return AE_ERROR;
input.count = 1;
input.pointer = wq_params;
wq_params[0].type = ACPI_TYPE_INTEGER;
wq_params[0].integer.value = instance;
/*
* If ACPI_WMI_EXPENSIVE, call the relevant WCxx method first to
* enable collection.
*/
if (block->flags & ACPI_WMI_EXPENSIVE) {
wc_input.count = 1;
wc_input.pointer = wc_params;
wc_params[0].type = ACPI_TYPE_INTEGER;
wc_params[0].integer.value = 1;
strncat(wc_method, block->object_id, 2);
/*
* Some GUIDs break the specification by declaring themselves
* expensive, but have no corresponding WCxx method. So we
* should not fail if this happens.
*/
wc_status = acpi_get_handle(handle, wc_method, &wc_handle);
if (ACPI_SUCCESS(wc_status))
wc_status = acpi_evaluate_object(handle, wc_method,
&wc_input, NULL);
}
strcpy(method, "WQ");
strncat(method, block->object_id, 2);
status = acpi_evaluate_object(handle, method, &input, out);
/*
* If ACPI_WMI_EXPENSIVE, call the relevant WCxx method, even if
* the WQxx method failed - we should disable collection anyway.
*/
if ((block->flags & ACPI_WMI_EXPENSIVE) && ACPI_SUCCESS(wc_status)) {
wc_params[0].integer.value = 0;
status = acpi_evaluate_object(handle,
wc_method, &wc_input, NULL);
}
return status;
}
EXPORT_SYMBOL_GPL(wmi_query_block);
/**
* wmi_set_block - Write to a WMI block
* @guid_string: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba
* @instance: Instance index
* &in: Buffer containing new values for the data block
*
* Write the contents of the input buffer to an ACPI-WMI data block
*/
acpi_status wmi_set_block(const char *guid_string, u8 instance,
const struct acpi_buffer *in)
{
struct guid_block *block = NULL;
struct wmi_block *wblock = NULL;
acpi_handle handle;
struct acpi_object_list input;
union acpi_object params[2];
char method[5] = "WS";
if (!guid_string || !in)
return AE_BAD_DATA;
if (!find_guid(guid_string, &wblock))
return AE_ERROR;
block = &wblock->gblock;
handle = wblock->handle;
if (block->instance_count < instance)
return AE_BAD_PARAMETER;
/* Check GUID is a data block */
if (block->flags & (ACPI_WMI_EVENT | ACPI_WMI_METHOD))
return AE_ERROR;
input.count = 2;
input.pointer = params;
params[0].type = ACPI_TYPE_INTEGER;
params[0].integer.value = instance;
if (block->flags & ACPI_WMI_STRING) {
params[1].type = ACPI_TYPE_STRING;
} else {
params[1].type = ACPI_TYPE_BUFFER;
}
params[1].buffer.length = in->length;
params[1].buffer.pointer = in->pointer;
strncat(method, block->object_id, 2);
return acpi_evaluate_object(handle, method, &input, NULL);
}
EXPORT_SYMBOL_GPL(wmi_set_block);
static void wmi_dump_wdg(const struct guid_block *g)
{
char guid_string[37];
wmi_gtoa(g->guid, guid_string);
pr_info("%s:\n", guid_string);
pr_info("\tobject_id: %c%c\n", g->object_id[0], g->object_id[1]);
pr_info("\tnotify_id: %02X\n", g->notify_id);
pr_info("\treserved: %02X\n", g->reserved);
pr_info("\tinstance_count: %d\n", g->instance_count);
pr_info("\tflags: %#x", g->flags);
if (g->flags) {
if (g->flags & ACPI_WMI_EXPENSIVE)
pr_cont(" ACPI_WMI_EXPENSIVE");
if (g->flags & ACPI_WMI_METHOD)
pr_cont(" ACPI_WMI_METHOD");
if (g->flags & ACPI_WMI_STRING)
pr_cont(" ACPI_WMI_STRING");
if (g->flags & ACPI_WMI_EVENT)
pr_cont(" ACPI_WMI_EVENT");
}
pr_cont("\n");
}
static void wmi_notify_debug(u32 value, void *context)
{
struct acpi_buffer response = { ACPI_ALLOCATE_BUFFER, NULL };
union acpi_object *obj;
acpi_status status;
status = wmi_get_event_data(value, &response);
if (status != AE_OK) {
pr_info("bad event status 0x%x\n", status);
return;
}
obj = (union acpi_object *)response.pointer;
if (!obj)
return;
pr_info("DEBUG Event ");
switch(obj->type) {
case ACPI_TYPE_BUFFER:
pr_cont("BUFFER_TYPE - length %d\n", obj->buffer.length);
break;
case ACPI_TYPE_STRING:
pr_cont("STRING_TYPE - %s\n", obj->string.pointer);
break;
case ACPI_TYPE_INTEGER:
pr_cont("INTEGER_TYPE - %llu\n", obj->integer.value);
break;
case ACPI_TYPE_PACKAGE:
pr_cont("PACKAGE_TYPE - %d elements\n", obj->package.count);
break;
default:
pr_cont("object type 0x%X\n", obj->type);
}
kfree(obj);
}
/**
* wmi_install_notify_handler - Register handler for WMI events
* @handler: Function to handle notifications
* @data: Data to be returned to handler when event is fired
*
* Register a handler for events sent to the ACPI-WMI mapper device.
*/
acpi_status wmi_install_notify_handler(const char *guid,
wmi_notify_handler handler, void *data)
{
struct wmi_block *block;
acpi_status status = AE_NOT_EXIST;
char tmp[16], guid_input[16];
struct list_head *p;
if (!guid || !handler)
return AE_BAD_PARAMETER;
wmi_parse_guid(guid, tmp);
wmi_swap_bytes(tmp, guid_input);
list_for_each(p, &wmi_block_list) {
acpi_status wmi_status;
block = list_entry(p, struct wmi_block, list);
if (memcmp(block->gblock.guid, guid_input, 16) == 0) {
if (block->handler &&
block->handler != wmi_notify_debug)
return AE_ALREADY_ACQUIRED;
block->handler = handler;
block->handler_data = data;
wmi_status = wmi_method_enable(block, 1);
if ((wmi_status != AE_OK) ||
((wmi_status == AE_OK) && (status == AE_NOT_EXIST)))
status = wmi_status;
}
}
return status;
}
EXPORT_SYMBOL_GPL(wmi_install_notify_handler);
/**
* wmi_uninstall_notify_handler - Unregister handler for WMI events
*
* Unregister handler for events sent to the ACPI-WMI mapper device.
*/
acpi_status wmi_remove_notify_handler(const char *guid)
{
struct wmi_block *block;
acpi_status status = AE_NOT_EXIST;
char tmp[16], guid_input[16];
struct list_head *p;
if (!guid)
return AE_BAD_PARAMETER;
wmi_parse_guid(guid, tmp);
wmi_swap_bytes(tmp, guid_input);
list_for_each(p, &wmi_block_list) {
acpi_status wmi_status;
block = list_entry(p, struct wmi_block, list);
if (memcmp(block->gblock.guid, guid_input, 16) == 0) {
if (!block->handler ||
block->handler == wmi_notify_debug)
return AE_NULL_ENTRY;
if (debug_event) {
block->handler = wmi_notify_debug;
status = AE_OK;
} else {
wmi_status = wmi_method_enable(block, 0);
block->handler = NULL;
block->handler_data = NULL;
if ((wmi_status != AE_OK) ||
((wmi_status == AE_OK) &&
(status == AE_NOT_EXIST)))
status = wmi_status;
}
}
}
return status;
}
EXPORT_SYMBOL_GPL(wmi_remove_notify_handler);
/**
* wmi_get_event_data - Get WMI data associated with an event
*
* @event: Event to find
* @out: Buffer to hold event data. out->pointer should be freed with kfree()
*
* Returns extra data associated with an event in WMI.
*/
acpi_status wmi_get_event_data(u32 event, struct acpi_buffer *out)
{
struct acpi_object_list input;
union acpi_object params[1];
struct guid_block *gblock;
struct wmi_block *wblock;
struct list_head *p;
input.count = 1;
input.pointer = params;
params[0].type = ACPI_TYPE_INTEGER;
params[0].integer.value = event;
list_for_each(p, &wmi_block_list) {
wblock = list_entry(p, struct wmi_block, list);
gblock = &wblock->gblock;
if ((gblock->flags & ACPI_WMI_EVENT) &&
(gblock->notify_id == event))
return acpi_evaluate_object(wblock->handle, "_WED",
&input, out);
}
return AE_NOT_FOUND;
}
EXPORT_SYMBOL_GPL(wmi_get_event_data);
/**
* wmi_has_guid - Check if a GUID is available
* @guid_string: 36 char string of the form fa50ff2b-f2e8-45de-83fa-65417f2f49ba
*
* Check if a given GUID is defined by _WDG
*/
bool wmi_has_guid(const char *guid_string)
{
return find_guid(guid_string, NULL);
}
EXPORT_SYMBOL_GPL(wmi_has_guid);
/*
* sysfs interface
*/
static ssize_t modalias_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
char guid_string[37];
struct wmi_block *wblock;
wblock = dev_get_drvdata(dev);
if (!wblock)
return -ENOMEM;
wmi_gtoa(wblock->gblock.guid, guid_string);
return sprintf(buf, "wmi:%s\n", guid_string);
}
static struct device_attribute wmi_dev_attrs[] = {
__ATTR_RO(modalias),
__ATTR_NULL
};
static int wmi_dev_uevent(struct device *dev, struct kobj_uevent_env *env)
{
char guid_string[37];
struct wmi_block *wblock;
if (add_uevent_var(env, "MODALIAS="))
return -ENOMEM;
wblock = dev_get_drvdata(dev);
if (!wblock)
return -ENOMEM;
wmi_gtoa(wblock->gblock.guid, guid_string);
strcpy(&env->buf[env->buflen - 1], "wmi:");
memcpy(&env->buf[env->buflen - 1 + 4], guid_string, 36);
env->buflen += 40;
return 0;
}
static void wmi_dev_free(struct device *dev)
{
struct wmi_block *wmi_block = container_of(dev, struct wmi_block, dev);
kfree(wmi_block);
}
static struct class wmi_class = {
.name = "wmi",
.dev_release = wmi_dev_free,
.dev_uevent = wmi_dev_uevent,
.dev_attrs = wmi_dev_attrs,
};
static int wmi_create_device(const struct guid_block *gblock,
struct wmi_block *wblock, acpi_handle handle)
{
char guid_string[37];
wblock->dev.class = &wmi_class;
wmi_gtoa(gblock->guid, guid_string);
dev_set_name(&wblock->dev, guid_string);
dev_set_drvdata(&wblock->dev, wblock);
return device_register(&wblock->dev);
}
static void wmi_free_devices(void)
{
struct wmi_block *wblock, *next;
/* Delete devices for all the GUIDs */
list_for_each_entry_safe(wblock, next, &wmi_block_list, list) {
list_del(&wblock->list);
if (wblock->dev.class)
device_unregister(&wblock->dev);
else
kfree(wblock);
}
}
static bool guid_already_parsed(const char *guid_string)
{
struct wmi_block *wblock;
list_for_each_entry(wblock, &wmi_block_list, list)
if (memcmp(wblock->gblock.guid, guid_string, 16) == 0)
return true;
return false;
}
/*
* Parse the _WDG method for the GUID data blocks
*/
static acpi_status parse_wdg(acpi_handle handle)
{
struct acpi_buffer out = {ACPI_ALLOCATE_BUFFER, NULL};
union acpi_object *obj;
const struct guid_block *gblock;
struct wmi_block *wblock;
acpi_status status;
int retval;
u32 i, total;
status = acpi_evaluate_object(handle, "_WDG", NULL, &out);
if (ACPI_FAILURE(status))
return -ENXIO;
obj = (union acpi_object *) out.pointer;
if (!obj)
return -ENXIO;
if (obj->type != ACPI_TYPE_BUFFER) {
retval = -ENXIO;
goto out_free_pointer;
}
gblock = (const struct guid_block *)obj->buffer.pointer;
total = obj->buffer.length / sizeof(struct guid_block);
for (i = 0; i < total; i++) {
if (debug_dump_wdg)
wmi_dump_wdg(&gblock[i]);
wblock = kzalloc(sizeof(struct wmi_block), GFP_KERNEL);
if (!wblock)
return AE_NO_MEMORY;
wblock->handle = handle;
wblock->gblock = gblock[i];
/*
Some WMI devices, like those for nVidia hooks, have a
duplicate GUID. It's not clear what we should do in this
case yet, so for now, we'll just ignore the duplicate
for device creation.
*/
if (!guid_already_parsed(gblock[i].guid)) {
retval = wmi_create_device(&gblock[i], wblock, handle);
if (retval) {
wmi_free_devices();
goto out_free_pointer;
}
}
list_add_tail(&wblock->list, &wmi_block_list);
if (debug_event) {
wblock->handler = wmi_notify_debug;
wmi_method_enable(wblock, 1);
}
}
retval = 0;
out_free_pointer:
kfree(out.pointer);
return retval;
}
/*
* WMI can have EmbeddedControl access regions. In which case, we just want to
* hand these off to the EC driver.
*/
static acpi_status
acpi_wmi_ec_space_handler(u32 function, acpi_physical_address address,
u32 bits, u64 *value,
void *handler_context, void *region_context)
{
int result = 0, i = 0;
u8 temp = 0;
if ((address > 0xFF) || !value)
return AE_BAD_PARAMETER;
if (function != ACPI_READ && function != ACPI_WRITE)
return AE_BAD_PARAMETER;
if (bits != 8)
return AE_BAD_PARAMETER;
if (function == ACPI_READ) {
result = ec_read(address, &temp);
(*value) |= ((u64)temp) << i;
} else {
temp = 0xff & ((*value) >> i);
result = ec_write(address, temp);
}
switch (result) {
case -EINVAL:
return AE_BAD_PARAMETER;
break;
case -ENODEV:
return AE_NOT_FOUND;
break;
case -ETIME:
return AE_TIME;
break;
default:
return AE_OK;
}
}
static void acpi_wmi_notify(struct acpi_device *device, u32 event)
{
struct guid_block *block;
struct wmi_block *wblock;
struct list_head *p;
char guid_string[37];
list_for_each(p, &wmi_block_list) {
wblock = list_entry(p, struct wmi_block, list);
block = &wblock->gblock;
if ((block->flags & ACPI_WMI_EVENT) &&
(block->notify_id == event)) {
if (wblock->handler)
wblock->handler(event, wblock->handler_data);
if (debug_event) {
wmi_gtoa(wblock->gblock.guid, guid_string);
pr_info("DEBUG Event GUID: %s\n", guid_string);
}
acpi_bus_generate_netlink_event(
device->pnp.device_class, dev_name(&device->dev),
event, 0);
break;
}
}
}
static int acpi_wmi_remove(struct acpi_device *device, int type)
{
acpi_remove_address_space_handler(device->handle,
ACPI_ADR_SPACE_EC, &acpi_wmi_ec_space_handler);
wmi_free_devices();
return 0;
}
static int acpi_wmi_add(struct acpi_device *device)
{
acpi_status status;
int error;
status = acpi_install_address_space_handler(device->handle,
ACPI_ADR_SPACE_EC,
&acpi_wmi_ec_space_handler,
NULL, NULL);
if (ACPI_FAILURE(status)) {
pr_err("Error installing EC region handler\n");
return -ENODEV;
}
error = parse_wdg(device->handle);
if (error) {
acpi_remove_address_space_handler(device->handle,
ACPI_ADR_SPACE_EC,
&acpi_wmi_ec_space_handler);
pr_err("Failed to parse WDG method\n");
return error;
}
return 0;
}
static int __init acpi_wmi_init(void)
{
int error;
if (acpi_disabled)
return -ENODEV;
error = class_register(&wmi_class);
if (error)
return error;
error = acpi_bus_register_driver(&acpi_wmi_driver);
if (error) {
pr_err("Error loading mapper\n");
class_unregister(&wmi_class);
return error;
}
pr_info("Mapper loaded\n");
return 0;
}
static void __exit acpi_wmi_exit(void)
{
acpi_bus_unregister_driver(&acpi_wmi_driver);
class_unregister(&wmi_class);
pr_info("Mapper unloaded\n");
}
subsys_initcall(acpi_wmi_init);
module_exit(acpi_wmi_exit);
| gpl-2.0 |
NinjahMeh/android_kernel_huawei_angler | security/apparmor/procattr.c | 7476 | 4770 | /*
* AppArmor security module
*
* This file contains AppArmor /proc/<pid>/attr/ interface functions
*
* Copyright (C) 1998-2008 Novell/SUSE
* Copyright 2009-2010 Canonical Ltd.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 2 of the
* License.
*/
#include "include/apparmor.h"
#include "include/context.h"
#include "include/policy.h"
#include "include/domain.h"
#include "include/procattr.h"
/**
* aa_getprocattr - Return the profile information for @profile
* @profile: the profile to print profile info about (NOT NULL)
* @string: Returns - string containing the profile info (NOT NULL)
*
* Returns: length of @string on success else error on failure
*
* Requires: profile != NULL
*
* Creates a string containing the namespace_name://profile_name for
* @profile.
*
* Returns: size of string placed in @string else error code on failure
*/
int aa_getprocattr(struct aa_profile *profile, char **string)
{
char *str;
int len = 0, mode_len = 0, ns_len = 0, name_len;
const char *mode_str = profile_mode_names[profile->mode];
const char *ns_name = NULL;
struct aa_namespace *ns = profile->ns;
struct aa_namespace *current_ns = __aa_current_profile()->ns;
char *s;
if (!aa_ns_visible(current_ns, ns))
return -EACCES;
ns_name = aa_ns_name(current_ns, ns);
ns_len = strlen(ns_name);
/* if the visible ns_name is > 0 increase size for : :// seperator */
if (ns_len)
ns_len += 4;
/* unconfined profiles don't have a mode string appended */
if (!unconfined(profile))
mode_len = strlen(mode_str) + 3; /* + 3 for _() */
name_len = strlen(profile->base.hname);
len = mode_len + ns_len + name_len + 1; /* + 1 for \n */
s = str = kmalloc(len + 1, GFP_KERNEL); /* + 1 \0 */
if (!str)
return -ENOMEM;
if (ns_len) {
/* skip over prefix current_ns->base.hname and separating // */
sprintf(s, ":%s://", ns_name);
s += ns_len;
}
if (unconfined(profile))
/* mode string not being appended */
sprintf(s, "%s\n", profile->base.hname);
else
sprintf(s, "%s (%s)\n", profile->base.hname, mode_str);
*string = str;
/* NOTE: len does not include \0 of string, not saved as part of file */
return len;
}
/**
* split_token_from_name - separate a string of form <token>^<name>
* @op: operation being checked
* @args: string to parse (NOT NULL)
* @token: stores returned parsed token value (NOT NULL)
*
* Returns: start position of name after token else NULL on failure
*/
static char *split_token_from_name(int op, char *args, u64 * token)
{
char *name;
*token = simple_strtoull(args, &name, 16);
if ((name == args) || *name != '^') {
AA_ERROR("%s: Invalid input '%s'", op_table[op], args);
return ERR_PTR(-EINVAL);
}
name++; /* skip ^ */
if (!*name)
name = NULL;
return name;
}
/**
* aa_setprocattr_chagnehat - handle procattr interface to change_hat
* @args: args received from writing to /proc/<pid>/attr/current (NOT NULL)
* @size: size of the args
* @test: true if this is a test of change_hat permissions
*
* Returns: %0 or error code if change_hat fails
*/
int aa_setprocattr_changehat(char *args, size_t size, int test)
{
char *hat;
u64 token;
const char *hats[16]; /* current hard limit on # of names */
int count = 0;
hat = split_token_from_name(OP_CHANGE_HAT, args, &token);
if (IS_ERR(hat))
return PTR_ERR(hat);
if (!hat && !token) {
AA_ERROR("change_hat: Invalid input, NULL hat and NULL magic");
return -EINVAL;
}
if (hat) {
/* set up hat name vector, args guaranteed null terminated
* at args[size] by setprocattr.
*
* If there are multiple hat names in the buffer each is
* separated by a \0. Ie. userspace writes them pre tokenized
*/
char *end = args + size;
for (count = 0; (hat < end) && count < 16; ++count) {
char *next = hat + strlen(hat) + 1;
hats[count] = hat;
hat = next;
}
}
AA_DEBUG("%s: Magic 0x%llx Hat '%s'\n",
__func__, token, hat ? hat : NULL);
return aa_change_hat(hats, count, token, test);
}
/**
* aa_setprocattr_changeprofile - handle procattr interface to changeprofile
* @fqname: args received from writting to /proc/<pid>/attr/current (NOT NULL)
* @onexec: true if change_profile should be delayed until exec
* @test: true if this is a test of change_profile permissions
*
* Returns: %0 or error code if change_profile fails
*/
int aa_setprocattr_changeprofile(char *fqname, bool onexec, int test)
{
char *name, *ns_name;
name = aa_split_fqname(fqname, &ns_name);
return aa_change_profile(ns_name, name, onexec, test);
}
int aa_setprocattr_permipc(char *fqname)
{
/* TODO: add ipc permission querying */
return -ENOTSUPP;
}
| gpl-2.0 |
A2109devs/lenovo_a2109a_kernel | net/activity_stats.c | 7988 | 2833 | /* net/activity_stats.c
*
* Copyright (C) 2010 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.
*
* Author: Mike Chan (mike@android.com)
*/
#include <linux/proc_fs.h>
#include <linux/suspend.h>
#include <net/net_namespace.h>
/*
* Track transmission rates in buckets (power of 2).
* 1,2,4,8...512 seconds.
*
* Buckets represent the count of network transmissions at least
* N seconds apart, where N is 1 << bucket index.
*/
#define BUCKET_MAX 10
/* Track network activity frequency */
static unsigned long activity_stats[BUCKET_MAX];
static ktime_t last_transmit;
static ktime_t suspend_time;
static DEFINE_SPINLOCK(activity_lock);
void activity_stats_update(void)
{
int i;
unsigned long flags;
ktime_t now;
s64 delta;
spin_lock_irqsave(&activity_lock, flags);
now = ktime_get();
delta = ktime_to_ns(ktime_sub(now, last_transmit));
for (i = BUCKET_MAX - 1; i >= 0; i--) {
/*
* Check if the time delta between network activity is within the
* minimum bucket range.
*/
if (delta < (1000000000ULL << i))
continue;
activity_stats[i]++;
last_transmit = now;
break;
}
spin_unlock_irqrestore(&activity_lock, flags);
}
static int activity_stats_read_proc(char *page, char **start, off_t off,
int count, int *eof, void *data)
{
int i;
int len;
char *p = page;
/* Only print if offset is 0, or we have enough buffer space */
if (off || count < (30 * BUCKET_MAX + 22))
return -ENOMEM;
len = snprintf(p, count, "Min Bucket(sec) Count\n");
count -= len;
p += len;
for (i = 0; i < BUCKET_MAX; i++) {
len = snprintf(p, count, "%15d %lu\n", 1 << i, activity_stats[i]);
count -= len;
p += len;
}
*eof = 1;
return p - page;
}
static int activity_stats_notifier(struct notifier_block *nb,
unsigned long event, void *dummy)
{
switch (event) {
case PM_SUSPEND_PREPARE:
suspend_time = ktime_get_real();
break;
case PM_POST_SUSPEND:
suspend_time = ktime_sub(ktime_get_real(), suspend_time);
last_transmit = ktime_sub(last_transmit, suspend_time);
}
return 0;
}
static struct notifier_block activity_stats_notifier_block = {
.notifier_call = activity_stats_notifier,
};
static int __init activity_stats_init(void)
{
create_proc_read_entry("activity", S_IRUGO,
init_net.proc_net_stat, activity_stats_read_proc, NULL);
return register_pm_notifier(&activity_stats_notifier_block);
}
subsys_initcall(activity_stats_init);
| gpl-2.0 |
SomethingExplosive/android_kernel_samsung_tuna | drivers/md/dm-zero.c | 8500 | 1586 | /*
* Copyright (C) 2003 Christophe Saout <christophe@saout.de>
*
* This file is released under the GPL.
*/
#include <linux/device-mapper.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/bio.h>
#define DM_MSG_PREFIX "zero"
/*
* Construct a dummy mapping that only returns zeros
*/
static int zero_ctr(struct dm_target *ti, unsigned int argc, char **argv)
{
if (argc != 0) {
ti->error = "No arguments required";
return -EINVAL;
}
/*
* Silently drop discards, avoiding -EOPNOTSUPP.
*/
ti->num_discard_requests = 1;
return 0;
}
/*
* Return zeros only on reads
*/
static int zero_map(struct dm_target *ti, struct bio *bio,
union map_info *map_context)
{
switch(bio_rw(bio)) {
case READ:
zero_fill_bio(bio);
break;
case READA:
/* readahead of null bytes only wastes buffer cache */
return -EIO;
case WRITE:
/* writes get silently dropped */
break;
}
bio_endio(bio, 0);
/* accepted bio, don't make new request */
return DM_MAPIO_SUBMITTED;
}
static struct target_type zero_target = {
.name = "zero",
.version = {1, 0, 0},
.module = THIS_MODULE,
.ctr = zero_ctr,
.map = zero_map,
};
static int __init dm_zero_init(void)
{
int r = dm_register_target(&zero_target);
if (r < 0)
DMERR("register failed %d", r);
return r;
}
static void __exit dm_zero_exit(void)
{
dm_unregister_target(&zero_target);
}
module_init(dm_zero_init)
module_exit(dm_zero_exit)
MODULE_AUTHOR("Christophe Saout <christophe@saout.de>");
MODULE_DESCRIPTION(DM_NAME " dummy target returning zeros");
MODULE_LICENSE("GPL");
| gpl-2.0 |
genopublic/kernel_u8800 | crypto/tea.c | 10036 | 7253 | /*
* Cryptographic API.
*
* TEA, XTEA, and XETA crypto alogrithms
*
* The TEA and Xtended TEA algorithms were developed by David Wheeler
* and Roger Needham at the Computer Laboratory of Cambridge University.
*
* Due to the order of evaluation in XTEA many people have incorrectly
* implemented it. XETA (XTEA in the wrong order), exists for
* compatibility with these implementations.
*
* Copyright (c) 2004 Aaron Grothe ajgrothe@yahoo.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/mm.h>
#include <asm/byteorder.h>
#include <linux/crypto.h>
#include <linux/types.h>
#define TEA_KEY_SIZE 16
#define TEA_BLOCK_SIZE 8
#define TEA_ROUNDS 32
#define TEA_DELTA 0x9e3779b9
#define XTEA_KEY_SIZE 16
#define XTEA_BLOCK_SIZE 8
#define XTEA_ROUNDS 32
#define XTEA_DELTA 0x9e3779b9
struct tea_ctx {
u32 KEY[4];
};
struct xtea_ctx {
u32 KEY[4];
};
static int tea_setkey(struct crypto_tfm *tfm, const u8 *in_key,
unsigned int key_len)
{
struct tea_ctx *ctx = crypto_tfm_ctx(tfm);
const __le32 *key = (const __le32 *)in_key;
ctx->KEY[0] = le32_to_cpu(key[0]);
ctx->KEY[1] = le32_to_cpu(key[1]);
ctx->KEY[2] = le32_to_cpu(key[2]);
ctx->KEY[3] = le32_to_cpu(key[3]);
return 0;
}
static void tea_encrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
u32 y, z, n, sum = 0;
u32 k0, k1, k2, k3;
struct tea_ctx *ctx = crypto_tfm_ctx(tfm);
const __le32 *in = (const __le32 *)src;
__le32 *out = (__le32 *)dst;
y = le32_to_cpu(in[0]);
z = le32_to_cpu(in[1]);
k0 = ctx->KEY[0];
k1 = ctx->KEY[1];
k2 = ctx->KEY[2];
k3 = ctx->KEY[3];
n = TEA_ROUNDS;
while (n-- > 0) {
sum += TEA_DELTA;
y += ((z << 4) + k0) ^ (z + sum) ^ ((z >> 5) + k1);
z += ((y << 4) + k2) ^ (y + sum) ^ ((y >> 5) + k3);
}
out[0] = cpu_to_le32(y);
out[1] = cpu_to_le32(z);
}
static void tea_decrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
u32 y, z, n, sum;
u32 k0, k1, k2, k3;
struct tea_ctx *ctx = crypto_tfm_ctx(tfm);
const __le32 *in = (const __le32 *)src;
__le32 *out = (__le32 *)dst;
y = le32_to_cpu(in[0]);
z = le32_to_cpu(in[1]);
k0 = ctx->KEY[0];
k1 = ctx->KEY[1];
k2 = ctx->KEY[2];
k3 = ctx->KEY[3];
sum = TEA_DELTA << 5;
n = TEA_ROUNDS;
while (n-- > 0) {
z -= ((y << 4) + k2) ^ (y + sum) ^ ((y >> 5) + k3);
y -= ((z << 4) + k0) ^ (z + sum) ^ ((z >> 5) + k1);
sum -= TEA_DELTA;
}
out[0] = cpu_to_le32(y);
out[1] = cpu_to_le32(z);
}
static int xtea_setkey(struct crypto_tfm *tfm, const u8 *in_key,
unsigned int key_len)
{
struct xtea_ctx *ctx = crypto_tfm_ctx(tfm);
const __le32 *key = (const __le32 *)in_key;
ctx->KEY[0] = le32_to_cpu(key[0]);
ctx->KEY[1] = le32_to_cpu(key[1]);
ctx->KEY[2] = le32_to_cpu(key[2]);
ctx->KEY[3] = le32_to_cpu(key[3]);
return 0;
}
static void xtea_encrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
u32 y, z, sum = 0;
u32 limit = XTEA_DELTA * XTEA_ROUNDS;
struct xtea_ctx *ctx = crypto_tfm_ctx(tfm);
const __le32 *in = (const __le32 *)src;
__le32 *out = (__le32 *)dst;
y = le32_to_cpu(in[0]);
z = le32_to_cpu(in[1]);
while (sum != limit) {
y += ((z << 4 ^ z >> 5) + z) ^ (sum + ctx->KEY[sum&3]);
sum += XTEA_DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + ctx->KEY[sum>>11 &3]);
}
out[0] = cpu_to_le32(y);
out[1] = cpu_to_le32(z);
}
static void xtea_decrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
u32 y, z, sum;
struct tea_ctx *ctx = crypto_tfm_ctx(tfm);
const __le32 *in = (const __le32 *)src;
__le32 *out = (__le32 *)dst;
y = le32_to_cpu(in[0]);
z = le32_to_cpu(in[1]);
sum = XTEA_DELTA * XTEA_ROUNDS;
while (sum) {
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + ctx->KEY[sum>>11 & 3]);
sum -= XTEA_DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + ctx->KEY[sum & 3]);
}
out[0] = cpu_to_le32(y);
out[1] = cpu_to_le32(z);
}
static void xeta_encrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
u32 y, z, sum = 0;
u32 limit = XTEA_DELTA * XTEA_ROUNDS;
struct xtea_ctx *ctx = crypto_tfm_ctx(tfm);
const __le32 *in = (const __le32 *)src;
__le32 *out = (__le32 *)dst;
y = le32_to_cpu(in[0]);
z = le32_to_cpu(in[1]);
while (sum != limit) {
y += (z << 4 ^ z >> 5) + (z ^ sum) + ctx->KEY[sum&3];
sum += XTEA_DELTA;
z += (y << 4 ^ y >> 5) + (y ^ sum) + ctx->KEY[sum>>11 &3];
}
out[0] = cpu_to_le32(y);
out[1] = cpu_to_le32(z);
}
static void xeta_decrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
u32 y, z, sum;
struct tea_ctx *ctx = crypto_tfm_ctx(tfm);
const __le32 *in = (const __le32 *)src;
__le32 *out = (__le32 *)dst;
y = le32_to_cpu(in[0]);
z = le32_to_cpu(in[1]);
sum = XTEA_DELTA * XTEA_ROUNDS;
while (sum) {
z -= (y << 4 ^ y >> 5) + (y ^ sum) + ctx->KEY[sum>>11 & 3];
sum -= XTEA_DELTA;
y -= (z << 4 ^ z >> 5) + (z ^ sum) + ctx->KEY[sum & 3];
}
out[0] = cpu_to_le32(y);
out[1] = cpu_to_le32(z);
}
static struct crypto_alg tea_alg = {
.cra_name = "tea",
.cra_flags = CRYPTO_ALG_TYPE_CIPHER,
.cra_blocksize = TEA_BLOCK_SIZE,
.cra_ctxsize = sizeof (struct tea_ctx),
.cra_alignmask = 3,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(tea_alg.cra_list),
.cra_u = { .cipher = {
.cia_min_keysize = TEA_KEY_SIZE,
.cia_max_keysize = TEA_KEY_SIZE,
.cia_setkey = tea_setkey,
.cia_encrypt = tea_encrypt,
.cia_decrypt = tea_decrypt } }
};
static struct crypto_alg xtea_alg = {
.cra_name = "xtea",
.cra_flags = CRYPTO_ALG_TYPE_CIPHER,
.cra_blocksize = XTEA_BLOCK_SIZE,
.cra_ctxsize = sizeof (struct xtea_ctx),
.cra_alignmask = 3,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(xtea_alg.cra_list),
.cra_u = { .cipher = {
.cia_min_keysize = XTEA_KEY_SIZE,
.cia_max_keysize = XTEA_KEY_SIZE,
.cia_setkey = xtea_setkey,
.cia_encrypt = xtea_encrypt,
.cia_decrypt = xtea_decrypt } }
};
static struct crypto_alg xeta_alg = {
.cra_name = "xeta",
.cra_flags = CRYPTO_ALG_TYPE_CIPHER,
.cra_blocksize = XTEA_BLOCK_SIZE,
.cra_ctxsize = sizeof (struct xtea_ctx),
.cra_alignmask = 3,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(xtea_alg.cra_list),
.cra_u = { .cipher = {
.cia_min_keysize = XTEA_KEY_SIZE,
.cia_max_keysize = XTEA_KEY_SIZE,
.cia_setkey = xtea_setkey,
.cia_encrypt = xeta_encrypt,
.cia_decrypt = xeta_decrypt } }
};
static int __init tea_mod_init(void)
{
int ret = 0;
ret = crypto_register_alg(&tea_alg);
if (ret < 0)
goto out;
ret = crypto_register_alg(&xtea_alg);
if (ret < 0) {
crypto_unregister_alg(&tea_alg);
goto out;
}
ret = crypto_register_alg(&xeta_alg);
if (ret < 0) {
crypto_unregister_alg(&tea_alg);
crypto_unregister_alg(&xtea_alg);
goto out;
}
out:
return ret;
}
static void __exit tea_mod_fini(void)
{
crypto_unregister_alg(&tea_alg);
crypto_unregister_alg(&xtea_alg);
crypto_unregister_alg(&xeta_alg);
}
MODULE_ALIAS("xtea");
MODULE_ALIAS("xeta");
module_init(tea_mod_init);
module_exit(tea_mod_fini);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("TEA, XTEA & XETA Cryptographic Algorithms");
| gpl-2.0 |
fkfk/linux_gt-i9000-gb | drivers/infiniband/hw/qib/qib_mmap.c | 12596 | 4883 | /*
* Copyright (c) 2006, 2007, 2008, 2009 QLogic Corporation. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/mm.h>
#include <linux/errno.h>
#include <asm/pgtable.h>
#include "qib_verbs.h"
/**
* qib_release_mmap_info - free mmap info structure
* @ref: a pointer to the kref within struct qib_mmap_info
*/
void qib_release_mmap_info(struct kref *ref)
{
struct qib_mmap_info *ip =
container_of(ref, struct qib_mmap_info, ref);
struct qib_ibdev *dev = to_idev(ip->context->device);
spin_lock_irq(&dev->pending_lock);
list_del(&ip->pending_mmaps);
spin_unlock_irq(&dev->pending_lock);
vfree(ip->obj);
kfree(ip);
}
/*
* open and close keep track of how many times the CQ is mapped,
* to avoid releasing it.
*/
static void qib_vma_open(struct vm_area_struct *vma)
{
struct qib_mmap_info *ip = vma->vm_private_data;
kref_get(&ip->ref);
}
static void qib_vma_close(struct vm_area_struct *vma)
{
struct qib_mmap_info *ip = vma->vm_private_data;
kref_put(&ip->ref, qib_release_mmap_info);
}
static struct vm_operations_struct qib_vm_ops = {
.open = qib_vma_open,
.close = qib_vma_close,
};
/**
* qib_mmap - create a new mmap region
* @context: the IB user context of the process making the mmap() call
* @vma: the VMA to be initialized
* Return zero if the mmap is OK. Otherwise, return an errno.
*/
int qib_mmap(struct ib_ucontext *context, struct vm_area_struct *vma)
{
struct qib_ibdev *dev = to_idev(context->device);
unsigned long offset = vma->vm_pgoff << PAGE_SHIFT;
unsigned long size = vma->vm_end - vma->vm_start;
struct qib_mmap_info *ip, *pp;
int ret = -EINVAL;
/*
* Search the device's list of objects waiting for a mmap call.
* Normally, this list is very short since a call to create a
* CQ, QP, or SRQ is soon followed by a call to mmap().
*/
spin_lock_irq(&dev->pending_lock);
list_for_each_entry_safe(ip, pp, &dev->pending_mmaps,
pending_mmaps) {
/* Only the creator is allowed to mmap the object */
if (context != ip->context || (__u64) offset != ip->offset)
continue;
/* Don't allow a mmap larger than the object. */
if (size > ip->size)
break;
list_del_init(&ip->pending_mmaps);
spin_unlock_irq(&dev->pending_lock);
ret = remap_vmalloc_range(vma, ip->obj, 0);
if (ret)
goto done;
vma->vm_ops = &qib_vm_ops;
vma->vm_private_data = ip;
qib_vma_open(vma);
goto done;
}
spin_unlock_irq(&dev->pending_lock);
done:
return ret;
}
/*
* Allocate information for qib_mmap
*/
struct qib_mmap_info *qib_create_mmap_info(struct qib_ibdev *dev,
u32 size,
struct ib_ucontext *context,
void *obj) {
struct qib_mmap_info *ip;
ip = kmalloc(sizeof *ip, GFP_KERNEL);
if (!ip)
goto bail;
size = PAGE_ALIGN(size);
spin_lock_irq(&dev->mmap_offset_lock);
if (dev->mmap_offset == 0)
dev->mmap_offset = PAGE_SIZE;
ip->offset = dev->mmap_offset;
dev->mmap_offset += size;
spin_unlock_irq(&dev->mmap_offset_lock);
INIT_LIST_HEAD(&ip->pending_mmaps);
ip->size = size;
ip->context = context;
ip->obj = obj;
kref_init(&ip->ref);
bail:
return ip;
}
void qib_update_mmap_info(struct qib_ibdev *dev, struct qib_mmap_info *ip,
u32 size, void *obj)
{
size = PAGE_ALIGN(size);
spin_lock_irq(&dev->mmap_offset_lock);
if (dev->mmap_offset == 0)
dev->mmap_offset = PAGE_SIZE;
ip->offset = dev->mmap_offset;
dev->mmap_offset += size;
spin_unlock_irq(&dev->mmap_offset_lock);
ip->size = size;
ip->obj = obj;
}
| gpl-2.0 |
abcdjdj/maximus | drivers/infiniband/hw/qib/qib_mmap.c | 12596 | 4883 | /*
* Copyright (c) 2006, 2007, 2008, 2009 QLogic Corporation. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/mm.h>
#include <linux/errno.h>
#include <asm/pgtable.h>
#include "qib_verbs.h"
/**
* qib_release_mmap_info - free mmap info structure
* @ref: a pointer to the kref within struct qib_mmap_info
*/
void qib_release_mmap_info(struct kref *ref)
{
struct qib_mmap_info *ip =
container_of(ref, struct qib_mmap_info, ref);
struct qib_ibdev *dev = to_idev(ip->context->device);
spin_lock_irq(&dev->pending_lock);
list_del(&ip->pending_mmaps);
spin_unlock_irq(&dev->pending_lock);
vfree(ip->obj);
kfree(ip);
}
/*
* open and close keep track of how many times the CQ is mapped,
* to avoid releasing it.
*/
static void qib_vma_open(struct vm_area_struct *vma)
{
struct qib_mmap_info *ip = vma->vm_private_data;
kref_get(&ip->ref);
}
static void qib_vma_close(struct vm_area_struct *vma)
{
struct qib_mmap_info *ip = vma->vm_private_data;
kref_put(&ip->ref, qib_release_mmap_info);
}
static struct vm_operations_struct qib_vm_ops = {
.open = qib_vma_open,
.close = qib_vma_close,
};
/**
* qib_mmap - create a new mmap region
* @context: the IB user context of the process making the mmap() call
* @vma: the VMA to be initialized
* Return zero if the mmap is OK. Otherwise, return an errno.
*/
int qib_mmap(struct ib_ucontext *context, struct vm_area_struct *vma)
{
struct qib_ibdev *dev = to_idev(context->device);
unsigned long offset = vma->vm_pgoff << PAGE_SHIFT;
unsigned long size = vma->vm_end - vma->vm_start;
struct qib_mmap_info *ip, *pp;
int ret = -EINVAL;
/*
* Search the device's list of objects waiting for a mmap call.
* Normally, this list is very short since a call to create a
* CQ, QP, or SRQ is soon followed by a call to mmap().
*/
spin_lock_irq(&dev->pending_lock);
list_for_each_entry_safe(ip, pp, &dev->pending_mmaps,
pending_mmaps) {
/* Only the creator is allowed to mmap the object */
if (context != ip->context || (__u64) offset != ip->offset)
continue;
/* Don't allow a mmap larger than the object. */
if (size > ip->size)
break;
list_del_init(&ip->pending_mmaps);
spin_unlock_irq(&dev->pending_lock);
ret = remap_vmalloc_range(vma, ip->obj, 0);
if (ret)
goto done;
vma->vm_ops = &qib_vm_ops;
vma->vm_private_data = ip;
qib_vma_open(vma);
goto done;
}
spin_unlock_irq(&dev->pending_lock);
done:
return ret;
}
/*
* Allocate information for qib_mmap
*/
struct qib_mmap_info *qib_create_mmap_info(struct qib_ibdev *dev,
u32 size,
struct ib_ucontext *context,
void *obj) {
struct qib_mmap_info *ip;
ip = kmalloc(sizeof *ip, GFP_KERNEL);
if (!ip)
goto bail;
size = PAGE_ALIGN(size);
spin_lock_irq(&dev->mmap_offset_lock);
if (dev->mmap_offset == 0)
dev->mmap_offset = PAGE_SIZE;
ip->offset = dev->mmap_offset;
dev->mmap_offset += size;
spin_unlock_irq(&dev->mmap_offset_lock);
INIT_LIST_HEAD(&ip->pending_mmaps);
ip->size = size;
ip->context = context;
ip->obj = obj;
kref_init(&ip->ref);
bail:
return ip;
}
void qib_update_mmap_info(struct qib_ibdev *dev, struct qib_mmap_info *ip,
u32 size, void *obj)
{
size = PAGE_ALIGN(size);
spin_lock_irq(&dev->mmap_offset_lock);
if (dev->mmap_offset == 0)
dev->mmap_offset = PAGE_SIZE;
ip->offset = dev->mmap_offset;
dev->mmap_offset += size;
spin_unlock_irq(&dev->mmap_offset_lock);
ip->size = size;
ip->obj = obj;
}
| gpl-2.0 |
hoonir/iamroot_hypstudy_5th | drivers/net/wireless/ath/ath9k/init.c | 53 | 27478 | /*
* Copyright (c) 2008-2011 Atheros Communications Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <linux/ath9k_platform.h>
#include <linux/module.h>
#include <linux/relay.h>
#include "ath9k.h"
struct ath9k_eeprom_ctx {
struct completion complete;
struct ath_hw *ah;
};
static char *dev_info = "ath9k";
MODULE_AUTHOR("Atheros Communications");
MODULE_DESCRIPTION("Support for Atheros 802.11n wireless LAN cards.");
MODULE_SUPPORTED_DEVICE("Atheros 802.11n WLAN cards");
MODULE_LICENSE("Dual BSD/GPL");
static unsigned int ath9k_debug = ATH_DBG_DEFAULT;
module_param_named(debug, ath9k_debug, uint, 0);
MODULE_PARM_DESC(debug, "Debugging mask");
int ath9k_modparam_nohwcrypt;
module_param_named(nohwcrypt, ath9k_modparam_nohwcrypt, int, 0444);
MODULE_PARM_DESC(nohwcrypt, "Disable hardware encryption");
int led_blink;
module_param_named(blink, led_blink, int, 0444);
MODULE_PARM_DESC(blink, "Enable LED blink on activity");
static int ath9k_btcoex_enable;
module_param_named(btcoex_enable, ath9k_btcoex_enable, int, 0444);
MODULE_PARM_DESC(btcoex_enable, "Enable wifi-BT coexistence");
static int ath9k_enable_diversity;
module_param_named(enable_diversity, ath9k_enable_diversity, int, 0444);
MODULE_PARM_DESC(enable_diversity, "Enable Antenna diversity for AR9565");
bool is_ath9k_unloaded;
/* We use the hw_value as an index into our private channel structure */
#define CHAN2G(_freq, _idx) { \
.band = IEEE80211_BAND_2GHZ, \
.center_freq = (_freq), \
.hw_value = (_idx), \
.max_power = 20, \
}
#define CHAN5G(_freq, _idx) { \
.band = IEEE80211_BAND_5GHZ, \
.center_freq = (_freq), \
.hw_value = (_idx), \
.max_power = 20, \
}
/* Some 2 GHz radios are actually tunable on 2312-2732
* on 5 MHz steps, we support the channels which we know
* we have calibration data for all cards though to make
* this static */
static const struct ieee80211_channel ath9k_2ghz_chantable[] = {
CHAN2G(2412, 0), /* Channel 1 */
CHAN2G(2417, 1), /* Channel 2 */
CHAN2G(2422, 2), /* Channel 3 */
CHAN2G(2427, 3), /* Channel 4 */
CHAN2G(2432, 4), /* Channel 5 */
CHAN2G(2437, 5), /* Channel 6 */
CHAN2G(2442, 6), /* Channel 7 */
CHAN2G(2447, 7), /* Channel 8 */
CHAN2G(2452, 8), /* Channel 9 */
CHAN2G(2457, 9), /* Channel 10 */
CHAN2G(2462, 10), /* Channel 11 */
CHAN2G(2467, 11), /* Channel 12 */
CHAN2G(2472, 12), /* Channel 13 */
CHAN2G(2484, 13), /* Channel 14 */
};
/* Some 5 GHz radios are actually tunable on XXXX-YYYY
* on 5 MHz steps, we support the channels which we know
* we have calibration data for all cards though to make
* this static */
static const struct ieee80211_channel ath9k_5ghz_chantable[] = {
/* _We_ call this UNII 1 */
CHAN5G(5180, 14), /* Channel 36 */
CHAN5G(5200, 15), /* Channel 40 */
CHAN5G(5220, 16), /* Channel 44 */
CHAN5G(5240, 17), /* Channel 48 */
/* _We_ call this UNII 2 */
CHAN5G(5260, 18), /* Channel 52 */
CHAN5G(5280, 19), /* Channel 56 */
CHAN5G(5300, 20), /* Channel 60 */
CHAN5G(5320, 21), /* Channel 64 */
/* _We_ call this "Middle band" */
CHAN5G(5500, 22), /* Channel 100 */
CHAN5G(5520, 23), /* Channel 104 */
CHAN5G(5540, 24), /* Channel 108 */
CHAN5G(5560, 25), /* Channel 112 */
CHAN5G(5580, 26), /* Channel 116 */
CHAN5G(5600, 27), /* Channel 120 */
CHAN5G(5620, 28), /* Channel 124 */
CHAN5G(5640, 29), /* Channel 128 */
CHAN5G(5660, 30), /* Channel 132 */
CHAN5G(5680, 31), /* Channel 136 */
CHAN5G(5700, 32), /* Channel 140 */
/* _We_ call this UNII 3 */
CHAN5G(5745, 33), /* Channel 149 */
CHAN5G(5765, 34), /* Channel 153 */
CHAN5G(5785, 35), /* Channel 157 */
CHAN5G(5805, 36), /* Channel 161 */
CHAN5G(5825, 37), /* Channel 165 */
};
/* Atheros hardware rate code addition for short premble */
#define SHPCHECK(__hw_rate, __flags) \
((__flags & IEEE80211_RATE_SHORT_PREAMBLE) ? (__hw_rate | 0x04 ) : 0)
#define RATE(_bitrate, _hw_rate, _flags) { \
.bitrate = (_bitrate), \
.flags = (_flags), \
.hw_value = (_hw_rate), \
.hw_value_short = (SHPCHECK(_hw_rate, _flags)) \
}
static struct ieee80211_rate ath9k_legacy_rates[] = {
RATE(10, 0x1b, 0),
RATE(20, 0x1a, IEEE80211_RATE_SHORT_PREAMBLE),
RATE(55, 0x19, IEEE80211_RATE_SHORT_PREAMBLE),
RATE(110, 0x18, IEEE80211_RATE_SHORT_PREAMBLE),
RATE(60, 0x0b, 0),
RATE(90, 0x0f, 0),
RATE(120, 0x0a, 0),
RATE(180, 0x0e, 0),
RATE(240, 0x09, 0),
RATE(360, 0x0d, 0),
RATE(480, 0x08, 0),
RATE(540, 0x0c, 0),
};
#ifdef CONFIG_MAC80211_LEDS
static const struct ieee80211_tpt_blink ath9k_tpt_blink[] = {
{ .throughput = 0 * 1024, .blink_time = 334 },
{ .throughput = 1 * 1024, .blink_time = 260 },
{ .throughput = 5 * 1024, .blink_time = 220 },
{ .throughput = 10 * 1024, .blink_time = 190 },
{ .throughput = 20 * 1024, .blink_time = 170 },
{ .throughput = 50 * 1024, .blink_time = 150 },
{ .throughput = 70 * 1024, .blink_time = 130 },
{ .throughput = 100 * 1024, .blink_time = 110 },
{ .throughput = 200 * 1024, .blink_time = 80 },
{ .throughput = 300 * 1024, .blink_time = 50 },
};
#endif
static void ath9k_deinit_softc(struct ath_softc *sc);
/*
* Read and write, they both share the same lock. We do this to serialize
* reads and writes on Atheros 802.11n PCI devices only. This is required
* as the FIFO on these devices can only accept sanely 2 requests.
*/
static void ath9k_iowrite32(void *hw_priv, u32 val, u32 reg_offset)
{
struct ath_hw *ah = (struct ath_hw *) hw_priv;
struct ath_common *common = ath9k_hw_common(ah);
struct ath_softc *sc = (struct ath_softc *) common->priv;
if (NR_CPUS > 1 && ah->config.serialize_regmode == SER_REG_MODE_ON) {
unsigned long flags;
spin_lock_irqsave(&sc->sc_serial_rw, flags);
iowrite32(val, sc->mem + reg_offset);
spin_unlock_irqrestore(&sc->sc_serial_rw, flags);
} else
iowrite32(val, sc->mem + reg_offset);
}
static unsigned int ath9k_ioread32(void *hw_priv, u32 reg_offset)
{
struct ath_hw *ah = (struct ath_hw *) hw_priv;
struct ath_common *common = ath9k_hw_common(ah);
struct ath_softc *sc = (struct ath_softc *) common->priv;
u32 val;
if (NR_CPUS > 1 && ah->config.serialize_regmode == SER_REG_MODE_ON) {
unsigned long flags;
spin_lock_irqsave(&sc->sc_serial_rw, flags);
val = ioread32(sc->mem + reg_offset);
spin_unlock_irqrestore(&sc->sc_serial_rw, flags);
} else
val = ioread32(sc->mem + reg_offset);
return val;
}
static unsigned int __ath9k_reg_rmw(struct ath_softc *sc, u32 reg_offset,
u32 set, u32 clr)
{
u32 val;
val = ioread32(sc->mem + reg_offset);
val &= ~clr;
val |= set;
iowrite32(val, sc->mem + reg_offset);
return val;
}
static unsigned int ath9k_reg_rmw(void *hw_priv, u32 reg_offset, u32 set, u32 clr)
{
struct ath_hw *ah = (struct ath_hw *) hw_priv;
struct ath_common *common = ath9k_hw_common(ah);
struct ath_softc *sc = (struct ath_softc *) common->priv;
unsigned long uninitialized_var(flags);
u32 val;
if (NR_CPUS > 1 && ah->config.serialize_regmode == SER_REG_MODE_ON) {
spin_lock_irqsave(&sc->sc_serial_rw, flags);
val = __ath9k_reg_rmw(sc, reg_offset, set, clr);
spin_unlock_irqrestore(&sc->sc_serial_rw, flags);
} else
val = __ath9k_reg_rmw(sc, reg_offset, set, clr);
return val;
}
/**************************/
/* Initialization */
/**************************/
static void setup_ht_cap(struct ath_softc *sc,
struct ieee80211_sta_ht_cap *ht_info)
{
struct ath_hw *ah = sc->sc_ah;
struct ath_common *common = ath9k_hw_common(ah);
u8 tx_streams, rx_streams;
int i, max_streams;
ht_info->ht_supported = true;
ht_info->cap = IEEE80211_HT_CAP_SUP_WIDTH_20_40 |
IEEE80211_HT_CAP_SM_PS |
IEEE80211_HT_CAP_SGI_40 |
IEEE80211_HT_CAP_DSSSCCK40;
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_LDPC)
ht_info->cap |= IEEE80211_HT_CAP_LDPC_CODING;
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_SGI_20)
ht_info->cap |= IEEE80211_HT_CAP_SGI_20;
ht_info->ampdu_factor = IEEE80211_HT_MAX_AMPDU_64K;
ht_info->ampdu_density = IEEE80211_HT_MPDU_DENSITY_8;
if (AR_SREV_9330(ah) || AR_SREV_9485(ah) || AR_SREV_9565(ah))
max_streams = 1;
else if (AR_SREV_9462(ah))
max_streams = 2;
else if (AR_SREV_9300_20_OR_LATER(ah))
max_streams = 3;
else
max_streams = 2;
if (AR_SREV_9280_20_OR_LATER(ah)) {
if (max_streams >= 2)
ht_info->cap |= IEEE80211_HT_CAP_TX_STBC;
ht_info->cap |= (1 << IEEE80211_HT_CAP_RX_STBC_SHIFT);
}
/* set up supported mcs set */
memset(&ht_info->mcs, 0, sizeof(ht_info->mcs));
tx_streams = ath9k_cmn_count_streams(ah->txchainmask, max_streams);
rx_streams = ath9k_cmn_count_streams(ah->rxchainmask, max_streams);
ath_dbg(common, CONFIG, "TX streams %d, RX streams: %d\n",
tx_streams, rx_streams);
if (tx_streams != rx_streams) {
ht_info->mcs.tx_params |= IEEE80211_HT_MCS_TX_RX_DIFF;
ht_info->mcs.tx_params |= ((tx_streams - 1) <<
IEEE80211_HT_MCS_TX_MAX_STREAMS_SHIFT);
}
for (i = 0; i < rx_streams; i++)
ht_info->mcs.rx_mask[i] = 0xff;
ht_info->mcs.tx_params |= IEEE80211_HT_MCS_TX_DEFINED;
}
static void ath9k_reg_notifier(struct wiphy *wiphy,
struct regulatory_request *request)
{
struct ieee80211_hw *hw = wiphy_to_ieee80211_hw(wiphy);
struct ath_softc *sc = hw->priv;
struct ath_hw *ah = sc->sc_ah;
struct ath_regulatory *reg = ath9k_hw_regulatory(ah);
ath_reg_notifier_apply(wiphy, request, reg);
/* Set tx power */
if (ah->curchan) {
sc->config.txpowlimit = 2 * ah->curchan->chan->max_power;
ath9k_ps_wakeup(sc);
ath9k_hw_set_txpowerlimit(ah, sc->config.txpowlimit, false);
sc->curtxpow = ath9k_hw_regulatory(ah)->power_limit;
ath9k_ps_restore(sc);
}
}
/*
* This function will allocate both the DMA descriptor structure, and the
* buffers it contains. These are used to contain the descriptors used
* by the system.
*/
int ath_descdma_setup(struct ath_softc *sc, struct ath_descdma *dd,
struct list_head *head, const char *name,
int nbuf, int ndesc, bool is_tx)
{
struct ath_common *common = ath9k_hw_common(sc->sc_ah);
u8 *ds;
struct ath_buf *bf;
int i, bsize, desc_len;
ath_dbg(common, CONFIG, "%s DMA: %u buffers %u desc/buf\n",
name, nbuf, ndesc);
INIT_LIST_HEAD(head);
if (is_tx)
desc_len = sc->sc_ah->caps.tx_desc_len;
else
desc_len = sizeof(struct ath_desc);
/* ath_desc must be a multiple of DWORDs */
if ((desc_len % 4) != 0) {
ath_err(common, "ath_desc not DWORD aligned\n");
BUG_ON((desc_len % 4) != 0);
return -ENOMEM;
}
dd->dd_desc_len = desc_len * nbuf * ndesc;
/*
* Need additional DMA memory because we can't use
* descriptors that cross the 4K page boundary. Assume
* one skipped descriptor per 4K page.
*/
if (!(sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_4KB_SPLITTRANS)) {
u32 ndesc_skipped =
ATH_DESC_4KB_BOUND_NUM_SKIPPED(dd->dd_desc_len);
u32 dma_len;
while (ndesc_skipped) {
dma_len = ndesc_skipped * desc_len;
dd->dd_desc_len += dma_len;
ndesc_skipped = ATH_DESC_4KB_BOUND_NUM_SKIPPED(dma_len);
}
}
/* allocate descriptors */
dd->dd_desc = dmam_alloc_coherent(sc->dev, dd->dd_desc_len,
&dd->dd_desc_paddr, GFP_KERNEL);
if (!dd->dd_desc)
return -ENOMEM;
ds = (u8 *) dd->dd_desc;
ath_dbg(common, CONFIG, "%s DMA map: %p (%u) -> %llx (%u)\n",
name, ds, (u32) dd->dd_desc_len,
ito64(dd->dd_desc_paddr), /*XXX*/(u32) dd->dd_desc_len);
/* allocate buffers */
bsize = sizeof(struct ath_buf) * nbuf;
bf = devm_kzalloc(sc->dev, bsize, GFP_KERNEL);
if (!bf)
return -ENOMEM;
for (i = 0; i < nbuf; i++, bf++, ds += (desc_len * ndesc)) {
bf->bf_desc = ds;
bf->bf_daddr = DS2PHYS(dd, ds);
if (!(sc->sc_ah->caps.hw_caps &
ATH9K_HW_CAP_4KB_SPLITTRANS)) {
/*
* Skip descriptor addresses which can cause 4KB
* boundary crossing (addr + length) with a 32 dword
* descriptor fetch.
*/
while (ATH_DESC_4KB_BOUND_CHECK(bf->bf_daddr)) {
BUG_ON((caddr_t) bf->bf_desc >=
((caddr_t) dd->dd_desc +
dd->dd_desc_len));
ds += (desc_len * ndesc);
bf->bf_desc = ds;
bf->bf_daddr = DS2PHYS(dd, ds);
}
}
list_add_tail(&bf->list, head);
}
return 0;
}
static int ath9k_init_queues(struct ath_softc *sc)
{
int i = 0;
sc->beacon.beaconq = ath9k_hw_beaconq_setup(sc->sc_ah);
sc->beacon.cabq = ath_txq_setup(sc, ATH9K_TX_QUEUE_CAB, 0);
sc->config.cabqReadytime = ATH_CABQ_READY_TIME;
ath_cabq_update(sc);
for (i = 0; i < IEEE80211_NUM_ACS; i++) {
sc->tx.txq_map[i] = ath_txq_setup(sc, ATH9K_TX_QUEUE_DATA, i);
sc->tx.txq_map[i]->mac80211_qnum = i;
sc->tx.txq_max_pending[i] = ATH_MAX_QDEPTH;
}
return 0;
}
static int ath9k_init_channels_rates(struct ath_softc *sc)
{
void *channels;
BUILD_BUG_ON(ARRAY_SIZE(ath9k_2ghz_chantable) +
ARRAY_SIZE(ath9k_5ghz_chantable) !=
ATH9K_NUM_CHANNELS);
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_2GHZ) {
channels = devm_kzalloc(sc->dev,
sizeof(ath9k_2ghz_chantable), GFP_KERNEL);
if (!channels)
return -ENOMEM;
memcpy(channels, ath9k_2ghz_chantable,
sizeof(ath9k_2ghz_chantable));
sc->sbands[IEEE80211_BAND_2GHZ].channels = channels;
sc->sbands[IEEE80211_BAND_2GHZ].band = IEEE80211_BAND_2GHZ;
sc->sbands[IEEE80211_BAND_2GHZ].n_channels =
ARRAY_SIZE(ath9k_2ghz_chantable);
sc->sbands[IEEE80211_BAND_2GHZ].bitrates = ath9k_legacy_rates;
sc->sbands[IEEE80211_BAND_2GHZ].n_bitrates =
ARRAY_SIZE(ath9k_legacy_rates);
}
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_5GHZ) {
channels = devm_kzalloc(sc->dev,
sizeof(ath9k_5ghz_chantable), GFP_KERNEL);
if (!channels)
return -ENOMEM;
memcpy(channels, ath9k_5ghz_chantable,
sizeof(ath9k_5ghz_chantable));
sc->sbands[IEEE80211_BAND_5GHZ].channels = channels;
sc->sbands[IEEE80211_BAND_5GHZ].band = IEEE80211_BAND_5GHZ;
sc->sbands[IEEE80211_BAND_5GHZ].n_channels =
ARRAY_SIZE(ath9k_5ghz_chantable);
sc->sbands[IEEE80211_BAND_5GHZ].bitrates =
ath9k_legacy_rates + 4;
sc->sbands[IEEE80211_BAND_5GHZ].n_bitrates =
ARRAY_SIZE(ath9k_legacy_rates) - 4;
}
return 0;
}
static void ath9k_init_misc(struct ath_softc *sc)
{
struct ath_common *common = ath9k_hw_common(sc->sc_ah);
int i = 0;
setup_timer(&common->ani.timer, ath_ani_calibrate, (unsigned long)sc);
sc->last_rssi = ATH_RSSI_DUMMY_MARKER;
sc->config.txpowlimit = ATH_TXPOWER_MAX;
memcpy(common->bssidmask, ath_bcast_mac, ETH_ALEN);
sc->beacon.slottime = ATH9K_SLOT_TIME_9;
for (i = 0; i < ARRAY_SIZE(sc->beacon.bslot); i++)
sc->beacon.bslot[i] = NULL;
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_ANT_DIV_COMB)
sc->ant_comb.count = ATH_ANT_DIV_COMB_INIT_COUNT;
sc->spec_config.enabled = 0;
sc->spec_config.short_repeat = true;
sc->spec_config.count = 8;
sc->spec_config.endless = false;
sc->spec_config.period = 0xFF;
sc->spec_config.fft_period = 0xF;
}
static void ath9k_eeprom_request_cb(const struct firmware *eeprom_blob,
void *ctx)
{
struct ath9k_eeprom_ctx *ec = ctx;
if (eeprom_blob)
ec->ah->eeprom_blob = eeprom_blob;
complete(&ec->complete);
}
static int ath9k_eeprom_request(struct ath_softc *sc, const char *name)
{
struct ath9k_eeprom_ctx ec;
struct ath_hw *ah = ah = sc->sc_ah;
int err;
/* try to load the EEPROM content asynchronously */
init_completion(&ec.complete);
ec.ah = sc->sc_ah;
err = request_firmware_nowait(THIS_MODULE, 1, name, sc->dev, GFP_KERNEL,
&ec, ath9k_eeprom_request_cb);
if (err < 0) {
ath_err(ath9k_hw_common(ah),
"EEPROM request failed\n");
return err;
}
wait_for_completion(&ec.complete);
if (!ah->eeprom_blob) {
ath_err(ath9k_hw_common(ah),
"Unable to load EEPROM file %s\n", name);
return -EINVAL;
}
return 0;
}
static void ath9k_eeprom_release(struct ath_softc *sc)
{
release_firmware(sc->sc_ah->eeprom_blob);
}
static int ath9k_init_softc(u16 devid, struct ath_softc *sc,
const struct ath_bus_ops *bus_ops)
{
struct ath9k_platform_data *pdata = sc->dev->platform_data;
struct ath_hw *ah = NULL;
struct ath_common *common;
int ret = 0, i;
int csz = 0;
ah = devm_kzalloc(sc->dev, sizeof(struct ath_hw), GFP_KERNEL);
if (!ah)
return -ENOMEM;
ah->dev = sc->dev;
ah->hw = sc->hw;
ah->hw_version.devid = devid;
ah->reg_ops.read = ath9k_ioread32;
ah->reg_ops.write = ath9k_iowrite32;
ah->reg_ops.rmw = ath9k_reg_rmw;
atomic_set(&ah->intr_ref_cnt, -1);
sc->sc_ah = ah;
sc->dfs_detector = dfs_pattern_detector_init(NL80211_DFS_UNSET);
if (!pdata) {
ah->ah_flags |= AH_USE_EEPROM;
sc->sc_ah->led_pin = -1;
} else {
sc->sc_ah->gpio_mask = pdata->gpio_mask;
sc->sc_ah->gpio_val = pdata->gpio_val;
sc->sc_ah->led_pin = pdata->led_pin;
ah->is_clk_25mhz = pdata->is_clk_25mhz;
ah->get_mac_revision = pdata->get_mac_revision;
ah->external_reset = pdata->external_reset;
}
common = ath9k_hw_common(ah);
common->ops = &ah->reg_ops;
common->bus_ops = bus_ops;
common->ah = ah;
common->hw = sc->hw;
common->priv = sc;
common->debug_mask = ath9k_debug;
common->btcoex_enabled = ath9k_btcoex_enable == 1;
common->disable_ani = false;
/*
* Enable Antenna diversity only when BTCOEX is disabled
* and the user manually requests the feature.
*/
if (!common->btcoex_enabled && ath9k_enable_diversity)
common->antenna_diversity = 1;
spin_lock_init(&common->cc_lock);
spin_lock_init(&sc->sc_serial_rw);
spin_lock_init(&sc->sc_pm_lock);
mutex_init(&sc->mutex);
#ifdef CONFIG_ATH9K_MAC_DEBUG
spin_lock_init(&sc->debug.samp_lock);
#endif
tasklet_init(&sc->intr_tq, ath9k_tasklet, (unsigned long)sc);
tasklet_init(&sc->bcon_tasklet, ath9k_beacon_tasklet,
(unsigned long)sc);
INIT_WORK(&sc->hw_reset_work, ath_reset_work);
INIT_WORK(&sc->hw_check_work, ath_hw_check);
INIT_WORK(&sc->paprd_work, ath_paprd_calibrate);
INIT_DELAYED_WORK(&sc->hw_pll_work, ath_hw_pll_work);
setup_timer(&sc->rx_poll_timer, ath_rx_poll, (unsigned long)sc);
/*
* Cache line size is used to size and align various
* structures used to communicate with the hardware.
*/
ath_read_cachesize(common, &csz);
common->cachelsz = csz << 2; /* convert to bytes */
if (pdata && pdata->eeprom_name) {
ret = ath9k_eeprom_request(sc, pdata->eeprom_name);
if (ret)
return ret;
}
/* Initializes the hardware for all supported chipsets */
ret = ath9k_hw_init(ah);
if (ret)
goto err_hw;
if (pdata && pdata->macaddr)
memcpy(common->macaddr, pdata->macaddr, ETH_ALEN);
ret = ath9k_init_queues(sc);
if (ret)
goto err_queues;
ret = ath9k_init_btcoex(sc);
if (ret)
goto err_btcoex;
ret = ath9k_init_channels_rates(sc);
if (ret)
goto err_btcoex;
ath9k_cmn_init_crypto(sc->sc_ah);
ath9k_init_misc(sc);
ath_fill_led_pin(sc);
if (common->bus_ops->aspm_init)
common->bus_ops->aspm_init(common);
return 0;
err_btcoex:
for (i = 0; i < ATH9K_NUM_TX_QUEUES; i++)
if (ATH_TXQ_SETUP(sc, i))
ath_tx_cleanupq(sc, &sc->tx.txq[i]);
err_queues:
ath9k_hw_deinit(ah);
err_hw:
ath9k_eeprom_release(sc);
return ret;
}
static void ath9k_init_band_txpower(struct ath_softc *sc, int band)
{
struct ieee80211_supported_band *sband;
struct ieee80211_channel *chan;
struct ath_hw *ah = sc->sc_ah;
int i;
sband = &sc->sbands[band];
for (i = 0; i < sband->n_channels; i++) {
chan = &sband->channels[i];
ah->curchan = &ah->channels[chan->hw_value];
ath9k_cmn_update_ichannel(ah->curchan, chan, NL80211_CHAN_HT20);
ath9k_hw_set_txpowerlimit(ah, MAX_RATE_POWER, true);
}
}
static void ath9k_init_txpower_limits(struct ath_softc *sc)
{
struct ath_hw *ah = sc->sc_ah;
struct ath9k_channel *curchan = ah->curchan;
if (ah->caps.hw_caps & ATH9K_HW_CAP_2GHZ)
ath9k_init_band_txpower(sc, IEEE80211_BAND_2GHZ);
if (ah->caps.hw_caps & ATH9K_HW_CAP_5GHZ)
ath9k_init_band_txpower(sc, IEEE80211_BAND_5GHZ);
ah->curchan = curchan;
}
void ath9k_reload_chainmask_settings(struct ath_softc *sc)
{
if (!(sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_HT))
return;
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_2GHZ)
setup_ht_cap(sc, &sc->sbands[IEEE80211_BAND_2GHZ].ht_cap);
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_5GHZ)
setup_ht_cap(sc, &sc->sbands[IEEE80211_BAND_5GHZ].ht_cap);
}
static const struct ieee80211_iface_limit if_limits[] = {
{ .max = 2048, .types = BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_P2P_CLIENT) |
BIT(NL80211_IFTYPE_WDS) },
{ .max = 8, .types =
#ifdef CONFIG_MAC80211_MESH
BIT(NL80211_IFTYPE_MESH_POINT) |
#endif
BIT(NL80211_IFTYPE_AP) |
BIT(NL80211_IFTYPE_P2P_GO) },
};
static const struct ieee80211_iface_combination if_comb = {
.limits = if_limits,
.n_limits = ARRAY_SIZE(if_limits),
.max_interfaces = 2048,
.num_different_channels = 1,
.beacon_int_infra_match = true,
};
void ath9k_set_hw_capab(struct ath_softc *sc, struct ieee80211_hw *hw)
{
struct ath_hw *ah = sc->sc_ah;
struct ath_common *common = ath9k_hw_common(ah);
hw->flags = IEEE80211_HW_RX_INCLUDES_FCS |
IEEE80211_HW_HOST_BROADCAST_PS_BUFFERING |
IEEE80211_HW_SIGNAL_DBM |
IEEE80211_HW_SUPPORTS_PS |
IEEE80211_HW_PS_NULLFUNC_STACK |
IEEE80211_HW_SPECTRUM_MGMT |
IEEE80211_HW_REPORTS_TX_ACK_STATUS;
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_HT)
hw->flags |= IEEE80211_HW_AMPDU_AGGREGATION;
if (AR_SREV_9160_10_OR_LATER(sc->sc_ah) || ath9k_modparam_nohwcrypt)
hw->flags |= IEEE80211_HW_MFP_CAPABLE;
hw->wiphy->interface_modes =
BIT(NL80211_IFTYPE_P2P_GO) |
BIT(NL80211_IFTYPE_P2P_CLIENT) |
BIT(NL80211_IFTYPE_AP) |
BIT(NL80211_IFTYPE_WDS) |
BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_ADHOC) |
BIT(NL80211_IFTYPE_MESH_POINT);
hw->wiphy->iface_combinations = &if_comb;
hw->wiphy->n_iface_combinations = 1;
if (AR_SREV_5416(sc->sc_ah))
hw->wiphy->flags &= ~WIPHY_FLAG_PS_ON_BY_DEFAULT;
hw->wiphy->flags |= WIPHY_FLAG_IBSS_RSN;
hw->wiphy->flags |= WIPHY_FLAG_SUPPORTS_TDLS;
hw->wiphy->flags |= WIPHY_FLAG_HAS_REMAIN_ON_CHANNEL;
#ifdef CONFIG_PM_SLEEP
if ((ah->caps.hw_caps & ATH9K_HW_WOW_DEVICE_CAPABLE) &&
device_can_wakeup(sc->dev)) {
hw->wiphy->wowlan.flags = WIPHY_WOWLAN_MAGIC_PKT |
WIPHY_WOWLAN_DISCONNECT;
hw->wiphy->wowlan.n_patterns = MAX_NUM_USER_PATTERN;
hw->wiphy->wowlan.pattern_min_len = 1;
hw->wiphy->wowlan.pattern_max_len = MAX_PATTERN_SIZE;
}
atomic_set(&sc->wow_sleep_proc_intr, -1);
atomic_set(&sc->wow_got_bmiss_intr, -1);
#endif
hw->queues = 4;
hw->max_rates = 4;
hw->channel_change_time = 5000;
hw->max_listen_interval = 1;
hw->max_rate_tries = 10;
hw->sta_data_size = sizeof(struct ath_node);
hw->vif_data_size = sizeof(struct ath_vif);
hw->wiphy->available_antennas_rx = BIT(ah->caps.max_rxchains) - 1;
hw->wiphy->available_antennas_tx = BIT(ah->caps.max_txchains) - 1;
/* single chain devices with rx diversity */
if (ah->caps.hw_caps & ATH9K_HW_CAP_ANT_DIV_COMB)
hw->wiphy->available_antennas_rx = BIT(0) | BIT(1);
sc->ant_rx = hw->wiphy->available_antennas_rx;
sc->ant_tx = hw->wiphy->available_antennas_tx;
#ifdef CONFIG_ATH9K_RATE_CONTROL
hw->rate_control_algorithm = "ath9k_rate_control";
#endif
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_2GHZ)
hw->wiphy->bands[IEEE80211_BAND_2GHZ] =
&sc->sbands[IEEE80211_BAND_2GHZ];
if (sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_5GHZ)
hw->wiphy->bands[IEEE80211_BAND_5GHZ] =
&sc->sbands[IEEE80211_BAND_5GHZ];
ath9k_reload_chainmask_settings(sc);
SET_IEEE80211_PERM_ADDR(hw, common->macaddr);
}
int ath9k_init_device(u16 devid, struct ath_softc *sc,
const struct ath_bus_ops *bus_ops)
{
struct ieee80211_hw *hw = sc->hw;
struct ath_common *common;
struct ath_hw *ah;
int error = 0;
struct ath_regulatory *reg;
/* Bring up device */
error = ath9k_init_softc(devid, sc, bus_ops);
if (error)
return error;
ah = sc->sc_ah;
common = ath9k_hw_common(ah);
ath9k_set_hw_capab(sc, hw);
/* Initialize regulatory */
error = ath_regd_init(&common->regulatory, sc->hw->wiphy,
ath9k_reg_notifier);
if (error)
goto deinit;
reg = &common->regulatory;
/* Setup TX DMA */
error = ath_tx_init(sc, ATH_TXBUF);
if (error != 0)
goto deinit;
/* Setup RX DMA */
error = ath_rx_init(sc, ATH_RXBUF);
if (error != 0)
goto deinit;
ath9k_init_txpower_limits(sc);
#ifdef CONFIG_MAC80211_LEDS
/* must be initialized before ieee80211_register_hw */
sc->led_cdev.default_trigger = ieee80211_create_tpt_led_trigger(sc->hw,
IEEE80211_TPT_LEDTRIG_FL_RADIO, ath9k_tpt_blink,
ARRAY_SIZE(ath9k_tpt_blink));
#endif
/* Register with mac80211 */
error = ieee80211_register_hw(hw);
if (error)
goto rx_cleanup;
error = ath9k_init_debug(ah);
if (error) {
ath_err(common, "Unable to create debugfs files\n");
goto unregister;
}
/* Handle world regulatory */
if (!ath_is_world_regd(reg)) {
error = regulatory_hint(hw->wiphy, reg->alpha2);
if (error)
goto unregister;
}
ath_init_leds(sc);
ath_start_rfkill_poll(sc);
return 0;
unregister:
ieee80211_unregister_hw(hw);
rx_cleanup:
ath_rx_cleanup(sc);
deinit:
ath9k_deinit_softc(sc);
return error;
}
/*****************************/
/* De-Initialization */
/*****************************/
static void ath9k_deinit_softc(struct ath_softc *sc)
{
int i = 0;
ath9k_deinit_btcoex(sc);
for (i = 0; i < ATH9K_NUM_TX_QUEUES; i++)
if (ATH_TXQ_SETUP(sc, i))
ath_tx_cleanupq(sc, &sc->tx.txq[i]);
ath9k_hw_deinit(sc->sc_ah);
if (sc->dfs_detector != NULL)
sc->dfs_detector->exit(sc->dfs_detector);
ath9k_eeprom_release(sc);
if (config_enabled(CONFIG_ATH9K_DEBUGFS) && sc->rfs_chan_spec_scan) {
relay_close(sc->rfs_chan_spec_scan);
sc->rfs_chan_spec_scan = NULL;
}
}
void ath9k_deinit_device(struct ath_softc *sc)
{
struct ieee80211_hw *hw = sc->hw;
ath9k_ps_wakeup(sc);
wiphy_rfkill_stop_polling(sc->hw->wiphy);
ath_deinit_leds(sc);
ath9k_ps_restore(sc);
ieee80211_unregister_hw(hw);
ath_rx_cleanup(sc);
ath9k_deinit_softc(sc);
}
/************************/
/* Module Hooks */
/************************/
static int __init ath9k_init(void)
{
int error;
/* Register rate control algorithm */
error = ath_rate_control_register();
if (error != 0) {
pr_err("Unable to register rate control algorithm: %d\n",
error);
goto err_out;
}
error = ath_pci_init();
if (error < 0) {
pr_err("No PCI devices found, driver not installed\n");
error = -ENODEV;
goto err_rate_unregister;
}
error = ath_ahb_init();
if (error < 0) {
error = -ENODEV;
goto err_pci_exit;
}
return 0;
err_pci_exit:
ath_pci_exit();
err_rate_unregister:
ath_rate_control_unregister();
err_out:
return error;
}
module_init(ath9k_init);
static void __exit ath9k_exit(void)
{
is_ath9k_unloaded = true;
ath_ahb_exit();
ath_pci_exit();
ath_rate_control_unregister();
pr_info("%s: Driver unloaded\n", dev_info);
}
module_exit(ath9k_exit);
| gpl-2.0 |
gouwa/linux-rk3288 | drivers/net/wireless/rockchip_wlan/mt5931_kk/drv_wlan/mgmt/rlm_obss.c | 53 | 16977 | /*
** $Id: //Department/DaVinci/BRANCHES/MT662X_593X_WIFI_DRIVER_V2_3/mgmt/rlm_obss.c#1 $
*/
/*! \file "rlm_obss.c"
\brief
*/
/*******************************************************************************
* Copyright (c) 2009 MediaTek Inc.
*
* All rights reserved. Copying, compilation, modification, distribution
* or any other use whatsoever of this material is strictly prohibited
* except in accordance with a Software License Agreement with
* MediaTek Inc.
********************************************************************************
*/
/*******************************************************************************
* LEGAL DISCLAIMER
*
* BY OPENING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND
* AGREES THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK
* SOFTWARE") RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE
* PROVIDED TO BUYER ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY
* DISCLAIMS ANY AND ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE OR NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE
* ANY WARRANTY WHATSOEVER WITH RESPECT TO THE SOFTWARE OF ANY THIRD PARTY
* WHICH MAY BE USED BY, INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK
* SOFTWARE, AND BUYER AGREES TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY
* WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE
* FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S SPECIFICATION OR TO
* CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM.
*
* BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE
* LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL
* BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT
* ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY
* BUYER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE
* WITH THE LAWS OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT
* OF LAWS PRINCIPLES. ANY DISPUTES, CONTROVERSIES OR CLAIMS ARISING
* THEREOF AND RELATED THERETO SHALL BE SETTLED BY ARBITRATION IN SAN
* FRANCISCO, CA, UNDER THE RULES OF THE INTERNATIONAL CHAMBER OF COMMERCE
* (ICC).
********************************************************************************
*/
/*
** $Log: rlm_obss.c $
*
* 07 17 2012 yuche.tsai
* NULL
* Compile no error before trial run.
*
* 11 15 2011 cm.chang
* NULL
* Avoid possible OBSS scan when BSS is switched
*
* 11 08 2011 cm.chang
* NULL
* Add RLM and CNM debug message for XLOG
*
* 10 25 2011 cm.chang
* [WCXRP00001058] [All Wi-Fi][Driver] Fix sta_rec's phyTypeSet and OBSS scan in AP mode
* Regulation class is changed to 81 in 20_40_coexistence action frame
*
* 04 12 2011 cm.chang
* [WCXRP00000634] [MT6620 Wi-Fi][Driver][FW] 2nd BSS will not support 40MHz bandwidth for concurrency
* .
*
* 03 29 2011 cm.chang
* [WCXRP00000606] [MT6620 Wi-Fi][Driver][FW] Fix klocwork warning
* As CR title
*
* 01 24 2011 cm.chang
* [WCXRP00000384] [MT6620 Wi-Fi][Driver][FW] Handle 20/40 action frame in AP mode and stop ampdu timer when sta_rec is freed
* Process received 20/40 coexistence action frame for AP mode
*
* 01 13 2011 cm.chang
* [WCXRP00000358] [MT6620 Wi-Fi][Driver] Provide concurrent information for each module
* Refine function when rcv a 20/40M public action frame
*
* 01 13 2011 cm.chang
* [WCXRP00000354] [MT6620 Wi-Fi][Driver][FW] Follow NVRAM bandwidth setting
* Use SCO of BSS_INFO to replace user-defined setting variables
*
* 01 12 2011 cm.chang
* [WCXRP00000354] [MT6620 Wi-Fi][Driver][FW] Follow NVRAM bandwidth setting
* User-defined bandwidth is for 2.4G and 5G individually
*
* 10 18 2010 cp.wu
* [WCXRP00000052] [MT6620 Wi-Fi][Driver] Eliminate Linux Compile Warning
* use definition macro to replace hard-coded constant
*
* 09 16 2010 cm.chang
* NULL
* Change conditional compiling options for BOW
*
* 09 10 2010 cm.chang
* NULL
* Always update Beacon content if FW sync OBSS info
*
* 08 24 2010 cm.chang
* NULL
* Support RLM initail channel of Ad-hoc, P2P and BOW
*
* 08 20 2010 cm.chang
* NULL
* Migrate RLM code to host from FW
*
* 07 26 2010 yuche.tsai
*
* Fix compile error while enabling WiFi Direct function.
*
* 07 21 2010 yuche.tsai
*
* Add P2P Scan & Scan Result Parsing & Saving.
*
* 07 08 2010 cp.wu
*
* [WPD00003833] [MT6620 and MT5931] Driver migration - move to new repository.
*
* 07 08 2010 cm.chang
* [WPD00003841][LITE Driver] Migrate RLM/CNM to host driver
* Check draft RLM code for HT cap
*
* 05 07 2010 cm.chang
* [BORA00000018]Integrate WIFI part into BORA for the 1st time
* Process 20/40 coexistence public action frame in AP mode
*
* 05 05 2010 cm.chang
* [BORA00000018]Integrate WIFI part into BORA for the 1st time
* First draft support for 20/40M bandwidth for AP mode
*
* 04 24 2010 cm.chang
* [BORA00000018]Integrate WIFI part into BORA for the 1st time
* g_aprBssInfo[] depends on CFG_SUPPORT_P2P and CFG_SUPPORT_BOW
*
* 04 13 2010 cm.chang
* [BORA00000018]Integrate WIFI part into BORA for the 1st time
* Add more ASSERT to check exception
*
* 04 07 2010 cm.chang
* [BORA00000018]Integrate WIFI part into BORA for the 1st time
* Add virtual test for OBSS scan
*
* 03 30 2010 cm.chang
* [BORA00000018]Integrate WIFI part into BORA for the 1st time
* Support 2.4G OBSS scan
*
* 03 03 2010 cm.chang
* [BORA00000018]Integrate WIFI part into BORA for the 1st time
* To support CFG_SUPPORT_BCM_STP
*
* 02 13 2010 cm.chang
* [BORA00000018]Integrate WIFI part into BORA for the 1st time
* Support PCO in STA mode
*
* 02 12 2010 cm.chang
* [BORA00000018]Integrate WIFI part into BORA for the 1st time
* Use bss info array for concurrent handle
*
* 02 05 2010 kevin.huang
* [BORA00000603][WIFISYS] [New Feature] AAA Module Support
* Add AAA Module Support, Revise Net Type to Net Type Index for array lookup
*
* 01 25 2010 cm.chang
* [BORA00000018]Integrate WIFI part into BORA for the 1st time
* Support protection and bandwidth switch
*/
/*******************************************************************************
* C O M P I L E R F L A G S
********************************************************************************
*/
/*******************************************************************************
* E X T E R N A L R E F E R E N C E S
********************************************************************************
*/
#include "precomp.h"
/*******************************************************************************
* C O N S T A N T S
********************************************************************************
*/
/*******************************************************************************
* D A T A T Y P E S
********************************************************************************
*/
/*******************************************************************************
* P U B L I C D A T A
********************************************************************************
*/
/*******************************************************************************
* P R I V A T E D A T A
********************************************************************************
*/
/*******************************************************************************
* M A C R O S
********************************************************************************
*/
/*******************************************************************************
* F U N C T I O N D E C L A R A T I O N S
********************************************************************************
*/
static VOID
rlmObssScanTimeout (
P_ADAPTER_T prAdapter,
UINT_32 u4Data
);
/*******************************************************************************
* F U N C T I O N S
********************************************************************************
*/
/*----------------------------------------------------------------------------*/
/*!
* \brief
*
* \param[in]
*
* \return none
*/
/*----------------------------------------------------------------------------*/
VOID
rlmObssInit (
P_ADAPTER_T prAdapter
)
{
P_BSS_INFO_T prBssInfo;
UINT_8 ucNetIdx;
RLM_NET_FOR_EACH(ucNetIdx) {
prBssInfo = &prAdapter->rWifiVar.arBssInfo[ucNetIdx];
ASSERT(prBssInfo);
cnmTimerInitTimer(prAdapter, &prBssInfo->rObssScanTimer,
rlmObssScanTimeout, (UINT_32) prBssInfo);
} /* end of RLM_NET_FOR_EACH */
}
/*----------------------------------------------------------------------------*/
/*!
* \brief
*
* \param[in]
*
* \return none
*/
/*----------------------------------------------------------------------------*/
BOOLEAN
rlmObssUpdateChnlLists (
P_ADAPTER_T prAdapter,
P_SW_RFB_T prSwRfb
)
{
return TRUE;
}
/*----------------------------------------------------------------------------*/
/*!
* \brief
*
* \param[in]
*
* \return none
*/
/*----------------------------------------------------------------------------*/
VOID
rlmObssScanDone (
P_ADAPTER_T prAdapter,
P_MSG_HDR_T prMsgHdr
)
{
P_MSG_SCN_SCAN_DONE prScanDoneMsg;
P_BSS_INFO_T prBssInfo;
P_MSDU_INFO_T prMsduInfo;
P_ACTION_20_40_COEXIST_FRAME prTxFrame;
UINT_16 i, u2PayloadLen;
ASSERT(prMsgHdr);
prScanDoneMsg = (P_MSG_SCN_SCAN_DONE) prMsgHdr;
prBssInfo = &prAdapter->rWifiVar.arBssInfo[prScanDoneMsg->ucNetTypeIndex];
ASSERT(prBssInfo);
DBGLOG(RLM, INFO, ("OBSS Scan Done (NetIdx=%d, Mode=%d)\n",
prScanDoneMsg->ucNetTypeIndex, prBssInfo->eCurrentOPMode));
cnmMemFree(prAdapter, prMsgHdr);
#if CFG_ENABLE_WIFI_DIRECT
/* AP mode */
if ((prAdapter->fgIsP2PRegistered) &&
(IS_NET_ACTIVE(prAdapter, prBssInfo->ucNetTypeIndex)) &&
(prBssInfo->eCurrentOPMode == OP_MODE_ACCESS_POINT)) {
return;
}
#endif
/* STA mode */
if (prBssInfo->eCurrentOPMode != OP_MODE_INFRASTRUCTURE ||
!RLM_NET_PARAM_VALID(prBssInfo) || prBssInfo->u2ObssScanInterval == 0) {
DBGLOG(RLM, WARN, ("OBSS Scan Done (NetIdx=%d) -- Aborted!!\n",
prBssInfo->ucNetTypeIndex));
return;
}
/* To do: check 2.4G channel list to decide if obss mgmt should be
* sent to associated AP. Note: how to handle concurrent network?
* To do: invoke rlmObssChnlLevel() to decide if 20/40 BSS coexistence
* management frame is needed.
*/
if ((prBssInfo->auc2G_20mReqChnlList[0] > 0 ||
prBssInfo->auc2G_NonHtChnlList[0] > 0) &&
(prMsduInfo = (P_MSDU_INFO_T) cnmMgtPktAlloc(prAdapter,
MAC_TX_RESERVED_FIELD + PUBLIC_ACTION_MAX_LEN)) != NULL) {
DBGLOG(RLM, INFO, ("Send 20/40 coexistence mgmt(20mReq=%d, NonHt=%d)\n",
prBssInfo->auc2G_20mReqChnlList[0],
prBssInfo->auc2G_NonHtChnlList[0]));
prTxFrame = (P_ACTION_20_40_COEXIST_FRAME)
((UINT_32)(prMsduInfo->prPacket) + MAC_TX_RESERVED_FIELD);
prTxFrame->u2FrameCtrl = MAC_FRAME_ACTION;
COPY_MAC_ADDR(prTxFrame->aucDestAddr, prBssInfo->aucBSSID);
COPY_MAC_ADDR(prTxFrame->aucSrcAddr, prBssInfo->aucOwnMacAddr);
COPY_MAC_ADDR(prTxFrame->aucBSSID, prBssInfo->aucBSSID);
prTxFrame->ucCategory = CATEGORY_PUBLIC_ACTION;
prTxFrame->ucAction = ACTION_PUBLIC_20_40_COEXIST;
/* To do: find correct algorithm */
prTxFrame->rBssCoexist.ucId = ELEM_ID_20_40_BSS_COEXISTENCE;
prTxFrame->rBssCoexist.ucLength = 1;
prTxFrame->rBssCoexist.ucData =
(prBssInfo->auc2G_20mReqChnlList[0] > 0) ? BSS_COEXIST_20M_REQ : 0;
u2PayloadLen = 2 + 3;
if (prBssInfo->auc2G_NonHtChnlList[0] > 0) {
ASSERT(prBssInfo->auc2G_NonHtChnlList[0] <= CHNL_LIST_SZ_2G);
prTxFrame->rChnlReport.ucId = ELEM_ID_20_40_INTOLERANT_CHNL_REPORT;
prTxFrame->rChnlReport.ucLength =
prBssInfo->auc2G_NonHtChnlList[0] + 1;
prTxFrame->rChnlReport.ucRegulatoryClass = 81; /* 2.4GHz, ch1~13 */
for (i = 0; i < prBssInfo->auc2G_NonHtChnlList[0] &&
i < CHNL_LIST_SZ_2G; i++) {
prTxFrame->rChnlReport.aucChannelList[i] =
prBssInfo->auc2G_NonHtChnlList[i+1];
}
u2PayloadLen += IE_SIZE(&prTxFrame->rChnlReport);
}
ASSERT((WLAN_MAC_HEADER_LEN + u2PayloadLen) <= PUBLIC_ACTION_MAX_LEN);
/* Clear up channel lists in 2.4G band */
prBssInfo->auc2G_20mReqChnlList[0] = 0;
prBssInfo->auc2G_NonHtChnlList[0] = 0;
//4 Update information of MSDU_INFO_T
prMsduInfo->ucPacketType = HIF_TX_PACKET_TYPE_MGMT; /* Management frame */
prMsduInfo->ucStaRecIndex = prBssInfo->prStaRecOfAP->ucIndex;
prMsduInfo->ucNetworkType = prBssInfo->ucNetTypeIndex;
prMsduInfo->ucMacHeaderLength = WLAN_MAC_MGMT_HEADER_LEN;
prMsduInfo->fgIs802_1x = FALSE;
prMsduInfo->fgIs802_11 = TRUE;
prMsduInfo->u2FrameLength = WLAN_MAC_MGMT_HEADER_LEN + u2PayloadLen;
prMsduInfo->ucTxSeqNum = nicIncreaseTxSeqNum(prAdapter);
prMsduInfo->pfTxDoneHandler = NULL;
prMsduInfo->fgIsBasicRate = FALSE;
//4 Enqueue the frame to send this action frame.
nicTxEnqueueMsdu(prAdapter, prMsduInfo);
} /* end of prMsduInfo != NULL */
if (prBssInfo->u2ObssScanInterval > 0) {
DBGLOG(RLM, INFO, ("Set OBSS timer (NetIdx=%d, %d sec)\n",
prBssInfo->ucNetTypeIndex, prBssInfo->u2ObssScanInterval));
cnmTimerStartTimer(prAdapter, &prBssInfo->rObssScanTimer,
prBssInfo->u2ObssScanInterval * MSEC_PER_SEC);
}
}
/*----------------------------------------------------------------------------*/
/*!
* \brief
*
* \param[in]
*
* \return none
*/
/*----------------------------------------------------------------------------*/
static VOID
rlmObssScanTimeout (
P_ADAPTER_T prAdapter,
UINT_32 u4Data
)
{
P_BSS_INFO_T prBssInfo;
prBssInfo = (P_BSS_INFO_T) u4Data;
ASSERT(prBssInfo);
#if CFG_ENABLE_WIFI_DIRECT
/* AP mode */
if (prAdapter->fgIsP2PRegistered &&
(IS_NET_ACTIVE(prAdapter, prBssInfo->ucNetTypeIndex)) &&
(prBssInfo->eCurrentOPMode == OP_MODE_ACCESS_POINT)) {
prBssInfo->fgObssActionForcedTo20M = FALSE;
/* Check if Beacon content need to be updated */
rlmUpdateParamsForAP(prAdapter, prBssInfo, FALSE);
return;
}
#endif /* end of CFG_ENABLE_WIFI_DIRECT */
/* STA mode */
if (prBssInfo->eCurrentOPMode != OP_MODE_INFRASTRUCTURE ||
!RLM_NET_PARAM_VALID(prBssInfo) || prBssInfo->u2ObssScanInterval == 0) {
DBGLOG(RLM, WARN, ("OBSS Scan timeout (NetIdx=%d) -- Aborted!!\n",
prBssInfo->ucNetTypeIndex));
return;
}
rlmObssTriggerScan(prAdapter, prBssInfo);
}
/*----------------------------------------------------------------------------*/
/*!
* \brief
*
* \param[in]
*
* \return none
*/
/*----------------------------------------------------------------------------*/
VOID
rlmObssTriggerScan (
P_ADAPTER_T prAdapter,
P_BSS_INFO_T prBssInfo
)
{
P_MSG_SCN_SCAN_REQ prScanReqMsg;
ASSERT(prBssInfo);
prScanReqMsg = (P_MSG_SCN_SCAN_REQ)
cnmMemAlloc(prAdapter, RAM_TYPE_MSG, sizeof(MSG_SCN_SCAN_REQ));
ASSERT(prScanReqMsg);
if (!prScanReqMsg) {
DBGLOG(RLM, WARN, ("No buf for OBSS scan (NetIdx=%d)!!\n",
prBssInfo->ucNetTypeIndex));
cnmTimerStartTimer(prAdapter, &prBssInfo->rObssScanTimer,
prBssInfo->u2ObssScanInterval * MSEC_PER_SEC);
return;
}
/* It is ok that ucSeqNum is set to fixed value because the same network
* OBSS scan interval is limited to OBSS_SCAN_MIN_INTERVAL (min 10 sec)
* and scan module don't care seqNum of OBSS scanning
*/
prScanReqMsg->rMsgHdr.eMsgId = MID_RLM_SCN_SCAN_REQ;
prScanReqMsg->ucSeqNum = 0x33;
prScanReqMsg->ucNetTypeIndex = prBssInfo->ucNetTypeIndex;
prScanReqMsg->eScanType = SCAN_TYPE_ACTIVE_SCAN;
prScanReqMsg->ucSSIDType = SCAN_REQ_SSID_WILDCARD;
prScanReqMsg->ucSSIDLength = 0;
prScanReqMsg->eScanChannel = SCAN_CHANNEL_2G4;
prScanReqMsg->u2IELen = 0;
mboxSendMsg(prAdapter,
MBOX_ID_0,
(P_MSG_HDR_T) prScanReqMsg,
MSG_SEND_METHOD_BUF);
DBGLOG(RLM, INFO, ("Timeout to trigger OBSS scan (NetIdx=%d)!!\n",
prBssInfo->ucNetTypeIndex));
}
| gpl-2.0 |
squirrel20/linux-4.8.15 | kernel/power/main.c | 53 | 15787 | /*
* kernel/power/main.c - PM subsystem core functionality.
*
* Copyright (c) 2003 Patrick Mochel
* Copyright (c) 2003 Open Source Development Lab
*
* This file is released under the GPLv2
*
*/
#include <linux/export.h>
#include <linux/kobject.h>
#include <linux/string.h>
#include <linux/pm-trace.h>
#include <linux/workqueue.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#include "power.h"
DEFINE_MUTEX(pm_mutex);
#ifdef CONFIG_PM_SLEEP
/* Routines for PM-transition notifications */
static BLOCKING_NOTIFIER_HEAD(pm_chain_head);
int register_pm_notifier(struct notifier_block *nb)
{
return blocking_notifier_chain_register(&pm_chain_head, nb);
}
EXPORT_SYMBOL_GPL(register_pm_notifier);
int unregister_pm_notifier(struct notifier_block *nb)
{
return blocking_notifier_chain_unregister(&pm_chain_head, nb);
}
EXPORT_SYMBOL_GPL(unregister_pm_notifier);
int __pm_notifier_call_chain(unsigned long val, int nr_to_call, int *nr_calls)
{
int ret;
ret = __blocking_notifier_call_chain(&pm_chain_head, val, NULL,
nr_to_call, nr_calls);
return notifier_to_errno(ret);
}
int pm_notifier_call_chain(unsigned long val)
{
return __pm_notifier_call_chain(val, -1, NULL);
}
/* If set, devices may be suspended and resumed asynchronously. */
int pm_async_enabled = 1;
static ssize_t pm_async_show(struct kobject *kobj, struct kobj_attribute *attr,
char *buf)
{
return sprintf(buf, "%d\n", pm_async_enabled);
}
static ssize_t pm_async_store(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t n)
{
unsigned long val;
if (kstrtoul(buf, 10, &val))
return -EINVAL;
if (val > 1)
return -EINVAL;
pm_async_enabled = val;
return n;
}
power_attr(pm_async);
#ifdef CONFIG_PM_DEBUG
int pm_test_level = TEST_NONE;
static const char * const pm_tests[__TEST_AFTER_LAST] = {
[TEST_NONE] = "none",
[TEST_CORE] = "core",
[TEST_CPUS] = "processors",
[TEST_PLATFORM] = "platform",
[TEST_DEVICES] = "devices",
[TEST_FREEZER] = "freezer",
};
static ssize_t pm_test_show(struct kobject *kobj, struct kobj_attribute *attr,
char *buf)
{
char *s = buf;
int level;
for (level = TEST_FIRST; level <= TEST_MAX; level++)
if (pm_tests[level]) {
if (level == pm_test_level)
s += sprintf(s, "[%s] ", pm_tests[level]);
else
s += sprintf(s, "%s ", pm_tests[level]);
}
if (s != buf)
/* convert the last space to a newline */
*(s-1) = '\n';
return (s - buf);
}
static ssize_t pm_test_store(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t n)
{
const char * const *s;
int level;
char *p;
int len;
int error = -EINVAL;
p = memchr(buf, '\n', n);
len = p ? p - buf : n;
lock_system_sleep();
level = TEST_FIRST;
for (s = &pm_tests[level]; level <= TEST_MAX; s++, level++)
if (*s && len == strlen(*s) && !strncmp(buf, *s, len)) {
pm_test_level = level;
error = 0;
break;
}
unlock_system_sleep();
return error ? error : n;
}
power_attr(pm_test);
#endif /* CONFIG_PM_DEBUG */
#ifdef CONFIG_DEBUG_FS
static char *suspend_step_name(enum suspend_stat_step step)
{
switch (step) {
case SUSPEND_FREEZE:
return "freeze";
case SUSPEND_PREPARE:
return "prepare";
case SUSPEND_SUSPEND:
return "suspend";
case SUSPEND_SUSPEND_NOIRQ:
return "suspend_noirq";
case SUSPEND_RESUME_NOIRQ:
return "resume_noirq";
case SUSPEND_RESUME:
return "resume";
default:
return "";
}
}
static int suspend_stats_show(struct seq_file *s, void *unused)
{
int i, index, last_dev, last_errno, last_step;
last_dev = suspend_stats.last_failed_dev + REC_FAILED_NUM - 1;
last_dev %= REC_FAILED_NUM;
last_errno = suspend_stats.last_failed_errno + REC_FAILED_NUM - 1;
last_errno %= REC_FAILED_NUM;
last_step = suspend_stats.last_failed_step + REC_FAILED_NUM - 1;
last_step %= REC_FAILED_NUM;
seq_printf(s, "%s: %d\n%s: %d\n%s: %d\n%s: %d\n%s: %d\n"
"%s: %d\n%s: %d\n%s: %d\n%s: %d\n%s: %d\n",
"success", suspend_stats.success,
"fail", suspend_stats.fail,
"failed_freeze", suspend_stats.failed_freeze,
"failed_prepare", suspend_stats.failed_prepare,
"failed_suspend", suspend_stats.failed_suspend,
"failed_suspend_late",
suspend_stats.failed_suspend_late,
"failed_suspend_noirq",
suspend_stats.failed_suspend_noirq,
"failed_resume", suspend_stats.failed_resume,
"failed_resume_early",
suspend_stats.failed_resume_early,
"failed_resume_noirq",
suspend_stats.failed_resume_noirq);
seq_printf(s, "failures:\n last_failed_dev:\t%-s\n",
suspend_stats.failed_devs[last_dev]);
for (i = 1; i < REC_FAILED_NUM; i++) {
index = last_dev + REC_FAILED_NUM - i;
index %= REC_FAILED_NUM;
seq_printf(s, "\t\t\t%-s\n",
suspend_stats.failed_devs[index]);
}
seq_printf(s, " last_failed_errno:\t%-d\n",
suspend_stats.errno[last_errno]);
for (i = 1; i < REC_FAILED_NUM; i++) {
index = last_errno + REC_FAILED_NUM - i;
index %= REC_FAILED_NUM;
seq_printf(s, "\t\t\t%-d\n",
suspend_stats.errno[index]);
}
seq_printf(s, " last_failed_step:\t%-s\n",
suspend_step_name(
suspend_stats.failed_steps[last_step]));
for (i = 1; i < REC_FAILED_NUM; i++) {
index = last_step + REC_FAILED_NUM - i;
index %= REC_FAILED_NUM;
seq_printf(s, "\t\t\t%-s\n",
suspend_step_name(
suspend_stats.failed_steps[index]));
}
return 0;
}
static int suspend_stats_open(struct inode *inode, struct file *file)
{
return single_open(file, suspend_stats_show, NULL);
}
static const struct file_operations suspend_stats_operations = {
.open = suspend_stats_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int __init pm_debugfs_init(void)
{
debugfs_create_file("suspend_stats", S_IFREG | S_IRUGO,
NULL, NULL, &suspend_stats_operations);
return 0;
}
late_initcall(pm_debugfs_init);
#endif /* CONFIG_DEBUG_FS */
#endif /* CONFIG_PM_SLEEP */
#ifdef CONFIG_PM_SLEEP_DEBUG
/*
* pm_print_times: print time taken by devices to suspend and resume.
*
* show() returns whether printing of suspend and resume times is enabled.
* store() accepts 0 or 1. 0 disables printing and 1 enables it.
*/
bool pm_print_times_enabled;
static ssize_t pm_print_times_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return sprintf(buf, "%d\n", pm_print_times_enabled);
}
static ssize_t pm_print_times_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t n)
{
unsigned long val;
if (kstrtoul(buf, 10, &val))
return -EINVAL;
if (val > 1)
return -EINVAL;
pm_print_times_enabled = !!val;
return n;
}
power_attr(pm_print_times);
static inline void pm_print_times_init(void)
{
pm_print_times_enabled = !!initcall_debug;
}
static ssize_t pm_wakeup_irq_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
return pm_wakeup_irq ? sprintf(buf, "%u\n", pm_wakeup_irq) : -ENODATA;
}
power_attr_ro(pm_wakeup_irq);
#else /* !CONFIG_PM_SLEEP_DEBUG */
static inline void pm_print_times_init(void) {}
#endif /* CONFIG_PM_SLEEP_DEBUG */
struct kobject *power_kobj;
/**
* state - control system sleep states.
*
* show() returns available sleep state labels, which may be "mem", "standby",
* "freeze" and "disk" (hibernation). See Documentation/power/states.txt for a
* description of what they mean.
*
* store() accepts one of those strings, translates it into the proper
* enumerated value, and initiates a suspend transition.
*/
static ssize_t state_show(struct kobject *kobj, struct kobj_attribute *attr,
char *buf)
{
char *s = buf;
#ifdef CONFIG_SUSPEND
suspend_state_t i;
for (i = PM_SUSPEND_MIN; i < PM_SUSPEND_MAX; i++)
if (pm_states[i])
s += sprintf(s,"%s ", pm_states[i]);
#endif
if (hibernation_available())
s += sprintf(s, "disk ");
if (s != buf)
/* convert the last space to a newline */
*(s-1) = '\n';
return (s - buf);
}
static suspend_state_t decode_state(const char *buf, size_t n)
{
#ifdef CONFIG_SUSPEND
suspend_state_t state;
#endif
char *p;
int len;
p = memchr(buf, '\n', n);
len = p ? p - buf : n;
/* Check hibernation first. */
if (len == 4 && !strncmp(buf, "disk", len))
return PM_SUSPEND_MAX;
#ifdef CONFIG_SUSPEND
for (state = PM_SUSPEND_MIN; state < PM_SUSPEND_MAX; state++) {
const char *label = pm_states[state];
if (label && len == strlen(label) && !strncmp(buf, label, len))
return state;
}
#endif
return PM_SUSPEND_ON;
}
static ssize_t state_store(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t n)
{
suspend_state_t state;
int error;
error = pm_autosleep_lock();
if (error)
return error;
if (pm_autosleep_state() > PM_SUSPEND_ON) {
error = -EBUSY;
goto out;
}
state = decode_state(buf, n);
if (state < PM_SUSPEND_MAX)
error = pm_suspend(state);
else if (state == PM_SUSPEND_MAX)
error = hibernate();
else
error = -EINVAL;
out:
pm_autosleep_unlock();
return error ? error : n;
}
power_attr(state);
#ifdef CONFIG_PM_SLEEP
/*
* The 'wakeup_count' attribute, along with the functions defined in
* drivers/base/power/wakeup.c, provides a means by which wakeup events can be
* handled in a non-racy way.
*
* If a wakeup event occurs when the system is in a sleep state, it simply is
* woken up. In turn, if an event that would wake the system up from a sleep
* state occurs when it is undergoing a transition to that sleep state, the
* transition should be aborted. Moreover, if such an event occurs when the
* system is in the working state, an attempt to start a transition to the
* given sleep state should fail during certain period after the detection of
* the event. Using the 'state' attribute alone is not sufficient to satisfy
* these requirements, because a wakeup event may occur exactly when 'state'
* is being written to and may be delivered to user space right before it is
* frozen, so the event will remain only partially processed until the system is
* woken up by another event. In particular, it won't cause the transition to
* a sleep state to be aborted.
*
* This difficulty may be overcome if user space uses 'wakeup_count' before
* writing to 'state'. It first should read from 'wakeup_count' and store
* the read value. Then, after carrying out its own preparations for the system
* transition to a sleep state, it should write the stored value to
* 'wakeup_count'. If that fails, at least one wakeup event has occurred since
* 'wakeup_count' was read and 'state' should not be written to. Otherwise, it
* is allowed to write to 'state', but the transition will be aborted if there
* are any wakeup events detected after 'wakeup_count' was written to.
*/
static ssize_t wakeup_count_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
unsigned int val;
return pm_get_wakeup_count(&val, true) ?
sprintf(buf, "%u\n", val) : -EINTR;
}
static ssize_t wakeup_count_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t n)
{
unsigned int val;
int error;
error = pm_autosleep_lock();
if (error)
return error;
if (pm_autosleep_state() > PM_SUSPEND_ON) {
error = -EBUSY;
goto out;
}
error = -EINVAL;
if (sscanf(buf, "%u", &val) == 1) {
if (pm_save_wakeup_count(val))
error = n;
else
pm_print_active_wakeup_sources();
}
out:
pm_autosleep_unlock();
return error;
}
power_attr(wakeup_count);
#ifdef CONFIG_PM_AUTOSLEEP
static ssize_t autosleep_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
suspend_state_t state = pm_autosleep_state();
if (state == PM_SUSPEND_ON)
return sprintf(buf, "off\n");
#ifdef CONFIG_SUSPEND
if (state < PM_SUSPEND_MAX)
return sprintf(buf, "%s\n", pm_states[state] ?
pm_states[state] : "error");
#endif
#ifdef CONFIG_HIBERNATION
return sprintf(buf, "disk\n");
#else
return sprintf(buf, "error");
#endif
}
static ssize_t autosleep_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t n)
{
suspend_state_t state = decode_state(buf, n);
int error;
if (state == PM_SUSPEND_ON
&& strcmp(buf, "off") && strcmp(buf, "off\n"))
return -EINVAL;
error = pm_autosleep_set_state(state);
return error ? error : n;
}
power_attr(autosleep);
#endif /* CONFIG_PM_AUTOSLEEP */
#ifdef CONFIG_PM_WAKELOCKS
static ssize_t wake_lock_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
return pm_show_wakelocks(buf, true);
}
static ssize_t wake_lock_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t n)
{
int error = pm_wake_lock(buf);
return error ? error : n;
}
power_attr(wake_lock);
static ssize_t wake_unlock_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
return pm_show_wakelocks(buf, false);
}
static ssize_t wake_unlock_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t n)
{
int error = pm_wake_unlock(buf);
return error ? error : n;
}
power_attr(wake_unlock);
#endif /* CONFIG_PM_WAKELOCKS */
#endif /* CONFIG_PM_SLEEP */
#ifdef CONFIG_PM_TRACE
int pm_trace_enabled;
static ssize_t pm_trace_show(struct kobject *kobj, struct kobj_attribute *attr,
char *buf)
{
return sprintf(buf, "%d\n", pm_trace_enabled);
}
static ssize_t
pm_trace_store(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t n)
{
int val;
if (sscanf(buf, "%d", &val) == 1) {
pm_trace_enabled = !!val;
if (pm_trace_enabled) {
pr_warn("PM: Enabling pm_trace changes system date and time during resume.\n"
"PM: Correct system time has to be restored manually after resume.\n");
}
return n;
}
return -EINVAL;
}
power_attr(pm_trace);
static ssize_t pm_trace_dev_match_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
return show_trace_dev_match(buf, PAGE_SIZE);
}
power_attr_ro(pm_trace_dev_match);
#endif /* CONFIG_PM_TRACE */
#ifdef CONFIG_FREEZER
static ssize_t pm_freeze_timeout_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return sprintf(buf, "%u\n", freeze_timeout_msecs);
}
static ssize_t pm_freeze_timeout_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t n)
{
unsigned long val;
if (kstrtoul(buf, 10, &val))
return -EINVAL;
freeze_timeout_msecs = val;
return n;
}
power_attr(pm_freeze_timeout);
#endif /* CONFIG_FREEZER*/
static struct attribute * g[] = {
&state_attr.attr,
#ifdef CONFIG_PM_TRACE
&pm_trace_attr.attr,
&pm_trace_dev_match_attr.attr,
#endif
#ifdef CONFIG_PM_SLEEP
&pm_async_attr.attr,
&wakeup_count_attr.attr,
#ifdef CONFIG_PM_AUTOSLEEP
&autosleep_attr.attr,
#endif
#ifdef CONFIG_PM_WAKELOCKS
&wake_lock_attr.attr,
&wake_unlock_attr.attr,
#endif
#ifdef CONFIG_PM_DEBUG
&pm_test_attr.attr,
#endif
#ifdef CONFIG_PM_SLEEP_DEBUG
&pm_print_times_attr.attr,
&pm_wakeup_irq_attr.attr,
#endif
#endif
#ifdef CONFIG_FREEZER
&pm_freeze_timeout_attr.attr,
#endif
NULL,
};
static struct attribute_group attr_group = {
.attrs = g,
};
struct workqueue_struct *pm_wq;
EXPORT_SYMBOL_GPL(pm_wq);
static int __init pm_start_workqueue(void)
{
pm_wq = alloc_workqueue("pm", WQ_FREEZABLE, 0);
return pm_wq ? 0 : -ENOMEM;
}
static int __init pm_init(void)
{
int error = pm_start_workqueue();
if (error)
return error;
hibernate_image_size_init();
hibernate_reserved_size_init();
power_kobj = kobject_create_and_add("power", NULL);
if (!power_kobj)
return -ENOMEM;
error = sysfs_create_group(power_kobj, &attr_group);
if (error)
return error;
pm_print_times_init();
return pm_autosleep_init();
}
core_initcall(pm_init);
| gpl-2.0 |
skeeterslint/linux-2.6.29 | arch/sh/mm/cache-sh3.c | 309 | 2486 | /*
* arch/sh/mm/cache-sh3.c
*
* Copyright (C) 1999, 2000 Niibe Yutaka
* Copyright (C) 2002 Paul Mundt
*
* Released under the terms of the GNU GPL v2.0.
*/
#include <linux/init.h>
#include <linux/mman.h>
#include <linux/mm.h>
#include <linux/threads.h>
#include <asm/addrspace.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/processor.h>
#include <asm/cache.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <asm/pgalloc.h>
#include <asm/mmu_context.h>
#include <asm/cacheflush.h>
/*
* Write back the dirty D-caches, but not invalidate them.
*
* Is this really worth it, or should we just alias this routine
* to __flush_purge_region too?
*
* START: Virtual Address (U0, P1, or P3)
* SIZE: Size of the region.
*/
void __flush_wback_region(void *start, int size)
{
unsigned long v, j;
unsigned long begin, end;
unsigned long flags;
begin = (unsigned long)start & ~(L1_CACHE_BYTES-1);
end = ((unsigned long)start + size + L1_CACHE_BYTES-1)
& ~(L1_CACHE_BYTES-1);
for (v = begin; v < end; v+=L1_CACHE_BYTES) {
unsigned long addrstart = CACHE_OC_ADDRESS_ARRAY;
for (j = 0; j < current_cpu_data.dcache.ways; j++) {
unsigned long data, addr, p;
p = __pa(v);
addr = addrstart | (v & current_cpu_data.dcache.entry_mask);
local_irq_save(flags);
data = ctrl_inl(addr);
if ((data & CACHE_PHYSADDR_MASK) ==
(p & CACHE_PHYSADDR_MASK)) {
data &= ~SH_CACHE_UPDATED;
ctrl_outl(data, addr);
local_irq_restore(flags);
break;
}
local_irq_restore(flags);
addrstart += current_cpu_data.dcache.way_incr;
}
}
}
/*
* Write back the dirty D-caches and invalidate them.
*
* START: Virtual Address (U0, P1, or P3)
* SIZE: Size of the region.
*/
void __flush_purge_region(void *start, int size)
{
unsigned long v;
unsigned long begin, end;
begin = (unsigned long)start & ~(L1_CACHE_BYTES-1);
end = ((unsigned long)start + size + L1_CACHE_BYTES-1)
& ~(L1_CACHE_BYTES-1);
for (v = begin; v < end; v+=L1_CACHE_BYTES) {
unsigned long data, addr;
data = (v & 0xfffffc00); /* _Virtual_ address, ~U, ~V */
addr = CACHE_OC_ADDRESS_ARRAY |
(v & current_cpu_data.dcache.entry_mask) | SH_CACHE_ASSOC;
ctrl_outl(data, addr);
}
}
/*
* No write back please
*
* Except I don't think there's any way to avoid the writeback. So we
* just alias it to __flush_purge_region(). dwmw2.
*/
void __flush_invalidate_region(void *start, int size)
__attribute__((alias("__flush_purge_region")));
| gpl-2.0 |
azhou-nicira/net-next | arch/arm/mach-s3c64xx/mach-crag6410.c | 309 | 21087 | /* linux/arch/arm/mach-s3c64xx/mach-crag6410.c
*
* Copyright 2011 Wolfson Microelectronics plc
* Mark Brown <broonie@opensource.wolfsonmicro.com>
*
* Copyright 2011 Simtec Electronics
* Ben Dooks <ben@simtec.co.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/serial_core.h>
#include <linux/serial_s3c.h>
#include <linux/platform_device.h>
#include <linux/fb.h>
#include <linux/io.h>
#include <linux/init.h>
#include <linux/gpio.h>
#include <linux/leds.h>
#include <linux/delay.h>
#include <linux/mmc/host.h>
#include <linux/regulator/machine.h>
#include <linux/regulator/fixed.h>
#include <linux/pwm_backlight.h>
#include <linux/dm9000.h>
#include <linux/gpio_keys.h>
#include <linux/basic_mmio_gpio.h>
#include <linux/spi/spi.h>
#include <linux/platform_data/pca953x.h>
#include <linux/platform_data/s3c-hsotg.h>
#include <video/platform_lcd.h>
#include <linux/mfd/wm831x/core.h>
#include <linux/mfd/wm831x/pdata.h>
#include <linux/mfd/wm831x/irq.h>
#include <linux/mfd/wm831x/gpio.h>
#include <sound/wm1250-ev1.h>
#include <asm/mach/arch.h>
#include <asm/mach-types.h>
#include <video/samsung_fimd.h>
#include <mach/hardware.h>
#include <mach/map.h>
#include <mach/regs-gpio.h>
#include <mach/gpio-samsung.h>
#include <plat/fb.h>
#include <plat/sdhci.h>
#include <plat/gpio-cfg.h>
#include <linux/platform_data/spi-s3c64xx.h>
#include <plat/keypad.h>
#include <plat/devs.h>
#include <plat/cpu.h>
#include <plat/adc.h>
#include <linux/platform_data/i2c-s3c2410.h>
#include <plat/pm.h>
#include <plat/samsung-time.h>
#include "common.h"
#include "crag6410.h"
#include "regs-gpio-memport.h"
#include "regs-modem.h"
#include "regs-sys.h"
/* serial port setup */
#define UCON (S3C2410_UCON_DEFAULT | S3C2410_UCON_UCLK)
#define ULCON (S3C2410_LCON_CS8 | S3C2410_LCON_PNONE | S3C2410_LCON_STOPB)
#define UFCON (S3C2410_UFCON_RXTRIG8 | S3C2410_UFCON_FIFOMODE)
static struct s3c2410_uartcfg crag6410_uartcfgs[] __initdata = {
[0] = {
.hwport = 0,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
[1] = {
.hwport = 1,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
[2] = {
.hwport = 2,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
[3] = {
.hwport = 3,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
};
static struct platform_pwm_backlight_data crag6410_backlight_data = {
.pwm_id = 0,
.max_brightness = 1000,
.dft_brightness = 600,
.pwm_period_ns = 100000, /* about 1kHz */
.enable_gpio = -1,
};
static struct platform_device crag6410_backlight_device = {
.name = "pwm-backlight",
.id = -1,
.dev = {
.parent = &samsung_device_pwm.dev,
.platform_data = &crag6410_backlight_data,
},
};
static void crag6410_lcd_power_set(struct plat_lcd_data *pd, unsigned int power)
{
pr_debug("%s: setting power %d\n", __func__, power);
if (power) {
gpio_set_value(S3C64XX_GPB(0), 1);
msleep(1);
s3c_gpio_cfgpin(S3C64XX_GPF(14), S3C_GPIO_SFN(2));
} else {
gpio_direction_output(S3C64XX_GPF(14), 0);
gpio_set_value(S3C64XX_GPB(0), 0);
}
}
static struct platform_device crag6410_lcd_powerdev = {
.name = "platform-lcd",
.id = -1,
.dev.parent = &s3c_device_fb.dev,
.dev.platform_data = &(struct plat_lcd_data) {
.set_power = crag6410_lcd_power_set,
},
};
/* 640x480 URT */
static struct s3c_fb_pd_win crag6410_fb_win0 = {
.max_bpp = 32,
.default_bpp = 16,
.xres = 640,
.yres = 480,
.virtual_y = 480 * 2,
.virtual_x = 640,
};
static struct fb_videomode crag6410_lcd_timing = {
.left_margin = 150,
.right_margin = 80,
.upper_margin = 40,
.lower_margin = 5,
.hsync_len = 40,
.vsync_len = 5,
.xres = 640,
.yres = 480,
};
/* 405566 clocks per frame => 60Hz refresh requires 24333960Hz clock */
static struct s3c_fb_platdata crag6410_lcd_pdata = {
.setup_gpio = s3c64xx_fb_gpio_setup_24bpp,
.vtiming = &crag6410_lcd_timing,
.win[0] = &crag6410_fb_win0,
.vidcon0 = VIDCON0_VIDOUT_RGB | VIDCON0_PNRMODE_RGB,
.vidcon1 = VIDCON1_INV_HSYNC | VIDCON1_INV_VSYNC,
};
/* 2x6 keypad */
static uint32_t crag6410_keymap[] = {
/* KEY(row, col, keycode) */
KEY(0, 0, KEY_VOLUMEUP),
KEY(0, 1, KEY_HOME),
KEY(0, 2, KEY_VOLUMEDOWN),
KEY(0, 3, KEY_HELP),
KEY(0, 4, KEY_MENU),
KEY(0, 5, KEY_MEDIA),
KEY(1, 0, 232),
KEY(1, 1, KEY_DOWN),
KEY(1, 2, KEY_LEFT),
KEY(1, 3, KEY_UP),
KEY(1, 4, KEY_RIGHT),
KEY(1, 5, KEY_CAMERA),
};
static struct matrix_keymap_data crag6410_keymap_data = {
.keymap = crag6410_keymap,
.keymap_size = ARRAY_SIZE(crag6410_keymap),
};
static struct samsung_keypad_platdata crag6410_keypad_data = {
.keymap_data = &crag6410_keymap_data,
.rows = 2,
.cols = 6,
};
static struct gpio_keys_button crag6410_gpio_keys[] = {
[0] = {
.code = KEY_SUSPEND,
.gpio = S3C64XX_GPL(10), /* EINT 18 */
.type = EV_KEY,
.wakeup = 1,
.active_low = 1,
},
[1] = {
.code = SW_FRONT_PROXIMITY,
.gpio = S3C64XX_GPN(11), /* EINT 11 */
.type = EV_SW,
},
};
static struct gpio_keys_platform_data crag6410_gpio_keydata = {
.buttons = crag6410_gpio_keys,
.nbuttons = ARRAY_SIZE(crag6410_gpio_keys),
};
static struct platform_device crag6410_gpio_keydev = {
.name = "gpio-keys",
.id = 0,
.dev.platform_data = &crag6410_gpio_keydata,
};
static struct resource crag6410_dm9k_resource[] = {
[0] = DEFINE_RES_MEM(S3C64XX_PA_XM0CSN5, 2),
[1] = DEFINE_RES_MEM(S3C64XX_PA_XM0CSN5 + (1 << 8), 2),
[2] = DEFINE_RES_NAMED(S3C_EINT(17), 1, NULL, IORESOURCE_IRQ \
| IORESOURCE_IRQ_HIGHLEVEL),
};
static struct dm9000_plat_data mini6410_dm9k_pdata = {
.flags = DM9000_PLATF_16BITONLY,
};
static struct platform_device crag6410_dm9k_device = {
.name = "dm9000",
.id = -1,
.num_resources = ARRAY_SIZE(crag6410_dm9k_resource),
.resource = crag6410_dm9k_resource,
.dev.platform_data = &mini6410_dm9k_pdata,
};
static struct resource crag6410_mmgpio_resource[] = {
[0] = DEFINE_RES_MEM_NAMED(S3C64XX_PA_XM0CSN4, 1, "dat"),
};
static struct platform_device crag6410_mmgpio = {
.name = "basic-mmio-gpio",
.id = -1,
.resource = crag6410_mmgpio_resource,
.num_resources = ARRAY_SIZE(crag6410_mmgpio_resource),
.dev.platform_data = &(struct bgpio_pdata) {
.base = MMGPIO_GPIO_BASE,
},
};
static struct platform_device speyside_device = {
.name = "speyside",
.id = -1,
};
static struct platform_device lowland_device = {
.name = "lowland",
.id = -1,
};
static struct platform_device tobermory_device = {
.name = "tobermory",
.id = -1,
};
static struct platform_device littlemill_device = {
.name = "littlemill",
.id = -1,
};
static struct platform_device bells_wm2200_device = {
.name = "bells",
.id = 0,
};
static struct platform_device bells_wm5102_device = {
.name = "bells",
.id = 1,
};
static struct platform_device bells_wm5110_device = {
.name = "bells",
.id = 2,
};
static struct regulator_consumer_supply wallvdd_consumers[] = {
REGULATOR_SUPPLY("SPKVDD", "1-001a"),
REGULATOR_SUPPLY("SPKVDD1", "1-001a"),
REGULATOR_SUPPLY("SPKVDD2", "1-001a"),
REGULATOR_SUPPLY("SPKVDDL", "1-001a"),
REGULATOR_SUPPLY("SPKVDDR", "1-001a"),
REGULATOR_SUPPLY("SPKVDDL", "spi0.1"),
REGULATOR_SUPPLY("SPKVDDR", "spi0.1"),
REGULATOR_SUPPLY("DC1VDD", "0-0034"),
REGULATOR_SUPPLY("DC2VDD", "0-0034"),
REGULATOR_SUPPLY("DC3VDD", "0-0034"),
REGULATOR_SUPPLY("LDO1VDD", "0-0034"),
REGULATOR_SUPPLY("LDO2VDD", "0-0034"),
REGULATOR_SUPPLY("LDO4VDD", "0-0034"),
REGULATOR_SUPPLY("LDO5VDD", "0-0034"),
REGULATOR_SUPPLY("LDO6VDD", "0-0034"),
REGULATOR_SUPPLY("LDO7VDD", "0-0034"),
REGULATOR_SUPPLY("LDO8VDD", "0-0034"),
REGULATOR_SUPPLY("LDO9VDD", "0-0034"),
REGULATOR_SUPPLY("LDO10VDD", "0-0034"),
REGULATOR_SUPPLY("LDO11VDD", "0-0034"),
REGULATOR_SUPPLY("DC1VDD", "1-0034"),
REGULATOR_SUPPLY("DC2VDD", "1-0034"),
REGULATOR_SUPPLY("DC3VDD", "1-0034"),
REGULATOR_SUPPLY("LDO1VDD", "1-0034"),
REGULATOR_SUPPLY("LDO2VDD", "1-0034"),
REGULATOR_SUPPLY("LDO4VDD", "1-0034"),
REGULATOR_SUPPLY("LDO5VDD", "1-0034"),
REGULATOR_SUPPLY("LDO6VDD", "1-0034"),
REGULATOR_SUPPLY("LDO7VDD", "1-0034"),
REGULATOR_SUPPLY("LDO8VDD", "1-0034"),
REGULATOR_SUPPLY("LDO9VDD", "1-0034"),
REGULATOR_SUPPLY("LDO10VDD", "1-0034"),
REGULATOR_SUPPLY("LDO11VDD", "1-0034"),
};
static struct regulator_init_data wallvdd_data = {
.constraints = {
.always_on = 1,
},
.num_consumer_supplies = ARRAY_SIZE(wallvdd_consumers),
.consumer_supplies = wallvdd_consumers,
};
static struct fixed_voltage_config wallvdd_pdata = {
.supply_name = "WALLVDD",
.microvolts = 5000000,
.init_data = &wallvdd_data,
.gpio = -EINVAL,
};
static struct platform_device wallvdd_device = {
.name = "reg-fixed-voltage",
.id = -1,
.dev = {
.platform_data = &wallvdd_pdata,
},
};
static struct platform_device *crag6410_devices[] __initdata = {
&s3c_device_hsmmc0,
&s3c_device_hsmmc2,
&s3c_device_i2c0,
&s3c_device_i2c1,
&s3c_device_fb,
&s3c_device_ohci,
&s3c_device_usb_hsotg,
&samsung_device_pwm,
&s3c64xx_device_iis0,
&s3c64xx_device_iis1,
&samsung_device_keypad,
&crag6410_gpio_keydev,
&crag6410_dm9k_device,
&s3c64xx_device_spi0,
&crag6410_mmgpio,
&crag6410_lcd_powerdev,
&crag6410_backlight_device,
&speyside_device,
&tobermory_device,
&littlemill_device,
&lowland_device,
&bells_wm2200_device,
&bells_wm5102_device,
&bells_wm5110_device,
&wallvdd_device,
};
static struct pca953x_platform_data crag6410_pca_data = {
.gpio_base = PCA935X_GPIO_BASE,
.irq_base = -1,
};
/* VDDARM is controlled by DVS1 connected to GPK(0) */
static struct wm831x_buckv_pdata vddarm_pdata = {
.dvs_control_src = 1,
.dvs_gpio = S3C64XX_GPK(0),
};
static struct regulator_consumer_supply vddarm_consumers[] = {
REGULATOR_SUPPLY("vddarm", NULL),
};
static struct regulator_init_data vddarm = {
.constraints = {
.name = "VDDARM",
.min_uV = 1000000,
.max_uV = 1300000,
.always_on = 1,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE,
},
.num_consumer_supplies = ARRAY_SIZE(vddarm_consumers),
.consumer_supplies = vddarm_consumers,
.supply_regulator = "WALLVDD",
.driver_data = &vddarm_pdata,
};
static struct regulator_consumer_supply vddint_consumers[] = {
REGULATOR_SUPPLY("vddint", NULL),
};
static struct regulator_init_data vddint = {
.constraints = {
.name = "VDDINT",
.min_uV = 1000000,
.max_uV = 1200000,
.always_on = 1,
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE,
},
.num_consumer_supplies = ARRAY_SIZE(vddint_consumers),
.consumer_supplies = vddint_consumers,
.supply_regulator = "WALLVDD",
};
static struct regulator_init_data vddmem = {
.constraints = {
.name = "VDDMEM",
.always_on = 1,
},
};
static struct regulator_init_data vddsys = {
.constraints = {
.name = "VDDSYS,VDDEXT,VDDPCM,VDDSS",
.always_on = 1,
},
};
static struct regulator_consumer_supply vddmmc_consumers[] = {
REGULATOR_SUPPLY("vmmc", "s3c-sdhci.0"),
REGULATOR_SUPPLY("vmmc", "s3c-sdhci.1"),
REGULATOR_SUPPLY("vmmc", "s3c-sdhci.2"),
};
static struct regulator_init_data vddmmc = {
.constraints = {
.name = "VDDMMC,UH",
.always_on = 1,
},
.num_consumer_supplies = ARRAY_SIZE(vddmmc_consumers),
.consumer_supplies = vddmmc_consumers,
.supply_regulator = "WALLVDD",
};
static struct regulator_init_data vddotgi = {
.constraints = {
.name = "VDDOTGi",
.always_on = 1,
},
.supply_regulator = "WALLVDD",
};
static struct regulator_init_data vddotg = {
.constraints = {
.name = "VDDOTG",
.always_on = 1,
},
.supply_regulator = "WALLVDD",
};
static struct regulator_init_data vddhi = {
.constraints = {
.name = "VDDHI",
.always_on = 1,
},
.supply_regulator = "WALLVDD",
};
static struct regulator_init_data vddadc = {
.constraints = {
.name = "VDDADC,VDDDAC",
.always_on = 1,
},
.supply_regulator = "WALLVDD",
};
static struct regulator_init_data vddmem0 = {
.constraints = {
.name = "VDDMEM0",
.always_on = 1,
},
.supply_regulator = "WALLVDD",
};
static struct regulator_init_data vddpll = {
.constraints = {
.name = "VDDPLL",
.always_on = 1,
},
.supply_regulator = "WALLVDD",
};
static struct regulator_init_data vddlcd = {
.constraints = {
.name = "VDDLCD",
.always_on = 1,
},
.supply_regulator = "WALLVDD",
};
static struct regulator_init_data vddalive = {
.constraints = {
.name = "VDDALIVE",
.always_on = 1,
},
.supply_regulator = "WALLVDD",
};
static struct wm831x_backup_pdata banff_backup_pdata = {
.charger_enable = 1,
.vlim = 2500, /* mV */
.ilim = 200, /* uA */
};
static struct wm831x_status_pdata banff_red_led = {
.name = "banff:red:",
.default_src = WM831X_STATUS_MANUAL,
};
static struct wm831x_status_pdata banff_green_led = {
.name = "banff:green:",
.default_src = WM831X_STATUS_MANUAL,
};
static struct wm831x_touch_pdata touch_pdata = {
.data_irq = S3C_EINT(26),
.pd_irq = S3C_EINT(27),
};
static struct wm831x_pdata crag_pmic_pdata = {
.wm831x_num = 1,
.gpio_base = BANFF_PMIC_GPIO_BASE,
.soft_shutdown = true,
.backup = &banff_backup_pdata,
.gpio_defaults = {
/* GPIO5: DVS1_REQ - CMOS, DBVDD, active high */
[4] = WM831X_GPN_DIR | WM831X_GPN_POL | WM831X_GPN_ENA | 0x8,
/* GPIO11: Touchscreen data - CMOS, DBVDD, active high*/
[10] = WM831X_GPN_POL | WM831X_GPN_ENA | 0x6,
/* GPIO12: Touchscreen pen down - CMOS, DBVDD, active high*/
[11] = WM831X_GPN_POL | WM831X_GPN_ENA | 0x7,
},
.dcdc = {
&vddarm, /* DCDC1 */
&vddint, /* DCDC2 */
&vddmem, /* DCDC3 */
},
.ldo = {
&vddsys, /* LDO1 */
&vddmmc, /* LDO2 */
NULL, /* LDO3 */
&vddotgi, /* LDO4 */
&vddotg, /* LDO5 */
&vddhi, /* LDO6 */
&vddadc, /* LDO7 */
&vddmem0, /* LDO8 */
&vddpll, /* LDO9 */
&vddlcd, /* LDO10 */
&vddalive, /* LDO11 */
},
.status = {
&banff_green_led,
&banff_red_led,
},
.touch = &touch_pdata,
};
static struct i2c_board_info i2c_devs0[] = {
{ I2C_BOARD_INFO("24c08", 0x50), },
{ I2C_BOARD_INFO("tca6408", 0x20),
.platform_data = &crag6410_pca_data,
},
{ I2C_BOARD_INFO("wm8312", 0x34),
.platform_data = &crag_pmic_pdata,
.irq = S3C_EINT(23),
},
};
static struct s3c2410_platform_i2c i2c0_pdata = {
.frequency = 400000,
};
static struct regulator_consumer_supply pvdd_1v2_consumers[] = {
REGULATOR_SUPPLY("DCVDD", "spi0.0"),
REGULATOR_SUPPLY("AVDD", "spi0.0"),
REGULATOR_SUPPLY("AVDD", "spi0.1"),
};
static struct regulator_init_data pvdd_1v2 = {
.constraints = {
.name = "PVDD_1V2",
.valid_ops_mask = REGULATOR_CHANGE_STATUS,
},
.consumer_supplies = pvdd_1v2_consumers,
.num_consumer_supplies = ARRAY_SIZE(pvdd_1v2_consumers),
};
static struct regulator_consumer_supply pvdd_1v8_consumers[] = {
REGULATOR_SUPPLY("LDOVDD", "1-001a"),
REGULATOR_SUPPLY("PLLVDD", "1-001a"),
REGULATOR_SUPPLY("DBVDD", "1-001a"),
REGULATOR_SUPPLY("DBVDD1", "1-001a"),
REGULATOR_SUPPLY("DBVDD2", "1-001a"),
REGULATOR_SUPPLY("DBVDD3", "1-001a"),
REGULATOR_SUPPLY("CPVDD", "1-001a"),
REGULATOR_SUPPLY("AVDD2", "1-001a"),
REGULATOR_SUPPLY("DCVDD", "1-001a"),
REGULATOR_SUPPLY("AVDD", "1-001a"),
REGULATOR_SUPPLY("DBVDD", "spi0.0"),
REGULATOR_SUPPLY("DBVDD", "1-003a"),
REGULATOR_SUPPLY("LDOVDD", "1-003a"),
REGULATOR_SUPPLY("CPVDD", "1-003a"),
REGULATOR_SUPPLY("AVDD", "1-003a"),
REGULATOR_SUPPLY("DBVDD1", "spi0.1"),
REGULATOR_SUPPLY("DBVDD2", "spi0.1"),
REGULATOR_SUPPLY("DBVDD3", "spi0.1"),
REGULATOR_SUPPLY("LDOVDD", "spi0.1"),
REGULATOR_SUPPLY("CPVDD", "spi0.1"),
};
static struct regulator_init_data pvdd_1v8 = {
.constraints = {
.name = "PVDD_1V8",
.always_on = 1,
},
.consumer_supplies = pvdd_1v8_consumers,
.num_consumer_supplies = ARRAY_SIZE(pvdd_1v8_consumers),
};
static struct regulator_consumer_supply pvdd_3v3_consumers[] = {
REGULATOR_SUPPLY("MICVDD", "1-001a"),
REGULATOR_SUPPLY("AVDD1", "1-001a"),
};
static struct regulator_init_data pvdd_3v3 = {
.constraints = {
.name = "PVDD_3V3",
.always_on = 1,
},
.consumer_supplies = pvdd_3v3_consumers,
.num_consumer_supplies = ARRAY_SIZE(pvdd_3v3_consumers),
};
static struct wm831x_pdata glenfarclas_pmic_pdata = {
.wm831x_num = 2,
.irq_base = GLENFARCLAS_PMIC_IRQ_BASE,
.gpio_base = GLENFARCLAS_PMIC_GPIO_BASE,
.soft_shutdown = true,
.gpio_defaults = {
/* GPIO1-3: IRQ inputs, rising edge triggered, CMOS */
[0] = WM831X_GPN_DIR | WM831X_GPN_POL | WM831X_GPN_ENA,
[1] = WM831X_GPN_DIR | WM831X_GPN_POL | WM831X_GPN_ENA,
[2] = WM831X_GPN_DIR | WM831X_GPN_POL | WM831X_GPN_ENA,
},
.dcdc = {
&pvdd_1v2, /* DCDC1 */
&pvdd_1v8, /* DCDC2 */
&pvdd_3v3, /* DCDC3 */
},
.disable_touch = true,
};
static struct wm1250_ev1_pdata wm1250_ev1_pdata = {
.gpios = {
[WM1250_EV1_GPIO_CLK_ENA] = S3C64XX_GPN(12),
[WM1250_EV1_GPIO_CLK_SEL0] = S3C64XX_GPL(12),
[WM1250_EV1_GPIO_CLK_SEL1] = S3C64XX_GPL(13),
[WM1250_EV1_GPIO_OSR] = S3C64XX_GPL(14),
[WM1250_EV1_GPIO_MASTER] = S3C64XX_GPL(8),
},
};
static struct i2c_board_info i2c_devs1[] = {
{ I2C_BOARD_INFO("wm8311", 0x34),
.irq = S3C_EINT(0),
.platform_data = &glenfarclas_pmic_pdata },
{ I2C_BOARD_INFO("wlf-gf-module", 0x20) },
{ I2C_BOARD_INFO("wlf-gf-module", 0x22) },
{ I2C_BOARD_INFO("wlf-gf-module", 0x24) },
{ I2C_BOARD_INFO("wlf-gf-module", 0x25) },
{ I2C_BOARD_INFO("wlf-gf-module", 0x26) },
{ I2C_BOARD_INFO("wm1250-ev1", 0x27),
.platform_data = &wm1250_ev1_pdata },
};
static struct s3c2410_platform_i2c i2c1_pdata = {
.frequency = 400000,
.bus_num = 1,
};
static void __init crag6410_map_io(void)
{
s3c64xx_init_io(NULL, 0);
s3c64xx_set_xtal_freq(12000000);
s3c24xx_init_uarts(crag6410_uartcfgs, ARRAY_SIZE(crag6410_uartcfgs));
samsung_set_timer_source(SAMSUNG_PWM3, SAMSUNG_PWM4);
/* LCD type and Bypass set by bootloader */
}
static struct s3c_sdhci_platdata crag6410_hsmmc2_pdata = {
.max_width = 4,
.cd_type = S3C_SDHCI_CD_PERMANENT,
.host_caps = MMC_CAP_POWER_OFF_CARD,
};
static void crag6410_cfg_sdhci0(struct platform_device *dev, int width)
{
/* Set all the necessary GPG pins to special-function 2 */
s3c_gpio_cfgrange_nopull(S3C64XX_GPG(0), 2 + width, S3C_GPIO_SFN(2));
/* force card-detected for prototype 0 */
s3c_gpio_setpull(S3C64XX_GPG(6), S3C_GPIO_PULL_DOWN);
}
static struct s3c_sdhci_platdata crag6410_hsmmc0_pdata = {
.max_width = 4,
.cd_type = S3C_SDHCI_CD_INTERNAL,
.cfg_gpio = crag6410_cfg_sdhci0,
.host_caps = MMC_CAP_POWER_OFF_CARD,
};
static const struct gpio_led gpio_leds[] = {
{
.name = "d13:green:",
.gpio = MMGPIO_GPIO_BASE + 0,
.default_state = LEDS_GPIO_DEFSTATE_ON,
},
{
.name = "d14:green:",
.gpio = MMGPIO_GPIO_BASE + 1,
.default_state = LEDS_GPIO_DEFSTATE_ON,
},
{
.name = "d15:green:",
.gpio = MMGPIO_GPIO_BASE + 2,
.default_state = LEDS_GPIO_DEFSTATE_ON,
},
{
.name = "d16:green:",
.gpio = MMGPIO_GPIO_BASE + 3,
.default_state = LEDS_GPIO_DEFSTATE_ON,
},
{
.name = "d17:green:",
.gpio = MMGPIO_GPIO_BASE + 4,
.default_state = LEDS_GPIO_DEFSTATE_ON,
},
{
.name = "d18:green:",
.gpio = MMGPIO_GPIO_BASE + 5,
.default_state = LEDS_GPIO_DEFSTATE_ON,
},
{
.name = "d19:green:",
.gpio = MMGPIO_GPIO_BASE + 6,
.default_state = LEDS_GPIO_DEFSTATE_ON,
},
{
.name = "d20:green:",
.gpio = MMGPIO_GPIO_BASE + 7,
.default_state = LEDS_GPIO_DEFSTATE_ON,
},
};
static const struct gpio_led_platform_data gpio_leds_pdata = {
.leds = gpio_leds,
.num_leds = ARRAY_SIZE(gpio_leds),
};
static struct s3c_hsotg_plat crag6410_hsotg_pdata;
static void __init crag6410_machine_init(void)
{
/* Open drain IRQs need pullups */
s3c_gpio_setpull(S3C64XX_GPM(0), S3C_GPIO_PULL_UP);
s3c_gpio_setpull(S3C64XX_GPN(0), S3C_GPIO_PULL_UP);
gpio_request(S3C64XX_GPB(0), "LCD power");
gpio_direction_output(S3C64XX_GPB(0), 0);
gpio_request(S3C64XX_GPF(14), "LCD PWM");
gpio_direction_output(S3C64XX_GPF(14), 0); /* turn off */
gpio_request(S3C64XX_GPB(1), "SD power");
gpio_direction_output(S3C64XX_GPB(1), 0);
gpio_request(S3C64XX_GPF(10), "nRESETSEL");
gpio_direction_output(S3C64XX_GPF(10), 1);
s3c_sdhci0_set_platdata(&crag6410_hsmmc0_pdata);
s3c_sdhci2_set_platdata(&crag6410_hsmmc2_pdata);
s3c_i2c0_set_platdata(&i2c0_pdata);
s3c_i2c1_set_platdata(&i2c1_pdata);
s3c_fb_set_platdata(&crag6410_lcd_pdata);
s3c_hsotg_set_platdata(&crag6410_hsotg_pdata);
i2c_register_board_info(0, i2c_devs0, ARRAY_SIZE(i2c_devs0));
i2c_register_board_info(1, i2c_devs1, ARRAY_SIZE(i2c_devs1));
samsung_keypad_set_platdata(&crag6410_keypad_data);
s3c64xx_spi0_set_platdata(NULL, 0, 2);
platform_add_devices(crag6410_devices, ARRAY_SIZE(crag6410_devices));
gpio_led_register_device(-1, &gpio_leds_pdata);
regulator_has_full_constraints();
s3c64xx_pm_init();
}
MACHINE_START(WLF_CRAGG_6410, "Wolfson Cragganmore 6410")
/* Maintainer: Mark Brown <broonie@opensource.wolfsonmicro.com> */
.atag_offset = 0x100,
.init_irq = s3c6410_init_irq,
.map_io = crag6410_map_io,
.init_machine = crag6410_machine_init,
.init_time = samsung_timer_init,
.restart = s3c64xx_restart,
MACHINE_END
| gpl-2.0 |
danonbrown/trltetmo-kernel | drivers/message/fusion/mptfc.c | 2613 | 42804 | /*
* linux/drivers/message/fusion/mptfc.c
* For use with LSI PCI chip/adapter(s)
* running LSI Fusion MPT (Message Passing Technology) firmware.
*
* Copyright (c) 1999-2008 LSI Corporation
* (mailto:DL-MPTFusionLinux@lsi.com)
*
*/
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
NO WARRANTY
THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT
LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is
solely responsible for determining the appropriateness of using and
distributing the Program and assumes all risks associated with its
exercise of rights under this Agreement, including but not limited to
the risks and costs of program errors, damage to or loss of data,
programs or equipment, and unavailability or interruption of operations.
DISCLAIMER OF LIABILITY
NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/kdev_t.h>
#include <linux/blkdev.h>
#include <linux/delay.h> /* for mdelay */
#include <linux/interrupt.h> /* needed for in_interrupt() proto */
#include <linux/reboot.h> /* notifier code */
#include <linux/workqueue.h>
#include <linux/sort.h>
#include <linux/slab.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_tcq.h>
#include <scsi/scsi_transport_fc.h>
#include "mptbase.h"
#include "mptscsih.h"
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
#define my_NAME "Fusion MPT FC Host driver"
#define my_VERSION MPT_LINUX_VERSION_COMMON
#define MYNAM "mptfc"
MODULE_AUTHOR(MODULEAUTHOR);
MODULE_DESCRIPTION(my_NAME);
MODULE_LICENSE("GPL");
MODULE_VERSION(my_VERSION);
/* Command line args */
#define MPTFC_DEV_LOSS_TMO (60)
static int mptfc_dev_loss_tmo = MPTFC_DEV_LOSS_TMO; /* reasonable default */
module_param(mptfc_dev_loss_tmo, int, 0);
MODULE_PARM_DESC(mptfc_dev_loss_tmo, " Initial time the driver programs the "
" transport to wait for an rport to "
" return following a device loss event."
" Default=60.");
/* scsi-mid layer global parmeter is max_report_luns, which is 511 */
#define MPTFC_MAX_LUN (16895)
static int max_lun = MPTFC_MAX_LUN;
module_param(max_lun, int, 0);
MODULE_PARM_DESC(max_lun, " max lun, default=16895 ");
static u8 mptfcDoneCtx = MPT_MAX_PROTOCOL_DRIVERS;
static u8 mptfcTaskCtx = MPT_MAX_PROTOCOL_DRIVERS;
static u8 mptfcInternalCtx = MPT_MAX_PROTOCOL_DRIVERS;
static int mptfc_target_alloc(struct scsi_target *starget);
static int mptfc_slave_alloc(struct scsi_device *sdev);
static int mptfc_qcmd(struct Scsi_Host *shost, struct scsi_cmnd *SCpnt);
static void mptfc_target_destroy(struct scsi_target *starget);
static void mptfc_set_rport_loss_tmo(struct fc_rport *rport, uint32_t timeout);
static void mptfc_remove(struct pci_dev *pdev);
static int mptfc_abort(struct scsi_cmnd *SCpnt);
static int mptfc_dev_reset(struct scsi_cmnd *SCpnt);
static int mptfc_bus_reset(struct scsi_cmnd *SCpnt);
static int mptfc_host_reset(struct scsi_cmnd *SCpnt);
static struct scsi_host_template mptfc_driver_template = {
.module = THIS_MODULE,
.proc_name = "mptfc",
.show_info = mptscsih_show_info,
.name = "MPT FC Host",
.info = mptscsih_info,
.queuecommand = mptfc_qcmd,
.target_alloc = mptfc_target_alloc,
.slave_alloc = mptfc_slave_alloc,
.slave_configure = mptscsih_slave_configure,
.target_destroy = mptfc_target_destroy,
.slave_destroy = mptscsih_slave_destroy,
.change_queue_depth = mptscsih_change_queue_depth,
.eh_abort_handler = mptfc_abort,
.eh_device_reset_handler = mptfc_dev_reset,
.eh_bus_reset_handler = mptfc_bus_reset,
.eh_host_reset_handler = mptfc_host_reset,
.bios_param = mptscsih_bios_param,
.can_queue = MPT_FC_CAN_QUEUE,
.this_id = -1,
.sg_tablesize = MPT_SCSI_SG_DEPTH,
.max_sectors = 8192,
.cmd_per_lun = 7,
.use_clustering = ENABLE_CLUSTERING,
.shost_attrs = mptscsih_host_attrs,
};
/****************************************************************************
* Supported hardware
*/
static struct pci_device_id mptfc_pci_table[] = {
{ PCI_VENDOR_ID_LSI_LOGIC, MPI_MANUFACTPAGE_DEVICEID_FC909,
PCI_ANY_ID, PCI_ANY_ID },
{ PCI_VENDOR_ID_LSI_LOGIC, MPI_MANUFACTPAGE_DEVICEID_FC919,
PCI_ANY_ID, PCI_ANY_ID },
{ PCI_VENDOR_ID_LSI_LOGIC, MPI_MANUFACTPAGE_DEVICEID_FC929,
PCI_ANY_ID, PCI_ANY_ID },
{ PCI_VENDOR_ID_LSI_LOGIC, MPI_MANUFACTPAGE_DEVICEID_FC919X,
PCI_ANY_ID, PCI_ANY_ID },
{ PCI_VENDOR_ID_LSI_LOGIC, MPI_MANUFACTPAGE_DEVICEID_FC929X,
PCI_ANY_ID, PCI_ANY_ID },
{ PCI_VENDOR_ID_LSI_LOGIC, MPI_MANUFACTPAGE_DEVICEID_FC939X,
PCI_ANY_ID, PCI_ANY_ID },
{ PCI_VENDOR_ID_LSI_LOGIC, MPI_MANUFACTPAGE_DEVICEID_FC949X,
PCI_ANY_ID, PCI_ANY_ID },
{ PCI_VENDOR_ID_LSI_LOGIC, MPI_MANUFACTPAGE_DEVICEID_FC949E,
PCI_ANY_ID, PCI_ANY_ID },
{ PCI_VENDOR_ID_BROCADE, MPI_MANUFACTPAGE_DEVICEID_FC949E,
PCI_ANY_ID, PCI_ANY_ID },
{0} /* Terminating entry */
};
MODULE_DEVICE_TABLE(pci, mptfc_pci_table);
static struct scsi_transport_template *mptfc_transport_template = NULL;
static struct fc_function_template mptfc_transport_functions = {
.dd_fcrport_size = 8,
.show_host_node_name = 1,
.show_host_port_name = 1,
.show_host_supported_classes = 1,
.show_host_port_id = 1,
.show_rport_supported_classes = 1,
.show_starget_node_name = 1,
.show_starget_port_name = 1,
.show_starget_port_id = 1,
.set_rport_dev_loss_tmo = mptfc_set_rport_loss_tmo,
.show_rport_dev_loss_tmo = 1,
.show_host_supported_speeds = 1,
.show_host_maxframe_size = 1,
.show_host_speed = 1,
.show_host_fabric_name = 1,
.show_host_port_type = 1,
.show_host_port_state = 1,
.show_host_symbolic_name = 1,
};
static int
mptfc_block_error_handler(struct scsi_cmnd *SCpnt,
int (*func)(struct scsi_cmnd *SCpnt),
const char *caller)
{
MPT_SCSI_HOST *hd;
struct scsi_device *sdev = SCpnt->device;
struct Scsi_Host *shost = sdev->host;
struct fc_rport *rport = starget_to_rport(scsi_target(sdev));
unsigned long flags;
int ready;
MPT_ADAPTER *ioc;
int loops = 40; /* seconds */
hd = shost_priv(SCpnt->device->host);
ioc = hd->ioc;
spin_lock_irqsave(shost->host_lock, flags);
while ((ready = fc_remote_port_chkready(rport) >> 16) == DID_IMM_RETRY
|| (loops > 0 && ioc->active == 0)) {
spin_unlock_irqrestore(shost->host_lock, flags);
dfcprintk (ioc, printk(MYIOC_s_DEBUG_FMT
"mptfc_block_error_handler.%d: %d:%d, port status is "
"%x, active flag %d, deferring %s recovery.\n",
ioc->name, ioc->sh->host_no,
SCpnt->device->id, SCpnt->device->lun,
ready, ioc->active, caller));
msleep(1000);
spin_lock_irqsave(shost->host_lock, flags);
loops --;
}
spin_unlock_irqrestore(shost->host_lock, flags);
if (ready == DID_NO_CONNECT || !SCpnt->device->hostdata
|| ioc->active == 0) {
dfcprintk (ioc, printk(MYIOC_s_DEBUG_FMT
"%s.%d: %d:%d, failing recovery, "
"port state %x, active %d, vdevice %p.\n", caller,
ioc->name, ioc->sh->host_no,
SCpnt->device->id, SCpnt->device->lun, ready,
ioc->active, SCpnt->device->hostdata));
return FAILED;
}
dfcprintk (ioc, printk(MYIOC_s_DEBUG_FMT
"%s.%d: %d:%d, executing recovery.\n", caller,
ioc->name, ioc->sh->host_no,
SCpnt->device->id, SCpnt->device->lun));
return (*func)(SCpnt);
}
static int
mptfc_abort(struct scsi_cmnd *SCpnt)
{
return
mptfc_block_error_handler(SCpnt, mptscsih_abort, __func__);
}
static int
mptfc_dev_reset(struct scsi_cmnd *SCpnt)
{
return
mptfc_block_error_handler(SCpnt, mptscsih_dev_reset, __func__);
}
static int
mptfc_bus_reset(struct scsi_cmnd *SCpnt)
{
return
mptfc_block_error_handler(SCpnt, mptscsih_bus_reset, __func__);
}
static int
mptfc_host_reset(struct scsi_cmnd *SCpnt)
{
return
mptfc_block_error_handler(SCpnt, mptscsih_host_reset, __func__);
}
static void
mptfc_set_rport_loss_tmo(struct fc_rport *rport, uint32_t timeout)
{
if (timeout > 0)
rport->dev_loss_tmo = timeout;
else
rport->dev_loss_tmo = mptfc_dev_loss_tmo;
}
static int
mptfc_FcDevPage0_cmp_func(const void *a, const void *b)
{
FCDevicePage0_t **aa = (FCDevicePage0_t **)a;
FCDevicePage0_t **bb = (FCDevicePage0_t **)b;
if ((*aa)->CurrentBus == (*bb)->CurrentBus) {
if ((*aa)->CurrentTargetID == (*bb)->CurrentTargetID)
return 0;
if ((*aa)->CurrentTargetID < (*bb)->CurrentTargetID)
return -1;
return 1;
}
if ((*aa)->CurrentBus < (*bb)->CurrentBus)
return -1;
return 1;
}
static int
mptfc_GetFcDevPage0(MPT_ADAPTER *ioc, int ioc_port,
void(*func)(MPT_ADAPTER *ioc,int channel, FCDevicePage0_t *arg))
{
ConfigPageHeader_t hdr;
CONFIGPARMS cfg;
FCDevicePage0_t *ppage0_alloc, *fc;
dma_addr_t page0_dma;
int data_sz;
int ii;
FCDevicePage0_t *p0_array=NULL, *p_p0;
FCDevicePage0_t **pp0_array=NULL, **p_pp0;
int rc = -ENOMEM;
U32 port_id = 0xffffff;
int num_targ = 0;
int max_bus = ioc->facts.MaxBuses;
int max_targ;
max_targ = (ioc->facts.MaxDevices == 0) ? 256 : ioc->facts.MaxDevices;
data_sz = sizeof(FCDevicePage0_t) * max_bus * max_targ;
p_p0 = p0_array = kzalloc(data_sz, GFP_KERNEL);
if (!p0_array)
goto out;
data_sz = sizeof(FCDevicePage0_t *) * max_bus * max_targ;
p_pp0 = pp0_array = kzalloc(data_sz, GFP_KERNEL);
if (!pp0_array)
goto out;
do {
/* Get FC Device Page 0 header */
hdr.PageVersion = 0;
hdr.PageLength = 0;
hdr.PageNumber = 0;
hdr.PageType = MPI_CONFIG_PAGETYPE_FC_DEVICE;
cfg.cfghdr.hdr = &hdr;
cfg.physAddr = -1;
cfg.action = MPI_CONFIG_ACTION_PAGE_HEADER;
cfg.dir = 0;
cfg.pageAddr = port_id;
cfg.timeout = 0;
if ((rc = mpt_config(ioc, &cfg)) != 0)
break;
if (hdr.PageLength <= 0)
break;
data_sz = hdr.PageLength * 4;
ppage0_alloc = pci_alloc_consistent(ioc->pcidev, data_sz,
&page0_dma);
rc = -ENOMEM;
if (!ppage0_alloc)
break;
cfg.physAddr = page0_dma;
cfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT;
if ((rc = mpt_config(ioc, &cfg)) == 0) {
ppage0_alloc->PortIdentifier =
le32_to_cpu(ppage0_alloc->PortIdentifier);
ppage0_alloc->WWNN.Low =
le32_to_cpu(ppage0_alloc->WWNN.Low);
ppage0_alloc->WWNN.High =
le32_to_cpu(ppage0_alloc->WWNN.High);
ppage0_alloc->WWPN.Low =
le32_to_cpu(ppage0_alloc->WWPN.Low);
ppage0_alloc->WWPN.High =
le32_to_cpu(ppage0_alloc->WWPN.High);
ppage0_alloc->BBCredit =
le16_to_cpu(ppage0_alloc->BBCredit);
ppage0_alloc->MaxRxFrameSize =
le16_to_cpu(ppage0_alloc->MaxRxFrameSize);
port_id = ppage0_alloc->PortIdentifier;
num_targ++;
*p_p0 = *ppage0_alloc; /* save data */
*p_pp0++ = p_p0++; /* save addr */
}
pci_free_consistent(ioc->pcidev, data_sz,
(u8 *) ppage0_alloc, page0_dma);
if (rc != 0)
break;
} while (port_id <= 0xff0000);
if (num_targ) {
/* sort array */
if (num_targ > 1)
sort (pp0_array, num_targ, sizeof(FCDevicePage0_t *),
mptfc_FcDevPage0_cmp_func, NULL);
/* call caller's func for each targ */
for (ii = 0; ii < num_targ; ii++) {
fc = *(pp0_array+ii);
func(ioc, ioc_port, fc);
}
}
out:
kfree(pp0_array);
kfree(p0_array);
return rc;
}
static int
mptfc_generate_rport_ids(FCDevicePage0_t *pg0, struct fc_rport_identifiers *rid)
{
/* not currently usable */
if (pg0->Flags & (MPI_FC_DEVICE_PAGE0_FLAGS_PLOGI_INVALID |
MPI_FC_DEVICE_PAGE0_FLAGS_PRLI_INVALID))
return -1;
if (!(pg0->Flags & MPI_FC_DEVICE_PAGE0_FLAGS_TARGETID_BUS_VALID))
return -1;
if (!(pg0->Protocol & MPI_FC_DEVICE_PAGE0_PROT_FCP_TARGET))
return -1;
/*
* board data structure already normalized to platform endianness
* shifted to avoid unaligned access on 64 bit architecture
*/
rid->node_name = ((u64)pg0->WWNN.High) << 32 | (u64)pg0->WWNN.Low;
rid->port_name = ((u64)pg0->WWPN.High) << 32 | (u64)pg0->WWPN.Low;
rid->port_id = pg0->PortIdentifier;
rid->roles = FC_RPORT_ROLE_UNKNOWN;
return 0;
}
static void
mptfc_register_dev(MPT_ADAPTER *ioc, int channel, FCDevicePage0_t *pg0)
{
struct fc_rport_identifiers rport_ids;
struct fc_rport *rport;
struct mptfc_rport_info *ri;
int new_ri = 1;
u64 pn, nn;
VirtTarget *vtarget;
u32 roles = FC_RPORT_ROLE_UNKNOWN;
if (mptfc_generate_rport_ids(pg0, &rport_ids) < 0)
return;
roles |= FC_RPORT_ROLE_FCP_TARGET;
if (pg0->Protocol & MPI_FC_DEVICE_PAGE0_PROT_FCP_INITIATOR)
roles |= FC_RPORT_ROLE_FCP_INITIATOR;
/* scan list looking for a match */
list_for_each_entry(ri, &ioc->fc_rports, list) {
pn = (u64)ri->pg0.WWPN.High << 32 | (u64)ri->pg0.WWPN.Low;
if (pn == rport_ids.port_name) { /* match */
list_move_tail(&ri->list, &ioc->fc_rports);
new_ri = 0;
break;
}
}
if (new_ri) { /* allocate one */
ri = kzalloc(sizeof(struct mptfc_rport_info), GFP_KERNEL);
if (!ri)
return;
list_add_tail(&ri->list, &ioc->fc_rports);
}
ri->pg0 = *pg0; /* add/update pg0 data */
ri->flags &= ~MPT_RPORT_INFO_FLAGS_MISSING;
/* MPT_RPORT_INFO_FLAGS_REGISTERED - rport not previously deleted */
if (!(ri->flags & MPT_RPORT_INFO_FLAGS_REGISTERED)) {
ri->flags |= MPT_RPORT_INFO_FLAGS_REGISTERED;
rport = fc_remote_port_add(ioc->sh, channel, &rport_ids);
if (rport) {
ri->rport = rport;
if (new_ri) /* may have been reset by user */
rport->dev_loss_tmo = mptfc_dev_loss_tmo;
/*
* if already mapped, remap here. If not mapped,
* target_alloc will allocate vtarget and map,
* slave_alloc will fill in vdevice from vtarget.
*/
if (ri->starget) {
vtarget = ri->starget->hostdata;
if (vtarget) {
vtarget->id = pg0->CurrentTargetID;
vtarget->channel = pg0->CurrentBus;
vtarget->deleted = 0;
}
}
*((struct mptfc_rport_info **)rport->dd_data) = ri;
/* scan will be scheduled once rport becomes a target */
fc_remote_port_rolechg(rport,roles);
pn = (u64)ri->pg0.WWPN.High << 32 | (u64)ri->pg0.WWPN.Low;
nn = (u64)ri->pg0.WWNN.High << 32 | (u64)ri->pg0.WWNN.Low;
dfcprintk (ioc, printk(MYIOC_s_DEBUG_FMT
"mptfc_reg_dev.%d: %x, %llx / %llx, tid %d, "
"rport tid %d, tmo %d\n",
ioc->name,
ioc->sh->host_no,
pg0->PortIdentifier,
(unsigned long long)nn,
(unsigned long long)pn,
pg0->CurrentTargetID,
ri->rport->scsi_target_id,
ri->rport->dev_loss_tmo));
} else {
list_del(&ri->list);
kfree(ri);
ri = NULL;
}
}
}
/*
* OS entry point to allow for host driver to free allocated memory
* Called if no device present or device being unloaded
*/
static void
mptfc_target_destroy(struct scsi_target *starget)
{
struct fc_rport *rport;
struct mptfc_rport_info *ri;
rport = starget_to_rport(starget);
if (rport) {
ri = *((struct mptfc_rport_info **)rport->dd_data);
if (ri) /* better be! */
ri->starget = NULL;
}
if (starget->hostdata)
kfree(starget->hostdata);
starget->hostdata = NULL;
}
/*
* OS entry point to allow host driver to alloc memory
* for each scsi target. Called once per device the bus scan.
* Return non-zero if allocation fails.
*/
static int
mptfc_target_alloc(struct scsi_target *starget)
{
VirtTarget *vtarget;
struct fc_rport *rport;
struct mptfc_rport_info *ri;
int rc;
vtarget = kzalloc(sizeof(VirtTarget), GFP_KERNEL);
if (!vtarget)
return -ENOMEM;
starget->hostdata = vtarget;
rc = -ENODEV;
rport = starget_to_rport(starget);
if (rport) {
ri = *((struct mptfc_rport_info **)rport->dd_data);
if (ri) { /* better be! */
vtarget->id = ri->pg0.CurrentTargetID;
vtarget->channel = ri->pg0.CurrentBus;
ri->starget = starget;
rc = 0;
}
}
if (rc != 0) {
kfree(vtarget);
starget->hostdata = NULL;
}
return rc;
}
/*
* mptfc_dump_lun_info
* @ioc
* @rport
* @sdev
*
*/
static void
mptfc_dump_lun_info(MPT_ADAPTER *ioc, struct fc_rport *rport, struct scsi_device *sdev,
VirtTarget *vtarget)
{
u64 nn, pn;
struct mptfc_rport_info *ri;
ri = *((struct mptfc_rport_info **)rport->dd_data);
pn = (u64)ri->pg0.WWPN.High << 32 | (u64)ri->pg0.WWPN.Low;
nn = (u64)ri->pg0.WWNN.High << 32 | (u64)ri->pg0.WWNN.Low;
dfcprintk (ioc, printk(MYIOC_s_DEBUG_FMT
"mptfc_slv_alloc.%d: num_luns %d, sdev.id %d, "
"CurrentTargetID %d, %x %llx %llx\n",
ioc->name,
sdev->host->host_no,
vtarget->num_luns,
sdev->id, ri->pg0.CurrentTargetID,
ri->pg0.PortIdentifier,
(unsigned long long)pn,
(unsigned long long)nn));
}
/*
* OS entry point to allow host driver to alloc memory
* for each scsi device. Called once per device the bus scan.
* Return non-zero if allocation fails.
* Init memory once per LUN.
*/
static int
mptfc_slave_alloc(struct scsi_device *sdev)
{
MPT_SCSI_HOST *hd;
VirtTarget *vtarget;
VirtDevice *vdevice;
struct scsi_target *starget;
struct fc_rport *rport;
MPT_ADAPTER *ioc;
starget = scsi_target(sdev);
rport = starget_to_rport(starget);
if (!rport || fc_remote_port_chkready(rport))
return -ENXIO;
hd = shost_priv(sdev->host);
ioc = hd->ioc;
vdevice = kzalloc(sizeof(VirtDevice), GFP_KERNEL);
if (!vdevice) {
printk(MYIOC_s_ERR_FMT "slave_alloc kmalloc(%zd) FAILED!\n",
ioc->name, sizeof(VirtDevice));
return -ENOMEM;
}
sdev->hostdata = vdevice;
vtarget = starget->hostdata;
if (vtarget->num_luns == 0) {
vtarget->ioc_id = ioc->id;
vtarget->tflags = MPT_TARGET_FLAGS_Q_YES;
}
vdevice->vtarget = vtarget;
vdevice->lun = sdev->lun;
vtarget->num_luns++;
mptfc_dump_lun_info(ioc, rport, sdev, vtarget);
return 0;
}
static int
mptfc_qcmd_lck(struct scsi_cmnd *SCpnt, void (*done)(struct scsi_cmnd *))
{
struct mptfc_rport_info *ri;
struct fc_rport *rport = starget_to_rport(scsi_target(SCpnt->device));
int err;
VirtDevice *vdevice = SCpnt->device->hostdata;
if (!vdevice || !vdevice->vtarget) {
SCpnt->result = DID_NO_CONNECT << 16;
done(SCpnt);
return 0;
}
err = fc_remote_port_chkready(rport);
if (unlikely(err)) {
SCpnt->result = err;
done(SCpnt);
return 0;
}
/* dd_data is null until finished adding target */
ri = *((struct mptfc_rport_info **)rport->dd_data);
if (unlikely(!ri)) {
SCpnt->result = DID_IMM_RETRY << 16;
done(SCpnt);
return 0;
}
return mptscsih_qcmd(SCpnt,done);
}
static DEF_SCSI_QCMD(mptfc_qcmd)
/*
* mptfc_display_port_link_speed - displaying link speed
* @ioc: Pointer to MPT_ADAPTER structure
* @portnum: IOC Port number
* @pp0dest: port page0 data payload
*
*/
static void
mptfc_display_port_link_speed(MPT_ADAPTER *ioc, int portnum, FCPortPage0_t *pp0dest)
{
u8 old_speed, new_speed, state;
char *old, *new;
if (portnum >= 2)
return;
old_speed = ioc->fc_link_speed[portnum];
new_speed = pp0dest->CurrentSpeed;
state = pp0dest->PortState;
if (state != MPI_FCPORTPAGE0_PORTSTATE_OFFLINE &&
new_speed != MPI_FCPORTPAGE0_CURRENT_SPEED_UKNOWN) {
old = old_speed == MPI_FCPORTPAGE0_CURRENT_SPEED_1GBIT ? "1 Gbps" :
old_speed == MPI_FCPORTPAGE0_CURRENT_SPEED_2GBIT ? "2 Gbps" :
old_speed == MPI_FCPORTPAGE0_CURRENT_SPEED_4GBIT ? "4 Gbps" :
"Unknown";
new = new_speed == MPI_FCPORTPAGE0_CURRENT_SPEED_1GBIT ? "1 Gbps" :
new_speed == MPI_FCPORTPAGE0_CURRENT_SPEED_2GBIT ? "2 Gbps" :
new_speed == MPI_FCPORTPAGE0_CURRENT_SPEED_4GBIT ? "4 Gbps" :
"Unknown";
if (old_speed == 0)
printk(MYIOC_s_NOTE_FMT
"FC Link Established, Speed = %s\n",
ioc->name, new);
else if (old_speed != new_speed)
printk(MYIOC_s_WARN_FMT
"FC Link Speed Change, Old Speed = %s, New Speed = %s\n",
ioc->name, old, new);
ioc->fc_link_speed[portnum] = new_speed;
}
}
/*
* mptfc_GetFcPortPage0 - Fetch FCPort config Page0.
* @ioc: Pointer to MPT_ADAPTER structure
* @portnum: IOC Port number
*
* Return: 0 for success
* -ENOMEM if no memory available
* -EPERM if not allowed due to ISR context
* -EAGAIN if no msg frames currently available
* -EFAULT for non-successful reply or no reply (timeout)
* -EINVAL portnum arg out of range (hardwired to two elements)
*/
static int
mptfc_GetFcPortPage0(MPT_ADAPTER *ioc, int portnum)
{
ConfigPageHeader_t hdr;
CONFIGPARMS cfg;
FCPortPage0_t *ppage0_alloc;
FCPortPage0_t *pp0dest;
dma_addr_t page0_dma;
int data_sz;
int copy_sz;
int rc;
int count = 400;
if (portnum > 1)
return -EINVAL;
/* Get FCPort Page 0 header */
hdr.PageVersion = 0;
hdr.PageLength = 0;
hdr.PageNumber = 0;
hdr.PageType = MPI_CONFIG_PAGETYPE_FC_PORT;
cfg.cfghdr.hdr = &hdr;
cfg.physAddr = -1;
cfg.action = MPI_CONFIG_ACTION_PAGE_HEADER;
cfg.dir = 0;
cfg.pageAddr = portnum;
cfg.timeout = 0;
if ((rc = mpt_config(ioc, &cfg)) != 0)
return rc;
if (hdr.PageLength == 0)
return 0;
data_sz = hdr.PageLength * 4;
rc = -ENOMEM;
ppage0_alloc = (FCPortPage0_t *) pci_alloc_consistent(ioc->pcidev, data_sz, &page0_dma);
if (ppage0_alloc) {
try_again:
memset((u8 *)ppage0_alloc, 0, data_sz);
cfg.physAddr = page0_dma;
cfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT;
if ((rc = mpt_config(ioc, &cfg)) == 0) {
/* save the data */
pp0dest = &ioc->fc_port_page0[portnum];
copy_sz = min_t(int, sizeof(FCPortPage0_t), data_sz);
memcpy(pp0dest, ppage0_alloc, copy_sz);
/*
* Normalize endianness of structure data,
* by byte-swapping all > 1 byte fields!
*/
pp0dest->Flags = le32_to_cpu(pp0dest->Flags);
pp0dest->PortIdentifier = le32_to_cpu(pp0dest->PortIdentifier);
pp0dest->WWNN.Low = le32_to_cpu(pp0dest->WWNN.Low);
pp0dest->WWNN.High = le32_to_cpu(pp0dest->WWNN.High);
pp0dest->WWPN.Low = le32_to_cpu(pp0dest->WWPN.Low);
pp0dest->WWPN.High = le32_to_cpu(pp0dest->WWPN.High);
pp0dest->SupportedServiceClass = le32_to_cpu(pp0dest->SupportedServiceClass);
pp0dest->SupportedSpeeds = le32_to_cpu(pp0dest->SupportedSpeeds);
pp0dest->CurrentSpeed = le32_to_cpu(pp0dest->CurrentSpeed);
pp0dest->MaxFrameSize = le32_to_cpu(pp0dest->MaxFrameSize);
pp0dest->FabricWWNN.Low = le32_to_cpu(pp0dest->FabricWWNN.Low);
pp0dest->FabricWWNN.High = le32_to_cpu(pp0dest->FabricWWNN.High);
pp0dest->FabricWWPN.Low = le32_to_cpu(pp0dest->FabricWWPN.Low);
pp0dest->FabricWWPN.High = le32_to_cpu(pp0dest->FabricWWPN.High);
pp0dest->DiscoveredPortsCount = le32_to_cpu(pp0dest->DiscoveredPortsCount);
pp0dest->MaxInitiators = le32_to_cpu(pp0dest->MaxInitiators);
/*
* if still doing discovery,
* hang loose a while until finished
*/
if ((pp0dest->PortState == MPI_FCPORTPAGE0_PORTSTATE_UNKNOWN) ||
(pp0dest->PortState == MPI_FCPORTPAGE0_PORTSTATE_ONLINE &&
(pp0dest->Flags & MPI_FCPORTPAGE0_FLAGS_ATTACH_TYPE_MASK)
== MPI_FCPORTPAGE0_FLAGS_ATTACH_NO_INIT)) {
if (count-- > 0) {
msleep(100);
goto try_again;
}
printk(MYIOC_s_INFO_FMT "Firmware discovery not"
" complete.\n",
ioc->name);
}
mptfc_display_port_link_speed(ioc, portnum, pp0dest);
}
pci_free_consistent(ioc->pcidev, data_sz, (u8 *) ppage0_alloc, page0_dma);
}
return rc;
}
static int
mptfc_WriteFcPortPage1(MPT_ADAPTER *ioc, int portnum)
{
ConfigPageHeader_t hdr;
CONFIGPARMS cfg;
int rc;
if (portnum > 1)
return -EINVAL;
if (!(ioc->fc_data.fc_port_page1[portnum].data))
return -EINVAL;
/* get fcport page 1 header */
hdr.PageVersion = 0;
hdr.PageLength = 0;
hdr.PageNumber = 1;
hdr.PageType = MPI_CONFIG_PAGETYPE_FC_PORT;
cfg.cfghdr.hdr = &hdr;
cfg.physAddr = -1;
cfg.action = MPI_CONFIG_ACTION_PAGE_HEADER;
cfg.dir = 0;
cfg.pageAddr = portnum;
cfg.timeout = 0;
if ((rc = mpt_config(ioc, &cfg)) != 0)
return rc;
if (hdr.PageLength == 0)
return -ENODEV;
if (hdr.PageLength*4 != ioc->fc_data.fc_port_page1[portnum].pg_sz)
return -EINVAL;
cfg.physAddr = ioc->fc_data.fc_port_page1[portnum].dma;
cfg.action = MPI_CONFIG_ACTION_PAGE_WRITE_CURRENT;
cfg.dir = 1;
rc = mpt_config(ioc, &cfg);
return rc;
}
static int
mptfc_GetFcPortPage1(MPT_ADAPTER *ioc, int portnum)
{
ConfigPageHeader_t hdr;
CONFIGPARMS cfg;
FCPortPage1_t *page1_alloc;
dma_addr_t page1_dma;
int data_sz;
int rc;
if (portnum > 1)
return -EINVAL;
/* get fcport page 1 header */
hdr.PageVersion = 0;
hdr.PageLength = 0;
hdr.PageNumber = 1;
hdr.PageType = MPI_CONFIG_PAGETYPE_FC_PORT;
cfg.cfghdr.hdr = &hdr;
cfg.physAddr = -1;
cfg.action = MPI_CONFIG_ACTION_PAGE_HEADER;
cfg.dir = 0;
cfg.pageAddr = portnum;
cfg.timeout = 0;
if ((rc = mpt_config(ioc, &cfg)) != 0)
return rc;
if (hdr.PageLength == 0)
return -ENODEV;
start_over:
if (ioc->fc_data.fc_port_page1[portnum].data == NULL) {
data_sz = hdr.PageLength * 4;
if (data_sz < sizeof(FCPortPage1_t))
data_sz = sizeof(FCPortPage1_t);
page1_alloc = (FCPortPage1_t *) pci_alloc_consistent(ioc->pcidev,
data_sz,
&page1_dma);
if (!page1_alloc)
return -ENOMEM;
}
else {
page1_alloc = ioc->fc_data.fc_port_page1[portnum].data;
page1_dma = ioc->fc_data.fc_port_page1[portnum].dma;
data_sz = ioc->fc_data.fc_port_page1[portnum].pg_sz;
if (hdr.PageLength * 4 > data_sz) {
ioc->fc_data.fc_port_page1[portnum].data = NULL;
pci_free_consistent(ioc->pcidev, data_sz, (u8 *)
page1_alloc, page1_dma);
goto start_over;
}
}
memset(page1_alloc,0,data_sz);
cfg.physAddr = page1_dma;
cfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT;
if ((rc = mpt_config(ioc, &cfg)) == 0) {
ioc->fc_data.fc_port_page1[portnum].data = page1_alloc;
ioc->fc_data.fc_port_page1[portnum].pg_sz = data_sz;
ioc->fc_data.fc_port_page1[portnum].dma = page1_dma;
}
else {
ioc->fc_data.fc_port_page1[portnum].data = NULL;
pci_free_consistent(ioc->pcidev, data_sz, (u8 *)
page1_alloc, page1_dma);
}
return rc;
}
static void
mptfc_SetFcPortPage1_defaults(MPT_ADAPTER *ioc)
{
int ii;
FCPortPage1_t *pp1;
#define MPTFC_FW_DEVICE_TIMEOUT (1)
#define MPTFC_FW_IO_PEND_TIMEOUT (1)
#define ON_FLAGS (MPI_FCPORTPAGE1_FLAGS_IMMEDIATE_ERROR_REPLY)
#define OFF_FLAGS (MPI_FCPORTPAGE1_FLAGS_VERBOSE_RESCAN_EVENTS)
for (ii=0; ii<ioc->facts.NumberOfPorts; ii++) {
if (mptfc_GetFcPortPage1(ioc, ii) != 0)
continue;
pp1 = ioc->fc_data.fc_port_page1[ii].data;
if ((pp1->InitiatorDeviceTimeout == MPTFC_FW_DEVICE_TIMEOUT)
&& (pp1->InitiatorIoPendTimeout == MPTFC_FW_IO_PEND_TIMEOUT)
&& ((pp1->Flags & ON_FLAGS) == ON_FLAGS)
&& ((pp1->Flags & OFF_FLAGS) == 0))
continue;
pp1->InitiatorDeviceTimeout = MPTFC_FW_DEVICE_TIMEOUT;
pp1->InitiatorIoPendTimeout = MPTFC_FW_IO_PEND_TIMEOUT;
pp1->Flags &= ~OFF_FLAGS;
pp1->Flags |= ON_FLAGS;
mptfc_WriteFcPortPage1(ioc, ii);
}
}
static void
mptfc_init_host_attr(MPT_ADAPTER *ioc,int portnum)
{
unsigned class = 0;
unsigned cos = 0;
unsigned speed;
unsigned port_type;
unsigned port_state;
FCPortPage0_t *pp0;
struct Scsi_Host *sh;
char *sn;
/* don't know what to do as only one scsi (fc) host was allocated */
if (portnum != 0)
return;
pp0 = &ioc->fc_port_page0[portnum];
sh = ioc->sh;
sn = fc_host_symbolic_name(sh);
snprintf(sn, FC_SYMBOLIC_NAME_SIZE, "%s %s%08xh",
ioc->prod_name,
MPT_FW_REV_MAGIC_ID_STRING,
ioc->facts.FWVersion.Word);
fc_host_tgtid_bind_type(sh) = FC_TGTID_BIND_BY_WWPN;
fc_host_maxframe_size(sh) = pp0->MaxFrameSize;
fc_host_node_name(sh) =
(u64)pp0->WWNN.High << 32 | (u64)pp0->WWNN.Low;
fc_host_port_name(sh) =
(u64)pp0->WWPN.High << 32 | (u64)pp0->WWPN.Low;
fc_host_port_id(sh) = pp0->PortIdentifier;
class = pp0->SupportedServiceClass;
if (class & MPI_FCPORTPAGE0_SUPPORT_CLASS_1)
cos |= FC_COS_CLASS1;
if (class & MPI_FCPORTPAGE0_SUPPORT_CLASS_2)
cos |= FC_COS_CLASS2;
if (class & MPI_FCPORTPAGE0_SUPPORT_CLASS_3)
cos |= FC_COS_CLASS3;
fc_host_supported_classes(sh) = cos;
if (pp0->CurrentSpeed == MPI_FCPORTPAGE0_CURRENT_SPEED_1GBIT)
speed = FC_PORTSPEED_1GBIT;
else if (pp0->CurrentSpeed == MPI_FCPORTPAGE0_CURRENT_SPEED_2GBIT)
speed = FC_PORTSPEED_2GBIT;
else if (pp0->CurrentSpeed == MPI_FCPORTPAGE0_CURRENT_SPEED_4GBIT)
speed = FC_PORTSPEED_4GBIT;
else if (pp0->CurrentSpeed == MPI_FCPORTPAGE0_CURRENT_SPEED_10GBIT)
speed = FC_PORTSPEED_10GBIT;
else
speed = FC_PORTSPEED_UNKNOWN;
fc_host_speed(sh) = speed;
speed = 0;
if (pp0->SupportedSpeeds & MPI_FCPORTPAGE0_SUPPORT_1GBIT_SPEED)
speed |= FC_PORTSPEED_1GBIT;
if (pp0->SupportedSpeeds & MPI_FCPORTPAGE0_SUPPORT_2GBIT_SPEED)
speed |= FC_PORTSPEED_2GBIT;
if (pp0->SupportedSpeeds & MPI_FCPORTPAGE0_SUPPORT_4GBIT_SPEED)
speed |= FC_PORTSPEED_4GBIT;
if (pp0->SupportedSpeeds & MPI_FCPORTPAGE0_SUPPORT_10GBIT_SPEED)
speed |= FC_PORTSPEED_10GBIT;
fc_host_supported_speeds(sh) = speed;
port_state = FC_PORTSTATE_UNKNOWN;
if (pp0->PortState == MPI_FCPORTPAGE0_PORTSTATE_ONLINE)
port_state = FC_PORTSTATE_ONLINE;
else if (pp0->PortState == MPI_FCPORTPAGE0_PORTSTATE_OFFLINE)
port_state = FC_PORTSTATE_LINKDOWN;
fc_host_port_state(sh) = port_state;
port_type = FC_PORTTYPE_UNKNOWN;
if (pp0->Flags & MPI_FCPORTPAGE0_FLAGS_ATTACH_POINT_TO_POINT)
port_type = FC_PORTTYPE_PTP;
else if (pp0->Flags & MPI_FCPORTPAGE0_FLAGS_ATTACH_PRIVATE_LOOP)
port_type = FC_PORTTYPE_LPORT;
else if (pp0->Flags & MPI_FCPORTPAGE0_FLAGS_ATTACH_PUBLIC_LOOP)
port_type = FC_PORTTYPE_NLPORT;
else if (pp0->Flags & MPI_FCPORTPAGE0_FLAGS_ATTACH_FABRIC_DIRECT)
port_type = FC_PORTTYPE_NPORT;
fc_host_port_type(sh) = port_type;
fc_host_fabric_name(sh) =
(pp0->Flags & MPI_FCPORTPAGE0_FLAGS_FABRIC_WWN_VALID) ?
(u64) pp0->FabricWWNN.High << 32 | (u64) pp0->FabricWWPN.Low :
(u64)pp0->WWNN.High << 32 | (u64)pp0->WWNN.Low;
}
static void
mptfc_link_status_change(struct work_struct *work)
{
MPT_ADAPTER *ioc =
container_of(work, MPT_ADAPTER, fc_rescan_work);
int ii;
for (ii=0; ii < ioc->facts.NumberOfPorts; ii++)
(void) mptfc_GetFcPortPage0(ioc, ii);
}
static void
mptfc_setup_reset(struct work_struct *work)
{
MPT_ADAPTER *ioc =
container_of(work, MPT_ADAPTER, fc_setup_reset_work);
u64 pn;
struct mptfc_rport_info *ri;
struct scsi_target *starget;
VirtTarget *vtarget;
/* reset about to happen, delete (block) all rports */
list_for_each_entry(ri, &ioc->fc_rports, list) {
if (ri->flags & MPT_RPORT_INFO_FLAGS_REGISTERED) {
ri->flags &= ~MPT_RPORT_INFO_FLAGS_REGISTERED;
fc_remote_port_delete(ri->rport); /* won't sleep */
ri->rport = NULL;
starget = ri->starget;
if (starget) {
vtarget = starget->hostdata;
if (vtarget)
vtarget->deleted = 1;
}
pn = (u64)ri->pg0.WWPN.High << 32 |
(u64)ri->pg0.WWPN.Low;
dfcprintk (ioc, printk(MYIOC_s_DEBUG_FMT
"mptfc_setup_reset.%d: %llx deleted\n",
ioc->name,
ioc->sh->host_no,
(unsigned long long)pn));
}
}
}
static void
mptfc_rescan_devices(struct work_struct *work)
{
MPT_ADAPTER *ioc =
container_of(work, MPT_ADAPTER, fc_rescan_work);
int ii;
u64 pn;
struct mptfc_rport_info *ri;
struct scsi_target *starget;
VirtTarget *vtarget;
/* start by tagging all ports as missing */
list_for_each_entry(ri, &ioc->fc_rports, list) {
if (ri->flags & MPT_RPORT_INFO_FLAGS_REGISTERED) {
ri->flags |= MPT_RPORT_INFO_FLAGS_MISSING;
}
}
/*
* now rescan devices known to adapter,
* will reregister existing rports
*/
for (ii=0; ii < ioc->facts.NumberOfPorts; ii++) {
(void) mptfc_GetFcPortPage0(ioc, ii);
mptfc_init_host_attr(ioc, ii); /* refresh */
mptfc_GetFcDevPage0(ioc, ii, mptfc_register_dev);
}
/* delete devices still missing */
list_for_each_entry(ri, &ioc->fc_rports, list) {
/* if newly missing, delete it */
if (ri->flags & MPT_RPORT_INFO_FLAGS_MISSING) {
ri->flags &= ~(MPT_RPORT_INFO_FLAGS_REGISTERED|
MPT_RPORT_INFO_FLAGS_MISSING);
fc_remote_port_delete(ri->rport); /* won't sleep */
ri->rport = NULL;
starget = ri->starget;
if (starget) {
vtarget = starget->hostdata;
if (vtarget)
vtarget->deleted = 1;
}
pn = (u64)ri->pg0.WWPN.High << 32 |
(u64)ri->pg0.WWPN.Low;
dfcprintk (ioc, printk(MYIOC_s_DEBUG_FMT
"mptfc_rescan.%d: %llx deleted\n",
ioc->name,
ioc->sh->host_no,
(unsigned long long)pn));
}
}
}
static int
mptfc_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
struct Scsi_Host *sh;
MPT_SCSI_HOST *hd;
MPT_ADAPTER *ioc;
unsigned long flags;
int ii;
int numSGE = 0;
int scale;
int ioc_cap;
int error=0;
int r;
if ((r = mpt_attach(pdev,id)) != 0)
return r;
ioc = pci_get_drvdata(pdev);
ioc->DoneCtx = mptfcDoneCtx;
ioc->TaskCtx = mptfcTaskCtx;
ioc->InternalCtx = mptfcInternalCtx;
/* Added sanity check on readiness of the MPT adapter.
*/
if (ioc->last_state != MPI_IOC_STATE_OPERATIONAL) {
printk(MYIOC_s_WARN_FMT
"Skipping because it's not operational!\n",
ioc->name);
error = -ENODEV;
goto out_mptfc_probe;
}
if (!ioc->active) {
printk(MYIOC_s_WARN_FMT "Skipping because it's disabled!\n",
ioc->name);
error = -ENODEV;
goto out_mptfc_probe;
}
/* Sanity check - ensure at least 1 port is INITIATOR capable
*/
ioc_cap = 0;
for (ii=0; ii < ioc->facts.NumberOfPorts; ii++) {
if (ioc->pfacts[ii].ProtocolFlags &
MPI_PORTFACTS_PROTOCOL_INITIATOR)
ioc_cap ++;
}
if (!ioc_cap) {
printk(MYIOC_s_WARN_FMT
"Skipping ioc=%p because SCSI Initiator mode is NOT enabled!\n",
ioc->name, ioc);
return 0;
}
sh = scsi_host_alloc(&mptfc_driver_template, sizeof(MPT_SCSI_HOST));
if (!sh) {
printk(MYIOC_s_WARN_FMT
"Unable to register controller with SCSI subsystem\n",
ioc->name);
error = -1;
goto out_mptfc_probe;
}
spin_lock_init(&ioc->fc_rescan_work_lock);
INIT_WORK(&ioc->fc_rescan_work, mptfc_rescan_devices);
INIT_WORK(&ioc->fc_setup_reset_work, mptfc_setup_reset);
INIT_WORK(&ioc->fc_lsc_work, mptfc_link_status_change);
spin_lock_irqsave(&ioc->FreeQlock, flags);
/* Attach the SCSI Host to the IOC structure
*/
ioc->sh = sh;
sh->io_port = 0;
sh->n_io_port = 0;
sh->irq = 0;
/* set 16 byte cdb's */
sh->max_cmd_len = 16;
sh->max_id = ioc->pfacts->MaxDevices;
sh->max_lun = max_lun;
/* Required entry.
*/
sh->unique_id = ioc->id;
/* Verify that we won't exceed the maximum
* number of chain buffers
* We can optimize: ZZ = req_sz/sizeof(SGE)
* For 32bit SGE's:
* numSGE = 1 + (ZZ-1)*(maxChain -1) + ZZ
* + (req_sz - 64)/sizeof(SGE)
* A slightly different algorithm is required for
* 64bit SGEs.
*/
scale = ioc->req_sz/ioc->SGE_size;
if (ioc->sg_addr_size == sizeof(u64)) {
numSGE = (scale - 1) *
(ioc->facts.MaxChainDepth-1) + scale +
(ioc->req_sz - 60) / ioc->SGE_size;
} else {
numSGE = 1 + (scale - 1) *
(ioc->facts.MaxChainDepth-1) + scale +
(ioc->req_sz - 64) / ioc->SGE_size;
}
if (numSGE < sh->sg_tablesize) {
/* Reset this value */
dprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"Resetting sg_tablesize to %d from %d\n",
ioc->name, numSGE, sh->sg_tablesize));
sh->sg_tablesize = numSGE;
}
spin_unlock_irqrestore(&ioc->FreeQlock, flags);
hd = shost_priv(sh);
hd->ioc = ioc;
/* SCSI needs scsi_cmnd lookup table!
* (with size equal to req_depth*PtrSz!)
*/
ioc->ScsiLookup = kcalloc(ioc->req_depth, sizeof(void *), GFP_ATOMIC);
if (!ioc->ScsiLookup) {
error = -ENOMEM;
goto out_mptfc_probe;
}
spin_lock_init(&ioc->scsi_lookup_lock);
dprintk(ioc, printk(MYIOC_s_DEBUG_FMT "ScsiLookup @ %p\n",
ioc->name, ioc->ScsiLookup));
hd->last_queue_full = 0;
sh->transportt = mptfc_transport_template;
error = scsi_add_host (sh, &ioc->pcidev->dev);
if(error) {
dprintk(ioc, printk(MYIOC_s_ERR_FMT
"scsi_add_host failed\n", ioc->name));
goto out_mptfc_probe;
}
/* initialize workqueue */
snprintf(ioc->fc_rescan_work_q_name, sizeof(ioc->fc_rescan_work_q_name),
"mptfc_wq_%d", sh->host_no);
ioc->fc_rescan_work_q =
create_singlethread_workqueue(ioc->fc_rescan_work_q_name);
if (!ioc->fc_rescan_work_q)
goto out_mptfc_probe;
/*
* Pre-fetch FC port WWN and stuff...
* (FCPortPage0_t stuff)
*/
for (ii=0; ii < ioc->facts.NumberOfPorts; ii++) {
(void) mptfc_GetFcPortPage0(ioc, ii);
}
mptfc_SetFcPortPage1_defaults(ioc);
/*
* scan for rports -
* by doing it via the workqueue, some locking is eliminated
*/
queue_work(ioc->fc_rescan_work_q, &ioc->fc_rescan_work);
flush_workqueue(ioc->fc_rescan_work_q);
return 0;
out_mptfc_probe:
mptscsih_remove(pdev);
return error;
}
static struct pci_driver mptfc_driver = {
.name = "mptfc",
.id_table = mptfc_pci_table,
.probe = mptfc_probe,
.remove = mptfc_remove,
.shutdown = mptscsih_shutdown,
#ifdef CONFIG_PM
.suspend = mptscsih_suspend,
.resume = mptscsih_resume,
#endif
};
static int
mptfc_event_process(MPT_ADAPTER *ioc, EventNotificationReply_t *pEvReply)
{
MPT_SCSI_HOST *hd;
u8 event = le32_to_cpu(pEvReply->Event) & 0xFF;
unsigned long flags;
int rc=1;
if (ioc->bus_type != FC)
return 0;
devtverboseprintk(ioc, printk(MYIOC_s_DEBUG_FMT "MPT event (=%02Xh) routed to SCSI host driver!\n",
ioc->name, event));
if (ioc->sh == NULL ||
((hd = shost_priv(ioc->sh)) == NULL))
return 1;
switch (event) {
case MPI_EVENT_RESCAN:
spin_lock_irqsave(&ioc->fc_rescan_work_lock, flags);
if (ioc->fc_rescan_work_q) {
queue_work(ioc->fc_rescan_work_q,
&ioc->fc_rescan_work);
}
spin_unlock_irqrestore(&ioc->fc_rescan_work_lock, flags);
break;
case MPI_EVENT_LINK_STATUS_CHANGE:
spin_lock_irqsave(&ioc->fc_rescan_work_lock, flags);
if (ioc->fc_rescan_work_q) {
queue_work(ioc->fc_rescan_work_q,
&ioc->fc_lsc_work);
}
spin_unlock_irqrestore(&ioc->fc_rescan_work_lock, flags);
break;
default:
rc = mptscsih_event_process(ioc,pEvReply);
break;
}
return rc;
}
static int
mptfc_ioc_reset(MPT_ADAPTER *ioc, int reset_phase)
{
int rc;
unsigned long flags;
rc = mptscsih_ioc_reset(ioc,reset_phase);
if ((ioc->bus_type != FC) || (!rc))
return rc;
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
": IOC %s_reset routed to FC host driver!\n",ioc->name,
reset_phase==MPT_IOC_SETUP_RESET ? "setup" : (
reset_phase==MPT_IOC_PRE_RESET ? "pre" : "post")));
if (reset_phase == MPT_IOC_SETUP_RESET) {
spin_lock_irqsave(&ioc->fc_rescan_work_lock, flags);
if (ioc->fc_rescan_work_q) {
queue_work(ioc->fc_rescan_work_q,
&ioc->fc_setup_reset_work);
}
spin_unlock_irqrestore(&ioc->fc_rescan_work_lock, flags);
}
else if (reset_phase == MPT_IOC_PRE_RESET) {
}
else { /* MPT_IOC_POST_RESET */
mptfc_SetFcPortPage1_defaults(ioc);
spin_lock_irqsave(&ioc->fc_rescan_work_lock, flags);
if (ioc->fc_rescan_work_q) {
queue_work(ioc->fc_rescan_work_q,
&ioc->fc_rescan_work);
}
spin_unlock_irqrestore(&ioc->fc_rescan_work_lock, flags);
}
return 1;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* mptfc_init - Register MPT adapter(s) as SCSI host(s) with SCSI mid-layer.
*
* Returns 0 for success, non-zero for failure.
*/
static int __init
mptfc_init(void)
{
int error;
show_mptmod_ver(my_NAME, my_VERSION);
/* sanity check module parameters */
if (mptfc_dev_loss_tmo <= 0)
mptfc_dev_loss_tmo = MPTFC_DEV_LOSS_TMO;
mptfc_transport_template =
fc_attach_transport(&mptfc_transport_functions);
if (!mptfc_transport_template)
return -ENODEV;
mptfcDoneCtx = mpt_register(mptscsih_io_done, MPTFC_DRIVER,
"mptscsih_scandv_complete");
mptfcTaskCtx = mpt_register(mptscsih_taskmgmt_complete, MPTFC_DRIVER,
"mptscsih_scandv_complete");
mptfcInternalCtx = mpt_register(mptscsih_scandv_complete, MPTFC_DRIVER,
"mptscsih_scandv_complete");
mpt_event_register(mptfcDoneCtx, mptfc_event_process);
mpt_reset_register(mptfcDoneCtx, mptfc_ioc_reset);
error = pci_register_driver(&mptfc_driver);
if (error)
fc_release_transport(mptfc_transport_template);
return error;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* mptfc_remove - Remove fc infrastructure for devices
* @pdev: Pointer to pci_dev structure
*
*/
static void mptfc_remove(struct pci_dev *pdev)
{
MPT_ADAPTER *ioc = pci_get_drvdata(pdev);
struct mptfc_rport_info *p, *n;
struct workqueue_struct *work_q;
unsigned long flags;
int ii;
/* destroy workqueue */
if ((work_q=ioc->fc_rescan_work_q)) {
spin_lock_irqsave(&ioc->fc_rescan_work_lock, flags);
ioc->fc_rescan_work_q = NULL;
spin_unlock_irqrestore(&ioc->fc_rescan_work_lock, flags);
destroy_workqueue(work_q);
}
fc_remove_host(ioc->sh);
list_for_each_entry_safe(p, n, &ioc->fc_rports, list) {
list_del(&p->list);
kfree(p);
}
for (ii=0; ii<ioc->facts.NumberOfPorts; ii++) {
if (ioc->fc_data.fc_port_page1[ii].data) {
pci_free_consistent(ioc->pcidev,
ioc->fc_data.fc_port_page1[ii].pg_sz,
(u8 *) ioc->fc_data.fc_port_page1[ii].data,
ioc->fc_data.fc_port_page1[ii].dma);
ioc->fc_data.fc_port_page1[ii].data = NULL;
}
}
mptscsih_remove(pdev);
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* mptfc_exit - Unregisters MPT adapter(s)
*
*/
static void __exit
mptfc_exit(void)
{
pci_unregister_driver(&mptfc_driver);
fc_release_transport(mptfc_transport_template);
mpt_reset_deregister(mptfcDoneCtx);
mpt_event_deregister(mptfcDoneCtx);
mpt_deregister(mptfcInternalCtx);
mpt_deregister(mptfcTaskCtx);
mpt_deregister(mptfcDoneCtx);
}
module_init(mptfc_init);
module_exit(mptfc_exit);
| gpl-2.0 |
sembre/kernel_totoro_update3 | common/arch/mips/kernel/sync-r4k.c | 3893 | 3948 | /*
* Count register synchronisation.
*
* All CPUs will have their count registers synchronised to the CPU0 next time
* value. This can cause a small timewarp for CPU0. All other CPU's should
* not have done anything significant (but they may have had interrupts
* enabled briefly - prom_smp_finish() should not be responsible for enabling
* interrupts...)
*
* FIXME: broken for SMTC
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/irqflags.h>
#include <linux/cpumask.h>
#include <asm/r4k-timer.h>
#include <asm/atomic.h>
#include <asm/barrier.h>
#include <asm/mipsregs.h>
static atomic_t __cpuinitdata count_start_flag = ATOMIC_INIT(0);
static atomic_t __cpuinitdata count_count_start = ATOMIC_INIT(0);
static atomic_t __cpuinitdata count_count_stop = ATOMIC_INIT(0);
static atomic_t __cpuinitdata count_reference = ATOMIC_INIT(0);
#define COUNTON 100
#define NR_LOOPS 5
void __cpuinit synchronise_count_master(void)
{
int i;
unsigned long flags;
unsigned int initcount;
int nslaves;
#ifdef CONFIG_MIPS_MT_SMTC
/*
* SMTC needs to synchronise per VPE, not per CPU
* ignore for now
*/
return;
#endif
printk(KERN_INFO "Synchronize counters across %u CPUs: ",
num_online_cpus());
local_irq_save(flags);
/*
* Notify the slaves that it's time to start
*/
atomic_set(&count_reference, read_c0_count());
atomic_set(&count_start_flag, 1);
smp_wmb();
/* Count will be initialised to current timer for all CPU's */
initcount = read_c0_count();
/*
* We loop a few times to get a primed instruction cache,
* then the last pass is more or less synchronised and
* the master and slaves each set their cycle counters to a known
* value all at once. This reduces the chance of having random offsets
* between the processors, and guarantees that the maximum
* delay between the cycle counters is never bigger than
* the latency of information-passing (cachelines) between
* two CPUs.
*/
nslaves = num_online_cpus()-1;
for (i = 0; i < NR_LOOPS; i++) {
/* slaves loop on '!= ncpus' */
while (atomic_read(&count_count_start) != nslaves)
mb();
atomic_set(&count_count_stop, 0);
smp_wmb();
/* this lets the slaves write their count register */
atomic_inc(&count_count_start);
/*
* Everyone initialises count in the last loop:
*/
if (i == NR_LOOPS-1)
write_c0_count(initcount);
/*
* Wait for all slaves to leave the synchronization point:
*/
while (atomic_read(&count_count_stop) != nslaves)
mb();
atomic_set(&count_count_start, 0);
smp_wmb();
atomic_inc(&count_count_stop);
}
/* Arrange for an interrupt in a short while */
write_c0_compare(read_c0_count() + COUNTON);
local_irq_restore(flags);
/*
* i386 code reported the skew here, but the
* count registers were almost certainly out of sync
* so no point in alarming people
*/
printk("done.\n");
}
void __cpuinit synchronise_count_slave(void)
{
int i;
unsigned long flags;
unsigned int initcount;
int ncpus;
#ifdef CONFIG_MIPS_MT_SMTC
/*
* SMTC needs to synchronise per VPE, not per CPU
* ignore for now
*/
return;
#endif
local_irq_save(flags);
/*
* Not every cpu is online at the time this gets called,
* so we first wait for the master to say everyone is ready
*/
while (!atomic_read(&count_start_flag))
mb();
/* Count will be initialised to next expire for all CPU's */
initcount = atomic_read(&count_reference);
ncpus = num_online_cpus();
for (i = 0; i < NR_LOOPS; i++) {
atomic_inc(&count_count_start);
while (atomic_read(&count_count_start) != ncpus)
mb();
/*
* Everyone initialises count in the last loop:
*/
if (i == NR_LOOPS-1)
write_c0_count(initcount);
atomic_inc(&count_count_stop);
while (atomic_read(&count_count_stop) != ncpus)
mb();
}
/* Arrange for an interrupt in a short while */
write_c0_compare(read_c0_count() + COUNTON);
local_irq_restore(flags);
}
#undef NR_LOOPS
| gpl-2.0 |
alquez/HTC-Wildfire-S-Kernel | arch/s390/kernel/compat_signal.c | 3893 | 18245 | /*
* arch/s390/kernel/compat_signal.c
*
* Copyright (C) IBM Corp. 2000,2006
* Author(s): Denis Joseph Barrow (djbarrow@de.ibm.com,barrow_dj@yahoo.com)
* Gerhard Tonn (ton@de.ibm.com)
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* 1997-11-28 Modified for POSIX.1b signals by Richard Henderson
*/
#include <linux/compat.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/errno.h>
#include <linux/wait.h>
#include <linux/ptrace.h>
#include <linux/unistd.h>
#include <linux/stddef.h>
#include <linux/tty.h>
#include <linux/personality.h>
#include <linux/binfmts.h>
#include <asm/ucontext.h>
#include <asm/uaccess.h>
#include <asm/lowcore.h>
#include "compat_linux.h"
#include "compat_ptrace.h"
#include "entry.h"
#define _BLOCKABLE (~(sigmask(SIGKILL) | sigmask(SIGSTOP)))
typedef struct
{
__u8 callee_used_stack[__SIGNAL_FRAMESIZE32];
struct sigcontext32 sc;
_sigregs32 sregs;
int signo;
__u32 gprs_high[NUM_GPRS];
__u8 retcode[S390_SYSCALL_SIZE];
} sigframe32;
typedef struct
{
__u8 callee_used_stack[__SIGNAL_FRAMESIZE32];
__u8 retcode[S390_SYSCALL_SIZE];
compat_siginfo_t info;
struct ucontext32 uc;
__u32 gprs_high[NUM_GPRS];
} rt_sigframe32;
int copy_siginfo_to_user32(compat_siginfo_t __user *to, siginfo_t *from)
{
int err;
if (!access_ok (VERIFY_WRITE, to, sizeof(compat_siginfo_t)))
return -EFAULT;
/* If you change siginfo_t structure, please be sure
this code is fixed accordingly.
It should never copy any pad contained in the structure
to avoid security leaks, but must copy the generic
3 ints plus the relevant union member.
This routine must convert siginfo from 64bit to 32bit as well
at the same time. */
err = __put_user(from->si_signo, &to->si_signo);
err |= __put_user(from->si_errno, &to->si_errno);
err |= __put_user((short)from->si_code, &to->si_code);
if (from->si_code < 0)
err |= __copy_to_user(&to->_sifields._pad, &from->_sifields._pad, SI_PAD_SIZE);
else {
switch (from->si_code >> 16) {
case __SI_RT >> 16: /* This is not generated by the kernel as of now. */
case __SI_MESGQ >> 16:
err |= __put_user(from->si_int, &to->si_int);
/* fallthrough */
case __SI_KILL >> 16:
err |= __put_user(from->si_pid, &to->si_pid);
err |= __put_user(from->si_uid, &to->si_uid);
break;
case __SI_CHLD >> 16:
err |= __put_user(from->si_pid, &to->si_pid);
err |= __put_user(from->si_uid, &to->si_uid);
err |= __put_user(from->si_utime, &to->si_utime);
err |= __put_user(from->si_stime, &to->si_stime);
err |= __put_user(from->si_status, &to->si_status);
break;
case __SI_FAULT >> 16:
err |= __put_user((unsigned long) from->si_addr,
&to->si_addr);
break;
case __SI_POLL >> 16:
err |= __put_user(from->si_band, &to->si_band);
err |= __put_user(from->si_fd, &to->si_fd);
break;
case __SI_TIMER >> 16:
err |= __put_user(from->si_tid, &to->si_tid);
err |= __put_user(from->si_overrun, &to->si_overrun);
err |= __put_user(from->si_int, &to->si_int);
break;
default:
break;
}
}
return err;
}
int copy_siginfo_from_user32(siginfo_t *to, compat_siginfo_t __user *from)
{
int err;
u32 tmp;
if (!access_ok (VERIFY_READ, from, sizeof(compat_siginfo_t)))
return -EFAULT;
err = __get_user(to->si_signo, &from->si_signo);
err |= __get_user(to->si_errno, &from->si_errno);
err |= __get_user(to->si_code, &from->si_code);
if (to->si_code < 0)
err |= __copy_from_user(&to->_sifields._pad, &from->_sifields._pad, SI_PAD_SIZE);
else {
switch (to->si_code >> 16) {
case __SI_RT >> 16: /* This is not generated by the kernel as of now. */
case __SI_MESGQ >> 16:
err |= __get_user(to->si_int, &from->si_int);
/* fallthrough */
case __SI_KILL >> 16:
err |= __get_user(to->si_pid, &from->si_pid);
err |= __get_user(to->si_uid, &from->si_uid);
break;
case __SI_CHLD >> 16:
err |= __get_user(to->si_pid, &from->si_pid);
err |= __get_user(to->si_uid, &from->si_uid);
err |= __get_user(to->si_utime, &from->si_utime);
err |= __get_user(to->si_stime, &from->si_stime);
err |= __get_user(to->si_status, &from->si_status);
break;
case __SI_FAULT >> 16:
err |= __get_user(tmp, &from->si_addr);
to->si_addr = (void __user *)(u64) (tmp & PSW32_ADDR_INSN);
break;
case __SI_POLL >> 16:
err |= __get_user(to->si_band, &from->si_band);
err |= __get_user(to->si_fd, &from->si_fd);
break;
case __SI_TIMER >> 16:
err |= __get_user(to->si_tid, &from->si_tid);
err |= __get_user(to->si_overrun, &from->si_overrun);
err |= __get_user(to->si_int, &from->si_int);
break;
default:
break;
}
}
return err;
}
asmlinkage long
sys32_sigaction(int sig, const struct old_sigaction32 __user *act,
struct old_sigaction32 __user *oact)
{
struct k_sigaction new_ka, old_ka;
unsigned long sa_handler, sa_restorer;
int ret;
if (act) {
compat_old_sigset_t mask;
if (!access_ok(VERIFY_READ, act, sizeof(*act)) ||
__get_user(sa_handler, &act->sa_handler) ||
__get_user(sa_restorer, &act->sa_restorer) ||
__get_user(new_ka.sa.sa_flags, &act->sa_flags) ||
__get_user(mask, &act->sa_mask))
return -EFAULT;
new_ka.sa.sa_handler = (__sighandler_t) sa_handler;
new_ka.sa.sa_restorer = (void (*)(void)) sa_restorer;
siginitset(&new_ka.sa.sa_mask, mask);
}
ret = do_sigaction(sig, act ? &new_ka : NULL, oact ? &old_ka : NULL);
if (!ret && oact) {
sa_handler = (unsigned long) old_ka.sa.sa_handler;
sa_restorer = (unsigned long) old_ka.sa.sa_restorer;
if (!access_ok(VERIFY_WRITE, oact, sizeof(*oact)) ||
__put_user(sa_handler, &oact->sa_handler) ||
__put_user(sa_restorer, &oact->sa_restorer) ||
__put_user(old_ka.sa.sa_flags, &oact->sa_flags) ||
__put_user(old_ka.sa.sa_mask.sig[0], &oact->sa_mask))
return -EFAULT;
}
return ret;
}
asmlinkage long
sys32_rt_sigaction(int sig, const struct sigaction32 __user *act,
struct sigaction32 __user *oact, size_t sigsetsize)
{
struct k_sigaction new_ka, old_ka;
unsigned long sa_handler;
int ret;
compat_sigset_t set32;
/* XXX: Don't preclude handling different sized sigset_t's. */
if (sigsetsize != sizeof(compat_sigset_t))
return -EINVAL;
if (act) {
ret = get_user(sa_handler, &act->sa_handler);
ret |= __copy_from_user(&set32, &act->sa_mask,
sizeof(compat_sigset_t));
switch (_NSIG_WORDS) {
case 4: new_ka.sa.sa_mask.sig[3] = set32.sig[6]
| (((long)set32.sig[7]) << 32);
case 3: new_ka.sa.sa_mask.sig[2] = set32.sig[4]
| (((long)set32.sig[5]) << 32);
case 2: new_ka.sa.sa_mask.sig[1] = set32.sig[2]
| (((long)set32.sig[3]) << 32);
case 1: new_ka.sa.sa_mask.sig[0] = set32.sig[0]
| (((long)set32.sig[1]) << 32);
}
ret |= __get_user(new_ka.sa.sa_flags, &act->sa_flags);
if (ret)
return -EFAULT;
new_ka.sa.sa_handler = (__sighandler_t) sa_handler;
}
ret = do_sigaction(sig, act ? &new_ka : NULL, oact ? &old_ka : NULL);
if (!ret && oact) {
switch (_NSIG_WORDS) {
case 4:
set32.sig[7] = (old_ka.sa.sa_mask.sig[3] >> 32);
set32.sig[6] = old_ka.sa.sa_mask.sig[3];
case 3:
set32.sig[5] = (old_ka.sa.sa_mask.sig[2] >> 32);
set32.sig[4] = old_ka.sa.sa_mask.sig[2];
case 2:
set32.sig[3] = (old_ka.sa.sa_mask.sig[1] >> 32);
set32.sig[2] = old_ka.sa.sa_mask.sig[1];
case 1:
set32.sig[1] = (old_ka.sa.sa_mask.sig[0] >> 32);
set32.sig[0] = old_ka.sa.sa_mask.sig[0];
}
ret = put_user((unsigned long)old_ka.sa.sa_handler, &oact->sa_handler);
ret |= __copy_to_user(&oact->sa_mask, &set32,
sizeof(compat_sigset_t));
ret |= __put_user(old_ka.sa.sa_flags, &oact->sa_flags);
}
return ret;
}
asmlinkage long
sys32_sigaltstack(const stack_t32 __user *uss, stack_t32 __user *uoss)
{
struct pt_regs *regs = task_pt_regs(current);
stack_t kss, koss;
unsigned long ss_sp;
int ret, err = 0;
mm_segment_t old_fs = get_fs();
if (uss) {
if (!access_ok(VERIFY_READ, uss, sizeof(*uss)))
return -EFAULT;
err |= __get_user(ss_sp, &uss->ss_sp);
err |= __get_user(kss.ss_size, &uss->ss_size);
err |= __get_user(kss.ss_flags, &uss->ss_flags);
if (err)
return -EFAULT;
kss.ss_sp = (void __user *) ss_sp;
}
set_fs (KERNEL_DS);
ret = do_sigaltstack((stack_t __force __user *) (uss ? &kss : NULL),
(stack_t __force __user *) (uoss ? &koss : NULL),
regs->gprs[15]);
set_fs (old_fs);
if (!ret && uoss) {
if (!access_ok(VERIFY_WRITE, uoss, sizeof(*uoss)))
return -EFAULT;
ss_sp = (unsigned long) koss.ss_sp;
err |= __put_user(ss_sp, &uoss->ss_sp);
err |= __put_user(koss.ss_size, &uoss->ss_size);
err |= __put_user(koss.ss_flags, &uoss->ss_flags);
if (err)
return -EFAULT;
}
return ret;
}
static int save_sigregs32(struct pt_regs *regs, _sigregs32 __user *sregs)
{
_s390_regs_common32 regs32;
int err, i;
regs32.psw.mask = PSW32_MASK_MERGE(psw32_user_bits,
(__u32)(regs->psw.mask >> 32));
regs32.psw.addr = PSW32_ADDR_AMODE31 | (__u32) regs->psw.addr;
for (i = 0; i < NUM_GPRS; i++)
regs32.gprs[i] = (__u32) regs->gprs[i];
save_access_regs(current->thread.acrs);
memcpy(regs32.acrs, current->thread.acrs, sizeof(regs32.acrs));
err = __copy_to_user(&sregs->regs, ®s32, sizeof(regs32));
if (err)
return err;
save_fp_regs(¤t->thread.fp_regs);
/* s390_fp_regs and _s390_fp_regs32 are the same ! */
return __copy_to_user(&sregs->fpregs, ¤t->thread.fp_regs,
sizeof(_s390_fp_regs32));
}
static int restore_sigregs32(struct pt_regs *regs,_sigregs32 __user *sregs)
{
_s390_regs_common32 regs32;
int err, i;
/* Alwys make any pending restarted system call return -EINTR */
current_thread_info()->restart_block.fn = do_no_restart_syscall;
err = __copy_from_user(®s32, &sregs->regs, sizeof(regs32));
if (err)
return err;
regs->psw.mask = PSW_MASK_MERGE(regs->psw.mask,
(__u64)regs32.psw.mask << 32);
regs->psw.addr = (__u64)(regs32.psw.addr & PSW32_ADDR_INSN);
for (i = 0; i < NUM_GPRS; i++)
regs->gprs[i] = (__u64) regs32.gprs[i];
memcpy(current->thread.acrs, regs32.acrs, sizeof(current->thread.acrs));
restore_access_regs(current->thread.acrs);
err = __copy_from_user(¤t->thread.fp_regs, &sregs->fpregs,
sizeof(_s390_fp_regs32));
current->thread.fp_regs.fpc &= FPC_VALID_MASK;
if (err)
return err;
restore_fp_regs(¤t->thread.fp_regs);
regs->svcnr = 0; /* disable syscall checks */
return 0;
}
static int save_sigregs_gprs_high(struct pt_regs *regs, __u32 __user *uregs)
{
__u32 gprs_high[NUM_GPRS];
int i;
for (i = 0; i < NUM_GPRS; i++)
gprs_high[i] = regs->gprs[i] >> 32;
return __copy_to_user(uregs, &gprs_high, sizeof(gprs_high));
}
static int restore_sigregs_gprs_high(struct pt_regs *regs, __u32 __user *uregs)
{
__u32 gprs_high[NUM_GPRS];
int err, i;
err = __copy_from_user(&gprs_high, uregs, sizeof(gprs_high));
if (err)
return err;
for (i = 0; i < NUM_GPRS; i++)
*(__u32 *)®s->gprs[i] = gprs_high[i];
return 0;
}
asmlinkage long sys32_sigreturn(void)
{
struct pt_regs *regs = task_pt_regs(current);
sigframe32 __user *frame = (sigframe32 __user *)regs->gprs[15];
sigset_t set;
if (!access_ok(VERIFY_READ, frame, sizeof(*frame)))
goto badframe;
if (__copy_from_user(&set.sig, &frame->sc.oldmask, _SIGMASK_COPY_SIZE32))
goto badframe;
sigdelsetmask(&set, ~_BLOCKABLE);
spin_lock_irq(¤t->sighand->siglock);
current->blocked = set;
recalc_sigpending();
spin_unlock_irq(¤t->sighand->siglock);
if (restore_sigregs32(regs, &frame->sregs))
goto badframe;
if (restore_sigregs_gprs_high(regs, frame->gprs_high))
goto badframe;
return regs->gprs[2];
badframe:
force_sig(SIGSEGV, current);
return 0;
}
asmlinkage long sys32_rt_sigreturn(void)
{
struct pt_regs *regs = task_pt_regs(current);
rt_sigframe32 __user *frame = (rt_sigframe32 __user *)regs->gprs[15];
sigset_t set;
stack_t st;
__u32 ss_sp;
int err;
mm_segment_t old_fs = get_fs();
if (!access_ok(VERIFY_READ, frame, sizeof(*frame)))
goto badframe;
if (__copy_from_user(&set, &frame->uc.uc_sigmask, sizeof(set)))
goto badframe;
sigdelsetmask(&set, ~_BLOCKABLE);
spin_lock_irq(¤t->sighand->siglock);
current->blocked = set;
recalc_sigpending();
spin_unlock_irq(¤t->sighand->siglock);
if (restore_sigregs32(regs, &frame->uc.uc_mcontext))
goto badframe;
if (restore_sigregs_gprs_high(regs, frame->gprs_high))
goto badframe;
err = __get_user(ss_sp, &frame->uc.uc_stack.ss_sp);
st.ss_sp = compat_ptr(ss_sp);
err |= __get_user(st.ss_size, &frame->uc.uc_stack.ss_size);
err |= __get_user(st.ss_flags, &frame->uc.uc_stack.ss_flags);
if (err)
goto badframe;
set_fs (KERNEL_DS);
do_sigaltstack((stack_t __force __user *)&st, NULL, regs->gprs[15]);
set_fs (old_fs);
return regs->gprs[2];
badframe:
force_sig(SIGSEGV, current);
return 0;
}
/*
* Set up a signal frame.
*/
/*
* Determine which stack to use..
*/
static inline void __user *
get_sigframe(struct k_sigaction *ka, struct pt_regs * regs, size_t frame_size)
{
unsigned long sp;
/* Default to using normal stack */
sp = (unsigned long) A(regs->gprs[15]);
/* Overflow on alternate signal stack gives SIGSEGV. */
if (on_sig_stack(sp) && !on_sig_stack((sp - frame_size) & -8UL))
return (void __user *) -1UL;
/* This is the X/Open sanctioned signal stack switching. */
if (ka->sa.sa_flags & SA_ONSTACK) {
if (! sas_ss_flags(sp))
sp = current->sas_ss_sp + current->sas_ss_size;
}
/* This is the legacy signal stack switching. */
else if (!user_mode(regs) &&
!(ka->sa.sa_flags & SA_RESTORER) &&
ka->sa.sa_restorer) {
sp = (unsigned long) ka->sa.sa_restorer;
}
return (void __user *)((sp - frame_size) & -8ul);
}
static inline int map_signal(int sig)
{
if (current_thread_info()->exec_domain
&& current_thread_info()->exec_domain->signal_invmap
&& sig < 32)
return current_thread_info()->exec_domain->signal_invmap[sig];
else
return sig;
}
static int setup_frame32(int sig, struct k_sigaction *ka,
sigset_t *set, struct pt_regs * regs)
{
sigframe32 __user *frame = get_sigframe(ka, regs, sizeof(sigframe32));
if (!access_ok(VERIFY_WRITE, frame, sizeof(sigframe32)))
goto give_sigsegv;
if (frame == (void __user *) -1UL)
goto give_sigsegv;
if (__copy_to_user(&frame->sc.oldmask, &set->sig, _SIGMASK_COPY_SIZE32))
goto give_sigsegv;
if (save_sigregs32(regs, &frame->sregs))
goto give_sigsegv;
if (save_sigregs_gprs_high(regs, frame->gprs_high))
goto give_sigsegv;
if (__put_user((unsigned long) &frame->sregs, &frame->sc.sregs))
goto give_sigsegv;
/* Set up to return from userspace. If provided, use a stub
already in userspace. */
if (ka->sa.sa_flags & SA_RESTORER) {
regs->gprs[14] = (__u64) ka->sa.sa_restorer;
} else {
regs->gprs[14] = (__u64) frame->retcode;
if (__put_user(S390_SYSCALL_OPCODE | __NR_sigreturn,
(u16 __user *)(frame->retcode)))
goto give_sigsegv;
}
/* Set up backchain. */
if (__put_user(regs->gprs[15], (unsigned int __user *) frame))
goto give_sigsegv;
/* Set up registers for signal handler */
regs->gprs[15] = (__u64) frame;
regs->psw.addr = (__u64) ka->sa.sa_handler;
regs->gprs[2] = map_signal(sig);
regs->gprs[3] = (__u64) &frame->sc;
/* We forgot to include these in the sigcontext.
To avoid breaking binary compatibility, they are passed as args. */
regs->gprs[4] = current->thread.trap_no;
regs->gprs[5] = current->thread.prot_addr;
/* Place signal number on stack to allow backtrace from handler. */
if (__put_user(regs->gprs[2], (int __user *) &frame->signo))
goto give_sigsegv;
return 0;
give_sigsegv:
force_sigsegv(sig, current);
return -EFAULT;
}
static int setup_rt_frame32(int sig, struct k_sigaction *ka, siginfo_t *info,
sigset_t *set, struct pt_regs * regs)
{
int err = 0;
rt_sigframe32 __user *frame = get_sigframe(ka, regs, sizeof(rt_sigframe32));
if (!access_ok(VERIFY_WRITE, frame, sizeof(rt_sigframe32)))
goto give_sigsegv;
if (frame == (void __user *) -1UL)
goto give_sigsegv;
if (copy_siginfo_to_user32(&frame->info, info))
goto give_sigsegv;
/* Create the ucontext. */
err |= __put_user(UC_EXTENDED, &frame->uc.uc_flags);
err |= __put_user(0, &frame->uc.uc_link);
err |= __put_user(current->sas_ss_sp, &frame->uc.uc_stack.ss_sp);
err |= __put_user(sas_ss_flags(regs->gprs[15]),
&frame->uc.uc_stack.ss_flags);
err |= __put_user(current->sas_ss_size, &frame->uc.uc_stack.ss_size);
err |= save_sigregs32(regs, &frame->uc.uc_mcontext);
err |= save_sigregs_gprs_high(regs, frame->gprs_high);
err |= __copy_to_user(&frame->uc.uc_sigmask, set, sizeof(*set));
if (err)
goto give_sigsegv;
/* Set up to return from userspace. If provided, use a stub
already in userspace. */
if (ka->sa.sa_flags & SA_RESTORER) {
regs->gprs[14] = (__u64) ka->sa.sa_restorer;
} else {
regs->gprs[14] = (__u64) frame->retcode;
err |= __put_user(S390_SYSCALL_OPCODE | __NR_rt_sigreturn,
(u16 __user *)(frame->retcode));
}
/* Set up backchain. */
if (__put_user(regs->gprs[15], (unsigned int __user *) frame))
goto give_sigsegv;
/* Set up registers for signal handler */
regs->gprs[15] = (__u64) frame;
regs->psw.addr = (__u64) ka->sa.sa_handler;
regs->gprs[2] = map_signal(sig);
regs->gprs[3] = (__u64) &frame->info;
regs->gprs[4] = (__u64) &frame->uc;
return 0;
give_sigsegv:
force_sigsegv(sig, current);
return -EFAULT;
}
/*
* OK, we're invoking a handler
*/
int
handle_signal32(unsigned long sig, struct k_sigaction *ka,
siginfo_t *info, sigset_t *oldset, struct pt_regs * regs)
{
int ret;
/* Set up the stack frame */
if (ka->sa.sa_flags & SA_SIGINFO)
ret = setup_rt_frame32(sig, ka, info, oldset, regs);
else
ret = setup_frame32(sig, ka, oldset, regs);
if (ret == 0) {
spin_lock_irq(¤t->sighand->siglock);
sigorsets(¤t->blocked,¤t->blocked,&ka->sa.sa_mask);
if (!(ka->sa.sa_flags & SA_NODEFER))
sigaddset(¤t->blocked,sig);
recalc_sigpending();
spin_unlock_irq(¤t->sighand->siglock);
}
return ret;
}
| gpl-2.0 |
nico202/linux | drivers/pci/pcie/portdrv_acpi.c | 4149 | 1838 | /*
* PCIe Port Native Services Support, ACPI-Related Part
*
* Copyright (C) 2010 Rafael J. Wysocki <rjw@sisk.pl>, Novell Inc.
*
* This file is subject to the terms and conditions of the GNU General Public
* License V2. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/pci.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/acpi.h>
#include <linux/pci-acpi.h>
#include <linux/pcieport_if.h>
#include "aer/aerdrv.h"
#include "../pci.h"
#include "portdrv.h"
/**
* pcie_port_acpi_setup - Request the BIOS to release control of PCIe services.
* @port: PCIe Port service for a root port or event collector.
* @srv_mask: Bit mask of services that can be enabled for @port.
*
* Invoked when @port is identified as a PCIe port device. To avoid conflicts
* with the BIOS PCIe port native services support requires the BIOS to yield
* control of these services to the kernel. The mask of services that the BIOS
* allows to be enabled for @port is written to @srv_mask.
*
* NOTE: It turns out that we cannot do that for individual port services
* separately, because that would make some systems work incorrectly.
*/
int pcie_port_acpi_setup(struct pci_dev *port, int *srv_mask)
{
struct acpi_pci_root *root;
acpi_handle handle;
u32 flags;
if (acpi_pci_disabled)
return 0;
handle = acpi_find_root_bridge_handle(port);
if (!handle)
return -EINVAL;
root = acpi_pci_find_root(handle);
if (!root)
return -ENODEV;
flags = root->osc_control_set;
*srv_mask = PCIE_PORT_SERVICE_VC;
if (flags & OSC_PCI_EXPRESS_NATIVE_HP_CONTROL)
*srv_mask |= PCIE_PORT_SERVICE_HP;
if (flags & OSC_PCI_EXPRESS_PME_CONTROL)
*srv_mask |= PCIE_PORT_SERVICE_PME;
if (flags & OSC_PCI_EXPRESS_AER_CONTROL)
*srv_mask |= PCIE_PORT_SERVICE_AER;
return 0;
}
| gpl-2.0 |
TeamPrimo/android_kernel_htc_primo | drivers/staging/comedi/drivers/s626.c | 5429 | 108790 | /*
comedi/drivers/s626.c
Sensoray s626 Comedi driver
COMEDI - Linux Control and Measurement Device Interface
Copyright (C) 2000 David A. Schleef <ds@schleef.org>
Based on Sensoray Model 626 Linux driver Version 0.2
Copyright (C) 2002-2004 Sensoray Co., 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.
*/
/*
Driver: s626
Description: Sensoray 626 driver
Devices: [Sensoray] 626 (s626)
Authors: Gianluca Palli <gpalli@deis.unibo.it>,
Updated: Fri, 15 Feb 2008 10:28:42 +0000
Status: experimental
Configuration options:
[0] - PCI bus of device (optional)
[1] - PCI slot of device (optional)
If bus/slot is not specified, the first supported
PCI device found will be used.
INSN_CONFIG instructions:
analog input:
none
analog output:
none
digital channel:
s626 has 3 dio subdevices (2,3 and 4) each with 16 i/o channels
supported configuration options:
INSN_CONFIG_DIO_QUERY
COMEDI_INPUT
COMEDI_OUTPUT
encoder:
Every channel must be configured before reading.
Example code
insn.insn=INSN_CONFIG; //configuration instruction
insn.n=1; //number of operation (must be 1)
insn.data=&initialvalue; //initial value loaded into encoder
//during configuration
insn.subdev=5; //encoder subdevice
insn.chanspec=CR_PACK(encoder_channel,0,AREF_OTHER); //encoder_channel
//to configure
comedi_do_insn(cf,&insn); //executing configuration
*/
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include "../comedidev.h"
#include "comedi_pci.h"
#include "comedi_fc.h"
#include "s626.h"
MODULE_AUTHOR("Gianluca Palli <gpalli@deis.unibo.it>");
MODULE_DESCRIPTION("Sensoray 626 Comedi driver module");
MODULE_LICENSE("GPL");
struct s626_board {
const char *name;
int ai_chans;
int ai_bits;
int ao_chans;
int ao_bits;
int dio_chans;
int dio_banks;
int enc_chans;
};
static const struct s626_board s626_boards[] = {
{
.name = "s626",
.ai_chans = S626_ADC_CHANNELS,
.ai_bits = 14,
.ao_chans = S626_DAC_CHANNELS,
.ao_bits = 13,
.dio_chans = S626_DIO_CHANNELS,
.dio_banks = S626_DIO_BANKS,
.enc_chans = S626_ENCODER_CHANNELS,
}
};
#define thisboard ((const struct s626_board *)dev->board_ptr)
#define PCI_VENDOR_ID_S626 0x1131
#define PCI_DEVICE_ID_S626 0x7146
/*
* For devices with vendor:device id == 0x1131:0x7146 you must specify
* also subvendor:subdevice ids, because otherwise it will conflict with
* Philips SAA7146 media/dvb based cards.
*/
static DEFINE_PCI_DEVICE_TABLE(s626_pci_table) = {
{PCI_VENDOR_ID_S626, PCI_DEVICE_ID_S626, 0x6000, 0x0272, 0, 0, 0},
{0}
};
MODULE_DEVICE_TABLE(pci, s626_pci_table);
static int s626_attach(struct comedi_device *dev, struct comedi_devconfig *it);
static int s626_detach(struct comedi_device *dev);
static struct comedi_driver driver_s626 = {
.driver_name = "s626",
.module = THIS_MODULE,
.attach = s626_attach,
.detach = s626_detach,
};
struct s626_private {
struct pci_dev *pdev;
void *base_addr;
int got_regions;
short allocatedBuf;
uint8_t ai_cmd_running; /* ai_cmd is running */
uint8_t ai_continous; /* continous acquisition */
int ai_sample_count; /* number of samples to acquire */
unsigned int ai_sample_timer;
/* time between samples in units of the timer */
int ai_convert_count; /* conversion counter */
unsigned int ai_convert_timer;
/* time between conversion in units of the timer */
uint16_t CounterIntEnabs;
/* Counter interrupt enable mask for MISC2 register. */
uint8_t AdcItems; /* Number of items in ADC poll list. */
struct bufferDMA RPSBuf; /* DMA buffer used to hold ADC (RPS1) program. */
struct bufferDMA ANABuf;
/* DMA buffer used to receive ADC data and hold DAC data. */
uint32_t *pDacWBuf;
/* Pointer to logical adrs of DMA buffer used to hold DAC data. */
uint16_t Dacpol; /* Image of DAC polarity register. */
uint8_t TrimSetpoint[12]; /* Images of TrimDAC setpoints */
uint16_t ChargeEnabled; /* Image of MISC2 Battery */
/* Charge Enabled (0 or WRMISC2_CHARGE_ENABLE). */
uint16_t WDInterval; /* Image of MISC2 watchdog interval control bits. */
uint32_t I2CAdrs;
/* I2C device address for onboard EEPROM (board rev dependent). */
/* short I2Cards; */
unsigned int ao_readback[S626_DAC_CHANNELS];
};
struct dio_private {
uint16_t RDDIn;
uint16_t WRDOut;
uint16_t RDEdgSel;
uint16_t WREdgSel;
uint16_t RDCapSel;
uint16_t WRCapSel;
uint16_t RDCapFlg;
uint16_t RDIntSel;
uint16_t WRIntSel;
};
static struct dio_private dio_private_A = {
.RDDIn = LP_RDDINA,
.WRDOut = LP_WRDOUTA,
.RDEdgSel = LP_RDEDGSELA,
.WREdgSel = LP_WREDGSELA,
.RDCapSel = LP_RDCAPSELA,
.WRCapSel = LP_WRCAPSELA,
.RDCapFlg = LP_RDCAPFLGA,
.RDIntSel = LP_RDINTSELA,
.WRIntSel = LP_WRINTSELA,
};
static struct dio_private dio_private_B = {
.RDDIn = LP_RDDINB,
.WRDOut = LP_WRDOUTB,
.RDEdgSel = LP_RDEDGSELB,
.WREdgSel = LP_WREDGSELB,
.RDCapSel = LP_RDCAPSELB,
.WRCapSel = LP_WRCAPSELB,
.RDCapFlg = LP_RDCAPFLGB,
.RDIntSel = LP_RDINTSELB,
.WRIntSel = LP_WRINTSELB,
};
static struct dio_private dio_private_C = {
.RDDIn = LP_RDDINC,
.WRDOut = LP_WRDOUTC,
.RDEdgSel = LP_RDEDGSELC,
.WREdgSel = LP_WREDGSELC,
.RDCapSel = LP_RDCAPSELC,
.WRCapSel = LP_WRCAPSELC,
.RDCapFlg = LP_RDCAPFLGC,
.RDIntSel = LP_RDINTSELC,
.WRIntSel = LP_WRINTSELC,
};
/* to group dio devices (48 bits mask and data are not allowed ???)
static struct dio_private *dio_private_word[]={
&dio_private_A,
&dio_private_B,
&dio_private_C,
};
*/
#define devpriv ((struct s626_private *)dev->private)
#define diopriv ((struct dio_private *)s->private)
static int __devinit driver_s626_pci_probe(struct pci_dev *dev,
const struct pci_device_id *ent)
{
return comedi_pci_auto_config(dev, driver_s626.driver_name);
}
static void __devexit driver_s626_pci_remove(struct pci_dev *dev)
{
comedi_pci_auto_unconfig(dev);
}
static struct pci_driver driver_s626_pci_driver = {
.id_table = s626_pci_table,
.probe = &driver_s626_pci_probe,
.remove = __devexit_p(&driver_s626_pci_remove)
};
static int __init driver_s626_init_module(void)
{
int retval;
retval = comedi_driver_register(&driver_s626);
if (retval < 0)
return retval;
driver_s626_pci_driver.name = (char *)driver_s626.driver_name;
return pci_register_driver(&driver_s626_pci_driver);
}
static void __exit driver_s626_cleanup_module(void)
{
pci_unregister_driver(&driver_s626_pci_driver);
comedi_driver_unregister(&driver_s626);
}
module_init(driver_s626_init_module);
module_exit(driver_s626_cleanup_module);
/* ioctl routines */
static int s626_ai_insn_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
/* static int s626_ai_rinsn(struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data); */
static int s626_ai_insn_read(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int s626_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
static int s626_ai_cmdtest(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_cmd *cmd);
static int s626_ai_cancel(struct comedi_device *dev,
struct comedi_subdevice *s);
static int s626_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int s626_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int s626_dio_insn_bits(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int s626_dio_insn_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int s626_dio_set_irq(struct comedi_device *dev, unsigned int chan);
static int s626_dio_reset_irq(struct comedi_device *dev, unsigned int gruop,
unsigned int mask);
static int s626_dio_clear_irq(struct comedi_device *dev);
static int s626_enc_insn_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int s626_enc_insn_read(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int s626_enc_insn_write(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int s626_ns_to_timer(int *nanosec, int round_mode);
static int s626_ai_load_polllist(uint8_t *ppl, struct comedi_cmd *cmd);
static int s626_ai_inttrig(struct comedi_device *dev,
struct comedi_subdevice *s, unsigned int trignum);
static irqreturn_t s626_irq_handler(int irq, void *d);
static unsigned int s626_ai_reg_to_uint(int data);
/* static unsigned int s626_uint_to_reg(struct comedi_subdevice *s, int data); */
/* end ioctl routines */
/* internal routines */
static void s626_dio_init(struct comedi_device *dev);
static void ResetADC(struct comedi_device *dev, uint8_t * ppl);
static void LoadTrimDACs(struct comedi_device *dev);
static void WriteTrimDAC(struct comedi_device *dev, uint8_t LogicalChan,
uint8_t DacData);
static uint8_t I2Cread(struct comedi_device *dev, uint8_t addr);
static uint32_t I2Chandshake(struct comedi_device *dev, uint32_t val);
static void SetDAC(struct comedi_device *dev, uint16_t chan, short dacdata);
static void SendDAC(struct comedi_device *dev, uint32_t val);
static void WriteMISC2(struct comedi_device *dev, uint16_t NewImage);
static void DEBItransfer(struct comedi_device *dev);
static uint16_t DEBIread(struct comedi_device *dev, uint16_t addr);
static void DEBIwrite(struct comedi_device *dev, uint16_t addr, uint16_t wdata);
static void DEBIreplace(struct comedi_device *dev, uint16_t addr, uint16_t mask,
uint16_t wdata);
static void CloseDMAB(struct comedi_device *dev, struct bufferDMA *pdma,
size_t bsize);
/* COUNTER OBJECT ------------------------------------------------ */
struct enc_private {
/* Pointers to functions that differ for A and B counters: */
uint16_t(*GetEnable) (struct comedi_device *dev, struct enc_private *); /* Return clock enable. */
uint16_t(*GetIntSrc) (struct comedi_device *dev, struct enc_private *); /* Return interrupt source. */
uint16_t(*GetLoadTrig) (struct comedi_device *dev, struct enc_private *); /* Return preload trigger source. */
uint16_t(*GetMode) (struct comedi_device *dev, struct enc_private *); /* Return standardized operating mode. */
void (*PulseIndex) (struct comedi_device *dev, struct enc_private *); /* Generate soft index strobe. */
void (*SetEnable) (struct comedi_device *dev, struct enc_private *, uint16_t enab); /* Program clock enable. */
void (*SetIntSrc) (struct comedi_device *dev, struct enc_private *, uint16_t IntSource); /* Program interrupt source. */
void (*SetLoadTrig) (struct comedi_device *dev, struct enc_private *, uint16_t Trig); /* Program preload trigger source. */
void (*SetMode) (struct comedi_device *dev, struct enc_private *, uint16_t Setup, uint16_t DisableIntSrc); /* Program standardized operating mode. */
void (*ResetCapFlags) (struct comedi_device *dev, struct enc_private *); /* Reset event capture flags. */
uint16_t MyCRA; /* Address of CRA register. */
uint16_t MyCRB; /* Address of CRB register. */
uint16_t MyLatchLsw; /* Address of Latch least-significant-word */
/* register. */
uint16_t MyEventBits[4]; /* Bit translations for IntSrc -->RDMISC2. */
};
#define encpriv ((struct enc_private *)(dev->subdevices+5)->private)
/* counters routines */
static void s626_timer_load(struct comedi_device *dev, struct enc_private *k,
int tick);
static uint32_t ReadLatch(struct comedi_device *dev, struct enc_private *k);
static void ResetCapFlags_A(struct comedi_device *dev, struct enc_private *k);
static void ResetCapFlags_B(struct comedi_device *dev, struct enc_private *k);
static uint16_t GetMode_A(struct comedi_device *dev, struct enc_private *k);
static uint16_t GetMode_B(struct comedi_device *dev, struct enc_private *k);
static void SetMode_A(struct comedi_device *dev, struct enc_private *k,
uint16_t Setup, uint16_t DisableIntSrc);
static void SetMode_B(struct comedi_device *dev, struct enc_private *k,
uint16_t Setup, uint16_t DisableIntSrc);
static void SetEnable_A(struct comedi_device *dev, struct enc_private *k,
uint16_t enab);
static void SetEnable_B(struct comedi_device *dev, struct enc_private *k,
uint16_t enab);
static uint16_t GetEnable_A(struct comedi_device *dev, struct enc_private *k);
static uint16_t GetEnable_B(struct comedi_device *dev, struct enc_private *k);
static void SetLatchSource(struct comedi_device *dev, struct enc_private *k,
uint16_t value);
/* static uint16_t GetLatchSource(struct comedi_device *dev, struct enc_private *k ); */
static void SetLoadTrig_A(struct comedi_device *dev, struct enc_private *k,
uint16_t Trig);
static void SetLoadTrig_B(struct comedi_device *dev, struct enc_private *k,
uint16_t Trig);
static uint16_t GetLoadTrig_A(struct comedi_device *dev, struct enc_private *k);
static uint16_t GetLoadTrig_B(struct comedi_device *dev, struct enc_private *k);
static void SetIntSrc_B(struct comedi_device *dev, struct enc_private *k,
uint16_t IntSource);
static void SetIntSrc_A(struct comedi_device *dev, struct enc_private *k,
uint16_t IntSource);
static uint16_t GetIntSrc_A(struct comedi_device *dev, struct enc_private *k);
static uint16_t GetIntSrc_B(struct comedi_device *dev, struct enc_private *k);
/* static void SetClkMult(struct comedi_device *dev, struct enc_private *k, uint16_t value ) ; */
/* static uint16_t GetClkMult(struct comedi_device *dev, struct enc_private *k ) ; */
/* static void SetIndexPol(struct comedi_device *dev, struct enc_private *k, uint16_t value ); */
/* static uint16_t GetClkPol(struct comedi_device *dev, struct enc_private *k ) ; */
/* static void SetIndexSrc( struct comedi_device *dev,struct enc_private *k, uint16_t value ); */
/* static uint16_t GetClkSrc( struct comedi_device *dev,struct enc_private *k ); */
/* static void SetIndexSrc( struct comedi_device *dev,struct enc_private *k, uint16_t value ); */
/* static uint16_t GetIndexSrc( struct comedi_device *dev,struct enc_private *k ); */
static void PulseIndex_A(struct comedi_device *dev, struct enc_private *k);
static void PulseIndex_B(struct comedi_device *dev, struct enc_private *k);
static void Preload(struct comedi_device *dev, struct enc_private *k,
uint32_t value);
static void CountersInit(struct comedi_device *dev);
/* end internal routines */
/* Counter objects constructor. */
/* Counter overflow/index event flag masks for RDMISC2. */
#define INDXMASK(C) (1 << (((C) > 2) ? ((C) * 2 - 1) : ((C) * 2 + 4)))
#define OVERMASK(C) (1 << (((C) > 2) ? ((C) * 2 + 5) : ((C) * 2 + 10)))
#define EVBITS(C) { 0, OVERMASK(C), INDXMASK(C), OVERMASK(C) | INDXMASK(C) }
/* Translation table to map IntSrc into equivalent RDMISC2 event flag bits. */
/* static const uint16_t EventBits[][4] = { EVBITS(0), EVBITS(1), EVBITS(2), EVBITS(3), EVBITS(4), EVBITS(5) }; */
/* struct enc_private; */
static struct enc_private enc_private_data[] = {
{
.GetEnable = GetEnable_A,
.GetIntSrc = GetIntSrc_A,
.GetLoadTrig = GetLoadTrig_A,
.GetMode = GetMode_A,
.PulseIndex = PulseIndex_A,
.SetEnable = SetEnable_A,
.SetIntSrc = SetIntSrc_A,
.SetLoadTrig = SetLoadTrig_A,
.SetMode = SetMode_A,
.ResetCapFlags = ResetCapFlags_A,
.MyCRA = LP_CR0A,
.MyCRB = LP_CR0B,
.MyLatchLsw = LP_CNTR0ALSW,
.MyEventBits = EVBITS(0),
},
{
.GetEnable = GetEnable_A,
.GetIntSrc = GetIntSrc_A,
.GetLoadTrig = GetLoadTrig_A,
.GetMode = GetMode_A,
.PulseIndex = PulseIndex_A,
.SetEnable = SetEnable_A,
.SetIntSrc = SetIntSrc_A,
.SetLoadTrig = SetLoadTrig_A,
.SetMode = SetMode_A,
.ResetCapFlags = ResetCapFlags_A,
.MyCRA = LP_CR1A,
.MyCRB = LP_CR1B,
.MyLatchLsw = LP_CNTR1ALSW,
.MyEventBits = EVBITS(1),
},
{
.GetEnable = GetEnable_A,
.GetIntSrc = GetIntSrc_A,
.GetLoadTrig = GetLoadTrig_A,
.GetMode = GetMode_A,
.PulseIndex = PulseIndex_A,
.SetEnable = SetEnable_A,
.SetIntSrc = SetIntSrc_A,
.SetLoadTrig = SetLoadTrig_A,
.SetMode = SetMode_A,
.ResetCapFlags = ResetCapFlags_A,
.MyCRA = LP_CR2A,
.MyCRB = LP_CR2B,
.MyLatchLsw = LP_CNTR2ALSW,
.MyEventBits = EVBITS(2),
},
{
.GetEnable = GetEnable_B,
.GetIntSrc = GetIntSrc_B,
.GetLoadTrig = GetLoadTrig_B,
.GetMode = GetMode_B,
.PulseIndex = PulseIndex_B,
.SetEnable = SetEnable_B,
.SetIntSrc = SetIntSrc_B,
.SetLoadTrig = SetLoadTrig_B,
.SetMode = SetMode_B,
.ResetCapFlags = ResetCapFlags_B,
.MyCRA = LP_CR0A,
.MyCRB = LP_CR0B,
.MyLatchLsw = LP_CNTR0BLSW,
.MyEventBits = EVBITS(3),
},
{
.GetEnable = GetEnable_B,
.GetIntSrc = GetIntSrc_B,
.GetLoadTrig = GetLoadTrig_B,
.GetMode = GetMode_B,
.PulseIndex = PulseIndex_B,
.SetEnable = SetEnable_B,
.SetIntSrc = SetIntSrc_B,
.SetLoadTrig = SetLoadTrig_B,
.SetMode = SetMode_B,
.ResetCapFlags = ResetCapFlags_B,
.MyCRA = LP_CR1A,
.MyCRB = LP_CR1B,
.MyLatchLsw = LP_CNTR1BLSW,
.MyEventBits = EVBITS(4),
},
{
.GetEnable = GetEnable_B,
.GetIntSrc = GetIntSrc_B,
.GetLoadTrig = GetLoadTrig_B,
.GetMode = GetMode_B,
.PulseIndex = PulseIndex_B,
.SetEnable = SetEnable_B,
.SetIntSrc = SetIntSrc_B,
.SetLoadTrig = SetLoadTrig_B,
.SetMode = SetMode_B,
.ResetCapFlags = ResetCapFlags_B,
.MyCRA = LP_CR2A,
.MyCRB = LP_CR2B,
.MyLatchLsw = LP_CNTR2BLSW,
.MyEventBits = EVBITS(5),
},
};
/* enab/disable a function or test status bit(s) that are accessed */
/* through Main Control Registers 1 or 2. */
#define MC_ENABLE(REGADRS, CTRLWORD) writel(((uint32_t)(CTRLWORD) << 16) | (uint32_t)(CTRLWORD), devpriv->base_addr+(REGADRS))
#define MC_DISABLE(REGADRS, CTRLWORD) writel((uint32_t)(CTRLWORD) << 16 , devpriv->base_addr+(REGADRS))
#define MC_TEST(REGADRS, CTRLWORD) ((readl(devpriv->base_addr+(REGADRS)) & CTRLWORD) != 0)
/* #define WR7146(REGARDS,CTRLWORD)
writel(CTRLWORD,(uint32_t)(devpriv->base_addr+(REGARDS))) */
#define WR7146(REGARDS, CTRLWORD) writel(CTRLWORD, devpriv->base_addr+(REGARDS))
/* #define RR7146(REGARDS)
readl((uint32_t)(devpriv->base_addr+(REGARDS))) */
#define RR7146(REGARDS) readl(devpriv->base_addr+(REGARDS))
#define BUGFIX_STREG(REGADRS) (REGADRS - 4)
/* Write a time slot control record to TSL2. */
#define VECTPORT(VECTNUM) (P_TSL2 + ((VECTNUM) << 2))
#define SETVECT(VECTNUM, VECTVAL) WR7146(VECTPORT(VECTNUM), (VECTVAL))
/* Code macros used for constructing I2C command bytes. */
#define I2C_B2(ATTR, VAL) (((ATTR) << 6) | ((VAL) << 24))
#define I2C_B1(ATTR, VAL) (((ATTR) << 4) | ((VAL) << 16))
#define I2C_B0(ATTR, VAL) (((ATTR) << 2) | ((VAL) << 8))
static const struct comedi_lrange s626_range_table = { 2, {
RANGE(-5, 5),
RANGE(-10, 10),
}
};
static int s626_attach(struct comedi_device *dev, struct comedi_devconfig *it)
{
/* uint8_t PollList; */
/* uint16_t AdcData; */
/* uint16_t StartVal; */
/* uint16_t index; */
/* unsigned int data[16]; */
int result;
int i;
int ret;
resource_size_t resourceStart;
dma_addr_t appdma;
struct comedi_subdevice *s;
const struct pci_device_id *ids;
struct pci_dev *pdev = NULL;
if (alloc_private(dev, sizeof(struct s626_private)) < 0)
return -ENOMEM;
for (i = 0; i < (ARRAY_SIZE(s626_pci_table) - 1) && !pdev; i++) {
ids = &s626_pci_table[i];
do {
pdev = pci_get_subsys(ids->vendor, ids->device,
ids->subvendor, ids->subdevice,
pdev);
if ((it->options[0] || it->options[1]) && pdev) {
/* matches requested bus/slot */
if (pdev->bus->number == it->options[0] &&
PCI_SLOT(pdev->devfn) == it->options[1])
break;
} else
break;
} while (1);
}
devpriv->pdev = pdev;
if (pdev == NULL) {
printk(KERN_ERR "s626_attach: Board not present!!!\n");
return -ENODEV;
}
result = comedi_pci_enable(pdev, "s626");
if (result < 0) {
printk(KERN_ERR "s626_attach: comedi_pci_enable fails\n");
return -ENODEV;
}
devpriv->got_regions = 1;
resourceStart = pci_resource_start(devpriv->pdev, 0);
devpriv->base_addr = ioremap(resourceStart, SIZEOF_ADDRESS_SPACE);
if (devpriv->base_addr == NULL) {
printk(KERN_ERR "s626_attach: IOREMAP failed\n");
return -ENODEV;
}
if (devpriv->base_addr) {
/* disable master interrupt */
writel(0, devpriv->base_addr + P_IER);
/* soft reset */
writel(MC1_SOFT_RESET, devpriv->base_addr + P_MC1);
/* DMA FIXME DMA// */
DEBUG("s626_attach: DMA ALLOCATION\n");
/* adc buffer allocation */
devpriv->allocatedBuf = 0;
devpriv->ANABuf.LogicalBase =
pci_alloc_consistent(devpriv->pdev, DMABUF_SIZE, &appdma);
if (devpriv->ANABuf.LogicalBase == NULL) {
printk(KERN_ERR "s626_attach: DMA Memory mapping error\n");
return -ENOMEM;
}
devpriv->ANABuf.PhysicalBase = appdma;
DEBUG
("s626_attach: AllocDMAB ADC Logical=%p, bsize=%d, Physical=0x%x\n",
devpriv->ANABuf.LogicalBase, DMABUF_SIZE,
(uint32_t) devpriv->ANABuf.PhysicalBase);
devpriv->allocatedBuf++;
devpriv->RPSBuf.LogicalBase =
pci_alloc_consistent(devpriv->pdev, DMABUF_SIZE, &appdma);
if (devpriv->RPSBuf.LogicalBase == NULL) {
printk(KERN_ERR "s626_attach: DMA Memory mapping error\n");
return -ENOMEM;
}
devpriv->RPSBuf.PhysicalBase = appdma;
DEBUG
("s626_attach: AllocDMAB RPS Logical=%p, bsize=%d, Physical=0x%x\n",
devpriv->RPSBuf.LogicalBase, DMABUF_SIZE,
(uint32_t) devpriv->RPSBuf.PhysicalBase);
devpriv->allocatedBuf++;
}
dev->board_ptr = s626_boards;
dev->board_name = thisboard->name;
if (alloc_subdevices(dev, 6) < 0)
return -ENOMEM;
dev->iobase = (unsigned long)devpriv->base_addr;
dev->irq = devpriv->pdev->irq;
/* set up interrupt handler */
if (dev->irq == 0) {
printk(KERN_ERR " unknown irq (bad)\n");
} else {
ret = request_irq(dev->irq, s626_irq_handler, IRQF_SHARED,
"s626", dev);
if (ret < 0) {
printk(KERN_ERR " irq not available\n");
dev->irq = 0;
}
}
DEBUG("s626_attach: -- it opts %d,%d --\n",
it->options[0], it->options[1]);
s = dev->subdevices + 0;
/* analog input subdevice */
dev->read_subdev = s;
/* we support single-ended (ground) and differential */
s->type = COMEDI_SUBD_AI;
s->subdev_flags = SDF_READABLE | SDF_DIFF | SDF_CMD_READ;
s->n_chan = thisboard->ai_chans;
s->maxdata = (0xffff >> 2);
s->range_table = &s626_range_table;
s->len_chanlist = thisboard->ai_chans; /* This is the maximum chanlist
length that the board can
handle */
s->insn_config = s626_ai_insn_config;
s->insn_read = s626_ai_insn_read;
s->do_cmd = s626_ai_cmd;
s->do_cmdtest = s626_ai_cmdtest;
s->cancel = s626_ai_cancel;
s = dev->subdevices + 1;
/* analog output subdevice */
s->type = COMEDI_SUBD_AO;
s->subdev_flags = SDF_WRITABLE | SDF_READABLE;
s->n_chan = thisboard->ao_chans;
s->maxdata = (0x3fff);
s->range_table = &range_bipolar10;
s->insn_write = s626_ao_winsn;
s->insn_read = s626_ao_rinsn;
s = dev->subdevices + 2;
/* digital I/O subdevice */
s->type = COMEDI_SUBD_DIO;
s->subdev_flags = SDF_WRITABLE | SDF_READABLE;
s->n_chan = S626_DIO_CHANNELS;
s->maxdata = 1;
s->io_bits = 0xffff;
s->private = &dio_private_A;
s->range_table = &range_digital;
s->insn_config = s626_dio_insn_config;
s->insn_bits = s626_dio_insn_bits;
s = dev->subdevices + 3;
/* digital I/O subdevice */
s->type = COMEDI_SUBD_DIO;
s->subdev_flags = SDF_WRITABLE | SDF_READABLE;
s->n_chan = 16;
s->maxdata = 1;
s->io_bits = 0xffff;
s->private = &dio_private_B;
s->range_table = &range_digital;
s->insn_config = s626_dio_insn_config;
s->insn_bits = s626_dio_insn_bits;
s = dev->subdevices + 4;
/* digital I/O subdevice */
s->type = COMEDI_SUBD_DIO;
s->subdev_flags = SDF_WRITABLE | SDF_READABLE;
s->n_chan = 16;
s->maxdata = 1;
s->io_bits = 0xffff;
s->private = &dio_private_C;
s->range_table = &range_digital;
s->insn_config = s626_dio_insn_config;
s->insn_bits = s626_dio_insn_bits;
s = dev->subdevices + 5;
/* encoder (counter) subdevice */
s->type = COMEDI_SUBD_COUNTER;
s->subdev_flags = SDF_WRITABLE | SDF_READABLE | SDF_LSAMPL;
s->n_chan = thisboard->enc_chans;
s->private = enc_private_data;
s->insn_config = s626_enc_insn_config;
s->insn_read = s626_enc_insn_read;
s->insn_write = s626_enc_insn_write;
s->maxdata = 0xffffff;
s->range_table = &range_unknown;
/* stop ai_command */
devpriv->ai_cmd_running = 0;
if (devpriv->base_addr && (devpriv->allocatedBuf == 2)) {
dma_addr_t pPhysBuf;
uint16_t chan;
/* enab DEBI and audio pins, enable I2C interface. */
MC_ENABLE(P_MC1, MC1_DEBI | MC1_AUDIO | MC1_I2C);
/* Configure DEBI operating mode. */
WR7146(P_DEBICFG, DEBI_CFG_SLAVE16 /* Local bus is 16 */
/* bits wide. */
| (DEBI_TOUT << DEBI_CFG_TOUT_BIT)
/* Declare DEBI */
/* transfer timeout */
/* interval. */
|DEBI_SWAP /* Set up byte lane */
/* steering. */
| DEBI_CFG_INTEL); /* Intel-compatible */
/* local bus (DEBI */
/* never times out). */
DEBUG("s626_attach: %d debi init -- %d\n",
DEBI_CFG_SLAVE16 | (DEBI_TOUT << DEBI_CFG_TOUT_BIT) |
DEBI_SWAP | DEBI_CFG_INTEL,
DEBI_CFG_INTEL | DEBI_CFG_TOQ | DEBI_CFG_INCQ |
DEBI_CFG_16Q);
/* DEBI INIT S626 WR7146( P_DEBICFG, DEBI_CFG_INTEL | DEBI_CFG_TOQ */
/* | DEBI_CFG_INCQ| DEBI_CFG_16Q); //end */
/* Paging is disabled. */
WR7146(P_DEBIPAGE, DEBI_PAGE_DISABLE); /* Disable MMU paging. */
/* Init GPIO so that ADC Start* is negated. */
WR7146(P_GPIO, GPIO_BASE | GPIO1_HI);
/* IsBoardRevA is a boolean that indicates whether the board is RevA.
*
* VERSION 2.01 CHANGE: REV A & B BOARDS NOW SUPPORTED BY DYNAMIC
* EEPROM ADDRESS SELECTION. Initialize the I2C interface, which
* is used to access the onboard serial EEPROM. The EEPROM's I2C
* DeviceAddress is hardwired to a value that is dependent on the
* 626 board revision. On all board revisions, the EEPROM stores
* TrimDAC calibration constants for analog I/O. On RevB and
* higher boards, the DeviceAddress is hardwired to 0 to enable
* the EEPROM to also store the PCI SubVendorID and SubDeviceID;
* this is the address at which the SAA7146 expects a
* configuration EEPROM to reside. On RevA boards, the EEPROM
* device address, which is hardwired to 4, prevents the SAA7146
* from retrieving PCI sub-IDs, so the SAA7146 uses its built-in
* default values, instead.
*/
/* devpriv->I2Cards= IsBoardRevA ? 0xA8 : 0xA0; // Set I2C EEPROM */
/* DeviceType (0xA0) */
/* and DeviceAddress<<1. */
devpriv->I2CAdrs = 0xA0; /* I2C device address for onboard */
/* eeprom(revb) */
/* Issue an I2C ABORT command to halt any I2C operation in */
/* progress and reset BUSY flag. */
WR7146(P_I2CSTAT, I2C_CLKSEL | I2C_ABORT);
/* Write I2C control: abort any I2C activity. */
MC_ENABLE(P_MC2, MC2_UPLD_IIC);
/* Invoke command upload */
while ((RR7146(P_MC2) & MC2_UPLD_IIC) == 0)
;
/* and wait for upload to complete. */
/* Per SAA7146 data sheet, write to STATUS reg twice to
* reset all I2C error flags. */
for (i = 0; i < 2; i++) {
WR7146(P_I2CSTAT, I2C_CLKSEL);
/* Write I2C control: reset error flags. */
MC_ENABLE(P_MC2, MC2_UPLD_IIC); /* Invoke command upload */
while (!MC_TEST(P_MC2, MC2_UPLD_IIC))
;
/* and wait for upload to complete. */
}
/* Init audio interface functional attributes: set DAC/ADC
* serial clock rates, invert DAC serial clock so that
* DAC data setup times are satisfied, enable DAC serial
* clock out.
*/
WR7146(P_ACON2, ACON2_INIT);
/* Set up TSL1 slot list, which is used to control the
* accumulation of ADC data: RSD1 = shift data in on SD1.
* SIB_A1 = store data uint8_t at next available location in
* FB BUFFER1 register. */
WR7146(P_TSL1, RSD1 | SIB_A1);
/* Fetch ADC high data uint8_t. */
WR7146(P_TSL1 + 4, RSD1 | SIB_A1 | EOS);
/* Fetch ADC low data uint8_t; end of TSL1. */
/* enab TSL1 slot list so that it executes all the time. */
WR7146(P_ACON1, ACON1_ADCSTART);
/* Initialize RPS registers used for ADC. */
/* Physical start of RPS program. */
WR7146(P_RPSADDR1, (uint32_t) devpriv->RPSBuf.PhysicalBase);
WR7146(P_RPSPAGE1, 0);
/* RPS program performs no explicit mem writes. */
WR7146(P_RPS1_TOUT, 0); /* Disable RPS timeouts. */
/* SAA7146 BUG WORKAROUND. Initialize SAA7146 ADC interface
* to a known state by invoking ADCs until FB BUFFER 1
* register shows that it is correctly receiving ADC data.
* This is necessary because the SAA7146 ADC interface does
* not start up in a defined state after a PCI reset.
*/
/* PollList = EOPL; // Create a simple polling */
/* // list for analog input */
/* // channel 0. */
/* ResetADC( dev, &PollList ); */
/* s626_ai_rinsn(dev,dev->subdevices,NULL,data); //( &AdcData ); // */
/* //Get initial ADC */
/* //value. */
/* StartVal = data[0]; */
/* // VERSION 2.01 CHANGE: TIMEOUT ADDED TO PREVENT HANGED EXECUTION. */
/* // Invoke ADCs until the new ADC value differs from the initial */
/* // value or a timeout occurs. The timeout protects against the */
/* // possibility that the driver is restarting and the ADC data is a */
/* // fixed value resulting from the applied ADC analog input being */
/* // unusually quiet or at the rail. */
/* for ( index = 0; index < 500; index++ ) */
/* { */
/* s626_ai_rinsn(dev,dev->subdevices,NULL,data); */
/* AdcData = data[0]; //ReadADC( &AdcData ); */
/* if ( AdcData != StartVal ) */
/* break; */
/* } */
/* end initADC */
/* init the DAC interface */
/* Init Audio2's output DMAC attributes: burst length = 1
* DWORD, threshold = 1 DWORD.
*/
WR7146(P_PCI_BT_A, 0);
/* Init Audio2's output DMA physical addresses. The protection
* address is set to 1 DWORD past the base address so that a
* single DWORD will be transferred each time a DMA transfer is
* enabled. */
pPhysBuf =
devpriv->ANABuf.PhysicalBase +
(DAC_WDMABUF_OS * sizeof(uint32_t));
WR7146(P_BASEA2_OUT, (uint32_t) pPhysBuf); /* Buffer base adrs. */
WR7146(P_PROTA2_OUT, (uint32_t) (pPhysBuf + sizeof(uint32_t))); /* Protection address. */
/* Cache Audio2's output DMA buffer logical address. This is
* where DAC data is buffered for A2 output DMA transfers. */
devpriv->pDacWBuf =
(uint32_t *) devpriv->ANABuf.LogicalBase + DAC_WDMABUF_OS;
/* Audio2's output channels does not use paging. The protection
* violation handling bit is set so that the DMAC will
* automatically halt and its PCI address pointer will be reset
* when the protection address is reached. */
WR7146(P_PAGEA2_OUT, 8);
/* Initialize time slot list 2 (TSL2), which is used to control
* the clock generation for and serialization of data to be sent
* to the DAC devices. Slot 0 is a NOP that is used to trap TSL
* execution; this permits other slots to be safely modified
* without first turning off the TSL sequencer (which is
* apparently impossible to do). Also, SD3 (which is driven by a
* pull-up resistor) is shifted in and stored to the MSB of
* FB_BUFFER2 to be used as evidence that the slot sequence has
* not yet finished executing.
*/
SETVECT(0, XSD2 | RSD3 | SIB_A2 | EOS);
/* Slot 0: Trap TSL execution, shift 0xFF into FB_BUFFER2. */
/* Initialize slot 1, which is constant. Slot 1 causes a
* DWORD to be transferred from audio channel 2's output FIFO
* to the FIFO's output buffer so that it can be serialized
* and sent to the DAC during subsequent slots. All remaining
* slots are dynamically populated as required by the target
* DAC device.
*/
SETVECT(1, LF_A2);
/* Slot 1: Fetch DWORD from Audio2's output FIFO. */
/* Start DAC's audio interface (TSL2) running. */
WR7146(P_ACON1, ACON1_DACSTART);
/* end init DAC interface */
/* Init Trim DACs to calibrated values. Do it twice because the
* SAA7146 audio channel does not always reset properly and
* sometimes causes the first few TrimDAC writes to malfunction.
*/
LoadTrimDACs(dev);
LoadTrimDACs(dev); /* Insurance. */
/* Manually init all gate array hardware in case this is a soft
* reset (we have no way of determining whether this is a warm
* or cold start). This is necessary because the gate array will
* reset only in response to a PCI hard reset; there is no soft
* reset function. */
/* Init all DAC outputs to 0V and init all DAC setpoint and
* polarity images.
*/
for (chan = 0; chan < S626_DAC_CHANNELS; chan++)
SetDAC(dev, chan, 0);
/* Init image of WRMISC2 Battery Charger Enabled control bit.
* This image is used when the state of the charger control bit,
* which has no direct hardware readback mechanism, is queried.
*/
devpriv->ChargeEnabled = 0;
/* Init image of watchdog timer interval in WRMISC2. This image
* maintains the value of the control bits of MISC2 are
* continuously reset to zero as long as the WD timer is disabled.
*/
devpriv->WDInterval = 0;
/* Init Counter Interrupt enab mask for RDMISC2. This mask is
* applied against MISC2 when testing to determine which timer
* events are requesting interrupt service.
*/
devpriv->CounterIntEnabs = 0;
/* Init counters. */
CountersInit(dev);
/* Without modifying the state of the Battery Backup enab, disable
* the watchdog timer, set DIO channels 0-5 to operate in the
* standard DIO (vs. counter overflow) mode, disable the battery
* charger, and reset the watchdog interval selector to zero.
*/
WriteMISC2(dev, (uint16_t) (DEBIread(dev,
LP_RDMISC2) &
MISC2_BATT_ENABLE));
/* Initialize the digital I/O subsystem. */
s626_dio_init(dev);
/* enable interrupt test */
/* writel(IRQ_GPIO3 | IRQ_RPS1,devpriv->base_addr+P_IER); */
}
DEBUG("s626_attach: comedi%d s626 attached %04x\n", dev->minor,
(uint32_t) devpriv->base_addr);
return 1;
}
static unsigned int s626_ai_reg_to_uint(int data)
{
unsigned int tempdata;
tempdata = (data >> 18);
if (tempdata & 0x2000)
tempdata &= 0x1fff;
else
tempdata += (1 << 13);
return tempdata;
}
/* static unsigned int s626_uint_to_reg(struct comedi_subdevice *s, int data){ */
/* return 0; */
/* } */
static irqreturn_t s626_irq_handler(int irq, void *d)
{
struct comedi_device *dev = d;
struct comedi_subdevice *s;
struct comedi_cmd *cmd;
struct enc_private *k;
unsigned long flags;
int32_t *readaddr;
uint32_t irqtype, irqstatus;
int i = 0;
short tempdata;
uint8_t group;
uint16_t irqbit;
DEBUG("s626_irq_handler: interrupt request received!!!\n");
if (dev->attached == 0)
return IRQ_NONE;
/* lock to avoid race with comedi_poll */
spin_lock_irqsave(&dev->spinlock, flags);
/* save interrupt enable register state */
irqstatus = readl(devpriv->base_addr + P_IER);
/* read interrupt type */
irqtype = readl(devpriv->base_addr + P_ISR);
/* disable master interrupt */
writel(0, devpriv->base_addr + P_IER);
/* clear interrupt */
writel(irqtype, devpriv->base_addr + P_ISR);
/* do somethings */
DEBUG("s626_irq_handler: interrupt type %d\n", irqtype);
switch (irqtype) {
case IRQ_RPS1: /* end_of_scan occurs */
DEBUG("s626_irq_handler: RPS1 irq detected\n");
/* manage ai subdevice */
s = dev->subdevices;
cmd = &(s->async->cmd);
/* Init ptr to DMA buffer that holds new ADC data. We skip the
* first uint16_t in the buffer because it contains junk data from
* the final ADC of the previous poll list scan.
*/
readaddr = (int32_t *) devpriv->ANABuf.LogicalBase + 1;
/* get the data and hand it over to comedi */
for (i = 0; i < (s->async->cmd.chanlist_len); i++) {
/* Convert ADC data to 16-bit integer values and copy to application */
/* buffer. */
tempdata = s626_ai_reg_to_uint((int)*readaddr);
readaddr++;
/* put data into read buffer */
/* comedi_buf_put(s->async, tempdata); */
if (cfc_write_to_buffer(s, tempdata) == 0)
printk
("s626_irq_handler: cfc_write_to_buffer error!\n");
DEBUG("s626_irq_handler: ai channel %d acquired: %d\n",
i, tempdata);
}
/* end of scan occurs */
s->async->events |= COMEDI_CB_EOS;
if (!(devpriv->ai_continous))
devpriv->ai_sample_count--;
if (devpriv->ai_sample_count <= 0) {
devpriv->ai_cmd_running = 0;
/* Stop RPS program. */
MC_DISABLE(P_MC1, MC1_ERPS1);
/* send end of acquisition */
s->async->events |= COMEDI_CB_EOA;
/* disable master interrupt */
irqstatus = 0;
}
if (devpriv->ai_cmd_running && cmd->scan_begin_src == TRIG_EXT) {
DEBUG
("s626_irq_handler: enable interrupt on dio channel %d\n",
cmd->scan_begin_arg);
s626_dio_set_irq(dev, cmd->scan_begin_arg);
DEBUG("s626_irq_handler: External trigger is set!!!\n");
}
/* tell comedi that data is there */
DEBUG("s626_irq_handler: events %d\n", s->async->events);
comedi_event(dev, s);
break;
case IRQ_GPIO3: /* check dio and conter interrupt */
DEBUG("s626_irq_handler: GPIO3 irq detected\n");
/* manage ai subdevice */
s = dev->subdevices;
cmd = &(s->async->cmd);
/* s626_dio_clear_irq(dev); */
for (group = 0; group < S626_DIO_BANKS; group++) {
irqbit = 0;
/* read interrupt type */
irqbit = DEBIread(dev,
((struct dio_private *)(dev->
subdevices +
2 +
group)->
private)->RDCapFlg);
/* check if interrupt is generated from dio channels */
if (irqbit) {
s626_dio_reset_irq(dev, group, irqbit);
DEBUG
("s626_irq_handler: check interrupt on dio group %d %d\n",
group, i);
if (devpriv->ai_cmd_running) {
/* check if interrupt is an ai acquisition start trigger */
if ((irqbit >> (cmd->start_arg -
(16 * group)))
== 1 && cmd->start_src == TRIG_EXT) {
DEBUG
("s626_irq_handler: Edge capture interrupt received from channel %d\n",
cmd->start_arg);
/* Start executing the RPS program. */
MC_ENABLE(P_MC1, MC1_ERPS1);
DEBUG
("s626_irq_handler: acquisition start triggered!!!\n");
if (cmd->scan_begin_src ==
TRIG_EXT) {
DEBUG
("s626_ai_cmd: enable interrupt on dio channel %d\n",
cmd->
scan_begin_arg);
s626_dio_set_irq(dev,
cmd->scan_begin_arg);
DEBUG
("s626_irq_handler: External scan trigger is set!!!\n");
}
}
if ((irqbit >> (cmd->scan_begin_arg -
(16 * group)))
== 1
&& cmd->scan_begin_src ==
TRIG_EXT) {
DEBUG
("s626_irq_handler: Edge capture interrupt received from channel %d\n",
cmd->scan_begin_arg);
/* Trigger ADC scan loop start by setting RPS Signal 0. */
MC_ENABLE(P_MC2, MC2_ADC_RPS);
DEBUG
("s626_irq_handler: scan triggered!!! %d\n",
devpriv->ai_sample_count);
if (cmd->convert_src ==
TRIG_EXT) {
DEBUG
("s626_ai_cmd: enable interrupt on dio channel %d group %d\n",
cmd->convert_arg -
(16 * group),
group);
devpriv->ai_convert_count
= cmd->chanlist_len;
s626_dio_set_irq(dev,
cmd->convert_arg);
DEBUG
("s626_irq_handler: External convert trigger is set!!!\n");
}
if (cmd->convert_src ==
TRIG_TIMER) {
k = &encpriv[5];
devpriv->ai_convert_count
= cmd->chanlist_len;
k->SetEnable(dev, k,
CLKENAB_ALWAYS);
}
}
if ((irqbit >> (cmd->convert_arg -
(16 * group)))
== 1
&& cmd->convert_src == TRIG_EXT) {
DEBUG
("s626_irq_handler: Edge capture interrupt received from channel %d\n",
cmd->convert_arg);
/* Trigger ADC scan loop start by setting RPS Signal 0. */
MC_ENABLE(P_MC2, MC2_ADC_RPS);
DEBUG
("s626_irq_handler: adc convert triggered!!!\n");
devpriv->ai_convert_count--;
if (devpriv->ai_convert_count >
0) {
DEBUG
("s626_ai_cmd: enable interrupt on dio channel %d group %d\n",
cmd->convert_arg -
(16 * group),
group);
s626_dio_set_irq(dev,
cmd->convert_arg);
DEBUG
("s626_irq_handler: External trigger is set!!!\n");
}
}
}
break;
}
}
/* read interrupt type */
irqbit = DEBIread(dev, LP_RDMISC2);
/* check interrupt on counters */
DEBUG("s626_irq_handler: check counters interrupt %d\n",
irqbit);
if (irqbit & IRQ_COINT1A) {
DEBUG
("s626_irq_handler: interrupt on counter 1A overflow\n");
k = &encpriv[0];
/* clear interrupt capture flag */
k->ResetCapFlags(dev, k);
}
if (irqbit & IRQ_COINT2A) {
DEBUG
("s626_irq_handler: interrupt on counter 2A overflow\n");
k = &encpriv[1];
/* clear interrupt capture flag */
k->ResetCapFlags(dev, k);
}
if (irqbit & IRQ_COINT3A) {
DEBUG
("s626_irq_handler: interrupt on counter 3A overflow\n");
k = &encpriv[2];
/* clear interrupt capture flag */
k->ResetCapFlags(dev, k);
}
if (irqbit & IRQ_COINT1B) {
DEBUG
("s626_irq_handler: interrupt on counter 1B overflow\n");
k = &encpriv[3];
/* clear interrupt capture flag */
k->ResetCapFlags(dev, k);
}
if (irqbit & IRQ_COINT2B) {
DEBUG
("s626_irq_handler: interrupt on counter 2B overflow\n");
k = &encpriv[4];
/* clear interrupt capture flag */
k->ResetCapFlags(dev, k);
if (devpriv->ai_convert_count > 0) {
devpriv->ai_convert_count--;
if (devpriv->ai_convert_count == 0)
k->SetEnable(dev, k, CLKENAB_INDEX);
if (cmd->convert_src == TRIG_TIMER) {
DEBUG
("s626_irq_handler: conver timer trigger!!! %d\n",
devpriv->ai_convert_count);
/* Trigger ADC scan loop start by setting RPS Signal 0. */
MC_ENABLE(P_MC2, MC2_ADC_RPS);
}
}
}
if (irqbit & IRQ_COINT3B) {
DEBUG
("s626_irq_handler: interrupt on counter 3B overflow\n");
k = &encpriv[5];
/* clear interrupt capture flag */
k->ResetCapFlags(dev, k);
if (cmd->scan_begin_src == TRIG_TIMER) {
DEBUG
("s626_irq_handler: scan timer trigger!!!\n");
/* Trigger ADC scan loop start by setting RPS Signal 0. */
MC_ENABLE(P_MC2, MC2_ADC_RPS);
}
if (cmd->convert_src == TRIG_TIMER) {
DEBUG
("s626_irq_handler: convert timer trigger is set\n");
k = &encpriv[4];
devpriv->ai_convert_count = cmd->chanlist_len;
k->SetEnable(dev, k, CLKENAB_ALWAYS);
}
}
}
/* enable interrupt */
writel(irqstatus, devpriv->base_addr + P_IER);
DEBUG("s626_irq_handler: exit interrupt service routine.\n");
spin_unlock_irqrestore(&dev->spinlock, flags);
return IRQ_HANDLED;
}
static int s626_detach(struct comedi_device *dev)
{
if (devpriv) {
/* stop ai_command */
devpriv->ai_cmd_running = 0;
if (devpriv->base_addr) {
/* interrupt mask */
WR7146(P_IER, 0); /* Disable master interrupt. */
WR7146(P_ISR, IRQ_GPIO3 | IRQ_RPS1); /* Clear board's IRQ status flag. */
/* Disable the watchdog timer and battery charger. */
WriteMISC2(dev, 0);
/* Close all interfaces on 7146 device. */
WR7146(P_MC1, MC1_SHUTDOWN);
WR7146(P_ACON1, ACON1_BASE);
CloseDMAB(dev, &devpriv->RPSBuf, DMABUF_SIZE);
CloseDMAB(dev, &devpriv->ANABuf, DMABUF_SIZE);
}
if (dev->irq)
free_irq(dev->irq, dev);
if (devpriv->base_addr)
iounmap(devpriv->base_addr);
if (devpriv->pdev) {
if (devpriv->got_regions)
comedi_pci_disable(devpriv->pdev);
pci_dev_put(devpriv->pdev);
}
}
DEBUG("s626_detach: S626 detached!\n");
return 0;
}
/*
* this functions build the RPS program for hardware driven acquistion
*/
void ResetADC(struct comedi_device *dev, uint8_t * ppl)
{
register uint32_t *pRPS;
uint32_t JmpAdrs;
uint16_t i;
uint16_t n;
uint32_t LocalPPL;
struct comedi_cmd *cmd = &(dev->subdevices->async->cmd);
/* Stop RPS program in case it is currently running. */
MC_DISABLE(P_MC1, MC1_ERPS1);
/* Set starting logical address to write RPS commands. */
pRPS = (uint32_t *) devpriv->RPSBuf.LogicalBase;
/* Initialize RPS instruction pointer. */
WR7146(P_RPSADDR1, (uint32_t) devpriv->RPSBuf.PhysicalBase);
/* Construct RPS program in RPSBuf DMA buffer */
if (cmd != NULL && cmd->scan_begin_src != TRIG_FOLLOW) {
DEBUG("ResetADC: scan_begin pause inserted\n");
/* Wait for Start trigger. */
*pRPS++ = RPS_PAUSE | RPS_SIGADC;
*pRPS++ = RPS_CLRSIGNAL | RPS_SIGADC;
}
/* SAA7146 BUG WORKAROUND Do a dummy DEBI Write. This is necessary
* because the first RPS DEBI Write following a non-RPS DEBI write
* seems to always fail. If we don't do this dummy write, the ADC
* gain might not be set to the value required for the first slot in
* the poll list; the ADC gain would instead remain unchanged from
* the previously programmed value.
*/
*pRPS++ = RPS_LDREG | (P_DEBICMD >> 2);
/* Write DEBI Write command and address to shadow RAM. */
*pRPS++ = DEBI_CMD_WRWORD | LP_GSEL;
*pRPS++ = RPS_LDREG | (P_DEBIAD >> 2);
/* Write DEBI immediate data to shadow RAM: */
*pRPS++ = GSEL_BIPOLAR5V;
/* arbitrary immediate data value. */
*pRPS++ = RPS_CLRSIGNAL | RPS_DEBI;
/* Reset "shadow RAM uploaded" flag. */
*pRPS++ = RPS_UPLOAD | RPS_DEBI; /* Invoke shadow RAM upload. */
*pRPS++ = RPS_PAUSE | RPS_DEBI; /* Wait for shadow upload to finish. */
/* Digitize all slots in the poll list. This is implemented as a
* for loop to limit the slot count to 16 in case the application
* forgot to set the EOPL flag in the final slot.
*/
for (devpriv->AdcItems = 0; devpriv->AdcItems < 16; devpriv->AdcItems++) {
/* Convert application's poll list item to private board class
* format. Each app poll list item is an uint8_t with form
* (EOPL,x,x,RANGE,CHAN<3:0>), where RANGE code indicates 0 =
* +-10V, 1 = +-5V, and EOPL = End of Poll List marker.
*/
LocalPPL =
(*ppl << 8) | (*ppl & 0x10 ? GSEL_BIPOLAR5V :
GSEL_BIPOLAR10V);
/* Switch ADC analog gain. */
*pRPS++ = RPS_LDREG | (P_DEBICMD >> 2); /* Write DEBI command */
/* and address to */
/* shadow RAM. */
*pRPS++ = DEBI_CMD_WRWORD | LP_GSEL;
*pRPS++ = RPS_LDREG | (P_DEBIAD >> 2); /* Write DEBI */
/* immediate data to */
/* shadow RAM. */
*pRPS++ = LocalPPL;
*pRPS++ = RPS_CLRSIGNAL | RPS_DEBI; /* Reset "shadow RAM uploaded" */
/* flag. */
*pRPS++ = RPS_UPLOAD | RPS_DEBI; /* Invoke shadow RAM upload. */
*pRPS++ = RPS_PAUSE | RPS_DEBI; /* Wait for shadow upload to */
/* finish. */
/* Select ADC analog input channel. */
*pRPS++ = RPS_LDREG | (P_DEBICMD >> 2);
/* Write DEBI command and address to shadow RAM. */
*pRPS++ = DEBI_CMD_WRWORD | LP_ISEL;
*pRPS++ = RPS_LDREG | (P_DEBIAD >> 2);
/* Write DEBI immediate data to shadow RAM. */
*pRPS++ = LocalPPL;
*pRPS++ = RPS_CLRSIGNAL | RPS_DEBI;
/* Reset "shadow RAM uploaded" flag. */
*pRPS++ = RPS_UPLOAD | RPS_DEBI;
/* Invoke shadow RAM upload. */
*pRPS++ = RPS_PAUSE | RPS_DEBI;
/* Wait for shadow upload to finish. */
/* Delay at least 10 microseconds for analog input settling.
* Instead of padding with NOPs, we use RPS_JUMP instructions
* here; this allows us to produce a longer delay than is
* possible with NOPs because each RPS_JUMP flushes the RPS'
* instruction prefetch pipeline.
*/
JmpAdrs =
(uint32_t) devpriv->RPSBuf.PhysicalBase +
(uint32_t) ((unsigned long)pRPS -
(unsigned long)devpriv->RPSBuf.LogicalBase);
for (i = 0; i < (10 * RPSCLK_PER_US / 2); i++) {
JmpAdrs += 8; /* Repeat to implement time delay: */
*pRPS++ = RPS_JUMP; /* Jump to next RPS instruction. */
*pRPS++ = JmpAdrs;
}
if (cmd != NULL && cmd->convert_src != TRIG_NOW) {
DEBUG("ResetADC: convert pause inserted\n");
/* Wait for Start trigger. */
*pRPS++ = RPS_PAUSE | RPS_SIGADC;
*pRPS++ = RPS_CLRSIGNAL | RPS_SIGADC;
}
/* Start ADC by pulsing GPIO1. */
*pRPS++ = RPS_LDREG | (P_GPIO >> 2); /* Begin ADC Start pulse. */
*pRPS++ = GPIO_BASE | GPIO1_LO;
*pRPS++ = RPS_NOP;
/* VERSION 2.03 CHANGE: STRETCH OUT ADC START PULSE. */
*pRPS++ = RPS_LDREG | (P_GPIO >> 2); /* End ADC Start pulse. */
*pRPS++ = GPIO_BASE | GPIO1_HI;
/* Wait for ADC to complete (GPIO2 is asserted high when ADC not
* busy) and for data from previous conversion to shift into FB
* BUFFER 1 register.
*/
*pRPS++ = RPS_PAUSE | RPS_GPIO2; /* Wait for ADC done. */
/* Transfer ADC data from FB BUFFER 1 register to DMA buffer. */
*pRPS++ = RPS_STREG | (BUGFIX_STREG(P_FB_BUFFER1) >> 2);
*pRPS++ =
(uint32_t) devpriv->ANABuf.PhysicalBase +
(devpriv->AdcItems << 2);
/* If this slot's EndOfPollList flag is set, all channels have */
/* now been processed. */
if (*ppl++ & EOPL) {
devpriv->AdcItems++; /* Adjust poll list item count. */
break; /* Exit poll list processing loop. */
}
}
DEBUG("ResetADC: ADC items %d\n", devpriv->AdcItems);
/* VERSION 2.01 CHANGE: DELAY CHANGED FROM 250NS to 2US. Allow the
* ADC to stabilize for 2 microseconds before starting the final
* (dummy) conversion. This delay is necessary to allow sufficient
* time between last conversion finished and the start of the dummy
* conversion. Without this delay, the last conversion's data value
* is sometimes set to the previous conversion's data value.
*/
for (n = 0; n < (2 * RPSCLK_PER_US); n++)
*pRPS++ = RPS_NOP;
/* Start a dummy conversion to cause the data from the last
* conversion of interest to be shifted in.
*/
*pRPS++ = RPS_LDREG | (P_GPIO >> 2); /* Begin ADC Start pulse. */
*pRPS++ = GPIO_BASE | GPIO1_LO;
*pRPS++ = RPS_NOP;
/* VERSION 2.03 CHANGE: STRETCH OUT ADC START PULSE. */
*pRPS++ = RPS_LDREG | (P_GPIO >> 2); /* End ADC Start pulse. */
*pRPS++ = GPIO_BASE | GPIO1_HI;
/* Wait for the data from the last conversion of interest to arrive
* in FB BUFFER 1 register.
*/
*pRPS++ = RPS_PAUSE | RPS_GPIO2; /* Wait for ADC done. */
/* Transfer final ADC data from FB BUFFER 1 register to DMA buffer. */
*pRPS++ = RPS_STREG | (BUGFIX_STREG(P_FB_BUFFER1) >> 2); /* */
*pRPS++ =
(uint32_t) devpriv->ANABuf.PhysicalBase + (devpriv->AdcItems << 2);
/* Indicate ADC scan loop is finished. */
/* *pRPS++= RPS_CLRSIGNAL | RPS_SIGADC ; // Signal ReadADC() that scan is done. */
/* invoke interrupt */
if (devpriv->ai_cmd_running == 1) {
DEBUG("ResetADC: insert irq in ADC RPS task\n");
*pRPS++ = RPS_IRQ;
}
/* Restart RPS program at its beginning. */
*pRPS++ = RPS_JUMP; /* Branch to start of RPS program. */
*pRPS++ = (uint32_t) devpriv->RPSBuf.PhysicalBase;
/* End of RPS program build */
}
/* TO COMPLETE, IF NECESSARY */
static int s626_ai_insn_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
return -EINVAL;
}
/* static int s626_ai_rinsn(struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data) */
/* { */
/* register uint8_t i; */
/* register int32_t *readaddr; */
/* DEBUG("as626_ai_rinsn: ai_rinsn enter\n"); */
/* Trigger ADC scan loop start by setting RPS Signal 0. */
/* MC_ENABLE( P_MC2, MC2_ADC_RPS ); */
/* Wait until ADC scan loop is finished (RPS Signal 0 reset). */
/* while ( MC_TEST( P_MC2, MC2_ADC_RPS ) ); */
/* Init ptr to DMA buffer that holds new ADC data. We skip the
* first uint16_t in the buffer because it contains junk data from
* the final ADC of the previous poll list scan.
*/
/* readaddr = (uint32_t *)devpriv->ANABuf.LogicalBase + 1; */
/* Convert ADC data to 16-bit integer values and copy to application buffer. */
/* for ( i = 0; i < devpriv->AdcItems; i++ ) { */
/* *data = s626_ai_reg_to_uint( *readaddr++ ); */
/* DEBUG("s626_ai_rinsn: data %d\n",*data); */
/* data++; */
/* } */
/* DEBUG("s626_ai_rinsn: ai_rinsn escape\n"); */
/* return i; */
/* } */
static int s626_ai_insn_read(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
uint16_t chan = CR_CHAN(insn->chanspec);
uint16_t range = CR_RANGE(insn->chanspec);
uint16_t AdcSpec = 0;
uint32_t GpioImage;
int n;
/* interrupt call test */
/* writel(IRQ_GPIO3,devpriv->base_addr+P_PSR); */
/* Writing a logical 1 into any of the RPS_PSR bits causes the
* corresponding interrupt to be generated if enabled
*/
DEBUG("s626_ai_insn_read: entering\n");
/* Convert application's ADC specification into form
* appropriate for register programming.
*/
if (range == 0)
AdcSpec = (chan << 8) | (GSEL_BIPOLAR5V);
else
AdcSpec = (chan << 8) | (GSEL_BIPOLAR10V);
/* Switch ADC analog gain. */
DEBIwrite(dev, LP_GSEL, AdcSpec); /* Set gain. */
/* Select ADC analog input channel. */
DEBIwrite(dev, LP_ISEL, AdcSpec); /* Select channel. */
for (n = 0; n < insn->n; n++) {
/* Delay 10 microseconds for analog input settling. */
udelay(10);
/* Start ADC by pulsing GPIO1 low. */
GpioImage = RR7146(P_GPIO);
/* Assert ADC Start command */
WR7146(P_GPIO, GpioImage & ~GPIO1_HI);
/* and stretch it out. */
WR7146(P_GPIO, GpioImage & ~GPIO1_HI);
WR7146(P_GPIO, GpioImage & ~GPIO1_HI);
/* Negate ADC Start command. */
WR7146(P_GPIO, GpioImage | GPIO1_HI);
/* Wait for ADC to complete (GPIO2 is asserted high when */
/* ADC not busy) and for data from previous conversion to */
/* shift into FB BUFFER 1 register. */
/* Wait for ADC done. */
while (!(RR7146(P_PSR) & PSR_GPIO2))
;
/* Fetch ADC data. */
if (n != 0)
data[n - 1] = s626_ai_reg_to_uint(RR7146(P_FB_BUFFER1));
/* Allow the ADC to stabilize for 4 microseconds before
* starting the next (final) conversion. This delay is
* necessary to allow sufficient time between last
* conversion finished and the start of the next
* conversion. Without this delay, the last conversion's
* data value is sometimes set to the previous
* conversion's data value.
*/
udelay(4);
}
/* Start a dummy conversion to cause the data from the
* previous conversion to be shifted in. */
GpioImage = RR7146(P_GPIO);
/* Assert ADC Start command */
WR7146(P_GPIO, GpioImage & ~GPIO1_HI);
/* and stretch it out. */
WR7146(P_GPIO, GpioImage & ~GPIO1_HI);
WR7146(P_GPIO, GpioImage & ~GPIO1_HI);
/* Negate ADC Start command. */
WR7146(P_GPIO, GpioImage | GPIO1_HI);
/* Wait for the data to arrive in FB BUFFER 1 register. */
/* Wait for ADC done. */
while (!(RR7146(P_PSR) & PSR_GPIO2))
;
/* Fetch ADC data from audio interface's input shift register. */
/* Fetch ADC data. */
if (n != 0)
data[n - 1] = s626_ai_reg_to_uint(RR7146(P_FB_BUFFER1));
DEBUG("s626_ai_insn_read: samples %d, data %d\n", n, data[n - 1]);
return n;
}
static int s626_ai_load_polllist(uint8_t *ppl, struct comedi_cmd *cmd)
{
int n;
for (n = 0; n < cmd->chanlist_len; n++) {
if (CR_RANGE((cmd->chanlist)[n]) == 0)
ppl[n] = (CR_CHAN((cmd->chanlist)[n])) | (RANGE_5V);
else
ppl[n] = (CR_CHAN((cmd->chanlist)[n])) | (RANGE_10V);
}
if (n != 0)
ppl[n - 1] |= EOPL;
return n;
}
static int s626_ai_inttrig(struct comedi_device *dev,
struct comedi_subdevice *s, unsigned int trignum)
{
if (trignum != 0)
return -EINVAL;
DEBUG("s626_ai_inttrig: trigger adc start...");
/* Start executing the RPS program. */
MC_ENABLE(P_MC1, MC1_ERPS1);
s->async->inttrig = NULL;
DEBUG(" done\n");
return 1;
}
/* TO COMPLETE */
static int s626_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
{
uint8_t ppl[16];
struct comedi_cmd *cmd = &s->async->cmd;
struct enc_private *k;
int tick;
DEBUG("s626_ai_cmd: entering command function\n");
if (devpriv->ai_cmd_running) {
printk(KERN_ERR "s626_ai_cmd: Another ai_cmd is running %d\n",
dev->minor);
return -EBUSY;
}
/* disable interrupt */
writel(0, devpriv->base_addr + P_IER);
/* clear interrupt request */
writel(IRQ_RPS1 | IRQ_GPIO3, devpriv->base_addr + P_ISR);
/* clear any pending interrupt */
s626_dio_clear_irq(dev);
/* s626_enc_clear_irq(dev); */
/* reset ai_cmd_running flag */
devpriv->ai_cmd_running = 0;
/* test if cmd is valid */
if (cmd == NULL) {
DEBUG("s626_ai_cmd: NULL command\n");
return -EINVAL;
} else {
DEBUG("s626_ai_cmd: command received!!!\n");
}
if (dev->irq == 0) {
comedi_error(dev,
"s626_ai_cmd: cannot run command without an irq");
return -EIO;
}
s626_ai_load_polllist(ppl, cmd);
devpriv->ai_cmd_running = 1;
devpriv->ai_convert_count = 0;
switch (cmd->scan_begin_src) {
case TRIG_FOLLOW:
break;
case TRIG_TIMER:
/* set a conter to generate adc trigger at scan_begin_arg interval */
k = &encpriv[5];
tick = s626_ns_to_timer((int *)&cmd->scan_begin_arg,
cmd->flags & TRIG_ROUND_MASK);
/* load timer value and enable interrupt */
s626_timer_load(dev, k, tick);
k->SetEnable(dev, k, CLKENAB_ALWAYS);
DEBUG("s626_ai_cmd: scan trigger timer is set with value %d\n",
tick);
break;
case TRIG_EXT:
/* set the digital line and interrupt for scan trigger */
if (cmd->start_src != TRIG_EXT)
s626_dio_set_irq(dev, cmd->scan_begin_arg);
DEBUG("s626_ai_cmd: External scan trigger is set!!!\n");
break;
}
switch (cmd->convert_src) {
case TRIG_NOW:
break;
case TRIG_TIMER:
/* set a conter to generate adc trigger at convert_arg interval */
k = &encpriv[4];
tick = s626_ns_to_timer((int *)&cmd->convert_arg,
cmd->flags & TRIG_ROUND_MASK);
/* load timer value and enable interrupt */
s626_timer_load(dev, k, tick);
k->SetEnable(dev, k, CLKENAB_INDEX);
DEBUG
("s626_ai_cmd: convert trigger timer is set with value %d\n",
tick);
break;
case TRIG_EXT:
/* set the digital line and interrupt for convert trigger */
if (cmd->scan_begin_src != TRIG_EXT
&& cmd->start_src == TRIG_EXT)
s626_dio_set_irq(dev, cmd->convert_arg);
DEBUG("s626_ai_cmd: External convert trigger is set!!!\n");
break;
}
switch (cmd->stop_src) {
case TRIG_COUNT:
/* data arrives as one packet */
devpriv->ai_sample_count = cmd->stop_arg;
devpriv->ai_continous = 0;
break;
case TRIG_NONE:
/* continous acquisition */
devpriv->ai_continous = 1;
devpriv->ai_sample_count = 0;
break;
}
ResetADC(dev, ppl);
switch (cmd->start_src) {
case TRIG_NOW:
/* Trigger ADC scan loop start by setting RPS Signal 0. */
/* MC_ENABLE( P_MC2, MC2_ADC_RPS ); */
/* Start executing the RPS program. */
MC_ENABLE(P_MC1, MC1_ERPS1);
DEBUG("s626_ai_cmd: ADC triggered\n");
s->async->inttrig = NULL;
break;
case TRIG_EXT:
/* configure DIO channel for acquisition trigger */
s626_dio_set_irq(dev, cmd->start_arg);
DEBUG("s626_ai_cmd: External start trigger is set!!!\n");
s->async->inttrig = NULL;
break;
case TRIG_INT:
s->async->inttrig = s626_ai_inttrig;
break;
}
/* enable interrupt */
writel(IRQ_GPIO3 | IRQ_RPS1, devpriv->base_addr + P_IER);
DEBUG("s626_ai_cmd: command function terminated\n");
return 0;
}
static int s626_ai_cmdtest(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_cmd *cmd)
{
int err = 0;
int tmp;
/* cmdtest tests a particular command to see if it is valid. Using
* the cmdtest ioctl, a user can create a valid cmd and then have it
* executes by the cmd ioctl.
*
* cmdtest returns 1,2,3,4 or 0, depending on which tests the
* command passes. */
/* step 1: make sure trigger sources are trivially valid */
tmp = cmd->start_src;
cmd->start_src &= TRIG_NOW | TRIG_INT | TRIG_EXT;
if (!cmd->start_src || tmp != cmd->start_src)
err++;
tmp = cmd->scan_begin_src;
cmd->scan_begin_src &= TRIG_TIMER | TRIG_EXT | TRIG_FOLLOW;
if (!cmd->scan_begin_src || tmp != cmd->scan_begin_src)
err++;
tmp = cmd->convert_src;
cmd->convert_src &= TRIG_TIMER | TRIG_EXT | TRIG_NOW;
if (!cmd->convert_src || tmp != cmd->convert_src)
err++;
tmp = cmd->scan_end_src;
cmd->scan_end_src &= TRIG_COUNT;
if (!cmd->scan_end_src || tmp != cmd->scan_end_src)
err++;
tmp = cmd->stop_src;
cmd->stop_src &= TRIG_COUNT | TRIG_NONE;
if (!cmd->stop_src || tmp != cmd->stop_src)
err++;
if (err)
return 1;
/* step 2: make sure trigger sources are unique and mutually
compatible */
/* note that mutual compatibility is not an issue here */
if (cmd->scan_begin_src != TRIG_TIMER &&
cmd->scan_begin_src != TRIG_EXT
&& cmd->scan_begin_src != TRIG_FOLLOW)
err++;
if (cmd->convert_src != TRIG_TIMER &&
cmd->convert_src != TRIG_EXT && cmd->convert_src != TRIG_NOW)
err++;
if (cmd->stop_src != TRIG_COUNT && cmd->stop_src != TRIG_NONE)
err++;
if (err)
return 2;
/* step 3: make sure arguments are trivially compatible */
if (cmd->start_src != TRIG_EXT && cmd->start_arg != 0) {
cmd->start_arg = 0;
err++;
}
if (cmd->start_src == TRIG_EXT && cmd->start_arg > 39) {
cmd->start_arg = 39;
err++;
}
if (cmd->scan_begin_src == TRIG_EXT && cmd->scan_begin_arg > 39) {
cmd->scan_begin_arg = 39;
err++;
}
if (cmd->convert_src == TRIG_EXT && cmd->convert_arg > 39) {
cmd->convert_arg = 39;
err++;
}
#define MAX_SPEED 200000 /* in nanoseconds */
#define MIN_SPEED 2000000000 /* in nanoseconds */
if (cmd->scan_begin_src == TRIG_TIMER) {
if (cmd->scan_begin_arg < MAX_SPEED) {
cmd->scan_begin_arg = MAX_SPEED;
err++;
}
if (cmd->scan_begin_arg > MIN_SPEED) {
cmd->scan_begin_arg = MIN_SPEED;
err++;
}
} else {
/* external trigger */
/* should be level/edge, hi/lo specification here */
/* should specify multiple external triggers */
/* if(cmd->scan_begin_arg>9){ */
/* cmd->scan_begin_arg=9; */
/* err++; */
/* } */
}
if (cmd->convert_src == TRIG_TIMER) {
if (cmd->convert_arg < MAX_SPEED) {
cmd->convert_arg = MAX_SPEED;
err++;
}
if (cmd->convert_arg > MIN_SPEED) {
cmd->convert_arg = MIN_SPEED;
err++;
}
} else {
/* external trigger */
/* see above */
/* if(cmd->convert_arg>9){ */
/* cmd->convert_arg=9; */
/* err++; */
/* } */
}
if (cmd->scan_end_arg != cmd->chanlist_len) {
cmd->scan_end_arg = cmd->chanlist_len;
err++;
}
if (cmd->stop_src == TRIG_COUNT) {
if (cmd->stop_arg > 0x00ffffff) {
cmd->stop_arg = 0x00ffffff;
err++;
}
} else {
/* TRIG_NONE */
if (cmd->stop_arg != 0) {
cmd->stop_arg = 0;
err++;
}
}
if (err)
return 3;
/* step 4: fix up any arguments */
if (cmd->scan_begin_src == TRIG_TIMER) {
tmp = cmd->scan_begin_arg;
s626_ns_to_timer((int *)&cmd->scan_begin_arg,
cmd->flags & TRIG_ROUND_MASK);
if (tmp != cmd->scan_begin_arg)
err++;
}
if (cmd->convert_src == TRIG_TIMER) {
tmp = cmd->convert_arg;
s626_ns_to_timer((int *)&cmd->convert_arg,
cmd->flags & TRIG_ROUND_MASK);
if (tmp != cmd->convert_arg)
err++;
if (cmd->scan_begin_src == TRIG_TIMER &&
cmd->scan_begin_arg <
cmd->convert_arg * cmd->scan_end_arg) {
cmd->scan_begin_arg =
cmd->convert_arg * cmd->scan_end_arg;
err++;
}
}
if (err)
return 4;
return 0;
}
static int s626_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
{
/* Stop RPS program in case it is currently running. */
MC_DISABLE(P_MC1, MC1_ERPS1);
/* disable master interrupt */
writel(0, devpriv->base_addr + P_IER);
devpriv->ai_cmd_running = 0;
return 0;
}
/* This function doesn't require a particular form, this is just what
* happens to be used in some of the drivers. It should convert ns
* nanoseconds to a counter value suitable for programming the device.
* Also, it should adjust ns so that it cooresponds to the actual time
* that the device will use. */
static int s626_ns_to_timer(int *nanosec, int round_mode)
{
int divider, base;
base = 500; /* 2MHz internal clock */
switch (round_mode) {
case TRIG_ROUND_NEAREST:
default:
divider = (*nanosec + base / 2) / base;
break;
case TRIG_ROUND_DOWN:
divider = (*nanosec) / base;
break;
case TRIG_ROUND_UP:
divider = (*nanosec + base - 1) / base;
break;
}
*nanosec = base * divider;
return divider - 1;
}
static int s626_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int i;
uint16_t chan = CR_CHAN(insn->chanspec);
int16_t dacdata;
for (i = 0; i < insn->n; i++) {
dacdata = (int16_t) data[i];
devpriv->ao_readback[CR_CHAN(insn->chanspec)] = data[i];
dacdata -= (0x1fff);
SetDAC(dev, chan, dacdata);
}
return i;
}
static int s626_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int i;
for (i = 0; i < insn->n; i++)
data[i] = devpriv->ao_readback[CR_CHAN(insn->chanspec)];
return i;
}
/* *************** DIGITAL I/O FUNCTIONS ***************
* All DIO functions address a group of DIO channels by means of
* "group" argument. group may be 0, 1 or 2, which correspond to DIO
* ports A, B and C, respectively.
*/
static void s626_dio_init(struct comedi_device *dev)
{
uint16_t group;
struct comedi_subdevice *s;
/* Prepare to treat writes to WRCapSel as capture disables. */
DEBIwrite(dev, LP_MISC1, MISC1_NOEDCAP);
/* For each group of sixteen channels ... */
for (group = 0; group < S626_DIO_BANKS; group++) {
s = dev->subdevices + 2 + group;
DEBIwrite(dev, diopriv->WRIntSel, 0); /* Disable all interrupts. */
DEBIwrite(dev, diopriv->WRCapSel, 0xFFFF); /* Disable all event */
/* captures. */
DEBIwrite(dev, diopriv->WREdgSel, 0); /* Init all DIOs to */
/* default edge */
/* polarity. */
DEBIwrite(dev, diopriv->WRDOut, 0); /* Program all outputs */
/* to inactive state. */
}
DEBUG("s626_dio_init: DIO initialized\n");
}
/* DIO devices are slightly special. Although it is possible to
* implement the insn_read/insn_write interface, it is much more
* useful to applications if you implement the insn_bits interface.
* This allows packed reading/writing of the DIO channels. The comedi
* core can convert between insn_bits and insn_read/write */
static int s626_dio_insn_bits(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
/* Length of data must be 2 (mask and new data, see below) */
if (insn->n == 0)
return 0;
if (insn->n != 2) {
printk
("comedi%d: s626: s626_dio_insn_bits(): Invalid instruction length\n",
dev->minor);
return -EINVAL;
}
/*
* The insn data consists of a mask in data[0] and the new data in
* data[1]. The mask defines which bits we are concerning about.
* The new data must be anded with the mask. Each channel
* corresponds to a bit.
*/
if (data[0]) {
/* Check if requested ports are configured for output */
if ((s->io_bits & data[0]) != data[0])
return -EIO;
s->state &= ~data[0];
s->state |= data[0] & data[1];
/* Write out the new digital output lines */
DEBIwrite(dev, diopriv->WRDOut, s->state);
}
data[1] = DEBIread(dev, diopriv->RDDIn);
return 2;
}
static int s626_dio_insn_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
switch (data[0]) {
case INSN_CONFIG_DIO_QUERY:
data[1] =
(s->
io_bits & (1 << CR_CHAN(insn->chanspec))) ? COMEDI_OUTPUT :
COMEDI_INPUT;
return insn->n;
break;
case COMEDI_INPUT:
s->io_bits &= ~(1 << CR_CHAN(insn->chanspec));
break;
case COMEDI_OUTPUT:
s->io_bits |= 1 << CR_CHAN(insn->chanspec);
break;
default:
return -EINVAL;
break;
}
DEBIwrite(dev, diopriv->WRDOut, s->io_bits);
return 1;
}
static int s626_dio_set_irq(struct comedi_device *dev, unsigned int chan)
{
unsigned int group;
unsigned int bitmask;
unsigned int status;
/* select dio bank */
group = chan / 16;
bitmask = 1 << (chan - (16 * group));
DEBUG("s626_dio_set_irq: enable interrupt on dio channel %d group %d\n",
chan - (16 * group), group);
/* set channel to capture positive edge */
status = DEBIread(dev,
((struct dio_private *)(dev->subdevices + 2 +
group)->private)->RDEdgSel);
DEBIwrite(dev,
((struct dio_private *)(dev->subdevices + 2 +
group)->private)->WREdgSel,
bitmask | status);
/* enable interrupt on selected channel */
status = DEBIread(dev,
((struct dio_private *)(dev->subdevices + 2 +
group)->private)->RDIntSel);
DEBIwrite(dev,
((struct dio_private *)(dev->subdevices + 2 +
group)->private)->WRIntSel,
bitmask | status);
/* enable edge capture write command */
DEBIwrite(dev, LP_MISC1, MISC1_EDCAP);
/* enable edge capture on selected channel */
status = DEBIread(dev,
((struct dio_private *)(dev->subdevices + 2 +
group)->private)->RDCapSel);
DEBIwrite(dev,
((struct dio_private *)(dev->subdevices + 2 +
group)->private)->WRCapSel,
bitmask | status);
return 0;
}
static int s626_dio_reset_irq(struct comedi_device *dev, unsigned int group,
unsigned int mask)
{
DEBUG
("s626_dio_reset_irq: disable interrupt on dio channel %d group %d\n",
mask, group);
/* disable edge capture write command */
DEBIwrite(dev, LP_MISC1, MISC1_NOEDCAP);
/* enable edge capture on selected channel */
DEBIwrite(dev,
((struct dio_private *)(dev->subdevices + 2 +
group)->private)->WRCapSel, mask);
return 0;
}
static int s626_dio_clear_irq(struct comedi_device *dev)
{
unsigned int group;
/* disable edge capture write command */
DEBIwrite(dev, LP_MISC1, MISC1_NOEDCAP);
for (group = 0; group < S626_DIO_BANKS; group++) {
/* clear pending events and interrupt */
DEBIwrite(dev,
((struct dio_private *)(dev->subdevices + 2 +
group)->private)->WRCapSel,
0xffff);
}
return 0;
}
/* Now this function initializes the value of the counter (data[0])
and set the subdevice. To complete with trigger and interrupt
configuration */
static int s626_enc_insn_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
uint16_t Setup = (LOADSRC_INDX << BF_LOADSRC) | /* Preload upon */
/* index. */
(INDXSRC_SOFT << BF_INDXSRC) | /* Disable hardware index. */
(CLKSRC_COUNTER << BF_CLKSRC) | /* Operating mode is Counter. */
(CLKPOL_POS << BF_CLKPOL) | /* Active high clock. */
/* ( CNTDIR_UP << BF_CLKPOL ) | // Count direction is Down. */
(CLKMULT_1X << BF_CLKMULT) | /* Clock multiplier is 1x. */
(CLKENAB_INDEX << BF_CLKENAB);
/* uint16_t DisableIntSrc=TRUE; */
/* uint32_t Preloadvalue; //Counter initial value */
uint16_t valueSrclatch = LATCHSRC_AB_READ;
uint16_t enab = CLKENAB_ALWAYS;
struct enc_private *k = &encpriv[CR_CHAN(insn->chanspec)];
DEBUG("s626_enc_insn_config: encoder config\n");
/* (data==NULL) ? (Preloadvalue=0) : (Preloadvalue=data[0]); */
k->SetMode(dev, k, Setup, TRUE);
Preload(dev, k, *(insn->data));
k->PulseIndex(dev, k);
SetLatchSource(dev, k, valueSrclatch);
k->SetEnable(dev, k, (uint16_t) (enab != 0));
return insn->n;
}
static int s626_enc_insn_read(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int n;
struct enc_private *k = &encpriv[CR_CHAN(insn->chanspec)];
DEBUG("s626_enc_insn_read: encoder read channel %d\n",
CR_CHAN(insn->chanspec));
for (n = 0; n < insn->n; n++)
data[n] = ReadLatch(dev, k);
DEBUG("s626_enc_insn_read: encoder sample %d\n", data[n]);
return n;
}
static int s626_enc_insn_write(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
struct enc_private *k = &encpriv[CR_CHAN(insn->chanspec)];
DEBUG("s626_enc_insn_write: encoder write channel %d\n",
CR_CHAN(insn->chanspec));
/* Set the preload register */
Preload(dev, k, data[0]);
/* Software index pulse forces the preload register to load */
/* into the counter */
k->SetLoadTrig(dev, k, 0);
k->PulseIndex(dev, k);
k->SetLoadTrig(dev, k, 2);
DEBUG("s626_enc_insn_write: End encoder write\n");
return 1;
}
static void s626_timer_load(struct comedi_device *dev, struct enc_private *k,
int tick)
{
uint16_t Setup = (LOADSRC_INDX << BF_LOADSRC) | /* Preload upon */
/* index. */
(INDXSRC_SOFT << BF_INDXSRC) | /* Disable hardware index. */
(CLKSRC_TIMER << BF_CLKSRC) | /* Operating mode is Timer. */
(CLKPOL_POS << BF_CLKPOL) | /* Active high clock. */
(CNTDIR_DOWN << BF_CLKPOL) | /* Count direction is Down. */
(CLKMULT_1X << BF_CLKMULT) | /* Clock multiplier is 1x. */
(CLKENAB_INDEX << BF_CLKENAB);
uint16_t valueSrclatch = LATCHSRC_A_INDXA;
/* uint16_t enab=CLKENAB_ALWAYS; */
k->SetMode(dev, k, Setup, FALSE);
/* Set the preload register */
Preload(dev, k, tick);
/* Software index pulse forces the preload register to load */
/* into the counter */
k->SetLoadTrig(dev, k, 0);
k->PulseIndex(dev, k);
/* set reload on counter overflow */
k->SetLoadTrig(dev, k, 1);
/* set interrupt on overflow */
k->SetIntSrc(dev, k, INTSRC_OVER);
SetLatchSource(dev, k, valueSrclatch);
/* k->SetEnable(dev,k,(uint16_t)(enab != 0)); */
}
/* *********** DAC FUNCTIONS *********** */
/* Slot 0 base settings. */
#define VECT0 (XSD2 | RSD3 | SIB_A2)
/* Slot 0 always shifts in 0xFF and store it to FB_BUFFER2. */
/* TrimDac LogicalChan-to-PhysicalChan mapping table. */
static uint8_t trimchan[] = { 10, 9, 8, 3, 2, 7, 6, 1, 0, 5, 4 };
/* TrimDac LogicalChan-to-EepromAdrs mapping table. */
static uint8_t trimadrs[] = { 0x40, 0x41, 0x42, 0x50, 0x51, 0x52, 0x53, 0x60, 0x61, 0x62, 0x63 };
static void LoadTrimDACs(struct comedi_device *dev)
{
register uint8_t i;
/* Copy TrimDac setpoint values from EEPROM to TrimDacs. */
for (i = 0; i < ARRAY_SIZE(trimchan); i++)
WriteTrimDAC(dev, i, I2Cread(dev, trimadrs[i]));
}
static void WriteTrimDAC(struct comedi_device *dev, uint8_t LogicalChan,
uint8_t DacData)
{
uint32_t chan;
/* Save the new setpoint in case the application needs to read it back later. */
devpriv->TrimSetpoint[LogicalChan] = (uint8_t) DacData;
/* Map logical channel number to physical channel number. */
chan = (uint32_t) trimchan[LogicalChan];
/* Set up TSL2 records for TrimDac write operation. All slots shift
* 0xFF in from pulled-up SD3 so that the end of the slot sequence
* can be detected.
*/
SETVECT(2, XSD2 | XFIFO_1 | WS3);
/* Slot 2: Send high uint8_t to target TrimDac. */
SETVECT(3, XSD2 | XFIFO_0 | WS3);
/* Slot 3: Send low uint8_t to target TrimDac. */
SETVECT(4, XSD2 | XFIFO_3 | WS1);
/* Slot 4: Send NOP high uint8_t to DAC0 to keep clock running. */
SETVECT(5, XSD2 | XFIFO_2 | WS1 | EOS);
/* Slot 5: Send NOP low uint8_t to DAC0. */
/* Construct and transmit target DAC's serial packet:
* ( 0000 AAAA ), ( DDDD DDDD ),( 0x00 ),( 0x00 ) where A<3:0> is the
* DAC channel's address, and D<7:0> is the DAC setpoint. Append a
* WORD value (that writes a channel 0 NOP command to a non-existent
* main DAC channel) that serves to keep the clock running after the
* packet has been sent to the target DAC.
*/
/* Address the DAC channel within the trimdac device. */
SendDAC(dev, ((uint32_t) chan << 8)
| (uint32_t) DacData); /* Include DAC setpoint data. */
}
/* ************** EEPROM ACCESS FUNCTIONS ************** */
/* Read uint8_t from EEPROM. */
static uint8_t I2Cread(struct comedi_device *dev, uint8_t addr)
{
uint8_t rtnval;
/* Send EEPROM target address. */
if (I2Chandshake(dev, I2C_B2(I2C_ATTRSTART, I2CW)
/* Byte2 = I2C command: write to I2C EEPROM device. */
| I2C_B1(I2C_ATTRSTOP, addr)
/* Byte1 = EEPROM internal target address. */
| I2C_B0(I2C_ATTRNOP, 0))) { /* Byte0 = Not sent. */
/* Abort function and declare error if handshake failed. */
DEBUG("I2Cread: error handshake I2Cread a\n");
return 0;
}
/* Execute EEPROM read. */
if (I2Chandshake(dev, I2C_B2(I2C_ATTRSTART, I2CR)
/* Byte2 = I2C */
/* command: read */
/* from I2C EEPROM */
/* device. */
|I2C_B1(I2C_ATTRSTOP, 0)
/* Byte1 receives */
/* uint8_t from */
/* EEPROM. */
|I2C_B0(I2C_ATTRNOP, 0))) { /* Byte0 = Not sent. */
/* Abort function and declare error if handshake failed. */
DEBUG("I2Cread: error handshake I2Cread b\n");
return 0;
}
/* Return copy of EEPROM value. */
rtnval = (uint8_t) (RR7146(P_I2CCTRL) >> 16);
return rtnval;
}
static uint32_t I2Chandshake(struct comedi_device *dev, uint32_t val)
{
/* Write I2C command to I2C Transfer Control shadow register. */
WR7146(P_I2CCTRL, val);
/* Upload I2C shadow registers into working registers and wait for */
/* upload confirmation. */
MC_ENABLE(P_MC2, MC2_UPLD_IIC);
while (!MC_TEST(P_MC2, MC2_UPLD_IIC))
;
/* Wait until I2C bus transfer is finished or an error occurs. */
while ((RR7146(P_I2CCTRL) & (I2C_BUSY | I2C_ERR)) == I2C_BUSY)
;
/* Return non-zero if I2C error occurred. */
return RR7146(P_I2CCTRL) & I2C_ERR;
}
/* Private helper function: Write setpoint to an application DAC channel. */
static void SetDAC(struct comedi_device *dev, uint16_t chan, short dacdata)
{
register uint16_t signmask;
register uint32_t WSImage;
/* Adjust DAC data polarity and set up Polarity Control Register */
/* image. */
signmask = 1 << chan;
if (dacdata < 0) {
dacdata = -dacdata;
devpriv->Dacpol |= signmask;
} else
devpriv->Dacpol &= ~signmask;
/* Limit DAC setpoint value to valid range. */
if ((uint16_t) dacdata > 0x1FFF)
dacdata = 0x1FFF;
/* Set up TSL2 records (aka "vectors") for DAC update. Vectors V2
* and V3 transmit the setpoint to the target DAC. V4 and V5 send
* data to a non-existent TrimDac channel just to keep the clock
* running after sending data to the target DAC. This is necessary
* to eliminate the clock glitch that would otherwise occur at the
* end of the target DAC's serial data stream. When the sequence
* restarts at V0 (after executing V5), the gate array automatically
* disables gating for the DAC clock and all DAC chip selects.
*/
WSImage = (chan & 2) ? WS1 : WS2;
/* Choose DAC chip select to be asserted. */
SETVECT(2, XSD2 | XFIFO_1 | WSImage);
/* Slot 2: Transmit high data byte to target DAC. */
SETVECT(3, XSD2 | XFIFO_0 | WSImage);
/* Slot 3: Transmit low data byte to target DAC. */
SETVECT(4, XSD2 | XFIFO_3 | WS3);
/* Slot 4: Transmit to non-existent TrimDac channel to keep clock */
SETVECT(5, XSD2 | XFIFO_2 | WS3 | EOS);
/* Slot 5: running after writing target DAC's low data byte. */
/* Construct and transmit target DAC's serial packet:
* ( A10D DDDD ),( DDDD DDDD ),( 0x0F ),( 0x00 ) where A is chan<0>,
* and D<12:0> is the DAC setpoint. Append a WORD value (that writes
* to a non-existent TrimDac channel) that serves to keep the clock
* running after the packet has been sent to the target DAC.
*/
SendDAC(dev, 0x0F000000
/* Continue clock after target DAC data (write to non-existent trimdac). */
| 0x00004000
/* Address the two main dual-DAC devices (TSL's chip select enables
* target device). */
| ((uint32_t) (chan & 1) << 15)
/* Address the DAC channel within the device. */
| (uint32_t) dacdata); /* Include DAC setpoint data. */
}
/* Private helper function: Transmit serial data to DAC via Audio
* channel 2. Assumes: (1) TSL2 slot records initialized, and (2)
* Dacpol contains valid target image.
*/
static void SendDAC(struct comedi_device *dev, uint32_t val)
{
/* START THE SERIAL CLOCK RUNNING ------------- */
/* Assert DAC polarity control and enable gating of DAC serial clock
* and audio bit stream signals. At this point in time we must be
* assured of being in time slot 0. If we are not in slot 0, the
* serial clock and audio stream signals will be disabled; this is
* because the following DEBIwrite statement (which enables signals
* to be passed through the gate array) would execute before the
* trailing edge of WS1/WS3 (which turns off the signals), thus
* causing the signals to be inactive during the DAC write.
*/
DEBIwrite(dev, LP_DACPOL, devpriv->Dacpol);
/* TRANSFER OUTPUT DWORD VALUE INTO A2'S OUTPUT FIFO ---------------- */
/* Copy DAC setpoint value to DAC's output DMA buffer. */
/* WR7146( (uint32_t)devpriv->pDacWBuf, val ); */
*devpriv->pDacWBuf = val;
/* enab the output DMA transfer. This will cause the DMAC to copy
* the DAC's data value to A2's output FIFO. The DMA transfer will
* then immediately terminate because the protection address is
* reached upon transfer of the first DWORD value.
*/
MC_ENABLE(P_MC1, MC1_A2OUT);
/* While the DMA transfer is executing ... */
/* Reset Audio2 output FIFO's underflow flag (along with any other
* FIFO underflow/overflow flags). When set, this flag will
* indicate that we have emerged from slot 0.
*/
WR7146(P_ISR, ISR_AFOU);
/* Wait for the DMA transfer to finish so that there will be data
* available in the FIFO when time slot 1 tries to transfer a DWORD
* from the FIFO to the output buffer register. We test for DMA
* Done by polling the DMAC enable flag; this flag is automatically
* cleared when the transfer has finished.
*/
while ((RR7146(P_MC1) & MC1_A2OUT) != 0)
;
/* START THE OUTPUT STREAM TO THE TARGET DAC -------------------- */
/* FIFO data is now available, so we enable execution of time slots
* 1 and higher by clearing the EOS flag in slot 0. Note that SD3
* will be shifted in and stored in FB_BUFFER2 for end-of-slot-list
* detection.
*/
SETVECT(0, XSD2 | RSD3 | SIB_A2);
/* Wait for slot 1 to execute to ensure that the Packet will be
* transmitted. This is detected by polling the Audio2 output FIFO
* underflow flag, which will be set when slot 1 execution has
* finished transferring the DAC's data DWORD from the output FIFO
* to the output buffer register.
*/
while ((RR7146(P_SSR) & SSR_AF2_OUT) == 0)
;
/* Set up to trap execution at slot 0 when the TSL sequencer cycles
* back to slot 0 after executing the EOS in slot 5. Also,
* simultaneously shift out and in the 0x00 that is ALWAYS the value
* stored in the last byte to be shifted out of the FIFO's DWORD
* buffer register.
*/
SETVECT(0, XSD2 | XFIFO_2 | RSD2 | SIB_A2 | EOS);
/* WAIT FOR THE TRANSACTION TO FINISH ----------------------- */
/* Wait for the TSL to finish executing all time slots before
* exiting this function. We must do this so that the next DAC
* write doesn't start, thereby enabling clock/chip select signals:
*
* 1. Before the TSL sequence cycles back to slot 0, which disables
* the clock/cs signal gating and traps slot // list execution.
* we have not yet finished slot 5 then the clock/cs signals are
* still gated and we have not finished transmitting the stream.
*
* 2. While slots 2-5 are executing due to a late slot 0 trap. In
* this case, the slot sequence is currently repeating, but with
* clock/cs signals disabled. We must wait for slot 0 to trap
* execution before setting up the next DAC setpoint DMA transfer
* and enabling the clock/cs signals. To detect the end of slot 5,
* we test for the FB_BUFFER2 MSB contents to be equal to 0xFF. If
* the TSL has not yet finished executing slot 5 ...
*/
if ((RR7146(P_FB_BUFFER2) & 0xFF000000) != 0) {
/* The trap was set on time and we are still executing somewhere
* in slots 2-5, so we now wait for slot 0 to execute and trap
* TSL execution. This is detected when FB_BUFFER2 MSB changes
* from 0xFF to 0x00, which slot 0 causes to happen by shifting
* out/in on SD2 the 0x00 that is always referenced by slot 5.
*/
while ((RR7146(P_FB_BUFFER2) & 0xFF000000) != 0)
;
}
/* Either (1) we were too late setting the slot 0 trap; the TSL
* sequencer restarted slot 0 before we could set the EOS trap flag,
* or (2) we were not late and execution is now trapped at slot 0.
* In either case, we must now change slot 0 so that it will store
* value 0xFF (instead of 0x00) to FB_BUFFER2 next time it executes.
* In order to do this, we reprogram slot 0 so that it will shift in
* SD3, which is driven only by a pull-up resistor.
*/
SETVECT(0, RSD3 | SIB_A2 | EOS);
/* Wait for slot 0 to execute, at which time the TSL is setup for
* the next DAC write. This is detected when FB_BUFFER2 MSB changes
* from 0x00 to 0xFF.
*/
while ((RR7146(P_FB_BUFFER2) & 0xFF000000) == 0)
;
}
static void WriteMISC2(struct comedi_device *dev, uint16_t NewImage)
{
DEBIwrite(dev, LP_MISC1, MISC1_WENABLE); /* enab writes to */
/* MISC2 register. */
DEBIwrite(dev, LP_WRMISC2, NewImage); /* Write new image to MISC2. */
DEBIwrite(dev, LP_MISC1, MISC1_WDISABLE); /* Disable writes to MISC2. */
}
/* Initialize the DEBI interface for all transfers. */
static uint16_t DEBIread(struct comedi_device *dev, uint16_t addr)
{
uint16_t retval;
/* Set up DEBI control register value in shadow RAM. */
WR7146(P_DEBICMD, DEBI_CMD_RDWORD | addr);
/* Execute the DEBI transfer. */
DEBItransfer(dev);
/* Fetch target register value. */
retval = (uint16_t) RR7146(P_DEBIAD);
/* Return register value. */
return retval;
}
/* Execute a DEBI transfer. This must be called from within a */
/* critical section. */
static void DEBItransfer(struct comedi_device *dev)
{
/* Initiate upload of shadow RAM to DEBI control register. */
MC_ENABLE(P_MC2, MC2_UPLD_DEBI);
/* Wait for completion of upload from shadow RAM to DEBI control */
/* register. */
while (!MC_TEST(P_MC2, MC2_UPLD_DEBI))
;
/* Wait until DEBI transfer is done. */
while (RR7146(P_PSR) & PSR_DEBI_S)
;
}
/* Write a value to a gate array register. */
static void DEBIwrite(struct comedi_device *dev, uint16_t addr, uint16_t wdata)
{
/* Set up DEBI control register value in shadow RAM. */
WR7146(P_DEBICMD, DEBI_CMD_WRWORD | addr);
WR7146(P_DEBIAD, wdata);
/* Execute the DEBI transfer. */
DEBItransfer(dev);
}
/* Replace the specified bits in a gate array register. Imports: mask
* specifies bits that are to be preserved, wdata is new value to be
* or'd with the masked original.
*/
static void DEBIreplace(struct comedi_device *dev, uint16_t addr, uint16_t mask,
uint16_t wdata)
{
/* Copy target gate array register into P_DEBIAD register. */
WR7146(P_DEBICMD, DEBI_CMD_RDWORD | addr);
/* Set up DEBI control reg value in shadow RAM. */
DEBItransfer(dev); /* Execute the DEBI Read transfer. */
/* Write back the modified image. */
WR7146(P_DEBICMD, DEBI_CMD_WRWORD | addr);
/* Set up DEBI control reg value in shadow RAM. */
WR7146(P_DEBIAD, wdata | ((uint16_t) RR7146(P_DEBIAD) & mask));
/* Modify the register image. */
DEBItransfer(dev); /* Execute the DEBI Write transfer. */
}
static void CloseDMAB(struct comedi_device *dev, struct bufferDMA *pdma,
size_t bsize)
{
void *vbptr;
dma_addr_t vpptr;
DEBUG("CloseDMAB: Entering S626DRV_CloseDMAB():\n");
if (pdma == NULL)
return;
/* find the matching allocation from the board struct */
vbptr = pdma->LogicalBase;
vpptr = pdma->PhysicalBase;
if (vbptr) {
pci_free_consistent(devpriv->pdev, bsize, vbptr, vpptr);
pdma->LogicalBase = 0;
pdma->PhysicalBase = 0;
DEBUG("CloseDMAB(): Logical=%p, bsize=%d, Physical=0x%x\n",
vbptr, bsize, (uint32_t) vpptr);
}
}
/* ****** COUNTER FUNCTIONS ******* */
/* All counter functions address a specific counter by means of the
* "Counter" argument, which is a logical counter number. The Counter
* argument may have any of the following legal values: 0=0A, 1=1A,
* 2=2A, 3=0B, 4=1B, 5=2B.
*/
/* Forward declarations for functions that are common to both A and B counters: */
/* ****** PRIVATE COUNTER FUNCTIONS ****** */
/* Read a counter's output latch. */
static uint32_t ReadLatch(struct comedi_device *dev, struct enc_private *k)
{
register uint32_t value;
/* DEBUG FIXME DEBUG("ReadLatch: Read Latch enter\n"); */
/* Latch counts and fetch LSW of latched counts value. */
value = (uint32_t) DEBIread(dev, k->MyLatchLsw);
/* Fetch MSW of latched counts and combine with LSW. */
value |= ((uint32_t) DEBIread(dev, k->MyLatchLsw + 2) << 16);
/* DEBUG FIXME DEBUG("ReadLatch: Read Latch exit\n"); */
/* Return latched counts. */
return value;
}
/* Reset a counter's index and overflow event capture flags. */
static void ResetCapFlags_A(struct comedi_device *dev, struct enc_private *k)
{
DEBIreplace(dev, k->MyCRB, (uint16_t) (~CRBMSK_INTCTRL),
CRBMSK_INTRESETCMD | CRBMSK_INTRESET_A);
}
static void ResetCapFlags_B(struct comedi_device *dev, struct enc_private *k)
{
DEBIreplace(dev, k->MyCRB, (uint16_t) (~CRBMSK_INTCTRL),
CRBMSK_INTRESETCMD | CRBMSK_INTRESET_B);
}
/* Return counter setup in a format (COUNTER_SETUP) that is consistent */
/* for both A and B counters. */
static uint16_t GetMode_A(struct comedi_device *dev, struct enc_private *k)
{
register uint16_t cra;
register uint16_t crb;
register uint16_t setup;
/* Fetch CRA and CRB register images. */
cra = DEBIread(dev, k->MyCRA);
crb = DEBIread(dev, k->MyCRB);
/* Populate the standardized counter setup bit fields. Note: */
/* IndexSrc is restricted to ENC_X or IndxPol. */
setup = ((cra & STDMSK_LOADSRC) /* LoadSrc = LoadSrcA. */
|((crb << (STDBIT_LATCHSRC - CRBBIT_LATCHSRC)) & STDMSK_LATCHSRC) /* LatchSrc = LatchSrcA. */
|((cra << (STDBIT_INTSRC - CRABIT_INTSRC_A)) & STDMSK_INTSRC) /* IntSrc = IntSrcA. */
|((cra << (STDBIT_INDXSRC - (CRABIT_INDXSRC_A + 1))) & STDMSK_INDXSRC) /* IndxSrc = IndxSrcA<1>. */
|((cra >> (CRABIT_INDXPOL_A - STDBIT_INDXPOL)) & STDMSK_INDXPOL) /* IndxPol = IndxPolA. */
|((crb >> (CRBBIT_CLKENAB_A - STDBIT_CLKENAB)) & STDMSK_CLKENAB)); /* ClkEnab = ClkEnabA. */
/* Adjust mode-dependent parameters. */
if (cra & (2 << CRABIT_CLKSRC_A)) /* If Timer mode (ClkSrcA<1> == 1): */
setup |= ((CLKSRC_TIMER << STDBIT_CLKSRC) /* Indicate Timer mode. */
|((cra << (STDBIT_CLKPOL - CRABIT_CLKSRC_A)) & STDMSK_CLKPOL) /* Set ClkPol to indicate count direction (ClkSrcA<0>). */
|(MULT_X1 << STDBIT_CLKMULT)); /* ClkMult must be 1x in Timer mode. */
else /* If Counter mode (ClkSrcA<1> == 0): */
setup |= ((CLKSRC_COUNTER << STDBIT_CLKSRC) /* Indicate Counter mode. */
|((cra >> (CRABIT_CLKPOL_A - STDBIT_CLKPOL)) & STDMSK_CLKPOL) /* Pass through ClkPol. */
|(((cra & CRAMSK_CLKMULT_A) == (MULT_X0 << CRABIT_CLKMULT_A)) ? /* Force ClkMult to 1x if not legal, else pass through. */
(MULT_X1 << STDBIT_CLKMULT) :
((cra >> (CRABIT_CLKMULT_A -
STDBIT_CLKMULT)) & STDMSK_CLKMULT)));
/* Return adjusted counter setup. */
return setup;
}
static uint16_t GetMode_B(struct comedi_device *dev, struct enc_private *k)
{
register uint16_t cra;
register uint16_t crb;
register uint16_t setup;
/* Fetch CRA and CRB register images. */
cra = DEBIread(dev, k->MyCRA);
crb = DEBIread(dev, k->MyCRB);
/* Populate the standardized counter setup bit fields. Note: */
/* IndexSrc is restricted to ENC_X or IndxPol. */
setup = (((crb << (STDBIT_INTSRC - CRBBIT_INTSRC_B)) & STDMSK_INTSRC) /* IntSrc = IntSrcB. */
|((crb << (STDBIT_LATCHSRC - CRBBIT_LATCHSRC)) & STDMSK_LATCHSRC) /* LatchSrc = LatchSrcB. */
|((crb << (STDBIT_LOADSRC - CRBBIT_LOADSRC_B)) & STDMSK_LOADSRC) /* LoadSrc = LoadSrcB. */
|((crb << (STDBIT_INDXPOL - CRBBIT_INDXPOL_B)) & STDMSK_INDXPOL) /* IndxPol = IndxPolB. */
|((crb >> (CRBBIT_CLKENAB_B - STDBIT_CLKENAB)) & STDMSK_CLKENAB) /* ClkEnab = ClkEnabB. */
|((cra >> ((CRABIT_INDXSRC_B + 1) - STDBIT_INDXSRC)) & STDMSK_INDXSRC)); /* IndxSrc = IndxSrcB<1>. */
/* Adjust mode-dependent parameters. */
if ((crb & CRBMSK_CLKMULT_B) == (MULT_X0 << CRBBIT_CLKMULT_B)) /* If Extender mode (ClkMultB == MULT_X0): */
setup |= ((CLKSRC_EXTENDER << STDBIT_CLKSRC) /* Indicate Extender mode. */
|(MULT_X1 << STDBIT_CLKMULT) /* Indicate multiplier is 1x. */
|((cra >> (CRABIT_CLKSRC_B - STDBIT_CLKPOL)) & STDMSK_CLKPOL)); /* Set ClkPol equal to Timer count direction (ClkSrcB<0>). */
else if (cra & (2 << CRABIT_CLKSRC_B)) /* If Timer mode (ClkSrcB<1> == 1): */
setup |= ((CLKSRC_TIMER << STDBIT_CLKSRC) /* Indicate Timer mode. */
|(MULT_X1 << STDBIT_CLKMULT) /* Indicate multiplier is 1x. */
|((cra >> (CRABIT_CLKSRC_B - STDBIT_CLKPOL)) & STDMSK_CLKPOL)); /* Set ClkPol equal to Timer count direction (ClkSrcB<0>). */
else /* If Counter mode (ClkSrcB<1> == 0): */
setup |= ((CLKSRC_COUNTER << STDBIT_CLKSRC) /* Indicate Timer mode. */
|((crb >> (CRBBIT_CLKMULT_B - STDBIT_CLKMULT)) & STDMSK_CLKMULT) /* Clock multiplier is passed through. */
|((crb << (STDBIT_CLKPOL - CRBBIT_CLKPOL_B)) & STDMSK_CLKPOL)); /* Clock polarity is passed through. */
/* Return adjusted counter setup. */
return setup;
}
/*
* Set the operating mode for the specified counter. The setup
* parameter is treated as a COUNTER_SETUP data type. The following
* parameters are programmable (all other parms are ignored): ClkMult,
* ClkPol, ClkEnab, IndexSrc, IndexPol, LoadSrc.
*/
static void SetMode_A(struct comedi_device *dev, struct enc_private *k,
uint16_t Setup, uint16_t DisableIntSrc)
{
register uint16_t cra;
register uint16_t crb;
register uint16_t setup = Setup; /* Cache the Standard Setup. */
/* Initialize CRA and CRB images. */
cra = ((setup & CRAMSK_LOADSRC_A) /* Preload trigger is passed through. */
|((setup & STDMSK_INDXSRC) >> (STDBIT_INDXSRC - (CRABIT_INDXSRC_A + 1)))); /* IndexSrc is restricted to ENC_X or IndxPol. */
crb = (CRBMSK_INTRESETCMD | CRBMSK_INTRESET_A /* Reset any pending CounterA event captures. */
| ((setup & STDMSK_CLKENAB) << (CRBBIT_CLKENAB_A - STDBIT_CLKENAB))); /* Clock enable is passed through. */
/* Force IntSrc to Disabled if DisableIntSrc is asserted. */
if (!DisableIntSrc)
cra |= ((setup & STDMSK_INTSRC) >> (STDBIT_INTSRC -
CRABIT_INTSRC_A));
/* Populate all mode-dependent attributes of CRA & CRB images. */
switch ((setup & STDMSK_CLKSRC) >> STDBIT_CLKSRC) {
case CLKSRC_EXTENDER: /* Extender Mode: Force to Timer mode */
/* (Extender valid only for B counters). */
case CLKSRC_TIMER: /* Timer Mode: */
cra |= ((2 << CRABIT_CLKSRC_A) /* ClkSrcA<1> selects system clock */
|((setup & STDMSK_CLKPOL) >> (STDBIT_CLKPOL - CRABIT_CLKSRC_A)) /* with count direction (ClkSrcA<0>) obtained from ClkPol. */
|(1 << CRABIT_CLKPOL_A) /* ClkPolA behaves as always-on clock enable. */
|(MULT_X1 << CRABIT_CLKMULT_A)); /* ClkMult must be 1x. */
break;
default: /* Counter Mode: */
cra |= (CLKSRC_COUNTER /* Select ENC_C and ENC_D as clock/direction inputs. */
| ((setup & STDMSK_CLKPOL) << (CRABIT_CLKPOL_A - STDBIT_CLKPOL)) /* Clock polarity is passed through. */
|(((setup & STDMSK_CLKMULT) == (MULT_X0 << STDBIT_CLKMULT)) ? /* Force multiplier to x1 if not legal, otherwise pass through. */
(MULT_X1 << CRABIT_CLKMULT_A) :
((setup & STDMSK_CLKMULT) << (CRABIT_CLKMULT_A -
STDBIT_CLKMULT))));
}
/* Force positive index polarity if IndxSrc is software-driven only, */
/* otherwise pass it through. */
if (~setup & STDMSK_INDXSRC)
cra |= ((setup & STDMSK_INDXPOL) << (CRABIT_INDXPOL_A -
STDBIT_INDXPOL));
/* If IntSrc has been forced to Disabled, update the MISC2 interrupt */
/* enable mask to indicate the counter interrupt is disabled. */
if (DisableIntSrc)
devpriv->CounterIntEnabs &= ~k->MyEventBits[3];
/* While retaining CounterB and LatchSrc configurations, program the */
/* new counter operating mode. */
DEBIreplace(dev, k->MyCRA, CRAMSK_INDXSRC_B | CRAMSK_CLKSRC_B, cra);
DEBIreplace(dev, k->MyCRB,
(uint16_t) (~(CRBMSK_INTCTRL | CRBMSK_CLKENAB_A)), crb);
}
static void SetMode_B(struct comedi_device *dev, struct enc_private *k,
uint16_t Setup, uint16_t DisableIntSrc)
{
register uint16_t cra;
register uint16_t crb;
register uint16_t setup = Setup; /* Cache the Standard Setup. */
/* Initialize CRA and CRB images. */
cra = ((setup & STDMSK_INDXSRC) << ((CRABIT_INDXSRC_B + 1) - STDBIT_INDXSRC)); /* IndexSrc field is restricted to ENC_X or IndxPol. */
crb = (CRBMSK_INTRESETCMD | CRBMSK_INTRESET_B /* Reset event captures and disable interrupts. */
| ((setup & STDMSK_CLKENAB) << (CRBBIT_CLKENAB_B - STDBIT_CLKENAB)) /* Clock enable is passed through. */
|((setup & STDMSK_LOADSRC) >> (STDBIT_LOADSRC - CRBBIT_LOADSRC_B))); /* Preload trigger source is passed through. */
/* Force IntSrc to Disabled if DisableIntSrc is asserted. */
if (!DisableIntSrc)
crb |= ((setup & STDMSK_INTSRC) >> (STDBIT_INTSRC -
CRBBIT_INTSRC_B));
/* Populate all mode-dependent attributes of CRA & CRB images. */
switch ((setup & STDMSK_CLKSRC) >> STDBIT_CLKSRC) {
case CLKSRC_TIMER: /* Timer Mode: */
cra |= ((2 << CRABIT_CLKSRC_B) /* ClkSrcB<1> selects system clock */
|((setup & STDMSK_CLKPOL) << (CRABIT_CLKSRC_B - STDBIT_CLKPOL))); /* with direction (ClkSrcB<0>) obtained from ClkPol. */
crb |= ((1 << CRBBIT_CLKPOL_B) /* ClkPolB behaves as always-on clock enable. */
|(MULT_X1 << CRBBIT_CLKMULT_B)); /* ClkMultB must be 1x. */
break;
case CLKSRC_EXTENDER: /* Extender Mode: */
cra |= ((2 << CRABIT_CLKSRC_B) /* ClkSrcB source is OverflowA (same as "timer") */
|((setup & STDMSK_CLKPOL) << (CRABIT_CLKSRC_B - STDBIT_CLKPOL))); /* with direction obtained from ClkPol. */
crb |= ((1 << CRBBIT_CLKPOL_B) /* ClkPolB controls IndexB -- always set to active. */
|(MULT_X0 << CRBBIT_CLKMULT_B)); /* ClkMultB selects OverflowA as the clock source. */
break;
default: /* Counter Mode: */
cra |= (CLKSRC_COUNTER << CRABIT_CLKSRC_B); /* Select ENC_C and ENC_D as clock/direction inputs. */
crb |= (((setup & STDMSK_CLKPOL) >> (STDBIT_CLKPOL - CRBBIT_CLKPOL_B)) /* ClkPol is passed through. */
|(((setup & STDMSK_CLKMULT) == (MULT_X0 << STDBIT_CLKMULT)) ? /* Force ClkMult to x1 if not legal, otherwise pass through. */
(MULT_X1 << CRBBIT_CLKMULT_B) :
((setup & STDMSK_CLKMULT) << (CRBBIT_CLKMULT_B -
STDBIT_CLKMULT))));
}
/* Force positive index polarity if IndxSrc is software-driven only, */
/* otherwise pass it through. */
if (~setup & STDMSK_INDXSRC)
crb |= ((setup & STDMSK_INDXPOL) >> (STDBIT_INDXPOL -
CRBBIT_INDXPOL_B));
/* If IntSrc has been forced to Disabled, update the MISC2 interrupt */
/* enable mask to indicate the counter interrupt is disabled. */
if (DisableIntSrc)
devpriv->CounterIntEnabs &= ~k->MyEventBits[3];
/* While retaining CounterA and LatchSrc configurations, program the */
/* new counter operating mode. */
DEBIreplace(dev, k->MyCRA,
(uint16_t) (~(CRAMSK_INDXSRC_B | CRAMSK_CLKSRC_B)), cra);
DEBIreplace(dev, k->MyCRB, CRBMSK_CLKENAB_A | CRBMSK_LATCHSRC, crb);
}
/* Return/set a counter's enable. enab: 0=always enabled, 1=enabled by index. */
static void SetEnable_A(struct comedi_device *dev, struct enc_private *k,
uint16_t enab)
{
DEBUG("SetEnable_A: SetEnable_A enter 3541\n");
DEBIreplace(dev, k->MyCRB,
(uint16_t) (~(CRBMSK_INTCTRL | CRBMSK_CLKENAB_A)),
(uint16_t) (enab << CRBBIT_CLKENAB_A));
}
static void SetEnable_B(struct comedi_device *dev, struct enc_private *k,
uint16_t enab)
{
DEBIreplace(dev, k->MyCRB,
(uint16_t) (~(CRBMSK_INTCTRL | CRBMSK_CLKENAB_B)),
(uint16_t) (enab << CRBBIT_CLKENAB_B));
}
static uint16_t GetEnable_A(struct comedi_device *dev, struct enc_private *k)
{
return (DEBIread(dev, k->MyCRB) >> CRBBIT_CLKENAB_A) & 1;
}
static uint16_t GetEnable_B(struct comedi_device *dev, struct enc_private *k)
{
return (DEBIread(dev, k->MyCRB) >> CRBBIT_CLKENAB_B) & 1;
}
/* Return/set a counter pair's latch trigger source. 0: On read
* access, 1: A index latches A, 2: B index latches B, 3: A overflow
* latches B.
*/
static void SetLatchSource(struct comedi_device *dev, struct enc_private *k,
uint16_t value)
{
DEBUG("SetLatchSource: SetLatchSource enter 3550\n");
DEBIreplace(dev, k->MyCRB,
(uint16_t) (~(CRBMSK_INTCTRL | CRBMSK_LATCHSRC)),
(uint16_t) (value << CRBBIT_LATCHSRC));
DEBUG("SetLatchSource: SetLatchSource exit\n");
}
/*
* static uint16_t GetLatchSource(struct comedi_device *dev, struct enc_private *k )
* {
* return ( DEBIread( dev, k->MyCRB) >> CRBBIT_LATCHSRC ) & 3;
* }
*/
/*
* Return/set the event that will trigger transfer of the preload
* register into the counter. 0=ThisCntr_Index, 1=ThisCntr_Overflow,
* 2=OverflowA (B counters only), 3=disabled.
*/
static void SetLoadTrig_A(struct comedi_device *dev, struct enc_private *k,
uint16_t Trig)
{
DEBIreplace(dev, k->MyCRA, (uint16_t) (~CRAMSK_LOADSRC_A),
(uint16_t) (Trig << CRABIT_LOADSRC_A));
}
static void SetLoadTrig_B(struct comedi_device *dev, struct enc_private *k,
uint16_t Trig)
{
DEBIreplace(dev, k->MyCRB,
(uint16_t) (~(CRBMSK_LOADSRC_B | CRBMSK_INTCTRL)),
(uint16_t) (Trig << CRBBIT_LOADSRC_B));
}
static uint16_t GetLoadTrig_A(struct comedi_device *dev, struct enc_private *k)
{
return (DEBIread(dev, k->MyCRA) >> CRABIT_LOADSRC_A) & 3;
}
static uint16_t GetLoadTrig_B(struct comedi_device *dev, struct enc_private *k)
{
return (DEBIread(dev, k->MyCRB) >> CRBBIT_LOADSRC_B) & 3;
}
/* Return/set counter interrupt source and clear any captured
* index/overflow events. IntSource: 0=Disabled, 1=OverflowOnly,
* 2=IndexOnly, 3=IndexAndOverflow.
*/
static void SetIntSrc_A(struct comedi_device *dev, struct enc_private *k,
uint16_t IntSource)
{
/* Reset any pending counter overflow or index captures. */
DEBIreplace(dev, k->MyCRB, (uint16_t) (~CRBMSK_INTCTRL),
CRBMSK_INTRESETCMD | CRBMSK_INTRESET_A);
/* Program counter interrupt source. */
DEBIreplace(dev, k->MyCRA, ~CRAMSK_INTSRC_A,
(uint16_t) (IntSource << CRABIT_INTSRC_A));
/* Update MISC2 interrupt enable mask. */
devpriv->CounterIntEnabs =
(devpriv->CounterIntEnabs & ~k->
MyEventBits[3]) | k->MyEventBits[IntSource];
}
static void SetIntSrc_B(struct comedi_device *dev, struct enc_private *k,
uint16_t IntSource)
{
uint16_t crb;
/* Cache writeable CRB register image. */
crb = DEBIread(dev, k->MyCRB) & ~CRBMSK_INTCTRL;
/* Reset any pending counter overflow or index captures. */
DEBIwrite(dev, k->MyCRB,
(uint16_t) (crb | CRBMSK_INTRESETCMD | CRBMSK_INTRESET_B));
/* Program counter interrupt source. */
DEBIwrite(dev, k->MyCRB,
(uint16_t) ((crb & ~CRBMSK_INTSRC_B) | (IntSource <<
CRBBIT_INTSRC_B)));
/* Update MISC2 interrupt enable mask. */
devpriv->CounterIntEnabs =
(devpriv->CounterIntEnabs & ~k->
MyEventBits[3]) | k->MyEventBits[IntSource];
}
static uint16_t GetIntSrc_A(struct comedi_device *dev, struct enc_private *k)
{
return (DEBIread(dev, k->MyCRA) >> CRABIT_INTSRC_A) & 3;
}
static uint16_t GetIntSrc_B(struct comedi_device *dev, struct enc_private *k)
{
return (DEBIread(dev, k->MyCRB) >> CRBBIT_INTSRC_B) & 3;
}
/* Return/set the clock multiplier. */
/* static void SetClkMult(struct comedi_device *dev, struct enc_private *k, uint16_t value ) */
/* { */
/* k->SetMode(dev, k, (uint16_t)( ( k->GetMode(dev, k ) & ~STDMSK_CLKMULT ) | ( value << STDBIT_CLKMULT ) ), FALSE ); */
/* } */
/* static uint16_t GetClkMult(struct comedi_device *dev, struct enc_private *k ) */
/* { */
/* return ( k->GetMode(dev, k ) >> STDBIT_CLKMULT ) & 3; */
/* } */
/* Return/set the clock polarity. */
/* static void SetClkPol( struct comedi_device *dev,struct enc_private *k, uint16_t value ) */
/* { */
/* k->SetMode(dev, k, (uint16_t)( ( k->GetMode(dev, k ) & ~STDMSK_CLKPOL ) | ( value << STDBIT_CLKPOL ) ), FALSE ); */
/* } */
/* static uint16_t GetClkPol(struct comedi_device *dev, struct enc_private *k ) */
/* { */
/* return ( k->GetMode(dev, k ) >> STDBIT_CLKPOL ) & 1; */
/* } */
/* Return/set the clock source. */
/* static void SetClkSrc( struct comedi_device *dev,struct enc_private *k, uint16_t value ) */
/* { */
/* k->SetMode(dev, k, (uint16_t)( ( k->GetMode(dev, k ) & ~STDMSK_CLKSRC ) | ( value << STDBIT_CLKSRC ) ), FALSE ); */
/* } */
/* static uint16_t GetClkSrc( struct comedi_device *dev,struct enc_private *k ) */
/* { */
/* return ( k->GetMode(dev, k ) >> STDBIT_CLKSRC ) & 3; */
/* } */
/* Return/set the index polarity. */
/* static void SetIndexPol(struct comedi_device *dev, struct enc_private *k, uint16_t value ) */
/* { */
/* k->SetMode(dev, k, (uint16_t)( ( k->GetMode(dev, k ) & ~STDMSK_INDXPOL ) | ( (value != 0) << STDBIT_INDXPOL ) ), FALSE ); */
/* } */
/* static uint16_t GetIndexPol(struct comedi_device *dev, struct enc_private *k ) */
/* { */
/* return ( k->GetMode(dev, k ) >> STDBIT_INDXPOL ) & 1; */
/* } */
/* Return/set the index source. */
/* static void SetIndexSrc(struct comedi_device *dev, struct enc_private *k, uint16_t value ) */
/* { */
/* DEBUG("SetIndexSrc: set index src enter 3700\n"); */
/* k->SetMode(dev, k, (uint16_t)( ( k->GetMode(dev, k ) & ~STDMSK_INDXSRC ) | ( (value != 0) << STDBIT_INDXSRC ) ), FALSE ); */
/* } */
/* static uint16_t GetIndexSrc(struct comedi_device *dev, struct enc_private *k ) */
/* { */
/* return ( k->GetMode(dev, k ) >> STDBIT_INDXSRC ) & 1; */
/* } */
/* Generate an index pulse. */
static void PulseIndex_A(struct comedi_device *dev, struct enc_private *k)
{
register uint16_t cra;
DEBUG("PulseIndex_A: pulse index enter\n");
cra = DEBIread(dev, k->MyCRA); /* Pulse index. */
DEBIwrite(dev, k->MyCRA, (uint16_t) (cra ^ CRAMSK_INDXPOL_A));
DEBUG("PulseIndex_A: pulse index step1\n");
DEBIwrite(dev, k->MyCRA, cra);
}
static void PulseIndex_B(struct comedi_device *dev, struct enc_private *k)
{
register uint16_t crb;
crb = DEBIread(dev, k->MyCRB) & ~CRBMSK_INTCTRL; /* Pulse index. */
DEBIwrite(dev, k->MyCRB, (uint16_t) (crb ^ CRBMSK_INDXPOL_B));
DEBIwrite(dev, k->MyCRB, crb);
}
/* Write value into counter preload register. */
static void Preload(struct comedi_device *dev, struct enc_private *k,
uint32_t value)
{
DEBUG("Preload: preload enter\n");
DEBIwrite(dev, (uint16_t) (k->MyLatchLsw), (uint16_t) value); /* Write value to preload register. */
DEBUG("Preload: preload step 1\n");
DEBIwrite(dev, (uint16_t) (k->MyLatchLsw + 2),
(uint16_t) (value >> 16));
}
static void CountersInit(struct comedi_device *dev)
{
int chan;
struct enc_private *k;
uint16_t Setup = (LOADSRC_INDX << BF_LOADSRC) | /* Preload upon */
/* index. */
(INDXSRC_SOFT << BF_INDXSRC) | /* Disable hardware index. */
(CLKSRC_COUNTER << BF_CLKSRC) | /* Operating mode is counter. */
(CLKPOL_POS << BF_CLKPOL) | /* Active high clock. */
(CNTDIR_UP << BF_CLKPOL) | /* Count direction is up. */
(CLKMULT_1X << BF_CLKMULT) | /* Clock multiplier is 1x. */
(CLKENAB_INDEX << BF_CLKENAB); /* Enabled by index */
/* Disable all counter interrupts and clear any captured counter events. */
for (chan = 0; chan < S626_ENCODER_CHANNELS; chan++) {
k = &encpriv[chan];
k->SetMode(dev, k, Setup, TRUE);
k->SetIntSrc(dev, k, 0);
k->ResetCapFlags(dev, k);
k->SetEnable(dev, k, CLKENAB_ALWAYS);
}
DEBUG("CountersInit: counters initialized\n");
}
| gpl-2.0 |
faust93/F93_LGE975_KK_Kernel | drivers/media/dvb/dvb-usb/mxl111sf-i2c.c | 7733 | 18612 | /*
* mxl111sf-i2c.c - driver for the MaxLinear MXL111SF
*
* Copyright (C) 2010 Michael Krufky <mkrufky@kernellabs.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "mxl111sf-i2c.h"
#include "mxl111sf.h"
/* SW-I2C ----------------------------------------------------------------- */
#define SW_I2C_ADDR 0x1a
#define SW_I2C_EN 0x02
#define SW_SCL_OUT 0x04
#define SW_SDA_OUT 0x08
#define SW_SDA_IN 0x04
#define SW_I2C_BUSY_ADDR 0x2f
#define SW_I2C_BUSY 0x02
static int mxl111sf_i2c_bitbang_sendbyte(struct mxl111sf_state *state,
u8 byte)
{
int i, ret;
u8 data = 0;
mxl_i2c("(0x%02x)", byte);
ret = mxl111sf_read_reg(state, SW_I2C_BUSY_ADDR, &data);
if (mxl_fail(ret))
goto fail;
for (i = 0; i < 8; i++) {
data = (byte & (0x80 >> i)) ? SW_SDA_OUT : 0;
ret = mxl111sf_write_reg(state, SW_I2C_ADDR,
0x10 | SW_I2C_EN | data);
if (mxl_fail(ret))
goto fail;
ret = mxl111sf_write_reg(state, SW_I2C_ADDR,
0x10 | SW_I2C_EN | data | SW_SCL_OUT);
if (mxl_fail(ret))
goto fail;
ret = mxl111sf_write_reg(state, SW_I2C_ADDR,
0x10 | SW_I2C_EN | data);
if (mxl_fail(ret))
goto fail;
}
/* last bit was 0 so we need to release SDA */
if (!(byte & 1)) {
ret = mxl111sf_write_reg(state, SW_I2C_ADDR,
0x10 | SW_I2C_EN | SW_SDA_OUT);
if (mxl_fail(ret))
goto fail;
}
/* CLK high for ACK readback */
ret = mxl111sf_write_reg(state, SW_I2C_ADDR,
0x10 | SW_I2C_EN | SW_SCL_OUT | SW_SDA_OUT);
if (mxl_fail(ret))
goto fail;
ret = mxl111sf_read_reg(state, SW_I2C_BUSY_ADDR, &data);
if (mxl_fail(ret))
goto fail;
/* drop the CLK after getting ACK, SDA will go high right away */
ret = mxl111sf_write_reg(state, SW_I2C_ADDR,
0x10 | SW_I2C_EN | SW_SDA_OUT);
if (mxl_fail(ret))
goto fail;
if (data & SW_SDA_IN)
ret = -EIO;
fail:
return ret;
}
static int mxl111sf_i2c_bitbang_recvbyte(struct mxl111sf_state *state,
u8 *pbyte)
{
int i, ret;
u8 byte = 0;
u8 data = 0;
mxl_i2c("()");
*pbyte = 0;
ret = mxl111sf_write_reg(state, SW_I2C_ADDR,
0x10 | SW_I2C_EN | SW_SDA_OUT);
if (mxl_fail(ret))
goto fail;
for (i = 0; i < 8; i++) {
ret = mxl111sf_write_reg(state, SW_I2C_ADDR,
0x10 | SW_I2C_EN |
SW_SCL_OUT | SW_SDA_OUT);
if (mxl_fail(ret))
goto fail;
ret = mxl111sf_read_reg(state, SW_I2C_BUSY_ADDR, &data);
if (mxl_fail(ret))
goto fail;
if (data & SW_SDA_IN)
byte |= (0x80 >> i);
ret = mxl111sf_write_reg(state, SW_I2C_ADDR,
0x10 | SW_I2C_EN | SW_SDA_OUT);
if (mxl_fail(ret))
goto fail;
}
*pbyte = byte;
fail:
return ret;
}
static int mxl111sf_i2c_start(struct mxl111sf_state *state)
{
int ret;
mxl_i2c("()");
ret = mxl111sf_write_reg(state, SW_I2C_ADDR,
0x10 | SW_I2C_EN | SW_SCL_OUT | SW_SDA_OUT);
if (mxl_fail(ret))
goto fail;
ret = mxl111sf_write_reg(state, SW_I2C_ADDR,
0x10 | SW_I2C_EN | SW_SCL_OUT);
if (mxl_fail(ret))
goto fail;
ret = mxl111sf_write_reg(state, SW_I2C_ADDR,
0x10 | SW_I2C_EN); /* start */
mxl_fail(ret);
fail:
return ret;
}
static int mxl111sf_i2c_stop(struct mxl111sf_state *state)
{
int ret;
mxl_i2c("()");
ret = mxl111sf_write_reg(state, SW_I2C_ADDR,
0x10 | SW_I2C_EN); /* stop */
if (mxl_fail(ret))
goto fail;
ret = mxl111sf_write_reg(state, SW_I2C_ADDR,
0x10 | SW_I2C_EN | SW_SCL_OUT);
if (mxl_fail(ret))
goto fail;
ret = mxl111sf_write_reg(state, SW_I2C_ADDR,
0x10 | SW_I2C_EN | SW_SCL_OUT | SW_SDA_OUT);
if (mxl_fail(ret))
goto fail;
ret = mxl111sf_write_reg(state, SW_I2C_ADDR,
0x10 | SW_SCL_OUT | SW_SDA_OUT);
mxl_fail(ret);
fail:
return ret;
}
static int mxl111sf_i2c_ack(struct mxl111sf_state *state)
{
int ret;
u8 b = 0;
mxl_i2c("()");
ret = mxl111sf_read_reg(state, SW_I2C_BUSY_ADDR, &b);
if (mxl_fail(ret))
goto fail;
ret = mxl111sf_write_reg(state, SW_I2C_ADDR,
0x10 | SW_I2C_EN);
if (mxl_fail(ret))
goto fail;
/* pull SDA low */
ret = mxl111sf_write_reg(state, SW_I2C_ADDR,
0x10 | SW_I2C_EN | SW_SCL_OUT);
if (mxl_fail(ret))
goto fail;
ret = mxl111sf_write_reg(state, SW_I2C_ADDR,
0x10 | SW_I2C_EN | SW_SDA_OUT);
mxl_fail(ret);
fail:
return ret;
}
static int mxl111sf_i2c_nack(struct mxl111sf_state *state)
{
int ret;
mxl_i2c("()");
/* SDA high to signal last byte read from slave */
ret = mxl111sf_write_reg(state, SW_I2C_ADDR,
0x10 | SW_I2C_EN | SW_SCL_OUT | SW_SDA_OUT);
if (mxl_fail(ret))
goto fail;
ret = mxl111sf_write_reg(state, SW_I2C_ADDR,
0x10 | SW_I2C_EN | SW_SDA_OUT);
mxl_fail(ret);
fail:
return ret;
}
/* ------------------------------------------------------------------------ */
static int mxl111sf_i2c_sw_xfer_msg(struct mxl111sf_state *state,
struct i2c_msg *msg)
{
int i, ret;
mxl_i2c("()");
if (msg->flags & I2C_M_RD) {
ret = mxl111sf_i2c_start(state);
if (mxl_fail(ret))
goto fail;
ret = mxl111sf_i2c_bitbang_sendbyte(state,
(msg->addr << 1) | 0x01);
if (mxl_fail(ret)) {
mxl111sf_i2c_stop(state);
goto fail;
}
for (i = 0; i < msg->len; i++) {
ret = mxl111sf_i2c_bitbang_recvbyte(state,
&msg->buf[i]);
if (mxl_fail(ret)) {
mxl111sf_i2c_stop(state);
goto fail;
}
if (i < msg->len - 1)
mxl111sf_i2c_ack(state);
}
mxl111sf_i2c_nack(state);
ret = mxl111sf_i2c_stop(state);
if (mxl_fail(ret))
goto fail;
} else {
ret = mxl111sf_i2c_start(state);
if (mxl_fail(ret))
goto fail;
ret = mxl111sf_i2c_bitbang_sendbyte(state,
(msg->addr << 1) & 0xfe);
if (mxl_fail(ret)) {
mxl111sf_i2c_stop(state);
goto fail;
}
for (i = 0; i < msg->len; i++) {
ret = mxl111sf_i2c_bitbang_sendbyte(state,
msg->buf[i]);
if (mxl_fail(ret)) {
mxl111sf_i2c_stop(state);
goto fail;
}
}
/* FIXME: we only want to do this on the last transaction */
mxl111sf_i2c_stop(state);
}
fail:
return ret;
}
/* HW-I2C ----------------------------------------------------------------- */
#define USB_WRITE_I2C_CMD 0x99
#define USB_READ_I2C_CMD 0xdd
#define USB_END_I2C_CMD 0xfe
#define USB_WRITE_I2C_CMD_LEN 26
#define USB_READ_I2C_CMD_LEN 24
#define I2C_MUX_REG 0x30
#define I2C_CONTROL_REG 0x00
#define I2C_SLAVE_ADDR_REG 0x08
#define I2C_DATA_REG 0x0c
#define I2C_INT_STATUS_REG 0x10
static int mxl111sf_i2c_send_data(struct mxl111sf_state *state,
u8 index, u8 *wdata)
{
int ret = mxl111sf_ctrl_msg(state->d, wdata[0],
&wdata[1], 25, NULL, 0);
mxl_fail(ret);
return ret;
}
static int mxl111sf_i2c_get_data(struct mxl111sf_state *state,
u8 index, u8 *wdata, u8 *rdata)
{
int ret = mxl111sf_ctrl_msg(state->d, wdata[0],
&wdata[1], 25, rdata, 24);
mxl_fail(ret);
return ret;
}
static u8 mxl111sf_i2c_check_status(struct mxl111sf_state *state)
{
u8 status = 0;
u8 buf[26];
mxl_i2c_adv("()");
buf[0] = USB_READ_I2C_CMD;
buf[1] = 0x00;
buf[2] = I2C_INT_STATUS_REG;
buf[3] = 0x00;
buf[4] = 0x00;
buf[5] = USB_END_I2C_CMD;
mxl111sf_i2c_get_data(state, 0, buf, buf);
if (buf[1] & 0x04)
status = 1;
return status;
}
static u8 mxl111sf_i2c_check_fifo(struct mxl111sf_state *state)
{
u8 status = 0;
u8 buf[26];
mxl_i2c("()");
buf[0] = USB_READ_I2C_CMD;
buf[1] = 0x00;
buf[2] = I2C_MUX_REG;
buf[3] = 0x00;
buf[4] = 0x00;
buf[5] = I2C_INT_STATUS_REG;
buf[6] = 0x00;
buf[7] = 0x00;
buf[8] = USB_END_I2C_CMD;
mxl111sf_i2c_get_data(state, 0, buf, buf);
if (0x08 == (buf[1] & 0x08))
status = 1;
if ((buf[5] & 0x02) == 0x02)
mxl_i2c("(buf[5] & 0x02) == 0x02"); /* FIXME */
return status;
}
static int mxl111sf_i2c_readagain(struct mxl111sf_state *state,
u8 count, u8 *rbuf)
{
u8 i2c_w_data[26];
u8 i2c_r_data[24];
u8 i = 0;
u8 fifo_status = 0;
int status = 0;
mxl_i2c("read %d bytes", count);
while ((fifo_status == 0) && (i++ < 5))
fifo_status = mxl111sf_i2c_check_fifo(state);
i2c_w_data[0] = 0xDD;
i2c_w_data[1] = 0x00;
for (i = 2; i < 26; i++)
i2c_w_data[i] = 0xFE;
for (i = 0; i < count; i++) {
i2c_w_data[2+(i*3)] = 0x0C;
i2c_w_data[3+(i*3)] = 0x00;
i2c_w_data[4+(i*3)] = 0x00;
}
mxl111sf_i2c_get_data(state, 0, i2c_w_data, i2c_r_data);
/* Check for I2C NACK status */
if (mxl111sf_i2c_check_status(state) == 1) {
mxl_i2c("error!");
} else {
for (i = 0; i < count; i++) {
rbuf[i] = i2c_r_data[(i*3)+1];
mxl_i2c("%02x\t %02x",
i2c_r_data[(i*3)+1],
i2c_r_data[(i*3)+2]);
}
status = 1;
}
return status;
}
#define HWI2C400 1
static int mxl111sf_i2c_hw_xfer_msg(struct mxl111sf_state *state,
struct i2c_msg *msg)
{
int i, k, ret = 0;
u16 index = 0;
u8 buf[26];
u8 i2c_r_data[24];
u16 block_len;
u16 left_over_len;
u8 rd_status[8];
u8 ret_status;
u8 readbuff[26];
mxl_i2c("addr: 0x%02x, read buff len: %d, write buff len: %d",
msg->addr, (msg->flags & I2C_M_RD) ? msg->len : 0,
(!(msg->flags & I2C_M_RD)) ? msg->len : 0);
for (index = 0; index < 26; index++)
buf[index] = USB_END_I2C_CMD;
/* command to indicate data payload is destined for I2C interface */
buf[0] = USB_WRITE_I2C_CMD;
buf[1] = 0x00;
/* enable I2C interface */
buf[2] = I2C_MUX_REG;
buf[3] = 0x80;
buf[4] = 0x00;
/* enable I2C interface */
buf[5] = I2C_MUX_REG;
buf[6] = 0x81;
buf[7] = 0x00;
/* set Timeout register on I2C interface */
buf[8] = 0x14;
buf[9] = 0xff;
buf[10] = 0x00;
#if 0
/* enable Interrupts on I2C interface */
buf[8] = 0x24;
buf[9] = 0xF7;
buf[10] = 0x00;
#endif
buf[11] = 0x24;
buf[12] = 0xF7;
buf[13] = 0x00;
ret = mxl111sf_i2c_send_data(state, 0, buf);
/* write data on I2C bus */
if (!(msg->flags & I2C_M_RD) && (msg->len > 0)) {
mxl_i2c("%d\t%02x", msg->len, msg->buf[0]);
/* control register on I2C interface to initialize I2C bus */
buf[2] = I2C_CONTROL_REG;
buf[3] = 0x5E;
buf[4] = (HWI2C400) ? 0x03 : 0x0D;
/* I2C Slave device Address */
buf[5] = I2C_SLAVE_ADDR_REG;
buf[6] = (msg->addr);
buf[7] = 0x00;
buf[8] = USB_END_I2C_CMD;
ret = mxl111sf_i2c_send_data(state, 0, buf);
/* check for slave device status */
if (mxl111sf_i2c_check_status(state) == 1) {
mxl_i2c("NACK writing slave address %02x",
msg->addr);
/* if NACK, stop I2C bus and exit */
buf[2] = I2C_CONTROL_REG;
buf[3] = 0x4E;
buf[4] = (HWI2C400) ? 0x03 : 0x0D;
ret = -EIO;
goto exit;
}
/* I2C interface can do I2C operations in block of 8 bytes of
I2C data. calculation to figure out number of blocks of i2c
data required to program */
block_len = (msg->len / 8);
left_over_len = (msg->len % 8);
index = 0;
mxl_i2c("block_len %d, left_over_len %d",
block_len, left_over_len);
for (index = 0; index < block_len; index++) {
for (i = 0; i < 8; i++) {
/* write data on I2C interface */
buf[2+(i*3)] = I2C_DATA_REG;
buf[3+(i*3)] = msg->buf[(index*8)+i];
buf[4+(i*3)] = 0x00;
}
ret = mxl111sf_i2c_send_data(state, 0, buf);
/* check for I2C NACK status */
if (mxl111sf_i2c_check_status(state) == 1) {
mxl_i2c("NACK writing slave address %02x",
msg->addr);
/* if NACK, stop I2C bus and exit */
buf[2] = I2C_CONTROL_REG;
buf[3] = 0x4E;
buf[4] = (HWI2C400) ? 0x03 : 0x0D;
ret = -EIO;
goto exit;
}
}
if (left_over_len) {
for (k = 0; k < 26; k++)
buf[k] = USB_END_I2C_CMD;
buf[0] = 0x99;
buf[1] = 0x00;
for (i = 0; i < left_over_len; i++) {
buf[2+(i*3)] = I2C_DATA_REG;
buf[3+(i*3)] = msg->buf[(index*8)+i];
mxl_i2c("index = %d %d data %d",
index, i, msg->buf[(index*8)+i]);
buf[4+(i*3)] = 0x00;
}
ret = mxl111sf_i2c_send_data(state, 0, buf);
/* check for I2C NACK status */
if (mxl111sf_i2c_check_status(state) == 1) {
mxl_i2c("NACK writing slave address %02x",
msg->addr);
/* if NACK, stop I2C bus and exit */
buf[2] = I2C_CONTROL_REG;
buf[3] = 0x4E;
buf[4] = (HWI2C400) ? 0x03 : 0x0D;
ret = -EIO;
goto exit;
}
}
/* issue I2C STOP after write */
buf[2] = I2C_CONTROL_REG;
buf[3] = 0x4E;
buf[4] = (HWI2C400) ? 0x03 : 0x0D;
}
/* read data from I2C bus */
if ((msg->flags & I2C_M_RD) && (msg->len > 0)) {
mxl_i2c("read buf len %d", msg->len);
/* command to indicate data payload is
destined for I2C interface */
buf[2] = I2C_CONTROL_REG;
buf[3] = 0xDF;
buf[4] = (HWI2C400) ? 0x03 : 0x0D;
/* I2C xfer length */
buf[5] = 0x14;
buf[6] = (msg->len & 0xFF);
buf[7] = 0;
/* I2C slave device Address */
buf[8] = I2C_SLAVE_ADDR_REG;
buf[9] = msg->addr;
buf[10] = 0x00;
buf[11] = USB_END_I2C_CMD;
ret = mxl111sf_i2c_send_data(state, 0, buf);
/* check for I2C NACK status */
if (mxl111sf_i2c_check_status(state) == 1) {
mxl_i2c("NACK reading slave address %02x",
msg->addr);
/* if NACK, stop I2C bus and exit */
buf[2] = I2C_CONTROL_REG;
buf[3] = 0xC7;
buf[4] = (HWI2C400) ? 0x03 : 0x0D;
ret = -EIO;
goto exit;
}
/* I2C interface can do I2C operations in block of 8 bytes of
I2C data. calculation to figure out number of blocks of
i2c data required to program */
block_len = ((msg->len) / 8);
left_over_len = ((msg->len) % 8);
index = 0;
mxl_i2c("block_len %d, left_over_len %d",
block_len, left_over_len);
/* command to read data from I2C interface */
buf[0] = USB_READ_I2C_CMD;
buf[1] = 0x00;
for (index = 0; index < block_len; index++) {
/* setup I2C read request packet on I2C interface */
for (i = 0; i < 8; i++) {
buf[2+(i*3)] = I2C_DATA_REG;
buf[3+(i*3)] = 0x00;
buf[4+(i*3)] = 0x00;
}
ret = mxl111sf_i2c_get_data(state, 0, buf, i2c_r_data);
/* check for I2C NACK status */
if (mxl111sf_i2c_check_status(state) == 1) {
mxl_i2c("NACK reading slave address %02x",
msg->addr);
/* if NACK, stop I2C bus and exit */
buf[2] = I2C_CONTROL_REG;
buf[3] = 0xC7;
buf[4] = (HWI2C400) ? 0x03 : 0x0D;
ret = -EIO;
goto exit;
}
/* copy data from i2c data payload to read buffer */
for (i = 0; i < 8; i++) {
rd_status[i] = i2c_r_data[(i*3)+2];
if (rd_status[i] == 0x04) {
if (i < 7) {
mxl_i2c("i2c fifo empty!"
" @ %d", i);
msg->buf[(index*8)+i] =
i2c_r_data[(i*3)+1];
/* read again */
ret_status =
mxl111sf_i2c_readagain(
state, 8-(i+1),
readbuff);
if (ret_status == 1) {
for (k = 0;
k < 8-(i+1);
k++) {
msg->buf[(index*8)+(k+i+1)] =
readbuff[k];
mxl_i2c("read data: %02x\t %02x",
msg->buf[(index*8)+(k+i)],
(index*8)+(k+i));
mxl_i2c("read data: %02x\t %02x",
msg->buf[(index*8)+(k+i+1)],
readbuff[k]);
}
goto stop_copy;
} else {
mxl_i2c("readagain "
"ERROR!");
}
} else {
msg->buf[(index*8)+i] =
i2c_r_data[(i*3)+1];
}
} else {
msg->buf[(index*8)+i] =
i2c_r_data[(i*3)+1];
}
}
stop_copy:
;
}
if (left_over_len) {
for (k = 0; k < 26; k++)
buf[k] = USB_END_I2C_CMD;
buf[0] = 0xDD;
buf[1] = 0x00;
for (i = 0; i < left_over_len; i++) {
buf[2+(i*3)] = I2C_DATA_REG;
buf[3+(i*3)] = 0x00;
buf[4+(i*3)] = 0x00;
}
ret = mxl111sf_i2c_get_data(state, 0, buf,
i2c_r_data);
/* check for I2C NACK status */
if (mxl111sf_i2c_check_status(state) == 1) {
mxl_i2c("NACK reading slave address %02x",
msg->addr);
/* if NACK, stop I2C bus and exit */
buf[2] = I2C_CONTROL_REG;
buf[3] = 0xC7;
buf[4] = (HWI2C400) ? 0x03 : 0x0D;
ret = -EIO;
goto exit;
}
for (i = 0; i < left_over_len; i++) {
msg->buf[(block_len*8)+i] =
i2c_r_data[(i*3)+1];
mxl_i2c("read data: %02x\t %02x",
i2c_r_data[(i*3)+1],
i2c_r_data[(i*3)+2]);
}
}
/* indicate I2C interface to issue NACK
after next I2C read op */
buf[0] = USB_WRITE_I2C_CMD;
buf[1] = 0x00;
/* control register */
buf[2] = I2C_CONTROL_REG;
buf[3] = 0x17;
buf[4] = (HWI2C400) ? 0x03 : 0x0D;
buf[5] = USB_END_I2C_CMD;
ret = mxl111sf_i2c_send_data(state, 0, buf);
/* control register */
buf[2] = I2C_CONTROL_REG;
buf[3] = 0xC7;
buf[4] = (HWI2C400) ? 0x03 : 0x0D;
}
exit:
/* STOP and disable I2C MUX */
buf[0] = USB_WRITE_I2C_CMD;
buf[1] = 0x00;
/* de-initilize I2C BUS */
buf[5] = USB_END_I2C_CMD;
mxl111sf_i2c_send_data(state, 0, buf);
/* Control Register */
buf[2] = I2C_CONTROL_REG;
buf[3] = 0xDF;
buf[4] = 0x03;
/* disable I2C interface */
buf[5] = I2C_MUX_REG;
buf[6] = 0x00;
buf[7] = 0x00;
/* de-initilize I2C BUS */
buf[8] = USB_END_I2C_CMD;
mxl111sf_i2c_send_data(state, 0, buf);
/* disable I2C interface */
buf[2] = I2C_MUX_REG;
buf[3] = 0x81;
buf[4] = 0x00;
/* disable I2C interface */
buf[5] = I2C_MUX_REG;
buf[6] = 0x00;
buf[7] = 0x00;
/* disable I2C interface */
buf[8] = I2C_MUX_REG;
buf[9] = 0x00;
buf[10] = 0x00;
buf[11] = USB_END_I2C_CMD;
mxl111sf_i2c_send_data(state, 0, buf);
return ret;
}
/* ------------------------------------------------------------------------ */
int mxl111sf_i2c_xfer(struct i2c_adapter *adap,
struct i2c_msg msg[], int num)
{
struct dvb_usb_device *d = i2c_get_adapdata(adap);
struct mxl111sf_state *state = d->priv;
int hwi2c = (state->chip_rev > MXL111SF_V6);
int i, ret;
if (mutex_lock_interruptible(&d->i2c_mutex) < 0)
return -EAGAIN;
for (i = 0; i < num; i++) {
ret = (hwi2c) ?
mxl111sf_i2c_hw_xfer_msg(state, &msg[i]) :
mxl111sf_i2c_sw_xfer_msg(state, &msg[i]);
if (mxl_fail(ret)) {
mxl_debug_adv("failed with error %d on i2c "
"transaction %d of %d, %sing %d bytes "
"to/from 0x%02x", ret, i+1, num,
(msg[i].flags & I2C_M_RD) ?
"read" : "writ",
msg[i].len, msg[i].addr);
break;
}
}
mutex_unlock(&d->i2c_mutex);
return i == num ? num : -EREMOTEIO;
}
/*
* Local variables:
* c-basic-offset: 8
* End:
*/
| gpl-2.0 |
a-martynovich/kernel_goldfish | arch/blackfin/kernel/ftrace.c | 7733 | 3251 | /*
* ftrace graph code
*
* Copyright (C) 2009-2010 Analog Devices Inc.
* Licensed under the GPL-2 or later.
*/
#include <linux/ftrace.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/uaccess.h>
#include <linux/atomic.h>
#include <asm/cacheflush.h>
#ifdef CONFIG_DYNAMIC_FTRACE
static const unsigned char mnop[] = {
0x03, 0xc0, 0x00, 0x18, /* MNOP; */
0x03, 0xc0, 0x00, 0x18, /* MNOP; */
};
static void bfin_make_pcrel24(unsigned char *insn, unsigned long src,
unsigned long dst)
{
uint32_t pcrel = (dst - src) >> 1;
insn[0] = pcrel >> 16;
insn[1] = 0xe3;
insn[2] = pcrel;
insn[3] = pcrel >> 8;
}
#define bfin_make_pcrel24(insn, src, dst) bfin_make_pcrel24(insn, src, (unsigned long)(dst))
static int ftrace_modify_code(unsigned long ip, const unsigned char *code,
unsigned long len)
{
int ret = probe_kernel_write((void *)ip, (void *)code, len);
flush_icache_range(ip, ip + len);
return ret;
}
int ftrace_make_nop(struct module *mod, struct dyn_ftrace *rec,
unsigned long addr)
{
/* Turn the mcount call site into two MNOPs as those are 32bit insns */
return ftrace_modify_code(rec->ip, mnop, sizeof(mnop));
}
int ftrace_make_call(struct dyn_ftrace *rec, unsigned long addr)
{
/* Restore the mcount call site */
unsigned char call[8];
call[0] = 0x67; /* [--SP] = RETS; */
call[1] = 0x01;
bfin_make_pcrel24(&call[2], rec->ip + 2, addr);
call[6] = 0x27; /* RETS = [SP++]; */
call[7] = 0x01;
return ftrace_modify_code(rec->ip, call, sizeof(call));
}
int ftrace_update_ftrace_func(ftrace_func_t func)
{
unsigned char call[4];
unsigned long ip = (unsigned long)&ftrace_call;
bfin_make_pcrel24(call, ip, func);
return ftrace_modify_code(ip, call, sizeof(call));
}
int __init ftrace_dyn_arch_init(void *data)
{
/* return value is done indirectly via data */
*(unsigned long *)data = 0;
return 0;
}
#endif
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
# ifdef CONFIG_DYNAMIC_FTRACE
extern void ftrace_graph_call(void);
int ftrace_enable_ftrace_graph_caller(void)
{
unsigned long ip = (unsigned long)&ftrace_graph_call;
uint16_t jump_pcrel12 = ((unsigned long)&ftrace_graph_caller - ip) >> 1;
jump_pcrel12 |= 0x2000;
return ftrace_modify_code(ip, (void *)&jump_pcrel12, sizeof(jump_pcrel12));
}
int ftrace_disable_ftrace_graph_caller(void)
{
return ftrace_modify_code((unsigned long)&ftrace_graph_call, empty_zero_page, 2);
}
# endif
/*
* Hook the return address and push it in the stack of return addrs
* in current thread info.
*/
void prepare_ftrace_return(unsigned long *parent, unsigned long self_addr,
unsigned long frame_pointer)
{
struct ftrace_graph_ent trace;
unsigned long return_hooker = (unsigned long)&return_to_handler;
if (unlikely(atomic_read(¤t->tracing_graph_pause)))
return;
if (ftrace_push_return_trace(*parent, self_addr, &trace.depth,
frame_pointer) == -EBUSY)
return;
trace.func = self_addr;
/* Only trace if the calling function expects to */
if (!ftrace_graph_entry(&trace)) {
current->curr_ret_stack--;
return;
}
/* all is well in the world ! hijack RETS ... */
*parent = return_hooker;
}
#endif
| gpl-2.0 |
varunchitre15/android_kernel_xperiaL | arch/tile/kernel/asm-offsets.c | 10037 | 2662 | /*
* Copyright 2010 Tilera Corporation. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, version 2.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for
* more details.
*
* Generates definitions from c-type structures used by assembly sources.
*/
#include <linux/kbuild.h>
#include <linux/thread_info.h>
#include <linux/sched.h>
#include <linux/hardirq.h>
#include <linux/ptrace.h>
#include <hv/hypervisor.h>
/* Check for compatible compiler early in the build. */
#ifdef CONFIG_TILEGX
# ifndef __tilegx__
# error Can only build TILE-Gx configurations with tilegx compiler
# endif
# ifndef __LP64__
# error Must not specify -m32 when building the TILE-Gx kernel
# endif
#else
# ifdef __tilegx__
# error Can not build TILEPro/TILE64 configurations with tilegx compiler
# endif
#endif
void foo(void)
{
DEFINE(SINGLESTEP_STATE_BUFFER_OFFSET, \
offsetof(struct single_step_state, buffer));
DEFINE(SINGLESTEP_STATE_FLAGS_OFFSET, \
offsetof(struct single_step_state, flags));
DEFINE(SINGLESTEP_STATE_ORIG_PC_OFFSET, \
offsetof(struct single_step_state, orig_pc));
DEFINE(SINGLESTEP_STATE_NEXT_PC_OFFSET, \
offsetof(struct single_step_state, next_pc));
DEFINE(SINGLESTEP_STATE_BRANCH_NEXT_PC_OFFSET, \
offsetof(struct single_step_state, branch_next_pc));
DEFINE(SINGLESTEP_STATE_UPDATE_VALUE_OFFSET, \
offsetof(struct single_step_state, update_value));
DEFINE(THREAD_INFO_TASK_OFFSET, \
offsetof(struct thread_info, task));
DEFINE(THREAD_INFO_FLAGS_OFFSET, \
offsetof(struct thread_info, flags));
DEFINE(THREAD_INFO_STATUS_OFFSET, \
offsetof(struct thread_info, status));
DEFINE(THREAD_INFO_HOMECACHE_CPU_OFFSET, \
offsetof(struct thread_info, homecache_cpu));
DEFINE(THREAD_INFO_STEP_STATE_OFFSET, \
offsetof(struct thread_info, step_state));
DEFINE(TASK_STRUCT_THREAD_KSP_OFFSET,
offsetof(struct task_struct, thread.ksp));
DEFINE(TASK_STRUCT_THREAD_PC_OFFSET,
offsetof(struct task_struct, thread.pc));
DEFINE(HV_TOPOLOGY_WIDTH_OFFSET, \
offsetof(HV_Topology, width));
DEFINE(HV_TOPOLOGY_HEIGHT_OFFSET, \
offsetof(HV_Topology, height));
DEFINE(IRQ_CPUSTAT_SYSCALL_COUNT_OFFSET, \
offsetof(irq_cpustat_t, irq_syscall_count));
}
| gpl-2.0 |
santod/android_kernel_htc_m8 | drivers/tty/serial/8250/8250_accent.c | 12341 | 1029 | /*
* Copyright (C) 2005 Russell King.
* Data taken from include/asm-i386/serial.h
*
* 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/serial_8250.h>
#define PORT(_base,_irq) \
{ \
.iobase = _base, \
.irq = _irq, \
.uartclk = 1843200, \
.iotype = UPIO_PORT, \
.flags = UPF_BOOT_AUTOCONF, \
}
static struct plat_serial8250_port accent_data[] = {
PORT(0x330, 4),
PORT(0x338, 4),
{ },
};
static struct platform_device accent_device = {
.name = "serial8250",
.id = PLAT8250_DEV_ACCENT,
.dev = {
.platform_data = accent_data,
},
};
static int __init accent_init(void)
{
return platform_device_register(&accent_device);
}
module_init(accent_init);
MODULE_AUTHOR("Russell King");
MODULE_DESCRIPTION("8250 serial probe module for Accent Async cards");
MODULE_LICENSE("GPL");
| gpl-2.0 |
armani-dev/android_kernel_xiaomi_armani_OLD | drivers/tty/serial/8250/8250_accent.c | 12341 | 1029 | /*
* Copyright (C) 2005 Russell King.
* Data taken from include/asm-i386/serial.h
*
* 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/serial_8250.h>
#define PORT(_base,_irq) \
{ \
.iobase = _base, \
.irq = _irq, \
.uartclk = 1843200, \
.iotype = UPIO_PORT, \
.flags = UPF_BOOT_AUTOCONF, \
}
static struct plat_serial8250_port accent_data[] = {
PORT(0x330, 4),
PORT(0x338, 4),
{ },
};
static struct platform_device accent_device = {
.name = "serial8250",
.id = PLAT8250_DEV_ACCENT,
.dev = {
.platform_data = accent_data,
},
};
static int __init accent_init(void)
{
return platform_device_register(&accent_device);
}
module_init(accent_init);
MODULE_AUTHOR("Russell King");
MODULE_DESCRIPTION("8250 serial probe module for Accent Async cards");
MODULE_LICENSE("GPL");
| gpl-2.0 |
hallovveen31/smooth | drivers/tty/serial/8250_exar_st16c554.c | 12341 | 1151 | /*
* Written by Paul B Schroeder < pschroeder "at" uplogix "dot" com >
* Based on 8250_boca.
*
* Copyright (C) 2005 Russell King.
* Data taken from include/asm-i386/serial.h
*
* 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/serial_8250.h>
#define PORT(_base,_irq) \
{ \
.iobase = _base, \
.irq = _irq, \
.uartclk = 1843200, \
.iotype = UPIO_PORT, \
.flags = UPF_BOOT_AUTOCONF, \
}
static struct plat_serial8250_port exar_data[] = {
PORT(0x100, 5),
PORT(0x108, 5),
PORT(0x110, 5),
PORT(0x118, 5),
{ },
};
static struct platform_device exar_device = {
.name = "serial8250",
.id = PLAT8250_DEV_EXAR_ST16C554,
.dev = {
.platform_data = exar_data,
},
};
static int __init exar_init(void)
{
return platform_device_register(&exar_device);
}
module_init(exar_init);
MODULE_AUTHOR("Paul B Schroeder");
MODULE_DESCRIPTION("8250 serial probe module for Exar cards");
MODULE_LICENSE("GPL");
| gpl-2.0 |
1119553797/sprd-kernel-common | arch/sh/boards/mach-x3proto/setup.c | 12341 | 5933 | /*
* arch/sh/boards/mach-x3proto/setup.c
*
* Renesas SH-X3 Prototype Board Support.
*
* Copyright (C) 2007 - 2010 Paul Mundt
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/kernel.h>
#include <linux/io.h>
#include <linux/smc91x.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/usb/r8a66597.h>
#include <linux/usb/m66592.h>
#include <linux/gpio.h>
#include <linux/gpio_keys.h>
#include <mach/ilsel.h>
#include <mach/hardware.h>
#include <asm/smp-ops.h>
static struct resource heartbeat_resources[] = {
[0] = {
.start = 0xb8140020,
.end = 0xb8140020,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device heartbeat_device = {
.name = "heartbeat",
.id = -1,
.num_resources = ARRAY_SIZE(heartbeat_resources),
.resource = heartbeat_resources,
};
static struct smc91x_platdata smc91x_info = {
.flags = SMC91X_USE_16BIT | SMC91X_NOWAIT,
};
static struct resource smc91x_resources[] = {
[0] = {
.start = 0x18000300,
.end = 0x18000300 + 0x10 - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
/* Filled in by ilsel */
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device smc91x_device = {
.name = "smc91x",
.id = -1,
.resource = smc91x_resources,
.num_resources = ARRAY_SIZE(smc91x_resources),
.dev = {
.platform_data = &smc91x_info,
},
};
static struct r8a66597_platdata r8a66597_data = {
.xtal = R8A66597_PLATDATA_XTAL_12MHZ,
.vif = 1,
};
static struct resource r8a66597_usb_host_resources[] = {
[0] = {
.start = 0x18040000,
.end = 0x18080000 - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
/* Filled in by ilsel */
.flags = IORESOURCE_IRQ | IRQF_TRIGGER_LOW,
},
};
static struct platform_device r8a66597_usb_host_device = {
.name = "r8a66597_hcd",
.id = -1,
.dev = {
.dma_mask = NULL, /* don't use dma */
.coherent_dma_mask = 0xffffffff,
.platform_data = &r8a66597_data,
},
.num_resources = ARRAY_SIZE(r8a66597_usb_host_resources),
.resource = r8a66597_usb_host_resources,
};
static struct m66592_platdata usbf_platdata = {
.xtal = M66592_PLATDATA_XTAL_24MHZ,
.vif = 1,
};
static struct resource m66592_usb_peripheral_resources[] = {
[0] = {
.name = "m66592_udc",
.start = 0x18080000,
.end = 0x180c0000 - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.name = "m66592_udc",
/* Filled in by ilsel */
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device m66592_usb_peripheral_device = {
.name = "m66592_udc",
.id = -1,
.dev = {
.dma_mask = NULL, /* don't use dma */
.coherent_dma_mask = 0xffffffff,
.platform_data = &usbf_platdata,
},
.num_resources = ARRAY_SIZE(m66592_usb_peripheral_resources),
.resource = m66592_usb_peripheral_resources,
};
static struct gpio_keys_button baseboard_buttons[NR_BASEBOARD_GPIOS] = {
{
.desc = "key44",
.code = KEY_POWER,
.active_low = 1,
.wakeup = 1,
}, {
.desc = "key43",
.code = KEY_SUSPEND,
.active_low = 1,
.wakeup = 1,
}, {
.desc = "key42",
.code = KEY_KATAKANAHIRAGANA,
.active_low = 1,
}, {
.desc = "key41",
.code = KEY_SWITCHVIDEOMODE,
.active_low = 1,
}, {
.desc = "key34",
.code = KEY_F12,
.active_low = 1,
}, {
.desc = "key33",
.code = KEY_F11,
.active_low = 1,
}, {
.desc = "key32",
.code = KEY_F10,
.active_low = 1,
}, {
.desc = "key31",
.code = KEY_F9,
.active_low = 1,
}, {
.desc = "key24",
.code = KEY_F8,
.active_low = 1,
}, {
.desc = "key23",
.code = KEY_F7,
.active_low = 1,
}, {
.desc = "key22",
.code = KEY_F6,
.active_low = 1,
}, {
.desc = "key21",
.code = KEY_F5,
.active_low = 1,
}, {
.desc = "key14",
.code = KEY_F4,
.active_low = 1,
}, {
.desc = "key13",
.code = KEY_F3,
.active_low = 1,
}, {
.desc = "key12",
.code = KEY_F2,
.active_low = 1,
}, {
.desc = "key11",
.code = KEY_F1,
.active_low = 1,
},
};
static struct gpio_keys_platform_data baseboard_buttons_data = {
.buttons = baseboard_buttons,
.nbuttons = ARRAY_SIZE(baseboard_buttons),
};
static struct platform_device baseboard_buttons_device = {
.name = "gpio-keys",
.id = -1,
.dev = {
.platform_data = &baseboard_buttons_data,
},
};
static struct platform_device *x3proto_devices[] __initdata = {
&heartbeat_device,
&smc91x_device,
&r8a66597_usb_host_device,
&m66592_usb_peripheral_device,
&baseboard_buttons_device,
};
static void __init x3proto_init_irq(void)
{
plat_irq_setup_pins(IRQ_MODE_IRL3210);
/* Set ICR0.LVLMODE */
__raw_writel(__raw_readl(0xfe410000) | (1 << 21), 0xfe410000);
}
static int __init x3proto_devices_setup(void)
{
int ret, i;
/*
* IRLs are only needed for ILSEL mappings, so flip over the INTC
* pins at a later point to enable the GPIOs to settle.
*/
x3proto_init_irq();
/*
* Now that ILSELs are available, set up the baseboard GPIOs.
*/
ret = x3proto_gpio_setup();
if (unlikely(ret))
return ret;
/*
* Propagate dynamic GPIOs for the baseboard button device.
*/
for (i = 0; i < ARRAY_SIZE(baseboard_buttons); i++)
baseboard_buttons[i].gpio = x3proto_gpio_chip.base + i;
r8a66597_usb_host_resources[1].start =
r8a66597_usb_host_resources[1].end = ilsel_enable(ILSEL_USBH_I);
m66592_usb_peripheral_resources[1].start =
m66592_usb_peripheral_resources[1].end = ilsel_enable(ILSEL_USBP_I);
smc91x_resources[1].start =
smc91x_resources[1].end = ilsel_enable(ILSEL_LAN);
return platform_add_devices(x3proto_devices,
ARRAY_SIZE(x3proto_devices));
}
device_initcall(x3proto_devices_setup);
static void __init x3proto_setup(char **cmdline_p)
{
register_smp_ops(&shx3_smp_ops);
}
static struct sh_machine_vector mv_x3proto __initmv = {
.mv_name = "x3proto",
.mv_setup = x3proto_setup,
};
| gpl-2.0 |
StanislavPodolsky/RT5350 | linux-3.8.7/net/netfilter/nf_conntrack_netlink.c | 54 | 73116 | /* Connection tracking via netlink socket. Allows for user space
* protocol helpers and general trouble making from userspace.
*
* (C) 2001 by Jay Schulist <jschlst@samba.org>
* (C) 2002-2006 by Harald Welte <laforge@gnumonks.org>
* (C) 2003 by Patrick Mchardy <kaber@trash.net>
* (C) 2005-2012 by Pablo Neira Ayuso <pablo@netfilter.org>
*
* Initial connection tracking via netlink development funded and
* generally made possible by Network Robots, Inc. (www.networkrobots.com)
*
* Further development of this code funded by Astaro AG (http://www.astaro.com)
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/rculist.h>
#include <linux/rculist_nulls.h>
#include <linux/types.h>
#include <linux/timer.h>
#include <linux/security.h>
#include <linux/skbuff.h>
#include <linux/errno.h>
#include <linux/netlink.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/netfilter.h>
#include <net/netlink.h>
#include <net/sock.h>
#include <net/netfilter/nf_conntrack.h>
#include <net/netfilter/nf_conntrack_core.h>
#include <net/netfilter/nf_conntrack_expect.h>
#include <net/netfilter/nf_conntrack_helper.h>
#include <net/netfilter/nf_conntrack_l3proto.h>
#include <net/netfilter/nf_conntrack_l4proto.h>
#include <net/netfilter/nf_conntrack_tuple.h>
#include <net/netfilter/nf_conntrack_acct.h>
#include <net/netfilter/nf_conntrack_zones.h>
#include <net/netfilter/nf_conntrack_timestamp.h>
#ifdef CONFIG_NF_NAT_NEEDED
#include <net/netfilter/nf_nat_core.h>
#include <net/netfilter/nf_nat_l4proto.h>
#include <net/netfilter/nf_nat_helper.h>
#endif
#include <linux/netfilter/nfnetlink.h>
#include <linux/netfilter/nfnetlink_conntrack.h>
MODULE_LICENSE("GPL");
static char __initdata version[] = "0.93";
static inline int
ctnetlink_dump_tuples_proto(struct sk_buff *skb,
const struct nf_conntrack_tuple *tuple,
struct nf_conntrack_l4proto *l4proto)
{
int ret = 0;
struct nlattr *nest_parms;
nest_parms = nla_nest_start(skb, CTA_TUPLE_PROTO | NLA_F_NESTED);
if (!nest_parms)
goto nla_put_failure;
if (nla_put_u8(skb, CTA_PROTO_NUM, tuple->dst.protonum))
goto nla_put_failure;
if (likely(l4proto->tuple_to_nlattr))
ret = l4proto->tuple_to_nlattr(skb, tuple);
nla_nest_end(skb, nest_parms);
return ret;
nla_put_failure:
return -1;
}
static inline int
ctnetlink_dump_tuples_ip(struct sk_buff *skb,
const struct nf_conntrack_tuple *tuple,
struct nf_conntrack_l3proto *l3proto)
{
int ret = 0;
struct nlattr *nest_parms;
nest_parms = nla_nest_start(skb, CTA_TUPLE_IP | NLA_F_NESTED);
if (!nest_parms)
goto nla_put_failure;
if (likely(l3proto->tuple_to_nlattr))
ret = l3proto->tuple_to_nlattr(skb, tuple);
nla_nest_end(skb, nest_parms);
return ret;
nla_put_failure:
return -1;
}
static int
ctnetlink_dump_tuples(struct sk_buff *skb,
const struct nf_conntrack_tuple *tuple)
{
int ret;
struct nf_conntrack_l3proto *l3proto;
struct nf_conntrack_l4proto *l4proto;
rcu_read_lock();
l3proto = __nf_ct_l3proto_find(tuple->src.l3num);
ret = ctnetlink_dump_tuples_ip(skb, tuple, l3proto);
if (ret >= 0) {
l4proto = __nf_ct_l4proto_find(tuple->src.l3num,
tuple->dst.protonum);
ret = ctnetlink_dump_tuples_proto(skb, tuple, l4proto);
}
rcu_read_unlock();
return ret;
}
static inline int
ctnetlink_dump_status(struct sk_buff *skb, const struct nf_conn *ct)
{
if (nla_put_be32(skb, CTA_STATUS, htonl(ct->status)))
goto nla_put_failure;
return 0;
nla_put_failure:
return -1;
}
static inline int
ctnetlink_dump_timeout(struct sk_buff *skb, const struct nf_conn *ct)
{
long timeout = ((long)ct->timeout.expires - (long)jiffies) / HZ;
if (timeout < 0)
timeout = 0;
if (nla_put_be32(skb, CTA_TIMEOUT, htonl(timeout)))
goto nla_put_failure;
return 0;
nla_put_failure:
return -1;
}
static inline int
ctnetlink_dump_protoinfo(struct sk_buff *skb, struct nf_conn *ct)
{
struct nf_conntrack_l4proto *l4proto;
struct nlattr *nest_proto;
int ret;
l4proto = __nf_ct_l4proto_find(nf_ct_l3num(ct), nf_ct_protonum(ct));
if (!l4proto->to_nlattr)
return 0;
nest_proto = nla_nest_start(skb, CTA_PROTOINFO | NLA_F_NESTED);
if (!nest_proto)
goto nla_put_failure;
ret = l4proto->to_nlattr(skb, nest_proto, ct);
nla_nest_end(skb, nest_proto);
return ret;
nla_put_failure:
return -1;
}
static inline int
ctnetlink_dump_helpinfo(struct sk_buff *skb, const struct nf_conn *ct)
{
struct nlattr *nest_helper;
const struct nf_conn_help *help = nfct_help(ct);
struct nf_conntrack_helper *helper;
if (!help)
return 0;
helper = rcu_dereference(help->helper);
if (!helper)
goto out;
nest_helper = nla_nest_start(skb, CTA_HELP | NLA_F_NESTED);
if (!nest_helper)
goto nla_put_failure;
if (nla_put_string(skb, CTA_HELP_NAME, helper->name))
goto nla_put_failure;
if (helper->to_nlattr)
helper->to_nlattr(skb, ct);
nla_nest_end(skb, nest_helper);
out:
return 0;
nla_put_failure:
return -1;
}
static int
dump_counters(struct sk_buff *skb, u64 pkts, u64 bytes,
enum ip_conntrack_dir dir)
{
enum ctattr_type type = dir ? CTA_COUNTERS_REPLY: CTA_COUNTERS_ORIG;
struct nlattr *nest_count;
nest_count = nla_nest_start(skb, type | NLA_F_NESTED);
if (!nest_count)
goto nla_put_failure;
if (nla_put_be64(skb, CTA_COUNTERS_PACKETS, cpu_to_be64(pkts)) ||
nla_put_be64(skb, CTA_COUNTERS_BYTES, cpu_to_be64(bytes)))
goto nla_put_failure;
nla_nest_end(skb, nest_count);
return 0;
nla_put_failure:
return -1;
}
static int
ctnetlink_dump_counters(struct sk_buff *skb, const struct nf_conn *ct,
enum ip_conntrack_dir dir, int type)
{
struct nf_conn_counter *acct;
u64 pkts, bytes;
acct = nf_conn_acct_find(ct);
if (!acct)
return 0;
if (type == IPCTNL_MSG_CT_GET_CTRZERO) {
pkts = atomic64_xchg(&acct[dir].packets, 0);
bytes = atomic64_xchg(&acct[dir].bytes, 0);
} else {
pkts = atomic64_read(&acct[dir].packets);
bytes = atomic64_read(&acct[dir].bytes);
}
return dump_counters(skb, pkts, bytes, dir);
}
static int
ctnetlink_dump_timestamp(struct sk_buff *skb, const struct nf_conn *ct)
{
struct nlattr *nest_count;
const struct nf_conn_tstamp *tstamp;
tstamp = nf_conn_tstamp_find(ct);
if (!tstamp)
return 0;
nest_count = nla_nest_start(skb, CTA_TIMESTAMP | NLA_F_NESTED);
if (!nest_count)
goto nla_put_failure;
if (nla_put_be64(skb, CTA_TIMESTAMP_START, cpu_to_be64(tstamp->start)) ||
(tstamp->stop != 0 && nla_put_be64(skb, CTA_TIMESTAMP_STOP,
cpu_to_be64(tstamp->stop))))
goto nla_put_failure;
nla_nest_end(skb, nest_count);
return 0;
nla_put_failure:
return -1;
}
#ifdef CONFIG_NF_CONNTRACK_MARK
static inline int
ctnetlink_dump_mark(struct sk_buff *skb, const struct nf_conn *ct)
{
if (nla_put_be32(skb, CTA_MARK, htonl(ct->mark)))
goto nla_put_failure;
return 0;
nla_put_failure:
return -1;
}
#else
#define ctnetlink_dump_mark(a, b) (0)
#endif
#ifdef CONFIG_NF_CONNTRACK_SECMARK
static inline int
ctnetlink_dump_secctx(struct sk_buff *skb, const struct nf_conn *ct)
{
struct nlattr *nest_secctx;
int len, ret;
char *secctx;
ret = security_secid_to_secctx(ct->secmark, &secctx, &len);
if (ret)
return 0;
ret = -1;
nest_secctx = nla_nest_start(skb, CTA_SECCTX | NLA_F_NESTED);
if (!nest_secctx)
goto nla_put_failure;
if (nla_put_string(skb, CTA_SECCTX_NAME, secctx))
goto nla_put_failure;
nla_nest_end(skb, nest_secctx);
ret = 0;
nla_put_failure:
security_release_secctx(secctx, len);
return ret;
}
#else
#define ctnetlink_dump_secctx(a, b) (0)
#endif
#define master_tuple(ct) &(ct->master->tuplehash[IP_CT_DIR_ORIGINAL].tuple)
static inline int
ctnetlink_dump_master(struct sk_buff *skb, const struct nf_conn *ct)
{
struct nlattr *nest_parms;
if (!(ct->status & IPS_EXPECTED))
return 0;
nest_parms = nla_nest_start(skb, CTA_TUPLE_MASTER | NLA_F_NESTED);
if (!nest_parms)
goto nla_put_failure;
if (ctnetlink_dump_tuples(skb, master_tuple(ct)) < 0)
goto nla_put_failure;
nla_nest_end(skb, nest_parms);
return 0;
nla_put_failure:
return -1;
}
#ifdef CONFIG_NF_NAT_NEEDED
static int
dump_nat_seq_adj(struct sk_buff *skb, const struct nf_nat_seq *natseq, int type)
{
struct nlattr *nest_parms;
nest_parms = nla_nest_start(skb, type | NLA_F_NESTED);
if (!nest_parms)
goto nla_put_failure;
if (nla_put_be32(skb, CTA_NAT_SEQ_CORRECTION_POS,
htonl(natseq->correction_pos)) ||
nla_put_be32(skb, CTA_NAT_SEQ_OFFSET_BEFORE,
htonl(natseq->offset_before)) ||
nla_put_be32(skb, CTA_NAT_SEQ_OFFSET_AFTER,
htonl(natseq->offset_after)))
goto nla_put_failure;
nla_nest_end(skb, nest_parms);
return 0;
nla_put_failure:
return -1;
}
static inline int
ctnetlink_dump_nat_seq_adj(struct sk_buff *skb, const struct nf_conn *ct)
{
struct nf_nat_seq *natseq;
struct nf_conn_nat *nat = nfct_nat(ct);
if (!(ct->status & IPS_SEQ_ADJUST) || !nat)
return 0;
natseq = &nat->seq[IP_CT_DIR_ORIGINAL];
if (dump_nat_seq_adj(skb, natseq, CTA_NAT_SEQ_ADJ_ORIG) == -1)
return -1;
natseq = &nat->seq[IP_CT_DIR_REPLY];
if (dump_nat_seq_adj(skb, natseq, CTA_NAT_SEQ_ADJ_REPLY) == -1)
return -1;
return 0;
}
#else
#define ctnetlink_dump_nat_seq_adj(a, b) (0)
#endif
static inline int
ctnetlink_dump_id(struct sk_buff *skb, const struct nf_conn *ct)
{
if (nla_put_be32(skb, CTA_ID, htonl((unsigned long)ct)))
goto nla_put_failure;
return 0;
nla_put_failure:
return -1;
}
static inline int
ctnetlink_dump_use(struct sk_buff *skb, const struct nf_conn *ct)
{
if (nla_put_be32(skb, CTA_USE, htonl(atomic_read(&ct->ct_general.use))))
goto nla_put_failure;
return 0;
nla_put_failure:
return -1;
}
static int
ctnetlink_fill_info(struct sk_buff *skb, u32 portid, u32 seq, u32 type,
struct nf_conn *ct)
{
struct nlmsghdr *nlh;
struct nfgenmsg *nfmsg;
struct nlattr *nest_parms;
unsigned int flags = portid ? NLM_F_MULTI : 0, event;
event = (NFNL_SUBSYS_CTNETLINK << 8 | IPCTNL_MSG_CT_NEW);
nlh = nlmsg_put(skb, portid, seq, event, sizeof(*nfmsg), flags);
if (nlh == NULL)
goto nlmsg_failure;
nfmsg = nlmsg_data(nlh);
nfmsg->nfgen_family = nf_ct_l3num(ct);
nfmsg->version = NFNETLINK_V0;
nfmsg->res_id = 0;
nest_parms = nla_nest_start(skb, CTA_TUPLE_ORIG | NLA_F_NESTED);
if (!nest_parms)
goto nla_put_failure;
if (ctnetlink_dump_tuples(skb, nf_ct_tuple(ct, IP_CT_DIR_ORIGINAL)) < 0)
goto nla_put_failure;
nla_nest_end(skb, nest_parms);
nest_parms = nla_nest_start(skb, CTA_TUPLE_REPLY | NLA_F_NESTED);
if (!nest_parms)
goto nla_put_failure;
if (ctnetlink_dump_tuples(skb, nf_ct_tuple(ct, IP_CT_DIR_REPLY)) < 0)
goto nla_put_failure;
nla_nest_end(skb, nest_parms);
if (nf_ct_zone(ct) &&
nla_put_be16(skb, CTA_ZONE, htons(nf_ct_zone(ct))))
goto nla_put_failure;
if (ctnetlink_dump_status(skb, ct) < 0 ||
ctnetlink_dump_timeout(skb, ct) < 0 ||
ctnetlink_dump_counters(skb, ct, IP_CT_DIR_ORIGINAL, type) < 0 ||
ctnetlink_dump_counters(skb, ct, IP_CT_DIR_REPLY, type) < 0 ||
ctnetlink_dump_timestamp(skb, ct) < 0 ||
ctnetlink_dump_protoinfo(skb, ct) < 0 ||
ctnetlink_dump_helpinfo(skb, ct) < 0 ||
ctnetlink_dump_mark(skb, ct) < 0 ||
ctnetlink_dump_secctx(skb, ct) < 0 ||
ctnetlink_dump_id(skb, ct) < 0 ||
ctnetlink_dump_use(skb, ct) < 0 ||
ctnetlink_dump_master(skb, ct) < 0 ||
ctnetlink_dump_nat_seq_adj(skb, ct) < 0)
goto nla_put_failure;
nlmsg_end(skb, nlh);
return skb->len;
nlmsg_failure:
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -1;
}
static inline size_t
ctnetlink_proto_size(const struct nf_conn *ct)
{
struct nf_conntrack_l3proto *l3proto;
struct nf_conntrack_l4proto *l4proto;
size_t len = 0;
rcu_read_lock();
l3proto = __nf_ct_l3proto_find(nf_ct_l3num(ct));
len += l3proto->nla_size;
l4proto = __nf_ct_l4proto_find(nf_ct_l3num(ct), nf_ct_protonum(ct));
len += l4proto->nla_size;
rcu_read_unlock();
return len;
}
static inline size_t
ctnetlink_counters_size(const struct nf_conn *ct)
{
if (!nf_ct_ext_exist(ct, NF_CT_EXT_ACCT))
return 0;
return 2 * nla_total_size(0) /* CTA_COUNTERS_ORIG|REPL */
+ 2 * nla_total_size(sizeof(uint64_t)) /* CTA_COUNTERS_PACKETS */
+ 2 * nla_total_size(sizeof(uint64_t)) /* CTA_COUNTERS_BYTES */
;
}
static inline int
ctnetlink_secctx_size(const struct nf_conn *ct)
{
#ifdef CONFIG_NF_CONNTRACK_SECMARK
int len, ret;
ret = security_secid_to_secctx(ct->secmark, NULL, &len);
if (ret)
return 0;
return nla_total_size(0) /* CTA_SECCTX */
+ nla_total_size(sizeof(char) * len); /* CTA_SECCTX_NAME */
#else
return 0;
#endif
}
static inline size_t
ctnetlink_timestamp_size(const struct nf_conn *ct)
{
#ifdef CONFIG_NF_CONNTRACK_TIMESTAMP
if (!nf_ct_ext_exist(ct, NF_CT_EXT_TSTAMP))
return 0;
return nla_total_size(0) + 2 * nla_total_size(sizeof(uint64_t));
#else
return 0;
#endif
}
static inline size_t
ctnetlink_nlmsg_size(const struct nf_conn *ct)
{
return NLMSG_ALIGN(sizeof(struct nfgenmsg))
+ 3 * nla_total_size(0) /* CTA_TUPLE_ORIG|REPL|MASTER */
+ 3 * nla_total_size(0) /* CTA_TUPLE_IP */
+ 3 * nla_total_size(0) /* CTA_TUPLE_PROTO */
+ 3 * nla_total_size(sizeof(u_int8_t)) /* CTA_PROTO_NUM */
+ nla_total_size(sizeof(u_int32_t)) /* CTA_ID */
+ nla_total_size(sizeof(u_int32_t)) /* CTA_STATUS */
+ ctnetlink_counters_size(ct)
+ ctnetlink_timestamp_size(ct)
+ nla_total_size(sizeof(u_int32_t)) /* CTA_TIMEOUT */
+ nla_total_size(0) /* CTA_PROTOINFO */
+ nla_total_size(0) /* CTA_HELP */
+ nla_total_size(NF_CT_HELPER_NAME_LEN) /* CTA_HELP_NAME */
+ ctnetlink_secctx_size(ct)
#ifdef CONFIG_NF_NAT_NEEDED
+ 2 * nla_total_size(0) /* CTA_NAT_SEQ_ADJ_ORIG|REPL */
+ 6 * nla_total_size(sizeof(u_int32_t)) /* CTA_NAT_SEQ_OFFSET */
#endif
#ifdef CONFIG_NF_CONNTRACK_MARK
+ nla_total_size(sizeof(u_int32_t)) /* CTA_MARK */
#endif
+ ctnetlink_proto_size(ct)
;
}
#ifdef CONFIG_NF_CONNTRACK_EVENTS
static int
ctnetlink_conntrack_event(unsigned int events, struct nf_ct_event *item)
{
struct net *net;
struct nlmsghdr *nlh;
struct nfgenmsg *nfmsg;
struct nlattr *nest_parms;
struct nf_conn *ct = item->ct;
struct sk_buff *skb;
unsigned int type;
unsigned int flags = 0, group;
int err;
/* ignore our fake conntrack entry */
if (nf_ct_is_untracked(ct))
return 0;
if (events & (1 << IPCT_DESTROY)) {
type = IPCTNL_MSG_CT_DELETE;
group = NFNLGRP_CONNTRACK_DESTROY;
} else if (events & ((1 << IPCT_NEW) | (1 << IPCT_RELATED))) {
type = IPCTNL_MSG_CT_NEW;
flags = NLM_F_CREATE|NLM_F_EXCL;
group = NFNLGRP_CONNTRACK_NEW;
} else if (events) {
type = IPCTNL_MSG_CT_NEW;
group = NFNLGRP_CONNTRACK_UPDATE;
} else
return 0;
net = nf_ct_net(ct);
if (!item->report && !nfnetlink_has_listeners(net, group))
return 0;
skb = nlmsg_new(ctnetlink_nlmsg_size(ct), GFP_ATOMIC);
if (skb == NULL)
goto errout;
type |= NFNL_SUBSYS_CTNETLINK << 8;
nlh = nlmsg_put(skb, item->portid, 0, type, sizeof(*nfmsg), flags);
if (nlh == NULL)
goto nlmsg_failure;
nfmsg = nlmsg_data(nlh);
nfmsg->nfgen_family = nf_ct_l3num(ct);
nfmsg->version = NFNETLINK_V0;
nfmsg->res_id = 0;
rcu_read_lock();
nest_parms = nla_nest_start(skb, CTA_TUPLE_ORIG | NLA_F_NESTED);
if (!nest_parms)
goto nla_put_failure;
if (ctnetlink_dump_tuples(skb, nf_ct_tuple(ct, IP_CT_DIR_ORIGINAL)) < 0)
goto nla_put_failure;
nla_nest_end(skb, nest_parms);
nest_parms = nla_nest_start(skb, CTA_TUPLE_REPLY | NLA_F_NESTED);
if (!nest_parms)
goto nla_put_failure;
if (ctnetlink_dump_tuples(skb, nf_ct_tuple(ct, IP_CT_DIR_REPLY)) < 0)
goto nla_put_failure;
nla_nest_end(skb, nest_parms);
if (nf_ct_zone(ct) &&
nla_put_be16(skb, CTA_ZONE, htons(nf_ct_zone(ct))))
goto nla_put_failure;
if (ctnetlink_dump_id(skb, ct) < 0)
goto nla_put_failure;
if (ctnetlink_dump_status(skb, ct) < 0)
goto nla_put_failure;
if (events & (1 << IPCT_DESTROY)) {
if (ctnetlink_dump_counters(skb, ct,
IP_CT_DIR_ORIGINAL, type) < 0 ||
ctnetlink_dump_counters(skb, ct,
IP_CT_DIR_REPLY, type) < 0 ||
ctnetlink_dump_timestamp(skb, ct) < 0)
goto nla_put_failure;
} else {
if (ctnetlink_dump_timeout(skb, ct) < 0)
goto nla_put_failure;
if (events & (1 << IPCT_PROTOINFO)
&& ctnetlink_dump_protoinfo(skb, ct) < 0)
goto nla_put_failure;
if ((events & (1 << IPCT_HELPER) || nfct_help(ct))
&& ctnetlink_dump_helpinfo(skb, ct) < 0)
goto nla_put_failure;
#ifdef CONFIG_NF_CONNTRACK_SECMARK
if ((events & (1 << IPCT_SECMARK) || ct->secmark)
&& ctnetlink_dump_secctx(skb, ct) < 0)
goto nla_put_failure;
#endif
if (events & (1 << IPCT_RELATED) &&
ctnetlink_dump_master(skb, ct) < 0)
goto nla_put_failure;
if (events & (1 << IPCT_NATSEQADJ) &&
ctnetlink_dump_nat_seq_adj(skb, ct) < 0)
goto nla_put_failure;
}
#ifdef CONFIG_NF_CONNTRACK_MARK
if ((events & (1 << IPCT_MARK) || ct->mark)
&& ctnetlink_dump_mark(skb, ct) < 0)
goto nla_put_failure;
#endif
rcu_read_unlock();
nlmsg_end(skb, nlh);
err = nfnetlink_send(skb, net, item->portid, group, item->report,
GFP_ATOMIC);
if (err == -ENOBUFS || err == -EAGAIN)
return -ENOBUFS;
return 0;
nla_put_failure:
rcu_read_unlock();
nlmsg_cancel(skb, nlh);
nlmsg_failure:
kfree_skb(skb);
errout:
if (nfnetlink_set_err(net, 0, group, -ENOBUFS) > 0)
return -ENOBUFS;
return 0;
}
#endif /* CONFIG_NF_CONNTRACK_EVENTS */
static int ctnetlink_done(struct netlink_callback *cb)
{
if (cb->args[1])
nf_ct_put((struct nf_conn *)cb->args[1]);
if (cb->data)
kfree(cb->data);
return 0;
}
struct ctnetlink_dump_filter {
struct {
u_int32_t val;
u_int32_t mask;
} mark;
};
static int
ctnetlink_dump_table(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct nf_conn *ct, *last;
struct nf_conntrack_tuple_hash *h;
struct hlist_nulls_node *n;
struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
u_int8_t l3proto = nfmsg->nfgen_family;
int res;
#ifdef CONFIG_NF_CONNTRACK_MARK
const struct ctnetlink_dump_filter *filter = cb->data;
#endif
spin_lock_bh(&nf_conntrack_lock);
last = (struct nf_conn *)cb->args[1];
for (; cb->args[0] < net->ct.htable_size; cb->args[0]++) {
restart:
hlist_nulls_for_each_entry(h, n, &net->ct.hash[cb->args[0]],
hnnode) {
if (NF_CT_DIRECTION(h) != IP_CT_DIR_ORIGINAL)
continue;
ct = nf_ct_tuplehash_to_ctrack(h);
/* Dump entries of a given L3 protocol number.
* If it is not specified, ie. l3proto == 0,
* then dump everything. */
if (l3proto && nf_ct_l3num(ct) != l3proto)
continue;
if (cb->args[1]) {
if (ct != last)
continue;
cb->args[1] = 0;
}
#ifdef CONFIG_NF_CONNTRACK_MARK
if (filter && !((ct->mark & filter->mark.mask) ==
filter->mark.val)) {
continue;
}
#endif
rcu_read_lock();
res =
ctnetlink_fill_info(skb, NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq,
NFNL_MSG_TYPE(cb->nlh->nlmsg_type),
ct);
rcu_read_unlock();
if (res < 0) {
nf_conntrack_get(&ct->ct_general);
cb->args[1] = (unsigned long)ct;
goto out;
}
}
if (cb->args[1]) {
cb->args[1] = 0;
goto restart;
}
}
out:
spin_unlock_bh(&nf_conntrack_lock);
if (last)
nf_ct_put(last);
return skb->len;
}
static inline int
ctnetlink_parse_tuple_ip(struct nlattr *attr, struct nf_conntrack_tuple *tuple)
{
struct nlattr *tb[CTA_IP_MAX+1];
struct nf_conntrack_l3proto *l3proto;
int ret = 0;
nla_parse_nested(tb, CTA_IP_MAX, attr, NULL);
rcu_read_lock();
l3proto = __nf_ct_l3proto_find(tuple->src.l3num);
if (likely(l3proto->nlattr_to_tuple)) {
ret = nla_validate_nested(attr, CTA_IP_MAX,
l3proto->nla_policy);
if (ret == 0)
ret = l3proto->nlattr_to_tuple(tb, tuple);
}
rcu_read_unlock();
return ret;
}
static const struct nla_policy proto_nla_policy[CTA_PROTO_MAX+1] = {
[CTA_PROTO_NUM] = { .type = NLA_U8 },
};
static inline int
ctnetlink_parse_tuple_proto(struct nlattr *attr,
struct nf_conntrack_tuple *tuple)
{
struct nlattr *tb[CTA_PROTO_MAX+1];
struct nf_conntrack_l4proto *l4proto;
int ret = 0;
ret = nla_parse_nested(tb, CTA_PROTO_MAX, attr, proto_nla_policy);
if (ret < 0)
return ret;
if (!tb[CTA_PROTO_NUM])
return -EINVAL;
tuple->dst.protonum = nla_get_u8(tb[CTA_PROTO_NUM]);
rcu_read_lock();
l4proto = __nf_ct_l4proto_find(tuple->src.l3num, tuple->dst.protonum);
if (likely(l4proto->nlattr_to_tuple)) {
ret = nla_validate_nested(attr, CTA_PROTO_MAX,
l4proto->nla_policy);
if (ret == 0)
ret = l4proto->nlattr_to_tuple(tb, tuple);
}
rcu_read_unlock();
return ret;
}
static const struct nla_policy tuple_nla_policy[CTA_TUPLE_MAX+1] = {
[CTA_TUPLE_IP] = { .type = NLA_NESTED },
[CTA_TUPLE_PROTO] = { .type = NLA_NESTED },
};
static int
ctnetlink_parse_tuple(const struct nlattr * const cda[],
struct nf_conntrack_tuple *tuple,
enum ctattr_type type, u_int8_t l3num)
{
struct nlattr *tb[CTA_TUPLE_MAX+1];
int err;
memset(tuple, 0, sizeof(*tuple));
nla_parse_nested(tb, CTA_TUPLE_MAX, cda[type], tuple_nla_policy);
if (!tb[CTA_TUPLE_IP])
return -EINVAL;
tuple->src.l3num = l3num;
err = ctnetlink_parse_tuple_ip(tb[CTA_TUPLE_IP], tuple);
if (err < 0)
return err;
if (!tb[CTA_TUPLE_PROTO])
return -EINVAL;
err = ctnetlink_parse_tuple_proto(tb[CTA_TUPLE_PROTO], tuple);
if (err < 0)
return err;
/* orig and expect tuples get DIR_ORIGINAL */
if (type == CTA_TUPLE_REPLY)
tuple->dst.dir = IP_CT_DIR_REPLY;
else
tuple->dst.dir = IP_CT_DIR_ORIGINAL;
return 0;
}
static int
ctnetlink_parse_zone(const struct nlattr *attr, u16 *zone)
{
if (attr)
#ifdef CONFIG_NF_CONNTRACK_ZONES
*zone = ntohs(nla_get_be16(attr));
#else
return -EOPNOTSUPP;
#endif
else
*zone = 0;
return 0;
}
static const struct nla_policy help_nla_policy[CTA_HELP_MAX+1] = {
[CTA_HELP_NAME] = { .type = NLA_NUL_STRING,
.len = NF_CT_HELPER_NAME_LEN - 1 },
};
static inline int
ctnetlink_parse_help(const struct nlattr *attr, char **helper_name,
struct nlattr **helpinfo)
{
struct nlattr *tb[CTA_HELP_MAX+1];
nla_parse_nested(tb, CTA_HELP_MAX, attr, help_nla_policy);
if (!tb[CTA_HELP_NAME])
return -EINVAL;
*helper_name = nla_data(tb[CTA_HELP_NAME]);
if (tb[CTA_HELP_INFO])
*helpinfo = tb[CTA_HELP_INFO];
return 0;
}
static const struct nla_policy ct_nla_policy[CTA_MAX+1] = {
[CTA_TUPLE_ORIG] = { .type = NLA_NESTED },
[CTA_TUPLE_REPLY] = { .type = NLA_NESTED },
[CTA_STATUS] = { .type = NLA_U32 },
[CTA_PROTOINFO] = { .type = NLA_NESTED },
[CTA_HELP] = { .type = NLA_NESTED },
[CTA_NAT_SRC] = { .type = NLA_NESTED },
[CTA_TIMEOUT] = { .type = NLA_U32 },
[CTA_MARK] = { .type = NLA_U32 },
[CTA_ID] = { .type = NLA_U32 },
[CTA_NAT_DST] = { .type = NLA_NESTED },
[CTA_TUPLE_MASTER] = { .type = NLA_NESTED },
[CTA_NAT_SEQ_ADJ_ORIG] = { .type = NLA_NESTED },
[CTA_NAT_SEQ_ADJ_REPLY] = { .type = NLA_NESTED },
[CTA_ZONE] = { .type = NLA_U16 },
[CTA_MARK_MASK] = { .type = NLA_U32 },
};
static int
ctnetlink_del_conntrack(struct sock *ctnl, struct sk_buff *skb,
const struct nlmsghdr *nlh,
const struct nlattr * const cda[])
{
struct net *net = sock_net(ctnl);
struct nf_conntrack_tuple_hash *h;
struct nf_conntrack_tuple tuple;
struct nf_conn *ct;
struct nfgenmsg *nfmsg = nlmsg_data(nlh);
u_int8_t u3 = nfmsg->nfgen_family;
u16 zone;
int err;
err = ctnetlink_parse_zone(cda[CTA_ZONE], &zone);
if (err < 0)
return err;
if (cda[CTA_TUPLE_ORIG])
err = ctnetlink_parse_tuple(cda, &tuple, CTA_TUPLE_ORIG, u3);
else if (cda[CTA_TUPLE_REPLY])
err = ctnetlink_parse_tuple(cda, &tuple, CTA_TUPLE_REPLY, u3);
else {
/* Flush the whole table */
nf_conntrack_flush_report(net,
NETLINK_CB(skb).portid,
nlmsg_report(nlh));
return 0;
}
if (err < 0)
return err;
h = nf_conntrack_find_get(net, zone, &tuple);
if (!h)
return -ENOENT;
ct = nf_ct_tuplehash_to_ctrack(h);
if (cda[CTA_ID]) {
u_int32_t id = ntohl(nla_get_be32(cda[CTA_ID]));
if (id != (u32)(unsigned long)ct) {
nf_ct_put(ct);
return -ENOENT;
}
}
if (del_timer(&ct->timeout)) {
if (nf_conntrack_event_report(IPCT_DESTROY, ct,
NETLINK_CB(skb).portid,
nlmsg_report(nlh)) < 0) {
nf_ct_delete_from_lists(ct);
/* we failed to report the event, try later */
nf_ct_dying_timeout(ct);
nf_ct_put(ct);
return 0;
}
/* death_by_timeout would report the event again */
set_bit(IPS_DYING_BIT, &ct->status);
nf_ct_delete_from_lists(ct);
nf_ct_put(ct);
}
nf_ct_put(ct);
return 0;
}
static int
ctnetlink_get_conntrack(struct sock *ctnl, struct sk_buff *skb,
const struct nlmsghdr *nlh,
const struct nlattr * const cda[])
{
struct net *net = sock_net(ctnl);
struct nf_conntrack_tuple_hash *h;
struct nf_conntrack_tuple tuple;
struct nf_conn *ct;
struct sk_buff *skb2 = NULL;
struct nfgenmsg *nfmsg = nlmsg_data(nlh);
u_int8_t u3 = nfmsg->nfgen_family;
u16 zone;
int err;
if (nlh->nlmsg_flags & NLM_F_DUMP) {
struct netlink_dump_control c = {
.dump = ctnetlink_dump_table,
.done = ctnetlink_done,
};
#ifdef CONFIG_NF_CONNTRACK_MARK
if (cda[CTA_MARK] && cda[CTA_MARK_MASK]) {
struct ctnetlink_dump_filter *filter;
filter = kzalloc(sizeof(struct ctnetlink_dump_filter),
GFP_ATOMIC);
if (filter == NULL)
return -ENOMEM;
filter->mark.val = ntohl(nla_get_be32(cda[CTA_MARK]));
filter->mark.mask =
ntohl(nla_get_be32(cda[CTA_MARK_MASK]));
c.data = filter;
}
#endif
return netlink_dump_start(ctnl, skb, nlh, &c);
}
err = ctnetlink_parse_zone(cda[CTA_ZONE], &zone);
if (err < 0)
return err;
if (cda[CTA_TUPLE_ORIG])
err = ctnetlink_parse_tuple(cda, &tuple, CTA_TUPLE_ORIG, u3);
else if (cda[CTA_TUPLE_REPLY])
err = ctnetlink_parse_tuple(cda, &tuple, CTA_TUPLE_REPLY, u3);
else
return -EINVAL;
if (err < 0)
return err;
h = nf_conntrack_find_get(net, zone, &tuple);
if (!h)
return -ENOENT;
ct = nf_ct_tuplehash_to_ctrack(h);
err = -ENOMEM;
skb2 = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (skb2 == NULL) {
nf_ct_put(ct);
return -ENOMEM;
}
rcu_read_lock();
err = ctnetlink_fill_info(skb2, NETLINK_CB(skb).portid, nlh->nlmsg_seq,
NFNL_MSG_TYPE(nlh->nlmsg_type), ct);
rcu_read_unlock();
nf_ct_put(ct);
if (err <= 0)
goto free;
err = netlink_unicast(ctnl, skb2, NETLINK_CB(skb).portid, MSG_DONTWAIT);
if (err < 0)
goto out;
return 0;
free:
kfree_skb(skb2);
out:
/* this avoids a loop in nfnetlink. */
return err == -EAGAIN ? -ENOBUFS : err;
}
static int ctnetlink_done_list(struct netlink_callback *cb)
{
if (cb->args[1])
nf_ct_put((struct nf_conn *)cb->args[1]);
return 0;
}
static int
ctnetlink_dump_list(struct sk_buff *skb, struct netlink_callback *cb,
struct hlist_nulls_head *list)
{
struct nf_conn *ct, *last;
struct nf_conntrack_tuple_hash *h;
struct hlist_nulls_node *n;
struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
u_int8_t l3proto = nfmsg->nfgen_family;
int res;
if (cb->args[2])
return 0;
spin_lock_bh(&nf_conntrack_lock);
last = (struct nf_conn *)cb->args[1];
restart:
hlist_nulls_for_each_entry(h, n, list, hnnode) {
ct = nf_ct_tuplehash_to_ctrack(h);
if (l3proto && nf_ct_l3num(ct) != l3proto)
continue;
if (cb->args[1]) {
if (ct != last)
continue;
cb->args[1] = 0;
}
rcu_read_lock();
res = ctnetlink_fill_info(skb, NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq,
NFNL_MSG_TYPE(cb->nlh->nlmsg_type),
ct);
rcu_read_unlock();
if (res < 0) {
nf_conntrack_get(&ct->ct_general);
cb->args[1] = (unsigned long)ct;
goto out;
}
}
if (cb->args[1]) {
cb->args[1] = 0;
goto restart;
} else
cb->args[2] = 1;
out:
spin_unlock_bh(&nf_conntrack_lock);
if (last)
nf_ct_put(last);
return skb->len;
}
static int
ctnetlink_dump_dying(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
return ctnetlink_dump_list(skb, cb, &net->ct.dying);
}
static int
ctnetlink_get_ct_dying(struct sock *ctnl, struct sk_buff *skb,
const struct nlmsghdr *nlh,
const struct nlattr * const cda[])
{
if (nlh->nlmsg_flags & NLM_F_DUMP) {
struct netlink_dump_control c = {
.dump = ctnetlink_dump_dying,
.done = ctnetlink_done_list,
};
return netlink_dump_start(ctnl, skb, nlh, &c);
}
return -EOPNOTSUPP;
}
static int
ctnetlink_dump_unconfirmed(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
return ctnetlink_dump_list(skb, cb, &net->ct.unconfirmed);
}
static int
ctnetlink_get_ct_unconfirmed(struct sock *ctnl, struct sk_buff *skb,
const struct nlmsghdr *nlh,
const struct nlattr * const cda[])
{
if (nlh->nlmsg_flags & NLM_F_DUMP) {
struct netlink_dump_control c = {
.dump = ctnetlink_dump_unconfirmed,
.done = ctnetlink_done_list,
};
return netlink_dump_start(ctnl, skb, nlh, &c);
}
return -EOPNOTSUPP;
}
#ifdef CONFIG_NF_NAT_NEEDED
static int
ctnetlink_parse_nat_setup(struct nf_conn *ct,
enum nf_nat_manip_type manip,
const struct nlattr *attr)
{
typeof(nfnetlink_parse_nat_setup_hook) parse_nat_setup;
int err;
parse_nat_setup = rcu_dereference(nfnetlink_parse_nat_setup_hook);
if (!parse_nat_setup) {
#ifdef CONFIG_MODULES
rcu_read_unlock();
nfnl_unlock();
if (request_module("nf-nat") < 0) {
nfnl_lock();
rcu_read_lock();
return -EOPNOTSUPP;
}
nfnl_lock();
rcu_read_lock();
if (nfnetlink_parse_nat_setup_hook)
return -EAGAIN;
#endif
return -EOPNOTSUPP;
}
err = parse_nat_setup(ct, manip, attr);
if (err == -EAGAIN) {
#ifdef CONFIG_MODULES
rcu_read_unlock();
nfnl_unlock();
if (request_module("nf-nat-%u", nf_ct_l3num(ct)) < 0) {
nfnl_lock();
rcu_read_lock();
return -EOPNOTSUPP;
}
nfnl_lock();
rcu_read_lock();
#else
err = -EOPNOTSUPP;
#endif
}
return err;
}
#endif
static int
ctnetlink_change_status(struct nf_conn *ct, const struct nlattr * const cda[])
{
unsigned long d;
unsigned int status = ntohl(nla_get_be32(cda[CTA_STATUS]));
d = ct->status ^ status;
if (d & (IPS_EXPECTED|IPS_CONFIRMED|IPS_DYING))
/* unchangeable */
return -EBUSY;
if (d & IPS_SEEN_REPLY && !(status & IPS_SEEN_REPLY))
/* SEEN_REPLY bit can only be set */
return -EBUSY;
if (d & IPS_ASSURED && !(status & IPS_ASSURED))
/* ASSURED bit can only be set */
return -EBUSY;
/* Be careful here, modifying NAT bits can screw up things,
* so don't let users modify them directly if they don't pass
* nf_nat_range. */
ct->status |= status & ~(IPS_NAT_DONE_MASK | IPS_NAT_MASK);
return 0;
}
static int
ctnetlink_change_nat(struct nf_conn *ct, const struct nlattr * const cda[])
{
#ifdef CONFIG_NF_NAT_NEEDED
int ret;
if (cda[CTA_NAT_DST]) {
ret = ctnetlink_parse_nat_setup(ct,
NF_NAT_MANIP_DST,
cda[CTA_NAT_DST]);
if (ret < 0)
return ret;
}
if (cda[CTA_NAT_SRC]) {
ret = ctnetlink_parse_nat_setup(ct,
NF_NAT_MANIP_SRC,
cda[CTA_NAT_SRC]);
if (ret < 0)
return ret;
}
return 0;
#else
return -EOPNOTSUPP;
#endif
}
static inline int
ctnetlink_change_helper(struct nf_conn *ct, const struct nlattr * const cda[])
{
struct nf_conntrack_helper *helper;
struct nf_conn_help *help = nfct_help(ct);
char *helpname = NULL;
struct nlattr *helpinfo = NULL;
int err;
/* don't change helper of sibling connections */
if (ct->master)
return -EBUSY;
err = ctnetlink_parse_help(cda[CTA_HELP], &helpname, &helpinfo);
if (err < 0)
return err;
if (!strcmp(helpname, "")) {
if (help && help->helper) {
/* we had a helper before ... */
nf_ct_remove_expectations(ct);
RCU_INIT_POINTER(help->helper, NULL);
}
return 0;
}
helper = __nf_conntrack_helper_find(helpname, nf_ct_l3num(ct),
nf_ct_protonum(ct));
if (helper == NULL) {
#ifdef CONFIG_MODULES
spin_unlock_bh(&nf_conntrack_lock);
if (request_module("nfct-helper-%s", helpname) < 0) {
spin_lock_bh(&nf_conntrack_lock);
return -EOPNOTSUPP;
}
spin_lock_bh(&nf_conntrack_lock);
helper = __nf_conntrack_helper_find(helpname, nf_ct_l3num(ct),
nf_ct_protonum(ct));
if (helper)
return -EAGAIN;
#endif
return -EOPNOTSUPP;
}
if (help) {
if (help->helper == helper) {
/* update private helper data if allowed. */
if (helper->from_nlattr)
helper->from_nlattr(helpinfo, ct);
return 0;
} else
return -EBUSY;
}
/* we cannot set a helper for an existing conntrack */
return -EOPNOTSUPP;
}
static inline int
ctnetlink_change_timeout(struct nf_conn *ct, const struct nlattr * const cda[])
{
u_int32_t timeout = ntohl(nla_get_be32(cda[CTA_TIMEOUT]));
if (!del_timer(&ct->timeout))
return -ETIME;
ct->timeout.expires = jiffies + timeout * HZ;
add_timer(&ct->timeout);
return 0;
}
static const struct nla_policy protoinfo_policy[CTA_PROTOINFO_MAX+1] = {
[CTA_PROTOINFO_TCP] = { .type = NLA_NESTED },
[CTA_PROTOINFO_DCCP] = { .type = NLA_NESTED },
[CTA_PROTOINFO_SCTP] = { .type = NLA_NESTED },
};
static inline int
ctnetlink_change_protoinfo(struct nf_conn *ct, const struct nlattr * const cda[])
{
const struct nlattr *attr = cda[CTA_PROTOINFO];
struct nlattr *tb[CTA_PROTOINFO_MAX+1];
struct nf_conntrack_l4proto *l4proto;
int err = 0;
nla_parse_nested(tb, CTA_PROTOINFO_MAX, attr, protoinfo_policy);
rcu_read_lock();
l4proto = __nf_ct_l4proto_find(nf_ct_l3num(ct), nf_ct_protonum(ct));
if (l4proto->from_nlattr)
err = l4proto->from_nlattr(tb, ct);
rcu_read_unlock();
return err;
}
#ifdef CONFIG_NF_NAT_NEEDED
static const struct nla_policy nat_seq_policy[CTA_NAT_SEQ_MAX+1] = {
[CTA_NAT_SEQ_CORRECTION_POS] = { .type = NLA_U32 },
[CTA_NAT_SEQ_OFFSET_BEFORE] = { .type = NLA_U32 },
[CTA_NAT_SEQ_OFFSET_AFTER] = { .type = NLA_U32 },
};
static inline int
change_nat_seq_adj(struct nf_nat_seq *natseq, const struct nlattr * const attr)
{
struct nlattr *cda[CTA_NAT_SEQ_MAX+1];
nla_parse_nested(cda, CTA_NAT_SEQ_MAX, attr, nat_seq_policy);
if (!cda[CTA_NAT_SEQ_CORRECTION_POS])
return -EINVAL;
natseq->correction_pos =
ntohl(nla_get_be32(cda[CTA_NAT_SEQ_CORRECTION_POS]));
if (!cda[CTA_NAT_SEQ_OFFSET_BEFORE])
return -EINVAL;
natseq->offset_before =
ntohl(nla_get_be32(cda[CTA_NAT_SEQ_OFFSET_BEFORE]));
if (!cda[CTA_NAT_SEQ_OFFSET_AFTER])
return -EINVAL;
natseq->offset_after =
ntohl(nla_get_be32(cda[CTA_NAT_SEQ_OFFSET_AFTER]));
return 0;
}
static int
ctnetlink_change_nat_seq_adj(struct nf_conn *ct,
const struct nlattr * const cda[])
{
int ret = 0;
struct nf_conn_nat *nat = nfct_nat(ct);
if (!nat)
return 0;
if (cda[CTA_NAT_SEQ_ADJ_ORIG]) {
ret = change_nat_seq_adj(&nat->seq[IP_CT_DIR_ORIGINAL],
cda[CTA_NAT_SEQ_ADJ_ORIG]);
if (ret < 0)
return ret;
ct->status |= IPS_SEQ_ADJUST;
}
if (cda[CTA_NAT_SEQ_ADJ_REPLY]) {
ret = change_nat_seq_adj(&nat->seq[IP_CT_DIR_REPLY],
cda[CTA_NAT_SEQ_ADJ_REPLY]);
if (ret < 0)
return ret;
ct->status |= IPS_SEQ_ADJUST;
}
return 0;
}
#endif
static int
ctnetlink_change_conntrack(struct nf_conn *ct,
const struct nlattr * const cda[])
{
int err;
/* only allow NAT changes and master assignation for new conntracks */
if (cda[CTA_NAT_SRC] || cda[CTA_NAT_DST] || cda[CTA_TUPLE_MASTER])
return -EOPNOTSUPP;
if (cda[CTA_HELP]) {
err = ctnetlink_change_helper(ct, cda);
if (err < 0)
return err;
}
if (cda[CTA_TIMEOUT]) {
err = ctnetlink_change_timeout(ct, cda);
if (err < 0)
return err;
}
if (cda[CTA_STATUS]) {
err = ctnetlink_change_status(ct, cda);
if (err < 0)
return err;
}
if (cda[CTA_PROTOINFO]) {
err = ctnetlink_change_protoinfo(ct, cda);
if (err < 0)
return err;
}
#if defined(CONFIG_NF_CONNTRACK_MARK)
if (cda[CTA_MARK])
ct->mark = ntohl(nla_get_be32(cda[CTA_MARK]));
#endif
#ifdef CONFIG_NF_NAT_NEEDED
if (cda[CTA_NAT_SEQ_ADJ_ORIG] || cda[CTA_NAT_SEQ_ADJ_REPLY]) {
err = ctnetlink_change_nat_seq_adj(ct, cda);
if (err < 0)
return err;
}
#endif
return 0;
}
static struct nf_conn *
ctnetlink_create_conntrack(struct net *net, u16 zone,
const struct nlattr * const cda[],
struct nf_conntrack_tuple *otuple,
struct nf_conntrack_tuple *rtuple,
u8 u3)
{
struct nf_conn *ct;
int err = -EINVAL;
struct nf_conntrack_helper *helper;
struct nf_conn_tstamp *tstamp;
ct = nf_conntrack_alloc(net, zone, otuple, rtuple, GFP_ATOMIC);
if (IS_ERR(ct))
return ERR_PTR(-ENOMEM);
if (!cda[CTA_TIMEOUT])
goto err1;
ct->timeout.expires = ntohl(nla_get_be32(cda[CTA_TIMEOUT]));
ct->timeout.expires = jiffies + ct->timeout.expires * HZ;
rcu_read_lock();
if (cda[CTA_HELP]) {
char *helpname = NULL;
struct nlattr *helpinfo = NULL;
err = ctnetlink_parse_help(cda[CTA_HELP], &helpname, &helpinfo);
if (err < 0)
goto err2;
helper = __nf_conntrack_helper_find(helpname, nf_ct_l3num(ct),
nf_ct_protonum(ct));
if (helper == NULL) {
rcu_read_unlock();
#ifdef CONFIG_MODULES
if (request_module("nfct-helper-%s", helpname) < 0) {
err = -EOPNOTSUPP;
goto err1;
}
rcu_read_lock();
helper = __nf_conntrack_helper_find(helpname,
nf_ct_l3num(ct),
nf_ct_protonum(ct));
if (helper) {
err = -EAGAIN;
goto err2;
}
rcu_read_unlock();
#endif
err = -EOPNOTSUPP;
goto err1;
} else {
struct nf_conn_help *help;
help = nf_ct_helper_ext_add(ct, helper, GFP_ATOMIC);
if (help == NULL) {
err = -ENOMEM;
goto err2;
}
/* set private helper data if allowed. */
if (helper->from_nlattr)
helper->from_nlattr(helpinfo, ct);
/* not in hash table yet so not strictly necessary */
RCU_INIT_POINTER(help->helper, helper);
}
} else {
/* try an implicit helper assignation */
err = __nf_ct_try_assign_helper(ct, NULL, GFP_ATOMIC);
if (err < 0)
goto err2;
}
if (cda[CTA_NAT_SRC] || cda[CTA_NAT_DST]) {
err = ctnetlink_change_nat(ct, cda);
if (err < 0)
goto err2;
}
nf_ct_acct_ext_add(ct, GFP_ATOMIC);
nf_ct_tstamp_ext_add(ct, GFP_ATOMIC);
nf_ct_ecache_ext_add(ct, 0, 0, GFP_ATOMIC);
/* we must add conntrack extensions before confirmation. */
ct->status |= IPS_CONFIRMED;
if (cda[CTA_STATUS]) {
err = ctnetlink_change_status(ct, cda);
if (err < 0)
goto err2;
}
#ifdef CONFIG_NF_NAT_NEEDED
if (cda[CTA_NAT_SEQ_ADJ_ORIG] || cda[CTA_NAT_SEQ_ADJ_REPLY]) {
err = ctnetlink_change_nat_seq_adj(ct, cda);
if (err < 0)
goto err2;
}
#endif
memset(&ct->proto, 0, sizeof(ct->proto));
if (cda[CTA_PROTOINFO]) {
err = ctnetlink_change_protoinfo(ct, cda);
if (err < 0)
goto err2;
}
#if defined(CONFIG_NF_CONNTRACK_MARK)
if (cda[CTA_MARK])
ct->mark = ntohl(nla_get_be32(cda[CTA_MARK]));
#endif
/* setup master conntrack: this is a confirmed expectation */
if (cda[CTA_TUPLE_MASTER]) {
struct nf_conntrack_tuple master;
struct nf_conntrack_tuple_hash *master_h;
struct nf_conn *master_ct;
err = ctnetlink_parse_tuple(cda, &master, CTA_TUPLE_MASTER, u3);
if (err < 0)
goto err2;
master_h = nf_conntrack_find_get(net, zone, &master);
if (master_h == NULL) {
err = -ENOENT;
goto err2;
}
master_ct = nf_ct_tuplehash_to_ctrack(master_h);
__set_bit(IPS_EXPECTED_BIT, &ct->status);
ct->master = master_ct;
}
tstamp = nf_conn_tstamp_find(ct);
if (tstamp)
tstamp->start = ktime_to_ns(ktime_get_real());
err = nf_conntrack_hash_check_insert(ct);
if (err < 0)
goto err2;
rcu_read_unlock();
return ct;
err2:
rcu_read_unlock();
err1:
nf_conntrack_free(ct);
return ERR_PTR(err);
}
static int
ctnetlink_new_conntrack(struct sock *ctnl, struct sk_buff *skb,
const struct nlmsghdr *nlh,
const struct nlattr * const cda[])
{
struct net *net = sock_net(ctnl);
struct nf_conntrack_tuple otuple, rtuple;
struct nf_conntrack_tuple_hash *h = NULL;
struct nfgenmsg *nfmsg = nlmsg_data(nlh);
struct nf_conn *ct;
u_int8_t u3 = nfmsg->nfgen_family;
u16 zone;
int err;
err = ctnetlink_parse_zone(cda[CTA_ZONE], &zone);
if (err < 0)
return err;
if (cda[CTA_TUPLE_ORIG]) {
err = ctnetlink_parse_tuple(cda, &otuple, CTA_TUPLE_ORIG, u3);
if (err < 0)
return err;
}
if (cda[CTA_TUPLE_REPLY]) {
err = ctnetlink_parse_tuple(cda, &rtuple, CTA_TUPLE_REPLY, u3);
if (err < 0)
return err;
}
if (cda[CTA_TUPLE_ORIG])
h = nf_conntrack_find_get(net, zone, &otuple);
else if (cda[CTA_TUPLE_REPLY])
h = nf_conntrack_find_get(net, zone, &rtuple);
if (h == NULL) {
err = -ENOENT;
if (nlh->nlmsg_flags & NLM_F_CREATE) {
enum ip_conntrack_events events;
ct = ctnetlink_create_conntrack(net, zone, cda, &otuple,
&rtuple, u3);
if (IS_ERR(ct))
return PTR_ERR(ct);
err = 0;
if (test_bit(IPS_EXPECTED_BIT, &ct->status))
events = IPCT_RELATED;
else
events = IPCT_NEW;
nf_conntrack_eventmask_report((1 << IPCT_REPLY) |
(1 << IPCT_ASSURED) |
(1 << IPCT_HELPER) |
(1 << IPCT_PROTOINFO) |
(1 << IPCT_NATSEQADJ) |
(1 << IPCT_MARK) | events,
ct, NETLINK_CB(skb).portid,
nlmsg_report(nlh));
nf_ct_put(ct);
}
return err;
}
/* implicit 'else' */
err = -EEXIST;
ct = nf_ct_tuplehash_to_ctrack(h);
if (!(nlh->nlmsg_flags & NLM_F_EXCL)) {
spin_lock_bh(&nf_conntrack_lock);
err = ctnetlink_change_conntrack(ct, cda);
spin_unlock_bh(&nf_conntrack_lock);
if (err == 0) {
nf_conntrack_eventmask_report((1 << IPCT_REPLY) |
(1 << IPCT_ASSURED) |
(1 << IPCT_HELPER) |
(1 << IPCT_PROTOINFO) |
(1 << IPCT_NATSEQADJ) |
(1 << IPCT_MARK),
ct, NETLINK_CB(skb).portid,
nlmsg_report(nlh));
}
}
nf_ct_put(ct);
return err;
}
static int
ctnetlink_ct_stat_cpu_fill_info(struct sk_buff *skb, u32 portid, u32 seq,
__u16 cpu, const struct ip_conntrack_stat *st)
{
struct nlmsghdr *nlh;
struct nfgenmsg *nfmsg;
unsigned int flags = portid ? NLM_F_MULTI : 0, event;
event = (NFNL_SUBSYS_CTNETLINK << 8 | IPCTNL_MSG_CT_GET_STATS_CPU);
nlh = nlmsg_put(skb, portid, seq, event, sizeof(*nfmsg), flags);
if (nlh == NULL)
goto nlmsg_failure;
nfmsg = nlmsg_data(nlh);
nfmsg->nfgen_family = AF_UNSPEC;
nfmsg->version = NFNETLINK_V0;
nfmsg->res_id = htons(cpu);
if (nla_put_be32(skb, CTA_STATS_SEARCHED, htonl(st->searched)) ||
nla_put_be32(skb, CTA_STATS_FOUND, htonl(st->found)) ||
nla_put_be32(skb, CTA_STATS_NEW, htonl(st->new)) ||
nla_put_be32(skb, CTA_STATS_INVALID, htonl(st->invalid)) ||
nla_put_be32(skb, CTA_STATS_IGNORE, htonl(st->ignore)) ||
nla_put_be32(skb, CTA_STATS_DELETE, htonl(st->delete)) ||
nla_put_be32(skb, CTA_STATS_DELETE_LIST, htonl(st->delete_list)) ||
nla_put_be32(skb, CTA_STATS_INSERT, htonl(st->insert)) ||
nla_put_be32(skb, CTA_STATS_INSERT_FAILED,
htonl(st->insert_failed)) ||
nla_put_be32(skb, CTA_STATS_DROP, htonl(st->drop)) ||
nla_put_be32(skb, CTA_STATS_EARLY_DROP, htonl(st->early_drop)) ||
nla_put_be32(skb, CTA_STATS_ERROR, htonl(st->error)) ||
nla_put_be32(skb, CTA_STATS_SEARCH_RESTART,
htonl(st->search_restart)))
goto nla_put_failure;
nlmsg_end(skb, nlh);
return skb->len;
nla_put_failure:
nlmsg_failure:
nlmsg_cancel(skb, nlh);
return -1;
}
static int
ctnetlink_ct_stat_cpu_dump(struct sk_buff *skb, struct netlink_callback *cb)
{
int cpu;
struct net *net = sock_net(skb->sk);
if (cb->args[0] == nr_cpu_ids)
return 0;
for (cpu = cb->args[0]; cpu < nr_cpu_ids; cpu++) {
const struct ip_conntrack_stat *st;
if (!cpu_possible(cpu))
continue;
st = per_cpu_ptr(net->ct.stat, cpu);
if (ctnetlink_ct_stat_cpu_fill_info(skb,
NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq,
cpu, st) < 0)
break;
}
cb->args[0] = cpu;
return skb->len;
}
static int
ctnetlink_stat_ct_cpu(struct sock *ctnl, struct sk_buff *skb,
const struct nlmsghdr *nlh,
const struct nlattr * const cda[])
{
if (nlh->nlmsg_flags & NLM_F_DUMP) {
struct netlink_dump_control c = {
.dump = ctnetlink_ct_stat_cpu_dump,
};
return netlink_dump_start(ctnl, skb, nlh, &c);
}
return 0;
}
static int
ctnetlink_stat_ct_fill_info(struct sk_buff *skb, u32 portid, u32 seq, u32 type,
struct net *net)
{
struct nlmsghdr *nlh;
struct nfgenmsg *nfmsg;
unsigned int flags = portid ? NLM_F_MULTI : 0, event;
unsigned int nr_conntracks = atomic_read(&net->ct.count);
event = (NFNL_SUBSYS_CTNETLINK << 8 | IPCTNL_MSG_CT_GET_STATS);
nlh = nlmsg_put(skb, portid, seq, event, sizeof(*nfmsg), flags);
if (nlh == NULL)
goto nlmsg_failure;
nfmsg = nlmsg_data(nlh);
nfmsg->nfgen_family = AF_UNSPEC;
nfmsg->version = NFNETLINK_V0;
nfmsg->res_id = 0;
if (nla_put_be32(skb, CTA_STATS_GLOBAL_ENTRIES, htonl(nr_conntracks)))
goto nla_put_failure;
nlmsg_end(skb, nlh);
return skb->len;
nla_put_failure:
nlmsg_failure:
nlmsg_cancel(skb, nlh);
return -1;
}
static int
ctnetlink_stat_ct(struct sock *ctnl, struct sk_buff *skb,
const struct nlmsghdr *nlh,
const struct nlattr * const cda[])
{
struct sk_buff *skb2;
int err;
skb2 = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (skb2 == NULL)
return -ENOMEM;
err = ctnetlink_stat_ct_fill_info(skb2, NETLINK_CB(skb).portid,
nlh->nlmsg_seq,
NFNL_MSG_TYPE(nlh->nlmsg_type),
sock_net(skb->sk));
if (err <= 0)
goto free;
err = netlink_unicast(ctnl, skb2, NETLINK_CB(skb).portid, MSG_DONTWAIT);
if (err < 0)
goto out;
return 0;
free:
kfree_skb(skb2);
out:
/* this avoids a loop in nfnetlink. */
return err == -EAGAIN ? -ENOBUFS : err;
}
#ifdef CONFIG_NETFILTER_NETLINK_QUEUE_CT
static size_t
ctnetlink_nfqueue_build_size(const struct nf_conn *ct)
{
return 3 * nla_total_size(0) /* CTA_TUPLE_ORIG|REPL|MASTER */
+ 3 * nla_total_size(0) /* CTA_TUPLE_IP */
+ 3 * nla_total_size(0) /* CTA_TUPLE_PROTO */
+ 3 * nla_total_size(sizeof(u_int8_t)) /* CTA_PROTO_NUM */
+ nla_total_size(sizeof(u_int32_t)) /* CTA_ID */
+ nla_total_size(sizeof(u_int32_t)) /* CTA_STATUS */
+ nla_total_size(sizeof(u_int32_t)) /* CTA_TIMEOUT */
+ nla_total_size(0) /* CTA_PROTOINFO */
+ nla_total_size(0) /* CTA_HELP */
+ nla_total_size(NF_CT_HELPER_NAME_LEN) /* CTA_HELP_NAME */
+ ctnetlink_secctx_size(ct)
#ifdef CONFIG_NF_NAT_NEEDED
+ 2 * nla_total_size(0) /* CTA_NAT_SEQ_ADJ_ORIG|REPL */
+ 6 * nla_total_size(sizeof(u_int32_t)) /* CTA_NAT_SEQ_OFFSET */
#endif
#ifdef CONFIG_NF_CONNTRACK_MARK
+ nla_total_size(sizeof(u_int32_t)) /* CTA_MARK */
#endif
+ ctnetlink_proto_size(ct)
;
}
static int
ctnetlink_nfqueue_build(struct sk_buff *skb, struct nf_conn *ct)
{
struct nlattr *nest_parms;
rcu_read_lock();
nest_parms = nla_nest_start(skb, CTA_TUPLE_ORIG | NLA_F_NESTED);
if (!nest_parms)
goto nla_put_failure;
if (ctnetlink_dump_tuples(skb, nf_ct_tuple(ct, IP_CT_DIR_ORIGINAL)) < 0)
goto nla_put_failure;
nla_nest_end(skb, nest_parms);
nest_parms = nla_nest_start(skb, CTA_TUPLE_REPLY | NLA_F_NESTED);
if (!nest_parms)
goto nla_put_failure;
if (ctnetlink_dump_tuples(skb, nf_ct_tuple(ct, IP_CT_DIR_REPLY)) < 0)
goto nla_put_failure;
nla_nest_end(skb, nest_parms);
if (nf_ct_zone(ct)) {
if (nla_put_be16(skb, CTA_ZONE, htons(nf_ct_zone(ct))))
goto nla_put_failure;
}
if (ctnetlink_dump_id(skb, ct) < 0)
goto nla_put_failure;
if (ctnetlink_dump_status(skb, ct) < 0)
goto nla_put_failure;
if (ctnetlink_dump_timeout(skb, ct) < 0)
goto nla_put_failure;
if (ctnetlink_dump_protoinfo(skb, ct) < 0)
goto nla_put_failure;
if (ctnetlink_dump_helpinfo(skb, ct) < 0)
goto nla_put_failure;
#ifdef CONFIG_NF_CONNTRACK_SECMARK
if (ct->secmark && ctnetlink_dump_secctx(skb, ct) < 0)
goto nla_put_failure;
#endif
if (ct->master && ctnetlink_dump_master(skb, ct) < 0)
goto nla_put_failure;
if ((ct->status & IPS_SEQ_ADJUST) &&
ctnetlink_dump_nat_seq_adj(skb, ct) < 0)
goto nla_put_failure;
#ifdef CONFIG_NF_CONNTRACK_MARK
if (ct->mark && ctnetlink_dump_mark(skb, ct) < 0)
goto nla_put_failure;
#endif
rcu_read_unlock();
return 0;
nla_put_failure:
rcu_read_unlock();
return -ENOSPC;
}
static int
ctnetlink_nfqueue_parse_ct(const struct nlattr *cda[], struct nf_conn *ct)
{
int err;
if (cda[CTA_TIMEOUT]) {
err = ctnetlink_change_timeout(ct, cda);
if (err < 0)
return err;
}
if (cda[CTA_STATUS]) {
err = ctnetlink_change_status(ct, cda);
if (err < 0)
return err;
}
if (cda[CTA_HELP]) {
err = ctnetlink_change_helper(ct, cda);
if (err < 0)
return err;
}
#if defined(CONFIG_NF_CONNTRACK_MARK)
if (cda[CTA_MARK])
ct->mark = ntohl(nla_get_be32(cda[CTA_MARK]));
#endif
return 0;
}
static int
ctnetlink_nfqueue_parse(const struct nlattr *attr, struct nf_conn *ct)
{
struct nlattr *cda[CTA_MAX+1];
int ret;
nla_parse_nested(cda, CTA_MAX, attr, ct_nla_policy);
spin_lock_bh(&nf_conntrack_lock);
ret = ctnetlink_nfqueue_parse_ct((const struct nlattr **)cda, ct);
spin_unlock_bh(&nf_conntrack_lock);
return ret;
}
static struct nfq_ct_hook ctnetlink_nfqueue_hook = {
.build_size = ctnetlink_nfqueue_build_size,
.build = ctnetlink_nfqueue_build,
.parse = ctnetlink_nfqueue_parse,
};
#endif /* CONFIG_NETFILTER_NETLINK_QUEUE_CT */
/***********************************************************************
* EXPECT
***********************************************************************/
static inline int
ctnetlink_exp_dump_tuple(struct sk_buff *skb,
const struct nf_conntrack_tuple *tuple,
enum ctattr_expect type)
{
struct nlattr *nest_parms;
nest_parms = nla_nest_start(skb, type | NLA_F_NESTED);
if (!nest_parms)
goto nla_put_failure;
if (ctnetlink_dump_tuples(skb, tuple) < 0)
goto nla_put_failure;
nla_nest_end(skb, nest_parms);
return 0;
nla_put_failure:
return -1;
}
static inline int
ctnetlink_exp_dump_mask(struct sk_buff *skb,
const struct nf_conntrack_tuple *tuple,
const struct nf_conntrack_tuple_mask *mask)
{
int ret;
struct nf_conntrack_l3proto *l3proto;
struct nf_conntrack_l4proto *l4proto;
struct nf_conntrack_tuple m;
struct nlattr *nest_parms;
memset(&m, 0xFF, sizeof(m));
memcpy(&m.src.u3, &mask->src.u3, sizeof(m.src.u3));
m.src.u.all = mask->src.u.all;
m.dst.protonum = tuple->dst.protonum;
nest_parms = nla_nest_start(skb, CTA_EXPECT_MASK | NLA_F_NESTED);
if (!nest_parms)
goto nla_put_failure;
rcu_read_lock();
l3proto = __nf_ct_l3proto_find(tuple->src.l3num);
ret = ctnetlink_dump_tuples_ip(skb, &m, l3proto);
if (ret >= 0) {
l4proto = __nf_ct_l4proto_find(tuple->src.l3num,
tuple->dst.protonum);
ret = ctnetlink_dump_tuples_proto(skb, &m, l4proto);
}
rcu_read_unlock();
if (unlikely(ret < 0))
goto nla_put_failure;
nla_nest_end(skb, nest_parms);
return 0;
nla_put_failure:
return -1;
}
static const union nf_inet_addr any_addr;
static int
ctnetlink_exp_dump_expect(struct sk_buff *skb,
const struct nf_conntrack_expect *exp)
{
struct nf_conn *master = exp->master;
long timeout = ((long)exp->timeout.expires - (long)jiffies) / HZ;
struct nf_conn_help *help;
#ifdef CONFIG_NF_NAT_NEEDED
struct nlattr *nest_parms;
struct nf_conntrack_tuple nat_tuple = {};
#endif
struct nf_ct_helper_expectfn *expfn;
if (timeout < 0)
timeout = 0;
if (ctnetlink_exp_dump_tuple(skb, &exp->tuple, CTA_EXPECT_TUPLE) < 0)
goto nla_put_failure;
if (ctnetlink_exp_dump_mask(skb, &exp->tuple, &exp->mask) < 0)
goto nla_put_failure;
if (ctnetlink_exp_dump_tuple(skb,
&master->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
CTA_EXPECT_MASTER) < 0)
goto nla_put_failure;
#ifdef CONFIG_NF_NAT_NEEDED
if (!nf_inet_addr_cmp(&exp->saved_addr, &any_addr) ||
exp->saved_proto.all) {
nest_parms = nla_nest_start(skb, CTA_EXPECT_NAT | NLA_F_NESTED);
if (!nest_parms)
goto nla_put_failure;
if (nla_put_be32(skb, CTA_EXPECT_NAT_DIR, htonl(exp->dir)))
goto nla_put_failure;
nat_tuple.src.l3num = nf_ct_l3num(master);
nat_tuple.src.u3 = exp->saved_addr;
nat_tuple.dst.protonum = nf_ct_protonum(master);
nat_tuple.src.u = exp->saved_proto;
if (ctnetlink_exp_dump_tuple(skb, &nat_tuple,
CTA_EXPECT_NAT_TUPLE) < 0)
goto nla_put_failure;
nla_nest_end(skb, nest_parms);
}
#endif
if (nla_put_be32(skb, CTA_EXPECT_TIMEOUT, htonl(timeout)) ||
nla_put_be32(skb, CTA_EXPECT_ID, htonl((unsigned long)exp)) ||
nla_put_be32(skb, CTA_EXPECT_FLAGS, htonl(exp->flags)) ||
nla_put_be32(skb, CTA_EXPECT_CLASS, htonl(exp->class)))
goto nla_put_failure;
help = nfct_help(master);
if (help) {
struct nf_conntrack_helper *helper;
helper = rcu_dereference(help->helper);
if (helper &&
nla_put_string(skb, CTA_EXPECT_HELP_NAME, helper->name))
goto nla_put_failure;
}
expfn = nf_ct_helper_expectfn_find_by_symbol(exp->expectfn);
if (expfn != NULL &&
nla_put_string(skb, CTA_EXPECT_FN, expfn->name))
goto nla_put_failure;
return 0;
nla_put_failure:
return -1;
}
static int
ctnetlink_exp_fill_info(struct sk_buff *skb, u32 portid, u32 seq,
int event, const struct nf_conntrack_expect *exp)
{
struct nlmsghdr *nlh;
struct nfgenmsg *nfmsg;
unsigned int flags = portid ? NLM_F_MULTI : 0;
event |= NFNL_SUBSYS_CTNETLINK_EXP << 8;
nlh = nlmsg_put(skb, portid, seq, event, sizeof(*nfmsg), flags);
if (nlh == NULL)
goto nlmsg_failure;
nfmsg = nlmsg_data(nlh);
nfmsg->nfgen_family = exp->tuple.src.l3num;
nfmsg->version = NFNETLINK_V0;
nfmsg->res_id = 0;
if (ctnetlink_exp_dump_expect(skb, exp) < 0)
goto nla_put_failure;
nlmsg_end(skb, nlh);
return skb->len;
nlmsg_failure:
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -1;
}
#ifdef CONFIG_NF_CONNTRACK_EVENTS
static int
ctnetlink_expect_event(unsigned int events, struct nf_exp_event *item)
{
struct nf_conntrack_expect *exp = item->exp;
struct net *net = nf_ct_exp_net(exp);
struct nlmsghdr *nlh;
struct nfgenmsg *nfmsg;
struct sk_buff *skb;
unsigned int type, group;
int flags = 0;
if (events & (1 << IPEXP_DESTROY)) {
type = IPCTNL_MSG_EXP_DELETE;
group = NFNLGRP_CONNTRACK_EXP_DESTROY;
} else if (events & (1 << IPEXP_NEW)) {
type = IPCTNL_MSG_EXP_NEW;
flags = NLM_F_CREATE|NLM_F_EXCL;
group = NFNLGRP_CONNTRACK_EXP_NEW;
} else
return 0;
if (!item->report && !nfnetlink_has_listeners(net, group))
return 0;
skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
if (skb == NULL)
goto errout;
type |= NFNL_SUBSYS_CTNETLINK_EXP << 8;
nlh = nlmsg_put(skb, item->portid, 0, type, sizeof(*nfmsg), flags);
if (nlh == NULL)
goto nlmsg_failure;
nfmsg = nlmsg_data(nlh);
nfmsg->nfgen_family = exp->tuple.src.l3num;
nfmsg->version = NFNETLINK_V0;
nfmsg->res_id = 0;
rcu_read_lock();
if (ctnetlink_exp_dump_expect(skb, exp) < 0)
goto nla_put_failure;
rcu_read_unlock();
nlmsg_end(skb, nlh);
nfnetlink_send(skb, net, item->portid, group, item->report, GFP_ATOMIC);
return 0;
nla_put_failure:
rcu_read_unlock();
nlmsg_cancel(skb, nlh);
nlmsg_failure:
kfree_skb(skb);
errout:
nfnetlink_set_err(net, 0, 0, -ENOBUFS);
return 0;
}
#endif
static int ctnetlink_exp_done(struct netlink_callback *cb)
{
if (cb->args[1])
nf_ct_expect_put((struct nf_conntrack_expect *)cb->args[1]);
return 0;
}
static int
ctnetlink_exp_dump_table(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct nf_conntrack_expect *exp, *last;
struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
struct hlist_node *n;
u_int8_t l3proto = nfmsg->nfgen_family;
rcu_read_lock();
last = (struct nf_conntrack_expect *)cb->args[1];
for (; cb->args[0] < nf_ct_expect_hsize; cb->args[0]++) {
restart:
hlist_for_each_entry(exp, n, &net->ct.expect_hash[cb->args[0]],
hnode) {
if (l3proto && exp->tuple.src.l3num != l3proto)
continue;
if (cb->args[1]) {
if (exp != last)
continue;
cb->args[1] = 0;
}
if (ctnetlink_exp_fill_info(skb,
NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq,
IPCTNL_MSG_EXP_NEW,
exp) < 0) {
if (!atomic_inc_not_zero(&exp->use))
continue;
cb->args[1] = (unsigned long)exp;
goto out;
}
}
if (cb->args[1]) {
cb->args[1] = 0;
goto restart;
}
}
out:
rcu_read_unlock();
if (last)
nf_ct_expect_put(last);
return skb->len;
}
static const struct nla_policy exp_nla_policy[CTA_EXPECT_MAX+1] = {
[CTA_EXPECT_MASTER] = { .type = NLA_NESTED },
[CTA_EXPECT_TUPLE] = { .type = NLA_NESTED },
[CTA_EXPECT_MASK] = { .type = NLA_NESTED },
[CTA_EXPECT_TIMEOUT] = { .type = NLA_U32 },
[CTA_EXPECT_ID] = { .type = NLA_U32 },
[CTA_EXPECT_HELP_NAME] = { .type = NLA_NUL_STRING,
.len = NF_CT_HELPER_NAME_LEN - 1 },
[CTA_EXPECT_ZONE] = { .type = NLA_U16 },
[CTA_EXPECT_FLAGS] = { .type = NLA_U32 },
[CTA_EXPECT_CLASS] = { .type = NLA_U32 },
[CTA_EXPECT_NAT] = { .type = NLA_NESTED },
[CTA_EXPECT_FN] = { .type = NLA_NUL_STRING },
};
static int
ctnetlink_get_expect(struct sock *ctnl, struct sk_buff *skb,
const struct nlmsghdr *nlh,
const struct nlattr * const cda[])
{
struct net *net = sock_net(ctnl);
struct nf_conntrack_tuple tuple;
struct nf_conntrack_expect *exp;
struct sk_buff *skb2;
struct nfgenmsg *nfmsg = nlmsg_data(nlh);
u_int8_t u3 = nfmsg->nfgen_family;
u16 zone;
int err;
if (nlh->nlmsg_flags & NLM_F_DUMP) {
struct netlink_dump_control c = {
.dump = ctnetlink_exp_dump_table,
.done = ctnetlink_exp_done,
};
return netlink_dump_start(ctnl, skb, nlh, &c);
}
err = ctnetlink_parse_zone(cda[CTA_EXPECT_ZONE], &zone);
if (err < 0)
return err;
if (cda[CTA_EXPECT_TUPLE])
err = ctnetlink_parse_tuple(cda, &tuple, CTA_EXPECT_TUPLE, u3);
else if (cda[CTA_EXPECT_MASTER])
err = ctnetlink_parse_tuple(cda, &tuple, CTA_EXPECT_MASTER, u3);
else
return -EINVAL;
if (err < 0)
return err;
exp = nf_ct_expect_find_get(net, zone, &tuple);
if (!exp)
return -ENOENT;
if (cda[CTA_EXPECT_ID]) {
__be32 id = nla_get_be32(cda[CTA_EXPECT_ID]);
if (ntohl(id) != (u32)(unsigned long)exp) {
nf_ct_expect_put(exp);
return -ENOENT;
}
}
err = -ENOMEM;
skb2 = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (skb2 == NULL) {
nf_ct_expect_put(exp);
goto out;
}
rcu_read_lock();
err = ctnetlink_exp_fill_info(skb2, NETLINK_CB(skb).portid,
nlh->nlmsg_seq, IPCTNL_MSG_EXP_NEW, exp);
rcu_read_unlock();
nf_ct_expect_put(exp);
if (err <= 0)
goto free;
err = netlink_unicast(ctnl, skb2, NETLINK_CB(skb).portid, MSG_DONTWAIT);
if (err < 0)
goto out;
return 0;
free:
kfree_skb(skb2);
out:
/* this avoids a loop in nfnetlink. */
return err == -EAGAIN ? -ENOBUFS : err;
}
static int
ctnetlink_del_expect(struct sock *ctnl, struct sk_buff *skb,
const struct nlmsghdr *nlh,
const struct nlattr * const cda[])
{
struct net *net = sock_net(ctnl);
struct nf_conntrack_expect *exp;
struct nf_conntrack_tuple tuple;
struct nfgenmsg *nfmsg = nlmsg_data(nlh);
struct hlist_node *n, *next;
u_int8_t u3 = nfmsg->nfgen_family;
unsigned int i;
u16 zone;
int err;
if (cda[CTA_EXPECT_TUPLE]) {
/* delete a single expect by tuple */
err = ctnetlink_parse_zone(cda[CTA_EXPECT_ZONE], &zone);
if (err < 0)
return err;
err = ctnetlink_parse_tuple(cda, &tuple, CTA_EXPECT_TUPLE, u3);
if (err < 0)
return err;
/* bump usage count to 2 */
exp = nf_ct_expect_find_get(net, zone, &tuple);
if (!exp)
return -ENOENT;
if (cda[CTA_EXPECT_ID]) {
__be32 id = nla_get_be32(cda[CTA_EXPECT_ID]);
if (ntohl(id) != (u32)(unsigned long)exp) {
nf_ct_expect_put(exp);
return -ENOENT;
}
}
/* after list removal, usage count == 1 */
spin_lock_bh(&nf_conntrack_lock);
if (del_timer(&exp->timeout)) {
nf_ct_unlink_expect_report(exp, NETLINK_CB(skb).portid,
nlmsg_report(nlh));
nf_ct_expect_put(exp);
}
spin_unlock_bh(&nf_conntrack_lock);
/* have to put what we 'get' above.
* after this line usage count == 0 */
nf_ct_expect_put(exp);
} else if (cda[CTA_EXPECT_HELP_NAME]) {
char *name = nla_data(cda[CTA_EXPECT_HELP_NAME]);
struct nf_conn_help *m_help;
/* delete all expectations for this helper */
spin_lock_bh(&nf_conntrack_lock);
for (i = 0; i < nf_ct_expect_hsize; i++) {
hlist_for_each_entry_safe(exp, n, next,
&net->ct.expect_hash[i],
hnode) {
m_help = nfct_help(exp->master);
if (!strcmp(m_help->helper->name, name) &&
del_timer(&exp->timeout)) {
nf_ct_unlink_expect_report(exp,
NETLINK_CB(skb).portid,
nlmsg_report(nlh));
nf_ct_expect_put(exp);
}
}
}
spin_unlock_bh(&nf_conntrack_lock);
} else {
/* This basically means we have to flush everything*/
spin_lock_bh(&nf_conntrack_lock);
for (i = 0; i < nf_ct_expect_hsize; i++) {
hlist_for_each_entry_safe(exp, n, next,
&net->ct.expect_hash[i],
hnode) {
if (del_timer(&exp->timeout)) {
nf_ct_unlink_expect_report(exp,
NETLINK_CB(skb).portid,
nlmsg_report(nlh));
nf_ct_expect_put(exp);
}
}
}
spin_unlock_bh(&nf_conntrack_lock);
}
return 0;
}
static int
ctnetlink_change_expect(struct nf_conntrack_expect *x,
const struct nlattr * const cda[])
{
if (cda[CTA_EXPECT_TIMEOUT]) {
if (!del_timer(&x->timeout))
return -ETIME;
x->timeout.expires = jiffies +
ntohl(nla_get_be32(cda[CTA_EXPECT_TIMEOUT])) * HZ;
add_timer(&x->timeout);
}
return 0;
}
static const struct nla_policy exp_nat_nla_policy[CTA_EXPECT_NAT_MAX+1] = {
[CTA_EXPECT_NAT_DIR] = { .type = NLA_U32 },
[CTA_EXPECT_NAT_TUPLE] = { .type = NLA_NESTED },
};
static int
ctnetlink_parse_expect_nat(const struct nlattr *attr,
struct nf_conntrack_expect *exp,
u_int8_t u3)
{
#ifdef CONFIG_NF_NAT_NEEDED
struct nlattr *tb[CTA_EXPECT_NAT_MAX+1];
struct nf_conntrack_tuple nat_tuple = {};
int err;
nla_parse_nested(tb, CTA_EXPECT_NAT_MAX, attr, exp_nat_nla_policy);
if (!tb[CTA_EXPECT_NAT_DIR] || !tb[CTA_EXPECT_NAT_TUPLE])
return -EINVAL;
err = ctnetlink_parse_tuple((const struct nlattr * const *)tb,
&nat_tuple, CTA_EXPECT_NAT_TUPLE, u3);
if (err < 0)
return err;
exp->saved_addr = nat_tuple.src.u3;
exp->saved_proto = nat_tuple.src.u;
exp->dir = ntohl(nla_get_be32(tb[CTA_EXPECT_NAT_DIR]));
return 0;
#else
return -EOPNOTSUPP;
#endif
}
static int
ctnetlink_create_expect(struct net *net, u16 zone,
const struct nlattr * const cda[],
u_int8_t u3,
u32 portid, int report)
{
struct nf_conntrack_tuple tuple, mask, master_tuple;
struct nf_conntrack_tuple_hash *h = NULL;
struct nf_conntrack_expect *exp;
struct nf_conn *ct;
struct nf_conn_help *help;
struct nf_conntrack_helper *helper = NULL;
u_int32_t class = 0;
int err = 0;
/* caller guarantees that those three CTA_EXPECT_* exist */
err = ctnetlink_parse_tuple(cda, &tuple, CTA_EXPECT_TUPLE, u3);
if (err < 0)
return err;
err = ctnetlink_parse_tuple(cda, &mask, CTA_EXPECT_MASK, u3);
if (err < 0)
return err;
err = ctnetlink_parse_tuple(cda, &master_tuple, CTA_EXPECT_MASTER, u3);
if (err < 0)
return err;
/* Look for master conntrack of this expectation */
h = nf_conntrack_find_get(net, zone, &master_tuple);
if (!h)
return -ENOENT;
ct = nf_ct_tuplehash_to_ctrack(h);
/* Look for helper of this expectation */
if (cda[CTA_EXPECT_HELP_NAME]) {
const char *helpname = nla_data(cda[CTA_EXPECT_HELP_NAME]);
helper = __nf_conntrack_helper_find(helpname, nf_ct_l3num(ct),
nf_ct_protonum(ct));
if (helper == NULL) {
#ifdef CONFIG_MODULES
if (request_module("nfct-helper-%s", helpname) < 0) {
err = -EOPNOTSUPP;
goto out;
}
helper = __nf_conntrack_helper_find(helpname,
nf_ct_l3num(ct),
nf_ct_protonum(ct));
if (helper) {
err = -EAGAIN;
goto out;
}
#endif
err = -EOPNOTSUPP;
goto out;
}
}
if (cda[CTA_EXPECT_CLASS] && helper) {
class = ntohl(nla_get_be32(cda[CTA_EXPECT_CLASS]));
if (class > helper->expect_class_max) {
err = -EINVAL;
goto out;
}
}
exp = nf_ct_expect_alloc(ct);
if (!exp) {
err = -ENOMEM;
goto out;
}
help = nfct_help(ct);
if (!help) {
if (!cda[CTA_EXPECT_TIMEOUT]) {
err = -EINVAL;
goto err_out;
}
exp->timeout.expires =
jiffies + ntohl(nla_get_be32(cda[CTA_EXPECT_TIMEOUT])) * HZ;
exp->flags = NF_CT_EXPECT_USERSPACE;
if (cda[CTA_EXPECT_FLAGS]) {
exp->flags |=
ntohl(nla_get_be32(cda[CTA_EXPECT_FLAGS]));
}
} else {
if (cda[CTA_EXPECT_FLAGS]) {
exp->flags = ntohl(nla_get_be32(cda[CTA_EXPECT_FLAGS]));
exp->flags &= ~NF_CT_EXPECT_USERSPACE;
} else
exp->flags = 0;
}
if (cda[CTA_EXPECT_FN]) {
const char *name = nla_data(cda[CTA_EXPECT_FN]);
struct nf_ct_helper_expectfn *expfn;
expfn = nf_ct_helper_expectfn_find_by_name(name);
if (expfn == NULL) {
err = -EINVAL;
goto err_out;
}
exp->expectfn = expfn->expectfn;
} else
exp->expectfn = NULL;
exp->class = class;
exp->master = ct;
exp->helper = helper;
memcpy(&exp->tuple, &tuple, sizeof(struct nf_conntrack_tuple));
memcpy(&exp->mask.src.u3, &mask.src.u3, sizeof(exp->mask.src.u3));
exp->mask.src.u.all = mask.src.u.all;
if (cda[CTA_EXPECT_NAT]) {
err = ctnetlink_parse_expect_nat(cda[CTA_EXPECT_NAT],
exp, u3);
if (err < 0)
goto err_out;
}
err = nf_ct_expect_related_report(exp, portid, report);
err_out:
nf_ct_expect_put(exp);
out:
nf_ct_put(nf_ct_tuplehash_to_ctrack(h));
return err;
}
static int
ctnetlink_new_expect(struct sock *ctnl, struct sk_buff *skb,
const struct nlmsghdr *nlh,
const struct nlattr * const cda[])
{
struct net *net = sock_net(ctnl);
struct nf_conntrack_tuple tuple;
struct nf_conntrack_expect *exp;
struct nfgenmsg *nfmsg = nlmsg_data(nlh);
u_int8_t u3 = nfmsg->nfgen_family;
u16 zone;
int err;
if (!cda[CTA_EXPECT_TUPLE]
|| !cda[CTA_EXPECT_MASK]
|| !cda[CTA_EXPECT_MASTER])
return -EINVAL;
err = ctnetlink_parse_zone(cda[CTA_EXPECT_ZONE], &zone);
if (err < 0)
return err;
err = ctnetlink_parse_tuple(cda, &tuple, CTA_EXPECT_TUPLE, u3);
if (err < 0)
return err;
spin_lock_bh(&nf_conntrack_lock);
exp = __nf_ct_expect_find(net, zone, &tuple);
if (!exp) {
spin_unlock_bh(&nf_conntrack_lock);
err = -ENOENT;
if (nlh->nlmsg_flags & NLM_F_CREATE) {
err = ctnetlink_create_expect(net, zone, cda,
u3,
NETLINK_CB(skb).portid,
nlmsg_report(nlh));
}
return err;
}
err = -EEXIST;
if (!(nlh->nlmsg_flags & NLM_F_EXCL))
err = ctnetlink_change_expect(exp, cda);
spin_unlock_bh(&nf_conntrack_lock);
return err;
}
static int
ctnetlink_exp_stat_fill_info(struct sk_buff *skb, u32 portid, u32 seq, int cpu,
const struct ip_conntrack_stat *st)
{
struct nlmsghdr *nlh;
struct nfgenmsg *nfmsg;
unsigned int flags = portid ? NLM_F_MULTI : 0, event;
event = (NFNL_SUBSYS_CTNETLINK << 8 | IPCTNL_MSG_EXP_GET_STATS_CPU);
nlh = nlmsg_put(skb, portid, seq, event, sizeof(*nfmsg), flags);
if (nlh == NULL)
goto nlmsg_failure;
nfmsg = nlmsg_data(nlh);
nfmsg->nfgen_family = AF_UNSPEC;
nfmsg->version = NFNETLINK_V0;
nfmsg->res_id = htons(cpu);
if (nla_put_be32(skb, CTA_STATS_EXP_NEW, htonl(st->expect_new)) ||
nla_put_be32(skb, CTA_STATS_EXP_CREATE, htonl(st->expect_create)) ||
nla_put_be32(skb, CTA_STATS_EXP_DELETE, htonl(st->expect_delete)))
goto nla_put_failure;
nlmsg_end(skb, nlh);
return skb->len;
nla_put_failure:
nlmsg_failure:
nlmsg_cancel(skb, nlh);
return -1;
}
static int
ctnetlink_exp_stat_cpu_dump(struct sk_buff *skb, struct netlink_callback *cb)
{
int cpu;
struct net *net = sock_net(skb->sk);
if (cb->args[0] == nr_cpu_ids)
return 0;
for (cpu = cb->args[0]; cpu < nr_cpu_ids; cpu++) {
const struct ip_conntrack_stat *st;
if (!cpu_possible(cpu))
continue;
st = per_cpu_ptr(net->ct.stat, cpu);
if (ctnetlink_exp_stat_fill_info(skb, NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq,
cpu, st) < 0)
break;
}
cb->args[0] = cpu;
return skb->len;
}
static int
ctnetlink_stat_exp_cpu(struct sock *ctnl, struct sk_buff *skb,
const struct nlmsghdr *nlh,
const struct nlattr * const cda[])
{
if (nlh->nlmsg_flags & NLM_F_DUMP) {
struct netlink_dump_control c = {
.dump = ctnetlink_exp_stat_cpu_dump,
};
return netlink_dump_start(ctnl, skb, nlh, &c);
}
return 0;
}
#ifdef CONFIG_NF_CONNTRACK_EVENTS
static struct nf_ct_event_notifier ctnl_notifier = {
.fcn = ctnetlink_conntrack_event,
};
static struct nf_exp_event_notifier ctnl_notifier_exp = {
.fcn = ctnetlink_expect_event,
};
#endif
static const struct nfnl_callback ctnl_cb[IPCTNL_MSG_MAX] = {
[IPCTNL_MSG_CT_NEW] = { .call = ctnetlink_new_conntrack,
.attr_count = CTA_MAX,
.policy = ct_nla_policy },
[IPCTNL_MSG_CT_GET] = { .call = ctnetlink_get_conntrack,
.attr_count = CTA_MAX,
.policy = ct_nla_policy },
[IPCTNL_MSG_CT_DELETE] = { .call = ctnetlink_del_conntrack,
.attr_count = CTA_MAX,
.policy = ct_nla_policy },
[IPCTNL_MSG_CT_GET_CTRZERO] = { .call = ctnetlink_get_conntrack,
.attr_count = CTA_MAX,
.policy = ct_nla_policy },
[IPCTNL_MSG_CT_GET_STATS_CPU] = { .call = ctnetlink_stat_ct_cpu },
[IPCTNL_MSG_CT_GET_STATS] = { .call = ctnetlink_stat_ct },
[IPCTNL_MSG_CT_GET_DYING] = { .call = ctnetlink_get_ct_dying },
[IPCTNL_MSG_CT_GET_UNCONFIRMED] = { .call = ctnetlink_get_ct_unconfirmed },
};
static const struct nfnl_callback ctnl_exp_cb[IPCTNL_MSG_EXP_MAX] = {
[IPCTNL_MSG_EXP_GET] = { .call = ctnetlink_get_expect,
.attr_count = CTA_EXPECT_MAX,
.policy = exp_nla_policy },
[IPCTNL_MSG_EXP_NEW] = { .call = ctnetlink_new_expect,
.attr_count = CTA_EXPECT_MAX,
.policy = exp_nla_policy },
[IPCTNL_MSG_EXP_DELETE] = { .call = ctnetlink_del_expect,
.attr_count = CTA_EXPECT_MAX,
.policy = exp_nla_policy },
[IPCTNL_MSG_EXP_GET_STATS_CPU] = { .call = ctnetlink_stat_exp_cpu },
};
static const struct nfnetlink_subsystem ctnl_subsys = {
.name = "conntrack",
.subsys_id = NFNL_SUBSYS_CTNETLINK,
.cb_count = IPCTNL_MSG_MAX,
.cb = ctnl_cb,
};
static const struct nfnetlink_subsystem ctnl_exp_subsys = {
.name = "conntrack_expect",
.subsys_id = NFNL_SUBSYS_CTNETLINK_EXP,
.cb_count = IPCTNL_MSG_EXP_MAX,
.cb = ctnl_exp_cb,
};
MODULE_ALIAS("ip_conntrack_netlink");
MODULE_ALIAS_NFNL_SUBSYS(NFNL_SUBSYS_CTNETLINK);
MODULE_ALIAS_NFNL_SUBSYS(NFNL_SUBSYS_CTNETLINK_EXP);
static int __net_init ctnetlink_net_init(struct net *net)
{
#ifdef CONFIG_NF_CONNTRACK_EVENTS
int ret;
ret = nf_conntrack_register_notifier(net, &ctnl_notifier);
if (ret < 0) {
pr_err("ctnetlink_init: cannot register notifier.\n");
goto err_out;
}
ret = nf_ct_expect_register_notifier(net, &ctnl_notifier_exp);
if (ret < 0) {
pr_err("ctnetlink_init: cannot expect register notifier.\n");
goto err_unreg_notifier;
}
#endif
return 0;
#ifdef CONFIG_NF_CONNTRACK_EVENTS
err_unreg_notifier:
nf_conntrack_unregister_notifier(net, &ctnl_notifier);
err_out:
return ret;
#endif
}
static void ctnetlink_net_exit(struct net *net)
{
#ifdef CONFIG_NF_CONNTRACK_EVENTS
nf_ct_expect_unregister_notifier(net, &ctnl_notifier_exp);
nf_conntrack_unregister_notifier(net, &ctnl_notifier);
#endif
}
static void __net_exit ctnetlink_net_exit_batch(struct list_head *net_exit_list)
{
struct net *net;
list_for_each_entry(net, net_exit_list, exit_list)
ctnetlink_net_exit(net);
}
static struct pernet_operations ctnetlink_net_ops = {
.init = ctnetlink_net_init,
.exit_batch = ctnetlink_net_exit_batch,
};
static int __init ctnetlink_init(void)
{
int ret;
pr_info("ctnetlink v%s: registering with nfnetlink.\n", version);
ret = nfnetlink_subsys_register(&ctnl_subsys);
if (ret < 0) {
pr_err("ctnetlink_init: cannot register with nfnetlink.\n");
goto err_out;
}
ret = nfnetlink_subsys_register(&ctnl_exp_subsys);
if (ret < 0) {
pr_err("ctnetlink_init: cannot register exp with nfnetlink.\n");
goto err_unreg_subsys;
}
ret = register_pernet_subsys(&ctnetlink_net_ops);
if (ret < 0) {
pr_err("ctnetlink_init: cannot register pernet operations\n");
goto err_unreg_exp_subsys;
}
#ifdef CONFIG_NETFILTER_NETLINK_QUEUE_CT
/* setup interaction between nf_queue and nf_conntrack_netlink. */
RCU_INIT_POINTER(nfq_ct_hook, &ctnetlink_nfqueue_hook);
#endif
return 0;
err_unreg_exp_subsys:
nfnetlink_subsys_unregister(&ctnl_exp_subsys);
err_unreg_subsys:
nfnetlink_subsys_unregister(&ctnl_subsys);
err_out:
return ret;
}
static void __exit ctnetlink_exit(void)
{
pr_info("ctnetlink: unregistering from nfnetlink.\n");
unregister_pernet_subsys(&ctnetlink_net_ops);
nfnetlink_subsys_unregister(&ctnl_exp_subsys);
nfnetlink_subsys_unregister(&ctnl_subsys);
#ifdef CONFIG_NETFILTER_NETLINK_QUEUE_CT
RCU_INIT_POINTER(nfq_ct_hook, NULL);
#endif
}
module_init(ctnetlink_init);
module_exit(ctnetlink_exit);
| gpl-2.0 |
markushx/linux | drivers/gpu/drm/nouveau/nvd0_display.c | 54 | 58091 | /*
* Copyright 2011 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Ben Skeggs
*/
#include <linux/dma-mapping.h>
#include "drmP.h"
#include "drm_crtc_helper.h"
#include "nouveau_drv.h"
#include "nouveau_connector.h"
#include "nouveau_encoder.h"
#include "nouveau_crtc.h"
#include "nouveau_dma.h"
#include "nouveau_fb.h"
#include "nouveau_software.h"
#include "nv50_display.h"
#define EVO_DMA_NR 9
#define EVO_MASTER (0x00)
#define EVO_FLIP(c) (0x01 + (c))
#define EVO_OVLY(c) (0x05 + (c))
#define EVO_OIMM(c) (0x09 + (c))
#define EVO_CURS(c) (0x0d + (c))
/* offsets in shared sync bo of various structures */
#define EVO_SYNC(c, o) ((c) * 0x0100 + (o))
#define EVO_MAST_NTFY EVO_SYNC( 0, 0x00)
#define EVO_FLIP_SEM0(c) EVO_SYNC((c), 0x00)
#define EVO_FLIP_SEM1(c) EVO_SYNC((c), 0x10)
struct evo {
int idx;
dma_addr_t handle;
u32 *ptr;
struct {
u32 offset;
u16 value;
} sem;
};
struct nvd0_display {
struct nouveau_gpuobj *mem;
struct nouveau_bo *sync;
struct evo evo[9];
struct tasklet_struct tasklet;
u32 modeset;
};
static struct nvd0_display *
nvd0_display(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
return dev_priv->engine.display.priv;
}
static struct drm_crtc *
nvd0_display_crtc_get(struct drm_encoder *encoder)
{
return nouveau_encoder(encoder)->crtc;
}
/******************************************************************************
* EVO channel helpers
*****************************************************************************/
static inline int
evo_icmd(struct drm_device *dev, int id, u32 mthd, u32 data)
{
int ret = 0;
nv_mask(dev, 0x610700 + (id * 0x10), 0x00000001, 0x00000001);
nv_wr32(dev, 0x610704 + (id * 0x10), data);
nv_mask(dev, 0x610704 + (id * 0x10), 0x80000ffc, 0x80000000 | mthd);
if (!nv_wait(dev, 0x610704 + (id * 0x10), 0x80000000, 0x00000000))
ret = -EBUSY;
nv_mask(dev, 0x610700 + (id * 0x10), 0x00000001, 0x00000000);
return ret;
}
static u32 *
evo_wait(struct drm_device *dev, int id, int nr)
{
struct nvd0_display *disp = nvd0_display(dev);
u32 put = nv_rd32(dev, 0x640000 + (id * 0x1000)) / 4;
if (put + nr >= (PAGE_SIZE / 4)) {
disp->evo[id].ptr[put] = 0x20000000;
nv_wr32(dev, 0x640000 + (id * 0x1000), 0x00000000);
if (!nv_wait(dev, 0x640004 + (id * 0x1000), ~0, 0x00000000)) {
NV_ERROR(dev, "evo %d dma stalled\n", id);
return NULL;
}
put = 0;
}
if (nouveau_reg_debug & NOUVEAU_REG_DEBUG_EVO)
NV_INFO(dev, "Evo%d: %p START\n", id, disp->evo[id].ptr + put);
return disp->evo[id].ptr + put;
}
static void
evo_kick(u32 *push, struct drm_device *dev, int id)
{
struct nvd0_display *disp = nvd0_display(dev);
if (nouveau_reg_debug & NOUVEAU_REG_DEBUG_EVO) {
u32 curp = nv_rd32(dev, 0x640000 + (id * 0x1000)) >> 2;
u32 *cur = disp->evo[id].ptr + curp;
while (cur < push)
NV_INFO(dev, "Evo%d: 0x%08x\n", id, *cur++);
NV_INFO(dev, "Evo%d: %p KICK!\n", id, push);
}
nv_wr32(dev, 0x640000 + (id * 0x1000), (push - disp->evo[id].ptr) << 2);
}
#define evo_mthd(p,m,s) *((p)++) = (((s) << 18) | (m))
#define evo_data(p,d) *((p)++) = (d)
static int
evo_init_dma(struct drm_device *dev, int ch)
{
struct nvd0_display *disp = nvd0_display(dev);
u32 flags;
flags = 0x00000000;
if (ch == EVO_MASTER)
flags |= 0x01000000;
nv_wr32(dev, 0x610494 + (ch * 0x0010), (disp->evo[ch].handle >> 8) | 3);
nv_wr32(dev, 0x610498 + (ch * 0x0010), 0x00010000);
nv_wr32(dev, 0x61049c + (ch * 0x0010), 0x00000001);
nv_mask(dev, 0x610490 + (ch * 0x0010), 0x00000010, 0x00000010);
nv_wr32(dev, 0x640000 + (ch * 0x1000), 0x00000000);
nv_wr32(dev, 0x610490 + (ch * 0x0010), 0x00000013 | flags);
if (!nv_wait(dev, 0x610490 + (ch * 0x0010), 0x80000000, 0x00000000)) {
NV_ERROR(dev, "PDISP: ch%d 0x%08x\n", ch,
nv_rd32(dev, 0x610490 + (ch * 0x0010)));
return -EBUSY;
}
nv_mask(dev, 0x610090, (1 << ch), (1 << ch));
nv_mask(dev, 0x6100a0, (1 << ch), (1 << ch));
return 0;
}
static void
evo_fini_dma(struct drm_device *dev, int ch)
{
if (!(nv_rd32(dev, 0x610490 + (ch * 0x0010)) & 0x00000010))
return;
nv_mask(dev, 0x610490 + (ch * 0x0010), 0x00000010, 0x00000000);
nv_mask(dev, 0x610490 + (ch * 0x0010), 0x00000003, 0x00000000);
nv_wait(dev, 0x610490 + (ch * 0x0010), 0x80000000, 0x00000000);
nv_mask(dev, 0x610090, (1 << ch), 0x00000000);
nv_mask(dev, 0x6100a0, (1 << ch), 0x00000000);
}
static inline void
evo_piow(struct drm_device *dev, int ch, u16 mthd, u32 data)
{
nv_wr32(dev, 0x640000 + (ch * 0x1000) + mthd, data);
}
static int
evo_init_pio(struct drm_device *dev, int ch)
{
nv_wr32(dev, 0x610490 + (ch * 0x0010), 0x00000001);
if (!nv_wait(dev, 0x610490 + (ch * 0x0010), 0x00010000, 0x00010000)) {
NV_ERROR(dev, "PDISP: ch%d 0x%08x\n", ch,
nv_rd32(dev, 0x610490 + (ch * 0x0010)));
return -EBUSY;
}
nv_mask(dev, 0x610090, (1 << ch), (1 << ch));
nv_mask(dev, 0x6100a0, (1 << ch), (1 << ch));
return 0;
}
static void
evo_fini_pio(struct drm_device *dev, int ch)
{
if (!(nv_rd32(dev, 0x610490 + (ch * 0x0010)) & 0x00000001))
return;
nv_mask(dev, 0x610490 + (ch * 0x0010), 0x00000010, 0x00000010);
nv_mask(dev, 0x610490 + (ch * 0x0010), 0x00000001, 0x00000000);
nv_wait(dev, 0x610490 + (ch * 0x0010), 0x00010000, 0x00000000);
nv_mask(dev, 0x610090, (1 << ch), 0x00000000);
nv_mask(dev, 0x6100a0, (1 << ch), 0x00000000);
}
static bool
evo_sync_wait(void *data)
{
return nouveau_bo_rd32(data, EVO_MAST_NTFY) != 0x00000000;
}
static int
evo_sync(struct drm_device *dev, int ch)
{
struct nvd0_display *disp = nvd0_display(dev);
u32 *push = evo_wait(dev, ch, 8);
if (push) {
nouveau_bo_wr32(disp->sync, EVO_MAST_NTFY, 0x00000000);
evo_mthd(push, 0x0084, 1);
evo_data(push, 0x80000000 | EVO_MAST_NTFY);
evo_mthd(push, 0x0080, 2);
evo_data(push, 0x00000000);
evo_data(push, 0x00000000);
evo_kick(push, dev, ch);
if (nv_wait_cb(dev, evo_sync_wait, disp->sync))
return 0;
}
return -EBUSY;
}
/******************************************************************************
* Page flipping channel
*****************************************************************************/
struct nouveau_bo *
nvd0_display_crtc_sema(struct drm_device *dev, int crtc)
{
return nvd0_display(dev)->sync;
}
void
nvd0_display_flip_stop(struct drm_crtc *crtc)
{
struct nvd0_display *disp = nvd0_display(crtc->dev);
struct nouveau_crtc *nv_crtc = nouveau_crtc(crtc);
struct evo *evo = &disp->evo[EVO_FLIP(nv_crtc->index)];
u32 *push;
push = evo_wait(crtc->dev, evo->idx, 8);
if (push) {
evo_mthd(push, 0x0084, 1);
evo_data(push, 0x00000000);
evo_mthd(push, 0x0094, 1);
evo_data(push, 0x00000000);
evo_mthd(push, 0x00c0, 1);
evo_data(push, 0x00000000);
evo_mthd(push, 0x0080, 1);
evo_data(push, 0x00000000);
evo_kick(push, crtc->dev, evo->idx);
}
}
int
nvd0_display_flip_next(struct drm_crtc *crtc, struct drm_framebuffer *fb,
struct nouveau_channel *chan, u32 swap_interval)
{
struct nouveau_framebuffer *nv_fb = nouveau_framebuffer(fb);
struct nvd0_display *disp = nvd0_display(crtc->dev);
struct nouveau_crtc *nv_crtc = nouveau_crtc(crtc);
struct evo *evo = &disp->evo[EVO_FLIP(nv_crtc->index)];
u64 offset;
u32 *push;
int ret;
swap_interval <<= 4;
if (swap_interval == 0)
swap_interval |= 0x100;
push = evo_wait(crtc->dev, evo->idx, 128);
if (unlikely(push == NULL))
return -EBUSY;
/* synchronise with the rendering channel, if necessary */
if (likely(chan)) {
ret = RING_SPACE(chan, 10);
if (ret)
return ret;
offset = nvc0_software_crtc(chan, nv_crtc->index);
offset += evo->sem.offset;
BEGIN_NVC0(chan, 0, NV84_SUBCHAN_SEMAPHORE_ADDRESS_HIGH, 4);
OUT_RING (chan, upper_32_bits(offset));
OUT_RING (chan, lower_32_bits(offset));
OUT_RING (chan, 0xf00d0000 | evo->sem.value);
OUT_RING (chan, 0x1002);
BEGIN_NVC0(chan, 0, NV84_SUBCHAN_SEMAPHORE_ADDRESS_HIGH, 4);
OUT_RING (chan, upper_32_bits(offset));
OUT_RING (chan, lower_32_bits(offset ^ 0x10));
OUT_RING (chan, 0x74b1e000);
OUT_RING (chan, 0x1001);
FIRE_RING (chan);
} else {
nouveau_bo_wr32(disp->sync, evo->sem.offset / 4,
0xf00d0000 | evo->sem.value);
evo_sync(crtc->dev, EVO_MASTER);
}
/* queue the flip */
evo_mthd(push, 0x0100, 1);
evo_data(push, 0xfffe0000);
evo_mthd(push, 0x0084, 1);
evo_data(push, swap_interval);
if (!(swap_interval & 0x00000100)) {
evo_mthd(push, 0x00e0, 1);
evo_data(push, 0x40000000);
}
evo_mthd(push, 0x0088, 4);
evo_data(push, evo->sem.offset);
evo_data(push, 0xf00d0000 | evo->sem.value);
evo_data(push, 0x74b1e000);
evo_data(push, NvEvoSync);
evo_mthd(push, 0x00a0, 2);
evo_data(push, 0x00000000);
evo_data(push, 0x00000000);
evo_mthd(push, 0x00c0, 1);
evo_data(push, nv_fb->r_dma);
evo_mthd(push, 0x0110, 2);
evo_data(push, 0x00000000);
evo_data(push, 0x00000000);
evo_mthd(push, 0x0400, 5);
evo_data(push, nv_fb->nvbo->bo.offset >> 8);
evo_data(push, 0);
evo_data(push, (fb->height << 16) | fb->width);
evo_data(push, nv_fb->r_pitch);
evo_data(push, nv_fb->r_format);
evo_mthd(push, 0x0080, 1);
evo_data(push, 0x00000000);
evo_kick(push, crtc->dev, evo->idx);
evo->sem.offset ^= 0x10;
evo->sem.value++;
return 0;
}
/******************************************************************************
* CRTC
*****************************************************************************/
static int
nvd0_crtc_set_dither(struct nouveau_crtc *nv_crtc, bool update)
{
struct drm_nouveau_private *dev_priv = nv_crtc->base.dev->dev_private;
struct drm_device *dev = nv_crtc->base.dev;
struct nouveau_connector *nv_connector;
struct drm_connector *connector;
u32 *push, mode = 0x00;
u32 mthd;
nv_connector = nouveau_crtc_connector_get(nv_crtc);
connector = &nv_connector->base;
if (nv_connector->dithering_mode == DITHERING_MODE_AUTO) {
if (nv_crtc->base.fb->depth > connector->display_info.bpc * 3)
mode = DITHERING_MODE_DYNAMIC2X2;
} else {
mode = nv_connector->dithering_mode;
}
if (nv_connector->dithering_depth == DITHERING_DEPTH_AUTO) {
if (connector->display_info.bpc >= 8)
mode |= DITHERING_DEPTH_8BPC;
} else {
mode |= nv_connector->dithering_depth;
}
if (dev_priv->card_type < NV_E0)
mthd = 0x0490 + (nv_crtc->index * 0x0300);
else
mthd = 0x04a0 + (nv_crtc->index * 0x0300);
push = evo_wait(dev, EVO_MASTER, 4);
if (push) {
evo_mthd(push, mthd, 1);
evo_data(push, mode);
if (update) {
evo_mthd(push, 0x0080, 1);
evo_data(push, 0x00000000);
}
evo_kick(push, dev, EVO_MASTER);
}
return 0;
}
static int
nvd0_crtc_set_scale(struct nouveau_crtc *nv_crtc, bool update)
{
struct drm_display_mode *omode, *umode = &nv_crtc->base.mode;
struct drm_device *dev = nv_crtc->base.dev;
struct drm_crtc *crtc = &nv_crtc->base;
struct nouveau_connector *nv_connector;
int mode = DRM_MODE_SCALE_NONE;
u32 oX, oY, *push;
/* start off at the resolution we programmed the crtc for, this
* effectively handles NONE/FULL scaling
*/
nv_connector = nouveau_crtc_connector_get(nv_crtc);
if (nv_connector && nv_connector->native_mode)
mode = nv_connector->scaling_mode;
if (mode != DRM_MODE_SCALE_NONE)
omode = nv_connector->native_mode;
else
omode = umode;
oX = omode->hdisplay;
oY = omode->vdisplay;
if (omode->flags & DRM_MODE_FLAG_DBLSCAN)
oY *= 2;
/* add overscan compensation if necessary, will keep the aspect
* ratio the same as the backend mode unless overridden by the
* user setting both hborder and vborder properties.
*/
if (nv_connector && ( nv_connector->underscan == UNDERSCAN_ON ||
(nv_connector->underscan == UNDERSCAN_AUTO &&
nv_connector->edid &&
drm_detect_hdmi_monitor(nv_connector->edid)))) {
u32 bX = nv_connector->underscan_hborder;
u32 bY = nv_connector->underscan_vborder;
u32 aspect = (oY << 19) / oX;
if (bX) {
oX -= (bX * 2);
if (bY) oY -= (bY * 2);
else oY = ((oX * aspect) + (aspect / 2)) >> 19;
} else {
oX -= (oX >> 4) + 32;
if (bY) oY -= (bY * 2);
else oY = ((oX * aspect) + (aspect / 2)) >> 19;
}
}
/* handle CENTER/ASPECT scaling, taking into account the areas
* removed already for overscan compensation
*/
switch (mode) {
case DRM_MODE_SCALE_CENTER:
oX = min((u32)umode->hdisplay, oX);
oY = min((u32)umode->vdisplay, oY);
/* fall-through */
case DRM_MODE_SCALE_ASPECT:
if (oY < oX) {
u32 aspect = (umode->hdisplay << 19) / umode->vdisplay;
oX = ((oY * aspect) + (aspect / 2)) >> 19;
} else {
u32 aspect = (umode->vdisplay << 19) / umode->hdisplay;
oY = ((oX * aspect) + (aspect / 2)) >> 19;
}
break;
default:
break;
}
push = evo_wait(dev, EVO_MASTER, 8);
if (push) {
evo_mthd(push, 0x04c0 + (nv_crtc->index * 0x300), 3);
evo_data(push, (oY << 16) | oX);
evo_data(push, (oY << 16) | oX);
evo_data(push, (oY << 16) | oX);
evo_mthd(push, 0x0494 + (nv_crtc->index * 0x300), 1);
evo_data(push, 0x00000000);
evo_mthd(push, 0x04b8 + (nv_crtc->index * 0x300), 1);
evo_data(push, (umode->vdisplay << 16) | umode->hdisplay);
evo_kick(push, dev, EVO_MASTER);
if (update) {
nvd0_display_flip_stop(crtc);
nvd0_display_flip_next(crtc, crtc->fb, NULL, 1);
}
}
return 0;
}
static int
nvd0_crtc_set_image(struct nouveau_crtc *nv_crtc, struct drm_framebuffer *fb,
int x, int y, bool update)
{
struct nouveau_framebuffer *nvfb = nouveau_framebuffer(fb);
u32 *push;
push = evo_wait(fb->dev, EVO_MASTER, 16);
if (push) {
evo_mthd(push, 0x0460 + (nv_crtc->index * 0x300), 1);
evo_data(push, nvfb->nvbo->bo.offset >> 8);
evo_mthd(push, 0x0468 + (nv_crtc->index * 0x300), 4);
evo_data(push, (fb->height << 16) | fb->width);
evo_data(push, nvfb->r_pitch);
evo_data(push, nvfb->r_format);
evo_data(push, nvfb->r_dma);
evo_mthd(push, 0x04b0 + (nv_crtc->index * 0x300), 1);
evo_data(push, (y << 16) | x);
if (update) {
evo_mthd(push, 0x0080, 1);
evo_data(push, 0x00000000);
}
evo_kick(push, fb->dev, EVO_MASTER);
}
nv_crtc->fb.tile_flags = nvfb->r_dma;
return 0;
}
static void
nvd0_crtc_cursor_show(struct nouveau_crtc *nv_crtc, bool show, bool update)
{
struct drm_device *dev = nv_crtc->base.dev;
u32 *push = evo_wait(dev, EVO_MASTER, 16);
if (push) {
if (show) {
evo_mthd(push, 0x0480 + (nv_crtc->index * 0x300), 2);
evo_data(push, 0x85000000);
evo_data(push, nv_crtc->cursor.nvbo->bo.offset >> 8);
evo_mthd(push, 0x048c + (nv_crtc->index * 0x300), 1);
evo_data(push, NvEvoVRAM);
} else {
evo_mthd(push, 0x0480 + (nv_crtc->index * 0x300), 1);
evo_data(push, 0x05000000);
evo_mthd(push, 0x048c + (nv_crtc->index * 0x300), 1);
evo_data(push, 0x00000000);
}
if (update) {
evo_mthd(push, 0x0080, 1);
evo_data(push, 0x00000000);
}
evo_kick(push, dev, EVO_MASTER);
}
}
static void
nvd0_crtc_dpms(struct drm_crtc *crtc, int mode)
{
}
static void
nvd0_crtc_prepare(struct drm_crtc *crtc)
{
struct nouveau_crtc *nv_crtc = nouveau_crtc(crtc);
u32 *push;
nvd0_display_flip_stop(crtc);
push = evo_wait(crtc->dev, EVO_MASTER, 2);
if (push) {
evo_mthd(push, 0x0474 + (nv_crtc->index * 0x300), 1);
evo_data(push, 0x00000000);
evo_mthd(push, 0x0440 + (nv_crtc->index * 0x300), 1);
evo_data(push, 0x03000000);
evo_mthd(push, 0x045c + (nv_crtc->index * 0x300), 1);
evo_data(push, 0x00000000);
evo_kick(push, crtc->dev, EVO_MASTER);
}
nvd0_crtc_cursor_show(nv_crtc, false, false);
}
static void
nvd0_crtc_commit(struct drm_crtc *crtc)
{
struct nouveau_crtc *nv_crtc = nouveau_crtc(crtc);
u32 *push;
push = evo_wait(crtc->dev, EVO_MASTER, 32);
if (push) {
evo_mthd(push, 0x0474 + (nv_crtc->index * 0x300), 1);
evo_data(push, nv_crtc->fb.tile_flags);
evo_mthd(push, 0x0440 + (nv_crtc->index * 0x300), 4);
evo_data(push, 0x83000000);
evo_data(push, nv_crtc->lut.nvbo->bo.offset >> 8);
evo_data(push, 0x00000000);
evo_data(push, 0x00000000);
evo_mthd(push, 0x045c + (nv_crtc->index * 0x300), 1);
evo_data(push, NvEvoVRAM);
evo_mthd(push, 0x0430 + (nv_crtc->index * 0x300), 1);
evo_data(push, 0xffffff00);
evo_kick(push, crtc->dev, EVO_MASTER);
}
nvd0_crtc_cursor_show(nv_crtc, nv_crtc->cursor.visible, true);
nvd0_display_flip_next(crtc, crtc->fb, NULL, 1);
}
static bool
nvd0_crtc_mode_fixup(struct drm_crtc *crtc, const struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
return true;
}
static int
nvd0_crtc_swap_fbs(struct drm_crtc *crtc, struct drm_framebuffer *old_fb)
{
struct nouveau_framebuffer *nvfb = nouveau_framebuffer(crtc->fb);
int ret;
ret = nouveau_bo_pin(nvfb->nvbo, TTM_PL_FLAG_VRAM);
if (ret)
return ret;
if (old_fb) {
nvfb = nouveau_framebuffer(old_fb);
nouveau_bo_unpin(nvfb->nvbo);
}
return 0;
}
static int
nvd0_crtc_mode_set(struct drm_crtc *crtc, struct drm_display_mode *umode,
struct drm_display_mode *mode, int x, int y,
struct drm_framebuffer *old_fb)
{
struct nouveau_crtc *nv_crtc = nouveau_crtc(crtc);
struct nouveau_connector *nv_connector;
u32 ilace = (mode->flags & DRM_MODE_FLAG_INTERLACE) ? 2 : 1;
u32 vscan = (mode->flags & DRM_MODE_FLAG_DBLSCAN) ? 2 : 1;
u32 hactive, hsynce, hbackp, hfrontp, hblanke, hblanks;
u32 vactive, vsynce, vbackp, vfrontp, vblanke, vblanks;
u32 vblan2e = 0, vblan2s = 1;
u32 *push;
int ret;
hactive = mode->htotal;
hsynce = mode->hsync_end - mode->hsync_start - 1;
hbackp = mode->htotal - mode->hsync_end;
hblanke = hsynce + hbackp;
hfrontp = mode->hsync_start - mode->hdisplay;
hblanks = mode->htotal - hfrontp - 1;
vactive = mode->vtotal * vscan / ilace;
vsynce = ((mode->vsync_end - mode->vsync_start) * vscan / ilace) - 1;
vbackp = (mode->vtotal - mode->vsync_end) * vscan / ilace;
vblanke = vsynce + vbackp;
vfrontp = (mode->vsync_start - mode->vdisplay) * vscan / ilace;
vblanks = vactive - vfrontp - 1;
if (mode->flags & DRM_MODE_FLAG_INTERLACE) {
vblan2e = vactive + vsynce + vbackp;
vblan2s = vblan2e + (mode->vdisplay * vscan / ilace);
vactive = (vactive * 2) + 1;
}
ret = nvd0_crtc_swap_fbs(crtc, old_fb);
if (ret)
return ret;
push = evo_wait(crtc->dev, EVO_MASTER, 64);
if (push) {
evo_mthd(push, 0x0410 + (nv_crtc->index * 0x300), 6);
evo_data(push, 0x00000000);
evo_data(push, (vactive << 16) | hactive);
evo_data(push, ( vsynce << 16) | hsynce);
evo_data(push, (vblanke << 16) | hblanke);
evo_data(push, (vblanks << 16) | hblanks);
evo_data(push, (vblan2e << 16) | vblan2s);
evo_mthd(push, 0x042c + (nv_crtc->index * 0x300), 1);
evo_data(push, 0x00000000); /* ??? */
evo_mthd(push, 0x0450 + (nv_crtc->index * 0x300), 3);
evo_data(push, mode->clock * 1000);
evo_data(push, 0x00200000); /* ??? */
evo_data(push, mode->clock * 1000);
evo_mthd(push, 0x04d0 + (nv_crtc->index * 0x300), 2);
evo_data(push, 0x00000311);
evo_data(push, 0x00000100);
evo_kick(push, crtc->dev, EVO_MASTER);
}
nv_connector = nouveau_crtc_connector_get(nv_crtc);
nvd0_crtc_set_dither(nv_crtc, false);
nvd0_crtc_set_scale(nv_crtc, false);
nvd0_crtc_set_image(nv_crtc, crtc->fb, x, y, false);
return 0;
}
static int
nvd0_crtc_mode_set_base(struct drm_crtc *crtc, int x, int y,
struct drm_framebuffer *old_fb)
{
struct nouveau_crtc *nv_crtc = nouveau_crtc(crtc);
int ret;
if (!crtc->fb) {
NV_DEBUG_KMS(crtc->dev, "No FB bound\n");
return 0;
}
ret = nvd0_crtc_swap_fbs(crtc, old_fb);
if (ret)
return ret;
nvd0_display_flip_stop(crtc);
nvd0_crtc_set_image(nv_crtc, crtc->fb, x, y, true);
nvd0_display_flip_next(crtc, crtc->fb, NULL, 1);
return 0;
}
static int
nvd0_crtc_mode_set_base_atomic(struct drm_crtc *crtc,
struct drm_framebuffer *fb, int x, int y,
enum mode_set_atomic state)
{
struct nouveau_crtc *nv_crtc = nouveau_crtc(crtc);
nvd0_display_flip_stop(crtc);
nvd0_crtc_set_image(nv_crtc, fb, x, y, true);
return 0;
}
static void
nvd0_crtc_lut_load(struct drm_crtc *crtc)
{
struct nouveau_crtc *nv_crtc = nouveau_crtc(crtc);
void __iomem *lut = nvbo_kmap_obj_iovirtual(nv_crtc->lut.nvbo);
int i;
for (i = 0; i < 256; i++) {
writew(0x6000 + (nv_crtc->lut.r[i] >> 2), lut + (i * 0x20) + 0);
writew(0x6000 + (nv_crtc->lut.g[i] >> 2), lut + (i * 0x20) + 2);
writew(0x6000 + (nv_crtc->lut.b[i] >> 2), lut + (i * 0x20) + 4);
}
}
static int
nvd0_crtc_cursor_set(struct drm_crtc *crtc, struct drm_file *file_priv,
uint32_t handle, uint32_t width, uint32_t height)
{
struct nouveau_crtc *nv_crtc = nouveau_crtc(crtc);
struct drm_device *dev = crtc->dev;
struct drm_gem_object *gem;
struct nouveau_bo *nvbo;
bool visible = (handle != 0);
int i, ret = 0;
if (visible) {
if (width != 64 || height != 64)
return -EINVAL;
gem = drm_gem_object_lookup(dev, file_priv, handle);
if (unlikely(!gem))
return -ENOENT;
nvbo = nouveau_gem_object(gem);
ret = nouveau_bo_map(nvbo);
if (ret == 0) {
for (i = 0; i < 64 * 64; i++) {
u32 v = nouveau_bo_rd32(nvbo, i);
nouveau_bo_wr32(nv_crtc->cursor.nvbo, i, v);
}
nouveau_bo_unmap(nvbo);
}
drm_gem_object_unreference_unlocked(gem);
}
if (visible != nv_crtc->cursor.visible) {
nvd0_crtc_cursor_show(nv_crtc, visible, true);
nv_crtc->cursor.visible = visible;
}
return ret;
}
static int
nvd0_crtc_cursor_move(struct drm_crtc *crtc, int x, int y)
{
struct nouveau_crtc *nv_crtc = nouveau_crtc(crtc);
int ch = EVO_CURS(nv_crtc->index);
evo_piow(crtc->dev, ch, 0x0084, (y << 16) | (x & 0xffff));
evo_piow(crtc->dev, ch, 0x0080, 0x00000000);
return 0;
}
static void
nvd0_crtc_gamma_set(struct drm_crtc *crtc, u16 *r, u16 *g, u16 *b,
uint32_t start, uint32_t size)
{
struct nouveau_crtc *nv_crtc = nouveau_crtc(crtc);
u32 end = max(start + size, (u32)256);
u32 i;
for (i = start; i < end; i++) {
nv_crtc->lut.r[i] = r[i];
nv_crtc->lut.g[i] = g[i];
nv_crtc->lut.b[i] = b[i];
}
nvd0_crtc_lut_load(crtc);
}
static void
nvd0_crtc_destroy(struct drm_crtc *crtc)
{
struct nouveau_crtc *nv_crtc = nouveau_crtc(crtc);
nouveau_bo_unmap(nv_crtc->cursor.nvbo);
nouveau_bo_ref(NULL, &nv_crtc->cursor.nvbo);
nouveau_bo_unmap(nv_crtc->lut.nvbo);
nouveau_bo_ref(NULL, &nv_crtc->lut.nvbo);
drm_crtc_cleanup(crtc);
kfree(crtc);
}
static const struct drm_crtc_helper_funcs nvd0_crtc_hfunc = {
.dpms = nvd0_crtc_dpms,
.prepare = nvd0_crtc_prepare,
.commit = nvd0_crtc_commit,
.mode_fixup = nvd0_crtc_mode_fixup,
.mode_set = nvd0_crtc_mode_set,
.mode_set_base = nvd0_crtc_mode_set_base,
.mode_set_base_atomic = nvd0_crtc_mode_set_base_atomic,
.load_lut = nvd0_crtc_lut_load,
};
static const struct drm_crtc_funcs nvd0_crtc_func = {
.cursor_set = nvd0_crtc_cursor_set,
.cursor_move = nvd0_crtc_cursor_move,
.gamma_set = nvd0_crtc_gamma_set,
.set_config = drm_crtc_helper_set_config,
.destroy = nvd0_crtc_destroy,
.page_flip = nouveau_crtc_page_flip,
};
static void
nvd0_cursor_set_pos(struct nouveau_crtc *nv_crtc, int x, int y)
{
}
static void
nvd0_cursor_set_offset(struct nouveau_crtc *nv_crtc, uint32_t offset)
{
}
static int
nvd0_crtc_create(struct drm_device *dev, int index)
{
struct nouveau_crtc *nv_crtc;
struct drm_crtc *crtc;
int ret, i;
nv_crtc = kzalloc(sizeof(*nv_crtc), GFP_KERNEL);
if (!nv_crtc)
return -ENOMEM;
nv_crtc->index = index;
nv_crtc->set_dither = nvd0_crtc_set_dither;
nv_crtc->set_scale = nvd0_crtc_set_scale;
nv_crtc->cursor.set_offset = nvd0_cursor_set_offset;
nv_crtc->cursor.set_pos = nvd0_cursor_set_pos;
for (i = 0; i < 256; i++) {
nv_crtc->lut.r[i] = i << 8;
nv_crtc->lut.g[i] = i << 8;
nv_crtc->lut.b[i] = i << 8;
}
crtc = &nv_crtc->base;
drm_crtc_init(dev, crtc, &nvd0_crtc_func);
drm_crtc_helper_add(crtc, &nvd0_crtc_hfunc);
drm_mode_crtc_set_gamma_size(crtc, 256);
ret = nouveau_bo_new(dev, 64 * 64 * 4, 0x100, TTM_PL_FLAG_VRAM,
0, 0x0000, NULL, &nv_crtc->cursor.nvbo);
if (!ret) {
ret = nouveau_bo_pin(nv_crtc->cursor.nvbo, TTM_PL_FLAG_VRAM);
if (!ret)
ret = nouveau_bo_map(nv_crtc->cursor.nvbo);
if (ret)
nouveau_bo_ref(NULL, &nv_crtc->cursor.nvbo);
}
if (ret)
goto out;
ret = nouveau_bo_new(dev, 8192, 0x100, TTM_PL_FLAG_VRAM,
0, 0x0000, NULL, &nv_crtc->lut.nvbo);
if (!ret) {
ret = nouveau_bo_pin(nv_crtc->lut.nvbo, TTM_PL_FLAG_VRAM);
if (!ret)
ret = nouveau_bo_map(nv_crtc->lut.nvbo);
if (ret)
nouveau_bo_ref(NULL, &nv_crtc->lut.nvbo);
}
if (ret)
goto out;
nvd0_crtc_lut_load(crtc);
out:
if (ret)
nvd0_crtc_destroy(crtc);
return ret;
}
/******************************************************************************
* DAC
*****************************************************************************/
static void
nvd0_dac_dpms(struct drm_encoder *encoder, int mode)
{
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
struct drm_device *dev = encoder->dev;
int or = nv_encoder->or;
u32 dpms_ctrl;
dpms_ctrl = 0x80000000;
if (mode == DRM_MODE_DPMS_STANDBY || mode == DRM_MODE_DPMS_OFF)
dpms_ctrl |= 0x00000001;
if (mode == DRM_MODE_DPMS_SUSPEND || mode == DRM_MODE_DPMS_OFF)
dpms_ctrl |= 0x00000004;
nv_wait(dev, 0x61a004 + (or * 0x0800), 0x80000000, 0x00000000);
nv_mask(dev, 0x61a004 + (or * 0x0800), 0xc000007f, dpms_ctrl);
nv_wait(dev, 0x61a004 + (or * 0x0800), 0x80000000, 0x00000000);
}
static bool
nvd0_dac_mode_fixup(struct drm_encoder *encoder,
const struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
struct nouveau_connector *nv_connector;
nv_connector = nouveau_encoder_connector_get(nv_encoder);
if (nv_connector && nv_connector->native_mode) {
if (nv_connector->scaling_mode != DRM_MODE_SCALE_NONE) {
int id = adjusted_mode->base.id;
*adjusted_mode = *nv_connector->native_mode;
adjusted_mode->base.id = id;
}
}
return true;
}
static void
nvd0_dac_commit(struct drm_encoder *encoder)
{
}
static void
nvd0_dac_mode_set(struct drm_encoder *encoder, struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
struct nouveau_crtc *nv_crtc = nouveau_crtc(encoder->crtc);
u32 syncs, magic, *push;
syncs = 0x00000001;
if (mode->flags & DRM_MODE_FLAG_NHSYNC)
syncs |= 0x00000008;
if (mode->flags & DRM_MODE_FLAG_NVSYNC)
syncs |= 0x00000010;
magic = 0x31ec6000 | (nv_crtc->index << 25);
if (mode->flags & DRM_MODE_FLAG_INTERLACE)
magic |= 0x00000001;
nvd0_dac_dpms(encoder, DRM_MODE_DPMS_ON);
push = evo_wait(encoder->dev, EVO_MASTER, 8);
if (push) {
evo_mthd(push, 0x0404 + (nv_crtc->index * 0x300), 2);
evo_data(push, syncs);
evo_data(push, magic);
evo_mthd(push, 0x0180 + (nv_encoder->or * 0x020), 2);
evo_data(push, 1 << nv_crtc->index);
evo_data(push, 0x00ff);
evo_kick(push, encoder->dev, EVO_MASTER);
}
nv_encoder->crtc = encoder->crtc;
}
static void
nvd0_dac_disconnect(struct drm_encoder *encoder)
{
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
struct drm_device *dev = encoder->dev;
u32 *push;
if (nv_encoder->crtc) {
nvd0_crtc_prepare(nv_encoder->crtc);
push = evo_wait(dev, EVO_MASTER, 4);
if (push) {
evo_mthd(push, 0x0180 + (nv_encoder->or * 0x20), 1);
evo_data(push, 0x00000000);
evo_mthd(push, 0x0080, 1);
evo_data(push, 0x00000000);
evo_kick(push, dev, EVO_MASTER);
}
nv_encoder->crtc = NULL;
}
}
static enum drm_connector_status
nvd0_dac_detect(struct drm_encoder *encoder, struct drm_connector *connector)
{
enum drm_connector_status status = connector_status_disconnected;
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
struct drm_device *dev = encoder->dev;
int or = nv_encoder->or;
u32 load;
nv_wr32(dev, 0x61a00c + (or * 0x800), 0x00100000);
udelay(9500);
nv_wr32(dev, 0x61a00c + (or * 0x800), 0x80000000);
load = nv_rd32(dev, 0x61a00c + (or * 0x800));
if ((load & 0x38000000) == 0x38000000)
status = connector_status_connected;
nv_wr32(dev, 0x61a00c + (or * 0x800), 0x00000000);
return status;
}
static void
nvd0_dac_destroy(struct drm_encoder *encoder)
{
drm_encoder_cleanup(encoder);
kfree(encoder);
}
static const struct drm_encoder_helper_funcs nvd0_dac_hfunc = {
.dpms = nvd0_dac_dpms,
.mode_fixup = nvd0_dac_mode_fixup,
.prepare = nvd0_dac_disconnect,
.commit = nvd0_dac_commit,
.mode_set = nvd0_dac_mode_set,
.disable = nvd0_dac_disconnect,
.get_crtc = nvd0_display_crtc_get,
.detect = nvd0_dac_detect
};
static const struct drm_encoder_funcs nvd0_dac_func = {
.destroy = nvd0_dac_destroy,
};
static int
nvd0_dac_create(struct drm_connector *connector, struct dcb_entry *dcbe)
{
struct drm_device *dev = connector->dev;
struct nouveau_encoder *nv_encoder;
struct drm_encoder *encoder;
nv_encoder = kzalloc(sizeof(*nv_encoder), GFP_KERNEL);
if (!nv_encoder)
return -ENOMEM;
nv_encoder->dcb = dcbe;
nv_encoder->or = ffs(dcbe->or) - 1;
encoder = to_drm_encoder(nv_encoder);
encoder->possible_crtcs = dcbe->heads;
encoder->possible_clones = 0;
drm_encoder_init(dev, encoder, &nvd0_dac_func, DRM_MODE_ENCODER_DAC);
drm_encoder_helper_add(encoder, &nvd0_dac_hfunc);
drm_mode_connector_attach_encoder(connector, encoder);
return 0;
}
/******************************************************************************
* Audio
*****************************************************************************/
static void
nvd0_audio_mode_set(struct drm_encoder *encoder, struct drm_display_mode *mode)
{
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
struct nouveau_connector *nv_connector;
struct drm_device *dev = encoder->dev;
int i, or = nv_encoder->or * 0x30;
nv_connector = nouveau_encoder_connector_get(nv_encoder);
if (!drm_detect_monitor_audio(nv_connector->edid))
return;
nv_mask(dev, 0x10ec10 + or, 0x80000003, 0x80000001);
drm_edid_to_eld(&nv_connector->base, nv_connector->edid);
if (nv_connector->base.eld[0]) {
u8 *eld = nv_connector->base.eld;
for (i = 0; i < eld[2] * 4; i++)
nv_wr32(dev, 0x10ec00 + or, (i << 8) | eld[i]);
for (i = eld[2] * 4; i < 0x60; i++)
nv_wr32(dev, 0x10ec00 + or, (i << 8) | 0x00);
nv_mask(dev, 0x10ec10 + or, 0x80000002, 0x80000002);
}
}
static void
nvd0_audio_disconnect(struct drm_encoder *encoder)
{
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
struct drm_device *dev = encoder->dev;
int or = nv_encoder->or * 0x30;
nv_mask(dev, 0x10ec10 + or, 0x80000003, 0x80000000);
}
/******************************************************************************
* HDMI
*****************************************************************************/
static void
nvd0_hdmi_mode_set(struct drm_encoder *encoder, struct drm_display_mode *mode)
{
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
struct nouveau_crtc *nv_crtc = nouveau_crtc(encoder->crtc);
struct nouveau_connector *nv_connector;
struct drm_device *dev = encoder->dev;
int head = nv_crtc->index * 0x800;
u32 rekey = 56; /* binary driver, and tegra constant */
u32 max_ac_packet;
nv_connector = nouveau_encoder_connector_get(nv_encoder);
if (!drm_detect_hdmi_monitor(nv_connector->edid))
return;
max_ac_packet = mode->htotal - mode->hdisplay;
max_ac_packet -= rekey;
max_ac_packet -= 18; /* constant from tegra */
max_ac_packet /= 32;
/* AVI InfoFrame */
nv_mask(dev, 0x616714 + head, 0x00000001, 0x00000000);
nv_wr32(dev, 0x61671c + head, 0x000d0282);
nv_wr32(dev, 0x616720 + head, 0x0000006f);
nv_wr32(dev, 0x616724 + head, 0x00000000);
nv_wr32(dev, 0x616728 + head, 0x00000000);
nv_wr32(dev, 0x61672c + head, 0x00000000);
nv_mask(dev, 0x616714 + head, 0x00000001, 0x00000001);
/* ??? InfoFrame? */
nv_mask(dev, 0x6167a4 + head, 0x00000001, 0x00000000);
nv_wr32(dev, 0x6167ac + head, 0x00000010);
nv_mask(dev, 0x6167a4 + head, 0x00000001, 0x00000001);
/* HDMI_CTRL */
nv_mask(dev, 0x616798 + head, 0x401f007f, 0x40000000 | rekey |
max_ac_packet << 16);
/* NFI, audio doesn't work without it though.. */
nv_mask(dev, 0x616548 + head, 0x00000070, 0x00000000);
nvd0_audio_mode_set(encoder, mode);
}
static void
nvd0_hdmi_disconnect(struct drm_encoder *encoder)
{
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
struct nouveau_crtc *nv_crtc = nouveau_crtc(nv_encoder->crtc);
struct drm_device *dev = encoder->dev;
int head = nv_crtc->index * 0x800;
nvd0_audio_disconnect(encoder);
nv_mask(dev, 0x616798 + head, 0x40000000, 0x00000000);
nv_mask(dev, 0x6167a4 + head, 0x00000001, 0x00000000);
nv_mask(dev, 0x616714 + head, 0x00000001, 0x00000000);
}
/******************************************************************************
* SOR
*****************************************************************************/
static inline u32
nvd0_sor_dp_lane_map(struct drm_device *dev, struct dcb_entry *dcb, u8 lane)
{
static const u8 nvd0[] = { 16, 8, 0, 24 };
return nvd0[lane];
}
static void
nvd0_sor_dp_train_set(struct drm_device *dev, struct dcb_entry *dcb, u8 pattern)
{
const u32 or = ffs(dcb->or) - 1, link = !(dcb->sorconf.link & 1);
const u32 loff = (or * 0x800) + (link * 0x80);
nv_mask(dev, 0x61c110 + loff, 0x0f0f0f0f, 0x01010101 * pattern);
}
static void
nvd0_sor_dp_train_adj(struct drm_device *dev, struct dcb_entry *dcb,
u8 lane, u8 swing, u8 preem)
{
const u32 or = ffs(dcb->or) - 1, link = !(dcb->sorconf.link & 1);
const u32 loff = (or * 0x800) + (link * 0x80);
u32 shift = nvd0_sor_dp_lane_map(dev, dcb, lane);
u32 mask = 0x000000ff << shift;
u8 *table, *entry, *config = NULL;
switch (swing) {
case 0: preem += 0; break;
case 1: preem += 4; break;
case 2: preem += 7; break;
case 3: preem += 9; break;
}
table = nouveau_dp_bios_data(dev, dcb, &entry);
if (table) {
if (table[0] == 0x30) {
config = entry + table[4];
config += table[5] * preem;
} else
if (table[0] == 0x40) {
config = table + table[1];
config += table[2] * table[3];
config += table[6] * preem;
}
}
if (!config) {
NV_ERROR(dev, "PDISP: unsupported DP table for chipset\n");
return;
}
nv_mask(dev, 0x61c118 + loff, mask, config[1] << shift);
nv_mask(dev, 0x61c120 + loff, mask, config[2] << shift);
nv_mask(dev, 0x61c130 + loff, 0x0000ff00, config[3] << 8);
nv_mask(dev, 0x61c13c + loff, 0x00000000, 0x00000000);
}
static void
nvd0_sor_dp_link_set(struct drm_device *dev, struct dcb_entry *dcb, int crtc,
int link_nr, u32 link_bw, bool enhframe)
{
const u32 or = ffs(dcb->or) - 1, link = !(dcb->sorconf.link & 1);
const u32 loff = (or * 0x800) + (link * 0x80);
const u32 soff = (or * 0x800);
u32 dpctrl = nv_rd32(dev, 0x61c10c + loff) & ~0x001f4000;
u32 clksor = nv_rd32(dev, 0x612300 + soff) & ~0x007c0000;
u32 script = 0x0000, lane_mask = 0;
u8 *table, *entry;
int i;
link_bw /= 27000;
table = nouveau_dp_bios_data(dev, dcb, &entry);
if (table) {
if (table[0] == 0x30) entry = ROMPTR(dev, entry[10]);
else if (table[0] == 0x40) entry = ROMPTR(dev, entry[9]);
else entry = NULL;
while (entry) {
if (entry[0] >= link_bw)
break;
entry += 3;
}
nouveau_bios_run_init_table(dev, script, dcb, crtc);
}
clksor |= link_bw << 18;
dpctrl |= ((1 << link_nr) - 1) << 16;
if (enhframe)
dpctrl |= 0x00004000;
for (i = 0; i < link_nr; i++)
lane_mask |= 1 << (nvd0_sor_dp_lane_map(dev, dcb, i) >> 3);
nv_wr32(dev, 0x612300 + soff, clksor);
nv_wr32(dev, 0x61c10c + loff, dpctrl);
nv_mask(dev, 0x61c130 + loff, 0x0000000f, lane_mask);
}
static void
nvd0_sor_dp_link_get(struct drm_device *dev, struct dcb_entry *dcb,
u32 *link_nr, u32 *link_bw)
{
const u32 or = ffs(dcb->or) - 1, link = !(dcb->sorconf.link & 1);
const u32 loff = (or * 0x800) + (link * 0x80);
const u32 soff = (or * 0x800);
u32 dpctrl = nv_rd32(dev, 0x61c10c + loff) & 0x000f0000;
u32 clksor = nv_rd32(dev, 0x612300 + soff);
if (dpctrl > 0x00030000) *link_nr = 4;
else if (dpctrl > 0x00010000) *link_nr = 2;
else *link_nr = 1;
*link_bw = (clksor & 0x007c0000) >> 18;
*link_bw *= 27000;
}
static void
nvd0_sor_dp_calc_tu(struct drm_device *dev, struct dcb_entry *dcb,
u32 crtc, u32 datarate)
{
const u32 symbol = 100000;
const u32 TU = 64;
u32 link_nr, link_bw;
u64 ratio, value;
nvd0_sor_dp_link_get(dev, dcb, &link_nr, &link_bw);
ratio = datarate;
ratio *= symbol;
do_div(ratio, link_nr * link_bw);
value = (symbol - ratio) * TU;
value *= ratio;
do_div(value, symbol);
do_div(value, symbol);
value += 5;
value |= 0x08000000;
nv_wr32(dev, 0x616610 + (crtc * 0x800), value);
}
static void
nvd0_sor_dpms(struct drm_encoder *encoder, int mode)
{
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
struct drm_device *dev = encoder->dev;
struct drm_encoder *partner;
int or = nv_encoder->or;
u32 dpms_ctrl;
nv_encoder->last_dpms = mode;
list_for_each_entry(partner, &dev->mode_config.encoder_list, head) {
struct nouveau_encoder *nv_partner = nouveau_encoder(partner);
if (partner->encoder_type != DRM_MODE_ENCODER_TMDS)
continue;
if (nv_partner != nv_encoder &&
nv_partner->dcb->or == nv_encoder->dcb->or) {
if (nv_partner->last_dpms == DRM_MODE_DPMS_ON)
return;
break;
}
}
dpms_ctrl = (mode == DRM_MODE_DPMS_ON);
dpms_ctrl |= 0x80000000;
nv_wait(dev, 0x61c004 + (or * 0x0800), 0x80000000, 0x00000000);
nv_mask(dev, 0x61c004 + (or * 0x0800), 0x80000001, dpms_ctrl);
nv_wait(dev, 0x61c004 + (or * 0x0800), 0x80000000, 0x00000000);
nv_wait(dev, 0x61c030 + (or * 0x0800), 0x10000000, 0x00000000);
if (nv_encoder->dcb->type == OUTPUT_DP) {
struct dp_train_func func = {
.link_set = nvd0_sor_dp_link_set,
.train_set = nvd0_sor_dp_train_set,
.train_adj = nvd0_sor_dp_train_adj
};
nouveau_dp_dpms(encoder, mode, nv_encoder->dp.datarate, &func);
}
}
static bool
nvd0_sor_mode_fixup(struct drm_encoder *encoder,
const struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
struct nouveau_connector *nv_connector;
nv_connector = nouveau_encoder_connector_get(nv_encoder);
if (nv_connector && nv_connector->native_mode) {
if (nv_connector->scaling_mode != DRM_MODE_SCALE_NONE) {
int id = adjusted_mode->base.id;
*adjusted_mode = *nv_connector->native_mode;
adjusted_mode->base.id = id;
}
}
return true;
}
static void
nvd0_sor_disconnect(struct drm_encoder *encoder)
{
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
struct drm_device *dev = encoder->dev;
u32 *push;
if (nv_encoder->crtc) {
nvd0_crtc_prepare(nv_encoder->crtc);
push = evo_wait(dev, EVO_MASTER, 4);
if (push) {
evo_mthd(push, 0x0200 + (nv_encoder->or * 0x20), 1);
evo_data(push, 0x00000000);
evo_mthd(push, 0x0080, 1);
evo_data(push, 0x00000000);
evo_kick(push, dev, EVO_MASTER);
}
nvd0_hdmi_disconnect(encoder);
nv_encoder->crtc = NULL;
nv_encoder->last_dpms = DRM_MODE_DPMS_OFF;
}
}
static void
nvd0_sor_prepare(struct drm_encoder *encoder)
{
nvd0_sor_disconnect(encoder);
if (nouveau_encoder(encoder)->dcb->type == OUTPUT_DP)
evo_sync(encoder->dev, EVO_MASTER);
}
static void
nvd0_sor_commit(struct drm_encoder *encoder)
{
}
static void
nvd0_sor_mode_set(struct drm_encoder *encoder, struct drm_display_mode *umode,
struct drm_display_mode *mode)
{
struct drm_device *dev = encoder->dev;
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_encoder *nv_encoder = nouveau_encoder(encoder);
struct nouveau_crtc *nv_crtc = nouveau_crtc(encoder->crtc);
struct nouveau_connector *nv_connector;
struct nvbios *bios = &dev_priv->vbios;
u32 mode_ctrl = (1 << nv_crtc->index);
u32 syncs, magic, *push;
u32 or_config;
syncs = 0x00000001;
if (mode->flags & DRM_MODE_FLAG_NHSYNC)
syncs |= 0x00000008;
if (mode->flags & DRM_MODE_FLAG_NVSYNC)
syncs |= 0x00000010;
magic = 0x31ec6000 | (nv_crtc->index << 25);
if (mode->flags & DRM_MODE_FLAG_INTERLACE)
magic |= 0x00000001;
nv_connector = nouveau_encoder_connector_get(nv_encoder);
switch (nv_encoder->dcb->type) {
case OUTPUT_TMDS:
if (nv_encoder->dcb->sorconf.link & 1) {
if (mode->clock < 165000)
mode_ctrl |= 0x00000100;
else
mode_ctrl |= 0x00000500;
} else {
mode_ctrl |= 0x00000200;
}
or_config = (mode_ctrl & 0x00000f00) >> 8;
if (mode->clock >= 165000)
or_config |= 0x0100;
nvd0_hdmi_mode_set(encoder, mode);
break;
case OUTPUT_LVDS:
or_config = (mode_ctrl & 0x00000f00) >> 8;
if (bios->fp_no_ddc) {
if (bios->fp.dual_link)
or_config |= 0x0100;
if (bios->fp.if_is_24bit)
or_config |= 0x0200;
} else {
if (nv_connector->type == DCB_CONNECTOR_LVDS_SPWG) {
if (((u8 *)nv_connector->edid)[121] == 2)
or_config |= 0x0100;
} else
if (mode->clock >= bios->fp.duallink_transition_clk) {
or_config |= 0x0100;
}
if (or_config & 0x0100) {
if (bios->fp.strapless_is_24bit & 2)
or_config |= 0x0200;
} else {
if (bios->fp.strapless_is_24bit & 1)
or_config |= 0x0200;
}
if (nv_connector->base.display_info.bpc == 8)
or_config |= 0x0200;
}
break;
case OUTPUT_DP:
if (nv_connector->base.display_info.bpc == 6) {
nv_encoder->dp.datarate = mode->clock * 18 / 8;
syncs |= 0x00000002 << 6;
} else {
nv_encoder->dp.datarate = mode->clock * 24 / 8;
syncs |= 0x00000005 << 6;
}
if (nv_encoder->dcb->sorconf.link & 1)
mode_ctrl |= 0x00000800;
else
mode_ctrl |= 0x00000900;
or_config = (mode_ctrl & 0x00000f00) >> 8;
break;
default:
BUG_ON(1);
break;
}
nvd0_sor_dpms(encoder, DRM_MODE_DPMS_ON);
if (nv_encoder->dcb->type == OUTPUT_DP) {
nvd0_sor_dp_calc_tu(dev, nv_encoder->dcb, nv_crtc->index,
nv_encoder->dp.datarate);
}
push = evo_wait(dev, EVO_MASTER, 8);
if (push) {
evo_mthd(push, 0x0404 + (nv_crtc->index * 0x300), 2);
evo_data(push, syncs);
evo_data(push, magic);
evo_mthd(push, 0x0200 + (nv_encoder->or * 0x020), 2);
evo_data(push, mode_ctrl);
evo_data(push, or_config);
evo_kick(push, dev, EVO_MASTER);
}
nv_encoder->crtc = encoder->crtc;
}
static void
nvd0_sor_destroy(struct drm_encoder *encoder)
{
drm_encoder_cleanup(encoder);
kfree(encoder);
}
static const struct drm_encoder_helper_funcs nvd0_sor_hfunc = {
.dpms = nvd0_sor_dpms,
.mode_fixup = nvd0_sor_mode_fixup,
.prepare = nvd0_sor_prepare,
.commit = nvd0_sor_commit,
.mode_set = nvd0_sor_mode_set,
.disable = nvd0_sor_disconnect,
.get_crtc = nvd0_display_crtc_get,
};
static const struct drm_encoder_funcs nvd0_sor_func = {
.destroy = nvd0_sor_destroy,
};
static int
nvd0_sor_create(struct drm_connector *connector, struct dcb_entry *dcbe)
{
struct drm_device *dev = connector->dev;
struct nouveau_encoder *nv_encoder;
struct drm_encoder *encoder;
nv_encoder = kzalloc(sizeof(*nv_encoder), GFP_KERNEL);
if (!nv_encoder)
return -ENOMEM;
nv_encoder->dcb = dcbe;
nv_encoder->or = ffs(dcbe->or) - 1;
nv_encoder->last_dpms = DRM_MODE_DPMS_OFF;
encoder = to_drm_encoder(nv_encoder);
encoder->possible_crtcs = dcbe->heads;
encoder->possible_clones = 0;
drm_encoder_init(dev, encoder, &nvd0_sor_func, DRM_MODE_ENCODER_TMDS);
drm_encoder_helper_add(encoder, &nvd0_sor_hfunc);
drm_mode_connector_attach_encoder(connector, encoder);
return 0;
}
/******************************************************************************
* IRQ
*****************************************************************************/
static struct dcb_entry *
lookup_dcb(struct drm_device *dev, int id, u32 mc)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
int type, or, i, link = -1;
if (id < 4) {
type = OUTPUT_ANALOG;
or = id;
} else {
switch (mc & 0x00000f00) {
case 0x00000000: link = 0; type = OUTPUT_LVDS; break;
case 0x00000100: link = 0; type = OUTPUT_TMDS; break;
case 0x00000200: link = 1; type = OUTPUT_TMDS; break;
case 0x00000500: link = 0; type = OUTPUT_TMDS; break;
case 0x00000800: link = 0; type = OUTPUT_DP; break;
case 0x00000900: link = 1; type = OUTPUT_DP; break;
default:
NV_ERROR(dev, "PDISP: unknown SOR mc 0x%08x\n", mc);
return NULL;
}
or = id - 4;
}
for (i = 0; i < dev_priv->vbios.dcb.entries; i++) {
struct dcb_entry *dcb = &dev_priv->vbios.dcb.entry[i];
if (dcb->type == type && (dcb->or & (1 << or)) &&
(link < 0 || link == !(dcb->sorconf.link & 1)))
return dcb;
}
NV_ERROR(dev, "PDISP: DCB for %d/0x%08x not found\n", id, mc);
return NULL;
}
static void
nvd0_display_unk1_handler(struct drm_device *dev, u32 crtc, u32 mask)
{
struct dcb_entry *dcb;
int i;
for (i = 0; mask && i < 8; i++) {
u32 mcc = nv_rd32(dev, 0x640180 + (i * 0x20));
if (!(mcc & (1 << crtc)))
continue;
dcb = lookup_dcb(dev, i, mcc);
if (!dcb)
continue;
nouveau_bios_run_display_table(dev, 0x0000, -1, dcb, crtc);
}
nv_wr32(dev, 0x6101d4, 0x00000000);
nv_wr32(dev, 0x6109d4, 0x00000000);
nv_wr32(dev, 0x6101d0, 0x80000000);
}
static void
nvd0_display_unk2_handler(struct drm_device *dev, u32 crtc, u32 mask)
{
struct dcb_entry *dcb;
u32 or, tmp, pclk;
int i;
for (i = 0; mask && i < 8; i++) {
u32 mcc = nv_rd32(dev, 0x640180 + (i * 0x20));
if (!(mcc & (1 << crtc)))
continue;
dcb = lookup_dcb(dev, i, mcc);
if (!dcb)
continue;
nouveau_bios_run_display_table(dev, 0x0000, -2, dcb, crtc);
}
pclk = nv_rd32(dev, 0x660450 + (crtc * 0x300)) / 1000;
NV_DEBUG_KMS(dev, "PDISP: crtc %d pclk %d mask 0x%08x\n",
crtc, pclk, mask);
if (pclk && (mask & 0x00010000)) {
nv50_crtc_set_clock(dev, crtc, pclk);
}
for (i = 0; mask && i < 8; i++) {
u32 mcp = nv_rd32(dev, 0x660180 + (i * 0x20));
u32 cfg = nv_rd32(dev, 0x660184 + (i * 0x20));
if (!(mcp & (1 << crtc)))
continue;
dcb = lookup_dcb(dev, i, mcp);
if (!dcb)
continue;
or = ffs(dcb->or) - 1;
nouveau_bios_run_display_table(dev, cfg, pclk, dcb, crtc);
nv_wr32(dev, 0x612200 + (crtc * 0x800), 0x00000000);
switch (dcb->type) {
case OUTPUT_ANALOG:
nv_wr32(dev, 0x612280 + (or * 0x800), 0x00000000);
break;
case OUTPUT_TMDS:
case OUTPUT_LVDS:
case OUTPUT_DP:
if (cfg & 0x00000100)
tmp = 0x00000101;
else
tmp = 0x00000000;
nv_mask(dev, 0x612300 + (or * 0x800), 0x00000707, tmp);
break;
default:
break;
}
break;
}
nv_wr32(dev, 0x6101d4, 0x00000000);
nv_wr32(dev, 0x6109d4, 0x00000000);
nv_wr32(dev, 0x6101d0, 0x80000000);
}
static void
nvd0_display_unk4_handler(struct drm_device *dev, u32 crtc, u32 mask)
{
struct dcb_entry *dcb;
int pclk, i;
pclk = nv_rd32(dev, 0x660450 + (crtc * 0x300)) / 1000;
for (i = 0; mask && i < 8; i++) {
u32 mcp = nv_rd32(dev, 0x660180 + (i * 0x20));
u32 cfg = nv_rd32(dev, 0x660184 + (i * 0x20));
if (!(mcp & (1 << crtc)))
continue;
dcb = lookup_dcb(dev, i, mcp);
if (!dcb)
continue;
nouveau_bios_run_display_table(dev, cfg, -pclk, dcb, crtc);
}
nv_wr32(dev, 0x6101d4, 0x00000000);
nv_wr32(dev, 0x6109d4, 0x00000000);
nv_wr32(dev, 0x6101d0, 0x80000000);
}
static void
nvd0_display_bh(unsigned long data)
{
struct drm_device *dev = (struct drm_device *)data;
struct nvd0_display *disp = nvd0_display(dev);
u32 mask = 0, crtc = ~0;
int i;
if (drm_debug & (DRM_UT_DRIVER | DRM_UT_KMS)) {
NV_INFO(dev, "PDISP: modeset req %d\n", disp->modeset);
NV_INFO(dev, " STAT: 0x%08x 0x%08x 0x%08x\n",
nv_rd32(dev, 0x6101d0),
nv_rd32(dev, 0x6101d4), nv_rd32(dev, 0x6109d4));
for (i = 0; i < 8; i++) {
NV_INFO(dev, " %s%d: 0x%08x 0x%08x\n",
i < 4 ? "DAC" : "SOR", i,
nv_rd32(dev, 0x640180 + (i * 0x20)),
nv_rd32(dev, 0x660180 + (i * 0x20)));
}
}
while (!mask && ++crtc < dev->mode_config.num_crtc)
mask = nv_rd32(dev, 0x6101d4 + (crtc * 0x800));
if (disp->modeset & 0x00000001)
nvd0_display_unk1_handler(dev, crtc, mask);
if (disp->modeset & 0x00000002)
nvd0_display_unk2_handler(dev, crtc, mask);
if (disp->modeset & 0x00000004)
nvd0_display_unk4_handler(dev, crtc, mask);
}
static void
nvd0_display_intr(struct drm_device *dev)
{
struct nvd0_display *disp = nvd0_display(dev);
u32 intr = nv_rd32(dev, 0x610088);
int i;
if (intr & 0x00000001) {
u32 stat = nv_rd32(dev, 0x61008c);
nv_wr32(dev, 0x61008c, stat);
intr &= ~0x00000001;
}
if (intr & 0x00000002) {
u32 stat = nv_rd32(dev, 0x61009c);
int chid = ffs(stat) - 1;
if (chid >= 0) {
u32 mthd = nv_rd32(dev, 0x6101f0 + (chid * 12));
u32 data = nv_rd32(dev, 0x6101f4 + (chid * 12));
u32 unkn = nv_rd32(dev, 0x6101f8 + (chid * 12));
NV_INFO(dev, "EvoCh: chid %d mthd 0x%04x data 0x%08x "
"0x%08x 0x%08x\n",
chid, (mthd & 0x0000ffc), data, mthd, unkn);
nv_wr32(dev, 0x61009c, (1 << chid));
nv_wr32(dev, 0x6101f0 + (chid * 12), 0x90000000);
}
intr &= ~0x00000002;
}
if (intr & 0x00100000) {
u32 stat = nv_rd32(dev, 0x6100ac);
if (stat & 0x00000007) {
disp->modeset = stat;
tasklet_schedule(&disp->tasklet);
nv_wr32(dev, 0x6100ac, (stat & 0x00000007));
stat &= ~0x00000007;
}
if (stat) {
NV_INFO(dev, "PDISP: unknown intr24 0x%08x\n", stat);
nv_wr32(dev, 0x6100ac, stat);
}
intr &= ~0x00100000;
}
for (i = 0; i < dev->mode_config.num_crtc; i++) {
u32 mask = 0x01000000 << i;
if (intr & mask) {
u32 stat = nv_rd32(dev, 0x6100bc + (i * 0x800));
nv_wr32(dev, 0x6100bc + (i * 0x800), stat);
intr &= ~mask;
}
}
if (intr)
NV_INFO(dev, "PDISP: unknown intr 0x%08x\n", intr);
}
/******************************************************************************
* Init
*****************************************************************************/
void
nvd0_display_fini(struct drm_device *dev)
{
int i;
/* fini cursors + overlays + flips */
for (i = 1; i >= 0; i--) {
evo_fini_pio(dev, EVO_CURS(i));
evo_fini_pio(dev, EVO_OIMM(i));
evo_fini_dma(dev, EVO_OVLY(i));
evo_fini_dma(dev, EVO_FLIP(i));
}
/* fini master */
evo_fini_dma(dev, EVO_MASTER);
}
int
nvd0_display_init(struct drm_device *dev)
{
struct nvd0_display *disp = nvd0_display(dev);
int ret, i;
u32 *push;
if (nv_rd32(dev, 0x6100ac) & 0x00000100) {
nv_wr32(dev, 0x6100ac, 0x00000100);
nv_mask(dev, 0x6194e8, 0x00000001, 0x00000000);
if (!nv_wait(dev, 0x6194e8, 0x00000002, 0x00000000)) {
NV_ERROR(dev, "PDISP: 0x6194e8 0x%08x\n",
nv_rd32(dev, 0x6194e8));
return -EBUSY;
}
}
/* nfi what these are exactly, i do know that SOR_MODE_CTRL won't
* work at all unless you do the SOR part below.
*/
for (i = 0; i < 3; i++) {
u32 dac = nv_rd32(dev, 0x61a000 + (i * 0x800));
nv_wr32(dev, 0x6101c0 + (i * 0x800), dac);
}
for (i = 0; i < 4; i++) {
u32 sor = nv_rd32(dev, 0x61c000 + (i * 0x800));
nv_wr32(dev, 0x6301c4 + (i * 0x800), sor);
}
for (i = 0; i < dev->mode_config.num_crtc; i++) {
u32 crtc0 = nv_rd32(dev, 0x616104 + (i * 0x800));
u32 crtc1 = nv_rd32(dev, 0x616108 + (i * 0x800));
u32 crtc2 = nv_rd32(dev, 0x61610c + (i * 0x800));
nv_wr32(dev, 0x6101b4 + (i * 0x800), crtc0);
nv_wr32(dev, 0x6101b8 + (i * 0x800), crtc1);
nv_wr32(dev, 0x6101bc + (i * 0x800), crtc2);
}
/* point at our hash table / objects, enable interrupts */
nv_wr32(dev, 0x610010, (disp->mem->vinst >> 8) | 9);
nv_mask(dev, 0x6100b0, 0x00000307, 0x00000307);
/* init master */
ret = evo_init_dma(dev, EVO_MASTER);
if (ret)
goto error;
/* init flips + overlays + cursors */
for (i = 0; i < dev->mode_config.num_crtc; i++) {
if ((ret = evo_init_dma(dev, EVO_FLIP(i))) ||
(ret = evo_init_dma(dev, EVO_OVLY(i))) ||
(ret = evo_init_pio(dev, EVO_OIMM(i))) ||
(ret = evo_init_pio(dev, EVO_CURS(i))))
goto error;
}
push = evo_wait(dev, EVO_MASTER, 32);
if (!push) {
ret = -EBUSY;
goto error;
}
evo_mthd(push, 0x0088, 1);
evo_data(push, NvEvoSync);
evo_mthd(push, 0x0084, 1);
evo_data(push, 0x00000000);
evo_mthd(push, 0x0084, 1);
evo_data(push, 0x80000000);
evo_mthd(push, 0x008c, 1);
evo_data(push, 0x00000000);
evo_kick(push, dev, EVO_MASTER);
error:
if (ret)
nvd0_display_fini(dev);
return ret;
}
void
nvd0_display_destroy(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nvd0_display *disp = nvd0_display(dev);
struct pci_dev *pdev = dev->pdev;
int i;
for (i = 0; i < EVO_DMA_NR; i++) {
struct evo *evo = &disp->evo[i];
pci_free_consistent(pdev, PAGE_SIZE, evo->ptr, evo->handle);
}
nouveau_gpuobj_ref(NULL, &disp->mem);
nouveau_bo_unmap(disp->sync);
nouveau_bo_ref(NULL, &disp->sync);
nouveau_irq_unregister(dev, 26);
dev_priv->engine.display.priv = NULL;
kfree(disp);
}
int
nvd0_display_create(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_instmem_engine *pinstmem = &dev_priv->engine.instmem;
struct dcb_table *dcb = &dev_priv->vbios.dcb;
struct drm_connector *connector, *tmp;
struct pci_dev *pdev = dev->pdev;
struct nvd0_display *disp;
struct dcb_entry *dcbe;
int crtcs, ret, i;
disp = kzalloc(sizeof(*disp), GFP_KERNEL);
if (!disp)
return -ENOMEM;
dev_priv->engine.display.priv = disp;
/* create crtc objects to represent the hw heads */
crtcs = nv_rd32(dev, 0x022448);
for (i = 0; i < crtcs; i++) {
ret = nvd0_crtc_create(dev, i);
if (ret)
goto out;
}
/* create encoder/connector objects based on VBIOS DCB table */
for (i = 0, dcbe = &dcb->entry[0]; i < dcb->entries; i++, dcbe++) {
connector = nouveau_connector_create(dev, dcbe->connector);
if (IS_ERR(connector))
continue;
if (dcbe->location != DCB_LOC_ON_CHIP) {
NV_WARN(dev, "skipping off-chip encoder %d/%d\n",
dcbe->type, ffs(dcbe->or) - 1);
continue;
}
switch (dcbe->type) {
case OUTPUT_TMDS:
case OUTPUT_LVDS:
case OUTPUT_DP:
nvd0_sor_create(connector, dcbe);
break;
case OUTPUT_ANALOG:
nvd0_dac_create(connector, dcbe);
break;
default:
NV_WARN(dev, "skipping unsupported encoder %d/%d\n",
dcbe->type, ffs(dcbe->or) - 1);
continue;
}
}
/* cull any connectors we created that don't have an encoder */
list_for_each_entry_safe(connector, tmp, &dev->mode_config.connector_list, head) {
if (connector->encoder_ids[0])
continue;
NV_WARN(dev, "%s has no encoders, removing\n",
drm_get_connector_name(connector));
connector->funcs->destroy(connector);
}
/* setup interrupt handling */
tasklet_init(&disp->tasklet, nvd0_display_bh, (unsigned long)dev);
nouveau_irq_register(dev, 26, nvd0_display_intr);
/* small shared memory area we use for notifiers and semaphores */
ret = nouveau_bo_new(dev, 4096, 0x1000, TTM_PL_FLAG_VRAM,
0, 0x0000, NULL, &disp->sync);
if (!ret) {
ret = nouveau_bo_pin(disp->sync, TTM_PL_FLAG_VRAM);
if (!ret)
ret = nouveau_bo_map(disp->sync);
if (ret)
nouveau_bo_ref(NULL, &disp->sync);
}
if (ret)
goto out;
/* hash table and dma objects for the memory areas we care about */
ret = nouveau_gpuobj_new(dev, NULL, 0x4000, 0x10000,
NVOBJ_FLAG_ZERO_ALLOC, &disp->mem);
if (ret)
goto out;
/* create evo dma channels */
for (i = 0; i < EVO_DMA_NR; i++) {
struct evo *evo = &disp->evo[i];
u64 offset = disp->sync->bo.offset;
u32 dmao = 0x1000 + (i * 0x100);
u32 hash = 0x0000 + (i * 0x040);
evo->idx = i;
evo->sem.offset = EVO_SYNC(evo->idx, 0x00);
evo->ptr = pci_alloc_consistent(pdev, PAGE_SIZE, &evo->handle);
if (!evo->ptr) {
ret = -ENOMEM;
goto out;
}
nv_wo32(disp->mem, dmao + 0x00, 0x00000049);
nv_wo32(disp->mem, dmao + 0x04, (offset + 0x0000) >> 8);
nv_wo32(disp->mem, dmao + 0x08, (offset + 0x0fff) >> 8);
nv_wo32(disp->mem, dmao + 0x0c, 0x00000000);
nv_wo32(disp->mem, dmao + 0x10, 0x00000000);
nv_wo32(disp->mem, dmao + 0x14, 0x00000000);
nv_wo32(disp->mem, hash + 0x00, NvEvoSync);
nv_wo32(disp->mem, hash + 0x04, 0x00000001 | (i << 27) |
((dmao + 0x00) << 9));
nv_wo32(disp->mem, dmao + 0x20, 0x00000049);
nv_wo32(disp->mem, dmao + 0x24, 0x00000000);
nv_wo32(disp->mem, dmao + 0x28, (dev_priv->vram_size - 1) >> 8);
nv_wo32(disp->mem, dmao + 0x2c, 0x00000000);
nv_wo32(disp->mem, dmao + 0x30, 0x00000000);
nv_wo32(disp->mem, dmao + 0x34, 0x00000000);
nv_wo32(disp->mem, hash + 0x08, NvEvoVRAM);
nv_wo32(disp->mem, hash + 0x0c, 0x00000001 | (i << 27) |
((dmao + 0x20) << 9));
nv_wo32(disp->mem, dmao + 0x40, 0x00000009);
nv_wo32(disp->mem, dmao + 0x44, 0x00000000);
nv_wo32(disp->mem, dmao + 0x48, (dev_priv->vram_size - 1) >> 8);
nv_wo32(disp->mem, dmao + 0x4c, 0x00000000);
nv_wo32(disp->mem, dmao + 0x50, 0x00000000);
nv_wo32(disp->mem, dmao + 0x54, 0x00000000);
nv_wo32(disp->mem, hash + 0x10, NvEvoVRAM_LP);
nv_wo32(disp->mem, hash + 0x14, 0x00000001 | (i << 27) |
((dmao + 0x40) << 9));
nv_wo32(disp->mem, dmao + 0x60, 0x0fe00009);
nv_wo32(disp->mem, dmao + 0x64, 0x00000000);
nv_wo32(disp->mem, dmao + 0x68, (dev_priv->vram_size - 1) >> 8);
nv_wo32(disp->mem, dmao + 0x6c, 0x00000000);
nv_wo32(disp->mem, dmao + 0x70, 0x00000000);
nv_wo32(disp->mem, dmao + 0x74, 0x00000000);
nv_wo32(disp->mem, hash + 0x18, NvEvoFB32);
nv_wo32(disp->mem, hash + 0x1c, 0x00000001 | (i << 27) |
((dmao + 0x60) << 9));
}
pinstmem->flush(dev);
out:
if (ret)
nvd0_display_destroy(dev);
return ret;
}
| gpl-2.0 |
Lineson/linux-ons45 | drivers/net/wireless/ath/ath9k/link.c | 566 | 14271 | /*
* Copyright (c) 2012 Qualcomm Atheros, Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "ath9k.h"
/*
* TX polling - checks if the TX engine is stuck somewhere
* and issues a chip reset if so.
*/
void ath_tx_complete_poll_work(struct work_struct *work)
{
struct ath_softc *sc = container_of(work, struct ath_softc,
tx_complete_work.work);
struct ath_txq *txq;
int i;
bool needreset = false;
if (sc->tx99_state) {
ath_dbg(ath9k_hw_common(sc->sc_ah), RESET,
"skip tx hung detection on tx99\n");
return;
}
for (i = 0; i < IEEE80211_NUM_ACS; i++) {
txq = sc->tx.txq_map[i];
ath_txq_lock(sc, txq);
if (txq->axq_depth) {
if (txq->axq_tx_inprogress) {
needreset = true;
ath_txq_unlock(sc, txq);
break;
} else {
txq->axq_tx_inprogress = true;
}
}
ath_txq_unlock(sc, txq);
}
if (needreset) {
ath_dbg(ath9k_hw_common(sc->sc_ah), RESET,
"tx hung, resetting the chip\n");
ath9k_queue_reset(sc, RESET_TYPE_TX_HANG);
return;
}
ieee80211_queue_delayed_work(sc->hw, &sc->tx_complete_work,
msecs_to_jiffies(ATH_TX_COMPLETE_POLL_INT));
}
/*
* Checks if the BB/MAC is hung.
*/
bool ath_hw_check(struct ath_softc *sc)
{
struct ath_common *common = ath9k_hw_common(sc->sc_ah);
enum ath_reset_type type;
bool is_alive;
ath9k_ps_wakeup(sc);
is_alive = ath9k_hw_check_alive(sc->sc_ah);
if (!is_alive) {
ath_dbg(common, RESET,
"HW hang detected, schedule chip reset\n");
type = RESET_TYPE_MAC_HANG;
ath9k_queue_reset(sc, type);
}
ath9k_ps_restore(sc);
return is_alive;
}
/*
* PLL-WAR for AR9485/AR9340
*/
static bool ath_hw_pll_rx_hang_check(struct ath_softc *sc, u32 pll_sqsum)
{
static int count;
struct ath_common *common = ath9k_hw_common(sc->sc_ah);
if (pll_sqsum >= 0x40000) {
count++;
if (count == 3) {
ath_dbg(common, RESET, "PLL WAR, resetting the chip\n");
ath9k_queue_reset(sc, RESET_TYPE_PLL_HANG);
count = 0;
return true;
}
} else {
count = 0;
}
return false;
}
void ath_hw_pll_work(struct work_struct *work)
{
u32 pll_sqsum;
struct ath_softc *sc = container_of(work, struct ath_softc,
hw_pll_work.work);
struct ath_common *common = ath9k_hw_common(sc->sc_ah);
/*
* ensure that the PLL WAR is executed only
* after the STA is associated (or) if the
* beaconing had started in interfaces that
* uses beacons.
*/
if (!test_bit(ATH_OP_BEACONS, &common->op_flags))
return;
if (sc->tx99_state)
return;
ath9k_ps_wakeup(sc);
pll_sqsum = ar9003_get_pll_sqsum_dvc(sc->sc_ah);
ath9k_ps_restore(sc);
if (ath_hw_pll_rx_hang_check(sc, pll_sqsum))
return;
ieee80211_queue_delayed_work(sc->hw, &sc->hw_pll_work,
msecs_to_jiffies(ATH_PLL_WORK_INTERVAL));
}
/*
* PA Pre-distortion.
*/
static void ath_paprd_activate(struct ath_softc *sc)
{
struct ath_hw *ah = sc->sc_ah;
struct ath_common *common = ath9k_hw_common(ah);
struct ath9k_hw_cal_data *caldata = ah->caldata;
int chain;
if (!caldata || !test_bit(PAPRD_DONE, &caldata->cal_flags)) {
ath_dbg(common, CALIBRATE, "Failed to activate PAPRD\n");
return;
}
ar9003_paprd_enable(ah, false);
for (chain = 0; chain < AR9300_MAX_CHAINS; chain++) {
if (!(ah->txchainmask & BIT(chain)))
continue;
ar9003_paprd_populate_single_table(ah, caldata, chain);
}
ath_dbg(common, CALIBRATE, "Activating PAPRD\n");
ar9003_paprd_enable(ah, true);
}
static bool ath_paprd_send_frame(struct ath_softc *sc, struct sk_buff *skb, int chain)
{
struct ieee80211_hw *hw = sc->hw;
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
struct ath_hw *ah = sc->sc_ah;
struct ath_common *common = ath9k_hw_common(ah);
struct ath_tx_control txctl;
int time_left;
memset(&txctl, 0, sizeof(txctl));
txctl.txq = sc->tx.txq_map[IEEE80211_AC_BE];
memset(tx_info, 0, sizeof(*tx_info));
tx_info->band = sc->cur_chandef.chan->band;
tx_info->flags |= IEEE80211_TX_CTL_NO_ACK;
tx_info->control.rates[0].idx = 0;
tx_info->control.rates[0].count = 1;
tx_info->control.rates[0].flags = IEEE80211_TX_RC_MCS;
tx_info->control.rates[1].idx = -1;
init_completion(&sc->paprd_complete);
txctl.paprd = BIT(chain);
if (ath_tx_start(hw, skb, &txctl) != 0) {
ath_dbg(common, CALIBRATE, "PAPRD TX failed\n");
dev_kfree_skb_any(skb);
return false;
}
time_left = wait_for_completion_timeout(&sc->paprd_complete,
msecs_to_jiffies(ATH_PAPRD_TIMEOUT));
if (!time_left)
ath_dbg(common, CALIBRATE,
"Timeout waiting for paprd training on TX chain %d\n",
chain);
return !!time_left;
}
void ath_paprd_calibrate(struct work_struct *work)
{
struct ath_softc *sc = container_of(work, struct ath_softc, paprd_work);
struct ieee80211_hw *hw = sc->hw;
struct ath_hw *ah = sc->sc_ah;
struct ieee80211_hdr *hdr;
struct sk_buff *skb = NULL;
struct ath9k_hw_cal_data *caldata = ah->caldata;
struct ath_common *common = ath9k_hw_common(ah);
int ftype;
int chain_ok = 0;
int chain;
int len = 1800;
int ret;
if (!caldata ||
!test_bit(PAPRD_PACKET_SENT, &caldata->cal_flags) ||
test_bit(PAPRD_DONE, &caldata->cal_flags)) {
ath_dbg(common, CALIBRATE, "Skipping PAPRD calibration\n");
return;
}
ath9k_ps_wakeup(sc);
if (ar9003_paprd_init_table(ah) < 0)
goto fail_paprd;
skb = alloc_skb(len, GFP_KERNEL);
if (!skb)
goto fail_paprd;
skb_put(skb, len);
memset(skb->data, 0, len);
hdr = (struct ieee80211_hdr *)skb->data;
ftype = IEEE80211_FTYPE_DATA | IEEE80211_STYPE_NULLFUNC;
hdr->frame_control = cpu_to_le16(ftype);
hdr->duration_id = cpu_to_le16(10);
memcpy(hdr->addr1, hw->wiphy->perm_addr, ETH_ALEN);
memcpy(hdr->addr2, hw->wiphy->perm_addr, ETH_ALEN);
memcpy(hdr->addr3, hw->wiphy->perm_addr, ETH_ALEN);
for (chain = 0; chain < AR9300_MAX_CHAINS; chain++) {
if (!(ah->txchainmask & BIT(chain)))
continue;
chain_ok = 0;
ar9003_paprd_setup_gain_table(ah, chain);
ath_dbg(common, CALIBRATE,
"Sending PAPRD training frame on chain %d\n", chain);
if (!ath_paprd_send_frame(sc, skb, chain))
goto fail_paprd;
if (!ar9003_paprd_is_done(ah)) {
ath_dbg(common, CALIBRATE,
"PAPRD not yet done on chain %d\n", chain);
break;
}
ret = ar9003_paprd_create_curve(ah, caldata, chain);
if (ret == -EINPROGRESS) {
ath_dbg(common, CALIBRATE,
"PAPRD curve on chain %d needs to be re-trained\n",
chain);
break;
} else if (ret) {
ath_dbg(common, CALIBRATE,
"PAPRD create curve failed on chain %d\n",
chain);
break;
}
chain_ok = 1;
}
kfree_skb(skb);
if (chain_ok) {
set_bit(PAPRD_DONE, &caldata->cal_flags);
ath_paprd_activate(sc);
}
fail_paprd:
ath9k_ps_restore(sc);
}
/*
* ANI performs periodic noise floor calibration
* that is used to adjust and optimize the chip performance. This
* takes environmental changes (location, temperature) into account.
* When the task is complete, it reschedules itself depending on the
* appropriate interval that was calculated.
*/
void ath_ani_calibrate(unsigned long data)
{
struct ath_softc *sc = (struct ath_softc *)data;
struct ath_hw *ah = sc->sc_ah;
struct ath_common *common = ath9k_hw_common(ah);
bool longcal = false;
bool shortcal = false;
bool aniflag = false;
unsigned int timestamp = jiffies_to_msecs(jiffies);
u32 cal_interval, short_cal_interval, long_cal_interval;
unsigned long flags;
if (ah->caldata && test_bit(NFCAL_INTF, &ah->caldata->cal_flags))
long_cal_interval = ATH_LONG_CALINTERVAL_INT;
else
long_cal_interval = ATH_LONG_CALINTERVAL;
short_cal_interval = (ah->opmode == NL80211_IFTYPE_AP) ?
ATH_AP_SHORT_CALINTERVAL : ATH_STA_SHORT_CALINTERVAL;
/* Only calibrate if awake */
if (sc->sc_ah->power_mode != ATH9K_PM_AWAKE) {
if (++ah->ani_skip_count >= ATH_ANI_MAX_SKIP_COUNT) {
spin_lock_irqsave(&sc->sc_pm_lock, flags);
sc->ps_flags |= PS_WAIT_FOR_ANI;
spin_unlock_irqrestore(&sc->sc_pm_lock, flags);
}
goto set_timer;
}
ah->ani_skip_count = 0;
spin_lock_irqsave(&sc->sc_pm_lock, flags);
sc->ps_flags &= ~PS_WAIT_FOR_ANI;
spin_unlock_irqrestore(&sc->sc_pm_lock, flags);
ath9k_ps_wakeup(sc);
/* Long calibration runs independently of short calibration. */
if ((timestamp - common->ani.longcal_timer) >= long_cal_interval) {
longcal = true;
common->ani.longcal_timer = timestamp;
}
/* Short calibration applies only while caldone is false */
if (!common->ani.caldone) {
if ((timestamp - common->ani.shortcal_timer) >= short_cal_interval) {
shortcal = true;
common->ani.shortcal_timer = timestamp;
common->ani.resetcal_timer = timestamp;
}
} else {
if ((timestamp - common->ani.resetcal_timer) >=
ATH_RESTART_CALINTERVAL) {
common->ani.caldone = ath9k_hw_reset_calvalid(ah);
if (common->ani.caldone)
common->ani.resetcal_timer = timestamp;
}
}
/* Verify whether we must check ANI */
if ((timestamp - common->ani.checkani_timer) >= ah->config.ani_poll_interval) {
aniflag = true;
common->ani.checkani_timer = timestamp;
}
/* Call ANI routine if necessary */
if (aniflag) {
spin_lock(&common->cc_lock);
ath9k_hw_ani_monitor(ah, ah->curchan);
ath_update_survey_stats(sc);
spin_unlock(&common->cc_lock);
}
/* Perform calibration if necessary */
if (longcal || shortcal) {
int ret = ath9k_hw_calibrate(ah, ah->curchan, ah->rxchainmask,
longcal);
if (ret < 0) {
common->ani.caldone = 0;
ath9k_queue_reset(sc, RESET_TYPE_CALIBRATION);
return;
}
common->ani.caldone = ret;
}
ath_dbg(common, ANI,
"Calibration @%lu finished: %s %s %s, caldone: %s\n",
jiffies,
longcal ? "long" : "", shortcal ? "short" : "",
aniflag ? "ani" : "", common->ani.caldone ? "true" : "false");
ath9k_ps_restore(sc);
set_timer:
/*
* Set timer interval based on previous results.
* The interval must be the shortest necessary to satisfy ANI,
* short calibration and long calibration.
*/
cal_interval = ATH_LONG_CALINTERVAL;
cal_interval = min(cal_interval, (u32)ah->config.ani_poll_interval);
if (!common->ani.caldone)
cal_interval = min(cal_interval, (u32)short_cal_interval);
mod_timer(&common->ani.timer, jiffies + msecs_to_jiffies(cal_interval));
if (ar9003_is_paprd_enabled(ah) && ah->caldata) {
if (!test_bit(PAPRD_DONE, &ah->caldata->cal_flags)) {
ieee80211_queue_work(sc->hw, &sc->paprd_work);
} else if (!ah->paprd_table_write_done) {
ath9k_ps_wakeup(sc);
ath_paprd_activate(sc);
ath9k_ps_restore(sc);
}
}
}
void ath_start_ani(struct ath_softc *sc)
{
struct ath_hw *ah = sc->sc_ah;
struct ath_common *common = ath9k_hw_common(ah);
unsigned long timestamp = jiffies_to_msecs(jiffies);
if (common->disable_ani ||
!test_bit(ATH_OP_ANI_RUN, &common->op_flags) ||
sc->cur_chan->offchannel)
return;
common->ani.longcal_timer = timestamp;
common->ani.shortcal_timer = timestamp;
common->ani.checkani_timer = timestamp;
ath_dbg(common, ANI, "Starting ANI\n");
mod_timer(&common->ani.timer,
jiffies + msecs_to_jiffies((u32)ah->config.ani_poll_interval));
}
void ath_stop_ani(struct ath_softc *sc)
{
struct ath_common *common = ath9k_hw_common(sc->sc_ah);
ath_dbg(common, ANI, "Stopping ANI\n");
del_timer_sync(&common->ani.timer);
}
void ath_check_ani(struct ath_softc *sc)
{
struct ath_hw *ah = sc->sc_ah;
struct ath_common *common = ath9k_hw_common(sc->sc_ah);
struct ath_beacon_config *cur_conf = &sc->cur_chan->beacon;
/*
* Check for the various conditions in which ANI has to
* be stopped.
*/
if (ah->opmode == NL80211_IFTYPE_ADHOC) {
if (!cur_conf->enable_beacon)
goto stop_ani;
} else if (ah->opmode == NL80211_IFTYPE_AP) {
if (!cur_conf->enable_beacon) {
/*
* Disable ANI only when there are no
* associated stations.
*/
if (!test_bit(ATH_OP_PRIM_STA_VIF, &common->op_flags))
goto stop_ani;
}
} else if (ah->opmode == NL80211_IFTYPE_STATION) {
if (!test_bit(ATH_OP_PRIM_STA_VIF, &common->op_flags))
goto stop_ani;
}
if (!test_bit(ATH_OP_ANI_RUN, &common->op_flags)) {
set_bit(ATH_OP_ANI_RUN, &common->op_flags);
ath_start_ani(sc);
}
return;
stop_ani:
clear_bit(ATH_OP_ANI_RUN, &common->op_flags);
ath_stop_ani(sc);
}
void ath_update_survey_nf(struct ath_softc *sc, int channel)
{
struct ath_hw *ah = sc->sc_ah;
struct ath9k_channel *chan = &ah->channels[channel];
struct survey_info *survey = &sc->survey[channel];
if (chan->noisefloor) {
survey->filled |= SURVEY_INFO_NOISE_DBM;
survey->noise = ath9k_hw_getchan_noise(ah, chan,
chan->noisefloor);
}
}
/*
* Updates the survey statistics and returns the busy time since last
* update in %, if the measurement duration was long enough for the
* result to be useful, -1 otherwise.
*/
int ath_update_survey_stats(struct ath_softc *sc)
{
struct ath_hw *ah = sc->sc_ah;
struct ath_common *common = ath9k_hw_common(ah);
int pos = ah->curchan - &ah->channels[0];
struct survey_info *survey = &sc->survey[pos];
struct ath_cycle_counters *cc = &common->cc_survey;
unsigned int div = common->clockrate * 1000;
int ret = 0;
if (!ah->curchan)
return -1;
if (ah->power_mode == ATH9K_PM_AWAKE)
ath_hw_cycle_counters_update(common);
if (cc->cycles > 0) {
survey->filled |= SURVEY_INFO_TIME |
SURVEY_INFO_TIME_BUSY |
SURVEY_INFO_TIME_RX |
SURVEY_INFO_TIME_TX;
survey->time += cc->cycles / div;
survey->time_busy += cc->rx_busy / div;
survey->time_rx += cc->rx_frame / div;
survey->time_tx += cc->tx_frame / div;
}
if (cc->cycles < div)
return -1;
if (cc->cycles > 0)
ret = cc->rx_busy * 100 / cc->cycles;
memset(cc, 0, sizeof(*cc));
ath_update_survey_nf(sc, pos);
return ret;
}
| gpl-2.0 |
ashwinr64/android_kernel_motorola_msm8952 | kernel/extable.c | 2102 | 3931 | /* Rewritten by Rusty Russell, on the backs of many others...
Copyright (C) 2001 Rusty Russell, 2002 Rusty Russell IBM.
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/ftrace.h>
#include <linux/memory.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/init.h>
#include <asm/sections.h>
#include <asm/uaccess.h>
/*
* mutex protecting text section modification (dynamic code patching).
* some users need to sleep (allocating memory...) while they hold this lock.
*
* NOT exported to modules - patching kernel text is a really delicate matter.
*/
DEFINE_MUTEX(text_mutex);
extern struct exception_table_entry __start___ex_table[];
extern struct exception_table_entry __stop___ex_table[];
/* Cleared by build time tools if the table is already sorted. */
u32 __initdata main_extable_sort_needed = 1;
/* Sort the kernel's built-in exception table */
void __init sort_main_extable(void)
{
if (main_extable_sort_needed) {
pr_notice("Sorting __ex_table...\n");
sort_extable(__start___ex_table, __stop___ex_table);
}
}
/* Given an address, look for it in the exception tables. */
const struct exception_table_entry *search_exception_tables(unsigned long addr)
{
const struct exception_table_entry *e;
e = search_extable(__start___ex_table, __stop___ex_table-1, addr);
if (!e)
e = search_module_extables(addr);
return e;
}
static inline int init_kernel_text(unsigned long addr)
{
if (addr >= (unsigned long)_sinittext &&
addr <= (unsigned long)_einittext)
return 1;
return 0;
}
int core_kernel_text(unsigned long addr)
{
if (addr >= (unsigned long)_stext &&
addr <= (unsigned long)_etext)
return 1;
if (system_state == SYSTEM_BOOTING &&
init_kernel_text(addr))
return 1;
return 0;
}
/**
* core_kernel_data - tell if addr points to kernel data
* @addr: address to test
*
* Returns true if @addr passed in is from the core kernel data
* section.
*
* Note: On some archs it may return true for core RODATA, and false
* for others. But will always be true for core RW data.
*/
int core_kernel_data(unsigned long addr)
{
if (addr >= (unsigned long)_sdata &&
addr < (unsigned long)_edata)
return 1;
return 0;
}
int __kernel_text_address(unsigned long addr)
{
if (core_kernel_text(addr))
return 1;
if (is_module_text_address(addr))
return 1;
/*
* There might be init symbols in saved stacktraces.
* Give those symbols a chance to be printed in
* backtraces (such as lockdep traces).
*
* Since we are after the module-symbols check, there's
* no danger of address overlap:
*/
if (init_kernel_text(addr))
return 1;
return 0;
}
int kernel_text_address(unsigned long addr)
{
if (core_kernel_text(addr))
return 1;
return is_module_text_address(addr);
}
/*
* On some architectures (PPC64, IA64) function pointers
* are actually only tokens to some data that then holds the
* real function address. As a result, to find if a function
* pointer is part of the kernel text, we need to do some
* special dereferencing first.
*/
int func_ptr_is_kernel_text(void *ptr)
{
unsigned long addr;
addr = (unsigned long) dereference_function_descriptor(ptr);
if (core_kernel_text(addr))
return 1;
return is_module_text_address(addr);
}
| gpl-2.0 |
denggww123/IMX6_DB_Kernel_3.10.53 | kernel/extable.c | 2102 | 3931 | /* Rewritten by Rusty Russell, on the backs of many others...
Copyright (C) 2001 Rusty Russell, 2002 Rusty Russell IBM.
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/ftrace.h>
#include <linux/memory.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/init.h>
#include <asm/sections.h>
#include <asm/uaccess.h>
/*
* mutex protecting text section modification (dynamic code patching).
* some users need to sleep (allocating memory...) while they hold this lock.
*
* NOT exported to modules - patching kernel text is a really delicate matter.
*/
DEFINE_MUTEX(text_mutex);
extern struct exception_table_entry __start___ex_table[];
extern struct exception_table_entry __stop___ex_table[];
/* Cleared by build time tools if the table is already sorted. */
u32 __initdata main_extable_sort_needed = 1;
/* Sort the kernel's built-in exception table */
void __init sort_main_extable(void)
{
if (main_extable_sort_needed) {
pr_notice("Sorting __ex_table...\n");
sort_extable(__start___ex_table, __stop___ex_table);
}
}
/* Given an address, look for it in the exception tables. */
const struct exception_table_entry *search_exception_tables(unsigned long addr)
{
const struct exception_table_entry *e;
e = search_extable(__start___ex_table, __stop___ex_table-1, addr);
if (!e)
e = search_module_extables(addr);
return e;
}
static inline int init_kernel_text(unsigned long addr)
{
if (addr >= (unsigned long)_sinittext &&
addr <= (unsigned long)_einittext)
return 1;
return 0;
}
int core_kernel_text(unsigned long addr)
{
if (addr >= (unsigned long)_stext &&
addr <= (unsigned long)_etext)
return 1;
if (system_state == SYSTEM_BOOTING &&
init_kernel_text(addr))
return 1;
return 0;
}
/**
* core_kernel_data - tell if addr points to kernel data
* @addr: address to test
*
* Returns true if @addr passed in is from the core kernel data
* section.
*
* Note: On some archs it may return true for core RODATA, and false
* for others. But will always be true for core RW data.
*/
int core_kernel_data(unsigned long addr)
{
if (addr >= (unsigned long)_sdata &&
addr < (unsigned long)_edata)
return 1;
return 0;
}
int __kernel_text_address(unsigned long addr)
{
if (core_kernel_text(addr))
return 1;
if (is_module_text_address(addr))
return 1;
/*
* There might be init symbols in saved stacktraces.
* Give those symbols a chance to be printed in
* backtraces (such as lockdep traces).
*
* Since we are after the module-symbols check, there's
* no danger of address overlap:
*/
if (init_kernel_text(addr))
return 1;
return 0;
}
int kernel_text_address(unsigned long addr)
{
if (core_kernel_text(addr))
return 1;
return is_module_text_address(addr);
}
/*
* On some architectures (PPC64, IA64) function pointers
* are actually only tokens to some data that then holds the
* real function address. As a result, to find if a function
* pointer is part of the kernel text, we need to do some
* special dereferencing first.
*/
int func_ptr_is_kernel_text(void *ptr)
{
unsigned long addr;
addr = (unsigned long) dereference_function_descriptor(ptr);
if (core_kernel_text(addr))
return 1;
return is_module_text_address(addr);
}
| gpl-2.0 |
duvall/android_kernel_samsung_smdk4412 | arch/arm/mach-nuc93x/nuc932.c | 3894 | 1255 | /*
* linux/arch/arm/mach-nuc93x/nuc932.c
*
* Copyright (c) 2009 Nuvoton corporation.
*
* Wan ZongShun <mcuos.com@gmail.com>
*
* NUC932 cpu support
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation;version 2 of the License.
*
*/
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <asm/mach/map.h>
#include <mach/hardware.h>
#include "cpu.h"
#include "clock.h"
/* define specific CPU platform device */
static struct platform_device *nuc932_dev[] __initdata = {
};
/* define specific CPU platform io map */
static struct map_desc nuc932evb_iodesc[] __initdata = {
};
/*Init NUC932 evb io*/
void __init nuc932_map_io(void)
{
nuc93x_map_io(nuc932evb_iodesc, ARRAY_SIZE(nuc932evb_iodesc));
}
/*Init NUC932 clock*/
void __init nuc932_init_clocks(void)
{
nuc93x_init_clocks();
}
/*enable NUC932 uart clock*/
void __init nuc932_init_uartclk(void)
{
struct clk *ck_uart = clk_get(NULL, "uart");
BUG_ON(IS_ERR(ck_uart));
clk_enable(ck_uart);
}
/*Init NUC932 board info*/
void __init nuc932_board_init(void)
{
nuc93x_board_init(nuc932_dev, ARRAY_SIZE(nuc932_dev));
}
| gpl-2.0 |
johnhubbard/kgdb-pci-kernel | arch/arm/mach-imx/iomux-imx31.c | 5174 | 4502 | /*
* Copyright 2004-2006 Freescale Semiconductor, Inc. All Rights Reserved.
* Copyright (C) 2008 by Sascha Hauer <kernel@pengutronix.de>
* Copyright (C) 2009 by Valentin Longchamp <valentin.longchamp@epfl.ch>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <linux/gpio.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <mach/hardware.h>
#include <mach/iomux-mx3.h>
/*
* IOMUX register (base) addresses
*/
#define IOMUX_BASE MX31_IO_ADDRESS(MX31_IOMUXC_BASE_ADDR)
#define IOMUXINT_OBS1 (IOMUX_BASE + 0x000)
#define IOMUXINT_OBS2 (IOMUX_BASE + 0x004)
#define IOMUXGPR (IOMUX_BASE + 0x008)
#define IOMUXSW_MUX_CTL (IOMUX_BASE + 0x00C)
#define IOMUXSW_PAD_CTL (IOMUX_BASE + 0x154)
static DEFINE_SPINLOCK(gpio_mux_lock);
#define IOMUX_REG_MASK (IOMUX_PADNUM_MASK & ~0x3)
unsigned long mxc_pin_alloc_map[NB_PORTS * 32 / BITS_PER_LONG];
/*
* set the mode for a IOMUX pin.
*/
int mxc_iomux_mode(unsigned int pin_mode)
{
u32 field, l, mode, ret = 0;
void __iomem *reg;
reg = IOMUXSW_MUX_CTL + (pin_mode & IOMUX_REG_MASK);
field = pin_mode & 0x3;
mode = (pin_mode & IOMUX_MODE_MASK) >> IOMUX_MODE_SHIFT;
spin_lock(&gpio_mux_lock);
l = __raw_readl(reg);
l &= ~(0xff << (field * 8));
l |= mode << (field * 8);
__raw_writel(l, reg);
spin_unlock(&gpio_mux_lock);
return ret;
}
EXPORT_SYMBOL(mxc_iomux_mode);
/*
* This function configures the pad value for a IOMUX pin.
*/
void mxc_iomux_set_pad(enum iomux_pins pin, u32 config)
{
u32 field, l;
void __iomem *reg;
pin &= IOMUX_PADNUM_MASK;
reg = IOMUXSW_PAD_CTL + (pin + 2) / 3 * 4;
field = (pin + 2) % 3;
pr_debug("%s: reg offset = 0x%x, field = %d\n",
__func__, (pin + 2) / 3, field);
spin_lock(&gpio_mux_lock);
l = __raw_readl(reg);
l &= ~(0x1ff << (field * 10));
l |= config << (field * 10);
__raw_writel(l, reg);
spin_unlock(&gpio_mux_lock);
}
EXPORT_SYMBOL(mxc_iomux_set_pad);
/*
* allocs a single pin:
* - reserves the pin so that it is not claimed by another driver
* - setups the iomux according to the configuration
*/
int mxc_iomux_alloc_pin(unsigned int pin, const char *label)
{
unsigned pad = pin & IOMUX_PADNUM_MASK;
if (pad >= (PIN_MAX + 1)) {
printk(KERN_ERR "mxc_iomux: Attempt to request nonexistant pin %u for \"%s\"\n",
pad, label ? label : "?");
return -EINVAL;
}
if (test_and_set_bit(pad, mxc_pin_alloc_map)) {
printk(KERN_ERR "mxc_iomux: pin %u already used. Allocation for \"%s\" failed\n",
pad, label ? label : "?");
return -EBUSY;
}
mxc_iomux_mode(pin);
return 0;
}
EXPORT_SYMBOL(mxc_iomux_alloc_pin);
int mxc_iomux_setup_multiple_pins(const unsigned int *pin_list, unsigned count,
const char *label)
{
const unsigned int *p = pin_list;
int i;
int ret = -EINVAL;
for (i = 0; i < count; i++) {
ret = mxc_iomux_alloc_pin(*p, label);
if (ret)
goto setup_error;
p++;
}
return 0;
setup_error:
mxc_iomux_release_multiple_pins(pin_list, i);
return ret;
}
EXPORT_SYMBOL(mxc_iomux_setup_multiple_pins);
void mxc_iomux_release_pin(unsigned int pin)
{
unsigned pad = pin & IOMUX_PADNUM_MASK;
if (pad < (PIN_MAX + 1))
clear_bit(pad, mxc_pin_alloc_map);
}
EXPORT_SYMBOL(mxc_iomux_release_pin);
void mxc_iomux_release_multiple_pins(const unsigned int *pin_list, int count)
{
const unsigned int *p = pin_list;
int i;
for (i = 0; i < count; i++) {
mxc_iomux_release_pin(*p);
p++;
}
}
EXPORT_SYMBOL(mxc_iomux_release_multiple_pins);
/*
* This function enables/disables the general purpose function for a particular
* signal.
*/
void mxc_iomux_set_gpr(enum iomux_gp_func gp, bool en)
{
u32 l;
spin_lock(&gpio_mux_lock);
l = __raw_readl(IOMUXGPR);
if (en)
l |= gp;
else
l &= ~gp;
__raw_writel(l, IOMUXGPR);
spin_unlock(&gpio_mux_lock);
}
EXPORT_SYMBOL(mxc_iomux_set_gpr);
| gpl-2.0 |
rex-xxx/mt6572_x201 | kernel/net/irda/ircomm/ircomm_tty_ioctl.c | 7990 | 11665 | /*********************************************************************
*
* Filename: ircomm_tty_ioctl.c
* Version:
* Description:
* Status: Experimental.
* Author: Dag Brattli <dagb@cs.uit.no>
* Created at: Thu Jun 10 14:39:09 1999
* Modified at: Wed Jan 5 14:45:43 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/init.h>
#include <linux/fs.h>
#include <linux/termios.h>
#include <linux/tty.h>
#include <linux/serial.h>
#include <asm/uaccess.h>
#include <net/irda/irda.h>
#include <net/irda/irmod.h>
#include <net/irda/ircomm_core.h>
#include <net/irda/ircomm_param.h>
#include <net/irda/ircomm_tty_attach.h>
#include <net/irda/ircomm_tty.h>
#define RELEVANT_IFLAG(iflag) (iflag & (IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK))
/*
* Function ircomm_tty_change_speed (driver)
*
* Change speed of the driver. If the remote device is a DCE, then this
* should make it change the speed of its serial port
*/
static void ircomm_tty_change_speed(struct ircomm_tty_cb *self)
{
unsigned cflag, cval;
int baud;
IRDA_DEBUG(2, "%s()\n", __func__ );
if (!self->tty || !self->tty->termios || !self->ircomm)
return;
cflag = self->tty->termios->c_cflag;
/* byte size and parity */
switch (cflag & CSIZE) {
case CS5: cval = IRCOMM_WSIZE_5; break;
case CS6: cval = IRCOMM_WSIZE_6; break;
case CS7: cval = IRCOMM_WSIZE_7; break;
case CS8: cval = IRCOMM_WSIZE_8; break;
default: cval = IRCOMM_WSIZE_5; break;
}
if (cflag & CSTOPB)
cval |= IRCOMM_2_STOP_BIT;
if (cflag & PARENB)
cval |= IRCOMM_PARITY_ENABLE;
if (!(cflag & PARODD))
cval |= IRCOMM_PARITY_EVEN;
/* Determine divisor based on baud rate */
baud = tty_get_baud_rate(self->tty);
if (!baud)
baud = 9600; /* B0 transition handled in rs_set_termios */
self->settings.data_rate = baud;
ircomm_param_request(self, IRCOMM_DATA_RATE, FALSE);
/* CTS flow control flag and modem status interrupts */
if (cflag & CRTSCTS) {
self->flags |= ASYNC_CTS_FLOW;
self->settings.flow_control |= IRCOMM_RTS_CTS_IN;
/* This got me. Bummer. Jean II */
if (self->service_type == IRCOMM_3_WIRE_RAW)
IRDA_WARNING("%s(), enabling RTS/CTS on link that doesn't support it (3-wire-raw)\n", __func__);
} else {
self->flags &= ~ASYNC_CTS_FLOW;
self->settings.flow_control &= ~IRCOMM_RTS_CTS_IN;
}
if (cflag & CLOCAL)
self->flags &= ~ASYNC_CHECK_CD;
else
self->flags |= ASYNC_CHECK_CD;
#if 0
/*
* Set up parity check flag
*/
if (I_INPCK(self->tty))
driver->read_status_mask |= LSR_FE | LSR_PE;
if (I_BRKINT(driver->tty) || I_PARMRK(driver->tty))
driver->read_status_mask |= LSR_BI;
/*
* Characters to ignore
*/
driver->ignore_status_mask = 0;
if (I_IGNPAR(driver->tty))
driver->ignore_status_mask |= LSR_PE | LSR_FE;
if (I_IGNBRK(self->tty)) {
self->ignore_status_mask |= LSR_BI;
/*
* If we're ignore parity and break indicators, ignore
* overruns too. (For real raw support).
*/
if (I_IGNPAR(self->tty))
self->ignore_status_mask |= LSR_OE;
}
#endif
self->settings.data_format = cval;
ircomm_param_request(self, IRCOMM_DATA_FORMAT, FALSE);
ircomm_param_request(self, IRCOMM_FLOW_CONTROL, TRUE);
}
/*
* Function ircomm_tty_set_termios (tty, old_termios)
*
* This routine allows the tty driver to be notified when device's
* termios settings have changed. Note that a well-designed tty driver
* should be prepared to accept the case where old == NULL, and try to
* do something rational.
*/
void ircomm_tty_set_termios(struct tty_struct *tty,
struct ktermios *old_termios)
{
struct ircomm_tty_cb *self = (struct ircomm_tty_cb *) tty->driver_data;
unsigned int cflag = tty->termios->c_cflag;
IRDA_DEBUG(2, "%s()\n", __func__ );
if ((cflag == old_termios->c_cflag) &&
(RELEVANT_IFLAG(tty->termios->c_iflag) ==
RELEVANT_IFLAG(old_termios->c_iflag)))
{
return;
}
ircomm_tty_change_speed(self);
/* Handle transition to B0 status */
if ((old_termios->c_cflag & CBAUD) &&
!(cflag & CBAUD)) {
self->settings.dte &= ~(IRCOMM_DTR|IRCOMM_RTS);
ircomm_param_request(self, IRCOMM_DTE, TRUE);
}
/* Handle transition away from B0 status */
if (!(old_termios->c_cflag & CBAUD) &&
(cflag & CBAUD)) {
self->settings.dte |= IRCOMM_DTR;
if (!(tty->termios->c_cflag & CRTSCTS) ||
!test_bit(TTY_THROTTLED, &tty->flags)) {
self->settings.dte |= IRCOMM_RTS;
}
ircomm_param_request(self, IRCOMM_DTE, TRUE);
}
/* Handle turning off CRTSCTS */
if ((old_termios->c_cflag & CRTSCTS) &&
!(tty->termios->c_cflag & CRTSCTS))
{
tty->hw_stopped = 0;
ircomm_tty_start(tty);
}
}
/*
* Function ircomm_tty_tiocmget (tty)
*
*
*
*/
int ircomm_tty_tiocmget(struct tty_struct *tty)
{
struct ircomm_tty_cb *self = (struct ircomm_tty_cb *) tty->driver_data;
unsigned int result;
IRDA_DEBUG(2, "%s()\n", __func__ );
if (tty->flags & (1 << TTY_IO_ERROR))
return -EIO;
result = ((self->settings.dte & IRCOMM_RTS) ? TIOCM_RTS : 0)
| ((self->settings.dte & IRCOMM_DTR) ? TIOCM_DTR : 0)
| ((self->settings.dce & IRCOMM_CD) ? TIOCM_CAR : 0)
| ((self->settings.dce & IRCOMM_RI) ? TIOCM_RNG : 0)
| ((self->settings.dce & IRCOMM_DSR) ? TIOCM_DSR : 0)
| ((self->settings.dce & IRCOMM_CTS) ? TIOCM_CTS : 0);
return result;
}
/*
* Function ircomm_tty_tiocmset (tty, set, clear)
*
*
*
*/
int ircomm_tty_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear)
{
struct ircomm_tty_cb *self = (struct ircomm_tty_cb *) tty->driver_data;
IRDA_DEBUG(2, "%s()\n", __func__ );
if (tty->flags & (1 << TTY_IO_ERROR))
return -EIO;
IRDA_ASSERT(self != NULL, return -1;);
IRDA_ASSERT(self->magic == IRCOMM_TTY_MAGIC, return -1;);
if (set & TIOCM_RTS)
self->settings.dte |= IRCOMM_RTS;
if (set & TIOCM_DTR)
self->settings.dte |= IRCOMM_DTR;
if (clear & TIOCM_RTS)
self->settings.dte &= ~IRCOMM_RTS;
if (clear & TIOCM_DTR)
self->settings.dte &= ~IRCOMM_DTR;
if ((set|clear) & TIOCM_RTS)
self->settings.dte |= IRCOMM_DELTA_RTS;
if ((set|clear) & TIOCM_DTR)
self->settings.dte |= IRCOMM_DELTA_DTR;
ircomm_param_request(self, IRCOMM_DTE, TRUE);
return 0;
}
/*
* Function get_serial_info (driver, retinfo)
*
*
*
*/
static int ircomm_tty_get_serial_info(struct ircomm_tty_cb *self,
struct serial_struct __user *retinfo)
{
struct serial_struct info;
if (!retinfo)
return -EFAULT;
IRDA_DEBUG(2, "%s()\n", __func__ );
memset(&info, 0, sizeof(info));
info.line = self->line;
info.flags = self->flags;
info.baud_base = self->settings.data_rate;
info.close_delay = self->close_delay;
info.closing_wait = self->closing_wait;
/* For compatibility */
info.type = PORT_16550A;
info.port = 0;
info.irq = 0;
info.xmit_fifo_size = 0;
info.hub6 = 0;
info.custom_divisor = 0;
if (copy_to_user(retinfo, &info, sizeof(*retinfo)))
return -EFAULT;
return 0;
}
/*
* Function set_serial_info (driver, new_info)
*
*
*
*/
static int ircomm_tty_set_serial_info(struct ircomm_tty_cb *self,
struct serial_struct __user *new_info)
{
#if 0
struct serial_struct new_serial;
struct ircomm_tty_cb old_state, *state;
IRDA_DEBUG(0, "%s()\n", __func__ );
if (copy_from_user(&new_serial,new_info,sizeof(new_serial)))
return -EFAULT;
state = self
old_state = *self;
if (!capable(CAP_SYS_ADMIN)) {
if ((new_serial.baud_base != state->settings.data_rate) ||
(new_serial.close_delay != state->close_delay) ||
((new_serial.flags & ~ASYNC_USR_MASK) !=
(self->flags & ~ASYNC_USR_MASK)))
return -EPERM;
state->flags = ((state->flags & ~ASYNC_USR_MASK) |
(new_serial.flags & ASYNC_USR_MASK));
self->flags = ((self->flags & ~ASYNC_USR_MASK) |
(new_serial.flags & ASYNC_USR_MASK));
/* self->custom_divisor = new_serial.custom_divisor; */
goto check_and_exit;
}
/*
* OK, past this point, all the error checking has been done.
* At this point, we start making changes.....
*/
if (self->settings.data_rate != new_serial.baud_base) {
self->settings.data_rate = new_serial.baud_base;
ircomm_param_request(self, IRCOMM_DATA_RATE, TRUE);
}
self->close_delay = new_serial.close_delay * HZ/100;
self->closing_wait = new_serial.closing_wait * HZ/100;
/* self->custom_divisor = new_serial.custom_divisor; */
self->flags = ((self->flags & ~ASYNC_FLAGS) |
(new_serial.flags & ASYNC_FLAGS));
self->tty->low_latency = (self->flags & ASYNC_LOW_LATENCY) ? 1 : 0;
check_and_exit:
if (self->flags & ASYNC_INITIALIZED) {
if (((old_state.flags & ASYNC_SPD_MASK) !=
(self->flags & ASYNC_SPD_MASK)) ||
(old_driver.custom_divisor != driver->custom_divisor)) {
if ((driver->flags & ASYNC_SPD_MASK) == ASYNC_SPD_HI)
driver->tty->alt_speed = 57600;
if ((driver->flags & ASYNC_SPD_MASK) == ASYNC_SPD_VHI)
driver->tty->alt_speed = 115200;
if ((driver->flags & ASYNC_SPD_MASK) == ASYNC_SPD_SHI)
driver->tty->alt_speed = 230400;
if ((driver->flags & ASYNC_SPD_MASK) == ASYNC_SPD_WARP)
driver->tty->alt_speed = 460800;
ircomm_tty_change_speed(driver);
}
}
#endif
return 0;
}
/*
* Function ircomm_tty_ioctl (tty, cmd, arg)
*
*
*
*/
int ircomm_tty_ioctl(struct tty_struct *tty,
unsigned int cmd, unsigned long arg)
{
struct ircomm_tty_cb *self = (struct ircomm_tty_cb *) tty->driver_data;
int ret = 0;
IRDA_DEBUG(2, "%s()\n", __func__ );
if ((cmd != TIOCGSERIAL) && (cmd != TIOCSSERIAL) &&
(cmd != TIOCSERCONFIG) && (cmd != TIOCSERGSTRUCT) &&
(cmd != TIOCMIWAIT) && (cmd != TIOCGICOUNT)) {
if (tty->flags & (1 << TTY_IO_ERROR))
return -EIO;
}
switch (cmd) {
case TIOCGSERIAL:
ret = ircomm_tty_get_serial_info(self, (struct serial_struct __user *) arg);
break;
case TIOCSSERIAL:
ret = ircomm_tty_set_serial_info(self, (struct serial_struct __user *) arg);
break;
case TIOCMIWAIT:
IRDA_DEBUG(0, "(), TIOCMIWAIT, not impl!\n");
break;
case TIOCGICOUNT:
IRDA_DEBUG(0, "%s(), TIOCGICOUNT not impl!\n", __func__ );
#if 0
save_flags(flags); cli();
cnow = driver->icount;
restore_flags(flags);
p_cuser = (struct serial_icounter_struct __user *) arg;
if (put_user(cnow.cts, &p_cuser->cts) ||
put_user(cnow.dsr, &p_cuser->dsr) ||
put_user(cnow.rng, &p_cuser->rng) ||
put_user(cnow.dcd, &p_cuser->dcd) ||
put_user(cnow.rx, &p_cuser->rx) ||
put_user(cnow.tx, &p_cuser->tx) ||
put_user(cnow.frame, &p_cuser->frame) ||
put_user(cnow.overrun, &p_cuser->overrun) ||
put_user(cnow.parity, &p_cuser->parity) ||
put_user(cnow.brk, &p_cuser->brk) ||
put_user(cnow.buf_overrun, &p_cuser->buf_overrun))
return -EFAULT;
#endif
return 0;
default:
ret = -ENOIOCTLCMD; /* ioctls which we must ignore */
}
return ret;
}
| gpl-2.0 |
psndna88/AGNi-pureCM | drivers/net/wireless/hostap/hostap_download.c | 9270 | 18521 | static int prism2_enable_aux_port(struct net_device *dev, int enable)
{
u16 val, reg;
int i, tries;
unsigned long flags;
struct hostap_interface *iface;
local_info_t *local;
iface = netdev_priv(dev);
local = iface->local;
if (local->no_pri) {
if (enable) {
PDEBUG(DEBUG_EXTRA2, "%s: no PRI f/w - assuming Aux "
"port is already enabled\n", dev->name);
}
return 0;
}
spin_lock_irqsave(&local->cmdlock, flags);
/* wait until busy bit is clear */
tries = HFA384X_CMD_BUSY_TIMEOUT;
while (HFA384X_INW(HFA384X_CMD_OFF) & HFA384X_CMD_BUSY && tries > 0) {
tries--;
udelay(1);
}
if (tries == 0) {
reg = HFA384X_INW(HFA384X_CMD_OFF);
spin_unlock_irqrestore(&local->cmdlock, flags);
printk("%s: prism2_enable_aux_port - timeout - reg=0x%04x\n",
dev->name, reg);
return -ETIMEDOUT;
}
val = HFA384X_INW(HFA384X_CONTROL_OFF);
if (enable) {
HFA384X_OUTW(HFA384X_AUX_MAGIC0, HFA384X_PARAM0_OFF);
HFA384X_OUTW(HFA384X_AUX_MAGIC1, HFA384X_PARAM1_OFF);
HFA384X_OUTW(HFA384X_AUX_MAGIC2, HFA384X_PARAM2_OFF);
if ((val & HFA384X_AUX_PORT_MASK) != HFA384X_AUX_PORT_DISABLED)
printk("prism2_enable_aux_port: was not disabled!?\n");
val &= ~HFA384X_AUX_PORT_MASK;
val |= HFA384X_AUX_PORT_ENABLE;
} else {
HFA384X_OUTW(0, HFA384X_PARAM0_OFF);
HFA384X_OUTW(0, HFA384X_PARAM1_OFF);
HFA384X_OUTW(0, HFA384X_PARAM2_OFF);
if ((val & HFA384X_AUX_PORT_MASK) != HFA384X_AUX_PORT_ENABLED)
printk("prism2_enable_aux_port: was not enabled!?\n");
val &= ~HFA384X_AUX_PORT_MASK;
val |= HFA384X_AUX_PORT_DISABLE;
}
HFA384X_OUTW(val, HFA384X_CONTROL_OFF);
udelay(5);
i = 10000;
while (i > 0) {
val = HFA384X_INW(HFA384X_CONTROL_OFF);
val &= HFA384X_AUX_PORT_MASK;
if ((enable && val == HFA384X_AUX_PORT_ENABLED) ||
(!enable && val == HFA384X_AUX_PORT_DISABLED))
break;
udelay(10);
i--;
}
spin_unlock_irqrestore(&local->cmdlock, flags);
if (i == 0) {
printk("prism2_enable_aux_port(%d) timed out\n",
enable);
return -ETIMEDOUT;
}
return 0;
}
static int hfa384x_from_aux(struct net_device *dev, unsigned int addr, int len,
void *buf)
{
u16 page, offset;
if (addr & 1 || len & 1)
return -1;
page = addr >> 7;
offset = addr & 0x7f;
HFA384X_OUTW(page, HFA384X_AUXPAGE_OFF);
HFA384X_OUTW(offset, HFA384X_AUXOFFSET_OFF);
udelay(5);
#ifdef PRISM2_PCI
{
__le16 *pos = (__le16 *) buf;
while (len > 0) {
*pos++ = HFA384X_INW_DATA(HFA384X_AUXDATA_OFF);
len -= 2;
}
}
#else /* PRISM2_PCI */
HFA384X_INSW(HFA384X_AUXDATA_OFF, buf, len / 2);
#endif /* PRISM2_PCI */
return 0;
}
static int hfa384x_to_aux(struct net_device *dev, unsigned int addr, int len,
void *buf)
{
u16 page, offset;
if (addr & 1 || len & 1)
return -1;
page = addr >> 7;
offset = addr & 0x7f;
HFA384X_OUTW(page, HFA384X_AUXPAGE_OFF);
HFA384X_OUTW(offset, HFA384X_AUXOFFSET_OFF);
udelay(5);
#ifdef PRISM2_PCI
{
__le16 *pos = (__le16 *) buf;
while (len > 0) {
HFA384X_OUTW_DATA(*pos++, HFA384X_AUXDATA_OFF);
len -= 2;
}
}
#else /* PRISM2_PCI */
HFA384X_OUTSW(HFA384X_AUXDATA_OFF, buf, len / 2);
#endif /* PRISM2_PCI */
return 0;
}
static int prism2_pda_ok(u8 *buf)
{
__le16 *pda = (__le16 *) buf;
int pos;
u16 len, pdr;
if (buf[0] == 0xff && buf[1] == 0x00 && buf[2] == 0xff &&
buf[3] == 0x00)
return 0;
pos = 0;
while (pos + 1 < PRISM2_PDA_SIZE / 2) {
len = le16_to_cpu(pda[pos]);
pdr = le16_to_cpu(pda[pos + 1]);
if (len == 0 || pos + len > PRISM2_PDA_SIZE / 2)
return 0;
if (pdr == 0x0000 && len == 2) {
/* PDA end found */
return 1;
}
pos += len + 1;
}
return 0;
}
static int prism2_download_aux_dump(struct net_device *dev,
unsigned int addr, int len, u8 *buf)
{
int res;
prism2_enable_aux_port(dev, 1);
res = hfa384x_from_aux(dev, addr, len, buf);
prism2_enable_aux_port(dev, 0);
if (res)
return -1;
return 0;
}
static u8 * prism2_read_pda(struct net_device *dev)
{
u8 *buf;
int res, i, found = 0;
#define NUM_PDA_ADDRS 4
unsigned int pda_addr[NUM_PDA_ADDRS] = {
0x7f0000 /* others than HFA3841 */,
0x3f0000 /* HFA3841 */,
0x390000 /* apparently used in older cards */,
0x7f0002 /* Intel PRO/Wireless 2011B (PCI) */,
};
buf = kmalloc(PRISM2_PDA_SIZE, GFP_KERNEL);
if (buf == NULL)
return NULL;
/* Note: wlan card should be in initial state (just after init cmd)
* and no other operations should be performed concurrently. */
prism2_enable_aux_port(dev, 1);
for (i = 0; i < NUM_PDA_ADDRS; i++) {
PDEBUG(DEBUG_EXTRA2, "%s: trying to read PDA from 0x%08x",
dev->name, pda_addr[i]);
res = hfa384x_from_aux(dev, pda_addr[i], PRISM2_PDA_SIZE, buf);
if (res)
continue;
if (res == 0 && prism2_pda_ok(buf)) {
PDEBUG2(DEBUG_EXTRA2, ": OK\n");
found = 1;
break;
} else {
PDEBUG2(DEBUG_EXTRA2, ": failed\n");
}
}
prism2_enable_aux_port(dev, 0);
if (!found) {
printk(KERN_DEBUG "%s: valid PDA not found\n", dev->name);
kfree(buf);
buf = NULL;
}
return buf;
}
static int prism2_download_volatile(local_info_t *local,
struct prism2_download_data *param)
{
struct net_device *dev = local->dev;
int ret = 0, i;
u16 param0, param1;
if (local->hw_downloading) {
printk(KERN_WARNING "%s: Already downloading - aborting new "
"request\n", dev->name);
return -1;
}
local->hw_downloading = 1;
if (local->pri_only) {
hfa384x_disable_interrupts(dev);
} else {
prism2_hw_shutdown(dev, 0);
if (prism2_hw_init(dev, 0)) {
printk(KERN_WARNING "%s: Could not initialize card for"
" download\n", dev->name);
ret = -1;
goto out;
}
}
if (prism2_enable_aux_port(dev, 1)) {
printk(KERN_WARNING "%s: Could not enable AUX port\n",
dev->name);
ret = -1;
goto out;
}
param0 = param->start_addr & 0xffff;
param1 = param->start_addr >> 16;
HFA384X_OUTW(0, HFA384X_PARAM2_OFF);
HFA384X_OUTW(param1, HFA384X_PARAM1_OFF);
if (hfa384x_cmd_wait(dev, HFA384X_CMDCODE_DOWNLOAD |
(HFA384X_PROGMODE_ENABLE_VOLATILE << 8),
param0)) {
printk(KERN_WARNING "%s: Download command execution failed\n",
dev->name);
ret = -1;
goto out;
}
for (i = 0; i < param->num_areas; i++) {
PDEBUG(DEBUG_EXTRA2, "%s: Writing %d bytes at 0x%08x\n",
dev->name, param->data[i].len, param->data[i].addr);
if (hfa384x_to_aux(dev, param->data[i].addr,
param->data[i].len, param->data[i].data)) {
printk(KERN_WARNING "%s: RAM download at 0x%08x "
"(len=%d) failed\n", dev->name,
param->data[i].addr, param->data[i].len);
ret = -1;
goto out;
}
}
HFA384X_OUTW(param1, HFA384X_PARAM1_OFF);
HFA384X_OUTW(0, HFA384X_PARAM2_OFF);
if (hfa384x_cmd_no_wait(dev, HFA384X_CMDCODE_DOWNLOAD |
(HFA384X_PROGMODE_DISABLE << 8), param0)) {
printk(KERN_WARNING "%s: Download command execution failed\n",
dev->name);
ret = -1;
goto out;
}
/* ProgMode disable causes the hardware to restart itself from the
* given starting address. Give hw some time and ACK command just in
* case restart did not happen. */
mdelay(5);
HFA384X_OUTW(HFA384X_EV_CMD, HFA384X_EVACK_OFF);
if (prism2_enable_aux_port(dev, 0)) {
printk(KERN_DEBUG "%s: Disabling AUX port failed\n",
dev->name);
/* continue anyway.. restart should have taken care of this */
}
mdelay(5);
local->hw_downloading = 0;
if (prism2_hw_config(dev, 2)) {
printk(KERN_WARNING "%s: Card configuration after RAM "
"download failed\n", dev->name);
ret = -1;
goto out;
}
out:
local->hw_downloading = 0;
return ret;
}
static int prism2_enable_genesis(local_info_t *local, int hcr)
{
struct net_device *dev = local->dev;
u8 initseq[4] = { 0x00, 0xe1, 0xa1, 0xff };
u8 readbuf[4];
printk(KERN_DEBUG "%s: test Genesis mode with HCR 0x%02x\n",
dev->name, hcr);
local->func->cor_sreset(local);
hfa384x_to_aux(dev, 0x7e0038, sizeof(initseq), initseq);
local->func->genesis_reset(local, hcr);
/* Readback test */
hfa384x_from_aux(dev, 0x7e0038, sizeof(readbuf), readbuf);
hfa384x_to_aux(dev, 0x7e0038, sizeof(initseq), initseq);
hfa384x_from_aux(dev, 0x7e0038, sizeof(readbuf), readbuf);
if (memcmp(initseq, readbuf, sizeof(initseq)) == 0) {
printk(KERN_DEBUG "Readback test succeeded, HCR 0x%02x\n",
hcr);
return 0;
} else {
printk(KERN_DEBUG "Readback test failed, HCR 0x%02x "
"write %02x %02x %02x %02x read %02x %02x %02x %02x\n",
hcr, initseq[0], initseq[1], initseq[2], initseq[3],
readbuf[0], readbuf[1], readbuf[2], readbuf[3]);
return 1;
}
}
static int prism2_get_ram_size(local_info_t *local)
{
int ret;
/* Try to enable genesis mode; 0x1F for x8 SRAM or 0x0F for x16 SRAM */
if (prism2_enable_genesis(local, 0x1f) == 0)
ret = 8;
else if (prism2_enable_genesis(local, 0x0f) == 0)
ret = 16;
else
ret = -1;
/* Disable genesis mode */
local->func->genesis_reset(local, ret == 16 ? 0x07 : 0x17);
return ret;
}
static int prism2_download_genesis(local_info_t *local,
struct prism2_download_data *param)
{
struct net_device *dev = local->dev;
int ram16 = 0, i;
int ret = 0;
if (local->hw_downloading) {
printk(KERN_WARNING "%s: Already downloading - aborting new "
"request\n", dev->name);
return -EBUSY;
}
if (!local->func->genesis_reset || !local->func->cor_sreset) {
printk(KERN_INFO "%s: Genesis mode downloading not supported "
"with this hwmodel\n", dev->name);
return -EOPNOTSUPP;
}
local->hw_downloading = 1;
if (prism2_enable_aux_port(dev, 1)) {
printk(KERN_DEBUG "%s: failed to enable AUX port\n",
dev->name);
ret = -EIO;
goto out;
}
if (local->sram_type == -1) {
/* 0x1F for x8 SRAM or 0x0F for x16 SRAM */
if (prism2_enable_genesis(local, 0x1f) == 0) {
ram16 = 0;
PDEBUG(DEBUG_EXTRA2, "%s: Genesis mode OK using x8 "
"SRAM\n", dev->name);
} else if (prism2_enable_genesis(local, 0x0f) == 0) {
ram16 = 1;
PDEBUG(DEBUG_EXTRA2, "%s: Genesis mode OK using x16 "
"SRAM\n", dev->name);
} else {
printk(KERN_DEBUG "%s: Could not initiate genesis "
"mode\n", dev->name);
ret = -EIO;
goto out;
}
} else {
if (prism2_enable_genesis(local, local->sram_type == 8 ?
0x1f : 0x0f)) {
printk(KERN_DEBUG "%s: Failed to set Genesis "
"mode (sram_type=%d)\n", dev->name,
local->sram_type);
ret = -EIO;
goto out;
}
ram16 = local->sram_type != 8;
}
for (i = 0; i < param->num_areas; i++) {
PDEBUG(DEBUG_EXTRA2, "%s: Writing %d bytes at 0x%08x\n",
dev->name, param->data[i].len, param->data[i].addr);
if (hfa384x_to_aux(dev, param->data[i].addr,
param->data[i].len, param->data[i].data)) {
printk(KERN_WARNING "%s: RAM download at 0x%08x "
"(len=%d) failed\n", dev->name,
param->data[i].addr, param->data[i].len);
ret = -EIO;
goto out;
}
}
PDEBUG(DEBUG_EXTRA2, "Disable genesis mode\n");
local->func->genesis_reset(local, ram16 ? 0x07 : 0x17);
if (prism2_enable_aux_port(dev, 0)) {
printk(KERN_DEBUG "%s: Failed to disable AUX port\n",
dev->name);
}
mdelay(5);
local->hw_downloading = 0;
PDEBUG(DEBUG_EXTRA2, "Trying to initialize card\n");
/*
* Make sure the INIT command does not generate a command completion
* event by disabling interrupts.
*/
hfa384x_disable_interrupts(dev);
if (prism2_hw_init(dev, 1)) {
printk(KERN_DEBUG "%s: Initialization after genesis mode "
"download failed\n", dev->name);
ret = -EIO;
goto out;
}
PDEBUG(DEBUG_EXTRA2, "Card initialized - running PRI only\n");
if (prism2_hw_init2(dev, 1)) {
printk(KERN_DEBUG "%s: Initialization(2) after genesis mode "
"download failed\n", dev->name);
ret = -EIO;
goto out;
}
out:
local->hw_downloading = 0;
return ret;
}
#ifdef PRISM2_NON_VOLATILE_DOWNLOAD
/* Note! Non-volatile downloading functionality has not yet been tested
* thoroughly and it may corrupt flash image and effectively kill the card that
* is being updated. You have been warned. */
static inline int prism2_download_block(struct net_device *dev,
u32 addr, u8 *data,
u32 bufaddr, int rest_len)
{
u16 param0, param1;
int block_len;
block_len = rest_len < 4096 ? rest_len : 4096;
param0 = addr & 0xffff;
param1 = addr >> 16;
HFA384X_OUTW(block_len, HFA384X_PARAM2_OFF);
HFA384X_OUTW(param1, HFA384X_PARAM1_OFF);
if (hfa384x_cmd_wait(dev, HFA384X_CMDCODE_DOWNLOAD |
(HFA384X_PROGMODE_ENABLE_NON_VOLATILE << 8),
param0)) {
printk(KERN_WARNING "%s: Flash download command execution "
"failed\n", dev->name);
return -1;
}
if (hfa384x_to_aux(dev, bufaddr, block_len, data)) {
printk(KERN_WARNING "%s: flash download at 0x%08x "
"(len=%d) failed\n", dev->name, addr, block_len);
return -1;
}
HFA384X_OUTW(0, HFA384X_PARAM2_OFF);
HFA384X_OUTW(0, HFA384X_PARAM1_OFF);
if (hfa384x_cmd_wait(dev, HFA384X_CMDCODE_DOWNLOAD |
(HFA384X_PROGMODE_PROGRAM_NON_VOLATILE << 8),
0)) {
printk(KERN_WARNING "%s: Flash write command execution "
"failed\n", dev->name);
return -1;
}
return block_len;
}
static int prism2_download_nonvolatile(local_info_t *local,
struct prism2_download_data *dl)
{
struct net_device *dev = local->dev;
int ret = 0, i;
struct {
__le16 page;
__le16 offset;
__le16 len;
} dlbuffer;
u32 bufaddr;
if (local->hw_downloading) {
printk(KERN_WARNING "%s: Already downloading - aborting new "
"request\n", dev->name);
return -1;
}
ret = local->func->get_rid(dev, HFA384X_RID_DOWNLOADBUFFER,
&dlbuffer, 6, 0);
if (ret < 0) {
printk(KERN_WARNING "%s: Could not read download buffer "
"parameters\n", dev->name);
goto out;
}
printk(KERN_DEBUG "Download buffer: %d bytes at 0x%04x:0x%04x\n",
le16_to_cpu(dlbuffer.len),
le16_to_cpu(dlbuffer.page),
le16_to_cpu(dlbuffer.offset));
bufaddr = (le16_to_cpu(dlbuffer.page) << 7) + le16_to_cpu(dlbuffer.offset);
local->hw_downloading = 1;
if (!local->pri_only) {
prism2_hw_shutdown(dev, 0);
if (prism2_hw_init(dev, 0)) {
printk(KERN_WARNING "%s: Could not initialize card for"
" download\n", dev->name);
ret = -1;
goto out;
}
}
hfa384x_disable_interrupts(dev);
if (prism2_enable_aux_port(dev, 1)) {
printk(KERN_WARNING "%s: Could not enable AUX port\n",
dev->name);
ret = -1;
goto out;
}
printk(KERN_DEBUG "%s: starting flash download\n", dev->name);
for (i = 0; i < dl->num_areas; i++) {
int rest_len = dl->data[i].len;
int data_off = 0;
while (rest_len > 0) {
int block_len;
block_len = prism2_download_block(
dev, dl->data[i].addr + data_off,
dl->data[i].data + data_off, bufaddr,
rest_len);
if (block_len < 0) {
ret = -1;
goto out;
}
rest_len -= block_len;
data_off += block_len;
}
}
HFA384X_OUTW(0, HFA384X_PARAM1_OFF);
HFA384X_OUTW(0, HFA384X_PARAM2_OFF);
if (hfa384x_cmd_wait(dev, HFA384X_CMDCODE_DOWNLOAD |
(HFA384X_PROGMODE_DISABLE << 8), 0)) {
printk(KERN_WARNING "%s: Download command execution failed\n",
dev->name);
ret = -1;
goto out;
}
if (prism2_enable_aux_port(dev, 0)) {
printk(KERN_DEBUG "%s: Disabling AUX port failed\n",
dev->name);
/* continue anyway.. restart should have taken care of this */
}
mdelay(5);
local->func->hw_reset(dev);
local->hw_downloading = 0;
if (prism2_hw_config(dev, 2)) {
printk(KERN_WARNING "%s: Card configuration after flash "
"download failed\n", dev->name);
ret = -1;
} else {
printk(KERN_INFO "%s: Card initialized successfully after "
"flash download\n", dev->name);
}
out:
local->hw_downloading = 0;
return ret;
}
#endif /* PRISM2_NON_VOLATILE_DOWNLOAD */
static void prism2_download_free_data(struct prism2_download_data *dl)
{
int i;
if (dl == NULL)
return;
for (i = 0; i < dl->num_areas; i++)
kfree(dl->data[i].data);
kfree(dl);
}
static int prism2_download(local_info_t *local,
struct prism2_download_param *param)
{
int ret = 0;
int i;
u32 total_len = 0;
struct prism2_download_data *dl = NULL;
printk(KERN_DEBUG "prism2_download: dl_cmd=%d start_addr=0x%08x "
"num_areas=%d\n",
param->dl_cmd, param->start_addr, param->num_areas);
if (param->num_areas > 100) {
ret = -EINVAL;
goto out;
}
dl = kzalloc(sizeof(*dl) + param->num_areas *
sizeof(struct prism2_download_data_area), GFP_KERNEL);
if (dl == NULL) {
ret = -ENOMEM;
goto out;
}
dl->dl_cmd = param->dl_cmd;
dl->start_addr = param->start_addr;
dl->num_areas = param->num_areas;
for (i = 0; i < param->num_areas; i++) {
PDEBUG(DEBUG_EXTRA2,
" area %d: addr=0x%08x len=%d ptr=0x%p\n",
i, param->data[i].addr, param->data[i].len,
param->data[i].ptr);
dl->data[i].addr = param->data[i].addr;
dl->data[i].len = param->data[i].len;
total_len += param->data[i].len;
if (param->data[i].len > PRISM2_MAX_DOWNLOAD_AREA_LEN ||
total_len > PRISM2_MAX_DOWNLOAD_LEN) {
ret = -E2BIG;
goto out;
}
dl->data[i].data = kmalloc(dl->data[i].len, GFP_KERNEL);
if (dl->data[i].data == NULL) {
ret = -ENOMEM;
goto out;
}
if (copy_from_user(dl->data[i].data, param->data[i].ptr,
param->data[i].len)) {
ret = -EFAULT;
goto out;
}
}
switch (param->dl_cmd) {
case PRISM2_DOWNLOAD_VOLATILE:
case PRISM2_DOWNLOAD_VOLATILE_PERSISTENT:
ret = prism2_download_volatile(local, dl);
break;
case PRISM2_DOWNLOAD_VOLATILE_GENESIS:
case PRISM2_DOWNLOAD_VOLATILE_GENESIS_PERSISTENT:
ret = prism2_download_genesis(local, dl);
break;
case PRISM2_DOWNLOAD_NON_VOLATILE:
#ifdef PRISM2_NON_VOLATILE_DOWNLOAD
ret = prism2_download_nonvolatile(local, dl);
#else /* PRISM2_NON_VOLATILE_DOWNLOAD */
printk(KERN_INFO "%s: non-volatile downloading not enabled\n",
local->dev->name);
ret = -EOPNOTSUPP;
#endif /* PRISM2_NON_VOLATILE_DOWNLOAD */
break;
default:
printk(KERN_DEBUG "%s: unsupported download command %d\n",
local->dev->name, param->dl_cmd);
ret = -EINVAL;
break;
}
out:
if (ret == 0 && dl &&
param->dl_cmd == PRISM2_DOWNLOAD_VOLATILE_GENESIS_PERSISTENT) {
prism2_download_free_data(local->dl_pri);
local->dl_pri = dl;
} else if (ret == 0 && dl &&
param->dl_cmd == PRISM2_DOWNLOAD_VOLATILE_PERSISTENT) {
prism2_download_free_data(local->dl_sec);
local->dl_sec = dl;
} else
prism2_download_free_data(dl);
return ret;
}
| gpl-2.0 |
12thmantec/linux-3.5 | drivers/firewire/core-topology.c | 9526 | 15219 | /*
* Incremental bus scan, based on bus topology
*
* Copyright (C) 2004-2006 Kristian Hoegsberg <krh@bitplanet.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <linux/bug.h>
#include <linux/errno.h>
#include <linux/firewire.h>
#include <linux/firewire-constants.h>
#include <linux/jiffies.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/atomic.h>
#include <asm/byteorder.h>
#include "core.h"
#define SELF_ID_PHY_ID(q) (((q) >> 24) & 0x3f)
#define SELF_ID_EXTENDED(q) (((q) >> 23) & 0x01)
#define SELF_ID_LINK_ON(q) (((q) >> 22) & 0x01)
#define SELF_ID_GAP_COUNT(q) (((q) >> 16) & 0x3f)
#define SELF_ID_PHY_SPEED(q) (((q) >> 14) & 0x03)
#define SELF_ID_CONTENDER(q) (((q) >> 11) & 0x01)
#define SELF_ID_PHY_INITIATOR(q) (((q) >> 1) & 0x01)
#define SELF_ID_MORE_PACKETS(q) (((q) >> 0) & 0x01)
#define SELF_ID_EXT_SEQUENCE(q) (((q) >> 20) & 0x07)
#define SELFID_PORT_CHILD 0x3
#define SELFID_PORT_PARENT 0x2
#define SELFID_PORT_NCONN 0x1
#define SELFID_PORT_NONE 0x0
static u32 *count_ports(u32 *sid, int *total_port_count, int *child_port_count)
{
u32 q;
int port_type, shift, seq;
*total_port_count = 0;
*child_port_count = 0;
shift = 6;
q = *sid;
seq = 0;
while (1) {
port_type = (q >> shift) & 0x03;
switch (port_type) {
case SELFID_PORT_CHILD:
(*child_port_count)++;
case SELFID_PORT_PARENT:
case SELFID_PORT_NCONN:
(*total_port_count)++;
case SELFID_PORT_NONE:
break;
}
shift -= 2;
if (shift == 0) {
if (!SELF_ID_MORE_PACKETS(q))
return sid + 1;
shift = 16;
sid++;
q = *sid;
/*
* Check that the extra packets actually are
* extended self ID packets and that the
* sequence numbers in the extended self ID
* packets increase as expected.
*/
if (!SELF_ID_EXTENDED(q) ||
seq != SELF_ID_EXT_SEQUENCE(q))
return NULL;
seq++;
}
}
}
static int get_port_type(u32 *sid, int port_index)
{
int index, shift;
index = (port_index + 5) / 8;
shift = 16 - ((port_index + 5) & 7) * 2;
return (sid[index] >> shift) & 0x03;
}
static struct fw_node *fw_node_create(u32 sid, int port_count, int color)
{
struct fw_node *node;
node = kzalloc(sizeof(*node) + port_count * sizeof(node->ports[0]),
GFP_ATOMIC);
if (node == NULL)
return NULL;
node->color = color;
node->node_id = LOCAL_BUS | SELF_ID_PHY_ID(sid);
node->link_on = SELF_ID_LINK_ON(sid);
node->phy_speed = SELF_ID_PHY_SPEED(sid);
node->initiated_reset = SELF_ID_PHY_INITIATOR(sid);
node->port_count = port_count;
atomic_set(&node->ref_count, 1);
INIT_LIST_HEAD(&node->link);
return node;
}
/*
* Compute the maximum hop count for this node and it's children. The
* maximum hop count is the maximum number of connections between any
* two nodes in the subtree rooted at this node. We need this for
* setting the gap count. As we build the tree bottom up in
* build_tree() below, this is fairly easy to do: for each node we
* maintain the max hop count and the max depth, ie the number of hops
* to the furthest leaf. Computing the max hop count breaks down into
* two cases: either the path goes through this node, in which case
* the hop count is the sum of the two biggest child depths plus 2.
* Or it could be the case that the max hop path is entirely
* containted in a child tree, in which case the max hop count is just
* the max hop count of this child.
*/
static void update_hop_count(struct fw_node *node)
{
int depths[2] = { -1, -1 };
int max_child_hops = 0;
int i;
for (i = 0; i < node->port_count; i++) {
if (node->ports[i] == NULL)
continue;
if (node->ports[i]->max_hops > max_child_hops)
max_child_hops = node->ports[i]->max_hops;
if (node->ports[i]->max_depth > depths[0]) {
depths[1] = depths[0];
depths[0] = node->ports[i]->max_depth;
} else if (node->ports[i]->max_depth > depths[1])
depths[1] = node->ports[i]->max_depth;
}
node->max_depth = depths[0] + 1;
node->max_hops = max(max_child_hops, depths[0] + depths[1] + 2);
}
static inline struct fw_node *fw_node(struct list_head *l)
{
return list_entry(l, struct fw_node, link);
}
/*
* This function builds the tree representation of the topology given
* by the self IDs from the latest bus reset. During the construction
* of the tree, the function checks that the self IDs are valid and
* internally consistent. On success this function returns the
* fw_node corresponding to the local card otherwise NULL.
*/
static struct fw_node *build_tree(struct fw_card *card,
u32 *sid, int self_id_count)
{
struct fw_node *node, *child, *local_node, *irm_node;
struct list_head stack, *h;
u32 *next_sid, *end, q;
int i, port_count, child_port_count, phy_id, parent_count, stack_depth;
int gap_count;
bool beta_repeaters_present;
local_node = NULL;
node = NULL;
INIT_LIST_HEAD(&stack);
stack_depth = 0;
end = sid + self_id_count;
phy_id = 0;
irm_node = NULL;
gap_count = SELF_ID_GAP_COUNT(*sid);
beta_repeaters_present = false;
while (sid < end) {
next_sid = count_ports(sid, &port_count, &child_port_count);
if (next_sid == NULL) {
fw_err(card, "inconsistent extended self IDs\n");
return NULL;
}
q = *sid;
if (phy_id != SELF_ID_PHY_ID(q)) {
fw_err(card, "PHY ID mismatch in self ID: %d != %d\n",
phy_id, SELF_ID_PHY_ID(q));
return NULL;
}
if (child_port_count > stack_depth) {
fw_err(card, "topology stack underflow\n");
return NULL;
}
/*
* Seek back from the top of our stack to find the
* start of the child nodes for this node.
*/
for (i = 0, h = &stack; i < child_port_count; i++)
h = h->prev;
/*
* When the stack is empty, this yields an invalid value,
* but that pointer will never be dereferenced.
*/
child = fw_node(h);
node = fw_node_create(q, port_count, card->color);
if (node == NULL) {
fw_err(card, "out of memory while building topology\n");
return NULL;
}
if (phy_id == (card->node_id & 0x3f))
local_node = node;
if (SELF_ID_CONTENDER(q))
irm_node = node;
parent_count = 0;
for (i = 0; i < port_count; i++) {
switch (get_port_type(sid, i)) {
case SELFID_PORT_PARENT:
/*
* Who's your daddy? We dont know the
* parent node at this time, so we
* temporarily abuse node->color for
* remembering the entry in the
* node->ports array where the parent
* node should be. Later, when we
* handle the parent node, we fix up
* the reference.
*/
parent_count++;
node->color = i;
break;
case SELFID_PORT_CHILD:
node->ports[i] = child;
/*
* Fix up parent reference for this
* child node.
*/
child->ports[child->color] = node;
child->color = card->color;
child = fw_node(child->link.next);
break;
}
}
/*
* Check that the node reports exactly one parent
* port, except for the root, which of course should
* have no parents.
*/
if ((next_sid == end && parent_count != 0) ||
(next_sid < end && parent_count != 1)) {
fw_err(card, "parent port inconsistency for node %d: "
"parent_count=%d\n", phy_id, parent_count);
return NULL;
}
/* Pop the child nodes off the stack and push the new node. */
__list_del(h->prev, &stack);
list_add_tail(&node->link, &stack);
stack_depth += 1 - child_port_count;
if (node->phy_speed == SCODE_BETA &&
parent_count + child_port_count > 1)
beta_repeaters_present = true;
/*
* If PHYs report different gap counts, set an invalid count
* which will force a gap count reconfiguration and a reset.
*/
if (SELF_ID_GAP_COUNT(q) != gap_count)
gap_count = 0;
update_hop_count(node);
sid = next_sid;
phy_id++;
}
card->root_node = node;
card->irm_node = irm_node;
card->gap_count = gap_count;
card->beta_repeaters_present = beta_repeaters_present;
return local_node;
}
typedef void (*fw_node_callback_t)(struct fw_card * card,
struct fw_node * node,
struct fw_node * parent);
static void for_each_fw_node(struct fw_card *card, struct fw_node *root,
fw_node_callback_t callback)
{
struct list_head list;
struct fw_node *node, *next, *child, *parent;
int i;
INIT_LIST_HEAD(&list);
fw_node_get(root);
list_add_tail(&root->link, &list);
parent = NULL;
list_for_each_entry(node, &list, link) {
node->color = card->color;
for (i = 0; i < node->port_count; i++) {
child = node->ports[i];
if (!child)
continue;
if (child->color == card->color)
parent = child;
else {
fw_node_get(child);
list_add_tail(&child->link, &list);
}
}
callback(card, node, parent);
}
list_for_each_entry_safe(node, next, &list, link)
fw_node_put(node);
}
static void report_lost_node(struct fw_card *card,
struct fw_node *node, struct fw_node *parent)
{
fw_node_event(card, node, FW_NODE_DESTROYED);
fw_node_put(node);
/* Topology has changed - reset bus manager retry counter */
card->bm_retries = 0;
}
static void report_found_node(struct fw_card *card,
struct fw_node *node, struct fw_node *parent)
{
int b_path = (node->phy_speed == SCODE_BETA);
if (parent != NULL) {
/* min() macro doesn't work here with gcc 3.4 */
node->max_speed = parent->max_speed < node->phy_speed ?
parent->max_speed : node->phy_speed;
node->b_path = parent->b_path && b_path;
} else {
node->max_speed = node->phy_speed;
node->b_path = b_path;
}
fw_node_event(card, node, FW_NODE_CREATED);
/* Topology has changed - reset bus manager retry counter */
card->bm_retries = 0;
}
void fw_destroy_nodes(struct fw_card *card)
{
unsigned long flags;
spin_lock_irqsave(&card->lock, flags);
card->color++;
if (card->local_node != NULL)
for_each_fw_node(card, card->local_node, report_lost_node);
card->local_node = NULL;
spin_unlock_irqrestore(&card->lock, flags);
}
static void move_tree(struct fw_node *node0, struct fw_node *node1, int port)
{
struct fw_node *tree;
int i;
tree = node1->ports[port];
node0->ports[port] = tree;
for (i = 0; i < tree->port_count; i++) {
if (tree->ports[i] == node1) {
tree->ports[i] = node0;
break;
}
}
}
/*
* Compare the old topology tree for card with the new one specified by root.
* Queue the nodes and mark them as either found, lost or updated.
* Update the nodes in the card topology tree as we go.
*/
static void update_tree(struct fw_card *card, struct fw_node *root)
{
struct list_head list0, list1;
struct fw_node *node0, *node1, *next1;
int i, event;
INIT_LIST_HEAD(&list0);
list_add_tail(&card->local_node->link, &list0);
INIT_LIST_HEAD(&list1);
list_add_tail(&root->link, &list1);
node0 = fw_node(list0.next);
node1 = fw_node(list1.next);
while (&node0->link != &list0) {
WARN_ON(node0->port_count != node1->port_count);
if (node0->link_on && !node1->link_on)
event = FW_NODE_LINK_OFF;
else if (!node0->link_on && node1->link_on)
event = FW_NODE_LINK_ON;
else if (node1->initiated_reset && node1->link_on)
event = FW_NODE_INITIATED_RESET;
else
event = FW_NODE_UPDATED;
node0->node_id = node1->node_id;
node0->color = card->color;
node0->link_on = node1->link_on;
node0->initiated_reset = node1->initiated_reset;
node0->max_hops = node1->max_hops;
node1->color = card->color;
fw_node_event(card, node0, event);
if (card->root_node == node1)
card->root_node = node0;
if (card->irm_node == node1)
card->irm_node = node0;
for (i = 0; i < node0->port_count; i++) {
if (node0->ports[i] && node1->ports[i]) {
/*
* This port didn't change, queue the
* connected node for further
* investigation.
*/
if (node0->ports[i]->color == card->color)
continue;
list_add_tail(&node0->ports[i]->link, &list0);
list_add_tail(&node1->ports[i]->link, &list1);
} else if (node0->ports[i]) {
/*
* The nodes connected here were
* unplugged; unref the lost nodes and
* queue FW_NODE_LOST callbacks for
* them.
*/
for_each_fw_node(card, node0->ports[i],
report_lost_node);
node0->ports[i] = NULL;
} else if (node1->ports[i]) {
/*
* One or more node were connected to
* this port. Move the new nodes into
* the tree and queue FW_NODE_CREATED
* callbacks for them.
*/
move_tree(node0, node1, i);
for_each_fw_node(card, node0->ports[i],
report_found_node);
}
}
node0 = fw_node(node0->link.next);
next1 = fw_node(node1->link.next);
fw_node_put(node1);
node1 = next1;
}
}
static void update_topology_map(struct fw_card *card,
u32 *self_ids, int self_id_count)
{
int node_count = (card->root_node->node_id & 0x3f) + 1;
__be32 *map = card->topology_map;
*map++ = cpu_to_be32((self_id_count + 2) << 16);
*map++ = cpu_to_be32(be32_to_cpu(card->topology_map[1]) + 1);
*map++ = cpu_to_be32((node_count << 16) | self_id_count);
while (self_id_count--)
*map++ = cpu_to_be32p(self_ids++);
fw_compute_block_crc(card->topology_map);
}
void fw_core_handle_bus_reset(struct fw_card *card, int node_id, int generation,
int self_id_count, u32 *self_ids, bool bm_abdicate)
{
struct fw_node *local_node;
unsigned long flags;
/*
* If the selfID buffer is not the immediate successor of the
* previously processed one, we cannot reliably compare the
* old and new topologies.
*/
if (!is_next_generation(generation, card->generation) &&
card->local_node != NULL) {
fw_destroy_nodes(card);
card->bm_retries = 0;
}
spin_lock_irqsave(&card->lock, flags);
card->broadcast_channel_allocated = card->broadcast_channel_auto_allocated;
card->node_id = node_id;
/*
* Update node_id before generation to prevent anybody from using
* a stale node_id together with a current generation.
*/
smp_wmb();
card->generation = generation;
card->reset_jiffies = get_jiffies_64();
card->bm_node_id = 0xffff;
card->bm_abdicate = bm_abdicate;
fw_schedule_bm_work(card, 0);
local_node = build_tree(card, self_ids, self_id_count);
update_topology_map(card, self_ids, self_id_count);
card->color++;
if (local_node == NULL) {
fw_err(card, "topology build failed\n");
/* FIXME: We need to issue a bus reset in this case. */
} else if (card->local_node == NULL) {
card->local_node = local_node;
for_each_fw_node(card, local_node, report_found_node);
} else {
update_tree(card, local_node);
}
spin_unlock_irqrestore(&card->lock, flags);
}
EXPORT_SYMBOL(fw_core_handle_bus_reset);
| gpl-2.0 |
cooldudezach/android_kernel_zte_warplte | drivers/uwb/allocator.c | 9782 | 10168 | /*
* UWB reservation management.
*
* Copyright (C) 2008 Cambridge Silicon Radio Ltd.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/uwb.h>
#include "uwb-internal.h"
static void uwb_rsv_fill_column_alloc(struct uwb_rsv_alloc_info *ai)
{
int col, mas, safe_mas, unsafe_mas;
unsigned char *bm = ai->bm;
struct uwb_rsv_col_info *ci = ai->ci;
unsigned char c;
for (col = ci->csi.start_col; col < UWB_NUM_ZONES; col += ci->csi.interval) {
safe_mas = ci->csi.safe_mas_per_col;
unsafe_mas = ci->csi.unsafe_mas_per_col;
for (mas = 0; mas < UWB_MAS_PER_ZONE; mas++ ) {
if (bm[col * UWB_MAS_PER_ZONE + mas] == 0) {
if (safe_mas > 0) {
safe_mas--;
c = UWB_RSV_MAS_SAFE;
} else if (unsafe_mas > 0) {
unsafe_mas--;
c = UWB_RSV_MAS_UNSAFE;
} else {
break;
}
bm[col * UWB_MAS_PER_ZONE + mas] = c;
}
}
}
}
static void uwb_rsv_fill_row_alloc(struct uwb_rsv_alloc_info *ai)
{
int mas, col, rows;
unsigned char *bm = ai->bm;
struct uwb_rsv_row_info *ri = &ai->ri;
unsigned char c;
rows = 1;
c = UWB_RSV_MAS_SAFE;
for (mas = UWB_MAS_PER_ZONE - 1; mas >= 0; mas--) {
if (ri->avail[mas] == 1) {
if (rows > ri->used_rows) {
break;
} else if (rows > 7) {
c = UWB_RSV_MAS_UNSAFE;
}
for (col = 0; col < UWB_NUM_ZONES; col++) {
if (bm[col * UWB_NUM_ZONES + mas] != UWB_RSV_MAS_NOT_AVAIL) {
bm[col * UWB_NUM_ZONES + mas] = c;
if(c == UWB_RSV_MAS_SAFE)
ai->safe_allocated_mases++;
else
ai->unsafe_allocated_mases++;
}
}
rows++;
}
}
ai->total_allocated_mases = ai->safe_allocated_mases + ai->unsafe_allocated_mases;
}
/*
* Find the best column set for a given availability, interval, num safe mas and
* num unsafe mas.
*
* The different sets are tried in order as shown below, depending on the interval.
*
* interval = 16
* deep = 0
* set 1 -> { 8 }
* deep = 1
* set 1 -> { 4 }
* set 2 -> { 12 }
* deep = 2
* set 1 -> { 2 }
* set 2 -> { 6 }
* set 3 -> { 10 }
* set 4 -> { 14 }
* deep = 3
* set 1 -> { 1 }
* set 2 -> { 3 }
* set 3 -> { 5 }
* set 4 -> { 7 }
* set 5 -> { 9 }
* set 6 -> { 11 }
* set 7 -> { 13 }
* set 8 -> { 15 }
*
* interval = 8
* deep = 0
* set 1 -> { 4 12 }
* deep = 1
* set 1 -> { 2 10 }
* set 2 -> { 6 14 }
* deep = 2
* set 1 -> { 1 9 }
* set 2 -> { 3 11 }
* set 3 -> { 5 13 }
* set 4 -> { 7 15 }
*
* interval = 4
* deep = 0
* set 1 -> { 2 6 10 14 }
* deep = 1
* set 1 -> { 1 5 9 13 }
* set 2 -> { 3 7 11 15 }
*
* interval = 2
* deep = 0
* set 1 -> { 1 3 5 7 9 11 13 15 }
*/
static int uwb_rsv_find_best_column_set(struct uwb_rsv_alloc_info *ai, int interval,
int num_safe_mas, int num_unsafe_mas)
{
struct uwb_rsv_col_info *ci = ai->ci;
struct uwb_rsv_col_set_info *csi = &ci->csi;
struct uwb_rsv_col_set_info tmp_csi;
int deep, set, col, start_col_deep, col_start_set;
int start_col, max_mas_in_set, lowest_max_mas_in_deep;
int n_mas;
int found = UWB_RSV_ALLOC_NOT_FOUND;
tmp_csi.start_col = 0;
start_col_deep = interval;
n_mas = num_unsafe_mas + num_safe_mas;
for (deep = 0; ((interval >> deep) & 0x1) == 0; deep++) {
start_col_deep /= 2;
col_start_set = 0;
lowest_max_mas_in_deep = UWB_MAS_PER_ZONE;
for (set = 1; set <= (1 << deep); set++) {
max_mas_in_set = 0;
start_col = start_col_deep + col_start_set;
for (col = start_col; col < UWB_NUM_ZONES; col += interval) {
if (ci[col].max_avail_safe >= num_safe_mas &&
ci[col].max_avail_unsafe >= n_mas) {
if (ci[col].highest_mas[n_mas] > max_mas_in_set)
max_mas_in_set = ci[col].highest_mas[n_mas];
} else {
max_mas_in_set = 0;
break;
}
}
if ((lowest_max_mas_in_deep > max_mas_in_set) && max_mas_in_set) {
lowest_max_mas_in_deep = max_mas_in_set;
tmp_csi.start_col = start_col;
}
col_start_set += (interval >> deep);
}
if (lowest_max_mas_in_deep < 8) {
csi->start_col = tmp_csi.start_col;
found = UWB_RSV_ALLOC_FOUND;
break;
} else if ((lowest_max_mas_in_deep > 8) &&
(lowest_max_mas_in_deep != UWB_MAS_PER_ZONE) &&
(found == UWB_RSV_ALLOC_NOT_FOUND)) {
csi->start_col = tmp_csi.start_col;
found = UWB_RSV_ALLOC_FOUND;
}
}
if (found == UWB_RSV_ALLOC_FOUND) {
csi->interval = interval;
csi->safe_mas_per_col = num_safe_mas;
csi->unsafe_mas_per_col = num_unsafe_mas;
ai->safe_allocated_mases = (UWB_NUM_ZONES / interval) * num_safe_mas;
ai->unsafe_allocated_mases = (UWB_NUM_ZONES / interval) * num_unsafe_mas;
ai->total_allocated_mases = ai->safe_allocated_mases + ai->unsafe_allocated_mases;
ai->interval = interval;
}
return found;
}
static void get_row_descriptors(struct uwb_rsv_alloc_info *ai)
{
unsigned char *bm = ai->bm;
struct uwb_rsv_row_info *ri = &ai->ri;
int col, mas;
ri->free_rows = 16;
for (mas = 0; mas < UWB_MAS_PER_ZONE; mas ++) {
ri->avail[mas] = 1;
for (col = 1; col < UWB_NUM_ZONES; col++) {
if (bm[col * UWB_NUM_ZONES + mas] == UWB_RSV_MAS_NOT_AVAIL) {
ri->free_rows--;
ri->avail[mas]=0;
break;
}
}
}
}
static void uwb_rsv_fill_column_info(unsigned char *bm, int column, struct uwb_rsv_col_info *rci)
{
int mas;
int block_count = 0, start_block = 0;
int previous_avail = 0;
int available = 0;
int safe_mas_in_row[UWB_MAS_PER_ZONE] = {
8, 7, 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1,
};
rci->max_avail_safe = 0;
for (mas = 0; mas < UWB_MAS_PER_ZONE; mas ++) {
if (!bm[column * UWB_NUM_ZONES + mas]) {
available++;
rci->max_avail_unsafe = available;
rci->highest_mas[available] = mas;
if (previous_avail) {
block_count++;
if ((block_count > safe_mas_in_row[start_block]) &&
(!rci->max_avail_safe))
rci->max_avail_safe = available - 1;
} else {
previous_avail = 1;
start_block = mas;
block_count = 1;
}
} else {
previous_avail = 0;
}
}
if (!rci->max_avail_safe)
rci->max_avail_safe = rci->max_avail_unsafe;
}
static void get_column_descriptors(struct uwb_rsv_alloc_info *ai)
{
unsigned char *bm = ai->bm;
struct uwb_rsv_col_info *ci = ai->ci;
int col;
for (col = 1; col < UWB_NUM_ZONES; col++) {
uwb_rsv_fill_column_info(bm, col, &ci[col]);
}
}
static int uwb_rsv_find_best_row_alloc(struct uwb_rsv_alloc_info *ai)
{
int n_rows;
int max_rows = ai->max_mas / UWB_USABLE_MAS_PER_ROW;
int min_rows = ai->min_mas / UWB_USABLE_MAS_PER_ROW;
if (ai->min_mas % UWB_USABLE_MAS_PER_ROW)
min_rows++;
for (n_rows = max_rows; n_rows >= min_rows; n_rows--) {
if (n_rows <= ai->ri.free_rows) {
ai->ri.used_rows = n_rows;
ai->interval = 1; /* row reservation */
uwb_rsv_fill_row_alloc(ai);
return UWB_RSV_ALLOC_FOUND;
}
}
return UWB_RSV_ALLOC_NOT_FOUND;
}
static int uwb_rsv_find_best_col_alloc(struct uwb_rsv_alloc_info *ai, int interval)
{
int n_safe, n_unsafe, n_mas;
int n_column = UWB_NUM_ZONES / interval;
int max_per_zone = ai->max_mas / n_column;
int min_per_zone = ai->min_mas / n_column;
if (ai->min_mas % n_column)
min_per_zone++;
if (min_per_zone > UWB_MAS_PER_ZONE) {
return UWB_RSV_ALLOC_NOT_FOUND;
}
if (max_per_zone > UWB_MAS_PER_ZONE) {
max_per_zone = UWB_MAS_PER_ZONE;
}
for (n_mas = max_per_zone; n_mas >= min_per_zone; n_mas--) {
if (uwb_rsv_find_best_column_set(ai, interval, 0, n_mas) == UWB_RSV_ALLOC_NOT_FOUND)
continue;
for (n_safe = n_mas; n_safe >= 0; n_safe--) {
n_unsafe = n_mas - n_safe;
if (uwb_rsv_find_best_column_set(ai, interval, n_safe, n_unsafe) == UWB_RSV_ALLOC_FOUND) {
uwb_rsv_fill_column_alloc(ai);
return UWB_RSV_ALLOC_FOUND;
}
}
}
return UWB_RSV_ALLOC_NOT_FOUND;
}
int uwb_rsv_find_best_allocation(struct uwb_rsv *rsv, struct uwb_mas_bm *available,
struct uwb_mas_bm *result)
{
struct uwb_rsv_alloc_info *ai;
int interval;
int bit_index;
ai = kzalloc(sizeof(struct uwb_rsv_alloc_info), GFP_KERNEL);
if (!ai)
return UWB_RSV_ALLOC_NOT_FOUND;
ai->min_mas = rsv->min_mas;
ai->max_mas = rsv->max_mas;
ai->max_interval = rsv->max_interval;
/* fill the not available vector from the available bm */
for_each_clear_bit(bit_index, available->bm, UWB_NUM_MAS)
ai->bm[bit_index] = UWB_RSV_MAS_NOT_AVAIL;
if (ai->max_interval == 1) {
get_row_descriptors(ai);
if (uwb_rsv_find_best_row_alloc(ai) == UWB_RSV_ALLOC_FOUND)
goto alloc_found;
else
goto alloc_not_found;
}
get_column_descriptors(ai);
for (interval = 16; interval >= 2; interval>>=1) {
if (interval > ai->max_interval)
continue;
if (uwb_rsv_find_best_col_alloc(ai, interval) == UWB_RSV_ALLOC_FOUND)
goto alloc_found;
}
/* try row reservation if no column is found */
get_row_descriptors(ai);
if (uwb_rsv_find_best_row_alloc(ai) == UWB_RSV_ALLOC_FOUND)
goto alloc_found;
else
goto alloc_not_found;
alloc_found:
bitmap_zero(result->bm, UWB_NUM_MAS);
bitmap_zero(result->unsafe_bm, UWB_NUM_MAS);
/* fill the safe and unsafe bitmaps */
for (bit_index = 0; bit_index < UWB_NUM_MAS; bit_index++) {
if (ai->bm[bit_index] == UWB_RSV_MAS_SAFE)
set_bit(bit_index, result->bm);
else if (ai->bm[bit_index] == UWB_RSV_MAS_UNSAFE)
set_bit(bit_index, result->unsafe_bm);
}
bitmap_or(result->bm, result->bm, result->unsafe_bm, UWB_NUM_MAS);
result->safe = ai->safe_allocated_mases;
result->unsafe = ai->unsafe_allocated_mases;
kfree(ai);
return UWB_RSV_ALLOC_FOUND;
alloc_not_found:
kfree(ai);
return UWB_RSV_ALLOC_NOT_FOUND;
}
| gpl-2.0 |
drod2169/Linux-Kernel | drivers/gpu/drm/gma500/mdfld_tpo_vid.c | 10038 | 4086 | /*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE 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.
*
* Authors:
* jim liu <jim.liu@intel.com>
* Jackie Li<yaodong.li@intel.com>
*/
#include "mdfld_dsi_dpi.h"
static struct drm_display_mode *tpo_vid_get_config_mode(struct drm_device *dev)
{
struct drm_display_mode *mode;
struct drm_psb_private *dev_priv = dev->dev_private;
struct oaktrail_timing_info *ti = &dev_priv->gct_data.DTD;
bool use_gct = false;
mode = kzalloc(sizeof(*mode), GFP_KERNEL);
if (!mode)
return NULL;
if (use_gct) {
mode->hdisplay = (ti->hactive_hi << 8) | ti->hactive_lo;
mode->vdisplay = (ti->vactive_hi << 8) | ti->vactive_lo;
mode->hsync_start = mode->hdisplay +
((ti->hsync_offset_hi << 8) |
ti->hsync_offset_lo);
mode->hsync_end = mode->hsync_start +
((ti->hsync_pulse_width_hi << 8) |
ti->hsync_pulse_width_lo);
mode->htotal = mode->hdisplay + ((ti->hblank_hi << 8) |
ti->hblank_lo);
mode->vsync_start =
mode->vdisplay + ((ti->vsync_offset_hi << 8) |
ti->vsync_offset_lo);
mode->vsync_end =
mode->vsync_start + ((ti->vsync_pulse_width_hi << 8) |
ti->vsync_pulse_width_lo);
mode->vtotal = mode->vdisplay +
((ti->vblank_hi << 8) | ti->vblank_lo);
mode->clock = ti->pixel_clock * 10;
dev_dbg(dev->dev, "hdisplay is %d\n", mode->hdisplay);
dev_dbg(dev->dev, "vdisplay is %d\n", mode->vdisplay);
dev_dbg(dev->dev, "HSS is %d\n", mode->hsync_start);
dev_dbg(dev->dev, "HSE is %d\n", mode->hsync_end);
dev_dbg(dev->dev, "htotal is %d\n", mode->htotal);
dev_dbg(dev->dev, "VSS is %d\n", mode->vsync_start);
dev_dbg(dev->dev, "VSE is %d\n", mode->vsync_end);
dev_dbg(dev->dev, "vtotal is %d\n", mode->vtotal);
dev_dbg(dev->dev, "clock is %d\n", mode->clock);
} else {
mode->hdisplay = 864;
mode->vdisplay = 480;
mode->hsync_start = 873;
mode->hsync_end = 876;
mode->htotal = 887;
mode->vsync_start = 487;
mode->vsync_end = 490;
mode->vtotal = 499;
mode->clock = 33264;
}
drm_mode_set_name(mode);
drm_mode_set_crtcinfo(mode, 0);
mode->type |= DRM_MODE_TYPE_PREFERRED;
return mode;
}
static int tpo_vid_get_panel_info(struct drm_device *dev,
int pipe,
struct panel_info *pi)
{
if (!dev || !pi)
return -EINVAL;
pi->width_mm = TPO_PANEL_WIDTH;
pi->height_mm = TPO_PANEL_HEIGHT;
return 0;
}
/*TPO DPI encoder helper funcs*/
static const struct drm_encoder_helper_funcs
mdfld_tpo_dpi_encoder_helper_funcs = {
.dpms = mdfld_dsi_dpi_dpms,
.mode_fixup = mdfld_dsi_dpi_mode_fixup,
.prepare = mdfld_dsi_dpi_prepare,
.mode_set = mdfld_dsi_dpi_mode_set,
.commit = mdfld_dsi_dpi_commit,
};
/*TPO DPI encoder funcs*/
static const struct drm_encoder_funcs mdfld_tpo_dpi_encoder_funcs = {
.destroy = drm_encoder_cleanup,
};
const struct panel_funcs mdfld_tpo_vid_funcs = {
.encoder_funcs = &mdfld_tpo_dpi_encoder_funcs,
.encoder_helper_funcs = &mdfld_tpo_dpi_encoder_helper_funcs,
.get_config_mode = &tpo_vid_get_config_mode,
.get_panel_info = tpo_vid_get_panel_info,
};
| gpl-2.0 |
skyem123/android_kernel_oneplus_one | drivers/misc/sgi-xp/xp_sn2.c | 14134 | 4676 | /*
* 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) 2008 Silicon Graphics, Inc. All Rights Reserved.
*/
/*
* Cross Partition (XP) sn2-based functions.
*
* Architecture specific implementation of common functions.
*/
#include <linux/module.h>
#include <linux/device.h>
#include <asm/sn/bte.h>
#include <asm/sn/sn_sal.h>
#include "xp.h"
/*
* The export of xp_nofault_PIOR needs to happen here since it is defined
* in drivers/misc/sgi-xp/xp_nofault.S. The target of the nofault read is
* defined here.
*/
EXPORT_SYMBOL_GPL(xp_nofault_PIOR);
u64 xp_nofault_PIOR_target;
EXPORT_SYMBOL_GPL(xp_nofault_PIOR_target);
/*
* Register a nofault code region which performs a cross-partition PIO read.
* If the PIO read times out, the MCA handler will consume the error and
* return to a kernel-provided instruction to indicate an error. This PIO read
* exists because it is guaranteed to timeout if the destination is down
* (amo operations do not timeout on at least some CPUs on Shubs <= v1.2,
* which unfortunately we have to work around).
*/
static enum xp_retval
xp_register_nofault_code_sn2(void)
{
int ret;
u64 func_addr;
u64 err_func_addr;
func_addr = *(u64 *)xp_nofault_PIOR;
err_func_addr = *(u64 *)xp_error_PIOR;
ret = sn_register_nofault_code(func_addr, err_func_addr, err_func_addr,
1, 1);
if (ret != 0) {
dev_err(xp, "can't register nofault code, error=%d\n", ret);
return xpSalError;
}
/*
* Setup the nofault PIO read target. (There is no special reason why
* SH_IPI_ACCESS was selected.)
*/
if (is_shub1())
xp_nofault_PIOR_target = SH1_IPI_ACCESS;
else if (is_shub2())
xp_nofault_PIOR_target = SH2_IPI_ACCESS0;
return xpSuccess;
}
static void
xp_unregister_nofault_code_sn2(void)
{
u64 func_addr = *(u64 *)xp_nofault_PIOR;
u64 err_func_addr = *(u64 *)xp_error_PIOR;
/* unregister the PIO read nofault code region */
(void)sn_register_nofault_code(func_addr, err_func_addr,
err_func_addr, 1, 0);
}
/*
* Convert a virtual memory address to a physical memory address.
*/
static unsigned long
xp_pa_sn2(void *addr)
{
return __pa(addr);
}
/*
* Convert a global physical to a socket physical address.
*/
static unsigned long
xp_socket_pa_sn2(unsigned long gpa)
{
return gpa;
}
/*
* Wrapper for bte_copy().
*
* dst_pa - physical address of the destination of the transfer.
* src_pa - physical address of the source of the transfer.
* len - number of bytes to transfer from source to destination.
*
* Note: xp_remote_memcpy_sn2() should never be called while holding a spinlock.
*/
static enum xp_retval
xp_remote_memcpy_sn2(unsigned long dst_pa, const unsigned long src_pa,
size_t len)
{
bte_result_t ret;
ret = bte_copy(src_pa, dst_pa, len, (BTE_NOTIFY | BTE_WACQUIRE), NULL);
if (ret == BTE_SUCCESS)
return xpSuccess;
if (is_shub2()) {
dev_err(xp, "bte_copy() on shub2 failed, error=0x%x dst_pa="
"0x%016lx src_pa=0x%016lx len=%ld\\n", ret, dst_pa,
src_pa, len);
} else {
dev_err(xp, "bte_copy() failed, error=%d dst_pa=0x%016lx "
"src_pa=0x%016lx len=%ld\\n", ret, dst_pa, src_pa, len);
}
return xpBteCopyError;
}
static int
xp_cpu_to_nasid_sn2(int cpuid)
{
return cpuid_to_nasid(cpuid);
}
static enum xp_retval
xp_expand_memprotect_sn2(unsigned long phys_addr, unsigned long size)
{
u64 nasid_array = 0;
int ret;
ret = sn_change_memprotect(phys_addr, size, SN_MEMPROT_ACCESS_CLASS_1,
&nasid_array);
if (ret != 0) {
dev_err(xp, "sn_change_memprotect(,, "
"SN_MEMPROT_ACCESS_CLASS_1,) failed ret=%d\n", ret);
return xpSalError;
}
return xpSuccess;
}
static enum xp_retval
xp_restrict_memprotect_sn2(unsigned long phys_addr, unsigned long size)
{
u64 nasid_array = 0;
int ret;
ret = sn_change_memprotect(phys_addr, size, SN_MEMPROT_ACCESS_CLASS_0,
&nasid_array);
if (ret != 0) {
dev_err(xp, "sn_change_memprotect(,, "
"SN_MEMPROT_ACCESS_CLASS_0,) failed ret=%d\n", ret);
return xpSalError;
}
return xpSuccess;
}
enum xp_retval
xp_init_sn2(void)
{
BUG_ON(!is_shub());
xp_max_npartitions = XP_MAX_NPARTITIONS_SN2;
xp_partition_id = sn_partition_id;
xp_region_size = sn_region_size;
xp_pa = xp_pa_sn2;
xp_socket_pa = xp_socket_pa_sn2;
xp_remote_memcpy = xp_remote_memcpy_sn2;
xp_cpu_to_nasid = xp_cpu_to_nasid_sn2;
xp_expand_memprotect = xp_expand_memprotect_sn2;
xp_restrict_memprotect = xp_restrict_memprotect_sn2;
return xp_register_nofault_code_sn2();
}
void
xp_exit_sn2(void)
{
BUG_ON(!is_shub());
xp_unregister_nofault_code_sn2();
}
| gpl-2.0 |
entrusc/linux-lcd | drivers/misc/sgi-xp/xp_sn2.c | 14134 | 4676 | /*
* 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) 2008 Silicon Graphics, Inc. All Rights Reserved.
*/
/*
* Cross Partition (XP) sn2-based functions.
*
* Architecture specific implementation of common functions.
*/
#include <linux/module.h>
#include <linux/device.h>
#include <asm/sn/bte.h>
#include <asm/sn/sn_sal.h>
#include "xp.h"
/*
* The export of xp_nofault_PIOR needs to happen here since it is defined
* in drivers/misc/sgi-xp/xp_nofault.S. The target of the nofault read is
* defined here.
*/
EXPORT_SYMBOL_GPL(xp_nofault_PIOR);
u64 xp_nofault_PIOR_target;
EXPORT_SYMBOL_GPL(xp_nofault_PIOR_target);
/*
* Register a nofault code region which performs a cross-partition PIO read.
* If the PIO read times out, the MCA handler will consume the error and
* return to a kernel-provided instruction to indicate an error. This PIO read
* exists because it is guaranteed to timeout if the destination is down
* (amo operations do not timeout on at least some CPUs on Shubs <= v1.2,
* which unfortunately we have to work around).
*/
static enum xp_retval
xp_register_nofault_code_sn2(void)
{
int ret;
u64 func_addr;
u64 err_func_addr;
func_addr = *(u64 *)xp_nofault_PIOR;
err_func_addr = *(u64 *)xp_error_PIOR;
ret = sn_register_nofault_code(func_addr, err_func_addr, err_func_addr,
1, 1);
if (ret != 0) {
dev_err(xp, "can't register nofault code, error=%d\n", ret);
return xpSalError;
}
/*
* Setup the nofault PIO read target. (There is no special reason why
* SH_IPI_ACCESS was selected.)
*/
if (is_shub1())
xp_nofault_PIOR_target = SH1_IPI_ACCESS;
else if (is_shub2())
xp_nofault_PIOR_target = SH2_IPI_ACCESS0;
return xpSuccess;
}
static void
xp_unregister_nofault_code_sn2(void)
{
u64 func_addr = *(u64 *)xp_nofault_PIOR;
u64 err_func_addr = *(u64 *)xp_error_PIOR;
/* unregister the PIO read nofault code region */
(void)sn_register_nofault_code(func_addr, err_func_addr,
err_func_addr, 1, 0);
}
/*
* Convert a virtual memory address to a physical memory address.
*/
static unsigned long
xp_pa_sn2(void *addr)
{
return __pa(addr);
}
/*
* Convert a global physical to a socket physical address.
*/
static unsigned long
xp_socket_pa_sn2(unsigned long gpa)
{
return gpa;
}
/*
* Wrapper for bte_copy().
*
* dst_pa - physical address of the destination of the transfer.
* src_pa - physical address of the source of the transfer.
* len - number of bytes to transfer from source to destination.
*
* Note: xp_remote_memcpy_sn2() should never be called while holding a spinlock.
*/
static enum xp_retval
xp_remote_memcpy_sn2(unsigned long dst_pa, const unsigned long src_pa,
size_t len)
{
bte_result_t ret;
ret = bte_copy(src_pa, dst_pa, len, (BTE_NOTIFY | BTE_WACQUIRE), NULL);
if (ret == BTE_SUCCESS)
return xpSuccess;
if (is_shub2()) {
dev_err(xp, "bte_copy() on shub2 failed, error=0x%x dst_pa="
"0x%016lx src_pa=0x%016lx len=%ld\\n", ret, dst_pa,
src_pa, len);
} else {
dev_err(xp, "bte_copy() failed, error=%d dst_pa=0x%016lx "
"src_pa=0x%016lx len=%ld\\n", ret, dst_pa, src_pa, len);
}
return xpBteCopyError;
}
static int
xp_cpu_to_nasid_sn2(int cpuid)
{
return cpuid_to_nasid(cpuid);
}
static enum xp_retval
xp_expand_memprotect_sn2(unsigned long phys_addr, unsigned long size)
{
u64 nasid_array = 0;
int ret;
ret = sn_change_memprotect(phys_addr, size, SN_MEMPROT_ACCESS_CLASS_1,
&nasid_array);
if (ret != 0) {
dev_err(xp, "sn_change_memprotect(,, "
"SN_MEMPROT_ACCESS_CLASS_1,) failed ret=%d\n", ret);
return xpSalError;
}
return xpSuccess;
}
static enum xp_retval
xp_restrict_memprotect_sn2(unsigned long phys_addr, unsigned long size)
{
u64 nasid_array = 0;
int ret;
ret = sn_change_memprotect(phys_addr, size, SN_MEMPROT_ACCESS_CLASS_0,
&nasid_array);
if (ret != 0) {
dev_err(xp, "sn_change_memprotect(,, "
"SN_MEMPROT_ACCESS_CLASS_0,) failed ret=%d\n", ret);
return xpSalError;
}
return xpSuccess;
}
enum xp_retval
xp_init_sn2(void)
{
BUG_ON(!is_shub());
xp_max_npartitions = XP_MAX_NPARTITIONS_SN2;
xp_partition_id = sn_partition_id;
xp_region_size = sn_region_size;
xp_pa = xp_pa_sn2;
xp_socket_pa = xp_socket_pa_sn2;
xp_remote_memcpy = xp_remote_memcpy_sn2;
xp_cpu_to_nasid = xp_cpu_to_nasid_sn2;
xp_expand_memprotect = xp_expand_memprotect_sn2;
xp_restrict_memprotect = xp_restrict_memprotect_sn2;
return xp_register_nofault_code_sn2();
}
void
xp_exit_sn2(void)
{
BUG_ON(!is_shub());
xp_unregister_nofault_code_sn2();
}
| gpl-2.0 |
ghmajx/asuswrt-merlin | release/src/router/iproute2-3.x/tc/f_route.c | 55 | 4352 | /*
* f_route.c ROUTE filter.
*
* 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.
*
* Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <syslog.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include "utils.h"
#include "rt_names.h"
#include "tc_common.h"
#include "tc_util.h"
static void explain(void)
{
fprintf(stderr, "Usage: ... route [ from REALM | fromif TAG ] [ to REALM ]\n");
fprintf(stderr, " [ flowid CLASSID ] [ police POLICE_SPEC ]\n");
fprintf(stderr, " POLICE_SPEC := ... look at TBF\n");
fprintf(stderr, " CLASSID := X:Y\n");
fprintf(stderr, "\nNOTE: CLASSID is parsed as hexadecimal input.\n");
}
static int route_parse_opt(struct filter_util *qu, char *handle, int argc, char **argv, struct nlmsghdr *n)
{
struct tc_police tp;
struct tcmsg *t = NLMSG_DATA(n);
struct rtattr *tail;
__u32 fh = 0xFFFF8000;
__u32 order = 0;
memset(&tp, 0, sizeof(tp));
if (handle) {
if (get_u32(&t->tcm_handle, handle, 0)) {
fprintf(stderr, "Illegal \"handle\"\n");
return -1;
}
}
if (argc == 0)
return 0;
tail = NLMSG_TAIL(n);
addattr_l(n, 4096, TCA_OPTIONS, NULL, 0);
while (argc > 0) {
if (matches(*argv, "to") == 0) {
__u32 id;
NEXT_ARG();
if (rtnl_rtrealm_a2n(&id, *argv)) {
fprintf(stderr, "Illegal \"to\"\n");
return -1;
}
addattr_l(n, 4096, TCA_ROUTE4_TO, &id, 4);
fh &= ~0x80FF;
fh |= id&0xFF;
} else if (matches(*argv, "from") == 0) {
__u32 id;
NEXT_ARG();
if (rtnl_rtrealm_a2n(&id, *argv)) {
fprintf(stderr, "Illegal \"from\"\n");
return -1;
}
addattr_l(n, 4096, TCA_ROUTE4_FROM, &id, 4);
fh &= 0xFFFF;
fh |= id<<16;
} else if (matches(*argv, "fromif") == 0) {
__u32 id;
NEXT_ARG();
ll_init_map(&rth);
if ((id=ll_name_to_index(*argv)) <= 0) {
fprintf(stderr, "Illegal \"fromif\"\n");
return -1;
}
addattr_l(n, 4096, TCA_ROUTE4_IIF, &id, 4);
fh &= 0xFFFF;
fh |= (0x8000|id)<<16;
} else if (matches(*argv, "classid") == 0 ||
strcmp(*argv, "flowid") == 0) {
unsigned handle;
NEXT_ARG();
if (get_tc_classid(&handle, *argv)) {
fprintf(stderr, "Illegal \"classid\"\n");
return -1;
}
addattr_l(n, 4096, TCA_ROUTE4_CLASSID, &handle, 4);
} else if (matches(*argv, "police") == 0) {
NEXT_ARG();
if (parse_police(&argc, &argv, TCA_ROUTE4_POLICE, n)) {
fprintf(stderr, "Illegal \"police\"\n");
return -1;
}
continue;
} else if (matches(*argv, "order") == 0) {
NEXT_ARG();
if (get_u32(&order, *argv, 0)) {
fprintf(stderr, "Illegal \"order\"\n");
return -1;
}
} else if (strcmp(*argv, "help") == 0) {
explain();
return -1;
} else {
fprintf(stderr, "What is \"%s\"?\n", *argv);
explain();
return -1;
}
argc--; argv++;
}
tail->rta_len = (void *) NLMSG_TAIL(n) - (void *) tail;
if (order) {
fh &= ~0x7F00;
fh |= (order<<8)&0x7F00;
}
if (!t->tcm_handle)
t->tcm_handle = fh;
return 0;
}
static int route_print_opt(struct filter_util *qu, FILE *f, struct rtattr *opt, __u32 handle)
{
struct rtattr *tb[TCA_ROUTE4_MAX+1];
SPRINT_BUF(b1);
if (opt == NULL)
return 0;
parse_rtattr_nested(tb, TCA_ROUTE4_MAX, opt);
if (handle)
fprintf(f, "fh 0x%08x ", handle);
if (handle&0x7F00)
fprintf(f, "order %d ", (handle>>8)&0x7F);
if (tb[TCA_ROUTE4_CLASSID]) {
SPRINT_BUF(b1);
fprintf(f, "flowid %s ", sprint_tc_classid(*(__u32*)RTA_DATA(tb[TCA_ROUTE4_CLASSID]), b1));
}
if (tb[TCA_ROUTE4_TO])
fprintf(f, "to %s ", rtnl_rtrealm_n2a(*(__u32*)RTA_DATA(tb[TCA_ROUTE4_TO]), b1, sizeof(b1)));
if (tb[TCA_ROUTE4_FROM])
fprintf(f, "from %s ", rtnl_rtrealm_n2a(*(__u32*)RTA_DATA(tb[TCA_ROUTE4_FROM]), b1, sizeof(b1)));
if (tb[TCA_ROUTE4_IIF])
fprintf(f, "fromif %s", ll_index_to_name(*(int*)RTA_DATA(tb[TCA_ROUTE4_IIF])));
if (tb[TCA_ROUTE4_POLICE])
tc_print_police(f, tb[TCA_ROUTE4_POLICE]);
return 0;
}
struct filter_util route_filter_util = {
.id = "route",
.parse_fopt = route_parse_opt,
.print_fopt = route_print_opt,
};
| gpl-2.0 |
wilesduan/linux-part1 | drivers/iio/imu/adis16400_core.c | 55 | 27215 | /*
* adis16400.c support Analog Devices ADIS16400/5
* 3d 2g Linear Accelerometers,
* 3d Gyroscopes,
* 3d Magnetometers via SPI
*
* Copyright (c) 2009 Manuel Stahl <manuel.stahl@iis.fraunhofer.de>
* Copyright (c) 2007 Jonathan Cameron <jic23@kernel.org>
* Copyright (c) 2011 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/interrupt.h>
#include <linux/irq.h>
#include <linux/delay.h>
#include <linux/mutex.h>
#include <linux/device.h>
#include <linux/kernel.h>
#include <linux/spi/spi.h>
#include <linux/slab.h>
#include <linux/sysfs.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/debugfs.h>
#include <linux/iio/iio.h>
#include <linux/iio/sysfs.h>
#include <linux/iio/buffer.h>
#include "adis16400.h"
#ifdef CONFIG_DEBUG_FS
static ssize_t adis16400_show_serial_number(struct file *file,
char __user *userbuf, size_t count, loff_t *ppos)
{
struct adis16400_state *st = file->private_data;
u16 lot1, lot2, serial_number;
char buf[16];
size_t len;
int ret;
ret = adis_read_reg_16(&st->adis, ADIS16334_LOT_ID1, &lot1);
if (ret < 0)
return ret;
ret = adis_read_reg_16(&st->adis, ADIS16334_LOT_ID2, &lot2);
if (ret < 0)
return ret;
ret = adis_read_reg_16(&st->adis, ADIS16334_SERIAL_NUMBER,
&serial_number);
if (ret < 0)
return ret;
len = snprintf(buf, sizeof(buf), "%.4x-%.4x-%.4x\n", lot1, lot2,
serial_number);
return simple_read_from_buffer(userbuf, count, ppos, buf, len);
}
static const struct file_operations adis16400_serial_number_fops = {
.open = simple_open,
.read = adis16400_show_serial_number,
.llseek = default_llseek,
.owner = THIS_MODULE,
};
static int adis16400_show_product_id(void *arg, u64 *val)
{
struct adis16400_state *st = arg;
uint16_t prod_id;
int ret;
ret = adis_read_reg_16(&st->adis, ADIS16400_PRODUCT_ID, &prod_id);
if (ret < 0)
return ret;
*val = prod_id;
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(adis16400_product_id_fops,
adis16400_show_product_id, NULL, "%lld\n");
static int adis16400_show_flash_count(void *arg, u64 *val)
{
struct adis16400_state *st = arg;
uint16_t flash_count;
int ret;
ret = adis_read_reg_16(&st->adis, ADIS16400_FLASH_CNT, &flash_count);
if (ret < 0)
return ret;
*val = flash_count;
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(adis16400_flash_count_fops,
adis16400_show_flash_count, NULL, "%lld\n");
static int adis16400_debugfs_init(struct iio_dev *indio_dev)
{
struct adis16400_state *st = iio_priv(indio_dev);
if (st->variant->flags & ADIS16400_HAS_SERIAL_NUMBER)
debugfs_create_file("serial_number", 0400,
indio_dev->debugfs_dentry, st,
&adis16400_serial_number_fops);
if (st->variant->flags & ADIS16400_HAS_PROD_ID)
debugfs_create_file("product_id", 0400,
indio_dev->debugfs_dentry, st,
&adis16400_product_id_fops);
debugfs_create_file("flash_count", 0400, indio_dev->debugfs_dentry,
st, &adis16400_flash_count_fops);
return 0;
}
#else
static int adis16400_debugfs_init(struct iio_dev *indio_dev)
{
return 0;
}
#endif
enum adis16400_chip_variant {
ADIS16300,
ADIS16334,
ADIS16350,
ADIS16360,
ADIS16362,
ADIS16364,
ADIS16400,
ADIS16448,
};
static int adis16334_get_freq(struct adis16400_state *st)
{
int ret;
uint16_t t;
ret = adis_read_reg_16(&st->adis, ADIS16400_SMPL_PRD, &t);
if (ret < 0)
return ret;
t >>= ADIS16334_RATE_DIV_SHIFT;
return 819200 >> t;
}
static int adis16334_set_freq(struct adis16400_state *st, unsigned int freq)
{
unsigned int t;
if (freq < 819200)
t = ilog2(819200 / freq);
else
t = 0;
if (t > 0x31)
t = 0x31;
t <<= ADIS16334_RATE_DIV_SHIFT;
t |= ADIS16334_RATE_INT_CLK;
return adis_write_reg_16(&st->adis, ADIS16400_SMPL_PRD, t);
}
static int adis16400_get_freq(struct adis16400_state *st)
{
int sps, ret;
uint16_t t;
ret = adis_read_reg_16(&st->adis, ADIS16400_SMPL_PRD, &t);
if (ret < 0)
return ret;
sps = (t & ADIS16400_SMPL_PRD_TIME_BASE) ? 52851 : 1638404;
sps /= (t & ADIS16400_SMPL_PRD_DIV_MASK) + 1;
return sps;
}
static int adis16400_set_freq(struct adis16400_state *st, unsigned int freq)
{
unsigned int t;
uint8_t val = 0;
t = 1638404 / freq;
if (t >= 128) {
val |= ADIS16400_SMPL_PRD_TIME_BASE;
t = 52851 / freq;
if (t >= 128)
t = 127;
} else if (t != 0) {
t--;
}
val |= t;
if (t >= 0x0A || (val & ADIS16400_SMPL_PRD_TIME_BASE))
st->adis.spi->max_speed_hz = ADIS16400_SPI_SLOW;
else
st->adis.spi->max_speed_hz = ADIS16400_SPI_FAST;
return adis_write_reg_8(&st->adis, ADIS16400_SMPL_PRD, val);
}
static ssize_t adis16400_read_frequency(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *indio_dev = dev_to_iio_dev(dev);
struct adis16400_state *st = iio_priv(indio_dev);
int ret;
ret = st->variant->get_freq(st);
if (ret < 0)
return ret;
return sprintf(buf, "%d.%.3d\n", ret / 1000, ret % 1000);
}
static const unsigned adis16400_3db_divisors[] = {
[0] = 2, /* Special case */
[1] = 6,
[2] = 12,
[3] = 25,
[4] = 50,
[5] = 100,
[6] = 200,
[7] = 200, /* Not a valid setting */
};
static int adis16400_set_filter(struct iio_dev *indio_dev, int sps, int val)
{
struct adis16400_state *st = iio_priv(indio_dev);
uint16_t val16;
int i, ret;
for (i = ARRAY_SIZE(adis16400_3db_divisors) - 1; i >= 1; i--) {
if (sps / adis16400_3db_divisors[i] >= val)
break;
}
ret = adis_read_reg_16(&st->adis, ADIS16400_SENS_AVG, &val16);
if (ret < 0)
return ret;
ret = adis_write_reg_16(&st->adis, ADIS16400_SENS_AVG,
(val16 & ~0x07) | i);
return ret;
}
static ssize_t adis16400_write_frequency(struct device *dev,
struct device_attribute *attr, const char *buf, size_t len)
{
struct iio_dev *indio_dev = dev_to_iio_dev(dev);
struct adis16400_state *st = iio_priv(indio_dev);
int i, f, val;
int ret;
ret = iio_str_to_fixpoint(buf, 100, &i, &f);
if (ret)
return ret;
val = i * 1000 + f;
if (val <= 0)
return -EINVAL;
mutex_lock(&indio_dev->mlock);
st->variant->set_freq(st, val);
mutex_unlock(&indio_dev->mlock);
return ret ? ret : len;
}
/* Power down the device */
static int adis16400_stop_device(struct iio_dev *indio_dev)
{
struct adis16400_state *st = iio_priv(indio_dev);
int ret;
ret = adis_write_reg_16(&st->adis, ADIS16400_SLP_CNT,
ADIS16400_SLP_CNT_POWER_OFF);
if (ret)
dev_err(&indio_dev->dev,
"problem with turning device off: SLP_CNT");
return ret;
}
static int adis16400_initial_setup(struct iio_dev *indio_dev)
{
struct adis16400_state *st = iio_priv(indio_dev);
uint16_t prod_id, smp_prd;
unsigned int device_id;
int ret;
/* use low spi speed for init if the device has a slow mode */
if (st->variant->flags & ADIS16400_HAS_SLOW_MODE)
st->adis.spi->max_speed_hz = ADIS16400_SPI_SLOW;
else
st->adis.spi->max_speed_hz = ADIS16400_SPI_FAST;
st->adis.spi->mode = SPI_MODE_3;
spi_setup(st->adis.spi);
ret = adis_initial_startup(&st->adis);
if (ret)
return ret;
if (st->variant->flags & ADIS16400_HAS_PROD_ID) {
ret = adis_read_reg_16(&st->adis,
ADIS16400_PRODUCT_ID, &prod_id);
if (ret)
goto err_ret;
sscanf(indio_dev->name, "adis%u\n", &device_id);
if (prod_id != device_id)
dev_warn(&indio_dev->dev, "Device ID(%u) and product ID(%u) do not match.",
device_id, prod_id);
dev_info(&indio_dev->dev, "%s: prod_id 0x%04x at CS%d (irq %d)\n",
indio_dev->name, prod_id,
st->adis.spi->chip_select, st->adis.spi->irq);
}
/* use high spi speed if possible */
if (st->variant->flags & ADIS16400_HAS_SLOW_MODE) {
ret = adis_read_reg_16(&st->adis, ADIS16400_SMPL_PRD, &smp_prd);
if (ret)
goto err_ret;
if ((smp_prd & ADIS16400_SMPL_PRD_DIV_MASK) < 0x0A) {
st->adis.spi->max_speed_hz = ADIS16400_SPI_FAST;
spi_setup(st->adis.spi);
}
}
err_ret:
return ret;
}
static IIO_DEV_ATTR_SAMP_FREQ(S_IWUSR | S_IRUGO,
adis16400_read_frequency,
adis16400_write_frequency);
static const uint8_t adis16400_addresses[] = {
[ADIS16400_SCAN_GYRO_X] = ADIS16400_XGYRO_OFF,
[ADIS16400_SCAN_GYRO_Y] = ADIS16400_YGYRO_OFF,
[ADIS16400_SCAN_GYRO_Z] = ADIS16400_ZGYRO_OFF,
[ADIS16400_SCAN_ACC_X] = ADIS16400_XACCL_OFF,
[ADIS16400_SCAN_ACC_Y] = ADIS16400_YACCL_OFF,
[ADIS16400_SCAN_ACC_Z] = ADIS16400_ZACCL_OFF,
};
static int adis16400_write_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan, int val, int val2, long info)
{
struct adis16400_state *st = iio_priv(indio_dev);
int ret, sps;
switch (info) {
case IIO_CHAN_INFO_CALIBBIAS:
mutex_lock(&indio_dev->mlock);
ret = adis_write_reg_16(&st->adis,
adis16400_addresses[chan->scan_index], val);
mutex_unlock(&indio_dev->mlock);
return ret;
case IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY:
/*
* Need to cache values so we can update if the frequency
* changes.
*/
mutex_lock(&indio_dev->mlock);
st->filt_int = val;
/* Work out update to current value */
sps = st->variant->get_freq(st);
if (sps < 0) {
mutex_unlock(&indio_dev->mlock);
return sps;
}
ret = adis16400_set_filter(indio_dev, sps,
val * 1000 + val2 / 1000);
mutex_unlock(&indio_dev->mlock);
return ret;
default:
return -EINVAL;
}
}
static int adis16400_read_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan, int *val, int *val2, long info)
{
struct adis16400_state *st = iio_priv(indio_dev);
int16_t val16;
int ret;
switch (info) {
case IIO_CHAN_INFO_RAW:
return adis_single_conversion(indio_dev, chan, 0, val);
case IIO_CHAN_INFO_SCALE:
switch (chan->type) {
case IIO_ANGL_VEL:
*val = 0;
*val2 = st->variant->gyro_scale_micro;
return IIO_VAL_INT_PLUS_MICRO;
case IIO_VOLTAGE:
*val = 0;
if (chan->channel == 0) {
*val = 2;
*val2 = 418000; /* 2.418 mV */
} else {
*val = 0;
*val2 = 805800; /* 805.8 uV */
}
return IIO_VAL_INT_PLUS_MICRO;
case IIO_ACCEL:
*val = 0;
*val2 = st->variant->accel_scale_micro;
return IIO_VAL_INT_PLUS_MICRO;
case IIO_MAGN:
*val = 0;
*val2 = 500; /* 0.5 mgauss */
return IIO_VAL_INT_PLUS_MICRO;
case IIO_TEMP:
*val = st->variant->temp_scale_nano / 1000000;
*val2 = (st->variant->temp_scale_nano % 1000000);
return IIO_VAL_INT_PLUS_MICRO;
default:
return -EINVAL;
}
case IIO_CHAN_INFO_CALIBBIAS:
mutex_lock(&indio_dev->mlock);
ret = adis_read_reg_16(&st->adis,
adis16400_addresses[chan->scan_index], &val16);
mutex_unlock(&indio_dev->mlock);
if (ret)
return ret;
val16 = ((val16 & 0xFFF) << 4) >> 4;
*val = val16;
return IIO_VAL_INT;
case IIO_CHAN_INFO_OFFSET:
/* currently only temperature */
*val = st->variant->temp_offset;
return IIO_VAL_INT;
case IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY:
mutex_lock(&indio_dev->mlock);
/* Need both the number of taps and the sampling frequency */
ret = adis_read_reg_16(&st->adis,
ADIS16400_SENS_AVG,
&val16);
if (ret < 0) {
mutex_unlock(&indio_dev->mlock);
return ret;
}
ret = st->variant->get_freq(st);
if (ret >= 0) {
ret /= adis16400_3db_divisors[val16 & 0x07];
*val = ret / 1000;
*val2 = (ret % 1000) * 1000;
}
mutex_unlock(&indio_dev->mlock);
if (ret < 0)
return ret;
return IIO_VAL_INT_PLUS_MICRO;
default:
return -EINVAL;
}
}
#define ADIS16400_VOLTAGE_CHAN(addr, bits, name, si) { \
.type = IIO_VOLTAGE, \
.indexed = 1, \
.channel = 0, \
.extend_name = name, \
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | \
BIT(IIO_CHAN_INFO_SCALE), \
.address = (addr), \
.scan_index = (si), \
.scan_type = { \
.sign = 'u', \
.realbits = (bits), \
.storagebits = 16, \
.shift = 0, \
.endianness = IIO_BE, \
}, \
}
#define ADIS16400_SUPPLY_CHAN(addr, bits) \
ADIS16400_VOLTAGE_CHAN(addr, bits, "supply", ADIS16400_SCAN_SUPPLY)
#define ADIS16400_AUX_ADC_CHAN(addr, bits) \
ADIS16400_VOLTAGE_CHAN(addr, bits, NULL, ADIS16400_SCAN_ADC)
#define ADIS16400_GYRO_CHAN(mod, addr, bits) { \
.type = IIO_ANGL_VEL, \
.modified = 1, \
.channel2 = IIO_MOD_ ## mod, \
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | \
BIT(IIO_CHAN_INFO_CALIBBIAS), \
.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE) | \
BIT(IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY), \
.address = addr, \
.scan_index = ADIS16400_SCAN_GYRO_ ## mod, \
.scan_type = { \
.sign = 's', \
.realbits = (bits), \
.storagebits = 16, \
.shift = 0, \
.endianness = IIO_BE, \
}, \
}
#define ADIS16400_ACCEL_CHAN(mod, addr, bits) { \
.type = IIO_ACCEL, \
.modified = 1, \
.channel2 = IIO_MOD_ ## mod, \
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | \
BIT(IIO_CHAN_INFO_CALIBBIAS), \
.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE) | \
BIT(IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY), \
.address = (addr), \
.scan_index = ADIS16400_SCAN_ACC_ ## mod, \
.scan_type = { \
.sign = 's', \
.realbits = (bits), \
.storagebits = 16, \
.shift = 0, \
.endianness = IIO_BE, \
}, \
}
#define ADIS16400_MAGN_CHAN(mod, addr, bits) { \
.type = IIO_MAGN, \
.modified = 1, \
.channel2 = IIO_MOD_ ## mod, \
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW), \
.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE) | \
BIT(IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY), \
.address = (addr), \
.scan_index = ADIS16400_SCAN_MAGN_ ## mod, \
.scan_type = { \
.sign = 's', \
.realbits = (bits), \
.storagebits = 16, \
.shift = 0, \
.endianness = IIO_BE, \
}, \
}
#define ADIS16400_MOD_TEMP_NAME_X "x"
#define ADIS16400_MOD_TEMP_NAME_Y "y"
#define ADIS16400_MOD_TEMP_NAME_Z "z"
#define ADIS16400_MOD_TEMP_CHAN(mod, addr, bits) { \
.type = IIO_TEMP, \
.indexed = 1, \
.channel = 0, \
.extend_name = ADIS16400_MOD_TEMP_NAME_ ## mod, \
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | \
BIT(IIO_CHAN_INFO_OFFSET) | \
BIT(IIO_CHAN_INFO_SCALE), \
.info_mask_shared_by_type = \
BIT(IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY), \
.address = (addr), \
.scan_index = ADIS16350_SCAN_TEMP_ ## mod, \
.scan_type = { \
.sign = 's', \
.realbits = (bits), \
.storagebits = 16, \
.shift = 0, \
.endianness = IIO_BE, \
}, \
}
#define ADIS16400_TEMP_CHAN(addr, bits) { \
.type = IIO_TEMP, \
.indexed = 1, \
.channel = 0, \
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | \
BIT(IIO_CHAN_INFO_OFFSET) | \
BIT(IIO_CHAN_INFO_SCALE), \
.address = (addr), \
.scan_index = ADIS16350_SCAN_TEMP_X, \
.scan_type = { \
.sign = 's', \
.realbits = (bits), \
.storagebits = 16, \
.shift = 0, \
.endianness = IIO_BE, \
}, \
}
#define ADIS16400_INCLI_CHAN(mod, addr, bits) { \
.type = IIO_INCLI, \
.modified = 1, \
.channel2 = IIO_MOD_ ## mod, \
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW), \
.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE), \
.address = (addr), \
.scan_index = ADIS16300_SCAN_INCLI_ ## mod, \
.scan_type = { \
.sign = 's', \
.realbits = (bits), \
.storagebits = 16, \
.shift = 0, \
.endianness = IIO_BE, \
}, \
}
static const struct iio_chan_spec adis16400_channels[] = {
ADIS16400_SUPPLY_CHAN(ADIS16400_SUPPLY_OUT, 14),
ADIS16400_GYRO_CHAN(X, ADIS16400_XGYRO_OUT, 14),
ADIS16400_GYRO_CHAN(Y, ADIS16400_YGYRO_OUT, 14),
ADIS16400_GYRO_CHAN(Z, ADIS16400_ZGYRO_OUT, 14),
ADIS16400_ACCEL_CHAN(X, ADIS16400_XACCL_OUT, 14),
ADIS16400_ACCEL_CHAN(Y, ADIS16400_YACCL_OUT, 14),
ADIS16400_ACCEL_CHAN(Z, ADIS16400_ZACCL_OUT, 14),
ADIS16400_MAGN_CHAN(X, ADIS16400_XMAGN_OUT, 14),
ADIS16400_MAGN_CHAN(Y, ADIS16400_YMAGN_OUT, 14),
ADIS16400_MAGN_CHAN(Z, ADIS16400_ZMAGN_OUT, 14),
ADIS16400_TEMP_CHAN(ADIS16400_TEMP_OUT, 12),
ADIS16400_AUX_ADC_CHAN(ADIS16400_AUX_ADC, 12),
IIO_CHAN_SOFT_TIMESTAMP(12)
};
static const struct iio_chan_spec adis16448_channels[] = {
ADIS16400_GYRO_CHAN(X, ADIS16400_XGYRO_OUT, 16),
ADIS16400_GYRO_CHAN(Y, ADIS16400_YGYRO_OUT, 16),
ADIS16400_GYRO_CHAN(Z, ADIS16400_ZGYRO_OUT, 16),
ADIS16400_ACCEL_CHAN(X, ADIS16400_XACCL_OUT, 16),
ADIS16400_ACCEL_CHAN(Y, ADIS16400_YACCL_OUT, 16),
ADIS16400_ACCEL_CHAN(Z, ADIS16400_ZACCL_OUT, 16),
ADIS16400_MAGN_CHAN(X, ADIS16400_XMAGN_OUT, 16),
ADIS16400_MAGN_CHAN(Y, ADIS16400_YMAGN_OUT, 16),
ADIS16400_MAGN_CHAN(Z, ADIS16400_ZMAGN_OUT, 16),
{
.type = IIO_PRESSURE,
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE),
.address = ADIS16448_BARO_OUT,
.scan_index = ADIS16400_SCAN_BARO,
.scan_type = {
.sign = 's',
.realbits = 16,
.storagebits = 16,
.endianness = IIO_BE,
},
},
ADIS16400_TEMP_CHAN(ADIS16448_TEMP_OUT, 12),
IIO_CHAN_SOFT_TIMESTAMP(11)
};
static const struct iio_chan_spec adis16350_channels[] = {
ADIS16400_SUPPLY_CHAN(ADIS16400_SUPPLY_OUT, 12),
ADIS16400_GYRO_CHAN(X, ADIS16400_XGYRO_OUT, 14),
ADIS16400_GYRO_CHAN(Y, ADIS16400_YGYRO_OUT, 14),
ADIS16400_GYRO_CHAN(Z, ADIS16400_ZGYRO_OUT, 14),
ADIS16400_ACCEL_CHAN(X, ADIS16400_XACCL_OUT, 14),
ADIS16400_ACCEL_CHAN(Y, ADIS16400_YACCL_OUT, 14),
ADIS16400_ACCEL_CHAN(Z, ADIS16400_ZACCL_OUT, 14),
ADIS16400_MAGN_CHAN(X, ADIS16400_XMAGN_OUT, 14),
ADIS16400_MAGN_CHAN(Y, ADIS16400_YMAGN_OUT, 14),
ADIS16400_MAGN_CHAN(Z, ADIS16400_ZMAGN_OUT, 14),
ADIS16400_AUX_ADC_CHAN(ADIS16300_AUX_ADC, 12),
ADIS16400_MOD_TEMP_CHAN(X, ADIS16350_XTEMP_OUT, 12),
ADIS16400_MOD_TEMP_CHAN(Y, ADIS16350_YTEMP_OUT, 12),
ADIS16400_MOD_TEMP_CHAN(Z, ADIS16350_ZTEMP_OUT, 12),
IIO_CHAN_SOFT_TIMESTAMP(11)
};
static const struct iio_chan_spec adis16300_channels[] = {
ADIS16400_SUPPLY_CHAN(ADIS16400_SUPPLY_OUT, 12),
ADIS16400_GYRO_CHAN(X, ADIS16400_XGYRO_OUT, 14),
ADIS16400_ACCEL_CHAN(X, ADIS16400_XACCL_OUT, 14),
ADIS16400_ACCEL_CHAN(Y, ADIS16400_YACCL_OUT, 14),
ADIS16400_ACCEL_CHAN(Z, ADIS16400_ZACCL_OUT, 14),
ADIS16400_TEMP_CHAN(ADIS16350_XTEMP_OUT, 12),
ADIS16400_AUX_ADC_CHAN(ADIS16300_AUX_ADC, 12),
ADIS16400_INCLI_CHAN(X, ADIS16300_PITCH_OUT, 13),
ADIS16400_INCLI_CHAN(Y, ADIS16300_ROLL_OUT, 13),
IIO_CHAN_SOFT_TIMESTAMP(14)
};
static const struct iio_chan_spec adis16334_channels[] = {
ADIS16400_GYRO_CHAN(X, ADIS16400_XGYRO_OUT, 14),
ADIS16400_GYRO_CHAN(Y, ADIS16400_YGYRO_OUT, 14),
ADIS16400_GYRO_CHAN(Z, ADIS16400_ZGYRO_OUT, 14),
ADIS16400_ACCEL_CHAN(X, ADIS16400_XACCL_OUT, 14),
ADIS16400_ACCEL_CHAN(Y, ADIS16400_YACCL_OUT, 14),
ADIS16400_ACCEL_CHAN(Z, ADIS16400_ZACCL_OUT, 14),
ADIS16400_TEMP_CHAN(ADIS16350_XTEMP_OUT, 12),
IIO_CHAN_SOFT_TIMESTAMP(8)
};
static struct attribute *adis16400_attributes[] = {
&iio_dev_attr_sampling_frequency.dev_attr.attr,
NULL
};
static const struct attribute_group adis16400_attribute_group = {
.attrs = adis16400_attributes,
};
static struct adis16400_chip_info adis16400_chips[] = {
[ADIS16300] = {
.channels = adis16300_channels,
.num_channels = ARRAY_SIZE(adis16300_channels),
.flags = ADIS16400_HAS_SLOW_MODE,
.gyro_scale_micro = IIO_DEGREE_TO_RAD(50000), /* 0.05 deg/s */
.accel_scale_micro = 5884,
.temp_scale_nano = 140000000, /* 0.14 C */
.temp_offset = 25000000 / 140000, /* 25 C = 0x00 */
.set_freq = adis16400_set_freq,
.get_freq = adis16400_get_freq,
},
[ADIS16334] = {
.channels = adis16334_channels,
.num_channels = ARRAY_SIZE(adis16334_channels),
.flags = ADIS16400_HAS_PROD_ID | ADIS16400_NO_BURST |
ADIS16400_HAS_SERIAL_NUMBER,
.gyro_scale_micro = IIO_DEGREE_TO_RAD(50000), /* 0.05 deg/s */
.accel_scale_micro = IIO_G_TO_M_S_2(1000), /* 1 mg */
.temp_scale_nano = 67850000, /* 0.06785 C */
.temp_offset = 25000000 / 67850, /* 25 C = 0x00 */
.set_freq = adis16334_set_freq,
.get_freq = adis16334_get_freq,
},
[ADIS16350] = {
.channels = adis16350_channels,
.num_channels = ARRAY_SIZE(adis16350_channels),
.gyro_scale_micro = IIO_DEGREE_TO_RAD(73260), /* 0.07326 deg/s */
.accel_scale_micro = IIO_G_TO_M_S_2(2522), /* 0.002522 g */
.temp_scale_nano = 145300000, /* 0.1453 C */
.temp_offset = 25000000 / 145300, /* 25 C = 0x00 */
.flags = ADIS16400_NO_BURST | ADIS16400_HAS_SLOW_MODE,
.set_freq = adis16400_set_freq,
.get_freq = adis16400_get_freq,
},
[ADIS16360] = {
.channels = adis16350_channels,
.num_channels = ARRAY_SIZE(adis16350_channels),
.flags = ADIS16400_HAS_PROD_ID | ADIS16400_HAS_SLOW_MODE |
ADIS16400_HAS_SERIAL_NUMBER,
.gyro_scale_micro = IIO_DEGREE_TO_RAD(50000), /* 0.05 deg/s */
.accel_scale_micro = IIO_G_TO_M_S_2(3333), /* 3.333 mg */
.temp_scale_nano = 136000000, /* 0.136 C */
.temp_offset = 25000000 / 136000, /* 25 C = 0x00 */
.set_freq = adis16400_set_freq,
.get_freq = adis16400_get_freq,
},
[ADIS16362] = {
.channels = adis16350_channels,
.num_channels = ARRAY_SIZE(adis16350_channels),
.flags = ADIS16400_HAS_PROD_ID | ADIS16400_HAS_SLOW_MODE |
ADIS16400_HAS_SERIAL_NUMBER,
.gyro_scale_micro = IIO_DEGREE_TO_RAD(50000), /* 0.05 deg/s */
.accel_scale_micro = IIO_G_TO_M_S_2(333), /* 0.333 mg */
.temp_scale_nano = 136000000, /* 0.136 C */
.temp_offset = 25000000 / 136000, /* 25 C = 0x00 */
.set_freq = adis16400_set_freq,
.get_freq = adis16400_get_freq,
},
[ADIS16364] = {
.channels = adis16350_channels,
.num_channels = ARRAY_SIZE(adis16350_channels),
.flags = ADIS16400_HAS_PROD_ID | ADIS16400_HAS_SLOW_MODE |
ADIS16400_HAS_SERIAL_NUMBER,
.gyro_scale_micro = IIO_DEGREE_TO_RAD(50000), /* 0.05 deg/s */
.accel_scale_micro = IIO_G_TO_M_S_2(1000), /* 1 mg */
.temp_scale_nano = 136000000, /* 0.136 C */
.temp_offset = 25000000 / 136000, /* 25 C = 0x00 */
.set_freq = adis16400_set_freq,
.get_freq = adis16400_get_freq,
},
[ADIS16400] = {
.channels = adis16400_channels,
.num_channels = ARRAY_SIZE(adis16400_channels),
.flags = ADIS16400_HAS_PROD_ID | ADIS16400_HAS_SLOW_MODE,
.gyro_scale_micro = IIO_DEGREE_TO_RAD(50000), /* 0.05 deg/s */
.accel_scale_micro = IIO_G_TO_M_S_2(3333), /* 3.333 mg */
.temp_scale_nano = 140000000, /* 0.14 C */
.temp_offset = 25000000 / 140000, /* 25 C = 0x00 */
.set_freq = adis16400_set_freq,
.get_freq = adis16400_get_freq,
},
[ADIS16448] = {
.channels = adis16448_channels,
.num_channels = ARRAY_SIZE(adis16448_channels),
.flags = ADIS16400_HAS_PROD_ID |
ADIS16400_HAS_SERIAL_NUMBER,
.gyro_scale_micro = IIO_DEGREE_TO_RAD(10000), /* 0.01 deg/s */
.accel_scale_micro = IIO_G_TO_M_S_2(833), /* 1/1200 g */
.temp_scale_nano = 73860000, /* 0.07386 C */
.temp_offset = 31000000 / 73860, /* 31 C = 0x00 */
.set_freq = adis16334_set_freq,
.get_freq = adis16334_get_freq,
}
};
static const struct iio_info adis16400_info = {
.driver_module = THIS_MODULE,
.read_raw = &adis16400_read_raw,
.write_raw = &adis16400_write_raw,
.attrs = &adis16400_attribute_group,
.update_scan_mode = adis16400_update_scan_mode,
.debugfs_reg_access = adis_debugfs_reg_access,
};
static const unsigned long adis16400_burst_scan_mask[] = {
~0UL,
0,
};
static const char * const adis16400_status_error_msgs[] = {
[ADIS16400_DIAG_STAT_ZACCL_FAIL] = "Z-axis accelerometer self-test failure",
[ADIS16400_DIAG_STAT_YACCL_FAIL] = "Y-axis accelerometer self-test failure",
[ADIS16400_DIAG_STAT_XACCL_FAIL] = "X-axis accelerometer self-test failure",
[ADIS16400_DIAG_STAT_XGYRO_FAIL] = "X-axis gyroscope self-test failure",
[ADIS16400_DIAG_STAT_YGYRO_FAIL] = "Y-axis gyroscope self-test failure",
[ADIS16400_DIAG_STAT_ZGYRO_FAIL] = "Z-axis gyroscope self-test failure",
[ADIS16400_DIAG_STAT_ALARM2] = "Alarm 2 active",
[ADIS16400_DIAG_STAT_ALARM1] = "Alarm 1 active",
[ADIS16400_DIAG_STAT_FLASH_CHK] = "Flash checksum error",
[ADIS16400_DIAG_STAT_SELF_TEST] = "Self test error",
[ADIS16400_DIAG_STAT_OVERFLOW] = "Sensor overrange",
[ADIS16400_DIAG_STAT_SPI_FAIL] = "SPI failure",
[ADIS16400_DIAG_STAT_FLASH_UPT] = "Flash update failed",
[ADIS16400_DIAG_STAT_POWER_HIGH] = "Power supply above 5.25V",
[ADIS16400_DIAG_STAT_POWER_LOW] = "Power supply below 4.75V",
};
static const struct adis_data adis16400_data = {
.msc_ctrl_reg = ADIS16400_MSC_CTRL,
.glob_cmd_reg = ADIS16400_GLOB_CMD,
.diag_stat_reg = ADIS16400_DIAG_STAT,
.read_delay = 50,
.write_delay = 50,
.self_test_mask = ADIS16400_MSC_CTRL_MEM_TEST,
.startup_delay = ADIS16400_STARTUP_DELAY,
.status_error_msgs = adis16400_status_error_msgs,
.status_error_mask = BIT(ADIS16400_DIAG_STAT_ZACCL_FAIL) |
BIT(ADIS16400_DIAG_STAT_YACCL_FAIL) |
BIT(ADIS16400_DIAG_STAT_XACCL_FAIL) |
BIT(ADIS16400_DIAG_STAT_XGYRO_FAIL) |
BIT(ADIS16400_DIAG_STAT_YGYRO_FAIL) |
BIT(ADIS16400_DIAG_STAT_ZGYRO_FAIL) |
BIT(ADIS16400_DIAG_STAT_ALARM2) |
BIT(ADIS16400_DIAG_STAT_ALARM1) |
BIT(ADIS16400_DIAG_STAT_FLASH_CHK) |
BIT(ADIS16400_DIAG_STAT_SELF_TEST) |
BIT(ADIS16400_DIAG_STAT_OVERFLOW) |
BIT(ADIS16400_DIAG_STAT_SPI_FAIL) |
BIT(ADIS16400_DIAG_STAT_FLASH_UPT) |
BIT(ADIS16400_DIAG_STAT_POWER_HIGH) |
BIT(ADIS16400_DIAG_STAT_POWER_LOW),
};
static int adis16400_probe(struct spi_device *spi)
{
struct adis16400_state *st;
struct iio_dev *indio_dev;
int ret;
indio_dev = devm_iio_device_alloc(&spi->dev, sizeof(*st));
if (indio_dev == NULL)
return -ENOMEM;
st = iio_priv(indio_dev);
/* this is only used for removal purposes */
spi_set_drvdata(spi, indio_dev);
/* setup the industrialio driver allocated elements */
st->variant = &adis16400_chips[spi_get_device_id(spi)->driver_data];
indio_dev->dev.parent = &spi->dev;
indio_dev->name = spi_get_device_id(spi)->name;
indio_dev->channels = st->variant->channels;
indio_dev->num_channels = st->variant->num_channels;
indio_dev->info = &adis16400_info;
indio_dev->modes = INDIO_DIRECT_MODE;
if (!(st->variant->flags & ADIS16400_NO_BURST))
indio_dev->available_scan_masks = adis16400_burst_scan_mask;
ret = adis_init(&st->adis, indio_dev, spi, &adis16400_data);
if (ret)
return ret;
ret = adis_setup_buffer_and_trigger(&st->adis, indio_dev,
adis16400_trigger_handler);
if (ret)
return ret;
/* Get the device into a sane initial state */
ret = adis16400_initial_setup(indio_dev);
if (ret)
goto error_cleanup_buffer;
ret = iio_device_register(indio_dev);
if (ret)
goto error_cleanup_buffer;
adis16400_debugfs_init(indio_dev);
return 0;
error_cleanup_buffer:
adis_cleanup_buffer_and_trigger(&st->adis, indio_dev);
return ret;
}
static int adis16400_remove(struct spi_device *spi)
{
struct iio_dev *indio_dev = spi_get_drvdata(spi);
struct adis16400_state *st = iio_priv(indio_dev);
iio_device_unregister(indio_dev);
adis16400_stop_device(indio_dev);
adis_cleanup_buffer_and_trigger(&st->adis, indio_dev);
return 0;
}
static const struct spi_device_id adis16400_id[] = {
{"adis16300", ADIS16300},
{"adis16334", ADIS16334},
{"adis16350", ADIS16350},
{"adis16354", ADIS16350},
{"adis16355", ADIS16350},
{"adis16360", ADIS16360},
{"adis16362", ADIS16362},
{"adis16364", ADIS16364},
{"adis16365", ADIS16360},
{"adis16400", ADIS16400},
{"adis16405", ADIS16400},
{"adis16448", ADIS16448},
{}
};
MODULE_DEVICE_TABLE(spi, adis16400_id);
static struct spi_driver adis16400_driver = {
.driver = {
.name = "adis16400",
.owner = THIS_MODULE,
},
.id_table = adis16400_id,
.probe = adis16400_probe,
.remove = adis16400_remove,
};
module_spi_driver(adis16400_driver);
MODULE_AUTHOR("Manuel Stahl <manuel.stahl@iis.fraunhofer.de>");
MODULE_DESCRIPTION("Analog Devices ADIS16400/5 IMU SPI driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
vm03/android_kernel_lge_msm8226 | mm/filemap.c | 55 | 71061 | /*
* linux/mm/filemap.c
*
* Copyright (C) 1994-1999 Linus Torvalds
*/
/*
* This file handles the generic file mmap semantics used by
* most "normal" filesystems (but you don't /have/ to use this:
* the NFS filesystem used to do this differently, for example)
*/
#include <linux/export.h>
#include <linux/compiler.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/aio.h>
#include <linux/capability.h>
#include <linux/kernel_stat.h>
#include <linux/gfp.h>
#include <linux/mm.h>
#include <linux/swap.h>
#include <linux/mman.h>
#include <linux/pagemap.h>
#include <linux/file.h>
#include <linux/uio.h>
#include <linux/hash.h>
#include <linux/writeback.h>
#include <linux/backing-dev.h>
#include <linux/pagevec.h>
#include <linux/blkdev.h>
#include <linux/security.h>
#include <linux/syscalls.h>
#include <linux/cpuset.h>
#include <linux/hardirq.h> /* for BUG_ON(!in_atomic()) only */
#include <linux/memcontrol.h>
#include <linux/cleancache.h>
#include "internal.h"
#include "../fs/sreadahead_prof.h"
/*
* FIXME: remove all knowledge of the buffer layer from the core VM
*/
#include <linux/buffer_head.h> /* for try_to_free_buffers */
#include <asm/mman.h>
/*
* Shared mappings implemented 30.11.1994. It's not fully working yet,
* though.
*
* Shared mappings now work. 15.8.1995 Bruno.
*
* finished 'unifying' the page and buffer cache and SMP-threaded the
* page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
*
* SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
*/
/*
* Lock ordering:
*
* ->i_mmap_mutex (truncate_pagecache)
* ->private_lock (__free_pte->__set_page_dirty_buffers)
* ->swap_lock (exclusive_swap_page, others)
* ->mapping->tree_lock
*
* ->i_mutex
* ->i_mmap_mutex (truncate->unmap_mapping_range)
*
* ->mmap_sem
* ->i_mmap_mutex
* ->page_table_lock or pte_lock (various, mainly in memory.c)
* ->mapping->tree_lock (arch-dependent flush_dcache_mmap_lock)
*
* ->mmap_sem
* ->lock_page (access_process_vm)
*
* ->i_mutex (generic_file_buffered_write)
* ->mmap_sem (fault_in_pages_readable->do_page_fault)
*
* bdi->wb.list_lock
* sb_lock (fs/fs-writeback.c)
* ->mapping->tree_lock (__sync_single_inode)
*
* ->i_mmap_mutex
* ->anon_vma.lock (vma_adjust)
*
* ->anon_vma.lock
* ->page_table_lock or pte_lock (anon_vma_prepare and various)
*
* ->page_table_lock or pte_lock
* ->swap_lock (try_to_unmap_one)
* ->private_lock (try_to_unmap_one)
* ->tree_lock (try_to_unmap_one)
* ->zone.lru_lock (follow_page->mark_page_accessed)
* ->zone.lru_lock (check_pte_range->isolate_lru_page)
* ->private_lock (page_remove_rmap->set_page_dirty)
* ->tree_lock (page_remove_rmap->set_page_dirty)
* bdi.wb->list_lock (page_remove_rmap->set_page_dirty)
* ->inode->i_lock (page_remove_rmap->set_page_dirty)
* bdi.wb->list_lock (zap_pte_range->set_page_dirty)
* ->inode->i_lock (zap_pte_range->set_page_dirty)
* ->private_lock (zap_pte_range->__set_page_dirty_buffers)
*
* ->i_mmap_mutex
* ->tasklist_lock (memory_failure, collect_procs_ao)
*/
/*
* Delete a page from the page cache and free it. Caller has to make
* sure the page is locked and that nobody else uses it - or that usage
* is safe. The caller must hold the mapping's tree_lock.
*/
void __delete_from_page_cache(struct page *page)
{
struct address_space *mapping = page->mapping;
/*
* if we're uptodate, flush out into the cleancache, otherwise
* invalidate any existing cleancache entries. We can't leave
* stale data around in the cleancache once our page is gone
*/
if (PageUptodate(page) && PageMappedToDisk(page))
cleancache_put_page(page);
else
cleancache_invalidate_page(mapping, page);
radix_tree_delete(&mapping->page_tree, page->index);
page->mapping = NULL;
/* Leave page->index set: truncation lookup relies upon it */
mapping->nrpages--;
__dec_zone_page_state(page, NR_FILE_PAGES);
if (PageSwapBacked(page))
__dec_zone_page_state(page, NR_SHMEM);
BUG_ON(page_mapped(page));
/*
* Some filesystems seem to re-dirty the page even after
* the VM has canceled the dirty bit (eg ext3 journaling).
*
* Fix it up by doing a final dirty accounting check after
* having removed the page entirely.
*/
if (PageDirty(page) && mapping_cap_account_dirty(mapping)) {
dec_zone_page_state(page, NR_FILE_DIRTY);
dec_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE);
}
}
/**
* delete_from_page_cache - delete page from page cache
* @page: the page which the kernel is trying to remove from page cache
*
* This must be called only on pages that have been verified to be in the page
* cache and locked. It will never put the page into the free list, the caller
* has a reference on the page.
*/
void delete_from_page_cache(struct page *page)
{
struct address_space *mapping = page->mapping;
void (*freepage)(struct page *);
BUG_ON(!PageLocked(page));
freepage = mapping->a_ops->freepage;
spin_lock_irq(&mapping->tree_lock);
__delete_from_page_cache(page);
spin_unlock_irq(&mapping->tree_lock);
mem_cgroup_uncharge_cache_page(page);
if (freepage)
freepage(page);
page_cache_release(page);
}
EXPORT_SYMBOL(delete_from_page_cache);
static int sleep_on_page(void *word)
{
io_schedule();
return 0;
}
static int sleep_on_page_killable(void *word)
{
sleep_on_page(word);
return fatal_signal_pending(current) ? -EINTR : 0;
}
/**
* __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
* @mapping: address space structure to write
* @start: offset in bytes where the range starts
* @end: offset in bytes where the range ends (inclusive)
* @sync_mode: enable synchronous operation
*
* Start writeback against all of a mapping's dirty pages that lie
* within the byte offsets <start, end> inclusive.
*
* If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
* opposed to a regular memory cleansing writeback. The difference between
* these two operations is that if a dirty page/buffer is encountered, it must
* be waited upon, and not just skipped over.
*/
int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
loff_t end, int sync_mode)
{
int ret;
struct writeback_control wbc = {
.sync_mode = sync_mode,
.nr_to_write = LONG_MAX,
.range_start = start,
.range_end = end,
};
if (!mapping_cap_writeback_dirty(mapping))
return 0;
ret = do_writepages(mapping, &wbc);
return ret;
}
static inline int __filemap_fdatawrite(struct address_space *mapping,
int sync_mode)
{
return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
}
int filemap_fdatawrite(struct address_space *mapping)
{
return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
}
EXPORT_SYMBOL(filemap_fdatawrite);
int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
loff_t end)
{
return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
}
EXPORT_SYMBOL(filemap_fdatawrite_range);
/**
* filemap_flush - mostly a non-blocking flush
* @mapping: target address_space
*
* This is a mostly non-blocking flush. Not suitable for data-integrity
* purposes - I/O may not be started against all dirty pages.
*/
int filemap_flush(struct address_space *mapping)
{
return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
}
EXPORT_SYMBOL(filemap_flush);
/**
* filemap_fdatawait_range - wait for writeback to complete
* @mapping: address space structure to wait for
* @start_byte: offset in bytes where the range starts
* @end_byte: offset in bytes where the range ends (inclusive)
*
* Walk the list of under-writeback pages of the given address space
* in the given range and wait for all of them.
*/
int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
loff_t end_byte)
{
pgoff_t index = start_byte >> PAGE_CACHE_SHIFT;
pgoff_t end = end_byte >> PAGE_CACHE_SHIFT;
struct pagevec pvec;
int nr_pages;
int ret = 0;
if (end_byte < start_byte)
return 0;
pagevec_init(&pvec, 0);
while ((index <= end) &&
(nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
PAGECACHE_TAG_WRITEBACK,
min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1)) != 0) {
unsigned i;
for (i = 0; i < nr_pages; i++) {
struct page *page = pvec.pages[i];
/* until radix tree lookup accepts end_index */
if (page->index > end)
continue;
wait_on_page_writeback(page);
if (TestClearPageError(page))
ret = -EIO;
}
pagevec_release(&pvec);
cond_resched();
}
/* Check for outstanding write errors */
if (test_and_clear_bit(AS_ENOSPC, &mapping->flags))
ret = -ENOSPC;
if (test_and_clear_bit(AS_EIO, &mapping->flags))
ret = -EIO;
return ret;
}
EXPORT_SYMBOL(filemap_fdatawait_range);
/**
* filemap_fdatawait - wait for all under-writeback pages to complete
* @mapping: address space structure to wait for
*
* Walk the list of under-writeback pages of the given address space
* and wait for all of them.
*/
int filemap_fdatawait(struct address_space *mapping)
{
loff_t i_size = i_size_read(mapping->host);
if (i_size == 0)
return 0;
return filemap_fdatawait_range(mapping, 0, i_size - 1);
}
EXPORT_SYMBOL(filemap_fdatawait);
int filemap_write_and_wait(struct address_space *mapping)
{
int err = 0;
if (mapping->nrpages) {
err = filemap_fdatawrite(mapping);
/*
* Even if the above returned error, the pages may be
* written partially (e.g. -ENOSPC), so we wait for it.
* But the -EIO is special case, it may indicate the worst
* thing (e.g. bug) happened, so we avoid waiting for it.
*/
if (err != -EIO) {
int err2 = filemap_fdatawait(mapping);
if (!err)
err = err2;
}
}
return err;
}
EXPORT_SYMBOL(filemap_write_and_wait);
/**
* filemap_write_and_wait_range - write out & wait on a file range
* @mapping: the address_space for the pages
* @lstart: offset in bytes where the range starts
* @lend: offset in bytes where the range ends (inclusive)
*
* Write out and wait upon file offsets lstart->lend, inclusive.
*
* Note that `lend' is inclusive (describes the last byte to be written) so
* that this function can be used to write to the very end-of-file (end = -1).
*/
int filemap_write_and_wait_range(struct address_space *mapping,
loff_t lstart, loff_t lend)
{
int err = 0;
if (mapping->nrpages) {
err = __filemap_fdatawrite_range(mapping, lstart, lend,
WB_SYNC_ALL);
/* See comment of filemap_write_and_wait() */
if (err != -EIO) {
int err2 = filemap_fdatawait_range(mapping,
lstart, lend);
if (!err)
err = err2;
}
}
return err;
}
EXPORT_SYMBOL(filemap_write_and_wait_range);
/**
* replace_page_cache_page - replace a pagecache page with a new one
* @old: page to be replaced
* @new: page to replace with
* @gfp_mask: allocation mode
*
* This function replaces a page in the pagecache with a new one. On
* success it acquires the pagecache reference for the new page and
* drops it for the old page. Both the old and new pages must be
* locked. This function does not add the new page to the LRU, the
* caller must do that.
*
* The remove + add is atomic. The only way this function can fail is
* memory allocation failure.
*/
int replace_page_cache_page(struct page *old, struct page *new, gfp_t gfp_mask)
{
int error;
VM_BUG_ON(!PageLocked(old));
VM_BUG_ON(!PageLocked(new));
VM_BUG_ON(new->mapping);
error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);
if (!error) {
struct address_space *mapping = old->mapping;
void (*freepage)(struct page *);
pgoff_t offset = old->index;
freepage = mapping->a_ops->freepage;
page_cache_get(new);
new->mapping = mapping;
new->index = offset;
spin_lock_irq(&mapping->tree_lock);
__delete_from_page_cache(old);
error = radix_tree_insert(&mapping->page_tree, offset, new);
BUG_ON(error);
mapping->nrpages++;
__inc_zone_page_state(new, NR_FILE_PAGES);
if (PageSwapBacked(new))
__inc_zone_page_state(new, NR_SHMEM);
spin_unlock_irq(&mapping->tree_lock);
/* mem_cgroup codes must not be called under tree_lock */
mem_cgroup_replace_page_cache(old, new);
radix_tree_preload_end();
if (freepage)
freepage(old);
page_cache_release(old);
}
return error;
}
EXPORT_SYMBOL_GPL(replace_page_cache_page);
/**
* add_to_page_cache_locked - add a locked page to the pagecache
* @page: page to add
* @mapping: the page's address_space
* @offset: page index
* @gfp_mask: page allocation mode
*
* This function is used to add a page to the pagecache. It must be locked.
* This function does not add the page to the LRU. The caller must do that.
*/
int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
pgoff_t offset, gfp_t gfp_mask)
{
int error;
VM_BUG_ON(!PageLocked(page));
VM_BUG_ON(PageSwapBacked(page));
error = mem_cgroup_cache_charge(page, current->mm,
gfp_mask & GFP_RECLAIM_MASK);
if (error)
goto out;
error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);
if (error == 0) {
page_cache_get(page);
page->mapping = mapping;
page->index = offset;
spin_lock_irq(&mapping->tree_lock);
error = radix_tree_insert(&mapping->page_tree, offset, page);
if (likely(!error)) {
mapping->nrpages++;
__inc_zone_page_state(page, NR_FILE_PAGES);
spin_unlock_irq(&mapping->tree_lock);
} else {
page->mapping = NULL;
/* Leave page->index set: truncation relies upon it */
spin_unlock_irq(&mapping->tree_lock);
mem_cgroup_uncharge_cache_page(page);
page_cache_release(page);
}
radix_tree_preload_end();
} else
mem_cgroup_uncharge_cache_page(page);
out:
return error;
}
EXPORT_SYMBOL(add_to_page_cache_locked);
int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
pgoff_t offset, gfp_t gfp_mask)
{
int ret;
ret = add_to_page_cache(page, mapping, offset, gfp_mask);
if (ret == 0)
lru_cache_add_file(page);
return ret;
}
EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
#ifdef CONFIG_NUMA
struct page *__page_cache_alloc(gfp_t gfp)
{
int n;
struct page *page;
if (cpuset_do_page_mem_spread()) {
unsigned int cpuset_mems_cookie;
do {
cpuset_mems_cookie = get_mems_allowed();
n = cpuset_mem_spread_node();
page = alloc_pages_exact_node(n, gfp, 0);
} while (!put_mems_allowed(cpuset_mems_cookie) && !page);
return page;
}
return alloc_pages(gfp, 0);
}
EXPORT_SYMBOL(__page_cache_alloc);
#endif
/*
* In order to wait for pages to become available there must be
* waitqueues associated with pages. By using a hash table of
* waitqueues where the bucket discipline is to maintain all
* waiters on the same queue and wake all when any of the pages
* become available, and for the woken contexts to check to be
* sure the appropriate page became available, this saves space
* at a cost of "thundering herd" phenomena during rare hash
* collisions.
*/
static wait_queue_head_t *page_waitqueue(struct page *page)
{
const struct zone *zone = page_zone(page);
return &zone->wait_table[hash_ptr(page, zone->wait_table_bits)];
}
static inline void wake_up_page(struct page *page, int bit)
{
__wake_up_bit(page_waitqueue(page), &page->flags, bit);
}
void wait_on_page_bit(struct page *page, int bit_nr)
{
DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
if (test_bit(bit_nr, &page->flags))
__wait_on_bit(page_waitqueue(page), &wait, sleep_on_page,
TASK_UNINTERRUPTIBLE);
}
EXPORT_SYMBOL(wait_on_page_bit);
int wait_on_page_bit_killable(struct page *page, int bit_nr)
{
DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
if (!test_bit(bit_nr, &page->flags))
return 0;
return __wait_on_bit(page_waitqueue(page), &wait,
sleep_on_page_killable, TASK_KILLABLE);
}
/**
* add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
* @page: Page defining the wait queue of interest
* @waiter: Waiter to add to the queue
*
* Add an arbitrary @waiter to the wait queue for the nominated @page.
*/
void add_page_wait_queue(struct page *page, wait_queue_t *waiter)
{
wait_queue_head_t *q = page_waitqueue(page);
unsigned long flags;
spin_lock_irqsave(&q->lock, flags);
__add_wait_queue(q, waiter);
spin_unlock_irqrestore(&q->lock, flags);
}
EXPORT_SYMBOL_GPL(add_page_wait_queue);
/**
* unlock_page - unlock a locked page
* @page: the page
*
* Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
* Also wakes sleepers in wait_on_page_writeback() because the wakeup
* mechananism between PageLocked pages and PageWriteback pages is shared.
* But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
*
* The mb is necessary to enforce ordering between the clear_bit and the read
* of the waitqueue (to avoid SMP races with a parallel wait_on_page_locked()).
*/
void unlock_page(struct page *page)
{
VM_BUG_ON(!PageLocked(page));
clear_bit_unlock(PG_locked, &page->flags);
smp_mb__after_clear_bit();
wake_up_page(page, PG_locked);
}
EXPORT_SYMBOL(unlock_page);
/**
* end_page_writeback - end writeback against a page
* @page: the page
*/
void end_page_writeback(struct page *page)
{
if (TestClearPageReclaim(page))
rotate_reclaimable_page(page);
if (!test_clear_page_writeback(page))
BUG();
smp_mb__after_clear_bit();
wake_up_page(page, PG_writeback);
}
EXPORT_SYMBOL(end_page_writeback);
/**
* __lock_page - get a lock on the page, assuming we need to sleep to get it
* @page: the page to lock
*/
void __lock_page(struct page *page)
{
DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
__wait_on_bit_lock(page_waitqueue(page), &wait, sleep_on_page,
TASK_UNINTERRUPTIBLE);
}
EXPORT_SYMBOL(__lock_page);
int __lock_page_killable(struct page *page)
{
DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
return __wait_on_bit_lock(page_waitqueue(page), &wait,
sleep_on_page_killable, TASK_KILLABLE);
}
EXPORT_SYMBOL_GPL(__lock_page_killable);
int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
unsigned int flags)
{
if (flags & FAULT_FLAG_ALLOW_RETRY) {
/*
* CAUTION! In this case, mmap_sem is not released
* even though return 0.
*/
if (flags & FAULT_FLAG_RETRY_NOWAIT)
return 0;
up_read(&mm->mmap_sem);
if (flags & FAULT_FLAG_KILLABLE)
wait_on_page_locked_killable(page);
else
wait_on_page_locked(page);
return 0;
} else {
if (flags & FAULT_FLAG_KILLABLE) {
int ret;
ret = __lock_page_killable(page);
if (ret) {
up_read(&mm->mmap_sem);
return 0;
}
} else
__lock_page(page);
return 1;
}
}
/**
* find_get_page - find and get a page reference
* @mapping: the address_space to search
* @offset: the page index
*
* Is there a pagecache struct page at the given (mapping, offset) tuple?
* If yes, increment its refcount and return it; if no, return NULL.
*/
struct page *find_get_page(struct address_space *mapping, pgoff_t offset)
{
void **pagep;
struct page *page;
rcu_read_lock();
repeat:
page = NULL;
pagep = radix_tree_lookup_slot(&mapping->page_tree, offset);
if (pagep) {
page = radix_tree_deref_slot(pagep);
if (unlikely(!page))
goto out;
if (radix_tree_exception(page)) {
if (radix_tree_deref_retry(page))
goto repeat;
/*
* Otherwise, shmem/tmpfs must be storing a swap entry
* here as an exceptional entry: so return it without
* attempting to raise page count.
*/
goto out;
}
if (!page_cache_get_speculative(page))
goto repeat;
/*
* Has the page moved?
* This is part of the lockless pagecache protocol. See
* include/linux/pagemap.h for details.
*/
if (unlikely(page != *pagep)) {
page_cache_release(page);
goto repeat;
}
}
out:
rcu_read_unlock();
return page;
}
EXPORT_SYMBOL(find_get_page);
/**
* find_lock_page - locate, pin and lock a pagecache page
* @mapping: the address_space to search
* @offset: the page index
*
* Locates the desired pagecache page, locks it, increments its reference
* count and returns its address.
*
* Returns zero if the page was not present. find_lock_page() may sleep.
*/
struct page *find_lock_page(struct address_space *mapping, pgoff_t offset)
{
struct page *page;
repeat:
page = find_get_page(mapping, offset);
if (page && !radix_tree_exception(page)) {
lock_page(page);
/* Has the page been truncated? */
if (unlikely(page->mapping != mapping)) {
unlock_page(page);
page_cache_release(page);
goto repeat;
}
VM_BUG_ON(page->index != offset);
}
return page;
}
EXPORT_SYMBOL(find_lock_page);
/**
* find_or_create_page - locate or add a pagecache page
* @mapping: the page's address_space
* @index: the page's index into the mapping
* @gfp_mask: page allocation mode
*
* Locates a page in the pagecache. If the page is not present, a new page
* is allocated using @gfp_mask and is added to the pagecache and to the VM's
* LRU list. The returned page is locked and has its reference count
* incremented.
*
* find_or_create_page() may sleep, even if @gfp_flags specifies an atomic
* allocation!
*
* find_or_create_page() returns the desired page's address, or zero on
* memory exhaustion.
*/
struct page *find_or_create_page(struct address_space *mapping,
pgoff_t index, gfp_t gfp_mask)
{
struct page *page;
int err;
repeat:
page = find_lock_page(mapping, index);
if (!page) {
page = __page_cache_alloc(gfp_mask);
if (!page)
return NULL;
/*
* We want a regular kernel memory (not highmem or DMA etc)
* allocation for the radix tree nodes, but we need to honour
* the context-specific requirements the caller has asked for.
* GFP_RECLAIM_MASK collects those requirements.
*/
err = add_to_page_cache_lru(page, mapping, index,
(gfp_mask & GFP_RECLAIM_MASK));
if (unlikely(err)) {
page_cache_release(page);
page = NULL;
if (err == -EEXIST)
goto repeat;
}
}
return page;
}
EXPORT_SYMBOL(find_or_create_page);
/**
* find_get_pages - gang pagecache lookup
* @mapping: The address_space to search
* @start: The starting page index
* @nr_pages: The maximum number of pages
* @pages: Where the resulting pages are placed
*
* find_get_pages() will search for and return a group of up to
* @nr_pages pages in the mapping. The pages are placed at @pages.
* find_get_pages() takes a reference against the returned pages.
*
* The search returns a group of mapping-contiguous pages with ascending
* indexes. There may be holes in the indices due to not-present pages.
*
* find_get_pages() returns the number of pages which were found.
*/
unsigned find_get_pages(struct address_space *mapping, pgoff_t start,
unsigned int nr_pages, struct page **pages)
{
struct radix_tree_iter iter;
void **slot;
unsigned ret = 0;
if (unlikely(!nr_pages))
return 0;
rcu_read_lock();
restart:
radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, start) {
struct page *page;
repeat:
page = radix_tree_deref_slot(slot);
if (unlikely(!page))
continue;
if (radix_tree_exception(page)) {
if (radix_tree_deref_retry(page)) {
/*
* Transient condition which can only trigger
* when entry at index 0 moves out of or back
* to root: none yet gotten, safe to restart.
*/
WARN_ON(iter.index);
goto restart;
}
/*
* Otherwise, shmem/tmpfs must be storing a swap entry
* here as an exceptional entry: so skip over it -
* we only reach this from invalidate_mapping_pages().
*/
continue;
}
if (!page_cache_get_speculative(page))
goto repeat;
/* Has the page moved? */
if (unlikely(page != *slot)) {
page_cache_release(page);
goto repeat;
}
pages[ret] = page;
if (++ret == nr_pages)
break;
}
rcu_read_unlock();
return ret;
}
/**
* find_get_pages_contig - gang contiguous pagecache lookup
* @mapping: The address_space to search
* @index: The starting page index
* @nr_pages: The maximum number of pages
* @pages: Where the resulting pages are placed
*
* find_get_pages_contig() works exactly like find_get_pages(), except
* that the returned number of pages are guaranteed to be contiguous.
*
* find_get_pages_contig() returns the number of pages which were found.
*/
unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
unsigned int nr_pages, struct page **pages)
{
struct radix_tree_iter iter;
void **slot;
unsigned int ret = 0;
if (unlikely(!nr_pages))
return 0;
rcu_read_lock();
restart:
radix_tree_for_each_contig(slot, &mapping->page_tree, &iter, index) {
struct page *page;
repeat:
page = radix_tree_deref_slot(slot);
/* The hole, there no reason to continue */
if (unlikely(!page))
break;
if (radix_tree_exception(page)) {
if (radix_tree_deref_retry(page)) {
/*
* Transient condition which can only trigger
* when entry at index 0 moves out of or back
* to root: none yet gotten, safe to restart.
*/
goto restart;
}
/*
* Otherwise, shmem/tmpfs must be storing a swap entry
* here as an exceptional entry: so stop looking for
* contiguous pages.
*/
break;
}
if (!page_cache_get_speculative(page))
goto repeat;
/* Has the page moved? */
if (unlikely(page != *slot)) {
page_cache_release(page);
goto repeat;
}
/*
* must check mapping and index after taking the ref.
* otherwise we can get both false positives and false
* negatives, which is just confusing to the caller.
*/
if (page->mapping == NULL || page->index != iter.index) {
page_cache_release(page);
break;
}
pages[ret] = page;
if (++ret == nr_pages)
break;
}
rcu_read_unlock();
return ret;
}
EXPORT_SYMBOL(find_get_pages_contig);
/**
* find_get_pages_tag - find and return pages that match @tag
* @mapping: the address_space to search
* @index: the starting page index
* @tag: the tag index
* @nr_pages: the maximum number of pages
* @pages: where the resulting pages are placed
*
* Like find_get_pages, except we only return pages which are tagged with
* @tag. We update @index to index the next page for the traversal.
*/
unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,
int tag, unsigned int nr_pages, struct page **pages)
{
struct radix_tree_iter iter;
void **slot;
unsigned ret = 0;
if (unlikely(!nr_pages))
return 0;
rcu_read_lock();
restart:
radix_tree_for_each_tagged(slot, &mapping->page_tree,
&iter, *index, tag) {
struct page *page;
repeat:
page = radix_tree_deref_slot(slot);
if (unlikely(!page))
continue;
if (radix_tree_exception(page)) {
if (radix_tree_deref_retry(page)) {
/*
* Transient condition which can only trigger
* when entry at index 0 moves out of or back
* to root: none yet gotten, safe to restart.
*/
goto restart;
}
/*
* This function is never used on a shmem/tmpfs
* mapping, so a swap entry won't be found here.
*/
BUG();
}
if (!page_cache_get_speculative(page))
goto repeat;
/* Has the page moved? */
if (unlikely(page != *slot)) {
page_cache_release(page);
goto repeat;
}
pages[ret] = page;
if (++ret == nr_pages)
break;
}
rcu_read_unlock();
if (ret)
*index = pages[ret - 1]->index + 1;
return ret;
}
EXPORT_SYMBOL(find_get_pages_tag);
/**
* grab_cache_page_nowait - returns locked page at given index in given cache
* @mapping: target address_space
* @index: the page index
*
* Same as grab_cache_page(), but do not wait if the page is unavailable.
* This is intended for speculative data generators, where the data can
* be regenerated if the page couldn't be grabbed. This routine should
* be safe to call while holding the lock for another page.
*
* Clear __GFP_FS when allocating the page to avoid recursion into the fs
* and deadlock against the caller's locked page.
*/
struct page *
grab_cache_page_nowait(struct address_space *mapping, pgoff_t index)
{
struct page *page = find_get_page(mapping, index);
if (page) {
if (trylock_page(page))
return page;
page_cache_release(page);
return NULL;
}
page = __page_cache_alloc(mapping_gfp_mask(mapping) & ~__GFP_FS);
if (page && add_to_page_cache_lru(page, mapping, index, GFP_NOFS)) {
page_cache_release(page);
page = NULL;
}
return page;
}
EXPORT_SYMBOL(grab_cache_page_nowait);
/*
* CD/DVDs are error prone. When a medium error occurs, the driver may fail
* a _large_ part of the i/o request. Imagine the worst scenario:
*
* ---R__________________________________________B__________
* ^ reading here ^ bad block(assume 4k)
*
* read(R) => miss => readahead(R...B) => media error => frustrating retries
* => failing the whole request => read(R) => read(R+1) =>
* readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
* readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
* readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
*
* It is going insane. Fix it by quickly scaling down the readahead size.
*/
static void shrink_readahead_size_eio(struct file *filp,
struct file_ra_state *ra)
{
ra->ra_pages /= 4;
}
/**
* do_generic_file_read - generic file read routine
* @filp: the file to read
* @ppos: current file position
* @desc: read_descriptor
* @actor: read method
*
* This is a generic file read routine, and uses the
* mapping->a_ops->readpage() function for the actual low-level stuff.
*
* This is really ugly. But the goto's actually try to clarify some
* of the logic when it comes to error handling etc.
*/
static void do_generic_file_read(struct file *filp, loff_t *ppos,
read_descriptor_t *desc, read_actor_t actor)
{
struct address_space *mapping = filp->f_mapping;
struct inode *inode = mapping->host;
struct file_ra_state *ra = &filp->f_ra;
pgoff_t index;
pgoff_t last_index;
pgoff_t prev_index;
unsigned long offset; /* offset into pagecache page */
unsigned int prev_offset;
int error;
index = *ppos >> PAGE_CACHE_SHIFT;
prev_index = ra->prev_pos >> PAGE_CACHE_SHIFT;
prev_offset = ra->prev_pos & (PAGE_CACHE_SIZE-1);
last_index = (*ppos + desc->count + PAGE_CACHE_SIZE-1) >> PAGE_CACHE_SHIFT;
offset = *ppos & ~PAGE_CACHE_MASK;
for (;;) {
struct page *page;
pgoff_t end_index;
loff_t isize;
unsigned long nr, ret;
cond_resched();
find_page:
page = find_get_page(mapping, index);
if (!page) {
page_cache_sync_readahead(mapping,
ra, filp,
index, last_index - index);
page = find_get_page(mapping, index);
if (unlikely(page == NULL))
goto no_cached_page;
}
if (PageReadahead(page)) {
page_cache_async_readahead(mapping,
ra, filp, page,
index, last_index - index);
}
if (!PageUptodate(page)) {
if (inode->i_blkbits == PAGE_CACHE_SHIFT ||
!mapping->a_ops->is_partially_uptodate)
goto page_not_up_to_date;
if (!trylock_page(page))
goto page_not_up_to_date;
/* Did it get truncated before we got the lock? */
if (!page->mapping)
goto page_not_up_to_date_locked;
if (!mapping->a_ops->is_partially_uptodate(page,
desc, offset))
goto page_not_up_to_date_locked;
unlock_page(page);
}
page_ok:
/*
* i_size must be checked after we know the page is Uptodate.
*
* Checking i_size after the check allows us to calculate
* the correct value for "nr", which means the zero-filled
* part of the page is not copied back to userspace (unless
* another truncate extends the file - this is desired though).
*/
isize = i_size_read(inode);
end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
if (unlikely(!isize || index > end_index)) {
page_cache_release(page);
goto out;
}
/* nr is the maximum number of bytes to copy from this page */
nr = PAGE_CACHE_SIZE;
if (index == end_index) {
nr = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
if (nr <= offset) {
page_cache_release(page);
goto out;
}
}
nr = nr - offset;
/* If users can be writing to this page using arbitrary
* virtual addresses, take care about potential aliasing
* before reading the page on the kernel side.
*/
if (mapping_writably_mapped(mapping))
flush_dcache_page(page);
/*
* When a sequential read accesses a page several times,
* only mark it as accessed the first time.
*/
if (prev_index != index || offset != prev_offset)
mark_page_accessed(page);
prev_index = index;
/*
* Ok, we have the page, and it's up-to-date, so
* now we can copy it to user space...
*
* The actor routine returns how many bytes were actually used..
* NOTE! This may not be the same as how much of a user buffer
* we filled up (we may be padding etc), so we can only update
* "pos" here (the actor routine has to update the user buffer
* pointers and the remaining count).
*/
ret = actor(desc, page, offset, nr);
offset += ret;
index += offset >> PAGE_CACHE_SHIFT;
offset &= ~PAGE_CACHE_MASK;
prev_offset = offset;
page_cache_release(page);
if (ret == nr && desc->count)
continue;
goto out;
page_not_up_to_date:
/* Get exclusive access to the page ... */
error = lock_page_killable(page);
if (unlikely(error))
goto readpage_error;
page_not_up_to_date_locked:
/* Did it get truncated before we got the lock? */
if (!page->mapping) {
unlock_page(page);
page_cache_release(page);
continue;
}
/* Did somebody else fill it already? */
if (PageUptodate(page)) {
unlock_page(page);
goto page_ok;
}
readpage:
/*
* A previous I/O error may have been due to temporary
* failures, eg. multipath errors.
* PG_error will be set again if readpage fails.
*/
ClearPageError(page);
/* Start the actual read. The read will unlock the page. */
error = mapping->a_ops->readpage(filp, page);
if (unlikely(error)) {
if (error == AOP_TRUNCATED_PAGE) {
page_cache_release(page);
goto find_page;
}
goto readpage_error;
}
if (!PageUptodate(page)) {
error = lock_page_killable(page);
if (unlikely(error))
goto readpage_error;
if (!PageUptodate(page)) {
if (page->mapping == NULL) {
/*
* invalidate_mapping_pages got it
*/
unlock_page(page);
page_cache_release(page);
goto find_page;
}
unlock_page(page);
shrink_readahead_size_eio(filp, ra);
error = -EIO;
goto readpage_error;
}
unlock_page(page);
}
goto page_ok;
readpage_error:
/* UHHUH! A synchronous read error occurred. Report it */
desc->error = error;
page_cache_release(page);
goto out;
no_cached_page:
/*
* Ok, it wasn't cached, so we need to create a new
* page..
*/
page = page_cache_alloc_cold(mapping);
if (!page) {
desc->error = -ENOMEM;
goto out;
}
error = add_to_page_cache_lru(page, mapping,
index, GFP_KERNEL);
if (error) {
page_cache_release(page);
if (error == -EEXIST)
goto find_page;
desc->error = error;
goto out;
}
goto readpage;
}
out:
ra->prev_pos = prev_index;
ra->prev_pos <<= PAGE_CACHE_SHIFT;
ra->prev_pos |= prev_offset;
*ppos = ((loff_t)index << PAGE_CACHE_SHIFT) + offset;
file_accessed(filp);
}
int file_read_actor(read_descriptor_t *desc, struct page *page,
unsigned long offset, unsigned long size)
{
char *kaddr;
unsigned long left, count = desc->count;
if (size > count)
size = count;
/*
* Faults on the destination of a read are common, so do it before
* taking the kmap.
*/
if (!fault_in_pages_writeable(desc->arg.buf, size)) {
kaddr = kmap_atomic(page);
left = __copy_to_user_inatomic(desc->arg.buf,
kaddr + offset, size);
kunmap_atomic(kaddr);
if (left == 0)
goto success;
}
/* Do it the slow way */
kaddr = kmap(page);
left = __copy_to_user(desc->arg.buf, kaddr + offset, size);
kunmap(page);
if (left) {
size -= left;
desc->error = -EFAULT;
}
success:
desc->count = count - size;
desc->written += size;
desc->arg.buf += size;
return size;
}
/*
* Performs necessary checks before doing a write
* @iov: io vector request
* @nr_segs: number of segments in the iovec
* @count: number of bytes to write
* @access_flags: type of access: %VERIFY_READ or %VERIFY_WRITE
*
* Adjust number of segments and amount of bytes to write (nr_segs should be
* properly initialized first). Returns appropriate error code that caller
* should return or zero in case that write should be allowed.
*/
int generic_segment_checks(const struct iovec *iov,
unsigned long *nr_segs, size_t *count, int access_flags)
{
unsigned long seg;
size_t cnt = 0;
for (seg = 0; seg < *nr_segs; seg++) {
const struct iovec *iv = &iov[seg];
/*
* If any segment has a negative length, or the cumulative
* length ever wraps negative then return -EINVAL.
*/
cnt += iv->iov_len;
if (unlikely((ssize_t)(cnt|iv->iov_len) < 0))
return -EINVAL;
if (access_ok(access_flags, iv->iov_base, iv->iov_len))
continue;
if (seg == 0)
return -EFAULT;
*nr_segs = seg;
cnt -= iv->iov_len; /* This segment is no good */
break;
}
*count = cnt;
return 0;
}
EXPORT_SYMBOL(generic_segment_checks);
/**
* generic_file_aio_read - generic filesystem read routine
* @iocb: kernel I/O control block
* @iov: io vector request
* @nr_segs: number of segments in the iovec
* @pos: current file position
*
* This is the "read()" routine for all filesystems
* that can use the page cache directly.
*/
ssize_t
generic_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t pos)
{
struct file *filp = iocb->ki_filp;
ssize_t retval;
unsigned long seg = 0;
size_t count;
loff_t *ppos = &iocb->ki_pos;
count = 0;
retval = generic_segment_checks(iov, &nr_segs, &count, VERIFY_WRITE);
if (retval)
return retval;
/* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
if (filp->f_flags & O_DIRECT) {
loff_t size;
struct address_space *mapping;
struct inode *inode;
mapping = filp->f_mapping;
inode = mapping->host;
if (!count)
goto out; /* skip atime */
size = i_size_read(inode);
if (pos < size) {
retval = filemap_write_and_wait_range(mapping, pos,
pos + iov_length(iov, nr_segs) - 1);
if (!retval) {
struct blk_plug plug;
blk_start_plug(&plug);
retval = mapping->a_ops->direct_IO(READ, iocb,
iov, pos, nr_segs);
blk_finish_plug(&plug);
}
if (retval > 0) {
*ppos = pos + retval;
count -= retval;
}
/*
* Btrfs can have a short DIO read if we encounter
* compressed extents, so if there was an error, or if
* we've already read everything we wanted to, or if
* there was a short read because we hit EOF, go ahead
* and return. Otherwise fallthrough to buffered io for
* the rest of the read.
*/
if (retval < 0 || !count || *ppos >= size) {
file_accessed(filp);
goto out;
}
}
}
count = retval;
for (seg = 0; seg < nr_segs; seg++) {
read_descriptor_t desc;
loff_t offset = 0;
/*
* If we did a short DIO read we need to skip the section of the
* iov that we've already read data into.
*/
if (count) {
if (count > iov[seg].iov_len) {
count -= iov[seg].iov_len;
continue;
}
offset = count;
count = 0;
}
desc.written = 0;
desc.arg.buf = iov[seg].iov_base + offset;
desc.count = iov[seg].iov_len - offset;
if (desc.count == 0)
continue;
desc.error = 0;
do_generic_file_read(filp, ppos, &desc, file_read_actor);
retval += desc.written;
if (desc.error) {
retval = retval ?: desc.error;
break;
}
if (desc.count > 0)
break;
}
out:
return retval;
}
EXPORT_SYMBOL(generic_file_aio_read);
static ssize_t
do_readahead(struct address_space *mapping, struct file *filp,
pgoff_t index, unsigned long nr)
{
if (!mapping || !mapping->a_ops || !mapping->a_ops->readpage)
return -EINVAL;
force_page_cache_readahead(mapping, filp, index, nr);
return 0;
}
SYSCALL_DEFINE(readahead)(int fd, loff_t offset, size_t count)
{
ssize_t ret;
struct file *file;
ret = -EBADF;
file = fget(fd);
if (file) {
if (file->f_mode & FMODE_READ) {
struct address_space *mapping = file->f_mapping;
pgoff_t start = offset >> PAGE_CACHE_SHIFT;
pgoff_t end = (offset + count - 1) >> PAGE_CACHE_SHIFT;
unsigned long len = end - start + 1;
ret = do_readahead(mapping, file, start, len);
}
fput(file);
}
return ret;
}
#ifdef CONFIG_HAVE_SYSCALL_WRAPPERS
asmlinkage long SyS_readahead(long fd, loff_t offset, long count)
{
return SYSC_readahead((int) fd, offset, (size_t) count);
}
SYSCALL_ALIAS(sys_readahead, SyS_readahead);
#endif
#ifdef CONFIG_MMU
/**
* page_cache_read - adds requested page to the page cache if not already there
* @file: file to read
* @offset: page index
*
* This adds the requested page to the page cache if it isn't already there,
* and schedules an I/O to read in its contents from disk.
*/
static int page_cache_read(struct file *file, pgoff_t offset)
{
struct address_space *mapping = file->f_mapping;
struct page *page;
int ret;
do {
page = page_cache_alloc_cold(mapping);
if (!page)
return -ENOMEM;
ret = add_to_page_cache_lru(page, mapping, offset, GFP_KERNEL);
if (ret == 0)
ret = mapping->a_ops->readpage(file, page);
else if (ret == -EEXIST)
ret = 0; /* losing race to add is OK */
page_cache_release(page);
} while (ret == AOP_TRUNCATED_PAGE);
return ret;
}
#define MMAP_LOTSAMISS (100)
/*
* Synchronous readahead happens when we don't even find
* a page in the page cache at all.
*/
static void do_sync_mmap_readahead(struct vm_area_struct *vma,
struct file_ra_state *ra,
struct file *file,
pgoff_t offset)
{
unsigned long ra_pages;
struct address_space *mapping = file->f_mapping;
/* If we don't want any read-ahead, don't bother */
if (VM_RandomReadHint(vma))
return;
if (!ra->ra_pages)
return;
if (VM_SequentialReadHint(vma)) {
page_cache_sync_readahead(mapping, ra, file, offset,
ra->ra_pages);
return;
}
/* Avoid banging the cache line if not needed */
if (ra->mmap_miss < MMAP_LOTSAMISS * 10)
ra->mmap_miss++;
/*
* Do we miss much more than hit in this file? If so,
* stop bothering with read-ahead. It will only hurt.
*/
if (ra->mmap_miss > MMAP_LOTSAMISS)
return;
/*
* mmap read-around
*/
ra_pages = max_sane_readahead(ra->ra_pages);
ra->start = max_t(long, 0, offset - ra_pages / 2);
ra->size = ra_pages;
ra->async_size = ra_pages / 4;
ra_submit(ra, mapping, file);
}
/*
* Asynchronous readahead happens when we find the page and PG_readahead,
* so we want to possibly extend the readahead further..
*/
static void do_async_mmap_readahead(struct vm_area_struct *vma,
struct file_ra_state *ra,
struct file *file,
struct page *page,
pgoff_t offset)
{
struct address_space *mapping = file->f_mapping;
/* If we don't want any read-ahead, don't bother */
if (VM_RandomReadHint(vma))
return;
if (ra->mmap_miss > 0)
ra->mmap_miss--;
if (PageReadahead(page))
page_cache_async_readahead(mapping, ra, file,
page, offset, ra->ra_pages);
}
/**
* filemap_fault - read in file data for page fault handling
* @vma: vma in which the fault was taken
* @vmf: struct vm_fault containing details of the fault
*
* filemap_fault() is invoked via the vma operations vector for a
* mapped memory region to read in file data during a page fault.
*
* The goto's are kind of ugly, but this streamlines the normal case of having
* it in the page cache, and handles the special cases reasonably without
* having a lot of duplicated code.
*/
int filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
int error;
struct file *file = vma->vm_file;
struct address_space *mapping = file->f_mapping;
struct file_ra_state *ra = &file->f_ra;
struct inode *inode = mapping->host;
pgoff_t offset = vmf->pgoff;
struct page *page;
pgoff_t size;
int ret = 0;
size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
if (offset >= size)
return VM_FAULT_SIGBUS;
/*
* Do we have something in the page cache already?
*/
page = find_get_page(mapping, offset);
if (likely(page)) {
/*
* We found the page, so try async readahead before
* waiting for the lock.
*/
do_async_mmap_readahead(vma, ra, file, page, offset);
} else {
/* No page in the page cache at all */
do_sync_mmap_readahead(vma, ra, file, offset);
count_vm_event(PGMAJFAULT);
/* LGE_CHANGE_S
*
* Profile files related to pgmajfault during 1st booting
* in order to use the data as readahead args
*
* matia.kim@lge.com 20130612
*/
sreadahead_prof(file, 0, 0);
/* LGE_CHANGE_E */
mem_cgroup_count_vm_event(vma->vm_mm, PGMAJFAULT);
ret = VM_FAULT_MAJOR;
retry_find:
page = find_get_page(mapping, offset);
if (!page)
goto no_cached_page;
}
if (!lock_page_or_retry(page, vma->vm_mm, vmf->flags)) {
page_cache_release(page);
return ret | VM_FAULT_RETRY;
}
/* Did it get truncated? */
if (unlikely(page->mapping != mapping)) {
unlock_page(page);
put_page(page);
goto retry_find;
}
VM_BUG_ON(page->index != offset);
/*
* We have a locked page in the page cache, now we need to check
* that it's up-to-date. If not, it is going to be due to an error.
*/
if (unlikely(!PageUptodate(page)))
goto page_not_uptodate;
/*
* Found the page and have a reference on it.
* We must recheck i_size under page lock.
*/
size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
if (unlikely(offset >= size)) {
unlock_page(page);
page_cache_release(page);
return VM_FAULT_SIGBUS;
}
vmf->page = page;
return ret | VM_FAULT_LOCKED;
no_cached_page:
/*
* We're only likely to ever get here if MADV_RANDOM is in
* effect.
*/
error = page_cache_read(file, offset);
/*
* The page we want has now been added to the page cache.
* In the unlikely event that someone removed it in the
* meantime, we'll just come back here and read it again.
*/
if (error >= 0)
goto retry_find;
/*
* An error return from page_cache_read can result if the
* system is low on memory, or a problem occurs while trying
* to schedule I/O.
*/
if (error == -ENOMEM)
return VM_FAULT_OOM;
return VM_FAULT_SIGBUS;
page_not_uptodate:
/*
* Umm, take care of errors if the page isn't up-to-date.
* Try to re-read it _once_. We do this synchronously,
* because there really aren't any performance issues here
* and we need to check for errors.
*/
ClearPageError(page);
error = mapping->a_ops->readpage(file, page);
if (!error) {
wait_on_page_locked(page);
if (!PageUptodate(page))
error = -EIO;
}
page_cache_release(page);
if (!error || error == AOP_TRUNCATED_PAGE)
goto retry_find;
/* Things didn't work out. Return zero to tell the mm layer so. */
shrink_readahead_size_eio(file, ra);
return VM_FAULT_SIGBUS;
}
EXPORT_SYMBOL(filemap_fault);
const struct vm_operations_struct generic_file_vm_ops = {
.fault = filemap_fault,
};
/* This is used for a general mmap of a disk file */
int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
{
struct address_space *mapping = file->f_mapping;
if (!mapping->a_ops->readpage)
return -ENOEXEC;
file_accessed(file);
vma->vm_ops = &generic_file_vm_ops;
vma->vm_flags |= VM_CAN_NONLINEAR;
return 0;
}
/*
* This is for filesystems which do not implement ->writepage.
*/
int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
{
if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
return -EINVAL;
return generic_file_mmap(file, vma);
}
#else
int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
{
return -ENOSYS;
}
int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
{
return -ENOSYS;
}
#endif /* CONFIG_MMU */
EXPORT_SYMBOL(generic_file_mmap);
EXPORT_SYMBOL(generic_file_readonly_mmap);
static struct page *__read_cache_page(struct address_space *mapping,
pgoff_t index,
int (*filler)(void *, struct page *),
void *data,
gfp_t gfp)
{
struct page *page;
int err;
repeat:
page = find_get_page(mapping, index);
if (!page) {
page = __page_cache_alloc(gfp | __GFP_COLD);
if (!page)
return ERR_PTR(-ENOMEM);
err = add_to_page_cache_lru(page, mapping, index, gfp);
if (unlikely(err)) {
page_cache_release(page);
if (err == -EEXIST)
goto repeat;
/* Presumably ENOMEM for radix tree node */
return ERR_PTR(err);
}
err = filler(data, page);
if (err < 0) {
page_cache_release(page);
page = ERR_PTR(err);
}
}
return page;
}
static struct page *do_read_cache_page(struct address_space *mapping,
pgoff_t index,
int (*filler)(void *, struct page *),
void *data,
gfp_t gfp)
{
struct page *page;
int err;
retry:
page = __read_cache_page(mapping, index, filler, data, gfp);
if (IS_ERR(page))
return page;
if (PageUptodate(page))
goto out;
lock_page(page);
if (!page->mapping) {
unlock_page(page);
page_cache_release(page);
goto retry;
}
if (PageUptodate(page)) {
unlock_page(page);
goto out;
}
err = filler(data, page);
if (err < 0) {
page_cache_release(page);
return ERR_PTR(err);
}
out:
mark_page_accessed(page);
return page;
}
/**
* read_cache_page_async - read into page cache, fill it if needed
* @mapping: the page's address_space
* @index: the page index
* @filler: function to perform the read
* @data: first arg to filler(data, page) function, often left as NULL
*
* Same as read_cache_page, but don't wait for page to become unlocked
* after submitting it to the filler.
*
* Read into the page cache. If a page already exists, and PageUptodate() is
* not set, try to fill the page but don't wait for it to become unlocked.
*
* If the page does not get brought uptodate, return -EIO.
*/
struct page *read_cache_page_async(struct address_space *mapping,
pgoff_t index,
int (*filler)(void *, struct page *),
void *data)
{
return do_read_cache_page(mapping, index, filler, data, mapping_gfp_mask(mapping));
}
EXPORT_SYMBOL(read_cache_page_async);
static struct page *wait_on_page_read(struct page *page)
{
if (!IS_ERR(page)) {
wait_on_page_locked(page);
if (!PageUptodate(page)) {
page_cache_release(page);
page = ERR_PTR(-EIO);
}
}
return page;
}
/**
* read_cache_page_gfp - read into page cache, using specified page allocation flags.
* @mapping: the page's address_space
* @index: the page index
* @gfp: the page allocator flags to use if allocating
*
* This is the same as "read_mapping_page(mapping, index, NULL)", but with
* any new page allocations done using the specified allocation flags.
*
* If the page does not get brought uptodate, return -EIO.
*/
struct page *read_cache_page_gfp(struct address_space *mapping,
pgoff_t index,
gfp_t gfp)
{
filler_t *filler = (filler_t *)mapping->a_ops->readpage;
return wait_on_page_read(do_read_cache_page(mapping, index, filler, NULL, gfp));
}
EXPORT_SYMBOL(read_cache_page_gfp);
/**
* read_cache_page - read into page cache, fill it if needed
* @mapping: the page's address_space
* @index: the page index
* @filler: function to perform the read
* @data: first arg to filler(data, page) function, often left as NULL
*
* Read into the page cache. If a page already exists, and PageUptodate() is
* not set, try to fill the page then wait for it to become unlocked.
*
* If the page does not get brought uptodate, return -EIO.
*/
struct page *read_cache_page(struct address_space *mapping,
pgoff_t index,
int (*filler)(void *, struct page *),
void *data)
{
return wait_on_page_read(read_cache_page_async(mapping, index, filler, data));
}
EXPORT_SYMBOL(read_cache_page);
/*
* The logic we want is
*
* if suid or (sgid and xgrp)
* remove privs
*/
int should_remove_suid(struct dentry *dentry)
{
umode_t mode = dentry->d_inode->i_mode;
int kill = 0;
/* suid always must be killed */
if (unlikely(mode & S_ISUID))
kill = ATTR_KILL_SUID;
/*
* sgid without any exec bits is just a mandatory locking mark; leave
* it alone. If some exec bits are set, it's a real sgid; kill it.
*/
if (unlikely((mode & S_ISGID) && (mode & S_IXGRP)))
kill |= ATTR_KILL_SGID;
if (unlikely(kill && !capable(CAP_FSETID) && S_ISREG(mode)))
return kill;
return 0;
}
EXPORT_SYMBOL(should_remove_suid);
static int __remove_suid(struct dentry *dentry, int kill)
{
struct iattr newattrs;
newattrs.ia_valid = ATTR_FORCE | kill;
return notify_change(dentry, &newattrs);
}
int file_remove_suid(struct file *file)
{
struct dentry *dentry = file->f_path.dentry;
struct inode *inode = dentry->d_inode;
int killsuid;
int killpriv;
int error = 0;
/* Fast path for nothing security related */
if (IS_NOSEC(inode))
return 0;
killsuid = should_remove_suid(dentry);
killpriv = security_inode_need_killpriv(dentry);
if (killpriv < 0)
return killpriv;
if (killpriv)
error = security_inode_killpriv(dentry);
if (!error && killsuid)
error = __remove_suid(dentry, killsuid);
if (!error && (inode->i_sb->s_flags & MS_NOSEC))
inode->i_flags |= S_NOSEC;
return error;
}
EXPORT_SYMBOL(file_remove_suid);
static size_t __iovec_copy_from_user_inatomic(char *vaddr,
const struct iovec *iov, size_t base, size_t bytes)
{
size_t copied = 0, left = 0;
while (bytes) {
char __user *buf = iov->iov_base + base;
int copy = min(bytes, iov->iov_len - base);
base = 0;
left = __copy_from_user_inatomic(vaddr, buf, copy);
copied += copy;
bytes -= copy;
vaddr += copy;
iov++;
if (unlikely(left))
break;
}
return copied - left;
}
/*
* Copy as much as we can into the page and return the number of bytes which
* were successfully copied. If a fault is encountered then return the number of
* bytes which were copied.
*/
size_t iov_iter_copy_from_user_atomic(struct page *page,
struct iov_iter *i, unsigned long offset, size_t bytes)
{
char *kaddr;
size_t copied;
BUG_ON(!in_atomic());
kaddr = kmap_atomic(page);
if (likely(i->nr_segs == 1)) {
int left;
char __user *buf = i->iov->iov_base + i->iov_offset;
left = __copy_from_user_inatomic(kaddr + offset, buf, bytes);
copied = bytes - left;
} else {
copied = __iovec_copy_from_user_inatomic(kaddr + offset,
i->iov, i->iov_offset, bytes);
}
kunmap_atomic(kaddr);
return copied;
}
EXPORT_SYMBOL(iov_iter_copy_from_user_atomic);
/*
* This has the same sideeffects and return value as
* iov_iter_copy_from_user_atomic().
* The difference is that it attempts to resolve faults.
* Page must not be locked.
*/
size_t iov_iter_copy_from_user(struct page *page,
struct iov_iter *i, unsigned long offset, size_t bytes)
{
char *kaddr;
size_t copied;
kaddr = kmap(page);
if (likely(i->nr_segs == 1)) {
int left;
char __user *buf = i->iov->iov_base + i->iov_offset;
left = __copy_from_user(kaddr + offset, buf, bytes);
copied = bytes - left;
} else {
copied = __iovec_copy_from_user_inatomic(kaddr + offset,
i->iov, i->iov_offset, bytes);
}
kunmap(page);
return copied;
}
EXPORT_SYMBOL(iov_iter_copy_from_user);
void iov_iter_advance(struct iov_iter *i, size_t bytes)
{
BUG_ON(i->count < bytes);
if (likely(i->nr_segs == 1)) {
i->iov_offset += bytes;
i->count -= bytes;
} else {
const struct iovec *iov = i->iov;
size_t base = i->iov_offset;
unsigned long nr_segs = i->nr_segs;
/*
* The !iov->iov_len check ensures we skip over unlikely
* zero-length segments (without overruning the iovec).
*/
while (bytes || unlikely(i->count && !iov->iov_len)) {
int copy;
copy = min(bytes, iov->iov_len - base);
BUG_ON(!i->count || i->count < copy);
i->count -= copy;
bytes -= copy;
base += copy;
if (iov->iov_len == base) {
iov++;
nr_segs--;
base = 0;
}
}
i->iov = iov;
i->iov_offset = base;
i->nr_segs = nr_segs;
}
}
EXPORT_SYMBOL(iov_iter_advance);
/*
* Fault in the first iovec of the given iov_iter, to a maximum length
* of bytes. Returns 0 on success, or non-zero if the memory could not be
* accessed (ie. because it is an invalid address).
*
* writev-intensive code may want this to prefault several iovecs -- that
* would be possible (callers must not rely on the fact that _only_ the
* first iovec will be faulted with the current implementation).
*/
int iov_iter_fault_in_readable(struct iov_iter *i, size_t bytes)
{
char __user *buf = i->iov->iov_base + i->iov_offset;
bytes = min(bytes, i->iov->iov_len - i->iov_offset);
return fault_in_pages_readable(buf, bytes);
}
EXPORT_SYMBOL(iov_iter_fault_in_readable);
/*
* Return the count of just the current iov_iter segment.
*/
size_t iov_iter_single_seg_count(struct iov_iter *i)
{
const struct iovec *iov = i->iov;
if (i->nr_segs == 1)
return i->count;
else
return min(i->count, iov->iov_len - i->iov_offset);
}
EXPORT_SYMBOL(iov_iter_single_seg_count);
/*
* Performs necessary checks before doing a write
*
* Can adjust writing position or amount of bytes to write.
* Returns appropriate error code that caller should return or
* zero in case that write should be allowed.
*/
inline int generic_write_checks(struct file *file, loff_t *pos, size_t *count, int isblk)
{
struct inode *inode = file->f_mapping->host;
unsigned long limit = rlimit(RLIMIT_FSIZE);
if (unlikely(*pos < 0))
return -EINVAL;
if (!isblk) {
/* FIXME: this is for backwards compatibility with 2.4 */
if (file->f_flags & O_APPEND)
*pos = i_size_read(inode);
if (limit != RLIM_INFINITY) {
if (*pos >= limit) {
send_sig(SIGXFSZ, current, 0);
return -EFBIG;
}
if (*count > limit - (typeof(limit))*pos) {
*count = limit - (typeof(limit))*pos;
}
}
}
/*
* LFS rule
*/
if (unlikely(*pos + *count > MAX_NON_LFS &&
!(file->f_flags & O_LARGEFILE))) {
if (*pos >= MAX_NON_LFS) {
return -EFBIG;
}
if (*count > MAX_NON_LFS - (unsigned long)*pos) {
*count = MAX_NON_LFS - (unsigned long)*pos;
}
}
/*
* Are we about to exceed the fs block limit ?
*
* If we have written data it becomes a short write. If we have
* exceeded without writing data we send a signal and return EFBIG.
* Linus frestrict idea will clean these up nicely..
*/
if (likely(!isblk)) {
if (unlikely(*pos >= inode->i_sb->s_maxbytes)) {
if (*count || *pos > inode->i_sb->s_maxbytes) {
return -EFBIG;
}
/* zero-length writes at ->s_maxbytes are OK */
}
if (unlikely(*pos + *count > inode->i_sb->s_maxbytes))
*count = inode->i_sb->s_maxbytes - *pos;
} else {
#ifdef CONFIG_BLOCK
loff_t isize;
if (bdev_read_only(I_BDEV(inode)))
return -EPERM;
isize = i_size_read(inode);
if (*pos >= isize) {
if (*count || *pos > isize)
return -ENOSPC;
}
if (*pos + *count > isize)
*count = isize - *pos;
#else
return -EPERM;
#endif
}
return 0;
}
EXPORT_SYMBOL(generic_write_checks);
int pagecache_write_begin(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned flags,
struct page **pagep, void **fsdata)
{
const struct address_space_operations *aops = mapping->a_ops;
return aops->write_begin(file, mapping, pos, len, flags,
pagep, fsdata);
}
EXPORT_SYMBOL(pagecache_write_begin);
int pagecache_write_end(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *page, void *fsdata)
{
const struct address_space_operations *aops = mapping->a_ops;
mark_page_accessed(page);
return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
}
EXPORT_SYMBOL(pagecache_write_end);
ssize_t
generic_file_direct_write(struct kiocb *iocb, const struct iovec *iov,
unsigned long *nr_segs, loff_t pos, loff_t *ppos,
size_t count, size_t ocount)
{
struct file *file = iocb->ki_filp;
struct address_space *mapping = file->f_mapping;
struct inode *inode = mapping->host;
ssize_t written;
size_t write_len;
pgoff_t end;
if (count != ocount)
*nr_segs = iov_shorten((struct iovec *)iov, *nr_segs, count);
write_len = iov_length(iov, *nr_segs);
end = (pos + write_len - 1) >> PAGE_CACHE_SHIFT;
written = filemap_write_and_wait_range(mapping, pos, pos + write_len - 1);
if (written)
goto out;
/*
* After a write we want buffered reads to be sure to go to disk to get
* the new data. We invalidate clean cached page from the region we're
* about to write. We do this *before* the write so that we can return
* without clobbering -EIOCBQUEUED from ->direct_IO().
*/
if (mapping->nrpages) {
written = invalidate_inode_pages2_range(mapping,
pos >> PAGE_CACHE_SHIFT, end);
/*
* If a page can not be invalidated, return 0 to fall back
* to buffered write.
*/
if (written) {
if (written == -EBUSY)
return 0;
goto out;
}
}
written = mapping->a_ops->direct_IO(WRITE, iocb, iov, pos, *nr_segs);
/*
* Finally, try again to invalidate clean pages which might have been
* cached by non-direct readahead, or faulted in by get_user_pages()
* if the source of the write was an mmap'ed region of the file
* we're writing. Either one is a pretty crazy thing to do,
* so we don't support it 100%. If this invalidation
* fails, tough, the write still worked...
*/
if (mapping->nrpages) {
invalidate_inode_pages2_range(mapping,
pos >> PAGE_CACHE_SHIFT, end);
}
if (written > 0) {
pos += written;
if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
i_size_write(inode, pos);
mark_inode_dirty(inode);
}
*ppos = pos;
}
out:
return written;
}
EXPORT_SYMBOL(generic_file_direct_write);
/*
* Find or create a page at the given pagecache position. Return the locked
* page. This function is specifically for buffered writes.
*/
struct page *grab_cache_page_write_begin(struct address_space *mapping,
pgoff_t index, unsigned flags)
{
int status;
gfp_t gfp_mask;
struct page *page;
gfp_t gfp_notmask = 0;
gfp_mask = mapping_gfp_mask(mapping);
if (mapping_cap_account_dirty(mapping))
gfp_mask |= __GFP_WRITE;
if (flags & AOP_FLAG_NOFS)
gfp_notmask = __GFP_FS;
repeat:
page = find_lock_page(mapping, index);
if (page)
goto found;
retry:
page = __page_cache_alloc(gfp_mask & ~gfp_notmask);
if (!page)
return NULL;
if (is_cma_pageblock(page)) {
__free_page(page);
gfp_notmask |= __GFP_MOVABLE;
goto retry;
}
status = add_to_page_cache_lru(page, mapping, index,
GFP_KERNEL & ~gfp_notmask);
if (unlikely(status)) {
page_cache_release(page);
if (status == -EEXIST)
goto repeat;
return NULL;
}
found:
wait_on_page_writeback(page);
return page;
}
EXPORT_SYMBOL(grab_cache_page_write_begin);
static ssize_t generic_perform_write(struct file *file,
struct iov_iter *i, loff_t pos)
{
struct address_space *mapping = file->f_mapping;
const struct address_space_operations *a_ops = mapping->a_ops;
long status = 0;
ssize_t written = 0;
unsigned int flags = 0;
/*
* Copies from kernel address space cannot fail (NFSD is a big user).
*/
if (segment_eq(get_fs(), KERNEL_DS))
flags |= AOP_FLAG_UNINTERRUPTIBLE;
do {
struct page *page;
unsigned long offset; /* Offset into pagecache page */
unsigned long bytes; /* Bytes to write to page */
size_t copied; /* Bytes copied from user */
void *fsdata;
offset = (pos & (PAGE_CACHE_SIZE - 1));
bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
iov_iter_count(i));
again:
/*
* Bring in the user page that we will copy from _first_.
* Otherwise there's a nasty deadlock on copying from the
* same page as we're writing to, without it being marked
* up-to-date.
*
* Not only is this an optimisation, but it is also required
* to check that the address is actually valid, when atomic
* usercopies are used, below.
*/
if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
status = -EFAULT;
break;
}
status = a_ops->write_begin(file, mapping, pos, bytes, flags,
&page, &fsdata);
if (unlikely(status))
break;
if (mapping_writably_mapped(mapping))
flush_dcache_page(page);
pagefault_disable();
copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
pagefault_enable();
flush_dcache_page(page);
mark_page_accessed(page);
status = a_ops->write_end(file, mapping, pos, bytes, copied,
page, fsdata);
if (unlikely(status < 0))
break;
copied = status;
cond_resched();
iov_iter_advance(i, copied);
if (unlikely(copied == 0)) {
/*
* If we were unable to copy any data at all, we must
* fall back to a single segment length write.
*
* If we didn't fallback here, we could livelock
* because not all segments in the iov can be copied at
* once without a pagefault.
*/
bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
iov_iter_single_seg_count(i));
goto again;
}
pos += copied;
written += copied;
balance_dirty_pages_ratelimited(mapping);
if (fatal_signal_pending(current)) {
status = -EINTR;
break;
}
} while (iov_iter_count(i));
return written ? written : status;
}
ssize_t
generic_file_buffered_write(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t pos, loff_t *ppos,
size_t count, ssize_t written)
{
struct file *file = iocb->ki_filp;
ssize_t status;
struct iov_iter i;
iov_iter_init(&i, iov, nr_segs, count, written);
status = generic_perform_write(file, &i, pos);
if (likely(status >= 0)) {
written += status;
*ppos = pos + status;
}
return written ? written : status;
}
EXPORT_SYMBOL(generic_file_buffered_write);
/**
* __generic_file_aio_write - write data to a file
* @iocb: IO state structure (file, offset, etc.)
* @iov: vector with data to write
* @nr_segs: number of segments in the vector
* @ppos: position where to write
*
* This function does all the work needed for actually writing data to a
* file. It does all basic checks, removes SUID from the file, updates
* modification times and calls proper subroutines depending on whether we
* do direct IO or a standard buffered write.
*
* It expects i_mutex to be grabbed unless we work on a block device or similar
* object which does not need locking at all.
*
* This function does *not* take care of syncing data in case of O_SYNC write.
* A caller has to handle it. This is mainly due to the fact that we want to
* avoid syncing under i_mutex.
*/
ssize_t __generic_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t *ppos)
{
struct file *file = iocb->ki_filp;
struct address_space * mapping = file->f_mapping;
size_t ocount; /* original count */
size_t count; /* after file limit checks */
struct inode *inode = mapping->host;
loff_t pos;
ssize_t written;
ssize_t err;
ocount = 0;
err = generic_segment_checks(iov, &nr_segs, &ocount, VERIFY_READ);
if (err)
return err;
count = ocount;
pos = *ppos;
vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
/* We can write back this queue in page reclaim */
current->backing_dev_info = mapping->backing_dev_info;
written = 0;
err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
if (err)
goto out;
if (count == 0)
goto out;
err = file_remove_suid(file);
if (err)
goto out;
file_update_time(file);
/* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
if (unlikely(file->f_flags & O_DIRECT)) {
loff_t endbyte;
ssize_t written_buffered;
written = generic_file_direct_write(iocb, iov, &nr_segs, pos,
ppos, count, ocount);
if (written < 0 || written == count)
goto out;
/*
* direct-io write to a hole: fall through to buffered I/O
* for completing the rest of the request.
*/
pos += written;
count -= written;
written_buffered = generic_file_buffered_write(iocb, iov,
nr_segs, pos, ppos, count,
written);
/*
* If generic_file_buffered_write() retuned a synchronous error
* then we want to return the number of bytes which were
* direct-written, or the error code if that was zero. Note
* that this differs from normal direct-io semantics, which
* will return -EFOO even if some bytes were written.
*/
if (written_buffered < 0) {
err = written_buffered;
goto out;
}
/*
* We need to ensure that the page cache pages are written to
* disk and invalidated to preserve the expected O_DIRECT
* semantics.
*/
endbyte = pos + written_buffered - written - 1;
err = filemap_write_and_wait_range(file->f_mapping, pos, endbyte);
if (err == 0) {
written = written_buffered;
invalidate_mapping_pages(mapping,
pos >> PAGE_CACHE_SHIFT,
endbyte >> PAGE_CACHE_SHIFT);
} else {
/*
* We don't know how much we wrote, so just return
* the number of bytes which were direct-written
*/
}
} else {
written = generic_file_buffered_write(iocb, iov, nr_segs,
pos, ppos, count, written);
}
out:
current->backing_dev_info = NULL;
return written ? written : err;
}
EXPORT_SYMBOL(__generic_file_aio_write);
/**
* generic_file_aio_write - write data to a file
* @iocb: IO state structure
* @iov: vector with data to write
* @nr_segs: number of segments in the vector
* @pos: position in file where to write
*
* This is a wrapper around __generic_file_aio_write() to be used by most
* filesystems. It takes care of syncing the file in case of O_SYNC file
* and acquires i_mutex as needed.
*/
ssize_t generic_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t pos)
{
struct file *file = iocb->ki_filp;
struct inode *inode = file->f_mapping->host;
struct blk_plug plug;
ssize_t ret;
BUG_ON(iocb->ki_pos != pos);
mutex_lock(&inode->i_mutex);
blk_start_plug(&plug);
ret = __generic_file_aio_write(iocb, iov, nr_segs, &iocb->ki_pos);
mutex_unlock(&inode->i_mutex);
if (ret > 0 || ret == -EIOCBQUEUED) {
ssize_t err;
err = generic_write_sync(file, pos, ret);
if (err < 0 && ret > 0)
ret = err;
}
blk_finish_plug(&plug);
return ret;
}
EXPORT_SYMBOL(generic_file_aio_write);
/**
* try_to_release_page() - release old fs-specific metadata on a page
*
* @page: the page which the kernel is trying to free
* @gfp_mask: memory allocation flags (and I/O mode)
*
* The address_space is to try to release any data against the page
* (presumably at page->private). If the release was successful, return `1'.
* Otherwise return zero.
*
* This may also be called if PG_fscache is set on a page, indicating that the
* page is known to the local caching routines.
*
* The @gfp_mask argument specifies whether I/O may be performed to release
* this page (__GFP_IO), and whether the call may block (__GFP_WAIT & __GFP_FS).
*
*/
int try_to_release_page(struct page *page, gfp_t gfp_mask)
{
struct address_space * const mapping = page->mapping;
BUG_ON(!PageLocked(page));
if (PageWriteback(page))
return 0;
if (mapping && mapping->a_ops->releasepage)
return mapping->a_ops->releasepage(page, gfp_mask);
return try_to_free_buffers(page);
}
EXPORT_SYMBOL(try_to_release_page);
| gpl-2.0 |
androidbftab1/bf-kernel | drivers/char/hw_random/mxc-rnga.c | 823 | 5534 | /*
* RNG driver for Freescale RNGA
*
* Copyright 2008-2009 Freescale Semiconductor, Inc. All Rights Reserved.
* Author: Alan Carvalho de Assis <acassis@gmail.com>
*/
/*
* The code contained herein is licensed under the GNU General Public
* License. You may obtain a copy of the GNU General Public License
* Version 2 or later at the following locations:
*
* http://www.opensource.org/licenses/gpl-license.html
* http://www.gnu.org/copyleft/gpl.html
*
* This driver is based on other RNG drivers.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/ioport.h>
#include <linux/platform_device.h>
#include <linux/hw_random.h>
#include <linux/delay.h>
#include <linux/io.h>
/* RNGA Registers */
#define RNGA_CONTROL 0x00
#define RNGA_STATUS 0x04
#define RNGA_ENTROPY 0x08
#define RNGA_OUTPUT_FIFO 0x0c
#define RNGA_MODE 0x10
#define RNGA_VERIFICATION_CONTROL 0x14
#define RNGA_OSC_CONTROL_COUNTER 0x18
#define RNGA_OSC1_COUNTER 0x1c
#define RNGA_OSC2_COUNTER 0x20
#define RNGA_OSC_COUNTER_STATUS 0x24
/* RNGA Registers Range */
#define RNG_ADDR_RANGE 0x28
/* RNGA Control Register */
#define RNGA_CONTROL_SLEEP 0x00000010
#define RNGA_CONTROL_CLEAR_INT 0x00000008
#define RNGA_CONTROL_MASK_INTS 0x00000004
#define RNGA_CONTROL_HIGH_ASSURANCE 0x00000002
#define RNGA_CONTROL_GO 0x00000001
#define RNGA_STATUS_LEVEL_MASK 0x0000ff00
/* RNGA Status Register */
#define RNGA_STATUS_OSC_DEAD 0x80000000
#define RNGA_STATUS_SLEEP 0x00000010
#define RNGA_STATUS_ERROR_INT 0x00000008
#define RNGA_STATUS_FIFO_UNDERFLOW 0x00000004
#define RNGA_STATUS_LAST_READ_STATUS 0x00000002
#define RNGA_STATUS_SECURITY_VIOLATION 0x00000001
struct mxc_rng {
struct device *dev;
struct hwrng rng;
void __iomem *mem;
struct clk *clk;
};
static int mxc_rnga_data_present(struct hwrng *rng, int wait)
{
int i;
struct mxc_rng *mxc_rng = container_of(rng, struct mxc_rng, rng);
for (i = 0; i < 20; i++) {
/* how many random numbers are in FIFO? [0-16] */
int level = (__raw_readl(mxc_rng->mem + RNGA_STATUS) &
RNGA_STATUS_LEVEL_MASK) >> 8;
if (level || !wait)
return !!level;
udelay(10);
}
return 0;
}
static int mxc_rnga_data_read(struct hwrng *rng, u32 * data)
{
int err;
u32 ctrl;
struct mxc_rng *mxc_rng = container_of(rng, struct mxc_rng, rng);
/* retrieve a random number from FIFO */
*data = __raw_readl(mxc_rng->mem + RNGA_OUTPUT_FIFO);
/* some error while reading this random number? */
err = __raw_readl(mxc_rng->mem + RNGA_STATUS) & RNGA_STATUS_ERROR_INT;
/* if error: clear error interrupt, but doesn't return random number */
if (err) {
dev_dbg(mxc_rng->dev, "Error while reading random number!\n");
ctrl = __raw_readl(mxc_rng->mem + RNGA_CONTROL);
__raw_writel(ctrl | RNGA_CONTROL_CLEAR_INT,
mxc_rng->mem + RNGA_CONTROL);
return 0;
} else
return 4;
}
static int mxc_rnga_init(struct hwrng *rng)
{
u32 ctrl, osc;
struct mxc_rng *mxc_rng = container_of(rng, struct mxc_rng, rng);
/* wake up */
ctrl = __raw_readl(mxc_rng->mem + RNGA_CONTROL);
__raw_writel(ctrl & ~RNGA_CONTROL_SLEEP, mxc_rng->mem + RNGA_CONTROL);
/* verify if oscillator is working */
osc = __raw_readl(mxc_rng->mem + RNGA_STATUS);
if (osc & RNGA_STATUS_OSC_DEAD) {
dev_err(mxc_rng->dev, "RNGA Oscillator is dead!\n");
return -ENODEV;
}
/* go running */
ctrl = __raw_readl(mxc_rng->mem + RNGA_CONTROL);
__raw_writel(ctrl | RNGA_CONTROL_GO, mxc_rng->mem + RNGA_CONTROL);
return 0;
}
static void mxc_rnga_cleanup(struct hwrng *rng)
{
u32 ctrl;
struct mxc_rng *mxc_rng = container_of(rng, struct mxc_rng, rng);
ctrl = __raw_readl(mxc_rng->mem + RNGA_CONTROL);
/* stop rnga */
__raw_writel(ctrl & ~RNGA_CONTROL_GO, mxc_rng->mem + RNGA_CONTROL);
}
static int __init mxc_rnga_probe(struct platform_device *pdev)
{
int err = -ENODEV;
struct resource *res;
struct mxc_rng *mxc_rng;
mxc_rng = devm_kzalloc(&pdev->dev, sizeof(struct mxc_rng),
GFP_KERNEL);
if (!mxc_rng)
return -ENOMEM;
mxc_rng->dev = &pdev->dev;
mxc_rng->rng.name = "mxc-rnga";
mxc_rng->rng.init = mxc_rnga_init;
mxc_rng->rng.cleanup = mxc_rnga_cleanup,
mxc_rng->rng.data_present = mxc_rnga_data_present,
mxc_rng->rng.data_read = mxc_rnga_data_read,
mxc_rng->clk = devm_clk_get(&pdev->dev, NULL);
if (IS_ERR(mxc_rng->clk)) {
dev_err(&pdev->dev, "Could not get rng_clk!\n");
err = PTR_ERR(mxc_rng->clk);
goto out;
}
err = clk_prepare_enable(mxc_rng->clk);
if (err)
goto out;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
mxc_rng->mem = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(mxc_rng->mem)) {
err = PTR_ERR(mxc_rng->mem);
goto err_ioremap;
}
err = hwrng_register(&mxc_rng->rng);
if (err) {
dev_err(&pdev->dev, "MXC RNGA registering failed (%d)\n", err);
goto err_ioremap;
}
dev_info(&pdev->dev, "MXC RNGA Registered.\n");
return 0;
err_ioremap:
clk_disable_unprepare(mxc_rng->clk);
out:
return err;
}
static int __exit mxc_rnga_remove(struct platform_device *pdev)
{
struct mxc_rng *mxc_rng = platform_get_drvdata(pdev);
hwrng_unregister(&mxc_rng->rng);
clk_disable_unprepare(mxc_rng->clk);
return 0;
}
static struct platform_driver mxc_rnga_driver = {
.driver = {
.name = "mxc_rnga",
},
.remove = __exit_p(mxc_rnga_remove),
};
module_platform_driver_probe(mxc_rnga_driver, mxc_rnga_probe);
MODULE_AUTHOR("Freescale Semiconductor, Inc.");
MODULE_DESCRIPTION("H/W RNGA driver for i.MX");
MODULE_LICENSE("GPL");
| gpl-2.0 |
wow73611/smdk6410-linux-3.18.14 | scripts/asn1_compiler.c | 1079 | 34595 | /* Simplified ASN.1 notation parser
*
* Copyright (C) 2012 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <linux/asn1_ber_bytecode.h>
enum token_type {
DIRECTIVE_ABSENT,
DIRECTIVE_ALL,
DIRECTIVE_ANY,
DIRECTIVE_APPLICATION,
DIRECTIVE_AUTOMATIC,
DIRECTIVE_BEGIN,
DIRECTIVE_BIT,
DIRECTIVE_BMPString,
DIRECTIVE_BOOLEAN,
DIRECTIVE_BY,
DIRECTIVE_CHARACTER,
DIRECTIVE_CHOICE,
DIRECTIVE_CLASS,
DIRECTIVE_COMPONENT,
DIRECTIVE_COMPONENTS,
DIRECTIVE_CONSTRAINED,
DIRECTIVE_CONTAINING,
DIRECTIVE_DEFAULT,
DIRECTIVE_DEFINED,
DIRECTIVE_DEFINITIONS,
DIRECTIVE_EMBEDDED,
DIRECTIVE_ENCODED,
DIRECTIVE_ENCODING_CONTROL,
DIRECTIVE_END,
DIRECTIVE_ENUMERATED,
DIRECTIVE_EXCEPT,
DIRECTIVE_EXPLICIT,
DIRECTIVE_EXPORTS,
DIRECTIVE_EXTENSIBILITY,
DIRECTIVE_EXTERNAL,
DIRECTIVE_FALSE,
DIRECTIVE_FROM,
DIRECTIVE_GeneralString,
DIRECTIVE_GeneralizedTime,
DIRECTIVE_GraphicString,
DIRECTIVE_IA5String,
DIRECTIVE_IDENTIFIER,
DIRECTIVE_IMPLICIT,
DIRECTIVE_IMPLIED,
DIRECTIVE_IMPORTS,
DIRECTIVE_INCLUDES,
DIRECTIVE_INSTANCE,
DIRECTIVE_INSTRUCTIONS,
DIRECTIVE_INTEGER,
DIRECTIVE_INTERSECTION,
DIRECTIVE_ISO646String,
DIRECTIVE_MAX,
DIRECTIVE_MIN,
DIRECTIVE_MINUS_INFINITY,
DIRECTIVE_NULL,
DIRECTIVE_NumericString,
DIRECTIVE_OBJECT,
DIRECTIVE_OCTET,
DIRECTIVE_OF,
DIRECTIVE_OPTIONAL,
DIRECTIVE_ObjectDescriptor,
DIRECTIVE_PATTERN,
DIRECTIVE_PDV,
DIRECTIVE_PLUS_INFINITY,
DIRECTIVE_PRESENT,
DIRECTIVE_PRIVATE,
DIRECTIVE_PrintableString,
DIRECTIVE_REAL,
DIRECTIVE_RELATIVE_OID,
DIRECTIVE_SEQUENCE,
DIRECTIVE_SET,
DIRECTIVE_SIZE,
DIRECTIVE_STRING,
DIRECTIVE_SYNTAX,
DIRECTIVE_T61String,
DIRECTIVE_TAGS,
DIRECTIVE_TRUE,
DIRECTIVE_TeletexString,
DIRECTIVE_UNION,
DIRECTIVE_UNIQUE,
DIRECTIVE_UNIVERSAL,
DIRECTIVE_UTCTime,
DIRECTIVE_UTF8String,
DIRECTIVE_UniversalString,
DIRECTIVE_VideotexString,
DIRECTIVE_VisibleString,
DIRECTIVE_WITH,
NR__DIRECTIVES,
TOKEN_ASSIGNMENT = NR__DIRECTIVES,
TOKEN_OPEN_CURLY,
TOKEN_CLOSE_CURLY,
TOKEN_OPEN_SQUARE,
TOKEN_CLOSE_SQUARE,
TOKEN_OPEN_ACTION,
TOKEN_CLOSE_ACTION,
TOKEN_COMMA,
TOKEN_NUMBER,
TOKEN_TYPE_NAME,
TOKEN_ELEMENT_NAME,
NR__TOKENS
};
static const unsigned char token_to_tag[NR__TOKENS] = {
/* EOC goes first */
[DIRECTIVE_BOOLEAN] = ASN1_BOOL,
[DIRECTIVE_INTEGER] = ASN1_INT,
[DIRECTIVE_BIT] = ASN1_BTS,
[DIRECTIVE_OCTET] = ASN1_OTS,
[DIRECTIVE_NULL] = ASN1_NULL,
[DIRECTIVE_OBJECT] = ASN1_OID,
[DIRECTIVE_ObjectDescriptor] = ASN1_ODE,
[DIRECTIVE_EXTERNAL] = ASN1_EXT,
[DIRECTIVE_REAL] = ASN1_REAL,
[DIRECTIVE_ENUMERATED] = ASN1_ENUM,
[DIRECTIVE_EMBEDDED] = 0,
[DIRECTIVE_UTF8String] = ASN1_UTF8STR,
[DIRECTIVE_RELATIVE_OID] = ASN1_RELOID,
/* 14 */
/* 15 */
[DIRECTIVE_SEQUENCE] = ASN1_SEQ,
[DIRECTIVE_SET] = ASN1_SET,
[DIRECTIVE_NumericString] = ASN1_NUMSTR,
[DIRECTIVE_PrintableString] = ASN1_PRNSTR,
[DIRECTIVE_T61String] = ASN1_TEXSTR,
[DIRECTIVE_TeletexString] = ASN1_TEXSTR,
[DIRECTIVE_VideotexString] = ASN1_VIDSTR,
[DIRECTIVE_IA5String] = ASN1_IA5STR,
[DIRECTIVE_UTCTime] = ASN1_UNITIM,
[DIRECTIVE_GeneralizedTime] = ASN1_GENTIM,
[DIRECTIVE_GraphicString] = ASN1_GRASTR,
[DIRECTIVE_VisibleString] = ASN1_VISSTR,
[DIRECTIVE_GeneralString] = ASN1_GENSTR,
[DIRECTIVE_UniversalString] = ASN1_UNITIM,
[DIRECTIVE_CHARACTER] = ASN1_CHRSTR,
[DIRECTIVE_BMPString] = ASN1_BMPSTR,
};
static const char asn1_classes[4][5] = {
[ASN1_UNIV] = "UNIV",
[ASN1_APPL] = "APPL",
[ASN1_CONT] = "CONT",
[ASN1_PRIV] = "PRIV"
};
static const char asn1_methods[2][5] = {
[ASN1_UNIV] = "PRIM",
[ASN1_APPL] = "CONS"
};
static const char *const asn1_universal_tags[32] = {
"EOC",
"BOOL",
"INT",
"BTS",
"OTS",
"NULL",
"OID",
"ODE",
"EXT",
"REAL",
"ENUM",
"EPDV",
"UTF8STR",
"RELOID",
NULL, /* 14 */
NULL, /* 15 */
"SEQ",
"SET",
"NUMSTR",
"PRNSTR",
"TEXSTR",
"VIDSTR",
"IA5STR",
"UNITIM",
"GENTIM",
"GRASTR",
"VISSTR",
"GENSTR",
"UNISTR",
"CHRSTR",
"BMPSTR",
NULL /* 31 */
};
static const char *filename;
static const char *grammar_name;
static const char *outputname;
static const char *headername;
static const char *const directives[NR__DIRECTIVES] = {
#define _(X) [DIRECTIVE_##X] = #X
_(ABSENT),
_(ALL),
_(ANY),
_(APPLICATION),
_(AUTOMATIC),
_(BEGIN),
_(BIT),
_(BMPString),
_(BOOLEAN),
_(BY),
_(CHARACTER),
_(CHOICE),
_(CLASS),
_(COMPONENT),
_(COMPONENTS),
_(CONSTRAINED),
_(CONTAINING),
_(DEFAULT),
_(DEFINED),
_(DEFINITIONS),
_(EMBEDDED),
_(ENCODED),
[DIRECTIVE_ENCODING_CONTROL] = "ENCODING-CONTROL",
_(END),
_(ENUMERATED),
_(EXCEPT),
_(EXPLICIT),
_(EXPORTS),
_(EXTENSIBILITY),
_(EXTERNAL),
_(FALSE),
_(FROM),
_(GeneralString),
_(GeneralizedTime),
_(GraphicString),
_(IA5String),
_(IDENTIFIER),
_(IMPLICIT),
_(IMPLIED),
_(IMPORTS),
_(INCLUDES),
_(INSTANCE),
_(INSTRUCTIONS),
_(INTEGER),
_(INTERSECTION),
_(ISO646String),
_(MAX),
_(MIN),
[DIRECTIVE_MINUS_INFINITY] = "MINUS-INFINITY",
[DIRECTIVE_NULL] = "NULL",
_(NumericString),
_(OBJECT),
_(OCTET),
_(OF),
_(OPTIONAL),
_(ObjectDescriptor),
_(PATTERN),
_(PDV),
[DIRECTIVE_PLUS_INFINITY] = "PLUS-INFINITY",
_(PRESENT),
_(PRIVATE),
_(PrintableString),
_(REAL),
[DIRECTIVE_RELATIVE_OID] = "RELATIVE-OID",
_(SEQUENCE),
_(SET),
_(SIZE),
_(STRING),
_(SYNTAX),
_(T61String),
_(TAGS),
_(TRUE),
_(TeletexString),
_(UNION),
_(UNIQUE),
_(UNIVERSAL),
_(UTCTime),
_(UTF8String),
_(UniversalString),
_(VideotexString),
_(VisibleString),
_(WITH)
};
struct action {
struct action *next;
unsigned char index;
char name[];
};
static struct action *action_list;
static unsigned nr_actions;
struct token {
unsigned short line;
enum token_type token_type : 8;
unsigned char size;
struct action *action;
const char *value;
struct type *type;
};
static struct token *token_list;
static unsigned nr_tokens;
static int directive_compare(const void *_key, const void *_pdir)
{
const struct token *token = _key;
const char *const *pdir = _pdir, *dir = *pdir;
size_t dlen, clen;
int val;
dlen = strlen(dir);
clen = (dlen < token->size) ? dlen : token->size;
//printf("cmp(%*.*s,%s) = ",
// (int)token->size, (int)token->size, token->value,
// dir);
val = memcmp(token->value, dir, clen);
if (val != 0) {
//printf("%d [cmp]\n", val);
return val;
}
if (dlen == token->size) {
//printf("0\n");
return 0;
}
//printf("%d\n", (int)dlen - (int)token->size);
return dlen - token->size; /* shorter -> negative */
}
/*
* Tokenise an ASN.1 grammar
*/
static void tokenise(char *buffer, char *end)
{
struct token *tokens;
char *line, *nl, *p, *q;
unsigned tix, lineno;
/* Assume we're going to have half as many tokens as we have
* characters
*/
token_list = tokens = calloc((end - buffer) / 2, sizeof(struct token));
if (!tokens) {
perror(NULL);
exit(1);
}
tix = 0;
lineno = 0;
while (buffer < end) {
/* First of all, break out a line */
lineno++;
line = buffer;
nl = memchr(line, '\n', end - buffer);
if (!nl) {
buffer = nl = end;
} else {
buffer = nl + 1;
*nl = '\0';
}
/* Remove "--" comments */
p = line;
next_comment:
while ((p = memchr(p, '-', nl - p))) {
if (p[1] == '-') {
/* Found a comment; see if there's a terminator */
q = p + 2;
while ((q = memchr(q, '-', nl - q))) {
if (q[1] == '-') {
/* There is - excise the comment */
q += 2;
memmove(p, q, nl - q);
goto next_comment;
}
q++;
}
*p = '\0';
nl = p;
break;
} else {
p++;
}
}
p = line;
while (p < nl) {
/* Skip white space */
while (p < nl && isspace(*p))
*(p++) = 0;
if (p >= nl)
break;
tokens[tix].line = lineno;
tokens[tix].value = p;
/* Handle string tokens */
if (isalpha(*p)) {
const char **dir;
/* Can be a directive, type name or element
* name. Find the end of the name.
*/
q = p + 1;
while (q < nl && (isalnum(*q) || *q == '-' || *q == '_'))
q++;
tokens[tix].size = q - p;
p = q;
/* If it begins with a lowercase letter then
* it's an element name
*/
if (islower(tokens[tix].value[0])) {
tokens[tix++].token_type = TOKEN_ELEMENT_NAME;
continue;
}
/* Otherwise we need to search the directive
* table
*/
dir = bsearch(&tokens[tix], directives,
sizeof(directives) / sizeof(directives[1]),
sizeof(directives[1]),
directive_compare);
if (dir) {
tokens[tix++].token_type = dir - directives;
continue;
}
tokens[tix++].token_type = TOKEN_TYPE_NAME;
continue;
}
/* Handle numbers */
if (isdigit(*p)) {
/* Find the end of the number */
q = p + 1;
while (q < nl && (isdigit(*q)))
q++;
tokens[tix].size = q - p;
p = q;
tokens[tix++].token_type = TOKEN_NUMBER;
continue;
}
if (nl - p >= 3) {
if (memcmp(p, "::=", 3) == 0) {
p += 3;
tokens[tix].size = 3;
tokens[tix++].token_type = TOKEN_ASSIGNMENT;
continue;
}
}
if (nl - p >= 2) {
if (memcmp(p, "({", 2) == 0) {
p += 2;
tokens[tix].size = 2;
tokens[tix++].token_type = TOKEN_OPEN_ACTION;
continue;
}
if (memcmp(p, "})", 2) == 0) {
p += 2;
tokens[tix].size = 2;
tokens[tix++].token_type = TOKEN_CLOSE_ACTION;
continue;
}
}
if (nl - p >= 1) {
tokens[tix].size = 1;
switch (*p) {
case '{':
p += 1;
tokens[tix++].token_type = TOKEN_OPEN_CURLY;
continue;
case '}':
p += 1;
tokens[tix++].token_type = TOKEN_CLOSE_CURLY;
continue;
case '[':
p += 1;
tokens[tix++].token_type = TOKEN_OPEN_SQUARE;
continue;
case ']':
p += 1;
tokens[tix++].token_type = TOKEN_CLOSE_SQUARE;
continue;
case ',':
p += 1;
tokens[tix++].token_type = TOKEN_COMMA;
continue;
default:
break;
}
}
fprintf(stderr, "%s:%u: Unknown character in grammar: '%c'\n",
filename, lineno, *p);
exit(1);
}
}
nr_tokens = tix;
printf("Extracted %u tokens\n", nr_tokens);
#if 0
{
int n;
for (n = 0; n < nr_tokens; n++)
printf("Token %3u: '%*.*s'\n",
n,
(int)token_list[n].size, (int)token_list[n].size,
token_list[n].value);
}
#endif
}
static void build_type_list(void);
static void parse(void);
static void render(FILE *out, FILE *hdr);
/*
*
*/
int main(int argc, char **argv)
{
struct stat st;
ssize_t readlen;
FILE *out, *hdr;
char *buffer, *p;
int fd;
if (argc != 4) {
fprintf(stderr, "Format: %s <grammar-file> <c-file> <hdr-file>\n",
argv[0]);
exit(2);
}
filename = argv[1];
outputname = argv[2];
headername = argv[3];
fd = open(filename, O_RDONLY);
if (fd < 0) {
perror(filename);
exit(1);
}
if (fstat(fd, &st) < 0) {
perror(filename);
exit(1);
}
if (!(buffer = malloc(st.st_size + 1))) {
perror(NULL);
exit(1);
}
if ((readlen = read(fd, buffer, st.st_size)) < 0) {
perror(filename);
exit(1);
}
if (close(fd) < 0) {
perror(filename);
exit(1);
}
if (readlen != st.st_size) {
fprintf(stderr, "%s: Short read\n", filename);
exit(1);
}
p = strrchr(argv[1], '/');
p = p ? p + 1 : argv[1];
grammar_name = strdup(p);
if (!p) {
perror(NULL);
exit(1);
}
p = strchr(grammar_name, '.');
if (p)
*p = '\0';
buffer[readlen] = 0;
tokenise(buffer, buffer + readlen);
build_type_list();
parse();
out = fopen(outputname, "w");
if (!out) {
perror(outputname);
exit(1);
}
hdr = fopen(headername, "w");
if (!out) {
perror(headername);
exit(1);
}
render(out, hdr);
if (fclose(out) < 0) {
perror(outputname);
exit(1);
}
if (fclose(hdr) < 0) {
perror(headername);
exit(1);
}
return 0;
}
enum compound {
NOT_COMPOUND,
SET,
SET_OF,
SEQUENCE,
SEQUENCE_OF,
CHOICE,
ANY,
TYPE_REF,
TAG_OVERRIDE
};
struct element {
struct type *type_def;
struct token *name;
struct token *type;
struct action *action;
struct element *children;
struct element *next;
struct element *render_next;
struct element *list_next;
uint8_t n_elements;
enum compound compound : 8;
enum asn1_class class : 8;
enum asn1_method method : 8;
uint8_t tag;
unsigned entry_index;
unsigned flags;
#define ELEMENT_IMPLICIT 0x0001
#define ELEMENT_EXPLICIT 0x0002
#define ELEMENT_MARKED 0x0004
#define ELEMENT_RENDERED 0x0008
#define ELEMENT_SKIPPABLE 0x0010
#define ELEMENT_CONDITIONAL 0x0020
};
struct type {
struct token *name;
struct token *def;
struct element *element;
unsigned ref_count;
unsigned flags;
#define TYPE_STOP_MARKER 0x0001
#define TYPE_BEGIN 0x0002
};
static struct type *type_list;
static struct type **type_index;
static unsigned nr_types;
static int type_index_compare(const void *_a, const void *_b)
{
const struct type *const *a = _a, *const *b = _b;
if ((*a)->name->size != (*b)->name->size)
return (*a)->name->size - (*b)->name->size;
else
return memcmp((*a)->name->value, (*b)->name->value,
(*a)->name->size);
}
static int type_finder(const void *_key, const void *_ti)
{
const struct token *token = _key;
const struct type *const *ti = _ti;
const struct type *type = *ti;
if (token->size != type->name->size)
return token->size - type->name->size;
else
return memcmp(token->value, type->name->value,
token->size);
}
/*
* Build up a list of types and a sorted index to that list.
*/
static void build_type_list(void)
{
struct type *types;
unsigned nr, t, n;
nr = 0;
for (n = 0; n < nr_tokens - 1; n++)
if (token_list[n + 0].token_type == TOKEN_TYPE_NAME &&
token_list[n + 1].token_type == TOKEN_ASSIGNMENT)
nr++;
if (nr == 0) {
fprintf(stderr, "%s: No defined types\n", filename);
exit(1);
}
nr_types = nr;
types = type_list = calloc(nr + 1, sizeof(type_list[0]));
if (!type_list) {
perror(NULL);
exit(1);
}
type_index = calloc(nr, sizeof(type_index[0]));
if (!type_index) {
perror(NULL);
exit(1);
}
t = 0;
types[t].flags |= TYPE_BEGIN;
for (n = 0; n < nr_tokens - 1; n++) {
if (token_list[n + 0].token_type == TOKEN_TYPE_NAME &&
token_list[n + 1].token_type == TOKEN_ASSIGNMENT) {
types[t].name = &token_list[n];
type_index[t] = &types[t];
t++;
}
}
types[t].name = &token_list[n + 1];
types[t].flags |= TYPE_STOP_MARKER;
qsort(type_index, nr, sizeof(type_index[0]), type_index_compare);
printf("Extracted %u types\n", nr_types);
#if 0
for (n = 0; n < nr_types; n++) {
struct type *type = type_index[n];
printf("- %*.*s\n",
(int)type->name->size,
(int)type->name->size,
type->name->value);
}
#endif
}
static struct element *parse_type(struct token **_cursor, struct token *stop,
struct token *name);
/*
* Parse the token stream
*/
static void parse(void)
{
struct token *cursor;
struct type *type;
/* Parse one type definition statement at a time */
type = type_list;
do {
cursor = type->name;
if (cursor[0].token_type != TOKEN_TYPE_NAME ||
cursor[1].token_type != TOKEN_ASSIGNMENT)
abort();
cursor += 2;
type->element = parse_type(&cursor, type[1].name, NULL);
type->element->type_def = type;
if (cursor != type[1].name) {
fprintf(stderr, "%s:%d: Parse error at token '%*.*s'\n",
filename, cursor->line,
(int)cursor->size, (int)cursor->size, cursor->value);
exit(1);
}
} while (type++, !(type->flags & TYPE_STOP_MARKER));
printf("Extracted %u actions\n", nr_actions);
}
static struct element *element_list;
static struct element *alloc_elem(struct token *type)
{
struct element *e = calloc(1, sizeof(*e));
if (!e) {
perror(NULL);
exit(1);
}
e->list_next = element_list;
element_list = e;
return e;
}
static struct element *parse_compound(struct token **_cursor, struct token *end,
int alternates);
/*
* Parse one type definition statement
*/
static struct element *parse_type(struct token **_cursor, struct token *end,
struct token *name)
{
struct element *top, *element;
struct action *action, **ppaction;
struct token *cursor = *_cursor;
struct type **ref;
char *p;
int labelled = 0, implicit = 0;
top = element = alloc_elem(cursor);
element->class = ASN1_UNIV;
element->method = ASN1_PRIM;
element->tag = token_to_tag[cursor->token_type];
element->name = name;
/* Extract the tag value if one given */
if (cursor->token_type == TOKEN_OPEN_SQUARE) {
cursor++;
if (cursor >= end)
goto overrun_error;
switch (cursor->token_type) {
case DIRECTIVE_UNIVERSAL:
element->class = ASN1_UNIV;
cursor++;
break;
case DIRECTIVE_APPLICATION:
element->class = ASN1_APPL;
cursor++;
break;
case TOKEN_NUMBER:
element->class = ASN1_CONT;
break;
case DIRECTIVE_PRIVATE:
element->class = ASN1_PRIV;
cursor++;
break;
default:
fprintf(stderr, "%s:%d: Unrecognised tag class token '%*.*s'\n",
filename, cursor->line,
(int)cursor->size, (int)cursor->size, cursor->value);
exit(1);
}
if (cursor >= end)
goto overrun_error;
if (cursor->token_type != TOKEN_NUMBER) {
fprintf(stderr, "%s:%d: Missing tag number '%*.*s'\n",
filename, cursor->line,
(int)cursor->size, (int)cursor->size, cursor->value);
exit(1);
}
element->tag &= ~0x1f;
element->tag |= strtoul(cursor->value, &p, 10);
if (p - cursor->value != cursor->size)
abort();
cursor++;
if (cursor >= end)
goto overrun_error;
if (cursor->token_type != TOKEN_CLOSE_SQUARE) {
fprintf(stderr, "%s:%d: Missing closing square bracket '%*.*s'\n",
filename, cursor->line,
(int)cursor->size, (int)cursor->size, cursor->value);
exit(1);
}
cursor++;
if (cursor >= end)
goto overrun_error;
labelled = 1;
}
/* Handle implicit and explicit markers */
if (cursor->token_type == DIRECTIVE_IMPLICIT) {
element->flags |= ELEMENT_IMPLICIT;
implicit = 1;
cursor++;
if (cursor >= end)
goto overrun_error;
} else if (cursor->token_type == DIRECTIVE_EXPLICIT) {
element->flags |= ELEMENT_EXPLICIT;
cursor++;
if (cursor >= end)
goto overrun_error;
}
if (labelled) {
if (!implicit)
element->method |= ASN1_CONS;
element->compound = implicit ? TAG_OVERRIDE : SEQUENCE;
element->children = alloc_elem(cursor);
element = element->children;
element->class = ASN1_UNIV;
element->method = ASN1_PRIM;
element->tag = token_to_tag[cursor->token_type];
element->name = name;
}
/* Extract the type we're expecting here */
element->type = cursor;
switch (cursor->token_type) {
case DIRECTIVE_ANY:
element->compound = ANY;
cursor++;
break;
case DIRECTIVE_NULL:
case DIRECTIVE_BOOLEAN:
case DIRECTIVE_ENUMERATED:
case DIRECTIVE_INTEGER:
element->compound = NOT_COMPOUND;
cursor++;
break;
case DIRECTIVE_EXTERNAL:
element->method = ASN1_CONS;
case DIRECTIVE_BMPString:
case DIRECTIVE_GeneralString:
case DIRECTIVE_GraphicString:
case DIRECTIVE_IA5String:
case DIRECTIVE_ISO646String:
case DIRECTIVE_NumericString:
case DIRECTIVE_PrintableString:
case DIRECTIVE_T61String:
case DIRECTIVE_TeletexString:
case DIRECTIVE_UniversalString:
case DIRECTIVE_UTF8String:
case DIRECTIVE_VideotexString:
case DIRECTIVE_VisibleString:
case DIRECTIVE_ObjectDescriptor:
case DIRECTIVE_GeneralizedTime:
case DIRECTIVE_UTCTime:
element->compound = NOT_COMPOUND;
cursor++;
break;
case DIRECTIVE_BIT:
case DIRECTIVE_OCTET:
element->compound = NOT_COMPOUND;
cursor++;
if (cursor >= end)
goto overrun_error;
if (cursor->token_type != DIRECTIVE_STRING)
goto parse_error;
cursor++;
break;
case DIRECTIVE_OBJECT:
element->compound = NOT_COMPOUND;
cursor++;
if (cursor >= end)
goto overrun_error;
if (cursor->token_type != DIRECTIVE_IDENTIFIER)
goto parse_error;
cursor++;
break;
case TOKEN_TYPE_NAME:
element->compound = TYPE_REF;
ref = bsearch(cursor, type_index, nr_types, sizeof(type_index[0]),
type_finder);
if (!ref) {
fprintf(stderr, "%s:%d: Type '%*.*s' undefined\n",
filename, cursor->line,
(int)cursor->size, (int)cursor->size, cursor->value);
exit(1);
}
cursor->type = *ref;
(*ref)->ref_count++;
cursor++;
break;
case DIRECTIVE_CHOICE:
element->compound = CHOICE;
cursor++;
element->children = parse_compound(&cursor, end, 1);
break;
case DIRECTIVE_SEQUENCE:
element->compound = SEQUENCE;
element->method = ASN1_CONS;
cursor++;
if (cursor >= end)
goto overrun_error;
if (cursor->token_type == DIRECTIVE_OF) {
element->compound = SEQUENCE_OF;
cursor++;
if (cursor >= end)
goto overrun_error;
element->children = parse_type(&cursor, end, NULL);
} else {
element->children = parse_compound(&cursor, end, 0);
}
break;
case DIRECTIVE_SET:
element->compound = SET;
element->method = ASN1_CONS;
cursor++;
if (cursor >= end)
goto overrun_error;
if (cursor->token_type == DIRECTIVE_OF) {
element->compound = SET_OF;
cursor++;
if (cursor >= end)
goto parse_error;
element->children = parse_type(&cursor, end, NULL);
} else {
element->children = parse_compound(&cursor, end, 1);
}
break;
default:
fprintf(stderr, "%s:%d: Token '%*.*s' does not introduce a type\n",
filename, cursor->line,
(int)cursor->size, (int)cursor->size, cursor->value);
exit(1);
}
/* Handle elements that are optional */
if (cursor < end && (cursor->token_type == DIRECTIVE_OPTIONAL ||
cursor->token_type == DIRECTIVE_DEFAULT)
) {
cursor++;
top->flags |= ELEMENT_SKIPPABLE;
}
if (cursor < end && cursor->token_type == TOKEN_OPEN_ACTION) {
cursor++;
if (cursor >= end)
goto overrun_error;
if (cursor->token_type != TOKEN_ELEMENT_NAME) {
fprintf(stderr, "%s:%d: Token '%*.*s' is not an action function name\n",
filename, cursor->line,
(int)cursor->size, (int)cursor->size, cursor->value);
exit(1);
}
action = malloc(sizeof(struct action) + cursor->size + 1);
if (!action) {
perror(NULL);
exit(1);
}
action->index = 0;
memcpy(action->name, cursor->value, cursor->size);
action->name[cursor->size] = 0;
for (ppaction = &action_list;
*ppaction;
ppaction = &(*ppaction)->next
) {
int cmp = strcmp(action->name, (*ppaction)->name);
if (cmp == 0) {
free(action);
action = *ppaction;
goto found;
}
if (cmp < 0) {
action->next = *ppaction;
*ppaction = action;
nr_actions++;
goto found;
}
}
action->next = NULL;
*ppaction = action;
nr_actions++;
found:
element->action = action;
cursor->action = action;
cursor++;
if (cursor >= end)
goto overrun_error;
if (cursor->token_type != TOKEN_CLOSE_ACTION) {
fprintf(stderr, "%s:%d: Missing close action, got '%*.*s'\n",
filename, cursor->line,
(int)cursor->size, (int)cursor->size, cursor->value);
exit(1);
}
cursor++;
}
*_cursor = cursor;
return top;
parse_error:
fprintf(stderr, "%s:%d: Unexpected token '%*.*s'\n",
filename, cursor->line,
(int)cursor->size, (int)cursor->size, cursor->value);
exit(1);
overrun_error:
fprintf(stderr, "%s: Unexpectedly hit EOF\n", filename);
exit(1);
}
/*
* Parse a compound type list
*/
static struct element *parse_compound(struct token **_cursor, struct token *end,
int alternates)
{
struct element *children, **child_p = &children, *element;
struct token *cursor = *_cursor, *name;
if (cursor->token_type != TOKEN_OPEN_CURLY) {
fprintf(stderr, "%s:%d: Expected compound to start with brace not '%*.*s'\n",
filename, cursor->line,
(int)cursor->size, (int)cursor->size, cursor->value);
exit(1);
}
cursor++;
if (cursor >= end)
goto overrun_error;
if (cursor->token_type == TOKEN_OPEN_CURLY) {
fprintf(stderr, "%s:%d: Empty compound\n",
filename, cursor->line);
exit(1);
}
for (;;) {
name = NULL;
if (cursor->token_type == TOKEN_ELEMENT_NAME) {
name = cursor;
cursor++;
if (cursor >= end)
goto overrun_error;
}
element = parse_type(&cursor, end, name);
if (alternates)
element->flags |= ELEMENT_SKIPPABLE | ELEMENT_CONDITIONAL;
*child_p = element;
child_p = &element->next;
if (cursor >= end)
goto overrun_error;
if (cursor->token_type != TOKEN_COMMA)
break;
cursor++;
if (cursor >= end)
goto overrun_error;
}
children->flags &= ~ELEMENT_CONDITIONAL;
if (cursor->token_type != TOKEN_CLOSE_CURLY) {
fprintf(stderr, "%s:%d: Expected compound closure, got '%*.*s'\n",
filename, cursor->line,
(int)cursor->size, (int)cursor->size, cursor->value);
exit(1);
}
cursor++;
*_cursor = cursor;
return children;
overrun_error:
fprintf(stderr, "%s: Unexpectedly hit EOF\n", filename);
exit(1);
}
static void render_element(FILE *out, struct element *e, struct element *tag);
static void render_out_of_line_list(FILE *out);
static int nr_entries;
static int render_depth = 1;
static struct element *render_list, **render_list_p = &render_list;
__attribute__((format(printf, 2, 3)))
static void render_opcode(FILE *out, const char *fmt, ...)
{
va_list va;
if (out) {
fprintf(out, "\t[%4d] =%*s", nr_entries, render_depth, "");
va_start(va, fmt);
vfprintf(out, fmt, va);
va_end(va);
}
nr_entries++;
}
__attribute__((format(printf, 2, 3)))
static void render_more(FILE *out, const char *fmt, ...)
{
va_list va;
if (out) {
va_start(va, fmt);
vfprintf(out, fmt, va);
va_end(va);
}
}
/*
* Render the grammar into a state machine definition.
*/
static void render(FILE *out, FILE *hdr)
{
struct element *e;
struct action *action;
struct type *root;
int index;
fprintf(hdr, "/*\n");
fprintf(hdr, " * Automatically generated by asn1_compiler. Do not edit\n");
fprintf(hdr, " *\n");
fprintf(hdr, " * ASN.1 parser for %s\n", grammar_name);
fprintf(hdr, " */\n");
fprintf(hdr, "#include <linux/asn1_decoder.h>\n");
fprintf(hdr, "\n");
fprintf(hdr, "extern const struct asn1_decoder %s_decoder;\n", grammar_name);
if (ferror(hdr)) {
perror(headername);
exit(1);
}
fprintf(out, "/*\n");
fprintf(out, " * Automatically generated by asn1_compiler. Do not edit\n");
fprintf(out, " *\n");
fprintf(out, " * ASN.1 parser for %s\n", grammar_name);
fprintf(out, " */\n");
fprintf(out, "#include <linux/asn1_ber_bytecode.h>\n");
fprintf(out, "#include \"%s-asn1.h\"\n", grammar_name);
fprintf(out, "\n");
if (ferror(out)) {
perror(outputname);
exit(1);
}
/* Tabulate the action functions we might have to call */
fprintf(hdr, "\n");
index = 0;
for (action = action_list; action; action = action->next) {
action->index = index++;
fprintf(hdr,
"extern int %s(void *, size_t, unsigned char,"
" const void *, size_t);\n",
action->name);
}
fprintf(hdr, "\n");
fprintf(out, "enum %s_actions {\n", grammar_name);
for (action = action_list; action; action = action->next)
fprintf(out, "\tACT_%s = %u,\n",
action->name, action->index);
fprintf(out, "\tNR__%s_actions = %u\n", grammar_name, nr_actions);
fprintf(out, "};\n");
fprintf(out, "\n");
fprintf(out, "static const asn1_action_t %s_action_table[NR__%s_actions] = {\n",
grammar_name, grammar_name);
for (action = action_list; action; action = action->next)
fprintf(out, "\t[%4u] = %s,\n", action->index, action->name);
fprintf(out, "};\n");
if (ferror(out)) {
perror(outputname);
exit(1);
}
/* We do two passes - the first one calculates all the offsets */
printf("Pass 1\n");
nr_entries = 0;
root = &type_list[0];
render_element(NULL, root->element, NULL);
render_opcode(NULL, "ASN1_OP_COMPLETE,\n");
render_out_of_line_list(NULL);
for (e = element_list; e; e = e->list_next)
e->flags &= ~ELEMENT_RENDERED;
/* And then we actually render */
printf("Pass 2\n");
fprintf(out, "\n");
fprintf(out, "static const unsigned char %s_machine[] = {\n",
grammar_name);
nr_entries = 0;
root = &type_list[0];
render_element(out, root->element, NULL);
render_opcode(out, "ASN1_OP_COMPLETE,\n");
render_out_of_line_list(out);
fprintf(out, "};\n");
fprintf(out, "\n");
fprintf(out, "const struct asn1_decoder %s_decoder = {\n", grammar_name);
fprintf(out, "\t.machine = %s_machine,\n", grammar_name);
fprintf(out, "\t.machlen = sizeof(%s_machine),\n", grammar_name);
fprintf(out, "\t.actions = %s_action_table,\n", grammar_name);
fprintf(out, "};\n");
}
/*
* Render the out-of-line elements
*/
static void render_out_of_line_list(FILE *out)
{
struct element *e, *ce;
const char *act;
int entry;
while ((e = render_list)) {
render_list = e->render_next;
if (!render_list)
render_list_p = &render_list;
render_more(out, "\n");
e->entry_index = entry = nr_entries;
render_depth++;
for (ce = e->children; ce; ce = ce->next)
render_element(out, ce, NULL);
render_depth--;
act = e->action ? "_ACT" : "";
switch (e->compound) {
case SEQUENCE:
render_opcode(out, "ASN1_OP_END_SEQ%s,\n", act);
break;
case SEQUENCE_OF:
render_opcode(out, "ASN1_OP_END_SEQ_OF%s,\n", act);
render_opcode(out, "_jump_target(%u),\n", entry);
break;
case SET:
render_opcode(out, "ASN1_OP_END_SET%s,\n", act);
break;
case SET_OF:
render_opcode(out, "ASN1_OP_END_SET_OF%s,\n", act);
render_opcode(out, "_jump_target(%u),\n", entry);
break;
default:
break;
}
if (e->action)
render_opcode(out, "_action(ACT_%s),\n",
e->action->name);
render_opcode(out, "ASN1_OP_RETURN,\n");
}
}
/*
* Render an element.
*/
static void render_element(FILE *out, struct element *e, struct element *tag)
{
struct element *ec;
const char *cond, *act;
int entry, skippable = 0, outofline = 0;
if (e->flags & ELEMENT_SKIPPABLE ||
(tag && tag->flags & ELEMENT_SKIPPABLE))
skippable = 1;
if ((e->type_def && e->type_def->ref_count > 1) ||
skippable)
outofline = 1;
if (e->type_def && out) {
render_more(out, "\t// %*.*s\n",
(int)e->type_def->name->size, (int)e->type_def->name->size,
e->type_def->name->value);
}
/* Render the operation */
cond = (e->flags & ELEMENT_CONDITIONAL ||
(tag && tag->flags & ELEMENT_CONDITIONAL)) ? "COND_" : "";
act = e->action ? "_ACT" : "";
switch (e->compound) {
case ANY:
render_opcode(out, "ASN1_OP_%sMATCH_ANY%s,", cond, act);
if (e->name)
render_more(out, "\t\t// %*.*s",
(int)e->name->size, (int)e->name->size,
e->name->value);
render_more(out, "\n");
goto dont_render_tag;
case TAG_OVERRIDE:
render_element(out, e->children, e);
return;
case SEQUENCE:
case SEQUENCE_OF:
case SET:
case SET_OF:
render_opcode(out, "ASN1_OP_%sMATCH%s%s,",
cond,
outofline ? "_JUMP" : "",
skippable ? "_OR_SKIP" : "");
break;
case CHOICE:
goto dont_render_tag;
case TYPE_REF:
if (e->class == ASN1_UNIV && e->method == ASN1_PRIM && e->tag == 0)
goto dont_render_tag;
default:
render_opcode(out, "ASN1_OP_%sMATCH%s%s,",
cond, act,
skippable ? "_OR_SKIP" : "");
break;
}
if (e->name)
render_more(out, "\t\t// %*.*s",
(int)e->name->size, (int)e->name->size,
e->name->value);
render_more(out, "\n");
/* Render the tag */
if (!tag)
tag = e;
if (tag->class == ASN1_UNIV &&
tag->tag != 14 &&
tag->tag != 15 &&
tag->tag != 31)
render_opcode(out, "_tag(%s, %s, %s),\n",
asn1_classes[tag->class],
asn1_methods[tag->method | e->method],
asn1_universal_tags[tag->tag]);
else
render_opcode(out, "_tagn(%s, %s, %2u),\n",
asn1_classes[tag->class],
asn1_methods[tag->method | e->method],
tag->tag);
tag = NULL;
dont_render_tag:
/* Deal with compound types */
switch (e->compound) {
case TYPE_REF:
render_element(out, e->type->type->element, tag);
if (e->action)
render_opcode(out, "ASN1_OP_ACT,\n");
break;
case SEQUENCE:
if (outofline) {
/* Render out-of-line for multiple use or
* skipability */
render_opcode(out, "_jump_target(%u),", e->entry_index);
if (e->type_def && e->type_def->name)
render_more(out, "\t\t// --> %*.*s",
(int)e->type_def->name->size,
(int)e->type_def->name->size,
e->type_def->name->value);
render_more(out, "\n");
if (!(e->flags & ELEMENT_RENDERED)) {
e->flags |= ELEMENT_RENDERED;
*render_list_p = e;
render_list_p = &e->render_next;
}
return;
} else {
/* Render inline for single use */
render_depth++;
for (ec = e->children; ec; ec = ec->next)
render_element(out, ec, NULL);
render_depth--;
render_opcode(out, "ASN1_OP_END_SEQ%s,\n", act);
}
break;
case SEQUENCE_OF:
case SET_OF:
if (outofline) {
/* Render out-of-line for multiple use or
* skipability */
render_opcode(out, "_jump_target(%u),", e->entry_index);
if (e->type_def && e->type_def->name)
render_more(out, "\t\t// --> %*.*s",
(int)e->type_def->name->size,
(int)e->type_def->name->size,
e->type_def->name->value);
render_more(out, "\n");
if (!(e->flags & ELEMENT_RENDERED)) {
e->flags |= ELEMENT_RENDERED;
*render_list_p = e;
render_list_p = &e->render_next;
}
return;
} else {
/* Render inline for single use */
entry = nr_entries;
render_depth++;
render_element(out, e->children, NULL);
render_depth--;
if (e->compound == SEQUENCE_OF)
render_opcode(out, "ASN1_OP_END_SEQ_OF%s,\n", act);
else
render_opcode(out, "ASN1_OP_END_SET_OF%s,\n", act);
render_opcode(out, "_jump_target(%u),\n", entry);
}
break;
case SET:
/* I can't think of a nice way to do SET support without having
* a stack of bitmasks to make sure no element is repeated.
* The bitmask has also to be checked that no non-optional
* elements are left out whilst not preventing optional
* elements from being left out.
*/
fprintf(stderr, "The ASN.1 SET type is not currently supported.\n");
exit(1);
case CHOICE:
for (ec = e->children; ec; ec = ec->next)
render_element(out, ec, NULL);
if (!skippable)
render_opcode(out, "ASN1_OP_COND_FAIL,\n");
if (e->action)
render_opcode(out, "ASN1_OP_ACT,\n");
break;
default:
break;
}
if (e->action)
render_opcode(out, "_action(ACT_%s),\n", e->action->name);
}
| gpl-2.0 |
sricharanaz/iommu | drivers/gpu/drm/i915/intel_acpi.c | 1591 | 3696 | /*
* Intel ACPI functions
*
* _DSM related code stolen from nouveau_acpi.c.
*/
#include <linux/pci.h>
#include <linux/acpi.h>
#include <linux/vga_switcheroo.h>
#include <drm/drmP.h>
#include "i915_drv.h"
#define INTEL_DSM_REVISION_ID 1 /* For Calpella anyway... */
#define INTEL_DSM_FN_PLATFORM_MUX_INFO 1 /* No args */
static struct intel_dsm_priv {
acpi_handle dhandle;
} intel_dsm_priv;
static const u8 intel_dsm_guid[] = {
0xd3, 0x73, 0xd8, 0x7e,
0xd0, 0xc2,
0x4f, 0x4e,
0xa8, 0x54,
0x0f, 0x13, 0x17, 0xb0, 0x1c, 0x2c
};
static char *intel_dsm_port_name(u8 id)
{
switch (id) {
case 0:
return "Reserved";
case 1:
return "Analog VGA";
case 2:
return "LVDS";
case 3:
return "Reserved";
case 4:
return "HDMI/DVI_B";
case 5:
return "HDMI/DVI_C";
case 6:
return "HDMI/DVI_D";
case 7:
return "DisplayPort_A";
case 8:
return "DisplayPort_B";
case 9:
return "DisplayPort_C";
case 0xa:
return "DisplayPort_D";
case 0xb:
case 0xc:
case 0xd:
return "Reserved";
case 0xe:
return "WiDi";
default:
return "bad type";
}
}
static char *intel_dsm_mux_type(u8 type)
{
switch (type) {
case 0:
return "unknown";
case 1:
return "No MUX, iGPU only";
case 2:
return "No MUX, dGPU only";
case 3:
return "MUXed between iGPU and dGPU";
default:
return "bad type";
}
}
static void intel_dsm_platform_mux_info(void)
{
int i;
union acpi_object *pkg, *connector_count;
pkg = acpi_evaluate_dsm_typed(intel_dsm_priv.dhandle, intel_dsm_guid,
INTEL_DSM_REVISION_ID, INTEL_DSM_FN_PLATFORM_MUX_INFO,
NULL, ACPI_TYPE_PACKAGE);
if (!pkg) {
DRM_DEBUG_DRIVER("failed to evaluate _DSM\n");
return;
}
connector_count = &pkg->package.elements[0];
DRM_DEBUG_DRIVER("MUX info connectors: %lld\n",
(unsigned long long)connector_count->integer.value);
for (i = 1; i < pkg->package.count; i++) {
union acpi_object *obj = &pkg->package.elements[i];
union acpi_object *connector_id = &obj->package.elements[0];
union acpi_object *info = &obj->package.elements[1];
DRM_DEBUG_DRIVER("Connector id: 0x%016llx\n",
(unsigned long long)connector_id->integer.value);
DRM_DEBUG_DRIVER(" port id: %s\n",
intel_dsm_port_name(info->buffer.pointer[0]));
DRM_DEBUG_DRIVER(" display mux info: %s\n",
intel_dsm_mux_type(info->buffer.pointer[1]));
DRM_DEBUG_DRIVER(" aux/dc mux info: %s\n",
intel_dsm_mux_type(info->buffer.pointer[2]));
DRM_DEBUG_DRIVER(" hpd mux info: %s\n",
intel_dsm_mux_type(info->buffer.pointer[3]));
}
ACPI_FREE(pkg);
}
static bool intel_dsm_pci_probe(struct pci_dev *pdev)
{
acpi_handle dhandle;
dhandle = ACPI_HANDLE(&pdev->dev);
if (!dhandle)
return false;
if (!acpi_check_dsm(dhandle, intel_dsm_guid, INTEL_DSM_REVISION_ID,
1 << INTEL_DSM_FN_PLATFORM_MUX_INFO)) {
DRM_DEBUG_KMS("no _DSM method for intel device\n");
return false;
}
intel_dsm_priv.dhandle = dhandle;
intel_dsm_platform_mux_info();
return true;
}
static bool intel_dsm_detect(void)
{
char acpi_method_name[255] = { 0 };
struct acpi_buffer buffer = {sizeof(acpi_method_name), acpi_method_name};
struct pci_dev *pdev = NULL;
bool has_dsm = false;
int vga_count = 0;
while ((pdev = pci_get_class(PCI_CLASS_DISPLAY_VGA << 8, pdev)) != NULL) {
vga_count++;
has_dsm |= intel_dsm_pci_probe(pdev);
}
if (vga_count == 2 && has_dsm) {
acpi_get_name(intel_dsm_priv.dhandle, ACPI_FULL_PATHNAME, &buffer);
DRM_DEBUG_DRIVER("VGA switcheroo: detected DSM switching method %s handle\n",
acpi_method_name);
return true;
}
return false;
}
void intel_register_dsm_handler(void)
{
if (!intel_dsm_detect())
return;
}
void intel_unregister_dsm_handler(void)
{
}
| gpl-2.0 |
Falklore/shamu | drivers/net/wireless/iwlwifi/dvm/main.c | 1591 | 61324 | /******************************************************************************
*
* Copyright(c) 2003 - 2013 Intel Corporation. All rights reserved.
*
* Portions of this file are derived from the ipw3945 project, as well
* as portions of the ieee80211 subsystem header files.
*
* 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:
* Intel Linux Wireless <ilw@linux.intel.com>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*
*****************************************************************************/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/if_arp.h>
#include <net/mac80211.h>
#include <asm/div64.h>
#include "iwl-eeprom-read.h"
#include "iwl-eeprom-parse.h"
#include "iwl-io.h"
#include "iwl-trans.h"
#include "iwl-op-mode.h"
#include "iwl-drv.h"
#include "iwl-modparams.h"
#include "iwl-prph.h"
#include "dev.h"
#include "calib.h"
#include "agn.h"
/******************************************************************************
*
* module boiler plate
*
******************************************************************************/
/*
* module name, copyright, version, etc.
*/
#define DRV_DESCRIPTION "Intel(R) Wireless WiFi Link AGN driver for Linux"
#ifdef CONFIG_IWLWIFI_DEBUG
#define VD "d"
#else
#define VD
#endif
#define DRV_VERSION IWLWIFI_VERSION VD
MODULE_DESCRIPTION(DRV_DESCRIPTION);
MODULE_VERSION(DRV_VERSION);
MODULE_AUTHOR(DRV_COPYRIGHT " " DRV_AUTHOR);
MODULE_LICENSE("GPL");
static const struct iwl_op_mode_ops iwl_dvm_ops;
void iwl_update_chain_flags(struct iwl_priv *priv)
{
struct iwl_rxon_context *ctx;
for_each_context(priv, ctx) {
iwlagn_set_rxon_chain(priv, ctx);
if (ctx->active.rx_chain != ctx->staging.rx_chain)
iwlagn_commit_rxon(priv, ctx);
}
}
/* Parse the beacon frame to find the TIM element and set tim_idx & tim_size */
static void iwl_set_beacon_tim(struct iwl_priv *priv,
struct iwl_tx_beacon_cmd *tx_beacon_cmd,
u8 *beacon, u32 frame_size)
{
u16 tim_idx;
struct ieee80211_mgmt *mgmt = (struct ieee80211_mgmt *)beacon;
/*
* The index is relative to frame start but we start looking at the
* variable-length part of the beacon.
*/
tim_idx = mgmt->u.beacon.variable - beacon;
/* Parse variable-length elements of beacon to find WLAN_EID_TIM */
while ((tim_idx < (frame_size - 2)) &&
(beacon[tim_idx] != WLAN_EID_TIM))
tim_idx += beacon[tim_idx+1] + 2;
/* If TIM field was found, set variables */
if ((tim_idx < (frame_size - 1)) && (beacon[tim_idx] == WLAN_EID_TIM)) {
tx_beacon_cmd->tim_idx = cpu_to_le16(tim_idx);
tx_beacon_cmd->tim_size = beacon[tim_idx+1];
} else
IWL_WARN(priv, "Unable to find TIM Element in beacon\n");
}
int iwlagn_send_beacon_cmd(struct iwl_priv *priv)
{
struct iwl_tx_beacon_cmd *tx_beacon_cmd;
struct iwl_host_cmd cmd = {
.id = REPLY_TX_BEACON,
.flags = CMD_SYNC,
};
struct ieee80211_tx_info *info;
u32 frame_size;
u32 rate_flags;
u32 rate;
/*
* We have to set up the TX command, the TX Beacon command, and the
* beacon contents.
*/
lockdep_assert_held(&priv->mutex);
if (!priv->beacon_ctx) {
IWL_ERR(priv, "trying to build beacon w/o beacon context!\n");
return 0;
}
if (WARN_ON(!priv->beacon_skb))
return -EINVAL;
/* Allocate beacon command */
if (!priv->beacon_cmd)
priv->beacon_cmd = kzalloc(sizeof(*tx_beacon_cmd), GFP_KERNEL);
tx_beacon_cmd = priv->beacon_cmd;
if (!tx_beacon_cmd)
return -ENOMEM;
frame_size = priv->beacon_skb->len;
/* Set up TX command fields */
tx_beacon_cmd->tx.len = cpu_to_le16((u16)frame_size);
tx_beacon_cmd->tx.sta_id = priv->beacon_ctx->bcast_sta_id;
tx_beacon_cmd->tx.stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
tx_beacon_cmd->tx.tx_flags = TX_CMD_FLG_SEQ_CTL_MSK |
TX_CMD_FLG_TSF_MSK | TX_CMD_FLG_STA_RATE_MSK;
/* Set up TX beacon command fields */
iwl_set_beacon_tim(priv, tx_beacon_cmd, priv->beacon_skb->data,
frame_size);
/* Set up packet rate and flags */
info = IEEE80211_SKB_CB(priv->beacon_skb);
/*
* Let's set up the rate at least somewhat correctly;
* it will currently not actually be used by the uCode,
* it uses the broadcast station's rate instead.
*/
if (info->control.rates[0].idx < 0 ||
info->control.rates[0].flags & IEEE80211_TX_RC_MCS)
rate = 0;
else
rate = info->control.rates[0].idx;
priv->mgmt_tx_ant = iwl_toggle_tx_ant(priv, priv->mgmt_tx_ant,
priv->nvm_data->valid_tx_ant);
rate_flags = iwl_ant_idx_to_flags(priv->mgmt_tx_ant);
/* In mac80211, rates for 5 GHz start at 0 */
if (info->band == IEEE80211_BAND_5GHZ)
rate += IWL_FIRST_OFDM_RATE;
else if (rate >= IWL_FIRST_CCK_RATE && rate <= IWL_LAST_CCK_RATE)
rate_flags |= RATE_MCS_CCK_MSK;
tx_beacon_cmd->tx.rate_n_flags =
iwl_hw_set_rate_n_flags(rate, rate_flags);
/* Submit command */
cmd.len[0] = sizeof(*tx_beacon_cmd);
cmd.data[0] = tx_beacon_cmd;
cmd.dataflags[0] = IWL_HCMD_DFL_NOCOPY;
cmd.len[1] = frame_size;
cmd.data[1] = priv->beacon_skb->data;
cmd.dataflags[1] = IWL_HCMD_DFL_NOCOPY;
return iwl_dvm_send_cmd(priv, &cmd);
}
static void iwl_bg_beacon_update(struct work_struct *work)
{
struct iwl_priv *priv =
container_of(work, struct iwl_priv, beacon_update);
struct sk_buff *beacon;
mutex_lock(&priv->mutex);
if (!priv->beacon_ctx) {
IWL_ERR(priv, "updating beacon w/o beacon context!\n");
goto out;
}
if (priv->beacon_ctx->vif->type != NL80211_IFTYPE_AP) {
/*
* The ucode will send beacon notifications even in
* IBSS mode, but we don't want to process them. But
* we need to defer the type check to here due to
* requiring locking around the beacon_ctx access.
*/
goto out;
}
/* Pull updated AP beacon from mac80211. will fail if not in AP mode */
beacon = ieee80211_beacon_get(priv->hw, priv->beacon_ctx->vif);
if (!beacon) {
IWL_ERR(priv, "update beacon failed -- keeping old\n");
goto out;
}
/* new beacon skb is allocated every time; dispose previous.*/
dev_kfree_skb(priv->beacon_skb);
priv->beacon_skb = beacon;
iwlagn_send_beacon_cmd(priv);
out:
mutex_unlock(&priv->mutex);
}
static void iwl_bg_bt_runtime_config(struct work_struct *work)
{
struct iwl_priv *priv =
container_of(work, struct iwl_priv, bt_runtime_config);
mutex_lock(&priv->mutex);
if (test_bit(STATUS_EXIT_PENDING, &priv->status))
goto out;
/* dont send host command if rf-kill is on */
if (!iwl_is_ready_rf(priv))
goto out;
iwlagn_send_advance_bt_config(priv);
out:
mutex_unlock(&priv->mutex);
}
static void iwl_bg_bt_full_concurrency(struct work_struct *work)
{
struct iwl_priv *priv =
container_of(work, struct iwl_priv, bt_full_concurrency);
struct iwl_rxon_context *ctx;
mutex_lock(&priv->mutex);
if (test_bit(STATUS_EXIT_PENDING, &priv->status))
goto out;
/* dont send host command if rf-kill is on */
if (!iwl_is_ready_rf(priv))
goto out;
IWL_DEBUG_INFO(priv, "BT coex in %s mode\n",
priv->bt_full_concurrent ?
"full concurrency" : "3-wire");
/*
* LQ & RXON updated cmds must be sent before BT Config cmd
* to avoid 3-wire collisions
*/
for_each_context(priv, ctx) {
iwlagn_set_rxon_chain(priv, ctx);
iwlagn_commit_rxon(priv, ctx);
}
iwlagn_send_advance_bt_config(priv);
out:
mutex_unlock(&priv->mutex);
}
int iwl_send_statistics_request(struct iwl_priv *priv, u8 flags, bool clear)
{
struct iwl_statistics_cmd statistics_cmd = {
.configuration_flags =
clear ? IWL_STATS_CONF_CLEAR_STATS : 0,
};
if (flags & CMD_ASYNC)
return iwl_dvm_send_cmd_pdu(priv, REPLY_STATISTICS_CMD,
CMD_ASYNC,
sizeof(struct iwl_statistics_cmd),
&statistics_cmd);
else
return iwl_dvm_send_cmd_pdu(priv, REPLY_STATISTICS_CMD,
CMD_SYNC,
sizeof(struct iwl_statistics_cmd),
&statistics_cmd);
}
/**
* iwl_bg_statistics_periodic - Timer callback to queue statistics
*
* This callback is provided in order to send a statistics request.
*
* This timer function is continually reset to execute within
* REG_RECALIB_PERIOD seconds since the last STATISTICS_NOTIFICATION
* was received. We need to ensure we receive the statistics in order
* to update the temperature used for calibrating the TXPOWER.
*/
static void iwl_bg_statistics_periodic(unsigned long data)
{
struct iwl_priv *priv = (struct iwl_priv *)data;
if (test_bit(STATUS_EXIT_PENDING, &priv->status))
return;
/* dont send host command if rf-kill is on */
if (!iwl_is_ready_rf(priv))
return;
iwl_send_statistics_request(priv, CMD_ASYNC, false);
}
static void iwl_print_cont_event_trace(struct iwl_priv *priv, u32 base,
u32 start_idx, u32 num_events,
u32 capacity, u32 mode)
{
u32 i;
u32 ptr; /* SRAM byte address of log data */
u32 ev, time, data; /* event log data */
unsigned long reg_flags;
if (mode == 0)
ptr = base + (4 * sizeof(u32)) + (start_idx * 2 * sizeof(u32));
else
ptr = base + (4 * sizeof(u32)) + (start_idx * 3 * sizeof(u32));
/* Make sure device is powered up for SRAM reads */
if (!iwl_trans_grab_nic_access(priv->trans, false, ®_flags))
return;
/* Set starting address; reads will auto-increment */
iwl_write32(priv->trans, HBUS_TARG_MEM_RADDR, ptr);
/*
* Refuse to read more than would have fit into the log from
* the current start_idx. This used to happen due to the race
* described below, but now WARN because the code below should
* prevent it from happening here.
*/
if (WARN_ON(num_events > capacity - start_idx))
num_events = capacity - start_idx;
/*
* "time" is actually "data" for mode 0 (no timestamp).
* place event id # at far right for easier visual parsing.
*/
for (i = 0; i < num_events; i++) {
ev = iwl_read32(priv->trans, HBUS_TARG_MEM_RDAT);
time = iwl_read32(priv->trans, HBUS_TARG_MEM_RDAT);
if (mode == 0) {
trace_iwlwifi_dev_ucode_cont_event(
priv->trans->dev, 0, time, ev);
} else {
data = iwl_read32(priv->trans, HBUS_TARG_MEM_RDAT);
trace_iwlwifi_dev_ucode_cont_event(
priv->trans->dev, time, data, ev);
}
}
/* Allow device to power down */
iwl_trans_release_nic_access(priv->trans, ®_flags);
}
static void iwl_continuous_event_trace(struct iwl_priv *priv)
{
u32 capacity; /* event log capacity in # entries */
struct {
u32 capacity;
u32 mode;
u32 wrap_counter;
u32 write_counter;
} __packed read;
u32 base; /* SRAM byte address of event log header */
u32 mode; /* 0 - no timestamp, 1 - timestamp recorded */
u32 num_wraps; /* # times uCode wrapped to top of log */
u32 next_entry; /* index of next entry to be written by uCode */
base = priv->device_pointers.log_event_table;
if (iwlagn_hw_valid_rtc_data_addr(base)) {
iwl_trans_read_mem_bytes(priv->trans, base,
&read, sizeof(read));
capacity = read.capacity;
mode = read.mode;
num_wraps = read.wrap_counter;
next_entry = read.write_counter;
} else
return;
/*
* Unfortunately, the uCode doesn't use temporary variables.
* Therefore, it can happen that we read next_entry == capacity,
* which really means next_entry == 0.
*/
if (unlikely(next_entry == capacity))
next_entry = 0;
/*
* Additionally, the uCode increases the write pointer before
* the wraps counter, so if the write pointer is smaller than
* the old write pointer (wrap occurred) but we read that no
* wrap occurred, we actually read between the next_entry and
* num_wraps update (this does happen in practice!!) -- take
* that into account by increasing num_wraps.
*/
if (unlikely(next_entry < priv->event_log.next_entry &&
num_wraps == priv->event_log.num_wraps))
num_wraps++;
if (num_wraps == priv->event_log.num_wraps) {
iwl_print_cont_event_trace(
priv, base, priv->event_log.next_entry,
next_entry - priv->event_log.next_entry,
capacity, mode);
priv->event_log.non_wraps_count++;
} else {
if (num_wraps - priv->event_log.num_wraps > 1)
priv->event_log.wraps_more_count++;
else
priv->event_log.wraps_once_count++;
trace_iwlwifi_dev_ucode_wrap_event(priv->trans->dev,
num_wraps - priv->event_log.num_wraps,
next_entry, priv->event_log.next_entry);
if (next_entry < priv->event_log.next_entry) {
iwl_print_cont_event_trace(
priv, base, priv->event_log.next_entry,
capacity - priv->event_log.next_entry,
capacity, mode);
iwl_print_cont_event_trace(
priv, base, 0, next_entry, capacity, mode);
} else {
iwl_print_cont_event_trace(
priv, base, next_entry,
capacity - next_entry,
capacity, mode);
iwl_print_cont_event_trace(
priv, base, 0, next_entry, capacity, mode);
}
}
priv->event_log.num_wraps = num_wraps;
priv->event_log.next_entry = next_entry;
}
/**
* iwl_bg_ucode_trace - Timer callback to log ucode event
*
* The timer is continually set to execute every
* UCODE_TRACE_PERIOD milliseconds after the last timer expired
* this function is to perform continuous uCode event logging operation
* if enabled
*/
static void iwl_bg_ucode_trace(unsigned long data)
{
struct iwl_priv *priv = (struct iwl_priv *)data;
if (test_bit(STATUS_EXIT_PENDING, &priv->status))
return;
if (priv->event_log.ucode_trace) {
iwl_continuous_event_trace(priv);
/* Reschedule the timer to occur in UCODE_TRACE_PERIOD */
mod_timer(&priv->ucode_trace,
jiffies + msecs_to_jiffies(UCODE_TRACE_PERIOD));
}
}
static void iwl_bg_tx_flush(struct work_struct *work)
{
struct iwl_priv *priv =
container_of(work, struct iwl_priv, tx_flush);
if (test_bit(STATUS_EXIT_PENDING, &priv->status))
return;
/* do nothing if rf-kill is on */
if (!iwl_is_ready_rf(priv))
return;
IWL_DEBUG_INFO(priv, "device request: flush all tx frames\n");
iwlagn_dev_txfifo_flush(priv);
}
/*
* queue/FIFO/AC mapping definitions
*/
static const u8 iwlagn_bss_ac_to_fifo[] = {
IWL_TX_FIFO_VO,
IWL_TX_FIFO_VI,
IWL_TX_FIFO_BE,
IWL_TX_FIFO_BK,
};
static const u8 iwlagn_bss_ac_to_queue[] = {
0, 1, 2, 3,
};
static const u8 iwlagn_pan_ac_to_fifo[] = {
IWL_TX_FIFO_VO_IPAN,
IWL_TX_FIFO_VI_IPAN,
IWL_TX_FIFO_BE_IPAN,
IWL_TX_FIFO_BK_IPAN,
};
static const u8 iwlagn_pan_ac_to_queue[] = {
7, 6, 5, 4,
};
static void iwl_init_context(struct iwl_priv *priv, u32 ucode_flags)
{
int i;
/*
* The default context is always valid,
* the PAN context depends on uCode.
*/
priv->valid_contexts = BIT(IWL_RXON_CTX_BSS);
if (ucode_flags & IWL_UCODE_TLV_FLAGS_PAN)
priv->valid_contexts |= BIT(IWL_RXON_CTX_PAN);
for (i = 0; i < NUM_IWL_RXON_CTX; i++)
priv->contexts[i].ctxid = i;
priv->contexts[IWL_RXON_CTX_BSS].always_active = true;
priv->contexts[IWL_RXON_CTX_BSS].is_active = true;
priv->contexts[IWL_RXON_CTX_BSS].rxon_cmd = REPLY_RXON;
priv->contexts[IWL_RXON_CTX_BSS].rxon_timing_cmd = REPLY_RXON_TIMING;
priv->contexts[IWL_RXON_CTX_BSS].rxon_assoc_cmd = REPLY_RXON_ASSOC;
priv->contexts[IWL_RXON_CTX_BSS].qos_cmd = REPLY_QOS_PARAM;
priv->contexts[IWL_RXON_CTX_BSS].ap_sta_id = IWL_AP_ID;
priv->contexts[IWL_RXON_CTX_BSS].wep_key_cmd = REPLY_WEPKEY;
priv->contexts[IWL_RXON_CTX_BSS].bcast_sta_id = IWLAGN_BROADCAST_ID;
priv->contexts[IWL_RXON_CTX_BSS].exclusive_interface_modes =
BIT(NL80211_IFTYPE_ADHOC) | BIT(NL80211_IFTYPE_MONITOR);
priv->contexts[IWL_RXON_CTX_BSS].interface_modes =
BIT(NL80211_IFTYPE_STATION);
priv->contexts[IWL_RXON_CTX_BSS].ap_devtype = RXON_DEV_TYPE_AP;
priv->contexts[IWL_RXON_CTX_BSS].ibss_devtype = RXON_DEV_TYPE_IBSS;
priv->contexts[IWL_RXON_CTX_BSS].station_devtype = RXON_DEV_TYPE_ESS;
priv->contexts[IWL_RXON_CTX_BSS].unused_devtype = RXON_DEV_TYPE_ESS;
memcpy(priv->contexts[IWL_RXON_CTX_BSS].ac_to_queue,
iwlagn_bss_ac_to_queue, sizeof(iwlagn_bss_ac_to_queue));
memcpy(priv->contexts[IWL_RXON_CTX_BSS].ac_to_fifo,
iwlagn_bss_ac_to_fifo, sizeof(iwlagn_bss_ac_to_fifo));
priv->contexts[IWL_RXON_CTX_PAN].rxon_cmd = REPLY_WIPAN_RXON;
priv->contexts[IWL_RXON_CTX_PAN].rxon_timing_cmd =
REPLY_WIPAN_RXON_TIMING;
priv->contexts[IWL_RXON_CTX_PAN].rxon_assoc_cmd =
REPLY_WIPAN_RXON_ASSOC;
priv->contexts[IWL_RXON_CTX_PAN].qos_cmd = REPLY_WIPAN_QOS_PARAM;
priv->contexts[IWL_RXON_CTX_PAN].ap_sta_id = IWL_AP_ID_PAN;
priv->contexts[IWL_RXON_CTX_PAN].wep_key_cmd = REPLY_WIPAN_WEPKEY;
priv->contexts[IWL_RXON_CTX_PAN].bcast_sta_id = IWLAGN_PAN_BCAST_ID;
priv->contexts[IWL_RXON_CTX_PAN].station_flags = STA_FLG_PAN_STATION;
priv->contexts[IWL_RXON_CTX_PAN].interface_modes =
BIT(NL80211_IFTYPE_STATION) | BIT(NL80211_IFTYPE_AP);
if (ucode_flags & IWL_UCODE_TLV_FLAGS_P2P)
priv->contexts[IWL_RXON_CTX_PAN].interface_modes |=
BIT(NL80211_IFTYPE_P2P_CLIENT) |
BIT(NL80211_IFTYPE_P2P_GO);
priv->contexts[IWL_RXON_CTX_PAN].ap_devtype = RXON_DEV_TYPE_CP;
priv->contexts[IWL_RXON_CTX_PAN].station_devtype = RXON_DEV_TYPE_2STA;
priv->contexts[IWL_RXON_CTX_PAN].unused_devtype = RXON_DEV_TYPE_P2P;
memcpy(priv->contexts[IWL_RXON_CTX_PAN].ac_to_queue,
iwlagn_pan_ac_to_queue, sizeof(iwlagn_pan_ac_to_queue));
memcpy(priv->contexts[IWL_RXON_CTX_PAN].ac_to_fifo,
iwlagn_pan_ac_to_fifo, sizeof(iwlagn_pan_ac_to_fifo));
priv->contexts[IWL_RXON_CTX_PAN].mcast_queue = IWL_IPAN_MCAST_QUEUE;
BUILD_BUG_ON(NUM_IWL_RXON_CTX != 2);
}
static void iwl_rf_kill_ct_config(struct iwl_priv *priv)
{
struct iwl_ct_kill_config cmd;
struct iwl_ct_kill_throttling_config adv_cmd;
int ret = 0;
iwl_write32(priv->trans, CSR_UCODE_DRV_GP1_CLR,
CSR_UCODE_DRV_GP1_REG_BIT_CT_KILL_EXIT);
priv->thermal_throttle.ct_kill_toggle = false;
if (priv->cfg->base_params->support_ct_kill_exit) {
adv_cmd.critical_temperature_enter =
cpu_to_le32(priv->hw_params.ct_kill_threshold);
adv_cmd.critical_temperature_exit =
cpu_to_le32(priv->hw_params.ct_kill_exit_threshold);
ret = iwl_dvm_send_cmd_pdu(priv,
REPLY_CT_KILL_CONFIG_CMD,
CMD_SYNC, sizeof(adv_cmd), &adv_cmd);
if (ret)
IWL_ERR(priv, "REPLY_CT_KILL_CONFIG_CMD failed\n");
else
IWL_DEBUG_INFO(priv, "REPLY_CT_KILL_CONFIG_CMD "
"succeeded, critical temperature enter is %d,"
"exit is %d\n",
priv->hw_params.ct_kill_threshold,
priv->hw_params.ct_kill_exit_threshold);
} else {
cmd.critical_temperature_R =
cpu_to_le32(priv->hw_params.ct_kill_threshold);
ret = iwl_dvm_send_cmd_pdu(priv,
REPLY_CT_KILL_CONFIG_CMD,
CMD_SYNC, sizeof(cmd), &cmd);
if (ret)
IWL_ERR(priv, "REPLY_CT_KILL_CONFIG_CMD failed\n");
else
IWL_DEBUG_INFO(priv, "REPLY_CT_KILL_CONFIG_CMD "
"succeeded, "
"critical temperature is %d\n",
priv->hw_params.ct_kill_threshold);
}
}
static int iwlagn_send_calib_cfg_rt(struct iwl_priv *priv, u32 cfg)
{
struct iwl_calib_cfg_cmd calib_cfg_cmd;
struct iwl_host_cmd cmd = {
.id = CALIBRATION_CFG_CMD,
.len = { sizeof(struct iwl_calib_cfg_cmd), },
.data = { &calib_cfg_cmd, },
};
memset(&calib_cfg_cmd, 0, sizeof(calib_cfg_cmd));
calib_cfg_cmd.ucd_calib_cfg.once.is_enable = IWL_CALIB_RT_CFG_ALL;
calib_cfg_cmd.ucd_calib_cfg.once.start = cpu_to_le32(cfg);
return iwl_dvm_send_cmd(priv, &cmd);
}
static int iwlagn_send_tx_ant_config(struct iwl_priv *priv, u8 valid_tx_ant)
{
struct iwl_tx_ant_config_cmd tx_ant_cmd = {
.valid = cpu_to_le32(valid_tx_ant),
};
if (IWL_UCODE_API(priv->fw->ucode_ver) > 1) {
IWL_DEBUG_HC(priv, "select valid tx ant: %u\n", valid_tx_ant);
return iwl_dvm_send_cmd_pdu(priv,
TX_ANT_CONFIGURATION_CMD,
CMD_SYNC,
sizeof(struct iwl_tx_ant_config_cmd),
&tx_ant_cmd);
} else {
IWL_DEBUG_HC(priv, "TX_ANT_CONFIGURATION_CMD not supported\n");
return -EOPNOTSUPP;
}
}
static void iwl_send_bt_config(struct iwl_priv *priv)
{
struct iwl_bt_cmd bt_cmd = {
.lead_time = BT_LEAD_TIME_DEF,
.max_kill = BT_MAX_KILL_DEF,
.kill_ack_mask = 0,
.kill_cts_mask = 0,
};
if (!iwlwifi_mod_params.bt_coex_active)
bt_cmd.flags = BT_COEX_DISABLE;
else
bt_cmd.flags = BT_COEX_ENABLE;
priv->bt_enable_flag = bt_cmd.flags;
IWL_DEBUG_INFO(priv, "BT coex %s\n",
(bt_cmd.flags == BT_COEX_DISABLE) ? "disable" : "active");
if (iwl_dvm_send_cmd_pdu(priv, REPLY_BT_CONFIG,
CMD_SYNC, sizeof(struct iwl_bt_cmd), &bt_cmd))
IWL_ERR(priv, "failed to send BT Coex Config\n");
}
/**
* iwl_alive_start - called after REPLY_ALIVE notification received
* from protocol/runtime uCode (initialization uCode's
* Alive gets handled by iwl_init_alive_start()).
*/
int iwl_alive_start(struct iwl_priv *priv)
{
int ret = 0;
struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS];
IWL_DEBUG_INFO(priv, "Runtime Alive received.\n");
/* After the ALIVE response, we can send host commands to the uCode */
set_bit(STATUS_ALIVE, &priv->status);
if (iwl_is_rfkill(priv))
return -ERFKILL;
if (priv->event_log.ucode_trace) {
/* start collecting data now */
mod_timer(&priv->ucode_trace, jiffies);
}
/* download priority table before any calibration request */
if (priv->cfg->bt_params &&
priv->cfg->bt_params->advanced_bt_coexist) {
/* Configure Bluetooth device coexistence support */
if (priv->cfg->bt_params->bt_sco_disable)
priv->bt_enable_pspoll = false;
else
priv->bt_enable_pspoll = true;
priv->bt_valid = IWLAGN_BT_ALL_VALID_MSK;
priv->kill_ack_mask = IWLAGN_BT_KILL_ACK_MASK_DEFAULT;
priv->kill_cts_mask = IWLAGN_BT_KILL_CTS_MASK_DEFAULT;
iwlagn_send_advance_bt_config(priv);
priv->bt_valid = IWLAGN_BT_VALID_ENABLE_FLAGS;
priv->cur_rssi_ctx = NULL;
iwl_send_prio_tbl(priv);
/* FIXME: w/a to force change uCode BT state machine */
ret = iwl_send_bt_env(priv, IWL_BT_COEX_ENV_OPEN,
BT_COEX_PRIO_TBL_EVT_INIT_CALIB2);
if (ret)
return ret;
ret = iwl_send_bt_env(priv, IWL_BT_COEX_ENV_CLOSE,
BT_COEX_PRIO_TBL_EVT_INIT_CALIB2);
if (ret)
return ret;
} else if (priv->cfg->bt_params) {
/*
* default is 2-wire BT coexexistence support
*/
iwl_send_bt_config(priv);
}
/*
* Perform runtime calibrations, including DC calibration.
*/
iwlagn_send_calib_cfg_rt(priv, IWL_CALIB_CFG_DC_IDX);
ieee80211_wake_queues(priv->hw);
/* Configure Tx antenna selection based on H/W config */
iwlagn_send_tx_ant_config(priv, priv->nvm_data->valid_tx_ant);
if (iwl_is_associated_ctx(ctx) && !priv->wowlan) {
struct iwl_rxon_cmd *active_rxon =
(struct iwl_rxon_cmd *)&ctx->active;
/* apply any changes in staging */
ctx->staging.filter_flags |= RXON_FILTER_ASSOC_MSK;
active_rxon->filter_flags &= ~RXON_FILTER_ASSOC_MSK;
} else {
struct iwl_rxon_context *tmp;
/* Initialize our rx_config data */
for_each_context(priv, tmp)
iwl_connection_init_rx_config(priv, tmp);
iwlagn_set_rxon_chain(priv, ctx);
}
if (!priv->wowlan) {
/* WoWLAN ucode will not reply in the same way, skip it */
iwl_reset_run_time_calib(priv);
}
set_bit(STATUS_READY, &priv->status);
/* Configure the adapter for unassociated operation */
ret = iwlagn_commit_rxon(priv, ctx);
if (ret)
return ret;
/* At this point, the NIC is initialized and operational */
iwl_rf_kill_ct_config(priv);
IWL_DEBUG_INFO(priv, "ALIVE processing complete.\n");
return iwl_power_update_mode(priv, true);
}
/**
* iwl_clear_driver_stations - clear knowledge of all stations from driver
* @priv: iwl priv struct
*
* This is called during iwl_down() to make sure that in the case
* we're coming there from a hardware restart mac80211 will be
* able to reconfigure stations -- if we're getting there in the
* normal down flow then the stations will already be cleared.
*/
static void iwl_clear_driver_stations(struct iwl_priv *priv)
{
struct iwl_rxon_context *ctx;
spin_lock_bh(&priv->sta_lock);
memset(priv->stations, 0, sizeof(priv->stations));
priv->num_stations = 0;
priv->ucode_key_table = 0;
for_each_context(priv, ctx) {
/*
* Remove all key information that is not stored as part
* of station information since mac80211 may not have had
* a chance to remove all the keys. When device is
* reconfigured by mac80211 after an error all keys will
* be reconfigured.
*/
memset(ctx->wep_keys, 0, sizeof(ctx->wep_keys));
ctx->key_mapping_keys = 0;
}
spin_unlock_bh(&priv->sta_lock);
}
void iwl_down(struct iwl_priv *priv)
{
int exit_pending;
IWL_DEBUG_INFO(priv, DRV_NAME " is going down\n");
lockdep_assert_held(&priv->mutex);
iwl_scan_cancel_timeout(priv, 200);
/*
* If active, scanning won't cancel it, so say it expired.
* No race since we hold the mutex here and a new one
* can't come in at this time.
*/
if (priv->ucode_loaded && priv->cur_ucode != IWL_UCODE_INIT)
ieee80211_remain_on_channel_expired(priv->hw);
exit_pending =
test_and_set_bit(STATUS_EXIT_PENDING, &priv->status);
iwl_clear_ucode_stations(priv, NULL);
iwl_dealloc_bcast_stations(priv);
iwl_clear_driver_stations(priv);
/* reset BT coex data */
priv->bt_status = 0;
priv->cur_rssi_ctx = NULL;
priv->bt_is_sco = 0;
if (priv->cfg->bt_params)
priv->bt_traffic_load =
priv->cfg->bt_params->bt_init_traffic_load;
else
priv->bt_traffic_load = 0;
priv->bt_full_concurrent = false;
priv->bt_ci_compliance = 0;
/* Wipe out the EXIT_PENDING status bit if we are not actually
* exiting the module */
if (!exit_pending)
clear_bit(STATUS_EXIT_PENDING, &priv->status);
if (priv->mac80211_registered)
ieee80211_stop_queues(priv->hw);
priv->ucode_loaded = false;
iwl_trans_stop_device(priv->trans);
/* Set num_aux_in_flight must be done after the transport is stopped */
atomic_set(&priv->num_aux_in_flight, 0);
/* Clear out all status bits but a few that are stable across reset */
priv->status &= test_bit(STATUS_RF_KILL_HW, &priv->status) <<
STATUS_RF_KILL_HW |
test_bit(STATUS_FW_ERROR, &priv->status) <<
STATUS_FW_ERROR |
test_bit(STATUS_EXIT_PENDING, &priv->status) <<
STATUS_EXIT_PENDING;
dev_kfree_skb(priv->beacon_skb);
priv->beacon_skb = NULL;
}
/*****************************************************************************
*
* Workqueue callbacks
*
*****************************************************************************/
static void iwl_bg_run_time_calib_work(struct work_struct *work)
{
struct iwl_priv *priv = container_of(work, struct iwl_priv,
run_time_calib_work);
mutex_lock(&priv->mutex);
if (test_bit(STATUS_EXIT_PENDING, &priv->status) ||
test_bit(STATUS_SCANNING, &priv->status)) {
mutex_unlock(&priv->mutex);
return;
}
if (priv->start_calib) {
iwl_chain_noise_calibration(priv);
iwl_sensitivity_calibration(priv);
}
mutex_unlock(&priv->mutex);
}
void iwlagn_prepare_restart(struct iwl_priv *priv)
{
bool bt_full_concurrent;
u8 bt_ci_compliance;
u8 bt_load;
u8 bt_status;
bool bt_is_sco;
int i;
lockdep_assert_held(&priv->mutex);
priv->is_open = 0;
/*
* __iwl_down() will clear the BT status variables,
* which is correct, but when we restart we really
* want to keep them so restore them afterwards.
*
* The restart process will later pick them up and
* re-configure the hw when we reconfigure the BT
* command.
*/
bt_full_concurrent = priv->bt_full_concurrent;
bt_ci_compliance = priv->bt_ci_compliance;
bt_load = priv->bt_traffic_load;
bt_status = priv->bt_status;
bt_is_sco = priv->bt_is_sco;
iwl_down(priv);
priv->bt_full_concurrent = bt_full_concurrent;
priv->bt_ci_compliance = bt_ci_compliance;
priv->bt_traffic_load = bt_load;
priv->bt_status = bt_status;
priv->bt_is_sco = bt_is_sco;
/* reset aggregation queues */
for (i = IWLAGN_FIRST_AMPDU_QUEUE; i < IWL_MAX_HW_QUEUES; i++)
priv->queue_to_mac80211[i] = IWL_INVALID_MAC80211_QUEUE;
/* and stop counts */
for (i = 0; i < IWL_MAX_HW_QUEUES; i++)
atomic_set(&priv->queue_stop_count[i], 0);
memset(priv->agg_q_alloc, 0, sizeof(priv->agg_q_alloc));
}
static void iwl_bg_restart(struct work_struct *data)
{
struct iwl_priv *priv = container_of(data, struct iwl_priv, restart);
if (test_bit(STATUS_EXIT_PENDING, &priv->status))
return;
if (test_and_clear_bit(STATUS_FW_ERROR, &priv->status)) {
mutex_lock(&priv->mutex);
iwlagn_prepare_restart(priv);
mutex_unlock(&priv->mutex);
iwl_cancel_deferred_work(priv);
if (priv->mac80211_registered)
ieee80211_restart_hw(priv->hw);
else
IWL_ERR(priv,
"Cannot request restart before registrating with mac80211");
} else {
WARN_ON(1);
}
}
void iwlagn_disable_roc(struct iwl_priv *priv)
{
struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_PAN];
lockdep_assert_held(&priv->mutex);
if (!priv->hw_roc_setup)
return;
ctx->staging.dev_type = RXON_DEV_TYPE_P2P;
ctx->staging.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
priv->hw_roc_channel = NULL;
memset(ctx->staging.node_addr, 0, ETH_ALEN);
iwlagn_commit_rxon(priv, ctx);
ctx->is_active = false;
priv->hw_roc_setup = false;
}
static void iwlagn_disable_roc_work(struct work_struct *work)
{
struct iwl_priv *priv = container_of(work, struct iwl_priv,
hw_roc_disable_work.work);
mutex_lock(&priv->mutex);
iwlagn_disable_roc(priv);
mutex_unlock(&priv->mutex);
}
/*****************************************************************************
*
* driver setup and teardown
*
*****************************************************************************/
static void iwl_setup_deferred_work(struct iwl_priv *priv)
{
priv->workqueue = create_singlethread_workqueue(DRV_NAME);
INIT_WORK(&priv->restart, iwl_bg_restart);
INIT_WORK(&priv->beacon_update, iwl_bg_beacon_update);
INIT_WORK(&priv->run_time_calib_work, iwl_bg_run_time_calib_work);
INIT_WORK(&priv->tx_flush, iwl_bg_tx_flush);
INIT_WORK(&priv->bt_full_concurrency, iwl_bg_bt_full_concurrency);
INIT_WORK(&priv->bt_runtime_config, iwl_bg_bt_runtime_config);
INIT_DELAYED_WORK(&priv->hw_roc_disable_work,
iwlagn_disable_roc_work);
iwl_setup_scan_deferred_work(priv);
if (priv->cfg->bt_params)
iwlagn_bt_setup_deferred_work(priv);
init_timer(&priv->statistics_periodic);
priv->statistics_periodic.data = (unsigned long)priv;
priv->statistics_periodic.function = iwl_bg_statistics_periodic;
init_timer(&priv->ucode_trace);
priv->ucode_trace.data = (unsigned long)priv;
priv->ucode_trace.function = iwl_bg_ucode_trace;
}
void iwl_cancel_deferred_work(struct iwl_priv *priv)
{
if (priv->cfg->bt_params)
iwlagn_bt_cancel_deferred_work(priv);
cancel_work_sync(&priv->run_time_calib_work);
cancel_work_sync(&priv->beacon_update);
iwl_cancel_scan_deferred_work(priv);
cancel_work_sync(&priv->bt_full_concurrency);
cancel_work_sync(&priv->bt_runtime_config);
cancel_delayed_work_sync(&priv->hw_roc_disable_work);
del_timer_sync(&priv->statistics_periodic);
del_timer_sync(&priv->ucode_trace);
}
static int iwl_init_drv(struct iwl_priv *priv)
{
spin_lock_init(&priv->sta_lock);
mutex_init(&priv->mutex);
INIT_LIST_HEAD(&priv->calib_results);
priv->band = IEEE80211_BAND_2GHZ;
priv->plcp_delta_threshold =
priv->cfg->base_params->plcp_delta_threshold;
priv->iw_mode = NL80211_IFTYPE_STATION;
priv->current_ht_config.smps = IEEE80211_SMPS_STATIC;
priv->missed_beacon_threshold = IWL_MISSED_BEACON_THRESHOLD_DEF;
priv->agg_tids_count = 0;
priv->ucode_owner = IWL_OWNERSHIP_DRIVER;
priv->rx_statistics_jiffies = jiffies;
/* Choose which receivers/antennas to use */
iwlagn_set_rxon_chain(priv, &priv->contexts[IWL_RXON_CTX_BSS]);
iwl_init_scan_params(priv);
/* init bt coex */
if (priv->cfg->bt_params &&
priv->cfg->bt_params->advanced_bt_coexist) {
priv->kill_ack_mask = IWLAGN_BT_KILL_ACK_MASK_DEFAULT;
priv->kill_cts_mask = IWLAGN_BT_KILL_CTS_MASK_DEFAULT;
priv->bt_valid = IWLAGN_BT_ALL_VALID_MSK;
priv->bt_on_thresh = BT_ON_THRESHOLD_DEF;
priv->bt_duration = BT_DURATION_LIMIT_DEF;
priv->dynamic_frag_thresh = BT_FRAG_THRESHOLD_DEF;
}
return 0;
}
static void iwl_uninit_drv(struct iwl_priv *priv)
{
kfree(priv->scan_cmd);
kfree(priv->beacon_cmd);
kfree(rcu_dereference_raw(priv->noa_data));
iwl_calib_free_results(priv);
#ifdef CONFIG_IWLWIFI_DEBUGFS
kfree(priv->wowlan_sram);
#endif
}
static void iwl_set_hw_params(struct iwl_priv *priv)
{
if (priv->cfg->ht_params)
priv->hw_params.use_rts_for_aggregation =
priv->cfg->ht_params->use_rts_for_aggregation;
/* Device-specific setup */
priv->lib->set_hw_params(priv);
}
/* show what optional capabilities we have */
static void iwl_option_config(struct iwl_priv *priv)
{
#ifdef CONFIG_IWLWIFI_DEBUG
IWL_INFO(priv, "CONFIG_IWLWIFI_DEBUG enabled\n");
#else
IWL_INFO(priv, "CONFIG_IWLWIFI_DEBUG disabled\n");
#endif
#ifdef CONFIG_IWLWIFI_DEBUGFS
IWL_INFO(priv, "CONFIG_IWLWIFI_DEBUGFS enabled\n");
#else
IWL_INFO(priv, "CONFIG_IWLWIFI_DEBUGFS disabled\n");
#endif
#ifdef CONFIG_IWLWIFI_DEVICE_TRACING
IWL_INFO(priv, "CONFIG_IWLWIFI_DEVICE_TRACING enabled\n");
#else
IWL_INFO(priv, "CONFIG_IWLWIFI_DEVICE_TRACING disabled\n");
#endif
#ifdef CONFIG_IWLWIFI_DEVICE_TESTMODE
IWL_INFO(priv, "CONFIG_IWLWIFI_DEVICE_TESTMODE enabled\n");
#else
IWL_INFO(priv, "CONFIG_IWLWIFI_DEVICE_TESTMODE disabled\n");
#endif
#ifdef CONFIG_IWLWIFI_P2P
IWL_INFO(priv, "CONFIG_IWLWIFI_P2P enabled\n");
#else
IWL_INFO(priv, "CONFIG_IWLWIFI_P2P disabled\n");
#endif
}
static int iwl_eeprom_init_hw_params(struct iwl_priv *priv)
{
struct iwl_nvm_data *data = priv->nvm_data;
char *debug_msg;
if (data->sku_cap_11n_enable &&
!priv->cfg->ht_params) {
IWL_ERR(priv, "Invalid 11n configuration\n");
return -EINVAL;
}
if (!data->sku_cap_11n_enable && !data->sku_cap_band_24GHz_enable &&
!data->sku_cap_band_52GHz_enable) {
IWL_ERR(priv, "Invalid device sku\n");
return -EINVAL;
}
debug_msg = "Device SKU: 24GHz %s %s, 52GHz %s %s, 11.n %s %s\n";
IWL_DEBUG_INFO(priv, debug_msg,
data->sku_cap_band_24GHz_enable ? "" : "NOT", "enabled",
data->sku_cap_band_52GHz_enable ? "" : "NOT", "enabled",
data->sku_cap_11n_enable ? "" : "NOT", "enabled");
priv->hw_params.tx_chains_num =
num_of_ant(data->valid_tx_ant);
if (priv->cfg->rx_with_siso_diversity)
priv->hw_params.rx_chains_num = 1;
else
priv->hw_params.rx_chains_num =
num_of_ant(data->valid_rx_ant);
IWL_DEBUG_INFO(priv, "Valid Tx ant: 0x%X, Valid Rx ant: 0x%X\n",
data->valid_tx_ant,
data->valid_rx_ant);
return 0;
}
static struct iwl_op_mode *iwl_op_mode_dvm_start(struct iwl_trans *trans,
const struct iwl_cfg *cfg,
const struct iwl_fw *fw,
struct dentry *dbgfs_dir)
{
struct iwl_priv *priv;
struct ieee80211_hw *hw;
struct iwl_op_mode *op_mode;
u16 num_mac;
u32 ucode_flags;
struct iwl_trans_config trans_cfg = {};
static const u8 no_reclaim_cmds[] = {
REPLY_RX_PHY_CMD,
REPLY_RX_MPDU_CMD,
REPLY_COMPRESSED_BA,
STATISTICS_NOTIFICATION,
REPLY_TX,
};
int i;
/************************
* 1. Allocating HW data
************************/
hw = iwl_alloc_all();
if (!hw) {
pr_err("%s: Cannot allocate network device\n", cfg->name);
goto out;
}
op_mode = hw->priv;
op_mode->ops = &iwl_dvm_ops;
priv = IWL_OP_MODE_GET_DVM(op_mode);
priv->trans = trans;
priv->dev = trans->dev;
priv->cfg = cfg;
priv->fw = fw;
switch (priv->cfg->device_family) {
case IWL_DEVICE_FAMILY_1000:
case IWL_DEVICE_FAMILY_100:
priv->lib = &iwl1000_lib;
break;
case IWL_DEVICE_FAMILY_2000:
case IWL_DEVICE_FAMILY_105:
priv->lib = &iwl2000_lib;
break;
case IWL_DEVICE_FAMILY_2030:
case IWL_DEVICE_FAMILY_135:
priv->lib = &iwl2030_lib;
break;
case IWL_DEVICE_FAMILY_5000:
priv->lib = &iwl5000_lib;
break;
case IWL_DEVICE_FAMILY_5150:
priv->lib = &iwl5150_lib;
break;
case IWL_DEVICE_FAMILY_6000:
case IWL_DEVICE_FAMILY_6005:
case IWL_DEVICE_FAMILY_6000i:
case IWL_DEVICE_FAMILY_6050:
case IWL_DEVICE_FAMILY_6150:
priv->lib = &iwl6000_lib;
break;
case IWL_DEVICE_FAMILY_6030:
priv->lib = &iwl6030_lib;
break;
default:
break;
}
if (WARN_ON(!priv->lib))
goto out_free_hw;
/*
* Populate the state variables that the transport layer needs
* to know about.
*/
trans_cfg.op_mode = op_mode;
trans_cfg.no_reclaim_cmds = no_reclaim_cmds;
trans_cfg.n_no_reclaim_cmds = ARRAY_SIZE(no_reclaim_cmds);
trans_cfg.rx_buf_size_8k = iwlwifi_mod_params.amsdu_size_8K;
if (!iwlwifi_mod_params.wd_disable)
trans_cfg.queue_watchdog_timeout =
priv->cfg->base_params->wd_timeout;
else
trans_cfg.queue_watchdog_timeout = IWL_WATCHDOG_DISABLED;
trans_cfg.command_names = iwl_dvm_cmd_strings;
trans_cfg.cmd_fifo = IWLAGN_CMD_FIFO_NUM;
WARN_ON(sizeof(priv->transport_queue_stop) * BITS_PER_BYTE <
priv->cfg->base_params->num_of_queues);
ucode_flags = fw->ucode_capa.flags;
#ifndef CONFIG_IWLWIFI_P2P
ucode_flags &= ~IWL_UCODE_TLV_FLAGS_P2P;
#endif
if (ucode_flags & IWL_UCODE_TLV_FLAGS_PAN) {
priv->sta_key_max_num = STA_KEY_MAX_NUM_PAN;
trans_cfg.cmd_queue = IWL_IPAN_CMD_QUEUE_NUM;
} else {
priv->sta_key_max_num = STA_KEY_MAX_NUM;
trans_cfg.cmd_queue = IWL_DEFAULT_CMD_QUEUE_NUM;
}
/* Configure transport layer */
iwl_trans_configure(priv->trans, &trans_cfg);
trans->rx_mpdu_cmd = REPLY_RX_MPDU_CMD;
trans->rx_mpdu_cmd_hdr_size = sizeof(struct iwl_rx_mpdu_res_start);
/* At this point both hw and priv are allocated. */
SET_IEEE80211_DEV(priv->hw, priv->trans->dev);
iwl_option_config(priv);
IWL_DEBUG_INFO(priv, "*** LOAD DRIVER ***\n");
/* is antenna coupling more than 35dB ? */
priv->bt_ant_couple_ok =
(iwlwifi_mod_params.ant_coupling >
IWL_BT_ANTENNA_COUPLING_THRESHOLD) ?
true : false;
/* enable/disable bt channel inhibition */
priv->bt_ch_announce = iwlwifi_mod_params.bt_ch_announce;
IWL_DEBUG_INFO(priv, "BT channel inhibition is %s\n",
(priv->bt_ch_announce) ? "On" : "Off");
/* these spin locks will be used in apm_ops.init and EEPROM access
* we should init now
*/
spin_lock_init(&priv->statistics.lock);
/***********************
* 2. Read REV register
***********************/
IWL_INFO(priv, "Detected %s, REV=0x%X\n",
priv->cfg->name, priv->trans->hw_rev);
if (iwl_trans_start_hw(priv->trans))
goto out_free_hw;
/* Read the EEPROM */
if (iwl_read_eeprom(priv->trans, &priv->eeprom_blob,
&priv->eeprom_blob_size)) {
IWL_ERR(priv, "Unable to init EEPROM\n");
goto out_free_hw;
}
/* Reset chip to save power until we load uCode during "up". */
iwl_trans_stop_hw(priv->trans, false);
priv->nvm_data = iwl_parse_eeprom_data(priv->trans->dev, priv->cfg,
priv->eeprom_blob,
priv->eeprom_blob_size);
if (!priv->nvm_data)
goto out_free_eeprom_blob;
if (iwl_nvm_check_version(priv->nvm_data, priv->trans))
goto out_free_eeprom;
if (iwl_eeprom_init_hw_params(priv))
goto out_free_eeprom;
/* extract MAC Address */
memcpy(priv->addresses[0].addr, priv->nvm_data->hw_addr, ETH_ALEN);
IWL_DEBUG_INFO(priv, "MAC address: %pM\n", priv->addresses[0].addr);
priv->hw->wiphy->addresses = priv->addresses;
priv->hw->wiphy->n_addresses = 1;
num_mac = priv->nvm_data->n_hw_addrs;
if (num_mac > 1) {
memcpy(priv->addresses[1].addr, priv->addresses[0].addr,
ETH_ALEN);
priv->addresses[1].addr[5]++;
priv->hw->wiphy->n_addresses++;
}
/************************
* 4. Setup HW constants
************************/
iwl_set_hw_params(priv);
if (!(priv->nvm_data->sku_cap_ipan_enable)) {
IWL_DEBUG_INFO(priv, "Your EEPROM disabled PAN");
ucode_flags &= ~IWL_UCODE_TLV_FLAGS_PAN;
/*
* if not PAN, then don't support P2P -- might be a uCode
* packaging bug or due to the eeprom check above
*/
ucode_flags &= ~IWL_UCODE_TLV_FLAGS_P2P;
priv->sta_key_max_num = STA_KEY_MAX_NUM;
trans_cfg.cmd_queue = IWL_DEFAULT_CMD_QUEUE_NUM;
/* Configure transport layer again*/
iwl_trans_configure(priv->trans, &trans_cfg);
}
/*******************
* 5. Setup priv
*******************/
for (i = 0; i < IWL_MAX_HW_QUEUES; i++) {
priv->queue_to_mac80211[i] = IWL_INVALID_MAC80211_QUEUE;
if (i < IWLAGN_FIRST_AMPDU_QUEUE &&
i != IWL_DEFAULT_CMD_QUEUE_NUM &&
i != IWL_IPAN_CMD_QUEUE_NUM)
priv->queue_to_mac80211[i] = i;
atomic_set(&priv->queue_stop_count[i], 0);
}
if (iwl_init_drv(priv))
goto out_free_eeprom;
/* At this point both hw and priv are initialized. */
/********************
* 6. Setup services
********************/
iwl_setup_deferred_work(priv);
iwl_setup_rx_handlers(priv);
iwl_testmode_init(priv);
iwl_power_initialize(priv);
iwl_tt_initialize(priv);
snprintf(priv->hw->wiphy->fw_version,
sizeof(priv->hw->wiphy->fw_version),
"%s", fw->fw_version);
priv->new_scan_threshold_behaviour =
!!(ucode_flags & IWL_UCODE_TLV_FLAGS_NEWSCAN);
priv->phy_calib_chain_noise_reset_cmd =
fw->ucode_capa.standard_phy_calibration_size;
priv->phy_calib_chain_noise_gain_cmd =
fw->ucode_capa.standard_phy_calibration_size + 1;
/* initialize all valid contexts */
iwl_init_context(priv, ucode_flags);
/**************************************************
* This is still part of probe() in a sense...
*
* 7. Setup and register with mac80211 and debugfs
**************************************************/
if (iwlagn_mac_setup_register(priv, &fw->ucode_capa))
goto out_destroy_workqueue;
if (iwl_dbgfs_register(priv, dbgfs_dir))
goto out_mac80211_unregister;
return op_mode;
out_mac80211_unregister:
iwlagn_mac_unregister(priv);
out_destroy_workqueue:
iwl_tt_exit(priv);
iwl_testmode_free(priv);
iwl_cancel_deferred_work(priv);
destroy_workqueue(priv->workqueue);
priv->workqueue = NULL;
iwl_uninit_drv(priv);
out_free_eeprom_blob:
kfree(priv->eeprom_blob);
out_free_eeprom:
iwl_free_nvm_data(priv->nvm_data);
out_free_hw:
ieee80211_free_hw(priv->hw);
out:
op_mode = NULL;
return op_mode;
}
static void iwl_op_mode_dvm_stop(struct iwl_op_mode *op_mode)
{
struct iwl_priv *priv = IWL_OP_MODE_GET_DVM(op_mode);
IWL_DEBUG_INFO(priv, "*** UNLOAD DRIVER ***\n");
iwl_testmode_free(priv);
iwlagn_mac_unregister(priv);
iwl_tt_exit(priv);
kfree(priv->eeprom_blob);
iwl_free_nvm_data(priv->nvm_data);
/*netif_stop_queue(dev); */
flush_workqueue(priv->workqueue);
/* ieee80211_unregister_hw calls iwlagn_mac_stop, which flushes
* priv->workqueue... so we can't take down the workqueue
* until now... */
destroy_workqueue(priv->workqueue);
priv->workqueue = NULL;
iwl_uninit_drv(priv);
dev_kfree_skb(priv->beacon_skb);
iwl_trans_stop_hw(priv->trans, true);
ieee80211_free_hw(priv->hw);
}
static const char * const desc_lookup_text[] = {
"OK",
"FAIL",
"BAD_PARAM",
"BAD_CHECKSUM",
"NMI_INTERRUPT_WDG",
"SYSASSERT",
"FATAL_ERROR",
"BAD_COMMAND",
"HW_ERROR_TUNE_LOCK",
"HW_ERROR_TEMPERATURE",
"ILLEGAL_CHAN_FREQ",
"VCC_NOT_STABLE",
"FH_ERROR",
"NMI_INTERRUPT_HOST",
"NMI_INTERRUPT_ACTION_PT",
"NMI_INTERRUPT_UNKNOWN",
"UCODE_VERSION_MISMATCH",
"HW_ERROR_ABS_LOCK",
"HW_ERROR_CAL_LOCK_FAIL",
"NMI_INTERRUPT_INST_ACTION_PT",
"NMI_INTERRUPT_DATA_ACTION_PT",
"NMI_TRM_HW_ER",
"NMI_INTERRUPT_TRM",
"NMI_INTERRUPT_BREAK_POINT",
"DEBUG_0",
"DEBUG_1",
"DEBUG_2",
"DEBUG_3",
};
static struct { char *name; u8 num; } advanced_lookup[] = {
{ "NMI_INTERRUPT_WDG", 0x34 },
{ "SYSASSERT", 0x35 },
{ "UCODE_VERSION_MISMATCH", 0x37 },
{ "BAD_COMMAND", 0x38 },
{ "NMI_INTERRUPT_DATA_ACTION_PT", 0x3C },
{ "FATAL_ERROR", 0x3D },
{ "NMI_TRM_HW_ERR", 0x46 },
{ "NMI_INTERRUPT_TRM", 0x4C },
{ "NMI_INTERRUPT_BREAK_POINT", 0x54 },
{ "NMI_INTERRUPT_WDG_RXF_FULL", 0x5C },
{ "NMI_INTERRUPT_WDG_NO_RBD_RXF_FULL", 0x64 },
{ "NMI_INTERRUPT_HOST", 0x66 },
{ "NMI_INTERRUPT_ACTION_PT", 0x7C },
{ "NMI_INTERRUPT_UNKNOWN", 0x84 },
{ "NMI_INTERRUPT_INST_ACTION_PT", 0x86 },
{ "ADVANCED_SYSASSERT", 0 },
};
static const char *desc_lookup(u32 num)
{
int i;
int max = ARRAY_SIZE(desc_lookup_text);
if (num < max)
return desc_lookup_text[num];
max = ARRAY_SIZE(advanced_lookup) - 1;
for (i = 0; i < max; i++) {
if (advanced_lookup[i].num == num)
break;
}
return advanced_lookup[i].name;
}
#define ERROR_START_OFFSET (1 * sizeof(u32))
#define ERROR_ELEM_SIZE (7 * sizeof(u32))
static void iwl_dump_nic_error_log(struct iwl_priv *priv)
{
struct iwl_trans *trans = priv->trans;
u32 base;
struct iwl_error_event_table table;
base = priv->device_pointers.error_event_table;
if (priv->cur_ucode == IWL_UCODE_INIT) {
if (!base)
base = priv->fw->init_errlog_ptr;
} else {
if (!base)
base = priv->fw->inst_errlog_ptr;
}
if (!iwlagn_hw_valid_rtc_data_addr(base)) {
IWL_ERR(priv,
"Not valid error log pointer 0x%08X for %s uCode\n",
base,
(priv->cur_ucode == IWL_UCODE_INIT)
? "Init" : "RT");
return;
}
/*TODO: Update dbgfs with ISR error stats obtained below */
iwl_trans_read_mem_bytes(trans, base, &table, sizeof(table));
if (ERROR_START_OFFSET <= table.valid * ERROR_ELEM_SIZE) {
IWL_ERR(trans, "Start IWL Error Log Dump:\n");
IWL_ERR(trans, "Status: 0x%08lX, count: %d\n",
priv->status, table.valid);
}
trace_iwlwifi_dev_ucode_error(trans->dev, table.error_id, table.tsf_low,
table.data1, table.data2, table.line,
table.blink1, table.blink2, table.ilink1,
table.ilink2, table.bcon_time, table.gp1,
table.gp2, table.gp3, table.ucode_ver,
table.hw_ver, table.brd_ver);
IWL_ERR(priv, "0x%08X | %-28s\n", table.error_id,
desc_lookup(table.error_id));
IWL_ERR(priv, "0x%08X | uPc\n", table.pc);
IWL_ERR(priv, "0x%08X | branchlink1\n", table.blink1);
IWL_ERR(priv, "0x%08X | branchlink2\n", table.blink2);
IWL_ERR(priv, "0x%08X | interruptlink1\n", table.ilink1);
IWL_ERR(priv, "0x%08X | interruptlink2\n", table.ilink2);
IWL_ERR(priv, "0x%08X | data1\n", table.data1);
IWL_ERR(priv, "0x%08X | data2\n", table.data2);
IWL_ERR(priv, "0x%08X | line\n", table.line);
IWL_ERR(priv, "0x%08X | beacon time\n", table.bcon_time);
IWL_ERR(priv, "0x%08X | tsf low\n", table.tsf_low);
IWL_ERR(priv, "0x%08X | tsf hi\n", table.tsf_hi);
IWL_ERR(priv, "0x%08X | time gp1\n", table.gp1);
IWL_ERR(priv, "0x%08X | time gp2\n", table.gp2);
IWL_ERR(priv, "0x%08X | time gp3\n", table.gp3);
IWL_ERR(priv, "0x%08X | uCode version\n", table.ucode_ver);
IWL_ERR(priv, "0x%08X | hw version\n", table.hw_ver);
IWL_ERR(priv, "0x%08X | board version\n", table.brd_ver);
IWL_ERR(priv, "0x%08X | hcmd\n", table.hcmd);
IWL_ERR(priv, "0x%08X | isr0\n", table.isr0);
IWL_ERR(priv, "0x%08X | isr1\n", table.isr1);
IWL_ERR(priv, "0x%08X | isr2\n", table.isr2);
IWL_ERR(priv, "0x%08X | isr3\n", table.isr3);
IWL_ERR(priv, "0x%08X | isr4\n", table.isr4);
IWL_ERR(priv, "0x%08X | isr_pref\n", table.isr_pref);
IWL_ERR(priv, "0x%08X | wait_event\n", table.wait_event);
IWL_ERR(priv, "0x%08X | l2p_control\n", table.l2p_control);
IWL_ERR(priv, "0x%08X | l2p_duration\n", table.l2p_duration);
IWL_ERR(priv, "0x%08X | l2p_mhvalid\n", table.l2p_mhvalid);
IWL_ERR(priv, "0x%08X | l2p_addr_match\n", table.l2p_addr_match);
IWL_ERR(priv, "0x%08X | lmpm_pmg_sel\n", table.lmpm_pmg_sel);
IWL_ERR(priv, "0x%08X | timestamp\n", table.u_timestamp);
IWL_ERR(priv, "0x%08X | flow_handler\n", table.flow_handler);
}
#define EVENT_START_OFFSET (4 * sizeof(u32))
/**
* iwl_print_event_log - Dump error event log to syslog
*
*/
static int iwl_print_event_log(struct iwl_priv *priv, u32 start_idx,
u32 num_events, u32 mode,
int pos, char **buf, size_t bufsz)
{
u32 i;
u32 base; /* SRAM byte address of event log header */
u32 event_size; /* 2 u32s, or 3 u32s if timestamp recorded */
u32 ptr; /* SRAM byte address of log data */
u32 ev, time, data; /* event log data */
unsigned long reg_flags;
struct iwl_trans *trans = priv->trans;
if (num_events == 0)
return pos;
base = priv->device_pointers.log_event_table;
if (priv->cur_ucode == IWL_UCODE_INIT) {
if (!base)
base = priv->fw->init_evtlog_ptr;
} else {
if (!base)
base = priv->fw->inst_evtlog_ptr;
}
if (mode == 0)
event_size = 2 * sizeof(u32);
else
event_size = 3 * sizeof(u32);
ptr = base + EVENT_START_OFFSET + (start_idx * event_size);
/* Make sure device is powered up for SRAM reads */
if (!iwl_trans_grab_nic_access(trans, false, ®_flags))
return pos;
/* Set starting address; reads will auto-increment */
iwl_write32(trans, HBUS_TARG_MEM_RADDR, ptr);
/* "time" is actually "data" for mode 0 (no timestamp).
* place event id # at far right for easier visual parsing. */
for (i = 0; i < num_events; i++) {
ev = iwl_read32(trans, HBUS_TARG_MEM_RDAT);
time = iwl_read32(trans, HBUS_TARG_MEM_RDAT);
if (mode == 0) {
/* data, ev */
if (bufsz) {
pos += scnprintf(*buf + pos, bufsz - pos,
"EVT_LOG:0x%08x:%04u\n",
time, ev);
} else {
trace_iwlwifi_dev_ucode_event(trans->dev, 0,
time, ev);
IWL_ERR(priv, "EVT_LOG:0x%08x:%04u\n",
time, ev);
}
} else {
data = iwl_read32(trans, HBUS_TARG_MEM_RDAT);
if (bufsz) {
pos += scnprintf(*buf + pos, bufsz - pos,
"EVT_LOGT:%010u:0x%08x:%04u\n",
time, data, ev);
} else {
IWL_ERR(priv, "EVT_LOGT:%010u:0x%08x:%04u\n",
time, data, ev);
trace_iwlwifi_dev_ucode_event(trans->dev, time,
data, ev);
}
}
}
/* Allow device to power down */
iwl_trans_release_nic_access(trans, ®_flags);
return pos;
}
/**
* iwl_print_last_event_logs - Dump the newest # of event log to syslog
*/
static int iwl_print_last_event_logs(struct iwl_priv *priv, u32 capacity,
u32 num_wraps, u32 next_entry,
u32 size, u32 mode,
int pos, char **buf, size_t bufsz)
{
/*
* display the newest DEFAULT_LOG_ENTRIES entries
* i.e the entries just before the next ont that uCode would fill.
*/
if (num_wraps) {
if (next_entry < size) {
pos = iwl_print_event_log(priv,
capacity - (size - next_entry),
size - next_entry, mode,
pos, buf, bufsz);
pos = iwl_print_event_log(priv, 0,
next_entry, mode,
pos, buf, bufsz);
} else
pos = iwl_print_event_log(priv, next_entry - size,
size, mode, pos, buf, bufsz);
} else {
if (next_entry < size) {
pos = iwl_print_event_log(priv, 0, next_entry,
mode, pos, buf, bufsz);
} else {
pos = iwl_print_event_log(priv, next_entry - size,
size, mode, pos, buf, bufsz);
}
}
return pos;
}
#define DEFAULT_DUMP_EVENT_LOG_ENTRIES (20)
int iwl_dump_nic_event_log(struct iwl_priv *priv, bool full_log,
char **buf)
{
u32 base; /* SRAM byte address of event log header */
u32 capacity; /* event log capacity in # entries */
u32 mode; /* 0 - no timestamp, 1 - timestamp recorded */
u32 num_wraps; /* # times uCode wrapped to top of log */
u32 next_entry; /* index of next entry to be written by uCode */
u32 size; /* # entries that we'll print */
u32 logsize;
int pos = 0;
size_t bufsz = 0;
struct iwl_trans *trans = priv->trans;
base = priv->device_pointers.log_event_table;
if (priv->cur_ucode == IWL_UCODE_INIT) {
logsize = priv->fw->init_evtlog_size;
if (!base)
base = priv->fw->init_evtlog_ptr;
} else {
logsize = priv->fw->inst_evtlog_size;
if (!base)
base = priv->fw->inst_evtlog_ptr;
}
if (!iwlagn_hw_valid_rtc_data_addr(base)) {
IWL_ERR(priv,
"Invalid event log pointer 0x%08X for %s uCode\n",
base,
(priv->cur_ucode == IWL_UCODE_INIT)
? "Init" : "RT");
return -EINVAL;
}
/* event log header */
capacity = iwl_trans_read_mem32(trans, base);
mode = iwl_trans_read_mem32(trans, base + (1 * sizeof(u32)));
num_wraps = iwl_trans_read_mem32(trans, base + (2 * sizeof(u32)));
next_entry = iwl_trans_read_mem32(trans, base + (3 * sizeof(u32)));
if (capacity > logsize) {
IWL_ERR(priv, "Log capacity %d is bogus, limit to %d "
"entries\n", capacity, logsize);
capacity = logsize;
}
if (next_entry > logsize) {
IWL_ERR(priv, "Log write index %d is bogus, limit to %d\n",
next_entry, logsize);
next_entry = logsize;
}
size = num_wraps ? capacity : next_entry;
/* bail out if nothing in log */
if (size == 0) {
IWL_ERR(trans, "Start IWL Event Log Dump: nothing in log\n");
return pos;
}
#ifdef CONFIG_IWLWIFI_DEBUG
if (!(iwl_have_debug_level(IWL_DL_FW_ERRORS)) && !full_log)
size = (size > DEFAULT_DUMP_EVENT_LOG_ENTRIES)
? DEFAULT_DUMP_EVENT_LOG_ENTRIES : size;
#else
size = (size > DEFAULT_DUMP_EVENT_LOG_ENTRIES)
? DEFAULT_DUMP_EVENT_LOG_ENTRIES : size;
#endif
IWL_ERR(priv, "Start IWL Event Log Dump: display last %u entries\n",
size);
#ifdef CONFIG_IWLWIFI_DEBUG
if (buf) {
if (full_log)
bufsz = capacity * 48;
else
bufsz = size * 48;
*buf = kmalloc(bufsz, GFP_KERNEL);
if (!*buf)
return -ENOMEM;
}
if (iwl_have_debug_level(IWL_DL_FW_ERRORS) || full_log) {
/*
* if uCode has wrapped back to top of log,
* start at the oldest entry,
* i.e the next one that uCode would fill.
*/
if (num_wraps)
pos = iwl_print_event_log(priv, next_entry,
capacity - next_entry, mode,
pos, buf, bufsz);
/* (then/else) start at top of log */
pos = iwl_print_event_log(priv, 0,
next_entry, mode, pos, buf, bufsz);
} else
pos = iwl_print_last_event_logs(priv, capacity, num_wraps,
next_entry, size, mode,
pos, buf, bufsz);
#else
pos = iwl_print_last_event_logs(priv, capacity, num_wraps,
next_entry, size, mode,
pos, buf, bufsz);
#endif
return pos;
}
static void iwlagn_fw_error(struct iwl_priv *priv, bool ondemand)
{
unsigned int reload_msec;
unsigned long reload_jiffies;
#ifdef CONFIG_IWLWIFI_DEBUG
if (iwl_have_debug_level(IWL_DL_FW_ERRORS))
iwl_print_rx_config_cmd(priv, IWL_RXON_CTX_BSS);
#endif
/* uCode is no longer loaded. */
priv->ucode_loaded = false;
/* Set the FW error flag -- cleared on iwl_down */
set_bit(STATUS_FW_ERROR, &priv->status);
iwl_abort_notification_waits(&priv->notif_wait);
/* Keep the restart process from trying to send host
* commands by clearing the ready bit */
clear_bit(STATUS_READY, &priv->status);
if (!ondemand) {
/*
* If firmware keep reloading, then it indicate something
* serious wrong and firmware having problem to recover
* from it. Instead of keep trying which will fill the syslog
* and hang the system, let's just stop it
*/
reload_jiffies = jiffies;
reload_msec = jiffies_to_msecs((long) reload_jiffies -
(long) priv->reload_jiffies);
priv->reload_jiffies = reload_jiffies;
if (reload_msec <= IWL_MIN_RELOAD_DURATION) {
priv->reload_count++;
if (priv->reload_count >= IWL_MAX_CONTINUE_RELOAD_CNT) {
IWL_ERR(priv, "BUG_ON, Stop restarting\n");
return;
}
} else
priv->reload_count = 0;
}
if (!test_bit(STATUS_EXIT_PENDING, &priv->status)) {
if (iwlwifi_mod_params.restart_fw) {
IWL_DEBUG_FW_ERRORS(priv,
"Restarting adapter due to uCode error.\n");
queue_work(priv->workqueue, &priv->restart);
} else
IWL_DEBUG_FW_ERRORS(priv,
"Detected FW error, but not restarting\n");
}
}
static void iwl_nic_error(struct iwl_op_mode *op_mode)
{
struct iwl_priv *priv = IWL_OP_MODE_GET_DVM(op_mode);
IWL_ERR(priv, "Loaded firmware version: %s\n",
priv->fw->fw_version);
iwl_dump_nic_error_log(priv);
iwl_dump_nic_event_log(priv, false, NULL);
iwlagn_fw_error(priv, false);
}
static void iwl_cmd_queue_full(struct iwl_op_mode *op_mode)
{
struct iwl_priv *priv = IWL_OP_MODE_GET_DVM(op_mode);
if (!iwl_check_for_ct_kill(priv)) {
IWL_ERR(priv, "Restarting adapter queue is full\n");
iwlagn_fw_error(priv, false);
}
}
#define EEPROM_RF_CONFIG_TYPE_MAX 0x3
static void iwl_nic_config(struct iwl_op_mode *op_mode)
{
struct iwl_priv *priv = IWL_OP_MODE_GET_DVM(op_mode);
/* SKU Control */
iwl_trans_set_bits_mask(priv->trans, CSR_HW_IF_CONFIG_REG,
CSR_HW_IF_CONFIG_REG_MSK_MAC_DASH |
CSR_HW_IF_CONFIG_REG_MSK_MAC_STEP,
(CSR_HW_REV_STEP(priv->trans->hw_rev) <<
CSR_HW_IF_CONFIG_REG_POS_MAC_STEP) |
(CSR_HW_REV_DASH(priv->trans->hw_rev) <<
CSR_HW_IF_CONFIG_REG_POS_MAC_DASH));
/* write radio config values to register */
if (priv->nvm_data->radio_cfg_type <= EEPROM_RF_CONFIG_TYPE_MAX) {
u32 reg_val =
priv->nvm_data->radio_cfg_type <<
CSR_HW_IF_CONFIG_REG_POS_PHY_TYPE |
priv->nvm_data->radio_cfg_step <<
CSR_HW_IF_CONFIG_REG_POS_PHY_STEP |
priv->nvm_data->radio_cfg_dash <<
CSR_HW_IF_CONFIG_REG_POS_PHY_DASH;
iwl_trans_set_bits_mask(priv->trans, CSR_HW_IF_CONFIG_REG,
CSR_HW_IF_CONFIG_REG_MSK_PHY_TYPE |
CSR_HW_IF_CONFIG_REG_MSK_PHY_STEP |
CSR_HW_IF_CONFIG_REG_MSK_PHY_DASH,
reg_val);
IWL_INFO(priv, "Radio type=0x%x-0x%x-0x%x\n",
priv->nvm_data->radio_cfg_type,
priv->nvm_data->radio_cfg_step,
priv->nvm_data->radio_cfg_dash);
} else {
WARN_ON(1);
}
/* set CSR_HW_CONFIG_REG for uCode use */
iwl_set_bit(priv->trans, CSR_HW_IF_CONFIG_REG,
CSR_HW_IF_CONFIG_REG_BIT_RADIO_SI |
CSR_HW_IF_CONFIG_REG_BIT_MAC_SI);
/* W/A : NIC is stuck in a reset state after Early PCIe power off
* (PCIe power is lost before PERST# is asserted),
* causing ME FW to lose ownership and not being able to obtain it back.
*/
iwl_set_bits_mask_prph(priv->trans, APMG_PS_CTRL_REG,
APMG_PS_CTRL_EARLY_PWR_OFF_RESET_DIS,
~APMG_PS_CTRL_EARLY_PWR_OFF_RESET_DIS);
if (priv->lib->nic_config)
priv->lib->nic_config(priv);
}
static void iwl_wimax_active(struct iwl_op_mode *op_mode)
{
struct iwl_priv *priv = IWL_OP_MODE_GET_DVM(op_mode);
clear_bit(STATUS_READY, &priv->status);
IWL_ERR(priv, "RF is used by WiMAX\n");
}
static void iwl_stop_sw_queue(struct iwl_op_mode *op_mode, int queue)
{
struct iwl_priv *priv = IWL_OP_MODE_GET_DVM(op_mode);
int mq = priv->queue_to_mac80211[queue];
if (WARN_ON_ONCE(mq == IWL_INVALID_MAC80211_QUEUE))
return;
if (atomic_inc_return(&priv->queue_stop_count[mq]) > 1) {
IWL_DEBUG_TX_QUEUES(priv,
"queue %d (mac80211 %d) already stopped\n",
queue, mq);
return;
}
set_bit(mq, &priv->transport_queue_stop);
ieee80211_stop_queue(priv->hw, mq);
}
static void iwl_wake_sw_queue(struct iwl_op_mode *op_mode, int queue)
{
struct iwl_priv *priv = IWL_OP_MODE_GET_DVM(op_mode);
int mq = priv->queue_to_mac80211[queue];
if (WARN_ON_ONCE(mq == IWL_INVALID_MAC80211_QUEUE))
return;
if (atomic_dec_return(&priv->queue_stop_count[mq]) > 0) {
IWL_DEBUG_TX_QUEUES(priv,
"queue %d (mac80211 %d) already awake\n",
queue, mq);
return;
}
clear_bit(mq, &priv->transport_queue_stop);
if (!priv->passive_no_rx)
ieee80211_wake_queue(priv->hw, mq);
}
void iwlagn_lift_passive_no_rx(struct iwl_priv *priv)
{
int mq;
if (!priv->passive_no_rx)
return;
for (mq = 0; mq < IWLAGN_FIRST_AMPDU_QUEUE; mq++) {
if (!test_bit(mq, &priv->transport_queue_stop)) {
IWL_DEBUG_TX_QUEUES(priv, "Wake queue %d", mq);
ieee80211_wake_queue(priv->hw, mq);
} else {
IWL_DEBUG_TX_QUEUES(priv, "Don't wake queue %d", mq);
}
}
priv->passive_no_rx = false;
}
static void iwl_free_skb(struct iwl_op_mode *op_mode, struct sk_buff *skb)
{
struct iwl_priv *priv = IWL_OP_MODE_GET_DVM(op_mode);
struct ieee80211_tx_info *info;
info = IEEE80211_SKB_CB(skb);
iwl_trans_free_tx_cmd(priv->trans, info->driver_data[1]);
ieee80211_free_txskb(priv->hw, skb);
}
static void iwl_set_hw_rfkill_state(struct iwl_op_mode *op_mode, bool state)
{
struct iwl_priv *priv = IWL_OP_MODE_GET_DVM(op_mode);
if (state)
set_bit(STATUS_RF_KILL_HW, &priv->status);
else
clear_bit(STATUS_RF_KILL_HW, &priv->status);
wiphy_rfkill_set_hw_state(priv->hw->wiphy, state);
}
static const struct iwl_op_mode_ops iwl_dvm_ops = {
.start = iwl_op_mode_dvm_start,
.stop = iwl_op_mode_dvm_stop,
.rx = iwl_rx_dispatch,
.queue_full = iwl_stop_sw_queue,
.queue_not_full = iwl_wake_sw_queue,
.hw_rf_kill = iwl_set_hw_rfkill_state,
.free_skb = iwl_free_skb,
.nic_error = iwl_nic_error,
.cmd_queue_full = iwl_cmd_queue_full,
.nic_config = iwl_nic_config,
.wimax_active = iwl_wimax_active,
};
/*****************************************************************************
*
* driver and module entry point
*
*****************************************************************************/
static int __init iwl_init(void)
{
int ret;
ret = iwlagn_rate_control_register();
if (ret) {
pr_err("Unable to register rate control algorithm: %d\n", ret);
return ret;
}
ret = iwl_opmode_register("iwldvm", &iwl_dvm_ops);
if (ret) {
pr_err("Unable to register op_mode: %d\n", ret);
iwlagn_rate_control_unregister();
}
return ret;
}
module_init(iwl_init);
static void __exit iwl_exit(void)
{
iwl_opmode_deregister("iwldvm");
iwlagn_rate_control_unregister();
}
module_exit(iwl_exit);
| gpl-2.0 |
tako0910/android_kernel_htc_valentewx | drivers/gpu/drm/nouveau/nv50_vram.c | 2103 | 5711 | /*
* Copyright 2010 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Ben Skeggs
*/
#include "drmP.h"
#include "nouveau_drv.h"
#include "nouveau_mm.h"
static int types[0x80] = {
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 0, 2, 2, 2, 2, 2, 2, 2, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 0, 0,
0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 2, 2, 2, 2,
1, 0, 2, 0, 1, 0, 2, 0, 1, 1, 2, 2, 1, 1, 0, 0
};
bool
nv50_vram_flags_valid(struct drm_device *dev, u32 tile_flags)
{
int type = (tile_flags & NOUVEAU_GEM_TILE_LAYOUT_MASK) >> 8;
if (likely(type < ARRAY_SIZE(types) && types[type]))
return true;
return false;
}
void
nv50_vram_del(struct drm_device *dev, struct nouveau_mem **pmem)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct ttm_bo_device *bdev = &dev_priv->ttm.bdev;
struct ttm_mem_type_manager *man = &bdev->man[TTM_PL_VRAM];
struct nouveau_mm *mm = man->priv;
struct nouveau_mm_node *this;
struct nouveau_mem *mem;
mem = *pmem;
*pmem = NULL;
if (unlikely(mem == NULL))
return;
mutex_lock(&mm->mutex);
while (!list_empty(&mem->regions)) {
this = list_first_entry(&mem->regions, struct nouveau_mm_node, rl_entry);
list_del(&this->rl_entry);
nouveau_mm_put(mm, this);
}
if (mem->tag) {
drm_mm_put_block(mem->tag);
mem->tag = NULL;
}
mutex_unlock(&mm->mutex);
kfree(mem);
}
int
nv50_vram_new(struct drm_device *dev, u64 size, u32 align, u32 size_nc,
u32 memtype, struct nouveau_mem **pmem)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct ttm_bo_device *bdev = &dev_priv->ttm.bdev;
struct ttm_mem_type_manager *man = &bdev->man[TTM_PL_VRAM];
struct nouveau_mm *mm = man->priv;
struct nouveau_mm_node *r;
struct nouveau_mem *mem;
int comp = (memtype & 0x300) >> 8;
int type = (memtype & 0x07f);
int ret;
if (!types[type])
return -EINVAL;
size >>= 12;
align >>= 12;
size_nc >>= 12;
mem = kzalloc(sizeof(*mem), GFP_KERNEL);
if (!mem)
return -ENOMEM;
mutex_lock(&mm->mutex);
if (comp) {
if (align == 16) {
struct nouveau_fb_engine *pfb = &dev_priv->engine.fb;
int n = (size >> 4) * comp;
mem->tag = drm_mm_search_free(&pfb->tag_heap, n, 0, 0);
if (mem->tag)
mem->tag = drm_mm_get_block(mem->tag, n, 0);
}
if (unlikely(!mem->tag))
comp = 0;
}
INIT_LIST_HEAD(&mem->regions);
mem->dev = dev_priv->dev;
mem->memtype = (comp << 7) | type;
mem->size = size;
do {
ret = nouveau_mm_get(mm, types[type], size, size_nc, align, &r);
if (ret) {
mutex_unlock(&mm->mutex);
nv50_vram_del(dev, &mem);
return ret;
}
list_add_tail(&r->rl_entry, &mem->regions);
size -= r->length;
} while (size);
mutex_unlock(&mm->mutex);
r = list_first_entry(&mem->regions, struct nouveau_mm_node, rl_entry);
mem->offset = (u64)r->offset << 12;
*pmem = mem;
return 0;
}
static u32
nv50_vram_rblock(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
int i, parts, colbits, rowbitsa, rowbitsb, banks;
u64 rowsize, predicted;
u32 r0, r4, rt, ru, rblock_size;
r0 = nv_rd32(dev, 0x100200);
r4 = nv_rd32(dev, 0x100204);
rt = nv_rd32(dev, 0x100250);
ru = nv_rd32(dev, 0x001540);
NV_DEBUG(dev, "memcfg 0x%08x 0x%08x 0x%08x 0x%08x\n", r0, r4, rt, ru);
for (i = 0, parts = 0; i < 8; i++) {
if (ru & (0x00010000 << i))
parts++;
}
colbits = (r4 & 0x0000f000) >> 12;
rowbitsa = ((r4 & 0x000f0000) >> 16) + 8;
rowbitsb = ((r4 & 0x00f00000) >> 20) + 8;
banks = ((r4 & 0x01000000) ? 8 : 4);
rowsize = parts * banks * (1 << colbits) * 8;
predicted = rowsize << rowbitsa;
if (r0 & 0x00000004)
predicted += rowsize << rowbitsb;
if (predicted != dev_priv->vram_size) {
NV_WARN(dev, "memory controller reports %dMiB VRAM\n",
(u32)(dev_priv->vram_size >> 20));
NV_WARN(dev, "we calculated %dMiB VRAM\n",
(u32)(predicted >> 20));
}
rblock_size = rowsize;
if (rt & 1)
rblock_size *= 3;
NV_DEBUG(dev, "rblock %d bytes\n", rblock_size);
return rblock_size;
}
int
nv50_vram_init(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
dev_priv->vram_size = nv_rd32(dev, 0x10020c);
dev_priv->vram_size |= (dev_priv->vram_size & 0xff) << 32;
dev_priv->vram_size &= 0xffffffff00ULL;
switch (dev_priv->chipset) {
case 0xaa:
case 0xac:
case 0xaf:
dev_priv->vram_sys_base = (u64)nv_rd32(dev, 0x100e10) << 12;
dev_priv->vram_rblock_size = 4096;
break;
default:
dev_priv->vram_rblock_size = nv50_vram_rblock(dev);
break;
}
return 0;
}
| gpl-2.0 |
Mirenk/android_kernel_semc_msm7x30 | arch/x86/power/hibernate_32.c | 3383 | 4023 | /*
* Hibernation support specific for i386 - temporary page tables
*
* Distribute under GPLv2
*
* Copyright (c) 2006 Rafael J. Wysocki <rjw@sisk.pl>
*/
#include <linux/gfp.h>
#include <linux/suspend.h>
#include <linux/bootmem.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/mmzone.h>
/* Defined in hibernate_asm_32.S */
extern int restore_image(void);
/* References to section boundaries */
extern const void __nosave_begin, __nosave_end;
/* Pointer to the temporary resume page tables */
pgd_t *resume_pg_dir;
/* The following three functions are based on the analogous code in
* arch/x86/mm/init_32.c
*/
/*
* Create a middle page table on a resume-safe page and put a pointer to it in
* the given global directory entry. This only returns the gd entry
* in non-PAE compilation mode, since the middle layer is folded.
*/
static pmd_t *resume_one_md_table_init(pgd_t *pgd)
{
pud_t *pud;
pmd_t *pmd_table;
#ifdef CONFIG_X86_PAE
pmd_table = (pmd_t *)get_safe_page(GFP_ATOMIC);
if (!pmd_table)
return NULL;
set_pgd(pgd, __pgd(__pa(pmd_table) | _PAGE_PRESENT));
pud = pud_offset(pgd, 0);
BUG_ON(pmd_table != pmd_offset(pud, 0));
#else
pud = pud_offset(pgd, 0);
pmd_table = pmd_offset(pud, 0);
#endif
return pmd_table;
}
/*
* Create a page table on a resume-safe page and place a pointer to it in
* a middle page directory entry.
*/
static pte_t *resume_one_page_table_init(pmd_t *pmd)
{
if (pmd_none(*pmd)) {
pte_t *page_table = (pte_t *)get_safe_page(GFP_ATOMIC);
if (!page_table)
return NULL;
set_pmd(pmd, __pmd(__pa(page_table) | _PAGE_TABLE));
BUG_ON(page_table != pte_offset_kernel(pmd, 0));
return page_table;
}
return pte_offset_kernel(pmd, 0);
}
/*
* This maps the physical memory to kernel virtual address space, a total
* of max_low_pfn pages, by creating page tables starting from address
* PAGE_OFFSET. The page tables are allocated out of resume-safe pages.
*/
static int resume_physical_mapping_init(pgd_t *pgd_base)
{
unsigned long pfn;
pgd_t *pgd;
pmd_t *pmd;
pte_t *pte;
int pgd_idx, pmd_idx;
pgd_idx = pgd_index(PAGE_OFFSET);
pgd = pgd_base + pgd_idx;
pfn = 0;
for (; pgd_idx < PTRS_PER_PGD; pgd++, pgd_idx++) {
pmd = resume_one_md_table_init(pgd);
if (!pmd)
return -ENOMEM;
if (pfn >= max_low_pfn)
continue;
for (pmd_idx = 0; pmd_idx < PTRS_PER_PMD; pmd++, pmd_idx++) {
if (pfn >= max_low_pfn)
break;
/* Map with big pages if possible, otherwise create
* normal page tables.
* NOTE: We can mark everything as executable here
*/
if (cpu_has_pse) {
set_pmd(pmd, pfn_pmd(pfn, PAGE_KERNEL_LARGE_EXEC));
pfn += PTRS_PER_PTE;
} else {
pte_t *max_pte;
pte = resume_one_page_table_init(pmd);
if (!pte)
return -ENOMEM;
max_pte = pte + PTRS_PER_PTE;
for (; pte < max_pte; pte++, pfn++) {
if (pfn >= max_low_pfn)
break;
set_pte(pte, pfn_pte(pfn, PAGE_KERNEL_EXEC));
}
}
}
}
resume_map_numa_kva(pgd_base);
return 0;
}
static inline void resume_init_first_level_page_table(pgd_t *pg_dir)
{
#ifdef CONFIG_X86_PAE
int i;
/* Init entries of the first-level page table to the zero page */
for (i = 0; i < PTRS_PER_PGD; i++)
set_pgd(pg_dir + i,
__pgd(__pa(empty_zero_page) | _PAGE_PRESENT));
#endif
}
int swsusp_arch_resume(void)
{
int error;
resume_pg_dir = (pgd_t *)get_safe_page(GFP_ATOMIC);
if (!resume_pg_dir)
return -ENOMEM;
resume_init_first_level_page_table(resume_pg_dir);
error = resume_physical_mapping_init(resume_pg_dir);
if (error)
return error;
/* We have got enough memory and from now on we cannot recover */
restore_image();
return 0;
}
/*
* pfn_is_nosave - check if given pfn is in the 'nosave' section
*/
int pfn_is_nosave(unsigned long pfn)
{
unsigned long nosave_begin_pfn = __pa_symbol(&__nosave_begin) >> PAGE_SHIFT;
unsigned long nosave_end_pfn = PAGE_ALIGN(__pa_symbol(&__nosave_end)) >> PAGE_SHIFT;
return (pfn >= nosave_begin_pfn) && (pfn < nosave_end_pfn);
}
| gpl-2.0 |
fortunaFiWn/android_kernel_samsung_fortuna-common | arch/arm/mach-lpc32xx/clock.c | 3639 | 35139 | /*
* arch/arm/mach-lpc32xx/clock.c
*
* Author: Kevin Wells <kevin.wells@nxp.com>
*
* Copyright (C) 2010 NXP Semiconductors
*
* 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.
*/
/*
* LPC32xx clock management driver overview
*
* The LPC32XX contains a number of high level system clocks that can be
* generated from different sources. These system clocks are used to
* generate the CPU and bus rates and the individual peripheral clocks in
* the system. When Linux is started by the boot loader, the system
* clocks are already running. Stopping a system clock during normal
* Linux operation should never be attempted, as peripherals that require
* those clocks will quit working (ie, DRAM).
*
* The LPC32xx high level clock tree looks as follows. Clocks marked with
* an asterisk are always on and cannot be disabled. Clocks marked with
* an ampersand can only be disabled in CPU suspend mode. Clocks marked
* with a caret are always on if it is the selected clock for the SYSCLK
* source. The clock that isn't used for SYSCLK can be enabled and
* disabled normally.
* 32KHz oscillator*
* / | \
* RTC* PLL397^ TOUCH
* /
* Main oscillator^ /
* | \ /
* | SYSCLK&
* | \
* | \
* USB_PLL HCLK_PLL&
* | | |
* USB host/device PCLK& |
* | |
* Peripherals
*
* The CPU and chip bus rates are derived from the HCLK PLL, which can
* generate various clock rates up to 266MHz and beyond. The internal bus
* rates (PCLK and HCLK) are generated from dividers based on the HCLK
* PLL rate. HCLK can be a ratio of 1:1, 1:2, or 1:4 or HCLK PLL rate,
* while PCLK can be 1:1 to 1:32 of HCLK PLL rate. Most peripherals high
* level clocks are based on either HCLK or PCLK, but have their own
* dividers as part of the IP itself. Because of this, the system clock
* rates should not be changed.
*
* The HCLK PLL is clocked from SYSCLK, which can be derived from the
* main oscillator or PLL397. PLL397 generates a rate that is 397 times
* the 32KHz oscillator rate. The main oscillator runs at the selected
* oscillator/crystal rate on the mosc_in pin of the LPC32xx. This rate
* is normally 13MHz, but depends on the selection of external crystals
* or oscillators. If USB operation is required, the main oscillator must
* be used in the system.
*
* Switching SYSCLK between sources during normal Linux operation is not
* supported. SYSCLK is preset in the bootloader. Because of the
* complexities of clock management during clock frequency changes,
* there are some limitations to the clock driver explained below:
* - The PLL397 and main oscillator can be enabled and disabled by the
* clk_enable() and clk_disable() functions unless SYSCLK is based
* on that clock. This allows the other oscillator that isn't driving
* the HCLK PLL to be used as another system clock that can be routed
* to an external pin.
* - The muxed SYSCLK input and HCLK_PLL rate cannot be changed with
* this driver.
* - HCLK and PCLK rates cannot be changed as part of this driver.
* - Most peripherals have their own dividers are part of the peripheral
* block. Changing SYSCLK, HCLK PLL, HCLK, or PCLK sources or rates
* will also impact the individual peripheral rates.
*/
#include <linux/export.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/errno.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/amba/bus.h>
#include <linux/amba/clcd.h>
#include <linux/clkdev.h>
#include <mach/hardware.h>
#include <mach/platform.h>
#include "clock.h"
#include "common.h"
static DEFINE_SPINLOCK(global_clkregs_lock);
static int usb_pll_enable, usb_pll_valid;
static struct clk clk_armpll;
static struct clk clk_usbpll;
/*
* Post divider values for PLLs based on selected register value
*/
static const u32 pll_postdivs[4] = {1, 2, 4, 8};
static unsigned long local_return_parent_rate(struct clk *clk)
{
/*
* If a clock has a rate of 0, then it inherits it's parent
* clock rate
*/
while (clk->rate == 0)
clk = clk->parent;
return clk->rate;
}
/* 32KHz clock has a fixed rate and is not stoppable */
static struct clk osc_32KHz = {
.rate = LPC32XX_CLOCK_OSC_FREQ,
.get_rate = local_return_parent_rate,
};
static int local_pll397_enable(struct clk *clk, int enable)
{
u32 reg;
unsigned long timeout = jiffies + msecs_to_jiffies(10);
reg = __raw_readl(LPC32XX_CLKPWR_PLL397_CTRL);
if (enable == 0) {
reg |= LPC32XX_CLKPWR_SYSCTRL_PLL397_DIS;
__raw_writel(reg, LPC32XX_CLKPWR_PLL397_CTRL);
} else {
/* Enable PLL397 */
reg &= ~LPC32XX_CLKPWR_SYSCTRL_PLL397_DIS;
__raw_writel(reg, LPC32XX_CLKPWR_PLL397_CTRL);
/* Wait for PLL397 lock */
while (((__raw_readl(LPC32XX_CLKPWR_PLL397_CTRL) &
LPC32XX_CLKPWR_SYSCTRL_PLL397_STS) == 0) &&
time_before(jiffies, timeout))
cpu_relax();
if ((__raw_readl(LPC32XX_CLKPWR_PLL397_CTRL) &
LPC32XX_CLKPWR_SYSCTRL_PLL397_STS) == 0)
return -ENODEV;
}
return 0;
}
static int local_oscmain_enable(struct clk *clk, int enable)
{
u32 reg;
unsigned long timeout = jiffies + msecs_to_jiffies(10);
reg = __raw_readl(LPC32XX_CLKPWR_MAIN_OSC_CTRL);
if (enable == 0) {
reg |= LPC32XX_CLKPWR_MOSC_DISABLE;
__raw_writel(reg, LPC32XX_CLKPWR_MAIN_OSC_CTRL);
} else {
/* Enable main oscillator */
reg &= ~LPC32XX_CLKPWR_MOSC_DISABLE;
__raw_writel(reg, LPC32XX_CLKPWR_MAIN_OSC_CTRL);
/* Wait for main oscillator to start */
while (((__raw_readl(LPC32XX_CLKPWR_MAIN_OSC_CTRL) &
LPC32XX_CLKPWR_MOSC_DISABLE) != 0) &&
time_before(jiffies, timeout))
cpu_relax();
if ((__raw_readl(LPC32XX_CLKPWR_MAIN_OSC_CTRL) &
LPC32XX_CLKPWR_MOSC_DISABLE) != 0)
return -ENODEV;
}
return 0;
}
static struct clk osc_pll397 = {
.parent = &osc_32KHz,
.enable = local_pll397_enable,
.rate = LPC32XX_CLOCK_OSC_FREQ * 397,
.get_rate = local_return_parent_rate,
};
static struct clk osc_main = {
.enable = local_oscmain_enable,
.rate = LPC32XX_MAIN_OSC_FREQ,
.get_rate = local_return_parent_rate,
};
static struct clk clk_sys;
/*
* Convert a PLL register value to a PLL output frequency
*/
u32 clk_get_pllrate_from_reg(u32 inputclk, u32 regval)
{
struct clk_pll_setup pllcfg;
pllcfg.cco_bypass_b15 = 0;
pllcfg.direct_output_b14 = 0;
pllcfg.fdbk_div_ctrl_b13 = 0;
if ((regval & LPC32XX_CLKPWR_HCLKPLL_CCO_BYPASS) != 0)
pllcfg.cco_bypass_b15 = 1;
if ((regval & LPC32XX_CLKPWR_HCLKPLL_POSTDIV_BYPASS) != 0)
pllcfg.direct_output_b14 = 1;
if ((regval & LPC32XX_CLKPWR_HCLKPLL_FDBK_SEL_FCLK) != 0)
pllcfg.fdbk_div_ctrl_b13 = 1;
pllcfg.pll_m = 1 + ((regval >> 1) & 0xFF);
pllcfg.pll_n = 1 + ((regval >> 9) & 0x3);
pllcfg.pll_p = pll_postdivs[((regval >> 11) & 0x3)];
return clk_check_pll_setup(inputclk, &pllcfg);
}
/*
* Setup the HCLK PLL with a PLL structure
*/
static u32 local_clk_pll_setup(struct clk_pll_setup *PllSetup)
{
u32 tv, tmp = 0;
if (PllSetup->analog_on != 0)
tmp |= LPC32XX_CLKPWR_HCLKPLL_POWER_UP;
if (PllSetup->cco_bypass_b15 != 0)
tmp |= LPC32XX_CLKPWR_HCLKPLL_CCO_BYPASS;
if (PllSetup->direct_output_b14 != 0)
tmp |= LPC32XX_CLKPWR_HCLKPLL_POSTDIV_BYPASS;
if (PllSetup->fdbk_div_ctrl_b13 != 0)
tmp |= LPC32XX_CLKPWR_HCLKPLL_FDBK_SEL_FCLK;
tv = ffs(PllSetup->pll_p) - 1;
if ((!is_power_of_2(PllSetup->pll_p)) || (tv > 3))
return 0;
tmp |= LPC32XX_CLKPWR_HCLKPLL_POSTDIV_2POW(tv);
tmp |= LPC32XX_CLKPWR_HCLKPLL_PREDIV_PLUS1(PllSetup->pll_n - 1);
tmp |= LPC32XX_CLKPWR_HCLKPLL_PLLM(PllSetup->pll_m - 1);
return tmp;
}
/*
* Update the ARM core PLL frequency rate variable from the actual PLL setting
*/
static void local_update_armpll_rate(void)
{
u32 clkin, pllreg;
clkin = clk_armpll.parent->rate;
pllreg = __raw_readl(LPC32XX_CLKPWR_HCLKPLL_CTRL) & 0x1FFFF;
clk_armpll.rate = clk_get_pllrate_from_reg(clkin, pllreg);
}
/*
* Find a PLL configuration for the selected input frequency
*/
static u32 local_clk_find_pll_cfg(u32 pllin_freq, u32 target_freq,
struct clk_pll_setup *pllsetup)
{
u32 ifreq, freqtol, m, n, p, fclkout;
/* Determine frequency tolerance limits */
freqtol = target_freq / 250;
ifreq = pllin_freq;
/* Is direct bypass mode possible? */
if (abs(pllin_freq - target_freq) <= freqtol) {
pllsetup->analog_on = 0;
pllsetup->cco_bypass_b15 = 1;
pllsetup->direct_output_b14 = 1;
pllsetup->fdbk_div_ctrl_b13 = 1;
pllsetup->pll_p = pll_postdivs[0];
pllsetup->pll_n = 1;
pllsetup->pll_m = 1;
return clk_check_pll_setup(ifreq, pllsetup);
} else if (target_freq <= ifreq) {
pllsetup->analog_on = 0;
pllsetup->cco_bypass_b15 = 1;
pllsetup->direct_output_b14 = 0;
pllsetup->fdbk_div_ctrl_b13 = 1;
pllsetup->pll_n = 1;
pllsetup->pll_m = 1;
for (p = 0; p <= 3; p++) {
pllsetup->pll_p = pll_postdivs[p];
fclkout = clk_check_pll_setup(ifreq, pllsetup);
if (abs(target_freq - fclkout) <= freqtol)
return fclkout;
}
}
/* Is direct mode possible? */
pllsetup->analog_on = 1;
pllsetup->cco_bypass_b15 = 0;
pllsetup->direct_output_b14 = 1;
pllsetup->fdbk_div_ctrl_b13 = 0;
pllsetup->pll_p = pll_postdivs[0];
for (m = 1; m <= 256; m++) {
for (n = 1; n <= 4; n++) {
/* Compute output frequency for this value */
pllsetup->pll_n = n;
pllsetup->pll_m = m;
fclkout = clk_check_pll_setup(ifreq,
pllsetup);
if (abs(target_freq - fclkout) <=
freqtol)
return fclkout;
}
}
/* Is integer mode possible? */
pllsetup->analog_on = 1;
pllsetup->cco_bypass_b15 = 0;
pllsetup->direct_output_b14 = 0;
pllsetup->fdbk_div_ctrl_b13 = 1;
for (m = 1; m <= 256; m++) {
for (n = 1; n <= 4; n++) {
for (p = 0; p < 4; p++) {
/* Compute output frequency */
pllsetup->pll_p = pll_postdivs[p];
pllsetup->pll_n = n;
pllsetup->pll_m = m;
fclkout = clk_check_pll_setup(
ifreq, pllsetup);
if (abs(target_freq - fclkout) <= freqtol)
return fclkout;
}
}
}
/* Try non-integer mode */
pllsetup->analog_on = 1;
pllsetup->cco_bypass_b15 = 0;
pllsetup->direct_output_b14 = 0;
pllsetup->fdbk_div_ctrl_b13 = 0;
for (m = 1; m <= 256; m++) {
for (n = 1; n <= 4; n++) {
for (p = 0; p < 4; p++) {
/* Compute output frequency */
pllsetup->pll_p = pll_postdivs[p];
pllsetup->pll_n = n;
pllsetup->pll_m = m;
fclkout = clk_check_pll_setup(
ifreq, pllsetup);
if (abs(target_freq - fclkout) <= freqtol)
return fclkout;
}
}
}
return 0;
}
static struct clk clk_armpll = {
.parent = &clk_sys,
.get_rate = local_return_parent_rate,
};
/*
* Setup the USB PLL with a PLL structure
*/
static u32 local_clk_usbpll_setup(struct clk_pll_setup *pHCLKPllSetup)
{
u32 reg, tmp = local_clk_pll_setup(pHCLKPllSetup);
reg = __raw_readl(LPC32XX_CLKPWR_USB_CTRL) & ~0x1FFFF;
reg |= tmp;
__raw_writel(reg, LPC32XX_CLKPWR_USB_CTRL);
return clk_check_pll_setup(clk_usbpll.parent->rate,
pHCLKPllSetup);
}
static int local_usbpll_enable(struct clk *clk, int enable)
{
u32 reg;
int ret = 0;
unsigned long timeout = jiffies + msecs_to_jiffies(20);
reg = __raw_readl(LPC32XX_CLKPWR_USB_CTRL);
__raw_writel(reg & ~(LPC32XX_CLKPWR_USBCTRL_CLK_EN2 |
LPC32XX_CLKPWR_USBCTRL_PLL_PWRUP),
LPC32XX_CLKPWR_USB_CTRL);
__raw_writel(reg & ~LPC32XX_CLKPWR_USBCTRL_CLK_EN1,
LPC32XX_CLKPWR_USB_CTRL);
if (enable && usb_pll_valid && usb_pll_enable) {
ret = -ENODEV;
/*
* If the PLL rate has been previously set, then the rate
* in the PLL register is valid and can be enabled here.
* Otherwise, it needs to be enabled as part of setrate.
*/
/*
* Gate clock into PLL
*/
reg |= LPC32XX_CLKPWR_USBCTRL_CLK_EN1;
__raw_writel(reg, LPC32XX_CLKPWR_USB_CTRL);
/*
* Enable PLL
*/
reg |= LPC32XX_CLKPWR_USBCTRL_PLL_PWRUP;
__raw_writel(reg, LPC32XX_CLKPWR_USB_CTRL);
/*
* Wait for PLL to lock
*/
while (time_before(jiffies, timeout) && (ret == -ENODEV)) {
reg = __raw_readl(LPC32XX_CLKPWR_USB_CTRL);
if (reg & LPC32XX_CLKPWR_USBCTRL_PLL_STS)
ret = 0;
else
udelay(10);
}
/*
* Gate clock from PLL if PLL is locked
*/
if (ret == 0) {
__raw_writel(reg | LPC32XX_CLKPWR_USBCTRL_CLK_EN2,
LPC32XX_CLKPWR_USB_CTRL);
} else {
__raw_writel(reg & ~(LPC32XX_CLKPWR_USBCTRL_CLK_EN1 |
LPC32XX_CLKPWR_USBCTRL_PLL_PWRUP),
LPC32XX_CLKPWR_USB_CTRL);
}
} else if ((enable == 0) && usb_pll_valid && usb_pll_enable) {
usb_pll_valid = 0;
usb_pll_enable = 0;
}
return ret;
}
static unsigned long local_usbpll_round_rate(struct clk *clk,
unsigned long rate)
{
u32 clkin, usbdiv;
struct clk_pll_setup pllsetup;
/*
* Unlike other clocks, this clock has a KHz input rate, so bump
* it up to work with the PLL function
*/
rate = rate * 1000;
clkin = clk->get_rate(clk);
usbdiv = (__raw_readl(LPC32XX_CLKPWR_USBCLK_PDIV) &
LPC32XX_CLKPWR_USBPDIV_PLL_MASK) + 1;
clkin = clkin / usbdiv;
/* Try to find a good rate setup */
if (local_clk_find_pll_cfg(clkin, rate, &pllsetup) == 0)
return 0;
return clk_check_pll_setup(clkin, &pllsetup);
}
static int local_usbpll_set_rate(struct clk *clk, unsigned long rate)
{
int ret = -ENODEV;
u32 clkin, usbdiv;
struct clk_pll_setup pllsetup;
/*
* Unlike other clocks, this clock has a KHz input rate, so bump
* it up to work with the PLL function
*/
rate = rate * 1000;
clkin = clk->get_rate(clk->parent);
usbdiv = (__raw_readl(LPC32XX_CLKPWR_USBCLK_PDIV) &
LPC32XX_CLKPWR_USBPDIV_PLL_MASK) + 1;
clkin = clkin / usbdiv;
/* Try to find a good rate setup */
if (local_clk_find_pll_cfg(clkin, rate, &pllsetup) == 0)
return -EINVAL;
/*
* Disable PLL clocks during PLL change
*/
local_usbpll_enable(clk, 0);
pllsetup.analog_on = 0;
local_clk_usbpll_setup(&pllsetup);
/*
* Start USB PLL and check PLL status
*/
usb_pll_valid = 1;
usb_pll_enable = 1;
ret = local_usbpll_enable(clk, 1);
if (ret >= 0)
clk->rate = clk_check_pll_setup(clkin, &pllsetup);
return ret;
}
static struct clk clk_usbpll = {
.parent = &osc_main,
.set_rate = local_usbpll_set_rate,
.enable = local_usbpll_enable,
.rate = 48000, /* In KHz */
.get_rate = local_return_parent_rate,
.round_rate = local_usbpll_round_rate,
};
static u32 clk_get_hclk_div(void)
{
static const u32 hclkdivs[4] = {1, 2, 4, 4};
return hclkdivs[LPC32XX_CLKPWR_HCLKDIV_DIV_2POW(
__raw_readl(LPC32XX_CLKPWR_HCLK_DIV))];
}
static struct clk clk_hclk = {
.parent = &clk_armpll,
.get_rate = local_return_parent_rate,
};
static struct clk clk_pclk = {
.parent = &clk_armpll,
.get_rate = local_return_parent_rate,
};
static int local_onoff_enable(struct clk *clk, int enable)
{
u32 tmp;
tmp = __raw_readl(clk->enable_reg);
if (enable == 0)
tmp &= ~clk->enable_mask;
else
tmp |= clk->enable_mask;
__raw_writel(tmp, clk->enable_reg);
return 0;
}
/* Peripheral clock sources */
static struct clk clk_timer0 = {
.parent = &clk_pclk,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_TIMERS_PWMS_CLK_CTRL_1,
.enable_mask = LPC32XX_CLKPWR_TMRPWMCLK_TIMER0_EN,
.get_rate = local_return_parent_rate,
};
static struct clk clk_timer1 = {
.parent = &clk_pclk,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_TIMERS_PWMS_CLK_CTRL_1,
.enable_mask = LPC32XX_CLKPWR_TMRPWMCLK_TIMER1_EN,
.get_rate = local_return_parent_rate,
};
static struct clk clk_timer2 = {
.parent = &clk_pclk,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_TIMERS_PWMS_CLK_CTRL_1,
.enable_mask = LPC32XX_CLKPWR_TMRPWMCLK_TIMER2_EN,
.get_rate = local_return_parent_rate,
};
static struct clk clk_timer3 = {
.parent = &clk_pclk,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_TIMERS_PWMS_CLK_CTRL_1,
.enable_mask = LPC32XX_CLKPWR_TMRPWMCLK_TIMER3_EN,
.get_rate = local_return_parent_rate,
};
static struct clk clk_mpwm = {
.parent = &clk_pclk,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_TIMERS_PWMS_CLK_CTRL_1,
.enable_mask = LPC32XX_CLKPWR_TMRPWMCLK_MPWM_EN,
.get_rate = local_return_parent_rate,
};
static struct clk clk_wdt = {
.parent = &clk_pclk,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_TIMER_CLK_CTRL,
.enable_mask = LPC32XX_CLKPWR_PWMCLK_WDOG_EN,
.get_rate = local_return_parent_rate,
};
static struct clk clk_vfp9 = {
.parent = &clk_pclk,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_DEBUG_CTRL,
.enable_mask = LPC32XX_CLKPWR_VFP_CLOCK_ENABLE_BIT,
.get_rate = local_return_parent_rate,
};
static struct clk clk_dma = {
.parent = &clk_hclk,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_DMA_CLK_CTRL,
.enable_mask = LPC32XX_CLKPWR_DMACLKCTRL_CLK_EN,
.get_rate = local_return_parent_rate,
};
static struct clk clk_pwm = {
.parent = &clk_pclk,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_PWM_CLK_CTRL,
.enable_mask = LPC32XX_CLKPWR_PWMCLK_PWM1CLK_EN |
LPC32XX_CLKPWR_PWMCLK_PWM1SEL_PCLK |
LPC32XX_CLKPWR_PWMCLK_PWM1_DIV(1) |
LPC32XX_CLKPWR_PWMCLK_PWM2CLK_EN |
LPC32XX_CLKPWR_PWMCLK_PWM2SEL_PCLK |
LPC32XX_CLKPWR_PWMCLK_PWM2_DIV(1),
.get_rate = local_return_parent_rate,
};
static struct clk clk_uart3 = {
.parent = &clk_pclk,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_UART_CLK_CTRL,
.enable_mask = LPC32XX_CLKPWR_UARTCLKCTRL_UART3_EN,
.get_rate = local_return_parent_rate,
};
static struct clk clk_uart4 = {
.parent = &clk_pclk,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_UART_CLK_CTRL,
.enable_mask = LPC32XX_CLKPWR_UARTCLKCTRL_UART4_EN,
.get_rate = local_return_parent_rate,
};
static struct clk clk_uart5 = {
.parent = &clk_pclk,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_UART_CLK_CTRL,
.enable_mask = LPC32XX_CLKPWR_UARTCLKCTRL_UART5_EN,
.get_rate = local_return_parent_rate,
};
static struct clk clk_uart6 = {
.parent = &clk_pclk,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_UART_CLK_CTRL,
.enable_mask = LPC32XX_CLKPWR_UARTCLKCTRL_UART6_EN,
.get_rate = local_return_parent_rate,
};
static struct clk clk_i2c0 = {
.parent = &clk_hclk,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_I2C_CLK_CTRL,
.enable_mask = LPC32XX_CLKPWR_I2CCLK_I2C1CLK_EN,
.get_rate = local_return_parent_rate,
};
static struct clk clk_i2c1 = {
.parent = &clk_hclk,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_I2C_CLK_CTRL,
.enable_mask = LPC32XX_CLKPWR_I2CCLK_I2C2CLK_EN,
.get_rate = local_return_parent_rate,
};
static struct clk clk_i2c2 = {
.parent = &clk_pclk,
.enable = local_onoff_enable,
.enable_reg = io_p2v(LPC32XX_USB_BASE + 0xFF4),
.enable_mask = 0x4,
.get_rate = local_return_parent_rate,
};
static struct clk clk_ssp0 = {
.parent = &clk_hclk,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_SSP_CLK_CTRL,
.enable_mask = LPC32XX_CLKPWR_SSPCTRL_SSPCLK0_EN,
.get_rate = local_return_parent_rate,
};
static struct clk clk_ssp1 = {
.parent = &clk_hclk,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_SSP_CLK_CTRL,
.enable_mask = LPC32XX_CLKPWR_SSPCTRL_SSPCLK1_EN,
.get_rate = local_return_parent_rate,
};
static struct clk clk_kscan = {
.parent = &osc_32KHz,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_KEY_CLK_CTRL,
.enable_mask = LPC32XX_CLKPWR_KEYCLKCTRL_CLK_EN,
.get_rate = local_return_parent_rate,
};
static struct clk clk_nand = {
.parent = &clk_hclk,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_NAND_CLK_CTRL,
.enable_mask = LPC32XX_CLKPWR_NANDCLK_SLCCLK_EN |
LPC32XX_CLKPWR_NANDCLK_SEL_SLC,
.get_rate = local_return_parent_rate,
};
static struct clk clk_nand_mlc = {
.parent = &clk_hclk,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_NAND_CLK_CTRL,
.enable_mask = LPC32XX_CLKPWR_NANDCLK_MLCCLK_EN |
LPC32XX_CLKPWR_NANDCLK_DMA_INT |
LPC32XX_CLKPWR_NANDCLK_INTSEL_MLC,
.get_rate = local_return_parent_rate,
};
static struct clk clk_i2s0 = {
.parent = &clk_hclk,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_I2S_CLK_CTRL,
.enable_mask = LPC32XX_CLKPWR_I2SCTRL_I2SCLK0_EN,
.get_rate = local_return_parent_rate,
};
static struct clk clk_i2s1 = {
.parent = &clk_hclk,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_I2S_CLK_CTRL,
.enable_mask = LPC32XX_CLKPWR_I2SCTRL_I2SCLK1_EN |
LPC32XX_CLKPWR_I2SCTRL_I2S1_USE_DMA,
.get_rate = local_return_parent_rate,
};
static struct clk clk_net = {
.parent = &clk_hclk,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_MACCLK_CTRL,
.enable_mask = (LPC32XX_CLKPWR_MACCTRL_DMACLK_EN |
LPC32XX_CLKPWR_MACCTRL_MMIOCLK_EN |
LPC32XX_CLKPWR_MACCTRL_HRCCLK_EN),
.get_rate = local_return_parent_rate,
};
static struct clk clk_rtc = {
.parent = &osc_32KHz,
.rate = 1, /* 1 Hz */
.get_rate = local_return_parent_rate,
};
static int local_usb_enable(struct clk *clk, int enable)
{
u32 tmp;
if (enable) {
/* Set up I2C pull levels */
tmp = __raw_readl(LPC32XX_CLKPWR_I2C_CLK_CTRL);
tmp |= LPC32XX_CLKPWR_I2CCLK_USBI2CHI_DRIVE;
__raw_writel(tmp, LPC32XX_CLKPWR_I2C_CLK_CTRL);
}
return local_onoff_enable(clk, enable);
}
static struct clk clk_usbd = {
.parent = &clk_usbpll,
.enable = local_usb_enable,
.enable_reg = LPC32XX_CLKPWR_USB_CTRL,
.enable_mask = LPC32XX_CLKPWR_USBCTRL_HCLK_EN,
.get_rate = local_return_parent_rate,
};
#define OTG_ALWAYS_MASK (LPC32XX_USB_OTG_OTG_CLOCK_ON | \
LPC32XX_USB_OTG_I2C_CLOCK_ON)
static int local_usb_otg_enable(struct clk *clk, int enable)
{
int to = 1000;
if (enable) {
__raw_writel(clk->enable_mask, clk->enable_reg);
while (((__raw_readl(LPC32XX_USB_OTG_CLK_STAT) &
clk->enable_mask) != clk->enable_mask) && (to > 0))
to--;
} else {
__raw_writel(OTG_ALWAYS_MASK, clk->enable_reg);
while (((__raw_readl(LPC32XX_USB_OTG_CLK_STAT) &
OTG_ALWAYS_MASK) != OTG_ALWAYS_MASK) && (to > 0))
to--;
}
if (to)
return 0;
else
return -1;
}
static struct clk clk_usb_otg_dev = {
.parent = &clk_usbpll,
.enable = local_usb_otg_enable,
.enable_reg = LPC32XX_USB_OTG_CLK_CTRL,
.enable_mask = LPC32XX_USB_OTG_AHB_M_CLOCK_ON |
LPC32XX_USB_OTG_OTG_CLOCK_ON |
LPC32XX_USB_OTG_DEV_CLOCK_ON |
LPC32XX_USB_OTG_I2C_CLOCK_ON,
.get_rate = local_return_parent_rate,
};
static struct clk clk_usb_otg_host = {
.parent = &clk_usbpll,
.enable = local_usb_otg_enable,
.enable_reg = LPC32XX_USB_OTG_CLK_CTRL,
.enable_mask = LPC32XX_USB_OTG_AHB_M_CLOCK_ON |
LPC32XX_USB_OTG_OTG_CLOCK_ON |
LPC32XX_USB_OTG_HOST_CLOCK_ON |
LPC32XX_USB_OTG_I2C_CLOCK_ON,
.get_rate = local_return_parent_rate,
};
static int tsc_onoff_enable(struct clk *clk, int enable)
{
u32 tmp;
/* Make sure 32KHz clock is the selected clock */
tmp = __raw_readl(LPC32XX_CLKPWR_ADC_CLK_CTRL_1);
tmp &= ~LPC32XX_CLKPWR_ADCCTRL1_PCLK_SEL;
__raw_writel(tmp, LPC32XX_CLKPWR_ADC_CLK_CTRL_1);
if (enable == 0)
__raw_writel(0, clk->enable_reg);
else
__raw_writel(clk->enable_mask, clk->enable_reg);
return 0;
}
static struct clk clk_tsc = {
.parent = &osc_32KHz,
.enable = tsc_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_ADC_CLK_CTRL,
.enable_mask = LPC32XX_CLKPWR_ADC32CLKCTRL_CLK_EN,
.get_rate = local_return_parent_rate,
};
static int adc_onoff_enable(struct clk *clk, int enable)
{
u32 tmp;
u32 divider;
/* Use PERIPH_CLOCK */
tmp = __raw_readl(LPC32XX_CLKPWR_ADC_CLK_CTRL_1);
tmp |= LPC32XX_CLKPWR_ADCCTRL1_PCLK_SEL;
/*
* Set clock divider so that we have equal to or less than
* 4.5MHz clock at ADC
*/
divider = clk->get_rate(clk) / 4500000 + 1;
tmp |= divider;
__raw_writel(tmp, LPC32XX_CLKPWR_ADC_CLK_CTRL_1);
/* synchronize rate of this clock w/ actual HW setting */
clk->rate = clk->get_rate(clk->parent) / divider;
if (enable == 0)
__raw_writel(0, clk->enable_reg);
else
__raw_writel(clk->enable_mask, clk->enable_reg);
return 0;
}
static struct clk clk_adc = {
.parent = &clk_pclk,
.enable = adc_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_ADC_CLK_CTRL,
.enable_mask = LPC32XX_CLKPWR_ADC32CLKCTRL_CLK_EN,
.get_rate = local_return_parent_rate,
};
static int mmc_onoff_enable(struct clk *clk, int enable)
{
u32 tmp;
tmp = __raw_readl(LPC32XX_CLKPWR_MS_CTRL) &
~(LPC32XX_CLKPWR_MSCARD_SDCARD_EN |
LPC32XX_CLKPWR_MSCARD_MSDIO_PU_EN |
LPC32XX_CLKPWR_MSCARD_MSDIO_PIN_DIS |
LPC32XX_CLKPWR_MSCARD_MSDIO0_DIS |
LPC32XX_CLKPWR_MSCARD_MSDIO1_DIS |
LPC32XX_CLKPWR_MSCARD_MSDIO23_DIS);
/* If rate is 0, disable clock */
if (enable != 0)
tmp |= LPC32XX_CLKPWR_MSCARD_SDCARD_EN |
LPC32XX_CLKPWR_MSCARD_MSDIO_PU_EN;
__raw_writel(tmp, LPC32XX_CLKPWR_MS_CTRL);
return 0;
}
static unsigned long mmc_get_rate(struct clk *clk)
{
u32 div, rate, oldclk;
/* The MMC clock must be on when accessing an MMC register */
oldclk = __raw_readl(LPC32XX_CLKPWR_MS_CTRL);
__raw_writel(oldclk | LPC32XX_CLKPWR_MSCARD_SDCARD_EN,
LPC32XX_CLKPWR_MS_CTRL);
div = __raw_readl(LPC32XX_CLKPWR_MS_CTRL);
__raw_writel(oldclk, LPC32XX_CLKPWR_MS_CTRL);
/* Get the parent clock rate */
rate = clk->parent->get_rate(clk->parent);
/* Get the MMC controller clock divider value */
div = div & LPC32XX_CLKPWR_MSCARD_SDCARD_DIV(0xf);
if (!div)
div = 1;
return rate / div;
}
static unsigned long mmc_round_rate(struct clk *clk, unsigned long rate)
{
unsigned long div, prate;
/* Get the parent clock rate */
prate = clk->parent->get_rate(clk->parent);
if (rate >= prate)
return prate;
div = prate / rate;
if (div > 0xf)
div = 0xf;
return prate / div;
}
static int mmc_set_rate(struct clk *clk, unsigned long rate)
{
u32 tmp;
unsigned long prate, div, crate = mmc_round_rate(clk, rate);
prate = clk->parent->get_rate(clk->parent);
div = prate / crate;
/* The MMC clock must be on when accessing an MMC register */
tmp = __raw_readl(LPC32XX_CLKPWR_MS_CTRL) &
~LPC32XX_CLKPWR_MSCARD_SDCARD_DIV(0xf);
tmp |= LPC32XX_CLKPWR_MSCARD_SDCARD_DIV(div) |
LPC32XX_CLKPWR_MSCARD_SDCARD_EN;
__raw_writel(tmp, LPC32XX_CLKPWR_MS_CTRL);
return 0;
}
static struct clk clk_mmc = {
.parent = &clk_armpll,
.set_rate = mmc_set_rate,
.get_rate = mmc_get_rate,
.round_rate = mmc_round_rate,
.enable = mmc_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_MS_CTRL,
.enable_mask = LPC32XX_CLKPWR_MSCARD_SDCARD_EN,
};
static unsigned long clcd_get_rate(struct clk *clk)
{
u32 tmp, div, rate, oldclk;
/* The LCD clock must be on when accessing an LCD register */
oldclk = __raw_readl(LPC32XX_CLKPWR_LCDCLK_CTRL);
__raw_writel(oldclk | LPC32XX_CLKPWR_LCDCTRL_CLK_EN,
LPC32XX_CLKPWR_LCDCLK_CTRL);
tmp = __raw_readl(io_p2v(LPC32XX_LCD_BASE + CLCD_TIM2));
__raw_writel(oldclk, LPC32XX_CLKPWR_LCDCLK_CTRL);
rate = clk->parent->get_rate(clk->parent);
/* Only supports internal clocking */
if (tmp & TIM2_BCD)
return rate;
div = (tmp & 0x1F) | ((tmp & 0xF8) >> 22);
tmp = rate / (2 + div);
return tmp;
}
static int clcd_set_rate(struct clk *clk, unsigned long rate)
{
u32 tmp, prate, div, oldclk;
/* The LCD clock must be on when accessing an LCD register */
oldclk = __raw_readl(LPC32XX_CLKPWR_LCDCLK_CTRL);
__raw_writel(oldclk | LPC32XX_CLKPWR_LCDCTRL_CLK_EN,
LPC32XX_CLKPWR_LCDCLK_CTRL);
tmp = __raw_readl(io_p2v(LPC32XX_LCD_BASE + CLCD_TIM2)) | TIM2_BCD;
prate = clk->parent->get_rate(clk->parent);
if (rate < prate) {
/* Find closest divider */
div = prate / rate;
if (div >= 2) {
div -= 2;
tmp &= ~TIM2_BCD;
}
tmp &= ~(0xF800001F);
tmp |= (div & 0x1F);
tmp |= (((div >> 5) & 0x1F) << 27);
}
__raw_writel(tmp, io_p2v(LPC32XX_LCD_BASE + CLCD_TIM2));
__raw_writel(oldclk, LPC32XX_CLKPWR_LCDCLK_CTRL);
return 0;
}
static unsigned long clcd_round_rate(struct clk *clk, unsigned long rate)
{
u32 prate, div;
prate = clk->parent->get_rate(clk->parent);
if (rate >= prate)
rate = prate;
else {
div = prate / rate;
if (div > 0x3ff)
div = 0x3ff;
rate = prate / div;
}
return rate;
}
static struct clk clk_lcd = {
.parent = &clk_hclk,
.set_rate = clcd_set_rate,
.get_rate = clcd_get_rate,
.round_rate = clcd_round_rate,
.enable = local_onoff_enable,
.enable_reg = LPC32XX_CLKPWR_LCDCLK_CTRL,
.enable_mask = LPC32XX_CLKPWR_LCDCTRL_CLK_EN,
};
static void local_clk_disable(struct clk *clk)
{
/* Don't attempt to disable clock if it has no users */
if (clk->usecount > 0) {
clk->usecount--;
/* Only disable clock when it has no more users */
if ((clk->usecount == 0) && (clk->enable))
clk->enable(clk, 0);
/* Check parent clocks, they may need to be disabled too */
if (clk->parent)
local_clk_disable(clk->parent);
}
}
static int local_clk_enable(struct clk *clk)
{
int ret = 0;
/* Enable parent clocks first and update use counts */
if (clk->parent)
ret = local_clk_enable(clk->parent);
if (!ret) {
/* Only enable clock if it's currently disabled */
if ((clk->usecount == 0) && (clk->enable))
ret = clk->enable(clk, 1);
if (!ret)
clk->usecount++;
else if (clk->parent)
local_clk_disable(clk->parent);
}
return ret;
}
/*
* clk_enable - inform the system when the clock source should be running.
*/
int clk_enable(struct clk *clk)
{
int ret;
unsigned long flags;
spin_lock_irqsave(&global_clkregs_lock, flags);
ret = local_clk_enable(clk);
spin_unlock_irqrestore(&global_clkregs_lock, flags);
return ret;
}
EXPORT_SYMBOL(clk_enable);
/*
* clk_disable - inform the system when the clock source is no longer required
*/
void clk_disable(struct clk *clk)
{
unsigned long flags;
spin_lock_irqsave(&global_clkregs_lock, flags);
local_clk_disable(clk);
spin_unlock_irqrestore(&global_clkregs_lock, flags);
}
EXPORT_SYMBOL(clk_disable);
/*
* clk_get_rate - obtain the current clock rate (in Hz) for a clock source
*/
unsigned long clk_get_rate(struct clk *clk)
{
return clk->get_rate(clk);
}
EXPORT_SYMBOL(clk_get_rate);
/*
* clk_set_rate - set the clock rate for a clock source
*/
int clk_set_rate(struct clk *clk, unsigned long rate)
{
int ret = -EINVAL;
/*
* Most system clocks can only be enabled or disabled, with
* the actual rate set as part of the peripheral dividers
* instead of high level clock control
*/
if (clk->set_rate)
ret = clk->set_rate(clk, rate);
return ret;
}
EXPORT_SYMBOL(clk_set_rate);
/*
* clk_round_rate - adjust a rate to the exact rate a clock can provide
*/
long clk_round_rate(struct clk *clk, unsigned long rate)
{
if (clk->round_rate)
rate = clk->round_rate(clk, rate);
else
rate = clk->get_rate(clk);
return rate;
}
EXPORT_SYMBOL(clk_round_rate);
/*
* clk_set_parent - set the parent clock source for this clock
*/
int clk_set_parent(struct clk *clk, struct clk *parent)
{
/* Clock re-parenting is not supported */
return -EINVAL;
}
EXPORT_SYMBOL(clk_set_parent);
/*
* clk_get_parent - get the parent clock source for this clock
*/
struct clk *clk_get_parent(struct clk *clk)
{
return clk->parent;
}
EXPORT_SYMBOL(clk_get_parent);
static struct clk_lookup lookups[] = {
CLKDEV_INIT(NULL, "osc_32KHz", &osc_32KHz),
CLKDEV_INIT(NULL, "osc_pll397", &osc_pll397),
CLKDEV_INIT(NULL, "osc_main", &osc_main),
CLKDEV_INIT(NULL, "sys_ck", &clk_sys),
CLKDEV_INIT(NULL, "arm_pll_ck", &clk_armpll),
CLKDEV_INIT(NULL, "ck_pll5", &clk_usbpll),
CLKDEV_INIT(NULL, "hclk_ck", &clk_hclk),
CLKDEV_INIT(NULL, "pclk_ck", &clk_pclk),
CLKDEV_INIT(NULL, "timer0_ck", &clk_timer0),
CLKDEV_INIT(NULL, "timer1_ck", &clk_timer1),
CLKDEV_INIT(NULL, "timer2_ck", &clk_timer2),
CLKDEV_INIT(NULL, "timer3_ck", &clk_timer3),
CLKDEV_INIT(NULL, "vfp9_ck", &clk_vfp9),
CLKDEV_INIT("pl08xdmac", NULL, &clk_dma),
CLKDEV_INIT("4003c000.watchdog", NULL, &clk_wdt),
CLKDEV_INIT("4005c000.pwm", NULL, &clk_pwm),
CLKDEV_INIT("400e8000.mpwm", NULL, &clk_mpwm),
CLKDEV_INIT(NULL, "uart3_ck", &clk_uart3),
CLKDEV_INIT(NULL, "uart4_ck", &clk_uart4),
CLKDEV_INIT(NULL, "uart5_ck", &clk_uart5),
CLKDEV_INIT(NULL, "uart6_ck", &clk_uart6),
CLKDEV_INIT("400a0000.i2c", NULL, &clk_i2c0),
CLKDEV_INIT("400a8000.i2c", NULL, &clk_i2c1),
CLKDEV_INIT("31020300.i2c", NULL, &clk_i2c2),
CLKDEV_INIT("dev:ssp0", NULL, &clk_ssp0),
CLKDEV_INIT("dev:ssp1", NULL, &clk_ssp1),
CLKDEV_INIT("40050000.key", NULL, &clk_kscan),
CLKDEV_INIT("20020000.flash", NULL, &clk_nand),
CLKDEV_INIT("200a8000.flash", NULL, &clk_nand_mlc),
CLKDEV_INIT("40048000.adc", NULL, &clk_adc),
CLKDEV_INIT(NULL, "i2s0_ck", &clk_i2s0),
CLKDEV_INIT(NULL, "i2s1_ck", &clk_i2s1),
CLKDEV_INIT("40048000.tsc", NULL, &clk_tsc),
CLKDEV_INIT("20098000.sd", NULL, &clk_mmc),
CLKDEV_INIT("31060000.ethernet", NULL, &clk_net),
CLKDEV_INIT("dev:clcd", NULL, &clk_lcd),
CLKDEV_INIT("31020000.usbd", "ck_usbd", &clk_usbd),
CLKDEV_INIT("31020000.ohci", "ck_usbd", &clk_usbd),
CLKDEV_INIT("31020000.usbd", "ck_usb_otg", &clk_usb_otg_dev),
CLKDEV_INIT("31020000.ohci", "ck_usb_otg", &clk_usb_otg_host),
CLKDEV_INIT("lpc32xx_rtc", NULL, &clk_rtc),
};
static int __init clk_init(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(lookups); i++)
clkdev_add(&lookups[i]);
/*
* Setup muxed SYSCLK for HCLK PLL base -this selects the
* parent clock used for the ARM PLL and is used to derive
* the many system clock rates in the device.
*/
if (clk_is_sysclk_mainosc() != 0)
clk_sys.parent = &osc_main;
else
clk_sys.parent = &osc_pll397;
clk_sys.rate = clk_sys.parent->rate;
/* Compute the current ARM PLL and USB PLL frequencies */
local_update_armpll_rate();
/* Compute HCLK and PCLK bus rates */
clk_hclk.rate = clk_hclk.parent->rate / clk_get_hclk_div();
clk_pclk.rate = clk_pclk.parent->rate / clk_get_pclk_div();
/*
* Enable system clocks - this step is somewhat formal, as the
* clocks are already running, but it does get the clock data
* inline with the actual system state. Never disable these
* clocks as they will only stop if the system is going to sleep.
* In that case, the chip/system power management functions will
* handle clock gating.
*/
if (clk_enable(&clk_hclk) || clk_enable(&clk_pclk))
printk(KERN_ERR "Error enabling system HCLK and PCLK\n");
/*
* Timers 0 and 1 were enabled and are being used by the high
* resolution tick function prior to this driver being initialized.
* Tag them now as used.
*/
if (clk_enable(&clk_timer0) || clk_enable(&clk_timer1))
printk(KERN_ERR "Error enabling timer tick clocks\n");
return 0;
}
core_initcall(clk_init);
| gpl-2.0 |
holyangel/HTC_M8_GPE-4.4.4 | drivers/acpi/acpica/nswalk.c | 4919 | 11303 | /******************************************************************************
*
* Module Name: nswalk - Functions for walking the ACPI namespace
*
*****************************************************************************/
/*
* Copyright (C) 2000 - 2012, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#include "acnamesp.h"
#define _COMPONENT ACPI_NAMESPACE
ACPI_MODULE_NAME("nswalk")
/*******************************************************************************
*
* FUNCTION: acpi_ns_get_next_node
*
* PARAMETERS: parent_node - Parent node whose children we are
* getting
* child_node - Previous child that was found.
* The NEXT child will be returned
*
* RETURN: struct acpi_namespace_node - Pointer to the NEXT child or NULL if
* none is found.
*
* DESCRIPTION: Return the next peer node within the namespace. If Handle
* is valid, Scope is ignored. Otherwise, the first node
* within Scope is returned.
*
******************************************************************************/
struct acpi_namespace_node *acpi_ns_get_next_node(struct acpi_namespace_node
*parent_node,
struct acpi_namespace_node
*child_node)
{
ACPI_FUNCTION_ENTRY();
if (!child_node) {
/* It's really the parent's _scope_ that we want */
return parent_node->child;
}
/* Otherwise just return the next peer */
return child_node->peer;
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_get_next_node_typed
*
* PARAMETERS: Type - Type of node to be searched for
* parent_node - Parent node whose children we are
* getting
* child_node - Previous child that was found.
* The NEXT child will be returned
*
* RETURN: struct acpi_namespace_node - Pointer to the NEXT child or NULL if
* none is found.
*
* DESCRIPTION: Return the next peer node within the namespace. If Handle
* is valid, Scope is ignored. Otherwise, the first node
* within Scope is returned.
*
******************************************************************************/
struct acpi_namespace_node *acpi_ns_get_next_node_typed(acpi_object_type type,
struct
acpi_namespace_node
*parent_node,
struct
acpi_namespace_node
*child_node)
{
struct acpi_namespace_node *next_node = NULL;
ACPI_FUNCTION_ENTRY();
next_node = acpi_ns_get_next_node(parent_node, child_node);
/* If any type is OK, we are done */
if (type == ACPI_TYPE_ANY) {
/* next_node is NULL if we are at the end-of-list */
return (next_node);
}
/* Must search for the node -- but within this scope only */
while (next_node) {
/* If type matches, we are done */
if (next_node->type == type) {
return (next_node);
}
/* Otherwise, move on to the next peer node */
next_node = next_node->peer;
}
/* Not found */
return (NULL);
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_walk_namespace
*
* PARAMETERS: Type - acpi_object_type to search for
* start_node - Handle in namespace where search begins
* max_depth - Depth to which search is to reach
* Flags - Whether to unlock the NS before invoking
* the callback routine
* pre_order_visit - Called during tree pre-order visit
* when an object of "Type" is found
* post_order_visit - Called during tree post-order visit
* when an object of "Type" is found
* Context - Passed to user function(s) above
* return_value - from the user_function if terminated
* early. Otherwise, returns NULL.
* RETURNS: Status
*
* DESCRIPTION: Performs a modified depth-first walk of the namespace tree,
* starting (and ending) at the node specified by start_handle.
* The callback function is called whenever a node that matches
* the type parameter is found. If the callback function returns
* a non-zero value, the search is terminated immediately and
* this value is returned to the caller.
*
* The point of this procedure is to provide a generic namespace
* walk routine that can be called from multiple places to
* provide multiple services; the callback function(s) can be
* tailored to each task, whether it is a print function,
* a compare function, etc.
*
******************************************************************************/
acpi_status
acpi_ns_walk_namespace(acpi_object_type type,
acpi_handle start_node,
u32 max_depth,
u32 flags,
acpi_walk_callback pre_order_visit,
acpi_walk_callback post_order_visit,
void *context, void **return_value)
{
acpi_status status;
acpi_status mutex_status;
struct acpi_namespace_node *child_node;
struct acpi_namespace_node *parent_node;
acpi_object_type child_type;
u32 level;
u8 node_previously_visited = FALSE;
ACPI_FUNCTION_TRACE(ns_walk_namespace);
/* Special case for the namespace Root Node */
if (start_node == ACPI_ROOT_OBJECT) {
start_node = acpi_gbl_root_node;
}
/* Null child means "get first node" */
parent_node = start_node;
child_node = acpi_ns_get_next_node(parent_node, NULL);
child_type = ACPI_TYPE_ANY;
level = 1;
/*
* Traverse the tree of nodes until we bubble back up to where we
* started. When Level is zero, the loop is done because we have
* bubbled up to (and passed) the original parent handle (start_entry)
*/
while (level > 0 && child_node) {
status = AE_OK;
/* Found next child, get the type if we are not searching for ANY */
if (type != ACPI_TYPE_ANY) {
child_type = child_node->type;
}
/*
* Ignore all temporary namespace nodes (created during control
* method execution) unless told otherwise. These temporary nodes
* can cause a race condition because they can be deleted during
* the execution of the user function (if the namespace is
* unlocked before invocation of the user function.) Only the
* debugger namespace dump will examine the temporary nodes.
*/
if ((child_node->flags & ANOBJ_TEMPORARY) &&
!(flags & ACPI_NS_WALK_TEMP_NODES)) {
status = AE_CTRL_DEPTH;
}
/* Type must match requested type */
else if (child_type == type) {
/*
* Found a matching node, invoke the user callback function.
* Unlock the namespace if flag is set.
*/
if (flags & ACPI_NS_WALK_UNLOCK) {
mutex_status =
acpi_ut_release_mutex(ACPI_MTX_NAMESPACE);
if (ACPI_FAILURE(mutex_status)) {
return_ACPI_STATUS(mutex_status);
}
}
/*
* Invoke the user function, either pre-order or post-order
* or both.
*/
if (!node_previously_visited) {
if (pre_order_visit) {
status =
pre_order_visit(child_node, level,
context,
return_value);
}
} else {
if (post_order_visit) {
status =
post_order_visit(child_node, level,
context,
return_value);
}
}
if (flags & ACPI_NS_WALK_UNLOCK) {
mutex_status =
acpi_ut_acquire_mutex(ACPI_MTX_NAMESPACE);
if (ACPI_FAILURE(mutex_status)) {
return_ACPI_STATUS(mutex_status);
}
}
switch (status) {
case AE_OK:
case AE_CTRL_DEPTH:
/* Just keep going */
break;
case AE_CTRL_TERMINATE:
/* Exit now, with OK status */
return_ACPI_STATUS(AE_OK);
default:
/* All others are valid exceptions */
return_ACPI_STATUS(status);
}
}
/*
* Depth first search: Attempt to go down another level in the
* namespace if we are allowed to. Don't go any further if we have
* reached the caller specified maximum depth or if the user
* function has specified that the maximum depth has been reached.
*/
if (!node_previously_visited &&
(level < max_depth) && (status != AE_CTRL_DEPTH)) {
if (child_node->child) {
/* There is at least one child of this node, visit it */
level++;
parent_node = child_node;
child_node =
acpi_ns_get_next_node(parent_node, NULL);
continue;
}
}
/* No more children, re-visit this node */
if (!node_previously_visited) {
node_previously_visited = TRUE;
continue;
}
/* No more children, visit peers */
child_node = acpi_ns_get_next_node(parent_node, child_node);
if (child_node) {
node_previously_visited = FALSE;
}
/* No peers, re-visit parent */
else {
/*
* No more children of this node (acpi_ns_get_next_node failed), go
* back upwards in the namespace tree to the node's parent.
*/
level--;
child_node = parent_node;
parent_node = parent_node->parent;
node_previously_visited = TRUE;
}
}
/* Complete walk, not terminated by user function */
return_ACPI_STATUS(AE_OK);
}
| gpl-2.0 |
z8cpaul/lsikernel-3.4 | drivers/acpi/acpica/psargs.c | 4919 | 22270 | /******************************************************************************
*
* Module Name: psargs - Parse AML opcode arguments
*
*****************************************************************************/
/*
* Copyright (C) 2000 - 2012, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#include "acparser.h"
#include "amlcode.h"
#include "acnamesp.h"
#include "acdispat.h"
#define _COMPONENT ACPI_PARSER
ACPI_MODULE_NAME("psargs")
/* Local prototypes */
static u32
acpi_ps_get_next_package_length(struct acpi_parse_state *parser_state);
static union acpi_parse_object *acpi_ps_get_next_field(struct acpi_parse_state
*parser_state);
/*******************************************************************************
*
* FUNCTION: acpi_ps_get_next_package_length
*
* PARAMETERS: parser_state - Current parser state object
*
* RETURN: Decoded package length. On completion, the AML pointer points
* past the length byte or bytes.
*
* DESCRIPTION: Decode and return a package length field.
* Note: Largest package length is 28 bits, from ACPI specification
*
******************************************************************************/
static u32
acpi_ps_get_next_package_length(struct acpi_parse_state *parser_state)
{
u8 *aml = parser_state->aml;
u32 package_length = 0;
u32 byte_count;
u8 byte_zero_mask = 0x3F; /* Default [0:5] */
ACPI_FUNCTION_TRACE(ps_get_next_package_length);
/*
* Byte 0 bits [6:7] contain the number of additional bytes
* used to encode the package length, either 0,1,2, or 3
*/
byte_count = (aml[0] >> 6);
parser_state->aml += ((acpi_size) byte_count + 1);
/* Get bytes 3, 2, 1 as needed */
while (byte_count) {
/*
* Final bit positions for the package length bytes:
* Byte3->[20:27]
* Byte2->[12:19]
* Byte1->[04:11]
* Byte0->[00:03]
*/
package_length |= (aml[byte_count] << ((byte_count << 3) - 4));
byte_zero_mask = 0x0F; /* Use bits [0:3] of byte 0 */
byte_count--;
}
/* Byte 0 is a special case, either bits [0:3] or [0:5] are used */
package_length |= (aml[0] & byte_zero_mask);
return_UINT32(package_length);
}
/*******************************************************************************
*
* FUNCTION: acpi_ps_get_next_package_end
*
* PARAMETERS: parser_state - Current parser state object
*
* RETURN: Pointer to end-of-package +1
*
* DESCRIPTION: Get next package length and return a pointer past the end of
* the package. Consumes the package length field
*
******************************************************************************/
u8 *acpi_ps_get_next_package_end(struct acpi_parse_state *parser_state)
{
u8 *start = parser_state->aml;
u32 package_length;
ACPI_FUNCTION_TRACE(ps_get_next_package_end);
/* Function below updates parser_state->Aml */
package_length = acpi_ps_get_next_package_length(parser_state);
return_PTR(start + package_length); /* end of package */
}
/*******************************************************************************
*
* FUNCTION: acpi_ps_get_next_namestring
*
* PARAMETERS: parser_state - Current parser state object
*
* RETURN: Pointer to the start of the name string (pointer points into
* the AML.
*
* DESCRIPTION: Get next raw namestring within the AML stream. Handles all name
* prefix characters. Set parser state to point past the string.
* (Name is consumed from the AML.)
*
******************************************************************************/
char *acpi_ps_get_next_namestring(struct acpi_parse_state *parser_state)
{
u8 *start = parser_state->aml;
u8 *end = parser_state->aml;
ACPI_FUNCTION_TRACE(ps_get_next_namestring);
/* Point past any namestring prefix characters (backslash or carat) */
while (acpi_ps_is_prefix_char(*end)) {
end++;
}
/* Decode the path prefix character */
switch (*end) {
case 0:
/* null_name */
if (end == start) {
start = NULL;
}
end++;
break;
case AML_DUAL_NAME_PREFIX:
/* Two name segments */
end += 1 + (2 * ACPI_NAME_SIZE);
break;
case AML_MULTI_NAME_PREFIX_OP:
/* Multiple name segments, 4 chars each, count in next byte */
end += 2 + (*(end + 1) * ACPI_NAME_SIZE);
break;
default:
/* Single name segment */
end += ACPI_NAME_SIZE;
break;
}
parser_state->aml = end;
return_PTR((char *)start);
}
/*******************************************************************************
*
* FUNCTION: acpi_ps_get_next_namepath
*
* PARAMETERS: parser_state - Current parser state object
* Arg - Where the namepath will be stored
* arg_count - If the namepath points to a control method
* the method's argument is returned here.
* possible_method_call - Whether the namepath can possibly be the
* start of a method call
*
* RETURN: Status
*
* DESCRIPTION: Get next name (if method call, return # of required args).
* Names are looked up in the internal namespace to determine
* if the name represents a control method. If a method
* is found, the number of arguments to the method is returned.
* This information is critical for parsing to continue correctly.
*
******************************************************************************/
acpi_status
acpi_ps_get_next_namepath(struct acpi_walk_state *walk_state,
struct acpi_parse_state *parser_state,
union acpi_parse_object *arg, u8 possible_method_call)
{
acpi_status status;
char *path;
union acpi_parse_object *name_op;
union acpi_operand_object *method_desc;
struct acpi_namespace_node *node;
u8 *start = parser_state->aml;
ACPI_FUNCTION_TRACE(ps_get_next_namepath);
path = acpi_ps_get_next_namestring(parser_state);
acpi_ps_init_op(arg, AML_INT_NAMEPATH_OP);
/* Null path case is allowed, just exit */
if (!path) {
arg->common.value.name = path;
return_ACPI_STATUS(AE_OK);
}
/*
* Lookup the name in the internal namespace, starting with the current
* scope. We don't want to add anything new to the namespace here,
* however, so we use MODE_EXECUTE.
* Allow searching of the parent tree, but don't open a new scope -
* we just want to lookup the object (must be mode EXECUTE to perform
* the upsearch)
*/
status = acpi_ns_lookup(walk_state->scope_info, path,
ACPI_TYPE_ANY, ACPI_IMODE_EXECUTE,
ACPI_NS_SEARCH_PARENT | ACPI_NS_DONT_OPEN_SCOPE,
NULL, &node);
/*
* If this name is a control method invocation, we must
* setup the method call
*/
if (ACPI_SUCCESS(status) &&
possible_method_call && (node->type == ACPI_TYPE_METHOD)) {
if (walk_state->opcode == AML_UNLOAD_OP) {
/*
* acpi_ps_get_next_namestring has increased the AML pointer,
* so we need to restore the saved AML pointer for method call.
*/
walk_state->parser_state.aml = start;
walk_state->arg_count = 1;
acpi_ps_init_op(arg, AML_INT_METHODCALL_OP);
return_ACPI_STATUS(AE_OK);
}
/* This name is actually a control method invocation */
method_desc = acpi_ns_get_attached_object(node);
ACPI_DEBUG_PRINT((ACPI_DB_PARSE,
"Control Method - %p Desc %p Path=%p\n", node,
method_desc, path));
name_op = acpi_ps_alloc_op(AML_INT_NAMEPATH_OP);
if (!name_op) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
/* Change Arg into a METHOD CALL and attach name to it */
acpi_ps_init_op(arg, AML_INT_METHODCALL_OP);
name_op->common.value.name = path;
/* Point METHODCALL/NAME to the METHOD Node */
name_op->common.node = node;
acpi_ps_append_arg(arg, name_op);
if (!method_desc) {
ACPI_ERROR((AE_INFO,
"Control Method %p has no attached object",
node));
return_ACPI_STATUS(AE_AML_INTERNAL);
}
ACPI_DEBUG_PRINT((ACPI_DB_PARSE,
"Control Method - %p Args %X\n",
node, method_desc->method.param_count));
/* Get the number of arguments to expect */
walk_state->arg_count = method_desc->method.param_count;
return_ACPI_STATUS(AE_OK);
}
/*
* Special handling if the name was not found during the lookup -
* some not_found cases are allowed
*/
if (status == AE_NOT_FOUND) {
/* 1) not_found is ok during load pass 1/2 (allow forward references) */
if ((walk_state->parse_flags & ACPI_PARSE_MODE_MASK) !=
ACPI_PARSE_EXECUTE) {
status = AE_OK;
}
/* 2) not_found during a cond_ref_of(x) is ok by definition */
else if (walk_state->op->common.aml_opcode ==
AML_COND_REF_OF_OP) {
status = AE_OK;
}
/*
* 3) not_found while building a Package is ok at this point, we
* may flag as an error later if slack mode is not enabled.
* (Some ASL code depends on allowing this behavior)
*/
else if ((arg->common.parent) &&
((arg->common.parent->common.aml_opcode ==
AML_PACKAGE_OP)
|| (arg->common.parent->common.aml_opcode ==
AML_VAR_PACKAGE_OP))) {
status = AE_OK;
}
}
/* Final exception check (may have been changed from code above) */
if (ACPI_FAILURE(status)) {
ACPI_ERROR_NAMESPACE(path, status);
if ((walk_state->parse_flags & ACPI_PARSE_MODE_MASK) ==
ACPI_PARSE_EXECUTE) {
/* Report a control method execution error */
status = acpi_ds_method_error(status, walk_state);
}
}
/* Save the namepath */
arg->common.value.name = path;
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ps_get_next_simple_arg
*
* PARAMETERS: parser_state - Current parser state object
* arg_type - The argument type (AML_*_ARG)
* Arg - Where the argument is returned
*
* RETURN: None
*
* DESCRIPTION: Get the next simple argument (constant, string, or namestring)
*
******************************************************************************/
void
acpi_ps_get_next_simple_arg(struct acpi_parse_state *parser_state,
u32 arg_type, union acpi_parse_object *arg)
{
u32 length;
u16 opcode;
u8 *aml = parser_state->aml;
ACPI_FUNCTION_TRACE_U32(ps_get_next_simple_arg, arg_type);
switch (arg_type) {
case ARGP_BYTEDATA:
/* Get 1 byte from the AML stream */
opcode = AML_BYTE_OP;
arg->common.value.integer = (u64) *aml;
length = 1;
break;
case ARGP_WORDDATA:
/* Get 2 bytes from the AML stream */
opcode = AML_WORD_OP;
ACPI_MOVE_16_TO_64(&arg->common.value.integer, aml);
length = 2;
break;
case ARGP_DWORDDATA:
/* Get 4 bytes from the AML stream */
opcode = AML_DWORD_OP;
ACPI_MOVE_32_TO_64(&arg->common.value.integer, aml);
length = 4;
break;
case ARGP_QWORDDATA:
/* Get 8 bytes from the AML stream */
opcode = AML_QWORD_OP;
ACPI_MOVE_64_TO_64(&arg->common.value.integer, aml);
length = 8;
break;
case ARGP_CHARLIST:
/* Get a pointer to the string, point past the string */
opcode = AML_STRING_OP;
arg->common.value.string = ACPI_CAST_PTR(char, aml);
/* Find the null terminator */
length = 0;
while (aml[length]) {
length++;
}
length++;
break;
case ARGP_NAME:
case ARGP_NAMESTRING:
acpi_ps_init_op(arg, AML_INT_NAMEPATH_OP);
arg->common.value.name =
acpi_ps_get_next_namestring(parser_state);
return_VOID;
default:
ACPI_ERROR((AE_INFO, "Invalid ArgType 0x%X", arg_type));
return_VOID;
}
acpi_ps_init_op(arg, opcode);
parser_state->aml += length;
return_VOID;
}
/*******************************************************************************
*
* FUNCTION: acpi_ps_get_next_field
*
* PARAMETERS: parser_state - Current parser state object
*
* RETURN: A newly allocated FIELD op
*
* DESCRIPTION: Get next field (named_field, reserved_field, or access_field)
*
******************************************************************************/
static union acpi_parse_object *acpi_ps_get_next_field(struct acpi_parse_state
*parser_state)
{
u32 aml_offset;
union acpi_parse_object *field;
union acpi_parse_object *arg = NULL;
u16 opcode;
u32 name;
u8 access_type;
u8 access_attribute;
u8 access_length;
u32 pkg_length;
u8 *pkg_end;
u32 buffer_length;
ACPI_FUNCTION_TRACE(ps_get_next_field);
aml_offset =
(u32)ACPI_PTR_DIFF(parser_state->aml, parser_state->aml_start);
/* Determine field type */
switch (ACPI_GET8(parser_state->aml)) {
case AML_FIELD_OFFSET_OP:
opcode = AML_INT_RESERVEDFIELD_OP;
parser_state->aml++;
break;
case AML_FIELD_ACCESS_OP:
opcode = AML_INT_ACCESSFIELD_OP;
parser_state->aml++;
break;
case AML_FIELD_CONNECTION_OP:
opcode = AML_INT_CONNECTION_OP;
parser_state->aml++;
break;
case AML_FIELD_EXT_ACCESS_OP:
opcode = AML_INT_EXTACCESSFIELD_OP;
parser_state->aml++;
break;
default:
opcode = AML_INT_NAMEDFIELD_OP;
break;
}
/* Allocate a new field op */
field = acpi_ps_alloc_op(opcode);
if (!field) {
return_PTR(NULL);
}
field->common.aml_offset = aml_offset;
/* Decode the field type */
switch (opcode) {
case AML_INT_NAMEDFIELD_OP:
/* Get the 4-character name */
ACPI_MOVE_32_TO_32(&name, parser_state->aml);
acpi_ps_set_name(field, name);
parser_state->aml += ACPI_NAME_SIZE;
/* Get the length which is encoded as a package length */
field->common.value.size =
acpi_ps_get_next_package_length(parser_state);
break;
case AML_INT_RESERVEDFIELD_OP:
/* Get the length which is encoded as a package length */
field->common.value.size =
acpi_ps_get_next_package_length(parser_state);
break;
case AML_INT_ACCESSFIELD_OP:
case AML_INT_EXTACCESSFIELD_OP:
/*
* Get access_type and access_attrib and merge into the field Op
* access_type is first operand, access_attribute is second. stuff
* these bytes into the node integer value for convenience.
*/
/* Get the two bytes (Type/Attribute) */
access_type = ACPI_GET8(parser_state->aml);
parser_state->aml++;
access_attribute = ACPI_GET8(parser_state->aml);
parser_state->aml++;
field->common.value.integer = (u8)access_type;
field->common.value.integer |= (u16)(access_attribute << 8);
/* This opcode has a third byte, access_length */
if (opcode == AML_INT_EXTACCESSFIELD_OP) {
access_length = ACPI_GET8(parser_state->aml);
parser_state->aml++;
field->common.value.integer |=
(u32)(access_length << 16);
}
break;
case AML_INT_CONNECTION_OP:
/*
* Argument for Connection operator can be either a Buffer
* (resource descriptor), or a name_string.
*/
if (ACPI_GET8(parser_state->aml) == AML_BUFFER_OP) {
parser_state->aml++;
pkg_end = parser_state->aml;
pkg_length =
acpi_ps_get_next_package_length(parser_state);
pkg_end += pkg_length;
if (parser_state->aml < pkg_end) {
/* Non-empty list */
arg = acpi_ps_alloc_op(AML_INT_BYTELIST_OP);
if (!arg) {
return_PTR(NULL);
}
/* Get the actual buffer length argument */
opcode = ACPI_GET8(parser_state->aml);
parser_state->aml++;
switch (opcode) {
case AML_BYTE_OP: /* AML_BYTEDATA_ARG */
buffer_length =
ACPI_GET8(parser_state->aml);
parser_state->aml += 1;
break;
case AML_WORD_OP: /* AML_WORDDATA_ARG */
buffer_length =
ACPI_GET16(parser_state->aml);
parser_state->aml += 2;
break;
case AML_DWORD_OP: /* AML_DWORDATA_ARG */
buffer_length =
ACPI_GET32(parser_state->aml);
parser_state->aml += 4;
break;
default:
buffer_length = 0;
break;
}
/* Fill in bytelist data */
arg->named.value.size = buffer_length;
arg->named.data = parser_state->aml;
}
/* Skip to End of byte data */
parser_state->aml = pkg_end;
} else {
arg = acpi_ps_alloc_op(AML_INT_NAMEPATH_OP);
if (!arg) {
return_PTR(NULL);
}
/* Get the Namestring argument */
arg->common.value.name =
acpi_ps_get_next_namestring(parser_state);
}
/* Link the buffer/namestring to parent (CONNECTION_OP) */
acpi_ps_append_arg(field, arg);
break;
default:
/* Opcode was set in previous switch */
break;
}
return_PTR(field);
}
/*******************************************************************************
*
* FUNCTION: acpi_ps_get_next_arg
*
* PARAMETERS: walk_state - Current state
* parser_state - Current parser state object
* arg_type - The argument type (AML_*_ARG)
* return_arg - Where the next arg is returned
*
* RETURN: Status, and an op object containing the next argument.
*
* DESCRIPTION: Get next argument (including complex list arguments that require
* pushing the parser stack)
*
******************************************************************************/
acpi_status
acpi_ps_get_next_arg(struct acpi_walk_state *walk_state,
struct acpi_parse_state *parser_state,
u32 arg_type, union acpi_parse_object **return_arg)
{
union acpi_parse_object *arg = NULL;
union acpi_parse_object *prev = NULL;
union acpi_parse_object *field;
u32 subop;
acpi_status status = AE_OK;
ACPI_FUNCTION_TRACE_PTR(ps_get_next_arg, parser_state);
switch (arg_type) {
case ARGP_BYTEDATA:
case ARGP_WORDDATA:
case ARGP_DWORDDATA:
case ARGP_CHARLIST:
case ARGP_NAME:
case ARGP_NAMESTRING:
/* Constants, strings, and namestrings are all the same size */
arg = acpi_ps_alloc_op(AML_BYTE_OP);
if (!arg) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
acpi_ps_get_next_simple_arg(parser_state, arg_type, arg);
break;
case ARGP_PKGLENGTH:
/* Package length, nothing returned */
parser_state->pkg_end =
acpi_ps_get_next_package_end(parser_state);
break;
case ARGP_FIELDLIST:
if (parser_state->aml < parser_state->pkg_end) {
/* Non-empty list */
while (parser_state->aml < parser_state->pkg_end) {
field = acpi_ps_get_next_field(parser_state);
if (!field) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
if (prev) {
prev->common.next = field;
} else {
arg = field;
}
prev = field;
}
/* Skip to End of byte data */
parser_state->aml = parser_state->pkg_end;
}
break;
case ARGP_BYTELIST:
if (parser_state->aml < parser_state->pkg_end) {
/* Non-empty list */
arg = acpi_ps_alloc_op(AML_INT_BYTELIST_OP);
if (!arg) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
/* Fill in bytelist data */
arg->common.value.size = (u32)
ACPI_PTR_DIFF(parser_state->pkg_end,
parser_state->aml);
arg->named.data = parser_state->aml;
/* Skip to End of byte data */
parser_state->aml = parser_state->pkg_end;
}
break;
case ARGP_TARGET:
case ARGP_SUPERNAME:
case ARGP_SIMPLENAME:
subop = acpi_ps_peek_opcode(parser_state);
if (subop == 0 ||
acpi_ps_is_leading_char(subop) ||
acpi_ps_is_prefix_char(subop)) {
/* null_name or name_string */
arg = acpi_ps_alloc_op(AML_INT_NAMEPATH_OP);
if (!arg) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
/* To support super_name arg of Unload */
if (walk_state->opcode == AML_UNLOAD_OP) {
status =
acpi_ps_get_next_namepath(walk_state,
parser_state, arg,
1);
/*
* If the super_name arg of Unload is a method call,
* we have restored the AML pointer, just free this Arg
*/
if (arg->common.aml_opcode ==
AML_INT_METHODCALL_OP) {
acpi_ps_free_op(arg);
arg = NULL;
}
} else {
status =
acpi_ps_get_next_namepath(walk_state,
parser_state, arg,
0);
}
} else {
/* Single complex argument, nothing returned */
walk_state->arg_count = 1;
}
break;
case ARGP_DATAOBJ:
case ARGP_TERMARG:
/* Single complex argument, nothing returned */
walk_state->arg_count = 1;
break;
case ARGP_DATAOBJLIST:
case ARGP_TERMLIST:
case ARGP_OBJLIST:
if (parser_state->aml < parser_state->pkg_end) {
/* Non-empty list of variable arguments, nothing returned */
walk_state->arg_count = ACPI_VAR_ARGS;
}
break;
default:
ACPI_ERROR((AE_INFO, "Invalid ArgType: 0x%X", arg_type));
status = AE_AML_OPERAND_TYPE;
break;
}
*return_arg = arg;
return_ACPI_STATUS(status);
}
| gpl-2.0 |
revjunkie/lge-g2-d802 | drivers/acpi/acpica/nsrepair2.c | 4919 | 24376 | /******************************************************************************
*
* Module Name: nsrepair2 - Repair for objects returned by specific
* predefined methods
*
*****************************************************************************/
/*
* Copyright (C) 2000 - 2012, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#include "acnamesp.h"
#define _COMPONENT ACPI_NAMESPACE
ACPI_MODULE_NAME("nsrepair2")
/*
* Information structure and handler for ACPI predefined names that can
* be repaired on a per-name basis.
*/
typedef
acpi_status(*acpi_repair_function) (struct acpi_predefined_data *data,
union acpi_operand_object **return_object_ptr);
typedef struct acpi_repair_info {
char name[ACPI_NAME_SIZE];
acpi_repair_function repair_function;
} acpi_repair_info;
/* Local prototypes */
static const struct acpi_repair_info *acpi_ns_match_repairable_name(struct
acpi_namespace_node
*node);
static acpi_status
acpi_ns_repair_ALR(struct acpi_predefined_data *data,
union acpi_operand_object **return_object_ptr);
static acpi_status
acpi_ns_repair_CID(struct acpi_predefined_data *data,
union acpi_operand_object **return_object_ptr);
static acpi_status
acpi_ns_repair_FDE(struct acpi_predefined_data *data,
union acpi_operand_object **return_object_ptr);
static acpi_status
acpi_ns_repair_HID(struct acpi_predefined_data *data,
union acpi_operand_object **return_object_ptr);
static acpi_status
acpi_ns_repair_PSS(struct acpi_predefined_data *data,
union acpi_operand_object **return_object_ptr);
static acpi_status
acpi_ns_repair_TSS(struct acpi_predefined_data *data,
union acpi_operand_object **return_object_ptr);
static acpi_status
acpi_ns_check_sorted_list(struct acpi_predefined_data *data,
union acpi_operand_object *return_object,
u32 expected_count,
u32 sort_index,
u8 sort_direction, char *sort_key_name);
static void
acpi_ns_sort_list(union acpi_operand_object **elements,
u32 count, u32 index, u8 sort_direction);
/* Values for sort_direction above */
#define ACPI_SORT_ASCENDING 0
#define ACPI_SORT_DESCENDING 1
/*
* This table contains the names of the predefined methods for which we can
* perform more complex repairs.
*
* As necessary:
*
* _ALR: Sort the list ascending by ambient_illuminance
* _CID: Strings: uppercase all, remove any leading asterisk
* _FDE: Convert Buffer of BYTEs to a Buffer of DWORDs
* _GTM: Convert Buffer of BYTEs to a Buffer of DWORDs
* _HID: Strings: uppercase all, remove any leading asterisk
* _PSS: Sort the list descending by Power
* _TSS: Sort the list descending by Power
*
* Names that must be packages, but cannot be sorted:
*
* _BCL: Values are tied to the Package index where they appear, and cannot
* be moved or sorted. These index values are used for _BQC and _BCM.
* However, we can fix the case where a buffer is returned, by converting
* it to a Package of integers.
*/
static const struct acpi_repair_info acpi_ns_repairable_names[] = {
{"_ALR", acpi_ns_repair_ALR},
{"_CID", acpi_ns_repair_CID},
{"_FDE", acpi_ns_repair_FDE},
{"_GTM", acpi_ns_repair_FDE}, /* _GTM has same repair as _FDE */
{"_HID", acpi_ns_repair_HID},
{"_PSS", acpi_ns_repair_PSS},
{"_TSS", acpi_ns_repair_TSS},
{{0, 0, 0, 0}, NULL} /* Table terminator */
};
#define ACPI_FDE_FIELD_COUNT 5
#define ACPI_FDE_BYTE_BUFFER_SIZE 5
#define ACPI_FDE_DWORD_BUFFER_SIZE (ACPI_FDE_FIELD_COUNT * sizeof (u32))
/******************************************************************************
*
* FUNCTION: acpi_ns_complex_repairs
*
* PARAMETERS: Data - Pointer to validation data structure
* Node - Namespace node for the method/object
* validate_status - Original status of earlier validation
* return_object_ptr - Pointer to the object returned from the
* evaluation of a method or object
*
* RETURN: Status. AE_OK if repair was successful. If name is not
* matched, validate_status is returned.
*
* DESCRIPTION: Attempt to repair/convert a return object of a type that was
* not expected.
*
*****************************************************************************/
acpi_status
acpi_ns_complex_repairs(struct acpi_predefined_data *data,
struct acpi_namespace_node *node,
acpi_status validate_status,
union acpi_operand_object **return_object_ptr)
{
const struct acpi_repair_info *predefined;
acpi_status status;
/* Check if this name is in the list of repairable names */
predefined = acpi_ns_match_repairable_name(node);
if (!predefined) {
return (validate_status);
}
status = predefined->repair_function(data, return_object_ptr);
return (status);
}
/******************************************************************************
*
* FUNCTION: acpi_ns_match_repairable_name
*
* PARAMETERS: Node - Namespace node for the method/object
*
* RETURN: Pointer to entry in repair table. NULL indicates not found.
*
* DESCRIPTION: Check an object name against the repairable object list.
*
*****************************************************************************/
static const struct acpi_repair_info *acpi_ns_match_repairable_name(struct
acpi_namespace_node
*node)
{
const struct acpi_repair_info *this_name;
/* Search info table for a repairable predefined method/object name */
this_name = acpi_ns_repairable_names;
while (this_name->repair_function) {
if (ACPI_COMPARE_NAME(node->name.ascii, this_name->name)) {
return (this_name);
}
this_name++;
}
return (NULL); /* Not found */
}
/******************************************************************************
*
* FUNCTION: acpi_ns_repair_ALR
*
* PARAMETERS: Data - Pointer to validation data structure
* return_object_ptr - Pointer to the object returned from the
* evaluation of a method or object
*
* RETURN: Status. AE_OK if object is OK or was repaired successfully
*
* DESCRIPTION: Repair for the _ALR object. If necessary, sort the object list
* ascending by the ambient illuminance values.
*
*****************************************************************************/
static acpi_status
acpi_ns_repair_ALR(struct acpi_predefined_data *data,
union acpi_operand_object **return_object_ptr)
{
union acpi_operand_object *return_object = *return_object_ptr;
acpi_status status;
status = acpi_ns_check_sorted_list(data, return_object, 2, 1,
ACPI_SORT_ASCENDING,
"AmbientIlluminance");
return (status);
}
/******************************************************************************
*
* FUNCTION: acpi_ns_repair_FDE
*
* PARAMETERS: Data - Pointer to validation data structure
* return_object_ptr - Pointer to the object returned from the
* evaluation of a method or object
*
* RETURN: Status. AE_OK if object is OK or was repaired successfully
*
* DESCRIPTION: Repair for the _FDE and _GTM objects. The expected return
* value is a Buffer of 5 DWORDs. This function repairs a common
* problem where the return value is a Buffer of BYTEs, not
* DWORDs.
*
*****************************************************************************/
static acpi_status
acpi_ns_repair_FDE(struct acpi_predefined_data *data,
union acpi_operand_object **return_object_ptr)
{
union acpi_operand_object *return_object = *return_object_ptr;
union acpi_operand_object *buffer_object;
u8 *byte_buffer;
u32 *dword_buffer;
u32 i;
ACPI_FUNCTION_NAME(ns_repair_FDE);
switch (return_object->common.type) {
case ACPI_TYPE_BUFFER:
/* This is the expected type. Length should be (at least) 5 DWORDs */
if (return_object->buffer.length >= ACPI_FDE_DWORD_BUFFER_SIZE) {
return (AE_OK);
}
/* We can only repair if we have exactly 5 BYTEs */
if (return_object->buffer.length != ACPI_FDE_BYTE_BUFFER_SIZE) {
ACPI_WARN_PREDEFINED((AE_INFO, data->pathname,
data->node_flags,
"Incorrect return buffer length %u, expected %u",
return_object->buffer.length,
ACPI_FDE_DWORD_BUFFER_SIZE));
return (AE_AML_OPERAND_TYPE);
}
/* Create the new (larger) buffer object */
buffer_object =
acpi_ut_create_buffer_object(ACPI_FDE_DWORD_BUFFER_SIZE);
if (!buffer_object) {
return (AE_NO_MEMORY);
}
/* Expand each byte to a DWORD */
byte_buffer = return_object->buffer.pointer;
dword_buffer =
ACPI_CAST_PTR(u32, buffer_object->buffer.pointer);
for (i = 0; i < ACPI_FDE_FIELD_COUNT; i++) {
*dword_buffer = (u32) *byte_buffer;
dword_buffer++;
byte_buffer++;
}
ACPI_DEBUG_PRINT((ACPI_DB_REPAIR,
"%s Expanded Byte Buffer to expected DWord Buffer\n",
data->pathname));
break;
default:
return (AE_AML_OPERAND_TYPE);
}
/* Delete the original return object, return the new buffer object */
acpi_ut_remove_reference(return_object);
*return_object_ptr = buffer_object;
data->flags |= ACPI_OBJECT_REPAIRED;
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: acpi_ns_repair_CID
*
* PARAMETERS: Data - Pointer to validation data structure
* return_object_ptr - Pointer to the object returned from the
* evaluation of a method or object
*
* RETURN: Status. AE_OK if object is OK or was repaired successfully
*
* DESCRIPTION: Repair for the _CID object. If a string, ensure that all
* letters are uppercase and that there is no leading asterisk.
* If a Package, ensure same for all string elements.
*
*****************************************************************************/
static acpi_status
acpi_ns_repair_CID(struct acpi_predefined_data *data,
union acpi_operand_object **return_object_ptr)
{
acpi_status status;
union acpi_operand_object *return_object = *return_object_ptr;
union acpi_operand_object **element_ptr;
union acpi_operand_object *original_element;
u16 original_ref_count;
u32 i;
/* Check for _CID as a simple string */
if (return_object->common.type == ACPI_TYPE_STRING) {
status = acpi_ns_repair_HID(data, return_object_ptr);
return (status);
}
/* Exit if not a Package */
if (return_object->common.type != ACPI_TYPE_PACKAGE) {
return (AE_OK);
}
/* Examine each element of the _CID package */
element_ptr = return_object->package.elements;
for (i = 0; i < return_object->package.count; i++) {
original_element = *element_ptr;
original_ref_count = original_element->common.reference_count;
status = acpi_ns_repair_HID(data, element_ptr);
if (ACPI_FAILURE(status)) {
return (status);
}
/* Take care with reference counts */
if (original_element != *element_ptr) {
/* Element was replaced */
(*element_ptr)->common.reference_count =
original_ref_count;
acpi_ut_remove_reference(original_element);
}
element_ptr++;
}
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: acpi_ns_repair_HID
*
* PARAMETERS: Data - Pointer to validation data structure
* return_object_ptr - Pointer to the object returned from the
* evaluation of a method or object
*
* RETURN: Status. AE_OK if object is OK or was repaired successfully
*
* DESCRIPTION: Repair for the _HID object. If a string, ensure that all
* letters are uppercase and that there is no leading asterisk.
*
*****************************************************************************/
static acpi_status
acpi_ns_repair_HID(struct acpi_predefined_data *data,
union acpi_operand_object **return_object_ptr)
{
union acpi_operand_object *return_object = *return_object_ptr;
union acpi_operand_object *new_string;
char *source;
char *dest;
ACPI_FUNCTION_NAME(ns_repair_HID);
/* We only care about string _HID objects (not integers) */
if (return_object->common.type != ACPI_TYPE_STRING) {
return (AE_OK);
}
if (return_object->string.length == 0) {
ACPI_WARN_PREDEFINED((AE_INFO, data->pathname, data->node_flags,
"Invalid zero-length _HID or _CID string"));
/* Return AE_OK anyway, let driver handle it */
data->flags |= ACPI_OBJECT_REPAIRED;
return (AE_OK);
}
/* It is simplest to always create a new string object */
new_string = acpi_ut_create_string_object(return_object->string.length);
if (!new_string) {
return (AE_NO_MEMORY);
}
/*
* Remove a leading asterisk if present. For some unknown reason, there
* are many machines in the field that contains IDs like this.
*
* Examples: "*PNP0C03", "*ACPI0003"
*/
source = return_object->string.pointer;
if (*source == '*') {
source++;
new_string->string.length--;
ACPI_DEBUG_PRINT((ACPI_DB_REPAIR,
"%s: Removed invalid leading asterisk\n",
data->pathname));
}
/*
* Copy and uppercase the string. From the ACPI 5.0 specification:
*
* A valid PNP ID must be of the form "AAA####" where A is an uppercase
* letter and # is a hex digit. A valid ACPI ID must be of the form
* "NNNN####" where N is an uppercase letter or decimal digit, and
* # is a hex digit.
*/
for (dest = new_string->string.pointer; *source; dest++, source++) {
*dest = (char)ACPI_TOUPPER(*source);
}
acpi_ut_remove_reference(return_object);
*return_object_ptr = new_string;
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: acpi_ns_repair_TSS
*
* PARAMETERS: Data - Pointer to validation data structure
* return_object_ptr - Pointer to the object returned from the
* evaluation of a method or object
*
* RETURN: Status. AE_OK if object is OK or was repaired successfully
*
* DESCRIPTION: Repair for the _TSS object. If necessary, sort the object list
* descending by the power dissipation values.
*
*****************************************************************************/
static acpi_status
acpi_ns_repair_TSS(struct acpi_predefined_data *data,
union acpi_operand_object **return_object_ptr)
{
union acpi_operand_object *return_object = *return_object_ptr;
acpi_status status;
struct acpi_namespace_node *node;
/*
* We can only sort the _TSS return package if there is no _PSS in the
* same scope. This is because if _PSS is present, the ACPI specification
* dictates that the _TSS Power Dissipation field is to be ignored, and
* therefore some BIOSs leave garbage values in the _TSS Power field(s).
* In this case, it is best to just return the _TSS package as-is.
* (May, 2011)
*/
status =
acpi_ns_get_node(data->node, "^_PSS", ACPI_NS_NO_UPSEARCH, &node);
if (ACPI_SUCCESS(status)) {
return (AE_OK);
}
status = acpi_ns_check_sorted_list(data, return_object, 5, 1,
ACPI_SORT_DESCENDING,
"PowerDissipation");
return (status);
}
/******************************************************************************
*
* FUNCTION: acpi_ns_repair_PSS
*
* PARAMETERS: Data - Pointer to validation data structure
* return_object_ptr - Pointer to the object returned from the
* evaluation of a method or object
*
* RETURN: Status. AE_OK if object is OK or was repaired successfully
*
* DESCRIPTION: Repair for the _PSS object. If necessary, sort the object list
* by the CPU frequencies. Check that the power dissipation values
* are all proportional to CPU frequency (i.e., sorting by
* frequency should be the same as sorting by power.)
*
*****************************************************************************/
static acpi_status
acpi_ns_repair_PSS(struct acpi_predefined_data *data,
union acpi_operand_object **return_object_ptr)
{
union acpi_operand_object *return_object = *return_object_ptr;
union acpi_operand_object **outer_elements;
u32 outer_element_count;
union acpi_operand_object **elements;
union acpi_operand_object *obj_desc;
u32 previous_value;
acpi_status status;
u32 i;
/*
* Entries (sub-packages) in the _PSS Package must be sorted by power
* dissipation, in descending order. If it appears that the list is
* incorrectly sorted, sort it. We sort by cpu_frequency, since this
* should be proportional to the power.
*/
status = acpi_ns_check_sorted_list(data, return_object, 6, 0,
ACPI_SORT_DESCENDING,
"CpuFrequency");
if (ACPI_FAILURE(status)) {
return (status);
}
/*
* We now know the list is correctly sorted by CPU frequency. Check if
* the power dissipation values are proportional.
*/
previous_value = ACPI_UINT32_MAX;
outer_elements = return_object->package.elements;
outer_element_count = return_object->package.count;
for (i = 0; i < outer_element_count; i++) {
elements = (*outer_elements)->package.elements;
obj_desc = elements[1]; /* Index1 = power_dissipation */
if ((u32) obj_desc->integer.value > previous_value) {
ACPI_WARN_PREDEFINED((AE_INFO, data->pathname,
data->node_flags,
"SubPackage[%u,%u] - suspicious power dissipation values",
i - 1, i));
}
previous_value = (u32) obj_desc->integer.value;
outer_elements++;
}
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: acpi_ns_check_sorted_list
*
* PARAMETERS: Data - Pointer to validation data structure
* return_object - Pointer to the top-level returned object
* expected_count - Minimum length of each sub-package
* sort_index - Sub-package entry to sort on
* sort_direction - Ascending or descending
* sort_key_name - Name of the sort_index field
*
* RETURN: Status. AE_OK if the list is valid and is sorted correctly or
* has been repaired by sorting the list.
*
* DESCRIPTION: Check if the package list is valid and sorted correctly by the
* sort_index. If not, then sort the list.
*
*****************************************************************************/
static acpi_status
acpi_ns_check_sorted_list(struct acpi_predefined_data *data,
union acpi_operand_object *return_object,
u32 expected_count,
u32 sort_index,
u8 sort_direction, char *sort_key_name)
{
u32 outer_element_count;
union acpi_operand_object **outer_elements;
union acpi_operand_object **elements;
union acpi_operand_object *obj_desc;
u32 i;
u32 previous_value;
ACPI_FUNCTION_NAME(ns_check_sorted_list);
/* The top-level object must be a package */
if (return_object->common.type != ACPI_TYPE_PACKAGE) {
return (AE_AML_OPERAND_TYPE);
}
/*
* NOTE: assumes list of sub-packages contains no NULL elements.
* Any NULL elements should have been removed by earlier call
* to acpi_ns_remove_null_elements.
*/
outer_elements = return_object->package.elements;
outer_element_count = return_object->package.count;
if (!outer_element_count) {
return (AE_AML_PACKAGE_LIMIT);
}
previous_value = 0;
if (sort_direction == ACPI_SORT_DESCENDING) {
previous_value = ACPI_UINT32_MAX;
}
/* Examine each subpackage */
for (i = 0; i < outer_element_count; i++) {
/* Each element of the top-level package must also be a package */
if ((*outer_elements)->common.type != ACPI_TYPE_PACKAGE) {
return (AE_AML_OPERAND_TYPE);
}
/* Each sub-package must have the minimum length */
if ((*outer_elements)->package.count < expected_count) {
return (AE_AML_PACKAGE_LIMIT);
}
elements = (*outer_elements)->package.elements;
obj_desc = elements[sort_index];
if (obj_desc->common.type != ACPI_TYPE_INTEGER) {
return (AE_AML_OPERAND_TYPE);
}
/*
* The list must be sorted in the specified order. If we detect a
* discrepancy, sort the entire list.
*/
if (((sort_direction == ACPI_SORT_ASCENDING) &&
(obj_desc->integer.value < previous_value)) ||
((sort_direction == ACPI_SORT_DESCENDING) &&
(obj_desc->integer.value > previous_value))) {
acpi_ns_sort_list(return_object->package.elements,
outer_element_count, sort_index,
sort_direction);
data->flags |= ACPI_OBJECT_REPAIRED;
ACPI_DEBUG_PRINT((ACPI_DB_REPAIR,
"%s: Repaired unsorted list - now sorted by %s\n",
data->pathname, sort_key_name));
return (AE_OK);
}
previous_value = (u32) obj_desc->integer.value;
outer_elements++;
}
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: acpi_ns_sort_list
*
* PARAMETERS: Elements - Package object element list
* Count - Element count for above
* Index - Sort by which package element
* sort_direction - Ascending or Descending sort
*
* RETURN: None
*
* DESCRIPTION: Sort the objects that are in a package element list.
*
* NOTE: Assumes that all NULL elements have been removed from the package,
* and that all elements have been verified to be of type Integer.
*
*****************************************************************************/
static void
acpi_ns_sort_list(union acpi_operand_object **elements,
u32 count, u32 index, u8 sort_direction)
{
union acpi_operand_object *obj_desc1;
union acpi_operand_object *obj_desc2;
union acpi_operand_object *temp_obj;
u32 i;
u32 j;
/* Simple bubble sort */
for (i = 1; i < count; i++) {
for (j = (count - 1); j >= i; j--) {
obj_desc1 = elements[j - 1]->package.elements[index];
obj_desc2 = elements[j]->package.elements[index];
if (((sort_direction == ACPI_SORT_ASCENDING) &&
(obj_desc1->integer.value >
obj_desc2->integer.value))
|| ((sort_direction == ACPI_SORT_DESCENDING)
&& (obj_desc1->integer.value <
obj_desc2->integer.value))) {
temp_obj = elements[j - 1];
elements[j - 1] = elements[j];
elements[j] = temp_obj;
}
}
}
}
| gpl-2.0 |
AICP/kernel_samsung_exynos5410 | drivers/video/asiliantfb.c | 9271 | 17013 | /*
* drivers/video/asiliantfb.c
* frame buffer driver for Asiliant 69000 chip
* Copyright (C) 2001-2003 Saito.K & Jeanne
*
* from driver/video/chipsfb.c and,
*
* drivers/video/asiliantfb.c -- frame buffer device for
* Asiliant 69030 chip (formerly Intel, formerly Chips & Technologies)
* Author: apc@agelectronics.co.uk
* Copyright (C) 2000 AG Electronics
* Note: the data sheets don't seem to be available from Asiliant.
* They are available by searching developer.intel.com, but are not otherwise
* linked to.
*
* This driver should be portable with minimal effort to the 69000 display
* chip, and to the twin-display mode of the 69030.
* Contains code from Thomas Hhenleitner <th@visuelle-maschinen.de> (thanks)
*
* Derived from the CT65550 driver chipsfb.c:
* Copyright (C) 1998 Paul Mackerras
* ...which was derived from the Powermac "chips" driver:
* Copyright (C) 1997 Fabio Riccardi.
* And from the frame buffer device for Open Firmware-initialized devices:
* Copyright (C) 1997 Geert Uytterhoeven.
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive for
* more details.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/vmalloc.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <asm/io.h>
/* Built in clock of the 69030 */
static const unsigned Fref = 14318180;
#define mmio_base (p->screen_base + 0x400000)
#define mm_write_ind(num, val, ap, dp) do { \
writeb((num), mmio_base + (ap)); writeb((val), mmio_base + (dp)); \
} while (0)
static void mm_write_xr(struct fb_info *p, u8 reg, u8 data)
{
mm_write_ind(reg, data, 0x7ac, 0x7ad);
}
#define write_xr(num, val) mm_write_xr(p, num, val)
static void mm_write_fr(struct fb_info *p, u8 reg, u8 data)
{
mm_write_ind(reg, data, 0x7a0, 0x7a1);
}
#define write_fr(num, val) mm_write_fr(p, num, val)
static void mm_write_cr(struct fb_info *p, u8 reg, u8 data)
{
mm_write_ind(reg, data, 0x7a8, 0x7a9);
}
#define write_cr(num, val) mm_write_cr(p, num, val)
static void mm_write_gr(struct fb_info *p, u8 reg, u8 data)
{
mm_write_ind(reg, data, 0x79c, 0x79d);
}
#define write_gr(num, val) mm_write_gr(p, num, val)
static void mm_write_sr(struct fb_info *p, u8 reg, u8 data)
{
mm_write_ind(reg, data, 0x788, 0x789);
}
#define write_sr(num, val) mm_write_sr(p, num, val)
static void mm_write_ar(struct fb_info *p, u8 reg, u8 data)
{
readb(mmio_base + 0x7b4);
mm_write_ind(reg, data, 0x780, 0x780);
}
#define write_ar(num, val) mm_write_ar(p, num, val)
static int asiliantfb_pci_init(struct pci_dev *dp, const struct pci_device_id *);
static int asiliantfb_check_var(struct fb_var_screeninfo *var,
struct fb_info *info);
static int asiliantfb_set_par(struct fb_info *info);
static int asiliantfb_setcolreg(u_int regno, u_int red, u_int green, u_int blue,
u_int transp, struct fb_info *info);
static struct fb_ops asiliantfb_ops = {
.owner = THIS_MODULE,
.fb_check_var = asiliantfb_check_var,
.fb_set_par = asiliantfb_set_par,
.fb_setcolreg = asiliantfb_setcolreg,
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
};
/* Calculate the ratios for the dot clocks without using a single long long
* value */
static void asiliant_calc_dclk2(u32 *ppixclock, u8 *dclk2_m, u8 *dclk2_n, u8 *dclk2_div)
{
unsigned pixclock = *ppixclock;
unsigned Ftarget = 1000000 * (1000000 / pixclock);
unsigned n;
unsigned best_error = 0xffffffff;
unsigned best_m = 0xffffffff,
best_n = 0xffffffff;
unsigned ratio;
unsigned remainder;
unsigned char divisor = 0;
/* Calculate the frequency required. This is hard enough. */
ratio = 1000000 / pixclock;
remainder = 1000000 % pixclock;
Ftarget = 1000000 * ratio + (1000000 * remainder) / pixclock;
while (Ftarget < 100000000) {
divisor += 0x10;
Ftarget <<= 1;
}
ratio = Ftarget / Fref;
remainder = Ftarget % Fref;
/* This expresses the constraint that 150kHz <= Fref/n <= 5Mhz,
* together with 3 <= n <= 257. */
for (n = 3; n <= 257; n++) {
unsigned m = n * ratio + (n * remainder) / Fref;
/* 3 <= m <= 257 */
if (m >= 3 && m <= 257) {
unsigned new_error = Ftarget * n >= Fref * m ?
((Ftarget * n) - (Fref * m)) : ((Fref * m) - (Ftarget * n));
if (new_error < best_error) {
best_n = n;
best_m = m;
best_error = new_error;
}
}
/* But if VLD = 4, then 4m <= 1028 */
else if (m <= 1028) {
/* remember there are still only 8-bits of precision in m, so
* avoid over-optimistic error calculations */
unsigned new_error = Ftarget * n >= Fref * (m & ~3) ?
((Ftarget * n) - (Fref * (m & ~3))) : ((Fref * (m & ~3)) - (Ftarget * n));
if (new_error < best_error) {
best_n = n;
best_m = m;
best_error = new_error;
}
}
}
if (best_m > 257)
best_m >>= 2; /* divide m by 4, and leave VCO loop divide at 4 */
else
divisor |= 4; /* or set VCO loop divide to 1 */
*dclk2_m = best_m - 2;
*dclk2_n = best_n - 2;
*dclk2_div = divisor;
*ppixclock = pixclock;
return;
}
static void asiliant_set_timing(struct fb_info *p)
{
unsigned hd = p->var.xres / 8;
unsigned hs = (p->var.xres + p->var.right_margin) / 8;
unsigned he = (p->var.xres + p->var.right_margin + p->var.hsync_len) / 8;
unsigned ht = (p->var.left_margin + p->var.xres + p->var.right_margin + p->var.hsync_len) / 8;
unsigned vd = p->var.yres;
unsigned vs = p->var.yres + p->var.lower_margin;
unsigned ve = p->var.yres + p->var.lower_margin + p->var.vsync_len;
unsigned vt = p->var.upper_margin + p->var.yres + p->var.lower_margin + p->var.vsync_len;
unsigned wd = (p->var.xres_virtual * ((p->var.bits_per_pixel+7)/8)) / 8;
if ((p->var.xres == 640) && (p->var.yres == 480) && (p->var.pixclock == 39722)) {
write_fr(0x01, 0x02); /* LCD */
} else {
write_fr(0x01, 0x01); /* CRT */
}
write_cr(0x11, (ve - 1) & 0x0f);
write_cr(0x00, (ht - 5) & 0xff);
write_cr(0x01, hd - 1);
write_cr(0x02, hd);
write_cr(0x03, ((ht - 1) & 0x1f) | 0x80);
write_cr(0x04, hs);
write_cr(0x05, (((ht - 1) & 0x20) <<2) | (he & 0x1f));
write_cr(0x3c, (ht - 1) & 0xc0);
write_cr(0x06, (vt - 2) & 0xff);
write_cr(0x30, (vt - 2) >> 8);
write_cr(0x07, 0x00);
write_cr(0x08, 0x00);
write_cr(0x09, 0x00);
write_cr(0x10, (vs - 1) & 0xff);
write_cr(0x32, ((vs - 1) >> 8) & 0xf);
write_cr(0x11, ((ve - 1) & 0x0f) | 0x80);
write_cr(0x12, (vd - 1) & 0xff);
write_cr(0x31, ((vd - 1) & 0xf00) >> 8);
write_cr(0x13, wd & 0xff);
write_cr(0x41, (wd & 0xf00) >> 8);
write_cr(0x15, (vs - 1) & 0xff);
write_cr(0x33, ((vs - 1) >> 8) & 0xf);
write_cr(0x38, ((ht - 5) & 0x100) >> 8);
write_cr(0x16, (vt - 1) & 0xff);
write_cr(0x18, 0x00);
if (p->var.xres == 640) {
writeb(0xc7, mmio_base + 0x784); /* set misc output reg */
} else {
writeb(0x07, mmio_base + 0x784); /* set misc output reg */
}
}
static int asiliantfb_check_var(struct fb_var_screeninfo *var,
struct fb_info *p)
{
unsigned long Ftarget, ratio, remainder;
ratio = 1000000 / var->pixclock;
remainder = 1000000 % var->pixclock;
Ftarget = 1000000 * ratio + (1000000 * remainder) / var->pixclock;
/* First check the constraint that the maximum post-VCO divisor is 32,
* and the maximum Fvco is 220MHz */
if (Ftarget > 220000000 || Ftarget < 3125000) {
printk(KERN_ERR "asiliantfb dotclock must be between 3.125 and 220MHz\n");
return -ENXIO;
}
var->xres_virtual = var->xres;
var->yres_virtual = var->yres;
if (var->bits_per_pixel == 24) {
var->red.offset = 16;
var->green.offset = 8;
var->blue.offset = 0;
var->red.length = var->blue.length = var->green.length = 8;
} else if (var->bits_per_pixel == 16) {
switch (var->red.offset) {
case 11:
var->green.length = 6;
break;
case 10:
var->green.length = 5;
break;
default:
return -EINVAL;
}
var->green.offset = 5;
var->blue.offset = 0;
var->red.length = var->blue.length = 5;
} else if (var->bits_per_pixel == 8) {
var->red.offset = var->green.offset = var->blue.offset = 0;
var->red.length = var->green.length = var->blue.length = 8;
}
return 0;
}
static int asiliantfb_set_par(struct fb_info *p)
{
u8 dclk2_m; /* Holds m-2 value for register */
u8 dclk2_n; /* Holds n-2 value for register */
u8 dclk2_div; /* Holds divisor bitmask */
/* Set pixclock */
asiliant_calc_dclk2(&p->var.pixclock, &dclk2_m, &dclk2_n, &dclk2_div);
/* Set color depth */
if (p->var.bits_per_pixel == 24) {
write_xr(0x81, 0x16); /* 24 bit packed color mode */
write_xr(0x82, 0x00); /* Disable palettes */
write_xr(0x20, 0x20); /* 24 bit blitter mode */
} else if (p->var.bits_per_pixel == 16) {
if (p->var.red.offset == 11)
write_xr(0x81, 0x15); /* 16 bit color mode */
else
write_xr(0x81, 0x14); /* 15 bit color mode */
write_xr(0x82, 0x00); /* Disable palettes */
write_xr(0x20, 0x10); /* 16 bit blitter mode */
} else if (p->var.bits_per_pixel == 8) {
write_xr(0x0a, 0x02); /* Linear */
write_xr(0x81, 0x12); /* 8 bit color mode */
write_xr(0x82, 0x00); /* Graphics gamma enable */
write_xr(0x20, 0x00); /* 8 bit blitter mode */
}
p->fix.line_length = p->var.xres * (p->var.bits_per_pixel >> 3);
p->fix.visual = (p->var.bits_per_pixel == 8) ? FB_VISUAL_PSEUDOCOLOR : FB_VISUAL_TRUECOLOR;
write_xr(0xc4, dclk2_m);
write_xr(0xc5, dclk2_n);
write_xr(0xc7, dclk2_div);
/* Set up the CR registers */
asiliant_set_timing(p);
return 0;
}
static int asiliantfb_setcolreg(u_int regno, u_int red, u_int green, u_int blue,
u_int transp, struct fb_info *p)
{
if (regno > 255)
return 1;
red >>= 8;
green >>= 8;
blue >>= 8;
/* Set hardware palete */
writeb(regno, mmio_base + 0x790);
udelay(1);
writeb(red, mmio_base + 0x791);
writeb(green, mmio_base + 0x791);
writeb(blue, mmio_base + 0x791);
if (regno < 16) {
switch(p->var.red.offset) {
case 10: /* RGB 555 */
((u32 *)(p->pseudo_palette))[regno] =
((red & 0xf8) << 7) |
((green & 0xf8) << 2) |
((blue & 0xf8) >> 3);
break;
case 11: /* RGB 565 */
((u32 *)(p->pseudo_palette))[regno] =
((red & 0xf8) << 8) |
((green & 0xfc) << 3) |
((blue & 0xf8) >> 3);
break;
case 16: /* RGB 888 */
((u32 *)(p->pseudo_palette))[regno] =
(red << 16) |
(green << 8) |
(blue);
break;
}
}
return 0;
}
struct chips_init_reg {
unsigned char addr;
unsigned char data;
};
static struct chips_init_reg chips_init_sr[] =
{
{0x00, 0x03}, /* Reset register */
{0x01, 0x01}, /* Clocking mode */
{0x02, 0x0f}, /* Plane mask */
{0x04, 0x0e} /* Memory mode */
};
static struct chips_init_reg chips_init_gr[] =
{
{0x03, 0x00}, /* Data rotate */
{0x05, 0x00}, /* Graphics mode */
{0x06, 0x01}, /* Miscellaneous */
{0x08, 0x00} /* Bit mask */
};
static struct chips_init_reg chips_init_ar[] =
{
{0x10, 0x01}, /* Mode control */
{0x11, 0x00}, /* Overscan */
{0x12, 0x0f}, /* Memory plane enable */
{0x13, 0x00} /* Horizontal pixel panning */
};
static struct chips_init_reg chips_init_cr[] =
{
{0x0c, 0x00}, /* Start address high */
{0x0d, 0x00}, /* Start address low */
{0x40, 0x00}, /* Extended Start Address */
{0x41, 0x00}, /* Extended Start Address */
{0x14, 0x00}, /* Underline location */
{0x17, 0xe3}, /* CRT mode control */
{0x70, 0x00} /* Interlace control */
};
static struct chips_init_reg chips_init_fr[] =
{
{0x01, 0x02},
{0x03, 0x08},
{0x08, 0xcc},
{0x0a, 0x08},
{0x18, 0x00},
{0x1e, 0x80},
{0x40, 0x83},
{0x41, 0x00},
{0x48, 0x13},
{0x4d, 0x60},
{0x4e, 0x0f},
{0x0b, 0x01},
{0x21, 0x51},
{0x22, 0x1d},
{0x23, 0x5f},
{0x20, 0x4f},
{0x34, 0x00},
{0x24, 0x51},
{0x25, 0x00},
{0x27, 0x0b},
{0x26, 0x00},
{0x37, 0x80},
{0x33, 0x0b},
{0x35, 0x11},
{0x36, 0x02},
{0x31, 0xea},
{0x32, 0x0c},
{0x30, 0xdf},
{0x10, 0x0c},
{0x11, 0xe0},
{0x12, 0x50},
{0x13, 0x00},
{0x16, 0x03},
{0x17, 0xbd},
{0x1a, 0x00},
};
static struct chips_init_reg chips_init_xr[] =
{
{0xce, 0x00}, /* set default memory clock */
{0xcc, 200 }, /* MCLK ratio M */
{0xcd, 18 }, /* MCLK ratio N */
{0xce, 0x90}, /* MCLK divisor = 2 */
{0xc4, 209 },
{0xc5, 118 },
{0xc7, 32 },
{0xcf, 0x06},
{0x09, 0x01}, /* IO Control - CRT controller extensions */
{0x0a, 0x02}, /* Frame buffer mapping */
{0x0b, 0x01}, /* PCI burst write */
{0x40, 0x03}, /* Memory access control */
{0x80, 0x82}, /* Pixel pipeline configuration 0 */
{0x81, 0x12}, /* Pixel pipeline configuration 1 */
{0x82, 0x08}, /* Pixel pipeline configuration 2 */
{0xd0, 0x0f},
{0xd1, 0x01},
};
static void __devinit chips_hw_init(struct fb_info *p)
{
int i;
for (i = 0; i < ARRAY_SIZE(chips_init_xr); ++i)
write_xr(chips_init_xr[i].addr, chips_init_xr[i].data);
write_xr(0x81, 0x12);
write_xr(0x82, 0x08);
write_xr(0x20, 0x00);
for (i = 0; i < ARRAY_SIZE(chips_init_sr); ++i)
write_sr(chips_init_sr[i].addr, chips_init_sr[i].data);
for (i = 0; i < ARRAY_SIZE(chips_init_gr); ++i)
write_gr(chips_init_gr[i].addr, chips_init_gr[i].data);
for (i = 0; i < ARRAY_SIZE(chips_init_ar); ++i)
write_ar(chips_init_ar[i].addr, chips_init_ar[i].data);
/* Enable video output in attribute index register */
writeb(0x20, mmio_base + 0x780);
for (i = 0; i < ARRAY_SIZE(chips_init_cr); ++i)
write_cr(chips_init_cr[i].addr, chips_init_cr[i].data);
for (i = 0; i < ARRAY_SIZE(chips_init_fr); ++i)
write_fr(chips_init_fr[i].addr, chips_init_fr[i].data);
}
static struct fb_fix_screeninfo asiliantfb_fix __devinitdata = {
.id = "Asiliant 69000",
.type = FB_TYPE_PACKED_PIXELS,
.visual = FB_VISUAL_PSEUDOCOLOR,
.accel = FB_ACCEL_NONE,
.line_length = 640,
.smem_len = 0x200000, /* 2MB */
};
static struct fb_var_screeninfo asiliantfb_var __devinitdata = {
.xres = 640,
.yres = 480,
.xres_virtual = 640,
.yres_virtual = 480,
.bits_per_pixel = 8,
.red = { .length = 8 },
.green = { .length = 8 },
.blue = { .length = 8 },
.height = -1,
.width = -1,
.vmode = FB_VMODE_NONINTERLACED,
.pixclock = 39722,
.left_margin = 48,
.right_margin = 16,
.upper_margin = 33,
.lower_margin = 10,
.hsync_len = 96,
.vsync_len = 2,
};
static int __devinit init_asiliant(struct fb_info *p, unsigned long addr)
{
int err;
p->fix = asiliantfb_fix;
p->fix.smem_start = addr;
p->var = asiliantfb_var;
p->fbops = &asiliantfb_ops;
p->flags = FBINFO_DEFAULT;
err = fb_alloc_cmap(&p->cmap, 256, 0);
if (err) {
printk(KERN_ERR "C&T 69000 fb failed to alloc cmap memory\n");
return err;
}
err = register_framebuffer(p);
if (err < 0) {
printk(KERN_ERR "C&T 69000 framebuffer failed to register\n");
fb_dealloc_cmap(&p->cmap);
return err;
}
printk(KERN_INFO "fb%d: Asiliant 69000 frame buffer (%dK RAM detected)\n",
p->node, p->fix.smem_len / 1024);
writeb(0xff, mmio_base + 0x78c);
chips_hw_init(p);
return 0;
}
static int __devinit
asiliantfb_pci_init(struct pci_dev *dp, const struct pci_device_id *ent)
{
unsigned long addr, size;
struct fb_info *p;
int err;
if ((dp->resource[0].flags & IORESOURCE_MEM) == 0)
return -ENODEV;
addr = pci_resource_start(dp, 0);
size = pci_resource_len(dp, 0);
if (addr == 0)
return -ENODEV;
if (!request_mem_region(addr, size, "asiliantfb"))
return -EBUSY;
p = framebuffer_alloc(sizeof(u32) * 16, &dp->dev);
if (!p) {
release_mem_region(addr, size);
return -ENOMEM;
}
p->pseudo_palette = p->par;
p->par = NULL;
p->screen_base = ioremap(addr, 0x800000);
if (p->screen_base == NULL) {
release_mem_region(addr, size);
framebuffer_release(p);
return -ENOMEM;
}
pci_write_config_dword(dp, 4, 0x02800083);
writeb(3, p->screen_base + 0x400784);
err = init_asiliant(p, addr);
if (err) {
iounmap(p->screen_base);
release_mem_region(addr, size);
framebuffer_release(p);
return err;
}
pci_set_drvdata(dp, p);
return 0;
}
static void __devexit asiliantfb_remove(struct pci_dev *dp)
{
struct fb_info *p = pci_get_drvdata(dp);
unregister_framebuffer(p);
fb_dealloc_cmap(&p->cmap);
iounmap(p->screen_base);
release_mem_region(pci_resource_start(dp, 0), pci_resource_len(dp, 0));
pci_set_drvdata(dp, NULL);
framebuffer_release(p);
}
static struct pci_device_id asiliantfb_pci_tbl[] __devinitdata = {
{ PCI_VENDOR_ID_CT, PCI_DEVICE_ID_CT_69000, PCI_ANY_ID, PCI_ANY_ID },
{ 0 }
};
MODULE_DEVICE_TABLE(pci, asiliantfb_pci_tbl);
static struct pci_driver asiliantfb_driver = {
.name = "asiliantfb",
.id_table = asiliantfb_pci_tbl,
.probe = asiliantfb_pci_init,
.remove = __devexit_p(asiliantfb_remove),
};
static int __init asiliantfb_init(void)
{
if (fb_get_options("asiliantfb", NULL))
return -ENODEV;
return pci_register_driver(&asiliantfb_driver);
}
module_init(asiliantfb_init);
static void __exit asiliantfb_exit(void)
{
pci_unregister_driver(&asiliantfb_driver);
}
MODULE_LICENSE("GPL");
| gpl-2.0 |
mickael-guene/gcc | gcc/testsuite/gcc.target/aarch64/vldN_lane_1.c | 56 | 3642 | /* { dg-do run } */
/* { dg-options "-O3 -fno-inline" } */
#include <arm_neon.h>
extern void abort (void);
#define VARIANTS(VARIANT, STRUCT) \
VARIANT (uint8, , 8, _u8, 6, STRUCT) \
VARIANT (uint16, , 4, _u16, 3, STRUCT) \
VARIANT (uint32, , 2, _u32, 1, STRUCT) \
VARIANT (uint64, , 1, _u64, 0, STRUCT) \
VARIANT (int8, , 8, _s8, 5, STRUCT) \
VARIANT (int16, , 4, _s16, 2, STRUCT) \
VARIANT (int32, , 2, _s32, 0, STRUCT) \
VARIANT (int64, , 1, _s64, 0, STRUCT) \
VARIANT (poly8, , 8, _p8, 7, STRUCT) \
VARIANT (poly16, , 4, _p16, 1, STRUCT) \
VARIANT (float16, , 4, _f16, 3, STRUCT) \
VARIANT (float32, , 2, _f32, 1, STRUCT) \
VARIANT (float64, , 1, _f64, 0, STRUCT) \
VARIANT (uint8, q, 16, _u8, 14, STRUCT) \
VARIANT (uint16, q, 8, _u16, 4, STRUCT) \
VARIANT (uint32, q, 4, _u32, 3, STRUCT) \
VARIANT (uint64, q, 2, _u64, 0, STRUCT) \
VARIANT (int8, q, 16, _s8, 13, STRUCT) \
VARIANT (int16, q, 8, _s16, 6, STRUCT) \
VARIANT (int32, q, 4, _s32, 2, STRUCT) \
VARIANT (int64, q, 2, _s64, 1, STRUCT) \
VARIANT (poly8, q, 16, _p8, 12, STRUCT) \
VARIANT (poly16, q, 8, _p16, 5, STRUCT) \
VARIANT (float16, q, 8, _f16, 7, STRUCT)\
VARIANT (float32, q, 4, _f32, 1, STRUCT)\
VARIANT (float64, q, 2, _f64, 0, STRUCT)
#define TESTMETH(BASE, Q, ELTS, SUFFIX, LANE, STRUCT) \
int \
test_vld##STRUCT##Q##_lane##SUFFIX (const BASE##_t *data, \
const BASE##_t *overwrite) \
{ \
BASE##x##ELTS##x##STRUCT##_t vectors; \
BASE##_t temp[ELTS]; \
int i,j; \
for (i = 0; i < STRUCT; i++, data += ELTS) \
vectors.val[i] = vld1##Q##SUFFIX (data); \
vectors = vld##STRUCT##Q##_lane##SUFFIX (overwrite, vectors, LANE); \
while (--i >= 0) \
{ \
vst1##Q##SUFFIX (temp, vectors.val[i]); \
data -= ELTS; /* Point at value loaded before vldN_lane. */ \
for (j = 0; j < ELTS; j++) \
if (temp[j] != (j == LANE ? overwrite[i] : data[j])) \
return 1; \
} \
return 0; \
}
/* Tests of vld2_lane and vld2q_lane. */
VARIANTS (TESTMETH, 2)
/* Tests of vld3_lane and vld3q_lane. */
VARIANTS (TESTMETH, 3)
/* Tests of vld4_lane and vld4q_lane. */
VARIANTS (TESTMETH, 4)
#define CHECK(BASE, Q, ELTS, SUFFIX, LANE, STRUCT) \
if (test_vld##STRUCT##Q##_lane##SUFFIX ((const BASE##_t *)orig_data, \
BASE##_data) != 0) \
abort ();
int
main (int argc, char **argv)
{
/* Original data for all vector formats. */
uint64_t orig_data[8] = {0x1234567890abcdefULL, 0x13579bdf02468aceULL,
0x012389ab4567cdefULL, 0xdeeddadacafe0431ULL,
0x1032547698badcfeULL, 0xbadbadbadbad0badULL,
0x0102030405060708ULL, 0x0f0e0d0c0b0a0908ULL};
/* Data with which vldN_lane will overwrite some of previous. */
uint8_t uint8_data[4] = { 7, 11, 13, 17 };
uint16_t uint16_data[4] = { 257, 263, 269, 271 };
uint32_t uint32_data[4] = { 65537, 65539, 65543, 65551 };
uint64_t uint64_data[4] = { 0xdeadbeefcafebabeULL, 0x0123456789abcdefULL,
0xfedcba9876543210LL, 0xdeadbabecafebeefLL };
int8_t int8_data[4] = { -1, 3, -5, 7 };
int16_t int16_data[4] = { 257, -259, 261, -263 };
int32_t int32_data[4] = { 123456789, -987654321, -135792468, 975318642 };
int64_t *int64_data = (int64_t *)uint64_data;
poly8_t poly8_data[4] = { 0, 7, 13, 18, };
poly16_t poly16_data[4] = { 11111, 2222, 333, 44 };
float16_t float16_data[4] = { 0.8125, 7.5, 19, 0.046875 };
float32_t float32_data[4] = { 3.14159, 2.718, 1.414, 100.0 };
float64_t float64_data[4] = { 1.010010001, 12345.6789, -9876.54321, 1.618 };
VARIANTS (CHECK, 2);
VARIANTS (CHECK, 3);
VARIANTS (CHECK, 4);
return 0;
}
| gpl-2.0 |
Stefan-Schmidt/linux-2.6 | drivers/gpu/drm/nouveau/nv40_fifo.c | 56 | 10171 | /*
* Copyright (C) 2007 Ben Skeggs.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include "drmP.h"
#include "nouveau_drv.h"
#include "nouveau_drm.h"
#include "nouveau_ramht.h"
#define NV40_RAMFC(c) (dev_priv->ramfc->pinst + ((c) * NV40_RAMFC__SIZE))
#define NV40_RAMFC__SIZE 128
int
nv40_fifo_create_context(struct nouveau_channel *chan)
{
struct drm_device *dev = chan->dev;
struct drm_nouveau_private *dev_priv = dev->dev_private;
uint32_t fc = NV40_RAMFC(chan->id);
unsigned long flags;
int ret;
ret = nouveau_gpuobj_new_fake(dev, NV40_RAMFC(chan->id), ~0,
NV40_RAMFC__SIZE, NVOBJ_FLAG_ZERO_ALLOC |
NVOBJ_FLAG_ZERO_FREE, &chan->ramfc);
if (ret)
return ret;
spin_lock_irqsave(&dev_priv->context_switch_lock, flags);
nv_wi32(dev, fc + 0, chan->pushbuf_base);
nv_wi32(dev, fc + 4, chan->pushbuf_base);
nv_wi32(dev, fc + 12, chan->pushbuf->pinst >> 4);
nv_wi32(dev, fc + 24, NV_PFIFO_CACHE1_DMA_FETCH_TRIG_128_BYTES |
NV_PFIFO_CACHE1_DMA_FETCH_SIZE_128_BYTES |
NV_PFIFO_CACHE1_DMA_FETCH_MAX_REQS_8 |
#ifdef __BIG_ENDIAN
NV_PFIFO_CACHE1_BIG_ENDIAN |
#endif
0x30000000 /* no idea.. */);
nv_wi32(dev, fc + 56, chan->ramin_grctx->pinst >> 4);
nv_wi32(dev, fc + 60, 0x0001FFFF);
/* enable the fifo dma operation */
nv_wr32(dev, NV04_PFIFO_MODE,
nv_rd32(dev, NV04_PFIFO_MODE) | (1 << chan->id));
spin_unlock_irqrestore(&dev_priv->context_switch_lock, flags);
return 0;
}
void
nv40_fifo_destroy_context(struct nouveau_channel *chan)
{
struct drm_device *dev = chan->dev;
nv_wr32(dev, NV04_PFIFO_MODE,
nv_rd32(dev, NV04_PFIFO_MODE) & ~(1 << chan->id));
nouveau_gpuobj_ref(NULL, &chan->ramfc);
}
static void
nv40_fifo_do_load_context(struct drm_device *dev, int chid)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
uint32_t fc = NV40_RAMFC(chid), tmp, tmp2;
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_PUT, nv_ri32(dev, fc + 0));
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_GET, nv_ri32(dev, fc + 4));
nv_wr32(dev, NV10_PFIFO_CACHE1_REF_CNT, nv_ri32(dev, fc + 8));
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_INSTANCE, nv_ri32(dev, fc + 12));
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_DCOUNT, nv_ri32(dev, fc + 16));
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_STATE, nv_ri32(dev, fc + 20));
/* No idea what 0x2058 is.. */
tmp = nv_ri32(dev, fc + 24);
tmp2 = nv_rd32(dev, 0x2058) & 0xFFF;
tmp2 |= (tmp & 0x30000000);
nv_wr32(dev, 0x2058, tmp2);
tmp &= ~0x30000000;
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_FETCH, tmp);
nv_wr32(dev, NV04_PFIFO_CACHE1_ENGINE, nv_ri32(dev, fc + 28));
nv_wr32(dev, NV04_PFIFO_CACHE1_PULL1, nv_ri32(dev, fc + 32));
nv_wr32(dev, NV10_PFIFO_CACHE1_ACQUIRE_VALUE, nv_ri32(dev, fc + 36));
tmp = nv_ri32(dev, fc + 40);
nv_wr32(dev, NV10_PFIFO_CACHE1_ACQUIRE_TIMESTAMP, tmp);
nv_wr32(dev, NV10_PFIFO_CACHE1_ACQUIRE_TIMEOUT, nv_ri32(dev, fc + 44));
nv_wr32(dev, NV10_PFIFO_CACHE1_SEMAPHORE, nv_ri32(dev, fc + 48));
nv_wr32(dev, NV10_PFIFO_CACHE1_DMA_SUBROUTINE, nv_ri32(dev, fc + 52));
nv_wr32(dev, NV40_PFIFO_GRCTX_INSTANCE, nv_ri32(dev, fc + 56));
/* Don't clobber the TIMEOUT_ENABLED flag when restoring from RAMFC */
tmp = nv_rd32(dev, NV04_PFIFO_DMA_TIMESLICE) & ~0x1FFFF;
tmp |= nv_ri32(dev, fc + 60) & 0x1FFFF;
nv_wr32(dev, NV04_PFIFO_DMA_TIMESLICE, tmp);
nv_wr32(dev, 0x32e4, nv_ri32(dev, fc + 64));
/* NVIDIA does this next line twice... */
nv_wr32(dev, 0x32e8, nv_ri32(dev, fc + 68));
nv_wr32(dev, 0x2088, nv_ri32(dev, fc + 76));
nv_wr32(dev, 0x3300, nv_ri32(dev, fc + 80));
nv_wr32(dev, NV03_PFIFO_CACHE1_GET, 0);
nv_wr32(dev, NV03_PFIFO_CACHE1_PUT, 0);
}
int
nv40_fifo_load_context(struct nouveau_channel *chan)
{
struct drm_device *dev = chan->dev;
uint32_t tmp;
nv40_fifo_do_load_context(dev, chan->id);
/* Set channel active, and in DMA mode */
nv_wr32(dev, NV03_PFIFO_CACHE1_PUSH1,
NV40_PFIFO_CACHE1_PUSH1_DMA | chan->id);
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_PUSH, 1);
/* Reset DMA_CTL_AT_INFO to INVALID */
tmp = nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_CTL) & ~(1 << 31);
nv_wr32(dev, NV04_PFIFO_CACHE1_DMA_CTL, tmp);
return 0;
}
int
nv40_fifo_unload_context(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_fifo_engine *pfifo = &dev_priv->engine.fifo;
uint32_t fc, tmp;
int chid;
chid = pfifo->channel_id(dev);
if (chid < 0 || chid >= dev_priv->engine.fifo.channels)
return 0;
fc = NV40_RAMFC(chid);
nv_wi32(dev, fc + 0, nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_PUT));
nv_wi32(dev, fc + 4, nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_GET));
nv_wi32(dev, fc + 8, nv_rd32(dev, NV10_PFIFO_CACHE1_REF_CNT));
nv_wi32(dev, fc + 12, nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_INSTANCE));
nv_wi32(dev, fc + 16, nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_DCOUNT));
nv_wi32(dev, fc + 20, nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_STATE));
tmp = nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_FETCH);
tmp |= nv_rd32(dev, 0x2058) & 0x30000000;
nv_wi32(dev, fc + 24, tmp);
nv_wi32(dev, fc + 28, nv_rd32(dev, NV04_PFIFO_CACHE1_ENGINE));
nv_wi32(dev, fc + 32, nv_rd32(dev, NV04_PFIFO_CACHE1_PULL1));
nv_wi32(dev, fc + 36, nv_rd32(dev, NV10_PFIFO_CACHE1_ACQUIRE_VALUE));
tmp = nv_rd32(dev, NV10_PFIFO_CACHE1_ACQUIRE_TIMESTAMP);
nv_wi32(dev, fc + 40, tmp);
nv_wi32(dev, fc + 44, nv_rd32(dev, NV10_PFIFO_CACHE1_ACQUIRE_TIMEOUT));
nv_wi32(dev, fc + 48, nv_rd32(dev, NV10_PFIFO_CACHE1_SEMAPHORE));
/* NVIDIA read 0x3228 first, then write DMA_GET here.. maybe something
* more involved depending on the value of 0x3228?
*/
nv_wi32(dev, fc + 52, nv_rd32(dev, NV04_PFIFO_CACHE1_DMA_GET));
nv_wi32(dev, fc + 56, nv_rd32(dev, NV40_PFIFO_GRCTX_INSTANCE));
nv_wi32(dev, fc + 60, nv_rd32(dev, NV04_PFIFO_DMA_TIMESLICE) & 0x1ffff);
/* No idea what the below is for exactly, ripped from a mmio-trace */
nv_wi32(dev, fc + 64, nv_rd32(dev, NV40_PFIFO_UNK32E4));
/* NVIDIA do this next line twice.. bug? */
nv_wi32(dev, fc + 68, nv_rd32(dev, 0x32e8));
nv_wi32(dev, fc + 76, nv_rd32(dev, 0x2088));
nv_wi32(dev, fc + 80, nv_rd32(dev, 0x3300));
#if 0 /* no real idea which is PUT/GET in UNK_48.. */
tmp = nv_rd32(dev, NV04_PFIFO_CACHE1_GET);
tmp |= (nv_rd32(dev, NV04_PFIFO_CACHE1_PUT) << 16);
nv_wi32(dev, fc + 72, tmp);
#endif
nv40_fifo_do_load_context(dev, pfifo->channels - 1);
nv_wr32(dev, NV03_PFIFO_CACHE1_PUSH1,
NV40_PFIFO_CACHE1_PUSH1_DMA | (pfifo->channels - 1));
return 0;
}
static void
nv40_fifo_init_reset(struct drm_device *dev)
{
int i;
nv_wr32(dev, NV03_PMC_ENABLE,
nv_rd32(dev, NV03_PMC_ENABLE) & ~NV_PMC_ENABLE_PFIFO);
nv_wr32(dev, NV03_PMC_ENABLE,
nv_rd32(dev, NV03_PMC_ENABLE) | NV_PMC_ENABLE_PFIFO);
nv_wr32(dev, 0x003224, 0x000f0078);
nv_wr32(dev, 0x003210, 0x00000000);
nv_wr32(dev, 0x003270, 0x00000000);
nv_wr32(dev, 0x003240, 0x00000000);
nv_wr32(dev, 0x003244, 0x00000000);
nv_wr32(dev, 0x003258, 0x00000000);
nv_wr32(dev, 0x002504, 0x00000000);
for (i = 0; i < 16; i++)
nv_wr32(dev, 0x002510 + (i * 4), 0x00000000);
nv_wr32(dev, 0x00250c, 0x0000ffff);
nv_wr32(dev, 0x002048, 0x00000000);
nv_wr32(dev, 0x003228, 0x00000000);
nv_wr32(dev, 0x0032e8, 0x00000000);
nv_wr32(dev, 0x002410, 0x00000000);
nv_wr32(dev, 0x002420, 0x00000000);
nv_wr32(dev, 0x002058, 0x00000001);
nv_wr32(dev, 0x00221c, 0x00000000);
/* something with 0x2084, read/modify/write, no change */
nv_wr32(dev, 0x002040, 0x000000ff);
nv_wr32(dev, 0x002500, 0x00000000);
nv_wr32(dev, 0x003200, 0x00000000);
nv_wr32(dev, NV04_PFIFO_DMA_TIMESLICE, 0x2101ffff);
}
static void
nv40_fifo_init_ramxx(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
nv_wr32(dev, NV03_PFIFO_RAMHT, (0x03 << 24) /* search 128 */ |
((dev_priv->ramht->bits - 9) << 16) |
(dev_priv->ramht->gpuobj->pinst >> 8));
nv_wr32(dev, NV03_PFIFO_RAMRO, dev_priv->ramro->pinst >> 8);
switch (dev_priv->chipset) {
case 0x47:
case 0x49:
case 0x4b:
nv_wr32(dev, 0x2230, 1);
break;
default:
break;
}
switch (dev_priv->chipset) {
case 0x40:
case 0x41:
case 0x42:
case 0x43:
case 0x45:
case 0x47:
case 0x48:
case 0x49:
case 0x4b:
nv_wr32(dev, NV40_PFIFO_RAMFC, 0x30002);
break;
default:
nv_wr32(dev, 0x2230, 0);
nv_wr32(dev, NV40_PFIFO_RAMFC,
((dev_priv->vram_size - 512 * 1024 +
dev_priv->ramfc->pinst) >> 16) | (3 << 16));
break;
}
}
static void
nv40_fifo_init_intr(struct drm_device *dev)
{
nv_wr32(dev, 0x002100, 0xffffffff);
nv_wr32(dev, 0x002140, 0xffffffff);
}
int
nv40_fifo_init(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_fifo_engine *pfifo = &dev_priv->engine.fifo;
int i;
nv40_fifo_init_reset(dev);
nv40_fifo_init_ramxx(dev);
nv40_fifo_do_load_context(dev, pfifo->channels - 1);
nv_wr32(dev, NV03_PFIFO_CACHE1_PUSH1, pfifo->channels - 1);
nv40_fifo_init_intr(dev);
pfifo->enable(dev);
pfifo->reassign(dev, true);
for (i = 0; i < dev_priv->engine.fifo.channels; i++) {
if (dev_priv->fifos[i]) {
uint32_t mode = nv_rd32(dev, NV04_PFIFO_MODE);
nv_wr32(dev, NV04_PFIFO_MODE, mode | (1 << i));
}
}
return 0;
}
| gpl-2.0 |
nicolaerosia/linux-bn-omap4 | drivers/clk/imx/clk-imx25.c | 568 | 13970 | /*
* Copyright (C) 2009 by Sascha Hauer, Pengutronix
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/clkdev.h>
#include <linux/err.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include "clk.h"
#define CCM_MPCTL 0x00
#define CCM_UPCTL 0x04
#define CCM_CCTL 0x08
#define CCM_CGCR0 0x0C
#define CCM_CGCR1 0x10
#define CCM_CGCR2 0x14
#define CCM_PCDR0 0x18
#define CCM_PCDR1 0x1C
#define CCM_PCDR2 0x20
#define CCM_PCDR3 0x24
#define CCM_RCSR 0x28
#define CCM_CRDR 0x2C
#define CCM_DCVR0 0x30
#define CCM_DCVR1 0x34
#define CCM_DCVR2 0x38
#define CCM_DCVR3 0x3c
#define CCM_LTR0 0x40
#define CCM_LTR1 0x44
#define CCM_LTR2 0x48
#define CCM_LTR3 0x4c
#define CCM_MCR 0x64
#define ccm(x) (ccm_base + (x))
static struct clk_onecell_data clk_data;
static const char *cpu_sel_clks[] = { "mpll", "mpll_cpu_3_4", };
static const char *per_sel_clks[] = { "ahb", "upll", };
static const char *cko_sel_clks[] = { "dummy", "osc", "cpu", "ahb",
"ipg", "dummy", "dummy", "dummy",
"dummy", "dummy", "per0", "per2",
"per13", "per14", "usbotg_ahb", "dummy",};
enum mx25_clks {
dummy, osc, mpll, upll, mpll_cpu_3_4, cpu_sel, cpu, ahb, usb_div, ipg,
per0_sel, per1_sel, per2_sel, per3_sel, per4_sel, per5_sel, per6_sel,
per7_sel, per8_sel, per9_sel, per10_sel, per11_sel, per12_sel,
per13_sel, per14_sel, per15_sel, per0, per1, per2, per3, per4, per5,
per6, per7, per8, per9, per10, per11, per12, per13, per14, per15,
csi_ipg_per, epit_ipg_per, esai_ipg_per, esdhc1_ipg_per, esdhc2_ipg_per,
gpt_ipg_per, i2c_ipg_per, lcdc_ipg_per, nfc_ipg_per, owire_ipg_per,
pwm_ipg_per, sim1_ipg_per, sim2_ipg_per, ssi1_ipg_per, ssi2_ipg_per,
uart_ipg_per, ata_ahb, reserved1, csi_ahb, emi_ahb, esai_ahb, esdhc1_ahb,
esdhc2_ahb, fec_ahb, lcdc_ahb, rtic_ahb, sdma_ahb, slcdc_ahb, usbotg_ahb,
reserved2, reserved3, reserved4, reserved5, can1_ipg, can2_ipg, csi_ipg,
cspi1_ipg, cspi2_ipg, cspi3_ipg, dryice_ipg, ect_ipg, epit1_ipg, epit2_ipg,
reserved6, esdhc1_ipg, esdhc2_ipg, fec_ipg, reserved7, reserved8, reserved9,
gpt1_ipg, gpt2_ipg, gpt3_ipg, gpt4_ipg, reserved10, reserved11, reserved12,
iim_ipg, reserved13, reserved14, kpp_ipg, lcdc_ipg, reserved15, pwm1_ipg,
pwm2_ipg, pwm3_ipg, pwm4_ipg, rngb_ipg, reserved16, scc_ipg, sdma_ipg,
sim1_ipg, sim2_ipg, slcdc_ipg, spba_ipg, ssi1_ipg, ssi2_ipg, tsc_ipg,
uart1_ipg, uart2_ipg, uart3_ipg, uart4_ipg, uart5_ipg, reserved17,
wdt_ipg, cko_div, cko_sel, cko, clk_max
};
static struct clk *clk[clk_max];
static struct clk ** const uart_clks[] __initconst = {
&clk[uart_ipg_per],
&clk[uart1_ipg],
&clk[uart2_ipg],
&clk[uart3_ipg],
&clk[uart4_ipg],
&clk[uart5_ipg],
NULL
};
static int __init __mx25_clocks_init(void __iomem *ccm_base)
{
BUG_ON(!ccm_base);
clk[dummy] = imx_clk_fixed("dummy", 0);
clk[mpll] = imx_clk_pllv1(IMX_PLLV1_IMX25, "mpll", "osc", ccm(CCM_MPCTL));
clk[upll] = imx_clk_pllv1(IMX_PLLV1_IMX25, "upll", "osc", ccm(CCM_UPCTL));
clk[mpll_cpu_3_4] = imx_clk_fixed_factor("mpll_cpu_3_4", "mpll", 3, 4);
clk[cpu_sel] = imx_clk_mux("cpu_sel", ccm(CCM_CCTL), 14, 1, cpu_sel_clks, ARRAY_SIZE(cpu_sel_clks));
clk[cpu] = imx_clk_divider("cpu", "cpu_sel", ccm(CCM_CCTL), 30, 2);
clk[ahb] = imx_clk_divider("ahb", "cpu", ccm(CCM_CCTL), 28, 2);
clk[usb_div] = imx_clk_divider("usb_div", "upll", ccm(CCM_CCTL), 16, 6);
clk[ipg] = imx_clk_fixed_factor("ipg", "ahb", 1, 2);
clk[per0_sel] = imx_clk_mux("per0_sel", ccm(CCM_MCR), 0, 1, per_sel_clks, ARRAY_SIZE(per_sel_clks));
clk[per1_sel] = imx_clk_mux("per1_sel", ccm(CCM_MCR), 1, 1, per_sel_clks, ARRAY_SIZE(per_sel_clks));
clk[per2_sel] = imx_clk_mux("per2_sel", ccm(CCM_MCR), 2, 1, per_sel_clks, ARRAY_SIZE(per_sel_clks));
clk[per3_sel] = imx_clk_mux("per3_sel", ccm(CCM_MCR), 3, 1, per_sel_clks, ARRAY_SIZE(per_sel_clks));
clk[per4_sel] = imx_clk_mux("per4_sel", ccm(CCM_MCR), 4, 1, per_sel_clks, ARRAY_SIZE(per_sel_clks));
clk[per5_sel] = imx_clk_mux("per5_sel", ccm(CCM_MCR), 5, 1, per_sel_clks, ARRAY_SIZE(per_sel_clks));
clk[per6_sel] = imx_clk_mux("per6_sel", ccm(CCM_MCR), 6, 1, per_sel_clks, ARRAY_SIZE(per_sel_clks));
clk[per7_sel] = imx_clk_mux("per7_sel", ccm(CCM_MCR), 7, 1, per_sel_clks, ARRAY_SIZE(per_sel_clks));
clk[per8_sel] = imx_clk_mux("per8_sel", ccm(CCM_MCR), 8, 1, per_sel_clks, ARRAY_SIZE(per_sel_clks));
clk[per9_sel] = imx_clk_mux("per9_sel", ccm(CCM_MCR), 9, 1, per_sel_clks, ARRAY_SIZE(per_sel_clks));
clk[per10_sel] = imx_clk_mux("per10_sel", ccm(CCM_MCR), 10, 1, per_sel_clks, ARRAY_SIZE(per_sel_clks));
clk[per11_sel] = imx_clk_mux("per11_sel", ccm(CCM_MCR), 11, 1, per_sel_clks, ARRAY_SIZE(per_sel_clks));
clk[per12_sel] = imx_clk_mux("per12_sel", ccm(CCM_MCR), 12, 1, per_sel_clks, ARRAY_SIZE(per_sel_clks));
clk[per13_sel] = imx_clk_mux("per13_sel", ccm(CCM_MCR), 13, 1, per_sel_clks, ARRAY_SIZE(per_sel_clks));
clk[per14_sel] = imx_clk_mux("per14_sel", ccm(CCM_MCR), 14, 1, per_sel_clks, ARRAY_SIZE(per_sel_clks));
clk[per15_sel] = imx_clk_mux("per15_sel", ccm(CCM_MCR), 15, 1, per_sel_clks, ARRAY_SIZE(per_sel_clks));
clk[cko_div] = imx_clk_divider("cko_div", "cko_sel", ccm(CCM_MCR), 24, 6);
clk[cko_sel] = imx_clk_mux("cko_sel", ccm(CCM_MCR), 20, 4, cko_sel_clks, ARRAY_SIZE(cko_sel_clks));
clk[cko] = imx_clk_gate("cko", "cko_div", ccm(CCM_MCR), 30);
clk[per0] = imx_clk_divider("per0", "per0_sel", ccm(CCM_PCDR0), 0, 6);
clk[per1] = imx_clk_divider("per1", "per1_sel", ccm(CCM_PCDR0), 8, 6);
clk[per2] = imx_clk_divider("per2", "per2_sel", ccm(CCM_PCDR0), 16, 6);
clk[per3] = imx_clk_divider("per3", "per3_sel", ccm(CCM_PCDR0), 24, 6);
clk[per4] = imx_clk_divider("per4", "per4_sel", ccm(CCM_PCDR1), 0, 6);
clk[per5] = imx_clk_divider("per5", "per5_sel", ccm(CCM_PCDR1), 8, 6);
clk[per6] = imx_clk_divider("per6", "per6_sel", ccm(CCM_PCDR1), 16, 6);
clk[per7] = imx_clk_divider("per7", "per7_sel", ccm(CCM_PCDR1), 24, 6);
clk[per8] = imx_clk_divider("per8", "per8_sel", ccm(CCM_PCDR2), 0, 6);
clk[per9] = imx_clk_divider("per9", "per9_sel", ccm(CCM_PCDR2), 8, 6);
clk[per10] = imx_clk_divider("per10", "per10_sel", ccm(CCM_PCDR2), 16, 6);
clk[per11] = imx_clk_divider("per11", "per11_sel", ccm(CCM_PCDR2), 24, 6);
clk[per12] = imx_clk_divider("per12", "per12_sel", ccm(CCM_PCDR3), 0, 6);
clk[per13] = imx_clk_divider("per13", "per13_sel", ccm(CCM_PCDR3), 8, 6);
clk[per14] = imx_clk_divider("per14", "per14_sel", ccm(CCM_PCDR3), 16, 6);
clk[per15] = imx_clk_divider("per15", "per15_sel", ccm(CCM_PCDR3), 24, 6);
clk[csi_ipg_per] = imx_clk_gate("csi_ipg_per", "per0", ccm(CCM_CGCR0), 0);
clk[epit_ipg_per] = imx_clk_gate("epit_ipg_per", "per1", ccm(CCM_CGCR0), 1);
clk[esai_ipg_per] = imx_clk_gate("esai_ipg_per", "per2", ccm(CCM_CGCR0), 2);
clk[esdhc1_ipg_per] = imx_clk_gate("esdhc1_ipg_per", "per3", ccm(CCM_CGCR0), 3);
clk[esdhc2_ipg_per] = imx_clk_gate("esdhc2_ipg_per", "per4", ccm(CCM_CGCR0), 4);
clk[gpt_ipg_per] = imx_clk_gate("gpt_ipg_per", "per5", ccm(CCM_CGCR0), 5);
clk[i2c_ipg_per] = imx_clk_gate("i2c_ipg_per", "per6", ccm(CCM_CGCR0), 6);
clk[lcdc_ipg_per] = imx_clk_gate("lcdc_ipg_per", "per7", ccm(CCM_CGCR0), 7);
clk[nfc_ipg_per] = imx_clk_gate("nfc_ipg_per", "per8", ccm(CCM_CGCR0), 8);
clk[owire_ipg_per] = imx_clk_gate("owire_ipg_per", "per9", ccm(CCM_CGCR0), 9);
clk[pwm_ipg_per] = imx_clk_gate("pwm_ipg_per", "per10", ccm(CCM_CGCR0), 10);
clk[sim1_ipg_per] = imx_clk_gate("sim1_ipg_per", "per11", ccm(CCM_CGCR0), 11);
clk[sim2_ipg_per] = imx_clk_gate("sim2_ipg_per", "per12", ccm(CCM_CGCR0), 12);
clk[ssi1_ipg_per] = imx_clk_gate("ssi1_ipg_per", "per13", ccm(CCM_CGCR0), 13);
clk[ssi2_ipg_per] = imx_clk_gate("ssi2_ipg_per", "per14", ccm(CCM_CGCR0), 14);
clk[uart_ipg_per] = imx_clk_gate("uart_ipg_per", "per15", ccm(CCM_CGCR0), 15);
clk[ata_ahb] = imx_clk_gate("ata_ahb", "ahb", ccm(CCM_CGCR0), 16);
/* CCM_CGCR0(17): reserved */
clk[csi_ahb] = imx_clk_gate("csi_ahb", "ahb", ccm(CCM_CGCR0), 18);
clk[emi_ahb] = imx_clk_gate("emi_ahb", "ahb", ccm(CCM_CGCR0), 19);
clk[esai_ahb] = imx_clk_gate("esai_ahb", "ahb", ccm(CCM_CGCR0), 20);
clk[esdhc1_ahb] = imx_clk_gate("esdhc1_ahb", "ahb", ccm(CCM_CGCR0), 21);
clk[esdhc2_ahb] = imx_clk_gate("esdhc2_ahb", "ahb", ccm(CCM_CGCR0), 22);
clk[fec_ahb] = imx_clk_gate("fec_ahb", "ahb", ccm(CCM_CGCR0), 23);
clk[lcdc_ahb] = imx_clk_gate("lcdc_ahb", "ahb", ccm(CCM_CGCR0), 24);
clk[rtic_ahb] = imx_clk_gate("rtic_ahb", "ahb", ccm(CCM_CGCR0), 25);
clk[sdma_ahb] = imx_clk_gate("sdma_ahb", "ahb", ccm(CCM_CGCR0), 26);
clk[slcdc_ahb] = imx_clk_gate("slcdc_ahb", "ahb", ccm(CCM_CGCR0), 27);
clk[usbotg_ahb] = imx_clk_gate("usbotg_ahb", "ahb", ccm(CCM_CGCR0), 28);
/* CCM_CGCR0(29-31): reserved */
/* CCM_CGCR1(0): reserved in datasheet, used as audmux in FSL kernel */
clk[can1_ipg] = imx_clk_gate("can1_ipg", "ipg", ccm(CCM_CGCR1), 2);
clk[can2_ipg] = imx_clk_gate("can2_ipg", "ipg", ccm(CCM_CGCR1), 3);
clk[csi_ipg] = imx_clk_gate("csi_ipg", "ipg", ccm(CCM_CGCR1), 4);
clk[cspi1_ipg] = imx_clk_gate("cspi1_ipg", "ipg", ccm(CCM_CGCR1), 5);
clk[cspi2_ipg] = imx_clk_gate("cspi2_ipg", "ipg", ccm(CCM_CGCR1), 6);
clk[cspi3_ipg] = imx_clk_gate("cspi3_ipg", "ipg", ccm(CCM_CGCR1), 7);
clk[dryice_ipg] = imx_clk_gate("dryice_ipg", "ipg", ccm(CCM_CGCR1), 8);
clk[ect_ipg] = imx_clk_gate("ect_ipg", "ipg", ccm(CCM_CGCR1), 9);
clk[epit1_ipg] = imx_clk_gate("epit1_ipg", "ipg", ccm(CCM_CGCR1), 10);
clk[epit2_ipg] = imx_clk_gate("epit2_ipg", "ipg", ccm(CCM_CGCR1), 11);
/* CCM_CGCR1(12): reserved in datasheet, used as esai in FSL kernel */
clk[esdhc1_ipg] = imx_clk_gate("esdhc1_ipg", "ipg", ccm(CCM_CGCR1), 13);
clk[esdhc2_ipg] = imx_clk_gate("esdhc2_ipg", "ipg", ccm(CCM_CGCR1), 14);
clk[fec_ipg] = imx_clk_gate("fec_ipg", "ipg", ccm(CCM_CGCR1), 15);
/* CCM_CGCR1(16): reserved in datasheet, used as gpio1 in FSL kernel */
/* CCM_CGCR1(17): reserved in datasheet, used as gpio2 in FSL kernel */
/* CCM_CGCR1(18): reserved in datasheet, used as gpio3 in FSL kernel */
clk[gpt1_ipg] = imx_clk_gate("gpt1_ipg", "ipg", ccm(CCM_CGCR1), 19);
clk[gpt2_ipg] = imx_clk_gate("gpt2_ipg", "ipg", ccm(CCM_CGCR1), 20);
clk[gpt3_ipg] = imx_clk_gate("gpt3_ipg", "ipg", ccm(CCM_CGCR1), 21);
clk[gpt4_ipg] = imx_clk_gate("gpt4_ipg", "ipg", ccm(CCM_CGCR1), 22);
/* CCM_CGCR1(23): reserved in datasheet, used as i2c1 in FSL kernel */
/* CCM_CGCR1(24): reserved in datasheet, used as i2c2 in FSL kernel */
/* CCM_CGCR1(25): reserved in datasheet, used as i2c3 in FSL kernel */
clk[iim_ipg] = imx_clk_gate("iim_ipg", "ipg", ccm(CCM_CGCR1), 26);
/* CCM_CGCR1(27): reserved in datasheet, used as iomuxc in FSL kernel */
/* CCM_CGCR1(28): reserved in datasheet, used as kpp in FSL kernel */
clk[kpp_ipg] = imx_clk_gate("kpp_ipg", "ipg", ccm(CCM_CGCR1), 28);
clk[lcdc_ipg] = imx_clk_gate("lcdc_ipg", "ipg", ccm(CCM_CGCR1), 29);
/* CCM_CGCR1(30): reserved in datasheet, used as owire in FSL kernel */
clk[pwm1_ipg] = imx_clk_gate("pwm1_ipg", "ipg", ccm(CCM_CGCR1), 31);
clk[pwm2_ipg] = imx_clk_gate("pwm2_ipg", "ipg", ccm(CCM_CGCR2), 0);
clk[pwm3_ipg] = imx_clk_gate("pwm3_ipg", "ipg", ccm(CCM_CGCR2), 1);
clk[pwm4_ipg] = imx_clk_gate("pwm4_ipg", "ipg", ccm(CCM_CGCR2), 2);
clk[rngb_ipg] = imx_clk_gate("rngb_ipg", "ipg", ccm(CCM_CGCR2), 3);
/* CCM_CGCR2(4): reserved in datasheet, used as rtic in FSL kernel */
clk[scc_ipg] = imx_clk_gate("scc_ipg", "ipg", ccm(CCM_CGCR2), 5);
clk[sdma_ipg] = imx_clk_gate("sdma_ipg", "ipg", ccm(CCM_CGCR2), 6);
clk[sim1_ipg] = imx_clk_gate("sim1_ipg", "ipg", ccm(CCM_CGCR2), 7);
clk[sim2_ipg] = imx_clk_gate("sim2_ipg", "ipg", ccm(CCM_CGCR2), 8);
clk[slcdc_ipg] = imx_clk_gate("slcdc_ipg", "ipg", ccm(CCM_CGCR2), 9);
clk[spba_ipg] = imx_clk_gate("spba_ipg", "ipg", ccm(CCM_CGCR2), 10);
clk[ssi1_ipg] = imx_clk_gate("ssi1_ipg", "ipg", ccm(CCM_CGCR2), 11);
clk[ssi2_ipg] = imx_clk_gate("ssi2_ipg", "ipg", ccm(CCM_CGCR2), 12);
clk[tsc_ipg] = imx_clk_gate("tsc_ipg", "ipg", ccm(CCM_CGCR2), 13);
clk[uart1_ipg] = imx_clk_gate("uart1_ipg", "ipg", ccm(CCM_CGCR2), 14);
clk[uart2_ipg] = imx_clk_gate("uart2_ipg", "ipg", ccm(CCM_CGCR2), 15);
clk[uart3_ipg] = imx_clk_gate("uart3_ipg", "ipg", ccm(CCM_CGCR2), 16);
clk[uart4_ipg] = imx_clk_gate("uart4_ipg", "ipg", ccm(CCM_CGCR2), 17);
clk[uart5_ipg] = imx_clk_gate("uart5_ipg", "ipg", ccm(CCM_CGCR2), 18);
/* CCM_CGCR2(19): reserved in datasheet, but used as wdt in FSL kernel */
clk[wdt_ipg] = imx_clk_gate("wdt_ipg", "ipg", ccm(CCM_CGCR2), 19);
imx_check_clocks(clk, ARRAY_SIZE(clk));
clk_prepare_enable(clk[emi_ahb]);
/* Clock source for gpt must be derived from AHB */
clk_set_parent(clk[per5_sel], clk[ahb]);
/*
* Let's initially set up CLKO parent as ipg, since this configuration
* is used on some imx25 board designs to clock the audio codec.
*/
clk_set_parent(clk[cko_sel], clk[ipg]);
imx_register_uart_clocks(uart_clks);
return 0;
}
static void __init mx25_clocks_init_dt(struct device_node *np)
{
void __iomem *ccm;
ccm = of_iomap(np, 0);
__mx25_clocks_init(ccm);
clk_data.clks = clk;
clk_data.clk_num = ARRAY_SIZE(clk);
of_clk_add_provider(np, of_clk_src_onecell_get, &clk_data);
}
CLK_OF_DECLARE(imx25_ccm, "fsl,imx25-ccm", mx25_clocks_init_dt);
| gpl-2.0 |
chunyeow/ath | drivers/infiniband/core/uverbs_marshall.c | 1336 | 5428 | /*
* Copyright (c) 2005 Intel Corporation. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/export.h>
#include <rdma/ib_marshall.h>
void ib_copy_ah_attr_to_user(struct ib_uverbs_ah_attr *dst,
struct ib_ah_attr *src)
{
memcpy(dst->grh.dgid, src->grh.dgid.raw, sizeof src->grh.dgid);
dst->grh.flow_label = src->grh.flow_label;
dst->grh.sgid_index = src->grh.sgid_index;
dst->grh.hop_limit = src->grh.hop_limit;
dst->grh.traffic_class = src->grh.traffic_class;
memset(&dst->grh.reserved, 0, sizeof(dst->grh.reserved));
dst->dlid = src->dlid;
dst->sl = src->sl;
dst->src_path_bits = src->src_path_bits;
dst->static_rate = src->static_rate;
dst->is_global = src->ah_flags & IB_AH_GRH ? 1 : 0;
dst->port_num = src->port_num;
dst->reserved = 0;
}
EXPORT_SYMBOL(ib_copy_ah_attr_to_user);
void ib_copy_qp_attr_to_user(struct ib_uverbs_qp_attr *dst,
struct ib_qp_attr *src)
{
dst->qp_state = src->qp_state;
dst->cur_qp_state = src->cur_qp_state;
dst->path_mtu = src->path_mtu;
dst->path_mig_state = src->path_mig_state;
dst->qkey = src->qkey;
dst->rq_psn = src->rq_psn;
dst->sq_psn = src->sq_psn;
dst->dest_qp_num = src->dest_qp_num;
dst->qp_access_flags = src->qp_access_flags;
dst->max_send_wr = src->cap.max_send_wr;
dst->max_recv_wr = src->cap.max_recv_wr;
dst->max_send_sge = src->cap.max_send_sge;
dst->max_recv_sge = src->cap.max_recv_sge;
dst->max_inline_data = src->cap.max_inline_data;
ib_copy_ah_attr_to_user(&dst->ah_attr, &src->ah_attr);
ib_copy_ah_attr_to_user(&dst->alt_ah_attr, &src->alt_ah_attr);
dst->pkey_index = src->pkey_index;
dst->alt_pkey_index = src->alt_pkey_index;
dst->en_sqd_async_notify = src->en_sqd_async_notify;
dst->sq_draining = src->sq_draining;
dst->max_rd_atomic = src->max_rd_atomic;
dst->max_dest_rd_atomic = src->max_dest_rd_atomic;
dst->min_rnr_timer = src->min_rnr_timer;
dst->port_num = src->port_num;
dst->timeout = src->timeout;
dst->retry_cnt = src->retry_cnt;
dst->rnr_retry = src->rnr_retry;
dst->alt_port_num = src->alt_port_num;
dst->alt_timeout = src->alt_timeout;
memset(dst->reserved, 0, sizeof(dst->reserved));
}
EXPORT_SYMBOL(ib_copy_qp_attr_to_user);
void ib_copy_path_rec_to_user(struct ib_user_path_rec *dst,
struct ib_sa_path_rec *src)
{
memcpy(dst->dgid, src->dgid.raw, sizeof src->dgid);
memcpy(dst->sgid, src->sgid.raw, sizeof src->sgid);
dst->dlid = src->dlid;
dst->slid = src->slid;
dst->raw_traffic = src->raw_traffic;
dst->flow_label = src->flow_label;
dst->hop_limit = src->hop_limit;
dst->traffic_class = src->traffic_class;
dst->reversible = src->reversible;
dst->numb_path = src->numb_path;
dst->pkey = src->pkey;
dst->sl = src->sl;
dst->mtu_selector = src->mtu_selector;
dst->mtu = src->mtu;
dst->rate_selector = src->rate_selector;
dst->rate = src->rate;
dst->packet_life_time = src->packet_life_time;
dst->preference = src->preference;
dst->packet_life_time_selector = src->packet_life_time_selector;
}
EXPORT_SYMBOL(ib_copy_path_rec_to_user);
void ib_copy_path_rec_from_user(struct ib_sa_path_rec *dst,
struct ib_user_path_rec *src)
{
memcpy(dst->dgid.raw, src->dgid, sizeof dst->dgid);
memcpy(dst->sgid.raw, src->sgid, sizeof dst->sgid);
dst->dlid = src->dlid;
dst->slid = src->slid;
dst->raw_traffic = src->raw_traffic;
dst->flow_label = src->flow_label;
dst->hop_limit = src->hop_limit;
dst->traffic_class = src->traffic_class;
dst->reversible = src->reversible;
dst->numb_path = src->numb_path;
dst->pkey = src->pkey;
dst->sl = src->sl;
dst->mtu_selector = src->mtu_selector;
dst->mtu = src->mtu;
dst->rate_selector = src->rate_selector;
dst->rate = src->rate;
dst->packet_life_time = src->packet_life_time;
dst->preference = src->preference;
dst->packet_life_time_selector = src->packet_life_time_selector;
memset(dst->smac, 0, sizeof(dst->smac));
memset(dst->dmac, 0, sizeof(dst->dmac));
dst->vlan_id = 0xffff;
}
EXPORT_SYMBOL(ib_copy_path_rec_from_user);
| gpl-2.0 |
andrea9a/oslab | arch/m32r/mm/discontig.c | 2360 | 3957 | /*
* linux/arch/m32r/mm/discontig.c
*
* Discontig memory support
*
* Copyright (c) 2003 Hitoshi Yamamoto
*/
#include <linux/mm.h>
#include <linux/bootmem.h>
#include <linux/mmzone.h>
#include <linux/initrd.h>
#include <linux/nodemask.h>
#include <linux/module.h>
#include <linux/pfn.h>
#include <asm/setup.h>
extern char _end[];
struct pglist_data *node_data[MAX_NUMNODES];
EXPORT_SYMBOL(node_data);
pg_data_t m32r_node_data[MAX_NUMNODES];
/* Memory profile */
typedef struct {
unsigned long start_pfn;
unsigned long pages;
unsigned long holes;
unsigned long free_pfn;
} mem_prof_t;
static mem_prof_t mem_prof[MAX_NUMNODES];
extern unsigned long memory_start;
extern unsigned long memory_end;
static void __init mem_prof_init(void)
{
unsigned long start_pfn, holes, free_pfn;
const unsigned long zone_alignment = 1UL << (MAX_ORDER - 1);
unsigned long ul;
mem_prof_t *mp;
/* Node#0 SDRAM */
mp = &mem_prof[0];
mp->start_pfn = PFN_UP(CONFIG_MEMORY_START);
mp->pages = PFN_DOWN(memory_end - memory_start);
mp->holes = 0;
mp->free_pfn = PFN_UP(__pa(_end));
/* Node#1 internal SRAM */
mp = &mem_prof[1];
start_pfn = free_pfn = PFN_UP(CONFIG_IRAM_START);
holes = 0;
if (start_pfn & (zone_alignment - 1)) {
ul = zone_alignment;
while (start_pfn >= ul)
ul += zone_alignment;
start_pfn = ul - zone_alignment;
holes = free_pfn - start_pfn;
}
mp->start_pfn = start_pfn;
mp->pages = PFN_DOWN(CONFIG_IRAM_SIZE) + holes;
mp->holes = holes;
mp->free_pfn = PFN_UP(CONFIG_IRAM_START);
}
unsigned long __init setup_memory(void)
{
unsigned long bootmap_size;
unsigned long min_pfn;
int nid;
mem_prof_t *mp;
max_low_pfn = 0;
min_low_pfn = -1;
mem_prof_init();
for_each_online_node(nid) {
mp = &mem_prof[nid];
NODE_DATA(nid)=(pg_data_t *)&m32r_node_data[nid];
NODE_DATA(nid)->bdata = &bootmem_node_data[nid];
min_pfn = mp->start_pfn;
max_pfn = mp->start_pfn + mp->pages;
bootmap_size = init_bootmem_node(NODE_DATA(nid), mp->free_pfn,
mp->start_pfn, max_pfn);
free_bootmem_node(NODE_DATA(nid), PFN_PHYS(mp->start_pfn),
PFN_PHYS(mp->pages));
reserve_bootmem_node(NODE_DATA(nid), PFN_PHYS(mp->start_pfn),
PFN_PHYS(mp->free_pfn - mp->start_pfn) + bootmap_size,
BOOTMEM_DEFAULT);
if (max_low_pfn < max_pfn)
max_low_pfn = max_pfn;
if (min_low_pfn > min_pfn)
min_low_pfn = min_pfn;
}
#ifdef CONFIG_BLK_DEV_INITRD
if (LOADER_TYPE && INITRD_START) {
if (INITRD_START + INITRD_SIZE <= PFN_PHYS(max_low_pfn)) {
reserve_bootmem_node(NODE_DATA(0), INITRD_START,
INITRD_SIZE, BOOTMEM_DEFAULT);
initrd_start = INITRD_START + PAGE_OFFSET;
initrd_end = initrd_start + INITRD_SIZE;
printk("initrd:start[%08lx],size[%08lx]\n",
initrd_start, INITRD_SIZE);
} else {
printk("initrd extends beyond end of memory "
"(0x%08lx > 0x%08llx)\ndisabling initrd\n",
INITRD_START + INITRD_SIZE,
(unsigned long long)PFN_PHYS(max_low_pfn));
initrd_start = 0;
}
}
#endif /* CONFIG_BLK_DEV_INITRD */
return max_low_pfn;
}
#define START_PFN(nid) (NODE_DATA(nid)->bdata->node_min_pfn)
#define MAX_LOW_PFN(nid) (NODE_DATA(nid)->bdata->node_low_pfn)
void __init zone_sizes_init(void)
{
unsigned long zones_size[MAX_NR_ZONES], zholes_size[MAX_NR_ZONES];
unsigned long low, start_pfn;
int nid, i;
mem_prof_t *mp;
for_each_online_node(nid) {
mp = &mem_prof[nid];
for (i = 0 ; i < MAX_NR_ZONES ; i++) {
zones_size[i] = 0;
zholes_size[i] = 0;
}
start_pfn = START_PFN(nid);
low = MAX_LOW_PFN(nid);
zones_size[ZONE_DMA] = low - start_pfn;
zholes_size[ZONE_DMA] = mp->holes;
node_set_state(nid, N_NORMAL_MEMORY);
free_area_init_node(nid, zones_size, start_pfn, zholes_size);
}
/*
* For test
* Use all area of internal RAM.
* see __alloc_pages()
*/
NODE_DATA(1)->node_zones->watermark[WMARK_MIN] = 0;
NODE_DATA(1)->node_zones->watermark[WMARK_LOW] = 0;
NODE_DATA(1)->node_zones->watermark[WMARK_HIGH] = 0;
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.