repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
jamison904/android_kernel_samsung_hlte | kernel/kallsyms.c | 4044 | 15090 | /*
* kallsyms.c: in-kernel printing of symbolic oopses and stack traces.
*
* Rewritten and vastly simplified by Rusty Russell for in-kernel
* module loader:
* Copyright 2002 Rusty Russell <rusty@rustcorp.com.au> IBM Corporation
*
* ChangeLog:
*
* (25/Aug/2004) Paulo Marques <pmarques@grupopie.com>
* Changed the compression method from stem compression to "table lookup"
* compression (see scripts/kallsyms.c for a more complete description)
*/
#include <linux/kallsyms.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/seq_file.h>
#include <linux/fs.h>
#include <linux/kdb.h>
#include <linux/err.h>
#include <linux/proc_fs.h>
#include <linux/sched.h> /* for cond_resched */
#include <linux/mm.h>
#include <linux/ctype.h>
#include <linux/slab.h>
#include <asm/sections.h>
#ifdef CONFIG_KALLSYMS_ALL
#define all_var 1
#else
#define all_var 0
#endif
/*
* These will be re-linked against their real values
* during the second link stage.
*/
extern const unsigned long kallsyms_addresses[] __attribute__((weak));
extern const u8 kallsyms_names[] __attribute__((weak));
/*
* Tell the compiler that the count isn't in the small data section if the arch
* has one (eg: FRV).
*/
extern const unsigned long kallsyms_num_syms
__attribute__((weak, section(".rodata")));
extern const u8 kallsyms_token_table[] __attribute__((weak));
extern const u16 kallsyms_token_index[] __attribute__((weak));
extern const unsigned long kallsyms_markers[] __attribute__((weak));
static inline int is_kernel_inittext(unsigned long addr)
{
if (addr >= (unsigned long)_sinittext
&& addr <= (unsigned long)_einittext)
return 1;
return 0;
}
static inline int is_kernel_text(unsigned long addr)
{
if ((addr >= (unsigned long)_stext && addr <= (unsigned long)_etext) ||
arch_is_kernel_text(addr))
return 1;
return in_gate_area_no_mm(addr);
}
static inline int is_kernel(unsigned long addr)
{
if (addr >= (unsigned long)_stext && addr <= (unsigned long)_end)
return 1;
return in_gate_area_no_mm(addr);
}
static int is_ksym_addr(unsigned long addr)
{
if (all_var)
return is_kernel(addr);
return is_kernel_text(addr) || is_kernel_inittext(addr);
}
/*
* Expand a compressed symbol data into the resulting uncompressed string,
* given the offset to where the symbol is in the compressed stream.
*/
static unsigned int kallsyms_expand_symbol(unsigned int off, char *result)
{
int len, skipped_first = 0;
const u8 *tptr, *data;
/* Get the compressed symbol length from the first symbol byte. */
data = &kallsyms_names[off];
len = *data;
data++;
/*
* Update the offset to return the offset for the next symbol on
* the compressed stream.
*/
off += len + 1;
/*
* For every byte on the compressed symbol data, copy the table
* entry for that byte.
*/
while (len) {
tptr = &kallsyms_token_table[kallsyms_token_index[*data]];
data++;
len--;
while (*tptr) {
if (skipped_first) {
*result = *tptr;
result++;
} else
skipped_first = 1;
tptr++;
}
}
*result = '\0';
/* Return to offset to the next symbol. */
return off;
}
/*
* Get symbol type information. This is encoded as a single char at the
* beginning of the symbol name.
*/
static char kallsyms_get_symbol_type(unsigned int off)
{
/*
* Get just the first code, look it up in the token table,
* and return the first char from this token.
*/
return kallsyms_token_table[kallsyms_token_index[kallsyms_names[off + 1]]];
}
/*
* Find the offset on the compressed stream given and index in the
* kallsyms array.
*/
static unsigned int get_symbol_offset(unsigned long pos)
{
const u8 *name;
int i;
/*
* Use the closest marker we have. We have markers every 256 positions,
* so that should be close enough.
*/
name = &kallsyms_names[kallsyms_markers[pos >> 8]];
/*
* Sequentially scan all the symbols up to the point we're searching
* for. Every symbol is stored in a [<len>][<len> bytes of data] format,
* so we just need to add the len to the current pointer for every
* symbol we wish to skip.
*/
for (i = 0; i < (pos & 0xFF); i++)
name = name + (*name) + 1;
return name - kallsyms_names;
}
/* Lookup the address for this symbol. Returns 0 if not found. */
unsigned long kallsyms_lookup_name(const char *name)
{
char namebuf[KSYM_NAME_LEN];
unsigned long i;
unsigned int off;
for (i = 0, off = 0; i < kallsyms_num_syms; i++) {
off = kallsyms_expand_symbol(off, namebuf);
if (strcmp(namebuf, name) == 0)
return kallsyms_addresses[i];
}
return module_kallsyms_lookup_name(name);
}
EXPORT_SYMBOL_GPL(kallsyms_lookup_name);
int kallsyms_on_each_symbol(int (*fn)(void *, const char *, struct module *,
unsigned long),
void *data)
{
char namebuf[KSYM_NAME_LEN];
unsigned long i;
unsigned int off;
int ret;
for (i = 0, off = 0; i < kallsyms_num_syms; i++) {
off = kallsyms_expand_symbol(off, namebuf);
ret = fn(data, namebuf, NULL, kallsyms_addresses[i]);
if (ret != 0)
return ret;
}
return module_kallsyms_on_each_symbol(fn, data);
}
EXPORT_SYMBOL_GPL(kallsyms_on_each_symbol);
static unsigned long get_symbol_pos(unsigned long addr,
unsigned long *symbolsize,
unsigned long *offset)
{
unsigned long symbol_start = 0, symbol_end = 0;
unsigned long i, low, high, mid;
/* This kernel should never had been booted. */
BUG_ON(!kallsyms_addresses);
/* Do a binary search on the sorted kallsyms_addresses array. */
low = 0;
high = kallsyms_num_syms;
while (high - low > 1) {
mid = low + (high - low) / 2;
if (kallsyms_addresses[mid] <= addr)
low = mid;
else
high = mid;
}
/*
* Search for the first aliased symbol. Aliased
* symbols are symbols with the same address.
*/
while (low && kallsyms_addresses[low-1] == kallsyms_addresses[low])
--low;
symbol_start = kallsyms_addresses[low];
/* Search for next non-aliased symbol. */
for (i = low + 1; i < kallsyms_num_syms; i++) {
if (kallsyms_addresses[i] > symbol_start) {
symbol_end = kallsyms_addresses[i];
break;
}
}
/* If we found no next symbol, we use the end of the section. */
if (!symbol_end) {
if (is_kernel_inittext(addr))
symbol_end = (unsigned long)_einittext;
else if (all_var)
symbol_end = (unsigned long)_end;
else
symbol_end = (unsigned long)_etext;
}
if (symbolsize)
*symbolsize = symbol_end - symbol_start;
if (offset)
*offset = addr - symbol_start;
return low;
}
/*
* Lookup an address but don't bother to find any names.
*/
int kallsyms_lookup_size_offset(unsigned long addr, unsigned long *symbolsize,
unsigned long *offset)
{
char namebuf[KSYM_NAME_LEN];
if (is_ksym_addr(addr))
return !!get_symbol_pos(addr, symbolsize, offset);
return !!module_address_lookup(addr, symbolsize, offset, NULL, namebuf);
}
/*
* Lookup an address
* - modname is set to NULL if it's in the kernel.
* - We guarantee that the returned name is valid until we reschedule even if.
* It resides in a module.
* - We also guarantee that modname will be valid until rescheduled.
*/
const char *kallsyms_lookup(unsigned long addr,
unsigned long *symbolsize,
unsigned long *offset,
char **modname, char *namebuf)
{
namebuf[KSYM_NAME_LEN - 1] = 0;
namebuf[0] = 0;
if (is_ksym_addr(addr)) {
unsigned long pos;
pos = get_symbol_pos(addr, symbolsize, offset);
/* Grab name */
kallsyms_expand_symbol(get_symbol_offset(pos), namebuf);
if (modname)
*modname = NULL;
return namebuf;
}
/* See if it's in a module. */
return module_address_lookup(addr, symbolsize, offset, modname,
namebuf);
}
int lookup_symbol_name(unsigned long addr, char *symname)
{
symname[0] = '\0';
symname[KSYM_NAME_LEN - 1] = '\0';
if (is_ksym_addr(addr)) {
unsigned long pos;
pos = get_symbol_pos(addr, NULL, NULL);
/* Grab name */
kallsyms_expand_symbol(get_symbol_offset(pos), symname);
return 0;
}
/* See if it's in a module. */
return lookup_module_symbol_name(addr, symname);
}
int lookup_symbol_attrs(unsigned long addr, unsigned long *size,
unsigned long *offset, char *modname, char *name)
{
name[0] = '\0';
name[KSYM_NAME_LEN - 1] = '\0';
if (is_ksym_addr(addr)) {
unsigned long pos;
pos = get_symbol_pos(addr, size, offset);
/* Grab name */
kallsyms_expand_symbol(get_symbol_offset(pos), name);
modname[0] = '\0';
return 0;
}
/* See if it's in a module. */
return lookup_module_symbol_attrs(addr, size, offset, modname, name);
}
/* Look up a kernel symbol and return it in a text buffer. */
static int __sprint_symbol(char *buffer, unsigned long address,
int symbol_offset, int add_offset)
{
char *modname;
const char *name;
unsigned long offset, size;
int len;
address += symbol_offset;
name = kallsyms_lookup(address, &size, &offset, &modname, buffer);
if (!name)
return sprintf(buffer, "0x%lx", address);
if (name != buffer)
strcpy(buffer, name);
len = strlen(buffer);
offset -= symbol_offset;
if (add_offset)
len += sprintf(buffer + len, "+%#lx/%#lx", offset, size);
if (modname)
len += sprintf(buffer + len, " [%s]", modname);
return len;
}
/**
* sprint_symbol - Look up a kernel symbol and return it in a text buffer
* @buffer: buffer to be stored
* @address: address to lookup
*
* This function looks up a kernel symbol with @address and stores its name,
* offset, size and module name to @buffer if possible. If no symbol was found,
* just saves its @address as is.
*
* This function returns the number of bytes stored in @buffer.
*/
int sprint_symbol(char *buffer, unsigned long address)
{
return __sprint_symbol(buffer, address, 0, 1);
}
EXPORT_SYMBOL_GPL(sprint_symbol);
/**
* sprint_symbol_no_offset - Look up a kernel symbol and return it in a text buffer
* @buffer: buffer to be stored
* @address: address to lookup
*
* This function looks up a kernel symbol with @address and stores its name
* and module name to @buffer if possible. If no symbol was found, just saves
* its @address as is.
*
* This function returns the number of bytes stored in @buffer.
*/
int sprint_symbol_no_offset(char *buffer, unsigned long address)
{
return __sprint_symbol(buffer, address, 0, 0);
}
EXPORT_SYMBOL_GPL(sprint_symbol_no_offset);
/**
* sprint_backtrace - Look up a backtrace symbol and return it in a text buffer
* @buffer: buffer to be stored
* @address: address to lookup
*
* This function is for stack backtrace and does the same thing as
* sprint_symbol() but with modified/decreased @address. If there is a
* tail-call to the function marked "noreturn", gcc optimized out code after
* the call so that the stack-saved return address could point outside of the
* caller. This function ensures that kallsyms will find the original caller
* by decreasing @address.
*
* This function returns the number of bytes stored in @buffer.
*/
int sprint_backtrace(char *buffer, unsigned long address)
{
return __sprint_symbol(buffer, address, -1, 1);
}
/* Look up a kernel symbol and print it to the kernel messages. */
void __print_symbol(const char *fmt, unsigned long address)
{
char buffer[KSYM_SYMBOL_LEN];
sprint_symbol(buffer, address);
printk(fmt, buffer);
}
EXPORT_SYMBOL(__print_symbol);
/* To avoid using get_symbol_offset for every symbol, we carry prefix along. */
struct kallsym_iter {
loff_t pos;
unsigned long value;
unsigned int nameoff; /* If iterating in core kernel symbols. */
char type;
char name[KSYM_NAME_LEN];
char module_name[MODULE_NAME_LEN];
int exported;
};
static int get_ksymbol_mod(struct kallsym_iter *iter)
{
if (module_get_kallsym(iter->pos - kallsyms_num_syms, &iter->value,
&iter->type, iter->name, iter->module_name,
&iter->exported) < 0)
return 0;
return 1;
}
/* Returns space to next name. */
static unsigned long get_ksymbol_core(struct kallsym_iter *iter)
{
unsigned off = iter->nameoff;
iter->module_name[0] = '\0';
iter->value = kallsyms_addresses[iter->pos];
iter->type = kallsyms_get_symbol_type(off);
off = kallsyms_expand_symbol(off, iter->name);
return off - iter->nameoff;
}
static void reset_iter(struct kallsym_iter *iter, loff_t new_pos)
{
iter->name[0] = '\0';
iter->nameoff = get_symbol_offset(new_pos);
iter->pos = new_pos;
}
/* Returns false if pos at or past end of file. */
static int update_iter(struct kallsym_iter *iter, loff_t pos)
{
/* Module symbols can be accessed randomly. */
if (pos >= kallsyms_num_syms) {
iter->pos = pos;
return get_ksymbol_mod(iter);
}
/* If we're not on the desired position, reset to new position. */
if (pos != iter->pos)
reset_iter(iter, pos);
iter->nameoff += get_ksymbol_core(iter);
iter->pos++;
return 1;
}
static void *s_next(struct seq_file *m, void *p, loff_t *pos)
{
(*pos)++;
if (!update_iter(m->private, *pos))
return NULL;
return p;
}
static void *s_start(struct seq_file *m, loff_t *pos)
{
if (!update_iter(m->private, *pos))
return NULL;
return m->private;
}
static void s_stop(struct seq_file *m, void *p)
{
}
static int s_show(struct seq_file *m, void *p)
{
struct kallsym_iter *iter = m->private;
/* Some debugging symbols have no name. Ignore them. */
if (!iter->name[0])
return 0;
if (iter->module_name[0]) {
char type;
/*
* Label it "global" if it is exported,
* "local" if not exported.
*/
type = iter->exported ? toupper(iter->type) :
tolower(iter->type);
seq_printf(m, "%pK %c %s\t[%s]\n", (void *)iter->value,
type, iter->name, iter->module_name);
} else
seq_printf(m, "%pK %c %s\n", (void *)iter->value,
iter->type, iter->name);
return 0;
}
static const struct seq_operations kallsyms_op = {
.start = s_start,
.next = s_next,
.stop = s_stop,
.show = s_show
};
static int kallsyms_open(struct inode *inode, struct file *file)
{
/*
* We keep iterator in m->private, since normal case is to
* s_start from where we left off, so we avoid doing
* using get_symbol_offset for every symbol.
*/
struct kallsym_iter *iter;
int ret;
iter = kmalloc(sizeof(*iter), GFP_KERNEL);
if (!iter)
return -ENOMEM;
reset_iter(iter, 0);
ret = seq_open(file, &kallsyms_op);
if (ret == 0)
((struct seq_file *)file->private_data)->private = iter;
else
kfree(iter);
return ret;
}
#ifdef CONFIG_KGDB_KDB
const char *kdb_walk_kallsyms(loff_t *pos)
{
static struct kallsym_iter kdb_walk_kallsyms_iter;
if (*pos == 0) {
memset(&kdb_walk_kallsyms_iter, 0,
sizeof(kdb_walk_kallsyms_iter));
reset_iter(&kdb_walk_kallsyms_iter, 0);
}
while (1) {
if (!update_iter(&kdb_walk_kallsyms_iter, *pos))
return NULL;
++*pos;
/* Some debugging symbols have no name. Ignore them. */
if (kdb_walk_kallsyms_iter.name[0])
return kdb_walk_kallsyms_iter.name;
}
}
#endif /* CONFIG_KGDB_KDB */
static const struct file_operations kallsyms_operations = {
.open = kallsyms_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_private,
};
static int __init kallsyms_init(void)
{
proc_create("kallsyms", 0444, NULL, &kallsyms_operations);
return 0;
}
device_initcall(kallsyms_init);
| gpl-2.0 |
civato/CivZ-P900-KitKat-SOURCE | arch/arm/mach-omap2/timer.c | 4556 | 13221 | /*
* linux/arch/arm/mach-omap2/timer.c
*
* OMAP2 GP timer support.
*
* Copyright (C) 2009 Nokia Corporation
*
* Update to use new clocksource/clockevent layers
* Author: Kevin Hilman, MontaVista Software, Inc. <source@mvista.com>
* Copyright (C) 2007 MontaVista Software, Inc.
*
* Original driver:
* Copyright (C) 2005 Nokia Corporation
* Author: Paul Mundt <paul.mundt@nokia.com>
* Juha Yrjölä <juha.yrjola@nokia.com>
* OMAP Dual-mode timer framework support by Timo Teras
*
* Some parts based off of TI's 24xx code:
*
* Copyright (C) 2004-2009 Texas Instruments, Inc.
*
* Roughly modelled after the OMAP1 MPU timer code.
* Added OMAP4 support - Santosh Shilimkar <santosh.shilimkar@ti.com>
*
* 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/time.h>
#include <linux/interrupt.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/irq.h>
#include <linux/clocksource.h>
#include <linux/clockchips.h>
#include <linux/slab.h>
#include <asm/mach/time.h>
#include <plat/dmtimer.h>
#include <asm/smp_twd.h>
#include <asm/sched_clock.h>
#include "common.h"
#include <plat/omap_hwmod.h>
#include <plat/omap_device.h>
#include <plat/omap-pm.h>
#include "powerdomain.h"
/* Parent clocks, eventually these will come from the clock framework */
#define OMAP2_MPU_SOURCE "sys_ck"
#define OMAP3_MPU_SOURCE OMAP2_MPU_SOURCE
#define OMAP4_MPU_SOURCE "sys_clkin_ck"
#define OMAP2_32K_SOURCE "func_32k_ck"
#define OMAP3_32K_SOURCE "omap_32k_fck"
#define OMAP4_32K_SOURCE "sys_32k_ck"
#ifdef CONFIG_OMAP_32K_TIMER
#define OMAP2_CLKEV_SOURCE OMAP2_32K_SOURCE
#define OMAP3_CLKEV_SOURCE OMAP3_32K_SOURCE
#define OMAP4_CLKEV_SOURCE OMAP4_32K_SOURCE
#define OMAP3_SECURE_TIMER 12
#else
#define OMAP2_CLKEV_SOURCE OMAP2_MPU_SOURCE
#define OMAP3_CLKEV_SOURCE OMAP3_MPU_SOURCE
#define OMAP4_CLKEV_SOURCE OMAP4_MPU_SOURCE
#define OMAP3_SECURE_TIMER 1
#endif
/* MAX_GPTIMER_ID: number of GPTIMERs on the chip */
#define MAX_GPTIMER_ID 12
static u32 sys_timer_reserved;
/* Clockevent code */
static struct omap_dm_timer clkev;
static struct clock_event_device clockevent_gpt;
static irqreturn_t omap2_gp_timer_interrupt(int irq, void *dev_id)
{
struct clock_event_device *evt = &clockevent_gpt;
__omap_dm_timer_write_status(&clkev, OMAP_TIMER_INT_OVERFLOW);
evt->event_handler(evt);
return IRQ_HANDLED;
}
static struct irqaction omap2_gp_timer_irq = {
.name = "gp timer",
.flags = IRQF_DISABLED | IRQF_TIMER | IRQF_IRQPOLL,
.handler = omap2_gp_timer_interrupt,
};
static int omap2_gp_timer_set_next_event(unsigned long cycles,
struct clock_event_device *evt)
{
__omap_dm_timer_load_start(&clkev, OMAP_TIMER_CTRL_ST,
0xffffffff - cycles, 1);
return 0;
}
static void omap2_gp_timer_set_mode(enum clock_event_mode mode,
struct clock_event_device *evt)
{
u32 period;
__omap_dm_timer_stop(&clkev, 1, clkev.rate);
switch (mode) {
case CLOCK_EVT_MODE_PERIODIC:
period = clkev.rate / HZ;
period -= 1;
/* Looks like we need to first set the load value separately */
__omap_dm_timer_write(&clkev, OMAP_TIMER_LOAD_REG,
0xffffffff - period, 1);
__omap_dm_timer_load_start(&clkev,
OMAP_TIMER_CTRL_AR | OMAP_TIMER_CTRL_ST,
0xffffffff - period, 1);
break;
case CLOCK_EVT_MODE_ONESHOT:
break;
case CLOCK_EVT_MODE_UNUSED:
case CLOCK_EVT_MODE_SHUTDOWN:
case CLOCK_EVT_MODE_RESUME:
break;
}
}
static struct clock_event_device clockevent_gpt = {
.name = "gp timer",
.features = CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT,
.shift = 32,
.set_next_event = omap2_gp_timer_set_next_event,
.set_mode = omap2_gp_timer_set_mode,
};
static int __init omap_dm_timer_init_one(struct omap_dm_timer *timer,
int gptimer_id,
const char *fck_source)
{
char name[10]; /* 10 = sizeof("gptXX_Xck0") */
struct omap_hwmod *oh;
size_t size;
int res = 0;
sprintf(name, "timer%d", gptimer_id);
omap_hwmod_setup_one(name);
oh = omap_hwmod_lookup(name);
if (!oh)
return -ENODEV;
timer->irq = oh->mpu_irqs[0].irq;
timer->phys_base = oh->slaves[0]->addr->pa_start;
size = oh->slaves[0]->addr->pa_end - timer->phys_base;
/* Static mapping, never released */
timer->io_base = ioremap(timer->phys_base, size);
if (!timer->io_base)
return -ENXIO;
/* After the dmtimer is using hwmod these clocks won't be needed */
sprintf(name, "gpt%d_fck", gptimer_id);
timer->fclk = clk_get(NULL, name);
if (IS_ERR(timer->fclk))
return -ENODEV;
sprintf(name, "gpt%d_ick", gptimer_id);
timer->iclk = clk_get(NULL, name);
if (IS_ERR(timer->iclk)) {
clk_put(timer->fclk);
return -ENODEV;
}
omap_hwmod_enable(oh);
sys_timer_reserved |= (1 << (gptimer_id - 1));
if (gptimer_id != 12) {
struct clk *src;
src = clk_get(NULL, fck_source);
if (IS_ERR(src)) {
res = -EINVAL;
} else {
res = __omap_dm_timer_set_source(timer->fclk, src);
if (IS_ERR_VALUE(res))
pr_warning("%s: timer%i cannot set source\n",
__func__, gptimer_id);
clk_put(src);
}
}
__omap_dm_timer_init_regs(timer);
__omap_dm_timer_reset(timer, 1, 1);
timer->posted = 1;
timer->rate = clk_get_rate(timer->fclk);
timer->reserved = 1;
return res;
}
static void __init omap2_gp_clockevent_init(int gptimer_id,
const char *fck_source)
{
int res;
res = omap_dm_timer_init_one(&clkev, gptimer_id, fck_source);
BUG_ON(res);
omap2_gp_timer_irq.dev_id = (void *)&clkev;
setup_irq(clkev.irq, &omap2_gp_timer_irq);
__omap_dm_timer_int_enable(&clkev, OMAP_TIMER_INT_OVERFLOW);
clockevent_gpt.mult = div_sc(clkev.rate, NSEC_PER_SEC,
clockevent_gpt.shift);
clockevent_gpt.max_delta_ns =
clockevent_delta2ns(0xffffffff, &clockevent_gpt);
clockevent_gpt.min_delta_ns =
clockevent_delta2ns(3, &clockevent_gpt);
/* Timer internal resynch latency. */
clockevent_gpt.cpumask = cpumask_of(0);
clockevents_register_device(&clockevent_gpt);
pr_info("OMAP clockevent source: GPTIMER%d at %lu Hz\n",
gptimer_id, clkev.rate);
}
/* Clocksource code */
#ifdef CONFIG_OMAP_32K_TIMER
/*
* When 32k-timer is enabled, don't use GPTimer for clocksource
* instead, just leave default clocksource which uses the 32k
* sync counter. See clocksource setup in plat-omap/counter_32k.c
*/
static void __init omap2_gp_clocksource_init(int unused, const char *dummy)
{
omap_init_clocksource_32k();
}
#else
static struct omap_dm_timer clksrc;
/*
* clocksource
*/
static cycle_t clocksource_read_cycles(struct clocksource *cs)
{
return (cycle_t)__omap_dm_timer_read_counter(&clksrc, 1);
}
static struct clocksource clocksource_gpt = {
.name = "gp timer",
.rating = 300,
.read = clocksource_read_cycles,
.mask = CLOCKSOURCE_MASK(32),
.flags = CLOCK_SOURCE_IS_CONTINUOUS,
};
static u32 notrace dmtimer_read_sched_clock(void)
{
if (clksrc.reserved)
return __omap_dm_timer_read_counter(&clksrc, 1);
return 0;
}
/* Setup free-running counter for clocksource */
static void __init omap2_gp_clocksource_init(int gptimer_id,
const char *fck_source)
{
int res;
res = omap_dm_timer_init_one(&clksrc, gptimer_id, fck_source);
BUG_ON(res);
pr_info("OMAP clocksource: GPTIMER%d at %lu Hz\n",
gptimer_id, clksrc.rate);
__omap_dm_timer_load_start(&clksrc,
OMAP_TIMER_CTRL_ST | OMAP_TIMER_CTRL_AR, 0, 1);
setup_sched_clock(dmtimer_read_sched_clock, 32, clksrc.rate);
if (clocksource_register_hz(&clocksource_gpt, clksrc.rate))
pr_err("Could not register clocksource %s\n",
clocksource_gpt.name);
}
#endif
#define OMAP_SYS_TIMER_INIT(name, clkev_nr, clkev_src, \
clksrc_nr, clksrc_src) \
static void __init omap##name##_timer_init(void) \
{ \
omap2_gp_clockevent_init((clkev_nr), clkev_src); \
omap2_gp_clocksource_init((clksrc_nr), clksrc_src); \
}
#define OMAP_SYS_TIMER(name) \
struct sys_timer omap##name##_timer = { \
.init = omap##name##_timer_init, \
};
#ifdef CONFIG_ARCH_OMAP2
OMAP_SYS_TIMER_INIT(2, 1, OMAP2_CLKEV_SOURCE, 2, OMAP2_MPU_SOURCE)
OMAP_SYS_TIMER(2)
#endif
#ifdef CONFIG_ARCH_OMAP3
OMAP_SYS_TIMER_INIT(3, 1, OMAP3_CLKEV_SOURCE, 2, OMAP3_MPU_SOURCE)
OMAP_SYS_TIMER(3)
OMAP_SYS_TIMER_INIT(3_secure, OMAP3_SECURE_TIMER, OMAP3_CLKEV_SOURCE,
2, OMAP3_MPU_SOURCE)
OMAP_SYS_TIMER(3_secure)
#endif
#ifdef CONFIG_ARCH_OMAP4
#ifdef CONFIG_LOCAL_TIMERS
static DEFINE_TWD_LOCAL_TIMER(twd_local_timer,
OMAP44XX_LOCAL_TWD_BASE,
OMAP44XX_IRQ_LOCALTIMER);
#endif
static void __init omap4_timer_init(void)
{
omap2_gp_clockevent_init(1, OMAP4_CLKEV_SOURCE);
omap2_gp_clocksource_init(2, OMAP4_MPU_SOURCE);
#ifdef CONFIG_LOCAL_TIMERS
/* Local timers are not supprted on OMAP4430 ES1.0 */
if (omap_rev() != OMAP4430_REV_ES1_0) {
int err;
err = twd_local_timer_register(&twd_local_timer);
if (err)
pr_err("twd_local_timer_register failed %d\n", err);
}
#endif
}
OMAP_SYS_TIMER(4)
#endif
/**
* omap2_dm_timer_set_src - change the timer input clock source
* @pdev: timer platform device pointer
* @source: array index of parent clock source
*/
static int omap2_dm_timer_set_src(struct platform_device *pdev, int source)
{
int ret;
struct dmtimer_platform_data *pdata = pdev->dev.platform_data;
struct clk *fclk, *parent;
char *parent_name = NULL;
fclk = clk_get(&pdev->dev, "fck");
if (IS_ERR_OR_NULL(fclk)) {
dev_err(&pdev->dev, "%s: %d: clk_get() FAILED\n",
__func__, __LINE__);
return -EINVAL;
}
switch (source) {
case OMAP_TIMER_SRC_SYS_CLK:
parent_name = "sys_ck";
break;
case OMAP_TIMER_SRC_32_KHZ:
parent_name = "32k_ck";
break;
case OMAP_TIMER_SRC_EXT_CLK:
if (pdata->timer_ip_version == OMAP_TIMER_IP_VERSION_1) {
parent_name = "alt_ck";
break;
}
dev_err(&pdev->dev, "%s: %d: invalid clk src.\n",
__func__, __LINE__);
clk_put(fclk);
return -EINVAL;
}
parent = clk_get(&pdev->dev, parent_name);
if (IS_ERR_OR_NULL(parent)) {
dev_err(&pdev->dev, "%s: %d: clk_get() %s FAILED\n",
__func__, __LINE__, parent_name);
clk_put(fclk);
return -EINVAL;
}
ret = clk_set_parent(fclk, parent);
if (IS_ERR_VALUE(ret)) {
dev_err(&pdev->dev, "%s: clk_set_parent() to %s FAILED\n",
__func__, parent_name);
ret = -EINVAL;
}
clk_put(parent);
clk_put(fclk);
return ret;
}
/**
* omap_timer_init - build and register timer device with an
* associated timer hwmod
* @oh: timer hwmod pointer to be used to build timer device
* @user: parameter that can be passed from calling hwmod API
*
* Called by omap_hwmod_for_each_by_class to register each of the timer
* devices present in the system. The number of timer devices is known
* by parsing through the hwmod database for a given class name. At the
* end of function call memory is allocated for timer device and it is
* registered to the framework ready to be proved by the driver.
*/
static int __init omap_timer_init(struct omap_hwmod *oh, void *unused)
{
int id;
int ret = 0;
char *name = "omap_timer";
struct dmtimer_platform_data *pdata;
struct platform_device *pdev;
struct omap_timer_capability_dev_attr *timer_dev_attr;
struct powerdomain *pwrdm;
pr_debug("%s: %s\n", __func__, oh->name);
/* on secure device, do not register secure timer */
timer_dev_attr = oh->dev_attr;
if (omap_type() != OMAP2_DEVICE_TYPE_GP && timer_dev_attr)
if (timer_dev_attr->timer_capability == OMAP_TIMER_SECURE)
return ret;
pdata = kzalloc(sizeof(*pdata), GFP_KERNEL);
if (!pdata) {
pr_err("%s: No memory for [%s]\n", __func__, oh->name);
return -ENOMEM;
}
/*
* Extract the IDs from name field in hwmod database
* and use the same for constructing ids' for the
* timer devices. In a way, we are avoiding usage of
* static variable witin the function to do the same.
* CAUTION: We have to be careful and make sure the
* name in hwmod database does not change in which case
* we might either make corresponding change here or
* switch back static variable mechanism.
*/
sscanf(oh->name, "timer%2d", &id);
pdata->set_timer_src = omap2_dm_timer_set_src;
pdata->timer_ip_version = oh->class->rev;
/* Mark clocksource and clockevent timers as reserved */
if ((sys_timer_reserved >> (id - 1)) & 0x1)
pdata->reserved = 1;
pwrdm = omap_hwmod_get_pwrdm(oh);
pdata->loses_context = pwrdm_can_ever_lose_context(pwrdm);
#ifdef CONFIG_PM
pdata->get_context_loss_count = omap_pm_get_dev_context_loss_count;
#endif
pdev = omap_device_build(name, id, oh, pdata, sizeof(*pdata),
NULL, 0, 0);
if (IS_ERR(pdev)) {
pr_err("%s: Can't build omap_device for %s: %s.\n",
__func__, name, oh->name);
ret = -EINVAL;
}
kfree(pdata);
return ret;
}
/**
* omap2_dm_timer_init - top level regular device initialization
*
* Uses dedicated hwmod api to parse through hwmod database for
* given class name and then build and register the timer device.
*/
static int __init omap2_dm_timer_init(void)
{
int ret;
ret = omap_hwmod_for_each_by_class("timer", omap_timer_init, NULL);
if (unlikely(ret)) {
pr_err("%s: device registration failed.\n", __func__);
return -EINVAL;
}
return 0;
}
arch_initcall(omap2_dm_timer_init);
| gpl-2.0 |
atinm/android_kernel_samsung_manta | drivers/media/video/tda9840.c | 4812 | 5608 | /*
tda9840 - i2c-driver for the tda9840 by SGS Thomson
Copyright (C) 1998-2003 Michael Hunold <michael@mihu.de>
Copyright (C) 2008 Hans Verkuil <hverkuil@xs4all.nl>
The tda9840 is a stereo/dual sound processor with digital
identification. It can be found at address 0x84 on the i2c-bus.
For detailed informations download the specifications directly
from SGS Thomson at http://www.st.com
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/ioctl.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <media/v4l2-device.h>
#include <media/v4l2-chip-ident.h>
MODULE_AUTHOR("Michael Hunold <michael@mihu.de>");
MODULE_DESCRIPTION("tda9840 driver");
MODULE_LICENSE("GPL");
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Debug level (0-1)");
#define SWITCH 0x00
#define LEVEL_ADJUST 0x02
#define STEREO_ADJUST 0x03
#define TEST 0x04
#define TDA9840_SET_MUTE 0x00
#define TDA9840_SET_MONO 0x10
#define TDA9840_SET_STEREO 0x2a
#define TDA9840_SET_LANG1 0x12
#define TDA9840_SET_LANG2 0x1e
#define TDA9840_SET_BOTH 0x1a
#define TDA9840_SET_BOTH_R 0x16
#define TDA9840_SET_EXTERNAL 0x7a
static void tda9840_write(struct v4l2_subdev *sd, u8 reg, u8 val)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
if (i2c_smbus_write_byte_data(client, reg, val))
v4l2_dbg(1, debug, sd, "error writing %02x to %02x\n",
val, reg);
}
static int tda9840_s_tuner(struct v4l2_subdev *sd, struct v4l2_tuner *t)
{
int byte;
if (t->index)
return -EINVAL;
switch (t->audmode) {
case V4L2_TUNER_MODE_STEREO:
byte = TDA9840_SET_STEREO;
break;
case V4L2_TUNER_MODE_LANG1_LANG2:
byte = TDA9840_SET_BOTH;
break;
case V4L2_TUNER_MODE_LANG1:
byte = TDA9840_SET_LANG1;
break;
case V4L2_TUNER_MODE_LANG2:
byte = TDA9840_SET_LANG2;
break;
default:
byte = TDA9840_SET_MONO;
break;
}
v4l2_dbg(1, debug, sd, "TDA9840_SWITCH: 0x%02x\n", byte);
tda9840_write(sd, SWITCH, byte);
return 0;
}
static int tda9840_g_tuner(struct v4l2_subdev *sd, struct v4l2_tuner *t)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
u8 byte;
t->rxsubchans = V4L2_TUNER_SUB_MONO;
if (1 != i2c_master_recv(client, &byte, 1)) {
v4l2_dbg(1, debug, sd,
"i2c_master_recv() failed\n");
return -EIO;
}
if (byte & 0x80) {
v4l2_dbg(1, debug, sd,
"TDA9840_DETECT: register contents invalid\n");
return -EINVAL;
}
v4l2_dbg(1, debug, sd, "TDA9840_DETECT: byte: 0x%02x\n", byte);
switch (byte & 0x60) {
case 0x00:
t->rxsubchans = V4L2_TUNER_SUB_MONO;
break;
case 0x20:
t->rxsubchans = V4L2_TUNER_SUB_LANG1 | V4L2_TUNER_SUB_LANG2;
break;
case 0x40:
t->rxsubchans = V4L2_TUNER_SUB_STEREO | V4L2_TUNER_SUB_MONO;
break;
default: /* Incorrect detect */
t->rxsubchans = V4L2_TUNER_MODE_MONO;
break;
}
return 0;
}
static int tda9840_g_chip_ident(struct v4l2_subdev *sd, struct v4l2_dbg_chip_ident *chip)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
return v4l2_chip_ident_i2c_client(client, chip, V4L2_IDENT_TDA9840, 0);
}
/* ----------------------------------------------------------------------- */
static const struct v4l2_subdev_core_ops tda9840_core_ops = {
.g_chip_ident = tda9840_g_chip_ident,
};
static const struct v4l2_subdev_tuner_ops tda9840_tuner_ops = {
.s_tuner = tda9840_s_tuner,
.g_tuner = tda9840_g_tuner,
};
static const struct v4l2_subdev_ops tda9840_ops = {
.core = &tda9840_core_ops,
.tuner = &tda9840_tuner_ops,
};
/* ----------------------------------------------------------------------- */
static int tda9840_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct v4l2_subdev *sd;
/* let's see whether this adapter can support what we need */
if (!i2c_check_functionality(client->adapter,
I2C_FUNC_SMBUS_READ_BYTE_DATA |
I2C_FUNC_SMBUS_WRITE_BYTE_DATA))
return -EIO;
v4l_info(client, "chip found @ 0x%x (%s)\n",
client->addr << 1, client->adapter->name);
sd = kzalloc(sizeof(struct v4l2_subdev), GFP_KERNEL);
if (sd == NULL)
return -ENOMEM;
v4l2_i2c_subdev_init(sd, client, &tda9840_ops);
/* set initial values for level & stereo - adjustment, mode */
tda9840_write(sd, LEVEL_ADJUST, 0);
tda9840_write(sd, STEREO_ADJUST, 0);
tda9840_write(sd, SWITCH, TDA9840_SET_STEREO);
return 0;
}
static int tda9840_remove(struct i2c_client *client)
{
struct v4l2_subdev *sd = i2c_get_clientdata(client);
v4l2_device_unregister_subdev(sd);
kfree(sd);
return 0;
}
static const struct i2c_device_id tda9840_id[] = {
{ "tda9840", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, tda9840_id);
static struct i2c_driver tda9840_driver = {
.driver = {
.owner = THIS_MODULE,
.name = "tda9840",
},
.probe = tda9840_probe,
.remove = tda9840_remove,
.id_table = tda9840_id,
};
module_i2c_driver(tda9840_driver);
| gpl-2.0 |
f1vefour/mako | drivers/media/dvb/dvb-usb/rtl28xxu.c | 4812 | 22737 | /*
* Realtek RTL28xxU DVB USB driver
*
* Copyright (C) 2009 Antti Palosaari <crope@iki.fi>
* Copyright (C) 2011 Antti Palosaari <crope@iki.fi>
*
* 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 "rtl28xxu.h"
#include "rtl2830.h"
#include "qt1010.h"
#include "mt2060.h"
#include "mxl5005s.h"
/* debug */
static int dvb_usb_rtl28xxu_debug;
module_param_named(debug, dvb_usb_rtl28xxu_debug, int, 0644);
MODULE_PARM_DESC(debug, "set debugging level" DVB_USB_DEBUG_STATUS);
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
static int rtl28xxu_ctrl_msg(struct dvb_usb_device *d, struct rtl28xxu_req *req)
{
int ret;
unsigned int pipe;
u8 requesttype;
u8 *buf;
buf = kmalloc(req->size, GFP_KERNEL);
if (!buf) {
ret = -ENOMEM;
goto err;
}
if (req->index & CMD_WR_FLAG) {
/* write */
memcpy(buf, req->data, req->size);
requesttype = (USB_TYPE_VENDOR | USB_DIR_OUT);
pipe = usb_sndctrlpipe(d->udev, 0);
} else {
/* read */
requesttype = (USB_TYPE_VENDOR | USB_DIR_IN);
pipe = usb_rcvctrlpipe(d->udev, 0);
}
ret = usb_control_msg(d->udev, pipe, 0, requesttype, req->value,
req->index, buf, req->size, 1000);
if (ret > 0)
ret = 0;
deb_dump(0, requesttype, req->value, req->index, buf, req->size,
deb_xfer);
/* read request, copy returned data to return buf */
if (!ret && requesttype == (USB_TYPE_VENDOR | USB_DIR_IN))
memcpy(req->data, buf, req->size);
kfree(buf);
if (ret)
goto err;
return ret;
err:
deb_info("%s: failed=%d\n", __func__, ret);
return ret;
}
static int rtl2831_wr_regs(struct dvb_usb_device *d, u16 reg, u8 *val, int len)
{
struct rtl28xxu_req req;
if (reg < 0x3000)
req.index = CMD_USB_WR;
else if (reg < 0x4000)
req.index = CMD_SYS_WR;
else
req.index = CMD_IR_WR;
req.value = reg;
req.size = len;
req.data = val;
return rtl28xxu_ctrl_msg(d, &req);
}
static int rtl2831_rd_regs(struct dvb_usb_device *d, u16 reg, u8 *val, int len)
{
struct rtl28xxu_req req;
if (reg < 0x3000)
req.index = CMD_USB_RD;
else if (reg < 0x4000)
req.index = CMD_SYS_RD;
else
req.index = CMD_IR_RD;
req.value = reg;
req.size = len;
req.data = val;
return rtl28xxu_ctrl_msg(d, &req);
}
static int rtl2831_wr_reg(struct dvb_usb_device *d, u16 reg, u8 val)
{
return rtl2831_wr_regs(d, reg, &val, 1);
}
static int rtl2831_rd_reg(struct dvb_usb_device *d, u16 reg, u8 *val)
{
return rtl2831_rd_regs(d, reg, val, 1);
}
/* I2C */
static int rtl28xxu_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg msg[],
int num)
{
int ret;
struct dvb_usb_device *d = i2c_get_adapdata(adap);
struct rtl28xxu_priv *priv = d->priv;
struct rtl28xxu_req req;
/*
* It is not known which are real I2C bus xfer limits, but testing
* with RTL2831U + MT2060 gives max RD 24 and max WR 22 bytes.
* TODO: find out RTL2832U lens
*/
/*
* I2C adapter logic looks rather complicated due to fact it handles
* three different access methods. Those methods are;
* 1) integrated demod access
* 2) old I2C access
* 3) new I2C access
*
* Used method is selected in order 1, 2, 3. Method 3 can handle all
* requests but there is two reasons why not use it always;
* 1) It is most expensive, usually two USB messages are needed
* 2) At least RTL2831U does not support it
*
* Method 3 is needed in case of I2C write+read (typical register read)
* where write is more than one byte.
*/
if (mutex_lock_interruptible(&d->i2c_mutex) < 0)
return -EAGAIN;
if (num == 2 && !(msg[0].flags & I2C_M_RD) &&
(msg[1].flags & I2C_M_RD)) {
if (msg[0].len > 24 || msg[1].len > 24) {
/* TODO: check msg[0].len max */
ret = -EOPNOTSUPP;
goto err_mutex_unlock;
} else if (msg[0].addr == 0x10) {
/* method 1 - integrated demod */
req.value = (msg[0].buf[0] << 8) | (msg[0].addr << 1);
req.index = CMD_DEMOD_RD | priv->page;
req.size = msg[1].len;
req.data = &msg[1].buf[0];
ret = rtl28xxu_ctrl_msg(d, &req);
} else if (msg[0].len < 2) {
/* method 2 - old I2C */
req.value = (msg[0].buf[0] << 8) | (msg[0].addr << 1);
req.index = CMD_I2C_RD;
req.size = msg[1].len;
req.data = &msg[1].buf[0];
ret = rtl28xxu_ctrl_msg(d, &req);
} else {
/* method 3 - new I2C */
req.value = (msg[0].addr << 1);
req.index = CMD_I2C_DA_WR;
req.size = msg[0].len;
req.data = msg[0].buf;
ret = rtl28xxu_ctrl_msg(d, &req);
if (ret)
goto err_mutex_unlock;
req.value = (msg[0].addr << 1);
req.index = CMD_I2C_DA_RD;
req.size = msg[1].len;
req.data = msg[1].buf;
ret = rtl28xxu_ctrl_msg(d, &req);
}
} else if (num == 1 && !(msg[0].flags & I2C_M_RD)) {
if (msg[0].len > 22) {
/* TODO: check msg[0].len max */
ret = -EOPNOTSUPP;
goto err_mutex_unlock;
} else if (msg[0].addr == 0x10) {
/* method 1 - integrated demod */
if (msg[0].buf[0] == 0x00) {
/* save demod page for later demod access */
priv->page = msg[0].buf[1];
ret = 0;
} else {
req.value = (msg[0].buf[0] << 8) |
(msg[0].addr << 1);
req.index = CMD_DEMOD_WR | priv->page;
req.size = msg[0].len-1;
req.data = &msg[0].buf[1];
ret = rtl28xxu_ctrl_msg(d, &req);
}
} else if (msg[0].len < 23) {
/* method 2 - old I2C */
req.value = (msg[0].buf[0] << 8) | (msg[0].addr << 1);
req.index = CMD_I2C_WR;
req.size = msg[0].len-1;
req.data = &msg[0].buf[1];
ret = rtl28xxu_ctrl_msg(d, &req);
} else {
/* method 3 - new I2C */
req.value = (msg[0].addr << 1);
req.index = CMD_I2C_DA_WR;
req.size = msg[0].len;
req.data = msg[0].buf;
ret = rtl28xxu_ctrl_msg(d, &req);
}
} else {
ret = -EINVAL;
}
err_mutex_unlock:
mutex_unlock(&d->i2c_mutex);
return ret ? ret : num;
}
static u32 rtl28xxu_i2c_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_I2C;
}
static struct i2c_algorithm rtl28xxu_i2c_algo = {
.master_xfer = rtl28xxu_i2c_xfer,
.functionality = rtl28xxu_i2c_func,
};
static struct rtl2830_config rtl28xxu_rtl2830_mt2060_config = {
.i2c_addr = 0x10, /* 0x20 */
.xtal = 28800000,
.ts_mode = 0,
.spec_inv = 1,
.if_dvbt = 36150000,
.vtop = 0x20,
.krf = 0x04,
.agc_targ_val = 0x2d,
};
static struct rtl2830_config rtl28xxu_rtl2830_qt1010_config = {
.i2c_addr = 0x10, /* 0x20 */
.xtal = 28800000,
.ts_mode = 0,
.spec_inv = 1,
.if_dvbt = 36125000,
.vtop = 0x20,
.krf = 0x04,
.agc_targ_val = 0x2d,
};
static struct rtl2830_config rtl28xxu_rtl2830_mxl5005s_config = {
.i2c_addr = 0x10, /* 0x20 */
.xtal = 28800000,
.ts_mode = 0,
.spec_inv = 0,
.if_dvbt = 4570000,
.vtop = 0x3f,
.krf = 0x04,
.agc_targ_val = 0x3e,
};
static int rtl2831u_frontend_attach(struct dvb_usb_adapter *adap)
{
int ret;
struct rtl28xxu_priv *priv = adap->dev->priv;
u8 buf[1];
struct rtl2830_config *rtl2830_config;
/* open RTL2831U/RTL2830 I2C gate */
struct rtl28xxu_req req_gate = { 0x0120, 0x0011, 0x0001, "\x08" };
/* for MT2060 tuner probe */
struct rtl28xxu_req req_mt2060 = { 0x00c0, CMD_I2C_RD, 1, buf };
/* for QT1010 tuner probe */
struct rtl28xxu_req req_qt1010 = { 0x0fc4, CMD_I2C_RD, 1, buf };
deb_info("%s:\n", __func__);
/*
* RTL2831U GPIOs
* =========================================================
* GPIO0 | tuner#0 | 0 off | 1 on | MXL5005S (?)
* GPIO2 | LED | 0 off | 1 on |
* GPIO4 | tuner#1 | 0 on | 1 off | MT2060
*/
/* GPIO direction */
ret = rtl2831_wr_reg(adap->dev, SYS_GPIO_DIR, 0x0a);
if (ret)
goto err;
/* enable as output GPIO0, GPIO2, GPIO4 */
ret = rtl2831_wr_reg(adap->dev, SYS_GPIO_OUT_EN, 0x15);
if (ret)
goto err;
/*
* Probe used tuner. We need to know used tuner before demod attach
* since there is some demod params needed to set according to tuner.
*/
/* open demod I2C gate */
ret = rtl28xxu_ctrl_msg(adap->dev, &req_gate);
if (ret)
goto err;
/* check QT1010 ID(?) register; reg=0f val=2c */
ret = rtl28xxu_ctrl_msg(adap->dev, &req_qt1010);
if (ret == 0 && buf[0] == 0x2c) {
priv->tuner = TUNER_RTL2830_QT1010;
rtl2830_config = &rtl28xxu_rtl2830_qt1010_config;
deb_info("%s: QT1010\n", __func__);
goto found;
} else {
deb_info("%s: QT1010 probe failed=%d - %02x\n",
__func__, ret, buf[0]);
}
/* open demod I2C gate */
ret = rtl28xxu_ctrl_msg(adap->dev, &req_gate);
if (ret)
goto err;
/* check MT2060 ID register; reg=00 val=63 */
ret = rtl28xxu_ctrl_msg(adap->dev, &req_mt2060);
if (ret == 0 && buf[0] == 0x63) {
priv->tuner = TUNER_RTL2830_MT2060;
rtl2830_config = &rtl28xxu_rtl2830_mt2060_config;
deb_info("%s: MT2060\n", __func__);
goto found;
} else {
deb_info("%s: MT2060 probe failed=%d - %02x\n",
__func__, ret, buf[0]);
}
/* assume MXL5005S */
ret = 0;
priv->tuner = TUNER_RTL2830_MXL5005S;
rtl2830_config = &rtl28xxu_rtl2830_mxl5005s_config;
deb_info("%s: MXL5005S\n", __func__);
goto found;
found:
/* attach demodulator */
adap->fe_adap[0].fe = dvb_attach(rtl2830_attach, rtl2830_config,
&adap->dev->i2c_adap);
if (adap->fe_adap[0].fe == NULL) {
ret = -ENODEV;
goto err;
}
return ret;
err:
deb_info("%s: failed=%d\n", __func__, ret);
return ret;
}
static int rtl2832u_frontend_attach(struct dvb_usb_adapter *adap)
{
int ret;
struct rtl28xxu_priv *priv = adap->dev->priv;
u8 buf[1];
/* open RTL2832U/RTL2832 I2C gate */
struct rtl28xxu_req req_gate_open = {0x0120, 0x0011, 0x0001, "\x18"};
/* close RTL2832U/RTL2832 I2C gate */
struct rtl28xxu_req req_gate_close = {0x0120, 0x0011, 0x0001, "\x10"};
/* for FC2580 tuner probe */
struct rtl28xxu_req req_fc2580 = {0x01ac, CMD_I2C_RD, 1, buf};
deb_info("%s:\n", __func__);
/* GPIO direction */
ret = rtl2831_wr_reg(adap->dev, SYS_GPIO_DIR, 0x0a);
if (ret)
goto err;
/* enable as output GPIO0, GPIO2, GPIO4 */
ret = rtl2831_wr_reg(adap->dev, SYS_GPIO_OUT_EN, 0x15);
if (ret)
goto err;
ret = rtl2831_wr_reg(adap->dev, SYS_DEMOD_CTL, 0xe8);
if (ret)
goto err;
/*
* Probe used tuner. We need to know used tuner before demod attach
* since there is some demod params needed to set according to tuner.
*/
/* open demod I2C gate */
ret = rtl28xxu_ctrl_msg(adap->dev, &req_gate_open);
if (ret)
goto err;
/* check FC2580 ID register; reg=01 val=56 */
ret = rtl28xxu_ctrl_msg(adap->dev, &req_fc2580);
if (ret == 0 && buf[0] == 0x56) {
priv->tuner = TUNER_RTL2832_FC2580;
deb_info("%s: FC2580\n", __func__);
goto found;
} else {
deb_info("%s: FC2580 probe failed=%d - %02x\n",
__func__, ret, buf[0]);
}
/* close demod I2C gate */
ret = rtl28xxu_ctrl_msg(adap->dev, &req_gate_close);
if (ret)
goto err;
/* tuner not found */
ret = -ENODEV;
goto err;
found:
/* close demod I2C gate */
ret = rtl28xxu_ctrl_msg(adap->dev, &req_gate_close);
if (ret)
goto err;
/* attach demodulator */
/* TODO: */
return ret;
err:
deb_info("%s: failed=%d\n", __func__, ret);
return ret;
}
static struct qt1010_config rtl28xxu_qt1010_config = {
.i2c_address = 0x62, /* 0xc4 */
};
static struct mt2060_config rtl28xxu_mt2060_config = {
.i2c_address = 0x60, /* 0xc0 */
.clock_out = 0,
};
static struct mxl5005s_config rtl28xxu_mxl5005s_config = {
.i2c_address = 0x63, /* 0xc6 */
.if_freq = IF_FREQ_4570000HZ,
.xtal_freq = CRYSTAL_FREQ_16000000HZ,
.agc_mode = MXL_SINGLE_AGC,
.tracking_filter = MXL_TF_C_H,
.rssi_enable = MXL_RSSI_ENABLE,
.cap_select = MXL_CAP_SEL_ENABLE,
.div_out = MXL_DIV_OUT_4,
.clock_out = MXL_CLOCK_OUT_DISABLE,
.output_load = MXL5005S_IF_OUTPUT_LOAD_200_OHM,
.top = MXL5005S_TOP_25P2,
.mod_mode = MXL_DIGITAL_MODE,
.if_mode = MXL_ZERO_IF,
.AgcMasterByte = 0x00,
};
static int rtl2831u_tuner_attach(struct dvb_usb_adapter *adap)
{
int ret;
struct rtl28xxu_priv *priv = adap->dev->priv;
struct i2c_adapter *rtl2830_tuner_i2c;
struct dvb_frontend *fe;
deb_info("%s:\n", __func__);
/* use rtl2830 driver I2C adapter, for more info see rtl2830 driver */
rtl2830_tuner_i2c = rtl2830_get_tuner_i2c_adapter(adap->fe_adap[0].fe);
switch (priv->tuner) {
case TUNER_RTL2830_QT1010:
fe = dvb_attach(qt1010_attach, adap->fe_adap[0].fe,
rtl2830_tuner_i2c, &rtl28xxu_qt1010_config);
break;
case TUNER_RTL2830_MT2060:
fe = dvb_attach(mt2060_attach, adap->fe_adap[0].fe,
rtl2830_tuner_i2c, &rtl28xxu_mt2060_config,
1220);
break;
case TUNER_RTL2830_MXL5005S:
fe = dvb_attach(mxl5005s_attach, adap->fe_adap[0].fe,
rtl2830_tuner_i2c, &rtl28xxu_mxl5005s_config);
break;
default:
fe = NULL;
err("unknown tuner=%d", priv->tuner);
}
if (fe == NULL) {
ret = -ENODEV;
goto err;
}
return 0;
err:
deb_info("%s: failed=%d\n", __func__, ret);
return ret;
}
static int rtl2832u_tuner_attach(struct dvb_usb_adapter *adap)
{
int ret;
struct rtl28xxu_priv *priv = adap->dev->priv;
struct dvb_frontend *fe;
deb_info("%s:\n", __func__);
switch (priv->tuner) {
case TUNER_RTL2832_FC2580:
/* TODO: */
fe = NULL;
break;
default:
fe = NULL;
err("unknown tuner=%d", priv->tuner);
}
if (fe == NULL) {
ret = -ENODEV;
goto err;
}
return 0;
err:
deb_info("%s: failed=%d\n", __func__, ret);
return ret;
}
static int rtl28xxu_streaming_ctrl(struct dvb_usb_adapter *adap , int onoff)
{
int ret;
u8 buf[2], gpio;
deb_info("%s: onoff=%d\n", __func__, onoff);
ret = rtl2831_rd_reg(adap->dev, SYS_GPIO_OUT_VAL, &gpio);
if (ret)
goto err;
if (onoff) {
buf[0] = 0x00;
buf[1] = 0x00;
gpio |= 0x04; /* LED on */
} else {
buf[0] = 0x10; /* stall EPA */
buf[1] = 0x02; /* reset EPA */
gpio &= (~0x04); /* LED off */
}
ret = rtl2831_wr_reg(adap->dev, SYS_GPIO_OUT_VAL, gpio);
if (ret)
goto err;
ret = rtl2831_wr_regs(adap->dev, USB_EPA_CTL, buf, 2);
if (ret)
goto err;
return ret;
err:
deb_info("%s: failed=%d\n", __func__, ret);
return ret;
}
static int rtl28xxu_power_ctrl(struct dvb_usb_device *d, int onoff)
{
int ret;
u8 gpio, sys0;
deb_info("%s: onoff=%d\n", __func__, onoff);
/* demod adc */
ret = rtl2831_rd_reg(d, SYS_SYS0, &sys0);
if (ret)
goto err;
/* tuner power, read GPIOs */
ret = rtl2831_rd_reg(d, SYS_GPIO_OUT_VAL, &gpio);
if (ret)
goto err;
deb_info("%s: RD SYS0=%02x GPIO_OUT_VAL=%02x\n", __func__, sys0, gpio);
if (onoff) {
gpio |= 0x01; /* GPIO0 = 1 */
gpio &= (~0x10); /* GPIO4 = 0 */
sys0 = sys0 & 0x0f;
sys0 |= 0xe0;
} else {
gpio &= (~0x01); /* GPIO0 = 0 */
gpio |= 0x10; /* GPIO4 = 1 */
sys0 = sys0 & (~0xc0);
}
deb_info("%s: WR SYS0=%02x GPIO_OUT_VAL=%02x\n", __func__, sys0, gpio);
/* demod adc */
ret = rtl2831_wr_reg(d, SYS_SYS0, sys0);
if (ret)
goto err;
/* tuner power, write GPIOs */
ret = rtl2831_wr_reg(d, SYS_GPIO_OUT_VAL, gpio);
if (ret)
goto err;
return ret;
err:
deb_info("%s: failed=%d\n", __func__, ret);
return ret;
}
static int rtl2831u_rc_query(struct dvb_usb_device *d)
{
int ret, i;
struct rtl28xxu_priv *priv = d->priv;
u8 buf[5];
u32 rc_code;
struct rtl28xxu_reg_val rc_nec_tab[] = {
{ 0x3033, 0x80 },
{ 0x3020, 0x43 },
{ 0x3021, 0x16 },
{ 0x3022, 0x16 },
{ 0x3023, 0x5a },
{ 0x3024, 0x2d },
{ 0x3025, 0x16 },
{ 0x3026, 0x01 },
{ 0x3028, 0xb0 },
{ 0x3029, 0x04 },
{ 0x302c, 0x88 },
{ 0x302e, 0x13 },
{ 0x3030, 0xdf },
{ 0x3031, 0x05 },
};
/* init remote controller */
if (!priv->rc_active) {
for (i = 0; i < ARRAY_SIZE(rc_nec_tab); i++) {
ret = rtl2831_wr_reg(d, rc_nec_tab[i].reg,
rc_nec_tab[i].val);
if (ret)
goto err;
}
priv->rc_active = true;
}
ret = rtl2831_rd_regs(d, SYS_IRRC_RP, buf, 5);
if (ret)
goto err;
if (buf[4] & 0x01) {
if (buf[2] == (u8) ~buf[3]) {
if (buf[0] == (u8) ~buf[1]) {
/* NEC standard (16 bit) */
rc_code = buf[0] << 8 | buf[2];
} else {
/* NEC extended (24 bit) */
rc_code = buf[0] << 16 |
buf[1] << 8 | buf[2];
}
} else {
/* NEC full (32 bit) */
rc_code = buf[0] << 24 | buf[1] << 16 |
buf[2] << 8 | buf[3];
}
rc_keydown(d->rc_dev, rc_code, 0);
ret = rtl2831_wr_reg(d, SYS_IRRC_SR, 1);
if (ret)
goto err;
/* repeated intentionally to avoid extra keypress */
ret = rtl2831_wr_reg(d, SYS_IRRC_SR, 1);
if (ret)
goto err;
}
return ret;
err:
deb_info("%s: failed=%d\n", __func__, ret);
return ret;
}
static int rtl2832u_rc_query(struct dvb_usb_device *d)
{
int ret, i;
struct rtl28xxu_priv *priv = d->priv;
u8 buf[128];
int len;
struct rtl28xxu_reg_val rc_nec_tab[] = {
{ IR_RX_CTRL, 0x20 },
{ IR_RX_BUF_CTRL, 0x80 },
{ IR_RX_IF, 0xff },
{ IR_RX_IE, 0xff },
{ IR_MAX_DURATION0, 0xd0 },
{ IR_MAX_DURATION1, 0x07 },
{ IR_IDLE_LEN0, 0xc0 },
{ IR_IDLE_LEN1, 0x00 },
{ IR_GLITCH_LEN, 0x03 },
{ IR_RX_CLK, 0x09 },
{ IR_RX_CFG, 0x1c },
{ IR_MAX_H_TOL_LEN, 0x1e },
{ IR_MAX_L_TOL_LEN, 0x1e },
{ IR_RX_CTRL, 0x80 },
};
/* init remote controller */
if (!priv->rc_active) {
for (i = 0; i < ARRAY_SIZE(rc_nec_tab); i++) {
ret = rtl2831_wr_reg(d, rc_nec_tab[i].reg,
rc_nec_tab[i].val);
if (ret)
goto err;
}
priv->rc_active = true;
}
ret = rtl2831_rd_reg(d, IR_RX_IF, &buf[0]);
if (ret)
goto err;
if (buf[0] != 0x83)
goto exit;
ret = rtl2831_rd_reg(d, IR_RX_BC, &buf[0]);
if (ret)
goto err;
len = buf[0];
ret = rtl2831_rd_regs(d, IR_RX_BUF, buf, len);
/* TODO: pass raw IR to Kernel IR decoder */
ret = rtl2831_wr_reg(d, IR_RX_IF, 0x03);
ret = rtl2831_wr_reg(d, IR_RX_BUF_CTRL, 0x80);
ret = rtl2831_wr_reg(d, IR_RX_CTRL, 0x80);
exit:
return ret;
err:
deb_info("%s: failed=%d\n", __func__, ret);
return ret;
}
enum rtl28xxu_usb_table_entry {
RTL2831U_0BDA_2831,
RTL2831U_14AA_0160,
RTL2831U_14AA_0161,
};
static struct usb_device_id rtl28xxu_table[] = {
/* RTL2831U */
[RTL2831U_0BDA_2831] = {
USB_DEVICE(USB_VID_REALTEK, USB_PID_REALTEK_RTL2831U)},
[RTL2831U_14AA_0160] = {
USB_DEVICE(USB_VID_WIDEVIEW, USB_PID_FREECOM_DVBT)},
[RTL2831U_14AA_0161] = {
USB_DEVICE(USB_VID_WIDEVIEW, USB_PID_FREECOM_DVBT_2)},
/* RTL2832U */
{} /* terminating entry */
};
MODULE_DEVICE_TABLE(usb, rtl28xxu_table);
static struct dvb_usb_device_properties rtl28xxu_properties[] = {
{
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = DEVICE_SPECIFIC,
.no_reconnect = 1,
.size_of_priv = sizeof(struct rtl28xxu_priv),
.num_adapters = 1,
.adapter = {
{
.num_frontends = 1,
.fe = {
{
.frontend_attach = rtl2831u_frontend_attach,
.tuner_attach = rtl2831u_tuner_attach,
.streaming_ctrl = rtl28xxu_streaming_ctrl,
.stream = {
.type = USB_BULK,
.count = 6,
.endpoint = 0x81,
.u = {
.bulk = {
.buffersize = 8*512,
}
}
}
}
}
}
},
.power_ctrl = rtl28xxu_power_ctrl,
.rc.core = {
.protocol = RC_TYPE_NEC,
.module_name = "rtl28xxu",
.rc_query = rtl2831u_rc_query,
.rc_interval = 400,
.allowed_protos = RC_TYPE_NEC,
.rc_codes = RC_MAP_EMPTY,
},
.i2c_algo = &rtl28xxu_i2c_algo,
.num_device_descs = 2,
.devices = {
{
.name = "Realtek RTL2831U reference design",
.warm_ids = {
&rtl28xxu_table[RTL2831U_0BDA_2831],
},
},
{
.name = "Freecom USB2.0 DVB-T",
.warm_ids = {
&rtl28xxu_table[RTL2831U_14AA_0160],
&rtl28xxu_table[RTL2831U_14AA_0161],
},
},
}
},
{
.caps = DVB_USB_IS_AN_I2C_ADAPTER,
.usb_ctrl = DEVICE_SPECIFIC,
.no_reconnect = 1,
.size_of_priv = sizeof(struct rtl28xxu_priv),
.num_adapters = 1,
.adapter = {
{
.num_frontends = 1,
.fe = {
{
.frontend_attach = rtl2832u_frontend_attach,
.tuner_attach = rtl2832u_tuner_attach,
.streaming_ctrl = rtl28xxu_streaming_ctrl,
.stream = {
.type = USB_BULK,
.count = 6,
.endpoint = 0x81,
.u = {
.bulk = {
.buffersize = 8*512,
}
}
}
}
}
}
},
.power_ctrl = rtl28xxu_power_ctrl,
.rc.core = {
.protocol = RC_TYPE_NEC,
.module_name = "rtl28xxu",
.rc_query = rtl2832u_rc_query,
.rc_interval = 400,
.allowed_protos = RC_TYPE_NEC,
.rc_codes = RC_MAP_EMPTY,
},
.i2c_algo = &rtl28xxu_i2c_algo,
.num_device_descs = 0, /* disabled as no support for RTL2832 */
.devices = {
{
.name = "Realtek RTL2832U reference design",
},
}
},
};
static int rtl28xxu_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
int ret, i;
int properties_count = ARRAY_SIZE(rtl28xxu_properties);
struct dvb_usb_device *d;
deb_info("%s: interface=%d\n", __func__,
intf->cur_altsetting->desc.bInterfaceNumber);
if (intf->cur_altsetting->desc.bInterfaceNumber != 0)
return 0;
for (i = 0; i < properties_count; i++) {
ret = dvb_usb_device_init(intf, &rtl28xxu_properties[i],
THIS_MODULE, &d, adapter_nr);
if (ret == 0 || ret != -ENODEV)
break;
}
if (ret)
goto err;
/* init USB endpoints */
ret = rtl2831_wr_reg(d, USB_SYSCTL_0, 0x09);
if (ret)
goto err;
ret = rtl2831_wr_regs(d, USB_EPA_MAXPKT, "\x00\x02\x00\x00", 4);
if (ret)
goto err;
ret = rtl2831_wr_regs(d, USB_EPA_FIFO_CFG, "\x14\x00\x00\x00", 4);
if (ret)
goto err;
return ret;
err:
deb_info("%s: failed=%d\n", __func__, ret);
return ret;
}
static struct usb_driver rtl28xxu_driver = {
.name = "dvb_usb_rtl28xxu",
.probe = rtl28xxu_probe,
.disconnect = dvb_usb_device_exit,
.id_table = rtl28xxu_table,
};
/* module stuff */
static int __init rtl28xxu_module_init(void)
{
int ret;
deb_info("%s:\n", __func__);
ret = usb_register(&rtl28xxu_driver);
if (ret)
err("usb_register failed=%d", ret);
return ret;
}
static void __exit rtl28xxu_module_exit(void)
{
deb_info("%s:\n", __func__);
/* deregister this driver from the USB subsystem */
usb_deregister(&rtl28xxu_driver);
}
module_init(rtl28xxu_module_init);
module_exit(rtl28xxu_module_exit);
MODULE_DESCRIPTION("Realtek RTL28xxU DVB USB driver");
MODULE_AUTHOR("Antti Palosaari <crope@iki.fi>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
bangprovn/android_kernel_lge_v400_10c | drivers/media/video/saa7134/saa7134-input.c | 4812 | 27293 | /*
*
* handle saa7134 IR remotes via linux kernel input layer.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include "saa7134-reg.h"
#include "saa7134.h"
#define MODULE_NAME "saa7134"
static unsigned int disable_ir;
module_param(disable_ir, int, 0444);
MODULE_PARM_DESC(disable_ir,"disable infrared remote support");
static unsigned int ir_debug;
module_param(ir_debug, int, 0644);
MODULE_PARM_DESC(ir_debug,"enable debug messages [IR]");
static int pinnacle_remote;
module_param(pinnacle_remote, int, 0644); /* Choose Pinnacle PCTV remote */
MODULE_PARM_DESC(pinnacle_remote, "Specify Pinnacle PCTV remote: 0=coloured, 1=grey (defaults to 0)");
#define dprintk(fmt, arg...) if (ir_debug) \
printk(KERN_DEBUG "%s/ir: " fmt, dev->name , ## arg)
#define i2cdprintk(fmt, arg...) if (ir_debug) \
printk(KERN_DEBUG "%s/ir: " fmt, ir->name , ## arg)
/* Helper function for raw decoding at GPIO16 or GPIO18 */
static int saa7134_raw_decode_irq(struct saa7134_dev *dev);
/* -------------------- GPIO generic keycode builder -------------------- */
static int build_key(struct saa7134_dev *dev)
{
struct saa7134_card_ir *ir = dev->remote;
u32 gpio, data;
/* here comes the additional handshake steps for some cards */
switch (dev->board) {
case SAA7134_BOARD_GOTVIEW_7135:
saa_setb(SAA7134_GPIO_GPSTATUS1, 0x80);
saa_clearb(SAA7134_GPIO_GPSTATUS1, 0x80);
break;
}
/* rising SAA7134_GPIO_GPRESCAN reads the status */
saa_clearb(SAA7134_GPIO_GPMODE3,SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3,SAA7134_GPIO_GPRESCAN);
gpio = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2);
if (ir->polling) {
if (ir->last_gpio == gpio)
return 0;
ir->last_gpio = gpio;
}
data = ir_extract_bits(gpio, ir->mask_keycode);
dprintk("build_key gpio=0x%x mask=0x%x data=%d\n",
gpio, ir->mask_keycode, data);
switch (dev->board) {
case SAA7134_BOARD_KWORLD_PLUS_TV_ANALOG:
if (data == ir->mask_keycode)
rc_keyup(ir->dev);
else
rc_keydown_notimeout(ir->dev, data, 0);
return 0;
}
if (ir->polling) {
if ((ir->mask_keydown && (0 != (gpio & ir->mask_keydown))) ||
(ir->mask_keyup && (0 == (gpio & ir->mask_keyup)))) {
rc_keydown_notimeout(ir->dev, data, 0);
} else {
rc_keyup(ir->dev);
}
}
else { /* IRQ driven mode - handle key press and release in one go */
if ((ir->mask_keydown && (0 != (gpio & ir->mask_keydown))) ||
(ir->mask_keyup && (0 == (gpio & ir->mask_keyup)))) {
rc_keydown_notimeout(ir->dev, data, 0);
rc_keyup(ir->dev);
}
}
return 0;
}
/* --------------------- Chip specific I2C key builders ----------------- */
static int get_key_flydvb_trio(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
int gpio;
int attempt = 0;
unsigned char b;
/* We need this to access GPI Used by the saa_readl macro. */
struct saa7134_dev *dev = ir->c->adapter->algo_data;
if (dev == NULL) {
i2cdprintk("get_key_flydvb_trio: "
"ir->c->adapter->algo_data is NULL!\n");
return -EIO;
}
/* rising SAA7134_GPIGPRESCAN reads the status */
saa_clearb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
gpio = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2);
if (0x40000 & ~gpio)
return 0; /* No button press */
/* No button press - only before first key pressed */
if (b == 0xFF)
return 0;
/* poll IR chip */
/* weak up the IR chip */
b = 0;
while (1 != i2c_master_send(ir->c, &b, 1)) {
if ((attempt++) < 10) {
/*
* wait a bit for next attempt -
* I don't know how make it better
*/
msleep(10);
continue;
}
i2cdprintk("send wake up byte to pic16C505 (IR chip)"
"failed %dx\n", attempt);
return -EIO;
}
if (1 != i2c_master_recv(ir->c, &b, 1)) {
i2cdprintk("read error\n");
return -EIO;
}
*ir_key = b;
*ir_raw = b;
return 1;
}
static int get_key_msi_tvanywhere_plus(struct IR_i2c *ir, u32 *ir_key,
u32 *ir_raw)
{
unsigned char b;
int gpio;
/* <dev> is needed to access GPIO. Used by the saa_readl macro. */
struct saa7134_dev *dev = ir->c->adapter->algo_data;
if (dev == NULL) {
i2cdprintk("get_key_msi_tvanywhere_plus: "
"ir->c->adapter->algo_data is NULL!\n");
return -EIO;
}
/* rising SAA7134_GPIO_GPRESCAN reads the status */
saa_clearb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
gpio = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2);
/* GPIO&0x40 is pulsed low when a button is pressed. Don't do
I2C receive if gpio&0x40 is not low. */
if (gpio & 0x40)
return 0; /* No button press */
/* GPIO says there is a button press. Get it. */
if (1 != i2c_master_recv(ir->c, &b, 1)) {
i2cdprintk("read error\n");
return -EIO;
}
/* No button press */
if (b == 0xff)
return 0;
/* Button pressed */
dprintk("get_key_msi_tvanywhere_plus: Key = 0x%02X\n", b);
*ir_key = b;
*ir_raw = b;
return 1;
}
/* copied and modified from get_key_msi_tvanywhere_plus() */
static int get_key_kworld_pc150u(struct IR_i2c *ir, u32 *ir_key,
u32 *ir_raw)
{
unsigned char b;
unsigned int gpio;
/* <dev> is needed to access GPIO. Used by the saa_readl macro. */
struct saa7134_dev *dev = ir->c->adapter->algo_data;
if (dev == NULL) {
i2cdprintk("get_key_kworld_pc150u: "
"ir->c->adapter->algo_data is NULL!\n");
return -EIO;
}
/* rising SAA7134_GPIO_GPRESCAN reads the status */
saa_clearb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
gpio = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2);
/* GPIO&0x100 is pulsed low when a button is pressed. Don't do
I2C receive if gpio&0x100 is not low. */
if (gpio & 0x100)
return 0; /* No button press */
/* GPIO says there is a button press. Get it. */
if (1 != i2c_master_recv(ir->c, &b, 1)) {
i2cdprintk("read error\n");
return -EIO;
}
/* No button press */
if (b == 0xff)
return 0;
/* Button pressed */
dprintk("get_key_kworld_pc150u: Key = 0x%02X\n", b);
*ir_key = b;
*ir_raw = b;
return 1;
}
static int get_key_purpletv(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
unsigned char b;
/* poll IR chip */
if (1 != i2c_master_recv(ir->c, &b, 1)) {
i2cdprintk("read error\n");
return -EIO;
}
/* no button press */
if (b==0)
return 0;
/* repeating */
if (b & 0x80)
return 1;
*ir_key = b;
*ir_raw = b;
return 1;
}
static int get_key_hvr1110(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
unsigned char buf[5];
/* poll IR chip */
if (5 != i2c_master_recv(ir->c, buf, 5))
return -EIO;
/* Check if some key were pressed */
if (!(buf[0] & 0x80))
return 0;
/*
* buf[3] & 0x80 is always high.
* buf[3] & 0x40 is a parity bit. A repeat event is marked
* by preserving it into two separate readings
* buf[4] bits 0 and 1, and buf[1] and buf[2] are always
* zero.
*/
*ir_key = 0x1fff & ((buf[3] << 8) | (buf[4] >> 2));
*ir_raw = *ir_key;
return 1;
}
static int get_key_beholdm6xx(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
unsigned char data[12];
u32 gpio;
struct saa7134_dev *dev = ir->c->adapter->algo_data;
/* rising SAA7134_GPIO_GPRESCAN reads the status */
saa_clearb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
gpio = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2);
if (0x400000 & ~gpio)
return 0; /* No button press */
ir->c->addr = 0x5a >> 1;
if (12 != i2c_master_recv(ir->c, data, 12)) {
i2cdprintk("read error\n");
return -EIO;
}
if (data[9] != (unsigned char)(~data[8]))
return 0;
*ir_raw = ((data[10] << 16) | (data[11] << 8) | (data[9] << 0));
*ir_key = *ir_raw;
return 1;
}
/* Common (grey or coloured) pinnacle PCTV remote handling
*
*/
static int get_key_pinnacle(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw,
int parity_offset, int marker, int code_modulo)
{
unsigned char b[4];
unsigned int start = 0,parity = 0,code = 0;
/* poll IR chip */
if (4 != i2c_master_recv(ir->c, b, 4)) {
i2cdprintk("read error\n");
return -EIO;
}
for (start = 0; start < ARRAY_SIZE(b); start++) {
if (b[start] == marker) {
code=b[(start+parity_offset + 1) % 4];
parity=b[(start+parity_offset) % 4];
}
}
/* Empty Request */
if (parity == 0)
return 0;
/* Repeating... */
if (ir->old == parity)
return 0;
ir->old = parity;
/* drop special codes when a key is held down a long time for the grey controller
In this case, the second bit of the code is asserted */
if (marker == 0xfe && (code & 0x40))
return 0;
code %= code_modulo;
*ir_raw = code;
*ir_key = code;
i2cdprintk("Pinnacle PCTV key %02x\n", code);
return 1;
}
/* The grey pinnacle PCTV remote
*
* There are one issue with this remote:
* - I2c packet does not change when the same key is pressed quickly. The workaround
* is to hold down each key for about half a second, so that another code is generated
* in the i2c packet, and the function can distinguish key presses.
*
* Sylvain Pasche <sylvain.pasche@gmail.com>
*/
static int get_key_pinnacle_grey(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
return get_key_pinnacle(ir, ir_key, ir_raw, 1, 0xfe, 0xff);
}
/* The new pinnacle PCTV remote (with the colored buttons)
*
* Ricardo Cerqueira <v4l@cerqueira.org>
*/
static int get_key_pinnacle_color(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
/* code_modulo parameter (0x88) is used to reduce code value to fit inside IR_KEYTAB_SIZE
*
* this is the only value that results in 42 unique
* codes < 128
*/
return get_key_pinnacle(ir, ir_key, ir_raw, 2, 0x80, 0x88);
}
void saa7134_input_irq(struct saa7134_dev *dev)
{
struct saa7134_card_ir *ir;
if (!dev || !dev->remote)
return;
ir = dev->remote;
if (!ir->running)
return;
if (!ir->polling && !ir->raw_decode) {
build_key(dev);
} else if (ir->raw_decode) {
saa7134_raw_decode_irq(dev);
}
}
static void saa7134_input_timer(unsigned long data)
{
struct saa7134_dev *dev = (struct saa7134_dev *)data;
struct saa7134_card_ir *ir = dev->remote;
build_key(dev);
mod_timer(&ir->timer, jiffies + msecs_to_jiffies(ir->polling));
}
static void ir_raw_decode_timer_end(unsigned long data)
{
struct saa7134_dev *dev = (struct saa7134_dev *)data;
struct saa7134_card_ir *ir = dev->remote;
ir_raw_event_handle(dev->remote->dev);
ir->active = false;
}
static int __saa7134_ir_start(void *priv)
{
struct saa7134_dev *dev = priv;
struct saa7134_card_ir *ir;
if (!dev || !dev->remote)
return -EINVAL;
ir = dev->remote;
if (ir->running)
return 0;
/* Moved here from saa7134_input_init1() because the latter
* is not called on device resume */
switch (dev->board) {
case SAA7134_BOARD_MD2819:
case SAA7134_BOARD_KWORLD_VSTREAM_XPERT:
case SAA7134_BOARD_AVERMEDIA_305:
case SAA7134_BOARD_AVERMEDIA_307:
case SAA7134_BOARD_AVERMEDIA_STUDIO_305:
case SAA7134_BOARD_AVERMEDIA_STUDIO_505:
case SAA7134_BOARD_AVERMEDIA_STUDIO_307:
case SAA7134_BOARD_AVERMEDIA_STUDIO_507:
case SAA7134_BOARD_AVERMEDIA_STUDIO_507UA:
case SAA7134_BOARD_AVERMEDIA_GO_007_FM:
case SAA7134_BOARD_AVERMEDIA_M102:
case SAA7134_BOARD_AVERMEDIA_GO_007_FM_PLUS:
/* Without this we won't receive key up events */
saa_setb(SAA7134_GPIO_GPMODE0, 0x4);
saa_setb(SAA7134_GPIO_GPSTATUS0, 0x4);
break;
case SAA7134_BOARD_AVERMEDIA_777:
case SAA7134_BOARD_AVERMEDIA_A16AR:
/* Without this we won't receive key up events */
saa_setb(SAA7134_GPIO_GPMODE1, 0x1);
saa_setb(SAA7134_GPIO_GPSTATUS1, 0x1);
break;
case SAA7134_BOARD_AVERMEDIA_A16D:
/* Without this we won't receive key up events */
saa_setb(SAA7134_GPIO_GPMODE1, 0x1);
saa_setb(SAA7134_GPIO_GPSTATUS1, 0x1);
break;
case SAA7134_BOARD_GOTVIEW_7135:
saa_setb(SAA7134_GPIO_GPMODE1, 0x80);
break;
}
ir->running = true;
ir->active = false;
if (ir->polling) {
setup_timer(&ir->timer, saa7134_input_timer,
(unsigned long)dev);
ir->timer.expires = jiffies + HZ;
add_timer(&ir->timer);
} else if (ir->raw_decode) {
/* set timer_end for code completion */
setup_timer(&ir->timer, ir_raw_decode_timer_end,
(unsigned long)dev);
}
return 0;
}
static void __saa7134_ir_stop(void *priv)
{
struct saa7134_dev *dev = priv;
struct saa7134_card_ir *ir;
if (!dev || !dev->remote)
return;
ir = dev->remote;
if (!ir->running)
return;
if (ir->polling || ir->raw_decode)
del_timer_sync(&ir->timer);
ir->active = false;
ir->running = false;
return;
}
int saa7134_ir_start(struct saa7134_dev *dev)
{
if (dev->remote->users)
return __saa7134_ir_start(dev);
return 0;
}
void saa7134_ir_stop(struct saa7134_dev *dev)
{
if (dev->remote->users)
__saa7134_ir_stop(dev);
}
static int saa7134_ir_open(struct rc_dev *rc)
{
struct saa7134_dev *dev = rc->priv;
dev->remote->users++;
return __saa7134_ir_start(dev);
}
static void saa7134_ir_close(struct rc_dev *rc)
{
struct saa7134_dev *dev = rc->priv;
dev->remote->users--;
if (!dev->remote->users)
__saa7134_ir_stop(dev);
}
int saa7134_input_init1(struct saa7134_dev *dev)
{
struct saa7134_card_ir *ir;
struct rc_dev *rc;
char *ir_codes = NULL;
u32 mask_keycode = 0;
u32 mask_keydown = 0;
u32 mask_keyup = 0;
unsigned polling = 0;
bool raw_decode = false;
int err;
if (dev->has_remote != SAA7134_REMOTE_GPIO)
return -ENODEV;
if (disable_ir)
return -ENODEV;
/* detect & configure */
switch (dev->board) {
case SAA7134_BOARD_FLYVIDEO2000:
case SAA7134_BOARD_FLYVIDEO3000:
case SAA7134_BOARD_FLYTVPLATINUM_FM:
case SAA7134_BOARD_FLYTVPLATINUM_MINI2:
case SAA7134_BOARD_ROVERMEDIA_LINK_PRO_FM:
ir_codes = RC_MAP_FLYVIDEO;
mask_keycode = 0xEC00000;
mask_keydown = 0x0040000;
break;
case SAA7134_BOARD_CINERGY400:
case SAA7134_BOARD_CINERGY600:
case SAA7134_BOARD_CINERGY600_MK3:
ir_codes = RC_MAP_CINERGY;
mask_keycode = 0x00003f;
mask_keyup = 0x040000;
break;
case SAA7134_BOARD_ECS_TVP3XP:
case SAA7134_BOARD_ECS_TVP3XP_4CB5:
ir_codes = RC_MAP_EZTV;
mask_keycode = 0x00017c;
mask_keyup = 0x000002;
polling = 50; // ms
break;
case SAA7134_BOARD_KWORLD_XPERT:
case SAA7134_BOARD_AVACSSMARTTV:
ir_codes = RC_MAP_PIXELVIEW;
mask_keycode = 0x00001F;
mask_keyup = 0x000020;
polling = 50; // ms
break;
case SAA7134_BOARD_MD2819:
case SAA7134_BOARD_KWORLD_VSTREAM_XPERT:
case SAA7134_BOARD_AVERMEDIA_305:
case SAA7134_BOARD_AVERMEDIA_307:
case SAA7134_BOARD_AVERMEDIA_STUDIO_305:
case SAA7134_BOARD_AVERMEDIA_STUDIO_505:
case SAA7134_BOARD_AVERMEDIA_STUDIO_307:
case SAA7134_BOARD_AVERMEDIA_STUDIO_507:
case SAA7134_BOARD_AVERMEDIA_STUDIO_507UA:
case SAA7134_BOARD_AVERMEDIA_GO_007_FM:
case SAA7134_BOARD_AVERMEDIA_M102:
case SAA7134_BOARD_AVERMEDIA_GO_007_FM_PLUS:
ir_codes = RC_MAP_AVERMEDIA;
mask_keycode = 0x0007C8;
mask_keydown = 0x000010;
polling = 50; // ms
/* GPIO stuff moved to __saa7134_ir_start() */
break;
case SAA7134_BOARD_AVERMEDIA_M135A:
ir_codes = RC_MAP_AVERMEDIA_M135A;
mask_keydown = 0x0040000; /* Enable GPIO18 line on both edges */
mask_keyup = 0x0040000;
mask_keycode = 0xffff;
raw_decode = true;
break;
case SAA7134_BOARD_AVERMEDIA_M733A:
ir_codes = RC_MAP_AVERMEDIA_M733A_RM_K6;
mask_keydown = 0x0040000;
mask_keyup = 0x0040000;
mask_keycode = 0xffff;
raw_decode = true;
break;
case SAA7134_BOARD_AVERMEDIA_777:
case SAA7134_BOARD_AVERMEDIA_A16AR:
ir_codes = RC_MAP_AVERMEDIA;
mask_keycode = 0x02F200;
mask_keydown = 0x000400;
polling = 50; // ms
/* GPIO stuff moved to __saa7134_ir_start() */
break;
case SAA7134_BOARD_AVERMEDIA_A16D:
ir_codes = RC_MAP_AVERMEDIA_A16D;
mask_keycode = 0x02F200;
mask_keydown = 0x000400;
polling = 50; /* ms */
/* GPIO stuff moved to __saa7134_ir_start() */
break;
case SAA7134_BOARD_KWORLD_TERMINATOR:
ir_codes = RC_MAP_PIXELVIEW;
mask_keycode = 0x00001f;
mask_keyup = 0x000060;
polling = 50; // ms
break;
case SAA7134_BOARD_MANLI_MTV001:
case SAA7134_BOARD_MANLI_MTV002:
ir_codes = RC_MAP_MANLI;
mask_keycode = 0x001f00;
mask_keyup = 0x004000;
polling = 50; /* ms */
break;
case SAA7134_BOARD_BEHOLD_409FM:
case SAA7134_BOARD_BEHOLD_401:
case SAA7134_BOARD_BEHOLD_403:
case SAA7134_BOARD_BEHOLD_403FM:
case SAA7134_BOARD_BEHOLD_405:
case SAA7134_BOARD_BEHOLD_405FM:
case SAA7134_BOARD_BEHOLD_407:
case SAA7134_BOARD_BEHOLD_407FM:
case SAA7134_BOARD_BEHOLD_409:
case SAA7134_BOARD_BEHOLD_505FM:
case SAA7134_BOARD_BEHOLD_505RDS_MK5:
case SAA7134_BOARD_BEHOLD_505RDS_MK3:
case SAA7134_BOARD_BEHOLD_507_9FM:
case SAA7134_BOARD_BEHOLD_507RDS_MK3:
case SAA7134_BOARD_BEHOLD_507RDS_MK5:
ir_codes = RC_MAP_MANLI;
mask_keycode = 0x003f00;
mask_keyup = 0x004000;
polling = 50; /* ms */
break;
case SAA7134_BOARD_BEHOLD_COLUMBUS_TVFM:
ir_codes = RC_MAP_BEHOLD_COLUMBUS;
mask_keycode = 0x003f00;
mask_keyup = 0x004000;
polling = 50; // ms
break;
case SAA7134_BOARD_SEDNA_PC_TV_CARDBUS:
ir_codes = RC_MAP_PCTV_SEDNA;
mask_keycode = 0x001f00;
mask_keyup = 0x004000;
polling = 50; // ms
break;
case SAA7134_BOARD_GOTVIEW_7135:
ir_codes = RC_MAP_GOTVIEW7135;
mask_keycode = 0x0003CC;
mask_keydown = 0x000010;
polling = 5; /* ms */
/* GPIO stuff moved to __saa7134_ir_start() */
break;
case SAA7134_BOARD_VIDEOMATE_TV_PVR:
case SAA7134_BOARD_VIDEOMATE_GOLD_PLUS:
case SAA7134_BOARD_VIDEOMATE_TV_GOLD_PLUSII:
ir_codes = RC_MAP_VIDEOMATE_TV_PVR;
mask_keycode = 0x00003F;
mask_keyup = 0x400000;
polling = 50; // ms
break;
case SAA7134_BOARD_PROTEUS_2309:
ir_codes = RC_MAP_PROTEUS_2309;
mask_keycode = 0x00007F;
mask_keyup = 0x000080;
polling = 50; // ms
break;
case SAA7134_BOARD_VIDEOMATE_DVBT_300:
case SAA7134_BOARD_VIDEOMATE_DVBT_200:
ir_codes = RC_MAP_VIDEOMATE_TV_PVR;
mask_keycode = 0x003F00;
mask_keyup = 0x040000;
break;
case SAA7134_BOARD_FLYDVBS_LR300:
case SAA7134_BOARD_FLYDVBT_LR301:
case SAA7134_BOARD_FLYDVBTDUO:
ir_codes = RC_MAP_FLYDVB;
mask_keycode = 0x0001F00;
mask_keydown = 0x0040000;
break;
case SAA7134_BOARD_ASUSTeK_P7131_DUAL:
case SAA7134_BOARD_ASUSTeK_P7131_HYBRID_LNA:
case SAA7134_BOARD_ASUSTeK_P7131_ANALOG:
ir_codes = RC_MAP_ASUS_PC39;
mask_keydown = 0x0040000; /* Enable GPIO18 line on both edges */
mask_keyup = 0x0040000;
mask_keycode = 0xffff;
raw_decode = true;
break;
case SAA7134_BOARD_ENCORE_ENLTV:
case SAA7134_BOARD_ENCORE_ENLTV_FM:
ir_codes = RC_MAP_ENCORE_ENLTV;
mask_keycode = 0x00007f;
mask_keyup = 0x040000;
polling = 50; // ms
break;
case SAA7134_BOARD_ENCORE_ENLTV_FM53:
case SAA7134_BOARD_ENCORE_ENLTV_FM3:
ir_codes = RC_MAP_ENCORE_ENLTV_FM53;
mask_keydown = 0x0040000; /* Enable GPIO18 line on both edges */
mask_keyup = 0x0040000;
mask_keycode = 0xffff;
raw_decode = true;
break;
case SAA7134_BOARD_10MOONSTVMASTER3:
ir_codes = RC_MAP_ENCORE_ENLTV;
mask_keycode = 0x5f80000;
mask_keyup = 0x8000000;
polling = 50; //ms
break;
case SAA7134_BOARD_GENIUS_TVGO_A11MCE:
ir_codes = RC_MAP_GENIUS_TVGO_A11MCE;
mask_keycode = 0xff;
mask_keydown = 0xf00000;
polling = 50; /* ms */
break;
case SAA7134_BOARD_REAL_ANGEL_220:
ir_codes = RC_MAP_REAL_AUDIO_220_32_KEYS;
mask_keycode = 0x3f00;
mask_keyup = 0x4000;
polling = 50; /* ms */
break;
case SAA7134_BOARD_KWORLD_PLUS_TV_ANALOG:
ir_codes = RC_MAP_KWORLD_PLUS_TV_ANALOG;
mask_keycode = 0x7f;
polling = 40; /* ms */
break;
case SAA7134_BOARD_VIDEOMATE_S350:
ir_codes = RC_MAP_VIDEOMATE_S350;
mask_keycode = 0x003f00;
mask_keydown = 0x040000;
break;
case SAA7134_BOARD_LEADTEK_WINFAST_DTV1000S:
ir_codes = RC_MAP_WINFAST;
mask_keycode = 0x5f00;
mask_keyup = 0x020000;
polling = 50; /* ms */
break;
case SAA7134_BOARD_VIDEOMATE_M1F:
ir_codes = RC_MAP_VIDEOMATE_K100;
mask_keycode = 0x0ff00;
mask_keyup = 0x040000;
break;
case SAA7134_BOARD_HAUPPAUGE_HVR1150:
case SAA7134_BOARD_HAUPPAUGE_HVR1120:
ir_codes = RC_MAP_HAUPPAUGE;
mask_keydown = 0x0040000; /* Enable GPIO18 line on both edges */
mask_keyup = 0x0040000;
mask_keycode = 0xffff;
raw_decode = true;
break;
}
if (NULL == ir_codes) {
printk("%s: Oops: IR config error [card=%d]\n",
dev->name, dev->board);
return -ENODEV;
}
ir = kzalloc(sizeof(*ir), GFP_KERNEL);
rc = rc_allocate_device();
if (!ir || !rc) {
err = -ENOMEM;
goto err_out_free;
}
ir->dev = rc;
dev->remote = ir;
/* init hardware-specific stuff */
ir->mask_keycode = mask_keycode;
ir->mask_keydown = mask_keydown;
ir->mask_keyup = mask_keyup;
ir->polling = polling;
ir->raw_decode = raw_decode;
/* init input device */
snprintf(ir->name, sizeof(ir->name), "saa7134 IR (%s)",
saa7134_boards[dev->board].name);
snprintf(ir->phys, sizeof(ir->phys), "pci-%s/ir0",
pci_name(dev->pci));
rc->priv = dev;
rc->open = saa7134_ir_open;
rc->close = saa7134_ir_close;
if (raw_decode)
rc->driver_type = RC_DRIVER_IR_RAW;
rc->input_name = ir->name;
rc->input_phys = ir->phys;
rc->input_id.bustype = BUS_PCI;
rc->input_id.version = 1;
if (dev->pci->subsystem_vendor) {
rc->input_id.vendor = dev->pci->subsystem_vendor;
rc->input_id.product = dev->pci->subsystem_device;
} else {
rc->input_id.vendor = dev->pci->vendor;
rc->input_id.product = dev->pci->device;
}
rc->dev.parent = &dev->pci->dev;
rc->map_name = ir_codes;
rc->driver_name = MODULE_NAME;
err = rc_register_device(rc);
if (err)
goto err_out_free;
return 0;
err_out_free:
rc_free_device(rc);
dev->remote = NULL;
kfree(ir);
return err;
}
void saa7134_input_fini(struct saa7134_dev *dev)
{
if (NULL == dev->remote)
return;
saa7134_ir_stop(dev);
rc_unregister_device(dev->remote->dev);
kfree(dev->remote);
dev->remote = NULL;
}
void saa7134_probe_i2c_ir(struct saa7134_dev *dev)
{
struct i2c_board_info info;
struct i2c_msg msg_msi = {
.addr = 0x50,
.flags = I2C_M_RD,
.len = 0,
.buf = NULL,
};
int rc;
if (disable_ir) {
dprintk("IR has been disabled, not probing for i2c remote\n");
return;
}
memset(&info, 0, sizeof(struct i2c_board_info));
memset(&dev->init_data, 0, sizeof(dev->init_data));
strlcpy(info.type, "ir_video", I2C_NAME_SIZE);
switch (dev->board) {
case SAA7134_BOARD_PINNACLE_PCTV_110i:
case SAA7134_BOARD_PINNACLE_PCTV_310i:
dev->init_data.name = "Pinnacle PCTV";
if (pinnacle_remote == 0) {
dev->init_data.get_key = get_key_pinnacle_color;
dev->init_data.ir_codes = RC_MAP_PINNACLE_COLOR;
info.addr = 0x47;
} else {
dev->init_data.get_key = get_key_pinnacle_grey;
dev->init_data.ir_codes = RC_MAP_PINNACLE_GREY;
info.addr = 0x47;
}
break;
case SAA7134_BOARD_UPMOST_PURPLE_TV:
dev->init_data.name = "Purple TV";
dev->init_data.get_key = get_key_purpletv;
dev->init_data.ir_codes = RC_MAP_PURPLETV;
info.addr = 0x7a;
break;
case SAA7134_BOARD_MSI_TVATANYWHERE_PLUS:
dev->init_data.name = "MSI TV@nywhere Plus";
dev->init_data.get_key = get_key_msi_tvanywhere_plus;
dev->init_data.ir_codes = RC_MAP_MSI_TVANYWHERE_PLUS;
/*
* MSI TV@nyware Plus requires more frequent polling
* otherwise it will miss some keypresses
*/
dev->init_data.polling_interval = 50;
info.addr = 0x30;
/* MSI TV@nywhere Plus controller doesn't seem to
respond to probes unless we read something from
an existing device. Weird...
REVISIT: might no longer be needed */
rc = i2c_transfer(&dev->i2c_adap, &msg_msi, 1);
dprintk("probe 0x%02x @ %s: %s\n",
msg_msi.addr, dev->i2c_adap.name,
(1 == rc) ? "yes" : "no");
break;
case SAA7134_BOARD_KWORLD_PC150U:
/* copied and modified from MSI TV@nywhere Plus */
dev->init_data.name = "Kworld PC150-U";
dev->init_data.get_key = get_key_kworld_pc150u;
dev->init_data.ir_codes = RC_MAP_KWORLD_PC150U;
info.addr = 0x30;
/* MSI TV@nywhere Plus controller doesn't seem to
respond to probes unless we read something from
an existing device. Weird...
REVISIT: might no longer be needed */
rc = i2c_transfer(&dev->i2c_adap, &msg_msi, 1);
dprintk("probe 0x%02x @ %s: %s\n",
msg_msi.addr, dev->i2c_adap.name,
(1 == rc) ? "yes" : "no");
break;
case SAA7134_BOARD_HAUPPAUGE_HVR1110:
dev->init_data.name = "HVR 1110";
dev->init_data.get_key = get_key_hvr1110;
dev->init_data.ir_codes = RC_MAP_HAUPPAUGE;
info.addr = 0x71;
break;
case SAA7134_BOARD_BEHOLD_607FM_MK3:
case SAA7134_BOARD_BEHOLD_607FM_MK5:
case SAA7134_BOARD_BEHOLD_609FM_MK3:
case SAA7134_BOARD_BEHOLD_609FM_MK5:
case SAA7134_BOARD_BEHOLD_607RDS_MK3:
case SAA7134_BOARD_BEHOLD_607RDS_MK5:
case SAA7134_BOARD_BEHOLD_609RDS_MK3:
case SAA7134_BOARD_BEHOLD_609RDS_MK5:
case SAA7134_BOARD_BEHOLD_M6:
case SAA7134_BOARD_BEHOLD_M63:
case SAA7134_BOARD_BEHOLD_M6_EXTRA:
case SAA7134_BOARD_BEHOLD_H6:
case SAA7134_BOARD_BEHOLD_X7:
case SAA7134_BOARD_BEHOLD_H7:
case SAA7134_BOARD_BEHOLD_A7:
dev->init_data.name = "BeholdTV";
dev->init_data.get_key = get_key_beholdm6xx;
dev->init_data.ir_codes = RC_MAP_BEHOLD;
dev->init_data.type = RC_TYPE_NEC;
info.addr = 0x2d;
break;
case SAA7134_BOARD_AVERMEDIA_CARDBUS_501:
case SAA7134_BOARD_AVERMEDIA_CARDBUS_506:
info.addr = 0x40;
break;
case SAA7134_BOARD_FLYDVB_TRIO:
dev->init_data.name = "FlyDVB Trio";
dev->init_data.get_key = get_key_flydvb_trio;
dev->init_data.ir_codes = RC_MAP_FLYDVB;
info.addr = 0x0b;
break;
default:
dprintk("No I2C IR support for board %x\n", dev->board);
return;
}
if (dev->init_data.name)
info.platform_data = &dev->init_data;
i2c_new_device(&dev->i2c_adap, &info);
}
static int saa7134_raw_decode_irq(struct saa7134_dev *dev)
{
struct saa7134_card_ir *ir = dev->remote;
unsigned long timeout;
int space;
/* Generate initial event */
saa_clearb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
saa_setb(SAA7134_GPIO_GPMODE3, SAA7134_GPIO_GPRESCAN);
space = saa_readl(SAA7134_GPIO_GPSTATUS0 >> 2) & ir->mask_keydown;
ir_raw_event_store_edge(dev->remote->dev, space ? IR_SPACE : IR_PULSE);
/*
* Wait 15 ms from the start of the first IR event before processing
* the event. This time is enough for NEC protocol. May need adjustments
* to work with other protocols.
*/
if (!ir->active) {
timeout = jiffies + msecs_to_jiffies(15);
mod_timer(&ir->timer, timeout);
ir->active = true;
}
return 1;
}
| gpl-2.0 |
martynbm/kernel-millet3g-sm-t331_kk | arch/x86/kernel/aperture_64.c | 4812 | 14448 | /*
* Firmware replacement code.
*
* Work around broken BIOSes that don't set an aperture, only set the
* aperture in the AGP bridge, or set too small aperture.
*
* If all fails map the aperture over some low memory. This is cheaper than
* doing bounce buffering. The memory is lost. This is done at early boot
* because only the bootmem allocator can allocate 32+MB.
*
* Copyright 2002 Andi Kleen, SuSE Labs.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/memblock.h>
#include <linux/mmzone.h>
#include <linux/pci_ids.h>
#include <linux/pci.h>
#include <linux/bitops.h>
#include <linux/ioport.h>
#include <linux/suspend.h>
#include <linux/kmemleak.h>
#include <asm/e820.h>
#include <asm/io.h>
#include <asm/iommu.h>
#include <asm/gart.h>
#include <asm/pci-direct.h>
#include <asm/dma.h>
#include <asm/amd_nb.h>
#include <asm/x86_init.h>
/*
* Using 512M as goal, in case kexec will load kernel_big
* that will do the on-position decompress, and could overlap with
* with the gart aperture that is used.
* Sequence:
* kernel_small
* ==> kexec (with kdump trigger path or gart still enabled)
* ==> kernel_small (gart area become e820_reserved)
* ==> kexec (with kdump trigger path or gart still enabled)
* ==> kerne_big (uncompressed size will be big than 64M or 128M)
* So don't use 512M below as gart iommu, leave the space for kernel
* code for safe.
*/
#define GART_MIN_ADDR (512ULL << 20)
#define GART_MAX_ADDR (1ULL << 32)
int gart_iommu_aperture;
int gart_iommu_aperture_disabled __initdata;
int gart_iommu_aperture_allowed __initdata;
int fallback_aper_order __initdata = 1; /* 64MB */
int fallback_aper_force __initdata;
int fix_aperture __initdata = 1;
static struct resource gart_resource = {
.name = "GART",
.flags = IORESOURCE_MEM,
};
static void __init insert_aperture_resource(u32 aper_base, u32 aper_size)
{
gart_resource.start = aper_base;
gart_resource.end = aper_base + aper_size - 1;
insert_resource(&iomem_resource, &gart_resource);
}
/* This code runs before the PCI subsystem is initialized, so just
access the northbridge directly. */
static u32 __init allocate_aperture(void)
{
u32 aper_size;
unsigned long addr;
/* aper_size should <= 1G */
if (fallback_aper_order > 5)
fallback_aper_order = 5;
aper_size = (32 * 1024 * 1024) << fallback_aper_order;
/*
* Aperture has to be naturally aligned. This means a 2GB aperture
* won't have much chance of finding a place in the lower 4GB of
* memory. Unfortunately we cannot move it up because that would
* make the IOMMU useless.
*/
addr = memblock_find_in_range(GART_MIN_ADDR, GART_MAX_ADDR,
aper_size, aper_size);
if (!addr || addr + aper_size > GART_MAX_ADDR) {
printk(KERN_ERR
"Cannot allocate aperture memory hole (%lx,%uK)\n",
addr, aper_size>>10);
return 0;
}
memblock_reserve(addr, aper_size);
/*
* Kmemleak should not scan this block as it may not be mapped via the
* kernel direct mapping.
*/
kmemleak_ignore(phys_to_virt(addr));
printk(KERN_INFO "Mapping aperture over %d KB of RAM @ %lx\n",
aper_size >> 10, addr);
insert_aperture_resource((u32)addr, aper_size);
register_nosave_region(addr >> PAGE_SHIFT,
(addr+aper_size) >> PAGE_SHIFT);
return (u32)addr;
}
/* Find a PCI capability */
static u32 __init find_cap(int bus, int slot, int func, int cap)
{
int bytes;
u8 pos;
if (!(read_pci_config_16(bus, slot, func, PCI_STATUS) &
PCI_STATUS_CAP_LIST))
return 0;
pos = read_pci_config_byte(bus, slot, func, PCI_CAPABILITY_LIST);
for (bytes = 0; bytes < 48 && pos >= 0x40; bytes++) {
u8 id;
pos &= ~3;
id = read_pci_config_byte(bus, slot, func, pos+PCI_CAP_LIST_ID);
if (id == 0xff)
break;
if (id == cap)
return pos;
pos = read_pci_config_byte(bus, slot, func,
pos+PCI_CAP_LIST_NEXT);
}
return 0;
}
/* Read a standard AGPv3 bridge header */
static u32 __init read_agp(int bus, int slot, int func, int cap, u32 *order)
{
u32 apsize;
u32 apsizereg;
int nbits;
u32 aper_low, aper_hi;
u64 aper;
u32 old_order;
printk(KERN_INFO "AGP bridge at %02x:%02x:%02x\n", bus, slot, func);
apsizereg = read_pci_config_16(bus, slot, func, cap + 0x14);
if (apsizereg == 0xffffffff) {
printk(KERN_ERR "APSIZE in AGP bridge unreadable\n");
return 0;
}
/* old_order could be the value from NB gart setting */
old_order = *order;
apsize = apsizereg & 0xfff;
/* Some BIOS use weird encodings not in the AGPv3 table. */
if (apsize & 0xff)
apsize |= 0xf00;
nbits = hweight16(apsize);
*order = 7 - nbits;
if ((int)*order < 0) /* < 32MB */
*order = 0;
aper_low = read_pci_config(bus, slot, func, 0x10);
aper_hi = read_pci_config(bus, slot, func, 0x14);
aper = (aper_low & ~((1<<22)-1)) | ((u64)aper_hi << 32);
/*
* On some sick chips, APSIZE is 0. It means it wants 4G
* so let double check that order, and lets trust AMD NB settings:
*/
printk(KERN_INFO "Aperture from AGP @ %Lx old size %u MB\n",
aper, 32 << old_order);
if (aper + (32ULL<<(20 + *order)) > 0x100000000ULL) {
printk(KERN_INFO "Aperture size %u MB (APSIZE %x) is not right, using settings from NB\n",
32 << *order, apsizereg);
*order = old_order;
}
printk(KERN_INFO "Aperture from AGP @ %Lx size %u MB (APSIZE %x)\n",
aper, 32 << *order, apsizereg);
if (!aperture_valid(aper, (32*1024*1024) << *order, 32<<20))
return 0;
return (u32)aper;
}
/*
* Look for an AGP bridge. Windows only expects the aperture in the
* AGP bridge and some BIOS forget to initialize the Northbridge too.
* Work around this here.
*
* Do an PCI bus scan by hand because we're running before the PCI
* subsystem.
*
* All AMD AGP bridges are AGPv3 compliant, so we can do this scan
* generically. It's probably overkill to always scan all slots because
* the AGP bridges should be always an own bus on the HT hierarchy,
* but do it here for future safety.
*/
static u32 __init search_agp_bridge(u32 *order, int *valid_agp)
{
int bus, slot, func;
/* Poor man's PCI discovery */
for (bus = 0; bus < 256; bus++) {
for (slot = 0; slot < 32; slot++) {
for (func = 0; func < 8; func++) {
u32 class, cap;
u8 type;
class = read_pci_config(bus, slot, func,
PCI_CLASS_REVISION);
if (class == 0xffffffff)
break;
switch (class >> 16) {
case PCI_CLASS_BRIDGE_HOST:
case PCI_CLASS_BRIDGE_OTHER: /* needed? */
/* AGP bridge? */
cap = find_cap(bus, slot, func,
PCI_CAP_ID_AGP);
if (!cap)
break;
*valid_agp = 1;
return read_agp(bus, slot, func, cap,
order);
}
/* No multi-function device? */
type = read_pci_config_byte(bus, slot, func,
PCI_HEADER_TYPE);
if (!(type & 0x80))
break;
}
}
}
printk(KERN_INFO "No AGP bridge found\n");
return 0;
}
static int gart_fix_e820 __initdata = 1;
static int __init parse_gart_mem(char *p)
{
if (!p)
return -EINVAL;
if (!strncmp(p, "off", 3))
gart_fix_e820 = 0;
else if (!strncmp(p, "on", 2))
gart_fix_e820 = 1;
return 0;
}
early_param("gart_fix_e820", parse_gart_mem);
void __init early_gart_iommu_check(void)
{
/*
* in case it is enabled before, esp for kexec/kdump,
* previous kernel already enable that. memset called
* by allocate_aperture/__alloc_bootmem_nopanic cause restart.
* or second kernel have different position for GART hole. and new
* kernel could use hole as RAM that is still used by GART set by
* first kernel
* or BIOS forget to put that in reserved.
* try to update e820 to make that region as reserved.
*/
u32 agp_aper_order = 0;
int i, fix, slot, valid_agp = 0;
u32 ctl;
u32 aper_size = 0, aper_order = 0, last_aper_order = 0;
u64 aper_base = 0, last_aper_base = 0;
int aper_enabled = 0, last_aper_enabled = 0, last_valid = 0;
if (!early_pci_allowed())
return;
/* This is mostly duplicate of iommu_hole_init */
search_agp_bridge(&agp_aper_order, &valid_agp);
fix = 0;
for (i = 0; amd_nb_bus_dev_ranges[i].dev_limit; i++) {
int bus;
int dev_base, dev_limit;
bus = amd_nb_bus_dev_ranges[i].bus;
dev_base = amd_nb_bus_dev_ranges[i].dev_base;
dev_limit = amd_nb_bus_dev_ranges[i].dev_limit;
for (slot = dev_base; slot < dev_limit; slot++) {
if (!early_is_amd_nb(read_pci_config(bus, slot, 3, 0x00)))
continue;
ctl = read_pci_config(bus, slot, 3, AMD64_GARTAPERTURECTL);
aper_enabled = ctl & GARTEN;
aper_order = (ctl >> 1) & 7;
aper_size = (32 * 1024 * 1024) << aper_order;
aper_base = read_pci_config(bus, slot, 3, AMD64_GARTAPERTUREBASE) & 0x7fff;
aper_base <<= 25;
if (last_valid) {
if ((aper_order != last_aper_order) ||
(aper_base != last_aper_base) ||
(aper_enabled != last_aper_enabled)) {
fix = 1;
break;
}
}
last_aper_order = aper_order;
last_aper_base = aper_base;
last_aper_enabled = aper_enabled;
last_valid = 1;
}
}
if (!fix && !aper_enabled)
return;
if (!aper_base || !aper_size || aper_base + aper_size > 0x100000000UL)
fix = 1;
if (gart_fix_e820 && !fix && aper_enabled) {
if (e820_any_mapped(aper_base, aper_base + aper_size,
E820_RAM)) {
/* reserve it, so we can reuse it in second kernel */
printk(KERN_INFO "update e820 for GART\n");
e820_add_region(aper_base, aper_size, E820_RESERVED);
update_e820();
}
}
if (valid_agp)
return;
/* disable them all at first */
for (i = 0; i < amd_nb_bus_dev_ranges[i].dev_limit; i++) {
int bus;
int dev_base, dev_limit;
bus = amd_nb_bus_dev_ranges[i].bus;
dev_base = amd_nb_bus_dev_ranges[i].dev_base;
dev_limit = amd_nb_bus_dev_ranges[i].dev_limit;
for (slot = dev_base; slot < dev_limit; slot++) {
if (!early_is_amd_nb(read_pci_config(bus, slot, 3, 0x00)))
continue;
ctl = read_pci_config(bus, slot, 3, AMD64_GARTAPERTURECTL);
ctl &= ~GARTEN;
write_pci_config(bus, slot, 3, AMD64_GARTAPERTURECTL, ctl);
}
}
}
static int __initdata printed_gart_size_msg;
int __init gart_iommu_hole_init(void)
{
u32 agp_aper_base = 0, agp_aper_order = 0;
u32 aper_size, aper_alloc = 0, aper_order = 0, last_aper_order = 0;
u64 aper_base, last_aper_base = 0;
int fix, slot, valid_agp = 0;
int i, node;
if (gart_iommu_aperture_disabled || !fix_aperture ||
!early_pci_allowed())
return -ENODEV;
printk(KERN_INFO "Checking aperture...\n");
if (!fallback_aper_force)
agp_aper_base = search_agp_bridge(&agp_aper_order, &valid_agp);
fix = 0;
node = 0;
for (i = 0; i < amd_nb_bus_dev_ranges[i].dev_limit; i++) {
int bus;
int dev_base, dev_limit;
u32 ctl;
bus = amd_nb_bus_dev_ranges[i].bus;
dev_base = amd_nb_bus_dev_ranges[i].dev_base;
dev_limit = amd_nb_bus_dev_ranges[i].dev_limit;
for (slot = dev_base; slot < dev_limit; slot++) {
if (!early_is_amd_nb(read_pci_config(bus, slot, 3, 0x00)))
continue;
iommu_detected = 1;
gart_iommu_aperture = 1;
x86_init.iommu.iommu_init = gart_iommu_init;
ctl = read_pci_config(bus, slot, 3,
AMD64_GARTAPERTURECTL);
/*
* Before we do anything else disable the GART. It may
* still be enabled if we boot into a crash-kernel here.
* Reconfiguring the GART while it is enabled could have
* unknown side-effects.
*/
ctl &= ~GARTEN;
write_pci_config(bus, slot, 3, AMD64_GARTAPERTURECTL, ctl);
aper_order = (ctl >> 1) & 7;
aper_size = (32 * 1024 * 1024) << aper_order;
aper_base = read_pci_config(bus, slot, 3, AMD64_GARTAPERTUREBASE) & 0x7fff;
aper_base <<= 25;
printk(KERN_INFO "Node %d: aperture @ %Lx size %u MB\n",
node, aper_base, aper_size >> 20);
node++;
if (!aperture_valid(aper_base, aper_size, 64<<20)) {
if (valid_agp && agp_aper_base &&
agp_aper_base == aper_base &&
agp_aper_order == aper_order) {
/* the same between two setting from NB and agp */
if (!no_iommu &&
max_pfn > MAX_DMA32_PFN &&
!printed_gart_size_msg) {
printk(KERN_ERR "you are using iommu with agp, but GART size is less than 64M\n");
printk(KERN_ERR "please increase GART size in your BIOS setup\n");
printk(KERN_ERR "if BIOS doesn't have that option, contact your HW vendor!\n");
printed_gart_size_msg = 1;
}
} else {
fix = 1;
goto out;
}
}
if ((last_aper_order && aper_order != last_aper_order) ||
(last_aper_base && aper_base != last_aper_base)) {
fix = 1;
goto out;
}
last_aper_order = aper_order;
last_aper_base = aper_base;
}
}
out:
if (!fix && !fallback_aper_force) {
if (last_aper_base) {
unsigned long n = (32 * 1024 * 1024) << last_aper_order;
insert_aperture_resource((u32)last_aper_base, n);
return 1;
}
return 0;
}
if (!fallback_aper_force) {
aper_alloc = agp_aper_base;
aper_order = agp_aper_order;
}
if (aper_alloc) {
/* Got the aperture from the AGP bridge */
} else if ((!no_iommu && max_pfn > MAX_DMA32_PFN) ||
force_iommu ||
valid_agp ||
fallback_aper_force) {
printk(KERN_INFO
"Your BIOS doesn't leave a aperture memory hole\n");
printk(KERN_INFO
"Please enable the IOMMU option in the BIOS setup\n");
printk(KERN_INFO
"This costs you %d MB of RAM\n",
32 << fallback_aper_order);
aper_order = fallback_aper_order;
aper_alloc = allocate_aperture();
if (!aper_alloc) {
/*
* Could disable AGP and IOMMU here, but it's
* probably not worth it. But the later users
* cannot deal with bad apertures and turning
* on the aperture over memory causes very
* strange problems, so it's better to panic
* early.
*/
panic("Not enough memory for aperture");
}
} else {
return 0;
}
/* Fix up the north bridges */
for (i = 0; i < amd_nb_bus_dev_ranges[i].dev_limit; i++) {
int bus, dev_base, dev_limit;
/*
* Don't enable translation yet but enable GART IO and CPU
* accesses and set DISTLBWALKPRB since GART table memory is UC.
*/
u32 ctl = aper_order << 1;
bus = amd_nb_bus_dev_ranges[i].bus;
dev_base = amd_nb_bus_dev_ranges[i].dev_base;
dev_limit = amd_nb_bus_dev_ranges[i].dev_limit;
for (slot = dev_base; slot < dev_limit; slot++) {
if (!early_is_amd_nb(read_pci_config(bus, slot, 3, 0x00)))
continue;
write_pci_config(bus, slot, 3, AMD64_GARTAPERTURECTL, ctl);
write_pci_config(bus, slot, 3, AMD64_GARTAPERTUREBASE, aper_alloc >> 25);
}
}
set_up_gart_resume(aper_order, aper_alloc);
return 1;
}
| gpl-2.0 |
Tegra4/android_kernel_hp_maya | drivers/media/video/gspca/sn9c20x.c | 4812 | 71049 | /*
* Sonix sn9c201 sn9c202 library
*
* Copyright (C) 2012 Jean-Francois Moine <http://moinejf.free.fr>
* Copyright (C) 2008-2009 microdia project <microdia@googlegroups.com>
* Copyright (C) 2009 Brian Johnson <brijohn@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
* 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/input.h>
#include "gspca.h"
#include "jpeg.h"
#include <media/v4l2-chip-ident.h>
#include <linux/dmi.h>
MODULE_AUTHOR("Brian Johnson <brijohn@gmail.com>, "
"microdia project <microdia@googlegroups.com>");
MODULE_DESCRIPTION("GSPCA/SN9C20X USB Camera Driver");
MODULE_LICENSE("GPL");
/*
* Pixel format private data
*/
#define SCALE_MASK 0x0f
#define SCALE_160x120 0
#define SCALE_320x240 1
#define SCALE_640x480 2
#define SCALE_1280x1024 3
#define MODE_RAW 0x10
#define MODE_JPEG 0x20
#define MODE_SXGA 0x80
#define SENSOR_OV9650 0
#define SENSOR_OV9655 1
#define SENSOR_SOI968 2
#define SENSOR_OV7660 3
#define SENSOR_OV7670 4
#define SENSOR_MT9V011 5
#define SENSOR_MT9V111 6
#define SENSOR_MT9V112 7
#define SENSOR_MT9M001 8
#define SENSOR_MT9M111 9
#define SENSOR_MT9M112 10
#define SENSOR_HV7131R 11
#define SENSOR_MT9VPRB 20
/* camera flags */
#define HAS_NO_BUTTON 0x1
#define LED_REVERSE 0x2 /* some cameras unset gpio to turn on leds */
#define FLIP_DETECT 0x4
enum e_ctrl {
BRIGHTNESS,
CONTRAST,
SATURATION,
HUE,
GAMMA,
BLUE,
RED,
VFLIP,
HFLIP,
EXPOSURE,
GAIN,
AUTOGAIN,
QUALITY,
NCTRLS /* number of controls */
};
/* specific webcam descriptor */
struct sd {
struct gspca_dev gspca_dev;
struct gspca_ctrl ctrls[NCTRLS];
struct work_struct work;
struct workqueue_struct *work_thread;
u32 pktsz; /* (used by pkt_scan) */
u16 npkt;
s8 nchg;
u8 fmt; /* (used for JPEG QTAB update */
#define MIN_AVG_LUM 80
#define MAX_AVG_LUM 130
atomic_t avg_lum;
u8 old_step;
u8 older_step;
u8 exposure_step;
u8 i2c_addr;
u8 sensor;
u8 hstart;
u8 vstart;
u8 jpeg_hdr[JPEG_HDR_SZ];
u8 flags;
};
static void qual_upd(struct work_struct *work);
struct i2c_reg_u8 {
u8 reg;
u8 val;
};
struct i2c_reg_u16 {
u8 reg;
u16 val;
};
static const struct dmi_system_id flip_dmi_table[] = {
{
.ident = "MSI MS-1034",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "MICRO-STAR INT'L CO.,LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "MS-1034"),
DMI_MATCH(DMI_PRODUCT_VERSION, "0341")
}
},
{
.ident = "MSI MS-1632",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "MSI"),
DMI_MATCH(DMI_BOARD_NAME, "MS-1632")
}
},
{
.ident = "MSI MS-1633X",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "MSI"),
DMI_MATCH(DMI_BOARD_NAME, "MS-1633X")
}
},
{
.ident = "MSI MS-1635X",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "MSI"),
DMI_MATCH(DMI_BOARD_NAME, "MS-1635X")
}
},
{
.ident = "ASUSTeK W7J",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "ASUSTeK Computer Inc."),
DMI_MATCH(DMI_BOARD_NAME, "W7J ")
}
},
{}
};
static void set_cmatrix(struct gspca_dev *gspca_dev);
static void set_gamma(struct gspca_dev *gspca_dev);
static void set_redblue(struct gspca_dev *gspca_dev);
static void set_hvflip(struct gspca_dev *gspca_dev);
static void set_exposure(struct gspca_dev *gspca_dev);
static void set_gain(struct gspca_dev *gspca_dev);
static void set_quality(struct gspca_dev *gspca_dev);
static const struct ctrl sd_ctrls[NCTRLS] = {
[BRIGHTNESS] = {
{
.id = V4L2_CID_BRIGHTNESS,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Brightness",
.minimum = 0,
.maximum = 0xff,
.step = 1,
.default_value = 0x7f
},
.set_control = set_cmatrix
},
[CONTRAST] = {
{
.id = V4L2_CID_CONTRAST,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Contrast",
.minimum = 0,
.maximum = 0xff,
.step = 1,
.default_value = 0x7f
},
.set_control = set_cmatrix
},
[SATURATION] = {
{
.id = V4L2_CID_SATURATION,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Saturation",
.minimum = 0,
.maximum = 0xff,
.step = 1,
.default_value = 0x7f
},
.set_control = set_cmatrix
},
[HUE] = {
{
.id = V4L2_CID_HUE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Hue",
.minimum = -180,
.maximum = 180,
.step = 1,
.default_value = 0
},
.set_control = set_cmatrix
},
[GAMMA] = {
{
.id = V4L2_CID_GAMMA,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Gamma",
.minimum = 0,
.maximum = 0xff,
.step = 1,
.default_value = 0x10
},
.set_control = set_gamma
},
[BLUE] = {
{
.id = V4L2_CID_BLUE_BALANCE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Blue Balance",
.minimum = 0,
.maximum = 0x7f,
.step = 1,
.default_value = 0x28
},
.set_control = set_redblue
},
[RED] = {
{
.id = V4L2_CID_RED_BALANCE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Red Balance",
.minimum = 0,
.maximum = 0x7f,
.step = 1,
.default_value = 0x28
},
.set_control = set_redblue
},
[HFLIP] = {
{
.id = V4L2_CID_HFLIP,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Horizontal Flip",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 0,
},
.set_control = set_hvflip
},
[VFLIP] = {
{
.id = V4L2_CID_VFLIP,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Vertical Flip",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 0,
},
.set_control = set_hvflip
},
[EXPOSURE] = {
{
.id = V4L2_CID_EXPOSURE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Exposure",
.minimum = 0,
.maximum = 0x1780,
.step = 1,
.default_value = 0x33,
},
.set_control = set_exposure
},
[GAIN] = {
{
.id = V4L2_CID_GAIN,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Gain",
.minimum = 0,
.maximum = 28,
.step = 1,
.default_value = 0,
},
.set_control = set_gain
},
[AUTOGAIN] = {
{
.id = V4L2_CID_AUTOGAIN,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Auto Exposure",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 1,
},
},
[QUALITY] = {
{
.id = V4L2_CID_JPEG_COMPRESSION_QUALITY,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Compression Quality",
#define QUALITY_MIN 50
#define QUALITY_MAX 90
#define QUALITY_DEF 80
.minimum = QUALITY_MIN,
.maximum = QUALITY_MAX,
.step = 1,
.default_value = QUALITY_DEF,
},
.set_control = set_quality
},
};
static const struct v4l2_pix_format vga_mode[] = {
{160, 120, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 160,
.sizeimage = 160 * 120 * 4 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = SCALE_160x120 | MODE_JPEG},
{160, 120, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE,
.bytesperline = 160,
.sizeimage = 160 * 120,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = SCALE_160x120 | MODE_RAW},
{160, 120, V4L2_PIX_FMT_SN9C20X_I420, V4L2_FIELD_NONE,
.bytesperline = 160,
.sizeimage = 240 * 120,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = SCALE_160x120},
{320, 240, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 * 4 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = SCALE_320x240 | MODE_JPEG},
{320, 240, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 ,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = SCALE_320x240 | MODE_RAW},
{320, 240, V4L2_PIX_FMT_SN9C20X_I420, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 480 * 240 ,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = SCALE_320x240},
{640, 480, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 640 * 480 * 4 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = SCALE_640x480 | MODE_JPEG},
{640, 480, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 640 * 480,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = SCALE_640x480 | MODE_RAW},
{640, 480, V4L2_PIX_FMT_SN9C20X_I420, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 960 * 480,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = SCALE_640x480},
};
static const struct v4l2_pix_format sxga_mode[] = {
{160, 120, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 160,
.sizeimage = 160 * 120 * 4 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = SCALE_160x120 | MODE_JPEG},
{160, 120, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE,
.bytesperline = 160,
.sizeimage = 160 * 120,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = SCALE_160x120 | MODE_RAW},
{160, 120, V4L2_PIX_FMT_SN9C20X_I420, V4L2_FIELD_NONE,
.bytesperline = 160,
.sizeimage = 240 * 120,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = SCALE_160x120},
{320, 240, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 * 4 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = SCALE_320x240 | MODE_JPEG},
{320, 240, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 ,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = SCALE_320x240 | MODE_RAW},
{320, 240, V4L2_PIX_FMT_SN9C20X_I420, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 480 * 240 ,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = SCALE_320x240},
{640, 480, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 640 * 480 * 4 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = SCALE_640x480 | MODE_JPEG},
{640, 480, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 640 * 480,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = SCALE_640x480 | MODE_RAW},
{640, 480, V4L2_PIX_FMT_SN9C20X_I420, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 960 * 480,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = SCALE_640x480},
{1280, 1024, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE,
.bytesperline = 1280,
.sizeimage = 1280 * 1024,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = SCALE_1280x1024 | MODE_RAW | MODE_SXGA},
};
static const struct v4l2_pix_format mono_mode[] = {
{160, 120, V4L2_PIX_FMT_GREY, V4L2_FIELD_NONE,
.bytesperline = 160,
.sizeimage = 160 * 120,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = SCALE_160x120 | MODE_RAW},
{320, 240, V4L2_PIX_FMT_GREY, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 ,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = SCALE_320x240 | MODE_RAW},
{640, 480, V4L2_PIX_FMT_GREY, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 640 * 480,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = SCALE_640x480 | MODE_RAW},
{1280, 1024, V4L2_PIX_FMT_GREY, V4L2_FIELD_NONE,
.bytesperline = 1280,
.sizeimage = 1280 * 1024,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = SCALE_1280x1024 | MODE_RAW | MODE_SXGA},
};
static const s16 hsv_red_x[] = {
41, 44, 46, 48, 50, 52, 54, 56,
58, 60, 62, 64, 66, 68, 70, 72,
74, 76, 78, 80, 81, 83, 85, 87,
88, 90, 92, 93, 95, 97, 98, 100,
101, 102, 104, 105, 107, 108, 109, 110,
112, 113, 114, 115, 116, 117, 118, 119,
120, 121, 122, 123, 123, 124, 125, 125,
126, 127, 127, 128, 128, 129, 129, 129,
130, 130, 130, 130, 131, 131, 131, 131,
131, 131, 131, 131, 130, 130, 130, 130,
129, 129, 129, 128, 128, 127, 127, 126,
125, 125, 124, 123, 122, 122, 121, 120,
119, 118, 117, 116, 115, 114, 112, 111,
110, 109, 107, 106, 105, 103, 102, 101,
99, 98, 96, 94, 93, 91, 90, 88,
86, 84, 83, 81, 79, 77, 75, 74,
72, 70, 68, 66, 64, 62, 60, 58,
56, 54, 52, 49, 47, 45, 43, 41,
39, 36, 34, 32, 30, 28, 25, 23,
21, 19, 16, 14, 12, 9, 7, 5,
3, 0, -1, -3, -6, -8, -10, -12,
-15, -17, -19, -22, -24, -26, -28, -30,
-33, -35, -37, -39, -41, -44, -46, -48,
-50, -52, -54, -56, -58, -60, -62, -64,
-66, -68, -70, -72, -74, -76, -78, -80,
-81, -83, -85, -87, -88, -90, -92, -93,
-95, -97, -98, -100, -101, -102, -104, -105,
-107, -108, -109, -110, -112, -113, -114, -115,
-116, -117, -118, -119, -120, -121, -122, -123,
-123, -124, -125, -125, -126, -127, -127, -128,
-128, -128, -128, -128, -128, -128, -128, -128,
-128, -128, -128, -128, -128, -128, -128, -128,
-128, -128, -128, -128, -128, -128, -128, -128,
-128, -127, -127, -126, -125, -125, -124, -123,
-122, -122, -121, -120, -119, -118, -117, -116,
-115, -114, -112, -111, -110, -109, -107, -106,
-105, -103, -102, -101, -99, -98, -96, -94,
-93, -91, -90, -88, -86, -84, -83, -81,
-79, -77, -75, -74, -72, -70, -68, -66,
-64, -62, -60, -58, -56, -54, -52, -49,
-47, -45, -43, -41, -39, -36, -34, -32,
-30, -28, -25, -23, -21, -19, -16, -14,
-12, -9, -7, -5, -3, 0, 1, 3,
6, 8, 10, 12, 15, 17, 19, 22,
24, 26, 28, 30, 33, 35, 37, 39, 41
};
static const s16 hsv_red_y[] = {
82, 80, 78, 76, 74, 73, 71, 69,
67, 65, 63, 61, 58, 56, 54, 52,
50, 48, 46, 44, 41, 39, 37, 35,
32, 30, 28, 26, 23, 21, 19, 16,
14, 12, 10, 7, 5, 3, 0, -1,
-3, -6, -8, -10, -13, -15, -17, -19,
-22, -24, -26, -29, -31, -33, -35, -38,
-40, -42, -44, -46, -48, -51, -53, -55,
-57, -59, -61, -63, -65, -67, -69, -71,
-73, -75, -77, -79, -81, -82, -84, -86,
-88, -89, -91, -93, -94, -96, -98, -99,
-101, -102, -104, -105, -106, -108, -109, -110,
-112, -113, -114, -115, -116, -117, -119, -120,
-120, -121, -122, -123, -124, -125, -126, -126,
-127, -128, -128, -128, -128, -128, -128, -128,
-128, -128, -128, -128, -128, -128, -128, -128,
-128, -128, -128, -128, -128, -128, -128, -128,
-128, -128, -128, -128, -128, -128, -128, -128,
-127, -127, -126, -125, -125, -124, -123, -122,
-121, -120, -119, -118, -117, -116, -115, -114,
-113, -111, -110, -109, -107, -106, -105, -103,
-102, -100, -99, -97, -96, -94, -92, -91,
-89, -87, -85, -84, -82, -80, -78, -76,
-74, -73, -71, -69, -67, -65, -63, -61,
-58, -56, -54, -52, -50, -48, -46, -44,
-41, -39, -37, -35, -32, -30, -28, -26,
-23, -21, -19, -16, -14, -12, -10, -7,
-5, -3, 0, 1, 3, 6, 8, 10,
13, 15, 17, 19, 22, 24, 26, 29,
31, 33, 35, 38, 40, 42, 44, 46,
48, 51, 53, 55, 57, 59, 61, 63,
65, 67, 69, 71, 73, 75, 77, 79,
81, 82, 84, 86, 88, 89, 91, 93,
94, 96, 98, 99, 101, 102, 104, 105,
106, 108, 109, 110, 112, 113, 114, 115,
116, 117, 119, 120, 120, 121, 122, 123,
124, 125, 126, 126, 127, 128, 128, 129,
129, 130, 130, 131, 131, 131, 131, 132,
132, 132, 132, 132, 132, 132, 132, 132,
132, 132, 132, 131, 131, 131, 130, 130,
130, 129, 129, 128, 127, 127, 126, 125,
125, 124, 123, 122, 121, 120, 119, 118,
117, 116, 115, 114, 113, 111, 110, 109,
107, 106, 105, 103, 102, 100, 99, 97,
96, 94, 92, 91, 89, 87, 85, 84, 82
};
static const s16 hsv_green_x[] = {
-124, -124, -125, -125, -125, -125, -125, -125,
-125, -126, -126, -125, -125, -125, -125, -125,
-125, -124, -124, -124, -123, -123, -122, -122,
-121, -121, -120, -120, -119, -118, -117, -117,
-116, -115, -114, -113, -112, -111, -110, -109,
-108, -107, -105, -104, -103, -102, -100, -99,
-98, -96, -95, -93, -92, -91, -89, -87,
-86, -84, -83, -81, -79, -77, -76, -74,
-72, -70, -69, -67, -65, -63, -61, -59,
-57, -55, -53, -51, -49, -47, -45, -43,
-41, -39, -37, -35, -33, -30, -28, -26,
-24, -22, -20, -18, -15, -13, -11, -9,
-7, -4, -2, 0, 1, 3, 6, 8,
10, 12, 14, 17, 19, 21, 23, 25,
27, 29, 32, 34, 36, 38, 40, 42,
44, 46, 48, 50, 52, 54, 56, 58,
60, 62, 64, 66, 68, 70, 71, 73,
75, 77, 78, 80, 82, 83, 85, 87,
88, 90, 91, 93, 94, 96, 97, 98,
100, 101, 102, 104, 105, 106, 107, 108,
109, 111, 112, 113, 113, 114, 115, 116,
117, 118, 118, 119, 120, 120, 121, 122,
122, 123, 123, 124, 124, 124, 125, 125,
125, 125, 125, 125, 125, 126, 126, 125,
125, 125, 125, 125, 125, 124, 124, 124,
123, 123, 122, 122, 121, 121, 120, 120,
119, 118, 117, 117, 116, 115, 114, 113,
112, 111, 110, 109, 108, 107, 105, 104,
103, 102, 100, 99, 98, 96, 95, 93,
92, 91, 89, 87, 86, 84, 83, 81,
79, 77, 76, 74, 72, 70, 69, 67,
65, 63, 61, 59, 57, 55, 53, 51,
49, 47, 45, 43, 41, 39, 37, 35,
33, 30, 28, 26, 24, 22, 20, 18,
15, 13, 11, 9, 7, 4, 2, 0,
-1, -3, -6, -8, -10, -12, -14, -17,
-19, -21, -23, -25, -27, -29, -32, -34,
-36, -38, -40, -42, -44, -46, -48, -50,
-52, -54, -56, -58, -60, -62, -64, -66,
-68, -70, -71, -73, -75, -77, -78, -80,
-82, -83, -85, -87, -88, -90, -91, -93,
-94, -96, -97, -98, -100, -101, -102, -104,
-105, -106, -107, -108, -109, -111, -112, -113,
-113, -114, -115, -116, -117, -118, -118, -119,
-120, -120, -121, -122, -122, -123, -123, -124, -124
};
static const s16 hsv_green_y[] = {
-100, -99, -98, -97, -95, -94, -93, -91,
-90, -89, -87, -86, -84, -83, -81, -80,
-78, -76, -75, -73, -71, -70, -68, -66,
-64, -63, -61, -59, -57, -55, -53, -51,
-49, -48, -46, -44, -42, -40, -38, -36,
-34, -32, -30, -27, -25, -23, -21, -19,
-17, -15, -13, -11, -9, -7, -4, -2,
0, 1, 3, 5, 7, 9, 11, 14,
16, 18, 20, 22, 24, 26, 28, 30,
32, 34, 36, 38, 40, 42, 44, 46,
48, 50, 52, 54, 56, 58, 59, 61,
63, 65, 67, 68, 70, 72, 74, 75,
77, 78, 80, 82, 83, 85, 86, 88,
89, 90, 92, 93, 95, 96, 97, 98,
100, 101, 102, 103, 104, 105, 106, 107,
108, 109, 110, 111, 112, 112, 113, 114,
115, 115, 116, 116, 117, 117, 118, 118,
119, 119, 119, 120, 120, 120, 120, 120,
121, 121, 121, 121, 121, 121, 120, 120,
120, 120, 120, 119, 119, 119, 118, 118,
117, 117, 116, 116, 115, 114, 114, 113,
112, 111, 111, 110, 109, 108, 107, 106,
105, 104, 103, 102, 100, 99, 98, 97,
95, 94, 93, 91, 90, 89, 87, 86,
84, 83, 81, 80, 78, 76, 75, 73,
71, 70, 68, 66, 64, 63, 61, 59,
57, 55, 53, 51, 49, 48, 46, 44,
42, 40, 38, 36, 34, 32, 30, 27,
25, 23, 21, 19, 17, 15, 13, 11,
9, 7, 4, 2, 0, -1, -3, -5,
-7, -9, -11, -14, -16, -18, -20, -22,
-24, -26, -28, -30, -32, -34, -36, -38,
-40, -42, -44, -46, -48, -50, -52, -54,
-56, -58, -59, -61, -63, -65, -67, -68,
-70, -72, -74, -75, -77, -78, -80, -82,
-83, -85, -86, -88, -89, -90, -92, -93,
-95, -96, -97, -98, -100, -101, -102, -103,
-104, -105, -106, -107, -108, -109, -110, -111,
-112, -112, -113, -114, -115, -115, -116, -116,
-117, -117, -118, -118, -119, -119, -119, -120,
-120, -120, -120, -120, -121, -121, -121, -121,
-121, -121, -120, -120, -120, -120, -120, -119,
-119, -119, -118, -118, -117, -117, -116, -116,
-115, -114, -114, -113, -112, -111, -111, -110,
-109, -108, -107, -106, -105, -104, -103, -102, -100
};
static const s16 hsv_blue_x[] = {
112, 113, 114, 114, 115, 116, 117, 117,
118, 118, 119, 119, 120, 120, 120, 121,
121, 121, 122, 122, 122, 122, 122, 122,
122, 122, 122, 122, 122, 122, 121, 121,
121, 120, 120, 120, 119, 119, 118, 118,
117, 116, 116, 115, 114, 113, 113, 112,
111, 110, 109, 108, 107, 106, 105, 104,
103, 102, 100, 99, 98, 97, 95, 94,
93, 91, 90, 88, 87, 85, 84, 82,
80, 79, 77, 76, 74, 72, 70, 69,
67, 65, 63, 61, 60, 58, 56, 54,
52, 50, 48, 46, 44, 42, 40, 38,
36, 34, 32, 30, 28, 26, 24, 22,
19, 17, 15, 13, 11, 9, 7, 5,
2, 0, -1, -3, -5, -7, -9, -12,
-14, -16, -18, -20, -22, -24, -26, -28,
-31, -33, -35, -37, -39, -41, -43, -45,
-47, -49, -51, -53, -54, -56, -58, -60,
-62, -64, -66, -67, -69, -71, -73, -74,
-76, -78, -79, -81, -83, -84, -86, -87,
-89, -90, -92, -93, -94, -96, -97, -98,
-99, -101, -102, -103, -104, -105, -106, -107,
-108, -109, -110, -111, -112, -113, -114, -114,
-115, -116, -117, -117, -118, -118, -119, -119,
-120, -120, -120, -121, -121, -121, -122, -122,
-122, -122, -122, -122, -122, -122, -122, -122,
-122, -122, -121, -121, -121, -120, -120, -120,
-119, -119, -118, -118, -117, -116, -116, -115,
-114, -113, -113, -112, -111, -110, -109, -108,
-107, -106, -105, -104, -103, -102, -100, -99,
-98, -97, -95, -94, -93, -91, -90, -88,
-87, -85, -84, -82, -80, -79, -77, -76,
-74, -72, -70, -69, -67, -65, -63, -61,
-60, -58, -56, -54, -52, -50, -48, -46,
-44, -42, -40, -38, -36, -34, -32, -30,
-28, -26, -24, -22, -19, -17, -15, -13,
-11, -9, -7, -5, -2, 0, 1, 3,
5, 7, 9, 12, 14, 16, 18, 20,
22, 24, 26, 28, 31, 33, 35, 37,
39, 41, 43, 45, 47, 49, 51, 53,
54, 56, 58, 60, 62, 64, 66, 67,
69, 71, 73, 74, 76, 78, 79, 81,
83, 84, 86, 87, 89, 90, 92, 93,
94, 96, 97, 98, 99, 101, 102, 103,
104, 105, 106, 107, 108, 109, 110, 111, 112
};
static const s16 hsv_blue_y[] = {
-11, -13, -15, -17, -19, -21, -23, -25,
-27, -29, -31, -33, -35, -37, -39, -41,
-43, -45, -46, -48, -50, -52, -54, -55,
-57, -59, -61, -62, -64, -66, -67, -69,
-71, -72, -74, -75, -77, -78, -80, -81,
-83, -84, -86, -87, -88, -90, -91, -92,
-93, -95, -96, -97, -98, -99, -100, -101,
-102, -103, -104, -105, -106, -106, -107, -108,
-109, -109, -110, -111, -111, -112, -112, -113,
-113, -114, -114, -114, -115, -115, -115, -115,
-116, -116, -116, -116, -116, -116, -116, -116,
-116, -115, -115, -115, -115, -114, -114, -114,
-113, -113, -112, -112, -111, -111, -110, -110,
-109, -108, -108, -107, -106, -105, -104, -103,
-102, -101, -100, -99, -98, -97, -96, -95,
-94, -93, -91, -90, -89, -88, -86, -85,
-84, -82, -81, -79, -78, -76, -75, -73,
-71, -70, -68, -67, -65, -63, -62, -60,
-58, -56, -55, -53, -51, -49, -47, -45,
-44, -42, -40, -38, -36, -34, -32, -30,
-28, -26, -24, -22, -20, -18, -16, -14,
-12, -10, -8, -6, -4, -2, 0, 1,
3, 5, 7, 9, 11, 13, 15, 17,
19, 21, 23, 25, 27, 29, 31, 33,
35, 37, 39, 41, 43, 45, 46, 48,
50, 52, 54, 55, 57, 59, 61, 62,
64, 66, 67, 69, 71, 72, 74, 75,
77, 78, 80, 81, 83, 84, 86, 87,
88, 90, 91, 92, 93, 95, 96, 97,
98, 99, 100, 101, 102, 103, 104, 105,
106, 106, 107, 108, 109, 109, 110, 111,
111, 112, 112, 113, 113, 114, 114, 114,
115, 115, 115, 115, 116, 116, 116, 116,
116, 116, 116, 116, 116, 115, 115, 115,
115, 114, 114, 114, 113, 113, 112, 112,
111, 111, 110, 110, 109, 108, 108, 107,
106, 105, 104, 103, 102, 101, 100, 99,
98, 97, 96, 95, 94, 93, 91, 90,
89, 88, 86, 85, 84, 82, 81, 79,
78, 76, 75, 73, 71, 70, 68, 67,
65, 63, 62, 60, 58, 56, 55, 53,
51, 49, 47, 45, 44, 42, 40, 38,
36, 34, 32, 30, 28, 26, 24, 22,
20, 18, 16, 14, 12, 10, 8, 6,
4, 2, 0, -1, -3, -5, -7, -9, -11
};
static u16 i2c_ident[] = {
V4L2_IDENT_OV9650,
V4L2_IDENT_OV9655,
V4L2_IDENT_SOI968,
V4L2_IDENT_OV7660,
V4L2_IDENT_OV7670,
V4L2_IDENT_MT9V011,
V4L2_IDENT_MT9V111,
V4L2_IDENT_MT9V112,
V4L2_IDENT_MT9M001C12ST,
V4L2_IDENT_MT9M111,
V4L2_IDENT_MT9M112,
V4L2_IDENT_HV7131R,
};
static u16 bridge_init[][2] = {
{0x1000, 0x78}, {0x1001, 0x40}, {0x1002, 0x1c},
{0x1020, 0x80}, {0x1061, 0x01}, {0x1067, 0x40},
{0x1068, 0x30}, {0x1069, 0x20}, {0x106a, 0x10},
{0x106b, 0x08}, {0x1188, 0x87}, {0x11a1, 0x00},
{0x11a2, 0x00}, {0x11a3, 0x6a}, {0x11a4, 0x50},
{0x11ab, 0x00}, {0x11ac, 0x00}, {0x11ad, 0x50},
{0x11ae, 0x3c}, {0x118a, 0x04}, {0x0395, 0x04},
{0x11b8, 0x3a}, {0x118b, 0x0e}, {0x10f7, 0x05},
{0x10f8, 0x14}, {0x10fa, 0xff}, {0x10f9, 0x00},
{0x11ba, 0x0a}, {0x11a5, 0x2d}, {0x11a6, 0x2d},
{0x11a7, 0x3a}, {0x11a8, 0x05}, {0x11a9, 0x04},
{0x11aa, 0x3f}, {0x11af, 0x28}, {0x11b0, 0xd8},
{0x11b1, 0x14}, {0x11b2, 0xec}, {0x11b3, 0x32},
{0x11b4, 0xdd}, {0x11b5, 0x32}, {0x11b6, 0xdd},
{0x10e0, 0x2c}, {0x11bc, 0x40}, {0x11bd, 0x01},
{0x11be, 0xf0}, {0x11bf, 0x00}, {0x118c, 0x1f},
{0x118d, 0x1f}, {0x118e, 0x1f}, {0x118f, 0x1f},
{0x1180, 0x01}, {0x1181, 0x00}, {0x1182, 0x01},
{0x1183, 0x00}, {0x1184, 0x50}, {0x1185, 0x80},
{0x1007, 0x00}
};
/* Gain = (bit[3:0] / 16 + 1) * (bit[4] + 1) * (bit[5] + 1) * (bit[6] + 1) */
static u8 ov_gain[] = {
0x00 /* 1x */, 0x04 /* 1.25x */, 0x08 /* 1.5x */, 0x0c /* 1.75x */,
0x10 /* 2x */, 0x12 /* 2.25x */, 0x14 /* 2.5x */, 0x16 /* 2.75x */,
0x18 /* 3x */, 0x1a /* 3.25x */, 0x1c /* 3.5x */, 0x1e /* 3.75x */,
0x30 /* 4x */, 0x31 /* 4.25x */, 0x32 /* 4.5x */, 0x33 /* 4.75x */,
0x34 /* 5x */, 0x35 /* 5.25x */, 0x36 /* 5.5x */, 0x37 /* 5.75x */,
0x38 /* 6x */, 0x39 /* 6.25x */, 0x3a /* 6.5x */, 0x3b /* 6.75x */,
0x3c /* 7x */, 0x3d /* 7.25x */, 0x3e /* 7.5x */, 0x3f /* 7.75x */,
0x70 /* 8x */
};
/* Gain = (bit[8] + 1) * (bit[7] + 1) * (bit[6:0] * 0.03125) */
static u16 micron1_gain[] = {
/* 1x 1.25x 1.5x 1.75x */
0x0020, 0x0028, 0x0030, 0x0038,
/* 2x 2.25x 2.5x 2.75x */
0x00a0, 0x00a4, 0x00a8, 0x00ac,
/* 3x 3.25x 3.5x 3.75x */
0x00b0, 0x00b4, 0x00b8, 0x00bc,
/* 4x 4.25x 4.5x 4.75x */
0x00c0, 0x00c4, 0x00c8, 0x00cc,
/* 5x 5.25x 5.5x 5.75x */
0x00d0, 0x00d4, 0x00d8, 0x00dc,
/* 6x 6.25x 6.5x 6.75x */
0x00e0, 0x00e4, 0x00e8, 0x00ec,
/* 7x 7.25x 7.5x 7.75x */
0x00f0, 0x00f4, 0x00f8, 0x00fc,
/* 8x */
0x01c0
};
/* mt9m001 sensor uses a different gain formula then other micron sensors */
/* Gain = (bit[6] + 1) * (bit[5-0] * 0.125) */
static u16 micron2_gain[] = {
/* 1x 1.25x 1.5x 1.75x */
0x0008, 0x000a, 0x000c, 0x000e,
/* 2x 2.25x 2.5x 2.75x */
0x0010, 0x0012, 0x0014, 0x0016,
/* 3x 3.25x 3.5x 3.75x */
0x0018, 0x001a, 0x001c, 0x001e,
/* 4x 4.25x 4.5x 4.75x */
0x0020, 0x0051, 0x0052, 0x0053,
/* 5x 5.25x 5.5x 5.75x */
0x0054, 0x0055, 0x0056, 0x0057,
/* 6x 6.25x 6.5x 6.75x */
0x0058, 0x0059, 0x005a, 0x005b,
/* 7x 7.25x 7.5x 7.75x */
0x005c, 0x005d, 0x005e, 0x005f,
/* 8x */
0x0060
};
/* Gain = .5 + bit[7:0] / 16 */
static u8 hv7131r_gain[] = {
0x08 /* 1x */, 0x0c /* 1.25x */, 0x10 /* 1.5x */, 0x14 /* 1.75x */,
0x18 /* 2x */, 0x1c /* 2.25x */, 0x20 /* 2.5x */, 0x24 /* 2.75x */,
0x28 /* 3x */, 0x2c /* 3.25x */, 0x30 /* 3.5x */, 0x34 /* 3.75x */,
0x38 /* 4x */, 0x3c /* 4.25x */, 0x40 /* 4.5x */, 0x44 /* 4.75x */,
0x48 /* 5x */, 0x4c /* 5.25x */, 0x50 /* 5.5x */, 0x54 /* 5.75x */,
0x58 /* 6x */, 0x5c /* 6.25x */, 0x60 /* 6.5x */, 0x64 /* 6.75x */,
0x68 /* 7x */, 0x6c /* 7.25x */, 0x70 /* 7.5x */, 0x74 /* 7.75x */,
0x78 /* 8x */
};
static struct i2c_reg_u8 soi968_init[] = {
{0x0c, 0x00}, {0x0f, 0x1f},
{0x11, 0x80}, {0x38, 0x52}, {0x1e, 0x00},
{0x33, 0x08}, {0x35, 0x8c}, {0x36, 0x0c},
{0x37, 0x04}, {0x45, 0x04}, {0x47, 0xff},
{0x3e, 0x00}, {0x3f, 0x00}, {0x3b, 0x20},
{0x3a, 0x96}, {0x3d, 0x0a}, {0x14, 0x8e},
{0x13, 0x8b}, {0x12, 0x40}, {0x17, 0x13},
{0x18, 0x63}, {0x19, 0x01}, {0x1a, 0x79},
{0x32, 0x24}, {0x03, 0x00}, {0x11, 0x40},
{0x2a, 0x10}, {0x2b, 0xe0}, {0x10, 0x32},
{0x00, 0x00}, {0x01, 0x80}, {0x02, 0x80},
};
static struct i2c_reg_u8 ov7660_init[] = {
{0x0e, 0x80}, {0x0d, 0x08}, {0x0f, 0xc3},
{0x04, 0xc3}, {0x10, 0x40}, {0x11, 0x40},
{0x12, 0x05}, {0x13, 0xba}, {0x14, 0x2a},
/* HDG Set hstart and hstop, datasheet default 0x11, 0x61, using
0x10, 0x61 and sd->hstart, vstart = 3, fixes ugly colored borders */
{0x17, 0x10}, {0x18, 0x61},
{0x37, 0x0f}, {0x38, 0x02}, {0x39, 0x43},
{0x3a, 0x00}, {0x69, 0x90}, {0x2d, 0xf6},
{0x2e, 0x0b}, {0x01, 0x78}, {0x02, 0x50},
};
static struct i2c_reg_u8 ov7670_init[] = {
{0x11, 0x80}, {0x3a, 0x04}, {0x12, 0x01},
{0x32, 0xb6}, {0x03, 0x0a}, {0x0c, 0x00}, {0x3e, 0x00},
{0x70, 0x3a}, {0x71, 0x35}, {0x72, 0x11}, {0x73, 0xf0},
{0xa2, 0x02}, {0x13, 0xe0}, {0x00, 0x00}, {0x10, 0x00},
{0x0d, 0x40}, {0x14, 0x28}, {0xa5, 0x05}, {0xab, 0x07},
{0x24, 0x95}, {0x25, 0x33}, {0x26, 0xe3}, {0x9f, 0x75},
{0xa0, 0x65}, {0xa1, 0x0b}, {0xa6, 0xd8}, {0xa7, 0xd8},
{0xa8, 0xf0}, {0xa9, 0x90}, {0xaa, 0x94}, {0x13, 0xe5},
{0x0e, 0x61}, {0x0f, 0x4b}, {0x16, 0x02}, {0x1e, 0x27},
{0x21, 0x02}, {0x22, 0x91}, {0x29, 0x07}, {0x33, 0x0b},
{0x35, 0x0b}, {0x37, 0x1d}, {0x38, 0x71}, {0x39, 0x2a},
{0x3c, 0x78}, {0x4d, 0x40}, {0x4e, 0x20}, {0x69, 0x00},
{0x74, 0x19}, {0x8d, 0x4f}, {0x8e, 0x00}, {0x8f, 0x00},
{0x90, 0x00}, {0x91, 0x00}, {0x96, 0x00}, {0x9a, 0x80},
{0xb0, 0x84}, {0xb1, 0x0c}, {0xb2, 0x0e}, {0xb3, 0x82},
{0xb8, 0x0a}, {0x43, 0x0a}, {0x44, 0xf0}, {0x45, 0x20},
{0x46, 0x7d}, {0x47, 0x29}, {0x48, 0x4a}, {0x59, 0x8c},
{0x5a, 0xa5}, {0x5b, 0xde}, {0x5c, 0x96}, {0x5d, 0x66},
{0x5e, 0x10}, {0x6c, 0x0a}, {0x6d, 0x55}, {0x6e, 0x11},
{0x6f, 0x9e}, {0x6a, 0x40}, {0x01, 0x40}, {0x02, 0x40},
{0x13, 0xe7}, {0x4f, 0x6e}, {0x50, 0x70}, {0x51, 0x02},
{0x52, 0x1d}, {0x53, 0x56}, {0x54, 0x73}, {0x55, 0x0a},
{0x56, 0x55}, {0x57, 0x80}, {0x58, 0x9e}, {0x41, 0x08},
{0x3f, 0x02}, {0x75, 0x03}, {0x76, 0x63}, {0x4c, 0x04},
{0x77, 0x06}, {0x3d, 0x02}, {0x4b, 0x09}, {0xc9, 0x30},
{0x41, 0x08}, {0x56, 0x48}, {0x34, 0x11}, {0xa4, 0x88},
{0x96, 0x00}, {0x97, 0x30}, {0x98, 0x20}, {0x99, 0x30},
{0x9a, 0x84}, {0x9b, 0x29}, {0x9c, 0x03}, {0x9d, 0x99},
{0x9e, 0x7f}, {0x78, 0x04}, {0x79, 0x01}, {0xc8, 0xf0},
{0x79, 0x0f}, {0xc8, 0x00}, {0x79, 0x10}, {0xc8, 0x7e},
{0x79, 0x0a}, {0xc8, 0x80}, {0x79, 0x0b}, {0xc8, 0x01},
{0x79, 0x0c}, {0xc8, 0x0f}, {0x79, 0x0d}, {0xc8, 0x20},
{0x79, 0x09}, {0xc8, 0x80}, {0x79, 0x02}, {0xc8, 0xc0},
{0x79, 0x03}, {0xc8, 0x40}, {0x79, 0x05}, {0xc8, 0x30},
{0x79, 0x26}, {0x62, 0x20}, {0x63, 0x00}, {0x64, 0x06},
{0x65, 0x00}, {0x66, 0x05}, {0x94, 0x05}, {0x95, 0x0a},
{0x17, 0x13}, {0x18, 0x01}, {0x19, 0x02}, {0x1a, 0x7a},
{0x46, 0x59}, {0x47, 0x30}, {0x58, 0x9a}, {0x59, 0x84},
{0x5a, 0x91}, {0x5b, 0x57}, {0x5c, 0x75}, {0x5d, 0x6d},
{0x5e, 0x13}, {0x64, 0x07}, {0x94, 0x07}, {0x95, 0x0d},
{0xa6, 0xdf}, {0xa7, 0xdf}, {0x48, 0x4d}, {0x51, 0x00},
{0x6b, 0x0a}, {0x11, 0x80}, {0x2a, 0x00}, {0x2b, 0x00},
{0x92, 0x00}, {0x93, 0x00}, {0x55, 0x0a}, {0x56, 0x60},
{0x4f, 0x6e}, {0x50, 0x70}, {0x51, 0x00}, {0x52, 0x1d},
{0x53, 0x56}, {0x54, 0x73}, {0x58, 0x9a}, {0x4f, 0x6e},
{0x50, 0x70}, {0x51, 0x00}, {0x52, 0x1d}, {0x53, 0x56},
{0x54, 0x73}, {0x58, 0x9a}, {0x3f, 0x01}, {0x7b, 0x03},
{0x7c, 0x09}, {0x7d, 0x16}, {0x7e, 0x38}, {0x7f, 0x47},
{0x80, 0x53}, {0x81, 0x5e}, {0x82, 0x6a}, {0x83, 0x74},
{0x84, 0x80}, {0x85, 0x8c}, {0x86, 0x9b}, {0x87, 0xb2},
{0x88, 0xcc}, {0x89, 0xe5}, {0x7a, 0x24}, {0x3b, 0x00},
{0x9f, 0x76}, {0xa0, 0x65}, {0x13, 0xe2}, {0x6b, 0x0a},
{0x11, 0x80}, {0x2a, 0x00}, {0x2b, 0x00}, {0x92, 0x00},
{0x93, 0x00},
};
static struct i2c_reg_u8 ov9650_init[] = {
{0x00, 0x00}, {0x01, 0x78},
{0x02, 0x78}, {0x03, 0x36}, {0x04, 0x03},
{0x05, 0x00}, {0x06, 0x00}, {0x08, 0x00},
{0x09, 0x01}, {0x0c, 0x00}, {0x0d, 0x00},
{0x0e, 0xa0}, {0x0f, 0x52}, {0x10, 0x7c},
{0x11, 0x80}, {0x12, 0x45}, {0x13, 0xc2},
{0x14, 0x2e}, {0x15, 0x00}, {0x16, 0x07},
{0x17, 0x24}, {0x18, 0xc5}, {0x19, 0x00},
{0x1a, 0x3c}, {0x1b, 0x00}, {0x1e, 0x04},
{0x1f, 0x00}, {0x24, 0x78}, {0x25, 0x68},
{0x26, 0xd4}, {0x27, 0x80}, {0x28, 0x80},
{0x29, 0x30}, {0x2a, 0x00}, {0x2b, 0x00},
{0x2c, 0x80}, {0x2d, 0x00}, {0x2e, 0x00},
{0x2f, 0x00}, {0x30, 0x08}, {0x31, 0x30},
{0x32, 0x84}, {0x33, 0xe2}, {0x34, 0xbf},
{0x35, 0x81}, {0x36, 0xf9}, {0x37, 0x00},
{0x38, 0x93}, {0x39, 0x50}, {0x3a, 0x01},
{0x3b, 0x01}, {0x3c, 0x73}, {0x3d, 0x19},
{0x3e, 0x0b}, {0x3f, 0x80}, {0x40, 0xc1},
{0x41, 0x00}, {0x42, 0x08}, {0x67, 0x80},
{0x68, 0x80}, {0x69, 0x40}, {0x6a, 0x00},
{0x6b, 0x0a}, {0x8b, 0x06}, {0x8c, 0x20},
{0x8d, 0x00}, {0x8e, 0x00}, {0x8f, 0xdf},
{0x92, 0x00}, {0x93, 0x00}, {0x94, 0x88},
{0x95, 0x88}, {0x96, 0x04}, {0xa1, 0x00},
{0xa5, 0x80}, {0xa8, 0x80}, {0xa9, 0xb8},
{0xaa, 0x92}, {0xab, 0x0a},
};
static struct i2c_reg_u8 ov9655_init[] = {
{0x0e, 0x61}, {0x11, 0x80}, {0x13, 0xba},
{0x14, 0x2e}, {0x16, 0x24}, {0x1e, 0x04}, {0x27, 0x08},
{0x28, 0x08}, {0x29, 0x15}, {0x2c, 0x08}, {0x34, 0x3d},
{0x35, 0x00}, {0x38, 0x12}, {0x0f, 0x42}, {0x39, 0x57},
{0x3a, 0x00}, {0x3b, 0xcc}, {0x3c, 0x0c}, {0x3d, 0x19},
{0x3e, 0x0c}, {0x3f, 0x01}, {0x41, 0x40}, {0x42, 0x80},
{0x45, 0x46}, {0x46, 0x62}, {0x47, 0x2a}, {0x48, 0x3c},
{0x4a, 0xf0}, {0x4b, 0xdc}, {0x4c, 0xdc}, {0x4d, 0xdc},
{0x4e, 0xdc}, {0x6c, 0x04}, {0x6f, 0x9e}, {0x70, 0x05},
{0x71, 0x78}, {0x77, 0x02}, {0x8a, 0x23}, {0x90, 0x7e},
{0x91, 0x7c}, {0x9f, 0x6e}, {0xa0, 0x6e}, {0xa5, 0x68},
{0xa6, 0x60}, {0xa8, 0xc1}, {0xa9, 0xfa}, {0xaa, 0x92},
{0xab, 0x04}, {0xac, 0x80}, {0xad, 0x80}, {0xae, 0x80},
{0xaf, 0x80}, {0xb2, 0xf2}, {0xb3, 0x20}, {0xb5, 0x00},
{0xb6, 0xaf}, {0xbb, 0xae}, {0xbc, 0x44}, {0xbd, 0x44},
{0xbe, 0x3b}, {0xbf, 0x3a}, {0xc1, 0xc8}, {0xc2, 0x01},
{0xc4, 0x00}, {0xc6, 0x85}, {0xc7, 0x81}, {0xc9, 0xe0},
{0xca, 0xe8}, {0xcc, 0xd8}, {0xcd, 0x93}, {0x2d, 0x00},
{0x2e, 0x00}, {0x01, 0x80}, {0x02, 0x80}, {0x12, 0x61},
{0x36, 0xfa}, {0x8c, 0x8d}, {0xc0, 0xaa}, {0x69, 0x0a},
{0x03, 0x09}, {0x17, 0x16}, {0x18, 0x6e}, {0x19, 0x01},
{0x1a, 0x3e}, {0x32, 0x09}, {0x2a, 0x10}, {0x2b, 0x0a},
{0x92, 0x00}, {0x93, 0x00}, {0xa1, 0x00}, {0x10, 0x7c},
{0x04, 0x03}, {0x00, 0x13},
};
static struct i2c_reg_u16 mt9v112_init[] = {
{0xf0, 0x0000}, {0x0d, 0x0021}, {0x0d, 0x0020},
{0x34, 0xc019}, {0x0a, 0x0011}, {0x0b, 0x000b},
{0x20, 0x0703}, {0x35, 0x2022}, {0xf0, 0x0001},
{0x05, 0x0000}, {0x06, 0x340c}, {0x3b, 0x042a},
{0x3c, 0x0400}, {0xf0, 0x0002}, {0x2e, 0x0c58},
{0x5b, 0x0001}, {0xc8, 0x9f0b}, {0xf0, 0x0001},
{0x9b, 0x5300}, {0xf0, 0x0000}, {0x2b, 0x0020},
{0x2c, 0x002a}, {0x2d, 0x0032}, {0x2e, 0x0020},
{0x09, 0x01dc}, {0x01, 0x000c}, {0x02, 0x0020},
{0x03, 0x01e0}, {0x04, 0x0280}, {0x06, 0x000c},
{0x05, 0x0098}, {0x20, 0x0703}, {0x09, 0x01f2},
{0x2b, 0x00a0}, {0x2c, 0x00a0}, {0x2d, 0x00a0},
{0x2e, 0x00a0}, {0x01, 0x000c}, {0x02, 0x0020},
{0x03, 0x01e0}, {0x04, 0x0280}, {0x06, 0x000c},
{0x05, 0x0098}, {0x09, 0x01c1}, {0x2b, 0x00ae},
{0x2c, 0x00ae}, {0x2d, 0x00ae}, {0x2e, 0x00ae},
};
static struct i2c_reg_u16 mt9v111_init[] = {
{0x01, 0x0004}, {0x0d, 0x0001}, {0x0d, 0x0000},
{0x01, 0x0001}, {0x05, 0x0004}, {0x2d, 0xe0a0},
{0x2e, 0x0c64}, {0x2f, 0x0064}, {0x06, 0x600e},
{0x08, 0x0480}, {0x01, 0x0004}, {0x02, 0x0016},
{0x03, 0x01e7}, {0x04, 0x0287}, {0x05, 0x0004},
{0x06, 0x002d}, {0x07, 0x3002}, {0x08, 0x0008},
{0x0e, 0x0008}, {0x20, 0x0000}
};
static struct i2c_reg_u16 mt9v011_init[] = {
{0x07, 0x0002}, {0x0d, 0x0001}, {0x0d, 0x0000},
{0x01, 0x0008}, {0x02, 0x0016}, {0x03, 0x01e1},
{0x04, 0x0281}, {0x05, 0x0083}, {0x06, 0x0006},
{0x0d, 0x0002}, {0x0a, 0x0000}, {0x0b, 0x0000},
{0x0c, 0x0000}, {0x0d, 0x0000}, {0x0e, 0x0000},
{0x0f, 0x0000}, {0x10, 0x0000}, {0x11, 0x0000},
{0x12, 0x0000}, {0x13, 0x0000}, {0x14, 0x0000},
{0x15, 0x0000}, {0x16, 0x0000}, {0x17, 0x0000},
{0x18, 0x0000}, {0x19, 0x0000}, {0x1a, 0x0000},
{0x1b, 0x0000}, {0x1c, 0x0000}, {0x1d, 0x0000},
{0x32, 0x0000}, {0x20, 0x1101}, {0x21, 0x0000},
{0x22, 0x0000}, {0x23, 0x0000}, {0x24, 0x0000},
{0x25, 0x0000}, {0x26, 0x0000}, {0x27, 0x0024},
{0x2f, 0xf7b0}, {0x30, 0x0005}, {0x31, 0x0000},
{0x32, 0x0000}, {0x33, 0x0000}, {0x34, 0x0100},
{0x3d, 0x068f}, {0x40, 0x01e0}, {0x41, 0x00d1},
{0x44, 0x0082}, {0x5a, 0x0000}, {0x5b, 0x0000},
{0x5c, 0x0000}, {0x5d, 0x0000}, {0x5e, 0x0000},
{0x5f, 0xa31d}, {0x62, 0x0611}, {0x0a, 0x0000},
{0x06, 0x0029}, {0x05, 0x0009}, {0x20, 0x1101},
{0x20, 0x1101}, {0x09, 0x0064}, {0x07, 0x0003},
{0x2b, 0x0033}, {0x2c, 0x00a0}, {0x2d, 0x00a0},
{0x2e, 0x0033}, {0x07, 0x0002}, {0x06, 0x0000},
{0x06, 0x0029}, {0x05, 0x0009},
};
static struct i2c_reg_u16 mt9m001_init[] = {
{0x0d, 0x0001},
{0x0d, 0x0000},
{0x04, 0x0500}, /* hres = 1280 */
{0x03, 0x0400}, /* vres = 1024 */
{0x20, 0x1100},
{0x06, 0x0010},
{0x2b, 0x0024},
{0x2e, 0x0024},
{0x35, 0x0024},
{0x2d, 0x0020},
{0x2c, 0x0020},
{0x09, 0x0ad4},
{0x35, 0x0057},
};
static struct i2c_reg_u16 mt9m111_init[] = {
{0xf0, 0x0000}, {0x0d, 0x0021}, {0x0d, 0x0008},
{0xf0, 0x0001}, {0x3a, 0x4300}, {0x9b, 0x4300},
{0x06, 0x708e}, {0xf0, 0x0002}, {0x2e, 0x0a1e},
{0xf0, 0x0000},
};
static struct i2c_reg_u16 mt9m112_init[] = {
{0xf0, 0x0000}, {0x0d, 0x0021}, {0x0d, 0x0008},
{0xf0, 0x0001}, {0x3a, 0x4300}, {0x9b, 0x4300},
{0x06, 0x708e}, {0xf0, 0x0002}, {0x2e, 0x0a1e},
{0xf0, 0x0000},
};
static struct i2c_reg_u8 hv7131r_init[] = {
{0x02, 0x08}, {0x02, 0x00}, {0x01, 0x08},
{0x02, 0x00}, {0x20, 0x00}, {0x21, 0xd0},
{0x22, 0x00}, {0x23, 0x09}, {0x01, 0x08},
{0x01, 0x08}, {0x01, 0x08}, {0x25, 0x07},
{0x26, 0xc3}, {0x27, 0x50}, {0x30, 0x62},
{0x31, 0x10}, {0x32, 0x06}, {0x33, 0x10},
{0x20, 0x00}, {0x21, 0xd0}, {0x22, 0x00},
{0x23, 0x09}, {0x01, 0x08},
};
static void reg_r(struct gspca_dev *gspca_dev, u16 reg, u16 length)
{
struct usb_device *dev = gspca_dev->dev;
int result;
if (gspca_dev->usb_err < 0)
return;
result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
0x00,
USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_INTERFACE,
reg,
0x00,
gspca_dev->usb_buf,
length,
500);
if (unlikely(result < 0 || result != length)) {
pr_err("Read register %02x failed %d\n", reg, result);
gspca_dev->usb_err = result;
}
}
static void reg_w(struct gspca_dev *gspca_dev, u16 reg,
const u8 *buffer, int length)
{
struct usb_device *dev = gspca_dev->dev;
int result;
if (gspca_dev->usb_err < 0)
return;
memcpy(gspca_dev->usb_buf, buffer, length);
result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
0x08,
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_INTERFACE,
reg,
0x00,
gspca_dev->usb_buf,
length,
500);
if (unlikely(result < 0 || result != length)) {
pr_err("Write register %02x failed %d\n", reg, result);
gspca_dev->usb_err = result;
}
}
static void reg_w1(struct gspca_dev *gspca_dev, u16 reg, const u8 value)
{
reg_w(gspca_dev, reg, &value, 1);
}
static void i2c_w(struct gspca_dev *gspca_dev, const u8 *buffer)
{
int i;
reg_w(gspca_dev, 0x10c0, buffer, 8);
for (i = 0; i < 5; i++) {
reg_r(gspca_dev, 0x10c0, 1);
if (gspca_dev->usb_err < 0)
return;
if (gspca_dev->usb_buf[0] & 0x04) {
if (gspca_dev->usb_buf[0] & 0x08) {
pr_err("i2c_w error\n");
gspca_dev->usb_err = -EIO;
}
return;
}
msleep(10);
}
pr_err("i2c_w reg %02x no response\n", buffer[2]);
/* gspca_dev->usb_err = -EIO; fixme: may occur */
}
static void i2c_w1(struct gspca_dev *gspca_dev, u8 reg, u8 val)
{
struct sd *sd = (struct sd *) gspca_dev;
u8 row[8];
/*
* from the point of view of the bridge, the length
* includes the address
*/
row[0] = 0x81 | (2 << 4);
row[1] = sd->i2c_addr;
row[2] = reg;
row[3] = val;
row[4] = 0x00;
row[5] = 0x00;
row[6] = 0x00;
row[7] = 0x10;
i2c_w(gspca_dev, row);
}
static void i2c_w1_buf(struct gspca_dev *gspca_dev,
struct i2c_reg_u8 *buf, int sz)
{
while (--sz >= 0) {
i2c_w1(gspca_dev, buf->reg, buf->val);
buf++;
}
}
static void i2c_w2(struct gspca_dev *gspca_dev, u8 reg, u16 val)
{
struct sd *sd = (struct sd *) gspca_dev;
u8 row[8];
/*
* from the point of view of the bridge, the length
* includes the address
*/
row[0] = 0x81 | (3 << 4);
row[1] = sd->i2c_addr;
row[2] = reg;
row[3] = val >> 8;
row[4] = val;
row[5] = 0x00;
row[6] = 0x00;
row[7] = 0x10;
i2c_w(gspca_dev, row);
}
static void i2c_w2_buf(struct gspca_dev *gspca_dev,
struct i2c_reg_u16 *buf, int sz)
{
while (--sz >= 0) {
i2c_w2(gspca_dev, buf->reg, buf->val);
buf++;
}
}
static void i2c_r1(struct gspca_dev *gspca_dev, u8 reg, u8 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
u8 row[8];
row[0] = 0x81 | (1 << 4);
row[1] = sd->i2c_addr;
row[2] = reg;
row[3] = 0;
row[4] = 0;
row[5] = 0;
row[6] = 0;
row[7] = 0x10;
i2c_w(gspca_dev, row);
row[0] = 0x81 | (1 << 4) | 0x02;
row[2] = 0;
i2c_w(gspca_dev, row);
reg_r(gspca_dev, 0x10c2, 5);
*val = gspca_dev->usb_buf[4];
}
static void i2c_r2(struct gspca_dev *gspca_dev, u8 reg, u16 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
u8 row[8];
row[0] = 0x81 | (1 << 4);
row[1] = sd->i2c_addr;
row[2] = reg;
row[3] = 0;
row[4] = 0;
row[5] = 0;
row[6] = 0;
row[7] = 0x10;
i2c_w(gspca_dev, row);
row[0] = 0x81 | (2 << 4) | 0x02;
row[2] = 0;
i2c_w(gspca_dev, row);
reg_r(gspca_dev, 0x10c2, 5);
*val = (gspca_dev->usb_buf[3] << 8) | gspca_dev->usb_buf[4];
}
static void ov9650_init_sensor(struct gspca_dev *gspca_dev)
{
u16 id;
struct sd *sd = (struct sd *) gspca_dev;
i2c_r2(gspca_dev, 0x1c, &id);
if (gspca_dev->usb_err < 0)
return;
if (id != 0x7fa2) {
pr_err("sensor id for ov9650 doesn't match (0x%04x)\n", id);
gspca_dev->usb_err = -ENODEV;
return;
}
i2c_w1(gspca_dev, 0x12, 0x80); /* sensor reset */
msleep(200);
i2c_w1_buf(gspca_dev, ov9650_init, ARRAY_SIZE(ov9650_init));
if (gspca_dev->usb_err < 0)
pr_err("OV9650 sensor initialization failed\n");
sd->hstart = 1;
sd->vstart = 7;
}
static void ov9655_init_sensor(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
i2c_w1(gspca_dev, 0x12, 0x80); /* sensor reset */
msleep(200);
i2c_w1_buf(gspca_dev, ov9655_init, ARRAY_SIZE(ov9655_init));
if (gspca_dev->usb_err < 0)
pr_err("OV9655 sensor initialization failed\n");
/* disable hflip and vflip */
gspca_dev->ctrl_dis = (1 << HFLIP) | (1 << VFLIP);
sd->hstart = 1;
sd->vstart = 2;
}
static void soi968_init_sensor(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
i2c_w1(gspca_dev, 0x12, 0x80); /* sensor reset */
msleep(200);
i2c_w1_buf(gspca_dev, soi968_init, ARRAY_SIZE(soi968_init));
if (gspca_dev->usb_err < 0)
pr_err("SOI968 sensor initialization failed\n");
/* disable hflip and vflip */
gspca_dev->ctrl_dis = (1 << HFLIP) | (1 << VFLIP)
| (1 << EXPOSURE);
sd->hstart = 60;
sd->vstart = 11;
}
static void ov7660_init_sensor(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
i2c_w1(gspca_dev, 0x12, 0x80); /* sensor reset */
msleep(200);
i2c_w1_buf(gspca_dev, ov7660_init, ARRAY_SIZE(ov7660_init));
if (gspca_dev->usb_err < 0)
pr_err("OV7660 sensor initialization failed\n");
sd->hstart = 3;
sd->vstart = 3;
}
static void ov7670_init_sensor(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
i2c_w1(gspca_dev, 0x12, 0x80); /* sensor reset */
msleep(200);
i2c_w1_buf(gspca_dev, ov7670_init, ARRAY_SIZE(ov7670_init));
if (gspca_dev->usb_err < 0)
pr_err("OV7670 sensor initialization failed\n");
/* disable hflip and vflip */
gspca_dev->ctrl_dis = (1 << HFLIP) | (1 << VFLIP);
sd->hstart = 0;
sd->vstart = 1;
}
static void mt9v_init_sensor(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
u16 value;
sd->i2c_addr = 0x5d;
i2c_r2(gspca_dev, 0xff, &value);
if (gspca_dev->usb_err >= 0
&& value == 0x8243) {
i2c_w2_buf(gspca_dev, mt9v011_init, ARRAY_SIZE(mt9v011_init));
if (gspca_dev->usb_err < 0) {
pr_err("MT9V011 sensor initialization failed\n");
return;
}
sd->hstart = 2;
sd->vstart = 2;
sd->sensor = SENSOR_MT9V011;
pr_info("MT9V011 sensor detected\n");
return;
}
gspca_dev->usb_err = 0;
sd->i2c_addr = 0x5c;
i2c_w2(gspca_dev, 0x01, 0x0004);
i2c_r2(gspca_dev, 0xff, &value);
if (gspca_dev->usb_err >= 0
&& value == 0x823a) {
i2c_w2_buf(gspca_dev, mt9v111_init, ARRAY_SIZE(mt9v111_init));
if (gspca_dev->usb_err < 0) {
pr_err("MT9V111 sensor initialization failed\n");
return;
}
gspca_dev->ctrl_dis = (1 << EXPOSURE)
| (1 << AUTOGAIN)
| (1 << GAIN);
sd->hstart = 2;
sd->vstart = 2;
sd->sensor = SENSOR_MT9V111;
pr_info("MT9V111 sensor detected\n");
return;
}
gspca_dev->usb_err = 0;
sd->i2c_addr = 0x5d;
i2c_w2(gspca_dev, 0xf0, 0x0000);
if (gspca_dev->usb_err < 0) {
gspca_dev->usb_err = 0;
sd->i2c_addr = 0x48;
i2c_w2(gspca_dev, 0xf0, 0x0000);
}
i2c_r2(gspca_dev, 0x00, &value);
if (gspca_dev->usb_err >= 0
&& value == 0x1229) {
i2c_w2_buf(gspca_dev, mt9v112_init, ARRAY_SIZE(mt9v112_init));
if (gspca_dev->usb_err < 0) {
pr_err("MT9V112 sensor initialization failed\n");
return;
}
sd->hstart = 6;
sd->vstart = 2;
sd->sensor = SENSOR_MT9V112;
pr_info("MT9V112 sensor detected\n");
return;
}
gspca_dev->usb_err = -ENODEV;
}
static void mt9m112_init_sensor(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
i2c_w2_buf(gspca_dev, mt9m112_init, ARRAY_SIZE(mt9m112_init));
if (gspca_dev->usb_err < 0)
pr_err("MT9M112 sensor initialization failed\n");
gspca_dev->ctrl_dis = (1 << EXPOSURE) | (1 << AUTOGAIN)
| (1 << GAIN);
sd->hstart = 0;
sd->vstart = 2;
}
static void mt9m111_init_sensor(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
i2c_w2_buf(gspca_dev, mt9m111_init, ARRAY_SIZE(mt9m111_init));
if (gspca_dev->usb_err < 0)
pr_err("MT9M111 sensor initialization failed\n");
gspca_dev->ctrl_dis = (1 << EXPOSURE) | (1 << AUTOGAIN)
| (1 << GAIN);
sd->hstart = 0;
sd->vstart = 2;
}
static void mt9m001_init_sensor(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
u16 id;
i2c_r2(gspca_dev, 0x00, &id);
if (gspca_dev->usb_err < 0)
return;
/* must be 0x8411 or 0x8421 for colour sensor and 8431 for bw */
switch (id) {
case 0x8411:
case 0x8421:
pr_info("MT9M001 color sensor detected\n");
break;
case 0x8431:
pr_info("MT9M001 mono sensor detected\n");
break;
default:
pr_err("No MT9M001 chip detected, ID = %x\n\n", id);
gspca_dev->usb_err = -ENODEV;
return;
}
i2c_w2_buf(gspca_dev, mt9m001_init, ARRAY_SIZE(mt9m001_init));
if (gspca_dev->usb_err < 0)
pr_err("MT9M001 sensor initialization failed\n");
/* disable hflip and vflip */
gspca_dev->ctrl_dis = (1 << HFLIP) | (1 << VFLIP);
sd->hstart = 1;
sd->vstart = 1;
}
static void hv7131r_init_sensor(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
i2c_w1_buf(gspca_dev, hv7131r_init, ARRAY_SIZE(hv7131r_init));
if (gspca_dev->usb_err < 0)
pr_err("HV7131R Sensor initialization failed\n");
sd->hstart = 0;
sd->vstart = 1;
}
static void set_cmatrix(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int satur;
s32 hue_coord, hue_index = 180 + sd->ctrls[HUE].val;
u8 cmatrix[21];
memset(cmatrix, 0, sizeof cmatrix);
cmatrix[2] = (sd->ctrls[CONTRAST].val * 0x25 / 0x100) + 0x26;
cmatrix[0] = 0x13 + (cmatrix[2] - 0x26) * 0x13 / 0x25;
cmatrix[4] = 0x07 + (cmatrix[2] - 0x26) * 0x07 / 0x25;
cmatrix[18] = sd->ctrls[BRIGHTNESS].val - 0x80;
satur = sd->ctrls[SATURATION].val;
hue_coord = (hsv_red_x[hue_index] * satur) >> 8;
cmatrix[6] = hue_coord;
cmatrix[7] = (hue_coord >> 8) & 0x0f;
hue_coord = (hsv_red_y[hue_index] * satur) >> 8;
cmatrix[8] = hue_coord;
cmatrix[9] = (hue_coord >> 8) & 0x0f;
hue_coord = (hsv_green_x[hue_index] * satur) >> 8;
cmatrix[10] = hue_coord;
cmatrix[11] = (hue_coord >> 8) & 0x0f;
hue_coord = (hsv_green_y[hue_index] * satur) >> 8;
cmatrix[12] = hue_coord;
cmatrix[13] = (hue_coord >> 8) & 0x0f;
hue_coord = (hsv_blue_x[hue_index] * satur) >> 8;
cmatrix[14] = hue_coord;
cmatrix[15] = (hue_coord >> 8) & 0x0f;
hue_coord = (hsv_blue_y[hue_index] * satur) >> 8;
cmatrix[16] = hue_coord;
cmatrix[17] = (hue_coord >> 8) & 0x0f;
reg_w(gspca_dev, 0x10e1, cmatrix, 21);
}
static void set_gamma(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
u8 gamma[17];
u8 gval = sd->ctrls[GAMMA].val * 0xb8 / 0x100;
gamma[0] = 0x0a;
gamma[1] = 0x13 + (gval * (0xcb - 0x13) / 0xb8);
gamma[2] = 0x25 + (gval * (0xee - 0x25) / 0xb8);
gamma[3] = 0x37 + (gval * (0xfa - 0x37) / 0xb8);
gamma[4] = 0x45 + (gval * (0xfc - 0x45) / 0xb8);
gamma[5] = 0x55 + (gval * (0xfb - 0x55) / 0xb8);
gamma[6] = 0x65 + (gval * (0xfc - 0x65) / 0xb8);
gamma[7] = 0x74 + (gval * (0xfd - 0x74) / 0xb8);
gamma[8] = 0x83 + (gval * (0xfe - 0x83) / 0xb8);
gamma[9] = 0x92 + (gval * (0xfc - 0x92) / 0xb8);
gamma[10] = 0xa1 + (gval * (0xfc - 0xa1) / 0xb8);
gamma[11] = 0xb0 + (gval * (0xfc - 0xb0) / 0xb8);
gamma[12] = 0xbf + (gval * (0xfb - 0xbf) / 0xb8);
gamma[13] = 0xce + (gval * (0xfb - 0xce) / 0xb8);
gamma[14] = 0xdf + (gval * (0xfd - 0xdf) / 0xb8);
gamma[15] = 0xea + (gval * (0xf9 - 0xea) / 0xb8);
gamma[16] = 0xf5;
reg_w(gspca_dev, 0x1190, gamma, 17);
}
static void set_redblue(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
reg_w1(gspca_dev, 0x118c, sd->ctrls[RED].val);
reg_w1(gspca_dev, 0x118f, sd->ctrls[BLUE].val);
}
static void set_hvflip(struct gspca_dev *gspca_dev)
{
u8 value, tslb, hflip, vflip;
u16 value2;
struct sd *sd = (struct sd *) gspca_dev;
if ((sd->flags & FLIP_DETECT) && dmi_check_system(flip_dmi_table)) {
hflip = !sd->ctrls[HFLIP].val;
vflip = !sd->ctrls[VFLIP].val;
} else {
hflip = sd->ctrls[HFLIP].val;
vflip = sd->ctrls[VFLIP].val;
}
switch (sd->sensor) {
case SENSOR_OV7660:
value = 0x01;
if (hflip)
value |= 0x20;
if (vflip) {
value |= 0x10;
sd->vstart = 2;
} else {
sd->vstart = 3;
}
reg_w1(gspca_dev, 0x1182, sd->vstart);
i2c_w1(gspca_dev, 0x1e, value);
break;
case SENSOR_OV9650:
i2c_r1(gspca_dev, 0x1e, &value);
value &= ~0x30;
tslb = 0x01;
if (hflip)
value |= 0x20;
if (vflip) {
value |= 0x10;
tslb = 0x49;
}
i2c_w1(gspca_dev, 0x1e, value);
i2c_w1(gspca_dev, 0x3a, tslb);
break;
case SENSOR_MT9V111:
case SENSOR_MT9V011:
i2c_r2(gspca_dev, 0x20, &value2);
value2 &= ~0xc0a0;
if (hflip)
value2 |= 0x8080;
if (vflip)
value2 |= 0x4020;
i2c_w2(gspca_dev, 0x20, value2);
break;
case SENSOR_MT9M112:
case SENSOR_MT9M111:
case SENSOR_MT9V112:
i2c_r2(gspca_dev, 0x20, &value2);
value2 &= ~0x0003;
if (hflip)
value2 |= 0x0002;
if (vflip)
value2 |= 0x0001;
i2c_w2(gspca_dev, 0x20, value2);
break;
case SENSOR_HV7131R:
i2c_r1(gspca_dev, 0x01, &value);
value &= ~0x03;
if (vflip)
value |= 0x01;
if (hflip)
value |= 0x02;
i2c_w1(gspca_dev, 0x01, value);
break;
}
}
static void set_exposure(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
u8 exp[8] = {0x81, sd->i2c_addr, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e};
int expo;
expo = sd->ctrls[EXPOSURE].val;
switch (sd->sensor) {
case SENSOR_OV7660:
case SENSOR_OV7670:
case SENSOR_OV9655:
case SENSOR_OV9650:
exp[0] |= (3 << 4);
exp[2] = 0x2d;
exp[3] = expo;
exp[4] = expo >> 8;
break;
case SENSOR_MT9M001:
case SENSOR_MT9V112:
case SENSOR_MT9V011:
exp[0] |= (3 << 4);
exp[2] = 0x09;
exp[3] = expo >> 8;
exp[4] = expo;
break;
case SENSOR_HV7131R:
exp[0] |= (4 << 4);
exp[2] = 0x25;
exp[3] = expo >> 5;
exp[4] = expo << 3;
exp[5] = 0;
break;
default:
return;
}
i2c_w(gspca_dev, exp);
}
static void set_gain(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
u8 gain[8] = {0x81, sd->i2c_addr, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1d};
int g;
g = sd->ctrls[GAIN].val;
switch (sd->sensor) {
case SENSOR_OV7660:
case SENSOR_OV7670:
case SENSOR_SOI968:
case SENSOR_OV9655:
case SENSOR_OV9650:
gain[0] |= (2 << 4);
gain[3] = ov_gain[g];
break;
case SENSOR_MT9V011:
gain[0] |= (3 << 4);
gain[2] = 0x35;
gain[3] = micron1_gain[g] >> 8;
gain[4] = micron1_gain[g];
break;
case SENSOR_MT9V112:
gain[0] |= (3 << 4);
gain[2] = 0x2f;
gain[3] = micron1_gain[g] >> 8;
gain[4] = micron1_gain[g];
break;
case SENSOR_MT9M001:
gain[0] |= (3 << 4);
gain[2] = 0x2f;
gain[3] = micron2_gain[g] >> 8;
gain[4] = micron2_gain[g];
break;
case SENSOR_HV7131R:
gain[0] |= (2 << 4);
gain[2] = 0x30;
gain[3] = hv7131r_gain[g];
break;
default:
return;
}
i2c_w(gspca_dev, gain);
}
static void set_quality(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
jpeg_set_qual(sd->jpeg_hdr, sd->ctrls[QUALITY].val);
reg_w1(gspca_dev, 0x1061, 0x01); /* stop transfer */
reg_w1(gspca_dev, 0x10e0, sd->fmt | 0x20); /* write QTAB */
reg_w(gspca_dev, 0x1100, &sd->jpeg_hdr[JPEG_QT0_OFFSET], 64);
reg_w(gspca_dev, 0x1140, &sd->jpeg_hdr[JPEG_QT1_OFFSET], 64);
reg_w1(gspca_dev, 0x1061, 0x03); /* restart transfer */
reg_w1(gspca_dev, 0x10e0, sd->fmt);
sd->fmt ^= 0x0c; /* invert QTAB use + write */
reg_w1(gspca_dev, 0x10e0, sd->fmt);
}
#ifdef CONFIG_VIDEO_ADV_DEBUG
static int sd_dbg_g_register(struct gspca_dev *gspca_dev,
struct v4l2_dbg_register *reg)
{
struct sd *sd = (struct sd *) gspca_dev;
switch (reg->match.type) {
case V4L2_CHIP_MATCH_HOST:
if (reg->match.addr != 0)
return -EINVAL;
if (reg->reg < 0x1000 || reg->reg > 0x11ff)
return -EINVAL;
reg_r(gspca_dev, reg->reg, 1);
reg->val = gspca_dev->usb_buf[0];
return gspca_dev->usb_err;
case V4L2_CHIP_MATCH_I2C_ADDR:
if (reg->match.addr != sd->i2c_addr)
return -EINVAL;
if (sd->sensor >= SENSOR_MT9V011 &&
sd->sensor <= SENSOR_MT9M112) {
i2c_r2(gspca_dev, reg->reg, (u16 *) ®->val);
} else {
i2c_r1(gspca_dev, reg->reg, (u8 *) ®->val);
}
return gspca_dev->usb_err;
}
return -EINVAL;
}
static int sd_dbg_s_register(struct gspca_dev *gspca_dev,
struct v4l2_dbg_register *reg)
{
struct sd *sd = (struct sd *) gspca_dev;
switch (reg->match.type) {
case V4L2_CHIP_MATCH_HOST:
if (reg->match.addr != 0)
return -EINVAL;
if (reg->reg < 0x1000 || reg->reg > 0x11ff)
return -EINVAL;
reg_w1(gspca_dev, reg->reg, reg->val);
return gspca_dev->usb_err;
case V4L2_CHIP_MATCH_I2C_ADDR:
if (reg->match.addr != sd->i2c_addr)
return -EINVAL;
if (sd->sensor >= SENSOR_MT9V011 &&
sd->sensor <= SENSOR_MT9M112) {
i2c_w2(gspca_dev, reg->reg, reg->val);
} else {
i2c_w1(gspca_dev, reg->reg, reg->val);
}
return gspca_dev->usb_err;
}
return -EINVAL;
}
#endif
static int sd_chip_ident(struct gspca_dev *gspca_dev,
struct v4l2_dbg_chip_ident *chip)
{
struct sd *sd = (struct sd *) gspca_dev;
switch (chip->match.type) {
case V4L2_CHIP_MATCH_HOST:
if (chip->match.addr != 0)
return -EINVAL;
chip->revision = 0;
chip->ident = V4L2_IDENT_SN9C20X;
return 0;
case V4L2_CHIP_MATCH_I2C_ADDR:
if (chip->match.addr != sd->i2c_addr)
return -EINVAL;
chip->revision = 0;
chip->ident = i2c_ident[sd->sensor];
return 0;
}
return -EINVAL;
}
static int sd_config(struct gspca_dev *gspca_dev,
const struct usb_device_id *id)
{
struct sd *sd = (struct sd *) gspca_dev;
struct cam *cam;
cam = &gspca_dev->cam;
cam->needs_full_bandwidth = 1;
sd->sensor = id->driver_info >> 8;
sd->i2c_addr = id->driver_info;
sd->flags = id->driver_info >> 16;
switch (sd->sensor) {
case SENSOR_MT9M112:
case SENSOR_MT9M111:
case SENSOR_OV9650:
case SENSOR_SOI968:
cam->cam_mode = sxga_mode;
cam->nmodes = ARRAY_SIZE(sxga_mode);
break;
case SENSOR_MT9M001:
cam->cam_mode = mono_mode;
cam->nmodes = ARRAY_SIZE(mono_mode);
break;
default:
cam->cam_mode = vga_mode;
cam->nmodes = ARRAY_SIZE(vga_mode);
break;
}
sd->old_step = 0;
sd->older_step = 0;
sd->exposure_step = 16;
gspca_dev->cam.ctrls = sd->ctrls;
INIT_WORK(&sd->work, qual_upd);
return 0;
}
static int sd_init(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int i;
u8 value;
u8 i2c_init[9] =
{0x80, sd->i2c_addr, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03};
for (i = 0; i < ARRAY_SIZE(bridge_init); i++) {
value = bridge_init[i][1];
reg_w(gspca_dev, bridge_init[i][0], &value, 1);
if (gspca_dev->usb_err < 0) {
pr_err("Device initialization failed\n");
return gspca_dev->usb_err;
}
}
if (sd->flags & LED_REVERSE)
reg_w1(gspca_dev, 0x1006, 0x00);
else
reg_w1(gspca_dev, 0x1006, 0x20);
reg_w(gspca_dev, 0x10c0, i2c_init, 9);
if (gspca_dev->usb_err < 0) {
pr_err("Device initialization failed\n");
return gspca_dev->usb_err;
}
switch (sd->sensor) {
case SENSOR_OV9650:
ov9650_init_sensor(gspca_dev);
if (gspca_dev->usb_err < 0)
break;
pr_info("OV9650 sensor detected\n");
break;
case SENSOR_OV9655:
ov9655_init_sensor(gspca_dev);
if (gspca_dev->usb_err < 0)
break;
pr_info("OV9655 sensor detected\n");
break;
case SENSOR_SOI968:
soi968_init_sensor(gspca_dev);
if (gspca_dev->usb_err < 0)
break;
pr_info("SOI968 sensor detected\n");
break;
case SENSOR_OV7660:
ov7660_init_sensor(gspca_dev);
if (gspca_dev->usb_err < 0)
break;
pr_info("OV7660 sensor detected\n");
break;
case SENSOR_OV7670:
ov7670_init_sensor(gspca_dev);
if (gspca_dev->usb_err < 0)
break;
pr_info("OV7670 sensor detected\n");
break;
case SENSOR_MT9VPRB:
mt9v_init_sensor(gspca_dev);
if (gspca_dev->usb_err < 0)
break;
pr_info("MT9VPRB sensor detected\n");
break;
case SENSOR_MT9M111:
mt9m111_init_sensor(gspca_dev);
if (gspca_dev->usb_err < 0)
break;
pr_info("MT9M111 sensor detected\n");
break;
case SENSOR_MT9M112:
mt9m112_init_sensor(gspca_dev);
if (gspca_dev->usb_err < 0)
break;
pr_info("MT9M112 sensor detected\n");
break;
case SENSOR_MT9M001:
mt9m001_init_sensor(gspca_dev);
if (gspca_dev->usb_err < 0)
break;
break;
case SENSOR_HV7131R:
hv7131r_init_sensor(gspca_dev);
if (gspca_dev->usb_err < 0)
break;
pr_info("HV7131R sensor detected\n");
break;
default:
pr_err("Unsupported sensor\n");
gspca_dev->usb_err = -ENODEV;
}
return gspca_dev->usb_err;
}
static void configure_sensor_output(struct gspca_dev *gspca_dev, int mode)
{
struct sd *sd = (struct sd *) gspca_dev;
u8 value;
switch (sd->sensor) {
case SENSOR_SOI968:
if (mode & MODE_SXGA) {
i2c_w1(gspca_dev, 0x17, 0x1d);
i2c_w1(gspca_dev, 0x18, 0xbd);
i2c_w1(gspca_dev, 0x19, 0x01);
i2c_w1(gspca_dev, 0x1a, 0x81);
i2c_w1(gspca_dev, 0x12, 0x00);
sd->hstart = 140;
sd->vstart = 19;
} else {
i2c_w1(gspca_dev, 0x17, 0x13);
i2c_w1(gspca_dev, 0x18, 0x63);
i2c_w1(gspca_dev, 0x19, 0x01);
i2c_w1(gspca_dev, 0x1a, 0x79);
i2c_w1(gspca_dev, 0x12, 0x40);
sd->hstart = 60;
sd->vstart = 11;
}
break;
case SENSOR_OV9650:
if (mode & MODE_SXGA) {
i2c_w1(gspca_dev, 0x17, 0x1b);
i2c_w1(gspca_dev, 0x18, 0xbc);
i2c_w1(gspca_dev, 0x19, 0x01);
i2c_w1(gspca_dev, 0x1a, 0x82);
i2c_r1(gspca_dev, 0x12, &value);
i2c_w1(gspca_dev, 0x12, value & 0x07);
} else {
i2c_w1(gspca_dev, 0x17, 0x24);
i2c_w1(gspca_dev, 0x18, 0xc5);
i2c_w1(gspca_dev, 0x19, 0x00);
i2c_w1(gspca_dev, 0x1a, 0x3c);
i2c_r1(gspca_dev, 0x12, &value);
i2c_w1(gspca_dev, 0x12, (value & 0x7) | 0x40);
}
break;
case SENSOR_MT9M112:
case SENSOR_MT9M111:
if (mode & MODE_SXGA) {
i2c_w2(gspca_dev, 0xf0, 0x0002);
i2c_w2(gspca_dev, 0xc8, 0x970b);
i2c_w2(gspca_dev, 0xf0, 0x0000);
} else {
i2c_w2(gspca_dev, 0xf0, 0x0002);
i2c_w2(gspca_dev, 0xc8, 0x8000);
i2c_w2(gspca_dev, 0xf0, 0x0000);
}
break;
}
}
static int sd_isoc_init(struct gspca_dev *gspca_dev)
{
struct usb_interface *intf;
u32 flags = gspca_dev->cam.cam_mode[(int)gspca_dev->curr_mode].priv;
/*
* When using the SN9C20X_I420 fmt the sn9c20x needs more bandwidth
* than our regular bandwidth calculations reserve, so we force the
* use of a specific altsetting when using the SN9C20X_I420 fmt.
*/
if (!(flags & (MODE_RAW | MODE_JPEG))) {
intf = usb_ifnum_to_if(gspca_dev->dev, gspca_dev->iface);
if (intf->num_altsetting != 9) {
pr_warn("sn9c20x camera with unknown number of alt "
"settings (%d), please report!\n",
intf->num_altsetting);
gspca_dev->alt = intf->num_altsetting;
return 0;
}
switch (gspca_dev->width) {
case 160: /* 160x120 */
gspca_dev->alt = 2;
break;
case 320: /* 320x240 */
gspca_dev->alt = 6;
break;
default: /* >= 640x480 */
gspca_dev->alt = 9;
break;
}
}
return 0;
}
#define HW_WIN(mode, hstart, vstart) \
((const u8 []){hstart, 0, vstart, 0, \
(mode & MODE_SXGA ? 1280 >> 4 : 640 >> 4), \
(mode & MODE_SXGA ? 1024 >> 3 : 480 >> 3)})
#define CLR_WIN(width, height) \
((const u8 [])\
{0, width >> 2, 0, height >> 1,\
((width >> 10) & 0x01) | ((height >> 8) & 0x6)})
static int sd_start(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int mode = gspca_dev->cam.cam_mode[(int) gspca_dev->curr_mode].priv;
int width = gspca_dev->width;
int height = gspca_dev->height;
u8 fmt, scale = 0;
jpeg_define(sd->jpeg_hdr, height, width,
0x21);
jpeg_set_qual(sd->jpeg_hdr, sd->ctrls[QUALITY].val);
if (mode & MODE_RAW)
fmt = 0x2d;
else if (mode & MODE_JPEG)
fmt = 0x24;
else
fmt = 0x2f; /* YUV 420 */
sd->fmt = fmt;
switch (mode & SCALE_MASK) {
case SCALE_1280x1024:
scale = 0xc0;
pr_info("Set 1280x1024\n");
break;
case SCALE_640x480:
scale = 0x80;
pr_info("Set 640x480\n");
break;
case SCALE_320x240:
scale = 0x90;
pr_info("Set 320x240\n");
break;
case SCALE_160x120:
scale = 0xa0;
pr_info("Set 160x120\n");
break;
}
configure_sensor_output(gspca_dev, mode);
reg_w(gspca_dev, 0x1100, &sd->jpeg_hdr[JPEG_QT0_OFFSET], 64);
reg_w(gspca_dev, 0x1140, &sd->jpeg_hdr[JPEG_QT1_OFFSET], 64);
reg_w(gspca_dev, 0x10fb, CLR_WIN(width, height), 5);
reg_w(gspca_dev, 0x1180, HW_WIN(mode, sd->hstart, sd->vstart), 6);
reg_w1(gspca_dev, 0x1189, scale);
reg_w1(gspca_dev, 0x10e0, fmt);
set_cmatrix(gspca_dev);
set_gamma(gspca_dev);
set_redblue(gspca_dev);
set_gain(gspca_dev);
set_exposure(gspca_dev);
set_hvflip(gspca_dev);
reg_w1(gspca_dev, 0x1007, 0x20);
reg_w1(gspca_dev, 0x1061, 0x03);
/* if JPEG, prepare the compression quality update */
if (mode & MODE_JPEG) {
sd->pktsz = sd->npkt = 0;
sd->nchg = 0;
sd->work_thread =
create_singlethread_workqueue(KBUILD_MODNAME);
}
return gspca_dev->usb_err;
}
static void sd_stopN(struct gspca_dev *gspca_dev)
{
reg_w1(gspca_dev, 0x1007, 0x00);
reg_w1(gspca_dev, 0x1061, 0x01);
}
/* called on streamoff with alt==0 and on disconnect */
/* the usb_lock is held at entry - restore on exit */
static void sd_stop0(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
if (sd->work_thread != NULL) {
mutex_unlock(&gspca_dev->usb_lock);
destroy_workqueue(sd->work_thread);
mutex_lock(&gspca_dev->usb_lock);
sd->work_thread = NULL;
}
}
static void do_autoexposure(struct gspca_dev *gspca_dev, u16 avg_lum)
{
struct sd *sd = (struct sd *) gspca_dev;
s16 new_exp;
/*
* some hardcoded values are present
* like those for maximal/minimal exposure
* and exposure steps
*/
if (avg_lum < MIN_AVG_LUM) {
if (sd->ctrls[EXPOSURE].val > 0x1770)
return;
new_exp = sd->ctrls[EXPOSURE].val + sd->exposure_step;
if (new_exp > 0x1770)
new_exp = 0x1770;
if (new_exp < 0x10)
new_exp = 0x10;
sd->ctrls[EXPOSURE].val = new_exp;
set_exposure(gspca_dev);
sd->older_step = sd->old_step;
sd->old_step = 1;
if (sd->old_step ^ sd->older_step)
sd->exposure_step /= 2;
else
sd->exposure_step += 2;
}
if (avg_lum > MAX_AVG_LUM) {
if (sd->ctrls[EXPOSURE].val < 0x10)
return;
new_exp = sd->ctrls[EXPOSURE].val - sd->exposure_step;
if (new_exp > 0x1700)
new_exp = 0x1770;
if (new_exp < 0x10)
new_exp = 0x10;
sd->ctrls[EXPOSURE].val = new_exp;
set_exposure(gspca_dev);
sd->older_step = sd->old_step;
sd->old_step = 0;
if (sd->old_step ^ sd->older_step)
sd->exposure_step /= 2;
else
sd->exposure_step += 2;
}
}
static void do_autogain(struct gspca_dev *gspca_dev, u16 avg_lum)
{
struct sd *sd = (struct sd *) gspca_dev;
if (avg_lum < MIN_AVG_LUM) {
if (sd->ctrls[GAIN].val + 1 <= 28) {
sd->ctrls[GAIN].val++;
set_gain(gspca_dev);
}
}
if (avg_lum > MAX_AVG_LUM) {
if (sd->ctrls[GAIN].val > 0) {
sd->ctrls[GAIN].val--;
set_gain(gspca_dev);
}
}
}
static void sd_dqcallback(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int avg_lum;
if (!sd->ctrls[AUTOGAIN].val)
return;
avg_lum = atomic_read(&sd->avg_lum);
if (sd->sensor == SENSOR_SOI968)
do_autogain(gspca_dev, avg_lum);
else
do_autoexposure(gspca_dev, avg_lum);
}
/* JPEG quality update */
/* This function is executed from a work queue. */
static void qual_upd(struct work_struct *work)
{
struct sd *sd = container_of(work, struct sd, work);
struct gspca_dev *gspca_dev = &sd->gspca_dev;
mutex_lock(&gspca_dev->usb_lock);
PDEBUG(D_STREAM, "qual_upd %d%%", sd->ctrls[QUALITY].val);
set_quality(gspca_dev);
mutex_unlock(&gspca_dev->usb_lock);
}
#if defined(CONFIG_INPUT) || defined(CONFIG_INPUT_MODULE)
static int sd_int_pkt_scan(struct gspca_dev *gspca_dev,
u8 *data, /* interrupt packet */
int len) /* interrupt packet length */
{
struct sd *sd = (struct sd *) gspca_dev;
if (!(sd->flags & HAS_NO_BUTTON) && len == 1) {
input_report_key(gspca_dev->input_dev, KEY_CAMERA, 1);
input_sync(gspca_dev->input_dev);
input_report_key(gspca_dev->input_dev, KEY_CAMERA, 0);
input_sync(gspca_dev->input_dev);
return 0;
}
return -EINVAL;
}
#endif
/* check the JPEG compression */
static void transfer_check(struct gspca_dev *gspca_dev,
u8 *data)
{
struct sd *sd = (struct sd *) gspca_dev;
int new_qual, r;
new_qual = 0;
/* if USB error, discard the frame and decrease the quality */
if (data[6] & 0x08) { /* USB FIFO full */
gspca_dev->last_packet_type = DISCARD_PACKET;
new_qual = -5;
} else {
/* else, compute the filling rate and a new JPEG quality */
r = (sd->pktsz * 100) /
(sd->npkt *
gspca_dev->urb[0]->iso_frame_desc[0].length);
if (r >= 85)
new_qual = -3;
else if (r < 75)
new_qual = 2;
}
if (new_qual != 0) {
sd->nchg += new_qual;
if (sd->nchg < -6 || sd->nchg >= 12) {
sd->nchg = 0;
new_qual += sd->ctrls[QUALITY].val;
if (new_qual < QUALITY_MIN)
new_qual = QUALITY_MIN;
else if (new_qual > QUALITY_MAX)
new_qual = QUALITY_MAX;
if (new_qual != sd->ctrls[QUALITY].val) {
sd->ctrls[QUALITY].val = new_qual;
queue_work(sd->work_thread, &sd->work);
}
}
} else {
sd->nchg = 0;
}
sd->pktsz = sd->npkt = 0;
}
static void sd_pkt_scan(struct gspca_dev *gspca_dev,
u8 *data, /* isoc packet */
int len) /* iso packet length */
{
struct sd *sd = (struct sd *) gspca_dev;
int avg_lum, is_jpeg;
static u8 frame_header[] =
{0xff, 0xff, 0x00, 0xc4, 0xc4, 0x96};
is_jpeg = (sd->fmt & 0x03) == 0;
if (len >= 64 && memcmp(data, frame_header, 6) == 0) {
avg_lum = ((data[35] >> 2) & 3) |
(data[20] << 2) |
(data[19] << 10);
avg_lum += ((data[35] >> 4) & 3) |
(data[22] << 2) |
(data[21] << 10);
avg_lum += ((data[35] >> 6) & 3) |
(data[24] << 2) |
(data[23] << 10);
avg_lum += (data[36] & 3) |
(data[26] << 2) |
(data[25] << 10);
avg_lum += ((data[36] >> 2) & 3) |
(data[28] << 2) |
(data[27] << 10);
avg_lum += ((data[36] >> 4) & 3) |
(data[30] << 2) |
(data[29] << 10);
avg_lum += ((data[36] >> 6) & 3) |
(data[32] << 2) |
(data[31] << 10);
avg_lum += ((data[44] >> 4) & 3) |
(data[34] << 2) |
(data[33] << 10);
avg_lum >>= 9;
atomic_set(&sd->avg_lum, avg_lum);
if (is_jpeg)
transfer_check(gspca_dev, data);
gspca_frame_add(gspca_dev, LAST_PACKET, NULL, 0);
len -= 64;
if (len == 0)
return;
data += 64;
}
if (gspca_dev->last_packet_type == LAST_PACKET) {
if (is_jpeg) {
gspca_frame_add(gspca_dev, FIRST_PACKET,
sd->jpeg_hdr, JPEG_HDR_SZ);
gspca_frame_add(gspca_dev, INTER_PACKET,
data, len);
} else {
gspca_frame_add(gspca_dev, FIRST_PACKET,
data, len);
}
} else {
/* if JPEG, count the packets and their size */
if (is_jpeg) {
sd->npkt++;
sd->pktsz += len;
}
gspca_frame_add(gspca_dev, INTER_PACKET, data, len);
}
}
/* sub-driver description */
static const struct sd_desc sd_desc = {
.name = KBUILD_MODNAME,
.ctrls = sd_ctrls,
.nctrls = ARRAY_SIZE(sd_ctrls),
.config = sd_config,
.init = sd_init,
.isoc_init = sd_isoc_init,
.start = sd_start,
.stopN = sd_stopN,
.stop0 = sd_stop0,
.pkt_scan = sd_pkt_scan,
#if defined(CONFIG_INPUT) || defined(CONFIG_INPUT_MODULE)
.int_pkt_scan = sd_int_pkt_scan,
#endif
.dq_callback = sd_dqcallback,
#ifdef CONFIG_VIDEO_ADV_DEBUG
.set_register = sd_dbg_s_register,
.get_register = sd_dbg_g_register,
#endif
.get_chip_ident = sd_chip_ident,
};
#define SN9C20X(sensor, i2c_addr, flags) \
.driver_info = ((flags & 0xff) << 16) \
| (SENSOR_ ## sensor << 8) \
| (i2c_addr)
static const struct usb_device_id device_table[] = {
{USB_DEVICE(0x0c45, 0x6240), SN9C20X(MT9M001, 0x5d, 0)},
{USB_DEVICE(0x0c45, 0x6242), SN9C20X(MT9M111, 0x5d, 0)},
{USB_DEVICE(0x0c45, 0x6248), SN9C20X(OV9655, 0x30, 0)},
{USB_DEVICE(0x0c45, 0x624c), SN9C20X(MT9M112, 0x5d, 0)},
{USB_DEVICE(0x0c45, 0x624e), SN9C20X(SOI968, 0x30, LED_REVERSE)},
{USB_DEVICE(0x0c45, 0x624f), SN9C20X(OV9650, 0x30,
(FLIP_DETECT | HAS_NO_BUTTON))},
{USB_DEVICE(0x0c45, 0x6251), SN9C20X(OV9650, 0x30, 0)},
{USB_DEVICE(0x0c45, 0x6253), SN9C20X(OV9650, 0x30, 0)},
{USB_DEVICE(0x0c45, 0x6260), SN9C20X(OV7670, 0x21, 0)},
{USB_DEVICE(0x0c45, 0x6270), SN9C20X(MT9VPRB, 0x00, 0)},
{USB_DEVICE(0x0c45, 0x627b), SN9C20X(OV7660, 0x21, FLIP_DETECT)},
{USB_DEVICE(0x0c45, 0x627c), SN9C20X(HV7131R, 0x11, 0)},
{USB_DEVICE(0x0c45, 0x627f), SN9C20X(OV9650, 0x30, 0)},
{USB_DEVICE(0x0c45, 0x6280), SN9C20X(MT9M001, 0x5d, 0)},
{USB_DEVICE(0x0c45, 0x6282), SN9C20X(MT9M111, 0x5d, 0)},
{USB_DEVICE(0x0c45, 0x6288), SN9C20X(OV9655, 0x30, 0)},
{USB_DEVICE(0x0c45, 0x628c), SN9C20X(MT9M112, 0x5d, 0)},
{USB_DEVICE(0x0c45, 0x628e), SN9C20X(SOI968, 0x30, 0)},
{USB_DEVICE(0x0c45, 0x628f), SN9C20X(OV9650, 0x30, 0)},
{USB_DEVICE(0x0c45, 0x62a0), SN9C20X(OV7670, 0x21, 0)},
{USB_DEVICE(0x0c45, 0x62b0), SN9C20X(MT9VPRB, 0x00, 0)},
{USB_DEVICE(0x0c45, 0x62b3), SN9C20X(OV9655, 0x30, LED_REVERSE)},
{USB_DEVICE(0x0c45, 0x62bb), SN9C20X(OV7660, 0x21, LED_REVERSE)},
{USB_DEVICE(0x0c45, 0x62bc), SN9C20X(HV7131R, 0x11, 0)},
{USB_DEVICE(0x045e, 0x00f4), SN9C20X(OV9650, 0x30, 0)},
{USB_DEVICE(0x145f, 0x013d), SN9C20X(OV7660, 0x21, 0)},
{USB_DEVICE(0x0458, 0x7029), SN9C20X(HV7131R, 0x11, 0)},
{USB_DEVICE(0x0458, 0x704a), SN9C20X(MT9M112, 0x5d, 0)},
{USB_DEVICE(0x0458, 0x704c), SN9C20X(MT9M112, 0x5d, 0)},
{USB_DEVICE(0xa168, 0x0610), SN9C20X(HV7131R, 0x11, 0)},
{USB_DEVICE(0xa168, 0x0611), SN9C20X(HV7131R, 0x11, 0)},
{USB_DEVICE(0xa168, 0x0613), SN9C20X(HV7131R, 0x11, 0)},
{USB_DEVICE(0xa168, 0x0618), SN9C20X(HV7131R, 0x11, 0)},
{USB_DEVICE(0xa168, 0x0614), SN9C20X(MT9M111, 0x5d, 0)},
{USB_DEVICE(0xa168, 0x0615), SN9C20X(MT9M111, 0x5d, 0)},
{USB_DEVICE(0xa168, 0x0617), SN9C20X(MT9M111, 0x5d, 0)},
{}
};
MODULE_DEVICE_TABLE(usb, device_table);
/* -- device connect -- */
static int sd_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
return gspca_dev_probe(intf, id, &sd_desc, sizeof(struct sd),
THIS_MODULE);
}
static struct usb_driver sd_driver = {
.name = KBUILD_MODNAME,
.id_table = device_table,
.probe = sd_probe,
.disconnect = gspca_disconnect,
#ifdef CONFIG_PM
.suspend = gspca_suspend,
.resume = gspca_resume,
.reset_resume = gspca_resume,
#endif
};
module_usb_driver(sd_driver);
| gpl-2.0 |
sony-msm8960/android_kernel_sony_apq8064 | drivers/staging/rtl8192u/ieee80211/ieee80211_softmac.c | 5068 | 89859 | /* IEEE 802.11 SoftMAC layer
* Copyright (c) 2005 Andrea Merello <andreamrl@tiscali.it>
*
* Mostly extracted from the rtl8180-sa2400 driver for the
* in-kernel generic ieee802.11 stack.
*
* Few lines might be stolen from other part of the ieee80211
* stack. Copyright who own it's copyright
*
* WPA code stolen from the ipw2200 driver.
* Copyright who own it's copyright.
*
* released under the GPL
*/
#include "ieee80211.h"
#include <linux/random.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include "dot11d.h"
u8 rsn_authen_cipher_suite[16][4] = {
{0x00,0x0F,0xAC,0x00}, //Use group key, //Reserved
{0x00,0x0F,0xAC,0x01}, //WEP-40 //RSNA default
{0x00,0x0F,0xAC,0x02}, //TKIP //NONE //{used just as default}
{0x00,0x0F,0xAC,0x03}, //WRAP-historical
{0x00,0x0F,0xAC,0x04}, //CCMP
{0x00,0x0F,0xAC,0x05}, //WEP-104
};
short ieee80211_is_54g(const struct ieee80211_network *net)
{
return (net->rates_ex_len > 0) || (net->rates_len > 4);
}
short ieee80211_is_shortslot(const struct ieee80211_network *net)
{
return net->capability & WLAN_CAPABILITY_SHORT_SLOT;
}
/* returns the total length needed for pleacing the RATE MFIE
* tag and the EXTENDED RATE MFIE tag if needed.
* It encludes two bytes per tag for the tag itself and its len
*/
unsigned int ieee80211_MFIE_rate_len(struct ieee80211_device *ieee)
{
unsigned int rate_len = 0;
if (ieee->modulation & IEEE80211_CCK_MODULATION)
rate_len = IEEE80211_CCK_RATE_LEN + 2;
if (ieee->modulation & IEEE80211_OFDM_MODULATION)
rate_len += IEEE80211_OFDM_RATE_LEN + 2;
return rate_len;
}
/* pleace the MFIE rate, tag to the memory (double) poined.
* Then it updates the pointer so that
* it points after the new MFIE tag added.
*/
void ieee80211_MFIE_Brate(struct ieee80211_device *ieee, u8 **tag_p)
{
u8 *tag = *tag_p;
if (ieee->modulation & IEEE80211_CCK_MODULATION){
*tag++ = MFIE_TYPE_RATES;
*tag++ = 4;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_1MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_2MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_5MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_11MB;
}
/* We may add an option for custom rates that specific HW might support */
*tag_p = tag;
}
void ieee80211_MFIE_Grate(struct ieee80211_device *ieee, u8 **tag_p)
{
u8 *tag = *tag_p;
if (ieee->modulation & IEEE80211_OFDM_MODULATION){
*tag++ = MFIE_TYPE_RATES_EX;
*tag++ = 8;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_6MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_9MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_12MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_18MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_24MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_36MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_48MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_54MB;
}
/* We may add an option for custom rates that specific HW might support */
*tag_p = tag;
}
void ieee80211_WMM_Info(struct ieee80211_device *ieee, u8 **tag_p) {
u8 *tag = *tag_p;
*tag++ = MFIE_TYPE_GENERIC; //0
*tag++ = 7;
*tag++ = 0x00;
*tag++ = 0x50;
*tag++ = 0xf2;
*tag++ = 0x02;//5
*tag++ = 0x00;
*tag++ = 0x01;
#ifdef SUPPORT_USPD
if(ieee->current_network.wmm_info & 0x80) {
*tag++ = 0x0f|MAX_SP_Len;
} else {
*tag++ = MAX_SP_Len;
}
#else
*tag++ = MAX_SP_Len;
#endif
*tag_p = tag;
}
#ifdef THOMAS_TURBO
void ieee80211_TURBO_Info(struct ieee80211_device *ieee, u8 **tag_p) {
u8 *tag = *tag_p;
*tag++ = MFIE_TYPE_GENERIC; //0
*tag++ = 7;
*tag++ = 0x00;
*tag++ = 0xe0;
*tag++ = 0x4c;
*tag++ = 0x01;//5
*tag++ = 0x02;
*tag++ = 0x11;
*tag++ = 0x00;
*tag_p = tag;
printk(KERN_ALERT "This is enable turbo mode IE process\n");
}
#endif
void enqueue_mgmt(struct ieee80211_device *ieee, struct sk_buff *skb)
{
int nh;
nh = (ieee->mgmt_queue_head +1) % MGMT_QUEUE_NUM;
/*
* if the queue is full but we have newer frames then
* just overwrites the oldest.
*
* if (nh == ieee->mgmt_queue_tail)
* return -1;
*/
ieee->mgmt_queue_head = nh;
ieee->mgmt_queue_ring[nh] = skb;
//return 0;
}
struct sk_buff *dequeue_mgmt(struct ieee80211_device *ieee)
{
struct sk_buff *ret;
if(ieee->mgmt_queue_tail == ieee->mgmt_queue_head)
return NULL;
ret = ieee->mgmt_queue_ring[ieee->mgmt_queue_tail];
ieee->mgmt_queue_tail =
(ieee->mgmt_queue_tail+1) % MGMT_QUEUE_NUM;
return ret;
}
void init_mgmt_queue(struct ieee80211_device *ieee)
{
ieee->mgmt_queue_tail = ieee->mgmt_queue_head = 0;
}
u8 MgntQuery_MgntFrameTxRate(struct ieee80211_device *ieee)
{
PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
u8 rate;
// 2008/01/25 MH For broadcom, MGNT frame set as OFDM 6M.
if(pHTInfo->IOTAction & HT_IOT_ACT_MGNT_USE_CCK_6M)
rate = 0x0c;
else
rate = ieee->basic_rate & 0x7f;
if(rate == 0){
// 2005.01.26, by rcnjko.
if(ieee->mode == IEEE_A||
ieee->mode== IEEE_N_5G||
(ieee->mode== IEEE_N_24G&&!pHTInfo->bCurSuppCCK))
rate = 0x0c;
else
rate = 0x02;
}
/*
// Data rate of ProbeReq is already decided. Annie, 2005-03-31
if( pMgntInfo->bScanInProgress || (pMgntInfo->bDualModeScanStep!=0) )
{
if(pMgntInfo->dot11CurrentWirelessMode==WIRELESS_MODE_A)
rate = 0x0c;
else
rate = 0x02;
}
*/
return rate;
}
void ieee80211_sta_wakeup(struct ieee80211_device *ieee, short nl);
inline void softmac_mgmt_xmit(struct sk_buff *skb, struct ieee80211_device *ieee)
{
unsigned long flags;
short single = ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE;
struct ieee80211_hdr_3addr *header=
(struct ieee80211_hdr_3addr *) skb->data;
cb_desc *tcb_desc = (cb_desc *)(skb->cb + 8);
spin_lock_irqsave(&ieee->lock, flags);
/* called with 2nd param 0, no mgmt lock required */
ieee80211_sta_wakeup(ieee,0);
tcb_desc->queue_index = MGNT_QUEUE;
tcb_desc->data_rate = MgntQuery_MgntFrameTxRate(ieee);
tcb_desc->RATRIndex = 7;
tcb_desc->bTxDisableRateFallBack = 1;
tcb_desc->bTxUseDriverAssingedRate = 1;
if(single){
if(ieee->queue_stop){
enqueue_mgmt(ieee,skb);
}else{
header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0]<<4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
/* avoid watchdog triggers */
ieee->dev->trans_start = jiffies;
ieee->softmac_data_hard_start_xmit(skb,ieee->dev,ieee->basic_rate);
//dev_kfree_skb_any(skb);//edit by thomas
}
spin_unlock_irqrestore(&ieee->lock, flags);
}else{
spin_unlock_irqrestore(&ieee->lock, flags);
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags);
header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
/* check wether the managed packet queued greater than 5 */
if(!ieee->check_nic_enough_desc(ieee->dev,tcb_desc->queue_index)||\
(skb_queue_len(&ieee->skb_waitQ[tcb_desc->queue_index]) != 0)||\
(ieee->queue_stop) ) {
/* insert the skb packet to the management queue */
/* as for the completion function, it does not need
* to check it any more.
* */
printk("%s():insert to waitqueue!\n",__FUNCTION__);
skb_queue_tail(&ieee->skb_waitQ[tcb_desc->queue_index], skb);
} else {
//printk("TX packet!\n");
ieee->softmac_hard_start_xmit(skb,ieee->dev);
//dev_kfree_skb_any(skb);//edit by thomas
}
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags);
}
}
inline void softmac_ps_mgmt_xmit(struct sk_buff *skb, struct ieee80211_device *ieee)
{
short single = ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE;
struct ieee80211_hdr_3addr *header =
(struct ieee80211_hdr_3addr *) skb->data;
if(single){
header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
/* avoid watchdog triggers */
ieee->dev->trans_start = jiffies;
ieee->softmac_data_hard_start_xmit(skb,ieee->dev,ieee->basic_rate);
}else{
header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
ieee->softmac_hard_start_xmit(skb,ieee->dev);
}
//dev_kfree_skb_any(skb);//edit by thomas
}
inline struct sk_buff *ieee80211_probe_req(struct ieee80211_device *ieee)
{
unsigned int len,rate_len;
u8 *tag;
struct sk_buff *skb;
struct ieee80211_probe_request *req;
len = ieee->current_network.ssid_len;
rate_len = ieee80211_MFIE_rate_len(ieee);
skb = dev_alloc_skb(sizeof(struct ieee80211_probe_request) +
2 + len + rate_len + ieee->tx_headroom);
if (!skb)
return NULL;
skb_reserve(skb, ieee->tx_headroom);
req = (struct ieee80211_probe_request *) skb_put(skb,sizeof(struct ieee80211_probe_request));
req->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_PROBE_REQ);
req->header.duration_id = 0; //FIXME: is this OK ?
memset(req->header.addr1, 0xff, ETH_ALEN);
memcpy(req->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memset(req->header.addr3, 0xff, ETH_ALEN);
tag = (u8 *) skb_put(skb,len+2+rate_len);
*tag++ = MFIE_TYPE_SSID;
*tag++ = len;
memcpy(tag, ieee->current_network.ssid, len);
tag += len;
ieee80211_MFIE_Brate(ieee,&tag);
ieee80211_MFIE_Grate(ieee,&tag);
return skb;
}
struct sk_buff *ieee80211_get_beacon_(struct ieee80211_device *ieee);
void ieee80211_send_beacon(struct ieee80211_device *ieee)
{
struct sk_buff *skb;
if(!ieee->ieee_up)
return;
//unsigned long flags;
skb = ieee80211_get_beacon_(ieee);
if (skb){
softmac_mgmt_xmit(skb, ieee);
ieee->softmac_stats.tx_beacons++;
//dev_kfree_skb_any(skb);//edit by thomas
}
// ieee->beacon_timer.expires = jiffies +
// (MSECS( ieee->current_network.beacon_interval -5));
//spin_lock_irqsave(&ieee->beacon_lock,flags);
if(ieee->beacon_txing && ieee->ieee_up){
// if(!timer_pending(&ieee->beacon_timer))
// add_timer(&ieee->beacon_timer);
mod_timer(&ieee->beacon_timer,jiffies+(MSECS(ieee->current_network.beacon_interval-5)));
}
//spin_unlock_irqrestore(&ieee->beacon_lock,flags);
}
void ieee80211_send_beacon_cb(unsigned long _ieee)
{
struct ieee80211_device *ieee =
(struct ieee80211_device *) _ieee;
unsigned long flags;
spin_lock_irqsave(&ieee->beacon_lock, flags);
ieee80211_send_beacon(ieee);
spin_unlock_irqrestore(&ieee->beacon_lock, flags);
}
void ieee80211_send_probe(struct ieee80211_device *ieee)
{
struct sk_buff *skb;
skb = ieee80211_probe_req(ieee);
if (skb){
softmac_mgmt_xmit(skb, ieee);
ieee->softmac_stats.tx_probe_rq++;
//dev_kfree_skb_any(skb);//edit by thomas
}
}
void ieee80211_send_probe_requests(struct ieee80211_device *ieee)
{
if (ieee->active_scan && (ieee->softmac_features & IEEE_SOFTMAC_PROBERQ)){
ieee80211_send_probe(ieee);
ieee80211_send_probe(ieee);
}
}
/* this performs syncro scan blocking the caller until all channels
* in the allowed channel map has been checked.
*/
void ieee80211_softmac_scan_syncro(struct ieee80211_device *ieee)
{
short ch = 0;
u8 channel_map[MAX_CHANNEL_NUMBER+1];
memcpy(channel_map, GET_DOT11D_INFO(ieee)->channel_map, MAX_CHANNEL_NUMBER+1);
down(&ieee->scan_sem);
while(1)
{
do{
ch++;
if (ch > MAX_CHANNEL_NUMBER)
goto out; /* scan completed */
}while(!channel_map[ch]);
/* this function can be called in two situations
* 1- We have switched to ad-hoc mode and we are
* performing a complete syncro scan before conclude
* there are no interesting cell and to create a
* new one. In this case the link state is
* IEEE80211_NOLINK until we found an interesting cell.
* If so the ieee8021_new_net, called by the RX path
* will set the state to IEEE80211_LINKED, so we stop
* scanning
* 2- We are linked and the root uses run iwlist scan.
* So we switch to IEEE80211_LINKED_SCANNING to remember
* that we are still logically linked (not interested in
* new network events, despite for updating the net list,
* but we are temporarly 'unlinked' as the driver shall
* not filter RX frames and the channel is changing.
* So the only situation in witch are interested is to check
* if the state become LINKED because of the #1 situation
*/
if (ieee->state == IEEE80211_LINKED)
goto out;
ieee->set_chan(ieee->dev, ch);
if(channel_map[ch] == 1)
ieee80211_send_probe_requests(ieee);
/* this prevent excessive time wait when we
* need to wait for a syncro scan to end..
*/
if(ieee->state < IEEE80211_LINKED)
;
else
if (ieee->sync_scan_hurryup)
goto out;
msleep_interruptible_rsl(IEEE80211_SOFTMAC_SCAN_TIME);
}
out:
if(ieee->state < IEEE80211_LINKED){
ieee->actscanning = false;
up(&ieee->scan_sem);
}
else{
ieee->sync_scan_hurryup = 0;
if(IS_DOT11D_ENABLE(ieee))
DOT11D_ScanComplete(ieee);
up(&ieee->scan_sem);
}
}
void ieee80211_softmac_scan_wq(struct work_struct *work)
{
struct delayed_work *dwork = container_of(work, struct delayed_work, work);
struct ieee80211_device *ieee = container_of(dwork, struct ieee80211_device, softmac_scan_wq);
static short watchdog = 0;
u8 channel_map[MAX_CHANNEL_NUMBER+1];
memcpy(channel_map, GET_DOT11D_INFO(ieee)->channel_map, MAX_CHANNEL_NUMBER+1);
if(!ieee->ieee_up)
return;
down(&ieee->scan_sem);
do{
ieee->current_network.channel =
(ieee->current_network.channel + 1) % MAX_CHANNEL_NUMBER;
if (watchdog++ > MAX_CHANNEL_NUMBER)
{
//if current channel is not in channel map, set to default channel.
if (!channel_map[ieee->current_network.channel]) {
ieee->current_network.channel = 6;
goto out; /* no good chans */
}
}
}while(!channel_map[ieee->current_network.channel]);
if (ieee->scanning == 0 )
goto out;
ieee->set_chan(ieee->dev, ieee->current_network.channel);
if(channel_map[ieee->current_network.channel] == 1)
ieee80211_send_probe_requests(ieee);
queue_delayed_work(ieee->wq, &ieee->softmac_scan_wq, IEEE80211_SOFTMAC_SCAN_TIME);
up(&ieee->scan_sem);
return;
out:
if(IS_DOT11D_ENABLE(ieee))
DOT11D_ScanComplete(ieee);
ieee->actscanning = false;
watchdog = 0;
ieee->scanning = 0;
up(&ieee->scan_sem);
}
void ieee80211_beacons_start(struct ieee80211_device *ieee)
{
unsigned long flags;
spin_lock_irqsave(&ieee->beacon_lock,flags);
ieee->beacon_txing = 1;
ieee80211_send_beacon(ieee);
spin_unlock_irqrestore(&ieee->beacon_lock,flags);
}
void ieee80211_beacons_stop(struct ieee80211_device *ieee)
{
unsigned long flags;
spin_lock_irqsave(&ieee->beacon_lock,flags);
ieee->beacon_txing = 0;
del_timer_sync(&ieee->beacon_timer);
spin_unlock_irqrestore(&ieee->beacon_lock,flags);
}
void ieee80211_stop_send_beacons(struct ieee80211_device *ieee)
{
if(ieee->stop_send_beacons)
ieee->stop_send_beacons(ieee->dev);
if (ieee->softmac_features & IEEE_SOFTMAC_BEACONS)
ieee80211_beacons_stop(ieee);
}
void ieee80211_start_send_beacons(struct ieee80211_device *ieee)
{
if(ieee->start_send_beacons)
ieee->start_send_beacons(ieee->dev,ieee->basic_rate);
if(ieee->softmac_features & IEEE_SOFTMAC_BEACONS)
ieee80211_beacons_start(ieee);
}
void ieee80211_softmac_stop_scan(struct ieee80211_device *ieee)
{
// unsigned long flags;
//ieee->sync_scan_hurryup = 1;
down(&ieee->scan_sem);
// spin_lock_irqsave(&ieee->lock, flags);
if (ieee->scanning == 1){
ieee->scanning = 0;
cancel_delayed_work(&ieee->softmac_scan_wq);
}
// spin_unlock_irqrestore(&ieee->lock, flags);
up(&ieee->scan_sem);
}
void ieee80211_stop_scan(struct ieee80211_device *ieee)
{
if (ieee->softmac_features & IEEE_SOFTMAC_SCAN)
ieee80211_softmac_stop_scan(ieee);
else
ieee->stop_scan(ieee->dev);
}
/* called with ieee->lock held */
void ieee80211_start_scan(struct ieee80211_device *ieee)
{
if(IS_DOT11D_ENABLE(ieee) )
{
if(IS_COUNTRY_IE_VALID(ieee))
{
RESET_CIE_WATCHDOG(ieee);
}
}
if (ieee->softmac_features & IEEE_SOFTMAC_SCAN){
if (ieee->scanning == 0){
ieee->scanning = 1;
queue_delayed_work(ieee->wq, &ieee->softmac_scan_wq, 0);
}
}else
ieee->start_scan(ieee->dev);
}
/* called with wx_sem held */
void ieee80211_start_scan_syncro(struct ieee80211_device *ieee)
{
if(IS_DOT11D_ENABLE(ieee) )
{
if(IS_COUNTRY_IE_VALID(ieee))
{
RESET_CIE_WATCHDOG(ieee);
}
}
ieee->sync_scan_hurryup = 0;
if (ieee->softmac_features & IEEE_SOFTMAC_SCAN)
ieee80211_softmac_scan_syncro(ieee);
else
ieee->scan_syncro(ieee->dev);
}
inline struct sk_buff *ieee80211_authentication_req(struct ieee80211_network *beacon,
struct ieee80211_device *ieee, int challengelen)
{
struct sk_buff *skb;
struct ieee80211_authentication *auth;
int len = sizeof(struct ieee80211_authentication) + challengelen + ieee->tx_headroom;
skb = dev_alloc_skb(len);
if (!skb) return NULL;
skb_reserve(skb, ieee->tx_headroom);
auth = (struct ieee80211_authentication *)
skb_put(skb, sizeof(struct ieee80211_authentication));
auth->header.frame_ctl = IEEE80211_STYPE_AUTH;
if (challengelen) auth->header.frame_ctl |= IEEE80211_FCTL_WEP;
auth->header.duration_id = 0x013a; //FIXME
memcpy(auth->header.addr1, beacon->bssid, ETH_ALEN);
memcpy(auth->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(auth->header.addr3, beacon->bssid, ETH_ALEN);
//auth->algorithm = ieee->open_wep ? WLAN_AUTH_OPEN : WLAN_AUTH_SHARED_KEY;
if(ieee->auth_mode == 0)
auth->algorithm = WLAN_AUTH_OPEN;
else if(ieee->auth_mode == 1)
auth->algorithm = WLAN_AUTH_SHARED_KEY;
else if(ieee->auth_mode == 2)
auth->algorithm = WLAN_AUTH_OPEN;//0x80;
printk("=================>%s():auth->algorithm is %d\n",__FUNCTION__,auth->algorithm);
auth->transaction = cpu_to_le16(ieee->associate_seq);
ieee->associate_seq++;
auth->status = cpu_to_le16(WLAN_STATUS_SUCCESS);
return skb;
}
static struct sk_buff* ieee80211_probe_resp(struct ieee80211_device *ieee, u8 *dest)
{
u8 *tag;
int beacon_size;
struct ieee80211_probe_response *beacon_buf;
struct sk_buff *skb = NULL;
int encrypt;
int atim_len,erp_len;
struct ieee80211_crypt_data* crypt;
char *ssid = ieee->current_network.ssid;
int ssid_len = ieee->current_network.ssid_len;
int rate_len = ieee->current_network.rates_len+2;
int rate_ex_len = ieee->current_network.rates_ex_len;
int wpa_ie_len = ieee->wpa_ie_len;
u8 erpinfo_content = 0;
u8* tmp_ht_cap_buf;
u8 tmp_ht_cap_len=0;
u8* tmp_ht_info_buf;
u8 tmp_ht_info_len=0;
PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
u8* tmp_generic_ie_buf=NULL;
u8 tmp_generic_ie_len=0;
if(rate_ex_len > 0) rate_ex_len+=2;
if(ieee->current_network.capability & WLAN_CAPABILITY_IBSS)
atim_len = 4;
else
atim_len = 0;
if(ieee80211_is_54g(&ieee->current_network))
erp_len = 3;
else
erp_len = 0;
crypt = ieee->crypt[ieee->tx_keyidx];
encrypt = ieee->host_encrypt && crypt && crypt->ops &&
((0 == strcmp(crypt->ops->name, "WEP") || wpa_ie_len));
//HT ralated element
tmp_ht_cap_buf =(u8*) &(ieee->pHTInfo->SelfHTCap);
tmp_ht_cap_len = sizeof(ieee->pHTInfo->SelfHTCap);
tmp_ht_info_buf =(u8*) &(ieee->pHTInfo->SelfHTInfo);
tmp_ht_info_len = sizeof(ieee->pHTInfo->SelfHTInfo);
HTConstructCapabilityElement(ieee, tmp_ht_cap_buf, &tmp_ht_cap_len,encrypt);
HTConstructInfoElement(ieee,tmp_ht_info_buf,&tmp_ht_info_len, encrypt);
if(pHTInfo->bRegRT2RTAggregation)
{
tmp_generic_ie_buf = ieee->pHTInfo->szRT2RTAggBuffer;
tmp_generic_ie_len = sizeof(ieee->pHTInfo->szRT2RTAggBuffer);
HTConstructRT2RTAggElement(ieee, tmp_generic_ie_buf, &tmp_generic_ie_len);
}
// printk("===============>tmp_ht_cap_len is %d,tmp_ht_info_len is %d, tmp_generic_ie_len is %d\n",tmp_ht_cap_len,tmp_ht_info_len,tmp_generic_ie_len);
beacon_size = sizeof(struct ieee80211_probe_response)+2+
ssid_len
+3 //channel
+rate_len
+rate_ex_len
+atim_len
+erp_len
+wpa_ie_len
// +tmp_ht_cap_len
// +tmp_ht_info_len
// +tmp_generic_ie_len
// +wmm_len+2
+ieee->tx_headroom;
skb = dev_alloc_skb(beacon_size);
if (!skb)
return NULL;
skb_reserve(skb, ieee->tx_headroom);
beacon_buf = (struct ieee80211_probe_response*) skb_put(skb, (beacon_size - ieee->tx_headroom));
memcpy (beacon_buf->header.addr1, dest,ETH_ALEN);
memcpy (beacon_buf->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy (beacon_buf->header.addr3, ieee->current_network.bssid, ETH_ALEN);
beacon_buf->header.duration_id = 0; //FIXME
beacon_buf->beacon_interval =
cpu_to_le16(ieee->current_network.beacon_interval);
beacon_buf->capability =
cpu_to_le16(ieee->current_network.capability & WLAN_CAPABILITY_IBSS);
beacon_buf->capability |=
cpu_to_le16(ieee->current_network.capability & WLAN_CAPABILITY_SHORT_PREAMBLE); //add short preamble here
if(ieee->short_slot && (ieee->current_network.capability & WLAN_CAPABILITY_SHORT_SLOT))
beacon_buf->capability |= cpu_to_le16(WLAN_CAPABILITY_SHORT_SLOT);
crypt = ieee->crypt[ieee->tx_keyidx];
if (encrypt)
beacon_buf->capability |= cpu_to_le16(WLAN_CAPABILITY_PRIVACY);
beacon_buf->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_PROBE_RESP);
beacon_buf->info_element[0].id = MFIE_TYPE_SSID;
beacon_buf->info_element[0].len = ssid_len;
tag = (u8*) beacon_buf->info_element[0].data;
memcpy(tag, ssid, ssid_len);
tag += ssid_len;
*(tag++) = MFIE_TYPE_RATES;
*(tag++) = rate_len-2;
memcpy(tag,ieee->current_network.rates,rate_len-2);
tag+=rate_len-2;
*(tag++) = MFIE_TYPE_DS_SET;
*(tag++) = 1;
*(tag++) = ieee->current_network.channel;
if(atim_len){
u16 val16;
*(tag++) = MFIE_TYPE_IBSS_SET;
*(tag++) = 2;
//*((u16*)(tag)) = cpu_to_le16(ieee->current_network.atim_window);
val16 = cpu_to_le16(ieee->current_network.atim_window);
memcpy((u8 *)tag, (u8 *)&val16, 2);
tag+=2;
}
if(erp_len){
*(tag++) = MFIE_TYPE_ERP;
*(tag++) = 1;
*(tag++) = erpinfo_content;
}
if(rate_ex_len){
*(tag++) = MFIE_TYPE_RATES_EX;
*(tag++) = rate_ex_len-2;
memcpy(tag,ieee->current_network.rates_ex,rate_ex_len-2);
tag+=rate_ex_len-2;
}
if (wpa_ie_len)
{
if (ieee->iw_mode == IW_MODE_ADHOC)
{//as Windows will set pairwise key same as the group key which is not allowed in Linux, so set this for IOT issue. WB 2008.07.07
memcpy(&ieee->wpa_ie[14], &ieee->wpa_ie[8], 4);
}
memcpy(tag, ieee->wpa_ie, ieee->wpa_ie_len);
tag += wpa_ie_len;
}
//skb->dev = ieee->dev;
return skb;
}
struct sk_buff* ieee80211_assoc_resp(struct ieee80211_device *ieee, u8 *dest)
{
struct sk_buff *skb;
u8* tag;
struct ieee80211_crypt_data* crypt;
struct ieee80211_assoc_response_frame *assoc;
short encrypt;
unsigned int rate_len = ieee80211_MFIE_rate_len(ieee);
int len = sizeof(struct ieee80211_assoc_response_frame) + rate_len + ieee->tx_headroom;
skb = dev_alloc_skb(len);
if (!skb)
return NULL;
skb_reserve(skb, ieee->tx_headroom);
assoc = (struct ieee80211_assoc_response_frame *)
skb_put(skb,sizeof(struct ieee80211_assoc_response_frame));
assoc->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_ASSOC_RESP);
memcpy(assoc->header.addr1, dest,ETH_ALEN);
memcpy(assoc->header.addr3, ieee->dev->dev_addr, ETH_ALEN);
memcpy(assoc->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
assoc->capability = cpu_to_le16(ieee->iw_mode == IW_MODE_MASTER ?
WLAN_CAPABILITY_BSS : WLAN_CAPABILITY_IBSS);
if(ieee->short_slot)
assoc->capability |= cpu_to_le16(WLAN_CAPABILITY_SHORT_SLOT);
if (ieee->host_encrypt)
crypt = ieee->crypt[ieee->tx_keyidx];
else crypt = NULL;
encrypt = ( crypt && crypt->ops);
if (encrypt)
assoc->capability |= cpu_to_le16(WLAN_CAPABILITY_PRIVACY);
assoc->status = 0;
assoc->aid = cpu_to_le16(ieee->assoc_id);
if (ieee->assoc_id == 0x2007) ieee->assoc_id=0;
else ieee->assoc_id++;
tag = (u8*) skb_put(skb, rate_len);
ieee80211_MFIE_Brate(ieee, &tag);
ieee80211_MFIE_Grate(ieee, &tag);
return skb;
}
struct sk_buff* ieee80211_auth_resp(struct ieee80211_device *ieee,int status, u8 *dest)
{
struct sk_buff *skb;
struct ieee80211_authentication *auth;
int len = ieee->tx_headroom + sizeof(struct ieee80211_authentication)+1;
skb = dev_alloc_skb(len);
if (!skb)
return NULL;
skb->len = sizeof(struct ieee80211_authentication);
auth = (struct ieee80211_authentication *)skb->data;
auth->status = cpu_to_le16(status);
auth->transaction = cpu_to_le16(2);
auth->algorithm = cpu_to_le16(WLAN_AUTH_OPEN);
memcpy(auth->header.addr3, ieee->dev->dev_addr, ETH_ALEN);
memcpy(auth->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(auth->header.addr1, dest, ETH_ALEN);
auth->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_AUTH);
return skb;
}
struct sk_buff* ieee80211_null_func(struct ieee80211_device *ieee,short pwr)
{
struct sk_buff *skb;
struct ieee80211_hdr_3addr* hdr;
skb = dev_alloc_skb(sizeof(struct ieee80211_hdr_3addr));
if (!skb)
return NULL;
hdr = (struct ieee80211_hdr_3addr*)skb_put(skb,sizeof(struct ieee80211_hdr_3addr));
memcpy(hdr->addr1, ieee->current_network.bssid, ETH_ALEN);
memcpy(hdr->addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(hdr->addr3, ieee->current_network.bssid, ETH_ALEN);
hdr->frame_ctl = cpu_to_le16(IEEE80211_FTYPE_DATA |
IEEE80211_STYPE_NULLFUNC | IEEE80211_FCTL_TODS |
(pwr ? IEEE80211_FCTL_PM:0));
return skb;
}
void ieee80211_resp_to_assoc_rq(struct ieee80211_device *ieee, u8* dest)
{
struct sk_buff *buf = ieee80211_assoc_resp(ieee, dest);
if (buf)
softmac_mgmt_xmit(buf, ieee);
}
void ieee80211_resp_to_auth(struct ieee80211_device *ieee, int s, u8* dest)
{
struct sk_buff *buf = ieee80211_auth_resp(ieee, s, dest);
if (buf)
softmac_mgmt_xmit(buf, ieee);
}
void ieee80211_resp_to_probe(struct ieee80211_device *ieee, u8 *dest)
{
struct sk_buff *buf = ieee80211_probe_resp(ieee, dest);
if (buf)
softmac_mgmt_xmit(buf, ieee);
}
inline struct sk_buff *ieee80211_association_req(struct ieee80211_network *beacon,struct ieee80211_device *ieee)
{
struct sk_buff *skb;
//unsigned long flags;
struct ieee80211_assoc_request_frame *hdr;
u8 *tag;//,*rsn_ie;
//short info_addr = 0;
//int i;
//u16 suite_count = 0;
//u8 suit_select = 0;
//unsigned int wpa_len = beacon->wpa_ie_len;
//for HT
u8* ht_cap_buf = NULL;
u8 ht_cap_len=0;
u8* realtek_ie_buf=NULL;
u8 realtek_ie_len=0;
int wpa_ie_len= ieee->wpa_ie_len;
unsigned int ckip_ie_len=0;
unsigned int ccxrm_ie_len=0;
unsigned int cxvernum_ie_len=0;
struct ieee80211_crypt_data* crypt;
int encrypt;
unsigned int rate_len = ieee80211_MFIE_rate_len(ieee);
unsigned int wmm_info_len = beacon->qos_data.supported?9:0;
#ifdef THOMAS_TURBO
unsigned int turbo_info_len = beacon->Turbo_Enable?9:0;
#endif
int len = 0;
crypt = ieee->crypt[ieee->tx_keyidx];
encrypt = ieee->host_encrypt && crypt && crypt->ops && ((0 == strcmp(crypt->ops->name,"WEP") || wpa_ie_len));
//Include High Throuput capability && Realtek proprietary
if(ieee->pHTInfo->bCurrentHTSupport&&ieee->pHTInfo->bEnableHT)
{
ht_cap_buf = (u8*)&(ieee->pHTInfo->SelfHTCap);
ht_cap_len = sizeof(ieee->pHTInfo->SelfHTCap);
HTConstructCapabilityElement(ieee, ht_cap_buf, &ht_cap_len, encrypt);
if(ieee->pHTInfo->bCurrentRT2RTAggregation)
{
realtek_ie_buf = ieee->pHTInfo->szRT2RTAggBuffer;
realtek_ie_len = sizeof( ieee->pHTInfo->szRT2RTAggBuffer);
HTConstructRT2RTAggElement(ieee, realtek_ie_buf, &realtek_ie_len);
}
}
if(ieee->qos_support){
wmm_info_len = beacon->qos_data.supported?9:0;
}
if(beacon->bCkipSupported)
{
ckip_ie_len = 30+2;
}
if(beacon->bCcxRmEnable)
{
ccxrm_ie_len = 6+2;
}
if( beacon->BssCcxVerNumber >= 2 )
{
cxvernum_ie_len = 5+2;
}
#ifdef THOMAS_TURBO
len = sizeof(struct ieee80211_assoc_request_frame)+ 2
+ beacon->ssid_len//essid tagged val
+ rate_len//rates tagged val
+ wpa_ie_len
+ wmm_info_len
+ turbo_info_len
+ ht_cap_len
+ realtek_ie_len
+ ckip_ie_len
+ ccxrm_ie_len
+ cxvernum_ie_len
+ ieee->tx_headroom;
#else
len = sizeof(struct ieee80211_assoc_request_frame)+ 2
+ beacon->ssid_len//essid tagged val
+ rate_len//rates tagged val
+ wpa_ie_len
+ wmm_info_len
+ ht_cap_len
+ realtek_ie_len
+ ckip_ie_len
+ ccxrm_ie_len
+ cxvernum_ie_len
+ ieee->tx_headroom;
#endif
skb = dev_alloc_skb(len);
if (!skb)
return NULL;
skb_reserve(skb, ieee->tx_headroom);
hdr = (struct ieee80211_assoc_request_frame *)
skb_put(skb, sizeof(struct ieee80211_assoc_request_frame)+2);
hdr->header.frame_ctl = IEEE80211_STYPE_ASSOC_REQ;
hdr->header.duration_id= 37; //FIXME
memcpy(hdr->header.addr1, beacon->bssid, ETH_ALEN);
memcpy(hdr->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(hdr->header.addr3, beacon->bssid, ETH_ALEN);
memcpy(ieee->ap_mac_addr, beacon->bssid, ETH_ALEN);//for HW security, John
hdr->capability = cpu_to_le16(WLAN_CAPABILITY_BSS);
if (beacon->capability & WLAN_CAPABILITY_PRIVACY )
hdr->capability |= cpu_to_le16(WLAN_CAPABILITY_PRIVACY);
if (beacon->capability & WLAN_CAPABILITY_SHORT_PREAMBLE)
hdr->capability |= cpu_to_le16(WLAN_CAPABILITY_SHORT_PREAMBLE); //add short_preamble here
if(ieee->short_slot)
hdr->capability |= cpu_to_le16(WLAN_CAPABILITY_SHORT_SLOT);
if (wmm_info_len) //QOS
hdr->capability |= cpu_to_le16(WLAN_CAPABILITY_QOS);
hdr->listen_interval = 0xa; //FIXME
hdr->info_element[0].id = MFIE_TYPE_SSID;
hdr->info_element[0].len = beacon->ssid_len;
tag = skb_put(skb, beacon->ssid_len);
memcpy(tag, beacon->ssid, beacon->ssid_len);
tag = skb_put(skb, rate_len);
ieee80211_MFIE_Brate(ieee, &tag);
ieee80211_MFIE_Grate(ieee, &tag);
// For CCX 1 S13, CKIP. Added by Annie, 2006-08-14.
if( beacon->bCkipSupported )
{
static u8 AironetIeOui[] = {0x00, 0x01, 0x66}; // "4500-client"
u8 CcxAironetBuf[30];
OCTET_STRING osCcxAironetIE;
memset(CcxAironetBuf, 0,30);
osCcxAironetIE.Octet = CcxAironetBuf;
osCcxAironetIE.Length = sizeof(CcxAironetBuf);
//
// Ref. CCX test plan v3.61, 3.2.3.1 step 13.
// We want to make the device type as "4500-client". 060926, by CCW.
//
memcpy(osCcxAironetIE.Octet, AironetIeOui, sizeof(AironetIeOui));
// CCX1 spec V1.13, A01.1 CKIP Negotiation (page23):
// "The CKIP negotiation is started with the associate request from the client to the access point,
// containing an Aironet element with both the MIC and KP bits set."
osCcxAironetIE.Octet[IE_CISCO_FLAG_POSITION] |= (SUPPORT_CKIP_PK|SUPPORT_CKIP_MIC) ;
tag = skb_put(skb, ckip_ie_len);
*tag++ = MFIE_TYPE_AIRONET;
*tag++ = osCcxAironetIE.Length;
memcpy(tag,osCcxAironetIE.Octet,osCcxAironetIE.Length);
tag += osCcxAironetIE.Length;
}
if(beacon->bCcxRmEnable)
{
static u8 CcxRmCapBuf[] = {0x00, 0x40, 0x96, 0x01, 0x01, 0x00};
OCTET_STRING osCcxRmCap;
osCcxRmCap.Octet = CcxRmCapBuf;
osCcxRmCap.Length = sizeof(CcxRmCapBuf);
tag = skb_put(skb,ccxrm_ie_len);
*tag++ = MFIE_TYPE_GENERIC;
*tag++ = osCcxRmCap.Length;
memcpy(tag,osCcxRmCap.Octet,osCcxRmCap.Length);
tag += osCcxRmCap.Length;
}
if( beacon->BssCcxVerNumber >= 2 )
{
u8 CcxVerNumBuf[] = {0x00, 0x40, 0x96, 0x03, 0x00};
OCTET_STRING osCcxVerNum;
CcxVerNumBuf[4] = beacon->BssCcxVerNumber;
osCcxVerNum.Octet = CcxVerNumBuf;
osCcxVerNum.Length = sizeof(CcxVerNumBuf);
tag = skb_put(skb,cxvernum_ie_len);
*tag++ = MFIE_TYPE_GENERIC;
*tag++ = osCcxVerNum.Length;
memcpy(tag,osCcxVerNum.Octet,osCcxVerNum.Length);
tag += osCcxVerNum.Length;
}
//HT cap element
if(ieee->pHTInfo->bCurrentHTSupport&&ieee->pHTInfo->bEnableHT){
if(ieee->pHTInfo->ePeerHTSpecVer != HT_SPEC_VER_EWC)
{
tag = skb_put(skb, ht_cap_len);
*tag++ = MFIE_TYPE_HT_CAP;
*tag++ = ht_cap_len - 2;
memcpy(tag, ht_cap_buf,ht_cap_len -2);
tag += ht_cap_len -2;
}
}
//choose what wpa_supplicant gives to associate.
tag = skb_put(skb, wpa_ie_len);
if (wpa_ie_len){
memcpy(tag, ieee->wpa_ie, ieee->wpa_ie_len);
}
tag = skb_put(skb,wmm_info_len);
if(wmm_info_len) {
ieee80211_WMM_Info(ieee, &tag);
}
#ifdef THOMAS_TURBO
tag = skb_put(skb,turbo_info_len);
if(turbo_info_len) {
ieee80211_TURBO_Info(ieee, &tag);
}
#endif
if(ieee->pHTInfo->bCurrentHTSupport&&ieee->pHTInfo->bEnableHT){
if(ieee->pHTInfo->ePeerHTSpecVer == HT_SPEC_VER_EWC)
{
tag = skb_put(skb, ht_cap_len);
*tag++ = MFIE_TYPE_GENERIC;
*tag++ = ht_cap_len - 2;
memcpy(tag, ht_cap_buf,ht_cap_len - 2);
tag += ht_cap_len -2;
}
if(ieee->pHTInfo->bCurrentRT2RTAggregation){
tag = skb_put(skb, realtek_ie_len);
*tag++ = MFIE_TYPE_GENERIC;
*tag++ = realtek_ie_len - 2;
memcpy(tag, realtek_ie_buf,realtek_ie_len -2 );
}
}
// printk("<=====%s(), %p, %p\n", __FUNCTION__, ieee->dev, ieee->dev->dev_addr);
// IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA, skb->data, skb->len);
return skb;
}
void ieee80211_associate_abort(struct ieee80211_device *ieee)
{
unsigned long flags;
spin_lock_irqsave(&ieee->lock, flags);
ieee->associate_seq++;
/* don't scan, and avoid to have the RX path possibily
* try again to associate. Even do not react to AUTH or
* ASSOC response. Just wait for the retry wq to be scheduled.
* Here we will check if there are good nets to associate
* with, so we retry or just get back to NO_LINK and scanning
*/
if (ieee->state == IEEE80211_ASSOCIATING_AUTHENTICATING){
IEEE80211_DEBUG_MGMT("Authentication failed\n");
ieee->softmac_stats.no_auth_rs++;
}else{
IEEE80211_DEBUG_MGMT("Association failed\n");
ieee->softmac_stats.no_ass_rs++;
}
ieee->state = IEEE80211_ASSOCIATING_RETRY;
queue_delayed_work(ieee->wq, &ieee->associate_retry_wq, \
IEEE80211_SOFTMAC_ASSOC_RETRY_TIME);
spin_unlock_irqrestore(&ieee->lock, flags);
}
void ieee80211_associate_abort_cb(unsigned long dev)
{
ieee80211_associate_abort((struct ieee80211_device *) dev);
}
void ieee80211_associate_step1(struct ieee80211_device *ieee)
{
struct ieee80211_network *beacon = &ieee->current_network;
struct sk_buff *skb;
IEEE80211_DEBUG_MGMT("Stopping scan\n");
ieee->softmac_stats.tx_auth_rq++;
skb=ieee80211_authentication_req(beacon, ieee, 0);
if (!skb)
ieee80211_associate_abort(ieee);
else{
ieee->state = IEEE80211_ASSOCIATING_AUTHENTICATING ;
IEEE80211_DEBUG_MGMT("Sending authentication request\n");
//printk(KERN_WARNING "Sending authentication request\n");
softmac_mgmt_xmit(skb, ieee);
//BUGON when you try to add_timer twice, using mod_timer may be better, john0709
if(!timer_pending(&ieee->associate_timer)){
ieee->associate_timer.expires = jiffies + (HZ / 2);
add_timer(&ieee->associate_timer);
}
//dev_kfree_skb_any(skb);//edit by thomas
}
}
void ieee80211_auth_challenge(struct ieee80211_device *ieee, u8 *challenge, int chlen)
{
u8 *c;
struct sk_buff *skb;
struct ieee80211_network *beacon = &ieee->current_network;
// int hlen = sizeof(struct ieee80211_authentication);
ieee->associate_seq++;
ieee->softmac_stats.tx_auth_rq++;
skb = ieee80211_authentication_req(beacon, ieee, chlen+2);
if (!skb)
ieee80211_associate_abort(ieee);
else{
c = skb_put(skb, chlen+2);
*(c++) = MFIE_TYPE_CHALLENGE;
*(c++) = chlen;
memcpy(c, challenge, chlen);
IEEE80211_DEBUG_MGMT("Sending authentication challenge response\n");
ieee80211_encrypt_fragment(ieee, skb, sizeof(struct ieee80211_hdr_3addr ));
softmac_mgmt_xmit(skb, ieee);
mod_timer(&ieee->associate_timer, jiffies + (HZ/2));
//dev_kfree_skb_any(skb);//edit by thomas
}
kfree(challenge);
}
void ieee80211_associate_step2(struct ieee80211_device *ieee)
{
struct sk_buff* skb;
struct ieee80211_network *beacon = &ieee->current_network;
del_timer_sync(&ieee->associate_timer);
IEEE80211_DEBUG_MGMT("Sending association request\n");
ieee->softmac_stats.tx_ass_rq++;
skb=ieee80211_association_req(beacon, ieee);
if (!skb)
ieee80211_associate_abort(ieee);
else{
softmac_mgmt_xmit(skb, ieee);
mod_timer(&ieee->associate_timer, jiffies + (HZ/2));
//dev_kfree_skb_any(skb);//edit by thomas
}
}
void ieee80211_associate_complete_wq(struct work_struct *work)
{
struct ieee80211_device *ieee = container_of(work, struct ieee80211_device, associate_complete_wq);
printk(KERN_INFO "Associated successfully\n");
if(ieee80211_is_54g(&ieee->current_network) &&
(ieee->modulation & IEEE80211_OFDM_MODULATION)){
ieee->rate = 108;
printk(KERN_INFO"Using G rates:%d\n", ieee->rate);
}else{
ieee->rate = 22;
printk(KERN_INFO"Using B rates:%d\n", ieee->rate);
}
if (ieee->pHTInfo->bCurrentHTSupport&&ieee->pHTInfo->bEnableHT)
{
printk("Successfully associated, ht enabled\n");
HTOnAssocRsp(ieee);
}
else
{
printk("Successfully associated, ht not enabled(%d, %d)\n", ieee->pHTInfo->bCurrentHTSupport, ieee->pHTInfo->bEnableHT);
memset(ieee->dot11HTOperationalRateSet, 0, 16);
//HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
}
ieee->LinkDetectInfo.SlotNum = 2 * (1 + ieee->current_network.beacon_interval/500);
// To prevent the immediately calling watch_dog after association.
if(ieee->LinkDetectInfo.NumRecvBcnInPeriod==0||ieee->LinkDetectInfo.NumRecvDataInPeriod==0 )
{
ieee->LinkDetectInfo.NumRecvBcnInPeriod = 1;
ieee->LinkDetectInfo.NumRecvDataInPeriod= 1;
}
ieee->link_change(ieee->dev);
if(ieee->is_silent_reset == 0){
printk("============>normal associate\n");
notify_wx_assoc_event(ieee);
}
else if(ieee->is_silent_reset == 1)
{
printk("==================>silent reset associate\n");
ieee->is_silent_reset = 0;
}
if (ieee->data_hard_resume)
ieee->data_hard_resume(ieee->dev);
netif_carrier_on(ieee->dev);
}
void ieee80211_associate_complete(struct ieee80211_device *ieee)
{
// int i;
// struct net_device* dev = ieee->dev;
del_timer_sync(&ieee->associate_timer);
ieee->state = IEEE80211_LINKED;
//ieee->UpdateHalRATRTableHandler(dev, ieee->dot11HTOperationalRateSet);
queue_work(ieee->wq, &ieee->associate_complete_wq);
}
void ieee80211_associate_procedure_wq(struct work_struct *work)
{
struct ieee80211_device *ieee = container_of(work, struct ieee80211_device, associate_procedure_wq);
ieee->sync_scan_hurryup = 1;
down(&ieee->wx_sem);
if (ieee->data_hard_stop)
ieee->data_hard_stop(ieee->dev);
ieee80211_stop_scan(ieee);
printk("===>%s(), chan:%d\n", __FUNCTION__, ieee->current_network.channel);
//ieee->set_chan(ieee->dev, ieee->current_network.channel);
HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
ieee->associate_seq = 1;
ieee80211_associate_step1(ieee);
up(&ieee->wx_sem);
}
inline void ieee80211_softmac_new_net(struct ieee80211_device *ieee, struct ieee80211_network *net)
{
u8 tmp_ssid[IW_ESSID_MAX_SIZE+1];
int tmp_ssid_len = 0;
short apset,ssidset,ssidbroad,apmatch,ssidmatch;
/* we are interested in new new only if we are not associated
* and we are not associating / authenticating
*/
if (ieee->state != IEEE80211_NOLINK)
return;
if ((ieee->iw_mode == IW_MODE_INFRA) && !(net->capability & WLAN_CAPABILITY_BSS))
return;
if ((ieee->iw_mode == IW_MODE_ADHOC) && !(net->capability & WLAN_CAPABILITY_IBSS))
return;
if (ieee->iw_mode == IW_MODE_INFRA || ieee->iw_mode == IW_MODE_ADHOC){
/* if the user specified the AP MAC, we need also the essid
* This could be obtained by beacons or, if the network does not
* broadcast it, it can be put manually.
*/
apset = ieee->wap_set;//(memcmp(ieee->current_network.bssid, zero,ETH_ALEN)!=0 );
ssidset = ieee->ssid_set;//ieee->current_network.ssid[0] != '\0';
ssidbroad = !(net->ssid_len == 0 || net->ssid[0]== '\0');
apmatch = (memcmp(ieee->current_network.bssid, net->bssid, ETH_ALEN)==0);
ssidmatch = (ieee->current_network.ssid_len == net->ssid_len)&&\
(!strncmp(ieee->current_network.ssid, net->ssid, net->ssid_len));
if ( /* if the user set the AP check if match.
* if the network does not broadcast essid we check the user supplyed ANY essid
* if the network does broadcast and the user does not set essid it is OK
* if the network does broadcast and the user did set essid chech if essid match
*/
( apset && apmatch &&
((ssidset && ssidbroad && ssidmatch) || (ssidbroad && !ssidset) || (!ssidbroad && ssidset)) ) ||
/* if the ap is not set, check that the user set the bssid
* and the network does bradcast and that those two bssid matches
*/
(!apset && ssidset && ssidbroad && ssidmatch)
){
/* if the essid is hidden replace it with the
* essid provided by the user.
*/
if (!ssidbroad){
strncpy(tmp_ssid, ieee->current_network.ssid, IW_ESSID_MAX_SIZE);
tmp_ssid_len = ieee->current_network.ssid_len;
}
memcpy(&ieee->current_network, net, sizeof(struct ieee80211_network));
if (!ssidbroad){
strncpy(ieee->current_network.ssid, tmp_ssid, IW_ESSID_MAX_SIZE);
ieee->current_network.ssid_len = tmp_ssid_len;
}
printk(KERN_INFO"Linking with %s,channel:%d, qos:%d, myHT:%d, networkHT:%d\n",ieee->current_network.ssid,ieee->current_network.channel, ieee->current_network.qos_data.supported, ieee->pHTInfo->bEnableHT, ieee->current_network.bssht.bdSupportHT);
//ieee->pHTInfo->IOTAction = 0;
HTResetIOTSetting(ieee->pHTInfo);
if (ieee->iw_mode == IW_MODE_INFRA){
/* Join the network for the first time */
ieee->AsocRetryCount = 0;
//for HT by amy 080514
if((ieee->current_network.qos_data.supported == 1) &&
// (ieee->pHTInfo->bEnableHT && ieee->current_network.bssht.bdSupportHT))
ieee->current_network.bssht.bdSupportHT)
/*WB, 2008.09.09:bCurrentHTSupport and bEnableHT two flags are going to put together to check whether we are in HT now, so needn't to check bEnableHT flags here. That's is to say we will set to HT support whenever joined AP has the ability to support HT. And whether we are in HT or not, please check bCurrentHTSupport&&bEnableHT now please.*/
{
// ieee->pHTInfo->bCurrentHTSupport = true;
HTResetSelfAndSavePeerSetting(ieee, &(ieee->current_network));
}
else
{
ieee->pHTInfo->bCurrentHTSupport = false;
}
ieee->state = IEEE80211_ASSOCIATING;
queue_work(ieee->wq, &ieee->associate_procedure_wq);
}else{
if(ieee80211_is_54g(&ieee->current_network) &&
(ieee->modulation & IEEE80211_OFDM_MODULATION)){
ieee->rate = 108;
ieee->SetWirelessMode(ieee->dev, IEEE_G);
printk(KERN_INFO"Using G rates\n");
}else{
ieee->rate = 22;
ieee->SetWirelessMode(ieee->dev, IEEE_B);
printk(KERN_INFO"Using B rates\n");
}
memset(ieee->dot11HTOperationalRateSet, 0, 16);
//HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
ieee->state = IEEE80211_LINKED;
}
}
}
}
void ieee80211_softmac_check_all_nets(struct ieee80211_device *ieee)
{
unsigned long flags;
struct ieee80211_network *target;
spin_lock_irqsave(&ieee->lock, flags);
list_for_each_entry(target, &ieee->network_list, list) {
/* if the state become different that NOLINK means
* we had found what we are searching for
*/
if (ieee->state != IEEE80211_NOLINK)
break;
if (ieee->scan_age == 0 || time_after(target->last_scanned + ieee->scan_age, jiffies))
ieee80211_softmac_new_net(ieee, target);
}
spin_unlock_irqrestore(&ieee->lock, flags);
}
static inline u16 auth_parse(struct sk_buff *skb, u8** challenge, int *chlen)
{
struct ieee80211_authentication *a;
u8 *t;
if (skb->len < (sizeof(struct ieee80211_authentication)-sizeof(struct ieee80211_info_element))){
IEEE80211_DEBUG_MGMT("invalid len in auth resp: %d\n",skb->len);
return 0xcafe;
}
*challenge = NULL;
a = (struct ieee80211_authentication*) skb->data;
if(skb->len > (sizeof(struct ieee80211_authentication) +3)){
t = skb->data + sizeof(struct ieee80211_authentication);
if(*(t++) == MFIE_TYPE_CHALLENGE){
*chlen = *(t++);
*challenge = kmemdup(t, *chlen, GFP_ATOMIC);
if (!*challenge)
return -ENOMEM;
}
}
return cpu_to_le16(a->status);
}
int auth_rq_parse(struct sk_buff *skb,u8* dest)
{
struct ieee80211_authentication *a;
if (skb->len < (sizeof(struct ieee80211_authentication)-sizeof(struct ieee80211_info_element))){
IEEE80211_DEBUG_MGMT("invalid len in auth request: %d\n",skb->len);
return -1;
}
a = (struct ieee80211_authentication*) skb->data;
memcpy(dest,a->header.addr2, ETH_ALEN);
if (le16_to_cpu(a->algorithm) != WLAN_AUTH_OPEN)
return WLAN_STATUS_NOT_SUPPORTED_AUTH_ALG;
return WLAN_STATUS_SUCCESS;
}
static short probe_rq_parse(struct ieee80211_device *ieee, struct sk_buff *skb, u8 *src)
{
u8 *tag;
u8 *skbend;
u8 *ssid=NULL;
u8 ssidlen = 0;
struct ieee80211_hdr_3addr *header =
(struct ieee80211_hdr_3addr *) skb->data;
if (skb->len < sizeof (struct ieee80211_hdr_3addr ))
return -1; /* corrupted */
memcpy(src,header->addr2, ETH_ALEN);
skbend = (u8*)skb->data + skb->len;
tag = skb->data + sizeof (struct ieee80211_hdr_3addr );
while (tag+1 < skbend){
if (*tag == 0){
ssid = tag+2;
ssidlen = *(tag+1);
break;
}
tag++; /* point to the len field */
tag = tag + *(tag); /* point to the last data byte of the tag */
tag++; /* point to the next tag */
}
//IEEE80211DMESG("Card MAC address is "MACSTR, MAC2STR(src));
if (ssidlen == 0) return 1;
if (!ssid) return 1; /* ssid not found in tagged param */
return (!strncmp(ssid, ieee->current_network.ssid, ssidlen));
}
int assoc_rq_parse(struct sk_buff *skb,u8* dest)
{
struct ieee80211_assoc_request_frame *a;
if (skb->len < (sizeof(struct ieee80211_assoc_request_frame) -
sizeof(struct ieee80211_info_element))) {
IEEE80211_DEBUG_MGMT("invalid len in auth request:%d \n", skb->len);
return -1;
}
a = (struct ieee80211_assoc_request_frame*) skb->data;
memcpy(dest,a->header.addr2,ETH_ALEN);
return 0;
}
static inline u16 assoc_parse(struct ieee80211_device *ieee, struct sk_buff *skb, int *aid)
{
struct ieee80211_assoc_response_frame *response_head;
u16 status_code;
if (skb->len < sizeof(struct ieee80211_assoc_response_frame)){
IEEE80211_DEBUG_MGMT("invalid len in auth resp: %d\n", skb->len);
return 0xcafe;
}
response_head = (struct ieee80211_assoc_response_frame*) skb->data;
*aid = le16_to_cpu(response_head->aid) & 0x3fff;
status_code = le16_to_cpu(response_head->status);
if((status_code==WLAN_STATUS_ASSOC_DENIED_RATES || \
status_code==WLAN_STATUS_CAPS_UNSUPPORTED)&&
((ieee->mode == IEEE_G) &&
(ieee->current_network.mode == IEEE_N_24G) &&
(ieee->AsocRetryCount++ < (RT_ASOC_RETRY_LIMIT-1)))) {
ieee->pHTInfo->IOTAction |= HT_IOT_ACT_PURE_N_MODE;
}else {
ieee->AsocRetryCount = 0;
}
return le16_to_cpu(response_head->status);
}
static inline void
ieee80211_rx_probe_rq(struct ieee80211_device *ieee, struct sk_buff *skb)
{
u8 dest[ETH_ALEN];
//IEEE80211DMESG("Rx probe");
ieee->softmac_stats.rx_probe_rq++;
//DMESG("Dest is "MACSTR, MAC2STR(dest));
if (probe_rq_parse(ieee, skb, dest)){
//IEEE80211DMESG("Was for me!");
ieee->softmac_stats.tx_probe_rs++;
ieee80211_resp_to_probe(ieee, dest);
}
}
static inline void
ieee80211_rx_auth_rq(struct ieee80211_device *ieee, struct sk_buff *skb)
{
u8 dest[ETH_ALEN];
int status;
//IEEE80211DMESG("Rx probe");
ieee->softmac_stats.rx_auth_rq++;
status = auth_rq_parse(skb, dest);
if (status != -1) {
ieee80211_resp_to_auth(ieee, status, dest);
}
//DMESG("Dest is "MACSTR, MAC2STR(dest));
}
static inline void
ieee80211_rx_assoc_rq(struct ieee80211_device *ieee, struct sk_buff *skb)
{
u8 dest[ETH_ALEN];
//unsigned long flags;
ieee->softmac_stats.rx_ass_rq++;
if (assoc_rq_parse(skb,dest) != -1){
ieee80211_resp_to_assoc_rq(ieee, dest);
}
printk(KERN_INFO"New client associated: %pM\n", dest);
//FIXME
}
void ieee80211_sta_ps_send_null_frame(struct ieee80211_device *ieee, short pwr)
{
struct sk_buff *buf = ieee80211_null_func(ieee, pwr);
if (buf)
softmac_ps_mgmt_xmit(buf, ieee);
}
short ieee80211_sta_ps_sleep(struct ieee80211_device *ieee, u32 *time_h, u32 *time_l)
{
int timeout = ieee->ps_timeout;
u8 dtim;
/*if(ieee->ps == IEEE80211_PS_DISABLED ||
ieee->iw_mode != IW_MODE_INFRA ||
ieee->state != IEEE80211_LINKED)
return 0;
*/
dtim = ieee->current_network.dtim_data;
//printk("DTIM\n");
if(!(dtim & IEEE80211_DTIM_VALID))
return 0;
timeout = ieee->current_network.beacon_interval; //should we use ps_timeout value or beacon_interval
//printk("VALID\n");
ieee->current_network.dtim_data = IEEE80211_DTIM_INVALID;
if(dtim & ((IEEE80211_DTIM_UCAST | IEEE80211_DTIM_MBCAST)& ieee->ps))
return 2;
if(!time_after(jiffies, ieee->dev->trans_start + MSECS(timeout)))
return 0;
if(!time_after(jiffies, ieee->last_rx_ps_time + MSECS(timeout)))
return 0;
if((ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE ) &&
(ieee->mgmt_queue_tail != ieee->mgmt_queue_head))
return 0;
if(time_l){
*time_l = ieee->current_network.last_dtim_sta_time[0]
+ (ieee->current_network.beacon_interval
* ieee->current_network.dtim_period) * 1000;
}
if(time_h){
*time_h = ieee->current_network.last_dtim_sta_time[1];
if(time_l && *time_l < ieee->current_network.last_dtim_sta_time[0])
*time_h += 1;
}
return 1;
}
inline void ieee80211_sta_ps(struct ieee80211_device *ieee)
{
u32 th,tl;
short sleep;
unsigned long flags,flags2;
spin_lock_irqsave(&ieee->lock, flags);
if((ieee->ps == IEEE80211_PS_DISABLED ||
ieee->iw_mode != IW_MODE_INFRA ||
ieee->state != IEEE80211_LINKED)){
// #warning CHECK_LOCK_HERE
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
ieee80211_sta_wakeup(ieee, 1);
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
}
sleep = ieee80211_sta_ps_sleep(ieee,&th, &tl);
/* 2 wake, 1 sleep, 0 do nothing */
if(sleep == 0)
goto out;
if(sleep == 1){
if(ieee->sta_sleep == 1)
ieee->enter_sleep_state(ieee->dev,th,tl);
else if(ieee->sta_sleep == 0){
// printk("send null 1\n");
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
if(ieee->ps_is_queue_empty(ieee->dev)){
ieee->sta_sleep = 2;
ieee->ps_request_tx_ack(ieee->dev);
ieee80211_sta_ps_send_null_frame(ieee,1);
ieee->ps_th = th;
ieee->ps_tl = tl;
}
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
}
}else if(sleep == 2){
//#warning CHECK_LOCK_HERE
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
ieee80211_sta_wakeup(ieee,1);
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
}
out:
spin_unlock_irqrestore(&ieee->lock, flags);
}
void ieee80211_sta_wakeup(struct ieee80211_device *ieee, short nl)
{
if(ieee->sta_sleep == 0){
if(nl){
printk("Warning: driver is probably failing to report TX ps error\n");
ieee->ps_request_tx_ack(ieee->dev);
ieee80211_sta_ps_send_null_frame(ieee, 0);
}
return;
}
if(ieee->sta_sleep == 1)
ieee->sta_wake_up(ieee->dev);
ieee->sta_sleep = 0;
if(nl){
ieee->ps_request_tx_ack(ieee->dev);
ieee80211_sta_ps_send_null_frame(ieee, 0);
}
}
void ieee80211_ps_tx_ack(struct ieee80211_device *ieee, short success)
{
unsigned long flags,flags2;
spin_lock_irqsave(&ieee->lock, flags);
if(ieee->sta_sleep == 2){
/* Null frame with PS bit set */
if(success){
ieee->sta_sleep = 1;
ieee->enter_sleep_state(ieee->dev,ieee->ps_th,ieee->ps_tl);
}
/* if the card report not success we can't be sure the AP
* has not RXed so we can't assume the AP believe us awake
*/
}
/* 21112005 - tx again null without PS bit if lost */
else {
if((ieee->sta_sleep == 0) && !success){
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
ieee80211_sta_ps_send_null_frame(ieee, 0);
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
}
}
spin_unlock_irqrestore(&ieee->lock, flags);
}
void ieee80211_process_action(struct ieee80211_device* ieee, struct sk_buff* skb)
{
struct ieee80211_hdr* header = (struct ieee80211_hdr*)skb->data;
u8* act = ieee80211_get_payload(header);
u8 tmp = 0;
// IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA|IEEE80211_DL_BA, skb->data, skb->len);
if (act == NULL)
{
IEEE80211_DEBUG(IEEE80211_DL_ERR, "error to get payload of action frame\n");
return;
}
tmp = *act;
act ++;
switch (tmp)
{
case ACT_CAT_BA:
if (*act == ACT_ADDBAREQ)
ieee80211_rx_ADDBAReq(ieee, skb);
else if (*act == ACT_ADDBARSP)
ieee80211_rx_ADDBARsp(ieee, skb);
else if (*act == ACT_DELBA)
ieee80211_rx_DELBA(ieee, skb);
break;
default:
// if (net_ratelimit())
// IEEE80211_DEBUG(IEEE80211_DL_BA, "unknown action frame(%d)\n", tmp);
break;
}
return;
}
inline int
ieee80211_rx_frame_softmac(struct ieee80211_device *ieee, struct sk_buff *skb,
struct ieee80211_rx_stats *rx_stats, u16 type,
u16 stype)
{
struct ieee80211_hdr_3addr *header = (struct ieee80211_hdr_3addr *) skb->data;
u16 errcode;
u8* challenge;
int chlen=0;
int aid;
struct ieee80211_assoc_response_frame *assoc_resp;
// struct ieee80211_info_element *info_element;
bool bSupportNmode = true, bHalfSupportNmode = false; //default support N mode, disable halfNmode
if(!ieee->proto_started)
return 0;
if(ieee->sta_sleep || (ieee->ps != IEEE80211_PS_DISABLED &&
ieee->iw_mode == IW_MODE_INFRA &&
ieee->state == IEEE80211_LINKED))
tasklet_schedule(&ieee->ps_task);
if(WLAN_FC_GET_STYPE(header->frame_ctl) != IEEE80211_STYPE_PROBE_RESP &&
WLAN_FC_GET_STYPE(header->frame_ctl) != IEEE80211_STYPE_BEACON)
ieee->last_rx_ps_time = jiffies;
switch (WLAN_FC_GET_STYPE(header->frame_ctl)) {
case IEEE80211_STYPE_ASSOC_RESP:
case IEEE80211_STYPE_REASSOC_RESP:
IEEE80211_DEBUG_MGMT("received [RE]ASSOCIATION RESPONSE (%d)\n",
WLAN_FC_GET_STYPE(header->frame_ctl));
if ((ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE) &&
ieee->state == IEEE80211_ASSOCIATING_AUTHENTICATED &&
ieee->iw_mode == IW_MODE_INFRA){
struct ieee80211_network network_resp;
struct ieee80211_network *network = &network_resp;
if (0 == (errcode=assoc_parse(ieee,skb, &aid))){
ieee->state=IEEE80211_LINKED;
ieee->assoc_id = aid;
ieee->softmac_stats.rx_ass_ok++;
/* station support qos */
/* Let the register setting defaultly with Legacy station */
if(ieee->qos_support) {
assoc_resp = (struct ieee80211_assoc_response_frame*)skb->data;
memset(network, 0, sizeof(*network));
if (ieee80211_parse_info_param(ieee,assoc_resp->info_element,\
rx_stats->len - sizeof(*assoc_resp),\
network,rx_stats)){
return 1;
}
else
{ //filling the PeerHTCap. //maybe not necessary as we can get its info from current_network.
memcpy(ieee->pHTInfo->PeerHTCapBuf, network->bssht.bdHTCapBuf, network->bssht.bdHTCapLen);
memcpy(ieee->pHTInfo->PeerHTInfoBuf, network->bssht.bdHTInfoBuf, network->bssht.bdHTInfoLen);
}
if (ieee->handle_assoc_response != NULL)
ieee->handle_assoc_response(ieee->dev, (struct ieee80211_assoc_response_frame*)header, network);
}
ieee80211_associate_complete(ieee);
} else {
/* aid could not been allocated */
ieee->softmac_stats.rx_ass_err++;
printk(
"Association response status code 0x%x\n",
errcode);
IEEE80211_DEBUG_MGMT(
"Association response status code 0x%x\n",
errcode);
if(ieee->AsocRetryCount < RT_ASOC_RETRY_LIMIT) {
queue_work(ieee->wq, &ieee->associate_procedure_wq);
} else {
ieee80211_associate_abort(ieee);
}
}
}
break;
case IEEE80211_STYPE_ASSOC_REQ:
case IEEE80211_STYPE_REASSOC_REQ:
if ((ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE) &&
ieee->iw_mode == IW_MODE_MASTER)
ieee80211_rx_assoc_rq(ieee, skb);
break;
case IEEE80211_STYPE_AUTH:
if (ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE){
if (ieee->state == IEEE80211_ASSOCIATING_AUTHENTICATING &&
ieee->iw_mode == IW_MODE_INFRA){
IEEE80211_DEBUG_MGMT("Received authentication response");
if (0 == (errcode=auth_parse(skb, &challenge, &chlen))){
if(ieee->open_wep || !challenge){
ieee->state = IEEE80211_ASSOCIATING_AUTHENTICATED;
ieee->softmac_stats.rx_auth_rs_ok++;
if(!(ieee->pHTInfo->IOTAction&HT_IOT_ACT_PURE_N_MODE))
{
if (!ieee->GetNmodeSupportBySecCfg(ieee->dev))
{
// WEP or TKIP encryption
if(IsHTHalfNmodeAPs(ieee))
{
bSupportNmode = true;
bHalfSupportNmode = true;
}
else
{
bSupportNmode = false;
bHalfSupportNmode = false;
}
printk("==========>to link with AP using SEC(%d, %d)", bSupportNmode, bHalfSupportNmode);
}
}
/* Dummy wirless mode setting to avoid encryption issue */
if(bSupportNmode) {
//N mode setting
ieee->SetWirelessMode(ieee->dev, \
ieee->current_network.mode);
}else{
//b/g mode setting
/*TODO*/
ieee->SetWirelessMode(ieee->dev, IEEE_G);
}
if (ieee->current_network.mode == IEEE_N_24G && bHalfSupportNmode == true)
{
printk("===============>entern half N mode\n");
ieee->bHalfWirelessN24GMode = true;
}
else
ieee->bHalfWirelessN24GMode = false;
ieee80211_associate_step2(ieee);
}else{
ieee80211_auth_challenge(ieee, challenge, chlen);
}
}else{
ieee->softmac_stats.rx_auth_rs_err++;
IEEE80211_DEBUG_MGMT("Authentication respose status code 0x%x",errcode);
ieee80211_associate_abort(ieee);
}
}else if (ieee->iw_mode == IW_MODE_MASTER){
ieee80211_rx_auth_rq(ieee, skb);
}
}
break;
case IEEE80211_STYPE_PROBE_REQ:
if ((ieee->softmac_features & IEEE_SOFTMAC_PROBERS) &&
((ieee->iw_mode == IW_MODE_ADHOC ||
ieee->iw_mode == IW_MODE_MASTER) &&
ieee->state == IEEE80211_LINKED)){
ieee80211_rx_probe_rq(ieee, skb);
}
break;
case IEEE80211_STYPE_DISASSOC:
case IEEE80211_STYPE_DEAUTH:
/* FIXME for now repeat all the association procedure
* both for disassociation and deauthentication
*/
if ((ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE) &&
ieee->state == IEEE80211_LINKED &&
ieee->iw_mode == IW_MODE_INFRA){
ieee->state = IEEE80211_ASSOCIATING;
ieee->softmac_stats.reassoc++;
notify_wx_assoc_event(ieee);
//HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
RemovePeerTS(ieee, header->addr2);
queue_work(ieee->wq, &ieee->associate_procedure_wq);
}
break;
case IEEE80211_STYPE_MANAGE_ACT:
ieee80211_process_action(ieee,skb);
break;
default:
return -1;
break;
}
//dev_kfree_skb_any(skb);
return 0;
}
/* following are for a simpler TX queue management.
* Instead of using netif_[stop/wake]_queue the driver
* will uses these two function (plus a reset one), that
* will internally uses the kernel netif_* and takes
* care of the ieee802.11 fragmentation.
* So the driver receives a fragment per time and might
* call the stop function when it want without take care
* to have enought room to TX an entire packet.
* This might be useful if each fragment need it's own
* descriptor, thus just keep a total free memory > than
* the max fragmentation treshold is not enought.. If the
* ieee802.11 stack passed a TXB struct then you needed
* to keep N free descriptors where
* N = MAX_PACKET_SIZE / MIN_FRAG_TRESHOLD
* In this way you need just one and the 802.11 stack
* will take care of buffering fragments and pass them to
* to the driver later, when it wakes the queue.
*/
void ieee80211_softmac_xmit(struct ieee80211_txb *txb, struct ieee80211_device *ieee)
{
unsigned int queue_index = txb->queue_index;
unsigned long flags;
int i;
cb_desc *tcb_desc = NULL;
spin_lock_irqsave(&ieee->lock,flags);
/* called with 2nd parm 0, no tx mgmt lock required */
ieee80211_sta_wakeup(ieee,0);
/* update the tx status */
ieee->stats.tx_bytes += txb->payload_size;
ieee->stats.tx_packets++;
tcb_desc = (cb_desc *)(txb->fragments[0]->cb + MAX_DEV_ADDR_SIZE);
if(tcb_desc->bMulticast) {
ieee->stats.multicast++;
}
/* if xmit available, just xmit it immediately, else just insert it to the wait queue */
for(i = 0; i < txb->nr_frags; i++) {
#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
if ((skb_queue_len(&ieee->skb_drv_aggQ[queue_index]) != 0) ||
#else
if ((skb_queue_len(&ieee->skb_waitQ[queue_index]) != 0) ||
#endif
(!ieee->check_nic_enough_desc(ieee->dev,queue_index))||\
(ieee->queue_stop)) {
/* insert the skb packet to the wait queue */
/* as for the completion function, it does not need
* to check it any more.
* */
//printk("error:no descriptor left@queue_index %d\n", queue_index);
//ieee80211_stop_queue(ieee);
#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
skb_queue_tail(&ieee->skb_drv_aggQ[queue_index], txb->fragments[i]);
#else
skb_queue_tail(&ieee->skb_waitQ[queue_index], txb->fragments[i]);
#endif
}else{
ieee->softmac_data_hard_start_xmit(
txb->fragments[i],
ieee->dev,ieee->rate);
//ieee->stats.tx_packets++;
//ieee->stats.tx_bytes += txb->fragments[i]->len;
//ieee->dev->trans_start = jiffies;
}
}
ieee80211_txb_free(txb);
//exit:
spin_unlock_irqrestore(&ieee->lock,flags);
}
/* called with ieee->lock acquired */
void ieee80211_resume_tx(struct ieee80211_device *ieee)
{
int i;
for(i = ieee->tx_pending.frag; i < ieee->tx_pending.txb->nr_frags; i++) {
if (ieee->queue_stop){
ieee->tx_pending.frag = i;
return;
}else{
ieee->softmac_data_hard_start_xmit(
ieee->tx_pending.txb->fragments[i],
ieee->dev,ieee->rate);
//(i+1)<ieee->tx_pending.txb->nr_frags);
ieee->stats.tx_packets++;
ieee->dev->trans_start = jiffies;
}
}
ieee80211_txb_free(ieee->tx_pending.txb);
ieee->tx_pending.txb = NULL;
}
void ieee80211_reset_queue(struct ieee80211_device *ieee)
{
unsigned long flags;
spin_lock_irqsave(&ieee->lock,flags);
init_mgmt_queue(ieee);
if (ieee->tx_pending.txb){
ieee80211_txb_free(ieee->tx_pending.txb);
ieee->tx_pending.txb = NULL;
}
ieee->queue_stop = 0;
spin_unlock_irqrestore(&ieee->lock,flags);
}
void ieee80211_wake_queue(struct ieee80211_device *ieee)
{
unsigned long flags;
struct sk_buff *skb;
struct ieee80211_hdr_3addr *header;
spin_lock_irqsave(&ieee->lock,flags);
if (! ieee->queue_stop) goto exit;
ieee->queue_stop = 0;
if(ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE){
while (!ieee->queue_stop && (skb = dequeue_mgmt(ieee))){
header = (struct ieee80211_hdr_3addr *) skb->data;
header->seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
ieee->softmac_data_hard_start_xmit(skb,ieee->dev,ieee->basic_rate);
//dev_kfree_skb_any(skb);//edit by thomas
}
}
if (!ieee->queue_stop && ieee->tx_pending.txb)
ieee80211_resume_tx(ieee);
if (!ieee->queue_stop && netif_queue_stopped(ieee->dev)){
ieee->softmac_stats.swtxawake++;
netif_wake_queue(ieee->dev);
}
exit :
spin_unlock_irqrestore(&ieee->lock,flags);
}
void ieee80211_stop_queue(struct ieee80211_device *ieee)
{
//unsigned long flags;
//spin_lock_irqsave(&ieee->lock,flags);
if (! netif_queue_stopped(ieee->dev)){
netif_stop_queue(ieee->dev);
ieee->softmac_stats.swtxstop++;
}
ieee->queue_stop = 1;
//spin_unlock_irqrestore(&ieee->lock,flags);
}
inline void ieee80211_randomize_cell(struct ieee80211_device *ieee)
{
get_random_bytes(ieee->current_network.bssid, ETH_ALEN);
/* an IBSS cell address must have the two less significant
* bits of the first byte = 2
*/
ieee->current_network.bssid[0] &= ~0x01;
ieee->current_network.bssid[0] |= 0x02;
}
/* called in user context only */
void ieee80211_start_master_bss(struct ieee80211_device *ieee)
{
ieee->assoc_id = 1;
if (ieee->current_network.ssid_len == 0){
strncpy(ieee->current_network.ssid,
IEEE80211_DEFAULT_TX_ESSID,
IW_ESSID_MAX_SIZE);
ieee->current_network.ssid_len = strlen(IEEE80211_DEFAULT_TX_ESSID);
ieee->ssid_set = 1;
}
memcpy(ieee->current_network.bssid, ieee->dev->dev_addr, ETH_ALEN);
ieee->set_chan(ieee->dev, ieee->current_network.channel);
ieee->state = IEEE80211_LINKED;
ieee->link_change(ieee->dev);
notify_wx_assoc_event(ieee);
if (ieee->data_hard_resume)
ieee->data_hard_resume(ieee->dev);
netif_carrier_on(ieee->dev);
}
void ieee80211_start_monitor_mode(struct ieee80211_device *ieee)
{
if(ieee->raw_tx){
if (ieee->data_hard_resume)
ieee->data_hard_resume(ieee->dev);
netif_carrier_on(ieee->dev);
}
}
void ieee80211_start_ibss_wq(struct work_struct *work)
{
struct delayed_work *dwork = container_of(work, struct delayed_work, work);
struct ieee80211_device *ieee = container_of(dwork, struct ieee80211_device, start_ibss_wq);
/* iwconfig mode ad-hoc will schedule this and return
* on the other hand this will block further iwconfig SET
* operations because of the wx_sem hold.
* Anyway some most set operations set a flag to speed-up
* (abort) this wq (when syncro scanning) before sleeping
* on the semaphore
*/
if(!ieee->proto_started){
printk("==========oh driver down return\n");
return;
}
down(&ieee->wx_sem);
if (ieee->current_network.ssid_len == 0){
strcpy(ieee->current_network.ssid,IEEE80211_DEFAULT_TX_ESSID);
ieee->current_network.ssid_len = strlen(IEEE80211_DEFAULT_TX_ESSID);
ieee->ssid_set = 1;
}
/* check if we have this cell in our network list */
ieee80211_softmac_check_all_nets(ieee);
// if((IS_DOT11D_ENABLE(ieee)) && (ieee->state == IEEE80211_NOLINK))
if (ieee->state == IEEE80211_NOLINK)
ieee->current_network.channel = 6;
/* if not then the state is not linked. Maybe the user swithced to
* ad-hoc mode just after being in monitor mode, or just after
* being very few time in managed mode (so the card have had no
* time to scan all the chans..) or we have just run up the iface
* after setting ad-hoc mode. So we have to give another try..
* Here, in ibss mode, should be safe to do this without extra care
* (in bss mode we had to make sure no-one tryed to associate when
* we had just checked the ieee->state and we was going to start the
* scan) beacause in ibss mode the ieee80211_new_net function, when
* finds a good net, just set the ieee->state to IEEE80211_LINKED,
* so, at worst, we waste a bit of time to initiate an unneeded syncro
* scan, that will stop at the first round because it sees the state
* associated.
*/
if (ieee->state == IEEE80211_NOLINK)
ieee80211_start_scan_syncro(ieee);
/* the network definitively is not here.. create a new cell */
if (ieee->state == IEEE80211_NOLINK){
printk("creating new IBSS cell\n");
if(!ieee->wap_set)
ieee80211_randomize_cell(ieee);
if(ieee->modulation & IEEE80211_CCK_MODULATION){
ieee->current_network.rates_len = 4;
ieee->current_network.rates[0] = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_1MB;
ieee->current_network.rates[1] = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_2MB;
ieee->current_network.rates[2] = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_5MB;
ieee->current_network.rates[3] = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_11MB;
}else
ieee->current_network.rates_len = 0;
if(ieee->modulation & IEEE80211_OFDM_MODULATION){
ieee->current_network.rates_ex_len = 8;
ieee->current_network.rates_ex[0] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_6MB;
ieee->current_network.rates_ex[1] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_9MB;
ieee->current_network.rates_ex[2] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_12MB;
ieee->current_network.rates_ex[3] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_18MB;
ieee->current_network.rates_ex[4] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_24MB;
ieee->current_network.rates_ex[5] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_36MB;
ieee->current_network.rates_ex[6] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_48MB;
ieee->current_network.rates_ex[7] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_54MB;
ieee->rate = 108;
}else{
ieee->current_network.rates_ex_len = 0;
ieee->rate = 22;
}
// By default, WMM function will be disabled in IBSS mode
ieee->current_network.QoS_Enable = 0;
ieee->SetWirelessMode(ieee->dev, IEEE_G);
ieee->current_network.atim_window = 0;
ieee->current_network.capability = WLAN_CAPABILITY_IBSS;
if(ieee->short_slot)
ieee->current_network.capability |= WLAN_CAPABILITY_SHORT_SLOT;
}
ieee->state = IEEE80211_LINKED;
ieee->set_chan(ieee->dev, ieee->current_network.channel);
ieee->link_change(ieee->dev);
notify_wx_assoc_event(ieee);
ieee80211_start_send_beacons(ieee);
if (ieee->data_hard_resume)
ieee->data_hard_resume(ieee->dev);
netif_carrier_on(ieee->dev);
up(&ieee->wx_sem);
}
inline void ieee80211_start_ibss(struct ieee80211_device *ieee)
{
queue_delayed_work(ieee->wq, &ieee->start_ibss_wq, 150);
}
/* this is called only in user context, with wx_sem held */
void ieee80211_start_bss(struct ieee80211_device *ieee)
{
unsigned long flags;
//
// Ref: 802.11d 11.1.3.3
// STA shall not start a BSS unless properly formed Beacon frame including a Country IE.
//
if(IS_DOT11D_ENABLE(ieee) && !IS_COUNTRY_IE_VALID(ieee))
{
if(! ieee->bGlobalDomain)
{
return;
}
}
/* check if we have already found the net we
* are interested in (if any).
* if not (we are disassociated and we are not
* in associating / authenticating phase) start the background scanning.
*/
ieee80211_softmac_check_all_nets(ieee);
/* ensure no-one start an associating process (thus setting
* the ieee->state to ieee80211_ASSOCIATING) while we
* have just cheked it and we are going to enable scan.
* The ieee80211_new_net function is always called with
* lock held (from both ieee80211_softmac_check_all_nets and
* the rx path), so we cannot be in the middle of such function
*/
spin_lock_irqsave(&ieee->lock, flags);
if (ieee->state == IEEE80211_NOLINK){
ieee->actscanning = true;
ieee80211_start_scan(ieee);
}
spin_unlock_irqrestore(&ieee->lock, flags);
}
/* called only in userspace context */
void ieee80211_disassociate(struct ieee80211_device *ieee)
{
netif_carrier_off(ieee->dev);
if (ieee->softmac_features & IEEE_SOFTMAC_TX_QUEUE)
ieee80211_reset_queue(ieee);
if (ieee->data_hard_stop)
ieee->data_hard_stop(ieee->dev);
if(IS_DOT11D_ENABLE(ieee))
Dot11d_Reset(ieee);
ieee->state = IEEE80211_NOLINK;
ieee->is_set_key = false;
ieee->link_change(ieee->dev);
//HTSetConnectBwMode(ieee, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
notify_wx_assoc_event(ieee);
}
void ieee80211_associate_retry_wq(struct work_struct *work)
{
struct delayed_work *dwork = container_of(work, struct delayed_work, work);
struct ieee80211_device *ieee = container_of(dwork, struct ieee80211_device, associate_retry_wq);
unsigned long flags;
down(&ieee->wx_sem);
if(!ieee->proto_started)
goto exit;
if(ieee->state != IEEE80211_ASSOCIATING_RETRY)
goto exit;
/* until we do not set the state to IEEE80211_NOLINK
* there are no possibility to have someone else trying
* to start an association procdure (we get here with
* ieee->state = IEEE80211_ASSOCIATING).
* When we set the state to IEEE80211_NOLINK it is possible
* that the RX path run an attempt to associate, but
* both ieee80211_softmac_check_all_nets and the
* RX path works with ieee->lock held so there are no
* problems. If we are still disassociated then start a scan.
* the lock here is necessary to ensure no one try to start
* an association procedure when we have just checked the
* state and we are going to start the scan.
*/
ieee->state = IEEE80211_NOLINK;
ieee80211_softmac_check_all_nets(ieee);
spin_lock_irqsave(&ieee->lock, flags);
if(ieee->state == IEEE80211_NOLINK)
ieee80211_start_scan(ieee);
spin_unlock_irqrestore(&ieee->lock, flags);
exit:
up(&ieee->wx_sem);
}
struct sk_buff *ieee80211_get_beacon_(struct ieee80211_device *ieee)
{
u8 broadcast_addr[] = {0xff,0xff,0xff,0xff,0xff,0xff};
struct sk_buff *skb;
struct ieee80211_probe_response *b;
skb = ieee80211_probe_resp(ieee, broadcast_addr);
if (!skb)
return NULL;
b = (struct ieee80211_probe_response *) skb->data;
b->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_BEACON);
return skb;
}
struct sk_buff *ieee80211_get_beacon(struct ieee80211_device *ieee)
{
struct sk_buff *skb;
struct ieee80211_probe_response *b;
skb = ieee80211_get_beacon_(ieee);
if(!skb)
return NULL;
b = (struct ieee80211_probe_response *) skb->data;
b->header.seq_ctl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
return skb;
}
void ieee80211_softmac_stop_protocol(struct ieee80211_device *ieee)
{
ieee->sync_scan_hurryup = 1;
down(&ieee->wx_sem);
ieee80211_stop_protocol(ieee);
up(&ieee->wx_sem);
}
void ieee80211_stop_protocol(struct ieee80211_device *ieee)
{
if (!ieee->proto_started)
return;
ieee->proto_started = 0;
ieee80211_stop_send_beacons(ieee);
del_timer_sync(&ieee->associate_timer);
cancel_delayed_work(&ieee->associate_retry_wq);
cancel_delayed_work(&ieee->start_ibss_wq);
ieee80211_stop_scan(ieee);
ieee80211_disassociate(ieee);
RemoveAllTS(ieee); //added as we disconnect from the previous BSS, Remove all TS
}
void ieee80211_softmac_start_protocol(struct ieee80211_device *ieee)
{
ieee->sync_scan_hurryup = 0;
down(&ieee->wx_sem);
ieee80211_start_protocol(ieee);
up(&ieee->wx_sem);
}
void ieee80211_start_protocol(struct ieee80211_device *ieee)
{
short ch = 0;
int i = 0;
if (ieee->proto_started)
return;
ieee->proto_started = 1;
if (ieee->current_network.channel == 0){
do{
ch++;
if (ch > MAX_CHANNEL_NUMBER)
return; /* no channel found */
}while(!GET_DOT11D_INFO(ieee)->channel_map[ch]);
ieee->current_network.channel = ch;
}
if (ieee->current_network.beacon_interval == 0)
ieee->current_network.beacon_interval = 100;
// printk("===>%s(), chan:%d\n", __FUNCTION__, ieee->current_network.channel);
// ieee->set_chan(ieee->dev,ieee->current_network.channel);
for(i = 0; i < 17; i++) {
ieee->last_rxseq_num[i] = -1;
ieee->last_rxfrag_num[i] = -1;
ieee->last_packet_time[i] = 0;
}
ieee->init_wmmparam_flag = 0;//reinitialize AC_xx_PARAM registers.
/* if the user set the MAC of the ad-hoc cell and then
* switch to managed mode, shall we make sure that association
* attempts does not fail just because the user provide the essid
* and the nic is still checking for the AP MAC ??
*/
if (ieee->iw_mode == IW_MODE_INFRA)
ieee80211_start_bss(ieee);
else if (ieee->iw_mode == IW_MODE_ADHOC)
ieee80211_start_ibss(ieee);
else if (ieee->iw_mode == IW_MODE_MASTER)
ieee80211_start_master_bss(ieee);
else if(ieee->iw_mode == IW_MODE_MONITOR)
ieee80211_start_monitor_mode(ieee);
}
#define DRV_NAME "Ieee80211"
void ieee80211_softmac_init(struct ieee80211_device *ieee)
{
int i;
memset(&ieee->current_network, 0, sizeof(struct ieee80211_network));
ieee->state = IEEE80211_NOLINK;
ieee->sync_scan_hurryup = 0;
for(i = 0; i < 5; i++) {
ieee->seq_ctrl[i] = 0;
}
ieee->pDot11dInfo = kzalloc(sizeof(RT_DOT11D_INFO), GFP_ATOMIC);
if (!ieee->pDot11dInfo)
IEEE80211_DEBUG(IEEE80211_DL_ERR, "can't alloc memory for DOT11D\n");
//added for AP roaming
ieee->LinkDetectInfo.SlotNum = 2;
ieee->LinkDetectInfo.NumRecvBcnInPeriod=0;
ieee->LinkDetectInfo.NumRecvDataInPeriod=0;
ieee->assoc_id = 0;
ieee->queue_stop = 0;
ieee->scanning = 0;
ieee->softmac_features = 0; //so IEEE2100-like driver are happy
ieee->wap_set = 0;
ieee->ssid_set = 0;
ieee->proto_started = 0;
ieee->basic_rate = IEEE80211_DEFAULT_BASIC_RATE;
ieee->rate = 22;
ieee->ps = IEEE80211_PS_DISABLED;
ieee->sta_sleep = 0;
ieee->Regdot11HTOperationalRateSet[0]= 0xff;//support MCS 0~7
ieee->Regdot11HTOperationalRateSet[1]= 0xff;//support MCS 8~15
ieee->Regdot11HTOperationalRateSet[4]= 0x01;
//added by amy
ieee->actscanning = false;
ieee->beinretry = false;
ieee->is_set_key = false;
init_mgmt_queue(ieee);
ieee->sta_edca_param[0] = 0x0000A403;
ieee->sta_edca_param[1] = 0x0000A427;
ieee->sta_edca_param[2] = 0x005E4342;
ieee->sta_edca_param[3] = 0x002F3262;
ieee->aggregation = true;
ieee->enable_rx_imm_BA = 1;
ieee->tx_pending.txb = NULL;
init_timer(&ieee->associate_timer);
ieee->associate_timer.data = (unsigned long)ieee;
ieee->associate_timer.function = ieee80211_associate_abort_cb;
init_timer(&ieee->beacon_timer);
ieee->beacon_timer.data = (unsigned long) ieee;
ieee->beacon_timer.function = ieee80211_send_beacon_cb;
ieee->wq = create_workqueue(DRV_NAME);
INIT_DELAYED_WORK(&ieee->start_ibss_wq,ieee80211_start_ibss_wq);
INIT_WORK(&ieee->associate_complete_wq, ieee80211_associate_complete_wq);
INIT_WORK(&ieee->associate_procedure_wq, ieee80211_associate_procedure_wq);
INIT_DELAYED_WORK(&ieee->softmac_scan_wq,ieee80211_softmac_scan_wq);
INIT_DELAYED_WORK(&ieee->associate_retry_wq, ieee80211_associate_retry_wq);
INIT_WORK(&ieee->wx_sync_scan_wq,ieee80211_wx_sync_scan_wq);
sema_init(&ieee->wx_sem, 1);
sema_init(&ieee->scan_sem, 1);
spin_lock_init(&ieee->mgmt_tx_lock);
spin_lock_init(&ieee->beacon_lock);
tasklet_init(&ieee->ps_task,
(void(*)(unsigned long)) ieee80211_sta_ps,
(unsigned long)ieee);
}
void ieee80211_softmac_free(struct ieee80211_device *ieee)
{
down(&ieee->wx_sem);
kfree(ieee->pDot11dInfo);
ieee->pDot11dInfo = NULL;
del_timer_sync(&ieee->associate_timer);
cancel_delayed_work(&ieee->associate_retry_wq);
destroy_workqueue(ieee->wq);
up(&ieee->wx_sem);
}
/********************************************************
* Start of WPA code. *
* this is stolen from the ipw2200 driver *
********************************************************/
static int ieee80211_wpa_enable(struct ieee80211_device *ieee, int value)
{
/* This is called when wpa_supplicant loads and closes the driver
* interface. */
printk("%s WPA\n",value ? "enabling" : "disabling");
ieee->wpa_enabled = value;
return 0;
}
void ieee80211_wpa_assoc_frame(struct ieee80211_device *ieee, char *wpa_ie, int wpa_ie_len)
{
/* make sure WPA is enabled */
ieee80211_wpa_enable(ieee, 1);
ieee80211_disassociate(ieee);
}
static int ieee80211_wpa_mlme(struct ieee80211_device *ieee, int command, int reason)
{
int ret = 0;
switch (command) {
case IEEE_MLME_STA_DEAUTH:
// silently ignore
break;
case IEEE_MLME_STA_DISASSOC:
ieee80211_disassociate(ieee);
break;
default:
printk("Unknown MLME request: %d\n", command);
ret = -EOPNOTSUPP;
}
return ret;
}
static int ieee80211_wpa_set_wpa_ie(struct ieee80211_device *ieee,
struct ieee_param *param, int plen)
{
u8 *buf;
if (param->u.wpa_ie.len > MAX_WPA_IE_LEN ||
(param->u.wpa_ie.len && param->u.wpa_ie.data == NULL))
return -EINVAL;
if (param->u.wpa_ie.len) {
buf = kmemdup(param->u.wpa_ie.data, param->u.wpa_ie.len,
GFP_KERNEL);
if (buf == NULL)
return -ENOMEM;
kfree(ieee->wpa_ie);
ieee->wpa_ie = buf;
ieee->wpa_ie_len = param->u.wpa_ie.len;
} else {
kfree(ieee->wpa_ie);
ieee->wpa_ie = NULL;
ieee->wpa_ie_len = 0;
}
ieee80211_wpa_assoc_frame(ieee, ieee->wpa_ie, ieee->wpa_ie_len);
return 0;
}
#define AUTH_ALG_OPEN_SYSTEM 0x1
#define AUTH_ALG_SHARED_KEY 0x2
static int ieee80211_wpa_set_auth_algs(struct ieee80211_device *ieee, int value)
{
struct ieee80211_security sec = {
.flags = SEC_AUTH_MODE,
};
int ret = 0;
if (value & AUTH_ALG_SHARED_KEY) {
sec.auth_mode = WLAN_AUTH_SHARED_KEY;
ieee->open_wep = 0;
ieee->auth_mode = 1;
} else if (value & AUTH_ALG_OPEN_SYSTEM){
sec.auth_mode = WLAN_AUTH_OPEN;
ieee->open_wep = 1;
ieee->auth_mode = 0;
}
else if (value & IW_AUTH_ALG_LEAP){
sec.auth_mode = WLAN_AUTH_LEAP;
ieee->open_wep = 1;
ieee->auth_mode = 2;
}
if (ieee->set_security)
ieee->set_security(ieee->dev, &sec);
//else
// ret = -EOPNOTSUPP;
return ret;
}
static int ieee80211_wpa_set_param(struct ieee80211_device *ieee, u8 name, u32 value)
{
int ret=0;
unsigned long flags;
switch (name) {
case IEEE_PARAM_WPA_ENABLED:
ret = ieee80211_wpa_enable(ieee, value);
break;
case IEEE_PARAM_TKIP_COUNTERMEASURES:
ieee->tkip_countermeasures=value;
break;
case IEEE_PARAM_DROP_UNENCRYPTED: {
/* HACK:
*
* wpa_supplicant calls set_wpa_enabled when the driver
* is loaded and unloaded, regardless of if WPA is being
* used. No other calls are made which can be used to
* determine if encryption will be used or not prior to
* association being expected. If encryption is not being
* used, drop_unencrypted is set to false, else true -- we
* can use this to determine if the CAP_PRIVACY_ON bit should
* be set.
*/
struct ieee80211_security sec = {
.flags = SEC_ENABLED,
.enabled = value,
};
ieee->drop_unencrypted = value;
/* We only change SEC_LEVEL for open mode. Others
* are set by ipw_wpa_set_encryption.
*/
if (!value) {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_0;
}
else {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_1;
}
if (ieee->set_security)
ieee->set_security(ieee->dev, &sec);
break;
}
case IEEE_PARAM_PRIVACY_INVOKED:
ieee->privacy_invoked=value;
break;
case IEEE_PARAM_AUTH_ALGS:
ret = ieee80211_wpa_set_auth_algs(ieee, value);
break;
case IEEE_PARAM_IEEE_802_1X:
ieee->ieee802_1x=value;
break;
case IEEE_PARAM_WPAX_SELECT:
// added for WPA2 mixed mode
spin_lock_irqsave(&ieee->wpax_suitlist_lock,flags);
ieee->wpax_type_set = 1;
ieee->wpax_type_notify = value;
spin_unlock_irqrestore(&ieee->wpax_suitlist_lock,flags);
break;
default:
printk("Unknown WPA param: %d\n",name);
ret = -EOPNOTSUPP;
}
return ret;
}
/* implementation borrowed from hostap driver */
static int ieee80211_wpa_set_encryption(struct ieee80211_device *ieee,
struct ieee_param *param, int param_len)
{
int ret = 0;
struct ieee80211_crypto_ops *ops;
struct ieee80211_crypt_data **crypt;
struct ieee80211_security sec = {
.flags = 0,
};
param->u.crypt.err = 0;
param->u.crypt.alg[IEEE_CRYPT_ALG_NAME_LEN - 1] = '\0';
if (param_len !=
(int) ((char *) param->u.crypt.key - (char *) param) +
param->u.crypt.key_len) {
printk("Len mismatch %d, %d\n", param_len,
param->u.crypt.key_len);
return -EINVAL;
}
if (param->sta_addr[0] == 0xff && param->sta_addr[1] == 0xff &&
param->sta_addr[2] == 0xff && param->sta_addr[3] == 0xff &&
param->sta_addr[4] == 0xff && param->sta_addr[5] == 0xff) {
if (param->u.crypt.idx >= WEP_KEYS)
return -EINVAL;
crypt = &ieee->crypt[param->u.crypt.idx];
} else {
return -EINVAL;
}
if (strcmp(param->u.crypt.alg, "none") == 0) {
if (crypt) {
sec.enabled = 0;
// FIXME FIXME
//sec.encrypt = 0;
sec.level = SEC_LEVEL_0;
sec.flags |= SEC_ENABLED | SEC_LEVEL;
ieee80211_crypt_delayed_deinit(ieee, crypt);
}
goto done;
}
sec.enabled = 1;
// FIXME FIXME
// sec.encrypt = 1;
sec.flags |= SEC_ENABLED;
/* IPW HW cannot build TKIP MIC, host decryption still needed. */
if (!(ieee->host_encrypt || ieee->host_decrypt) &&
strcmp(param->u.crypt.alg, "TKIP"))
goto skip_host_crypt;
ops = ieee80211_get_crypto_ops(param->u.crypt.alg);
if (ops == NULL && strcmp(param->u.crypt.alg, "WEP") == 0) {
request_module("ieee80211_crypt_wep");
ops = ieee80211_get_crypto_ops(param->u.crypt.alg);
//set WEP40 first, it will be modified according to WEP104 or WEP40 at other place
} else if (ops == NULL && strcmp(param->u.crypt.alg, "TKIP") == 0) {
request_module("ieee80211_crypt_tkip");
ops = ieee80211_get_crypto_ops(param->u.crypt.alg);
} else if (ops == NULL && strcmp(param->u.crypt.alg, "CCMP") == 0) {
request_module("ieee80211_crypt_ccmp");
ops = ieee80211_get_crypto_ops(param->u.crypt.alg);
}
if (ops == NULL) {
printk("unknown crypto alg '%s'\n", param->u.crypt.alg);
param->u.crypt.err = IEEE_CRYPT_ERR_UNKNOWN_ALG;
ret = -EINVAL;
goto done;
}
if (*crypt == NULL || (*crypt)->ops != ops) {
struct ieee80211_crypt_data *new_crypt;
ieee80211_crypt_delayed_deinit(ieee, crypt);
new_crypt = kmalloc(sizeof(*new_crypt), GFP_KERNEL);
if (new_crypt == NULL) {
ret = -ENOMEM;
goto done;
}
memset(new_crypt, 0, sizeof(struct ieee80211_crypt_data));
new_crypt->ops = ops;
if (new_crypt->ops && try_module_get(new_crypt->ops->owner))
new_crypt->priv =
new_crypt->ops->init(param->u.crypt.idx);
if (new_crypt->priv == NULL) {
kfree(new_crypt);
param->u.crypt.err = IEEE_CRYPT_ERR_CRYPT_INIT_FAILED;
ret = -EINVAL;
goto done;
}
*crypt = new_crypt;
}
if (param->u.crypt.key_len > 0 && (*crypt)->ops->set_key &&
(*crypt)->ops->set_key(param->u.crypt.key,
param->u.crypt.key_len, param->u.crypt.seq,
(*crypt)->priv) < 0) {
printk("key setting failed\n");
param->u.crypt.err = IEEE_CRYPT_ERR_KEY_SET_FAILED;
ret = -EINVAL;
goto done;
}
skip_host_crypt:
if (param->u.crypt.set_tx) {
ieee->tx_keyidx = param->u.crypt.idx;
sec.active_key = param->u.crypt.idx;
sec.flags |= SEC_ACTIVE_KEY;
} else
sec.flags &= ~SEC_ACTIVE_KEY;
if (param->u.crypt.alg != NULL) {
memcpy(sec.keys[param->u.crypt.idx],
param->u.crypt.key,
param->u.crypt.key_len);
sec.key_sizes[param->u.crypt.idx] = param->u.crypt.key_len;
sec.flags |= (1 << param->u.crypt.idx);
if (strcmp(param->u.crypt.alg, "WEP") == 0) {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_1;
} else if (strcmp(param->u.crypt.alg, "TKIP") == 0) {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_2;
} else if (strcmp(param->u.crypt.alg, "CCMP") == 0) {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_3;
}
}
done:
if (ieee->set_security)
ieee->set_security(ieee->dev, &sec);
/* Do not reset port if card is in Managed mode since resetting will
* generate new IEEE 802.11 authentication which may end up in looping
* with IEEE 802.1X. If your hardware requires a reset after WEP
* configuration (for example... Prism2), implement the reset_port in
* the callbacks structures used to initialize the 802.11 stack. */
if (ieee->reset_on_keychange &&
ieee->iw_mode != IW_MODE_INFRA &&
ieee->reset_port &&
ieee->reset_port(ieee->dev)) {
printk("reset_port failed\n");
param->u.crypt.err = IEEE_CRYPT_ERR_CARD_CONF_FAILED;
return -EINVAL;
}
return ret;
}
inline struct sk_buff *ieee80211_disassociate_skb(
struct ieee80211_network *beacon,
struct ieee80211_device *ieee,
u8 asRsn)
{
struct sk_buff *skb;
struct ieee80211_disassoc *disass;
skb = dev_alloc_skb(sizeof(struct ieee80211_disassoc));
if (!skb)
return NULL;
disass = (struct ieee80211_disassoc *) skb_put(skb,sizeof(struct ieee80211_disassoc));
disass->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_DISASSOC);
disass->header.duration_id = 0;
memcpy(disass->header.addr1, beacon->bssid, ETH_ALEN);
memcpy(disass->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(disass->header.addr3, beacon->bssid, ETH_ALEN);
disass->reason = asRsn;
return skb;
}
void
SendDisassociation(
struct ieee80211_device *ieee,
u8* asSta,
u8 asRsn
)
{
struct ieee80211_network *beacon = &ieee->current_network;
struct sk_buff *skb;
skb = ieee80211_disassociate_skb(beacon,ieee,asRsn);
if (skb){
softmac_mgmt_xmit(skb, ieee);
//dev_kfree_skb_any(skb);//edit by thomas
}
}
int ieee80211_wpa_supplicant_ioctl(struct ieee80211_device *ieee, struct iw_point *p)
{
struct ieee_param *param;
int ret=0;
down(&ieee->wx_sem);
//IEEE_DEBUG_INFO("wpa_supplicant: len=%d\n", p->length);
if (p->length < sizeof(struct ieee_param) || !p->pointer){
ret = -EINVAL;
goto out;
}
param = kmalloc(p->length, GFP_KERNEL);
if (param == NULL){
ret = -ENOMEM;
goto out;
}
if (copy_from_user(param, p->pointer, p->length)) {
kfree(param);
ret = -EFAULT;
goto out;
}
switch (param->cmd) {
case IEEE_CMD_SET_WPA_PARAM:
ret = ieee80211_wpa_set_param(ieee, param->u.wpa_param.name,
param->u.wpa_param.value);
break;
case IEEE_CMD_SET_WPA_IE:
ret = ieee80211_wpa_set_wpa_ie(ieee, param, p->length);
break;
case IEEE_CMD_SET_ENCRYPTION:
ret = ieee80211_wpa_set_encryption(ieee, param, p->length);
break;
case IEEE_CMD_MLME:
ret = ieee80211_wpa_mlme(ieee, param->u.mlme.command,
param->u.mlme.reason_code);
break;
default:
printk("Unknown WPA supplicant request: %d\n",param->cmd);
ret = -EOPNOTSUPP;
break;
}
if (ret == 0 && copy_to_user(p->pointer, param, p->length))
ret = -EFAULT;
kfree(param);
out:
up(&ieee->wx_sem);
return ret;
}
void notify_wx_assoc_event(struct ieee80211_device *ieee)
{
union iwreq_data wrqu;
wrqu.ap_addr.sa_family = ARPHRD_ETHER;
if (ieee->state == IEEE80211_LINKED)
memcpy(wrqu.ap_addr.sa_data, ieee->current_network.bssid, ETH_ALEN);
else
memset(wrqu.ap_addr.sa_data, 0, ETH_ALEN);
wireless_send_event(ieee->dev, SIOCGIWAP, &wrqu, NULL);
}
EXPORT_SYMBOL(ieee80211_get_beacon);
EXPORT_SYMBOL(ieee80211_wake_queue);
EXPORT_SYMBOL(ieee80211_stop_queue);
EXPORT_SYMBOL(ieee80211_reset_queue);
EXPORT_SYMBOL(ieee80211_softmac_stop_protocol);
EXPORT_SYMBOL(ieee80211_softmac_start_protocol);
EXPORT_SYMBOL(ieee80211_is_shortslot);
EXPORT_SYMBOL(ieee80211_is_54g);
EXPORT_SYMBOL(ieee80211_wpa_supplicant_ioctl);
EXPORT_SYMBOL(ieee80211_ps_tx_ack);
EXPORT_SYMBOL(ieee80211_softmac_xmit);
EXPORT_SYMBOL(ieee80211_stop_send_beacons);
EXPORT_SYMBOL(notify_wx_assoc_event);
EXPORT_SYMBOL(SendDisassociation);
EXPORT_SYMBOL(ieee80211_disassociate);
EXPORT_SYMBOL(ieee80211_start_send_beacons);
EXPORT_SYMBOL(ieee80211_stop_scan);
EXPORT_SYMBOL(ieee80211_send_probe_requests);
EXPORT_SYMBOL(ieee80211_softmac_scan_syncro);
EXPORT_SYMBOL(ieee80211_start_scan_syncro);
//EXPORT_SYMBOL(ieee80211_sta_ps_send_null_frame);
| gpl-2.0 |
Howpathetic/3.4_Shooter_U_kernel | drivers/infiniband/hw/cxgb4/ev.c | 5068 | 5854 | /*
* Copyright (c) 2009-2010 Chelsio, Inc. 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/slab.h>
#include <linux/mman.h>
#include <net/sock.h>
#include "iw_cxgb4.h"
static void post_qp_event(struct c4iw_dev *dev, struct c4iw_cq *chp,
struct c4iw_qp *qhp,
struct t4_cqe *err_cqe,
enum ib_event_type ib_event)
{
struct ib_event event;
struct c4iw_qp_attributes attrs;
unsigned long flag;
if ((qhp->attr.state == C4IW_QP_STATE_ERROR) ||
(qhp->attr.state == C4IW_QP_STATE_TERMINATE)) {
PDBG("%s AE received after RTS - "
"qp state %d qpid 0x%x status 0x%x\n", __func__,
qhp->attr.state, qhp->wq.sq.qid, CQE_STATUS(err_cqe));
return;
}
printk(KERN_ERR MOD "AE qpid 0x%x opcode %d status 0x%x "
"type %d wrid.hi 0x%x wrid.lo 0x%x\n",
CQE_QPID(err_cqe), CQE_OPCODE(err_cqe),
CQE_STATUS(err_cqe), CQE_TYPE(err_cqe),
CQE_WRID_HI(err_cqe), CQE_WRID_LOW(err_cqe));
if (qhp->attr.state == C4IW_QP_STATE_RTS) {
attrs.next_state = C4IW_QP_STATE_TERMINATE;
c4iw_modify_qp(qhp->rhp, qhp, C4IW_QP_ATTR_NEXT_STATE,
&attrs, 0);
}
event.event = ib_event;
event.device = chp->ibcq.device;
if (ib_event == IB_EVENT_CQ_ERR)
event.element.cq = &chp->ibcq;
else
event.element.qp = &qhp->ibqp;
if (qhp->ibqp.event_handler)
(*qhp->ibqp.event_handler)(&event, qhp->ibqp.qp_context);
spin_lock_irqsave(&chp->comp_handler_lock, flag);
(*chp->ibcq.comp_handler)(&chp->ibcq, chp->ibcq.cq_context);
spin_unlock_irqrestore(&chp->comp_handler_lock, flag);
}
void c4iw_ev_dispatch(struct c4iw_dev *dev, struct t4_cqe *err_cqe)
{
struct c4iw_cq *chp;
struct c4iw_qp *qhp;
u32 cqid;
spin_lock(&dev->lock);
qhp = get_qhp(dev, CQE_QPID(err_cqe));
if (!qhp) {
printk(KERN_ERR MOD "BAD AE qpid 0x%x opcode %d "
"status 0x%x type %d wrid.hi 0x%x wrid.lo 0x%x\n",
CQE_QPID(err_cqe),
CQE_OPCODE(err_cqe), CQE_STATUS(err_cqe),
CQE_TYPE(err_cqe), CQE_WRID_HI(err_cqe),
CQE_WRID_LOW(err_cqe));
spin_unlock(&dev->lock);
goto out;
}
if (SQ_TYPE(err_cqe))
cqid = qhp->attr.scq;
else
cqid = qhp->attr.rcq;
chp = get_chp(dev, cqid);
if (!chp) {
printk(KERN_ERR MOD "BAD AE cqid 0x%x qpid 0x%x opcode %d "
"status 0x%x type %d wrid.hi 0x%x wrid.lo 0x%x\n",
cqid, CQE_QPID(err_cqe),
CQE_OPCODE(err_cqe), CQE_STATUS(err_cqe),
CQE_TYPE(err_cqe), CQE_WRID_HI(err_cqe),
CQE_WRID_LOW(err_cqe));
spin_unlock(&dev->lock);
goto out;
}
c4iw_qp_add_ref(&qhp->ibqp);
atomic_inc(&chp->refcnt);
spin_unlock(&dev->lock);
/* Bad incoming write */
if (RQ_TYPE(err_cqe) &&
(CQE_OPCODE(err_cqe) == FW_RI_RDMA_WRITE)) {
post_qp_event(dev, chp, qhp, err_cqe, IB_EVENT_QP_REQ_ERR);
goto done;
}
switch (CQE_STATUS(err_cqe)) {
/* Completion Events */
case T4_ERR_SUCCESS:
printk(KERN_ERR MOD "AE with status 0!\n");
break;
case T4_ERR_STAG:
case T4_ERR_PDID:
case T4_ERR_QPID:
case T4_ERR_ACCESS:
case T4_ERR_WRAP:
case T4_ERR_BOUND:
case T4_ERR_INVALIDATE_SHARED_MR:
case T4_ERR_INVALIDATE_MR_WITH_MW_BOUND:
post_qp_event(dev, chp, qhp, err_cqe, IB_EVENT_QP_ACCESS_ERR);
break;
/* Device Fatal Errors */
case T4_ERR_ECC:
case T4_ERR_ECC_PSTAG:
case T4_ERR_INTERNAL_ERR:
post_qp_event(dev, chp, qhp, err_cqe, IB_EVENT_DEVICE_FATAL);
break;
/* QP Fatal Errors */
case T4_ERR_OUT_OF_RQE:
case T4_ERR_PBL_ADDR_BOUND:
case T4_ERR_CRC:
case T4_ERR_MARKER:
case T4_ERR_PDU_LEN_ERR:
case T4_ERR_DDP_VERSION:
case T4_ERR_RDMA_VERSION:
case T4_ERR_OPCODE:
case T4_ERR_DDP_QUEUE_NUM:
case T4_ERR_MSN:
case T4_ERR_TBIT:
case T4_ERR_MO:
case T4_ERR_MSN_GAP:
case T4_ERR_MSN_RANGE:
case T4_ERR_RQE_ADDR_BOUND:
case T4_ERR_IRD_OVERFLOW:
post_qp_event(dev, chp, qhp, err_cqe, IB_EVENT_QP_FATAL);
break;
default:
printk(KERN_ERR MOD "Unknown T4 status 0x%x QPID 0x%x\n",
CQE_STATUS(err_cqe), qhp->wq.sq.qid);
post_qp_event(dev, chp, qhp, err_cqe, IB_EVENT_QP_FATAL);
break;
}
done:
if (atomic_dec_and_test(&chp->refcnt))
wake_up(&chp->wait);
c4iw_qp_rem_ref(&qhp->ibqp);
out:
return;
}
int c4iw_ev_handler(struct c4iw_dev *dev, u32 qid)
{
struct c4iw_cq *chp;
unsigned long flag;
chp = get_chp(dev, qid);
if (chp) {
spin_lock_irqsave(&chp->comp_handler_lock, flag);
(*chp->ibcq.comp_handler)(&chp->ibcq, chp->ibcq.cq_context);
spin_unlock_irqrestore(&chp->comp_handler_lock, flag);
} else
PDBG("%s unknown cqid 0x%x\n", __func__, qid);
return 0;
}
| gpl-2.0 |
bilalliberty/android_kernel_htc_zaraul | drivers/power/pcf50633-charger.c | 5068 | 12786 | /* NXP PCF50633 Main Battery Charger Driver
*
* (C) 2006-2008 by Openmoko, Inc.
* Author: Balaji Rao <balajirrao@openmoko.org>
* All rights reserved.
*
* Broken down from monstrous PCF50633 driver mainly by
* Harald Welte, Andy Green and Werner Almesberger
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/device.h>
#include <linux/sysfs.h>
#include <linux/platform_device.h>
#include <linux/power_supply.h>
#include <linux/mfd/pcf50633/core.h>
#include <linux/mfd/pcf50633/mbc.h>
struct pcf50633_mbc {
struct pcf50633 *pcf;
int adapter_online;
int usb_online;
struct power_supply usb;
struct power_supply adapter;
struct power_supply ac;
};
int pcf50633_mbc_usb_curlim_set(struct pcf50633 *pcf, int ma)
{
struct pcf50633_mbc *mbc = platform_get_drvdata(pcf->mbc_pdev);
int ret = 0;
u8 bits;
int charging_start = 1;
u8 mbcs2, chgmod;
unsigned int mbcc5;
if (ma >= 1000) {
bits = PCF50633_MBCC7_USB_1000mA;
ma = 1000;
} else if (ma >= 500) {
bits = PCF50633_MBCC7_USB_500mA;
ma = 500;
} else if (ma >= 100) {
bits = PCF50633_MBCC7_USB_100mA;
ma = 100;
} else {
bits = PCF50633_MBCC7_USB_SUSPEND;
charging_start = 0;
ma = 0;
}
ret = pcf50633_reg_set_bit_mask(pcf, PCF50633_REG_MBCC7,
PCF50633_MBCC7_USB_MASK, bits);
if (ret)
dev_err(pcf->dev, "error setting usb curlim to %d mA\n", ma);
else
dev_info(pcf->dev, "usb curlim to %d mA\n", ma);
/*
* We limit the charging current to be the USB current limit.
* The reason is that on pcf50633, when it enters PMU Standby mode,
* which it does when the device goes "off", the USB current limit
* reverts to the variant default. In at least one common case, that
* default is 500mA. By setting the charging current to be the same
* as the USB limit we set here before PMU standby, we enforce it only
* using the correct amount of current even when the USB current limit
* gets reset to the wrong thing
*/
if (mbc->pcf->pdata->charger_reference_current_ma) {
mbcc5 = (ma << 8) / mbc->pcf->pdata->charger_reference_current_ma;
if (mbcc5 > 255)
mbcc5 = 255;
pcf50633_reg_write(mbc->pcf, PCF50633_REG_MBCC5, mbcc5);
}
mbcs2 = pcf50633_reg_read(mbc->pcf, PCF50633_REG_MBCS2);
chgmod = (mbcs2 & PCF50633_MBCS2_MBC_MASK);
/* If chgmod == BATFULL, setting chgena has no effect.
* Datasheet says we need to set resume instead but when autoresume is
* used resume doesn't work. Clear and set chgena instead.
*/
if (chgmod != PCF50633_MBCS2_MBC_BAT_FULL)
pcf50633_reg_set_bit_mask(pcf, PCF50633_REG_MBCC1,
PCF50633_MBCC1_CHGENA, PCF50633_MBCC1_CHGENA);
else {
pcf50633_reg_clear_bits(pcf, PCF50633_REG_MBCC1,
PCF50633_MBCC1_CHGENA);
pcf50633_reg_set_bit_mask(pcf, PCF50633_REG_MBCC1,
PCF50633_MBCC1_CHGENA, PCF50633_MBCC1_CHGENA);
}
power_supply_changed(&mbc->usb);
return ret;
}
EXPORT_SYMBOL_GPL(pcf50633_mbc_usb_curlim_set);
int pcf50633_mbc_get_status(struct pcf50633 *pcf)
{
struct pcf50633_mbc *mbc = platform_get_drvdata(pcf->mbc_pdev);
int status = 0;
u8 chgmod;
if (!mbc)
return 0;
chgmod = pcf50633_reg_read(mbc->pcf, PCF50633_REG_MBCS2)
& PCF50633_MBCS2_MBC_MASK;
if (mbc->usb_online)
status |= PCF50633_MBC_USB_ONLINE;
if (chgmod == PCF50633_MBCS2_MBC_USB_PRE ||
chgmod == PCF50633_MBCS2_MBC_USB_PRE_WAIT ||
chgmod == PCF50633_MBCS2_MBC_USB_FAST ||
chgmod == PCF50633_MBCS2_MBC_USB_FAST_WAIT)
status |= PCF50633_MBC_USB_ACTIVE;
if (mbc->adapter_online)
status |= PCF50633_MBC_ADAPTER_ONLINE;
if (chgmod == PCF50633_MBCS2_MBC_ADP_PRE ||
chgmod == PCF50633_MBCS2_MBC_ADP_PRE_WAIT ||
chgmod == PCF50633_MBCS2_MBC_ADP_FAST ||
chgmod == PCF50633_MBCS2_MBC_ADP_FAST_WAIT)
status |= PCF50633_MBC_ADAPTER_ACTIVE;
return status;
}
EXPORT_SYMBOL_GPL(pcf50633_mbc_get_status);
int pcf50633_mbc_get_usb_online_status(struct pcf50633 *pcf)
{
struct pcf50633_mbc *mbc = platform_get_drvdata(pcf->mbc_pdev);
if (!mbc)
return 0;
return mbc->usb_online;
}
EXPORT_SYMBOL_GPL(pcf50633_mbc_get_usb_online_status);
static ssize_t
show_chgmode(struct device *dev, struct device_attribute *attr, char *buf)
{
struct pcf50633_mbc *mbc = dev_get_drvdata(dev);
u8 mbcs2 = pcf50633_reg_read(mbc->pcf, PCF50633_REG_MBCS2);
u8 chgmod = (mbcs2 & PCF50633_MBCS2_MBC_MASK);
return sprintf(buf, "%d\n", chgmod);
}
static DEVICE_ATTR(chgmode, S_IRUGO, show_chgmode, NULL);
static ssize_t
show_usblim(struct device *dev, struct device_attribute *attr, char *buf)
{
struct pcf50633_mbc *mbc = dev_get_drvdata(dev);
u8 usblim = pcf50633_reg_read(mbc->pcf, PCF50633_REG_MBCC7) &
PCF50633_MBCC7_USB_MASK;
unsigned int ma;
if (usblim == PCF50633_MBCC7_USB_1000mA)
ma = 1000;
else if (usblim == PCF50633_MBCC7_USB_500mA)
ma = 500;
else if (usblim == PCF50633_MBCC7_USB_100mA)
ma = 100;
else
ma = 0;
return sprintf(buf, "%u\n", ma);
}
static ssize_t set_usblim(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct pcf50633_mbc *mbc = dev_get_drvdata(dev);
unsigned long ma;
int ret;
ret = strict_strtoul(buf, 10, &ma);
if (ret)
return -EINVAL;
pcf50633_mbc_usb_curlim_set(mbc->pcf, ma);
return count;
}
static DEVICE_ATTR(usb_curlim, S_IRUGO | S_IWUSR, show_usblim, set_usblim);
static ssize_t
show_chglim(struct device *dev, struct device_attribute *attr, char *buf)
{
struct pcf50633_mbc *mbc = dev_get_drvdata(dev);
u8 mbcc5 = pcf50633_reg_read(mbc->pcf, PCF50633_REG_MBCC5);
unsigned int ma;
if (!mbc->pcf->pdata->charger_reference_current_ma)
return -ENODEV;
ma = (mbc->pcf->pdata->charger_reference_current_ma * mbcc5) >> 8;
return sprintf(buf, "%u\n", ma);
}
static ssize_t set_chglim(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct pcf50633_mbc *mbc = dev_get_drvdata(dev);
unsigned long ma;
unsigned int mbcc5;
int ret;
if (!mbc->pcf->pdata->charger_reference_current_ma)
return -ENODEV;
ret = strict_strtoul(buf, 10, &ma);
if (ret)
return -EINVAL;
mbcc5 = (ma << 8) / mbc->pcf->pdata->charger_reference_current_ma;
if (mbcc5 > 255)
mbcc5 = 255;
pcf50633_reg_write(mbc->pcf, PCF50633_REG_MBCC5, mbcc5);
return count;
}
/*
* This attribute allows to change MBC charging limit on the fly
* independently of usb current limit. It also gets set automatically every
* time usb current limit is changed.
*/
static DEVICE_ATTR(chg_curlim, S_IRUGO | S_IWUSR, show_chglim, set_chglim);
static struct attribute *pcf50633_mbc_sysfs_entries[] = {
&dev_attr_chgmode.attr,
&dev_attr_usb_curlim.attr,
&dev_attr_chg_curlim.attr,
NULL,
};
static struct attribute_group mbc_attr_group = {
.name = NULL, /* put in device directory */
.attrs = pcf50633_mbc_sysfs_entries,
};
static void
pcf50633_mbc_irq_handler(int irq, void *data)
{
struct pcf50633_mbc *mbc = data;
/* USB */
if (irq == PCF50633_IRQ_USBINS) {
mbc->usb_online = 1;
} else if (irq == PCF50633_IRQ_USBREM) {
mbc->usb_online = 0;
pcf50633_mbc_usb_curlim_set(mbc->pcf, 0);
}
/* Adapter */
if (irq == PCF50633_IRQ_ADPINS)
mbc->adapter_online = 1;
else if (irq == PCF50633_IRQ_ADPREM)
mbc->adapter_online = 0;
power_supply_changed(&mbc->ac);
power_supply_changed(&mbc->usb);
power_supply_changed(&mbc->adapter);
if (mbc->pcf->pdata->mbc_event_callback)
mbc->pcf->pdata->mbc_event_callback(mbc->pcf, irq);
}
static int adapter_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct pcf50633_mbc *mbc = container_of(psy,
struct pcf50633_mbc, adapter);
int ret = 0;
switch (psp) {
case POWER_SUPPLY_PROP_ONLINE:
val->intval = mbc->adapter_online;
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
static int usb_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct pcf50633_mbc *mbc = container_of(psy, struct pcf50633_mbc, usb);
int ret = 0;
u8 usblim = pcf50633_reg_read(mbc->pcf, PCF50633_REG_MBCC7) &
PCF50633_MBCC7_USB_MASK;
switch (psp) {
case POWER_SUPPLY_PROP_ONLINE:
val->intval = mbc->usb_online &&
(usblim <= PCF50633_MBCC7_USB_500mA);
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
static int ac_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct pcf50633_mbc *mbc = container_of(psy, struct pcf50633_mbc, ac);
int ret = 0;
u8 usblim = pcf50633_reg_read(mbc->pcf, PCF50633_REG_MBCC7) &
PCF50633_MBCC7_USB_MASK;
switch (psp) {
case POWER_SUPPLY_PROP_ONLINE:
val->intval = mbc->usb_online &&
(usblim == PCF50633_MBCC7_USB_1000mA);
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
static enum power_supply_property power_props[] = {
POWER_SUPPLY_PROP_ONLINE,
};
static const u8 mbc_irq_handlers[] = {
PCF50633_IRQ_ADPINS,
PCF50633_IRQ_ADPREM,
PCF50633_IRQ_USBINS,
PCF50633_IRQ_USBREM,
PCF50633_IRQ_BATFULL,
PCF50633_IRQ_CHGHALT,
PCF50633_IRQ_THLIMON,
PCF50633_IRQ_THLIMOFF,
PCF50633_IRQ_USBLIMON,
PCF50633_IRQ_USBLIMOFF,
PCF50633_IRQ_LOWSYS,
PCF50633_IRQ_LOWBAT,
};
static int __devinit pcf50633_mbc_probe(struct platform_device *pdev)
{
struct pcf50633_mbc *mbc;
int ret;
int i;
u8 mbcs1;
mbc = kzalloc(sizeof(*mbc), GFP_KERNEL);
if (!mbc)
return -ENOMEM;
platform_set_drvdata(pdev, mbc);
mbc->pcf = dev_to_pcf50633(pdev->dev.parent);
/* Set up IRQ handlers */
for (i = 0; i < ARRAY_SIZE(mbc_irq_handlers); i++)
pcf50633_register_irq(mbc->pcf, mbc_irq_handlers[i],
pcf50633_mbc_irq_handler, mbc);
/* Create power supplies */
mbc->adapter.name = "adapter";
mbc->adapter.type = POWER_SUPPLY_TYPE_MAINS;
mbc->adapter.properties = power_props;
mbc->adapter.num_properties = ARRAY_SIZE(power_props);
mbc->adapter.get_property = &adapter_get_property;
mbc->adapter.supplied_to = mbc->pcf->pdata->batteries;
mbc->adapter.num_supplicants = mbc->pcf->pdata->num_batteries;
mbc->usb.name = "usb";
mbc->usb.type = POWER_SUPPLY_TYPE_USB;
mbc->usb.properties = power_props;
mbc->usb.num_properties = ARRAY_SIZE(power_props);
mbc->usb.get_property = usb_get_property;
mbc->usb.supplied_to = mbc->pcf->pdata->batteries;
mbc->usb.num_supplicants = mbc->pcf->pdata->num_batteries;
mbc->ac.name = "ac";
mbc->ac.type = POWER_SUPPLY_TYPE_MAINS;
mbc->ac.properties = power_props;
mbc->ac.num_properties = ARRAY_SIZE(power_props);
mbc->ac.get_property = ac_get_property;
mbc->ac.supplied_to = mbc->pcf->pdata->batteries;
mbc->ac.num_supplicants = mbc->pcf->pdata->num_batteries;
ret = power_supply_register(&pdev->dev, &mbc->adapter);
if (ret) {
dev_err(mbc->pcf->dev, "failed to register adapter\n");
kfree(mbc);
return ret;
}
ret = power_supply_register(&pdev->dev, &mbc->usb);
if (ret) {
dev_err(mbc->pcf->dev, "failed to register usb\n");
power_supply_unregister(&mbc->adapter);
kfree(mbc);
return ret;
}
ret = power_supply_register(&pdev->dev, &mbc->ac);
if (ret) {
dev_err(mbc->pcf->dev, "failed to register ac\n");
power_supply_unregister(&mbc->adapter);
power_supply_unregister(&mbc->usb);
kfree(mbc);
return ret;
}
ret = sysfs_create_group(&pdev->dev.kobj, &mbc_attr_group);
if (ret)
dev_err(mbc->pcf->dev, "failed to create sysfs entries\n");
mbcs1 = pcf50633_reg_read(mbc->pcf, PCF50633_REG_MBCS1);
if (mbcs1 & PCF50633_MBCS1_USBPRES)
pcf50633_mbc_irq_handler(PCF50633_IRQ_USBINS, mbc);
if (mbcs1 & PCF50633_MBCS1_ADAPTPRES)
pcf50633_mbc_irq_handler(PCF50633_IRQ_ADPINS, mbc);
return 0;
}
static int __devexit pcf50633_mbc_remove(struct platform_device *pdev)
{
struct pcf50633_mbc *mbc = platform_get_drvdata(pdev);
int i;
/* Remove IRQ handlers */
for (i = 0; i < ARRAY_SIZE(mbc_irq_handlers); i++)
pcf50633_free_irq(mbc->pcf, mbc_irq_handlers[i]);
sysfs_remove_group(&pdev->dev.kobj, &mbc_attr_group);
power_supply_unregister(&mbc->usb);
power_supply_unregister(&mbc->adapter);
power_supply_unregister(&mbc->ac);
kfree(mbc);
return 0;
}
static struct platform_driver pcf50633_mbc_driver = {
.driver = {
.name = "pcf50633-mbc",
},
.probe = pcf50633_mbc_probe,
.remove = __devexit_p(pcf50633_mbc_remove),
};
module_platform_driver(pcf50633_mbc_driver);
MODULE_AUTHOR("Balaji Rao <balajirrao@openmoko.org>");
MODULE_DESCRIPTION("PCF50633 mbc driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:pcf50633-mbc");
| gpl-2.0 |
armani-dev/kernel_test | sound/soc/fsl/pcm030-audio-fabric.c | 5068 | 2145 | /*
* Phytec pcm030 driver for the PSC of the Freescale MPC52xx
* configured as AC97 interface
*
* Copyright 2008 Jon Smirl, Digispeaker
* Author: Jon Smirl <jonsmirl@gmail.com>
*
* This file is licensed under the terms of the GNU General Public License
* version 2. This program is licensed "as is" without any warranty of any
* kind, whether express or implied.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/of_device.h>
#include <linux/of_platform.h>
#include <linux/dma-mapping.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/initval.h>
#include <sound/soc.h>
#include "mpc5200_dma.h"
#include "mpc5200_psc_ac97.h"
#include "../codecs/wm9712.h"
#define DRV_NAME "pcm030-audio-fabric"
static struct snd_soc_dai_link pcm030_fabric_dai[] = {
{
.name = "AC97",
.stream_name = "AC97 Analog",
.codec_dai_name = "wm9712-hifi",
.cpu_dai_name = "mpc5200-psc-ac97.0",
.platform_name = "mpc5200-pcm-audio",
.codec_name = "wm9712-codec",
},
{
.name = "AC97",
.stream_name = "AC97 IEC958",
.codec_dai_name = "wm9712-aux",
.cpu_dai_name = "mpc5200-psc-ac97.1",
.platform_name = "mpc5200-pcm-audio",
.codec_name = "wm9712-codec",
},
};
static struct snd_soc_card card = {
.name = "pcm030",
.owner = THIS_MODULE,
.dai_link = pcm030_fabric_dai,
.num_links = ARRAY_SIZE(pcm030_fabric_dai),
};
static __init int pcm030_fabric_init(void)
{
struct platform_device *pdev;
int rc;
if (!of_machine_is_compatible("phytec,pcm030"))
return -ENODEV;
pdev = platform_device_alloc("soc-audio", 1);
if (!pdev) {
pr_err("pcm030_fabric_init: platform_device_alloc() failed\n");
return -ENODEV;
}
platform_set_drvdata(pdev, &card);
rc = platform_device_add(pdev);
if (rc) {
pr_err("pcm030_fabric_init: platform_device_add() failed\n");
platform_device_put(pdev);
return -ENODEV;
}
return 0;
}
module_init(pcm030_fabric_init);
MODULE_AUTHOR("Jon Smirl <jonsmirl@gmail.com>");
MODULE_DESCRIPTION(DRV_NAME ": mpc5200 pcm030 fabric driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
CSIEMIAT/linux-3.6.0-MIAT | drivers/power/wm8350_power.c | 5068 | 15072 | /*
* Battery driver for wm8350 PMIC
*
* Copyright 2007, 2008 Wolfson Microelectronics PLC.
*
* Based on OLPC Battery Driver
*
* Copyright 2006 David Woodhouse <dwmw2@infradead.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/err.h>
#include <linux/platform_device.h>
#include <linux/power_supply.h>
#include <linux/mfd/wm8350/supply.h>
#include <linux/mfd/wm8350/core.h>
#include <linux/mfd/wm8350/comparator.h>
static int wm8350_read_battery_uvolts(struct wm8350 *wm8350)
{
return wm8350_read_auxadc(wm8350, WM8350_AUXADC_BATT, 0, 0)
* WM8350_AUX_COEFF;
}
static int wm8350_read_line_uvolts(struct wm8350 *wm8350)
{
return wm8350_read_auxadc(wm8350, WM8350_AUXADC_LINE, 0, 0)
* WM8350_AUX_COEFF;
}
static int wm8350_read_usb_uvolts(struct wm8350 *wm8350)
{
return wm8350_read_auxadc(wm8350, WM8350_AUXADC_USB, 0, 0)
* WM8350_AUX_COEFF;
}
#define WM8350_BATT_SUPPLY 1
#define WM8350_USB_SUPPLY 2
#define WM8350_LINE_SUPPLY 4
static inline int wm8350_charge_time_min(struct wm8350 *wm8350, int min)
{
if (!wm8350->power.rev_g_coeff)
return (((min - 30) / 15) & 0xf) << 8;
else
return (((min - 30) / 30) & 0xf) << 8;
}
static int wm8350_get_supplies(struct wm8350 *wm8350)
{
u16 sm, ov, co, chrg;
int supplies = 0;
sm = wm8350_reg_read(wm8350, WM8350_STATE_MACHINE_STATUS);
ov = wm8350_reg_read(wm8350, WM8350_MISC_OVERRIDES);
co = wm8350_reg_read(wm8350, WM8350_COMPARATOR_OVERRIDES);
chrg = wm8350_reg_read(wm8350, WM8350_BATTERY_CHARGER_CONTROL_2);
/* USB_SM */
sm = (sm & WM8350_USB_SM_MASK) >> WM8350_USB_SM_SHIFT;
/* CHG_ISEL */
chrg &= WM8350_CHG_ISEL_MASK;
/* If the USB state machine is active then we're using that with or
* without battery, otherwise check for wall supply */
if (((sm == WM8350_USB_SM_100_SLV) ||
(sm == WM8350_USB_SM_500_SLV) ||
(sm == WM8350_USB_SM_STDBY_SLV))
&& !(ov & WM8350_USB_LIMIT_OVRDE))
supplies = WM8350_USB_SUPPLY;
else if (((sm == WM8350_USB_SM_100_SLV) ||
(sm == WM8350_USB_SM_500_SLV) ||
(sm == WM8350_USB_SM_STDBY_SLV))
&& (ov & WM8350_USB_LIMIT_OVRDE) && (chrg == 0))
supplies = WM8350_USB_SUPPLY | WM8350_BATT_SUPPLY;
else if (co & WM8350_WALL_FB_OVRDE)
supplies = WM8350_LINE_SUPPLY;
else
supplies = WM8350_BATT_SUPPLY;
return supplies;
}
static int wm8350_charger_config(struct wm8350 *wm8350,
struct wm8350_charger_policy *policy)
{
u16 reg, eoc_mA, fast_limit_mA;
if (!policy) {
dev_warn(wm8350->dev,
"No charger policy, charger not configured.\n");
return -EINVAL;
}
/* make sure USB fast charge current is not > 500mA */
if (policy->fast_limit_USB_mA > 500) {
dev_err(wm8350->dev, "USB fast charge > 500mA\n");
return -EINVAL;
}
eoc_mA = WM8350_CHG_EOC_mA(policy->eoc_mA);
wm8350_reg_unlock(wm8350);
reg = wm8350_reg_read(wm8350, WM8350_BATTERY_CHARGER_CONTROL_1)
& WM8350_CHG_ENA_R168;
wm8350_reg_write(wm8350, WM8350_BATTERY_CHARGER_CONTROL_1,
reg | eoc_mA | policy->trickle_start_mV |
WM8350_CHG_TRICKLE_TEMP_CHOKE |
WM8350_CHG_TRICKLE_USB_CHOKE |
WM8350_CHG_FAST_USB_THROTTLE);
if (wm8350_get_supplies(wm8350) & WM8350_USB_SUPPLY) {
fast_limit_mA =
WM8350_CHG_FAST_LIMIT_mA(policy->fast_limit_USB_mA);
wm8350_reg_write(wm8350, WM8350_BATTERY_CHARGER_CONTROL_2,
policy->charge_mV | policy->trickle_charge_USB_mA |
fast_limit_mA | wm8350_charge_time_min(wm8350,
policy->charge_timeout));
} else {
fast_limit_mA =
WM8350_CHG_FAST_LIMIT_mA(policy->fast_limit_mA);
wm8350_reg_write(wm8350, WM8350_BATTERY_CHARGER_CONTROL_2,
policy->charge_mV | policy->trickle_charge_mA |
fast_limit_mA | wm8350_charge_time_min(wm8350,
policy->charge_timeout));
}
wm8350_reg_lock(wm8350);
return 0;
}
static int wm8350_batt_status(struct wm8350 *wm8350)
{
u16 state;
state = wm8350_reg_read(wm8350, WM8350_BATTERY_CHARGER_CONTROL_2);
state &= WM8350_CHG_STS_MASK;
switch (state) {
case WM8350_CHG_STS_OFF:
return POWER_SUPPLY_STATUS_DISCHARGING;
case WM8350_CHG_STS_TRICKLE:
case WM8350_CHG_STS_FAST:
return POWER_SUPPLY_STATUS_CHARGING;
default:
return POWER_SUPPLY_STATUS_UNKNOWN;
}
}
static ssize_t charger_state_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct wm8350 *wm8350 = dev_get_drvdata(dev);
char *charge;
int state;
state = wm8350_reg_read(wm8350, WM8350_BATTERY_CHARGER_CONTROL_2) &
WM8350_CHG_STS_MASK;
switch (state) {
case WM8350_CHG_STS_OFF:
charge = "Charger Off";
break;
case WM8350_CHG_STS_TRICKLE:
charge = "Trickle Charging";
break;
case WM8350_CHG_STS_FAST:
charge = "Fast Charging";
break;
default:
return 0;
}
return sprintf(buf, "%s\n", charge);
}
static DEVICE_ATTR(charger_state, 0444, charger_state_show, NULL);
static irqreturn_t wm8350_charger_handler(int irq, void *data)
{
struct wm8350 *wm8350 = data;
struct wm8350_power *power = &wm8350->power;
struct wm8350_charger_policy *policy = power->policy;
switch (irq - wm8350->irq_base) {
case WM8350_IRQ_CHG_BAT_FAIL:
dev_err(wm8350->dev, "battery failed\n");
break;
case WM8350_IRQ_CHG_TO:
dev_err(wm8350->dev, "charger timeout\n");
power_supply_changed(&power->battery);
break;
case WM8350_IRQ_CHG_BAT_HOT:
case WM8350_IRQ_CHG_BAT_COLD:
case WM8350_IRQ_CHG_START:
case WM8350_IRQ_CHG_END:
power_supply_changed(&power->battery);
break;
case WM8350_IRQ_CHG_FAST_RDY:
dev_dbg(wm8350->dev, "fast charger ready\n");
wm8350_charger_config(wm8350, policy);
wm8350_reg_unlock(wm8350);
wm8350_set_bits(wm8350, WM8350_BATTERY_CHARGER_CONTROL_1,
WM8350_CHG_FAST);
wm8350_reg_lock(wm8350);
break;
case WM8350_IRQ_CHG_VBATT_LT_3P9:
dev_warn(wm8350->dev, "battery < 3.9V\n");
break;
case WM8350_IRQ_CHG_VBATT_LT_3P1:
dev_warn(wm8350->dev, "battery < 3.1V\n");
break;
case WM8350_IRQ_CHG_VBATT_LT_2P85:
dev_warn(wm8350->dev, "battery < 2.85V\n");
break;
/* Supply change. We will overnotify but it should do
* no harm. */
case WM8350_IRQ_EXT_USB_FB:
case WM8350_IRQ_EXT_WALL_FB:
wm8350_charger_config(wm8350, policy);
case WM8350_IRQ_EXT_BAT_FB: /* Fall through */
power_supply_changed(&power->battery);
power_supply_changed(&power->usb);
power_supply_changed(&power->ac);
break;
default:
dev_err(wm8350->dev, "Unknown interrupt %d\n", irq);
}
return IRQ_HANDLED;
}
/*********************************************************************
* AC Power
*********************************************************************/
static int wm8350_ac_get_prop(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct wm8350 *wm8350 = dev_get_drvdata(psy->dev->parent);
int ret = 0;
switch (psp) {
case POWER_SUPPLY_PROP_ONLINE:
val->intval = !!(wm8350_get_supplies(wm8350) &
WM8350_LINE_SUPPLY);
break;
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
val->intval = wm8350_read_line_uvolts(wm8350);
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
static enum power_supply_property wm8350_ac_props[] = {
POWER_SUPPLY_PROP_ONLINE,
POWER_SUPPLY_PROP_VOLTAGE_NOW,
};
/*********************************************************************
* USB Power
*********************************************************************/
static int wm8350_usb_get_prop(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct wm8350 *wm8350 = dev_get_drvdata(psy->dev->parent);
int ret = 0;
switch (psp) {
case POWER_SUPPLY_PROP_ONLINE:
val->intval = !!(wm8350_get_supplies(wm8350) &
WM8350_USB_SUPPLY);
break;
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
val->intval = wm8350_read_usb_uvolts(wm8350);
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
static enum power_supply_property wm8350_usb_props[] = {
POWER_SUPPLY_PROP_ONLINE,
POWER_SUPPLY_PROP_VOLTAGE_NOW,
};
/*********************************************************************
* Battery properties
*********************************************************************/
static int wm8350_bat_check_health(struct wm8350 *wm8350)
{
u16 reg;
if (wm8350_read_battery_uvolts(wm8350) < 2850000)
return POWER_SUPPLY_HEALTH_UNSPEC_FAILURE;
reg = wm8350_reg_read(wm8350, WM8350_CHARGER_OVERRIDES);
if (reg & WM8350_CHG_BATT_HOT_OVRDE)
return POWER_SUPPLY_HEALTH_OVERHEAT;
if (reg & WM8350_CHG_BATT_COLD_OVRDE)
return POWER_SUPPLY_HEALTH_COLD;
return POWER_SUPPLY_HEALTH_GOOD;
}
static int wm8350_bat_get_charge_type(struct wm8350 *wm8350)
{
int state;
state = wm8350_reg_read(wm8350, WM8350_BATTERY_CHARGER_CONTROL_2) &
WM8350_CHG_STS_MASK;
switch (state) {
case WM8350_CHG_STS_OFF:
return POWER_SUPPLY_CHARGE_TYPE_NONE;
case WM8350_CHG_STS_TRICKLE:
return POWER_SUPPLY_CHARGE_TYPE_TRICKLE;
case WM8350_CHG_STS_FAST:
return POWER_SUPPLY_CHARGE_TYPE_FAST;
default:
return POWER_SUPPLY_CHARGE_TYPE_UNKNOWN;
}
}
static int wm8350_bat_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct wm8350 *wm8350 = dev_get_drvdata(psy->dev->parent);
int ret = 0;
switch (psp) {
case POWER_SUPPLY_PROP_STATUS:
val->intval = wm8350_batt_status(wm8350);
break;
case POWER_SUPPLY_PROP_ONLINE:
val->intval = !!(wm8350_get_supplies(wm8350) &
WM8350_BATT_SUPPLY);
break;
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
val->intval = wm8350_read_battery_uvolts(wm8350);
break;
case POWER_SUPPLY_PROP_HEALTH:
val->intval = wm8350_bat_check_health(wm8350);
break;
case POWER_SUPPLY_PROP_CHARGE_TYPE:
val->intval = wm8350_bat_get_charge_type(wm8350);
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
static enum power_supply_property wm8350_bat_props[] = {
POWER_SUPPLY_PROP_STATUS,
POWER_SUPPLY_PROP_ONLINE,
POWER_SUPPLY_PROP_VOLTAGE_NOW,
POWER_SUPPLY_PROP_HEALTH,
POWER_SUPPLY_PROP_CHARGE_TYPE,
};
/*********************************************************************
* Initialisation
*********************************************************************/
static void wm8350_init_charger(struct wm8350 *wm8350)
{
/* register our interest in charger events */
wm8350_register_irq(wm8350, WM8350_IRQ_CHG_BAT_HOT,
wm8350_charger_handler, 0, "Battery hot", wm8350);
wm8350_register_irq(wm8350, WM8350_IRQ_CHG_BAT_COLD,
wm8350_charger_handler, 0, "Battery cold", wm8350);
wm8350_register_irq(wm8350, WM8350_IRQ_CHG_BAT_FAIL,
wm8350_charger_handler, 0, "Battery fail", wm8350);
wm8350_register_irq(wm8350, WM8350_IRQ_CHG_TO,
wm8350_charger_handler, 0,
"Charger timeout", wm8350);
wm8350_register_irq(wm8350, WM8350_IRQ_CHG_END,
wm8350_charger_handler, 0,
"Charge end", wm8350);
wm8350_register_irq(wm8350, WM8350_IRQ_CHG_START,
wm8350_charger_handler, 0,
"Charge start", wm8350);
wm8350_register_irq(wm8350, WM8350_IRQ_CHG_FAST_RDY,
wm8350_charger_handler, 0,
"Fast charge ready", wm8350);
wm8350_register_irq(wm8350, WM8350_IRQ_CHG_VBATT_LT_3P9,
wm8350_charger_handler, 0,
"Battery <3.9V", wm8350);
wm8350_register_irq(wm8350, WM8350_IRQ_CHG_VBATT_LT_3P1,
wm8350_charger_handler, 0,
"Battery <3.1V", wm8350);
wm8350_register_irq(wm8350, WM8350_IRQ_CHG_VBATT_LT_2P85,
wm8350_charger_handler, 0,
"Battery <2.85V", wm8350);
/* and supply change events */
wm8350_register_irq(wm8350, WM8350_IRQ_EXT_USB_FB,
wm8350_charger_handler, 0, "USB", wm8350);
wm8350_register_irq(wm8350, WM8350_IRQ_EXT_WALL_FB,
wm8350_charger_handler, 0, "Wall", wm8350);
wm8350_register_irq(wm8350, WM8350_IRQ_EXT_BAT_FB,
wm8350_charger_handler, 0, "Battery", wm8350);
}
static void free_charger_irq(struct wm8350 *wm8350)
{
wm8350_free_irq(wm8350, WM8350_IRQ_CHG_BAT_HOT, wm8350);
wm8350_free_irq(wm8350, WM8350_IRQ_CHG_BAT_COLD, wm8350);
wm8350_free_irq(wm8350, WM8350_IRQ_CHG_BAT_FAIL, wm8350);
wm8350_free_irq(wm8350, WM8350_IRQ_CHG_TO, wm8350);
wm8350_free_irq(wm8350, WM8350_IRQ_CHG_END, wm8350);
wm8350_free_irq(wm8350, WM8350_IRQ_CHG_START, wm8350);
wm8350_free_irq(wm8350, WM8350_IRQ_CHG_VBATT_LT_3P9, wm8350);
wm8350_free_irq(wm8350, WM8350_IRQ_CHG_VBATT_LT_3P1, wm8350);
wm8350_free_irq(wm8350, WM8350_IRQ_CHG_VBATT_LT_2P85, wm8350);
wm8350_free_irq(wm8350, WM8350_IRQ_EXT_USB_FB, wm8350);
wm8350_free_irq(wm8350, WM8350_IRQ_EXT_WALL_FB, wm8350);
wm8350_free_irq(wm8350, WM8350_IRQ_EXT_BAT_FB, wm8350);
}
static __devinit int wm8350_power_probe(struct platform_device *pdev)
{
struct wm8350 *wm8350 = platform_get_drvdata(pdev);
struct wm8350_power *power = &wm8350->power;
struct wm8350_charger_policy *policy = power->policy;
struct power_supply *usb = &power->usb;
struct power_supply *battery = &power->battery;
struct power_supply *ac = &power->ac;
int ret;
ac->name = "wm8350-ac";
ac->type = POWER_SUPPLY_TYPE_MAINS;
ac->properties = wm8350_ac_props;
ac->num_properties = ARRAY_SIZE(wm8350_ac_props);
ac->get_property = wm8350_ac_get_prop;
ret = power_supply_register(&pdev->dev, ac);
if (ret)
return ret;
battery->name = "wm8350-battery";
battery->properties = wm8350_bat_props;
battery->num_properties = ARRAY_SIZE(wm8350_bat_props);
battery->get_property = wm8350_bat_get_property;
battery->use_for_apm = 1;
ret = power_supply_register(&pdev->dev, battery);
if (ret)
goto battery_failed;
usb->name = "wm8350-usb",
usb->type = POWER_SUPPLY_TYPE_USB;
usb->properties = wm8350_usb_props;
usb->num_properties = ARRAY_SIZE(wm8350_usb_props);
usb->get_property = wm8350_usb_get_prop;
ret = power_supply_register(&pdev->dev, usb);
if (ret)
goto usb_failed;
ret = device_create_file(&pdev->dev, &dev_attr_charger_state);
if (ret < 0)
dev_warn(wm8350->dev, "failed to add charge sysfs: %d\n", ret);
ret = 0;
wm8350_init_charger(wm8350);
if (wm8350_charger_config(wm8350, policy) == 0) {
wm8350_reg_unlock(wm8350);
wm8350_set_bits(wm8350, WM8350_POWER_MGMT_5, WM8350_CHG_ENA);
wm8350_reg_lock(wm8350);
}
return ret;
usb_failed:
power_supply_unregister(battery);
battery_failed:
power_supply_unregister(ac);
return ret;
}
static __devexit int wm8350_power_remove(struct platform_device *pdev)
{
struct wm8350 *wm8350 = platform_get_drvdata(pdev);
struct wm8350_power *power = &wm8350->power;
free_charger_irq(wm8350);
device_remove_file(&pdev->dev, &dev_attr_charger_state);
power_supply_unregister(&power->battery);
power_supply_unregister(&power->ac);
power_supply_unregister(&power->usb);
return 0;
}
static struct platform_driver wm8350_power_driver = {
.probe = wm8350_power_probe,
.remove = __devexit_p(wm8350_power_remove),
.driver = {
.name = "wm8350-power",
},
};
module_platform_driver(wm8350_power_driver);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Power supply driver for WM8350");
MODULE_ALIAS("platform:wm8350-power");
| gpl-2.0 |
GrandPrime/android_kernel_samsung_fortuna | net/sunrpc/sysctl.c | 7116 | 3638 | /*
* linux/net/sunrpc/sysctl.c
*
* Sysctl interface to sunrpc module.
*
* I would prefer to register the sunrpc table below sys/net, but that's
* impossible at the moment.
*/
#include <linux/types.h>
#include <linux/linkage.h>
#include <linux/ctype.h>
#include <linux/fs.h>
#include <linux/sysctl.h>
#include <linux/module.h>
#include <asm/uaccess.h>
#include <linux/sunrpc/types.h>
#include <linux/sunrpc/sched.h>
#include <linux/sunrpc/stats.h>
#include <linux/sunrpc/svc_xprt.h>
#include "netns.h"
/*
* Declare the debug flags here
*/
unsigned int rpc_debug;
EXPORT_SYMBOL_GPL(rpc_debug);
unsigned int nfs_debug;
EXPORT_SYMBOL_GPL(nfs_debug);
unsigned int nfsd_debug;
EXPORT_SYMBOL_GPL(nfsd_debug);
unsigned int nlm_debug;
EXPORT_SYMBOL_GPL(nlm_debug);
#ifdef RPC_DEBUG
static struct ctl_table_header *sunrpc_table_header;
static ctl_table sunrpc_table[];
void
rpc_register_sysctl(void)
{
if (!sunrpc_table_header)
sunrpc_table_header = register_sysctl_table(sunrpc_table);
}
void
rpc_unregister_sysctl(void)
{
if (sunrpc_table_header) {
unregister_sysctl_table(sunrpc_table_header);
sunrpc_table_header = NULL;
}
}
static int proc_do_xprt(ctl_table *table, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
char tmpbuf[256];
size_t len;
if ((*ppos && !write) || !*lenp) {
*lenp = 0;
return 0;
}
len = svc_print_xprts(tmpbuf, sizeof(tmpbuf));
return simple_read_from_buffer(buffer, *lenp, ppos, tmpbuf, len);
}
static int
proc_dodebug(ctl_table *table, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
char tmpbuf[20], c, *s;
char __user *p;
unsigned int value;
size_t left, len;
if ((*ppos && !write) || !*lenp) {
*lenp = 0;
return 0;
}
left = *lenp;
if (write) {
if (!access_ok(VERIFY_READ, buffer, left))
return -EFAULT;
p = buffer;
while (left && __get_user(c, p) >= 0 && isspace(c))
left--, p++;
if (!left)
goto done;
if (left > sizeof(tmpbuf) - 1)
return -EINVAL;
if (copy_from_user(tmpbuf, p, left))
return -EFAULT;
tmpbuf[left] = '\0';
for (s = tmpbuf, value = 0; '0' <= *s && *s <= '9'; s++, left--)
value = 10 * value + (*s - '0');
if (*s && !isspace(*s))
return -EINVAL;
while (left && isspace(*s))
left--, s++;
*(unsigned int *) table->data = value;
/* Display the RPC tasks on writing to rpc_debug */
if (strcmp(table->procname, "rpc_debug") == 0)
rpc_show_tasks(&init_net);
} else {
if (!access_ok(VERIFY_WRITE, buffer, left))
return -EFAULT;
len = sprintf(tmpbuf, "%d", *(unsigned int *) table->data);
if (len > left)
len = left;
if (__copy_to_user(buffer, tmpbuf, len))
return -EFAULT;
if ((left -= len) > 0) {
if (put_user('\n', (char __user *)buffer + len))
return -EFAULT;
left--;
}
}
done:
*lenp -= left;
*ppos += *lenp;
return 0;
}
static ctl_table debug_table[] = {
{
.procname = "rpc_debug",
.data = &rpc_debug,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dodebug
},
{
.procname = "nfs_debug",
.data = &nfs_debug,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dodebug
},
{
.procname = "nfsd_debug",
.data = &nfsd_debug,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dodebug
},
{
.procname = "nlm_debug",
.data = &nlm_debug,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dodebug
},
{
.procname = "transports",
.maxlen = 256,
.mode = 0444,
.proc_handler = proc_do_xprt,
},
{ }
};
static ctl_table sunrpc_table[] = {
{
.procname = "sunrpc",
.mode = 0555,
.child = debug_table
},
{ }
};
#endif
| gpl-2.0 |
oppo-source/Find7-5.1-kernel-source | drivers/net/wireless/ipw2x00/libipw_module.c | 7884 | 8960 | /*******************************************************************************
Copyright(c) 2004-2005 Intel Corporation. All rights reserved.
Portions of this file are based on the WEP enablement code provided by the
Host AP project hostap-drivers v0.1.3
Copyright (c) 2001-2002, SSH Communications Security Corp and Jouni Malinen
<j@w1.fi>
Copyright (c) 2002-2003, Jouni Malinen <j@w1.fi>
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., 59
Temple Place - Suite 330, Boston, MA 02111-1307, 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
*******************************************************************************/
#include <linux/compiler.h>
#include <linux/errno.h>
#include <linux/if_arp.h>
#include <linux/in6.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/proc_fs.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <linux/tcp.h>
#include <linux/types.h>
#include <linux/wireless.h>
#include <linux/etherdevice.h>
#include <asm/uaccess.h>
#include <net/net_namespace.h>
#include <net/arp.h>
#include "libipw.h"
#define DRV_DESCRIPTION "802.11 data/management/control stack"
#define DRV_NAME "libipw"
#define DRV_PROCNAME "ieee80211"
#define DRV_VERSION LIBIPW_VERSION
#define DRV_COPYRIGHT "Copyright (C) 2004-2005 Intel Corporation <jketreno@linux.intel.com>"
MODULE_VERSION(DRV_VERSION);
MODULE_DESCRIPTION(DRV_DESCRIPTION);
MODULE_AUTHOR(DRV_COPYRIGHT);
MODULE_LICENSE("GPL");
static struct cfg80211_ops libipw_config_ops = { };
static void *libipw_wiphy_privid = &libipw_wiphy_privid;
static int libipw_networks_allocate(struct libipw_device *ieee)
{
int i, j;
for (i = 0; i < MAX_NETWORK_COUNT; i++) {
ieee->networks[i] = kzalloc(sizeof(struct libipw_network),
GFP_KERNEL);
if (!ieee->networks[i]) {
LIBIPW_ERROR("Out of memory allocating beacons\n");
for (j = 0; j < i; j++)
kfree(ieee->networks[j]);
return -ENOMEM;
}
}
return 0;
}
void libipw_network_reset(struct libipw_network *network)
{
if (!network)
return;
if (network->ibss_dfs) {
kfree(network->ibss_dfs);
network->ibss_dfs = NULL;
}
}
static inline void libipw_networks_free(struct libipw_device *ieee)
{
int i;
for (i = 0; i < MAX_NETWORK_COUNT; i++) {
if (ieee->networks[i]->ibss_dfs)
kfree(ieee->networks[i]->ibss_dfs);
kfree(ieee->networks[i]);
}
}
void libipw_networks_age(struct libipw_device *ieee,
unsigned long age_secs)
{
struct libipw_network *network = NULL;
unsigned long flags;
unsigned long age_jiffies = msecs_to_jiffies(age_secs * MSEC_PER_SEC);
spin_lock_irqsave(&ieee->lock, flags);
list_for_each_entry(network, &ieee->network_list, list) {
network->last_scanned -= age_jiffies;
}
spin_unlock_irqrestore(&ieee->lock, flags);
}
EXPORT_SYMBOL(libipw_networks_age);
static void libipw_networks_initialize(struct libipw_device *ieee)
{
int i;
INIT_LIST_HEAD(&ieee->network_free_list);
INIT_LIST_HEAD(&ieee->network_list);
for (i = 0; i < MAX_NETWORK_COUNT; i++)
list_add_tail(&ieee->networks[i]->list,
&ieee->network_free_list);
}
int libipw_change_mtu(struct net_device *dev, int new_mtu)
{
if ((new_mtu < 68) || (new_mtu > LIBIPW_DATA_LEN))
return -EINVAL;
dev->mtu = new_mtu;
return 0;
}
EXPORT_SYMBOL(libipw_change_mtu);
struct net_device *alloc_libipw(int sizeof_priv, int monitor)
{
struct libipw_device *ieee;
struct net_device *dev;
int err;
LIBIPW_DEBUG_INFO("Initializing...\n");
dev = alloc_etherdev(sizeof(struct libipw_device) + sizeof_priv);
if (!dev)
goto failed;
ieee = netdev_priv(dev);
ieee->dev = dev;
if (!monitor) {
ieee->wdev.wiphy = wiphy_new(&libipw_config_ops, 0);
if (!ieee->wdev.wiphy) {
LIBIPW_ERROR("Unable to allocate wiphy.\n");
goto failed_free_netdev;
}
ieee->dev->ieee80211_ptr = &ieee->wdev;
ieee->wdev.iftype = NL80211_IFTYPE_STATION;
/* Fill-out wiphy structure bits we know... Not enough info
here to call set_wiphy_dev or set MAC address or channel info
-- have to do that in ->ndo_init... */
ieee->wdev.wiphy->privid = libipw_wiphy_privid;
ieee->wdev.wiphy->max_scan_ssids = 1;
ieee->wdev.wiphy->max_scan_ie_len = 0;
ieee->wdev.wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION)
| BIT(NL80211_IFTYPE_ADHOC);
}
err = libipw_networks_allocate(ieee);
if (err) {
LIBIPW_ERROR("Unable to allocate beacon storage: %d\n", err);
goto failed_free_wiphy;
}
libipw_networks_initialize(ieee);
/* Default fragmentation threshold is maximum payload size */
ieee->fts = DEFAULT_FTS;
ieee->rts = DEFAULT_FTS;
ieee->scan_age = DEFAULT_MAX_SCAN_AGE;
ieee->open_wep = 1;
/* Default to enabling full open WEP with host based encrypt/decrypt */
ieee->host_encrypt = 1;
ieee->host_decrypt = 1;
ieee->host_mc_decrypt = 1;
/* Host fragmentation in Open mode. Default is enabled.
* Note: host fragmentation is always enabled if host encryption
* is enabled. For cards can do hardware encryption, they must do
* hardware fragmentation as well. So we don't need a variable
* like host_enc_frag. */
ieee->host_open_frag = 1;
ieee->ieee802_1x = 1; /* Default to supporting 802.1x */
spin_lock_init(&ieee->lock);
lib80211_crypt_info_init(&ieee->crypt_info, dev->name, &ieee->lock);
ieee->wpa_enabled = 0;
ieee->drop_unencrypted = 0;
ieee->privacy_invoked = 0;
return dev;
failed_free_wiphy:
if (!monitor)
wiphy_free(ieee->wdev.wiphy);
failed_free_netdev:
free_netdev(dev);
failed:
return NULL;
}
EXPORT_SYMBOL(alloc_libipw);
void free_libipw(struct net_device *dev, int monitor)
{
struct libipw_device *ieee = netdev_priv(dev);
lib80211_crypt_info_free(&ieee->crypt_info);
libipw_networks_free(ieee);
/* free cfg80211 resources */
if (!monitor)
wiphy_free(ieee->wdev.wiphy);
free_netdev(dev);
}
EXPORT_SYMBOL(free_libipw);
#ifdef CONFIG_LIBIPW_DEBUG
static int debug = 0;
u32 libipw_debug_level = 0;
EXPORT_SYMBOL_GPL(libipw_debug_level);
static struct proc_dir_entry *libipw_proc = NULL;
static int debug_level_proc_show(struct seq_file *m, void *v)
{
seq_printf(m, "0x%08X\n", libipw_debug_level);
return 0;
}
static int debug_level_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, debug_level_proc_show, NULL);
}
static ssize_t debug_level_proc_write(struct file *file,
const char __user *buffer, size_t count, loff_t *pos)
{
char buf[] = "0x00000000\n";
size_t len = min(sizeof(buf) - 1, count);
unsigned long val;
if (copy_from_user(buf, buffer, len))
return count;
buf[len] = 0;
if (sscanf(buf, "%li", &val) != 1)
printk(KERN_INFO DRV_NAME
": %s is not in hex or decimal form.\n", buf);
else
libipw_debug_level = val;
return strnlen(buf, len);
}
static const struct file_operations debug_level_proc_fops = {
.owner = THIS_MODULE,
.open = debug_level_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.write = debug_level_proc_write,
};
#endif /* CONFIG_LIBIPW_DEBUG */
static int __init libipw_init(void)
{
#ifdef CONFIG_LIBIPW_DEBUG
struct proc_dir_entry *e;
libipw_debug_level = debug;
libipw_proc = proc_mkdir(DRV_PROCNAME, init_net.proc_net);
if (libipw_proc == NULL) {
LIBIPW_ERROR("Unable to create " DRV_PROCNAME
" proc directory\n");
return -EIO;
}
e = proc_create("debug_level", S_IRUGO | S_IWUSR, libipw_proc,
&debug_level_proc_fops);
if (!e) {
remove_proc_entry(DRV_PROCNAME, init_net.proc_net);
libipw_proc = NULL;
return -EIO;
}
#endif /* CONFIG_LIBIPW_DEBUG */
printk(KERN_INFO DRV_NAME ": " DRV_DESCRIPTION ", " DRV_VERSION "\n");
printk(KERN_INFO DRV_NAME ": " DRV_COPYRIGHT "\n");
return 0;
}
static void __exit libipw_exit(void)
{
#ifdef CONFIG_LIBIPW_DEBUG
if (libipw_proc) {
remove_proc_entry("debug_level", libipw_proc);
remove_proc_entry(DRV_PROCNAME, init_net.proc_net);
libipw_proc = NULL;
}
#endif /* CONFIG_LIBIPW_DEBUG */
}
#ifdef CONFIG_LIBIPW_DEBUG
#include <linux/moduleparam.h>
module_param(debug, int, 0444);
MODULE_PARM_DESC(debug, "debug output mask");
#endif /* CONFIG_LIBIPW_DEBUG */
module_exit(libipw_exit);
module_init(libipw_init);
| gpl-2.0 |
cphelps76/DEMENTED_kernel_grouper | drivers/eisa/eisa-bus.c | 9420 | 10851 | /*
* EISA bus support functions for sysfs.
*
* (C) 2002, 2003 Marc Zyngier <maz@wild-wind.fr.eu.org>
*
* This code is released under the GPL version 2.
*/
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/eisa.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/ioport.h>
#include <asm/io.h>
#define SLOT_ADDRESS(r,n) (r->bus_base_addr + (0x1000 * n))
#define EISA_DEVINFO(i,s) { .id = { .sig = i }, .name = s }
struct eisa_device_info {
struct eisa_device_id id;
char name[50];
};
#ifdef CONFIG_EISA_NAMES
static struct eisa_device_info __initdata eisa_table[] = {
#include "devlist.h"
};
#define EISA_INFOS (sizeof (eisa_table) / (sizeof (struct eisa_device_info)))
#endif
#define EISA_MAX_FORCED_DEV 16
static int enable_dev[EISA_MAX_FORCED_DEV];
static unsigned int enable_dev_count;
static int disable_dev[EISA_MAX_FORCED_DEV];
static unsigned int disable_dev_count;
static int is_forced_dev(int *forced_tab,
int forced_count,
struct eisa_root_device *root,
struct eisa_device *edev)
{
int i, x;
for (i = 0; i < forced_count; i++) {
x = (root->bus_nr << 8) | edev->slot;
if (forced_tab[i] == x)
return 1;
}
return 0;
}
static void __init eisa_name_device(struct eisa_device *edev)
{
#ifdef CONFIG_EISA_NAMES
int i;
for (i = 0; i < EISA_INFOS; i++) {
if (!strcmp(edev->id.sig, eisa_table[i].id.sig)) {
strlcpy(edev->pretty_name,
eisa_table[i].name,
sizeof(edev->pretty_name));
return;
}
}
/* No name was found */
sprintf(edev->pretty_name, "EISA device %.7s", edev->id.sig);
#endif
}
static char __init *decode_eisa_sig(unsigned long addr)
{
static char sig_str[EISA_SIG_LEN];
u8 sig[4];
u16 rev;
int i;
for (i = 0; i < 4; i++) {
#ifdef CONFIG_EISA_VLB_PRIMING
/*
* This ugly stuff is used to wake up VL-bus cards
* (AHA-284x is the only known example), so we can
* read the EISA id.
*
* Thankfully, this only exists on x86...
*/
outb(0x80 + i, addr);
#endif
sig[i] = inb(addr + i);
if (!i && (sig[0] & 0x80))
return NULL;
}
sig_str[0] = ((sig[0] >> 2) & 0x1f) + ('A' - 1);
sig_str[1] = (((sig[0] & 3) << 3) | (sig[1] >> 5)) + ('A' - 1);
sig_str[2] = (sig[1] & 0x1f) + ('A' - 1);
rev = (sig[2] << 8) | sig[3];
sprintf(sig_str + 3, "%04X", rev);
return sig_str;
}
static int eisa_bus_match(struct device *dev, struct device_driver *drv)
{
struct eisa_device *edev = to_eisa_device(dev);
struct eisa_driver *edrv = to_eisa_driver(drv);
const struct eisa_device_id *eids = edrv->id_table;
if (!eids)
return 0;
while (strlen(eids->sig)) {
if (!strcmp(eids->sig, edev->id.sig) &&
edev->state & EISA_CONFIG_ENABLED) {
edev->id.driver_data = eids->driver_data;
return 1;
}
eids++;
}
return 0;
}
static int eisa_bus_uevent(struct device *dev, struct kobj_uevent_env *env)
{
struct eisa_device *edev = to_eisa_device(dev);
add_uevent_var(env, "MODALIAS=" EISA_DEVICE_MODALIAS_FMT, edev->id.sig);
return 0;
}
struct bus_type eisa_bus_type = {
.name = "eisa",
.match = eisa_bus_match,
.uevent = eisa_bus_uevent,
};
EXPORT_SYMBOL(eisa_bus_type);
int eisa_driver_register(struct eisa_driver *edrv)
{
edrv->driver.bus = &eisa_bus_type;
return driver_register(&edrv->driver);
}
EXPORT_SYMBOL(eisa_driver_register);
void eisa_driver_unregister(struct eisa_driver *edrv)
{
driver_unregister(&edrv->driver);
}
EXPORT_SYMBOL(eisa_driver_unregister);
static ssize_t eisa_show_sig(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct eisa_device *edev = to_eisa_device(dev);
return sprintf(buf, "%s\n", edev->id.sig);
}
static DEVICE_ATTR(signature, S_IRUGO, eisa_show_sig, NULL);
static ssize_t eisa_show_state(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct eisa_device *edev = to_eisa_device(dev);
return sprintf(buf, "%d\n", edev->state & EISA_CONFIG_ENABLED);
}
static DEVICE_ATTR(enabled, S_IRUGO, eisa_show_state, NULL);
static ssize_t eisa_show_modalias(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct eisa_device *edev = to_eisa_device(dev);
return sprintf(buf, EISA_DEVICE_MODALIAS_FMT "\n", edev->id.sig);
}
static DEVICE_ATTR(modalias, S_IRUGO, eisa_show_modalias, NULL);
static int __init eisa_init_device(struct eisa_root_device *root,
struct eisa_device *edev,
int slot)
{
char *sig;
unsigned long sig_addr;
int i;
sig_addr = SLOT_ADDRESS(root, slot) + EISA_VENDOR_ID_OFFSET;
sig = decode_eisa_sig(sig_addr);
if (!sig)
return -1; /* No EISA device here */
memcpy(edev->id.sig, sig, EISA_SIG_LEN);
edev->slot = slot;
edev->state = inb(SLOT_ADDRESS(root, slot) + EISA_CONFIG_OFFSET)
& EISA_CONFIG_ENABLED;
edev->base_addr = SLOT_ADDRESS(root, slot);
edev->dma_mask = root->dma_mask; /* Default DMA mask */
eisa_name_device(edev);
edev->dev.parent = root->dev;
edev->dev.bus = &eisa_bus_type;
edev->dev.dma_mask = &edev->dma_mask;
edev->dev.coherent_dma_mask = edev->dma_mask;
dev_set_name(&edev->dev, "%02X:%02X", root->bus_nr, slot);
for (i = 0; i < EISA_MAX_RESOURCES; i++) {
#ifdef CONFIG_EISA_NAMES
edev->res[i].name = edev->pretty_name;
#else
edev->res[i].name = edev->id.sig;
#endif
}
if (is_forced_dev(enable_dev, enable_dev_count, root, edev))
edev->state = EISA_CONFIG_ENABLED | EISA_CONFIG_FORCED;
if (is_forced_dev(disable_dev, disable_dev_count, root, edev))
edev->state = EISA_CONFIG_FORCED;
return 0;
}
static int __init eisa_register_device(struct eisa_device *edev)
{
int rc = device_register(&edev->dev);
if (rc)
return rc;
rc = device_create_file(&edev->dev, &dev_attr_signature);
if (rc)
goto err_devreg;
rc = device_create_file(&edev->dev, &dev_attr_enabled);
if (rc)
goto err_sig;
rc = device_create_file(&edev->dev, &dev_attr_modalias);
if (rc)
goto err_enab;
return 0;
err_enab:
device_remove_file(&edev->dev, &dev_attr_enabled);
err_sig:
device_remove_file(&edev->dev, &dev_attr_signature);
err_devreg:
device_unregister(&edev->dev);
return rc;
}
static int __init eisa_request_resources(struct eisa_root_device *root,
struct eisa_device *edev,
int slot)
{
int i;
for (i = 0; i < EISA_MAX_RESOURCES; i++) {
/* Don't register resource for slot 0, since this is
* very likely to fail... :-( Instead, grab the EISA
* id, now we can display something in /proc/ioports.
*/
/* Only one region for mainboard */
if (!slot && i > 0) {
edev->res[i].start = edev->res[i].end = 0;
continue;
}
if (slot) {
edev->res[i].name = NULL;
edev->res[i].start = SLOT_ADDRESS(root, slot)
+ (i * 0x400);
edev->res[i].end = edev->res[i].start + 0xff;
edev->res[i].flags = IORESOURCE_IO;
} else {
edev->res[i].name = NULL;
edev->res[i].start = SLOT_ADDRESS(root, slot)
+ EISA_VENDOR_ID_OFFSET;
edev->res[i].end = edev->res[i].start + 3;
edev->res[i].flags = IORESOURCE_BUSY;
}
if (request_resource(root->res, &edev->res[i]))
goto failed;
}
return 0;
failed:
while (--i >= 0)
release_resource(&edev->res[i]);
return -1;
}
static void __init eisa_release_resources(struct eisa_device *edev)
{
int i;
for (i = 0; i < EISA_MAX_RESOURCES; i++)
if (edev->res[i].start || edev->res[i].end)
release_resource(&edev->res[i]);
}
static int __init eisa_probe(struct eisa_root_device *root)
{
int i, c;
struct eisa_device *edev;
printk(KERN_INFO "EISA: Probing bus %d at %s\n",
root->bus_nr, dev_name(root->dev));
/* First try to get hold of slot 0. If there is no device
* here, simply fail, unless root->force_probe is set. */
edev = kzalloc(sizeof(*edev), GFP_KERNEL);
if (!edev) {
printk(KERN_ERR "EISA: Couldn't allocate mainboard slot\n");
return -ENOMEM;
}
if (eisa_request_resources(root, edev, 0)) {
printk(KERN_WARNING \
"EISA: Cannot allocate resource for mainboard\n");
kfree(edev);
if (!root->force_probe)
return -EBUSY;
goto force_probe;
}
if (eisa_init_device(root, edev, 0)) {
eisa_release_resources(edev);
kfree(edev);
if (!root->force_probe)
return -ENODEV;
goto force_probe;
}
printk(KERN_INFO "EISA: Mainboard %s detected.\n", edev->id.sig);
if (eisa_register_device(edev)) {
printk(KERN_ERR "EISA: Failed to register %s\n",
edev->id.sig);
eisa_release_resources(edev);
kfree(edev);
}
force_probe:
for (c = 0, i = 1; i <= root->slots; i++) {
edev = kzalloc(sizeof(*edev), GFP_KERNEL);
if (!edev) {
printk(KERN_ERR "EISA: Out of memory for slot %d\n", i);
continue;
}
if (eisa_request_resources(root, edev, i)) {
printk(KERN_WARNING \
"Cannot allocate resource for EISA slot %d\n",
i);
kfree(edev);
continue;
}
if (eisa_init_device(root, edev, i)) {
eisa_release_resources(edev);
kfree(edev);
continue;
}
printk(KERN_INFO "EISA: slot %d : %s detected",
i, edev->id.sig);
switch (edev->state) {
case EISA_CONFIG_ENABLED | EISA_CONFIG_FORCED:
printk(" (forced enabled)");
break;
case EISA_CONFIG_FORCED:
printk(" (forced disabled)");
break;
case 0:
printk(" (disabled)");
break;
}
printk (".\n");
c++;
if (eisa_register_device(edev)) {
printk(KERN_ERR "EISA: Failed to register %s\n",
edev->id.sig);
eisa_release_resources(edev);
kfree(edev);
}
}
printk(KERN_INFO "EISA: Detected %d card%s.\n", c, c == 1 ? "" : "s");
return 0;
}
static struct resource eisa_root_res = {
.name = "EISA root resource",
.start = 0,
.end = 0xffffffff,
.flags = IORESOURCE_IO,
};
static int eisa_bus_count;
int __init eisa_root_register(struct eisa_root_device *root)
{
int err;
/* Use our own resources to check if this bus base address has
* been already registered. This prevents the virtual root
* device from registering after the real one has, for
* example... */
root->eisa_root_res.name = eisa_root_res.name;
root->eisa_root_res.start = root->res->start;
root->eisa_root_res.end = root->res->end;
root->eisa_root_res.flags = IORESOURCE_BUSY;
err = request_resource(&eisa_root_res, &root->eisa_root_res);
if (err)
return err;
root->bus_nr = eisa_bus_count++;
err = eisa_probe(root);
if (err)
release_resource(&root->eisa_root_res);
return err;
}
static int __init eisa_init(void)
{
int r;
r = bus_register(&eisa_bus_type);
if (r)
return r;
printk(KERN_INFO "EISA bus registered\n");
return 0;
}
module_param_array(enable_dev, int, &enable_dev_count, 0444);
module_param_array(disable_dev, int, &disable_dev_count, 0444);
postcore_initcall(eisa_init);
int EISA_bus; /* for legacy drivers */
EXPORT_SYMBOL(EISA_bus);
| gpl-2.0 |
tobigun/samsung-kernel-smg800m | drivers/scsi/aic7xxx/aicasm/aicasm_symbol.c | 12748 | 16088 | /*
* Aic7xxx SCSI host adapter firmware assembler symbol table implementation
*
* Copyright (c) 1997 Justin T. Gibbs.
* Copyright (c) 2002 Adaptec Inc.
* 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.
*
* $Id: //depot/aic7xxx/aic7xxx/aicasm/aicasm_symbol.c#24 $
*
* $FreeBSD$
*/
#include <sys/types.h>
#ifdef __linux__
#include "aicdb.h"
#else
#include <db.h>
#endif
#include <fcntl.h>
#include <inttypes.h>
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include "aicasm_symbol.h"
#include "aicasm.h"
static DB *symtable;
symbol_t *
symbol_create(char *name)
{
symbol_t *new_symbol;
new_symbol = (symbol_t *)malloc(sizeof(symbol_t));
if (new_symbol == NULL) {
perror("Unable to create new symbol");
exit(EX_SOFTWARE);
}
memset(new_symbol, 0, sizeof(*new_symbol));
new_symbol->name = strdup(name);
if (new_symbol->name == NULL)
stop("Unable to strdup symbol name", EX_SOFTWARE);
new_symbol->type = UNINITIALIZED;
new_symbol->count = 1;
return (new_symbol);
}
void
symbol_delete(symbol_t *symbol)
{
if (symtable != NULL) {
DBT key;
key.data = symbol->name;
key.size = strlen(symbol->name);
symtable->del(symtable, &key, /*flags*/0);
}
switch(symbol->type) {
case SCBLOC:
case SRAMLOC:
case REGISTER:
if (symbol->info.rinfo != NULL)
free(symbol->info.rinfo);
break;
case ALIAS:
if (symbol->info.ainfo != NULL)
free(symbol->info.ainfo);
break;
case MASK:
case FIELD:
case ENUM:
case ENUM_ENTRY:
if (symbol->info.finfo != NULL) {
symlist_free(&symbol->info.finfo->symrefs);
free(symbol->info.finfo);
}
break;
case DOWNLOAD_CONST:
case CONST:
if (symbol->info.cinfo != NULL)
free(symbol->info.cinfo);
break;
case LABEL:
if (symbol->info.linfo != NULL)
free(symbol->info.linfo);
break;
case UNINITIALIZED:
default:
break;
}
free(symbol->name);
free(symbol);
}
void
symtable_open()
{
symtable = dbopen(/*filename*/NULL,
O_CREAT | O_NONBLOCK | O_RDWR, /*mode*/0, DB_HASH,
/*openinfo*/NULL);
if (symtable == NULL) {
perror("Symbol table creation failed");
exit(EX_SOFTWARE);
/* NOTREACHED */
}
}
void
symtable_close()
{
if (symtable != NULL) {
DBT key;
DBT data;
while (symtable->seq(symtable, &key, &data, R_FIRST) == 0) {
symbol_t *stored_ptr;
memcpy(&stored_ptr, data.data, sizeof(stored_ptr));
symbol_delete(stored_ptr);
}
symtable->close(symtable);
}
}
/*
* The semantics of get is to return an uninitialized symbol entry
* if a lookup fails.
*/
symbol_t *
symtable_get(char *name)
{
symbol_t *stored_ptr;
DBT key;
DBT data;
int retval;
key.data = (void *)name;
key.size = strlen(name);
if ((retval = symtable->get(symtable, &key, &data, /*flags*/0)) != 0) {
if (retval == -1) {
perror("Symbol table get operation failed");
exit(EX_SOFTWARE);
/* NOTREACHED */
} else if (retval == 1) {
/* Symbol wasn't found, so create a new one */
symbol_t *new_symbol;
new_symbol = symbol_create(name);
data.data = &new_symbol;
data.size = sizeof(new_symbol);
if (symtable->put(symtable, &key, &data,
/*flags*/0) !=0) {
perror("Symtable put failed");
exit(EX_SOFTWARE);
}
return (new_symbol);
} else {
perror("Unexpected return value from db get routine");
exit(EX_SOFTWARE);
/* NOTREACHED */
}
}
memcpy(&stored_ptr, data.data, sizeof(stored_ptr));
stored_ptr->count++;
data.data = &stored_ptr;
if (symtable->put(symtable, &key, &data, /*flags*/0) !=0) {
perror("Symtable put failed");
exit(EX_SOFTWARE);
}
return (stored_ptr);
}
symbol_node_t *
symlist_search(symlist_t *symlist, char *symname)
{
symbol_node_t *curnode;
curnode = SLIST_FIRST(symlist);
while(curnode != NULL) {
if (strcmp(symname, curnode->symbol->name) == 0)
break;
curnode = SLIST_NEXT(curnode, links);
}
return (curnode);
}
void
symlist_add(symlist_t *symlist, symbol_t *symbol, int how)
{
symbol_node_t *newnode;
newnode = (symbol_node_t *)malloc(sizeof(symbol_node_t));
if (newnode == NULL) {
stop("symlist_add: Unable to malloc symbol_node", EX_SOFTWARE);
/* NOTREACHED */
}
newnode->symbol = symbol;
if (how == SYMLIST_SORT) {
symbol_node_t *curnode;
int field;
field = FALSE;
switch(symbol->type) {
case REGISTER:
case SCBLOC:
case SRAMLOC:
break;
case FIELD:
case MASK:
case ENUM:
case ENUM_ENTRY:
field = TRUE;
break;
default:
stop("symlist_add: Invalid symbol type for sorting",
EX_SOFTWARE);
/* NOTREACHED */
}
curnode = SLIST_FIRST(symlist);
if (curnode == NULL
|| (field
&& (curnode->symbol->type > newnode->symbol->type
|| (curnode->symbol->type == newnode->symbol->type
&& (curnode->symbol->info.finfo->value >
newnode->symbol->info.finfo->value))))
|| (!field && (curnode->symbol->info.rinfo->address >
newnode->symbol->info.rinfo->address))) {
SLIST_INSERT_HEAD(symlist, newnode, links);
return;
}
while (1) {
if (SLIST_NEXT(curnode, links) == NULL) {
SLIST_INSERT_AFTER(curnode, newnode,
links);
break;
} else {
symbol_t *cursymbol;
cursymbol = SLIST_NEXT(curnode, links)->symbol;
if ((field
&& (cursymbol->type > symbol->type
|| (cursymbol->type == symbol->type
&& (cursymbol->info.finfo->value >
symbol->info.finfo->value))))
|| (!field
&& (cursymbol->info.rinfo->address >
symbol->info.rinfo->address))) {
SLIST_INSERT_AFTER(curnode, newnode,
links);
break;
}
}
curnode = SLIST_NEXT(curnode, links);
}
} else {
SLIST_INSERT_HEAD(symlist, newnode, links);
}
}
void
symlist_free(symlist_t *symlist)
{
symbol_node_t *node1, *node2;
node1 = SLIST_FIRST(symlist);
while (node1 != NULL) {
node2 = SLIST_NEXT(node1, links);
free(node1);
node1 = node2;
}
SLIST_INIT(symlist);
}
void
symlist_merge(symlist_t *symlist_dest, symlist_t *symlist_src1,
symlist_t *symlist_src2)
{
symbol_node_t *node;
*symlist_dest = *symlist_src1;
while((node = SLIST_FIRST(symlist_src2)) != NULL) {
SLIST_REMOVE_HEAD(symlist_src2, links);
SLIST_INSERT_HEAD(symlist_dest, node, links);
}
/* These are now empty */
SLIST_INIT(symlist_src1);
SLIST_INIT(symlist_src2);
}
void
aic_print_file_prologue(FILE *ofile)
{
if (ofile == NULL)
return;
fprintf(ofile,
"/*\n"
" * DO NOT EDIT - This file is automatically generated\n"
" * from the following source files:\n"
" *\n"
"%s */\n",
versions);
}
void
aic_print_include(FILE *dfile, char *include_file)
{
if (dfile == NULL)
return;
fprintf(dfile, "\n#include \"%s\"\n\n", include_file);
}
void
aic_print_reg_dump_types(FILE *ofile)
{
if (ofile == NULL)
return;
fprintf(ofile,
"typedef int (%sreg_print_t)(u_int, u_int *, u_int);\n"
"typedef struct %sreg_parse_entry {\n"
" char *name;\n"
" uint8_t value;\n"
" uint8_t mask;\n"
"} %sreg_parse_entry_t;\n"
"\n",
prefix, prefix, prefix);
}
static void
aic_print_reg_dump_start(FILE *dfile, symbol_node_t *regnode)
{
if (dfile == NULL)
return;
fprintf(dfile,
"static const %sreg_parse_entry_t %s_parse_table[] = {\n",
prefix,
regnode->symbol->name);
}
static void
aic_print_reg_dump_end(FILE *ofile, FILE *dfile,
symbol_node_t *regnode, u_int num_entries)
{
char *lower_name;
char *letter;
lower_name = strdup(regnode->symbol->name);
if (lower_name == NULL)
stop("Unable to strdup symbol name", EX_SOFTWARE);
for (letter = lower_name; *letter != '\0'; letter++)
*letter = tolower(*letter);
if (dfile != NULL) {
if (num_entries != 0)
fprintf(dfile,
"\n"
"};\n"
"\n");
fprintf(dfile,
"int\n"
"%s%s_print(u_int regvalue, u_int *cur_col, u_int wrap)\n"
"{\n"
" return (%sprint_register(%s%s, %d, \"%s\",\n"
" 0x%02x, regvalue, cur_col, wrap));\n"
"}\n"
"\n",
prefix,
lower_name,
prefix,
num_entries != 0 ? regnode->symbol->name : "NULL",
num_entries != 0 ? "_parse_table" : "",
num_entries,
regnode->symbol->name,
regnode->symbol->info.rinfo->address);
}
fprintf(ofile,
"#if AIC_DEBUG_REGISTERS\n"
"%sreg_print_t %s%s_print;\n"
"#else\n"
"#define %s%s_print(regvalue, cur_col, wrap) \\\n"
" %sprint_register(NULL, 0, \"%s\", 0x%02x, regvalue, cur_col, wrap)\n"
"#endif\n"
"\n",
prefix,
prefix,
lower_name,
prefix,
lower_name,
prefix,
regnode->symbol->name,
regnode->symbol->info.rinfo->address);
}
static void
aic_print_reg_dump_entry(FILE *dfile, symbol_node_t *curnode)
{
int num_tabs;
if (dfile == NULL)
return;
fprintf(dfile,
" { \"%s\",",
curnode->symbol->name);
num_tabs = 3 - (strlen(curnode->symbol->name) + 5) / 8;
while (num_tabs-- > 0)
fputc('\t', dfile);
fprintf(dfile, "0x%02x, 0x%02x }",
curnode->symbol->info.finfo->value,
curnode->symbol->info.finfo->mask);
}
void
symtable_dump(FILE *ofile, FILE *dfile)
{
/*
* Sort the registers by address with a simple insertion sort.
* Put bitmasks next to the first register that defines them.
* Put constants at the end.
*/
symlist_t registers;
symlist_t masks;
symlist_t constants;
symlist_t download_constants;
symlist_t aliases;
symlist_t exported_labels;
symbol_node_t *curnode;
symbol_node_t *regnode;
DBT key;
DBT data;
int flag;
int reg_count = 0, reg_used = 0;
u_int i;
if (symtable == NULL)
return;
SLIST_INIT(®isters);
SLIST_INIT(&masks);
SLIST_INIT(&constants);
SLIST_INIT(&download_constants);
SLIST_INIT(&aliases);
SLIST_INIT(&exported_labels);
flag = R_FIRST;
while (symtable->seq(symtable, &key, &data, flag) == 0) {
symbol_t *cursym;
memcpy(&cursym, data.data, sizeof(cursym));
switch(cursym->type) {
case REGISTER:
case SCBLOC:
case SRAMLOC:
symlist_add(®isters, cursym, SYMLIST_SORT);
break;
case MASK:
case FIELD:
case ENUM:
case ENUM_ENTRY:
symlist_add(&masks, cursym, SYMLIST_SORT);
break;
case CONST:
symlist_add(&constants, cursym,
SYMLIST_INSERT_HEAD);
break;
case DOWNLOAD_CONST:
symlist_add(&download_constants, cursym,
SYMLIST_INSERT_HEAD);
break;
case ALIAS:
symlist_add(&aliases, cursym,
SYMLIST_INSERT_HEAD);
break;
case LABEL:
if (cursym->info.linfo->exported == 0)
break;
symlist_add(&exported_labels, cursym,
SYMLIST_INSERT_HEAD);
break;
default:
break;
}
flag = R_NEXT;
}
/* Register dianostic functions/declarations first. */
aic_print_file_prologue(ofile);
aic_print_reg_dump_types(ofile);
aic_print_file_prologue(dfile);
aic_print_include(dfile, stock_include_file);
SLIST_FOREACH(curnode, ®isters, links) {
if (curnode->symbol->dont_generate_debug_code)
continue;
switch(curnode->symbol->type) {
case REGISTER:
case SCBLOC:
case SRAMLOC:
{
symlist_t *fields;
symbol_node_t *fieldnode;
int num_entries;
num_entries = 0;
reg_count++;
if (curnode->symbol->count == 1)
break;
fields = &curnode->symbol->info.rinfo->fields;
SLIST_FOREACH(fieldnode, fields, links) {
if (num_entries == 0)
aic_print_reg_dump_start(dfile,
curnode);
else if (dfile != NULL)
fputs(",\n", dfile);
num_entries++;
aic_print_reg_dump_entry(dfile, fieldnode);
}
aic_print_reg_dump_end(ofile, dfile,
curnode, num_entries);
reg_used++;
}
default:
break;
}
}
fprintf(stderr, "%s: %d of %d register definitions used\n", appname,
reg_used, reg_count);
/* Fold in the masks and bits */
while (SLIST_FIRST(&masks) != NULL) {
char *regname;
curnode = SLIST_FIRST(&masks);
SLIST_REMOVE_HEAD(&masks, links);
regnode = SLIST_FIRST(&curnode->symbol->info.finfo->symrefs);
regname = regnode->symbol->name;
regnode = symlist_search(®isters, regname);
SLIST_INSERT_AFTER(regnode, curnode, links);
}
/* Add the aliases */
while (SLIST_FIRST(&aliases) != NULL) {
char *regname;
curnode = SLIST_FIRST(&aliases);
SLIST_REMOVE_HEAD(&aliases, links);
regname = curnode->symbol->info.ainfo->parent->name;
regnode = symlist_search(®isters, regname);
SLIST_INSERT_AFTER(regnode, curnode, links);
}
/* Output generated #defines. */
while (SLIST_FIRST(®isters) != NULL) {
symbol_node_t *curnode;
u_int value;
char *tab_str;
char *tab_str2;
curnode = SLIST_FIRST(®isters);
SLIST_REMOVE_HEAD(®isters, links);
switch(curnode->symbol->type) {
case REGISTER:
case SCBLOC:
case SRAMLOC:
fprintf(ofile, "\n");
value = curnode->symbol->info.rinfo->address;
tab_str = "\t";
tab_str2 = "\t\t";
break;
case ALIAS:
{
symbol_t *parent;
parent = curnode->symbol->info.ainfo->parent;
value = parent->info.rinfo->address;
tab_str = "\t";
tab_str2 = "\t\t";
break;
}
case MASK:
case FIELD:
case ENUM:
case ENUM_ENTRY:
value = curnode->symbol->info.finfo->value;
tab_str = "\t\t";
tab_str2 = "\t";
break;
default:
value = 0; /* Quiet compiler */
tab_str = NULL;
tab_str2 = NULL;
stop("symtable_dump: Invalid symbol type "
"encountered", EX_SOFTWARE);
break;
}
fprintf(ofile, "#define%s%-16s%s0x%02x\n",
tab_str, curnode->symbol->name, tab_str2,
value);
free(curnode);
}
fprintf(ofile, "\n\n");
while (SLIST_FIRST(&constants) != NULL) {
symbol_node_t *curnode;
curnode = SLIST_FIRST(&constants);
SLIST_REMOVE_HEAD(&constants, links);
fprintf(ofile, "#define\t%-8s\t0x%02x\n",
curnode->symbol->name,
curnode->symbol->info.cinfo->value);
free(curnode);
}
fprintf(ofile, "\n\n/* Downloaded Constant Definitions */\n");
for (i = 0; SLIST_FIRST(&download_constants) != NULL; i++) {
symbol_node_t *curnode;
curnode = SLIST_FIRST(&download_constants);
SLIST_REMOVE_HEAD(&download_constants, links);
fprintf(ofile, "#define\t%-8s\t0x%02x\n",
curnode->symbol->name,
curnode->symbol->info.cinfo->value);
free(curnode);
}
fprintf(ofile, "#define\tDOWNLOAD_CONST_COUNT\t0x%02x\n", i);
fprintf(ofile, "\n\n/* Exported Labels */\n");
while (SLIST_FIRST(&exported_labels) != NULL) {
symbol_node_t *curnode;
curnode = SLIST_FIRST(&exported_labels);
SLIST_REMOVE_HEAD(&exported_labels, links);
fprintf(ofile, "#define\tLABEL_%-8s\t0x%02x\n",
curnode->symbol->name,
curnode->symbol->info.linfo->address);
free(curnode);
}
}
| gpl-2.0 |
omnirom/android_kernel_huawei_angler | drivers/char/agp/compat_ioctl.c | 12748 | 7555 | /*
* AGPGART driver frontend compatibility ioctls
* Copyright (C) 2004 Silicon Graphics, Inc.
* Copyright (C) 2002-2003 Dave Jones
* Copyright (C) 1999 Jeff Hartmann
* Copyright (C) 1999 Precision Insight, Inc.
* Copyright (C) 1999 Xi Graphics, 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
* JEFF HARTMANN, OR ANY OTHER CONTRIBUTORS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/fs.h>
#include <linux/agpgart.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include "agp.h"
#include "compat_ioctl.h"
static int compat_agpioc_info_wrap(struct agp_file_private *priv, void __user *arg)
{
struct agp_info32 userinfo;
struct agp_kern_info kerninfo;
agp_copy_info(agp_bridge, &kerninfo);
userinfo.version.major = kerninfo.version.major;
userinfo.version.minor = kerninfo.version.minor;
userinfo.bridge_id = kerninfo.device->vendor |
(kerninfo.device->device << 16);
userinfo.agp_mode = kerninfo.mode;
userinfo.aper_base = (compat_long_t)kerninfo.aper_base;
userinfo.aper_size = kerninfo.aper_size;
userinfo.pg_total = userinfo.pg_system = kerninfo.max_memory;
userinfo.pg_used = kerninfo.current_memory;
if (copy_to_user(arg, &userinfo, sizeof(userinfo)))
return -EFAULT;
return 0;
}
static int compat_agpioc_reserve_wrap(struct agp_file_private *priv, void __user *arg)
{
struct agp_region32 ureserve;
struct agp_region kreserve;
struct agp_client *client;
struct agp_file_private *client_priv;
DBG("");
if (copy_from_user(&ureserve, arg, sizeof(ureserve)))
return -EFAULT;
if ((unsigned) ureserve.seg_count >= ~0U/sizeof(struct agp_segment32))
return -EFAULT;
kreserve.pid = ureserve.pid;
kreserve.seg_count = ureserve.seg_count;
client = agp_find_client_by_pid(kreserve.pid);
if (kreserve.seg_count == 0) {
/* remove a client */
client_priv = agp_find_private(kreserve.pid);
if (client_priv != NULL) {
set_bit(AGP_FF_IS_CLIENT, &client_priv->access_flags);
set_bit(AGP_FF_IS_VALID, &client_priv->access_flags);
}
if (client == NULL) {
/* client is already removed */
return 0;
}
return agp_remove_client(kreserve.pid);
} else {
struct agp_segment32 *usegment;
struct agp_segment *ksegment;
int seg;
if (ureserve.seg_count >= 16384)
return -EINVAL;
usegment = kmalloc(sizeof(*usegment) * ureserve.seg_count, GFP_KERNEL);
if (!usegment)
return -ENOMEM;
ksegment = kmalloc(sizeof(*ksegment) * kreserve.seg_count, GFP_KERNEL);
if (!ksegment) {
kfree(usegment);
return -ENOMEM;
}
if (copy_from_user(usegment, (void __user *) ureserve.seg_list,
sizeof(*usegment) * ureserve.seg_count)) {
kfree(usegment);
kfree(ksegment);
return -EFAULT;
}
for (seg = 0; seg < ureserve.seg_count; seg++) {
ksegment[seg].pg_start = usegment[seg].pg_start;
ksegment[seg].pg_count = usegment[seg].pg_count;
ksegment[seg].prot = usegment[seg].prot;
}
kfree(usegment);
kreserve.seg_list = ksegment;
if (client == NULL) {
/* Create the client and add the segment */
client = agp_create_client(kreserve.pid);
if (client == NULL) {
kfree(ksegment);
return -ENOMEM;
}
client_priv = agp_find_private(kreserve.pid);
if (client_priv != NULL) {
set_bit(AGP_FF_IS_CLIENT, &client_priv->access_flags);
set_bit(AGP_FF_IS_VALID, &client_priv->access_flags);
}
}
return agp_create_segment(client, &kreserve);
}
/* Will never really happen */
return -EINVAL;
}
static int compat_agpioc_allocate_wrap(struct agp_file_private *priv, void __user *arg)
{
struct agp_memory *memory;
struct agp_allocate32 alloc;
DBG("");
if (copy_from_user(&alloc, arg, sizeof(alloc)))
return -EFAULT;
memory = agp_allocate_memory_wrap(alloc.pg_count, alloc.type);
if (memory == NULL)
return -ENOMEM;
alloc.key = memory->key;
alloc.physical = memory->physical;
if (copy_to_user(arg, &alloc, sizeof(alloc))) {
agp_free_memory_wrap(memory);
return -EFAULT;
}
return 0;
}
static int compat_agpioc_bind_wrap(struct agp_file_private *priv, void __user *arg)
{
struct agp_bind32 bind_info;
struct agp_memory *memory;
DBG("");
if (copy_from_user(&bind_info, arg, sizeof(bind_info)))
return -EFAULT;
memory = agp_find_mem_by_key(bind_info.key);
if (memory == NULL)
return -EINVAL;
return agp_bind_memory(memory, bind_info.pg_start);
}
static int compat_agpioc_unbind_wrap(struct agp_file_private *priv, void __user *arg)
{
struct agp_memory *memory;
struct agp_unbind32 unbind;
DBG("");
if (copy_from_user(&unbind, arg, sizeof(unbind)))
return -EFAULT;
memory = agp_find_mem_by_key(unbind.key);
if (memory == NULL)
return -EINVAL;
return agp_unbind_memory(memory);
}
long compat_agp_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct agp_file_private *curr_priv = file->private_data;
int ret_val = -ENOTTY;
mutex_lock(&(agp_fe.agp_mutex));
if ((agp_fe.current_controller == NULL) &&
(cmd != AGPIOC_ACQUIRE32)) {
ret_val = -EINVAL;
goto ioctl_out;
}
if ((agp_fe.backend_acquired != true) &&
(cmd != AGPIOC_ACQUIRE32)) {
ret_val = -EBUSY;
goto ioctl_out;
}
if (cmd != AGPIOC_ACQUIRE32) {
if (!(test_bit(AGP_FF_IS_CONTROLLER, &curr_priv->access_flags))) {
ret_val = -EPERM;
goto ioctl_out;
}
/* Use the original pid of the controller,
* in case it's threaded */
if (agp_fe.current_controller->pid != curr_priv->my_pid) {
ret_val = -EBUSY;
goto ioctl_out;
}
}
switch (cmd) {
case AGPIOC_INFO32:
ret_val = compat_agpioc_info_wrap(curr_priv, (void __user *) arg);
break;
case AGPIOC_ACQUIRE32:
ret_val = agpioc_acquire_wrap(curr_priv);
break;
case AGPIOC_RELEASE32:
ret_val = agpioc_release_wrap(curr_priv);
break;
case AGPIOC_SETUP32:
ret_val = agpioc_setup_wrap(curr_priv, (void __user *) arg);
break;
case AGPIOC_RESERVE32:
ret_val = compat_agpioc_reserve_wrap(curr_priv, (void __user *) arg);
break;
case AGPIOC_PROTECT32:
ret_val = agpioc_protect_wrap(curr_priv);
break;
case AGPIOC_ALLOCATE32:
ret_val = compat_agpioc_allocate_wrap(curr_priv, (void __user *) arg);
break;
case AGPIOC_DEALLOCATE32:
ret_val = agpioc_deallocate_wrap(curr_priv, (int) arg);
break;
case AGPIOC_BIND32:
ret_val = compat_agpioc_bind_wrap(curr_priv, (void __user *) arg);
break;
case AGPIOC_UNBIND32:
ret_val = compat_agpioc_unbind_wrap(curr_priv, (void __user *) arg);
break;
case AGPIOC_CHIPSET_FLUSH32:
break;
}
ioctl_out:
DBG("ioctl returns %d\n", ret_val);
mutex_unlock(&(agp_fe.agp_mutex));
return ret_val;
}
| gpl-2.0 |
MoKee/android_kernel_samsung_espresso10 | drivers/media/dvb/dvb-usb/dvb-usb-firmware.c | 14284 | 3956 | /* dvb-usb-firmware.c is part of the DVB USB library.
*
* Copyright (C) 2004-6 Patrick Boettcher (patrick.boettcher@desy.de)
* see dvb-usb-init.c for copyright information.
*
* This file contains functions for downloading the firmware to Cypress FX 1 and 2 based devices.
*
* FIXME: This part does actually not belong to dvb-usb, but to the usb-subsystem.
*/
#include "dvb-usb-common.h"
#include <linux/usb.h>
struct usb_cypress_controller {
int id;
const char *name; /* name of the usb controller */
u16 cpu_cs_register; /* needs to be restarted, when the firmware has been downloaded. */
};
static struct usb_cypress_controller cypress[] = {
{ .id = DEVICE_SPECIFIC, .name = "Device specific", .cpu_cs_register = 0 },
{ .id = CYPRESS_AN2135, .name = "Cypress AN2135", .cpu_cs_register = 0x7f92 },
{ .id = CYPRESS_AN2235, .name = "Cypress AN2235", .cpu_cs_register = 0x7f92 },
{ .id = CYPRESS_FX2, .name = "Cypress FX2", .cpu_cs_register = 0xe600 },
};
/*
* load a firmware packet to the device
*/
static int usb_cypress_writemem(struct usb_device *udev,u16 addr,u8 *data, u8 len)
{
return usb_control_msg(udev, usb_sndctrlpipe(udev,0),
0xa0, USB_TYPE_VENDOR, addr, 0x00, data, len, 5000);
}
int usb_cypress_load_firmware(struct usb_device *udev, const struct firmware *fw, int type)
{
struct hexline hx;
u8 reset;
int ret,pos=0;
/* stop the CPU */
reset = 1;
if ((ret = usb_cypress_writemem(udev,cypress[type].cpu_cs_register,&reset,1)) != 1)
err("could not stop the USB controller CPU.");
while ((ret = dvb_usb_get_hexline(fw,&hx,&pos)) > 0) {
deb_fw("writing to address 0x%04x (buffer: 0x%02x %02x)\n",hx.addr,hx.len,hx.chk);
ret = usb_cypress_writemem(udev,hx.addr,hx.data,hx.len);
if (ret != hx.len) {
err("error while transferring firmware "
"(transferred size: %d, block size: %d)",
ret,hx.len);
ret = -EINVAL;
break;
}
}
if (ret < 0) {
err("firmware download failed at %d with %d",pos,ret);
return ret;
}
if (ret == 0) {
/* restart the CPU */
reset = 0;
if (ret || usb_cypress_writemem(udev,cypress[type].cpu_cs_register,&reset,1) != 1) {
err("could not restart the USB controller CPU.");
ret = -EINVAL;
}
} else
ret = -EIO;
return ret;
}
EXPORT_SYMBOL(usb_cypress_load_firmware);
int dvb_usb_download_firmware(struct usb_device *udev, struct dvb_usb_device_properties *props)
{
int ret;
const struct firmware *fw = NULL;
if ((ret = request_firmware(&fw, props->firmware, &udev->dev)) != 0) {
err("did not find the firmware file. (%s) "
"Please see linux/Documentation/dvb/ for more details on firmware-problems. (%d)",
props->firmware,ret);
return ret;
}
info("downloading firmware from file '%s'",props->firmware);
switch (props->usb_ctrl) {
case CYPRESS_AN2135:
case CYPRESS_AN2235:
case CYPRESS_FX2:
ret = usb_cypress_load_firmware(udev, fw, props->usb_ctrl);
break;
case DEVICE_SPECIFIC:
if (props->download_firmware)
ret = props->download_firmware(udev,fw);
else {
err("BUG: driver didn't specified a download_firmware-callback, although it claims to have a DEVICE_SPECIFIC one.");
ret = -EINVAL;
}
break;
default:
ret = -EINVAL;
break;
}
release_firmware(fw);
return ret;
}
int dvb_usb_get_hexline(const struct firmware *fw, struct hexline *hx,
int *pos)
{
u8 *b = (u8 *) &fw->data[*pos];
int data_offs = 4;
if (*pos >= fw->size)
return 0;
memset(hx,0,sizeof(struct hexline));
hx->len = b[0];
if ((*pos + hx->len + 4) >= fw->size)
return -EINVAL;
hx->addr = b[1] | (b[2] << 8);
hx->type = b[3];
if (hx->type == 0x04) {
/* b[4] and b[5] are the Extended linear address record data field */
hx->addr |= (b[4] << 24) | (b[5] << 16);
/* hx->len -= 2;
data_offs += 2; */
}
memcpy(hx->data,&b[data_offs],hx->len);
hx->chk = b[hx->len + data_offs];
*pos += hx->len + 5;
return *pos;
}
EXPORT_SYMBOL(dvb_usb_get_hexline);
| gpl-2.0 |
kgp700/neok-op3d-cuberoid-ics | arch/arm/mach-omap2/gpmc.c | 205 | 22361 | /*
* GPMC support functions
*
* Copyright (C) 2005-2006 Nokia Corporation
*
* Author: Juha Yrjola
*
* Copyright (C) 2009 Texas Instruments
* Added OMAP4 support - Santosh Shilimkar <santosh.shilimkar@ti.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#undef DEBUG
#include <linux/irq.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/ioport.h>
#include <linux/spinlock.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <asm/mach-types.h>
#include <plat/gpmc.h>
#include <plat/sdrc.h>
/* GPMC register offsets */
#define GPMC_REVISION 0x00
#define GPMC_SYSCONFIG 0x10
#define GPMC_SYSSTATUS 0x14
#define GPMC_IRQSTATUS 0x18
#define GPMC_IRQENABLE 0x1c
#define GPMC_TIMEOUT_CONTROL 0x40
#define GPMC_ERR_ADDRESS 0x44
#define GPMC_ERR_TYPE 0x48
#define GPMC_CONFIG 0x50
#define GPMC_STATUS 0x54
#define GPMC_PREFETCH_CONFIG1 0x1e0
#define GPMC_PREFETCH_CONFIG2 0x1e4
#define GPMC_PREFETCH_CONTROL 0x1ec
#define GPMC_PREFETCH_STATUS 0x1f0
#define GPMC_ECC_CONFIG 0x1f4
#define GPMC_ECC_CONTROL 0x1f8
#define GPMC_ECC_SIZE_CONFIG 0x1fc
#define GPMC_ECC1_RESULT 0x200
#define GPMC_CS0_OFFSET 0x60
#define GPMC_CS_SIZE 0x30
#define GPMC_MEM_START 0x00000000
#define GPMC_MEM_END 0x3FFFFFFF
#define BOOT_ROM_SPACE 0x100000 /* 1MB */
#define GPMC_CHUNK_SHIFT 24 /* 16 MB */
#define GPMC_SECTION_SHIFT 28 /* 128 MB */
#define CS_NUM_SHIFT 24
#define ENABLE_PREFETCH (0x1 << 7)
#define DMA_MPU_MODE 2
/* Structure to save gpmc cs context */
struct gpmc_cs_config {
u32 config1;
u32 config2;
u32 config3;
u32 config4;
u32 config5;
u32 config6;
u32 config7;
int is_valid;
};
/*
* Structure to save/restore gpmc context
* to support core off.
*/
struct omap_gpmc_regs {
u32 sysconfig;
u32 irqenable;
u32 timeout_ctrl;
u32 config;
u32 prefetch_config1;
u32 prefetch_config2;
u32 prefetch_control;
struct gpmc_cs_config cs_context[GPMC_CS_NUM];
};
static struct resource gpmc_mem_root;
static struct resource gpmc_cs_mem[GPMC_CS_NUM];
static DEFINE_SPINLOCK(gpmc_mem_lock);
static unsigned int gpmc_cs_map; /* flag for cs which are initialized */
static int gpmc_ecc_used = -EINVAL; /* cs using ecc engine */
static void __iomem *gpmc_base;
static struct clk *gpmc_l3_clk;
static irqreturn_t gpmc_handle_irq(int irq, void *dev);
static void gpmc_write_reg(int idx, u32 val)
{
__raw_writel(val, gpmc_base + idx);
}
static u32 gpmc_read_reg(int idx)
{
return __raw_readl(gpmc_base + idx);
}
static void gpmc_cs_write_byte(int cs, int idx, u8 val)
{
void __iomem *reg_addr;
reg_addr = gpmc_base + GPMC_CS0_OFFSET + (cs * GPMC_CS_SIZE) + idx;
__raw_writeb(val, reg_addr);
}
static u8 gpmc_cs_read_byte(int cs, int idx)
{
void __iomem *reg_addr;
reg_addr = gpmc_base + GPMC_CS0_OFFSET + (cs * GPMC_CS_SIZE) + idx;
return __raw_readb(reg_addr);
}
void gpmc_cs_write_reg(int cs, int idx, u32 val)
{
void __iomem *reg_addr;
reg_addr = gpmc_base + GPMC_CS0_OFFSET + (cs * GPMC_CS_SIZE) + idx;
__raw_writel(val, reg_addr);
}
u32 gpmc_cs_read_reg(int cs, int idx)
{
void __iomem *reg_addr;
reg_addr = gpmc_base + GPMC_CS0_OFFSET + (cs * GPMC_CS_SIZE) + idx;
return __raw_readl(reg_addr);
}
/* TODO: Add support for gpmc_fck to clock framework and use it */
unsigned long gpmc_get_fclk_period(void)
{
unsigned long rate = clk_get_rate(gpmc_l3_clk);
if (rate == 0) {
printk(KERN_WARNING "gpmc_l3_clk not enabled\n");
return 0;
}
rate /= 1000;
rate = 1000000000 / rate; /* In picoseconds */
return rate;
}
unsigned int gpmc_ns_to_ticks(unsigned int time_ns)
{
unsigned long tick_ps;
/* Calculate in picosecs to yield more exact results */
tick_ps = gpmc_get_fclk_period();
return (time_ns * 1000 + tick_ps - 1) / tick_ps;
}
unsigned int gpmc_ps_to_ticks(unsigned int time_ps)
{
unsigned long tick_ps;
/* Calculate in picosecs to yield more exact results */
tick_ps = gpmc_get_fclk_period();
return (time_ps + tick_ps - 1) / tick_ps;
}
unsigned int gpmc_ticks_to_ns(unsigned int ticks)
{
return ticks * gpmc_get_fclk_period() / 1000;
}
unsigned int gpmc_round_ns_to_ticks(unsigned int time_ns)
{
unsigned long ticks = gpmc_ns_to_ticks(time_ns);
return ticks * gpmc_get_fclk_period() / 1000;
}
#ifdef DEBUG
static int set_gpmc_timing_reg(int cs, int reg, int st_bit, int end_bit,
int time, const char *name)
#else
static int set_gpmc_timing_reg(int cs, int reg, int st_bit, int end_bit,
int time)
#endif
{
u32 l;
int ticks, mask, nr_bits;
if (time == 0)
ticks = 0;
else
ticks = gpmc_ns_to_ticks(time);
nr_bits = end_bit - st_bit + 1;
if (ticks >= 1 << nr_bits) {
#ifdef DEBUG
printk(KERN_INFO "GPMC CS%d: %-10s* %3d ns, %3d ticks >= %d\n",
cs, name, time, ticks, 1 << nr_bits);
#endif
return -1;
}
mask = (1 << nr_bits) - 1;
l = gpmc_cs_read_reg(cs, reg);
#ifdef DEBUG
printk(KERN_INFO
"GPMC CS%d: %-10s: %3d ticks, %3lu ns (was %3i ticks) %3d ns\n",
cs, name, ticks, gpmc_get_fclk_period() * ticks / 1000,
(l >> st_bit) & mask, time);
#endif
l &= ~(mask << st_bit);
l |= ticks << st_bit;
gpmc_cs_write_reg(cs, reg, l);
return 0;
}
#ifdef DEBUG
#define GPMC_SET_ONE(reg, st, end, field) \
if (set_gpmc_timing_reg(cs, (reg), (st), (end), \
t->field, #field) < 0) \
return -1
#else
#define GPMC_SET_ONE(reg, st, end, field) \
if (set_gpmc_timing_reg(cs, (reg), (st), (end), t->field) < 0) \
return -1
#endif
int gpmc_cs_calc_divider(int cs, unsigned int sync_clk)
{
int div;
u32 l;
l = sync_clk + (gpmc_get_fclk_period() - 1);
div = l / gpmc_get_fclk_period();
if (div > 4)
return -1;
if (div <= 0)
div = 1;
return div;
}
int gpmc_cs_set_timings(int cs, const struct gpmc_timings *t)
{
int div;
u32 l;
div = gpmc_cs_calc_divider(cs, t->sync_clk);
if (div < 0)
return -1;
GPMC_SET_ONE(GPMC_CS_CONFIG2, 0, 3, cs_on);
GPMC_SET_ONE(GPMC_CS_CONFIG2, 8, 12, cs_rd_off);
GPMC_SET_ONE(GPMC_CS_CONFIG2, 16, 20, cs_wr_off);
GPMC_SET_ONE(GPMC_CS_CONFIG3, 0, 3, adv_on);
GPMC_SET_ONE(GPMC_CS_CONFIG3, 8, 12, adv_rd_off);
GPMC_SET_ONE(GPMC_CS_CONFIG3, 16, 20, adv_wr_off);
GPMC_SET_ONE(GPMC_CS_CONFIG4, 0, 3, oe_on);
GPMC_SET_ONE(GPMC_CS_CONFIG4, 8, 12, oe_off);
GPMC_SET_ONE(GPMC_CS_CONFIG4, 16, 19, we_on);
GPMC_SET_ONE(GPMC_CS_CONFIG4, 24, 28, we_off);
GPMC_SET_ONE(GPMC_CS_CONFIG5, 0, 4, rd_cycle);
GPMC_SET_ONE(GPMC_CS_CONFIG5, 8, 12, wr_cycle);
GPMC_SET_ONE(GPMC_CS_CONFIG5, 16, 20, access);
GPMC_SET_ONE(GPMC_CS_CONFIG5, 24, 27, page_burst_access);
if (cpu_is_omap34xx()) {
GPMC_SET_ONE(GPMC_CS_CONFIG6, 16, 19, wr_data_mux_bus);
GPMC_SET_ONE(GPMC_CS_CONFIG6, 24, 28, wr_access);
}
/* caller is expected to have initialized CONFIG1 to cover
* at least sync vs async
*/
l = gpmc_cs_read_reg(cs, GPMC_CS_CONFIG1);
if (l & (GPMC_CONFIG1_READTYPE_SYNC | GPMC_CONFIG1_WRITETYPE_SYNC)) {
#ifdef DEBUG
printk(KERN_INFO "GPMC CS%d CLK period is %lu ns (div %d)\n",
cs, (div * gpmc_get_fclk_period()) / 1000, div);
#endif
l &= ~0x03;
l |= (div - 1);
gpmc_cs_write_reg(cs, GPMC_CS_CONFIG1, l);
}
return 0;
}
static void gpmc_cs_enable_mem(int cs, u32 base, u32 size)
{
u32 l;
u32 mask;
mask = (1 << GPMC_SECTION_SHIFT) - size;
l = gpmc_cs_read_reg(cs, GPMC_CS_CONFIG7);
l &= ~0x3f;
l = (base >> GPMC_CHUNK_SHIFT) & 0x3f;
l &= ~(0x0f << 8);
l |= ((mask >> GPMC_CHUNK_SHIFT) & 0x0f) << 8;
l |= GPMC_CONFIG7_CSVALID;
gpmc_cs_write_reg(cs, GPMC_CS_CONFIG7, l);
}
static void gpmc_cs_disable_mem(int cs)
{
u32 l;
l = gpmc_cs_read_reg(cs, GPMC_CS_CONFIG7);
l &= ~GPMC_CONFIG7_CSVALID;
gpmc_cs_write_reg(cs, GPMC_CS_CONFIG7, l);
}
static void gpmc_cs_get_memconf(int cs, u32 *base, u32 *size)
{
u32 l;
u32 mask;
l = gpmc_cs_read_reg(cs, GPMC_CS_CONFIG7);
*base = (l & 0x3f) << GPMC_CHUNK_SHIFT;
mask = (l >> 8) & 0x0f;
*size = (1 << GPMC_SECTION_SHIFT) - (mask << GPMC_CHUNK_SHIFT);
}
static int gpmc_cs_mem_enabled(int cs)
{
u32 l;
l = gpmc_cs_read_reg(cs, GPMC_CS_CONFIG7);
return l & GPMC_CONFIG7_CSVALID;
}
int gpmc_cs_set_reserved(int cs, int reserved)
{
if (cs > GPMC_CS_NUM)
return -ENODEV;
gpmc_cs_map &= ~(1 << cs);
gpmc_cs_map |= (reserved ? 1 : 0) << cs;
return 0;
}
int gpmc_cs_reserved(int cs)
{
if (cs > GPMC_CS_NUM)
return -ENODEV;
return gpmc_cs_map & (1 << cs);
}
static unsigned long gpmc_mem_align(unsigned long size)
{
int order;
size = (size - 1) >> (GPMC_CHUNK_SHIFT - 1);
order = GPMC_CHUNK_SHIFT - 1;
do {
size >>= 1;
order++;
} while (size);
size = 1 << order;
return size;
}
static int gpmc_cs_insert_mem(int cs, unsigned long base, unsigned long size)
{
struct resource *res = &gpmc_cs_mem[cs];
int r;
size = gpmc_mem_align(size);
spin_lock(&gpmc_mem_lock);
res->start = base;
res->end = base + size - 1;
r = request_resource(&gpmc_mem_root, res);
spin_unlock(&gpmc_mem_lock);
return r;
}
int gpmc_cs_request(int cs, unsigned long size, unsigned long *base)
{
struct resource *res = &gpmc_cs_mem[cs];
int r = -1;
if (cs > GPMC_CS_NUM)
return -ENODEV;
size = gpmc_mem_align(size);
if (size > (1 << GPMC_SECTION_SHIFT))
return -ENOMEM;
spin_lock(&gpmc_mem_lock);
if (gpmc_cs_reserved(cs)) {
r = -EBUSY;
goto out;
}
if (gpmc_cs_mem_enabled(cs))
r = adjust_resource(res, res->start & ~(size - 1), size);
if (r < 0)
r = allocate_resource(&gpmc_mem_root, res, size, 0, ~0,
size, NULL, NULL);
if (r < 0)
goto out;
gpmc_cs_enable_mem(cs, res->start, resource_size(res));
*base = res->start;
gpmc_cs_set_reserved(cs, 1);
out:
spin_unlock(&gpmc_mem_lock);
return r;
}
EXPORT_SYMBOL(gpmc_cs_request);
void gpmc_cs_free(int cs)
{
spin_lock(&gpmc_mem_lock);
if (cs >= GPMC_CS_NUM || cs < 0 || !gpmc_cs_reserved(cs)) {
printk(KERN_ERR "Trying to free non-reserved GPMC CS%d\n", cs);
BUG();
spin_unlock(&gpmc_mem_lock);
return;
}
gpmc_cs_disable_mem(cs);
release_resource(&gpmc_cs_mem[cs]);
gpmc_cs_set_reserved(cs, 0);
spin_unlock(&gpmc_mem_lock);
}
EXPORT_SYMBOL(gpmc_cs_free);
/**
* gpmc_read_status - read access request to get the different gpmc status
* @cmd: command type
* @return status
*/
int gpmc_read_status(int cmd)
{
int status = -EINVAL;
u32 regval = 0;
switch (cmd) {
case GPMC_GET_IRQ_STATUS:
status = gpmc_read_reg(GPMC_IRQSTATUS);
break;
case GPMC_PREFETCH_FIFO_CNT:
regval = gpmc_read_reg(GPMC_PREFETCH_STATUS);
status = GPMC_PREFETCH_STATUS_FIFO_CNT(regval);
break;
case GPMC_PREFETCH_COUNT:
regval = gpmc_read_reg(GPMC_PREFETCH_STATUS);
status = GPMC_PREFETCH_STATUS_COUNT(regval);
break;
case GPMC_STATUS_BUFFER:
regval = gpmc_read_reg(GPMC_STATUS);
/* 1 : buffer is available to write */
status = regval & GPMC_STATUS_BUFF_EMPTY;
break;
default:
printk(KERN_ERR "gpmc_read_status: Not supported\n");
}
return status;
}
EXPORT_SYMBOL(gpmc_read_status);
/**
* gpmc_cs_configure - write request to configure gpmc
* @cs: chip select number
* @cmd: command type
* @wval: value to write
* @return status of the operation
*/
int gpmc_cs_configure(int cs, int cmd, int wval)
{
int err = 0;
u32 regval = 0;
switch (cmd) {
case GPMC_ENABLE_IRQ:
gpmc_write_reg(GPMC_IRQENABLE, wval);
break;
case GPMC_SET_IRQ_STATUS:
gpmc_write_reg(GPMC_IRQSTATUS, wval);
break;
case GPMC_CONFIG_WP:
regval = gpmc_read_reg(GPMC_CONFIG);
if (wval)
regval &= ~GPMC_CONFIG_WRITEPROTECT; /* WP is ON */
else
regval |= GPMC_CONFIG_WRITEPROTECT; /* WP is OFF */
gpmc_write_reg(GPMC_CONFIG, regval);
break;
case GPMC_CONFIG_RDY_BSY:
regval = gpmc_cs_read_reg(cs, GPMC_CS_CONFIG1);
if (wval)
regval |= WR_RD_PIN_MONITORING;
else
regval &= ~WR_RD_PIN_MONITORING;
gpmc_cs_write_reg(cs, GPMC_CS_CONFIG1, regval);
break;
case GPMC_CONFIG_DEV_SIZE:
regval = gpmc_cs_read_reg(cs, GPMC_CS_CONFIG1);
/* clear 2 target bits */
regval &= ~GPMC_CONFIG1_DEVICESIZE(3);
/* set the proper value */
regval |= GPMC_CONFIG1_DEVICESIZE(wval);
gpmc_cs_write_reg(cs, GPMC_CS_CONFIG1, regval);
break;
case GPMC_CONFIG_DEV_TYPE:
regval = gpmc_cs_read_reg(cs, GPMC_CS_CONFIG1);
regval |= GPMC_CONFIG1_DEVICETYPE(wval);
if (wval == GPMC_DEVICETYPE_NOR)
regval |= GPMC_CONFIG1_MUXADDDATA;
gpmc_cs_write_reg(cs, GPMC_CS_CONFIG1, regval);
break;
default:
printk(KERN_ERR "gpmc_configure_cs: Not supported\n");
err = -EINVAL;
}
return err;
}
EXPORT_SYMBOL(gpmc_cs_configure);
/**
* gpmc_nand_read - nand specific read access request
* @cs: chip select number
* @cmd: command type
*/
int gpmc_nand_read(int cs, int cmd)
{
int rval = -EINVAL;
switch (cmd) {
case GPMC_NAND_DATA:
rval = gpmc_cs_read_byte(cs, GPMC_CS_NAND_DATA);
break;
default:
printk(KERN_ERR "gpmc_read_nand_ctrl: Not supported\n");
}
return rval;
}
EXPORT_SYMBOL(gpmc_nand_read);
/**
* gpmc_nand_write - nand specific write request
* @cs: chip select number
* @cmd: command type
* @wval: value to write
*/
int gpmc_nand_write(int cs, int cmd, int wval)
{
int err = 0;
switch (cmd) {
case GPMC_NAND_COMMAND:
gpmc_cs_write_byte(cs, GPMC_CS_NAND_COMMAND, wval);
break;
case GPMC_NAND_ADDRESS:
gpmc_cs_write_byte(cs, GPMC_CS_NAND_ADDRESS, wval);
break;
case GPMC_NAND_DATA:
gpmc_cs_write_byte(cs, GPMC_CS_NAND_DATA, wval);
default:
printk(KERN_ERR "gpmc_write_nand_ctrl: Not supported\n");
err = -EINVAL;
}
return err;
}
EXPORT_SYMBOL(gpmc_nand_write);
/**
* gpmc_prefetch_enable - configures and starts prefetch transfer
* @cs: cs (chip select) number
* @fifo_th: fifo threshold to be used for read/ write
* @dma_mode: dma mode enable (1) or disable (0)
* @u32_count: number of bytes to be transferred
* @is_write: prefetch read(0) or write post(1) mode
*/
int gpmc_prefetch_enable(int cs, int fifo_th, int dma_mode,
unsigned int u32_count, int is_write)
{
if (fifo_th > PREFETCH_FIFOTHRESHOLD_MAX) {
pr_err("gpmc: fifo threshold is not supported\n");
return -1;
} else if (!(gpmc_read_reg(GPMC_PREFETCH_CONTROL))) {
/* Set the amount of bytes to be prefetched */
gpmc_write_reg(GPMC_PREFETCH_CONFIG2, u32_count);
/* Set dma/mpu mode, the prefetch read / post write and
* enable the engine. Set which cs is has requested for.
*/
gpmc_write_reg(GPMC_PREFETCH_CONFIG1, ((cs << CS_NUM_SHIFT) |
PREFETCH_FIFOTHRESHOLD(fifo_th) |
ENABLE_PREFETCH |
(dma_mode << DMA_MPU_MODE) |
(0x1 & is_write)));
/* Start the prefetch engine */
gpmc_write_reg(GPMC_PREFETCH_CONTROL, 0x1);
} else {
return -EBUSY;
}
return 0;
}
EXPORT_SYMBOL(gpmc_prefetch_enable);
/**
* gpmc_prefetch_reset - disables and stops the prefetch engine
*/
int gpmc_prefetch_reset(int cs)
{
u32 config1;
/* check if the same module/cs is trying to reset */
config1 = gpmc_read_reg(GPMC_PREFETCH_CONFIG1);
if (((config1 >> CS_NUM_SHIFT) & 0x7) != cs)
return -EINVAL;
/* Stop the PFPW engine */
gpmc_write_reg(GPMC_PREFETCH_CONTROL, 0x0);
/* Reset/disable the PFPW engine */
gpmc_write_reg(GPMC_PREFETCH_CONFIG1, 0x0);
return 0;
}
EXPORT_SYMBOL(gpmc_prefetch_reset);
static void __init gpmc_mem_init(void)
{
int cs;
unsigned long boot_rom_space = 0;
/* never allocate the first page, to facilitate bug detection;
* even if we didn't boot from ROM.
*/
boot_rom_space = BOOT_ROM_SPACE;
/* In apollon the CS0 is mapped as 0x0000 0000 */
if (machine_is_omap_apollon())
boot_rom_space = 0;
gpmc_mem_root.start = GPMC_MEM_START + boot_rom_space;
gpmc_mem_root.end = GPMC_MEM_END;
/* Reserve all regions that has been set up by bootloader */
for (cs = 0; cs < GPMC_CS_NUM; cs++) {
u32 base, size;
if (!gpmc_cs_mem_enabled(cs))
continue;
gpmc_cs_get_memconf(cs, &base, &size);
if (gpmc_cs_insert_mem(cs, base, size) < 0)
BUG();
}
}
static int __init gpmc_init(void)
{
u32 l, irq;
int cs, ret = -EINVAL;
int gpmc_irq;
char *ck = NULL;
if (cpu_is_omap24xx()) {
ck = "core_l3_ck";
if (cpu_is_omap2420())
l = OMAP2420_GPMC_BASE;
else
l = OMAP34XX_GPMC_BASE;
gpmc_irq = INT_34XX_GPMC_IRQ;
} else if (cpu_is_omap34xx()) {
ck = "gpmc_fck";
l = OMAP34XX_GPMC_BASE;
gpmc_irq = INT_34XX_GPMC_IRQ;
} else if (cpu_is_omap44xx()) {
ck = "gpmc_ck";
l = OMAP44XX_GPMC_BASE;
gpmc_irq = OMAP44XX_IRQ_GPMC;
}
if (WARN_ON(!ck))
return ret;
gpmc_l3_clk = clk_get(NULL, ck);
if (IS_ERR(gpmc_l3_clk)) {
printk(KERN_ERR "Could not get GPMC clock %s\n", ck);
BUG();
}
gpmc_base = ioremap(l, SZ_4K);
if (!gpmc_base) {
clk_put(gpmc_l3_clk);
printk(KERN_ERR "Could not get GPMC register memory\n");
BUG();
}
clk_enable(gpmc_l3_clk);
l = gpmc_read_reg(GPMC_REVISION);
printk(KERN_INFO "GPMC revision %d.%d\n", (l >> 4) & 0x0f, l & 0x0f);
/* Set smart idle mode and automatic L3 clock gating */
l = gpmc_read_reg(GPMC_SYSCONFIG);
l &= 0x03 << 3;
l |= (0x02 << 3) | (1 << 0);
gpmc_write_reg(GPMC_SYSCONFIG, l);
gpmc_mem_init();
/* initalize the irq_chained */
irq = OMAP_GPMC_IRQ_BASE;
for (cs = 0; cs < GPMC_CS_NUM; cs++) {
irq_set_chip_and_handler(irq, &dummy_irq_chip,
handle_simple_irq);
set_irq_flags(irq, IRQF_VALID);
irq++;
}
ret = request_irq(gpmc_irq,
gpmc_handle_irq, IRQF_SHARED, "gpmc", gpmc_base);
if (ret)
pr_err("gpmc: irq-%d could not claim: err %d\n",
gpmc_irq, ret);
return ret;
}
postcore_initcall(gpmc_init);
static irqreturn_t gpmc_handle_irq(int irq, void *dev)
{
u8 cs;
/* check cs to invoke the irq */
cs = ((gpmc_read_reg(GPMC_PREFETCH_CONFIG1)) >> CS_NUM_SHIFT) & 0x7;
if (OMAP_GPMC_IRQ_BASE+cs <= OMAP_GPMC_IRQ_END)
generic_handle_irq(OMAP_GPMC_IRQ_BASE+cs);
return IRQ_HANDLED;
}
static struct omap_gpmc_regs gpmc_context;
void omap_gpmc_save_context(void)
{
int i;
gpmc_context.sysconfig = gpmc_read_reg(GPMC_SYSCONFIG);
gpmc_context.irqenable = gpmc_read_reg(GPMC_IRQENABLE);
gpmc_context.timeout_ctrl = gpmc_read_reg(GPMC_TIMEOUT_CONTROL);
gpmc_context.config = gpmc_read_reg(GPMC_CONFIG);
gpmc_context.prefetch_config1 = gpmc_read_reg(GPMC_PREFETCH_CONFIG1);
gpmc_context.prefetch_config2 = gpmc_read_reg(GPMC_PREFETCH_CONFIG2);
gpmc_context.prefetch_control = gpmc_read_reg(GPMC_PREFETCH_CONTROL);
for (i = 0; i < GPMC_CS_NUM; i++) {
gpmc_context.cs_context[i].is_valid = gpmc_cs_mem_enabled(i);
if (gpmc_context.cs_context[i].is_valid) {
gpmc_context.cs_context[i].config1 =
gpmc_cs_read_reg(i, GPMC_CS_CONFIG1);
gpmc_context.cs_context[i].config2 =
gpmc_cs_read_reg(i, GPMC_CS_CONFIG2);
gpmc_context.cs_context[i].config3 =
gpmc_cs_read_reg(i, GPMC_CS_CONFIG3);
gpmc_context.cs_context[i].config4 =
gpmc_cs_read_reg(i, GPMC_CS_CONFIG4);
gpmc_context.cs_context[i].config5 =
gpmc_cs_read_reg(i, GPMC_CS_CONFIG5);
gpmc_context.cs_context[i].config6 =
gpmc_cs_read_reg(i, GPMC_CS_CONFIG6);
gpmc_context.cs_context[i].config7 =
gpmc_cs_read_reg(i, GPMC_CS_CONFIG7);
}
}
}
void omap_gpmc_restore_context(void)
{
int i;
gpmc_write_reg(GPMC_SYSCONFIG, gpmc_context.sysconfig);
gpmc_write_reg(GPMC_IRQENABLE, gpmc_context.irqenable);
gpmc_write_reg(GPMC_TIMEOUT_CONTROL, gpmc_context.timeout_ctrl);
gpmc_write_reg(GPMC_CONFIG, gpmc_context.config);
gpmc_write_reg(GPMC_PREFETCH_CONFIG1, gpmc_context.prefetch_config1);
gpmc_write_reg(GPMC_PREFETCH_CONFIG2, gpmc_context.prefetch_config2);
gpmc_write_reg(GPMC_PREFETCH_CONTROL, gpmc_context.prefetch_control);
for (i = 0; i < GPMC_CS_NUM; i++) {
if (gpmc_context.cs_context[i].is_valid) {
gpmc_cs_write_reg(i, GPMC_CS_CONFIG1,
gpmc_context.cs_context[i].config1);
gpmc_cs_write_reg(i, GPMC_CS_CONFIG2,
gpmc_context.cs_context[i].config2);
gpmc_cs_write_reg(i, GPMC_CS_CONFIG3,
gpmc_context.cs_context[i].config3);
gpmc_cs_write_reg(i, GPMC_CS_CONFIG4,
gpmc_context.cs_context[i].config4);
gpmc_cs_write_reg(i, GPMC_CS_CONFIG5,
gpmc_context.cs_context[i].config5);
gpmc_cs_write_reg(i, GPMC_CS_CONFIG6,
gpmc_context.cs_context[i].config6);
gpmc_cs_write_reg(i, GPMC_CS_CONFIG7,
gpmc_context.cs_context[i].config7);
}
}
}
/**
* gpmc_enable_hwecc - enable hardware ecc functionality
* @cs: chip select number
* @mode: read/write mode
* @dev_width: device bus width(1 for x16, 0 for x8)
* @ecc_size: bytes for which ECC will be generated
*/
int gpmc_enable_hwecc(int cs, int mode, int dev_width, int ecc_size)
{
unsigned int val;
/* check if ecc module is in used */
if (gpmc_ecc_used != -EINVAL)
return -EINVAL;
gpmc_ecc_used = cs;
/* clear ecc and enable bits */
val = ((0x00000001<<8) | 0x00000001);
gpmc_write_reg(GPMC_ECC_CONTROL, val);
/* program ecc and result sizes */
val = ((((ecc_size >> 1) - 1) << 22) | (0x0000000F));
gpmc_write_reg(GPMC_ECC_SIZE_CONFIG, val);
switch (mode) {
case GPMC_ECC_READ:
gpmc_write_reg(GPMC_ECC_CONTROL, 0x101);
break;
case GPMC_ECC_READSYN:
gpmc_write_reg(GPMC_ECC_CONTROL, 0x100);
break;
case GPMC_ECC_WRITE:
gpmc_write_reg(GPMC_ECC_CONTROL, 0x101);
break;
default:
printk(KERN_INFO "Error: Unrecognized Mode[%d]!\n", mode);
break;
}
/* (ECC 16 or 8 bit col) | ( CS ) | ECC Enable */
val = (dev_width << 7) | (cs << 1) | (0x1);
gpmc_write_reg(GPMC_ECC_CONFIG, val);
return 0;
}
/**
* gpmc_calculate_ecc - generate non-inverted ecc bytes
* @cs: chip select number
* @dat: data pointer over which ecc is computed
* @ecc_code: ecc code buffer
*
* Using non-inverted ECC is considered ugly since writing a blank
* page (padding) will clear the ECC bytes. This is not a problem as long
* no one is trying to write data on the seemingly unused page. Reading
* an erased page will produce an ECC mismatch between generated and read
* ECC bytes that has to be dealt with separately.
*/
int gpmc_calculate_ecc(int cs, const u_char *dat, u_char *ecc_code)
{
unsigned int val = 0x0;
if (gpmc_ecc_used != cs)
return -EINVAL;
/* read ecc result */
val = gpmc_read_reg(GPMC_ECC1_RESULT);
*ecc_code++ = val; /* P128e, ..., P1e */
*ecc_code++ = val >> 16; /* P128o, ..., P1o */
/* P2048o, P1024o, P512o, P256o, P2048e, P1024e, P512e, P256e */
*ecc_code++ = ((val >> 8) & 0x0f) | ((val >> 20) & 0xf0);
gpmc_ecc_used = -EINVAL;
return 0;
}
| gpl-2.0 |
wangyikai/linux | drivers/mfd/kempld-core.c | 205 | 21200 | /*
* Kontron PLD MFD core driver
*
* Copyright (c) 2010-2013 Kontron Europe GmbH
* Author: Michael Brunner <michael.brunner@kontron.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License 2 as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/platform_device.h>
#include <linux/mfd/core.h>
#include <linux/mfd/kempld.h>
#include <linux/module.h>
#include <linux/dmi.h>
#include <linux/io.h>
#include <linux/delay.h>
#define MAX_ID_LEN 4
static char force_device_id[MAX_ID_LEN + 1] = "";
module_param_string(force_device_id, force_device_id,
sizeof(force_device_id), 0);
MODULE_PARM_DESC(force_device_id, "Override detected product");
/*
* Get hardware mutex to block firmware from accessing the pld.
* It is possible for the firmware may hold the mutex for an extended length of
* time. This function will block until access has been granted.
*/
static void kempld_get_hardware_mutex(struct kempld_device_data *pld)
{
/* The mutex bit will read 1 until access has been granted */
while (ioread8(pld->io_index) & KEMPLD_MUTEX_KEY)
usleep_range(1000, 3000);
}
static void kempld_release_hardware_mutex(struct kempld_device_data *pld)
{
/* The harware mutex is released when 1 is written to the mutex bit. */
iowrite8(KEMPLD_MUTEX_KEY, pld->io_index);
}
static int kempld_get_info_generic(struct kempld_device_data *pld)
{
u16 version;
u8 spec;
kempld_get_mutex(pld);
version = kempld_read16(pld, KEMPLD_VERSION);
spec = kempld_read8(pld, KEMPLD_SPEC);
pld->info.buildnr = kempld_read16(pld, KEMPLD_BUILDNR);
pld->info.minor = KEMPLD_VERSION_GET_MINOR(version);
pld->info.major = KEMPLD_VERSION_GET_MAJOR(version);
pld->info.number = KEMPLD_VERSION_GET_NUMBER(version);
pld->info.type = KEMPLD_VERSION_GET_TYPE(version);
if (spec == 0xff) {
pld->info.spec_minor = 0;
pld->info.spec_major = 1;
} else {
pld->info.spec_minor = KEMPLD_SPEC_GET_MINOR(spec);
pld->info.spec_major = KEMPLD_SPEC_GET_MAJOR(spec);
}
if (pld->info.spec_major > 0)
pld->feature_mask = kempld_read16(pld, KEMPLD_FEATURE);
else
pld->feature_mask = 0;
kempld_release_mutex(pld);
return 0;
}
enum kempld_cells {
KEMPLD_I2C = 0,
KEMPLD_WDT,
KEMPLD_GPIO,
KEMPLD_UART,
};
static const struct mfd_cell kempld_devs[] = {
[KEMPLD_I2C] = {
.name = "kempld-i2c",
},
[KEMPLD_WDT] = {
.name = "kempld-wdt",
},
[KEMPLD_GPIO] = {
.name = "kempld-gpio",
},
[KEMPLD_UART] = {
.name = "kempld-uart",
},
};
#define KEMPLD_MAX_DEVS ARRAY_SIZE(kempld_devs)
static int kempld_register_cells_generic(struct kempld_device_data *pld)
{
struct mfd_cell devs[KEMPLD_MAX_DEVS];
int i = 0;
if (pld->feature_mask & KEMPLD_FEATURE_BIT_I2C)
devs[i++] = kempld_devs[KEMPLD_I2C];
if (pld->feature_mask & KEMPLD_FEATURE_BIT_WATCHDOG)
devs[i++] = kempld_devs[KEMPLD_WDT];
if (pld->feature_mask & KEMPLD_FEATURE_BIT_GPIO)
devs[i++] = kempld_devs[KEMPLD_GPIO];
if (pld->feature_mask & KEMPLD_FEATURE_MASK_UART)
devs[i++] = kempld_devs[KEMPLD_UART];
return mfd_add_devices(pld->dev, -1, devs, i, NULL, 0, NULL);
}
static struct resource kempld_ioresource = {
.start = KEMPLD_IOINDEX,
.end = KEMPLD_IODATA,
.flags = IORESOURCE_IO,
};
static const struct kempld_platform_data kempld_platform_data_generic = {
.pld_clock = KEMPLD_CLK,
.ioresource = &kempld_ioresource,
.get_hardware_mutex = kempld_get_hardware_mutex,
.release_hardware_mutex = kempld_release_hardware_mutex,
.get_info = kempld_get_info_generic,
.register_cells = kempld_register_cells_generic,
};
static struct platform_device *kempld_pdev;
static int kempld_create_platform_device(const struct dmi_system_id *id)
{
struct kempld_platform_data *pdata = id->driver_data;
int ret;
kempld_pdev = platform_device_alloc("kempld", -1);
if (!kempld_pdev)
return -ENOMEM;
ret = platform_device_add_data(kempld_pdev, pdata, sizeof(*pdata));
if (ret)
goto err;
ret = platform_device_add_resources(kempld_pdev, pdata->ioresource, 1);
if (ret)
goto err;
ret = platform_device_add(kempld_pdev);
if (ret)
goto err;
return 0;
err:
platform_device_put(kempld_pdev);
return ret;
}
/**
* kempld_read8 - read 8 bit register
* @pld: kempld_device_data structure describing the PLD
* @index: register index on the chip
*
* kempld_get_mutex must be called prior to calling this function.
*/
u8 kempld_read8(struct kempld_device_data *pld, u8 index)
{
iowrite8(index, pld->io_index);
return ioread8(pld->io_data);
}
EXPORT_SYMBOL_GPL(kempld_read8);
/**
* kempld_write8 - write 8 bit register
* @pld: kempld_device_data structure describing the PLD
* @index: register index on the chip
* @data: new register value
*
* kempld_get_mutex must be called prior to calling this function.
*/
void kempld_write8(struct kempld_device_data *pld, u8 index, u8 data)
{
iowrite8(index, pld->io_index);
iowrite8(data, pld->io_data);
}
EXPORT_SYMBOL_GPL(kempld_write8);
/**
* kempld_read16 - read 16 bit register
* @pld: kempld_device_data structure describing the PLD
* @index: register index on the chip
*
* kempld_get_mutex must be called prior to calling this function.
*/
u16 kempld_read16(struct kempld_device_data *pld, u8 index)
{
return kempld_read8(pld, index) | kempld_read8(pld, index + 1) << 8;
}
EXPORT_SYMBOL_GPL(kempld_read16);
/**
* kempld_write16 - write 16 bit register
* @pld: kempld_device_data structure describing the PLD
* @index: register index on the chip
* @data: new register value
*
* kempld_get_mutex must be called prior to calling this function.
*/
void kempld_write16(struct kempld_device_data *pld, u8 index, u16 data)
{
kempld_write8(pld, index, (u8)data);
kempld_write8(pld, index + 1, (u8)(data >> 8));
}
EXPORT_SYMBOL_GPL(kempld_write16);
/**
* kempld_read32 - read 32 bit register
* @pld: kempld_device_data structure describing the PLD
* @index: register index on the chip
*
* kempld_get_mutex must be called prior to calling this function.
*/
u32 kempld_read32(struct kempld_device_data *pld, u8 index)
{
return kempld_read16(pld, index) | kempld_read16(pld, index + 2) << 16;
}
EXPORT_SYMBOL_GPL(kempld_read32);
/**
* kempld_write32 - write 32 bit register
* @pld: kempld_device_data structure describing the PLD
* @index: register index on the chip
* @data: new register value
*
* kempld_get_mutex must be called prior to calling this function.
*/
void kempld_write32(struct kempld_device_data *pld, u8 index, u32 data)
{
kempld_write16(pld, index, (u16)data);
kempld_write16(pld, index + 2, (u16)(data >> 16));
}
EXPORT_SYMBOL_GPL(kempld_write32);
/**
* kempld_get_mutex - acquire PLD mutex
* @pld: kempld_device_data structure describing the PLD
*/
void kempld_get_mutex(struct kempld_device_data *pld)
{
struct kempld_platform_data *pdata = dev_get_platdata(pld->dev);
mutex_lock(&pld->lock);
pdata->get_hardware_mutex(pld);
}
EXPORT_SYMBOL_GPL(kempld_get_mutex);
/**
* kempld_release_mutex - release PLD mutex
* @pld: kempld_device_data structure describing the PLD
*/
void kempld_release_mutex(struct kempld_device_data *pld)
{
struct kempld_platform_data *pdata = dev_get_platdata(pld->dev);
pdata->release_hardware_mutex(pld);
mutex_unlock(&pld->lock);
}
EXPORT_SYMBOL_GPL(kempld_release_mutex);
/**
* kempld_get_info - update device specific information
* @pld: kempld_device_data structure describing the PLD
*
* This function calls the configured board specific kempld_get_info_XXXX
* function which is responsible for gathering information about the specific
* hardware. The information is then stored within the pld structure.
*/
static int kempld_get_info(struct kempld_device_data *pld)
{
int ret;
struct kempld_platform_data *pdata = dev_get_platdata(pld->dev);
char major, minor;
ret = pdata->get_info(pld);
if (ret)
return ret;
/* The Kontron PLD firmware version string has the following format:
* Pwxy.zzzz
* P: Fixed
* w: PLD number - 1 hex digit
* x: Major version - 1 alphanumerical digit (0-9A-V)
* y: Minor version - 1 alphanumerical digit (0-9A-V)
* zzzz: Build number - 4 zero padded hex digits */
if (pld->info.major < 10)
major = pld->info.major + '0';
else
major = (pld->info.major - 10) + 'A';
if (pld->info.minor < 10)
minor = pld->info.minor + '0';
else
minor = (pld->info.minor - 10) + 'A';
ret = scnprintf(pld->info.version, sizeof(pld->info.version),
"P%X%c%c.%04X", pld->info.number, major, minor,
pld->info.buildnr);
if (ret < 0)
return ret;
return 0;
}
/*
* kempld_register_cells - register cell drivers
*
* This function registers cell drivers for the detected hardware by calling
* the configured kempld_register_cells_XXXX function which is responsible
* to detect and register the needed cell drivers.
*/
static int kempld_register_cells(struct kempld_device_data *pld)
{
struct kempld_platform_data *pdata = dev_get_platdata(pld->dev);
return pdata->register_cells(pld);
}
static const char *kempld_get_type_string(struct kempld_device_data *pld)
{
const char *version_type;
switch (pld->info.type) {
case 0:
version_type = "release";
break;
case 1:
version_type = "debug";
break;
case 2:
version_type = "custom";
break;
default:
version_type = "unspecified";
break;
}
return version_type;
}
static ssize_t kempld_version_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct kempld_device_data *pld = dev_get_drvdata(dev);
return scnprintf(buf, PAGE_SIZE, "%s\n", pld->info.version);
}
static ssize_t kempld_specification_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct kempld_device_data *pld = dev_get_drvdata(dev);
return scnprintf(buf, PAGE_SIZE, "%d.%d\n", pld->info.spec_major,
pld->info.spec_minor);
}
static ssize_t kempld_type_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct kempld_device_data *pld = dev_get_drvdata(dev);
return scnprintf(buf, PAGE_SIZE, "%s\n", kempld_get_type_string(pld));
}
static DEVICE_ATTR(pld_version, S_IRUGO, kempld_version_show, NULL);
static DEVICE_ATTR(pld_specification, S_IRUGO, kempld_specification_show,
NULL);
static DEVICE_ATTR(pld_type, S_IRUGO, kempld_type_show, NULL);
static struct attribute *pld_attributes[] = {
&dev_attr_pld_version.attr,
&dev_attr_pld_specification.attr,
&dev_attr_pld_type.attr,
NULL
};
static const struct attribute_group pld_attr_group = {
.attrs = pld_attributes,
};
static int kempld_detect_device(struct kempld_device_data *pld)
{
u8 index_reg;
int ret;
mutex_lock(&pld->lock);
/* Check for empty IO space */
index_reg = ioread8(pld->io_index);
if (index_reg == 0xff && ioread8(pld->io_data) == 0xff) {
mutex_unlock(&pld->lock);
return -ENODEV;
}
/* Release hardware mutex if acquired */
if (!(index_reg & KEMPLD_MUTEX_KEY)) {
iowrite8(KEMPLD_MUTEX_KEY, pld->io_index);
/* PXT and COMe-cPC2 boards may require a second release */
iowrite8(KEMPLD_MUTEX_KEY, pld->io_index);
}
mutex_unlock(&pld->lock);
ret = kempld_get_info(pld);
if (ret)
return ret;
dev_info(pld->dev, "Found Kontron PLD - %s (%s), spec %d.%d\n",
pld->info.version, kempld_get_type_string(pld),
pld->info.spec_major, pld->info.spec_minor);
ret = sysfs_create_group(&pld->dev->kobj, &pld_attr_group);
if (ret)
return ret;
ret = kempld_register_cells(pld);
if (ret)
sysfs_remove_group(&pld->dev->kobj, &pld_attr_group);
return ret;
}
static int kempld_probe(struct platform_device *pdev)
{
struct kempld_platform_data *pdata = dev_get_platdata(&pdev->dev);
struct device *dev = &pdev->dev;
struct kempld_device_data *pld;
struct resource *ioport;
int ret;
pld = devm_kzalloc(dev, sizeof(*pld), GFP_KERNEL);
if (!pld)
return -ENOMEM;
ioport = platform_get_resource(pdev, IORESOURCE_IO, 0);
if (!ioport)
return -EINVAL;
pld->io_base = devm_ioport_map(dev, ioport->start,
ioport->end - ioport->start);
if (!pld->io_base)
return -ENOMEM;
pld->io_index = pld->io_base;
pld->io_data = pld->io_base + 1;
pld->pld_clock = pdata->pld_clock;
pld->dev = dev;
mutex_init(&pld->lock);
platform_set_drvdata(pdev, pld);
ret = kempld_detect_device(pld);
if (ret)
return ret;
return 0;
}
static int kempld_remove(struct platform_device *pdev)
{
struct kempld_device_data *pld = platform_get_drvdata(pdev);
struct kempld_platform_data *pdata = dev_get_platdata(pld->dev);
sysfs_remove_group(&pld->dev->kobj, &pld_attr_group);
mfd_remove_devices(&pdev->dev);
pdata->release_hardware_mutex(pld);
return 0;
}
static struct platform_driver kempld_driver = {
.driver = {
.name = "kempld",
},
.probe = kempld_probe,
.remove = kempld_remove,
};
static struct dmi_system_id kempld_dmi_table[] __initdata = {
{
.ident = "BBL6",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "COMe-bBL6"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "BHL6",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "COMe-bHL6"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "CBL6",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "COMe-cBL6"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "CBW6",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "COMe-cBW6"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "CCR2",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "COMe-bIP2"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "CCR6",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "COMe-bIP6"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "CHL6",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "COMe-cHL6"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "CHR2",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "ETXexpress-SC T2"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "CHR2",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "ETXe-SC T2"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "CHR2",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "COMe-bSC2"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "CHR6",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "ETXexpress-SC T6"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "CHR6",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "ETXe-SC T6"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "CHR6",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "COMe-bSC6"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "CNTG",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "ETXexpress-PC"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "CNTG",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "COMe-bPC2"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "CNTX",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "PXT"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "CVV6",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "COMe-cBT"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "FRI2",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BIOS_VERSION, "FRI2"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "FRI2",
.matches = {
DMI_MATCH(DMI_PRODUCT_NAME, "Fish River Island II"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "MBR1",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "ETX-OH"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "MVV1",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "COMe-mBT"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "NTC1",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "nanoETXexpress-TT"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "NTC1",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "nETXe-TT"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "NTC1",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "COMe-mTT"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "NUP1",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "COMe-mCT"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "UNP1",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "microETXexpress-DC"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "UNP1",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "COMe-cDC2"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "UNTG",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "microETXexpress-PC"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "UNTG",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "COMe-cPC2"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
}, {
.ident = "UUP6",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "COMe-cCT6"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
},
{
.ident = "UTH6",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Kontron"),
DMI_MATCH(DMI_BOARD_NAME, "COMe-cTH6"),
},
.driver_data = (void *)&kempld_platform_data_generic,
.callback = kempld_create_platform_device,
},
{}
};
MODULE_DEVICE_TABLE(dmi, kempld_dmi_table);
static int __init kempld_init(void)
{
const struct dmi_system_id *id;
int ret;
if (force_device_id[0]) {
for (id = kempld_dmi_table;
id->matches[0].slot != DMI_NONE; id++)
if (strstr(id->ident, force_device_id))
if (id->callback && !id->callback(id))
break;
if (id->matches[0].slot == DMI_NONE)
return -ENODEV;
} else {
if (!dmi_check_system(kempld_dmi_table))
return -ENODEV;
}
ret = platform_driver_register(&kempld_driver);
if (ret)
return ret;
return 0;
}
static void __exit kempld_exit(void)
{
if (kempld_pdev)
platform_device_unregister(kempld_pdev);
platform_driver_unregister(&kempld_driver);
}
module_init(kempld_init);
module_exit(kempld_exit);
MODULE_DESCRIPTION("KEM PLD Core Driver");
MODULE_AUTHOR("Michael Brunner <michael.brunner@kontron.com>");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:kempld-core");
| gpl-2.0 |
cavium-thunderx-open-source/linux | arch/powerpc/sysdev/fsl_mpic_err.c | 4301 | 3730 | /*
* Copyright (C) 2012 Freescale Semiconductor, Inc.
*
* Author: Varun Sethi <varun.sethi@freescale.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2 of the
* License.
*
*/
#include <linux/irq.h>
#include <linux/smp.h>
#include <linux/interrupt.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/mpic.h>
#include "mpic.h"
#define MPIC_ERR_INT_BASE 0x3900
#define MPIC_ERR_INT_EISR 0x0000
#define MPIC_ERR_INT_EIMR 0x0010
static inline u32 mpic_fsl_err_read(u32 __iomem *base, unsigned int err_reg)
{
return in_be32(base + (err_reg >> 2));
}
static inline void mpic_fsl_err_write(u32 __iomem *base, u32 value)
{
out_be32(base + (MPIC_ERR_INT_EIMR >> 2), value);
}
static void fsl_mpic_mask_err(struct irq_data *d)
{
u32 eimr;
struct mpic *mpic = irq_data_get_irq_chip_data(d);
unsigned int src = virq_to_hw(d->irq) - mpic->err_int_vecs[0];
eimr = mpic_fsl_err_read(mpic->err_regs, MPIC_ERR_INT_EIMR);
eimr |= (1 << (31 - src));
mpic_fsl_err_write(mpic->err_regs, eimr);
}
static void fsl_mpic_unmask_err(struct irq_data *d)
{
u32 eimr;
struct mpic *mpic = irq_data_get_irq_chip_data(d);
unsigned int src = virq_to_hw(d->irq) - mpic->err_int_vecs[0];
eimr = mpic_fsl_err_read(mpic->err_regs, MPIC_ERR_INT_EIMR);
eimr &= ~(1 << (31 - src));
mpic_fsl_err_write(mpic->err_regs, eimr);
}
static struct irq_chip fsl_mpic_err_chip = {
.irq_disable = fsl_mpic_mask_err,
.irq_mask = fsl_mpic_mask_err,
.irq_unmask = fsl_mpic_unmask_err,
};
int mpic_setup_error_int(struct mpic *mpic, int intvec)
{
int i;
mpic->err_regs = ioremap(mpic->paddr + MPIC_ERR_INT_BASE, 0x1000);
if (!mpic->err_regs) {
pr_err("could not map mpic error registers\n");
return -ENOMEM;
}
mpic->hc_err = fsl_mpic_err_chip;
mpic->hc_err.name = mpic->name;
mpic->flags |= MPIC_FSL_HAS_EIMR;
/* allocate interrupt vectors for error interrupts */
for (i = MPIC_MAX_ERR - 1; i >= 0; i--)
mpic->err_int_vecs[i] = --intvec;
return 0;
}
int mpic_map_error_int(struct mpic *mpic, unsigned int virq, irq_hw_number_t hw)
{
if ((mpic->flags & MPIC_FSL_HAS_EIMR) &&
(hw >= mpic->err_int_vecs[0] &&
hw <= mpic->err_int_vecs[MPIC_MAX_ERR - 1])) {
WARN_ON(mpic->flags & MPIC_SECONDARY);
pr_debug("mpic: mapping as Error Interrupt\n");
irq_set_chip_data(virq, mpic);
irq_set_chip_and_handler(virq, &mpic->hc_err,
handle_level_irq);
return 1;
}
return 0;
}
static irqreturn_t fsl_error_int_handler(int irq, void *data)
{
struct mpic *mpic = (struct mpic *) data;
u32 eisr, eimr;
int errint;
unsigned int cascade_irq;
eisr = mpic_fsl_err_read(mpic->err_regs, MPIC_ERR_INT_EISR);
eimr = mpic_fsl_err_read(mpic->err_regs, MPIC_ERR_INT_EIMR);
if (!(eisr & ~eimr))
return IRQ_NONE;
while (eisr) {
errint = __builtin_clz(eisr);
cascade_irq = irq_linear_revmap(mpic->irqhost,
mpic->err_int_vecs[errint]);
WARN_ON(cascade_irq == NO_IRQ);
if (cascade_irq != NO_IRQ) {
generic_handle_irq(cascade_irq);
} else {
eimr |= 1 << (31 - errint);
mpic_fsl_err_write(mpic->err_regs, eimr);
}
eisr &= ~(1 << (31 - errint));
}
return IRQ_HANDLED;
}
void mpic_err_int_init(struct mpic *mpic, irq_hw_number_t irqnum)
{
unsigned int virq;
int ret;
virq = irq_create_mapping(mpic->irqhost, irqnum);
if (virq == NO_IRQ) {
pr_err("Error interrupt setup failed\n");
return;
}
/* Mask all error interrupts */
mpic_fsl_err_write(mpic->err_regs, ~0);
ret = request_irq(virq, fsl_error_int_handler, IRQF_NO_THREAD,
"mpic-error-int", mpic);
if (ret)
pr_err("Failed to register error interrupt handler\n");
}
| gpl-2.0 |
moonlightly/LOSP_kernel_lge_mako | arch/s390/kernel/sys_s390.c | 4557 | 4238 | /*
* arch/s390/kernel/sys_s390.c
*
* S390 version
* Copyright (C) 1999,2000 IBM Deutschland Entwicklung GmbH, IBM Corporation
* Author(s): Martin Schwidefsky (schwidefsky@de.ibm.com),
* Thomas Spatzier (tspat@de.ibm.com)
*
* Derived from "arch/i386/kernel/sys_i386.c"
*
* This file contains various random system calls that
* have a non-standard calling sequence on the Linux/s390
* platform.
*/
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/fs.h>
#include <linux/smp.h>
#include <linux/sem.h>
#include <linux/msg.h>
#include <linux/shm.h>
#include <linux/stat.h>
#include <linux/syscalls.h>
#include <linux/mman.h>
#include <linux/file.h>
#include <linux/utsname.h>
#include <linux/personality.h>
#include <linux/unistd.h>
#include <linux/ipc.h>
#include <asm/uaccess.h>
#include "entry.h"
/*
* Perform the mmap() system call. Linux for S/390 isn't able to handle more
* than 5 system call parameters, so this system call uses a memory block
* for parameter passing.
*/
struct s390_mmap_arg_struct {
unsigned long addr;
unsigned long len;
unsigned long prot;
unsigned long flags;
unsigned long fd;
unsigned long offset;
};
SYSCALL_DEFINE1(mmap2, struct s390_mmap_arg_struct __user *, arg)
{
struct s390_mmap_arg_struct a;
int error = -EFAULT;
if (copy_from_user(&a, arg, sizeof(a)))
goto out;
error = sys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd, a.offset);
out:
return error;
}
/*
* sys_ipc() is the de-multiplexer for the SysV IPC calls.
*/
SYSCALL_DEFINE5(s390_ipc, uint, call, int, first, unsigned long, second,
unsigned long, third, void __user *, ptr)
{
if (call >> 16)
return -EINVAL;
/* The s390 sys_ipc variant has only five parameters instead of six
* like the generic variant. The only difference is the handling of
* the SEMTIMEDOP subcall where on s390 the third parameter is used
* as a pointer to a struct timespec where the generic variant uses
* the fifth parameter.
* Therefore we can call the generic variant by simply passing the
* third parameter also as fifth parameter.
*/
return sys_ipc(call, first, second, third, ptr, third);
}
#ifdef CONFIG_64BIT
SYSCALL_DEFINE1(s390_personality, unsigned int, personality)
{
unsigned int ret;
if (current->personality == PER_LINUX32 && personality == PER_LINUX)
personality = PER_LINUX32;
ret = sys_personality(personality);
if (ret == PER_LINUX32)
ret = PER_LINUX;
return ret;
}
#endif /* CONFIG_64BIT */
/*
* Wrapper function for sys_fadvise64/fadvise64_64
*/
#ifndef CONFIG_64BIT
SYSCALL_DEFINE5(s390_fadvise64, int, fd, u32, offset_high, u32, offset_low,
size_t, len, int, advice)
{
return sys_fadvise64(fd, (u64) offset_high << 32 | offset_low,
len, advice);
}
struct fadvise64_64_args {
int fd;
long long offset;
long long len;
int advice;
};
SYSCALL_DEFINE1(s390_fadvise64_64, struct fadvise64_64_args __user *, args)
{
struct fadvise64_64_args a;
if ( copy_from_user(&a, args, sizeof(a)) )
return -EFAULT;
return sys_fadvise64_64(a.fd, a.offset, a.len, a.advice);
}
/*
* This is a wrapper to call sys_fallocate(). For 31 bit s390 the last
* 64 bit argument "len" is split into the upper and lower 32 bits. The
* system call wrapper in the user space loads the value to %r6/%r7.
* The code in entry.S keeps the values in %r2 - %r6 where they are and
* stores %r7 to 96(%r15). But the standard C linkage requires that
* the whole 64 bit value for len is stored on the stack and doesn't
* use %r6 at all. So s390_fallocate has to convert the arguments from
* %r2: fd, %r3: mode, %r4/%r5: offset, %r6/96(%r15)-99(%r15): len
* to
* %r2: fd, %r3: mode, %r4/%r5: offset, 96(%r15)-103(%r15): len
*/
SYSCALL_DEFINE(s390_fallocate)(int fd, int mode, loff_t offset,
u32 len_high, u32 len_low)
{
return sys_fallocate(fd, mode, offset, ((u64)len_high << 32) | len_low);
}
#ifdef CONFIG_HAVE_SYSCALL_WRAPPERS
asmlinkage long SyS_s390_fallocate(long fd, long mode, loff_t offset,
long len_high, long len_low)
{
return SYSC_s390_fallocate((int) fd, (int) mode, offset,
(u32) len_high, (u32) len_low);
}
SYSCALL_ALIAS(sys_s390_fallocate, SyS_s390_fallocate);
#endif
#endif
| gpl-2.0 |
aapav01/kernel_ms013g_3-4-x | drivers/net/ethernet/mellanox/mlx4/profile.c | 4813 | 8456 | /*
* Copyright (c) 2004, 2005 Topspin Communications. All rights reserved.
* Copyright (c) 2005 Mellanox Technologies. All rights reserved.
* Copyright (c) 2006, 2007 Cisco Systems, Inc. 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/slab.h>
#include "mlx4.h"
#include "fw.h"
enum {
MLX4_RES_QP,
MLX4_RES_RDMARC,
MLX4_RES_ALTC,
MLX4_RES_AUXC,
MLX4_RES_SRQ,
MLX4_RES_CQ,
MLX4_RES_EQ,
MLX4_RES_DMPT,
MLX4_RES_CMPT,
MLX4_RES_MTT,
MLX4_RES_MCG,
MLX4_RES_NUM
};
static const char *res_name[] = {
[MLX4_RES_QP] = "QP",
[MLX4_RES_RDMARC] = "RDMARC",
[MLX4_RES_ALTC] = "ALTC",
[MLX4_RES_AUXC] = "AUXC",
[MLX4_RES_SRQ] = "SRQ",
[MLX4_RES_CQ] = "CQ",
[MLX4_RES_EQ] = "EQ",
[MLX4_RES_DMPT] = "DMPT",
[MLX4_RES_CMPT] = "CMPT",
[MLX4_RES_MTT] = "MTT",
[MLX4_RES_MCG] = "MCG",
};
u64 mlx4_make_profile(struct mlx4_dev *dev,
struct mlx4_profile *request,
struct mlx4_dev_cap *dev_cap,
struct mlx4_init_hca_param *init_hca)
{
struct mlx4_priv *priv = mlx4_priv(dev);
struct mlx4_resource {
u64 size;
u64 start;
int type;
int num;
int log_num;
};
u64 total_size = 0;
struct mlx4_resource *profile;
struct mlx4_resource tmp;
struct sysinfo si;
int i, j;
profile = kcalloc(MLX4_RES_NUM, sizeof(*profile), GFP_KERNEL);
if (!profile)
return -ENOMEM;
/*
* We want to scale the number of MTTs with the size of the
* system memory, since it makes sense to register a lot of
* memory on a system with a lot of memory. As a heuristic,
* make sure we have enough MTTs to cover twice the system
* memory (with PAGE_SIZE entries).
*
* This number has to be a power of two and fit into 32 bits
* due to device limitations, so cap this at 2^31 as well.
* That limits us to 8TB of memory registration per HCA with
* 4KB pages, which is probably OK for the next few months.
*/
si_meminfo(&si);
request->num_mtt =
roundup_pow_of_two(max_t(unsigned, request->num_mtt,
min(1UL << 31,
si.totalram >> (log_mtts_per_seg - 1))));
profile[MLX4_RES_QP].size = dev_cap->qpc_entry_sz;
profile[MLX4_RES_RDMARC].size = dev_cap->rdmarc_entry_sz;
profile[MLX4_RES_ALTC].size = dev_cap->altc_entry_sz;
profile[MLX4_RES_AUXC].size = dev_cap->aux_entry_sz;
profile[MLX4_RES_SRQ].size = dev_cap->srq_entry_sz;
profile[MLX4_RES_CQ].size = dev_cap->cqc_entry_sz;
profile[MLX4_RES_EQ].size = dev_cap->eqc_entry_sz;
profile[MLX4_RES_DMPT].size = dev_cap->dmpt_entry_sz;
profile[MLX4_RES_CMPT].size = dev_cap->cmpt_entry_sz;
profile[MLX4_RES_MTT].size = dev_cap->mtt_entry_sz;
profile[MLX4_RES_MCG].size = mlx4_get_mgm_entry_size(dev);
profile[MLX4_RES_QP].num = request->num_qp;
profile[MLX4_RES_RDMARC].num = request->num_qp * request->rdmarc_per_qp;
profile[MLX4_RES_ALTC].num = request->num_qp;
profile[MLX4_RES_AUXC].num = request->num_qp;
profile[MLX4_RES_SRQ].num = request->num_srq;
profile[MLX4_RES_CQ].num = request->num_cq;
profile[MLX4_RES_EQ].num = min_t(unsigned, dev_cap->max_eqs, MAX_MSIX);
profile[MLX4_RES_DMPT].num = request->num_mpt;
profile[MLX4_RES_CMPT].num = MLX4_NUM_CMPTS;
profile[MLX4_RES_MTT].num = request->num_mtt * (1 << log_mtts_per_seg);
profile[MLX4_RES_MCG].num = request->num_mcg;
for (i = 0; i < MLX4_RES_NUM; ++i) {
profile[i].type = i;
profile[i].num = roundup_pow_of_two(profile[i].num);
profile[i].log_num = ilog2(profile[i].num);
profile[i].size *= profile[i].num;
profile[i].size = max(profile[i].size, (u64) PAGE_SIZE);
}
/*
* Sort the resources in decreasing order of size. Since they
* all have sizes that are powers of 2, we'll be able to keep
* resources aligned to their size and pack them without gaps
* using the sorted order.
*/
for (i = MLX4_RES_NUM; i > 0; --i)
for (j = 1; j < i; ++j) {
if (profile[j].size > profile[j - 1].size) {
tmp = profile[j];
profile[j] = profile[j - 1];
profile[j - 1] = tmp;
}
}
for (i = 0; i < MLX4_RES_NUM; ++i) {
if (profile[i].size) {
profile[i].start = total_size;
total_size += profile[i].size;
}
if (total_size > dev_cap->max_icm_sz) {
mlx4_err(dev, "Profile requires 0x%llx bytes; "
"won't fit in 0x%llx bytes of context memory.\n",
(unsigned long long) total_size,
(unsigned long long) dev_cap->max_icm_sz);
kfree(profile);
return -ENOMEM;
}
if (profile[i].size)
mlx4_dbg(dev, " profile[%2d] (%6s): 2^%02d entries @ 0x%10llx, "
"size 0x%10llx\n",
i, res_name[profile[i].type], profile[i].log_num,
(unsigned long long) profile[i].start,
(unsigned long long) profile[i].size);
}
mlx4_dbg(dev, "HCA context memory: reserving %d KB\n",
(int) (total_size >> 10));
for (i = 0; i < MLX4_RES_NUM; ++i) {
switch (profile[i].type) {
case MLX4_RES_QP:
dev->caps.num_qps = profile[i].num;
init_hca->qpc_base = profile[i].start;
init_hca->log_num_qps = profile[i].log_num;
break;
case MLX4_RES_RDMARC:
for (priv->qp_table.rdmarc_shift = 0;
request->num_qp << priv->qp_table.rdmarc_shift < profile[i].num;
++priv->qp_table.rdmarc_shift)
; /* nothing */
dev->caps.max_qp_dest_rdma = 1 << priv->qp_table.rdmarc_shift;
priv->qp_table.rdmarc_base = (u32) profile[i].start;
init_hca->rdmarc_base = profile[i].start;
init_hca->log_rd_per_qp = priv->qp_table.rdmarc_shift;
break;
case MLX4_RES_ALTC:
init_hca->altc_base = profile[i].start;
break;
case MLX4_RES_AUXC:
init_hca->auxc_base = profile[i].start;
break;
case MLX4_RES_SRQ:
dev->caps.num_srqs = profile[i].num;
init_hca->srqc_base = profile[i].start;
init_hca->log_num_srqs = profile[i].log_num;
break;
case MLX4_RES_CQ:
dev->caps.num_cqs = profile[i].num;
init_hca->cqc_base = profile[i].start;
init_hca->log_num_cqs = profile[i].log_num;
break;
case MLX4_RES_EQ:
dev->caps.num_eqs = profile[i].num;
init_hca->eqc_base = profile[i].start;
init_hca->log_num_eqs = profile[i].log_num;
break;
case MLX4_RES_DMPT:
dev->caps.num_mpts = profile[i].num;
priv->mr_table.mpt_base = profile[i].start;
init_hca->dmpt_base = profile[i].start;
init_hca->log_mpt_sz = profile[i].log_num;
break;
case MLX4_RES_CMPT:
init_hca->cmpt_base = profile[i].start;
break;
case MLX4_RES_MTT:
dev->caps.num_mtts = profile[i].num;
priv->mr_table.mtt_base = profile[i].start;
init_hca->mtt_base = profile[i].start;
break;
case MLX4_RES_MCG:
dev->caps.num_mgms = profile[i].num >> 1;
dev->caps.num_amgms = profile[i].num >> 1;
init_hca->mc_base = profile[i].start;
init_hca->log_mc_entry_sz =
ilog2(mlx4_get_mgm_entry_size(dev));
init_hca->log_mc_table_sz = profile[i].log_num;
init_hca->log_mc_hash_sz = profile[i].log_num - 1;
break;
default:
break;
}
}
/*
* PDs don't take any HCA memory, but we assign them as part
* of the HCA profile anyway.
*/
dev->caps.num_pds = MLX4_NUM_PDS;
kfree(profile);
return total_size;
}
| gpl-2.0 |
intermediaterepresentation/android_kernel_htc_endeavor | arch/m68k/hp300/config.c | 4813 | 6634 | /*
* linux/arch/m68k/hp300/config.c
*
* Copyright (C) 1998 Philip Blundell <philb@gnu.org>
*
* This file contains the HP300-specific initialisation code. It gets
* called by setup.c.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/console.h>
#include <asm/bootinfo.h>
#include <asm/machdep.h>
#include <asm/blinken.h>
#include <asm/io.h> /* readb() and writeb() */
#include <asm/hp300hw.h>
#include <asm/rtc.h>
#include "time.h"
unsigned long hp300_model;
unsigned long hp300_uart_scode = -1;
unsigned char ledstate;
static char s_hp330[] __initdata = "330";
static char s_hp340[] __initdata = "340";
static char s_hp345[] __initdata = "345";
static char s_hp360[] __initdata = "360";
static char s_hp370[] __initdata = "370";
static char s_hp375[] __initdata = "375";
static char s_hp380[] __initdata = "380";
static char s_hp385[] __initdata = "385";
static char s_hp400[] __initdata = "400";
static char s_hp425t[] __initdata = "425t";
static char s_hp425s[] __initdata = "425s";
static char s_hp425e[] __initdata = "425e";
static char s_hp433t[] __initdata = "433t";
static char s_hp433s[] __initdata = "433s";
static char *hp300_models[] __initdata = {
[HP_320] = NULL,
[HP_330] = s_hp330,
[HP_340] = s_hp340,
[HP_345] = s_hp345,
[HP_350] = NULL,
[HP_360] = s_hp360,
[HP_370] = s_hp370,
[HP_375] = s_hp375,
[HP_380] = s_hp380,
[HP_385] = s_hp385,
[HP_400] = s_hp400,
[HP_425T] = s_hp425t,
[HP_425S] = s_hp425s,
[HP_425E] = s_hp425e,
[HP_433T] = s_hp433t,
[HP_433S] = s_hp433s,
};
static char hp300_model_name[13] = "HP9000/";
extern void hp300_reset(void);
#ifdef CONFIG_SERIAL_8250_CONSOLE
extern int hp300_setup_serial_console(void) __init;
#endif
int __init hp300_parse_bootinfo(const struct bi_record *record)
{
int unknown = 0;
const unsigned long *data = record->data;
switch (record->tag) {
case BI_HP300_MODEL:
hp300_model = *data;
break;
case BI_HP300_UART_SCODE:
hp300_uart_scode = *data;
break;
case BI_HP300_UART_ADDR:
/* serial port address: ignored here */
break;
default:
unknown = 1;
}
return unknown;
}
#ifdef CONFIG_HEARTBEAT
static void hp300_pulse(int x)
{
if (x)
blinken_leds(0x10, 0);
else
blinken_leds(0, 0x10);
}
#endif
static void hp300_get_model(char *model)
{
strcpy(model, hp300_model_name);
}
#define RTCBASE 0xf0420000
#define RTC_DATA 0x1
#define RTC_CMD 0x3
#define RTC_BUSY 0x02
#define RTC_DATA_RDY 0x01
#define rtc_busy() (in_8(RTCBASE + RTC_CMD) & RTC_BUSY)
#define rtc_data_available() (in_8(RTCBASE + RTC_CMD) & RTC_DATA_RDY)
#define rtc_status() (in_8(RTCBASE + RTC_CMD))
#define rtc_command(x) out_8(RTCBASE + RTC_CMD, (x))
#define rtc_read_data() (in_8(RTCBASE + RTC_DATA))
#define rtc_write_data(x) out_8(RTCBASE + RTC_DATA, (x))
#define RTC_SETREG 0xe0
#define RTC_WRITEREG 0xc2
#define RTC_READREG 0xc3
#define RTC_REG_SEC2 0
#define RTC_REG_SEC1 1
#define RTC_REG_MIN2 2
#define RTC_REG_MIN1 3
#define RTC_REG_HOUR2 4
#define RTC_REG_HOUR1 5
#define RTC_REG_WDAY 6
#define RTC_REG_DAY2 7
#define RTC_REG_DAY1 8
#define RTC_REG_MON2 9
#define RTC_REG_MON1 10
#define RTC_REG_YEAR2 11
#define RTC_REG_YEAR1 12
#define RTC_HOUR1_24HMODE 0x8
#define RTC_STAT_MASK 0xf0
#define RTC_STAT_RDY 0x40
static inline unsigned char hp300_rtc_read(unsigned char reg)
{
unsigned char s, ret;
unsigned long flags;
local_irq_save(flags);
while (rtc_busy());
rtc_command(RTC_SETREG);
while (rtc_busy());
rtc_write_data(reg);
while (rtc_busy());
rtc_command(RTC_READREG);
do {
while (!rtc_data_available());
s = rtc_status();
ret = rtc_read_data();
} while ((s & RTC_STAT_MASK) != RTC_STAT_RDY);
local_irq_restore(flags);
return ret;
}
static inline unsigned char hp300_rtc_write(unsigned char reg,
unsigned char val)
{
unsigned char s, ret;
unsigned long flags;
local_irq_save(flags);
while (rtc_busy());
rtc_command(RTC_SETREG);
while (rtc_busy());
rtc_write_data((val << 4) | reg);
while (rtc_busy());
rtc_command(RTC_WRITEREG);
while (rtc_busy());
rtc_command(RTC_READREG);
do {
while (!rtc_data_available());
s = rtc_status();
ret = rtc_read_data();
} while ((s & RTC_STAT_MASK) != RTC_STAT_RDY);
local_irq_restore(flags);
return ret;
}
static int hp300_hwclk(int op, struct rtc_time *t)
{
if (!op) { /* read */
t->tm_sec = hp300_rtc_read(RTC_REG_SEC1) * 10 +
hp300_rtc_read(RTC_REG_SEC2);
t->tm_min = hp300_rtc_read(RTC_REG_MIN1) * 10 +
hp300_rtc_read(RTC_REG_MIN2);
t->tm_hour = (hp300_rtc_read(RTC_REG_HOUR1) & 3) * 10 +
hp300_rtc_read(RTC_REG_HOUR2);
t->tm_wday = -1;
t->tm_mday = hp300_rtc_read(RTC_REG_DAY1) * 10 +
hp300_rtc_read(RTC_REG_DAY2);
t->tm_mon = hp300_rtc_read(RTC_REG_MON1) * 10 +
hp300_rtc_read(RTC_REG_MON2) - 1;
t->tm_year = hp300_rtc_read(RTC_REG_YEAR1) * 10 +
hp300_rtc_read(RTC_REG_YEAR2);
if (t->tm_year <= 69)
t->tm_year += 100;
} else {
hp300_rtc_write(RTC_REG_SEC1, t->tm_sec / 10);
hp300_rtc_write(RTC_REG_SEC2, t->tm_sec % 10);
hp300_rtc_write(RTC_REG_MIN1, t->tm_min / 10);
hp300_rtc_write(RTC_REG_MIN2, t->tm_min % 10);
hp300_rtc_write(RTC_REG_HOUR1,
((t->tm_hour / 10) & 3) | RTC_HOUR1_24HMODE);
hp300_rtc_write(RTC_REG_HOUR2, t->tm_hour % 10);
hp300_rtc_write(RTC_REG_DAY1, t->tm_mday / 10);
hp300_rtc_write(RTC_REG_DAY2, t->tm_mday % 10);
hp300_rtc_write(RTC_REG_MON1, (t->tm_mon + 1) / 10);
hp300_rtc_write(RTC_REG_MON2, (t->tm_mon + 1) % 10);
if (t->tm_year >= 100)
t->tm_year -= 100;
hp300_rtc_write(RTC_REG_YEAR1, t->tm_year / 10);
hp300_rtc_write(RTC_REG_YEAR2, t->tm_year % 10);
}
return 0;
}
static unsigned int hp300_get_ss(void)
{
return hp300_rtc_read(RTC_REG_SEC1) * 10 +
hp300_rtc_read(RTC_REG_SEC2);
}
static void __init hp300_init_IRQ(void)
{
}
void __init config_hp300(void)
{
mach_sched_init = hp300_sched_init;
mach_init_IRQ = hp300_init_IRQ;
mach_get_model = hp300_get_model;
mach_gettimeoffset = hp300_gettimeoffset;
mach_hwclk = hp300_hwclk;
mach_get_ss = hp300_get_ss;
mach_reset = hp300_reset;
#ifdef CONFIG_HEARTBEAT
mach_heartbeat = hp300_pulse;
#endif
mach_max_dma_address = 0xffffffff;
if (hp300_model >= HP_330 && hp300_model <= HP_433S && hp300_model != HP_350) {
printk(KERN_INFO "Detected HP9000 model %s\n", hp300_models[hp300_model-HP_320]);
strcat(hp300_model_name, hp300_models[hp300_model-HP_320]);
}
else {
panic("Unknown HP9000 Model");
}
#ifdef CONFIG_SERIAL_8250_CONSOLE
hp300_setup_serial_console();
#endif
}
| gpl-2.0 |
TeamRegular/android_kernel_lge_e2nxx | drivers/hid/usbhid/usbmouse.c | 4813 | 6549 | /*
* Copyright (c) 1999-2001 Vojtech Pavlik
*
* USB HIDBP Mouse support
*/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Should you need to contact me, the author, you can do so either by
* e-mail - mail your message to <vojtech@ucw.cz>, or by paper mail:
* Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/usb/input.h>
#include <linux/hid.h>
/* for apple IDs */
#ifdef CONFIG_USB_HID_MODULE
#include "../hid-ids.h"
#endif
/*
* Version Information
*/
#define DRIVER_VERSION "v1.6"
#define DRIVER_AUTHOR "Vojtech Pavlik <vojtech@ucw.cz>"
#define DRIVER_DESC "USB HID Boot Protocol mouse driver"
#define DRIVER_LICENSE "GPL"
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE(DRIVER_LICENSE);
struct usb_mouse {
char name[128];
char phys[64];
struct usb_device *usbdev;
struct input_dev *dev;
struct urb *irq;
signed char *data;
dma_addr_t data_dma;
};
static void usb_mouse_irq(struct urb *urb)
{
struct usb_mouse *mouse = urb->context;
signed char *data = mouse->data;
struct input_dev *dev = mouse->dev;
int status;
switch (urb->status) {
case 0: /* success */
break;
case -ECONNRESET: /* unlink */
case -ENOENT:
case -ESHUTDOWN:
return;
/* -EPIPE: should clear the halt */
default: /* error */
goto resubmit;
}
input_report_key(dev, BTN_LEFT, data[0] & 0x01);
input_report_key(dev, BTN_RIGHT, data[0] & 0x02);
input_report_key(dev, BTN_MIDDLE, data[0] & 0x04);
input_report_key(dev, BTN_SIDE, data[0] & 0x08);
input_report_key(dev, BTN_EXTRA, data[0] & 0x10);
input_report_rel(dev, REL_X, data[1]);
input_report_rel(dev, REL_Y, data[2]);
input_report_rel(dev, REL_WHEEL, data[3]);
input_sync(dev);
resubmit:
status = usb_submit_urb (urb, GFP_ATOMIC);
if (status)
err ("can't resubmit intr, %s-%s/input0, status %d",
mouse->usbdev->bus->bus_name,
mouse->usbdev->devpath, status);
}
static int usb_mouse_open(struct input_dev *dev)
{
struct usb_mouse *mouse = input_get_drvdata(dev);
mouse->irq->dev = mouse->usbdev;
if (usb_submit_urb(mouse->irq, GFP_KERNEL))
return -EIO;
return 0;
}
static void usb_mouse_close(struct input_dev *dev)
{
struct usb_mouse *mouse = input_get_drvdata(dev);
usb_kill_urb(mouse->irq);
}
static int usb_mouse_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct usb_device *dev = interface_to_usbdev(intf);
struct usb_host_interface *interface;
struct usb_endpoint_descriptor *endpoint;
struct usb_mouse *mouse;
struct input_dev *input_dev;
int pipe, maxp;
int error = -ENOMEM;
interface = intf->cur_altsetting;
if (interface->desc.bNumEndpoints != 1)
return -ENODEV;
endpoint = &interface->endpoint[0].desc;
if (!usb_endpoint_is_int_in(endpoint))
return -ENODEV;
pipe = usb_rcvintpipe(dev, endpoint->bEndpointAddress);
maxp = usb_maxpacket(dev, pipe, usb_pipeout(pipe));
mouse = kzalloc(sizeof(struct usb_mouse), GFP_KERNEL);
input_dev = input_allocate_device();
if (!mouse || !input_dev)
goto fail1;
mouse->data = usb_alloc_coherent(dev, 8, GFP_ATOMIC, &mouse->data_dma);
if (!mouse->data)
goto fail1;
mouse->irq = usb_alloc_urb(0, GFP_KERNEL);
if (!mouse->irq)
goto fail2;
mouse->usbdev = dev;
mouse->dev = input_dev;
if (dev->manufacturer)
strlcpy(mouse->name, dev->manufacturer, sizeof(mouse->name));
if (dev->product) {
if (dev->manufacturer)
strlcat(mouse->name, " ", sizeof(mouse->name));
strlcat(mouse->name, dev->product, sizeof(mouse->name));
}
if (!strlen(mouse->name))
snprintf(mouse->name, sizeof(mouse->name),
"USB HIDBP Mouse %04x:%04x",
le16_to_cpu(dev->descriptor.idVendor),
le16_to_cpu(dev->descriptor.idProduct));
usb_make_path(dev, mouse->phys, sizeof(mouse->phys));
strlcat(mouse->phys, "/input0", sizeof(mouse->phys));
input_dev->name = mouse->name;
input_dev->phys = mouse->phys;
usb_to_input_id(dev, &input_dev->id);
input_dev->dev.parent = &intf->dev;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL);
input_dev->keybit[BIT_WORD(BTN_MOUSE)] = BIT_MASK(BTN_LEFT) |
BIT_MASK(BTN_RIGHT) | BIT_MASK(BTN_MIDDLE);
input_dev->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y);
input_dev->keybit[BIT_WORD(BTN_MOUSE)] |= BIT_MASK(BTN_SIDE) |
BIT_MASK(BTN_EXTRA);
input_dev->relbit[0] |= BIT_MASK(REL_WHEEL);
input_set_drvdata(input_dev, mouse);
input_dev->open = usb_mouse_open;
input_dev->close = usb_mouse_close;
usb_fill_int_urb(mouse->irq, dev, pipe, mouse->data,
(maxp > 8 ? 8 : maxp),
usb_mouse_irq, mouse, endpoint->bInterval);
mouse->irq->transfer_dma = mouse->data_dma;
mouse->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
error = input_register_device(mouse->dev);
if (error)
goto fail3;
usb_set_intfdata(intf, mouse);
return 0;
fail3:
usb_free_urb(mouse->irq);
fail2:
usb_free_coherent(dev, 8, mouse->data, mouse->data_dma);
fail1:
input_free_device(input_dev);
kfree(mouse);
return error;
}
static void usb_mouse_disconnect(struct usb_interface *intf)
{
struct usb_mouse *mouse = usb_get_intfdata (intf);
usb_set_intfdata(intf, NULL);
if (mouse) {
usb_kill_urb(mouse->irq);
input_unregister_device(mouse->dev);
usb_free_urb(mouse->irq);
usb_free_coherent(interface_to_usbdev(intf), 8, mouse->data, mouse->data_dma);
kfree(mouse);
}
}
static struct usb_device_id usb_mouse_id_table [] = {
{ USB_INTERFACE_INFO(USB_INTERFACE_CLASS_HID, USB_INTERFACE_SUBCLASS_BOOT,
USB_INTERFACE_PROTOCOL_MOUSE) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE (usb, usb_mouse_id_table);
static struct usb_driver usb_mouse_driver = {
.name = "usbmouse",
.probe = usb_mouse_probe,
.disconnect = usb_mouse_disconnect,
.id_table = usb_mouse_id_table,
};
module_usb_driver(usb_mouse_driver);
| gpl-2.0 |
beats4x/kernel_lge_g3-v10m | drivers/cpufreq/e_powersaver.c | 5069 | 12700 | /*
* Based on documentation provided by Dave Jones. Thanks!
*
* Licensed under the terms of the GNU GPL License version 2.
*
* BIG FAT DISCLAIMER: Work in progress code. Possibly *dangerous*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/cpufreq.h>
#include <linux/ioport.h>
#include <linux/slab.h>
#include <linux/timex.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <asm/cpu_device_id.h>
#include <asm/msr.h>
#include <asm/tsc.h>
#if defined CONFIG_ACPI_PROCESSOR || defined CONFIG_ACPI_PROCESSOR_MODULE
#include <linux/acpi.h>
#include <acpi/processor.h>
#endif
#define EPS_BRAND_C7M 0
#define EPS_BRAND_C7 1
#define EPS_BRAND_EDEN 2
#define EPS_BRAND_C3 3
#define EPS_BRAND_C7D 4
struct eps_cpu_data {
u32 fsb;
#if defined CONFIG_ACPI_PROCESSOR || defined CONFIG_ACPI_PROCESSOR_MODULE
u32 bios_limit;
#endif
struct cpufreq_frequency_table freq_table[];
};
static struct eps_cpu_data *eps_cpu[NR_CPUS];
/* Module parameters */
static int freq_failsafe_off;
static int voltage_failsafe_off;
static int set_max_voltage;
#if defined CONFIG_ACPI_PROCESSOR || defined CONFIG_ACPI_PROCESSOR_MODULE
static int ignore_acpi_limit;
static struct acpi_processor_performance *eps_acpi_cpu_perf;
/* Minimum necessary to get acpi_processor_get_bios_limit() working */
static int eps_acpi_init(void)
{
eps_acpi_cpu_perf = kzalloc(sizeof(struct acpi_processor_performance),
GFP_KERNEL);
if (!eps_acpi_cpu_perf)
return -ENOMEM;
if (!zalloc_cpumask_var(&eps_acpi_cpu_perf->shared_cpu_map,
GFP_KERNEL)) {
kfree(eps_acpi_cpu_perf);
eps_acpi_cpu_perf = NULL;
return -ENOMEM;
}
if (acpi_processor_register_performance(eps_acpi_cpu_perf, 0)) {
free_cpumask_var(eps_acpi_cpu_perf->shared_cpu_map);
kfree(eps_acpi_cpu_perf);
eps_acpi_cpu_perf = NULL;
return -EIO;
}
return 0;
}
static int eps_acpi_exit(struct cpufreq_policy *policy)
{
if (eps_acpi_cpu_perf) {
acpi_processor_unregister_performance(eps_acpi_cpu_perf, 0);
free_cpumask_var(eps_acpi_cpu_perf->shared_cpu_map);
kfree(eps_acpi_cpu_perf);
eps_acpi_cpu_perf = NULL;
}
return 0;
}
#endif
static unsigned int eps_get(unsigned int cpu)
{
struct eps_cpu_data *centaur;
u32 lo, hi;
if (cpu)
return 0;
centaur = eps_cpu[cpu];
if (centaur == NULL)
return 0;
/* Return current frequency */
rdmsr(MSR_IA32_PERF_STATUS, lo, hi);
return centaur->fsb * ((lo >> 8) & 0xff);
}
static int eps_set_state(struct eps_cpu_data *centaur,
unsigned int cpu,
u32 dest_state)
{
struct cpufreq_freqs freqs;
u32 lo, hi;
int err = 0;
int i;
freqs.old = eps_get(cpu);
freqs.new = centaur->fsb * ((dest_state >> 8) & 0xff);
freqs.cpu = cpu;
cpufreq_notify_transition(&freqs, CPUFREQ_PRECHANGE);
/* Wait while CPU is busy */
rdmsr(MSR_IA32_PERF_STATUS, lo, hi);
i = 0;
while (lo & ((1 << 16) | (1 << 17))) {
udelay(16);
rdmsr(MSR_IA32_PERF_STATUS, lo, hi);
i++;
if (unlikely(i > 64)) {
err = -ENODEV;
goto postchange;
}
}
/* Set new multiplier and voltage */
wrmsr(MSR_IA32_PERF_CTL, dest_state & 0xffff, 0);
/* Wait until transition end */
i = 0;
do {
udelay(16);
rdmsr(MSR_IA32_PERF_STATUS, lo, hi);
i++;
if (unlikely(i > 64)) {
err = -ENODEV;
goto postchange;
}
} while (lo & ((1 << 16) | (1 << 17)));
/* Return current frequency */
postchange:
rdmsr(MSR_IA32_PERF_STATUS, lo, hi);
freqs.new = centaur->fsb * ((lo >> 8) & 0xff);
#ifdef DEBUG
{
u8 current_multiplier, current_voltage;
/* Print voltage and multiplier */
rdmsr(MSR_IA32_PERF_STATUS, lo, hi);
current_voltage = lo & 0xff;
printk(KERN_INFO "eps: Current voltage = %dmV\n",
current_voltage * 16 + 700);
current_multiplier = (lo >> 8) & 0xff;
printk(KERN_INFO "eps: Current multiplier = %d\n",
current_multiplier);
}
#endif
cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE);
return err;
}
static int eps_target(struct cpufreq_policy *policy,
unsigned int target_freq,
unsigned int relation)
{
struct eps_cpu_data *centaur;
unsigned int newstate = 0;
unsigned int cpu = policy->cpu;
unsigned int dest_state;
int ret;
if (unlikely(eps_cpu[cpu] == NULL))
return -ENODEV;
centaur = eps_cpu[cpu];
if (unlikely(cpufreq_frequency_table_target(policy,
&eps_cpu[cpu]->freq_table[0],
target_freq,
relation,
&newstate))) {
return -EINVAL;
}
/* Make frequency transition */
dest_state = centaur->freq_table[newstate].index & 0xffff;
ret = eps_set_state(centaur, cpu, dest_state);
if (ret)
printk(KERN_ERR "eps: Timeout!\n");
return ret;
}
static int eps_verify(struct cpufreq_policy *policy)
{
return cpufreq_frequency_table_verify(policy,
&eps_cpu[policy->cpu]->freq_table[0]);
}
static int eps_cpu_init(struct cpufreq_policy *policy)
{
unsigned int i;
u32 lo, hi;
u64 val;
u8 current_multiplier, current_voltage;
u8 max_multiplier, max_voltage;
u8 min_multiplier, min_voltage;
u8 brand = 0;
u32 fsb;
struct eps_cpu_data *centaur;
struct cpuinfo_x86 *c = &cpu_data(0);
struct cpufreq_frequency_table *f_table;
int k, step, voltage;
int ret;
int states;
#if defined CONFIG_ACPI_PROCESSOR || defined CONFIG_ACPI_PROCESSOR_MODULE
unsigned int limit;
#endif
if (policy->cpu != 0)
return -ENODEV;
/* Check brand */
printk(KERN_INFO "eps: Detected VIA ");
switch (c->x86_model) {
case 10:
rdmsr(0x1153, lo, hi);
brand = (((lo >> 2) ^ lo) >> 18) & 3;
printk(KERN_CONT "Model A ");
break;
case 13:
rdmsr(0x1154, lo, hi);
brand = (((lo >> 4) ^ (lo >> 2))) & 0x000000ff;
printk(KERN_CONT "Model D ");
break;
}
switch (brand) {
case EPS_BRAND_C7M:
printk(KERN_CONT "C7-M\n");
break;
case EPS_BRAND_C7:
printk(KERN_CONT "C7\n");
break;
case EPS_BRAND_EDEN:
printk(KERN_CONT "Eden\n");
break;
case EPS_BRAND_C7D:
printk(KERN_CONT "C7-D\n");
break;
case EPS_BRAND_C3:
printk(KERN_CONT "C3\n");
return -ENODEV;
break;
}
/* Enable Enhanced PowerSaver */
rdmsrl(MSR_IA32_MISC_ENABLE, val);
if (!(val & MSR_IA32_MISC_ENABLE_ENHANCED_SPEEDSTEP)) {
val |= MSR_IA32_MISC_ENABLE_ENHANCED_SPEEDSTEP;
wrmsrl(MSR_IA32_MISC_ENABLE, val);
/* Can be locked at 0 */
rdmsrl(MSR_IA32_MISC_ENABLE, val);
if (!(val & MSR_IA32_MISC_ENABLE_ENHANCED_SPEEDSTEP)) {
printk(KERN_INFO "eps: Can't enable Enhanced PowerSaver\n");
return -ENODEV;
}
}
/* Print voltage and multiplier */
rdmsr(MSR_IA32_PERF_STATUS, lo, hi);
current_voltage = lo & 0xff;
printk(KERN_INFO "eps: Current voltage = %dmV\n",
current_voltage * 16 + 700);
current_multiplier = (lo >> 8) & 0xff;
printk(KERN_INFO "eps: Current multiplier = %d\n", current_multiplier);
/* Print limits */
max_voltage = hi & 0xff;
printk(KERN_INFO "eps: Highest voltage = %dmV\n",
max_voltage * 16 + 700);
max_multiplier = (hi >> 8) & 0xff;
printk(KERN_INFO "eps: Highest multiplier = %d\n", max_multiplier);
min_voltage = (hi >> 16) & 0xff;
printk(KERN_INFO "eps: Lowest voltage = %dmV\n",
min_voltage * 16 + 700);
min_multiplier = (hi >> 24) & 0xff;
printk(KERN_INFO "eps: Lowest multiplier = %d\n", min_multiplier);
/* Sanity checks */
if (current_multiplier == 0 || max_multiplier == 0
|| min_multiplier == 0)
return -EINVAL;
if (current_multiplier > max_multiplier
|| max_multiplier <= min_multiplier)
return -EINVAL;
if (current_voltage > 0x1f || max_voltage > 0x1f)
return -EINVAL;
if (max_voltage < min_voltage
|| current_voltage < min_voltage
|| current_voltage > max_voltage)
return -EINVAL;
/* Check for systems using underclocked CPU */
if (!freq_failsafe_off && max_multiplier != current_multiplier) {
printk(KERN_INFO "eps: Your processor is running at different "
"frequency then its maximum. Aborting.\n");
printk(KERN_INFO "eps: You can use freq_failsafe_off option "
"to disable this check.\n");
return -EINVAL;
}
if (!voltage_failsafe_off && max_voltage != current_voltage) {
printk(KERN_INFO "eps: Your processor is running at different "
"voltage then its maximum. Aborting.\n");
printk(KERN_INFO "eps: You can use voltage_failsafe_off "
"option to disable this check.\n");
return -EINVAL;
}
/* Calc FSB speed */
fsb = cpu_khz / current_multiplier;
#if defined CONFIG_ACPI_PROCESSOR || defined CONFIG_ACPI_PROCESSOR_MODULE
/* Check for ACPI processor speed limit */
if (!ignore_acpi_limit && !eps_acpi_init()) {
if (!acpi_processor_get_bios_limit(policy->cpu, &limit)) {
printk(KERN_INFO "eps: ACPI limit %u.%uGHz\n",
limit/1000000,
(limit%1000000)/10000);
eps_acpi_exit(policy);
/* Check if max_multiplier is in BIOS limits */
if (limit && max_multiplier * fsb > limit) {
printk(KERN_INFO "eps: Aborting.\n");
return -EINVAL;
}
}
}
#endif
/* Allow user to set lower maximum voltage then that reported
* by processor */
if (brand == EPS_BRAND_C7M && set_max_voltage) {
u32 v;
/* Change mV to something hardware can use */
v = (set_max_voltage - 700) / 16;
/* Check if voltage is within limits */
if (v >= min_voltage && v <= max_voltage) {
printk(KERN_INFO "eps: Setting %dmV as maximum.\n",
v * 16 + 700);
max_voltage = v;
}
}
/* Calc number of p-states supported */
if (brand == EPS_BRAND_C7M)
states = max_multiplier - min_multiplier + 1;
else
states = 2;
/* Allocate private data and frequency table for current cpu */
centaur = kzalloc(sizeof(struct eps_cpu_data)
+ (states + 1) * sizeof(struct cpufreq_frequency_table),
GFP_KERNEL);
if (!centaur)
return -ENOMEM;
eps_cpu[0] = centaur;
/* Copy basic values */
centaur->fsb = fsb;
#if defined CONFIG_ACPI_PROCESSOR || defined CONFIG_ACPI_PROCESSOR_MODULE
centaur->bios_limit = limit;
#endif
/* Fill frequency and MSR value table */
f_table = ¢aur->freq_table[0];
if (brand != EPS_BRAND_C7M) {
f_table[0].frequency = fsb * min_multiplier;
f_table[0].index = (min_multiplier << 8) | min_voltage;
f_table[1].frequency = fsb * max_multiplier;
f_table[1].index = (max_multiplier << 8) | max_voltage;
f_table[2].frequency = CPUFREQ_TABLE_END;
} else {
k = 0;
step = ((max_voltage - min_voltage) * 256)
/ (max_multiplier - min_multiplier);
for (i = min_multiplier; i <= max_multiplier; i++) {
voltage = (k * step) / 256 + min_voltage;
f_table[k].frequency = fsb * i;
f_table[k].index = (i << 8) | voltage;
k++;
}
f_table[k].frequency = CPUFREQ_TABLE_END;
}
policy->cpuinfo.transition_latency = 140000; /* 844mV -> 700mV in ns */
policy->cur = fsb * current_multiplier;
ret = cpufreq_frequency_table_cpuinfo(policy, ¢aur->freq_table[0]);
if (ret) {
kfree(centaur);
return ret;
}
cpufreq_frequency_table_get_attr(¢aur->freq_table[0], policy->cpu);
return 0;
}
static int eps_cpu_exit(struct cpufreq_policy *policy)
{
unsigned int cpu = policy->cpu;
/* Bye */
cpufreq_frequency_table_put_attr(policy->cpu);
kfree(eps_cpu[cpu]);
eps_cpu[cpu] = NULL;
return 0;
}
static struct freq_attr *eps_attr[] = {
&cpufreq_freq_attr_scaling_available_freqs,
NULL,
};
static struct cpufreq_driver eps_driver = {
.verify = eps_verify,
.target = eps_target,
.init = eps_cpu_init,
.exit = eps_cpu_exit,
.get = eps_get,
.name = "e_powersaver",
.owner = THIS_MODULE,
.attr = eps_attr,
};
/* This driver will work only on Centaur C7 processors with
* Enhanced SpeedStep/PowerSaver registers */
static const struct x86_cpu_id eps_cpu_id[] = {
{ X86_VENDOR_CENTAUR, 6, X86_MODEL_ANY, X86_FEATURE_EST },
{}
};
MODULE_DEVICE_TABLE(x86cpu, eps_cpu_id);
static int __init eps_init(void)
{
if (!x86_match_cpu(eps_cpu_id) || boot_cpu_data.x86_model < 10)
return -ENODEV;
if (cpufreq_register_driver(&eps_driver))
return -EINVAL;
return 0;
}
static void __exit eps_exit(void)
{
cpufreq_unregister_driver(&eps_driver);
}
/* Allow user to overclock his machine or to change frequency to higher after
* unloading module */
module_param(freq_failsafe_off, int, 0644);
MODULE_PARM_DESC(freq_failsafe_off, "Disable current vs max frequency check");
module_param(voltage_failsafe_off, int, 0644);
MODULE_PARM_DESC(voltage_failsafe_off, "Disable current vs max voltage check");
#if defined CONFIG_ACPI_PROCESSOR || defined CONFIG_ACPI_PROCESSOR_MODULE
module_param(ignore_acpi_limit, int, 0644);
MODULE_PARM_DESC(ignore_acpi_limit, "Don't check ACPI's processor speed limit");
#endif
module_param(set_max_voltage, int, 0644);
MODULE_PARM_DESC(set_max_voltage, "Set maximum CPU voltage (mV) C7-M only");
MODULE_AUTHOR("Rafal Bilski <rafalbilski@interia.pl>");
MODULE_DESCRIPTION("Enhanced PowerSaver driver for VIA C7 CPU's.");
MODULE_LICENSE("GPL");
module_init(eps_init);
module_exit(eps_exit);
| gpl-2.0 |
juanxincai521/us780 | net/netfilter/nf_conntrack_irc.c | 7629 | 8099 | /* IRC extension for IP connection tracking, Version 1.21
* (C) 2000-2002 by Harald Welte <laforge@gnumonks.org>
* based on RR's ip_conntrack_ftp.c
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/skbuff.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/netfilter.h>
#include <linux/slab.h>
#include <net/netfilter/nf_conntrack.h>
#include <net/netfilter/nf_conntrack_expect.h>
#include <net/netfilter/nf_conntrack_helper.h>
#include <linux/netfilter/nf_conntrack_irc.h>
#define MAX_PORTS 8
static unsigned short ports[MAX_PORTS];
static unsigned int ports_c;
static unsigned int max_dcc_channels = 8;
static unsigned int dcc_timeout __read_mostly = 300;
/* This is slow, but it's simple. --RR */
static char *irc_buffer;
static DEFINE_SPINLOCK(irc_buffer_lock);
unsigned int (*nf_nat_irc_hook)(struct sk_buff *skb,
enum ip_conntrack_info ctinfo,
unsigned int matchoff,
unsigned int matchlen,
struct nf_conntrack_expect *exp) __read_mostly;
EXPORT_SYMBOL_GPL(nf_nat_irc_hook);
MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>");
MODULE_DESCRIPTION("IRC (DCC) connection tracking helper");
MODULE_LICENSE("GPL");
MODULE_ALIAS("ip_conntrack_irc");
MODULE_ALIAS_NFCT_HELPER("irc");
module_param_array(ports, ushort, &ports_c, 0400);
MODULE_PARM_DESC(ports, "port numbers of IRC servers");
module_param(max_dcc_channels, uint, 0400);
MODULE_PARM_DESC(max_dcc_channels, "max number of expected DCC channels per "
"IRC session");
module_param(dcc_timeout, uint, 0400);
MODULE_PARM_DESC(dcc_timeout, "timeout on for unestablished DCC channels");
static const char *const dccprotos[] = {
"SEND ", "CHAT ", "MOVE ", "TSEND ", "SCHAT "
};
#define MINMATCHLEN 5
/* tries to get the ip_addr and port out of a dcc command
* return value: -1 on failure, 0 on success
* data pointer to first byte of DCC command data
* data_end pointer to last byte of dcc command data
* ip returns parsed ip of dcc command
* port returns parsed port of dcc command
* ad_beg_p returns pointer to first byte of addr data
* ad_end_p returns pointer to last byte of addr data
*/
static int parse_dcc(char *data, const char *data_end, __be32 *ip,
u_int16_t *port, char **ad_beg_p, char **ad_end_p)
{
char *tmp;
/* at least 12: "AAAAAAAA P\1\n" */
while (*data++ != ' ')
if (data > data_end - 12)
return -1;
/* Make sure we have a newline character within the packet boundaries
* because simple_strtoul parses until the first invalid character. */
for (tmp = data; tmp <= data_end; tmp++)
if (*tmp == '\n')
break;
if (tmp > data_end || *tmp != '\n')
return -1;
*ad_beg_p = data;
*ip = cpu_to_be32(simple_strtoul(data, &data, 10));
/* skip blanks between ip and port */
while (*data == ' ') {
if (data >= data_end)
return -1;
data++;
}
*port = simple_strtoul(data, &data, 10);
*ad_end_p = data;
return 0;
}
static int help(struct sk_buff *skb, unsigned int protoff,
struct nf_conn *ct, enum ip_conntrack_info ctinfo)
{
unsigned int dataoff;
const struct iphdr *iph;
const struct tcphdr *th;
struct tcphdr _tcph;
const char *data_limit;
char *data, *ib_ptr;
int dir = CTINFO2DIR(ctinfo);
struct nf_conntrack_expect *exp;
struct nf_conntrack_tuple *tuple;
__be32 dcc_ip;
u_int16_t dcc_port;
__be16 port;
int i, ret = NF_ACCEPT;
char *addr_beg_p, *addr_end_p;
typeof(nf_nat_irc_hook) nf_nat_irc;
/* If packet is coming from IRC server */
if (dir == IP_CT_DIR_REPLY)
return NF_ACCEPT;
/* Until there's been traffic both ways, don't look in packets. */
if (ctinfo != IP_CT_ESTABLISHED && ctinfo != IP_CT_ESTABLISHED_REPLY)
return NF_ACCEPT;
/* Not a full tcp header? */
th = skb_header_pointer(skb, protoff, sizeof(_tcph), &_tcph);
if (th == NULL)
return NF_ACCEPT;
/* No data? */
dataoff = protoff + th->doff*4;
if (dataoff >= skb->len)
return NF_ACCEPT;
spin_lock_bh(&irc_buffer_lock);
ib_ptr = skb_header_pointer(skb, dataoff, skb->len - dataoff,
irc_buffer);
BUG_ON(ib_ptr == NULL);
data = ib_ptr;
data_limit = ib_ptr + skb->len - dataoff;
/* strlen("\1DCC SENT t AAAAAAAA P\1\n")=24
* 5+MINMATCHLEN+strlen("t AAAAAAAA P\1\n")=14 */
while (data < data_limit - (19 + MINMATCHLEN)) {
if (memcmp(data, "\1DCC ", 5)) {
data++;
continue;
}
data += 5;
/* we have at least (19+MINMATCHLEN)-5 bytes valid data left */
iph = ip_hdr(skb);
pr_debug("DCC found in master %pI4:%u %pI4:%u\n",
&iph->saddr, ntohs(th->source),
&iph->daddr, ntohs(th->dest));
for (i = 0; i < ARRAY_SIZE(dccprotos); i++) {
if (memcmp(data, dccprotos[i], strlen(dccprotos[i]))) {
/* no match */
continue;
}
data += strlen(dccprotos[i]);
pr_debug("DCC %s detected\n", dccprotos[i]);
/* we have at least
* (19+MINMATCHLEN)-5-dccprotos[i].matchlen bytes valid
* data left (== 14/13 bytes) */
if (parse_dcc(data, data_limit, &dcc_ip,
&dcc_port, &addr_beg_p, &addr_end_p)) {
pr_debug("unable to parse dcc command\n");
continue;
}
pr_debug("DCC bound ip/port: %pI4:%u\n",
&dcc_ip, dcc_port);
/* dcc_ip can be the internal OR external (NAT'ed) IP */
tuple = &ct->tuplehash[dir].tuple;
if (tuple->src.u3.ip != dcc_ip &&
tuple->dst.u3.ip != dcc_ip) {
if (net_ratelimit())
printk(KERN_WARNING
"Forged DCC command from %pI4: %pI4:%u\n",
&tuple->src.u3.ip,
&dcc_ip, dcc_port);
continue;
}
exp = nf_ct_expect_alloc(ct);
if (exp == NULL) {
ret = NF_DROP;
goto out;
}
tuple = &ct->tuplehash[!dir].tuple;
port = htons(dcc_port);
nf_ct_expect_init(exp, NF_CT_EXPECT_CLASS_DEFAULT,
tuple->src.l3num,
NULL, &tuple->dst.u3,
IPPROTO_TCP, NULL, &port);
nf_nat_irc = rcu_dereference(nf_nat_irc_hook);
if (nf_nat_irc && ct->status & IPS_NAT_MASK)
ret = nf_nat_irc(skb, ctinfo,
addr_beg_p - ib_ptr,
addr_end_p - addr_beg_p,
exp);
else if (nf_ct_expect_related(exp) != 0)
ret = NF_DROP;
nf_ct_expect_put(exp);
goto out;
}
}
out:
spin_unlock_bh(&irc_buffer_lock);
return ret;
}
static struct nf_conntrack_helper irc[MAX_PORTS] __read_mostly;
static char irc_names[MAX_PORTS][sizeof("irc-65535")] __read_mostly;
static struct nf_conntrack_expect_policy irc_exp_policy;
static void nf_conntrack_irc_fini(void);
static int __init nf_conntrack_irc_init(void)
{
int i, ret;
char *tmpname;
if (max_dcc_channels < 1) {
printk(KERN_ERR "nf_ct_irc: max_dcc_channels must not be zero\n");
return -EINVAL;
}
irc_exp_policy.max_expected = max_dcc_channels;
irc_exp_policy.timeout = dcc_timeout;
irc_buffer = kmalloc(65536, GFP_KERNEL);
if (!irc_buffer)
return -ENOMEM;
/* If no port given, default to standard irc port */
if (ports_c == 0)
ports[ports_c++] = IRC_PORT;
for (i = 0; i < ports_c; i++) {
irc[i].tuple.src.l3num = AF_INET;
irc[i].tuple.src.u.tcp.port = htons(ports[i]);
irc[i].tuple.dst.protonum = IPPROTO_TCP;
irc[i].expect_policy = &irc_exp_policy;
irc[i].me = THIS_MODULE;
irc[i].help = help;
tmpname = &irc_names[i][0];
if (ports[i] == IRC_PORT)
sprintf(tmpname, "irc");
else
sprintf(tmpname, "irc-%u", i);
irc[i].name = tmpname;
ret = nf_conntrack_helper_register(&irc[i]);
if (ret) {
printk(KERN_ERR "nf_ct_irc: failed to register helper "
"for pf: %u port: %u\n",
irc[i].tuple.src.l3num, ports[i]);
nf_conntrack_irc_fini();
return ret;
}
}
return 0;
}
/* This function is intentionally _NOT_ defined as __exit, because
* it is needed by the init function */
static void nf_conntrack_irc_fini(void)
{
int i;
for (i = 0; i < ports_c; i++)
nf_conntrack_helper_unregister(&irc[i]);
kfree(irc_buffer);
}
module_init(nf_conntrack_irc_init);
module_exit(nf_conntrack_irc_fini);
| gpl-2.0 |
pershoot/android_kernel_asus_tf701t | net/ipv4/netfilter/arpt_mangle.c | 12749 | 2389 | /* module that allows mangling of the arp payload */
#include <linux/module.h>
#include <linux/netfilter.h>
#include <linux/netfilter_arp/arpt_mangle.h>
#include <net/sock.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Bart De Schuymer <bdschuym@pandora.be>");
MODULE_DESCRIPTION("arptables arp payload mangle target");
static unsigned int
target(struct sk_buff *skb, const struct xt_action_param *par)
{
const struct arpt_mangle *mangle = par->targinfo;
const struct arphdr *arp;
unsigned char *arpptr;
int pln, hln;
if (!skb_make_writable(skb, skb->len))
return NF_DROP;
arp = arp_hdr(skb);
arpptr = skb_network_header(skb) + sizeof(*arp);
pln = arp->ar_pln;
hln = arp->ar_hln;
/* We assume that pln and hln were checked in the match */
if (mangle->flags & ARPT_MANGLE_SDEV) {
if (ARPT_DEV_ADDR_LEN_MAX < hln ||
(arpptr + hln > skb_tail_pointer(skb)))
return NF_DROP;
memcpy(arpptr, mangle->src_devaddr, hln);
}
arpptr += hln;
if (mangle->flags & ARPT_MANGLE_SIP) {
if (ARPT_MANGLE_ADDR_LEN_MAX < pln ||
(arpptr + pln > skb_tail_pointer(skb)))
return NF_DROP;
memcpy(arpptr, &mangle->u_s.src_ip, pln);
}
arpptr += pln;
if (mangle->flags & ARPT_MANGLE_TDEV) {
if (ARPT_DEV_ADDR_LEN_MAX < hln ||
(arpptr + hln > skb_tail_pointer(skb)))
return NF_DROP;
memcpy(arpptr, mangle->tgt_devaddr, hln);
}
arpptr += hln;
if (mangle->flags & ARPT_MANGLE_TIP) {
if (ARPT_MANGLE_ADDR_LEN_MAX < pln ||
(arpptr + pln > skb_tail_pointer(skb)))
return NF_DROP;
memcpy(arpptr, &mangle->u_t.tgt_ip, pln);
}
return mangle->target;
}
static int checkentry(const struct xt_tgchk_param *par)
{
const struct arpt_mangle *mangle = par->targinfo;
if (mangle->flags & ~ARPT_MANGLE_MASK ||
!(mangle->flags & ARPT_MANGLE_MASK))
return -EINVAL;
if (mangle->target != NF_DROP && mangle->target != NF_ACCEPT &&
mangle->target != XT_CONTINUE)
return -EINVAL;
return 0;
}
static struct xt_target arpt_mangle_reg __read_mostly = {
.name = "mangle",
.family = NFPROTO_ARP,
.target = target,
.targetsize = sizeof(struct arpt_mangle),
.checkentry = checkentry,
.me = THIS_MODULE,
};
static int __init arpt_mangle_init(void)
{
return xt_register_target(&arpt_mangle_reg);
}
static void __exit arpt_mangle_fini(void)
{
xt_unregister_target(&arpt_mangle_reg);
}
module_init(arpt_mangle_init);
module_exit(arpt_mangle_fini);
| gpl-2.0 |
zarboz/brick_kernel_msm8960 | net/ipv4/netfilter/arpt_mangle.c | 12749 | 2389 | /* module that allows mangling of the arp payload */
#include <linux/module.h>
#include <linux/netfilter.h>
#include <linux/netfilter_arp/arpt_mangle.h>
#include <net/sock.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Bart De Schuymer <bdschuym@pandora.be>");
MODULE_DESCRIPTION("arptables arp payload mangle target");
static unsigned int
target(struct sk_buff *skb, const struct xt_action_param *par)
{
const struct arpt_mangle *mangle = par->targinfo;
const struct arphdr *arp;
unsigned char *arpptr;
int pln, hln;
if (!skb_make_writable(skb, skb->len))
return NF_DROP;
arp = arp_hdr(skb);
arpptr = skb_network_header(skb) + sizeof(*arp);
pln = arp->ar_pln;
hln = arp->ar_hln;
/* We assume that pln and hln were checked in the match */
if (mangle->flags & ARPT_MANGLE_SDEV) {
if (ARPT_DEV_ADDR_LEN_MAX < hln ||
(arpptr + hln > skb_tail_pointer(skb)))
return NF_DROP;
memcpy(arpptr, mangle->src_devaddr, hln);
}
arpptr += hln;
if (mangle->flags & ARPT_MANGLE_SIP) {
if (ARPT_MANGLE_ADDR_LEN_MAX < pln ||
(arpptr + pln > skb_tail_pointer(skb)))
return NF_DROP;
memcpy(arpptr, &mangle->u_s.src_ip, pln);
}
arpptr += pln;
if (mangle->flags & ARPT_MANGLE_TDEV) {
if (ARPT_DEV_ADDR_LEN_MAX < hln ||
(arpptr + hln > skb_tail_pointer(skb)))
return NF_DROP;
memcpy(arpptr, mangle->tgt_devaddr, hln);
}
arpptr += hln;
if (mangle->flags & ARPT_MANGLE_TIP) {
if (ARPT_MANGLE_ADDR_LEN_MAX < pln ||
(arpptr + pln > skb_tail_pointer(skb)))
return NF_DROP;
memcpy(arpptr, &mangle->u_t.tgt_ip, pln);
}
return mangle->target;
}
static int checkentry(const struct xt_tgchk_param *par)
{
const struct arpt_mangle *mangle = par->targinfo;
if (mangle->flags & ~ARPT_MANGLE_MASK ||
!(mangle->flags & ARPT_MANGLE_MASK))
return -EINVAL;
if (mangle->target != NF_DROP && mangle->target != NF_ACCEPT &&
mangle->target != XT_CONTINUE)
return -EINVAL;
return 0;
}
static struct xt_target arpt_mangle_reg __read_mostly = {
.name = "mangle",
.family = NFPROTO_ARP,
.target = target,
.targetsize = sizeof(struct arpt_mangle),
.checkentry = checkentry,
.me = THIS_MODULE,
};
static int __init arpt_mangle_init(void)
{
return xt_register_target(&arpt_mangle_reg);
}
static void __exit arpt_mangle_fini(void)
{
xt_unregister_target(&arpt_mangle_reg);
}
module_init(arpt_mangle_init);
module_exit(arpt_mangle_fini);
| gpl-2.0 |
CyanogenMod/android_kernel_samsung_aries | arch/avr32/mm/tlb.c | 13005 | 8501 | /*
* AVR32 TLB operations
*
* Copyright (C) 2004-2006 Atmel Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/mm.h>
#include <asm/mmu_context.h>
/* TODO: Get the correct number from the CONFIG1 system register */
#define NR_TLB_ENTRIES 32
static void show_dtlb_entry(unsigned int index)
{
u32 tlbehi, tlbehi_save, tlbelo, mmucr, mmucr_save;
unsigned long flags;
local_irq_save(flags);
mmucr_save = sysreg_read(MMUCR);
tlbehi_save = sysreg_read(TLBEHI);
mmucr = SYSREG_BFINS(DRP, index, mmucr_save);
sysreg_write(MMUCR, mmucr);
__builtin_tlbr();
cpu_sync_pipeline();
tlbehi = sysreg_read(TLBEHI);
tlbelo = sysreg_read(TLBELO);
printk("%2u: %c %c %02x %05x %05x %o %o %c %c %c %c\n",
index,
SYSREG_BFEXT(TLBEHI_V, tlbehi) ? '1' : '0',
SYSREG_BFEXT(G, tlbelo) ? '1' : '0',
SYSREG_BFEXT(ASID, tlbehi),
SYSREG_BFEXT(VPN, tlbehi) >> 2,
SYSREG_BFEXT(PFN, tlbelo) >> 2,
SYSREG_BFEXT(AP, tlbelo),
SYSREG_BFEXT(SZ, tlbelo),
SYSREG_BFEXT(TLBELO_C, tlbelo) ? 'C' : ' ',
SYSREG_BFEXT(B, tlbelo) ? 'B' : ' ',
SYSREG_BFEXT(W, tlbelo) ? 'W' : ' ',
SYSREG_BFEXT(TLBELO_D, tlbelo) ? 'D' : ' ');
sysreg_write(MMUCR, mmucr_save);
sysreg_write(TLBEHI, tlbehi_save);
cpu_sync_pipeline();
local_irq_restore(flags);
}
void dump_dtlb(void)
{
unsigned int i;
printk("ID V G ASID VPN PFN AP SZ C B W D\n");
for (i = 0; i < NR_TLB_ENTRIES; i++)
show_dtlb_entry(i);
}
static void update_dtlb(unsigned long address, pte_t pte)
{
u32 tlbehi;
u32 mmucr;
/*
* We're not changing the ASID here, so no need to flush the
* pipeline.
*/
tlbehi = sysreg_read(TLBEHI);
tlbehi = SYSREG_BF(ASID, SYSREG_BFEXT(ASID, tlbehi));
tlbehi |= address & MMU_VPN_MASK;
tlbehi |= SYSREG_BIT(TLBEHI_V);
sysreg_write(TLBEHI, tlbehi);
/* Does this mapping already exist? */
__builtin_tlbs();
mmucr = sysreg_read(MMUCR);
if (mmucr & SYSREG_BIT(MMUCR_N)) {
/* Not found -- pick a not-recently-accessed entry */
unsigned int rp;
u32 tlbar = sysreg_read(TLBARLO);
rp = 32 - fls(tlbar);
if (rp == 32) {
rp = 0;
sysreg_write(TLBARLO, -1L);
}
mmucr = SYSREG_BFINS(DRP, rp, mmucr);
sysreg_write(MMUCR, mmucr);
}
sysreg_write(TLBELO, pte_val(pte) & _PAGE_FLAGS_HARDWARE_MASK);
/* Let's go */
__builtin_tlbw();
}
void update_mmu_cache(struct vm_area_struct *vma,
unsigned long address, pte_t *ptep)
{
unsigned long flags;
/* ptrace may call this routine */
if (vma && current->active_mm != vma->vm_mm)
return;
local_irq_save(flags);
update_dtlb(address, *ptep);
local_irq_restore(flags);
}
static void __flush_tlb_page(unsigned long asid, unsigned long page)
{
u32 mmucr, tlbehi;
/*
* Caller is responsible for masking out non-PFN bits in page
* and changing the current ASID if necessary. This means that
* we don't need to flush the pipeline after writing TLBEHI.
*/
tlbehi = page | asid;
sysreg_write(TLBEHI, tlbehi);
__builtin_tlbs();
mmucr = sysreg_read(MMUCR);
if (!(mmucr & SYSREG_BIT(MMUCR_N))) {
unsigned int entry;
u32 tlbarlo;
/* Clear the "valid" bit */
sysreg_write(TLBEHI, tlbehi);
/* mark the entry as "not accessed" */
entry = SYSREG_BFEXT(DRP, mmucr);
tlbarlo = sysreg_read(TLBARLO);
tlbarlo |= (0x80000000UL >> entry);
sysreg_write(TLBARLO, tlbarlo);
/* update the entry with valid bit clear */
__builtin_tlbw();
}
}
void flush_tlb_page(struct vm_area_struct *vma, unsigned long page)
{
if (vma->vm_mm && vma->vm_mm->context != NO_CONTEXT) {
unsigned long flags, asid;
unsigned long saved_asid = MMU_NO_ASID;
asid = vma->vm_mm->context & MMU_CONTEXT_ASID_MASK;
page &= PAGE_MASK;
local_irq_save(flags);
if (vma->vm_mm != current->mm) {
saved_asid = get_asid();
set_asid(asid);
}
__flush_tlb_page(asid, page);
if (saved_asid != MMU_NO_ASID)
set_asid(saved_asid);
local_irq_restore(flags);
}
}
void flush_tlb_range(struct vm_area_struct *vma, unsigned long start,
unsigned long end)
{
struct mm_struct *mm = vma->vm_mm;
if (mm->context != NO_CONTEXT) {
unsigned long flags;
int size;
local_irq_save(flags);
size = (end - start + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
if (size > (MMU_DTLB_ENTRIES / 4)) { /* Too many entries to flush */
mm->context = NO_CONTEXT;
if (mm == current->mm)
activate_context(mm);
} else {
unsigned long asid;
unsigned long saved_asid;
asid = mm->context & MMU_CONTEXT_ASID_MASK;
saved_asid = MMU_NO_ASID;
start &= PAGE_MASK;
end += (PAGE_SIZE - 1);
end &= PAGE_MASK;
if (mm != current->mm) {
saved_asid = get_asid();
set_asid(asid);
}
while (start < end) {
__flush_tlb_page(asid, start);
start += PAGE_SIZE;
}
if (saved_asid != MMU_NO_ASID)
set_asid(saved_asid);
}
local_irq_restore(flags);
}
}
/*
* This function depends on the pages to be flushed having the G
* (global) bit set in their pte. This is true for all
* PAGE_KERNEL(_RO) pages.
*/
void flush_tlb_kernel_range(unsigned long start, unsigned long end)
{
unsigned long flags;
int size;
size = (end - start + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
if (size > (MMU_DTLB_ENTRIES / 4)) { /* Too many entries to flush */
flush_tlb_all();
} else {
unsigned long asid;
local_irq_save(flags);
asid = get_asid();
start &= PAGE_MASK;
end += (PAGE_SIZE - 1);
end &= PAGE_MASK;
while (start < end) {
__flush_tlb_page(asid, start);
start += PAGE_SIZE;
}
local_irq_restore(flags);
}
}
void flush_tlb_mm(struct mm_struct *mm)
{
/* Invalidate all TLB entries of this process by getting a new ASID */
if (mm->context != NO_CONTEXT) {
unsigned long flags;
local_irq_save(flags);
mm->context = NO_CONTEXT;
if (mm == current->mm)
activate_context(mm);
local_irq_restore(flags);
}
}
void flush_tlb_all(void)
{
unsigned long flags;
local_irq_save(flags);
sysreg_write(MMUCR, sysreg_read(MMUCR) | SYSREG_BIT(MMUCR_I));
local_irq_restore(flags);
}
#ifdef CONFIG_PROC_FS
#include <linux/seq_file.h>
#include <linux/proc_fs.h>
#include <linux/init.h>
static void *tlb_start(struct seq_file *tlb, loff_t *pos)
{
static unsigned long tlb_index;
if (*pos >= NR_TLB_ENTRIES)
return NULL;
tlb_index = 0;
return &tlb_index;
}
static void *tlb_next(struct seq_file *tlb, void *v, loff_t *pos)
{
unsigned long *index = v;
if (*index >= NR_TLB_ENTRIES - 1)
return NULL;
++*pos;
++*index;
return index;
}
static void tlb_stop(struct seq_file *tlb, void *v)
{
}
static int tlb_show(struct seq_file *tlb, void *v)
{
unsigned int tlbehi, tlbehi_save, tlbelo, mmucr, mmucr_save;
unsigned long flags;
unsigned long *index = v;
if (*index == 0)
seq_puts(tlb, "ID V G ASID VPN PFN AP SZ C B W D\n");
BUG_ON(*index >= NR_TLB_ENTRIES);
local_irq_save(flags);
mmucr_save = sysreg_read(MMUCR);
tlbehi_save = sysreg_read(TLBEHI);
mmucr = SYSREG_BFINS(DRP, *index, mmucr_save);
sysreg_write(MMUCR, mmucr);
/* TLBR might change the ASID */
__builtin_tlbr();
cpu_sync_pipeline();
tlbehi = sysreg_read(TLBEHI);
tlbelo = sysreg_read(TLBELO);
sysreg_write(MMUCR, mmucr_save);
sysreg_write(TLBEHI, tlbehi_save);
cpu_sync_pipeline();
local_irq_restore(flags);
seq_printf(tlb, "%2lu: %c %c %02x %05x %05x %o %o %c %c %c %c\n",
*index,
SYSREG_BFEXT(TLBEHI_V, tlbehi) ? '1' : '0',
SYSREG_BFEXT(G, tlbelo) ? '1' : '0',
SYSREG_BFEXT(ASID, tlbehi),
SYSREG_BFEXT(VPN, tlbehi) >> 2,
SYSREG_BFEXT(PFN, tlbelo) >> 2,
SYSREG_BFEXT(AP, tlbelo),
SYSREG_BFEXT(SZ, tlbelo),
SYSREG_BFEXT(TLBELO_C, tlbelo) ? '1' : '0',
SYSREG_BFEXT(B, tlbelo) ? '1' : '0',
SYSREG_BFEXT(W, tlbelo) ? '1' : '0',
SYSREG_BFEXT(TLBELO_D, tlbelo) ? '1' : '0');
return 0;
}
static const struct seq_operations tlb_ops = {
.start = tlb_start,
.next = tlb_next,
.stop = tlb_stop,
.show = tlb_show,
};
static int tlb_open(struct inode *inode, struct file *file)
{
return seq_open(file, &tlb_ops);
}
static const struct file_operations proc_tlb_operations = {
.open = tlb_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
static int __init proctlb_init(void)
{
proc_create("tlb", 0, NULL, &proc_tlb_operations);
return 0;
}
late_initcall(proctlb_init);
#endif /* CONFIG_PROC_FS */
| gpl-2.0 |
halfline/linux | arch/ia64/kernel/sal.c | 14029 | 10741 | /*
* System Abstraction Layer (SAL) interface routines.
*
* Copyright (C) 1998, 1999, 2001, 2003 Hewlett-Packard Co
* David Mosberger-Tang <davidm@hpl.hp.com>
* Copyright (C) 1999 VA Linux Systems
* Copyright (C) 1999 Walt Drummond <drummond@valinux.com>
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/string.h>
#include <asm/delay.h>
#include <asm/page.h>
#include <asm/sal.h>
#include <asm/pal.h>
__cacheline_aligned DEFINE_SPINLOCK(sal_lock);
unsigned long sal_platform_features;
unsigned short sal_revision;
unsigned short sal_version;
#define SAL_MAJOR(x) ((x) >> 8)
#define SAL_MINOR(x) ((x) & 0xff)
static struct {
void *addr; /* function entry point */
void *gpval; /* gp value to use */
} pdesc;
static long
default_handler (void)
{
return -1;
}
ia64_sal_handler ia64_sal = (ia64_sal_handler) default_handler;
ia64_sal_desc_ptc_t *ia64_ptc_domain_info;
const char *
ia64_sal_strerror (long status)
{
const char *str;
switch (status) {
case 0: str = "Call completed without error"; break;
case 1: str = "Effect a warm boot of the system to complete "
"the update"; break;
case -1: str = "Not implemented"; break;
case -2: str = "Invalid argument"; break;
case -3: str = "Call completed with error"; break;
case -4: str = "Virtual address not registered"; break;
case -5: str = "No information available"; break;
case -6: str = "Insufficient space to add the entry"; break;
case -7: str = "Invalid entry_addr value"; break;
case -8: str = "Invalid interrupt vector"; break;
case -9: str = "Requested memory not available"; break;
case -10: str = "Unable to write to the NVM device"; break;
case -11: str = "Invalid partition type specified"; break;
case -12: str = "Invalid NVM_Object id specified"; break;
case -13: str = "NVM_Object already has the maximum number "
"of partitions"; break;
case -14: str = "Insufficient space in partition for the "
"requested write sub-function"; break;
case -15: str = "Insufficient data buffer space for the "
"requested read record sub-function"; break;
case -16: str = "Scratch buffer required for the write/delete "
"sub-function"; break;
case -17: str = "Insufficient space in the NVM_Object for the "
"requested create sub-function"; break;
case -18: str = "Invalid value specified in the partition_rec "
"argument"; break;
case -19: str = "Record oriented I/O not supported for this "
"partition"; break;
case -20: str = "Bad format of record to be written or "
"required keyword variable not "
"specified"; break;
default: str = "Unknown SAL status code"; break;
}
return str;
}
void __init
ia64_sal_handler_init (void *entry_point, void *gpval)
{
/* fill in the SAL procedure descriptor and point ia64_sal to it: */
pdesc.addr = entry_point;
pdesc.gpval = gpval;
ia64_sal = (ia64_sal_handler) &pdesc;
}
static void __init
check_versions (struct ia64_sal_systab *systab)
{
sal_revision = (systab->sal_rev_major << 8) | systab->sal_rev_minor;
sal_version = (systab->sal_b_rev_major << 8) | systab->sal_b_rev_minor;
/* Check for broken firmware */
if ((sal_revision == SAL_VERSION_CODE(49, 29))
&& (sal_version == SAL_VERSION_CODE(49, 29)))
{
/*
* Old firmware for zx2000 prototypes have this weird version number,
* reset it to something sane.
*/
sal_revision = SAL_VERSION_CODE(2, 8);
sal_version = SAL_VERSION_CODE(0, 0);
}
if (ia64_platform_is("sn2") && (sal_revision == SAL_VERSION_CODE(2, 9)))
/*
* SGI Altix has hard-coded version 2.9 in their prom
* but they actually implement 3.2, so let's fix it here.
*/
sal_revision = SAL_VERSION_CODE(3, 2);
}
static void __init
sal_desc_entry_point (void *p)
{
struct ia64_sal_desc_entry_point *ep = p;
ia64_pal_handler_init(__va(ep->pal_proc));
ia64_sal_handler_init(__va(ep->sal_proc), __va(ep->gp));
}
#ifdef CONFIG_SMP
static void __init
set_smp_redirect (int flag)
{
#ifndef CONFIG_HOTPLUG_CPU
if (no_int_routing)
smp_int_redirect &= ~flag;
else
smp_int_redirect |= flag;
#else
/*
* For CPU Hotplug we dont want to do any chipset supported
* interrupt redirection. The reason is this would require that
* All interrupts be stopped and hard bind the irq to a cpu.
* Later when the interrupt is fired we need to set the redir hint
* on again in the vector. This is cumbersome for something that the
* user mode irq balancer will solve anyways.
*/
no_int_routing=1;
smp_int_redirect &= ~flag;
#endif
}
#else
#define set_smp_redirect(flag) do { } while (0)
#endif
static void __init
sal_desc_platform_feature (void *p)
{
struct ia64_sal_desc_platform_feature *pf = p;
sal_platform_features = pf->feature_mask;
printk(KERN_INFO "SAL Platform features:");
if (!sal_platform_features) {
printk(" None\n");
return;
}
if (sal_platform_features & IA64_SAL_PLATFORM_FEATURE_BUS_LOCK)
printk(" BusLock");
if (sal_platform_features & IA64_SAL_PLATFORM_FEATURE_IRQ_REDIR_HINT) {
printk(" IRQ_Redirection");
set_smp_redirect(SMP_IRQ_REDIRECTION);
}
if (sal_platform_features & IA64_SAL_PLATFORM_FEATURE_IPI_REDIR_HINT) {
printk(" IPI_Redirection");
set_smp_redirect(SMP_IPI_REDIRECTION);
}
if (sal_platform_features & IA64_SAL_PLATFORM_FEATURE_ITC_DRIFT)
printk(" ITC_Drift");
printk("\n");
}
#ifdef CONFIG_SMP
static void __init
sal_desc_ap_wakeup (void *p)
{
struct ia64_sal_desc_ap_wakeup *ap = p;
switch (ap->mechanism) {
case IA64_SAL_AP_EXTERNAL_INT:
ap_wakeup_vector = ap->vector;
printk(KERN_INFO "SAL: AP wakeup using external interrupt "
"vector 0x%lx\n", ap_wakeup_vector);
break;
default:
printk(KERN_ERR "SAL: AP wakeup mechanism unsupported!\n");
break;
}
}
static void __init
chk_nointroute_opt(void)
{
char *cp;
for (cp = boot_command_line; *cp; ) {
if (memcmp(cp, "nointroute", 10) == 0) {
no_int_routing = 1;
printk ("no_int_routing on\n");
break;
} else {
while (*cp != ' ' && *cp)
++cp;
while (*cp == ' ')
++cp;
}
}
}
#else
static void __init sal_desc_ap_wakeup(void *p) { }
#endif
/*
* HP rx5670 firmware polls for interrupts during SAL_CACHE_FLUSH by reading
* cr.ivr, but it never writes cr.eoi. This leaves any interrupt marked as
* "in-service" and masks other interrupts of equal or lower priority.
*
* HP internal defect reports: F1859, F2775, F3031.
*/
static int sal_cache_flush_drops_interrupts;
static int __init
force_pal_cache_flush(char *str)
{
sal_cache_flush_drops_interrupts = 1;
return 0;
}
early_param("force_pal_cache_flush", force_pal_cache_flush);
void __init
check_sal_cache_flush (void)
{
unsigned long flags;
int cpu;
u64 vector, cache_type = 3;
struct ia64_sal_retval isrv;
if (sal_cache_flush_drops_interrupts)
return;
cpu = get_cpu();
local_irq_save(flags);
/*
* Send ourselves a timer interrupt, wait until it's reported, and see
* if SAL_CACHE_FLUSH drops it.
*/
platform_send_ipi(cpu, IA64_TIMER_VECTOR, IA64_IPI_DM_INT, 0);
while (!ia64_get_irr(IA64_TIMER_VECTOR))
cpu_relax();
SAL_CALL(isrv, SAL_CACHE_FLUSH, cache_type, 0, 0, 0, 0, 0, 0);
if (isrv.status)
printk(KERN_ERR "SAL_CAL_FLUSH failed with %ld\n", isrv.status);
if (ia64_get_irr(IA64_TIMER_VECTOR)) {
vector = ia64_get_ivr();
ia64_eoi();
WARN_ON(vector != IA64_TIMER_VECTOR);
} else {
sal_cache_flush_drops_interrupts = 1;
printk(KERN_ERR "SAL: SAL_CACHE_FLUSH drops interrupts; "
"PAL_CACHE_FLUSH will be used instead\n");
ia64_eoi();
}
local_irq_restore(flags);
put_cpu();
}
s64
ia64_sal_cache_flush (u64 cache_type)
{
struct ia64_sal_retval isrv;
if (sal_cache_flush_drops_interrupts) {
unsigned long flags;
u64 progress;
s64 rc;
progress = 0;
local_irq_save(flags);
rc = ia64_pal_cache_flush(cache_type,
PAL_CACHE_FLUSH_INVALIDATE, &progress, NULL);
local_irq_restore(flags);
return rc;
}
SAL_CALL(isrv, SAL_CACHE_FLUSH, cache_type, 0, 0, 0, 0, 0, 0);
return isrv.status;
}
EXPORT_SYMBOL_GPL(ia64_sal_cache_flush);
void __init
ia64_sal_init (struct ia64_sal_systab *systab)
{
char *p;
int i;
if (!systab) {
printk(KERN_WARNING "Hmm, no SAL System Table.\n");
return;
}
if (strncmp(systab->signature, "SST_", 4) != 0)
printk(KERN_ERR "bad signature in system table!");
check_versions(systab);
#ifdef CONFIG_SMP
chk_nointroute_opt();
#endif
/* revisions are coded in BCD, so %x does the job for us */
printk(KERN_INFO "SAL %x.%x: %.32s %.32s%sversion %x.%x\n",
SAL_MAJOR(sal_revision), SAL_MINOR(sal_revision),
systab->oem_id, systab->product_id,
systab->product_id[0] ? " " : "",
SAL_MAJOR(sal_version), SAL_MINOR(sal_version));
p = (char *) (systab + 1);
for (i = 0; i < systab->entry_count; i++) {
/*
* The first byte of each entry type contains the type
* descriptor.
*/
switch (*p) {
case SAL_DESC_ENTRY_POINT:
sal_desc_entry_point(p);
break;
case SAL_DESC_PLATFORM_FEATURE:
sal_desc_platform_feature(p);
break;
case SAL_DESC_PTC:
ia64_ptc_domain_info = (ia64_sal_desc_ptc_t *)p;
break;
case SAL_DESC_AP_WAKEUP:
sal_desc_ap_wakeup(p);
break;
}
p += SAL_DESC_SIZE(*p);
}
}
int
ia64_sal_oemcall(struct ia64_sal_retval *isrvp, u64 oemfunc, u64 arg1,
u64 arg2, u64 arg3, u64 arg4, u64 arg5, u64 arg6, u64 arg7)
{
if (oemfunc < IA64_SAL_OEMFUNC_MIN || oemfunc > IA64_SAL_OEMFUNC_MAX)
return -1;
SAL_CALL(*isrvp, oemfunc, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
return 0;
}
EXPORT_SYMBOL(ia64_sal_oemcall);
int
ia64_sal_oemcall_nolock(struct ia64_sal_retval *isrvp, u64 oemfunc, u64 arg1,
u64 arg2, u64 arg3, u64 arg4, u64 arg5, u64 arg6,
u64 arg7)
{
if (oemfunc < IA64_SAL_OEMFUNC_MIN || oemfunc > IA64_SAL_OEMFUNC_MAX)
return -1;
SAL_CALL_NOLOCK(*isrvp, oemfunc, arg1, arg2, arg3, arg4, arg5, arg6,
arg7);
return 0;
}
EXPORT_SYMBOL(ia64_sal_oemcall_nolock);
int
ia64_sal_oemcall_reentrant(struct ia64_sal_retval *isrvp, u64 oemfunc,
u64 arg1, u64 arg2, u64 arg3, u64 arg4, u64 arg5,
u64 arg6, u64 arg7)
{
if (oemfunc < IA64_SAL_OEMFUNC_MIN || oemfunc > IA64_SAL_OEMFUNC_MAX)
return -1;
SAL_CALL_REENTRANT(*isrvp, oemfunc, arg1, arg2, arg3, arg4, arg5, arg6,
arg7);
return 0;
}
EXPORT_SYMBOL(ia64_sal_oemcall_reentrant);
long
ia64_sal_freq_base (unsigned long which, unsigned long *ticks_per_second,
unsigned long *drift_info)
{
struct ia64_sal_retval isrv;
SAL_CALL(isrv, SAL_FREQ_BASE, which, 0, 0, 0, 0, 0, 0);
*ticks_per_second = isrv.v0;
*drift_info = isrv.v1;
return isrv.status;
}
EXPORT_SYMBOL_GPL(ia64_sal_freq_base);
| gpl-2.0 |
cedrichu/kernel_tcp_stack_14.04LTS | net/llc/llc_c_ev.c | 15053 | 21776 | /*
* llc_c_ev.c - Connection component state transition event qualifiers
*
* A 'state' consists of a number of possible event matching functions,
* the actions associated with each being executed when that event is
* matched; a 'state machine' accepts events in a serial fashion from an
* event queue. Each event is passed to each successive event matching
* function until a match is made (the event matching function returns
* success, or '0') or the list of event matching functions is exhausted.
* If a match is made, the actions associated with the event are executed
* and the state is changed to that event's transition state. Before some
* events are recognized, even after a match has been made, a certain
* number of 'event qualifier' functions must also be executed. If these
* all execute successfully, then the event is finally executed.
*
* These event functions must return 0 for success, to show a matched
* event, of 1 if the event does not match. Event qualifier functions
* must return a 0 for success or a non-zero for failure. Each function
* is simply responsible for verifying one single thing and returning
* either a success or failure.
*
* All of followed event functions are described in 802.2 LLC Protocol
* standard document except two functions that we added that will explain
* in their comments, at below.
*
* Copyright (c) 1997 by Procom Technology, Inc.
* 2001-2003 by Arnaldo Carvalho de Melo <acme@conectiva.com.br>
*
* This program can be redistributed or modified under the terms of the
* GNU General Public License as published by the Free Software Foundation.
* This program is distributed without any warranty or implied warranty
* of merchantability or fitness for a particular purpose.
*
* See the GNU General Public License for more details.
*/
#include <linux/netdevice.h>
#include <net/llc_conn.h>
#include <net/llc_sap.h>
#include <net/sock.h>
#include <net/llc_c_ac.h>
#include <net/llc_c_ev.h>
#include <net/llc_pdu.h>
#if 1
#define dprintk(args...) printk(KERN_DEBUG args)
#else
#define dprintk(args...)
#endif
/**
* llc_util_ns_inside_rx_window - check if sequence number is in rx window
* @ns: sequence number of received pdu.
* @vr: sequence number which receiver expects to receive.
* @rw: receive window size of receiver.
*
* Checks if sequence number of received PDU is in range of receive
* window. Returns 0 for success, 1 otherwise
*/
static u16 llc_util_ns_inside_rx_window(u8 ns, u8 vr, u8 rw)
{
return !llc_circular_between(vr, ns,
(vr + rw - 1) % LLC_2_SEQ_NBR_MODULO);
}
/**
* llc_util_nr_inside_tx_window - check if sequence number is in tx window
* @sk: current connection.
* @nr: N(R) of received PDU.
*
* This routine checks if N(R) of received PDU is in range of transmit
* window; on the other hand checks if received PDU acknowledges some
* outstanding PDUs that are in transmit window. Returns 0 for success, 1
* otherwise.
*/
static u16 llc_util_nr_inside_tx_window(struct sock *sk, u8 nr)
{
u8 nr1, nr2;
struct sk_buff *skb;
struct llc_pdu_sn *pdu;
struct llc_sock *llc = llc_sk(sk);
int rc = 0;
if (llc->dev->flags & IFF_LOOPBACK)
goto out;
rc = 1;
if (skb_queue_empty(&llc->pdu_unack_q))
goto out;
skb = skb_peek(&llc->pdu_unack_q);
pdu = llc_pdu_sn_hdr(skb);
nr1 = LLC_I_GET_NS(pdu);
skb = skb_peek_tail(&llc->pdu_unack_q);
pdu = llc_pdu_sn_hdr(skb);
nr2 = LLC_I_GET_NS(pdu);
rc = !llc_circular_between(nr1, nr, (nr2 + 1) % LLC_2_SEQ_NBR_MODULO);
out:
return rc;
}
int llc_conn_ev_conn_req(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->prim == LLC_CONN_PRIM &&
ev->prim_type == LLC_PRIM_TYPE_REQ ? 0 : 1;
}
int llc_conn_ev_data_req(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->prim == LLC_DATA_PRIM &&
ev->prim_type == LLC_PRIM_TYPE_REQ ? 0 : 1;
}
int llc_conn_ev_disc_req(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->prim == LLC_DISC_PRIM &&
ev->prim_type == LLC_PRIM_TYPE_REQ ? 0 : 1;
}
int llc_conn_ev_rst_req(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->prim == LLC_RESET_PRIM &&
ev->prim_type == LLC_PRIM_TYPE_REQ ? 0 : 1;
}
int llc_conn_ev_local_busy_detected(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->type == LLC_CONN_EV_TYPE_SIMPLE &&
ev->prim_type == LLC_CONN_EV_LOCAL_BUSY_DETECTED ? 0 : 1;
}
int llc_conn_ev_local_busy_cleared(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->type == LLC_CONN_EV_TYPE_SIMPLE &&
ev->prim_type == LLC_CONN_EV_LOCAL_BUSY_CLEARED ? 0 : 1;
}
int llc_conn_ev_rx_bad_pdu(struct sock *sk, struct sk_buff *skb)
{
return 1;
}
int llc_conn_ev_rx_disc_cmd_pbit_set_x(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_U(pdu) &&
LLC_U_PDU_CMD(pdu) == LLC_2_PDU_CMD_DISC ? 0 : 1;
}
int llc_conn_ev_rx_dm_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_U(pdu) &&
LLC_U_PDU_RSP(pdu) == LLC_2_PDU_RSP_DM ? 0 : 1;
}
int llc_conn_ev_rx_frmr_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_U(pdu) &&
LLC_U_PDU_RSP(pdu) == LLC_2_PDU_RSP_FRMR ? 0 : 1;
}
int llc_conn_ev_rx_i_cmd_pbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return llc_conn_space(sk, skb) &&
LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_0(pdu) &&
LLC_I_GET_NS(pdu) == llc_sk(sk)->vR ? 0 : 1;
}
int llc_conn_ev_rx_i_cmd_pbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return llc_conn_space(sk, skb) &&
LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_1(pdu) &&
LLC_I_GET_NS(pdu) == llc_sk(sk)->vR ? 0 : 1;
}
int llc_conn_ev_rx_i_cmd_pbit_set_0_unexpd_ns(struct sock *sk,
struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vr = llc_sk(sk)->vR;
const u8 ns = LLC_I_GET_NS(pdu);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_0(pdu) && ns != vr &&
!llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1;
}
int llc_conn_ev_rx_i_cmd_pbit_set_1_unexpd_ns(struct sock *sk,
struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vr = llc_sk(sk)->vR;
const u8 ns = LLC_I_GET_NS(pdu);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_1(pdu) && ns != vr &&
!llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1;
}
int llc_conn_ev_rx_i_cmd_pbit_set_x_inval_ns(struct sock *sk,
struct sk_buff *skb)
{
const struct llc_pdu_sn * pdu = llc_pdu_sn_hdr(skb);
const u8 vr = llc_sk(sk)->vR;
const u8 ns = LLC_I_GET_NS(pdu);
const u16 rc = LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
ns != vr &&
llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1;
if (!rc)
dprintk("%s: matched, state=%d, ns=%d, vr=%d\n",
__func__, llc_sk(sk)->state, ns, vr);
return rc;
}
int llc_conn_ev_rx_i_rsp_fbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return llc_conn_space(sk, skb) &&
LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_0(pdu) &&
LLC_I_GET_NS(pdu) == llc_sk(sk)->vR ? 0 : 1;
}
int llc_conn_ev_rx_i_rsp_fbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_1(pdu) &&
LLC_I_GET_NS(pdu) == llc_sk(sk)->vR ? 0 : 1;
}
int llc_conn_ev_rx_i_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return llc_conn_space(sk, skb) &&
LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_GET_NS(pdu) == llc_sk(sk)->vR ? 0 : 1;
}
int llc_conn_ev_rx_i_rsp_fbit_set_0_unexpd_ns(struct sock *sk,
struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vr = llc_sk(sk)->vR;
const u8 ns = LLC_I_GET_NS(pdu);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_0(pdu) && ns != vr &&
!llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1;
}
int llc_conn_ev_rx_i_rsp_fbit_set_1_unexpd_ns(struct sock *sk,
struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vr = llc_sk(sk)->vR;
const u8 ns = LLC_I_GET_NS(pdu);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
LLC_I_PF_IS_1(pdu) && ns != vr &&
!llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1;
}
int llc_conn_ev_rx_i_rsp_fbit_set_x_unexpd_ns(struct sock *sk,
struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vr = llc_sk(sk)->vR;
const u8 ns = LLC_I_GET_NS(pdu);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) && ns != vr &&
!llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1;
}
int llc_conn_ev_rx_i_rsp_fbit_set_x_inval_ns(struct sock *sk,
struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vr = llc_sk(sk)->vR;
const u8 ns = LLC_I_GET_NS(pdu);
const u16 rc = LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) &&
ns != vr &&
llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1;
if (!rc)
dprintk("%s: matched, state=%d, ns=%d, vr=%d\n",
__func__, llc_sk(sk)->state, ns, vr);
return rc;
}
int llc_conn_ev_rx_rej_cmd_pbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_0(pdu) &&
LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_REJ ? 0 : 1;
}
int llc_conn_ev_rx_rej_cmd_pbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_1(pdu) &&
LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_REJ ? 0 : 1;
}
int llc_conn_ev_rx_rej_rsp_fbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_0(pdu) &&
LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_REJ ? 0 : 1;
}
int llc_conn_ev_rx_rej_rsp_fbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_1(pdu) &&
LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_REJ ? 0 : 1;
}
int llc_conn_ev_rx_rej_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_REJ ? 0 : 1;
}
int llc_conn_ev_rx_rnr_cmd_pbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_0(pdu) &&
LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_RNR ? 0 : 1;
}
int llc_conn_ev_rx_rnr_cmd_pbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_1(pdu) &&
LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_RNR ? 0 : 1;
}
int llc_conn_ev_rx_rnr_rsp_fbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_0(pdu) &&
LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_RNR ? 0 : 1;
}
int llc_conn_ev_rx_rnr_rsp_fbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_1(pdu) &&
LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_RNR ? 0 : 1;
}
int llc_conn_ev_rx_rr_cmd_pbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_0(pdu) &&
LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_RR ? 0 : 1;
}
int llc_conn_ev_rx_rr_cmd_pbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_1(pdu) &&
LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_RR ? 0 : 1;
}
int llc_conn_ev_rx_rr_rsp_fbit_set_0(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return llc_conn_space(sk, skb) &&
LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_0(pdu) &&
LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_RR ? 0 : 1;
}
int llc_conn_ev_rx_rr_rsp_fbit_set_1(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
return llc_conn_space(sk, skb) &&
LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) &&
LLC_S_PF_IS_1(pdu) &&
LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_RR ? 0 : 1;
}
int llc_conn_ev_rx_sabme_cmd_pbit_set_x(struct sock *sk, struct sk_buff *skb)
{
const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_U(pdu) &&
LLC_U_PDU_CMD(pdu) == LLC_2_PDU_CMD_SABME ? 0 : 1;
}
int llc_conn_ev_rx_ua_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb)
{
struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_U(pdu) &&
LLC_U_PDU_RSP(pdu) == LLC_2_PDU_RSP_UA ? 0 : 1;
}
int llc_conn_ev_rx_xxx_cmd_pbit_set_1(struct sock *sk, struct sk_buff *skb)
{
u16 rc = 1;
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
if (LLC_PDU_IS_CMD(pdu)) {
if (LLC_PDU_TYPE_IS_I(pdu) || LLC_PDU_TYPE_IS_S(pdu)) {
if (LLC_I_PF_IS_1(pdu))
rc = 0;
} else if (LLC_PDU_TYPE_IS_U(pdu) && LLC_U_PF_IS_1(pdu))
rc = 0;
}
return rc;
}
int llc_conn_ev_rx_xxx_cmd_pbit_set_x(struct sock *sk, struct sk_buff *skb)
{
u16 rc = 1;
const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
if (LLC_PDU_IS_CMD(pdu)) {
if (LLC_PDU_TYPE_IS_I(pdu) || LLC_PDU_TYPE_IS_S(pdu))
rc = 0;
else if (LLC_PDU_TYPE_IS_U(pdu))
switch (LLC_U_PDU_CMD(pdu)) {
case LLC_2_PDU_CMD_SABME:
case LLC_2_PDU_CMD_DISC:
rc = 0;
break;
}
}
return rc;
}
int llc_conn_ev_rx_xxx_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb)
{
u16 rc = 1;
const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
if (LLC_PDU_IS_RSP(pdu)) {
if (LLC_PDU_TYPE_IS_I(pdu) || LLC_PDU_TYPE_IS_S(pdu))
rc = 0;
else if (LLC_PDU_TYPE_IS_U(pdu))
switch (LLC_U_PDU_RSP(pdu)) {
case LLC_2_PDU_RSP_UA:
case LLC_2_PDU_RSP_DM:
case LLC_2_PDU_RSP_FRMR:
rc = 0;
break;
}
}
return rc;
}
int llc_conn_ev_rx_zzz_cmd_pbit_set_x_inval_nr(struct sock *sk,
struct sk_buff *skb)
{
u16 rc = 1;
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vs = llc_sk(sk)->vS;
const u8 nr = LLC_I_GET_NR(pdu);
if (LLC_PDU_IS_CMD(pdu) &&
(LLC_PDU_TYPE_IS_I(pdu) || LLC_PDU_TYPE_IS_S(pdu)) &&
nr != vs && llc_util_nr_inside_tx_window(sk, nr)) {
dprintk("%s: matched, state=%d, vs=%d, nr=%d\n",
__func__, llc_sk(sk)->state, vs, nr);
rc = 0;
}
return rc;
}
int llc_conn_ev_rx_zzz_rsp_fbit_set_x_inval_nr(struct sock *sk,
struct sk_buff *skb)
{
u16 rc = 1;
const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb);
const u8 vs = llc_sk(sk)->vS;
const u8 nr = LLC_I_GET_NR(pdu);
if (LLC_PDU_IS_RSP(pdu) &&
(LLC_PDU_TYPE_IS_I(pdu) || LLC_PDU_TYPE_IS_S(pdu)) &&
nr != vs && llc_util_nr_inside_tx_window(sk, nr)) {
rc = 0;
dprintk("%s: matched, state=%d, vs=%d, nr=%d\n",
__func__, llc_sk(sk)->state, vs, nr);
}
return rc;
}
int llc_conn_ev_rx_any_frame(struct sock *sk, struct sk_buff *skb)
{
return 0;
}
int llc_conn_ev_p_tmr_exp(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->type != LLC_CONN_EV_TYPE_P_TMR;
}
int llc_conn_ev_ack_tmr_exp(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->type != LLC_CONN_EV_TYPE_ACK_TMR;
}
int llc_conn_ev_rej_tmr_exp(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->type != LLC_CONN_EV_TYPE_REJ_TMR;
}
int llc_conn_ev_busy_tmr_exp(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->type != LLC_CONN_EV_TYPE_BUSY_TMR;
}
int llc_conn_ev_init_p_f_cycle(struct sock *sk, struct sk_buff *skb)
{
return 1;
}
int llc_conn_ev_tx_buffer_full(struct sock *sk, struct sk_buff *skb)
{
const struct llc_conn_state_ev *ev = llc_conn_ev(skb);
return ev->type == LLC_CONN_EV_TYPE_SIMPLE &&
ev->prim_type == LLC_CONN_EV_TX_BUFF_FULL ? 0 : 1;
}
/* Event qualifier functions
*
* these functions simply verify the value of a state flag associated with
* the connection and return either a 0 for success or a non-zero value
* for not-success; verify the event is the type we expect
*/
int llc_conn_ev_qlfy_data_flag_eq_1(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->data_flag != 1;
}
int llc_conn_ev_qlfy_data_flag_eq_0(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->data_flag;
}
int llc_conn_ev_qlfy_data_flag_eq_2(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->data_flag != 2;
}
int llc_conn_ev_qlfy_p_flag_eq_1(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->p_flag != 1;
}
/**
* conn_ev_qlfy_last_frame_eq_1 - checks if frame is last in tx window
* @sk: current connection structure.
* @skb: current event.
*
* This function determines when frame which is sent, is last frame of
* transmit window, if it is then this function return zero else return
* one. This function is used for sending last frame of transmit window
* as I-format command with p-bit set to one. Returns 0 if frame is last
* frame, 1 otherwise.
*/
int llc_conn_ev_qlfy_last_frame_eq_1(struct sock *sk, struct sk_buff *skb)
{
return !(skb_queue_len(&llc_sk(sk)->pdu_unack_q) + 1 == llc_sk(sk)->k);
}
/**
* conn_ev_qlfy_last_frame_eq_0 - checks if frame isn't last in tx window
* @sk: current connection structure.
* @skb: current event.
*
* This function determines when frame which is sent, isn't last frame of
* transmit window, if it isn't then this function return zero else return
* one. Returns 0 if frame isn't last frame, 1 otherwise.
*/
int llc_conn_ev_qlfy_last_frame_eq_0(struct sock *sk, struct sk_buff *skb)
{
return skb_queue_len(&llc_sk(sk)->pdu_unack_q) + 1 == llc_sk(sk)->k;
}
int llc_conn_ev_qlfy_p_flag_eq_0(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->p_flag;
}
int llc_conn_ev_qlfy_p_flag_eq_f(struct sock *sk, struct sk_buff *skb)
{
u8 f_bit;
llc_pdu_decode_pf_bit(skb, &f_bit);
return llc_sk(sk)->p_flag == f_bit ? 0 : 1;
}
int llc_conn_ev_qlfy_remote_busy_eq_0(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->remote_busy_flag;
}
int llc_conn_ev_qlfy_remote_busy_eq_1(struct sock *sk, struct sk_buff *skb)
{
return !llc_sk(sk)->remote_busy_flag;
}
int llc_conn_ev_qlfy_retry_cnt_lt_n2(struct sock *sk, struct sk_buff *skb)
{
return !(llc_sk(sk)->retry_count < llc_sk(sk)->n2);
}
int llc_conn_ev_qlfy_retry_cnt_gte_n2(struct sock *sk, struct sk_buff *skb)
{
return !(llc_sk(sk)->retry_count >= llc_sk(sk)->n2);
}
int llc_conn_ev_qlfy_s_flag_eq_1(struct sock *sk, struct sk_buff *skb)
{
return !llc_sk(sk)->s_flag;
}
int llc_conn_ev_qlfy_s_flag_eq_0(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->s_flag;
}
int llc_conn_ev_qlfy_cause_flag_eq_1(struct sock *sk, struct sk_buff *skb)
{
return !llc_sk(sk)->cause_flag;
}
int llc_conn_ev_qlfy_cause_flag_eq_0(struct sock *sk, struct sk_buff *skb)
{
return llc_sk(sk)->cause_flag;
}
int llc_conn_ev_qlfy_set_status_conn(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->status = LLC_STATUS_CONN;
return 0;
}
int llc_conn_ev_qlfy_set_status_disc(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->status = LLC_STATUS_DISC;
return 0;
}
int llc_conn_ev_qlfy_set_status_failed(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->status = LLC_STATUS_FAILED;
return 0;
}
int llc_conn_ev_qlfy_set_status_remote_busy(struct sock *sk,
struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->status = LLC_STATUS_REMOTE_BUSY;
return 0;
}
int llc_conn_ev_qlfy_set_status_refuse(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->status = LLC_STATUS_REFUSE;
return 0;
}
int llc_conn_ev_qlfy_set_status_conflict(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->status = LLC_STATUS_CONFLICT;
return 0;
}
int llc_conn_ev_qlfy_set_status_rst_done(struct sock *sk, struct sk_buff *skb)
{
struct llc_conn_state_ev *ev = llc_conn_ev(skb);
ev->status = LLC_STATUS_RESET_DONE;
return 0;
}
| gpl-2.0 |
rhtu/linux | drivers/net/irda/toim3232-sir.c | 974 | 12314 | /*********************************************************************
*
* Filename: toim3232-sir.c
* Version: 1.0
* Description: Implementation of dongles based on the Vishay/Temic
* TOIM3232 SIR Endec chipset. Currently only the
* IRWave IR320ST-2 is tested, although it should work
* with any TOIM3232 or TOIM4232 chipset based RS232
* dongle with minimal modification.
* Based heavily on the Tekram driver (tekram.c),
* with thanks to Dag Brattli and Martin Diehl.
* Status: Experimental.
* Author: David Basden <davidb-irda@rcpt.to>
* Created at: Thu Feb 09 23:47:32 2006
*
* Copyright (c) 2006 David Basden.
* Copyright (c) 1998-1999 Dag Brattli,
* Copyright (c) 2002 Martin Diehl,
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* Neither Dag Brattli nor University of Tromsø admit liability nor
* provide warranty for any of this software. This material is
* provided "AS-IS" and at no charge.
*
********************************************************************/
/*
* This driver has currently only been tested on the IRWave IR320ST-2
*
* PROTOCOL:
*
* The protocol for talking to the TOIM3232 is quite easy, and is
* designed to interface with RS232 with only level convertors. The
* BR/~D line on the chip is brought high to signal 'command mode',
* where a command byte is sent to select the baudrate of the RS232
* interface and the pulse length of the IRDA output. When BR/~D
* is brought low, the dongle then changes to the selected baudrate,
* and the RS232 interface is used for data until BR/~D is brought
* high again. The initial speed for the TOIMx323 after RESET is
* 9600 baud. The baudrate for command-mode is the last selected
* baud-rate, or 9600 after a RESET.
*
* The dongle I have (below) adds some extra hardware on the front end,
* but this is mostly directed towards pariasitic power from the RS232
* line rather than changing very much about how to communicate with
* the TOIM3232.
*
* The protocol to talk to the TOIM4232 chipset seems to be almost
* identical to the TOIM3232 (and the 4232 datasheet is more detailed)
* so this code will probably work on that as well, although I haven't
* tested it on that hardware.
*
* Target dongle variations that might be common:
*
* DTR and RTS function:
* The data sheet for the 4232 has a sample implementation that hooks the
* DTR and RTS lines to the RESET and BaudRate/~Data lines of the
* chip (through line-converters). Given both DTR and RTS would have to
* be held low in normal operation, and the TOIMx232 requires +5V to
* signal ground, most dongle designers would almost certainly choose
* an implementation that kept at least one of DTR or RTS high in
* normal operation to provide power to the dongle, but will likely
* vary between designs.
*
* User specified command bits:
* There are two user-controllable output lines from the TOIMx232 that
* can be set low or high by setting the appropriate bits in the
* high-nibble of the command byte (when setting speed and pulse length).
* These might be used to switch on and off added hardware or extra
* dongle features.
*
*
* Target hardware: IRWave IR320ST-2
*
* The IRWave IR320ST-2 is a simple dongle based on the Vishay/Temic
* TOIM3232 SIR Endec and the Vishay/Temic TFDS4500 SIR IRDA transceiver.
* It uses a hex inverter and some discrete components to buffer and
* line convert the RS232 down to 5V.
*
* The dongle is powered through a voltage regulator, fed by a large
* capacitor. To switch the dongle on, DTR is brought high to charge
* the capacitor and drive the voltage regulator. DTR isn't associated
* with any control lines on the TOIM3232. Parisitic power is also taken
* from the RTS, TD and RD lines when brought high, but through resistors.
* When DTR is low, the circuit might lose power even with RTS high.
*
* RTS is inverted and attached to the BR/~D input pin. When RTS
* is high, BR/~D is low, and the TOIM3232 is in the normal 'data' mode.
* RTS is brought low, BR/~D is high, and the TOIM3232 is in 'command
* mode'.
*
* For some unknown reason, the RESET line isn't actually connected
* to anything. This means to reset the dongle to get it to a known
* state (9600 baud) you must drop DTR and RTS low, wait for the power
* capacitor to discharge, and then bring DTR (and RTS for data mode)
* high again, and wait for the capacitor to charge, the power supply
* to stabilise, and the oscillator clock to stabilise.
*
* Fortunately, if the current baudrate is known, the chipset can
* easily change speed by entering command mode without having to
* reset the dongle first.
*
* Major Components:
*
* - Vishay/Temic TOIM3232 SIR Endec to change RS232 pulse timings
* to IRDA pulse timings
* - 3.6864MHz crystal to drive TOIM3232 clock oscillator
* - DM74lS04M Inverting Hex line buffer for RS232 input buffering
* and level conversion
* - PJ2951AC 150mA voltage regulator
* - Vishay/Temic TFDS4500 SIR IRDA front-end transceiver
*
*/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <net/irda/irda.h>
#include "sir-dev.h"
static int toim3232delay = 150; /* default is 150 ms */
module_param(toim3232delay, int, 0);
MODULE_PARM_DESC(toim3232delay, "toim3232 dongle write complete delay");
#if 0
static int toim3232flipdtr = 0; /* default is DTR high to reset */
module_param(toim3232flipdtr, int, 0);
MODULE_PARM_DESC(toim3232flipdtr, "toim3232 dongle invert DTR (Reset)");
static int toim3232fliprts = 0; /* default is RTS high for baud change */
module_param(toim3232fliptrs, int, 0);
MODULE_PARM_DESC(toim3232fliprts, "toim3232 dongle invert RTS (BR/D)");
#endif
static int toim3232_open(struct sir_dev *);
static int toim3232_close(struct sir_dev *);
static int toim3232_change_speed(struct sir_dev *, unsigned);
static int toim3232_reset(struct sir_dev *);
#define TOIM3232_115200 0x00
#define TOIM3232_57600 0x01
#define TOIM3232_38400 0x02
#define TOIM3232_19200 0x03
#define TOIM3232_9600 0x06
#define TOIM3232_2400 0x0A
#define TOIM3232_PW 0x10 /* Pulse select bit */
static struct dongle_driver toim3232 = {
.owner = THIS_MODULE,
.driver_name = "Vishay TOIM3232",
.type = IRDA_TOIM3232_DONGLE,
.open = toim3232_open,
.close = toim3232_close,
.reset = toim3232_reset,
.set_speed = toim3232_change_speed,
};
static int __init toim3232_sir_init(void)
{
if (toim3232delay < 1 || toim3232delay > 500)
toim3232delay = 200;
pr_debug("%s - using %d ms delay\n",
toim3232.driver_name, toim3232delay);
return irda_register_dongle(&toim3232);
}
static void __exit toim3232_sir_cleanup(void)
{
irda_unregister_dongle(&toim3232);
}
static int toim3232_open(struct sir_dev *dev)
{
struct qos_info *qos = &dev->qos;
/* Pull the lines high to start with.
*
* For the IR320ST-2, we need to charge the main supply capacitor to
* switch the device on. We keep DTR high throughout to do this.
* When RTS, TD and RD are high, they will also trickle-charge the
* cap. RTS is high for data transmission, and low for baud rate select.
* -- DGB
*/
sirdev_set_dtr_rts(dev, TRUE, TRUE);
/* The TOI3232 supports many speeds between 1200bps and 115000bps.
* We really only care about those supported by the IRDA spec, but
* 38400 seems to be implemented in many places */
qos->baud_rate.bits &= IR_2400|IR_9600|IR_19200|IR_38400|IR_57600|IR_115200;
/* From the tekram driver. Not sure what a reasonable value is -- DGB */
qos->min_turn_time.bits = 0x01; /* Needs at least 10 ms */
irda_qos_bits_to_value(qos);
/* irda thread waits 50 msec for power settling */
return 0;
}
static int toim3232_close(struct sir_dev *dev)
{
/* Power off dongle */
sirdev_set_dtr_rts(dev, FALSE, FALSE);
return 0;
}
/*
* Function toim3232change_speed (dev, state, speed)
*
* Set the speed for the TOIM3232 based dongle. Warning, this
* function must be called with a process context!
*
* Algorithm
* 1. keep DTR high but clear RTS to bring into baud programming mode
* 2. wait at least 7us to enter programming mode
* 3. send control word to set baud rate and timing
* 4. wait at least 1us
* 5. bring RTS high to enter DATA mode (RS232 is passed through to transceiver)
* 6. should take effect immediately (although probably worth waiting)
*/
#define TOIM3232_STATE_WAIT_SPEED (SIRDEV_STATE_DONGLE_SPEED + 1)
static int toim3232_change_speed(struct sir_dev *dev, unsigned speed)
{
unsigned state = dev->fsm.substate;
unsigned delay = 0;
u8 byte;
static int ret = 0;
switch(state) {
case SIRDEV_STATE_DONGLE_SPEED:
/* Figure out what we are going to send as a control byte */
switch (speed) {
case 2400:
byte = TOIM3232_PW|TOIM3232_2400;
break;
default:
speed = 9600;
ret = -EINVAL;
/* fall thru */
case 9600:
byte = TOIM3232_PW|TOIM3232_9600;
break;
case 19200:
byte = TOIM3232_PW|TOIM3232_19200;
break;
case 38400:
byte = TOIM3232_PW|TOIM3232_38400;
break;
case 57600:
byte = TOIM3232_PW|TOIM3232_57600;
break;
case 115200:
byte = TOIM3232_115200;
break;
}
/* Set DTR, Clear RTS: Go into baud programming mode */
sirdev_set_dtr_rts(dev, TRUE, FALSE);
/* Wait at least 7us */
udelay(14);
/* Write control byte */
sirdev_raw_write(dev, &byte, 1);
dev->speed = speed;
state = TOIM3232_STATE_WAIT_SPEED;
delay = toim3232delay;
break;
case TOIM3232_STATE_WAIT_SPEED:
/* Have transmitted control byte * Wait for 'at least 1us' */
udelay(14);
/* Set DTR, Set RTS: Go into normal data mode */
sirdev_set_dtr_rts(dev, TRUE, TRUE);
/* Wait (TODO: check this is needed) */
udelay(50);
break;
default:
printk(KERN_ERR "%s - undefined state %d\n", __func__, state);
ret = -EINVAL;
break;
}
dev->fsm.substate = state;
return (delay > 0) ? delay : ret;
}
/*
* Function toim3232reset (driver)
*
* This function resets the toim3232 dongle. Warning, this function
* must be called with a process context!!
*
* What we should do is:
* 0. Pull RESET high
* 1. Wait for at least 7us
* 2. Pull RESET low
* 3. Wait for at least 7us
* 4. Pull BR/~D high
* 5. Wait for at least 7us
* 6. Send control byte to set baud rate
* 7. Wait at least 1us after stop bit
* 8. Pull BR/~D low
* 9. Should then be in data mode
*
* Because the IR320ST-2 doesn't have the RESET line connected for some reason,
* we'll have to do something else.
*
* The default speed after a RESET is 9600, so lets try just bringing it up in
* data mode after switching it off, waiting for the supply capacitor to
* discharge, and then switch it back on. This isn't actually pulling RESET
* high, but it seems to have the same effect.
*
* This behaviour will probably work on dongles that have the RESET line connected,
* but if not, add a flag for the IR320ST-2, and implment the above-listed proper
* behaviour.
*
* RTS is inverted and then fed to BR/~D, so to put it in programming mode, we
* need to have pull RTS low
*/
static int toim3232_reset(struct sir_dev *dev)
{
/* Switch off both DTR and RTS to switch off dongle */
sirdev_set_dtr_rts(dev, FALSE, FALSE);
/* Should sleep a while. This might be evil doing it this way.*/
set_current_state(TASK_UNINTERRUPTIBLE);
schedule_timeout(msecs_to_jiffies(50));
/* Set DTR, Set RTS (data mode) */
sirdev_set_dtr_rts(dev, TRUE, TRUE);
/* Wait at least 10 ms for power to stabilize again */
set_current_state(TASK_UNINTERRUPTIBLE);
schedule_timeout(msecs_to_jiffies(10));
/* Speed should now be 9600 */
dev->speed = 9600;
return 0;
}
MODULE_AUTHOR("David Basden <davidb-linux@rcpt.to>");
MODULE_DESCRIPTION("Vishay/Temic TOIM3232 based dongle driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("irda-dongle-12"); /* IRDA_TOIM3232_DONGLE */
module_init(toim3232_sir_init);
module_exit(toim3232_sir_cleanup);
| gpl-2.0 |
rafal-krypa/smack-backport | net/lapb/lapb_iface.c | 1230 | 9072 | /*
* LAPB release 002
*
* This code REQUIRES 2.1.15 or higher/ NET3.038
*
* This module:
* This module 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.
*
* History
* LAPB 001 Jonathan Naylor Started Coding
* LAPB 002 Jonathan Naylor New timer architecture.
* 2000-10-29 Henner Eisen lapb_data_indication() return status.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/jiffies.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/inet.h>
#include <linux/if_arp.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <asm/uaccess.h>
#include <linux/fcntl.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/stat.h>
#include <linux/init.h>
#include <net/lapb.h>
static LIST_HEAD(lapb_list);
static DEFINE_RWLOCK(lapb_list_lock);
/*
* Free an allocated lapb control block.
*/
static void lapb_free_cb(struct lapb_cb *lapb)
{
kfree(lapb);
}
static __inline__ void lapb_hold(struct lapb_cb *lapb)
{
atomic_inc(&lapb->refcnt);
}
static __inline__ void lapb_put(struct lapb_cb *lapb)
{
if (atomic_dec_and_test(&lapb->refcnt))
lapb_free_cb(lapb);
}
/*
* Socket removal during an interrupt is now safe.
*/
static void __lapb_remove_cb(struct lapb_cb *lapb)
{
if (lapb->node.next) {
list_del(&lapb->node);
lapb_put(lapb);
}
}
EXPORT_SYMBOL(lapb_register);
/*
* Add a socket to the bound sockets list.
*/
static void __lapb_insert_cb(struct lapb_cb *lapb)
{
list_add(&lapb->node, &lapb_list);
lapb_hold(lapb);
}
static struct lapb_cb *__lapb_devtostruct(struct net_device *dev)
{
struct list_head *entry;
struct lapb_cb *lapb, *use = NULL;
list_for_each(entry, &lapb_list) {
lapb = list_entry(entry, struct lapb_cb, node);
if (lapb->dev == dev) {
use = lapb;
break;
}
}
if (use)
lapb_hold(use);
return use;
}
static struct lapb_cb *lapb_devtostruct(struct net_device *dev)
{
struct lapb_cb *rc;
read_lock_bh(&lapb_list_lock);
rc = __lapb_devtostruct(dev);
read_unlock_bh(&lapb_list_lock);
return rc;
}
/*
* Create an empty LAPB control block.
*/
static struct lapb_cb *lapb_create_cb(void)
{
struct lapb_cb *lapb = kzalloc(sizeof(*lapb), GFP_ATOMIC);
if (!lapb)
goto out;
skb_queue_head_init(&lapb->write_queue);
skb_queue_head_init(&lapb->ack_queue);
init_timer(&lapb->t1timer);
init_timer(&lapb->t2timer);
lapb->t1 = LAPB_DEFAULT_T1;
lapb->t2 = LAPB_DEFAULT_T2;
lapb->n2 = LAPB_DEFAULT_N2;
lapb->mode = LAPB_DEFAULT_MODE;
lapb->window = LAPB_DEFAULT_WINDOW;
lapb->state = LAPB_STATE_0;
atomic_set(&lapb->refcnt, 1);
out:
return lapb;
}
int lapb_register(struct net_device *dev,
const struct lapb_register_struct *callbacks)
{
struct lapb_cb *lapb;
int rc = LAPB_BADTOKEN;
write_lock_bh(&lapb_list_lock);
lapb = __lapb_devtostruct(dev);
if (lapb) {
lapb_put(lapb);
goto out;
}
lapb = lapb_create_cb();
rc = LAPB_NOMEM;
if (!lapb)
goto out;
lapb->dev = dev;
lapb->callbacks = callbacks;
__lapb_insert_cb(lapb);
lapb_start_t1timer(lapb);
rc = LAPB_OK;
out:
write_unlock_bh(&lapb_list_lock);
return rc;
}
int lapb_unregister(struct net_device *dev)
{
struct lapb_cb *lapb;
int rc = LAPB_BADTOKEN;
write_lock_bh(&lapb_list_lock);
lapb = __lapb_devtostruct(dev);
if (!lapb)
goto out;
lapb_stop_t1timer(lapb);
lapb_stop_t2timer(lapb);
lapb_clear_queues(lapb);
__lapb_remove_cb(lapb);
lapb_put(lapb);
rc = LAPB_OK;
out:
write_unlock_bh(&lapb_list_lock);
return rc;
}
EXPORT_SYMBOL(lapb_unregister);
int lapb_getparms(struct net_device *dev, struct lapb_parms_struct *parms)
{
int rc = LAPB_BADTOKEN;
struct lapb_cb *lapb = lapb_devtostruct(dev);
if (!lapb)
goto out;
parms->t1 = lapb->t1 / HZ;
parms->t2 = lapb->t2 / HZ;
parms->n2 = lapb->n2;
parms->n2count = lapb->n2count;
parms->state = lapb->state;
parms->window = lapb->window;
parms->mode = lapb->mode;
if (!timer_pending(&lapb->t1timer))
parms->t1timer = 0;
else
parms->t1timer = (lapb->t1timer.expires - jiffies) / HZ;
if (!timer_pending(&lapb->t2timer))
parms->t2timer = 0;
else
parms->t2timer = (lapb->t2timer.expires - jiffies) / HZ;
lapb_put(lapb);
rc = LAPB_OK;
out:
return rc;
}
EXPORT_SYMBOL(lapb_getparms);
int lapb_setparms(struct net_device *dev, struct lapb_parms_struct *parms)
{
int rc = LAPB_BADTOKEN;
struct lapb_cb *lapb = lapb_devtostruct(dev);
if (!lapb)
goto out;
rc = LAPB_INVALUE;
if (parms->t1 < 1 || parms->t2 < 1 || parms->n2 < 1)
goto out_put;
if (lapb->state == LAPB_STATE_0) {
if (parms->mode & LAPB_EXTENDED) {
if (parms->window < 1 || parms->window > 127)
goto out_put;
} else {
if (parms->window < 1 || parms->window > 7)
goto out_put;
}
lapb->mode = parms->mode;
lapb->window = parms->window;
}
lapb->t1 = parms->t1 * HZ;
lapb->t2 = parms->t2 * HZ;
lapb->n2 = parms->n2;
rc = LAPB_OK;
out_put:
lapb_put(lapb);
out:
return rc;
}
EXPORT_SYMBOL(lapb_setparms);
int lapb_connect_request(struct net_device *dev)
{
struct lapb_cb *lapb = lapb_devtostruct(dev);
int rc = LAPB_BADTOKEN;
if (!lapb)
goto out;
rc = LAPB_OK;
if (lapb->state == LAPB_STATE_1)
goto out_put;
rc = LAPB_CONNECTED;
if (lapb->state == LAPB_STATE_3 || lapb->state == LAPB_STATE_4)
goto out_put;
lapb_establish_data_link(lapb);
lapb_dbg(0, "(%p) S0 -> S1\n", lapb->dev);
lapb->state = LAPB_STATE_1;
rc = LAPB_OK;
out_put:
lapb_put(lapb);
out:
return rc;
}
EXPORT_SYMBOL(lapb_connect_request);
int lapb_disconnect_request(struct net_device *dev)
{
struct lapb_cb *lapb = lapb_devtostruct(dev);
int rc = LAPB_BADTOKEN;
if (!lapb)
goto out;
switch (lapb->state) {
case LAPB_STATE_0:
rc = LAPB_NOTCONNECTED;
goto out_put;
case LAPB_STATE_1:
lapb_dbg(1, "(%p) S1 TX DISC(1)\n", lapb->dev);
lapb_dbg(0, "(%p) S1 -> S0\n", lapb->dev);
lapb_send_control(lapb, LAPB_DISC, LAPB_POLLON, LAPB_COMMAND);
lapb->state = LAPB_STATE_0;
lapb_start_t1timer(lapb);
rc = LAPB_NOTCONNECTED;
goto out_put;
case LAPB_STATE_2:
rc = LAPB_OK;
goto out_put;
}
lapb_clear_queues(lapb);
lapb->n2count = 0;
lapb_send_control(lapb, LAPB_DISC, LAPB_POLLON, LAPB_COMMAND);
lapb_start_t1timer(lapb);
lapb_stop_t2timer(lapb);
lapb->state = LAPB_STATE_2;
lapb_dbg(1, "(%p) S3 DISC(1)\n", lapb->dev);
lapb_dbg(0, "(%p) S3 -> S2\n", lapb->dev);
rc = LAPB_OK;
out_put:
lapb_put(lapb);
out:
return rc;
}
EXPORT_SYMBOL(lapb_disconnect_request);
int lapb_data_request(struct net_device *dev, struct sk_buff *skb)
{
struct lapb_cb *lapb = lapb_devtostruct(dev);
int rc = LAPB_BADTOKEN;
if (!lapb)
goto out;
rc = LAPB_NOTCONNECTED;
if (lapb->state != LAPB_STATE_3 && lapb->state != LAPB_STATE_4)
goto out_put;
skb_queue_tail(&lapb->write_queue, skb);
lapb_kick(lapb);
rc = LAPB_OK;
out_put:
lapb_put(lapb);
out:
return rc;
}
EXPORT_SYMBOL(lapb_data_request);
int lapb_data_received(struct net_device *dev, struct sk_buff *skb)
{
struct lapb_cb *lapb = lapb_devtostruct(dev);
int rc = LAPB_BADTOKEN;
if (lapb) {
lapb_data_input(lapb, skb);
lapb_put(lapb);
rc = LAPB_OK;
}
return rc;
}
EXPORT_SYMBOL(lapb_data_received);
void lapb_connect_confirmation(struct lapb_cb *lapb, int reason)
{
if (lapb->callbacks->connect_confirmation)
lapb->callbacks->connect_confirmation(lapb->dev, reason);
}
void lapb_connect_indication(struct lapb_cb *lapb, int reason)
{
if (lapb->callbacks->connect_indication)
lapb->callbacks->connect_indication(lapb->dev, reason);
}
void lapb_disconnect_confirmation(struct lapb_cb *lapb, int reason)
{
if (lapb->callbacks->disconnect_confirmation)
lapb->callbacks->disconnect_confirmation(lapb->dev, reason);
}
void lapb_disconnect_indication(struct lapb_cb *lapb, int reason)
{
if (lapb->callbacks->disconnect_indication)
lapb->callbacks->disconnect_indication(lapb->dev, reason);
}
int lapb_data_indication(struct lapb_cb *lapb, struct sk_buff *skb)
{
if (lapb->callbacks->data_indication)
return lapb->callbacks->data_indication(lapb->dev, skb);
kfree_skb(skb);
return NET_RX_SUCCESS; /* For now; must be != NET_RX_DROP */
}
int lapb_data_transmit(struct lapb_cb *lapb, struct sk_buff *skb)
{
int used = 0;
if (lapb->callbacks->data_transmit) {
lapb->callbacks->data_transmit(lapb->dev, skb);
used = 1;
}
return used;
}
static int __init lapb_init(void)
{
return 0;
}
static void __exit lapb_exit(void)
{
WARN_ON(!list_empty(&lapb_list));
}
MODULE_AUTHOR("Jonathan Naylor <g4klx@g4klx.demon.co.uk>");
MODULE_DESCRIPTION("The X.25 Link Access Procedure B link layer protocol");
MODULE_LICENSE("GPL");
module_init(lapb_init);
module_exit(lapb_exit);
| gpl-2.0 |
DashBlacK/kernel_samsung_dart | arch/alpha/kernel/irq_i8259.c | 1486 | 4256 | /*
* linux/arch/alpha/kernel/irq_i8259.c
*
* This is the 'legacy' 8259A Programmable Interrupt Controller,
* present in the majority of PC/AT boxes.
*
* Started hacking from linux-2.3.30pre6/arch/i386/kernel/i8259.c.
*/
#include <linux/init.h>
#include <linux/cache.h>
#include <linux/sched.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <asm/io.h>
#include "proto.h"
#include "irq_impl.h"
/* Note mask bit is true for DISABLED irqs. */
static unsigned int cached_irq_mask = 0xffff;
static DEFINE_SPINLOCK(i8259_irq_lock);
static inline void
i8259_update_irq_hw(unsigned int irq, unsigned long mask)
{
int port = 0x21;
if (irq & 8) mask >>= 8;
if (irq & 8) port = 0xA1;
outb(mask, port);
}
inline void
i8259a_enable_irq(unsigned int irq)
{
spin_lock(&i8259_irq_lock);
i8259_update_irq_hw(irq, cached_irq_mask &= ~(1 << irq));
spin_unlock(&i8259_irq_lock);
}
static inline void
__i8259a_disable_irq(unsigned int irq)
{
i8259_update_irq_hw(irq, cached_irq_mask |= 1 << irq);
}
void
i8259a_disable_irq(unsigned int irq)
{
spin_lock(&i8259_irq_lock);
__i8259a_disable_irq(irq);
spin_unlock(&i8259_irq_lock);
}
void
i8259a_mask_and_ack_irq(unsigned int irq)
{
spin_lock(&i8259_irq_lock);
__i8259a_disable_irq(irq);
/* Ack the interrupt making it the lowest priority. */
if (irq >= 8) {
outb(0xE0 | (irq - 8), 0xa0); /* ack the slave */
irq = 2;
}
outb(0xE0 | irq, 0x20); /* ack the master */
spin_unlock(&i8259_irq_lock);
}
unsigned int
i8259a_startup_irq(unsigned int irq)
{
i8259a_enable_irq(irq);
return 0; /* never anything pending */
}
void
i8259a_end_irq(unsigned int irq)
{
if (!(irq_desc[irq].status & (IRQ_DISABLED|IRQ_INPROGRESS)))
i8259a_enable_irq(irq);
}
struct irq_chip i8259a_irq_type = {
.name = "XT-PIC",
.startup = i8259a_startup_irq,
.shutdown = i8259a_disable_irq,
.enable = i8259a_enable_irq,
.disable = i8259a_disable_irq,
.ack = i8259a_mask_and_ack_irq,
.end = i8259a_end_irq,
};
void __init
init_i8259a_irqs(void)
{
static struct irqaction cascade = {
.handler = no_action,
.name = "cascade",
};
long i;
outb(0xff, 0x21); /* mask all of 8259A-1 */
outb(0xff, 0xA1); /* mask all of 8259A-2 */
for (i = 0; i < 16; i++) {
irq_desc[i].status = IRQ_DISABLED;
irq_desc[i].chip = &i8259a_irq_type;
}
setup_irq(2, &cascade);
}
#if defined(CONFIG_ALPHA_GENERIC)
# define IACK_SC alpha_mv.iack_sc
#elif defined(CONFIG_ALPHA_APECS)
# define IACK_SC APECS_IACK_SC
#elif defined(CONFIG_ALPHA_LCA)
# define IACK_SC LCA_IACK_SC
#elif defined(CONFIG_ALPHA_CIA)
# define IACK_SC CIA_IACK_SC
#elif defined(CONFIG_ALPHA_PYXIS)
# define IACK_SC PYXIS_IACK_SC
#elif defined(CONFIG_ALPHA_TITAN)
# define IACK_SC TITAN_IACK_SC
#elif defined(CONFIG_ALPHA_TSUNAMI)
# define IACK_SC TSUNAMI_IACK_SC
#elif defined(CONFIG_ALPHA_IRONGATE)
# define IACK_SC IRONGATE_IACK_SC
#endif
/* Note that CONFIG_ALPHA_POLARIS is intentionally left out here, since
sys_rx164 wants to use isa_no_iack_sc_device_interrupt for some reason. */
#if defined(IACK_SC)
void
isa_device_interrupt(unsigned long vector)
{
/*
* Generate a PCI interrupt acknowledge cycle. The PIC will
* respond with the interrupt vector of the highest priority
* interrupt that is pending. The PALcode sets up the
* interrupts vectors such that irq level L generates vector L.
*/
int j = *(vuip) IACK_SC;
j &= 0xff;
handle_irq(j);
}
#endif
#if defined(CONFIG_ALPHA_GENERIC) || !defined(IACK_SC)
void
isa_no_iack_sc_device_interrupt(unsigned long vector)
{
unsigned long pic;
/*
* It seems to me that the probability of two or more *device*
* interrupts occurring at almost exactly the same time is
* pretty low. So why pay the price of checking for
* additional interrupts here if the common case can be
* handled so much easier?
*/
/*
* The first read of gives you *all* interrupting lines.
* Therefore, read the mask register and and out those lines
* not enabled. Note that some documentation has 21 and a1
* write only. This is not true.
*/
pic = inb(0x20) | (inb(0xA0) << 8); /* read isr */
pic &= 0xFFFB; /* mask out cascade & hibits */
while (pic) {
int j = ffz(~pic);
pic &= pic - 1;
handle_irq(j);
}
}
#endif
| gpl-2.0 |
Abhinav1997/kernel_cyanogen_msm8916 | drivers/gpu/drm/gma500/mdfld_dsi_pkg_sender.c | 2766 | 16273 | /*
* 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:
* Jackie Li<yaodong.li@intel.com>
*/
#include <linux/freezer.h>
#include "mdfld_dsi_output.h"
#include "mdfld_dsi_pkg_sender.h"
#include "mdfld_dsi_dpi.h"
#define MDFLD_DSI_READ_MAX_COUNT 5000
enum data_type {
DSI_DT_GENERIC_SHORT_WRITE_0 = 0x03,
DSI_DT_GENERIC_SHORT_WRITE_1 = 0x13,
DSI_DT_GENERIC_SHORT_WRITE_2 = 0x23,
DSI_DT_GENERIC_READ_0 = 0x04,
DSI_DT_GENERIC_READ_1 = 0x14,
DSI_DT_GENERIC_READ_2 = 0x24,
DSI_DT_GENERIC_LONG_WRITE = 0x29,
DSI_DT_DCS_SHORT_WRITE_0 = 0x05,
DSI_DT_DCS_SHORT_WRITE_1 = 0x15,
DSI_DT_DCS_READ = 0x06,
DSI_DT_DCS_LONG_WRITE = 0x39,
};
enum {
MDFLD_DSI_PANEL_MODE_SLEEP = 0x1,
};
enum {
MDFLD_DSI_PKG_SENDER_FREE = 0x0,
MDFLD_DSI_PKG_SENDER_BUSY = 0x1,
};
static const char *const dsi_errors[] = {
"RX SOT Error",
"RX SOT Sync Error",
"RX EOT Sync Error",
"RX Escape Mode Entry Error",
"RX LP TX Sync Error",
"RX HS Receive Timeout Error",
"RX False Control Error",
"RX ECC Single Bit Error",
"RX ECC Multibit Error",
"RX Checksum Error",
"RX DSI Data Type Not Recognised",
"RX DSI VC ID Invalid",
"TX False Control Error",
"TX ECC Single Bit Error",
"TX ECC Multibit Error",
"TX Checksum Error",
"TX DSI Data Type Not Recognised",
"TX DSI VC ID invalid",
"High Contention",
"Low contention",
"DPI FIFO Under run",
"HS TX Timeout",
"LP RX Timeout",
"Turn Around ACK Timeout",
"ACK With No Error",
"RX Invalid TX Length",
"RX Prot Violation",
"HS Generic Write FIFO Full",
"LP Generic Write FIFO Full",
"Generic Read Data Avail"
"Special Packet Sent",
"Tearing Effect",
};
static inline int wait_for_gen_fifo_empty(struct mdfld_dsi_pkg_sender *sender,
u32 mask)
{
struct drm_device *dev = sender->dev;
u32 gen_fifo_stat_reg = sender->mipi_gen_fifo_stat_reg;
int retry = 0xffff;
while (retry--) {
if ((mask & REG_READ(gen_fifo_stat_reg)) == mask)
return 0;
udelay(100);
}
DRM_ERROR("fifo is NOT empty 0x%08x\n", REG_READ(gen_fifo_stat_reg));
return -EIO;
}
static int wait_for_all_fifos_empty(struct mdfld_dsi_pkg_sender *sender)
{
return wait_for_gen_fifo_empty(sender, (BIT(2) | BIT(10) | BIT(18) |
BIT(26) | BIT(27) | BIT(28)));
}
static int wait_for_lp_fifos_empty(struct mdfld_dsi_pkg_sender *sender)
{
return wait_for_gen_fifo_empty(sender, (BIT(10) | BIT(26)));
}
static int wait_for_hs_fifos_empty(struct mdfld_dsi_pkg_sender *sender)
{
return wait_for_gen_fifo_empty(sender, (BIT(2) | BIT(18)));
}
static int handle_dsi_error(struct mdfld_dsi_pkg_sender *sender, u32 mask)
{
u32 intr_stat_reg = sender->mipi_intr_stat_reg;
struct drm_device *dev = sender->dev;
dev_dbg(sender->dev->dev, "Handling error 0x%08x\n", mask);
switch (mask) {
case BIT(0):
case BIT(1):
case BIT(2):
case BIT(3):
case BIT(4):
case BIT(5):
case BIT(6):
case BIT(7):
case BIT(8):
case BIT(9):
case BIT(10):
case BIT(11):
case BIT(12):
case BIT(13):
dev_dbg(sender->dev->dev, "No Action required\n");
break;
case BIT(14):
/*wait for all fifo empty*/
/*wait_for_all_fifos_empty(sender)*/;
break;
case BIT(15):
dev_dbg(sender->dev->dev, "No Action required\n");
break;
case BIT(16):
break;
case BIT(17):
break;
case BIT(18):
case BIT(19):
dev_dbg(sender->dev->dev, "High/Low contention detected\n");
/*wait for contention recovery time*/
/*mdelay(10);*/
/*wait for all fifo empty*/
if (0)
wait_for_all_fifos_empty(sender);
break;
case BIT(20):
dev_dbg(sender->dev->dev, "No Action required\n");
break;
case BIT(21):
/*wait for all fifo empty*/
/*wait_for_all_fifos_empty(sender);*/
break;
case BIT(22):
break;
case BIT(23):
case BIT(24):
case BIT(25):
case BIT(26):
case BIT(27):
dev_dbg(sender->dev->dev, "HS Gen fifo full\n");
REG_WRITE(intr_stat_reg, mask);
wait_for_hs_fifos_empty(sender);
break;
case BIT(28):
dev_dbg(sender->dev->dev, "LP Gen fifo full\n");
REG_WRITE(intr_stat_reg, mask);
wait_for_lp_fifos_empty(sender);
break;
case BIT(29):
case BIT(30):
case BIT(31):
dev_dbg(sender->dev->dev, "No Action required\n");
break;
}
if (mask & REG_READ(intr_stat_reg))
dev_dbg(sender->dev->dev,
"Cannot clean interrupt 0x%08x\n", mask);
return 0;
}
static int dsi_error_handler(struct mdfld_dsi_pkg_sender *sender)
{
struct drm_device *dev = sender->dev;
u32 intr_stat_reg = sender->mipi_intr_stat_reg;
u32 mask;
u32 intr_stat;
int i;
int err = 0;
intr_stat = REG_READ(intr_stat_reg);
for (i = 0; i < 32; i++) {
mask = (0x00000001UL) << i;
if (intr_stat & mask) {
dev_dbg(sender->dev->dev, "[DSI]: %s\n", dsi_errors[i]);
err = handle_dsi_error(sender, mask);
if (err)
DRM_ERROR("Cannot handle error\n");
}
}
return err;
}
static int send_short_pkg(struct mdfld_dsi_pkg_sender *sender, u8 data_type,
u8 cmd, u8 param, bool hs)
{
struct drm_device *dev = sender->dev;
u32 ctrl_reg;
u32 val;
u8 virtual_channel = 0;
if (hs) {
ctrl_reg = sender->mipi_hs_gen_ctrl_reg;
/* FIXME: wait_for_hs_fifos_empty(sender); */
} else {
ctrl_reg = sender->mipi_lp_gen_ctrl_reg;
/* FIXME: wait_for_lp_fifos_empty(sender); */
}
val = FLD_VAL(param, 23, 16) | FLD_VAL(cmd, 15, 8) |
FLD_VAL(virtual_channel, 7, 6) | FLD_VAL(data_type, 5, 0);
REG_WRITE(ctrl_reg, val);
return 0;
}
static int send_long_pkg(struct mdfld_dsi_pkg_sender *sender, u8 data_type,
u8 *data, int len, bool hs)
{
struct drm_device *dev = sender->dev;
u32 ctrl_reg;
u32 data_reg;
u32 val;
u8 *p;
u8 b1, b2, b3, b4;
u8 virtual_channel = 0;
int i;
if (hs) {
ctrl_reg = sender->mipi_hs_gen_ctrl_reg;
data_reg = sender->mipi_hs_gen_data_reg;
/* FIXME: wait_for_hs_fifos_empty(sender); */
} else {
ctrl_reg = sender->mipi_lp_gen_ctrl_reg;
data_reg = sender->mipi_lp_gen_data_reg;
/* FIXME: wait_for_lp_fifos_empty(sender); */
}
p = data;
for (i = 0; i < len / 4; i++) {
b1 = *p++;
b2 = *p++;
b3 = *p++;
b4 = *p++;
REG_WRITE(data_reg, b4 << 24 | b3 << 16 | b2 << 8 | b1);
}
i = len % 4;
if (i) {
b1 = 0; b2 = 0; b3 = 0;
switch (i) {
case 3:
b1 = *p++;
b2 = *p++;
b3 = *p++;
break;
case 2:
b1 = *p++;
b2 = *p++;
break;
case 1:
b1 = *p++;
break;
}
REG_WRITE(data_reg, b3 << 16 | b2 << 8 | b1);
}
val = FLD_VAL(len, 23, 8) | FLD_VAL(virtual_channel, 7, 6) |
FLD_VAL(data_type, 5, 0);
REG_WRITE(ctrl_reg, val);
return 0;
}
static int send_pkg_prepare(struct mdfld_dsi_pkg_sender *sender, u8 data_type,
u8 *data, u16 len)
{
u8 cmd;
switch (data_type) {
case DSI_DT_DCS_SHORT_WRITE_0:
case DSI_DT_DCS_SHORT_WRITE_1:
case DSI_DT_DCS_LONG_WRITE:
cmd = *data;
break;
default:
return 0;
}
/*this prevents other package sending while doing msleep*/
sender->status = MDFLD_DSI_PKG_SENDER_BUSY;
/*wait for 120 milliseconds in case exit_sleep_mode just be sent*/
if (unlikely(cmd == DCS_ENTER_SLEEP_MODE)) {
/*TODO: replace it with msleep later*/
mdelay(120);
}
if (unlikely(cmd == DCS_EXIT_SLEEP_MODE)) {
/*TODO: replace it with msleep later*/
mdelay(120);
}
return 0;
}
static int send_pkg_done(struct mdfld_dsi_pkg_sender *sender, u8 data_type,
u8 *data, u16 len)
{
u8 cmd;
switch (data_type) {
case DSI_DT_DCS_SHORT_WRITE_0:
case DSI_DT_DCS_SHORT_WRITE_1:
case DSI_DT_DCS_LONG_WRITE:
cmd = *data;
break;
default:
return 0;
}
/*update panel status*/
if (unlikely(cmd == DCS_ENTER_SLEEP_MODE)) {
sender->panel_mode |= MDFLD_DSI_PANEL_MODE_SLEEP;
/*TODO: replace it with msleep later*/
mdelay(120);
} else if (unlikely(cmd == DCS_EXIT_SLEEP_MODE)) {
sender->panel_mode &= ~MDFLD_DSI_PANEL_MODE_SLEEP;
/*TODO: replace it with msleep later*/
mdelay(120);
} else if (unlikely(cmd == DCS_SOFT_RESET)) {
/*TODO: replace it with msleep later*/
mdelay(5);
}
sender->status = MDFLD_DSI_PKG_SENDER_FREE;
return 0;
}
static int send_pkg(struct mdfld_dsi_pkg_sender *sender, u8 data_type,
u8 *data, u16 len, bool hs)
{
int ret;
/*handle DSI error*/
ret = dsi_error_handler(sender);
if (ret) {
DRM_ERROR("Error handling failed\n");
return -EAGAIN;
}
/* send pkg */
if (sender->status == MDFLD_DSI_PKG_SENDER_BUSY) {
DRM_ERROR("sender is busy\n");
return -EAGAIN;
}
ret = send_pkg_prepare(sender, data_type, data, len);
if (ret) {
DRM_ERROR("send_pkg_prepare error\n");
return ret;
}
switch (data_type) {
case DSI_DT_GENERIC_SHORT_WRITE_0:
case DSI_DT_GENERIC_SHORT_WRITE_1:
case DSI_DT_GENERIC_SHORT_WRITE_2:
case DSI_DT_GENERIC_READ_0:
case DSI_DT_GENERIC_READ_1:
case DSI_DT_GENERIC_READ_2:
case DSI_DT_DCS_SHORT_WRITE_0:
case DSI_DT_DCS_SHORT_WRITE_1:
case DSI_DT_DCS_READ:
ret = send_short_pkg(sender, data_type, data[0], data[1], hs);
break;
case DSI_DT_GENERIC_LONG_WRITE:
case DSI_DT_DCS_LONG_WRITE:
ret = send_long_pkg(sender, data_type, data, len, hs);
break;
}
send_pkg_done(sender, data_type, data, len);
/*FIXME: should I query complete and fifo empty here?*/
return ret;
}
int mdfld_dsi_send_mcs_long(struct mdfld_dsi_pkg_sender *sender, u8 *data,
u32 len, bool hs)
{
unsigned long flags;
if (!sender || !data || !len) {
DRM_ERROR("Invalid parameters\n");
return -EINVAL;
}
spin_lock_irqsave(&sender->lock, flags);
send_pkg(sender, DSI_DT_DCS_LONG_WRITE, data, len, hs);
spin_unlock_irqrestore(&sender->lock, flags);
return 0;
}
int mdfld_dsi_send_mcs_short(struct mdfld_dsi_pkg_sender *sender, u8 cmd,
u8 param, u8 param_num, bool hs)
{
u8 data[2];
unsigned long flags;
u8 data_type;
if (!sender) {
DRM_ERROR("Invalid parameter\n");
return -EINVAL;
}
data[0] = cmd;
if (param_num) {
data_type = DSI_DT_DCS_SHORT_WRITE_1;
data[1] = param;
} else {
data_type = DSI_DT_DCS_SHORT_WRITE_0;
data[1] = 0;
}
spin_lock_irqsave(&sender->lock, flags);
send_pkg(sender, data_type, data, sizeof(data), hs);
spin_unlock_irqrestore(&sender->lock, flags);
return 0;
}
int mdfld_dsi_send_gen_short(struct mdfld_dsi_pkg_sender *sender, u8 param0,
u8 param1, u8 param_num, bool hs)
{
u8 data[2];
unsigned long flags;
u8 data_type;
if (!sender || param_num > 2) {
DRM_ERROR("Invalid parameter\n");
return -EINVAL;
}
switch (param_num) {
case 0:
data_type = DSI_DT_GENERIC_SHORT_WRITE_0;
data[0] = 0;
data[1] = 0;
break;
case 1:
data_type = DSI_DT_GENERIC_SHORT_WRITE_1;
data[0] = param0;
data[1] = 0;
break;
case 2:
data_type = DSI_DT_GENERIC_SHORT_WRITE_2;
data[0] = param0;
data[1] = param1;
break;
}
spin_lock_irqsave(&sender->lock, flags);
send_pkg(sender, data_type, data, sizeof(data), hs);
spin_unlock_irqrestore(&sender->lock, flags);
return 0;
}
int mdfld_dsi_send_gen_long(struct mdfld_dsi_pkg_sender *sender, u8 *data,
u32 len, bool hs)
{
unsigned long flags;
if (!sender || !data || !len) {
DRM_ERROR("Invalid parameters\n");
return -EINVAL;
}
spin_lock_irqsave(&sender->lock, flags);
send_pkg(sender, DSI_DT_GENERIC_LONG_WRITE, data, len, hs);
spin_unlock_irqrestore(&sender->lock, flags);
return 0;
}
static int __read_panel_data(struct mdfld_dsi_pkg_sender *sender, u8 data_type,
u8 *data, u16 len, u32 *data_out, u16 len_out, bool hs)
{
unsigned long flags;
struct drm_device *dev = sender->dev;
int i;
u32 gen_data_reg;
int retry = MDFLD_DSI_READ_MAX_COUNT;
if (!sender || !data_out || !len_out) {
DRM_ERROR("Invalid parameters\n");
return -EINVAL;
}
/**
* do reading.
* 0) send out generic read request
* 1) polling read data avail interrupt
* 2) read data
*/
spin_lock_irqsave(&sender->lock, flags);
REG_WRITE(sender->mipi_intr_stat_reg, BIT(29));
if ((REG_READ(sender->mipi_intr_stat_reg) & BIT(29)))
DRM_ERROR("Can NOT clean read data valid interrupt\n");
/*send out read request*/
send_pkg(sender, data_type, data, len, hs);
/*polling read data avail interrupt*/
while (retry && !(REG_READ(sender->mipi_intr_stat_reg) & BIT(29))) {
udelay(100);
retry--;
}
if (!retry) {
spin_unlock_irqrestore(&sender->lock, flags);
return -ETIMEDOUT;
}
REG_WRITE(sender->mipi_intr_stat_reg, BIT(29));
/*read data*/
if (hs)
gen_data_reg = sender->mipi_hs_gen_data_reg;
else
gen_data_reg = sender->mipi_lp_gen_data_reg;
for (i = 0; i < len_out; i++)
*(data_out + i) = REG_READ(gen_data_reg);
spin_unlock_irqrestore(&sender->lock, flags);
return 0;
}
int mdfld_dsi_read_mcs(struct mdfld_dsi_pkg_sender *sender, u8 cmd,
u32 *data, u16 len, bool hs)
{
if (!sender || !data || !len) {
DRM_ERROR("Invalid parameters\n");
return -EINVAL;
}
return __read_panel_data(sender, DSI_DT_DCS_READ, &cmd, 1,
data, len, hs);
}
int mdfld_dsi_pkg_sender_init(struct mdfld_dsi_connector *dsi_connector,
int pipe)
{
struct mdfld_dsi_pkg_sender *pkg_sender;
struct mdfld_dsi_config *dsi_config =
mdfld_dsi_get_config(dsi_connector);
struct drm_device *dev = dsi_config->dev;
struct drm_psb_private *dev_priv = dev->dev_private;
const struct psb_offset *map = &dev_priv->regmap[pipe];
u32 mipi_val = 0;
if (!dsi_connector) {
DRM_ERROR("Invalid parameter\n");
return -EINVAL;
}
pkg_sender = dsi_connector->pkg_sender;
if (!pkg_sender || IS_ERR(pkg_sender)) {
pkg_sender = kzalloc(sizeof(struct mdfld_dsi_pkg_sender),
GFP_KERNEL);
if (!pkg_sender) {
DRM_ERROR("Create DSI pkg sender failed\n");
return -ENOMEM;
}
dsi_connector->pkg_sender = (void *)pkg_sender;
}
pkg_sender->dev = dev;
pkg_sender->dsi_connector = dsi_connector;
pkg_sender->pipe = pipe;
pkg_sender->pkg_num = 0;
pkg_sender->panel_mode = 0;
pkg_sender->status = MDFLD_DSI_PKG_SENDER_FREE;
/*init regs*/
/* FIXME: should just copy the regmap ptr ? */
pkg_sender->dpll_reg = map->dpll;
pkg_sender->dspcntr_reg = map->cntr;
pkg_sender->pipeconf_reg = map->conf;
pkg_sender->dsplinoff_reg = map->linoff;
pkg_sender->dspsurf_reg = map->surf;
pkg_sender->pipestat_reg = map->status;
pkg_sender->mipi_intr_stat_reg = MIPI_INTR_STAT_REG(pipe);
pkg_sender->mipi_lp_gen_data_reg = MIPI_LP_GEN_DATA_REG(pipe);
pkg_sender->mipi_hs_gen_data_reg = MIPI_HS_GEN_DATA_REG(pipe);
pkg_sender->mipi_lp_gen_ctrl_reg = MIPI_LP_GEN_CTRL_REG(pipe);
pkg_sender->mipi_hs_gen_ctrl_reg = MIPI_HS_GEN_CTRL_REG(pipe);
pkg_sender->mipi_gen_fifo_stat_reg = MIPI_GEN_FIFO_STAT_REG(pipe);
pkg_sender->mipi_data_addr_reg = MIPI_DATA_ADD_REG(pipe);
pkg_sender->mipi_data_len_reg = MIPI_DATA_LEN_REG(pipe);
pkg_sender->mipi_cmd_addr_reg = MIPI_CMD_ADD_REG(pipe);
pkg_sender->mipi_cmd_len_reg = MIPI_CMD_LEN_REG(pipe);
/*init lock*/
spin_lock_init(&pkg_sender->lock);
if (mdfld_get_panel_type(dev, pipe) != TC35876X) {
/**
* For video mode, don't enable DPI timing output here,
* will init the DPI timing output during mode setting.
*/
mipi_val = PASS_FROM_SPHY_TO_AFE | SEL_FLOPPED_HSTX;
if (pipe == 0)
mipi_val |= 0x2;
REG_WRITE(MIPI_PORT_CONTROL(pipe), mipi_val);
REG_READ(MIPI_PORT_CONTROL(pipe));
/* do dsi controller init */
mdfld_dsi_controller_init(dsi_config, pipe);
}
return 0;
}
void mdfld_dsi_pkg_sender_destroy(struct mdfld_dsi_pkg_sender *sender)
{
if (!sender || IS_ERR(sender))
return;
/*free*/
kfree(sender);
}
| gpl-2.0 |
vic-nation/android_kernel_gogh | arch/m68k/kernel/sys_m68k.c | 3022 | 13827 | /*
* linux/arch/m68k/kernel/sys_m68k.c
*
* This file contains various random system calls that
* have a non-standard calling sequence on the Linux/m68k
* platform.
*/
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/fs.h>
#include <linux/smp.h>
#include <linux/sem.h>
#include <linux/msg.h>
#include <linux/shm.h>
#include <linux/stat.h>
#include <linux/syscalls.h>
#include <linux/mman.h>
#include <linux/file.h>
#include <linux/ipc.h>
#include <asm/setup.h>
#include <asm/uaccess.h>
#include <asm/cachectl.h>
#include <asm/traps.h>
#include <asm/page.h>
#include <asm/unistd.h>
#include <asm/cacheflush.h>
#ifdef CONFIG_MMU
#include <asm/tlb.h>
asmlinkage int do_page_fault(struct pt_regs *regs, unsigned long address,
unsigned long error_code);
asmlinkage long sys_mmap2(unsigned long addr, unsigned long len,
unsigned long prot, unsigned long flags,
unsigned long fd, unsigned long pgoff)
{
/*
* This is wrong for sun3 - there PAGE_SIZE is 8Kb,
* so we need to shift the argument down by 1; m68k mmap64(3)
* (in libc) expects the last argument of mmap2 in 4Kb units.
*/
return sys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);
}
/* Convert virtual (user) address VADDR to physical address PADDR */
#define virt_to_phys_040(vaddr) \
({ \
unsigned long _mmusr, _paddr; \
\
__asm__ __volatile__ (".chip 68040\n\t" \
"ptestr (%1)\n\t" \
"movec %%mmusr,%0\n\t" \
".chip 68k" \
: "=r" (_mmusr) \
: "a" (vaddr)); \
_paddr = (_mmusr & MMU_R_040) ? (_mmusr & PAGE_MASK) : 0; \
_paddr; \
})
static inline int
cache_flush_040 (unsigned long addr, int scope, int cache, unsigned long len)
{
unsigned long paddr, i;
switch (scope)
{
case FLUSH_SCOPE_ALL:
switch (cache)
{
case FLUSH_CACHE_DATA:
/* This nop is needed for some broken versions of the 68040. */
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpusha %dc\n\t"
".chip 68k");
break;
case FLUSH_CACHE_INSN:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpusha %ic\n\t"
".chip 68k");
break;
default:
case FLUSH_CACHE_BOTH:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpusha %bc\n\t"
".chip 68k");
break;
}
break;
case FLUSH_SCOPE_LINE:
/* Find the physical address of the first mapped page in the
address range. */
if ((paddr = virt_to_phys_040(addr))) {
paddr += addr & ~(PAGE_MASK | 15);
len = (len + (addr & 15) + 15) >> 4;
} else {
unsigned long tmp = PAGE_SIZE - (addr & ~PAGE_MASK);
if (len <= tmp)
return 0;
addr += tmp;
len -= tmp;
tmp = PAGE_SIZE;
for (;;)
{
if ((paddr = virt_to_phys_040(addr)))
break;
if (len <= tmp)
return 0;
addr += tmp;
len -= tmp;
}
len = (len + 15) >> 4;
}
i = (PAGE_SIZE - (paddr & ~PAGE_MASK)) >> 4;
while (len--)
{
switch (cache)
{
case FLUSH_CACHE_DATA:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpushl %%dc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
case FLUSH_CACHE_INSN:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpushl %%ic,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
default:
case FLUSH_CACHE_BOTH:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpushl %%bc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
}
if (!--i && len)
{
/*
* No need to page align here since it is done by
* virt_to_phys_040().
*/
addr += PAGE_SIZE;
i = PAGE_SIZE / 16;
/* Recompute physical address when crossing a page
boundary. */
for (;;)
{
if ((paddr = virt_to_phys_040(addr)))
break;
if (len <= i)
return 0;
len -= i;
addr += PAGE_SIZE;
}
}
else
paddr += 16;
}
break;
default:
case FLUSH_SCOPE_PAGE:
len += (addr & ~PAGE_MASK) + (PAGE_SIZE - 1);
for (len >>= PAGE_SHIFT; len--; addr += PAGE_SIZE)
{
if (!(paddr = virt_to_phys_040(addr)))
continue;
switch (cache)
{
case FLUSH_CACHE_DATA:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpushp %%dc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
case FLUSH_CACHE_INSN:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpushp %%ic,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
default:
case FLUSH_CACHE_BOTH:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpushp %%bc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
}
}
break;
}
return 0;
}
#define virt_to_phys_060(vaddr) \
({ \
unsigned long paddr; \
__asm__ __volatile__ (".chip 68060\n\t" \
"plpar (%0)\n\t" \
".chip 68k" \
: "=a" (paddr) \
: "0" (vaddr)); \
(paddr); /* XXX */ \
})
static inline int
cache_flush_060 (unsigned long addr, int scope, int cache, unsigned long len)
{
unsigned long paddr, i;
/*
* 68060 manual says:
* cpush %dc : flush DC, remains valid (with our %cacr setup)
* cpush %ic : invalidate IC
* cpush %bc : flush DC + invalidate IC
*/
switch (scope)
{
case FLUSH_SCOPE_ALL:
switch (cache)
{
case FLUSH_CACHE_DATA:
__asm__ __volatile__ (".chip 68060\n\t"
"cpusha %dc\n\t"
".chip 68k");
break;
case FLUSH_CACHE_INSN:
__asm__ __volatile__ (".chip 68060\n\t"
"cpusha %ic\n\t"
".chip 68k");
break;
default:
case FLUSH_CACHE_BOTH:
__asm__ __volatile__ (".chip 68060\n\t"
"cpusha %bc\n\t"
".chip 68k");
break;
}
break;
case FLUSH_SCOPE_LINE:
/* Find the physical address of the first mapped page in the
address range. */
len += addr & 15;
addr &= -16;
if (!(paddr = virt_to_phys_060(addr))) {
unsigned long tmp = PAGE_SIZE - (addr & ~PAGE_MASK);
if (len <= tmp)
return 0;
addr += tmp;
len -= tmp;
tmp = PAGE_SIZE;
for (;;)
{
if ((paddr = virt_to_phys_060(addr)))
break;
if (len <= tmp)
return 0;
addr += tmp;
len -= tmp;
}
}
len = (len + 15) >> 4;
i = (PAGE_SIZE - (paddr & ~PAGE_MASK)) >> 4;
while (len--)
{
switch (cache)
{
case FLUSH_CACHE_DATA:
__asm__ __volatile__ (".chip 68060\n\t"
"cpushl %%dc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
case FLUSH_CACHE_INSN:
__asm__ __volatile__ (".chip 68060\n\t"
"cpushl %%ic,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
default:
case FLUSH_CACHE_BOTH:
__asm__ __volatile__ (".chip 68060\n\t"
"cpushl %%bc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
}
if (!--i && len)
{
/*
* We just want to jump to the first cache line
* in the next page.
*/
addr += PAGE_SIZE;
addr &= PAGE_MASK;
i = PAGE_SIZE / 16;
/* Recompute physical address when crossing a page
boundary. */
for (;;)
{
if ((paddr = virt_to_phys_060(addr)))
break;
if (len <= i)
return 0;
len -= i;
addr += PAGE_SIZE;
}
}
else
paddr += 16;
}
break;
default:
case FLUSH_SCOPE_PAGE:
len += (addr & ~PAGE_MASK) + (PAGE_SIZE - 1);
addr &= PAGE_MASK; /* Workaround for bug in some
revisions of the 68060 */
for (len >>= PAGE_SHIFT; len--; addr += PAGE_SIZE)
{
if (!(paddr = virt_to_phys_060(addr)))
continue;
switch (cache)
{
case FLUSH_CACHE_DATA:
__asm__ __volatile__ (".chip 68060\n\t"
"cpushp %%dc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
case FLUSH_CACHE_INSN:
__asm__ __volatile__ (".chip 68060\n\t"
"cpushp %%ic,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
default:
case FLUSH_CACHE_BOTH:
__asm__ __volatile__ (".chip 68060\n\t"
"cpushp %%bc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
}
}
break;
}
return 0;
}
/* sys_cacheflush -- flush (part of) the processor cache. */
asmlinkage int
sys_cacheflush (unsigned long addr, int scope, int cache, unsigned long len)
{
struct vm_area_struct *vma;
int ret = -EINVAL;
if (scope < FLUSH_SCOPE_LINE || scope > FLUSH_SCOPE_ALL ||
cache & ~FLUSH_CACHE_BOTH)
goto out;
if (scope == FLUSH_SCOPE_ALL) {
/* Only the superuser may explicitly flush the whole cache. */
ret = -EPERM;
if (!capable(CAP_SYS_ADMIN))
goto out;
} else {
/*
* Verify that the specified address region actually belongs
* to this process.
*/
vma = find_vma (current->mm, addr);
ret = -EINVAL;
/* Check for overflow. */
if (addr + len < addr)
goto out;
if (vma == NULL || addr < vma->vm_start || addr + len > vma->vm_end)
goto out;
}
if (CPU_IS_020_OR_030) {
if (scope == FLUSH_SCOPE_LINE && len < 256) {
unsigned long cacr;
__asm__ ("movec %%cacr, %0" : "=r" (cacr));
if (cache & FLUSH_CACHE_INSN)
cacr |= 4;
if (cache & FLUSH_CACHE_DATA)
cacr |= 0x400;
len >>= 2;
while (len--) {
__asm__ __volatile__ ("movec %1, %%caar\n\t"
"movec %0, %%cacr"
: /* no outputs */
: "r" (cacr), "r" (addr));
addr += 4;
}
} else {
/* Flush the whole cache, even if page granularity requested. */
unsigned long cacr;
__asm__ ("movec %%cacr, %0" : "=r" (cacr));
if (cache & FLUSH_CACHE_INSN)
cacr |= 8;
if (cache & FLUSH_CACHE_DATA)
cacr |= 0x800;
__asm__ __volatile__ ("movec %0, %%cacr" : : "r" (cacr));
}
ret = 0;
goto out;
} else {
/*
* 040 or 060: don't blindly trust 'scope', someone could
* try to flush a few megs of memory.
*/
if (len>=3*PAGE_SIZE && scope<FLUSH_SCOPE_PAGE)
scope=FLUSH_SCOPE_PAGE;
if (len>=10*PAGE_SIZE && scope<FLUSH_SCOPE_ALL)
scope=FLUSH_SCOPE_ALL;
if (CPU_IS_040) {
ret = cache_flush_040 (addr, scope, cache, len);
} else if (CPU_IS_060) {
ret = cache_flush_060 (addr, scope, cache, len);
}
}
out:
return ret;
}
/* This syscall gets its arguments in A0 (mem), D2 (oldval) and
D1 (newval). */
asmlinkage int
sys_atomic_cmpxchg_32(unsigned long newval, int oldval, int d3, int d4, int d5,
unsigned long __user * mem)
{
/* This was borrowed from ARM's implementation. */
for (;;) {
struct mm_struct *mm = current->mm;
pgd_t *pgd;
pmd_t *pmd;
pte_t *pte;
spinlock_t *ptl;
unsigned long mem_value;
down_read(&mm->mmap_sem);
pgd = pgd_offset(mm, (unsigned long)mem);
if (!pgd_present(*pgd))
goto bad_access;
pmd = pmd_offset(pgd, (unsigned long)mem);
if (!pmd_present(*pmd))
goto bad_access;
pte = pte_offset_map_lock(mm, pmd, (unsigned long)mem, &ptl);
if (!pte_present(*pte) || !pte_dirty(*pte)
|| !pte_write(*pte)) {
pte_unmap_unlock(pte, ptl);
goto bad_access;
}
/*
* No need to check for EFAULT; we know that the page is
* present and writable.
*/
__get_user(mem_value, mem);
if (mem_value == oldval)
__put_user(newval, mem);
pte_unmap_unlock(pte, ptl);
up_read(&mm->mmap_sem);
return mem_value;
bad_access:
up_read(&mm->mmap_sem);
/* This is not necessarily a bad access, we can get here if
a memory we're trying to write to should be copied-on-write.
Make the kernel do the necessary page stuff, then re-iterate.
Simulate a write access fault to do that. */
{
/* The first argument of the function corresponds to
D1, which is the first field of struct pt_regs. */
struct pt_regs *fp = (struct pt_regs *)&newval;
/* '3' is an RMW flag. */
if (do_page_fault(fp, (unsigned long)mem, 3))
/* If the do_page_fault() failed, we don't
have anything meaningful to return.
There should be a SIGSEGV pending for
the process. */
return 0xdeadbeef;
}
}
}
#else
/* sys_cacheflush -- flush (part of) the processor cache. */
asmlinkage int
sys_cacheflush (unsigned long addr, int scope, int cache, unsigned long len)
{
flush_cache_all();
return 0;
}
/* This syscall gets its arguments in A0 (mem), D2 (oldval) and
D1 (newval). */
asmlinkage int
sys_atomic_cmpxchg_32(unsigned long newval, int oldval, int d3, int d4, int d5,
unsigned long __user * mem)
{
struct mm_struct *mm = current->mm;
unsigned long mem_value;
down_read(&mm->mmap_sem);
mem_value = *mem;
if (mem_value == oldval)
*mem = newval;
up_read(&mm->mmap_sem);
return mem_value;
}
#endif /* CONFIG_MMU */
asmlinkage int sys_getpagesize(void)
{
return PAGE_SIZE;
}
/*
* Do a system call from kernel instead of calling sys_execve so we
* end up with proper pt_regs.
*/
int kernel_execve(const char *filename,
const char *const argv[],
const char *const envp[])
{
register long __res asm ("%d0") = __NR_execve;
register long __a asm ("%d1") = (long)(filename);
register long __b asm ("%d2") = (long)(argv);
register long __c asm ("%d3") = (long)(envp);
asm volatile ("trap #0" : "+d" (__res)
: "d" (__a), "d" (__b), "d" (__c));
return __res;
}
asmlinkage unsigned long sys_get_thread_area(void)
{
return current_thread_info()->tp_value;
}
asmlinkage int sys_set_thread_area(unsigned long tp)
{
current_thread_info()->tp_value = tp;
return 0;
}
asmlinkage int sys_atomic_barrier(void)
{
/* no code needed for uniprocs */
return 0;
}
| gpl-2.0 |
AzraelsKiss/android_kernel_samsung_smdk4412 | arch/m68k/kernel/sys_m68k.c | 3022 | 13827 | /*
* linux/arch/m68k/kernel/sys_m68k.c
*
* This file contains various random system calls that
* have a non-standard calling sequence on the Linux/m68k
* platform.
*/
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/fs.h>
#include <linux/smp.h>
#include <linux/sem.h>
#include <linux/msg.h>
#include <linux/shm.h>
#include <linux/stat.h>
#include <linux/syscalls.h>
#include <linux/mman.h>
#include <linux/file.h>
#include <linux/ipc.h>
#include <asm/setup.h>
#include <asm/uaccess.h>
#include <asm/cachectl.h>
#include <asm/traps.h>
#include <asm/page.h>
#include <asm/unistd.h>
#include <asm/cacheflush.h>
#ifdef CONFIG_MMU
#include <asm/tlb.h>
asmlinkage int do_page_fault(struct pt_regs *regs, unsigned long address,
unsigned long error_code);
asmlinkage long sys_mmap2(unsigned long addr, unsigned long len,
unsigned long prot, unsigned long flags,
unsigned long fd, unsigned long pgoff)
{
/*
* This is wrong for sun3 - there PAGE_SIZE is 8Kb,
* so we need to shift the argument down by 1; m68k mmap64(3)
* (in libc) expects the last argument of mmap2 in 4Kb units.
*/
return sys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);
}
/* Convert virtual (user) address VADDR to physical address PADDR */
#define virt_to_phys_040(vaddr) \
({ \
unsigned long _mmusr, _paddr; \
\
__asm__ __volatile__ (".chip 68040\n\t" \
"ptestr (%1)\n\t" \
"movec %%mmusr,%0\n\t" \
".chip 68k" \
: "=r" (_mmusr) \
: "a" (vaddr)); \
_paddr = (_mmusr & MMU_R_040) ? (_mmusr & PAGE_MASK) : 0; \
_paddr; \
})
static inline int
cache_flush_040 (unsigned long addr, int scope, int cache, unsigned long len)
{
unsigned long paddr, i;
switch (scope)
{
case FLUSH_SCOPE_ALL:
switch (cache)
{
case FLUSH_CACHE_DATA:
/* This nop is needed for some broken versions of the 68040. */
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpusha %dc\n\t"
".chip 68k");
break;
case FLUSH_CACHE_INSN:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpusha %ic\n\t"
".chip 68k");
break;
default:
case FLUSH_CACHE_BOTH:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpusha %bc\n\t"
".chip 68k");
break;
}
break;
case FLUSH_SCOPE_LINE:
/* Find the physical address of the first mapped page in the
address range. */
if ((paddr = virt_to_phys_040(addr))) {
paddr += addr & ~(PAGE_MASK | 15);
len = (len + (addr & 15) + 15) >> 4;
} else {
unsigned long tmp = PAGE_SIZE - (addr & ~PAGE_MASK);
if (len <= tmp)
return 0;
addr += tmp;
len -= tmp;
tmp = PAGE_SIZE;
for (;;)
{
if ((paddr = virt_to_phys_040(addr)))
break;
if (len <= tmp)
return 0;
addr += tmp;
len -= tmp;
}
len = (len + 15) >> 4;
}
i = (PAGE_SIZE - (paddr & ~PAGE_MASK)) >> 4;
while (len--)
{
switch (cache)
{
case FLUSH_CACHE_DATA:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpushl %%dc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
case FLUSH_CACHE_INSN:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpushl %%ic,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
default:
case FLUSH_CACHE_BOTH:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpushl %%bc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
}
if (!--i && len)
{
/*
* No need to page align here since it is done by
* virt_to_phys_040().
*/
addr += PAGE_SIZE;
i = PAGE_SIZE / 16;
/* Recompute physical address when crossing a page
boundary. */
for (;;)
{
if ((paddr = virt_to_phys_040(addr)))
break;
if (len <= i)
return 0;
len -= i;
addr += PAGE_SIZE;
}
}
else
paddr += 16;
}
break;
default:
case FLUSH_SCOPE_PAGE:
len += (addr & ~PAGE_MASK) + (PAGE_SIZE - 1);
for (len >>= PAGE_SHIFT; len--; addr += PAGE_SIZE)
{
if (!(paddr = virt_to_phys_040(addr)))
continue;
switch (cache)
{
case FLUSH_CACHE_DATA:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpushp %%dc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
case FLUSH_CACHE_INSN:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpushp %%ic,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
default:
case FLUSH_CACHE_BOTH:
__asm__ __volatile__ ("nop\n\t"
".chip 68040\n\t"
"cpushp %%bc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
}
}
break;
}
return 0;
}
#define virt_to_phys_060(vaddr) \
({ \
unsigned long paddr; \
__asm__ __volatile__ (".chip 68060\n\t" \
"plpar (%0)\n\t" \
".chip 68k" \
: "=a" (paddr) \
: "0" (vaddr)); \
(paddr); /* XXX */ \
})
static inline int
cache_flush_060 (unsigned long addr, int scope, int cache, unsigned long len)
{
unsigned long paddr, i;
/*
* 68060 manual says:
* cpush %dc : flush DC, remains valid (with our %cacr setup)
* cpush %ic : invalidate IC
* cpush %bc : flush DC + invalidate IC
*/
switch (scope)
{
case FLUSH_SCOPE_ALL:
switch (cache)
{
case FLUSH_CACHE_DATA:
__asm__ __volatile__ (".chip 68060\n\t"
"cpusha %dc\n\t"
".chip 68k");
break;
case FLUSH_CACHE_INSN:
__asm__ __volatile__ (".chip 68060\n\t"
"cpusha %ic\n\t"
".chip 68k");
break;
default:
case FLUSH_CACHE_BOTH:
__asm__ __volatile__ (".chip 68060\n\t"
"cpusha %bc\n\t"
".chip 68k");
break;
}
break;
case FLUSH_SCOPE_LINE:
/* Find the physical address of the first mapped page in the
address range. */
len += addr & 15;
addr &= -16;
if (!(paddr = virt_to_phys_060(addr))) {
unsigned long tmp = PAGE_SIZE - (addr & ~PAGE_MASK);
if (len <= tmp)
return 0;
addr += tmp;
len -= tmp;
tmp = PAGE_SIZE;
for (;;)
{
if ((paddr = virt_to_phys_060(addr)))
break;
if (len <= tmp)
return 0;
addr += tmp;
len -= tmp;
}
}
len = (len + 15) >> 4;
i = (PAGE_SIZE - (paddr & ~PAGE_MASK)) >> 4;
while (len--)
{
switch (cache)
{
case FLUSH_CACHE_DATA:
__asm__ __volatile__ (".chip 68060\n\t"
"cpushl %%dc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
case FLUSH_CACHE_INSN:
__asm__ __volatile__ (".chip 68060\n\t"
"cpushl %%ic,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
default:
case FLUSH_CACHE_BOTH:
__asm__ __volatile__ (".chip 68060\n\t"
"cpushl %%bc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
}
if (!--i && len)
{
/*
* We just want to jump to the first cache line
* in the next page.
*/
addr += PAGE_SIZE;
addr &= PAGE_MASK;
i = PAGE_SIZE / 16;
/* Recompute physical address when crossing a page
boundary. */
for (;;)
{
if ((paddr = virt_to_phys_060(addr)))
break;
if (len <= i)
return 0;
len -= i;
addr += PAGE_SIZE;
}
}
else
paddr += 16;
}
break;
default:
case FLUSH_SCOPE_PAGE:
len += (addr & ~PAGE_MASK) + (PAGE_SIZE - 1);
addr &= PAGE_MASK; /* Workaround for bug in some
revisions of the 68060 */
for (len >>= PAGE_SHIFT; len--; addr += PAGE_SIZE)
{
if (!(paddr = virt_to_phys_060(addr)))
continue;
switch (cache)
{
case FLUSH_CACHE_DATA:
__asm__ __volatile__ (".chip 68060\n\t"
"cpushp %%dc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
case FLUSH_CACHE_INSN:
__asm__ __volatile__ (".chip 68060\n\t"
"cpushp %%ic,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
default:
case FLUSH_CACHE_BOTH:
__asm__ __volatile__ (".chip 68060\n\t"
"cpushp %%bc,(%0)\n\t"
".chip 68k"
: : "a" (paddr));
break;
}
}
break;
}
return 0;
}
/* sys_cacheflush -- flush (part of) the processor cache. */
asmlinkage int
sys_cacheflush (unsigned long addr, int scope, int cache, unsigned long len)
{
struct vm_area_struct *vma;
int ret = -EINVAL;
if (scope < FLUSH_SCOPE_LINE || scope > FLUSH_SCOPE_ALL ||
cache & ~FLUSH_CACHE_BOTH)
goto out;
if (scope == FLUSH_SCOPE_ALL) {
/* Only the superuser may explicitly flush the whole cache. */
ret = -EPERM;
if (!capable(CAP_SYS_ADMIN))
goto out;
} else {
/*
* Verify that the specified address region actually belongs
* to this process.
*/
vma = find_vma (current->mm, addr);
ret = -EINVAL;
/* Check for overflow. */
if (addr + len < addr)
goto out;
if (vma == NULL || addr < vma->vm_start || addr + len > vma->vm_end)
goto out;
}
if (CPU_IS_020_OR_030) {
if (scope == FLUSH_SCOPE_LINE && len < 256) {
unsigned long cacr;
__asm__ ("movec %%cacr, %0" : "=r" (cacr));
if (cache & FLUSH_CACHE_INSN)
cacr |= 4;
if (cache & FLUSH_CACHE_DATA)
cacr |= 0x400;
len >>= 2;
while (len--) {
__asm__ __volatile__ ("movec %1, %%caar\n\t"
"movec %0, %%cacr"
: /* no outputs */
: "r" (cacr), "r" (addr));
addr += 4;
}
} else {
/* Flush the whole cache, even if page granularity requested. */
unsigned long cacr;
__asm__ ("movec %%cacr, %0" : "=r" (cacr));
if (cache & FLUSH_CACHE_INSN)
cacr |= 8;
if (cache & FLUSH_CACHE_DATA)
cacr |= 0x800;
__asm__ __volatile__ ("movec %0, %%cacr" : : "r" (cacr));
}
ret = 0;
goto out;
} else {
/*
* 040 or 060: don't blindly trust 'scope', someone could
* try to flush a few megs of memory.
*/
if (len>=3*PAGE_SIZE && scope<FLUSH_SCOPE_PAGE)
scope=FLUSH_SCOPE_PAGE;
if (len>=10*PAGE_SIZE && scope<FLUSH_SCOPE_ALL)
scope=FLUSH_SCOPE_ALL;
if (CPU_IS_040) {
ret = cache_flush_040 (addr, scope, cache, len);
} else if (CPU_IS_060) {
ret = cache_flush_060 (addr, scope, cache, len);
}
}
out:
return ret;
}
/* This syscall gets its arguments in A0 (mem), D2 (oldval) and
D1 (newval). */
asmlinkage int
sys_atomic_cmpxchg_32(unsigned long newval, int oldval, int d3, int d4, int d5,
unsigned long __user * mem)
{
/* This was borrowed from ARM's implementation. */
for (;;) {
struct mm_struct *mm = current->mm;
pgd_t *pgd;
pmd_t *pmd;
pte_t *pte;
spinlock_t *ptl;
unsigned long mem_value;
down_read(&mm->mmap_sem);
pgd = pgd_offset(mm, (unsigned long)mem);
if (!pgd_present(*pgd))
goto bad_access;
pmd = pmd_offset(pgd, (unsigned long)mem);
if (!pmd_present(*pmd))
goto bad_access;
pte = pte_offset_map_lock(mm, pmd, (unsigned long)mem, &ptl);
if (!pte_present(*pte) || !pte_dirty(*pte)
|| !pte_write(*pte)) {
pte_unmap_unlock(pte, ptl);
goto bad_access;
}
/*
* No need to check for EFAULT; we know that the page is
* present and writable.
*/
__get_user(mem_value, mem);
if (mem_value == oldval)
__put_user(newval, mem);
pte_unmap_unlock(pte, ptl);
up_read(&mm->mmap_sem);
return mem_value;
bad_access:
up_read(&mm->mmap_sem);
/* This is not necessarily a bad access, we can get here if
a memory we're trying to write to should be copied-on-write.
Make the kernel do the necessary page stuff, then re-iterate.
Simulate a write access fault to do that. */
{
/* The first argument of the function corresponds to
D1, which is the first field of struct pt_regs. */
struct pt_regs *fp = (struct pt_regs *)&newval;
/* '3' is an RMW flag. */
if (do_page_fault(fp, (unsigned long)mem, 3))
/* If the do_page_fault() failed, we don't
have anything meaningful to return.
There should be a SIGSEGV pending for
the process. */
return 0xdeadbeef;
}
}
}
#else
/* sys_cacheflush -- flush (part of) the processor cache. */
asmlinkage int
sys_cacheflush (unsigned long addr, int scope, int cache, unsigned long len)
{
flush_cache_all();
return 0;
}
/* This syscall gets its arguments in A0 (mem), D2 (oldval) and
D1 (newval). */
asmlinkage int
sys_atomic_cmpxchg_32(unsigned long newval, int oldval, int d3, int d4, int d5,
unsigned long __user * mem)
{
struct mm_struct *mm = current->mm;
unsigned long mem_value;
down_read(&mm->mmap_sem);
mem_value = *mem;
if (mem_value == oldval)
*mem = newval;
up_read(&mm->mmap_sem);
return mem_value;
}
#endif /* CONFIG_MMU */
asmlinkage int sys_getpagesize(void)
{
return PAGE_SIZE;
}
/*
* Do a system call from kernel instead of calling sys_execve so we
* end up with proper pt_regs.
*/
int kernel_execve(const char *filename,
const char *const argv[],
const char *const envp[])
{
register long __res asm ("%d0") = __NR_execve;
register long __a asm ("%d1") = (long)(filename);
register long __b asm ("%d2") = (long)(argv);
register long __c asm ("%d3") = (long)(envp);
asm volatile ("trap #0" : "+d" (__res)
: "d" (__a), "d" (__b), "d" (__c));
return __res;
}
asmlinkage unsigned long sys_get_thread_area(void)
{
return current_thread_info()->tp_value;
}
asmlinkage int sys_set_thread_area(unsigned long tp)
{
current_thread_info()->tp_value = tp;
return 0;
}
asmlinkage int sys_atomic_barrier(void)
{
/* no code needed for uniprocs */
return 0;
}
| gpl-2.0 |
jmztaylor/android_kernel_htc_a5dug | drivers/ide/ide-cs.c | 4814 | 12313 | /*======================================================================
A driver for PCMCIA IDE/ATA disk cards
The contents of this file are subject to the Mozilla Public
License Version 1.1 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS
IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
implied. See the License for the specific language governing
rights and limitations under the License.
The initial developer of the original code is David A. Hinds
<dahinds@users.sourceforge.net>. Portions created by David A. Hinds
are Copyright (C) 1999 David A. Hinds. All Rights Reserved.
Alternatively, the contents of this file may be used under the
terms of the GNU General Public License version 2 (the "GPL"), in
which case the provisions of the GPL are applicable instead of the
above. If you wish to allow the use of your version of this file
only under the terms of the GPL and not to allow others to use
your version of this file under the MPL, indicate your decision
by deleting the provisions above and replace them with the notice
and other provisions required by the GPL. If you do not delete
the provisions above, a recipient may use your version of this
file under either the MPL or the GPL.
======================================================================*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/ptrace.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/ioport.h>
#include <linux/ide.h>
#include <linux/major.h>
#include <linux/delay.h>
#include <asm/io.h>
#include <pcmcia/cistpl.h>
#include <pcmcia/ds.h>
#include <pcmcia/cisreg.h>
#include <pcmcia/ciscode.h>
#define DRV_NAME "ide-cs"
/*====================================================================*/
/* Module parameters */
MODULE_AUTHOR("David Hinds <dahinds@users.sourceforge.net>");
MODULE_DESCRIPTION("PCMCIA ATA/IDE card driver");
MODULE_LICENSE("Dual MPL/GPL");
/*====================================================================*/
typedef struct ide_info_t {
struct pcmcia_device *p_dev;
struct ide_host *host;
int ndev;
} ide_info_t;
static void ide_release(struct pcmcia_device *);
static int ide_config(struct pcmcia_device *);
static void ide_detach(struct pcmcia_device *p_dev);
static int ide_probe(struct pcmcia_device *link)
{
ide_info_t *info;
dev_dbg(&link->dev, "ide_attach()\n");
/* Create new ide device */
info = kzalloc(sizeof(*info), GFP_KERNEL);
if (!info)
return -ENOMEM;
info->p_dev = link;
link->priv = info;
link->config_flags |= CONF_ENABLE_IRQ | CONF_AUTO_SET_IO |
CONF_AUTO_SET_VPP | CONF_AUTO_CHECK_VCC;
return ide_config(link);
} /* ide_attach */
static void ide_detach(struct pcmcia_device *link)
{
ide_info_t *info = link->priv;
dev_dbg(&link->dev, "ide_detach(0x%p)\n", link);
ide_release(link);
kfree(info);
} /* ide_detach */
static const struct ide_port_ops idecs_port_ops = {
.quirkproc = ide_undecoded_slave,
};
static const struct ide_port_info idecs_port_info = {
.port_ops = &idecs_port_ops,
.host_flags = IDE_HFLAG_NO_DMA,
.irq_flags = IRQF_SHARED,
.chipset = ide_pci,
};
static struct ide_host *idecs_register(unsigned long io, unsigned long ctl,
unsigned long irq, struct pcmcia_device *handle)
{
struct ide_host *host;
ide_hwif_t *hwif;
int i, rc;
struct ide_hw hw, *hws[] = { &hw };
if (!request_region(io, 8, DRV_NAME)) {
printk(KERN_ERR "%s: I/O resource 0x%lX-0x%lX not free.\n",
DRV_NAME, io, io + 7);
return NULL;
}
if (!request_region(ctl, 1, DRV_NAME)) {
printk(KERN_ERR "%s: I/O resource 0x%lX not free.\n",
DRV_NAME, ctl);
release_region(io, 8);
return NULL;
}
memset(&hw, 0, sizeof(hw));
ide_std_init_ports(&hw, io, ctl);
hw.irq = irq;
hw.dev = &handle->dev;
rc = ide_host_add(&idecs_port_info, hws, 1, &host);
if (rc)
goto out_release;
hwif = host->ports[0];
if (hwif->present)
return host;
/* retry registration in case device is still spinning up */
for (i = 0; i < 10; i++) {
msleep(100);
ide_port_scan(hwif);
if (hwif->present)
return host;
}
return host;
out_release:
release_region(ctl, 1);
release_region(io, 8);
return NULL;
}
static int pcmcia_check_one_config(struct pcmcia_device *pdev, void *priv_data)
{
int *is_kme = priv_data;
if (!(pdev->resource[0]->flags & IO_DATA_PATH_WIDTH_8)) {
pdev->resource[0]->flags &= ~IO_DATA_PATH_WIDTH;
pdev->resource[0]->flags |= IO_DATA_PATH_WIDTH_AUTO;
}
pdev->resource[1]->flags &= ~IO_DATA_PATH_WIDTH;
pdev->resource[1]->flags |= IO_DATA_PATH_WIDTH_8;
if (pdev->resource[1]->end) {
pdev->resource[0]->end = 8;
pdev->resource[1]->end = (*is_kme) ? 2 : 1;
} else {
if (pdev->resource[0]->end < 16)
return -ENODEV;
}
return pcmcia_request_io(pdev);
}
static int ide_config(struct pcmcia_device *link)
{
ide_info_t *info = link->priv;
int ret = 0, is_kme = 0;
unsigned long io_base, ctl_base;
struct ide_host *host;
dev_dbg(&link->dev, "ide_config(0x%p)\n", link);
is_kme = ((link->manf_id == MANFID_KME) &&
((link->card_id == PRODID_KME_KXLC005_A) ||
(link->card_id == PRODID_KME_KXLC005_B)));
if (pcmcia_loop_config(link, pcmcia_check_one_config, &is_kme)) {
link->config_flags &= ~CONF_AUTO_CHECK_VCC;
if (pcmcia_loop_config(link, pcmcia_check_one_config, &is_kme))
goto failed; /* No suitable config found */
}
io_base = link->resource[0]->start;
if (link->resource[1]->end)
ctl_base = link->resource[1]->start;
else
ctl_base = link->resource[0]->start + 0x0e;
if (!link->irq)
goto failed;
ret = pcmcia_enable_device(link);
if (ret)
goto failed;
/* disable drive interrupts during IDE probe */
outb(0x02, ctl_base);
/* special setup for KXLC005 card */
if (is_kme)
outb(0x81, ctl_base+1);
host = idecs_register(io_base, ctl_base, link->irq, link);
if (host == NULL && resource_size(link->resource[0]) == 0x20) {
outb(0x02, ctl_base + 0x10);
host = idecs_register(io_base + 0x10, ctl_base + 0x10,
link->irq, link);
}
if (host == NULL)
goto failed;
info->ndev = 1;
info->host = host;
dev_info(&link->dev, "ide-cs: hd%c: Vpp = %d.%d\n",
'a' + host->ports[0]->index * 2,
link->vpp / 10, link->vpp % 10);
return 0;
failed:
ide_release(link);
return -ENODEV;
} /* ide_config */
static void ide_release(struct pcmcia_device *link)
{
ide_info_t *info = link->priv;
struct ide_host *host = info->host;
dev_dbg(&link->dev, "ide_release(0x%p)\n", link);
if (info->ndev) {
ide_hwif_t *hwif = host->ports[0];
unsigned long data_addr, ctl_addr;
data_addr = hwif->io_ports.data_addr;
ctl_addr = hwif->io_ports.ctl_addr;
ide_host_remove(host);
info->ndev = 0;
release_region(ctl_addr, 1);
release_region(data_addr, 8);
}
pcmcia_disable_device(link);
} /* ide_release */
static const struct pcmcia_device_id ide_ids[] = {
PCMCIA_DEVICE_FUNC_ID(4),
PCMCIA_DEVICE_MANF_CARD(0x0000, 0x0000), /* Corsair */
PCMCIA_DEVICE_MANF_CARD(0x0007, 0x0000), /* Hitachi */
PCMCIA_DEVICE_MANF_CARD(0x000a, 0x0000), /* I-O Data CFA */
PCMCIA_DEVICE_MANF_CARD(0x001c, 0x0001), /* Mitsubishi CFA */
PCMCIA_DEVICE_MANF_CARD(0x0032, 0x0704),
PCMCIA_DEVICE_MANF_CARD(0x0032, 0x2904),
PCMCIA_DEVICE_MANF_CARD(0x0045, 0x0401), /* SanDisk CFA */
PCMCIA_DEVICE_MANF_CARD(0x004f, 0x0000), /* Kingston */
PCMCIA_DEVICE_MANF_CARD(0x0097, 0x1620), /* TI emulated */
PCMCIA_DEVICE_MANF_CARD(0x0098, 0x0000), /* Toshiba */
PCMCIA_DEVICE_MANF_CARD(0x00a4, 0x002d),
PCMCIA_DEVICE_MANF_CARD(0x00ce, 0x0000), /* Samsung */
PCMCIA_DEVICE_MANF_CARD(0x0319, 0x0000), /* Hitachi */
PCMCIA_DEVICE_MANF_CARD(0x2080, 0x0001),
PCMCIA_DEVICE_MANF_CARD(0x4e01, 0x0100), /* Viking CFA */
PCMCIA_DEVICE_MANF_CARD(0x4e01, 0x0200), /* Lexar, Viking CFA */
PCMCIA_DEVICE_PROD_ID123("Caravelle", "PSC-IDE ", "PSC000", 0x8c36137c, 0xd0693ab8, 0x2768a9f0),
PCMCIA_DEVICE_PROD_ID123("CDROM", "IDE", "MCD-601p", 0x1b9179ca, 0xede88951, 0x0d902f74),
PCMCIA_DEVICE_PROD_ID123("PCMCIA", "IDE CARD", "F1", 0x281f1c5d, 0x1907960c, 0xf7fde8b9),
PCMCIA_DEVICE_PROD_ID12("ARGOSY", "CD-ROM", 0x78f308dc, 0x66536591),
PCMCIA_DEVICE_PROD_ID12("ARGOSY", "PnPIDE", 0x78f308dc, 0x0c694728),
PCMCIA_DEVICE_PROD_ID12("CNF ", "CD-ROM", 0x46d7db81, 0x66536591),
PCMCIA_DEVICE_PROD_ID12("CNF CD-M", "CD-ROM", 0x7d93b852, 0x66536591),
PCMCIA_DEVICE_PROD_ID12("Creative Technology Ltd.", "PCMCIA CD-ROM Interface Card", 0xff8c8a45, 0xfe8020c4),
PCMCIA_DEVICE_PROD_ID12("Digital Equipment Corporation.", "Digital Mobile Media CD-ROM", 0x17692a66, 0xef1dcbde),
PCMCIA_DEVICE_PROD_ID12("EXP", "CD+GAME", 0x6f58c983, 0x63c13aaf),
PCMCIA_DEVICE_PROD_ID12("EXP ", "CD-ROM", 0x0a5c52fd, 0x66536591),
PCMCIA_DEVICE_PROD_ID12("EXP ", "PnPIDE", 0x0a5c52fd, 0x0c694728),
PCMCIA_DEVICE_PROD_ID12("FREECOM", "PCCARD-IDE", 0x5714cbf7, 0x48e0ab8e),
PCMCIA_DEVICE_PROD_ID12("HITACHI", "FLASH", 0xf4f43949, 0x9eb86aae),
PCMCIA_DEVICE_PROD_ID12("HITACHI", "microdrive", 0xf4f43949, 0xa6d76178),
PCMCIA_DEVICE_PROD_ID12("Hyperstone", "Model1", 0x3d5b9ef5, 0xca6ab420),
PCMCIA_DEVICE_PROD_ID12("IBM", "microdrive", 0xb569a6e5, 0xa6d76178),
PCMCIA_DEVICE_PROD_ID12("IBM", "IBM17JSSFP20", 0xb569a6e5, 0xf2508753),
PCMCIA_DEVICE_PROD_ID12("KINGSTON", "CF CARD 1GB", 0x2e6d1829, 0x55d5bffb),
PCMCIA_DEVICE_PROD_ID12("KINGSTON", "CF CARD 4GB", 0x2e6d1829, 0x531e7d10),
PCMCIA_DEVICE_PROD_ID12("KINGSTON", "CF8GB", 0x2e6d1829, 0xacbe682e),
PCMCIA_DEVICE_PROD_ID12("IO DATA", "CBIDE2 ", 0x547e66dc, 0x8671043b),
PCMCIA_DEVICE_PROD_ID12("IO DATA", "PCIDE", 0x547e66dc, 0x5c5ab149),
PCMCIA_DEVICE_PROD_ID12("IO DATA", "PCIDEII", 0x547e66dc, 0xb3662674),
PCMCIA_DEVICE_PROD_ID12("LOOKMEET", "CBIDE2 ", 0xe37be2b5, 0x8671043b),
PCMCIA_DEVICE_PROD_ID12("M-Systems", "CF300", 0x7ed2ad87, 0x7e9e78ee),
PCMCIA_DEVICE_PROD_ID12("M-Systems", "CF500", 0x7ed2ad87, 0x7a13045c),
PCMCIA_DEVICE_PROD_ID2("NinjaATA-", 0xebe0bd79),
PCMCIA_DEVICE_PROD_ID12("PCMCIA", "CD-ROM", 0x281f1c5d, 0x66536591),
PCMCIA_DEVICE_PROD_ID12("PCMCIA", "PnPIDE", 0x281f1c5d, 0x0c694728),
PCMCIA_DEVICE_PROD_ID12("SHUTTLE TECHNOLOGY LTD.", "PCCARD-IDE/ATAPI Adapter", 0x4a3f0ba0, 0x322560e1),
PCMCIA_DEVICE_PROD_ID12("SEAGATE", "ST1", 0x87c1b330, 0xe1f30883),
PCMCIA_DEVICE_PROD_ID12("SAMSUNG", "04/05/06", 0x43d74cb4, 0x6a22777d),
PCMCIA_DEVICE_PROD_ID12("SMI VENDOR", "SMI PRODUCT", 0x30896c92, 0x703cc5f6),
PCMCIA_DEVICE_PROD_ID12("TOSHIBA", "MK2001MPL", 0xb4585a1a, 0x3489e003),
PCMCIA_DEVICE_PROD_ID1("TRANSCEND 512M ", 0xd0909443),
PCMCIA_DEVICE_PROD_ID12("TRANSCEND", "TS1GCF45", 0x709b1bf1, 0xf68b6f32),
PCMCIA_DEVICE_PROD_ID12("TRANSCEND", "TS1GCF80", 0x709b1bf1, 0x2a54d4b1),
PCMCIA_DEVICE_PROD_ID12("TRANSCEND", "TS2GCF120", 0x709b1bf1, 0x969aa4f2),
PCMCIA_DEVICE_PROD_ID12("TRANSCEND", "TS4GCF120", 0x709b1bf1, 0xf54a91c8),
PCMCIA_DEVICE_PROD_ID12("TRANSCEND", "TS4GCF133", 0x709b1bf1, 0x7558f133),
PCMCIA_DEVICE_PROD_ID12("TRANSCEND", "TS8GCF133", 0x709b1bf1, 0xb2f89b47),
PCMCIA_DEVICE_PROD_ID12("WIT", "IDE16", 0x244e5994, 0x3e232852),
PCMCIA_DEVICE_PROD_ID12("WEIDA", "TWTTI", 0xcc7cf69c, 0x212bb918),
PCMCIA_DEVICE_PROD_ID1("STI Flash", 0xe4a13209),
PCMCIA_DEVICE_PROD_ID12("STI", "Flash 5.0", 0xbf2df18d, 0x8cb57a0e),
PCMCIA_MFC_DEVICE_PROD_ID12(1, "SanDisk", "ConnectPlus", 0x7a954bd9, 0x74be00c6),
PCMCIA_DEVICE_PROD_ID2("Flash Card", 0x5a362506),
PCMCIA_DEVICE_NULL,
};
MODULE_DEVICE_TABLE(pcmcia, ide_ids);
static struct pcmcia_driver ide_cs_driver = {
.owner = THIS_MODULE,
.name = "ide-cs",
.probe = ide_probe,
.remove = ide_detach,
.id_table = ide_ids,
};
static int __init init_ide_cs(void)
{
return pcmcia_register_driver(&ide_cs_driver);
}
static void __exit exit_ide_cs(void)
{
pcmcia_unregister_driver(&ide_cs_driver);
}
late_initcall(init_ide_cs);
module_exit(exit_ide_cs);
| gpl-2.0 |
h8rift/android_kernel_htc_msm8930 | drivers/media/video/w9966.c | 4814 | 25224 | /*
Winbond w9966cf Webcam parport driver.
Version 0.33
Copyright (C) 2001 Jakob Kemi <jakob.kemi@post.utfors.se>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
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.
*/
/*
Supported devices:
*Lifeview FlyCam Supra (using the Philips saa7111a chip)
Does any other model using the w9966 interface chip exist ?
Todo:
*Add a working EPP mode, since DMA ECP read isn't implemented
in the parport drivers. (That's why it's so sloow)
*Add support for other ccd-control chips than the saa7111
please send me feedback on what kind of chips you have.
*Add proper probing. I don't know what's wrong with the IEEE1284
parport drivers but (IEEE1284_MODE_NIBBLE|IEEE1284_DEVICE_ID)
and nibble read seems to be broken for some peripherals.
*Add probing for onboard SRAM, port directions etc. (if possible)
*Add support for the hardware compressed modes (maybe using v4l2)
*Fix better support for the capture window (no skewed images, v4l
interface to capt. window)
*Probably some bugs that I don't know of
Please support me by sending feedback!
Changes:
Alan Cox: Removed RGB mode for kernel merge, added THIS_MODULE
and owner support for newer module locks
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/videodev2.h>
#include <linux/slab.h>
#include <media/v4l2-common.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-device.h>
#include <linux/parport.h>
/*#define DEBUG*/ /* Undef me for production */
#ifdef DEBUG
#define DPRINTF(x, a...) printk(KERN_DEBUG "W9966: %s(): "x, __func__ , ##a)
#else
#define DPRINTF(x...)
#endif
/*
* Defines, simple typedefs etc.
*/
#define W9966_DRIVERNAME "W9966CF Webcam"
#define W9966_MAXCAMS 4 /* Maximum number of cameras */
#define W9966_RBUFFER 2048 /* Read buffer (must be an even number) */
#define W9966_SRAMSIZE 131072 /* 128kb */
#define W9966_SRAMID 0x02 /* check w9966cf.pdf */
/* Empirically determined window limits */
#define W9966_WND_MIN_X 16
#define W9966_WND_MIN_Y 14
#define W9966_WND_MAX_X 705
#define W9966_WND_MAX_Y 253
#define W9966_WND_MAX_W (W9966_WND_MAX_X - W9966_WND_MIN_X)
#define W9966_WND_MAX_H (W9966_WND_MAX_Y - W9966_WND_MIN_Y)
/* Keep track of our current state */
#define W9966_STATE_PDEV 0x01
#define W9966_STATE_CLAIMED 0x02
#define W9966_STATE_VDEV 0x04
#define W9966_I2C_W_ID 0x48
#define W9966_I2C_R_ID 0x49
#define W9966_I2C_R_DATA 0x08
#define W9966_I2C_R_CLOCK 0x04
#define W9966_I2C_W_DATA 0x02
#define W9966_I2C_W_CLOCK 0x01
struct w9966 {
struct v4l2_device v4l2_dev;
unsigned char dev_state;
unsigned char i2c_state;
unsigned short ppmode;
struct parport *pport;
struct pardevice *pdev;
struct video_device vdev;
unsigned short width;
unsigned short height;
unsigned char brightness;
signed char contrast;
signed char color;
signed char hue;
struct mutex lock;
};
/*
* Module specific properties
*/
MODULE_AUTHOR("Jakob Kemi <jakob.kemi@post.utfors.se>");
MODULE_DESCRIPTION("Winbond w9966cf WebCam driver (0.32)");
MODULE_LICENSE("GPL");
MODULE_VERSION("0.33.1");
#ifdef MODULE
static char *pardev[] = {[0 ... W9966_MAXCAMS] = ""};
#else
static char *pardev[] = {[0 ... W9966_MAXCAMS] = "aggressive"};
#endif
module_param_array(pardev, charp, NULL, 0);
MODULE_PARM_DESC(pardev, "pardev: where to search for\n"
"\teach camera. 'aggressive' means brute-force search.\n"
"\tEg: >pardev=parport3,aggressive,parport2,parport1< would assign\n"
"\tcam 1 to parport3 and search every parport for cam 2 etc...");
static int parmode;
module_param(parmode, int, 0);
MODULE_PARM_DESC(parmode, "parmode: transfer mode (0=auto, 1=ecp, 2=epp");
static int video_nr = -1;
module_param(video_nr, int, 0);
static struct w9966 w9966_cams[W9966_MAXCAMS];
/*
* Private function defines
*/
/* Set camera phase flags, so we know what to uninit when terminating */
static inline void w9966_set_state(struct w9966 *cam, int mask, int val)
{
cam->dev_state = (cam->dev_state & ~mask) ^ val;
}
/* Get camera phase flags */
static inline int w9966_get_state(struct w9966 *cam, int mask, int val)
{
return ((cam->dev_state & mask) == val);
}
/* Claim parport for ourself */
static void w9966_pdev_claim(struct w9966 *cam)
{
if (w9966_get_state(cam, W9966_STATE_CLAIMED, W9966_STATE_CLAIMED))
return;
parport_claim_or_block(cam->pdev);
w9966_set_state(cam, W9966_STATE_CLAIMED, W9966_STATE_CLAIMED);
}
/* Release parport for others to use */
static void w9966_pdev_release(struct w9966 *cam)
{
if (w9966_get_state(cam, W9966_STATE_CLAIMED, 0))
return;
parport_release(cam->pdev);
w9966_set_state(cam, W9966_STATE_CLAIMED, 0);
}
/* Read register from W9966 interface-chip
Expects a claimed pdev
-1 on error, else register data (byte) */
static int w9966_read_reg(struct w9966 *cam, int reg)
{
/* ECP, read, regtransfer, REG, REG, REG, REG, REG */
const unsigned char addr = 0x80 | (reg & 0x1f);
unsigned char val;
if (parport_negotiate(cam->pport, cam->ppmode | IEEE1284_ADDR) != 0)
return -1;
if (parport_write(cam->pport, &addr, 1) != 1)
return -1;
if (parport_negotiate(cam->pport, cam->ppmode | IEEE1284_DATA) != 0)
return -1;
if (parport_read(cam->pport, &val, 1) != 1)
return -1;
return val;
}
/* Write register to W9966 interface-chip
Expects a claimed pdev
-1 on error */
static int w9966_write_reg(struct w9966 *cam, int reg, int data)
{
/* ECP, write, regtransfer, REG, REG, REG, REG, REG */
const unsigned char addr = 0xc0 | (reg & 0x1f);
const unsigned char val = data;
if (parport_negotiate(cam->pport, cam->ppmode | IEEE1284_ADDR) != 0)
return -1;
if (parport_write(cam->pport, &addr, 1) != 1)
return -1;
if (parport_negotiate(cam->pport, cam->ppmode | IEEE1284_DATA) != 0)
return -1;
if (parport_write(cam->pport, &val, 1) != 1)
return -1;
return 0;
}
/*
* Ugly and primitive i2c protocol functions
*/
/* Sets the data line on the i2c bus.
Expects a claimed pdev. */
static void w9966_i2c_setsda(struct w9966 *cam, int state)
{
if (state)
cam->i2c_state |= W9966_I2C_W_DATA;
else
cam->i2c_state &= ~W9966_I2C_W_DATA;
w9966_write_reg(cam, 0x18, cam->i2c_state);
udelay(5);
}
/* Get peripheral clock line
Expects a claimed pdev. */
static int w9966_i2c_getscl(struct w9966 *cam)
{
const unsigned char state = w9966_read_reg(cam, 0x18);
return ((state & W9966_I2C_R_CLOCK) > 0);
}
/* Sets the clock line on the i2c bus.
Expects a claimed pdev. -1 on error */
static int w9966_i2c_setscl(struct w9966 *cam, int state)
{
unsigned long timeout;
if (state)
cam->i2c_state |= W9966_I2C_W_CLOCK;
else
cam->i2c_state &= ~W9966_I2C_W_CLOCK;
w9966_write_reg(cam, 0x18, cam->i2c_state);
udelay(5);
/* we go to high, we also expect the peripheral to ack. */
if (state) {
timeout = jiffies + 100;
while (!w9966_i2c_getscl(cam)) {
if (time_after(jiffies, timeout))
return -1;
}
}
return 0;
}
#if 0
/* Get peripheral data line
Expects a claimed pdev. */
static int w9966_i2c_getsda(struct w9966 *cam)
{
const unsigned char state = w9966_read_reg(cam, 0x18);
return ((state & W9966_I2C_R_DATA) > 0);
}
#endif
/* Write a byte with ack to the i2c bus.
Expects a claimed pdev. -1 on error */
static int w9966_i2c_wbyte(struct w9966 *cam, int data)
{
int i;
for (i = 7; i >= 0; i--) {
w9966_i2c_setsda(cam, (data >> i) & 0x01);
if (w9966_i2c_setscl(cam, 1) == -1)
return -1;
w9966_i2c_setscl(cam, 0);
}
w9966_i2c_setsda(cam, 1);
if (w9966_i2c_setscl(cam, 1) == -1)
return -1;
w9966_i2c_setscl(cam, 0);
return 0;
}
/* Read a data byte with ack from the i2c-bus
Expects a claimed pdev. -1 on error */
#if 0
static int w9966_i2c_rbyte(struct w9966 *cam)
{
unsigned char data = 0x00;
int i;
w9966_i2c_setsda(cam, 1);
for (i = 0; i < 8; i++) {
if (w9966_i2c_setscl(cam, 1) == -1)
return -1;
data = data << 1;
if (w9966_i2c_getsda(cam))
data |= 0x01;
w9966_i2c_setscl(cam, 0);
}
return data;
}
#endif
/* Read a register from the i2c device.
Expects claimed pdev. -1 on error */
#if 0
static int w9966_read_reg_i2c(struct w9966 *cam, int reg)
{
int data;
w9966_i2c_setsda(cam, 0);
w9966_i2c_setscl(cam, 0);
if (w9966_i2c_wbyte(cam, W9966_I2C_W_ID) == -1 ||
w9966_i2c_wbyte(cam, reg) == -1)
return -1;
w9966_i2c_setsda(cam, 1);
if (w9966_i2c_setscl(cam, 1) == -1)
return -1;
w9966_i2c_setsda(cam, 0);
w9966_i2c_setscl(cam, 0);
if (w9966_i2c_wbyte(cam, W9966_I2C_R_ID) == -1)
return -1;
data = w9966_i2c_rbyte(cam);
if (data == -1)
return -1;
w9966_i2c_setsda(cam, 0);
if (w9966_i2c_setscl(cam, 1) == -1)
return -1;
w9966_i2c_setsda(cam, 1);
return data;
}
#endif
/* Write a register to the i2c device.
Expects claimed pdev. -1 on error */
static int w9966_write_reg_i2c(struct w9966 *cam, int reg, int data)
{
w9966_i2c_setsda(cam, 0);
w9966_i2c_setscl(cam, 0);
if (w9966_i2c_wbyte(cam, W9966_I2C_W_ID) == -1 ||
w9966_i2c_wbyte(cam, reg) == -1 ||
w9966_i2c_wbyte(cam, data) == -1)
return -1;
w9966_i2c_setsda(cam, 0);
if (w9966_i2c_setscl(cam, 1) == -1)
return -1;
w9966_i2c_setsda(cam, 1);
return 0;
}
/* Find a good length for capture window (used both for W and H)
A bit ugly but pretty functional. The capture length
have to match the downscale */
static int w9966_findlen(int near, int size, int maxlen)
{
int bestlen = size;
int besterr = abs(near - bestlen);
int len;
for (len = size + 1; len < maxlen; len++) {
int err;
if (((64 * size) % len) != 0)
continue;
err = abs(near - len);
/* Only continue as long as we keep getting better values */
if (err > besterr)
break;
besterr = err;
bestlen = len;
}
return bestlen;
}
/* Modify capture window (if necessary)
and calculate downscaling
Return -1 on error */
static int w9966_calcscale(int size, int min, int max, int *beg, int *end, unsigned char *factor)
{
int maxlen = max - min;
int len = *end - *beg + 1;
int newlen = w9966_findlen(len, size, maxlen);
int err = newlen - len;
/* Check for bad format */
if (newlen > maxlen || newlen < size)
return -1;
/* Set factor (6 bit fixed) */
*factor = (64 * size) / newlen;
if (*factor == 64)
*factor = 0x00; /* downscale is disabled */
else
*factor |= 0x80; /* set downscale-enable bit */
/* Modify old beginning and end */
*beg -= err / 2;
*end += err - (err / 2);
/* Move window if outside borders */
if (*beg < min) {
*end += min - *beg;
*beg += min - *beg;
}
if (*end > max) {
*beg -= *end - max;
*end -= *end - max;
}
return 0;
}
/* Setup the cameras capture window etc.
Expects a claimed pdev
return -1 on error */
static int w9966_setup(struct w9966 *cam, int x1, int y1, int x2, int y2, int w, int h)
{
unsigned int i;
unsigned int enh_s, enh_e;
unsigned char scale_x, scale_y;
unsigned char regs[0x1c];
unsigned char saa7111_regs[] = {
0x21, 0x00, 0xd8, 0x23, 0x00, 0x80, 0x80, 0x00,
0x88, 0x10, 0x80, 0x40, 0x40, 0x00, 0x01, 0x00,
0x48, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x71, 0xe7, 0x00, 0x00, 0xc0
};
if (w * h * 2 > W9966_SRAMSIZE) {
DPRINTF("capture window exceeds SRAM size!.\n");
w = 200; h = 160; /* Pick default values */
}
w &= ~0x1;
if (w < 2)
w = 2;
if (h < 1)
h = 1;
if (w > W9966_WND_MAX_W)
w = W9966_WND_MAX_W;
if (h > W9966_WND_MAX_H)
h = W9966_WND_MAX_H;
cam->width = w;
cam->height = h;
enh_s = 0;
enh_e = w * h * 2;
/* Modify capture window if necessary and calculate downscaling */
if (w9966_calcscale(w, W9966_WND_MIN_X, W9966_WND_MAX_X, &x1, &x2, &scale_x) != 0 ||
w9966_calcscale(h, W9966_WND_MIN_Y, W9966_WND_MAX_Y, &y1, &y2, &scale_y) != 0)
return -1;
DPRINTF("%dx%d, x: %d<->%d, y: %d<->%d, sx: %d/64, sy: %d/64.\n",
w, h, x1, x2, y1, y2, scale_x & ~0x80, scale_y & ~0x80);
/* Setup registers */
regs[0x00] = 0x00; /* Set normal operation */
regs[0x01] = 0x18; /* Capture mode */
regs[0x02] = scale_y; /* V-scaling */
regs[0x03] = scale_x; /* H-scaling */
/* Capture window */
regs[0x04] = (x1 & 0x0ff); /* X-start (8 low bits) */
regs[0x05] = (x1 & 0x300)>>8; /* X-start (2 high bits) */
regs[0x06] = (y1 & 0x0ff); /* Y-start (8 low bits) */
regs[0x07] = (y1 & 0x300)>>8; /* Y-start (2 high bits) */
regs[0x08] = (x2 & 0x0ff); /* X-end (8 low bits) */
regs[0x09] = (x2 & 0x300)>>8; /* X-end (2 high bits) */
regs[0x0a] = (y2 & 0x0ff); /* Y-end (8 low bits) */
regs[0x0c] = W9966_SRAMID; /* SRAM-banks (1x 128kb) */
/* Enhancement layer */
regs[0x0d] = (enh_s & 0x000ff); /* Enh. start (0-7) */
regs[0x0e] = (enh_s & 0x0ff00) >> 8; /* Enh. start (8-15) */
regs[0x0f] = (enh_s & 0x70000) >> 16; /* Enh. start (16-17/18??) */
regs[0x10] = (enh_e & 0x000ff); /* Enh. end (0-7) */
regs[0x11] = (enh_e & 0x0ff00) >> 8; /* Enh. end (8-15) */
regs[0x12] = (enh_e & 0x70000) >> 16; /* Enh. end (16-17/18??) */
/* Misc */
regs[0x13] = 0x40; /* VEE control (raw 4:2:2) */
regs[0x17] = 0x00; /* ??? */
regs[0x18] = cam->i2c_state = 0x00; /* Serial bus */
regs[0x19] = 0xff; /* I/O port direction control */
regs[0x1a] = 0xff; /* I/O port data register */
regs[0x1b] = 0x10; /* ??? */
/* SAA7111 chip settings */
saa7111_regs[0x0a] = cam->brightness;
saa7111_regs[0x0b] = cam->contrast;
saa7111_regs[0x0c] = cam->color;
saa7111_regs[0x0d] = cam->hue;
/* Reset (ECP-fifo & serial-bus) */
if (w9966_write_reg(cam, 0x00, 0x03) == -1)
return -1;
/* Write regs to w9966cf chip */
for (i = 0; i < 0x1c; i++)
if (w9966_write_reg(cam, i, regs[i]) == -1)
return -1;
/* Write regs to saa7111 chip */
for (i = 0; i < 0x20; i++)
if (w9966_write_reg_i2c(cam, i, saa7111_regs[i]) == -1)
return -1;
return 0;
}
/*
* Video4linux interfacing
*/
static int cam_querycap(struct file *file, void *priv,
struct v4l2_capability *vcap)
{
struct w9966 *cam = video_drvdata(file);
strlcpy(vcap->driver, cam->v4l2_dev.name, sizeof(vcap->driver));
strlcpy(vcap->card, W9966_DRIVERNAME, sizeof(vcap->card));
strlcpy(vcap->bus_info, "parport", sizeof(vcap->bus_info));
vcap->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_READWRITE;
return 0;
}
static int cam_enum_input(struct file *file, void *fh, struct v4l2_input *vin)
{
if (vin->index > 0)
return -EINVAL;
strlcpy(vin->name, "Camera", sizeof(vin->name));
vin->type = V4L2_INPUT_TYPE_CAMERA;
vin->audioset = 0;
vin->tuner = 0;
vin->std = 0;
vin->status = 0;
return 0;
}
static int cam_g_input(struct file *file, void *fh, unsigned int *inp)
{
*inp = 0;
return 0;
}
static int cam_s_input(struct file *file, void *fh, unsigned int inp)
{
return (inp > 0) ? -EINVAL : 0;
}
static int cam_queryctrl(struct file *file, void *priv,
struct v4l2_queryctrl *qc)
{
switch (qc->id) {
case V4L2_CID_BRIGHTNESS:
return v4l2_ctrl_query_fill(qc, 0, 255, 1, 128);
case V4L2_CID_CONTRAST:
return v4l2_ctrl_query_fill(qc, -64, 64, 1, 64);
case V4L2_CID_SATURATION:
return v4l2_ctrl_query_fill(qc, -64, 64, 1, 64);
case V4L2_CID_HUE:
return v4l2_ctrl_query_fill(qc, -128, 127, 1, 0);
}
return -EINVAL;
}
static int cam_g_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct w9966 *cam = video_drvdata(file);
int ret = 0;
switch (ctrl->id) {
case V4L2_CID_BRIGHTNESS:
ctrl->value = cam->brightness;
break;
case V4L2_CID_CONTRAST:
ctrl->value = cam->contrast;
break;
case V4L2_CID_SATURATION:
ctrl->value = cam->color;
break;
case V4L2_CID_HUE:
ctrl->value = cam->hue;
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
static int cam_s_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct w9966 *cam = video_drvdata(file);
int ret = 0;
mutex_lock(&cam->lock);
switch (ctrl->id) {
case V4L2_CID_BRIGHTNESS:
cam->brightness = ctrl->value;
break;
case V4L2_CID_CONTRAST:
cam->contrast = ctrl->value;
break;
case V4L2_CID_SATURATION:
cam->color = ctrl->value;
break;
case V4L2_CID_HUE:
cam->hue = ctrl->value;
break;
default:
ret = -EINVAL;
break;
}
if (ret == 0) {
w9966_pdev_claim(cam);
if (w9966_write_reg_i2c(cam, 0x0a, cam->brightness) == -1 ||
w9966_write_reg_i2c(cam, 0x0b, cam->contrast) == -1 ||
w9966_write_reg_i2c(cam, 0x0c, cam->color) == -1 ||
w9966_write_reg_i2c(cam, 0x0d, cam->hue) == -1) {
ret = -EIO;
}
w9966_pdev_release(cam);
}
mutex_unlock(&cam->lock);
return ret;
}
static int cam_g_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct w9966 *cam = video_drvdata(file);
struct v4l2_pix_format *pix = &fmt->fmt.pix;
pix->width = cam->width;
pix->height = cam->height;
pix->pixelformat = V4L2_PIX_FMT_YUYV;
pix->field = V4L2_FIELD_NONE;
pix->bytesperline = 2 * cam->width;
pix->sizeimage = 2 * cam->width * cam->height;
/* Just a guess */
pix->colorspace = V4L2_COLORSPACE_SMPTE170M;
return 0;
}
static int cam_try_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct v4l2_pix_format *pix = &fmt->fmt.pix;
if (pix->width < 2)
pix->width = 2;
if (pix->height < 1)
pix->height = 1;
if (pix->width > W9966_WND_MAX_W)
pix->width = W9966_WND_MAX_W;
if (pix->height > W9966_WND_MAX_H)
pix->height = W9966_WND_MAX_H;
pix->pixelformat = V4L2_PIX_FMT_YUYV;
pix->field = V4L2_FIELD_NONE;
pix->bytesperline = 2 * pix->width;
pix->sizeimage = 2 * pix->width * pix->height;
/* Just a guess */
pix->colorspace = V4L2_COLORSPACE_SMPTE170M;
return 0;
}
static int cam_s_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct w9966 *cam = video_drvdata(file);
struct v4l2_pix_format *pix = &fmt->fmt.pix;
int ret = cam_try_fmt_vid_cap(file, fh, fmt);
if (ret)
return ret;
mutex_lock(&cam->lock);
/* Update camera regs */
w9966_pdev_claim(cam);
ret = w9966_setup(cam, 0, 0, 1023, 1023, pix->width, pix->height);
w9966_pdev_release(cam);
mutex_unlock(&cam->lock);
return ret;
}
static int cam_enum_fmt_vid_cap(struct file *file, void *fh, struct v4l2_fmtdesc *fmt)
{
static struct v4l2_fmtdesc formats[] = {
{ 0, 0, 0,
"YUV 4:2:2", V4L2_PIX_FMT_YUYV,
{ 0, 0, 0, 0 }
},
};
enum v4l2_buf_type type = fmt->type;
if (fmt->index > 0)
return -EINVAL;
*fmt = formats[fmt->index];
fmt->type = type;
return 0;
}
/* Capture data */
static ssize_t w9966_v4l_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct w9966 *cam = video_drvdata(file);
unsigned char addr = 0xa0; /* ECP, read, CCD-transfer, 00000 */
unsigned char __user *dest = (unsigned char __user *)buf;
unsigned long dleft = count;
unsigned char *tbuf;
/* Why would anyone want more than this?? */
if (count > cam->width * cam->height * 2)
return -EINVAL;
mutex_lock(&cam->lock);
w9966_pdev_claim(cam);
w9966_write_reg(cam, 0x00, 0x02); /* Reset ECP-FIFO buffer */
w9966_write_reg(cam, 0x00, 0x00); /* Return to normal operation */
w9966_write_reg(cam, 0x01, 0x98); /* Enable capture */
/* write special capture-addr and negotiate into data transfer */
if ((parport_negotiate(cam->pport, cam->ppmode|IEEE1284_ADDR) != 0) ||
(parport_write(cam->pport, &addr, 1) != 1) ||
(parport_negotiate(cam->pport, cam->ppmode|IEEE1284_DATA) != 0)) {
w9966_pdev_release(cam);
mutex_unlock(&cam->lock);
return -EFAULT;
}
tbuf = kmalloc(W9966_RBUFFER, GFP_KERNEL);
if (tbuf == NULL) {
count = -ENOMEM;
goto out;
}
while (dleft > 0) {
unsigned long tsize = (dleft > W9966_RBUFFER) ? W9966_RBUFFER : dleft;
if (parport_read(cam->pport, tbuf, tsize) < tsize) {
count = -EFAULT;
goto out;
}
if (copy_to_user(dest, tbuf, tsize) != 0) {
count = -EFAULT;
goto out;
}
dest += tsize;
dleft -= tsize;
}
w9966_write_reg(cam, 0x01, 0x18); /* Disable capture */
out:
kfree(tbuf);
w9966_pdev_release(cam);
mutex_unlock(&cam->lock);
return count;
}
static const struct v4l2_file_operations w9966_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = video_ioctl2,
.read = w9966_v4l_read,
};
static const struct v4l2_ioctl_ops w9966_ioctl_ops = {
.vidioc_querycap = cam_querycap,
.vidioc_g_input = cam_g_input,
.vidioc_s_input = cam_s_input,
.vidioc_enum_input = cam_enum_input,
.vidioc_queryctrl = cam_queryctrl,
.vidioc_g_ctrl = cam_g_ctrl,
.vidioc_s_ctrl = cam_s_ctrl,
.vidioc_enum_fmt_vid_cap = cam_enum_fmt_vid_cap,
.vidioc_g_fmt_vid_cap = cam_g_fmt_vid_cap,
.vidioc_s_fmt_vid_cap = cam_s_fmt_vid_cap,
.vidioc_try_fmt_vid_cap = cam_try_fmt_vid_cap,
};
/* Initialize camera device. Setup all internal flags, set a
default video mode, setup ccd-chip, register v4l device etc..
Also used for 'probing' of hardware.
-1 on error */
static int w9966_init(struct w9966 *cam, struct parport *port)
{
struct v4l2_device *v4l2_dev = &cam->v4l2_dev;
if (cam->dev_state != 0)
return -1;
strlcpy(v4l2_dev->name, "w9966", sizeof(v4l2_dev->name));
if (v4l2_device_register(NULL, v4l2_dev) < 0) {
v4l2_err(v4l2_dev, "Could not register v4l2_device\n");
return -1;
}
cam->pport = port;
cam->brightness = 128;
cam->contrast = 64;
cam->color = 64;
cam->hue = 0;
/* Select requested transfer mode */
switch (parmode) {
default: /* Auto-detect (priority: hw-ecp, hw-epp, sw-ecp) */
case 0:
if (port->modes & PARPORT_MODE_ECP)
cam->ppmode = IEEE1284_MODE_ECP;
else if (port->modes & PARPORT_MODE_EPP)
cam->ppmode = IEEE1284_MODE_EPP;
else
cam->ppmode = IEEE1284_MODE_ECP;
break;
case 1: /* hw- or sw-ecp */
cam->ppmode = IEEE1284_MODE_ECP;
break;
case 2: /* hw- or sw-epp */
cam->ppmode = IEEE1284_MODE_EPP;
break;
}
/* Tell the parport driver that we exists */
cam->pdev = parport_register_device(port, "w9966", NULL, NULL, NULL, 0, NULL);
if (cam->pdev == NULL) {
DPRINTF("parport_register_device() failed\n");
return -1;
}
w9966_set_state(cam, W9966_STATE_PDEV, W9966_STATE_PDEV);
w9966_pdev_claim(cam);
/* Setup a default capture mode */
if (w9966_setup(cam, 0, 0, 1023, 1023, 200, 160) != 0) {
DPRINTF("w9966_setup() failed.\n");
return -1;
}
w9966_pdev_release(cam);
/* Fill in the video_device struct and register us to v4l */
strlcpy(cam->vdev.name, W9966_DRIVERNAME, sizeof(cam->vdev.name));
cam->vdev.v4l2_dev = v4l2_dev;
cam->vdev.fops = &w9966_fops;
cam->vdev.ioctl_ops = &w9966_ioctl_ops;
cam->vdev.release = video_device_release_empty;
video_set_drvdata(&cam->vdev, cam);
mutex_init(&cam->lock);
if (video_register_device(&cam->vdev, VFL_TYPE_GRABBER, video_nr) < 0)
return -1;
w9966_set_state(cam, W9966_STATE_VDEV, W9966_STATE_VDEV);
/* All ok */
v4l2_info(v4l2_dev, "Found and initialized a webcam on %s.\n",
cam->pport->name);
return 0;
}
/* Terminate everything gracefully */
static void w9966_term(struct w9966 *cam)
{
/* Unregister from v4l */
if (w9966_get_state(cam, W9966_STATE_VDEV, W9966_STATE_VDEV)) {
video_unregister_device(&cam->vdev);
w9966_set_state(cam, W9966_STATE_VDEV, 0);
}
/* Terminate from IEEE1284 mode and release pdev block */
if (w9966_get_state(cam, W9966_STATE_PDEV, W9966_STATE_PDEV)) {
w9966_pdev_claim(cam);
parport_negotiate(cam->pport, IEEE1284_MODE_COMPAT);
w9966_pdev_release(cam);
}
/* Unregister from parport */
if (w9966_get_state(cam, W9966_STATE_PDEV, W9966_STATE_PDEV)) {
parport_unregister_device(cam->pdev);
w9966_set_state(cam, W9966_STATE_PDEV, 0);
}
memset(cam, 0, sizeof(*cam));
}
/* Called once for every parport on init */
static void w9966_attach(struct parport *port)
{
int i;
for (i = 0; i < W9966_MAXCAMS; i++) {
if (w9966_cams[i].dev_state != 0) /* Cam is already assigned */
continue;
if (strcmp(pardev[i], "aggressive") == 0 || strcmp(pardev[i], port->name) == 0) {
if (w9966_init(&w9966_cams[i], port) != 0)
w9966_term(&w9966_cams[i]);
break; /* return */
}
}
}
/* Called once for every parport on termination */
static void w9966_detach(struct parport *port)
{
int i;
for (i = 0; i < W9966_MAXCAMS; i++)
if (w9966_cams[i].dev_state != 0 && w9966_cams[i].pport == port)
w9966_term(&w9966_cams[i]);
}
static struct parport_driver w9966_ppd = {
.name = W9966_DRIVERNAME,
.attach = w9966_attach,
.detach = w9966_detach,
};
/* Module entry point */
static int __init w9966_mod_init(void)
{
int i;
for (i = 0; i < W9966_MAXCAMS; i++)
w9966_cams[i].dev_state = 0;
return parport_register_driver(&w9966_ppd);
}
/* Module cleanup */
static void __exit w9966_mod_term(void)
{
parport_unregister_driver(&w9966_ppd);
}
module_init(w9966_mod_init);
module_exit(w9966_mod_term);
| gpl-2.0 |
Droid-Concepts/DC-Elite_kernel_jf | sound/soc/codecs/ad1836.c | 4814 | 9982 | /*
* Audio Codec driver supporting:
* AD1835A, AD1836, AD1837A, AD1838A, AD1839A
*
* Copyright 2009-2011 Analog Devices Inc.
*
* Licensed under the GPL-2 or later.
*/
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/initval.h>
#include <sound/soc.h>
#include <sound/tlv.h>
#include <linux/spi/spi.h>
#include "ad1836.h"
enum ad1836_type {
AD1835,
AD1836,
AD1838,
};
/* codec private data */
struct ad1836_priv {
enum ad1836_type type;
};
/*
* AD1836 volume/mute/de-emphasis etc. controls
*/
static const char *ad1836_deemp[] = {"None", "44.1kHz", "32kHz", "48kHz"};
static const struct soc_enum ad1836_deemp_enum =
SOC_ENUM_SINGLE(AD1836_DAC_CTRL1, 8, 4, ad1836_deemp);
#define AD1836_DAC_VOLUME(x) \
SOC_DOUBLE_R("DAC" #x " Playback Volume", AD1836_DAC_L_VOL(x), \
AD1836_DAC_R_VOL(x), 0, 0x3FF, 0)
#define AD1836_DAC_SWITCH(x) \
SOC_DOUBLE("DAC" #x " Playback Switch", AD1836_DAC_CTRL2, \
AD1836_MUTE_LEFT(x), AD1836_MUTE_RIGHT(x), 1, 1)
#define AD1836_ADC_SWITCH(x) \
SOC_DOUBLE("ADC" #x " Capture Switch", AD1836_ADC_CTRL2, \
AD1836_MUTE_LEFT(x), AD1836_MUTE_RIGHT(x), 1, 1)
static const struct snd_kcontrol_new ad183x_dac_controls[] = {
AD1836_DAC_VOLUME(1),
AD1836_DAC_SWITCH(1),
AD1836_DAC_VOLUME(2),
AD1836_DAC_SWITCH(2),
AD1836_DAC_VOLUME(3),
AD1836_DAC_SWITCH(3),
AD1836_DAC_VOLUME(4),
AD1836_DAC_SWITCH(4),
};
static const struct snd_soc_dapm_widget ad183x_dac_dapm_widgets[] = {
SND_SOC_DAPM_OUTPUT("DAC1OUT"),
SND_SOC_DAPM_OUTPUT("DAC2OUT"),
SND_SOC_DAPM_OUTPUT("DAC3OUT"),
SND_SOC_DAPM_OUTPUT("DAC4OUT"),
};
static const struct snd_soc_dapm_route ad183x_dac_routes[] = {
{ "DAC1OUT", NULL, "DAC" },
{ "DAC2OUT", NULL, "DAC" },
{ "DAC3OUT", NULL, "DAC" },
{ "DAC4OUT", NULL, "DAC" },
};
static const struct snd_kcontrol_new ad183x_adc_controls[] = {
AD1836_ADC_SWITCH(1),
AD1836_ADC_SWITCH(2),
AD1836_ADC_SWITCH(3),
};
static const struct snd_soc_dapm_widget ad183x_adc_dapm_widgets[] = {
SND_SOC_DAPM_INPUT("ADC1IN"),
SND_SOC_DAPM_INPUT("ADC2IN"),
};
static const struct snd_soc_dapm_route ad183x_adc_routes[] = {
{ "ADC", NULL, "ADC1IN" },
{ "ADC", NULL, "ADC2IN" },
};
static const struct snd_kcontrol_new ad183x_controls[] = {
/* ADC high-pass filter */
SOC_SINGLE("ADC High Pass Filter Switch", AD1836_ADC_CTRL1,
AD1836_ADC_HIGHPASS_FILTER, 1, 0),
/* DAC de-emphasis */
SOC_ENUM("Playback Deemphasis", ad1836_deemp_enum),
};
static const struct snd_soc_dapm_widget ad183x_dapm_widgets[] = {
SND_SOC_DAPM_DAC("DAC", "Playback", AD1836_DAC_CTRL1,
AD1836_DAC_POWERDOWN, 1),
SND_SOC_DAPM_ADC("ADC", "Capture", SND_SOC_NOPM, 0, 0),
SND_SOC_DAPM_SUPPLY("ADC_PWR", AD1836_ADC_CTRL1,
AD1836_ADC_POWERDOWN, 1, NULL, 0),
};
static const struct snd_soc_dapm_route ad183x_dapm_routes[] = {
{ "DAC", NULL, "ADC_PWR" },
{ "ADC", NULL, "ADC_PWR" },
};
static const DECLARE_TLV_DB_SCALE(ad1836_in_tlv, 0, 300, 0);
static const struct snd_kcontrol_new ad1836_controls[] = {
SOC_DOUBLE_TLV("ADC2 Capture Volume", AD1836_ADC_CTRL1, 3, 0, 4, 0,
ad1836_in_tlv),
};
/*
* DAI ops entries
*/
static int ad1836_set_dai_fmt(struct snd_soc_dai *codec_dai,
unsigned int fmt)
{
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
/* at present, we support adc aux mode to interface with
* blackfin sport tdm mode
*/
case SND_SOC_DAIFMT_DSP_A:
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_IB_IF:
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
/* ALCLK,ABCLK are both output, AD1836 can only be master */
case SND_SOC_DAIFMT_CBM_CFM:
break;
default:
return -EINVAL;
}
return 0;
}
static int ad1836_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
int word_len = 0;
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_codec *codec = rtd->codec;
/* bit size */
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
word_len = AD1836_WORD_LEN_16;
break;
case SNDRV_PCM_FORMAT_S20_3LE:
word_len = AD1836_WORD_LEN_20;
break;
case SNDRV_PCM_FORMAT_S24_LE:
case SNDRV_PCM_FORMAT_S32_LE:
word_len = AD1836_WORD_LEN_24;
break;
}
snd_soc_update_bits(codec, AD1836_DAC_CTRL1, AD1836_DAC_WORD_LEN_MASK,
word_len << AD1836_DAC_WORD_LEN_OFFSET);
snd_soc_update_bits(codec, AD1836_ADC_CTRL2, AD1836_ADC_WORD_LEN_MASK,
word_len << AD1836_ADC_WORD_OFFSET);
return 0;
}
static const struct snd_soc_dai_ops ad1836_dai_ops = {
.hw_params = ad1836_hw_params,
.set_fmt = ad1836_set_dai_fmt,
};
#define AD183X_DAI(_name, num_dacs, num_adcs) \
{ \
.name = _name "-hifi", \
.playback = { \
.stream_name = "Playback", \
.channels_min = 2, \
.channels_max = (num_dacs) * 2, \
.rates = SNDRV_PCM_RATE_48000, \
.formats = SNDRV_PCM_FMTBIT_S32_LE | SNDRV_PCM_FMTBIT_S16_LE | \
SNDRV_PCM_FMTBIT_S20_3LE | SNDRV_PCM_FMTBIT_S24_LE, \
}, \
.capture = { \
.stream_name = "Capture", \
.channels_min = 2, \
.channels_max = (num_adcs) * 2, \
.rates = SNDRV_PCM_RATE_48000, \
.formats = SNDRV_PCM_FMTBIT_S32_LE | SNDRV_PCM_FMTBIT_S16_LE | \
SNDRV_PCM_FMTBIT_S20_3LE | SNDRV_PCM_FMTBIT_S24_LE, \
}, \
.ops = &ad1836_dai_ops, \
}
static struct snd_soc_dai_driver ad183x_dais[] = {
[AD1835] = AD183X_DAI("ad1835", 4, 1),
[AD1836] = AD183X_DAI("ad1836", 3, 2),
[AD1838] = AD183X_DAI("ad1838", 3, 1),
};
#ifdef CONFIG_PM
static int ad1836_suspend(struct snd_soc_codec *codec)
{
/* reset clock control mode */
return snd_soc_update_bits(codec, AD1836_ADC_CTRL2,
AD1836_ADC_SERFMT_MASK, 0);
}
static int ad1836_resume(struct snd_soc_codec *codec)
{
/* restore clock control mode */
return snd_soc_update_bits(codec, AD1836_ADC_CTRL2,
AD1836_ADC_SERFMT_MASK, AD1836_ADC_AUX);
}
#else
#define ad1836_suspend NULL
#define ad1836_resume NULL
#endif
static int ad1836_probe(struct snd_soc_codec *codec)
{
struct ad1836_priv *ad1836 = snd_soc_codec_get_drvdata(codec);
struct snd_soc_dapm_context *dapm = &codec->dapm;
int num_dacs, num_adcs;
int ret = 0;
int i;
num_dacs = ad183x_dais[ad1836->type].playback.channels_max / 2;
num_adcs = ad183x_dais[ad1836->type].capture.channels_max / 2;
ret = snd_soc_codec_set_cache_io(codec, 4, 12, SND_SOC_SPI);
if (ret < 0) {
dev_err(codec->dev, "failed to set cache I/O: %d\n",
ret);
return ret;
}
/* default setting for ad1836 */
/* de-emphasis: 48kHz, power-on dac */
snd_soc_write(codec, AD1836_DAC_CTRL1, 0x300);
/* unmute dac channels */
snd_soc_write(codec, AD1836_DAC_CTRL2, 0x0);
/* high-pass filter enable, power-on adc */
snd_soc_write(codec, AD1836_ADC_CTRL1, 0x100);
/* unmute adc channles, adc aux mode */
snd_soc_write(codec, AD1836_ADC_CTRL2, 0x180);
/* volume */
for (i = 1; i <= num_dacs; ++i) {
snd_soc_write(codec, AD1836_DAC_L_VOL(i), 0x3FF);
snd_soc_write(codec, AD1836_DAC_R_VOL(i), 0x3FF);
}
if (ad1836->type == AD1836) {
/* left/right diff:PGA/MUX */
snd_soc_write(codec, AD1836_ADC_CTRL3, 0x3A);
ret = snd_soc_add_codec_controls(codec, ad1836_controls,
ARRAY_SIZE(ad1836_controls));
if (ret)
return ret;
} else {
snd_soc_write(codec, AD1836_ADC_CTRL3, 0x00);
}
ret = snd_soc_add_codec_controls(codec, ad183x_dac_controls, num_dacs * 2);
if (ret)
return ret;
ret = snd_soc_add_codec_controls(codec, ad183x_adc_controls, num_adcs);
if (ret)
return ret;
ret = snd_soc_dapm_new_controls(dapm, ad183x_dac_dapm_widgets, num_dacs);
if (ret)
return ret;
ret = snd_soc_dapm_new_controls(dapm, ad183x_adc_dapm_widgets, num_adcs);
if (ret)
return ret;
ret = snd_soc_dapm_add_routes(dapm, ad183x_dac_routes, num_dacs);
if (ret)
return ret;
ret = snd_soc_dapm_add_routes(dapm, ad183x_adc_routes, num_adcs);
if (ret)
return ret;
return ret;
}
/* power down chip */
static int ad1836_remove(struct snd_soc_codec *codec)
{
/* reset clock control mode */
return snd_soc_update_bits(codec, AD1836_ADC_CTRL2,
AD1836_ADC_SERFMT_MASK, 0);
}
static struct snd_soc_codec_driver soc_codec_dev_ad1836 = {
.probe = ad1836_probe,
.remove = ad1836_remove,
.suspend = ad1836_suspend,
.resume = ad1836_resume,
.reg_cache_size = AD1836_NUM_REGS,
.reg_word_size = sizeof(u16),
.controls = ad183x_controls,
.num_controls = ARRAY_SIZE(ad183x_controls),
.dapm_widgets = ad183x_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(ad183x_dapm_widgets),
.dapm_routes = ad183x_dapm_routes,
.num_dapm_routes = ARRAY_SIZE(ad183x_dapm_routes),
};
static int __devinit ad1836_spi_probe(struct spi_device *spi)
{
struct ad1836_priv *ad1836;
int ret;
ad1836 = devm_kzalloc(&spi->dev, sizeof(struct ad1836_priv),
GFP_KERNEL);
if (ad1836 == NULL)
return -ENOMEM;
ad1836->type = spi_get_device_id(spi)->driver_data;
spi_set_drvdata(spi, ad1836);
ret = snd_soc_register_codec(&spi->dev,
&soc_codec_dev_ad1836, &ad183x_dais[ad1836->type], 1);
return ret;
}
static int __devexit ad1836_spi_remove(struct spi_device *spi)
{
snd_soc_unregister_codec(&spi->dev);
return 0;
}
static const struct spi_device_id ad1836_ids[] = {
{ "ad1835", AD1835 },
{ "ad1836", AD1836 },
{ "ad1837", AD1835 },
{ "ad1838", AD1838 },
{ "ad1839", AD1838 },
{ },
};
MODULE_DEVICE_TABLE(spi, ad1836_ids);
static struct spi_driver ad1836_spi_driver = {
.driver = {
.name = "ad1836",
.owner = THIS_MODULE,
},
.probe = ad1836_spi_probe,
.remove = __devexit_p(ad1836_spi_remove),
.id_table = ad1836_ids,
};
static int __init ad1836_init(void)
{
return spi_register_driver(&ad1836_spi_driver);
}
module_init(ad1836_init);
static void __exit ad1836_exit(void)
{
spi_unregister_driver(&ad1836_spi_driver);
}
module_exit(ad1836_exit);
MODULE_DESCRIPTION("ASoC ad1836 driver");
MODULE_AUTHOR("Barry Song <21cnbao@gmail.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
partyajak/android_kernel_lge_g2m | drivers/tty/serial/ar933x_uart.c | 5070 | 16293 | /*
* Atheros AR933X SoC built-in UART driver
*
* Copyright (C) 2011 Gabor Juhos <juhosg@openwrt.org>
*
* Based on drivers/char/serial.c, by Linus Torvalds, Theodore Ts'o.
*
* 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/ioport.h>
#include <linux/init.h>
#include <linux/console.h>
#include <linux/sysrq.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/tty.h>
#include <linux/tty_flip.h>
#include <linux/serial_core.h>
#include <linux/serial.h>
#include <linux/slab.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <asm/mach-ath79/ar933x_uart.h>
#include <asm/mach-ath79/ar933x_uart_platform.h>
#define DRIVER_NAME "ar933x-uart"
#define AR933X_DUMMY_STATUS_RD 0x01
static struct uart_driver ar933x_uart_driver;
struct ar933x_uart_port {
struct uart_port port;
unsigned int ier; /* shadow Interrupt Enable Register */
};
static inline unsigned int ar933x_uart_read(struct ar933x_uart_port *up,
int offset)
{
return readl(up->port.membase + offset);
}
static inline void ar933x_uart_write(struct ar933x_uart_port *up,
int offset, unsigned int value)
{
writel(value, up->port.membase + offset);
}
static inline void ar933x_uart_rmw(struct ar933x_uart_port *up,
unsigned int offset,
unsigned int mask,
unsigned int val)
{
unsigned int t;
t = ar933x_uart_read(up, offset);
t &= ~mask;
t |= val;
ar933x_uart_write(up, offset, t);
}
static inline void ar933x_uart_rmw_set(struct ar933x_uart_port *up,
unsigned int offset,
unsigned int val)
{
ar933x_uart_rmw(up, offset, 0, val);
}
static inline void ar933x_uart_rmw_clear(struct ar933x_uart_port *up,
unsigned int offset,
unsigned int val)
{
ar933x_uart_rmw(up, offset, val, 0);
}
static inline void ar933x_uart_start_tx_interrupt(struct ar933x_uart_port *up)
{
up->ier |= AR933X_UART_INT_TX_EMPTY;
ar933x_uart_write(up, AR933X_UART_INT_EN_REG, up->ier);
}
static inline void ar933x_uart_stop_tx_interrupt(struct ar933x_uart_port *up)
{
up->ier &= ~AR933X_UART_INT_TX_EMPTY;
ar933x_uart_write(up, AR933X_UART_INT_EN_REG, up->ier);
}
static inline void ar933x_uart_putc(struct ar933x_uart_port *up, int ch)
{
unsigned int rdata;
rdata = ch & AR933X_UART_DATA_TX_RX_MASK;
rdata |= AR933X_UART_DATA_TX_CSR;
ar933x_uart_write(up, AR933X_UART_DATA_REG, rdata);
}
static unsigned int ar933x_uart_tx_empty(struct uart_port *port)
{
struct ar933x_uart_port *up = (struct ar933x_uart_port *) port;
unsigned long flags;
unsigned int rdata;
spin_lock_irqsave(&up->port.lock, flags);
rdata = ar933x_uart_read(up, AR933X_UART_DATA_REG);
spin_unlock_irqrestore(&up->port.lock, flags);
return (rdata & AR933X_UART_DATA_TX_CSR) ? 0 : TIOCSER_TEMT;
}
static unsigned int ar933x_uart_get_mctrl(struct uart_port *port)
{
return TIOCM_CAR;
}
static void ar933x_uart_set_mctrl(struct uart_port *port, unsigned int mctrl)
{
}
static void ar933x_uart_start_tx(struct uart_port *port)
{
struct ar933x_uart_port *up = (struct ar933x_uart_port *) port;
ar933x_uart_start_tx_interrupt(up);
}
static void ar933x_uart_stop_tx(struct uart_port *port)
{
struct ar933x_uart_port *up = (struct ar933x_uart_port *) port;
ar933x_uart_stop_tx_interrupt(up);
}
static void ar933x_uart_stop_rx(struct uart_port *port)
{
struct ar933x_uart_port *up = (struct ar933x_uart_port *) port;
up->ier &= ~AR933X_UART_INT_RX_VALID;
ar933x_uart_write(up, AR933X_UART_INT_EN_REG, up->ier);
}
static void ar933x_uart_break_ctl(struct uart_port *port, int break_state)
{
struct ar933x_uart_port *up = (struct ar933x_uart_port *) port;
unsigned long flags;
spin_lock_irqsave(&up->port.lock, flags);
if (break_state == -1)
ar933x_uart_rmw_set(up, AR933X_UART_CS_REG,
AR933X_UART_CS_TX_BREAK);
else
ar933x_uart_rmw_clear(up, AR933X_UART_CS_REG,
AR933X_UART_CS_TX_BREAK);
spin_unlock_irqrestore(&up->port.lock, flags);
}
static void ar933x_uart_enable_ms(struct uart_port *port)
{
}
static void ar933x_uart_set_termios(struct uart_port *port,
struct ktermios *new,
struct ktermios *old)
{
struct ar933x_uart_port *up = (struct ar933x_uart_port *) port;
unsigned int cs;
unsigned long flags;
unsigned int baud, scale;
/* Only CS8 is supported */
new->c_cflag &= ~CSIZE;
new->c_cflag |= CS8;
/* Only one stop bit is supported */
new->c_cflag &= ~CSTOPB;
cs = 0;
if (new->c_cflag & PARENB) {
if (!(new->c_cflag & PARODD))
cs |= AR933X_UART_CS_PARITY_EVEN;
else
cs |= AR933X_UART_CS_PARITY_ODD;
} else {
cs |= AR933X_UART_CS_PARITY_NONE;
}
/* Mark/space parity is not supported */
new->c_cflag &= ~CMSPAR;
baud = uart_get_baud_rate(port, new, old, 0, port->uartclk / 16);
scale = (port->uartclk / (16 * baud)) - 1;
/*
* Ok, we're now changing the port state. Do it with
* interrupts disabled.
*/
spin_lock_irqsave(&up->port.lock, flags);
/* Update the per-port timeout. */
uart_update_timeout(port, new->c_cflag, baud);
up->port.ignore_status_mask = 0;
/* ignore all characters if CREAD is not set */
if ((new->c_cflag & CREAD) == 0)
up->port.ignore_status_mask |= AR933X_DUMMY_STATUS_RD;
ar933x_uart_write(up, AR933X_UART_CLOCK_REG,
scale << AR933X_UART_CLOCK_SCALE_S | 8192);
/* setup configuration register */
ar933x_uart_rmw(up, AR933X_UART_CS_REG, AR933X_UART_CS_PARITY_M, cs);
/* enable host interrupt */
ar933x_uart_rmw_set(up, AR933X_UART_CS_REG,
AR933X_UART_CS_HOST_INT_EN);
spin_unlock_irqrestore(&up->port.lock, flags);
if (tty_termios_baud_rate(new))
tty_termios_encode_baud_rate(new, baud, baud);
}
static void ar933x_uart_rx_chars(struct ar933x_uart_port *up)
{
struct tty_struct *tty;
int max_count = 256;
tty = tty_port_tty_get(&up->port.state->port);
do {
unsigned int rdata;
unsigned char ch;
rdata = ar933x_uart_read(up, AR933X_UART_DATA_REG);
if ((rdata & AR933X_UART_DATA_RX_CSR) == 0)
break;
/* remove the character from the FIFO */
ar933x_uart_write(up, AR933X_UART_DATA_REG,
AR933X_UART_DATA_RX_CSR);
if (!tty) {
/* discard the data if no tty available */
continue;
}
up->port.icount.rx++;
ch = rdata & AR933X_UART_DATA_TX_RX_MASK;
if (uart_handle_sysrq_char(&up->port, ch))
continue;
if ((up->port.ignore_status_mask & AR933X_DUMMY_STATUS_RD) == 0)
tty_insert_flip_char(tty, ch, TTY_NORMAL);
} while (max_count-- > 0);
if (tty) {
tty_flip_buffer_push(tty);
tty_kref_put(tty);
}
}
static void ar933x_uart_tx_chars(struct ar933x_uart_port *up)
{
struct circ_buf *xmit = &up->port.state->xmit;
int count;
if (uart_tx_stopped(&up->port))
return;
count = up->port.fifosize;
do {
unsigned int rdata;
rdata = ar933x_uart_read(up, AR933X_UART_DATA_REG);
if ((rdata & AR933X_UART_DATA_TX_CSR) == 0)
break;
if (up->port.x_char) {
ar933x_uart_putc(up, up->port.x_char);
up->port.icount.tx++;
up->port.x_char = 0;
continue;
}
if (uart_circ_empty(xmit))
break;
ar933x_uart_putc(up, xmit->buf[xmit->tail]);
xmit->tail = (xmit->tail + 1) & (UART_XMIT_SIZE - 1);
up->port.icount.tx++;
} while (--count > 0);
if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS)
uart_write_wakeup(&up->port);
if (!uart_circ_empty(xmit))
ar933x_uart_start_tx_interrupt(up);
}
static irqreturn_t ar933x_uart_interrupt(int irq, void *dev_id)
{
struct ar933x_uart_port *up = dev_id;
unsigned int status;
status = ar933x_uart_read(up, AR933X_UART_CS_REG);
if ((status & AR933X_UART_CS_HOST_INT) == 0)
return IRQ_NONE;
spin_lock(&up->port.lock);
status = ar933x_uart_read(up, AR933X_UART_INT_REG);
status &= ar933x_uart_read(up, AR933X_UART_INT_EN_REG);
if (status & AR933X_UART_INT_RX_VALID) {
ar933x_uart_write(up, AR933X_UART_INT_REG,
AR933X_UART_INT_RX_VALID);
ar933x_uart_rx_chars(up);
}
if (status & AR933X_UART_INT_TX_EMPTY) {
ar933x_uart_write(up, AR933X_UART_INT_REG,
AR933X_UART_INT_TX_EMPTY);
ar933x_uart_stop_tx_interrupt(up);
ar933x_uart_tx_chars(up);
}
spin_unlock(&up->port.lock);
return IRQ_HANDLED;
}
static int ar933x_uart_startup(struct uart_port *port)
{
struct ar933x_uart_port *up = (struct ar933x_uart_port *) port;
unsigned long flags;
int ret;
ret = request_irq(up->port.irq, ar933x_uart_interrupt,
up->port.irqflags, dev_name(up->port.dev), up);
if (ret)
return ret;
spin_lock_irqsave(&up->port.lock, flags);
/* Enable HOST interrupts */
ar933x_uart_rmw_set(up, AR933X_UART_CS_REG,
AR933X_UART_CS_HOST_INT_EN);
/* Enable RX interrupts */
up->ier = AR933X_UART_INT_RX_VALID;
ar933x_uart_write(up, AR933X_UART_INT_EN_REG, up->ier);
spin_unlock_irqrestore(&up->port.lock, flags);
return 0;
}
static void ar933x_uart_shutdown(struct uart_port *port)
{
struct ar933x_uart_port *up = (struct ar933x_uart_port *) port;
/* Disable all interrupts */
up->ier = 0;
ar933x_uart_write(up, AR933X_UART_INT_EN_REG, up->ier);
/* Disable break condition */
ar933x_uart_rmw_clear(up, AR933X_UART_CS_REG,
AR933X_UART_CS_TX_BREAK);
free_irq(up->port.irq, up);
}
static const char *ar933x_uart_type(struct uart_port *port)
{
return (port->type == PORT_AR933X) ? "AR933X UART" : NULL;
}
static void ar933x_uart_release_port(struct uart_port *port)
{
/* Nothing to release ... */
}
static int ar933x_uart_request_port(struct uart_port *port)
{
/* UARTs always present */
return 0;
}
static void ar933x_uart_config_port(struct uart_port *port, int flags)
{
if (flags & UART_CONFIG_TYPE)
port->type = PORT_AR933X;
}
static int ar933x_uart_verify_port(struct uart_port *port,
struct serial_struct *ser)
{
if (ser->type != PORT_UNKNOWN &&
ser->type != PORT_AR933X)
return -EINVAL;
if (ser->irq < 0 || ser->irq >= NR_IRQS)
return -EINVAL;
if (ser->baud_base < 28800)
return -EINVAL;
return 0;
}
static struct uart_ops ar933x_uart_ops = {
.tx_empty = ar933x_uart_tx_empty,
.set_mctrl = ar933x_uart_set_mctrl,
.get_mctrl = ar933x_uart_get_mctrl,
.stop_tx = ar933x_uart_stop_tx,
.start_tx = ar933x_uart_start_tx,
.stop_rx = ar933x_uart_stop_rx,
.enable_ms = ar933x_uart_enable_ms,
.break_ctl = ar933x_uart_break_ctl,
.startup = ar933x_uart_startup,
.shutdown = ar933x_uart_shutdown,
.set_termios = ar933x_uart_set_termios,
.type = ar933x_uart_type,
.release_port = ar933x_uart_release_port,
.request_port = ar933x_uart_request_port,
.config_port = ar933x_uart_config_port,
.verify_port = ar933x_uart_verify_port,
};
#ifdef CONFIG_SERIAL_AR933X_CONSOLE
static struct ar933x_uart_port *
ar933x_console_ports[CONFIG_SERIAL_AR933X_NR_UARTS];
static void ar933x_uart_wait_xmitr(struct ar933x_uart_port *up)
{
unsigned int status;
unsigned int timeout = 60000;
/* Wait up to 60ms for the character(s) to be sent. */
do {
status = ar933x_uart_read(up, AR933X_UART_DATA_REG);
if (--timeout == 0)
break;
udelay(1);
} while ((status & AR933X_UART_DATA_TX_CSR) == 0);
}
static void ar933x_uart_console_putchar(struct uart_port *port, int ch)
{
struct ar933x_uart_port *up = (struct ar933x_uart_port *) port;
ar933x_uart_wait_xmitr(up);
ar933x_uart_putc(up, ch);
}
static void ar933x_uart_console_write(struct console *co, const char *s,
unsigned int count)
{
struct ar933x_uart_port *up = ar933x_console_ports[co->index];
unsigned long flags;
unsigned int int_en;
int locked = 1;
local_irq_save(flags);
if (up->port.sysrq)
locked = 0;
else if (oops_in_progress)
locked = spin_trylock(&up->port.lock);
else
spin_lock(&up->port.lock);
/*
* First save the IER then disable the interrupts
*/
int_en = ar933x_uart_read(up, AR933X_UART_INT_EN_REG);
ar933x_uart_write(up, AR933X_UART_INT_EN_REG, 0);
uart_console_write(&up->port, s, count, ar933x_uart_console_putchar);
/*
* Finally, wait for transmitter to become empty
* and restore the IER
*/
ar933x_uart_wait_xmitr(up);
ar933x_uart_write(up, AR933X_UART_INT_EN_REG, int_en);
ar933x_uart_write(up, AR933X_UART_INT_REG, AR933X_UART_INT_ALLINTS);
if (locked)
spin_unlock(&up->port.lock);
local_irq_restore(flags);
}
static int ar933x_uart_console_setup(struct console *co, char *options)
{
struct ar933x_uart_port *up;
int baud = 115200;
int bits = 8;
int parity = 'n';
int flow = 'n';
if (co->index < 0 || co->index >= CONFIG_SERIAL_AR933X_NR_UARTS)
return -EINVAL;
up = ar933x_console_ports[co->index];
if (!up)
return -ENODEV;
if (options)
uart_parse_options(options, &baud, &parity, &bits, &flow);
return uart_set_options(&up->port, co, baud, parity, bits, flow);
}
static struct console ar933x_uart_console = {
.name = "ttyATH",
.write = ar933x_uart_console_write,
.device = uart_console_device,
.setup = ar933x_uart_console_setup,
.flags = CON_PRINTBUFFER,
.index = -1,
.data = &ar933x_uart_driver,
};
static void ar933x_uart_add_console_port(struct ar933x_uart_port *up)
{
ar933x_console_ports[up->port.line] = up;
}
#define AR933X_SERIAL_CONSOLE (&ar933x_uart_console)
#else
static inline void ar933x_uart_add_console_port(struct ar933x_uart_port *up) {}
#define AR933X_SERIAL_CONSOLE NULL
#endif /* CONFIG_SERIAL_AR933X_CONSOLE */
static struct uart_driver ar933x_uart_driver = {
.owner = THIS_MODULE,
.driver_name = DRIVER_NAME,
.dev_name = "ttyATH",
.nr = CONFIG_SERIAL_AR933X_NR_UARTS,
.cons = AR933X_SERIAL_CONSOLE,
};
static int __devinit ar933x_uart_probe(struct platform_device *pdev)
{
struct ar933x_uart_platform_data *pdata;
struct ar933x_uart_port *up;
struct uart_port *port;
struct resource *mem_res;
struct resource *irq_res;
int id;
int ret;
pdata = pdev->dev.platform_data;
if (!pdata)
return -EINVAL;
id = pdev->id;
if (id == -1)
id = 0;
if (id > CONFIG_SERIAL_AR933X_NR_UARTS)
return -EINVAL;
mem_res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!mem_res) {
dev_err(&pdev->dev, "no MEM resource\n");
return -EINVAL;
}
irq_res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!irq_res) {
dev_err(&pdev->dev, "no IRQ resource\n");
return -EINVAL;
}
up = kzalloc(sizeof(struct ar933x_uart_port), GFP_KERNEL);
if (!up)
return -ENOMEM;
port = &up->port;
port->mapbase = mem_res->start;
port->membase = ioremap(mem_res->start, AR933X_UART_REGS_SIZE);
if (!port->membase) {
ret = -ENOMEM;
goto err_free_up;
}
port->line = id;
port->irq = irq_res->start;
port->dev = &pdev->dev;
port->type = PORT_AR933X;
port->iotype = UPIO_MEM32;
port->uartclk = pdata->uartclk;
port->regshift = 2;
port->fifosize = AR933X_UART_FIFO_SIZE;
port->ops = &ar933x_uart_ops;
ar933x_uart_add_console_port(up);
ret = uart_add_one_port(&ar933x_uart_driver, &up->port);
if (ret)
goto err_unmap;
platform_set_drvdata(pdev, up);
return 0;
err_unmap:
iounmap(up->port.membase);
err_free_up:
kfree(up);
return ret;
}
static int __devexit ar933x_uart_remove(struct platform_device *pdev)
{
struct ar933x_uart_port *up;
up = platform_get_drvdata(pdev);
platform_set_drvdata(pdev, NULL);
if (up) {
uart_remove_one_port(&ar933x_uart_driver, &up->port);
iounmap(up->port.membase);
kfree(up);
}
return 0;
}
static struct platform_driver ar933x_uart_platform_driver = {
.probe = ar933x_uart_probe,
.remove = __devexit_p(ar933x_uart_remove),
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
},
};
static int __init ar933x_uart_init(void)
{
int ret;
ar933x_uart_driver.nr = CONFIG_SERIAL_AR933X_NR_UARTS;
ret = uart_register_driver(&ar933x_uart_driver);
if (ret)
goto err_out;
ret = platform_driver_register(&ar933x_uart_platform_driver);
if (ret)
goto err_unregister_uart_driver;
return 0;
err_unregister_uart_driver:
uart_unregister_driver(&ar933x_uart_driver);
err_out:
return ret;
}
static void __exit ar933x_uart_exit(void)
{
platform_driver_unregister(&ar933x_uart_platform_driver);
uart_unregister_driver(&ar933x_uart_driver);
}
module_init(ar933x_uart_init);
module_exit(ar933x_uart_exit);
MODULE_DESCRIPTION("Atheros AR933X UART driver");
MODULE_AUTHOR("Gabor Juhos <juhosg@openwrt.org>");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:" DRIVER_NAME);
| gpl-2.0 |
hanshuebner/linux-xlnx | drivers/spi/spi-mpc52xx.c | 5070 | 14783 | /*
* MPC52xx SPI bus driver.
*
* Copyright (C) 2008 Secret Lab Technologies Ltd.
*
* This file is released under the GPLv2
*
* This is the driver for the MPC5200's dedicated SPI controller.
*
* Note: this driver does not support the MPC5200 PSC in SPI mode. For
* that driver see drivers/spi/mpc52xx_psc_spi.c
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/of_platform.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/spi/spi.h>
#include <linux/io.h>
#include <linux/of_gpio.h>
#include <linux/slab.h>
#include <asm/time.h>
#include <asm/mpc52xx.h>
MODULE_AUTHOR("Grant Likely <grant.likely@secretlab.ca>");
MODULE_DESCRIPTION("MPC52xx SPI (non-PSC) Driver");
MODULE_LICENSE("GPL");
/* Register offsets */
#define SPI_CTRL1 0x00
#define SPI_CTRL1_SPIE (1 << 7)
#define SPI_CTRL1_SPE (1 << 6)
#define SPI_CTRL1_MSTR (1 << 4)
#define SPI_CTRL1_CPOL (1 << 3)
#define SPI_CTRL1_CPHA (1 << 2)
#define SPI_CTRL1_SSOE (1 << 1)
#define SPI_CTRL1_LSBFE (1 << 0)
#define SPI_CTRL2 0x01
#define SPI_BRR 0x04
#define SPI_STATUS 0x05
#define SPI_STATUS_SPIF (1 << 7)
#define SPI_STATUS_WCOL (1 << 6)
#define SPI_STATUS_MODF (1 << 4)
#define SPI_DATA 0x09
#define SPI_PORTDATA 0x0d
#define SPI_DATADIR 0x10
/* FSM state return values */
#define FSM_STOP 0 /* Nothing more for the state machine to */
/* do. If something interesting happens */
/* then an IRQ will be received */
#define FSM_POLL 1 /* need to poll for completion, an IRQ is */
/* not expected */
#define FSM_CONTINUE 2 /* Keep iterating the state machine */
/* Driver internal data */
struct mpc52xx_spi {
struct spi_master *master;
void __iomem *regs;
int irq0; /* MODF irq */
int irq1; /* SPIF irq */
unsigned int ipb_freq;
/* Statistics; not used now, but will be reintroduced for debugfs */
int msg_count;
int wcol_count;
int wcol_ticks;
u32 wcol_tx_timestamp;
int modf_count;
int byte_count;
struct list_head queue; /* queue of pending messages */
spinlock_t lock;
struct work_struct work;
/* Details of current transfer (length, and buffer pointers) */
struct spi_message *message; /* current message */
struct spi_transfer *transfer; /* current transfer */
int (*state)(int irq, struct mpc52xx_spi *ms, u8 status, u8 data);
int len;
int timestamp;
u8 *rx_buf;
const u8 *tx_buf;
int cs_change;
int gpio_cs_count;
unsigned int *gpio_cs;
};
/*
* CS control function
*/
static void mpc52xx_spi_chipsel(struct mpc52xx_spi *ms, int value)
{
int cs;
if (ms->gpio_cs_count > 0) {
cs = ms->message->spi->chip_select;
gpio_set_value(ms->gpio_cs[cs], value ? 0 : 1);
} else
out_8(ms->regs + SPI_PORTDATA, value ? 0 : 0x08);
}
/*
* Start a new transfer. This is called both by the idle state
* for the first transfer in a message, and by the wait state when the
* previous transfer in a message is complete.
*/
static void mpc52xx_spi_start_transfer(struct mpc52xx_spi *ms)
{
ms->rx_buf = ms->transfer->rx_buf;
ms->tx_buf = ms->transfer->tx_buf;
ms->len = ms->transfer->len;
/* Activate the chip select */
if (ms->cs_change)
mpc52xx_spi_chipsel(ms, 1);
ms->cs_change = ms->transfer->cs_change;
/* Write out the first byte */
ms->wcol_tx_timestamp = get_tbl();
if (ms->tx_buf)
out_8(ms->regs + SPI_DATA, *ms->tx_buf++);
else
out_8(ms->regs + SPI_DATA, 0);
}
/* Forward declaration of state handlers */
static int mpc52xx_spi_fsmstate_transfer(int irq, struct mpc52xx_spi *ms,
u8 status, u8 data);
static int mpc52xx_spi_fsmstate_wait(int irq, struct mpc52xx_spi *ms,
u8 status, u8 data);
/*
* IDLE state
*
* No transfers are in progress; if another transfer is pending then retrieve
* it and kick it off. Otherwise, stop processing the state machine
*/
static int
mpc52xx_spi_fsmstate_idle(int irq, struct mpc52xx_spi *ms, u8 status, u8 data)
{
struct spi_device *spi;
int spr, sppr;
u8 ctrl1;
if (status && (irq != NO_IRQ))
dev_err(&ms->master->dev, "spurious irq, status=0x%.2x\n",
status);
/* Check if there is another transfer waiting. */
if (list_empty(&ms->queue))
return FSM_STOP;
/* get the head of the queue */
ms->message = list_first_entry(&ms->queue, struct spi_message, queue);
list_del_init(&ms->message->queue);
/* Setup the controller parameters */
ctrl1 = SPI_CTRL1_SPIE | SPI_CTRL1_SPE | SPI_CTRL1_MSTR;
spi = ms->message->spi;
if (spi->mode & SPI_CPHA)
ctrl1 |= SPI_CTRL1_CPHA;
if (spi->mode & SPI_CPOL)
ctrl1 |= SPI_CTRL1_CPOL;
if (spi->mode & SPI_LSB_FIRST)
ctrl1 |= SPI_CTRL1_LSBFE;
out_8(ms->regs + SPI_CTRL1, ctrl1);
/* Setup the controller speed */
/* minimum divider is '2'. Also, add '1' to force rounding the
* divider up. */
sppr = ((ms->ipb_freq / ms->message->spi->max_speed_hz) + 1) >> 1;
spr = 0;
if (sppr < 1)
sppr = 1;
while (((sppr - 1) & ~0x7) != 0) {
sppr = (sppr + 1) >> 1; /* add '1' to force rounding up */
spr++;
}
sppr--; /* sppr quantity in register is offset by 1 */
if (spr > 7) {
/* Don't overrun limits of SPI baudrate register */
spr = 7;
sppr = 7;
}
out_8(ms->regs + SPI_BRR, sppr << 4 | spr); /* Set speed */
ms->cs_change = 1;
ms->transfer = container_of(ms->message->transfers.next,
struct spi_transfer, transfer_list);
mpc52xx_spi_start_transfer(ms);
ms->state = mpc52xx_spi_fsmstate_transfer;
return FSM_CONTINUE;
}
/*
* TRANSFER state
*
* In the middle of a transfer. If the SPI core has completed processing
* a byte, then read out the received data and write out the next byte
* (unless this transfer is finished; in which case go on to the wait
* state)
*/
static int mpc52xx_spi_fsmstate_transfer(int irq, struct mpc52xx_spi *ms,
u8 status, u8 data)
{
if (!status)
return ms->irq0 ? FSM_STOP : FSM_POLL;
if (status & SPI_STATUS_WCOL) {
/* The SPI controller is stoopid. At slower speeds, it may
* raise the SPIF flag before the state machine is actually
* finished, which causes a collision (internal to the state
* machine only). The manual recommends inserting a delay
* between receiving the interrupt and sending the next byte,
* but it can also be worked around simply by retrying the
* transfer which is what we do here. */
ms->wcol_count++;
ms->wcol_ticks += get_tbl() - ms->wcol_tx_timestamp;
ms->wcol_tx_timestamp = get_tbl();
data = 0;
if (ms->tx_buf)
data = *(ms->tx_buf - 1);
out_8(ms->regs + SPI_DATA, data); /* try again */
return FSM_CONTINUE;
} else if (status & SPI_STATUS_MODF) {
ms->modf_count++;
dev_err(&ms->master->dev, "mode fault\n");
mpc52xx_spi_chipsel(ms, 0);
ms->message->status = -EIO;
ms->message->complete(ms->message->context);
ms->state = mpc52xx_spi_fsmstate_idle;
return FSM_CONTINUE;
}
/* Read data out of the spi device */
ms->byte_count++;
if (ms->rx_buf)
*ms->rx_buf++ = data;
/* Is the transfer complete? */
ms->len--;
if (ms->len == 0) {
ms->timestamp = get_tbl();
ms->timestamp += ms->transfer->delay_usecs * tb_ticks_per_usec;
ms->state = mpc52xx_spi_fsmstate_wait;
return FSM_CONTINUE;
}
/* Write out the next byte */
ms->wcol_tx_timestamp = get_tbl();
if (ms->tx_buf)
out_8(ms->regs + SPI_DATA, *ms->tx_buf++);
else
out_8(ms->regs + SPI_DATA, 0);
return FSM_CONTINUE;
}
/*
* WAIT state
*
* A transfer has completed; need to wait for the delay period to complete
* before starting the next transfer
*/
static int
mpc52xx_spi_fsmstate_wait(int irq, struct mpc52xx_spi *ms, u8 status, u8 data)
{
if (status && irq)
dev_err(&ms->master->dev, "spurious irq, status=0x%.2x\n",
status);
if (((int)get_tbl()) - ms->timestamp < 0)
return FSM_POLL;
ms->message->actual_length += ms->transfer->len;
/* Check if there is another transfer in this message. If there
* aren't then deactivate CS, notify sender, and drop back to idle
* to start the next message. */
if (ms->transfer->transfer_list.next == &ms->message->transfers) {
ms->msg_count++;
mpc52xx_spi_chipsel(ms, 0);
ms->message->status = 0;
ms->message->complete(ms->message->context);
ms->state = mpc52xx_spi_fsmstate_idle;
return FSM_CONTINUE;
}
/* There is another transfer; kick it off */
if (ms->cs_change)
mpc52xx_spi_chipsel(ms, 0);
ms->transfer = container_of(ms->transfer->transfer_list.next,
struct spi_transfer, transfer_list);
mpc52xx_spi_start_transfer(ms);
ms->state = mpc52xx_spi_fsmstate_transfer;
return FSM_CONTINUE;
}
/**
* mpc52xx_spi_fsm_process - Finite State Machine iteration function
* @irq: irq number that triggered the FSM or 0 for polling
* @ms: pointer to mpc52xx_spi driver data
*/
static void mpc52xx_spi_fsm_process(int irq, struct mpc52xx_spi *ms)
{
int rc = FSM_CONTINUE;
u8 status, data;
while (rc == FSM_CONTINUE) {
/* Interrupt cleared by read of STATUS followed by
* read of DATA registers */
status = in_8(ms->regs + SPI_STATUS);
data = in_8(ms->regs + SPI_DATA);
rc = ms->state(irq, ms, status, data);
}
if (rc == FSM_POLL)
schedule_work(&ms->work);
}
/**
* mpc52xx_spi_irq - IRQ handler
*/
static irqreturn_t mpc52xx_spi_irq(int irq, void *_ms)
{
struct mpc52xx_spi *ms = _ms;
spin_lock(&ms->lock);
mpc52xx_spi_fsm_process(irq, ms);
spin_unlock(&ms->lock);
return IRQ_HANDLED;
}
/**
* mpc52xx_spi_wq - Workqueue function for polling the state machine
*/
static void mpc52xx_spi_wq(struct work_struct *work)
{
struct mpc52xx_spi *ms = container_of(work, struct mpc52xx_spi, work);
unsigned long flags;
spin_lock_irqsave(&ms->lock, flags);
mpc52xx_spi_fsm_process(0, ms);
spin_unlock_irqrestore(&ms->lock, flags);
}
/*
* spi_master ops
*/
static int mpc52xx_spi_setup(struct spi_device *spi)
{
if (spi->bits_per_word % 8)
return -EINVAL;
if (spi->mode & ~(SPI_CPOL | SPI_CPHA | SPI_LSB_FIRST))
return -EINVAL;
if (spi->chip_select >= spi->master->num_chipselect)
return -EINVAL;
return 0;
}
static int mpc52xx_spi_transfer(struct spi_device *spi, struct spi_message *m)
{
struct mpc52xx_spi *ms = spi_master_get_devdata(spi->master);
unsigned long flags;
m->actual_length = 0;
m->status = -EINPROGRESS;
spin_lock_irqsave(&ms->lock, flags);
list_add_tail(&m->queue, &ms->queue);
spin_unlock_irqrestore(&ms->lock, flags);
schedule_work(&ms->work);
return 0;
}
/*
* OF Platform Bus Binding
*/
static int __devinit mpc52xx_spi_probe(struct platform_device *op)
{
struct spi_master *master;
struct mpc52xx_spi *ms;
void __iomem *regs;
u8 ctrl1;
int rc, i = 0;
int gpio_cs;
/* MMIO registers */
dev_dbg(&op->dev, "probing mpc5200 SPI device\n");
regs = of_iomap(op->dev.of_node, 0);
if (!regs)
return -ENODEV;
/* initialize the device */
ctrl1 = SPI_CTRL1_SPIE | SPI_CTRL1_SPE | SPI_CTRL1_MSTR;
out_8(regs + SPI_CTRL1, ctrl1);
out_8(regs + SPI_CTRL2, 0x0);
out_8(regs + SPI_DATADIR, 0xe); /* Set output pins */
out_8(regs + SPI_PORTDATA, 0x8); /* Deassert /SS signal */
/* Clear the status register and re-read it to check for a MODF
* failure. This driver cannot currently handle multiple masters
* on the SPI bus. This fault will also occur if the SPI signals
* are not connected to any pins (port_config setting) */
in_8(regs + SPI_STATUS);
out_8(regs + SPI_CTRL1, ctrl1);
in_8(regs + SPI_DATA);
if (in_8(regs + SPI_STATUS) & SPI_STATUS_MODF) {
dev_err(&op->dev, "mode fault; is port_config correct?\n");
rc = -EIO;
goto err_init;
}
dev_dbg(&op->dev, "allocating spi_master struct\n");
master = spi_alloc_master(&op->dev, sizeof *ms);
if (!master) {
rc = -ENOMEM;
goto err_alloc;
}
master->bus_num = -1;
master->setup = mpc52xx_spi_setup;
master->transfer = mpc52xx_spi_transfer;
master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_LSB_FIRST;
master->dev.of_node = op->dev.of_node;
dev_set_drvdata(&op->dev, master);
ms = spi_master_get_devdata(master);
ms->master = master;
ms->regs = regs;
ms->irq0 = irq_of_parse_and_map(op->dev.of_node, 0);
ms->irq1 = irq_of_parse_and_map(op->dev.of_node, 1);
ms->state = mpc52xx_spi_fsmstate_idle;
ms->ipb_freq = mpc5xxx_get_bus_frequency(op->dev.of_node);
ms->gpio_cs_count = of_gpio_count(op->dev.of_node);
if (ms->gpio_cs_count > 0) {
master->num_chipselect = ms->gpio_cs_count;
ms->gpio_cs = kmalloc(ms->gpio_cs_count * sizeof(unsigned int),
GFP_KERNEL);
if (!ms->gpio_cs) {
rc = -ENOMEM;
goto err_alloc;
}
for (i = 0; i < ms->gpio_cs_count; i++) {
gpio_cs = of_get_gpio(op->dev.of_node, i);
if (gpio_cs < 0) {
dev_err(&op->dev,
"could not parse the gpio field "
"in oftree\n");
rc = -ENODEV;
goto err_gpio;
}
rc = gpio_request(gpio_cs, dev_name(&op->dev));
if (rc) {
dev_err(&op->dev,
"can't request spi cs gpio #%d "
"on gpio line %d\n", i, gpio_cs);
goto err_gpio;
}
gpio_direction_output(gpio_cs, 1);
ms->gpio_cs[i] = gpio_cs;
}
} else {
master->num_chipselect = 1;
}
spin_lock_init(&ms->lock);
INIT_LIST_HEAD(&ms->queue);
INIT_WORK(&ms->work, mpc52xx_spi_wq);
/* Decide if interrupts can be used */
if (ms->irq0 && ms->irq1) {
rc = request_irq(ms->irq0, mpc52xx_spi_irq, 0,
"mpc5200-spi-modf", ms);
rc |= request_irq(ms->irq1, mpc52xx_spi_irq, 0,
"mpc5200-spi-spif", ms);
if (rc) {
free_irq(ms->irq0, ms);
free_irq(ms->irq1, ms);
ms->irq0 = ms->irq1 = 0;
}
} else {
/* operate in polled mode */
ms->irq0 = ms->irq1 = 0;
}
if (!ms->irq0)
dev_info(&op->dev, "using polled mode\n");
dev_dbg(&op->dev, "registering spi_master struct\n");
rc = spi_register_master(master);
if (rc)
goto err_register;
dev_info(&ms->master->dev, "registered MPC5200 SPI bus\n");
return rc;
err_register:
dev_err(&ms->master->dev, "initialization failed\n");
spi_master_put(master);
err_gpio:
while (i-- > 0)
gpio_free(ms->gpio_cs[i]);
kfree(ms->gpio_cs);
err_alloc:
err_init:
iounmap(regs);
return rc;
}
static int __devexit mpc52xx_spi_remove(struct platform_device *op)
{
struct spi_master *master = dev_get_drvdata(&op->dev);
struct mpc52xx_spi *ms = spi_master_get_devdata(master);
int i;
free_irq(ms->irq0, ms);
free_irq(ms->irq1, ms);
for (i = 0; i < ms->gpio_cs_count; i++)
gpio_free(ms->gpio_cs[i]);
kfree(ms->gpio_cs);
spi_unregister_master(master);
spi_master_put(master);
iounmap(ms->regs);
return 0;
}
static const struct of_device_id mpc52xx_spi_match[] __devinitconst = {
{ .compatible = "fsl,mpc5200-spi", },
{}
};
MODULE_DEVICE_TABLE(of, mpc52xx_spi_match);
static struct platform_driver mpc52xx_spi_of_driver = {
.driver = {
.name = "mpc52xx-spi",
.owner = THIS_MODULE,
.of_match_table = mpc52xx_spi_match,
},
.probe = mpc52xx_spi_probe,
.remove = __devexit_p(mpc52xx_spi_remove),
};
module_platform_driver(mpc52xx_spi_of_driver);
| gpl-2.0 |
speedbot/android_kernel_htc_golfu | drivers/staging/bcm/InterfaceTx.c | 8142 | 6413 | #include "headers.h"
/*this is transmit call-back(BULK OUT)*/
static void write_bulk_callback(struct urb *urb/*, struct pt_regs *regs*/)
{
PUSB_TCB pTcb= (PUSB_TCB)urb->context;
PS_INTERFACE_ADAPTER psIntfAdapter = pTcb->psIntfAdapter;
CONTROL_MESSAGE *pControlMsg = (CONTROL_MESSAGE *)urb->transfer_buffer;
PMINI_ADAPTER psAdapter = psIntfAdapter->psAdapter ;
BOOLEAN bpowerDownMsg = FALSE ;
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
if (unlikely(netif_msg_tx_done(Adapter)))
pr_info(PFX "%s: transmit status %d\n", Adapter->dev->name, urb->status);
if(urb->status != STATUS_SUCCESS)
{
if(urb->status == -EPIPE)
{
psIntfAdapter->psAdapter->bEndPointHalted = TRUE ;
wake_up(&psIntfAdapter->psAdapter->tx_packet_wait_queue);
}
else
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL,"Tx URB has got cancelled. status :%d", urb->status);
}
}
pTcb->bUsed = FALSE;
atomic_dec(&psIntfAdapter->uNumTcbUsed);
if(TRUE == psAdapter->bPreparingForLowPowerMode)
{
if(((pControlMsg->szData[0] == GO_TO_IDLE_MODE_PAYLOAD) &&
(pControlMsg->szData[1] == TARGET_CAN_GO_TO_IDLE_MODE)))
{
bpowerDownMsg = TRUE ;
//This covers the bus err while Idle Request msg sent down.
if(urb->status != STATUS_SUCCESS)
{
psAdapter->bPreparingForLowPowerMode = FALSE ;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL,"Idle Mode Request msg failed to reach to Modem");
//Signalling the cntrl pkt path in Ioctl
wake_up(&psAdapter->lowpower_mode_wait_queue);
StartInterruptUrb(psIntfAdapter);
goto err_exit;
}
if(psAdapter->bDoSuspend == FALSE)
{
psAdapter->IdleMode = TRUE;
//since going in Idle mode completed hence making this var false;
psAdapter->bPreparingForLowPowerMode = FALSE ;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL, "Host Entered in Idle Mode State...");
//Signalling the cntrl pkt path in Ioctl
wake_up(&psAdapter->lowpower_mode_wait_queue);
}
}
else if((pControlMsg->Leader.Status == LINK_UP_CONTROL_REQ) &&
(pControlMsg->szData[0] == LINK_UP_ACK) &&
(pControlMsg->szData[1] == LINK_SHUTDOWN_REQ_FROM_FIRMWARE) &&
(pControlMsg->szData[2] == SHUTDOWN_ACK_FROM_DRIVER))
{
//This covers the bus err while shutdown Request msg sent down.
if(urb->status != STATUS_SUCCESS)
{
psAdapter->bPreparingForLowPowerMode = FALSE ;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL,"Shutdown Request Msg failed to reach to Modem");
//Signalling the cntrl pkt path in Ioctl
wake_up(&psAdapter->lowpower_mode_wait_queue);
StartInterruptUrb(psIntfAdapter);
goto err_exit;
}
bpowerDownMsg = TRUE ;
if(psAdapter->bDoSuspend == FALSE)
{
psAdapter->bShutStatus = TRUE;
//since going in shutdown mode completed hence making this var false;
psAdapter->bPreparingForLowPowerMode = FALSE ;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL,"Host Entered in shutdown Mode State...");
//Signalling the cntrl pkt path in Ioctl
wake_up(&psAdapter->lowpower_mode_wait_queue);
}
}
if(psAdapter->bDoSuspend && bpowerDownMsg)
{
//issuing bus suspend request
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL,"Issuing the Bus suspend request to USB stack");
psIntfAdapter->bPreparingForBusSuspend = TRUE;
schedule_work(&psIntfAdapter->usbSuspendWork);
}
}
err_exit :
usb_free_coherent(urb->dev, urb->transfer_buffer_length,
urb->transfer_buffer, urb->transfer_dma);
}
static PUSB_TCB GetBulkOutTcb(PS_INTERFACE_ADAPTER psIntfAdapter)
{
PUSB_TCB pTcb = NULL;
UINT index = 0;
if((atomic_read(&psIntfAdapter->uNumTcbUsed) < MAXIMUM_USB_TCB) &&
(psIntfAdapter->psAdapter->StopAllXaction ==FALSE))
{
index = atomic_read(&psIntfAdapter->uCurrTcb);
pTcb = &psIntfAdapter->asUsbTcb[index];
pTcb->bUsed = TRUE;
pTcb->psIntfAdapter= psIntfAdapter;
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL, "Got Tx desc %d used %d",
index, atomic_read(&psIntfAdapter->uNumTcbUsed));
index = (index + 1) % MAXIMUM_USB_TCB;
atomic_set(&psIntfAdapter->uCurrTcb, index);
atomic_inc(&psIntfAdapter->uNumTcbUsed);
}
return pTcb;
}
static int TransmitTcb(PS_INTERFACE_ADAPTER psIntfAdapter, PUSB_TCB pTcb, PVOID data, int len)
{
struct urb *urb = pTcb->urb;
int retval = 0;
urb->transfer_buffer = usb_alloc_coherent(psIntfAdapter->udev, len,
GFP_ATOMIC, &urb->transfer_dma);
if (!urb->transfer_buffer)
{
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter,DBG_TYPE_PRINTK, 0, 0, "Error allocating memory\n");
return -ENOMEM;
}
memcpy(urb->transfer_buffer, data, len);
urb->transfer_buffer_length = len;
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL, "Sending Bulk out packet\n");
//For T3B,INT OUT end point will be used as bulk out end point
if((psIntfAdapter->psAdapter->chip_id == T3B) && (psIntfAdapter->bHighSpeedDevice == TRUE))
{
usb_fill_int_urb(urb, psIntfAdapter->udev,
psIntfAdapter->sBulkOut.bulk_out_pipe,
urb->transfer_buffer, len, write_bulk_callback, pTcb,
psIntfAdapter->sBulkOut.int_out_interval);
}
else
{
usb_fill_bulk_urb(urb, psIntfAdapter->udev,
psIntfAdapter->sBulkOut.bulk_out_pipe,
urb->transfer_buffer, len, write_bulk_callback, pTcb);
}
urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; /* For DMA transfer */
if(FALSE == psIntfAdapter->psAdapter->device_removed &&
FALSE == psIntfAdapter->psAdapter->bEndPointHalted &&
FALSE == psIntfAdapter->bSuspended &&
FALSE == psIntfAdapter->bPreparingForBusSuspend)
{
retval = usb_submit_urb(urb, GFP_ATOMIC);
if (retval)
{
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL, "failed submitting write urb, error %d", retval);
if(retval == -EPIPE)
{
psIntfAdapter->psAdapter->bEndPointHalted = TRUE ;
wake_up(&psIntfAdapter->psAdapter->tx_packet_wait_queue);
}
}
}
return retval;
}
int InterfaceTransmitPacket(PVOID arg, PVOID data, UINT len)
{
PUSB_TCB pTcb= NULL;
PS_INTERFACE_ADAPTER psIntfAdapter = (PS_INTERFACE_ADAPTER)arg;
pTcb= GetBulkOutTcb(psIntfAdapter);
if(pTcb == NULL)
{
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter,DBG_TYPE_PRINTK, 0, 0, "No URB to transmit packet, dropping packet");
return -EFAULT;
}
return TransmitTcb(psIntfAdapter, pTcb, data, len);
}
| gpl-2.0 |
silence-star/android_kernel_nubia_NX503A | drivers/staging/bcm/InterfaceTx.c | 8142 | 6413 | #include "headers.h"
/*this is transmit call-back(BULK OUT)*/
static void write_bulk_callback(struct urb *urb/*, struct pt_regs *regs*/)
{
PUSB_TCB pTcb= (PUSB_TCB)urb->context;
PS_INTERFACE_ADAPTER psIntfAdapter = pTcb->psIntfAdapter;
CONTROL_MESSAGE *pControlMsg = (CONTROL_MESSAGE *)urb->transfer_buffer;
PMINI_ADAPTER psAdapter = psIntfAdapter->psAdapter ;
BOOLEAN bpowerDownMsg = FALSE ;
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
if (unlikely(netif_msg_tx_done(Adapter)))
pr_info(PFX "%s: transmit status %d\n", Adapter->dev->name, urb->status);
if(urb->status != STATUS_SUCCESS)
{
if(urb->status == -EPIPE)
{
psIntfAdapter->psAdapter->bEndPointHalted = TRUE ;
wake_up(&psIntfAdapter->psAdapter->tx_packet_wait_queue);
}
else
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL,"Tx URB has got cancelled. status :%d", urb->status);
}
}
pTcb->bUsed = FALSE;
atomic_dec(&psIntfAdapter->uNumTcbUsed);
if(TRUE == psAdapter->bPreparingForLowPowerMode)
{
if(((pControlMsg->szData[0] == GO_TO_IDLE_MODE_PAYLOAD) &&
(pControlMsg->szData[1] == TARGET_CAN_GO_TO_IDLE_MODE)))
{
bpowerDownMsg = TRUE ;
//This covers the bus err while Idle Request msg sent down.
if(urb->status != STATUS_SUCCESS)
{
psAdapter->bPreparingForLowPowerMode = FALSE ;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL,"Idle Mode Request msg failed to reach to Modem");
//Signalling the cntrl pkt path in Ioctl
wake_up(&psAdapter->lowpower_mode_wait_queue);
StartInterruptUrb(psIntfAdapter);
goto err_exit;
}
if(psAdapter->bDoSuspend == FALSE)
{
psAdapter->IdleMode = TRUE;
//since going in Idle mode completed hence making this var false;
psAdapter->bPreparingForLowPowerMode = FALSE ;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL, "Host Entered in Idle Mode State...");
//Signalling the cntrl pkt path in Ioctl
wake_up(&psAdapter->lowpower_mode_wait_queue);
}
}
else if((pControlMsg->Leader.Status == LINK_UP_CONTROL_REQ) &&
(pControlMsg->szData[0] == LINK_UP_ACK) &&
(pControlMsg->szData[1] == LINK_SHUTDOWN_REQ_FROM_FIRMWARE) &&
(pControlMsg->szData[2] == SHUTDOWN_ACK_FROM_DRIVER))
{
//This covers the bus err while shutdown Request msg sent down.
if(urb->status != STATUS_SUCCESS)
{
psAdapter->bPreparingForLowPowerMode = FALSE ;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL,"Shutdown Request Msg failed to reach to Modem");
//Signalling the cntrl pkt path in Ioctl
wake_up(&psAdapter->lowpower_mode_wait_queue);
StartInterruptUrb(psIntfAdapter);
goto err_exit;
}
bpowerDownMsg = TRUE ;
if(psAdapter->bDoSuspend == FALSE)
{
psAdapter->bShutStatus = TRUE;
//since going in shutdown mode completed hence making this var false;
psAdapter->bPreparingForLowPowerMode = FALSE ;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL,"Host Entered in shutdown Mode State...");
//Signalling the cntrl pkt path in Ioctl
wake_up(&psAdapter->lowpower_mode_wait_queue);
}
}
if(psAdapter->bDoSuspend && bpowerDownMsg)
{
//issuing bus suspend request
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL,"Issuing the Bus suspend request to USB stack");
psIntfAdapter->bPreparingForBusSuspend = TRUE;
schedule_work(&psIntfAdapter->usbSuspendWork);
}
}
err_exit :
usb_free_coherent(urb->dev, urb->transfer_buffer_length,
urb->transfer_buffer, urb->transfer_dma);
}
static PUSB_TCB GetBulkOutTcb(PS_INTERFACE_ADAPTER psIntfAdapter)
{
PUSB_TCB pTcb = NULL;
UINT index = 0;
if((atomic_read(&psIntfAdapter->uNumTcbUsed) < MAXIMUM_USB_TCB) &&
(psIntfAdapter->psAdapter->StopAllXaction ==FALSE))
{
index = atomic_read(&psIntfAdapter->uCurrTcb);
pTcb = &psIntfAdapter->asUsbTcb[index];
pTcb->bUsed = TRUE;
pTcb->psIntfAdapter= psIntfAdapter;
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL, "Got Tx desc %d used %d",
index, atomic_read(&psIntfAdapter->uNumTcbUsed));
index = (index + 1) % MAXIMUM_USB_TCB;
atomic_set(&psIntfAdapter->uCurrTcb, index);
atomic_inc(&psIntfAdapter->uNumTcbUsed);
}
return pTcb;
}
static int TransmitTcb(PS_INTERFACE_ADAPTER psIntfAdapter, PUSB_TCB pTcb, PVOID data, int len)
{
struct urb *urb = pTcb->urb;
int retval = 0;
urb->transfer_buffer = usb_alloc_coherent(psIntfAdapter->udev, len,
GFP_ATOMIC, &urb->transfer_dma);
if (!urb->transfer_buffer)
{
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter,DBG_TYPE_PRINTK, 0, 0, "Error allocating memory\n");
return -ENOMEM;
}
memcpy(urb->transfer_buffer, data, len);
urb->transfer_buffer_length = len;
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL, "Sending Bulk out packet\n");
//For T3B,INT OUT end point will be used as bulk out end point
if((psIntfAdapter->psAdapter->chip_id == T3B) && (psIntfAdapter->bHighSpeedDevice == TRUE))
{
usb_fill_int_urb(urb, psIntfAdapter->udev,
psIntfAdapter->sBulkOut.bulk_out_pipe,
urb->transfer_buffer, len, write_bulk_callback, pTcb,
psIntfAdapter->sBulkOut.int_out_interval);
}
else
{
usb_fill_bulk_urb(urb, psIntfAdapter->udev,
psIntfAdapter->sBulkOut.bulk_out_pipe,
urb->transfer_buffer, len, write_bulk_callback, pTcb);
}
urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; /* For DMA transfer */
if(FALSE == psIntfAdapter->psAdapter->device_removed &&
FALSE == psIntfAdapter->psAdapter->bEndPointHalted &&
FALSE == psIntfAdapter->bSuspended &&
FALSE == psIntfAdapter->bPreparingForBusSuspend)
{
retval = usb_submit_urb(urb, GFP_ATOMIC);
if (retval)
{
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL, "failed submitting write urb, error %d", retval);
if(retval == -EPIPE)
{
psIntfAdapter->psAdapter->bEndPointHalted = TRUE ;
wake_up(&psIntfAdapter->psAdapter->tx_packet_wait_queue);
}
}
}
return retval;
}
int InterfaceTransmitPacket(PVOID arg, PVOID data, UINT len)
{
PUSB_TCB pTcb= NULL;
PS_INTERFACE_ADAPTER psIntfAdapter = (PS_INTERFACE_ADAPTER)arg;
pTcb= GetBulkOutTcb(psIntfAdapter);
if(pTcb == NULL)
{
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter,DBG_TYPE_PRINTK, 0, 0, "No URB to transmit packet, dropping packet");
return -EFAULT;
}
return TransmitTcb(psIntfAdapter, pTcb, data, len);
}
| gpl-2.0 |
HackerOO7/android_kernel_huawei_u8951 | net/atm/atm_misc.c | 9678 | 2635 | /* net/atm/atm_misc.c - Various functions for use by ATM drivers */
/* Written 1995-2000 by Werner Almesberger, EPFL ICA */
#include <linux/module.h>
#include <linux/atm.h>
#include <linux/atmdev.h>
#include <linux/skbuff.h>
#include <linux/sonet.h>
#include <linux/bitops.h>
#include <linux/errno.h>
#include <linux/atomic.h>
int atm_charge(struct atm_vcc *vcc, int truesize)
{
atm_force_charge(vcc, truesize);
if (atomic_read(&sk_atm(vcc)->sk_rmem_alloc) <= sk_atm(vcc)->sk_rcvbuf)
return 1;
atm_return(vcc, truesize);
atomic_inc(&vcc->stats->rx_drop);
return 0;
}
EXPORT_SYMBOL(atm_charge);
struct sk_buff *atm_alloc_charge(struct atm_vcc *vcc, int pdu_size,
gfp_t gfp_flags)
{
struct sock *sk = sk_atm(vcc);
int guess = SKB_TRUESIZE(pdu_size);
atm_force_charge(vcc, guess);
if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) {
struct sk_buff *skb = alloc_skb(pdu_size, gfp_flags);
if (skb) {
atomic_add(skb->truesize-guess,
&sk->sk_rmem_alloc);
return skb;
}
}
atm_return(vcc, guess);
atomic_inc(&vcc->stats->rx_drop);
return NULL;
}
EXPORT_SYMBOL(atm_alloc_charge);
/*
* atm_pcr_goal returns the positive PCR if it should be rounded up, the
* negative PCR if it should be rounded down, and zero if the maximum available
* bandwidth should be used.
*
* The rules are as follows (* = maximum, - = absent (0), x = value "x",
* (x+ = x or next value above x, x- = x or next value below):
*
* min max pcr result min max pcr result
* - - - * (UBR only) x - - x+
* - - * * x - * *
* - - z z- x - z z-
* - * - * x * - x+
* - * * * x * * *
* - * z z- x * z z-
* - y - y- x y - x+
* - y * y- x y * y-
* - y z z- x y z z-
*
* All non-error cases can be converted with the following simple set of rules:
*
* if pcr == z then z-
* else if min == x && pcr == - then x+
* else if max == y then y-
* else *
*/
int atm_pcr_goal(const struct atm_trafprm *tp)
{
if (tp->pcr && tp->pcr != ATM_MAX_PCR)
return -tp->pcr;
if (tp->min_pcr && !tp->pcr)
return tp->min_pcr;
if (tp->max_pcr != ATM_MAX_PCR)
return -tp->max_pcr;
return 0;
}
EXPORT_SYMBOL(atm_pcr_goal);
void sonet_copy_stats(struct k_sonet_stats *from, struct sonet_stats *to)
{
#define __HANDLE_ITEM(i) to->i = atomic_read(&from->i)
__SONET_ITEMS
#undef __HANDLE_ITEM
}
EXPORT_SYMBOL(sonet_copy_stats);
void sonet_subtract_stats(struct k_sonet_stats *from, struct sonet_stats *to)
{
#define __HANDLE_ITEM(i) atomic_sub(to->i, &from->i)
__SONET_ITEMS
#undef __HANDLE_ITEM
}
EXPORT_SYMBOL(sonet_subtract_stats);
| gpl-2.0 |
chuangWu/linux | drivers/xen/manage.c | 207 | 7377 | /*
* Handle extern requests for shutdown, reboot and sysrq
*/
#define pr_fmt(fmt) "xen:" KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/reboot.h>
#include <linux/sysrq.h>
#include <linux/stop_machine.h>
#include <linux/freezer.h>
#include <linux/syscore_ops.h>
#include <linux/export.h>
#include <xen/xen.h>
#include <xen/xenbus.h>
#include <xen/grant_table.h>
#include <xen/events.h>
#include <xen/hvc-console.h>
#include <xen/page.h>
#include <xen/xen-ops.h>
#include <asm/xen/hypercall.h>
#include <asm/xen/hypervisor.h>
enum shutdown_state {
SHUTDOWN_INVALID = -1,
SHUTDOWN_POWEROFF = 0,
SHUTDOWN_SUSPEND = 2,
/* Code 3 is SHUTDOWN_CRASH, which we don't use because the domain can only
report a crash, not be instructed to crash!
HALT is the same as POWEROFF, as far as we're concerned. The tools use
the distinction when we return the reason code to them. */
SHUTDOWN_HALT = 4,
};
/* Ignore multiple shutdown requests. */
static enum shutdown_state shutting_down = SHUTDOWN_INVALID;
struct suspend_info {
int cancelled;
};
static RAW_NOTIFIER_HEAD(xen_resume_notifier);
void xen_resume_notifier_register(struct notifier_block *nb)
{
raw_notifier_chain_register(&xen_resume_notifier, nb);
}
EXPORT_SYMBOL_GPL(xen_resume_notifier_register);
void xen_resume_notifier_unregister(struct notifier_block *nb)
{
raw_notifier_chain_unregister(&xen_resume_notifier, nb);
}
EXPORT_SYMBOL_GPL(xen_resume_notifier_unregister);
#ifdef CONFIG_HIBERNATE_CALLBACKS
static int xen_suspend(void *data)
{
struct suspend_info *si = data;
int err;
BUG_ON(!irqs_disabled());
err = syscore_suspend();
if (err) {
pr_err("%s: system core suspend failed: %d\n", __func__, err);
return err;
}
gnttab_suspend();
xen_arch_pre_suspend();
/*
* This hypercall returns 1 if suspend was cancelled
* or the domain was merely checkpointed, and 0 if it
* is resuming in a new domain.
*/
si->cancelled = HYPERVISOR_suspend(xen_pv_domain()
? virt_to_mfn(xen_start_info)
: 0);
xen_arch_post_suspend(si->cancelled);
gnttab_resume();
if (!si->cancelled) {
xen_irq_resume();
xen_timer_resume();
}
syscore_resume();
return 0;
}
static void do_suspend(void)
{
int err;
struct suspend_info si;
shutting_down = SHUTDOWN_SUSPEND;
err = freeze_processes();
if (err) {
pr_err("%s: freeze processes failed %d\n", __func__, err);
goto out;
}
err = freeze_kernel_threads();
if (err) {
pr_err("%s: freeze kernel threads failed %d\n", __func__, err);
goto out_thaw;
}
err = dpm_suspend_start(PMSG_FREEZE);
if (err) {
pr_err("%s: dpm_suspend_start %d\n", __func__, err);
goto out_thaw;
}
printk(KERN_DEBUG "suspending xenstore...\n");
xs_suspend();
err = dpm_suspend_end(PMSG_FREEZE);
if (err) {
pr_err("dpm_suspend_end failed: %d\n", err);
si.cancelled = 0;
goto out_resume;
}
xen_arch_suspend();
si.cancelled = 1;
err = stop_machine(xen_suspend, &si, cpumask_of(0));
/* Resume console as early as possible. */
if (!si.cancelled)
xen_console_resume();
raw_notifier_call_chain(&xen_resume_notifier, 0, NULL);
dpm_resume_start(si.cancelled ? PMSG_THAW : PMSG_RESTORE);
if (err) {
pr_err("failed to start xen_suspend: %d\n", err);
si.cancelled = 1;
}
xen_arch_resume();
out_resume:
if (!si.cancelled)
xs_resume();
else
xs_suspend_cancel();
dpm_resume_end(si.cancelled ? PMSG_THAW : PMSG_RESTORE);
out_thaw:
thaw_processes();
out:
shutting_down = SHUTDOWN_INVALID;
}
#endif /* CONFIG_HIBERNATE_CALLBACKS */
struct shutdown_handler {
const char *command;
void (*cb)(void);
};
static int poweroff_nb(struct notifier_block *cb, unsigned long code, void *unused)
{
switch (code) {
case SYS_DOWN:
case SYS_HALT:
case SYS_POWER_OFF:
shutting_down = SHUTDOWN_POWEROFF;
default:
break;
}
return NOTIFY_DONE;
}
static void do_poweroff(void)
{
switch (system_state) {
case SYSTEM_BOOTING:
orderly_poweroff(true);
break;
case SYSTEM_RUNNING:
orderly_poweroff(false);
break;
default:
/* Don't do it when we are halting/rebooting. */
pr_info("Ignoring Xen toolstack shutdown.\n");
break;
}
}
static void do_reboot(void)
{
shutting_down = SHUTDOWN_POWEROFF; /* ? */
ctrl_alt_del();
}
static void shutdown_handler(struct xenbus_watch *watch,
const char **vec, unsigned int len)
{
char *str;
struct xenbus_transaction xbt;
int err;
static struct shutdown_handler handlers[] = {
{ "poweroff", do_poweroff },
{ "halt", do_poweroff },
{ "reboot", do_reboot },
#ifdef CONFIG_HIBERNATE_CALLBACKS
{ "suspend", do_suspend },
#endif
{NULL, NULL},
};
static struct shutdown_handler *handler;
if (shutting_down != SHUTDOWN_INVALID)
return;
again:
err = xenbus_transaction_start(&xbt);
if (err)
return;
str = (char *)xenbus_read(xbt, "control", "shutdown", NULL);
/* Ignore read errors and empty reads. */
if (XENBUS_IS_ERR_READ(str)) {
xenbus_transaction_end(xbt, 1);
return;
}
for (handler = &handlers[0]; handler->command; handler++) {
if (strcmp(str, handler->command) == 0)
break;
}
/* Only acknowledge commands which we are prepared to handle. */
if (handler->cb)
xenbus_write(xbt, "control", "shutdown", "");
err = xenbus_transaction_end(xbt, 0);
if (err == -EAGAIN) {
kfree(str);
goto again;
}
if (handler->cb) {
handler->cb();
} else {
pr_info("Ignoring shutdown request: %s\n", str);
shutting_down = SHUTDOWN_INVALID;
}
kfree(str);
}
#ifdef CONFIG_MAGIC_SYSRQ
static void sysrq_handler(struct xenbus_watch *watch, const char **vec,
unsigned int len)
{
char sysrq_key = '\0';
struct xenbus_transaction xbt;
int err;
again:
err = xenbus_transaction_start(&xbt);
if (err)
return;
if (!xenbus_scanf(xbt, "control", "sysrq", "%c", &sysrq_key)) {
pr_err("Unable to read sysrq code in control/sysrq\n");
xenbus_transaction_end(xbt, 1);
return;
}
if (sysrq_key != '\0')
xenbus_printf(xbt, "control", "sysrq", "%c", '\0');
err = xenbus_transaction_end(xbt, 0);
if (err == -EAGAIN)
goto again;
if (sysrq_key != '\0')
handle_sysrq(sysrq_key);
}
static struct xenbus_watch sysrq_watch = {
.node = "control/sysrq",
.callback = sysrq_handler
};
#endif
static struct xenbus_watch shutdown_watch = {
.node = "control/shutdown",
.callback = shutdown_handler
};
static struct notifier_block xen_reboot_nb = {
.notifier_call = poweroff_nb,
};
static int setup_shutdown_watcher(void)
{
int err;
err = register_xenbus_watch(&shutdown_watch);
if (err) {
pr_err("Failed to set shutdown watcher\n");
return err;
}
#ifdef CONFIG_MAGIC_SYSRQ
err = register_xenbus_watch(&sysrq_watch);
if (err) {
pr_err("Failed to set sysrq watcher\n");
return err;
}
#endif
return 0;
}
static int shutdown_event(struct notifier_block *notifier,
unsigned long event,
void *data)
{
setup_shutdown_watcher();
return NOTIFY_DONE;
}
int xen_setup_shutdown_event(void)
{
static struct notifier_block xenstore_notifier = {
.notifier_call = shutdown_event
};
if (!xen_domain())
return -ENODEV;
register_xenstore_notifier(&xenstore_notifier);
register_reboot_notifier(&xen_reboot_nb);
return 0;
}
EXPORT_SYMBOL_GPL(xen_setup_shutdown_event);
subsys_initcall(xen_setup_shutdown_event);
| gpl-2.0 |
unusual-thoughts/linux-xps13 | drivers/net/ethernet/freescale/fman/fman_tgec.c | 207 | 22664 | /*
* Copyright 2008-2015 Freescale Semiconductor Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Freescale Semiconductor nor the
* names of its 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") as published by the Free Software
* Foundation, either version 2 of that License or (at your option) any
* later version.
*
* THIS SOFTWARE IS PROVIDED BY Freescale Semiconductor ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL Freescale Semiconductor BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include "fman_tgec.h"
#include "fman.h"
#include <linux/slab.h>
#include <linux/bitrev.h>
#include <linux/io.h>
#include <linux/crc32.h>
/* Transmit Inter-Packet Gap Length Register (TX_IPG_LENGTH) */
#define TGEC_TX_IPG_LENGTH_MASK 0x000003ff
/* Command and Configuration Register (COMMAND_CONFIG) */
#define CMD_CFG_NO_LEN_CHK 0x00020000
#define CMD_CFG_PAUSE_IGNORE 0x00000100
#define CMF_CFG_CRC_FWD 0x00000040
#define CMD_CFG_PROMIS_EN 0x00000010
#define CMD_CFG_RX_EN 0x00000002
#define CMD_CFG_TX_EN 0x00000001
/* Interrupt Mask Register (IMASK) */
#define TGEC_IMASK_MDIO_SCAN_EVENT 0x00010000
#define TGEC_IMASK_MDIO_CMD_CMPL 0x00008000
#define TGEC_IMASK_REM_FAULT 0x00004000
#define TGEC_IMASK_LOC_FAULT 0x00002000
#define TGEC_IMASK_TX_ECC_ER 0x00001000
#define TGEC_IMASK_TX_FIFO_UNFL 0x00000800
#define TGEC_IMASK_TX_FIFO_OVFL 0x00000400
#define TGEC_IMASK_TX_ER 0x00000200
#define TGEC_IMASK_RX_FIFO_OVFL 0x00000100
#define TGEC_IMASK_RX_ECC_ER 0x00000080
#define TGEC_IMASK_RX_JAB_FRM 0x00000040
#define TGEC_IMASK_RX_OVRSZ_FRM 0x00000020
#define TGEC_IMASK_RX_RUNT_FRM 0x00000010
#define TGEC_IMASK_RX_FRAG_FRM 0x00000008
#define TGEC_IMASK_RX_LEN_ER 0x00000004
#define TGEC_IMASK_RX_CRC_ER 0x00000002
#define TGEC_IMASK_RX_ALIGN_ER 0x00000001
/* Hashtable Control Register (HASHTABLE_CTRL) */
#define TGEC_HASH_MCAST_SHIFT 23
#define TGEC_HASH_MCAST_EN 0x00000200
#define TGEC_HASH_ADR_MSK 0x000001ff
#define DEFAULT_TX_IPG_LENGTH 12
#define DEFAULT_MAX_FRAME_LENGTH 0x600
#define DEFAULT_PAUSE_QUANT 0xf000
/* number of pattern match registers (entries) */
#define TGEC_NUM_OF_PADDRS 1
/* Group address bit indication */
#define GROUP_ADDRESS 0x0000010000000000LL
/* Hash table size (= 32 bits*8 regs) */
#define TGEC_HASH_TABLE_SIZE 512
/* tGEC memory map */
struct tgec_regs {
u32 tgec_id; /* 0x000 Controller ID */
u32 reserved001[1]; /* 0x004 */
u32 command_config; /* 0x008 Control and configuration */
u32 mac_addr_0; /* 0x00c Lower 32 bits of the MAC adr */
u32 mac_addr_1; /* 0x010 Upper 16 bits of the MAC adr */
u32 maxfrm; /* 0x014 Maximum frame length */
u32 pause_quant; /* 0x018 Pause quanta */
u32 rx_fifo_sections; /* 0x01c */
u32 tx_fifo_sections; /* 0x020 */
u32 rx_fifo_almost_f_e; /* 0x024 */
u32 tx_fifo_almost_f_e; /* 0x028 */
u32 hashtable_ctrl; /* 0x02c Hash table control */
u32 mdio_cfg_status; /* 0x030 */
u32 mdio_command; /* 0x034 */
u32 mdio_data; /* 0x038 */
u32 mdio_regaddr; /* 0x03c */
u32 status; /* 0x040 */
u32 tx_ipg_len; /* 0x044 Transmitter inter-packet-gap */
u32 mac_addr_2; /* 0x048 Lower 32 bits of 2nd MAC adr */
u32 mac_addr_3; /* 0x04c Upper 16 bits of 2nd MAC adr */
u32 rx_fifo_ptr_rd; /* 0x050 */
u32 rx_fifo_ptr_wr; /* 0x054 */
u32 tx_fifo_ptr_rd; /* 0x058 */
u32 tx_fifo_ptr_wr; /* 0x05c */
u32 imask; /* 0x060 Interrupt mask */
u32 ievent; /* 0x064 Interrupt event */
u32 udp_port; /* 0x068 Defines a UDP Port number */
u32 type_1588v2; /* 0x06c Type field for 1588v2 */
u32 reserved070[4]; /* 0x070 */
/* 10Ge Statistics Counter */
u32 tfrm_u; /* 80 aFramesTransmittedOK */
u32 tfrm_l; /* 84 aFramesTransmittedOK */
u32 rfrm_u; /* 88 aFramesReceivedOK */
u32 rfrm_l; /* 8c aFramesReceivedOK */
u32 rfcs_u; /* 90 aFrameCheckSequenceErrors */
u32 rfcs_l; /* 94 aFrameCheckSequenceErrors */
u32 raln_u; /* 98 aAlignmentErrors */
u32 raln_l; /* 9c aAlignmentErrors */
u32 txpf_u; /* A0 aPAUSEMACCtrlFramesTransmitted */
u32 txpf_l; /* A4 aPAUSEMACCtrlFramesTransmitted */
u32 rxpf_u; /* A8 aPAUSEMACCtrlFramesReceived */
u32 rxpf_l; /* Ac aPAUSEMACCtrlFramesReceived */
u32 rlong_u; /* B0 aFrameTooLongErrors */
u32 rlong_l; /* B4 aFrameTooLongErrors */
u32 rflr_u; /* B8 aInRangeLengthErrors */
u32 rflr_l; /* Bc aInRangeLengthErrors */
u32 tvlan_u; /* C0 VLANTransmittedOK */
u32 tvlan_l; /* C4 VLANTransmittedOK */
u32 rvlan_u; /* C8 VLANReceivedOK */
u32 rvlan_l; /* Cc VLANReceivedOK */
u32 toct_u; /* D0 if_out_octets */
u32 toct_l; /* D4 if_out_octets */
u32 roct_u; /* D8 if_in_octets */
u32 roct_l; /* Dc if_in_octets */
u32 ruca_u; /* E0 if_in_ucast_pkts */
u32 ruca_l; /* E4 if_in_ucast_pkts */
u32 rmca_u; /* E8 ifInMulticastPkts */
u32 rmca_l; /* Ec ifInMulticastPkts */
u32 rbca_u; /* F0 ifInBroadcastPkts */
u32 rbca_l; /* F4 ifInBroadcastPkts */
u32 terr_u; /* F8 if_out_errors */
u32 terr_l; /* Fc if_out_errors */
u32 reserved100[2]; /* 100-108 */
u32 tuca_u; /* 108 if_out_ucast_pkts */
u32 tuca_l; /* 10c if_out_ucast_pkts */
u32 tmca_u; /* 110 ifOutMulticastPkts */
u32 tmca_l; /* 114 ifOutMulticastPkts */
u32 tbca_u; /* 118 ifOutBroadcastPkts */
u32 tbca_l; /* 11c ifOutBroadcastPkts */
u32 rdrp_u; /* 120 etherStatsDropEvents */
u32 rdrp_l; /* 124 etherStatsDropEvents */
u32 reoct_u; /* 128 etherStatsOctets */
u32 reoct_l; /* 12c etherStatsOctets */
u32 rpkt_u; /* 130 etherStatsPkts */
u32 rpkt_l; /* 134 etherStatsPkts */
u32 trund_u; /* 138 etherStatsUndersizePkts */
u32 trund_l; /* 13c etherStatsUndersizePkts */
u32 r64_u; /* 140 etherStatsPkts64Octets */
u32 r64_l; /* 144 etherStatsPkts64Octets */
u32 r127_u; /* 148 etherStatsPkts65to127Octets */
u32 r127_l; /* 14c etherStatsPkts65to127Octets */
u32 r255_u; /* 150 etherStatsPkts128to255Octets */
u32 r255_l; /* 154 etherStatsPkts128to255Octets */
u32 r511_u; /* 158 etherStatsPkts256to511Octets */
u32 r511_l; /* 15c etherStatsPkts256to511Octets */
u32 r1023_u; /* 160 etherStatsPkts512to1023Octets */
u32 r1023_l; /* 164 etherStatsPkts512to1023Octets */
u32 r1518_u; /* 168 etherStatsPkts1024to1518Octets */
u32 r1518_l; /* 16c etherStatsPkts1024to1518Octets */
u32 r1519x_u; /* 170 etherStatsPkts1519toX */
u32 r1519x_l; /* 174 etherStatsPkts1519toX */
u32 trovr_u; /* 178 etherStatsOversizePkts */
u32 trovr_l; /* 17c etherStatsOversizePkts */
u32 trjbr_u; /* 180 etherStatsJabbers */
u32 trjbr_l; /* 184 etherStatsJabbers */
u32 trfrg_u; /* 188 etherStatsFragments */
u32 trfrg_l; /* 18C etherStatsFragments */
u32 rerr_u; /* 190 if_in_errors */
u32 rerr_l; /* 194 if_in_errors */
};
struct tgec_cfg {
bool pause_ignore;
bool promiscuous_mode_enable;
u16 max_frame_length;
u16 pause_quant;
u32 tx_ipg_length;
};
struct fman_mac {
/* Pointer to the memory mapped registers. */
struct tgec_regs __iomem *regs;
/* MAC address of device; */
u64 addr;
u16 max_speed;
void *dev_id; /* device cookie used by the exception cbs */
fman_mac_exception_cb *exception_cb;
fman_mac_exception_cb *event_cb;
/* pointer to driver's global address hash table */
struct eth_hash_t *multicast_addr_hash;
/* pointer to driver's individual address hash table */
struct eth_hash_t *unicast_addr_hash;
u8 mac_id;
u32 exceptions;
struct tgec_cfg *cfg;
void *fm;
struct fman_rev_info fm_rev_info;
};
static void set_mac_address(struct tgec_regs __iomem *regs, u8 *adr)
{
u32 tmp0, tmp1;
tmp0 = (u32)(adr[0] | adr[1] << 8 | adr[2] << 16 | adr[3] << 24);
tmp1 = (u32)(adr[4] | adr[5] << 8);
iowrite32be(tmp0, ®s->mac_addr_0);
iowrite32be(tmp1, ®s->mac_addr_1);
}
static void set_dflts(struct tgec_cfg *cfg)
{
cfg->promiscuous_mode_enable = false;
cfg->pause_ignore = false;
cfg->tx_ipg_length = DEFAULT_TX_IPG_LENGTH;
cfg->max_frame_length = DEFAULT_MAX_FRAME_LENGTH;
cfg->pause_quant = DEFAULT_PAUSE_QUANT;
}
static int init(struct tgec_regs __iomem *regs, struct tgec_cfg *cfg,
u32 exception_mask)
{
u32 tmp;
/* Config */
tmp = CMF_CFG_CRC_FWD;
if (cfg->promiscuous_mode_enable)
tmp |= CMD_CFG_PROMIS_EN;
if (cfg->pause_ignore)
tmp |= CMD_CFG_PAUSE_IGNORE;
/* Payload length check disable */
tmp |= CMD_CFG_NO_LEN_CHK;
iowrite32be(tmp, ®s->command_config);
/* Max Frame Length */
iowrite32be((u32)cfg->max_frame_length, ®s->maxfrm);
/* Pause Time */
iowrite32be(cfg->pause_quant, ®s->pause_quant);
/* clear all pending events and set-up interrupts */
iowrite32be(0xffffffff, ®s->ievent);
iowrite32be(ioread32be(®s->imask) | exception_mask, ®s->imask);
return 0;
}
static int check_init_parameters(struct fman_mac *tgec)
{
if (tgec->max_speed < SPEED_10000) {
pr_err("10G MAC driver only support 10G speed\n");
return -EINVAL;
}
if (tgec->addr == 0) {
pr_err("Ethernet 10G MAC Must have valid MAC Address\n");
return -EINVAL;
}
if (!tgec->exception_cb) {
pr_err("uninitialized exception_cb\n");
return -EINVAL;
}
if (!tgec->event_cb) {
pr_err("uninitialized event_cb\n");
return -EINVAL;
}
return 0;
}
static int get_exception_flag(enum fman_mac_exceptions exception)
{
u32 bit_mask;
switch (exception) {
case FM_MAC_EX_10G_MDIO_SCAN_EVENT:
bit_mask = TGEC_IMASK_MDIO_SCAN_EVENT;
break;
case FM_MAC_EX_10G_MDIO_CMD_CMPL:
bit_mask = TGEC_IMASK_MDIO_CMD_CMPL;
break;
case FM_MAC_EX_10G_REM_FAULT:
bit_mask = TGEC_IMASK_REM_FAULT;
break;
case FM_MAC_EX_10G_LOC_FAULT:
bit_mask = TGEC_IMASK_LOC_FAULT;
break;
case FM_MAC_EX_10G_TX_ECC_ER:
bit_mask = TGEC_IMASK_TX_ECC_ER;
break;
case FM_MAC_EX_10G_TX_FIFO_UNFL:
bit_mask = TGEC_IMASK_TX_FIFO_UNFL;
break;
case FM_MAC_EX_10G_TX_FIFO_OVFL:
bit_mask = TGEC_IMASK_TX_FIFO_OVFL;
break;
case FM_MAC_EX_10G_TX_ER:
bit_mask = TGEC_IMASK_TX_ER;
break;
case FM_MAC_EX_10G_RX_FIFO_OVFL:
bit_mask = TGEC_IMASK_RX_FIFO_OVFL;
break;
case FM_MAC_EX_10G_RX_ECC_ER:
bit_mask = TGEC_IMASK_RX_ECC_ER;
break;
case FM_MAC_EX_10G_RX_JAB_FRM:
bit_mask = TGEC_IMASK_RX_JAB_FRM;
break;
case FM_MAC_EX_10G_RX_OVRSZ_FRM:
bit_mask = TGEC_IMASK_RX_OVRSZ_FRM;
break;
case FM_MAC_EX_10G_RX_RUNT_FRM:
bit_mask = TGEC_IMASK_RX_RUNT_FRM;
break;
case FM_MAC_EX_10G_RX_FRAG_FRM:
bit_mask = TGEC_IMASK_RX_FRAG_FRM;
break;
case FM_MAC_EX_10G_RX_LEN_ER:
bit_mask = TGEC_IMASK_RX_LEN_ER;
break;
case FM_MAC_EX_10G_RX_CRC_ER:
bit_mask = TGEC_IMASK_RX_CRC_ER;
break;
case FM_MAC_EX_10G_RX_ALIGN_ER:
bit_mask = TGEC_IMASK_RX_ALIGN_ER;
break;
default:
bit_mask = 0;
break;
}
return bit_mask;
}
static void tgec_err_exception(void *handle)
{
struct fman_mac *tgec = (struct fman_mac *)handle;
struct tgec_regs __iomem *regs = tgec->regs;
u32 event;
/* do not handle MDIO events */
event = ioread32be(®s->ievent) &
~(TGEC_IMASK_MDIO_SCAN_EVENT |
TGEC_IMASK_MDIO_CMD_CMPL);
event &= ioread32be(®s->imask);
iowrite32be(event, ®s->ievent);
if (event & TGEC_IMASK_REM_FAULT)
tgec->exception_cb(tgec->dev_id, FM_MAC_EX_10G_REM_FAULT);
if (event & TGEC_IMASK_LOC_FAULT)
tgec->exception_cb(tgec->dev_id, FM_MAC_EX_10G_LOC_FAULT);
if (event & TGEC_IMASK_TX_ECC_ER)
tgec->exception_cb(tgec->dev_id, FM_MAC_EX_10G_TX_ECC_ER);
if (event & TGEC_IMASK_TX_FIFO_UNFL)
tgec->exception_cb(tgec->dev_id, FM_MAC_EX_10G_TX_FIFO_UNFL);
if (event & TGEC_IMASK_TX_FIFO_OVFL)
tgec->exception_cb(tgec->dev_id, FM_MAC_EX_10G_TX_FIFO_OVFL);
if (event & TGEC_IMASK_TX_ER)
tgec->exception_cb(tgec->dev_id, FM_MAC_EX_10G_TX_ER);
if (event & TGEC_IMASK_RX_FIFO_OVFL)
tgec->exception_cb(tgec->dev_id, FM_MAC_EX_10G_RX_FIFO_OVFL);
if (event & TGEC_IMASK_RX_ECC_ER)
tgec->exception_cb(tgec->dev_id, FM_MAC_EX_10G_RX_ECC_ER);
if (event & TGEC_IMASK_RX_JAB_FRM)
tgec->exception_cb(tgec->dev_id, FM_MAC_EX_10G_RX_JAB_FRM);
if (event & TGEC_IMASK_RX_OVRSZ_FRM)
tgec->exception_cb(tgec->dev_id, FM_MAC_EX_10G_RX_OVRSZ_FRM);
if (event & TGEC_IMASK_RX_RUNT_FRM)
tgec->exception_cb(tgec->dev_id, FM_MAC_EX_10G_RX_RUNT_FRM);
if (event & TGEC_IMASK_RX_FRAG_FRM)
tgec->exception_cb(tgec->dev_id, FM_MAC_EX_10G_RX_FRAG_FRM);
if (event & TGEC_IMASK_RX_LEN_ER)
tgec->exception_cb(tgec->dev_id, FM_MAC_EX_10G_RX_LEN_ER);
if (event & TGEC_IMASK_RX_CRC_ER)
tgec->exception_cb(tgec->dev_id, FM_MAC_EX_10G_RX_CRC_ER);
if (event & TGEC_IMASK_RX_ALIGN_ER)
tgec->exception_cb(tgec->dev_id, FM_MAC_EX_10G_RX_ALIGN_ER);
}
static void free_init_resources(struct fman_mac *tgec)
{
fman_unregister_intr(tgec->fm, FMAN_MOD_MAC, tgec->mac_id,
FMAN_INTR_TYPE_ERR);
/* release the driver's group hash table */
free_hash_table(tgec->multicast_addr_hash);
tgec->multicast_addr_hash = NULL;
/* release the driver's individual hash table */
free_hash_table(tgec->unicast_addr_hash);
tgec->unicast_addr_hash = NULL;
}
static bool is_init_done(struct tgec_cfg *cfg)
{
/* Checks if tGEC driver parameters were initialized */
if (!cfg)
return true;
return false;
}
int tgec_enable(struct fman_mac *tgec, enum comm_mode mode)
{
struct tgec_regs __iomem *regs = tgec->regs;
u32 tmp;
if (!is_init_done(tgec->cfg))
return -EINVAL;
tmp = ioread32be(®s->command_config);
if (mode & COMM_MODE_RX)
tmp |= CMD_CFG_RX_EN;
if (mode & COMM_MODE_TX)
tmp |= CMD_CFG_TX_EN;
iowrite32be(tmp, ®s->command_config);
return 0;
}
int tgec_disable(struct fman_mac *tgec, enum comm_mode mode)
{
struct tgec_regs __iomem *regs = tgec->regs;
u32 tmp;
if (!is_init_done(tgec->cfg))
return -EINVAL;
tmp = ioread32be(®s->command_config);
if (mode & COMM_MODE_RX)
tmp &= ~CMD_CFG_RX_EN;
if (mode & COMM_MODE_TX)
tmp &= ~CMD_CFG_TX_EN;
iowrite32be(tmp, ®s->command_config);
return 0;
}
int tgec_set_promiscuous(struct fman_mac *tgec, bool new_val)
{
struct tgec_regs __iomem *regs = tgec->regs;
u32 tmp;
if (!is_init_done(tgec->cfg))
return -EINVAL;
tmp = ioread32be(®s->command_config);
if (new_val)
tmp |= CMD_CFG_PROMIS_EN;
else
tmp &= ~CMD_CFG_PROMIS_EN;
iowrite32be(tmp, ®s->command_config);
return 0;
}
int tgec_cfg_max_frame_len(struct fman_mac *tgec, u16 new_val)
{
if (is_init_done(tgec->cfg))
return -EINVAL;
tgec->cfg->max_frame_length = new_val;
return 0;
}
int tgec_set_tx_pause_frames(struct fman_mac *tgec, u8 __maybe_unused priority,
u16 pause_time, u16 __maybe_unused thresh_time)
{
struct tgec_regs __iomem *regs = tgec->regs;
if (!is_init_done(tgec->cfg))
return -EINVAL;
iowrite32be((u32)pause_time, ®s->pause_quant);
return 0;
}
int tgec_accept_rx_pause_frames(struct fman_mac *tgec, bool en)
{
struct tgec_regs __iomem *regs = tgec->regs;
u32 tmp;
if (!is_init_done(tgec->cfg))
return -EINVAL;
tmp = ioread32be(®s->command_config);
if (!en)
tmp |= CMD_CFG_PAUSE_IGNORE;
else
tmp &= ~CMD_CFG_PAUSE_IGNORE;
iowrite32be(tmp, ®s->command_config);
return 0;
}
int tgec_modify_mac_address(struct fman_mac *tgec, enet_addr_t *p_enet_addr)
{
if (!is_init_done(tgec->cfg))
return -EINVAL;
tgec->addr = ENET_ADDR_TO_UINT64(*p_enet_addr);
set_mac_address(tgec->regs, (u8 *)(*p_enet_addr));
return 0;
}
int tgec_add_hash_mac_address(struct fman_mac *tgec, enet_addr_t *eth_addr)
{
struct tgec_regs __iomem *regs = tgec->regs;
struct eth_hash_entry *hash_entry;
u32 crc = 0xFFFFFFFF, hash;
u64 addr;
if (!is_init_done(tgec->cfg))
return -EINVAL;
addr = ENET_ADDR_TO_UINT64(*eth_addr);
if (!(addr & GROUP_ADDRESS)) {
/* Unicast addresses not supported in hash */
pr_err("Unicast Address\n");
return -EINVAL;
}
/* CRC calculation */
crc = crc32_le(crc, (u8 *)eth_addr, ETH_ALEN);
crc = bitrev32(crc);
/* Take 9 MSB bits */
hash = (crc >> TGEC_HASH_MCAST_SHIFT) & TGEC_HASH_ADR_MSK;
/* Create element to be added to the driver hash table */
hash_entry = kmalloc(sizeof(*hash_entry), GFP_KERNEL);
if (!hash_entry)
return -ENOMEM;
hash_entry->addr = addr;
INIT_LIST_HEAD(&hash_entry->node);
list_add_tail(&hash_entry->node,
&tgec->multicast_addr_hash->lsts[hash]);
iowrite32be((hash | TGEC_HASH_MCAST_EN), ®s->hashtable_ctrl);
return 0;
}
int tgec_del_hash_mac_address(struct fman_mac *tgec, enet_addr_t *eth_addr)
{
struct tgec_regs __iomem *regs = tgec->regs;
struct eth_hash_entry *hash_entry = NULL;
struct list_head *pos;
u32 crc = 0xFFFFFFFF, hash;
u64 addr;
if (!is_init_done(tgec->cfg))
return -EINVAL;
addr = ((*(u64 *)eth_addr) >> 16);
/* CRC calculation */
crc = crc32_le(crc, (u8 *)eth_addr, ETH_ALEN);
crc = bitrev32(crc);
/* Take 9 MSB bits */
hash = (crc >> TGEC_HASH_MCAST_SHIFT) & TGEC_HASH_ADR_MSK;
list_for_each(pos, &tgec->multicast_addr_hash->lsts[hash]) {
hash_entry = ETH_HASH_ENTRY_OBJ(pos);
if (hash_entry->addr == addr) {
list_del_init(&hash_entry->node);
kfree(hash_entry);
break;
}
}
if (list_empty(&tgec->multicast_addr_hash->lsts[hash]))
iowrite32be((hash & ~TGEC_HASH_MCAST_EN),
®s->hashtable_ctrl);
return 0;
}
int tgec_get_version(struct fman_mac *tgec, u32 *mac_version)
{
struct tgec_regs __iomem *regs = tgec->regs;
if (!is_init_done(tgec->cfg))
return -EINVAL;
*mac_version = ioread32be(®s->tgec_id);
return 0;
}
int tgec_set_exception(struct fman_mac *tgec,
enum fman_mac_exceptions exception, bool enable)
{
struct tgec_regs __iomem *regs = tgec->regs;
u32 bit_mask = 0;
if (!is_init_done(tgec->cfg))
return -EINVAL;
bit_mask = get_exception_flag(exception);
if (bit_mask) {
if (enable)
tgec->exceptions |= bit_mask;
else
tgec->exceptions &= ~bit_mask;
} else {
pr_err("Undefined exception\n");
return -EINVAL;
}
if (enable)
iowrite32be(ioread32be(®s->imask) | bit_mask, ®s->imask);
else
iowrite32be(ioread32be(®s->imask) & ~bit_mask, ®s->imask);
return 0;
}
int tgec_init(struct fman_mac *tgec)
{
struct tgec_cfg *cfg;
enet_addr_t eth_addr;
int err;
if (is_init_done(tgec->cfg))
return -EINVAL;
if (DEFAULT_RESET_ON_INIT &&
(fman_reset_mac(tgec->fm, tgec->mac_id) != 0)) {
pr_err("Can't reset MAC!\n");
return -EINVAL;
}
err = check_init_parameters(tgec);
if (err)
return err;
cfg = tgec->cfg;
MAKE_ENET_ADDR_FROM_UINT64(tgec->addr, eth_addr);
set_mac_address(tgec->regs, (u8 *)eth_addr);
/* interrupts */
/* FM_10G_REM_N_LCL_FLT_EX_10GMAC_ERRATA_SW005 Errata workaround */
if (tgec->fm_rev_info.major <= 2)
tgec->exceptions &= ~(TGEC_IMASK_REM_FAULT |
TGEC_IMASK_LOC_FAULT);
err = init(tgec->regs, cfg, tgec->exceptions);
if (err) {
free_init_resources(tgec);
pr_err("TGEC version doesn't support this i/f mode\n");
return err;
}
/* Max Frame Length */
err = fman_set_mac_max_frame(tgec->fm, tgec->mac_id,
cfg->max_frame_length);
if (err) {
pr_err("Setting max frame length FAILED\n");
free_init_resources(tgec);
return -EINVAL;
}
/* FM_TX_FIFO_CORRUPTION_ERRATA_10GMAC_A007 Errata workaround */
if (tgec->fm_rev_info.major == 2) {
struct tgec_regs __iomem *regs = tgec->regs;
u32 tmp;
/* restore the default tx ipg Length */
tmp = (ioread32be(®s->tx_ipg_len) &
~TGEC_TX_IPG_LENGTH_MASK) | 12;
iowrite32be(tmp, ®s->tx_ipg_len);
}
tgec->multicast_addr_hash = alloc_hash_table(TGEC_HASH_TABLE_SIZE);
if (!tgec->multicast_addr_hash) {
free_init_resources(tgec);
pr_err("allocation hash table is FAILED\n");
return -ENOMEM;
}
tgec->unicast_addr_hash = alloc_hash_table(TGEC_HASH_TABLE_SIZE);
if (!tgec->unicast_addr_hash) {
free_init_resources(tgec);
pr_err("allocation hash table is FAILED\n");
return -ENOMEM;
}
fman_register_intr(tgec->fm, FMAN_MOD_MAC, tgec->mac_id,
FMAN_INTR_TYPE_ERR, tgec_err_exception, tgec);
kfree(cfg);
tgec->cfg = NULL;
return 0;
}
int tgec_free(struct fman_mac *tgec)
{
free_init_resources(tgec);
if (tgec->cfg)
tgec->cfg = NULL;
kfree(tgec->cfg);
kfree(tgec);
return 0;
}
struct fman_mac *tgec_config(struct fman_mac_params *params)
{
struct fman_mac *tgec;
struct tgec_cfg *cfg;
void __iomem *base_addr;
base_addr = params->base_addr;
/* allocate memory for the UCC GETH data structure. */
tgec = kzalloc(sizeof(*tgec), GFP_KERNEL);
if (!tgec)
return NULL;
/* allocate memory for the 10G MAC driver parameters data structure. */
cfg = kzalloc(sizeof(*cfg), GFP_KERNEL);
if (!cfg) {
tgec_free(tgec);
return NULL;
}
/* Plant parameter structure pointer */
tgec->cfg = cfg;
set_dflts(cfg);
tgec->regs = base_addr;
tgec->addr = ENET_ADDR_TO_UINT64(params->addr);
tgec->max_speed = params->max_speed;
tgec->mac_id = params->mac_id;
tgec->exceptions = (TGEC_IMASK_MDIO_SCAN_EVENT |
TGEC_IMASK_REM_FAULT |
TGEC_IMASK_LOC_FAULT |
TGEC_IMASK_TX_ECC_ER |
TGEC_IMASK_TX_FIFO_UNFL |
TGEC_IMASK_TX_FIFO_OVFL |
TGEC_IMASK_TX_ER |
TGEC_IMASK_RX_FIFO_OVFL |
TGEC_IMASK_RX_ECC_ER |
TGEC_IMASK_RX_JAB_FRM |
TGEC_IMASK_RX_OVRSZ_FRM |
TGEC_IMASK_RX_RUNT_FRM |
TGEC_IMASK_RX_FRAG_FRM |
TGEC_IMASK_RX_CRC_ER |
TGEC_IMASK_RX_ALIGN_ER);
tgec->exception_cb = params->exception_cb;
tgec->event_cb = params->event_cb;
tgec->dev_id = params->dev_id;
tgec->fm = params->fm;
/* Save FMan revision */
fman_get_revision(tgec->fm, &tgec->fm_rev_info);
return tgec;
}
| gpl-2.0 |
crpalmer/android_kernel_sony_tetra | drivers/usb/host/r8a66597-hcd.c | 463 | 64485 | /*
* R8A66597 HCD (Host Controller Driver)
*
* Copyright (C) 2006-2007 Renesas Solutions Corp.
* Portions Copyright (C) 2004 Psion Teklogix (for NetBook PRO)
* Portions Copyright (C) 2004-2005 David Brownell
* Portions Copyright (C) 1999 Roman Weissgaerber
*
* Author : Yoshihiro Shimoda <yoshihiro.shimoda.uh@renesas.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.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/timer.h>
#include <linux/delay.h>
#include <linux/list.h>
#include <linux/interrupt.h>
#include <linux/usb.h>
#include <linux/usb/hcd.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/mm.h>
#include <linux/irq.h>
#include <linux/slab.h>
#include <asm/cacheflush.h>
#include "r8a66597.h"
MODULE_DESCRIPTION("R8A66597 USB Host Controller Driver");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Yoshihiro Shimoda");
MODULE_ALIAS("platform:r8a66597_hcd");
#define DRIVER_VERSION "2009-05-26"
static const char hcd_name[] = "r8a66597_hcd";
static void packet_write(struct r8a66597 *r8a66597, u16 pipenum);
static int r8a66597_get_frame(struct usb_hcd *hcd);
/* this function must be called with interrupt disabled */
static void enable_pipe_irq(struct r8a66597 *r8a66597, u16 pipenum,
unsigned long reg)
{
u16 tmp;
tmp = r8a66597_read(r8a66597, INTENB0);
r8a66597_bclr(r8a66597, BEMPE | NRDYE | BRDYE, INTENB0);
r8a66597_bset(r8a66597, 1 << pipenum, reg);
r8a66597_write(r8a66597, tmp, INTENB0);
}
/* this function must be called with interrupt disabled */
static void disable_pipe_irq(struct r8a66597 *r8a66597, u16 pipenum,
unsigned long reg)
{
u16 tmp;
tmp = r8a66597_read(r8a66597, INTENB0);
r8a66597_bclr(r8a66597, BEMPE | NRDYE | BRDYE, INTENB0);
r8a66597_bclr(r8a66597, 1 << pipenum, reg);
r8a66597_write(r8a66597, tmp, INTENB0);
}
static void set_devadd_reg(struct r8a66597 *r8a66597, u8 r8a66597_address,
u16 usbspd, u8 upphub, u8 hubport, int port)
{
u16 val;
unsigned long devadd_reg = get_devadd_addr(r8a66597_address);
val = (upphub << 11) | (hubport << 8) | (usbspd << 6) | (port & 0x0001);
r8a66597_write(r8a66597, val, devadd_reg);
}
static int r8a66597_clock_enable(struct r8a66597 *r8a66597)
{
u16 tmp;
int i = 0;
if (r8a66597->pdata->on_chip) {
clk_enable(r8a66597->clk);
do {
r8a66597_write(r8a66597, SCKE, SYSCFG0);
tmp = r8a66597_read(r8a66597, SYSCFG0);
if (i++ > 1000) {
printk(KERN_ERR "r8a66597: reg access fail.\n");
return -ENXIO;
}
} while ((tmp & SCKE) != SCKE);
r8a66597_write(r8a66597, 0x04, 0x02);
} else {
do {
r8a66597_write(r8a66597, USBE, SYSCFG0);
tmp = r8a66597_read(r8a66597, SYSCFG0);
if (i++ > 1000) {
printk(KERN_ERR "r8a66597: reg access fail.\n");
return -ENXIO;
}
} while ((tmp & USBE) != USBE);
r8a66597_bclr(r8a66597, USBE, SYSCFG0);
r8a66597_mdfy(r8a66597, get_xtal_from_pdata(r8a66597->pdata),
XTAL, SYSCFG0);
i = 0;
r8a66597_bset(r8a66597, XCKE, SYSCFG0);
do {
msleep(1);
tmp = r8a66597_read(r8a66597, SYSCFG0);
if (i++ > 500) {
printk(KERN_ERR "r8a66597: reg access fail.\n");
return -ENXIO;
}
} while ((tmp & SCKE) != SCKE);
}
return 0;
}
static void r8a66597_clock_disable(struct r8a66597 *r8a66597)
{
r8a66597_bclr(r8a66597, SCKE, SYSCFG0);
udelay(1);
if (r8a66597->pdata->on_chip) {
clk_disable(r8a66597->clk);
} else {
r8a66597_bclr(r8a66597, PLLC, SYSCFG0);
r8a66597_bclr(r8a66597, XCKE, SYSCFG0);
r8a66597_bclr(r8a66597, USBE, SYSCFG0);
}
}
static void r8a66597_enable_port(struct r8a66597 *r8a66597, int port)
{
u16 val;
val = port ? DRPD : DCFM | DRPD;
r8a66597_bset(r8a66597, val, get_syscfg_reg(port));
r8a66597_bset(r8a66597, HSE, get_syscfg_reg(port));
r8a66597_write(r8a66597, BURST | CPU_ADR_RD_WR, get_dmacfg_reg(port));
r8a66597_bclr(r8a66597, DTCHE, get_intenb_reg(port));
r8a66597_bset(r8a66597, ATTCHE, get_intenb_reg(port));
}
static void r8a66597_disable_port(struct r8a66597 *r8a66597, int port)
{
u16 val, tmp;
r8a66597_write(r8a66597, 0, get_intenb_reg(port));
r8a66597_write(r8a66597, 0, get_intsts_reg(port));
r8a66597_port_power(r8a66597, port, 0);
do {
tmp = r8a66597_read(r8a66597, SOFCFG) & EDGESTS;
udelay(640);
} while (tmp == EDGESTS);
val = port ? DRPD : DCFM | DRPD;
r8a66597_bclr(r8a66597, val, get_syscfg_reg(port));
r8a66597_bclr(r8a66597, HSE, get_syscfg_reg(port));
}
static int enable_controller(struct r8a66597 *r8a66597)
{
int ret, port;
u16 vif = r8a66597->pdata->vif ? LDRV : 0;
u16 irq_sense = r8a66597->irq_sense_low ? INTL : 0;
u16 endian = r8a66597->pdata->endian ? BIGEND : 0;
ret = r8a66597_clock_enable(r8a66597);
if (ret < 0)
return ret;
r8a66597_bset(r8a66597, vif & LDRV, PINCFG);
r8a66597_bset(r8a66597, USBE, SYSCFG0);
r8a66597_bset(r8a66597, BEMPE | NRDYE | BRDYE, INTENB0);
r8a66597_bset(r8a66597, irq_sense & INTL, SOFCFG);
r8a66597_bset(r8a66597, BRDY0, BRDYENB);
r8a66597_bset(r8a66597, BEMP0, BEMPENB);
r8a66597_bset(r8a66597, endian & BIGEND, CFIFOSEL);
r8a66597_bset(r8a66597, endian & BIGEND, D0FIFOSEL);
r8a66597_bset(r8a66597, endian & BIGEND, D1FIFOSEL);
r8a66597_bset(r8a66597, TRNENSEL, SOFCFG);
r8a66597_bset(r8a66597, SIGNE | SACKE, INTENB1);
for (port = 0; port < r8a66597->max_root_hub; port++)
r8a66597_enable_port(r8a66597, port);
return 0;
}
static void disable_controller(struct r8a66597 *r8a66597)
{
int port;
/* disable interrupts */
r8a66597_write(r8a66597, 0, INTENB0);
r8a66597_write(r8a66597, 0, INTENB1);
r8a66597_write(r8a66597, 0, BRDYENB);
r8a66597_write(r8a66597, 0, BEMPENB);
r8a66597_write(r8a66597, 0, NRDYENB);
/* clear status */
r8a66597_write(r8a66597, 0, BRDYSTS);
r8a66597_write(r8a66597, 0, NRDYSTS);
r8a66597_write(r8a66597, 0, BEMPSTS);
for (port = 0; port < r8a66597->max_root_hub; port++)
r8a66597_disable_port(r8a66597, port);
r8a66597_clock_disable(r8a66597);
}
static int get_parent_r8a66597_address(struct r8a66597 *r8a66597,
struct usb_device *udev)
{
struct r8a66597_device *dev;
if (udev->parent && udev->parent->devnum != 1)
udev = udev->parent;
dev = dev_get_drvdata(&udev->dev);
if (dev)
return dev->address;
else
return 0;
}
static int is_child_device(char *devpath)
{
return (devpath[2] ? 1 : 0);
}
static int is_hub_limit(char *devpath)
{
return ((strlen(devpath) >= 4) ? 1 : 0);
}
static void get_port_number(struct r8a66597 *r8a66597,
char *devpath, u16 *root_port, u16 *hub_port)
{
if (root_port) {
*root_port = (devpath[0] & 0x0F) - 1;
if (*root_port >= r8a66597->max_root_hub)
printk(KERN_ERR "r8a66597: Illegal root port number.\n");
}
if (hub_port)
*hub_port = devpath[2] & 0x0F;
}
static u16 get_r8a66597_usb_speed(enum usb_device_speed speed)
{
u16 usbspd = 0;
switch (speed) {
case USB_SPEED_LOW:
usbspd = LSMODE;
break;
case USB_SPEED_FULL:
usbspd = FSMODE;
break;
case USB_SPEED_HIGH:
usbspd = HSMODE;
break;
default:
printk(KERN_ERR "r8a66597: unknown speed\n");
break;
}
return usbspd;
}
static void set_child_connect_map(struct r8a66597 *r8a66597, int address)
{
int idx;
idx = address / 32;
r8a66597->child_connect_map[idx] |= 1 << (address % 32);
}
static void put_child_connect_map(struct r8a66597 *r8a66597, int address)
{
int idx;
idx = address / 32;
r8a66597->child_connect_map[idx] &= ~(1 << (address % 32));
}
static void set_pipe_reg_addr(struct r8a66597_pipe *pipe, u8 dma_ch)
{
u16 pipenum = pipe->info.pipenum;
const unsigned long fifoaddr[] = {D0FIFO, D1FIFO, CFIFO};
const unsigned long fifosel[] = {D0FIFOSEL, D1FIFOSEL, CFIFOSEL};
const unsigned long fifoctr[] = {D0FIFOCTR, D1FIFOCTR, CFIFOCTR};
if (dma_ch > R8A66597_PIPE_NO_DMA) /* dma fifo not use? */
dma_ch = R8A66597_PIPE_NO_DMA;
pipe->fifoaddr = fifoaddr[dma_ch];
pipe->fifosel = fifosel[dma_ch];
pipe->fifoctr = fifoctr[dma_ch];
if (pipenum == 0)
pipe->pipectr = DCPCTR;
else
pipe->pipectr = get_pipectr_addr(pipenum);
if (check_bulk_or_isoc(pipenum)) {
pipe->pipetre = get_pipetre_addr(pipenum);
pipe->pipetrn = get_pipetrn_addr(pipenum);
} else {
pipe->pipetre = 0;
pipe->pipetrn = 0;
}
}
static struct r8a66597_device *
get_urb_to_r8a66597_dev(struct r8a66597 *r8a66597, struct urb *urb)
{
if (usb_pipedevice(urb->pipe) == 0)
return &r8a66597->device0;
return dev_get_drvdata(&urb->dev->dev);
}
static int make_r8a66597_device(struct r8a66597 *r8a66597,
struct urb *urb, u8 addr)
{
struct r8a66597_device *dev;
int usb_address = urb->setup_packet[2]; /* urb->pipe is address 0 */
dev = kzalloc(sizeof(struct r8a66597_device), GFP_ATOMIC);
if (dev == NULL)
return -ENOMEM;
dev_set_drvdata(&urb->dev->dev, dev);
dev->udev = urb->dev;
dev->address = addr;
dev->usb_address = usb_address;
dev->state = USB_STATE_ADDRESS;
dev->ep_in_toggle = 0;
dev->ep_out_toggle = 0;
INIT_LIST_HEAD(&dev->device_list);
list_add_tail(&dev->device_list, &r8a66597->child_device);
get_port_number(r8a66597, urb->dev->devpath,
&dev->root_port, &dev->hub_port);
if (!is_child_device(urb->dev->devpath))
r8a66597->root_hub[dev->root_port].dev = dev;
set_devadd_reg(r8a66597, dev->address,
get_r8a66597_usb_speed(urb->dev->speed),
get_parent_r8a66597_address(r8a66597, urb->dev),
dev->hub_port, dev->root_port);
return 0;
}
/* this function must be called with interrupt disabled */
static u8 alloc_usb_address(struct r8a66597 *r8a66597, struct urb *urb)
{
u8 addr; /* R8A66597's address */
struct r8a66597_device *dev;
if (is_hub_limit(urb->dev->devpath)) {
dev_err(&urb->dev->dev, "External hub limit reached.\n");
return 0;
}
dev = get_urb_to_r8a66597_dev(r8a66597, urb);
if (dev && dev->state >= USB_STATE_ADDRESS)
return dev->address;
for (addr = 1; addr <= R8A66597_MAX_DEVICE; addr++) {
if (r8a66597->address_map & (1 << addr))
continue;
dev_dbg(&urb->dev->dev, "alloc_address: r8a66597_addr=%d\n", addr);
r8a66597->address_map |= 1 << addr;
if (make_r8a66597_device(r8a66597, urb, addr) < 0)
return 0;
return addr;
}
dev_err(&urb->dev->dev,
"cannot communicate with a USB device more than 10.(%x)\n",
r8a66597->address_map);
return 0;
}
/* this function must be called with interrupt disabled */
static void free_usb_address(struct r8a66597 *r8a66597,
struct r8a66597_device *dev, int reset)
{
int port;
if (!dev)
return;
dev_dbg(&dev->udev->dev, "free_addr: addr=%d\n", dev->address);
dev->state = USB_STATE_DEFAULT;
r8a66597->address_map &= ~(1 << dev->address);
dev->address = 0;
/*
* Only when resetting USB, it is necessary to erase drvdata. When
* a usb device with usb hub is disconnect, "dev->udev" is already
* freed on usb_desconnect(). So we cannot access the data.
*/
if (reset)
dev_set_drvdata(&dev->udev->dev, NULL);
list_del(&dev->device_list);
kfree(dev);
for (port = 0; port < r8a66597->max_root_hub; port++) {
if (r8a66597->root_hub[port].dev == dev) {
r8a66597->root_hub[port].dev = NULL;
break;
}
}
}
static void r8a66597_reg_wait(struct r8a66597 *r8a66597, unsigned long reg,
u16 mask, u16 loop)
{
u16 tmp;
int i = 0;
do {
tmp = r8a66597_read(r8a66597, reg);
if (i++ > 1000000) {
printk(KERN_ERR "r8a66597: register%lx, loop %x "
"is timeout\n", reg, loop);
break;
}
ndelay(1);
} while ((tmp & mask) != loop);
}
/* this function must be called with interrupt disabled */
static void pipe_start(struct r8a66597 *r8a66597, struct r8a66597_pipe *pipe)
{
u16 tmp;
tmp = r8a66597_read(r8a66597, pipe->pipectr) & PID;
if ((pipe->info.pipenum != 0) & ((tmp & PID_STALL) != 0)) /* stall? */
r8a66597_mdfy(r8a66597, PID_NAK, PID, pipe->pipectr);
r8a66597_mdfy(r8a66597, PID_BUF, PID, pipe->pipectr);
}
/* this function must be called with interrupt disabled */
static void pipe_stop(struct r8a66597 *r8a66597, struct r8a66597_pipe *pipe)
{
u16 tmp;
tmp = r8a66597_read(r8a66597, pipe->pipectr) & PID;
if ((tmp & PID_STALL11) != PID_STALL11) /* force stall? */
r8a66597_mdfy(r8a66597, PID_STALL, PID, pipe->pipectr);
r8a66597_mdfy(r8a66597, PID_NAK, PID, pipe->pipectr);
r8a66597_reg_wait(r8a66597, pipe->pipectr, PBUSY, 0);
}
/* this function must be called with interrupt disabled */
static void clear_all_buffer(struct r8a66597 *r8a66597,
struct r8a66597_pipe *pipe)
{
u16 tmp;
if (!pipe || pipe->info.pipenum == 0)
return;
pipe_stop(r8a66597, pipe);
r8a66597_bset(r8a66597, ACLRM, pipe->pipectr);
tmp = r8a66597_read(r8a66597, pipe->pipectr);
tmp = r8a66597_read(r8a66597, pipe->pipectr);
tmp = r8a66597_read(r8a66597, pipe->pipectr);
r8a66597_bclr(r8a66597, ACLRM, pipe->pipectr);
}
/* this function must be called with interrupt disabled */
static void r8a66597_pipe_toggle(struct r8a66597 *r8a66597,
struct r8a66597_pipe *pipe, int toggle)
{
if (toggle)
r8a66597_bset(r8a66597, SQSET, pipe->pipectr);
else
r8a66597_bset(r8a66597, SQCLR, pipe->pipectr);
}
static inline unsigned short mbw_value(struct r8a66597 *r8a66597)
{
if (r8a66597->pdata->on_chip)
return MBW_32;
else
return MBW_16;
}
/* this function must be called with interrupt disabled */
static inline void cfifo_change(struct r8a66597 *r8a66597, u16 pipenum)
{
unsigned short mbw = mbw_value(r8a66597);
r8a66597_mdfy(r8a66597, mbw | pipenum, mbw | CURPIPE, CFIFOSEL);
r8a66597_reg_wait(r8a66597, CFIFOSEL, CURPIPE, pipenum);
}
/* this function must be called with interrupt disabled */
static inline void fifo_change_from_pipe(struct r8a66597 *r8a66597,
struct r8a66597_pipe *pipe)
{
unsigned short mbw = mbw_value(r8a66597);
cfifo_change(r8a66597, 0);
r8a66597_mdfy(r8a66597, mbw | 0, mbw | CURPIPE, D0FIFOSEL);
r8a66597_mdfy(r8a66597, mbw | 0, mbw | CURPIPE, D1FIFOSEL);
r8a66597_mdfy(r8a66597, mbw | pipe->info.pipenum, mbw | CURPIPE,
pipe->fifosel);
r8a66597_reg_wait(r8a66597, pipe->fifosel, CURPIPE, pipe->info.pipenum);
}
static u16 r8a66597_get_pipenum(struct urb *urb, struct usb_host_endpoint *hep)
{
struct r8a66597_pipe *pipe = hep->hcpriv;
if (usb_pipeendpoint(urb->pipe) == 0)
return 0;
else
return pipe->info.pipenum;
}
static u16 get_urb_to_r8a66597_addr(struct r8a66597 *r8a66597, struct urb *urb)
{
struct r8a66597_device *dev = get_urb_to_r8a66597_dev(r8a66597, urb);
return (usb_pipedevice(urb->pipe) == 0) ? 0 : dev->address;
}
static unsigned short *get_toggle_pointer(struct r8a66597_device *dev,
int urb_pipe)
{
if (!dev)
return NULL;
return usb_pipein(urb_pipe) ? &dev->ep_in_toggle : &dev->ep_out_toggle;
}
/* this function must be called with interrupt disabled */
static void pipe_toggle_set(struct r8a66597 *r8a66597,
struct r8a66597_pipe *pipe,
struct urb *urb, int set)
{
struct r8a66597_device *dev = get_urb_to_r8a66597_dev(r8a66597, urb);
unsigned char endpoint = usb_pipeendpoint(urb->pipe);
unsigned short *toggle = get_toggle_pointer(dev, urb->pipe);
if (!toggle)
return;
if (set)
*toggle |= 1 << endpoint;
else
*toggle &= ~(1 << endpoint);
}
/* this function must be called with interrupt disabled */
static void pipe_toggle_save(struct r8a66597 *r8a66597,
struct r8a66597_pipe *pipe,
struct urb *urb)
{
if (r8a66597_read(r8a66597, pipe->pipectr) & SQMON)
pipe_toggle_set(r8a66597, pipe, urb, 1);
else
pipe_toggle_set(r8a66597, pipe, urb, 0);
}
/* this function must be called with interrupt disabled */
static void pipe_toggle_restore(struct r8a66597 *r8a66597,
struct r8a66597_pipe *pipe,
struct urb *urb)
{
struct r8a66597_device *dev = get_urb_to_r8a66597_dev(r8a66597, urb);
unsigned char endpoint = usb_pipeendpoint(urb->pipe);
unsigned short *toggle = get_toggle_pointer(dev, urb->pipe);
if (!toggle)
return;
r8a66597_pipe_toggle(r8a66597, pipe, *toggle & (1 << endpoint));
}
/* this function must be called with interrupt disabled */
static void pipe_buffer_setting(struct r8a66597 *r8a66597,
struct r8a66597_pipe_info *info)
{
u16 val = 0;
if (info->pipenum == 0)
return;
r8a66597_bset(r8a66597, ACLRM, get_pipectr_addr(info->pipenum));
r8a66597_bclr(r8a66597, ACLRM, get_pipectr_addr(info->pipenum));
r8a66597_write(r8a66597, info->pipenum, PIPESEL);
if (!info->dir_in)
val |= R8A66597_DIR;
if (info->type == R8A66597_BULK && info->dir_in)
val |= R8A66597_DBLB | R8A66597_SHTNAK;
val |= info->type | info->epnum;
r8a66597_write(r8a66597, val, PIPECFG);
r8a66597_write(r8a66597, (info->buf_bsize << 10) | (info->bufnum),
PIPEBUF);
r8a66597_write(r8a66597, make_devsel(info->address) | info->maxpacket,
PIPEMAXP);
r8a66597_write(r8a66597, info->interval, PIPEPERI);
}
/* this function must be called with interrupt disabled */
static void pipe_setting(struct r8a66597 *r8a66597, struct r8a66597_td *td)
{
struct r8a66597_pipe_info *info;
struct urb *urb = td->urb;
if (td->pipenum > 0) {
info = &td->pipe->info;
cfifo_change(r8a66597, 0);
pipe_buffer_setting(r8a66597, info);
if (!usb_gettoggle(urb->dev, usb_pipeendpoint(urb->pipe),
usb_pipeout(urb->pipe)) &&
!usb_pipecontrol(urb->pipe)) {
r8a66597_pipe_toggle(r8a66597, td->pipe, 0);
pipe_toggle_set(r8a66597, td->pipe, urb, 0);
clear_all_buffer(r8a66597, td->pipe);
usb_settoggle(urb->dev, usb_pipeendpoint(urb->pipe),
usb_pipeout(urb->pipe), 1);
}
pipe_toggle_restore(r8a66597, td->pipe, urb);
}
}
/* this function must be called with interrupt disabled */
static u16 get_empty_pipenum(struct r8a66597 *r8a66597,
struct usb_endpoint_descriptor *ep)
{
u16 array[R8A66597_MAX_NUM_PIPE], i = 0, min;
memset(array, 0, sizeof(array));
switch (usb_endpoint_type(ep)) {
case USB_ENDPOINT_XFER_BULK:
if (usb_endpoint_dir_in(ep))
array[i++] = 4;
else {
array[i++] = 3;
array[i++] = 5;
}
break;
case USB_ENDPOINT_XFER_INT:
if (usb_endpoint_dir_in(ep)) {
array[i++] = 6;
array[i++] = 7;
array[i++] = 8;
} else
array[i++] = 9;
break;
case USB_ENDPOINT_XFER_ISOC:
if (usb_endpoint_dir_in(ep))
array[i++] = 2;
else
array[i++] = 1;
break;
default:
printk(KERN_ERR "r8a66597: Illegal type\n");
return 0;
}
i = 1;
min = array[0];
while (array[i] != 0) {
if (r8a66597->pipe_cnt[min] > r8a66597->pipe_cnt[array[i]])
min = array[i];
i++;
}
return min;
}
static u16 get_r8a66597_type(__u8 type)
{
u16 r8a66597_type;
switch (type) {
case USB_ENDPOINT_XFER_BULK:
r8a66597_type = R8A66597_BULK;
break;
case USB_ENDPOINT_XFER_INT:
r8a66597_type = R8A66597_INT;
break;
case USB_ENDPOINT_XFER_ISOC:
r8a66597_type = R8A66597_ISO;
break;
default:
printk(KERN_ERR "r8a66597: Illegal type\n");
r8a66597_type = 0x0000;
break;
}
return r8a66597_type;
}
static u16 get_bufnum(u16 pipenum)
{
u16 bufnum = 0;
if (pipenum == 0)
bufnum = 0;
else if (check_bulk_or_isoc(pipenum))
bufnum = 8 + (pipenum - 1) * R8A66597_BUF_BSIZE*2;
else if (check_interrupt(pipenum))
bufnum = 4 + (pipenum - 6);
else
printk(KERN_ERR "r8a66597: Illegal pipenum (%d)\n", pipenum);
return bufnum;
}
static u16 get_buf_bsize(u16 pipenum)
{
u16 buf_bsize = 0;
if (pipenum == 0)
buf_bsize = 3;
else if (check_bulk_or_isoc(pipenum))
buf_bsize = R8A66597_BUF_BSIZE - 1;
else if (check_interrupt(pipenum))
buf_bsize = 0;
else
printk(KERN_ERR "r8a66597: Illegal pipenum (%d)\n", pipenum);
return buf_bsize;
}
/* this function must be called with interrupt disabled */
static void enable_r8a66597_pipe_dma(struct r8a66597 *r8a66597,
struct r8a66597_device *dev,
struct r8a66597_pipe *pipe,
struct urb *urb)
{
int i;
struct r8a66597_pipe_info *info = &pipe->info;
unsigned short mbw = mbw_value(r8a66597);
/* pipe dma is only for external controlles */
if (r8a66597->pdata->on_chip)
return;
if ((pipe->info.pipenum != 0) && (info->type != R8A66597_INT)) {
for (i = 0; i < R8A66597_MAX_DMA_CHANNEL; i++) {
if ((r8a66597->dma_map & (1 << i)) != 0)
continue;
dev_info(&dev->udev->dev,
"address %d, EndpointAddress 0x%02x use "
"DMA FIFO\n", usb_pipedevice(urb->pipe),
info->dir_in ?
USB_ENDPOINT_DIR_MASK + info->epnum
: info->epnum);
r8a66597->dma_map |= 1 << i;
dev->dma_map |= 1 << i;
set_pipe_reg_addr(pipe, i);
cfifo_change(r8a66597, 0);
r8a66597_mdfy(r8a66597, mbw | pipe->info.pipenum,
mbw | CURPIPE, pipe->fifosel);
r8a66597_reg_wait(r8a66597, pipe->fifosel, CURPIPE,
pipe->info.pipenum);
r8a66597_bset(r8a66597, BCLR, pipe->fifoctr);
break;
}
}
}
/* this function must be called with interrupt disabled */
static void enable_r8a66597_pipe(struct r8a66597 *r8a66597, struct urb *urb,
struct usb_host_endpoint *hep,
struct r8a66597_pipe_info *info)
{
struct r8a66597_device *dev = get_urb_to_r8a66597_dev(r8a66597, urb);
struct r8a66597_pipe *pipe = hep->hcpriv;
dev_dbg(&dev->udev->dev, "enable_pipe:\n");
pipe->info = *info;
set_pipe_reg_addr(pipe, R8A66597_PIPE_NO_DMA);
r8a66597->pipe_cnt[pipe->info.pipenum]++;
dev->pipe_cnt[pipe->info.pipenum]++;
enable_r8a66597_pipe_dma(r8a66597, dev, pipe, urb);
}
static void r8a66597_urb_done(struct r8a66597 *r8a66597, struct urb *urb,
int status)
__releases(r8a66597->lock)
__acquires(r8a66597->lock)
{
if (usb_pipein(urb->pipe) && usb_pipetype(urb->pipe) != PIPE_CONTROL) {
void *ptr;
for (ptr = urb->transfer_buffer;
ptr < urb->transfer_buffer + urb->transfer_buffer_length;
ptr += PAGE_SIZE)
flush_dcache_page(virt_to_page(ptr));
}
usb_hcd_unlink_urb_from_ep(r8a66597_to_hcd(r8a66597), urb);
spin_unlock(&r8a66597->lock);
usb_hcd_giveback_urb(r8a66597_to_hcd(r8a66597), urb, status);
spin_lock(&r8a66597->lock);
}
/* this function must be called with interrupt disabled */
static void force_dequeue(struct r8a66597 *r8a66597, u16 pipenum, u16 address)
{
struct r8a66597_td *td, *next;
struct urb *urb;
struct list_head *list = &r8a66597->pipe_queue[pipenum];
if (list_empty(list))
return;
list_for_each_entry_safe(td, next, list, queue) {
if (td->address != address)
continue;
urb = td->urb;
list_del(&td->queue);
kfree(td);
if (urb)
r8a66597_urb_done(r8a66597, urb, -ENODEV);
break;
}
}
/* this function must be called with interrupt disabled */
static void disable_r8a66597_pipe_all(struct r8a66597 *r8a66597,
struct r8a66597_device *dev)
{
int check_ep0 = 0;
u16 pipenum;
if (!dev)
return;
for (pipenum = 1; pipenum < R8A66597_MAX_NUM_PIPE; pipenum++) {
if (!dev->pipe_cnt[pipenum])
continue;
if (!check_ep0) {
check_ep0 = 1;
force_dequeue(r8a66597, 0, dev->address);
}
r8a66597->pipe_cnt[pipenum] -= dev->pipe_cnt[pipenum];
dev->pipe_cnt[pipenum] = 0;
force_dequeue(r8a66597, pipenum, dev->address);
}
dev_dbg(&dev->udev->dev, "disable_pipe\n");
r8a66597->dma_map &= ~(dev->dma_map);
dev->dma_map = 0;
}
static u16 get_interval(struct urb *urb, __u8 interval)
{
u16 time = 1;
int i;
if (urb->dev->speed == USB_SPEED_HIGH) {
if (interval > IITV)
time = IITV;
else
time = interval ? interval - 1 : 0;
} else {
if (interval > 128) {
time = IITV;
} else {
/* calculate the nearest value for PIPEPERI */
for (i = 0; i < 7; i++) {
if ((1 << i) < interval &&
(1 << (i + 1) > interval))
time = 1 << i;
}
}
}
return time;
}
static unsigned long get_timer_interval(struct urb *urb, __u8 interval)
{
__u8 i;
unsigned long time = 1;
if (usb_pipeisoc(urb->pipe))
return 0;
if (get_r8a66597_usb_speed(urb->dev->speed) == HSMODE) {
for (i = 0; i < (interval - 1); i++)
time *= 2;
time = time * 125 / 1000; /* uSOF -> msec */
} else {
time = interval;
}
return time;
}
/* this function must be called with interrupt disabled */
static void init_pipe_info(struct r8a66597 *r8a66597, struct urb *urb,
struct usb_host_endpoint *hep,
struct usb_endpoint_descriptor *ep)
{
struct r8a66597_pipe_info info;
info.pipenum = get_empty_pipenum(r8a66597, ep);
info.address = get_urb_to_r8a66597_addr(r8a66597, urb);
info.epnum = usb_endpoint_num(ep);
info.maxpacket = usb_endpoint_maxp(ep);
info.type = get_r8a66597_type(usb_endpoint_type(ep));
info.bufnum = get_bufnum(info.pipenum);
info.buf_bsize = get_buf_bsize(info.pipenum);
if (info.type == R8A66597_BULK) {
info.interval = 0;
info.timer_interval = 0;
} else {
info.interval = get_interval(urb, ep->bInterval);
info.timer_interval = get_timer_interval(urb, ep->bInterval);
}
if (usb_endpoint_dir_in(ep))
info.dir_in = 1;
else
info.dir_in = 0;
enable_r8a66597_pipe(r8a66597, urb, hep, &info);
}
static void init_pipe_config(struct r8a66597 *r8a66597, struct urb *urb)
{
struct r8a66597_device *dev;
dev = get_urb_to_r8a66597_dev(r8a66597, urb);
dev->state = USB_STATE_CONFIGURED;
}
static void pipe_irq_enable(struct r8a66597 *r8a66597, struct urb *urb,
u16 pipenum)
{
if (pipenum == 0 && usb_pipeout(urb->pipe))
enable_irq_empty(r8a66597, pipenum);
else
enable_irq_ready(r8a66597, pipenum);
if (!usb_pipeisoc(urb->pipe))
enable_irq_nrdy(r8a66597, pipenum);
}
static void pipe_irq_disable(struct r8a66597 *r8a66597, u16 pipenum)
{
disable_irq_ready(r8a66597, pipenum);
disable_irq_nrdy(r8a66597, pipenum);
}
static void r8a66597_root_hub_start_polling(struct r8a66597 *r8a66597)
{
mod_timer(&r8a66597->rh_timer,
jiffies + msecs_to_jiffies(R8A66597_RH_POLL_TIME));
}
static void start_root_hub_sampling(struct r8a66597 *r8a66597, int port,
int connect)
{
struct r8a66597_root_hub *rh = &r8a66597->root_hub[port];
rh->old_syssts = r8a66597_read(r8a66597, get_syssts_reg(port)) & LNST;
rh->scount = R8A66597_MAX_SAMPLING;
if (connect)
rh->port |= USB_PORT_STAT_CONNECTION;
else
rh->port &= ~USB_PORT_STAT_CONNECTION;
rh->port |= USB_PORT_STAT_C_CONNECTION << 16;
r8a66597_root_hub_start_polling(r8a66597);
}
/* this function must be called with interrupt disabled */
static void r8a66597_check_syssts(struct r8a66597 *r8a66597, int port,
u16 syssts)
__releases(r8a66597->lock)
__acquires(r8a66597->lock)
{
if (syssts == SE0) {
r8a66597_write(r8a66597, ~ATTCH, get_intsts_reg(port));
r8a66597_bset(r8a66597, ATTCHE, get_intenb_reg(port));
} else {
if (syssts == FS_JSTS)
r8a66597_bset(r8a66597, HSE, get_syscfg_reg(port));
else if (syssts == LS_JSTS)
r8a66597_bclr(r8a66597, HSE, get_syscfg_reg(port));
r8a66597_write(r8a66597, ~DTCH, get_intsts_reg(port));
r8a66597_bset(r8a66597, DTCHE, get_intenb_reg(port));
if (r8a66597->bus_suspended)
usb_hcd_resume_root_hub(r8a66597_to_hcd(r8a66597));
}
spin_unlock(&r8a66597->lock);
usb_hcd_poll_rh_status(r8a66597_to_hcd(r8a66597));
spin_lock(&r8a66597->lock);
}
/* this function must be called with interrupt disabled */
static void r8a66597_usb_connect(struct r8a66597 *r8a66597, int port)
{
u16 speed = get_rh_usb_speed(r8a66597, port);
struct r8a66597_root_hub *rh = &r8a66597->root_hub[port];
rh->port &= ~(USB_PORT_STAT_HIGH_SPEED | USB_PORT_STAT_LOW_SPEED);
if (speed == HSMODE)
rh->port |= USB_PORT_STAT_HIGH_SPEED;
else if (speed == LSMODE)
rh->port |= USB_PORT_STAT_LOW_SPEED;
rh->port &= ~USB_PORT_STAT_RESET;
rh->port |= USB_PORT_STAT_ENABLE;
}
/* this function must be called with interrupt disabled */
static void r8a66597_usb_disconnect(struct r8a66597 *r8a66597, int port)
{
struct r8a66597_device *dev = r8a66597->root_hub[port].dev;
disable_r8a66597_pipe_all(r8a66597, dev);
free_usb_address(r8a66597, dev, 0);
start_root_hub_sampling(r8a66597, port, 0);
}
/* this function must be called with interrupt disabled */
static void prepare_setup_packet(struct r8a66597 *r8a66597,
struct r8a66597_td *td)
{
int i;
__le16 *p = (__le16 *)td->urb->setup_packet;
unsigned long setup_addr = USBREQ;
r8a66597_write(r8a66597, make_devsel(td->address) | td->maxpacket,
DCPMAXP);
r8a66597_write(r8a66597, ~(SIGN | SACK), INTSTS1);
for (i = 0; i < 4; i++) {
r8a66597_write(r8a66597, le16_to_cpu(p[i]), setup_addr);
setup_addr += 2;
}
r8a66597_write(r8a66597, SUREQ, DCPCTR);
}
/* this function must be called with interrupt disabled */
static void prepare_packet_read(struct r8a66597 *r8a66597,
struct r8a66597_td *td)
{
struct urb *urb = td->urb;
if (usb_pipecontrol(urb->pipe)) {
r8a66597_bclr(r8a66597, R8A66597_DIR, DCPCFG);
r8a66597_mdfy(r8a66597, 0, ISEL | CURPIPE, CFIFOSEL);
r8a66597_reg_wait(r8a66597, CFIFOSEL, CURPIPE, 0);
if (urb->actual_length == 0) {
r8a66597_pipe_toggle(r8a66597, td->pipe, 1);
r8a66597_write(r8a66597, BCLR, CFIFOCTR);
}
pipe_irq_disable(r8a66597, td->pipenum);
pipe_start(r8a66597, td->pipe);
pipe_irq_enable(r8a66597, urb, td->pipenum);
} else {
if (urb->actual_length == 0) {
pipe_irq_disable(r8a66597, td->pipenum);
pipe_setting(r8a66597, td);
pipe_stop(r8a66597, td->pipe);
r8a66597_write(r8a66597, ~(1 << td->pipenum), BRDYSTS);
if (td->pipe->pipetre) {
r8a66597_write(r8a66597, TRCLR,
td->pipe->pipetre);
r8a66597_write(r8a66597,
DIV_ROUND_UP
(urb->transfer_buffer_length,
td->maxpacket),
td->pipe->pipetrn);
r8a66597_bset(r8a66597, TRENB,
td->pipe->pipetre);
}
pipe_start(r8a66597, td->pipe);
pipe_irq_enable(r8a66597, urb, td->pipenum);
}
}
}
/* this function must be called with interrupt disabled */
static void prepare_packet_write(struct r8a66597 *r8a66597,
struct r8a66597_td *td)
{
u16 tmp;
struct urb *urb = td->urb;
if (usb_pipecontrol(urb->pipe)) {
pipe_stop(r8a66597, td->pipe);
r8a66597_bset(r8a66597, R8A66597_DIR, DCPCFG);
r8a66597_mdfy(r8a66597, ISEL, ISEL | CURPIPE, CFIFOSEL);
r8a66597_reg_wait(r8a66597, CFIFOSEL, CURPIPE, 0);
if (urb->actual_length == 0) {
r8a66597_pipe_toggle(r8a66597, td->pipe, 1);
r8a66597_write(r8a66597, BCLR, CFIFOCTR);
}
} else {
if (urb->actual_length == 0)
pipe_setting(r8a66597, td);
if (td->pipe->pipetre)
r8a66597_bclr(r8a66597, TRENB, td->pipe->pipetre);
}
r8a66597_write(r8a66597, ~(1 << td->pipenum), BRDYSTS);
fifo_change_from_pipe(r8a66597, td->pipe);
tmp = r8a66597_read(r8a66597, td->pipe->fifoctr);
if (unlikely((tmp & FRDY) == 0))
pipe_irq_enable(r8a66597, urb, td->pipenum);
else
packet_write(r8a66597, td->pipenum);
pipe_start(r8a66597, td->pipe);
}
/* this function must be called with interrupt disabled */
static void prepare_status_packet(struct r8a66597 *r8a66597,
struct r8a66597_td *td)
{
struct urb *urb = td->urb;
r8a66597_pipe_toggle(r8a66597, td->pipe, 1);
pipe_stop(r8a66597, td->pipe);
if (urb->setup_packet[0] & USB_ENDPOINT_DIR_MASK) {
r8a66597_bset(r8a66597, R8A66597_DIR, DCPCFG);
r8a66597_mdfy(r8a66597, ISEL, ISEL | CURPIPE, CFIFOSEL);
r8a66597_reg_wait(r8a66597, CFIFOSEL, CURPIPE, 0);
r8a66597_write(r8a66597, ~BEMP0, BEMPSTS);
r8a66597_write(r8a66597, BCLR | BVAL, CFIFOCTR);
enable_irq_empty(r8a66597, 0);
} else {
r8a66597_bclr(r8a66597, R8A66597_DIR, DCPCFG);
r8a66597_mdfy(r8a66597, 0, ISEL | CURPIPE, CFIFOSEL);
r8a66597_reg_wait(r8a66597, CFIFOSEL, CURPIPE, 0);
r8a66597_write(r8a66597, BCLR, CFIFOCTR);
enable_irq_ready(r8a66597, 0);
}
enable_irq_nrdy(r8a66597, 0);
pipe_start(r8a66597, td->pipe);
}
static int is_set_address(unsigned char *setup_packet)
{
if (((setup_packet[0] & USB_TYPE_MASK) == USB_TYPE_STANDARD) &&
setup_packet[1] == USB_REQ_SET_ADDRESS)
return 1;
else
return 0;
}
/* this function must be called with interrupt disabled */
static int start_transfer(struct r8a66597 *r8a66597, struct r8a66597_td *td)
{
BUG_ON(!td);
switch (td->type) {
case USB_PID_SETUP:
if (is_set_address(td->urb->setup_packet)) {
td->set_address = 1;
td->urb->setup_packet[2] = alloc_usb_address(r8a66597,
td->urb);
if (td->urb->setup_packet[2] == 0)
return -EPIPE;
}
prepare_setup_packet(r8a66597, td);
break;
case USB_PID_IN:
prepare_packet_read(r8a66597, td);
break;
case USB_PID_OUT:
prepare_packet_write(r8a66597, td);
break;
case USB_PID_ACK:
prepare_status_packet(r8a66597, td);
break;
default:
printk(KERN_ERR "r8a66597: invalid type.\n");
break;
}
return 0;
}
static int check_transfer_finish(struct r8a66597_td *td, struct urb *urb)
{
if (usb_pipeisoc(urb->pipe)) {
if (urb->number_of_packets == td->iso_cnt)
return 1;
}
/* control or bulk or interrupt */
if ((urb->transfer_buffer_length <= urb->actual_length) ||
(td->short_packet) || (td->zero_packet))
return 1;
return 0;
}
/* this function must be called with interrupt disabled */
static void set_td_timer(struct r8a66597 *r8a66597, struct r8a66597_td *td)
{
unsigned long time;
BUG_ON(!td);
if (!list_empty(&r8a66597->pipe_queue[td->pipenum]) &&
!usb_pipecontrol(td->urb->pipe) && usb_pipein(td->urb->pipe)) {
r8a66597->timeout_map |= 1 << td->pipenum;
switch (usb_pipetype(td->urb->pipe)) {
case PIPE_INTERRUPT:
case PIPE_ISOCHRONOUS:
time = 30;
break;
default:
time = 300;
break;
}
mod_timer(&r8a66597->td_timer[td->pipenum],
jiffies + msecs_to_jiffies(time));
}
}
/* this function must be called with interrupt disabled */
static void finish_request(struct r8a66597 *r8a66597, struct r8a66597_td *td,
u16 pipenum, struct urb *urb, int status)
__releases(r8a66597->lock) __acquires(r8a66597->lock)
{
int restart = 0;
struct usb_hcd *hcd = r8a66597_to_hcd(r8a66597);
r8a66597->timeout_map &= ~(1 << pipenum);
if (likely(td)) {
if (td->set_address && (status != 0 || urb->unlinked))
r8a66597->address_map &= ~(1 << urb->setup_packet[2]);
pipe_toggle_save(r8a66597, td->pipe, urb);
list_del(&td->queue);
kfree(td);
}
if (!list_empty(&r8a66597->pipe_queue[pipenum]))
restart = 1;
if (likely(urb)) {
if (usb_pipeisoc(urb->pipe))
urb->start_frame = r8a66597_get_frame(hcd);
r8a66597_urb_done(r8a66597, urb, status);
}
if (restart) {
td = r8a66597_get_td(r8a66597, pipenum);
if (unlikely(!td))
return;
start_transfer(r8a66597, td);
set_td_timer(r8a66597, td);
}
}
static void packet_read(struct r8a66597 *r8a66597, u16 pipenum)
{
u16 tmp;
int rcv_len, bufsize, urb_len, size;
u16 *buf;
struct r8a66597_td *td = r8a66597_get_td(r8a66597, pipenum);
struct urb *urb;
int finish = 0;
int status = 0;
if (unlikely(!td))
return;
urb = td->urb;
fifo_change_from_pipe(r8a66597, td->pipe);
tmp = r8a66597_read(r8a66597, td->pipe->fifoctr);
if (unlikely((tmp & FRDY) == 0)) {
pipe_stop(r8a66597, td->pipe);
pipe_irq_disable(r8a66597, pipenum);
printk(KERN_ERR "r8a66597: in fifo not ready (%d)\n", pipenum);
finish_request(r8a66597, td, pipenum, td->urb, -EPIPE);
return;
}
/* prepare parameters */
rcv_len = tmp & DTLN;
if (usb_pipeisoc(urb->pipe)) {
buf = (u16 *)(urb->transfer_buffer +
urb->iso_frame_desc[td->iso_cnt].offset);
urb_len = urb->iso_frame_desc[td->iso_cnt].length;
} else {
buf = (void *)urb->transfer_buffer + urb->actual_length;
urb_len = urb->transfer_buffer_length - urb->actual_length;
}
bufsize = min(urb_len, (int) td->maxpacket);
if (rcv_len <= bufsize) {
size = rcv_len;
} else {
size = bufsize;
status = -EOVERFLOW;
finish = 1;
}
/* update parameters */
urb->actual_length += size;
if (rcv_len == 0)
td->zero_packet = 1;
if (rcv_len < bufsize) {
td->short_packet = 1;
}
if (usb_pipeisoc(urb->pipe)) {
urb->iso_frame_desc[td->iso_cnt].actual_length = size;
urb->iso_frame_desc[td->iso_cnt].status = status;
td->iso_cnt++;
finish = 0;
}
/* check transfer finish */
if (finish || check_transfer_finish(td, urb)) {
pipe_stop(r8a66597, td->pipe);
pipe_irq_disable(r8a66597, pipenum);
finish = 1;
}
/* read fifo */
if (urb->transfer_buffer) {
if (size == 0)
r8a66597_write(r8a66597, BCLR, td->pipe->fifoctr);
else
r8a66597_read_fifo(r8a66597, td->pipe->fifoaddr,
buf, size);
}
if (finish && pipenum != 0)
finish_request(r8a66597, td, pipenum, urb, status);
}
static void packet_write(struct r8a66597 *r8a66597, u16 pipenum)
{
u16 tmp;
int bufsize, size;
u16 *buf;
struct r8a66597_td *td = r8a66597_get_td(r8a66597, pipenum);
struct urb *urb;
if (unlikely(!td))
return;
urb = td->urb;
fifo_change_from_pipe(r8a66597, td->pipe);
tmp = r8a66597_read(r8a66597, td->pipe->fifoctr);
if (unlikely((tmp & FRDY) == 0)) {
pipe_stop(r8a66597, td->pipe);
pipe_irq_disable(r8a66597, pipenum);
printk(KERN_ERR "r8a66597: out fifo not ready (%d)\n", pipenum);
finish_request(r8a66597, td, pipenum, urb, -EPIPE);
return;
}
/* prepare parameters */
bufsize = td->maxpacket;
if (usb_pipeisoc(urb->pipe)) {
buf = (u16 *)(urb->transfer_buffer +
urb->iso_frame_desc[td->iso_cnt].offset);
size = min(bufsize,
(int)urb->iso_frame_desc[td->iso_cnt].length);
} else {
buf = (u16 *)(urb->transfer_buffer + urb->actual_length);
size = min_t(u32, bufsize,
urb->transfer_buffer_length - urb->actual_length);
}
/* write fifo */
if (pipenum > 0)
r8a66597_write(r8a66597, ~(1 << pipenum), BEMPSTS);
if (urb->transfer_buffer) {
r8a66597_write_fifo(r8a66597, td->pipe, buf, size);
if (!usb_pipebulk(urb->pipe) || td->maxpacket != size)
r8a66597_write(r8a66597, BVAL, td->pipe->fifoctr);
}
/* update parameters */
urb->actual_length += size;
if (usb_pipeisoc(urb->pipe)) {
urb->iso_frame_desc[td->iso_cnt].actual_length = size;
urb->iso_frame_desc[td->iso_cnt].status = 0;
td->iso_cnt++;
}
/* check transfer finish */
if (check_transfer_finish(td, urb)) {
disable_irq_ready(r8a66597, pipenum);
enable_irq_empty(r8a66597, pipenum);
if (!usb_pipeisoc(urb->pipe))
enable_irq_nrdy(r8a66597, pipenum);
} else
pipe_irq_enable(r8a66597, urb, pipenum);
}
static void check_next_phase(struct r8a66597 *r8a66597, int status)
{
struct r8a66597_td *td = r8a66597_get_td(r8a66597, 0);
struct urb *urb;
u8 finish = 0;
if (unlikely(!td))
return;
urb = td->urb;
switch (td->type) {
case USB_PID_IN:
case USB_PID_OUT:
if (check_transfer_finish(td, urb))
td->type = USB_PID_ACK;
break;
case USB_PID_SETUP:
if (urb->transfer_buffer_length == urb->actual_length)
td->type = USB_PID_ACK;
else if (usb_pipeout(urb->pipe))
td->type = USB_PID_OUT;
else
td->type = USB_PID_IN;
break;
case USB_PID_ACK:
finish = 1;
break;
}
if (finish || status != 0 || urb->unlinked)
finish_request(r8a66597, td, 0, urb, status);
else
start_transfer(r8a66597, td);
}
static int get_urb_error(struct r8a66597 *r8a66597, u16 pipenum)
{
struct r8a66597_td *td = r8a66597_get_td(r8a66597, pipenum);
if (td) {
u16 pid = r8a66597_read(r8a66597, td->pipe->pipectr) & PID;
if (pid == PID_NAK)
return -ECONNRESET;
else
return -EPIPE;
}
return 0;
}
static void irq_pipe_ready(struct r8a66597 *r8a66597)
{
u16 check;
u16 pipenum;
u16 mask;
struct r8a66597_td *td;
mask = r8a66597_read(r8a66597, BRDYSTS)
& r8a66597_read(r8a66597, BRDYENB);
r8a66597_write(r8a66597, ~mask, BRDYSTS);
if (mask & BRDY0) {
td = r8a66597_get_td(r8a66597, 0);
if (td && td->type == USB_PID_IN)
packet_read(r8a66597, 0);
else
pipe_irq_disable(r8a66597, 0);
check_next_phase(r8a66597, 0);
}
for (pipenum = 1; pipenum < R8A66597_MAX_NUM_PIPE; pipenum++) {
check = 1 << pipenum;
if (mask & check) {
td = r8a66597_get_td(r8a66597, pipenum);
if (unlikely(!td))
continue;
if (td->type == USB_PID_IN)
packet_read(r8a66597, pipenum);
else if (td->type == USB_PID_OUT)
packet_write(r8a66597, pipenum);
}
}
}
static void irq_pipe_empty(struct r8a66597 *r8a66597)
{
u16 tmp;
u16 check;
u16 pipenum;
u16 mask;
struct r8a66597_td *td;
mask = r8a66597_read(r8a66597, BEMPSTS)
& r8a66597_read(r8a66597, BEMPENB);
r8a66597_write(r8a66597, ~mask, BEMPSTS);
if (mask & BEMP0) {
cfifo_change(r8a66597, 0);
td = r8a66597_get_td(r8a66597, 0);
if (td && td->type != USB_PID_OUT)
disable_irq_empty(r8a66597, 0);
check_next_phase(r8a66597, 0);
}
for (pipenum = 1; pipenum < R8A66597_MAX_NUM_PIPE; pipenum++) {
check = 1 << pipenum;
if (mask & check) {
struct r8a66597_td *td;
td = r8a66597_get_td(r8a66597, pipenum);
if (unlikely(!td))
continue;
tmp = r8a66597_read(r8a66597, td->pipe->pipectr);
if ((tmp & INBUFM) == 0) {
disable_irq_empty(r8a66597, pipenum);
pipe_irq_disable(r8a66597, pipenum);
finish_request(r8a66597, td, pipenum, td->urb,
0);
}
}
}
}
static void irq_pipe_nrdy(struct r8a66597 *r8a66597)
{
u16 check;
u16 pipenum;
u16 mask;
int status;
mask = r8a66597_read(r8a66597, NRDYSTS)
& r8a66597_read(r8a66597, NRDYENB);
r8a66597_write(r8a66597, ~mask, NRDYSTS);
if (mask & NRDY0) {
cfifo_change(r8a66597, 0);
status = get_urb_error(r8a66597, 0);
pipe_irq_disable(r8a66597, 0);
check_next_phase(r8a66597, status);
}
for (pipenum = 1; pipenum < R8A66597_MAX_NUM_PIPE; pipenum++) {
check = 1 << pipenum;
if (mask & check) {
struct r8a66597_td *td;
td = r8a66597_get_td(r8a66597, pipenum);
if (unlikely(!td))
continue;
status = get_urb_error(r8a66597, pipenum);
pipe_irq_disable(r8a66597, pipenum);
pipe_stop(r8a66597, td->pipe);
finish_request(r8a66597, td, pipenum, td->urb, status);
}
}
}
static irqreturn_t r8a66597_irq(struct usb_hcd *hcd)
{
struct r8a66597 *r8a66597 = hcd_to_r8a66597(hcd);
u16 intsts0, intsts1, intsts2;
u16 intenb0, intenb1, intenb2;
u16 mask0, mask1, mask2;
int status;
spin_lock(&r8a66597->lock);
intsts0 = r8a66597_read(r8a66597, INTSTS0);
intsts1 = r8a66597_read(r8a66597, INTSTS1);
intsts2 = r8a66597_read(r8a66597, INTSTS2);
intenb0 = r8a66597_read(r8a66597, INTENB0);
intenb1 = r8a66597_read(r8a66597, INTENB1);
intenb2 = r8a66597_read(r8a66597, INTENB2);
mask2 = intsts2 & intenb2;
mask1 = intsts1 & intenb1;
mask0 = intsts0 & intenb0 & (BEMP | NRDY | BRDY);
if (mask2) {
if (mask2 & ATTCH) {
r8a66597_write(r8a66597, ~ATTCH, INTSTS2);
r8a66597_bclr(r8a66597, ATTCHE, INTENB2);
/* start usb bus sampling */
start_root_hub_sampling(r8a66597, 1, 1);
}
if (mask2 & DTCH) {
r8a66597_write(r8a66597, ~DTCH, INTSTS2);
r8a66597_bclr(r8a66597, DTCHE, INTENB2);
r8a66597_usb_disconnect(r8a66597, 1);
}
if (mask2 & BCHG) {
r8a66597_write(r8a66597, ~BCHG, INTSTS2);
r8a66597_bclr(r8a66597, BCHGE, INTENB2);
usb_hcd_resume_root_hub(r8a66597_to_hcd(r8a66597));
}
}
if (mask1) {
if (mask1 & ATTCH) {
r8a66597_write(r8a66597, ~ATTCH, INTSTS1);
r8a66597_bclr(r8a66597, ATTCHE, INTENB1);
/* start usb bus sampling */
start_root_hub_sampling(r8a66597, 0, 1);
}
if (mask1 & DTCH) {
r8a66597_write(r8a66597, ~DTCH, INTSTS1);
r8a66597_bclr(r8a66597, DTCHE, INTENB1);
r8a66597_usb_disconnect(r8a66597, 0);
}
if (mask1 & BCHG) {
r8a66597_write(r8a66597, ~BCHG, INTSTS1);
r8a66597_bclr(r8a66597, BCHGE, INTENB1);
usb_hcd_resume_root_hub(r8a66597_to_hcd(r8a66597));
}
if (mask1 & SIGN) {
r8a66597_write(r8a66597, ~SIGN, INTSTS1);
status = get_urb_error(r8a66597, 0);
check_next_phase(r8a66597, status);
}
if (mask1 & SACK) {
r8a66597_write(r8a66597, ~SACK, INTSTS1);
check_next_phase(r8a66597, 0);
}
}
if (mask0) {
if (mask0 & BRDY)
irq_pipe_ready(r8a66597);
if (mask0 & BEMP)
irq_pipe_empty(r8a66597);
if (mask0 & NRDY)
irq_pipe_nrdy(r8a66597);
}
spin_unlock(&r8a66597->lock);
return IRQ_HANDLED;
}
/* this function must be called with interrupt disabled */
static void r8a66597_root_hub_control(struct r8a66597 *r8a66597, int port)
{
u16 tmp;
struct r8a66597_root_hub *rh = &r8a66597->root_hub[port];
if (rh->port & USB_PORT_STAT_RESET) {
unsigned long dvstctr_reg = get_dvstctr_reg(port);
tmp = r8a66597_read(r8a66597, dvstctr_reg);
if ((tmp & USBRST) == USBRST) {
r8a66597_mdfy(r8a66597, UACT, USBRST | UACT,
dvstctr_reg);
r8a66597_root_hub_start_polling(r8a66597);
} else
r8a66597_usb_connect(r8a66597, port);
}
if (!(rh->port & USB_PORT_STAT_CONNECTION)) {
r8a66597_write(r8a66597, ~ATTCH, get_intsts_reg(port));
r8a66597_bset(r8a66597, ATTCHE, get_intenb_reg(port));
}
if (rh->scount > 0) {
tmp = r8a66597_read(r8a66597, get_syssts_reg(port)) & LNST;
if (tmp == rh->old_syssts) {
rh->scount--;
if (rh->scount == 0)
r8a66597_check_syssts(r8a66597, port, tmp);
else
r8a66597_root_hub_start_polling(r8a66597);
} else {
rh->scount = R8A66597_MAX_SAMPLING;
rh->old_syssts = tmp;
r8a66597_root_hub_start_polling(r8a66597);
}
}
}
static void r8a66597_interval_timer(unsigned long _r8a66597)
{
struct r8a66597 *r8a66597 = (struct r8a66597 *)_r8a66597;
unsigned long flags;
u16 pipenum;
struct r8a66597_td *td;
spin_lock_irqsave(&r8a66597->lock, flags);
for (pipenum = 0; pipenum < R8A66597_MAX_NUM_PIPE; pipenum++) {
if (!(r8a66597->interval_map & (1 << pipenum)))
continue;
if (timer_pending(&r8a66597->interval_timer[pipenum]))
continue;
td = r8a66597_get_td(r8a66597, pipenum);
if (td)
start_transfer(r8a66597, td);
}
spin_unlock_irqrestore(&r8a66597->lock, flags);
}
static void r8a66597_td_timer(unsigned long _r8a66597)
{
struct r8a66597 *r8a66597 = (struct r8a66597 *)_r8a66597;
unsigned long flags;
u16 pipenum;
struct r8a66597_td *td, *new_td = NULL;
struct r8a66597_pipe *pipe;
spin_lock_irqsave(&r8a66597->lock, flags);
for (pipenum = 0; pipenum < R8A66597_MAX_NUM_PIPE; pipenum++) {
if (!(r8a66597->timeout_map & (1 << pipenum)))
continue;
if (timer_pending(&r8a66597->td_timer[pipenum]))
continue;
td = r8a66597_get_td(r8a66597, pipenum);
if (!td) {
r8a66597->timeout_map &= ~(1 << pipenum);
continue;
}
if (td->urb->actual_length) {
set_td_timer(r8a66597, td);
break;
}
pipe = td->pipe;
pipe_stop(r8a66597, pipe);
new_td = td;
do {
list_move_tail(&new_td->queue,
&r8a66597->pipe_queue[pipenum]);
new_td = r8a66597_get_td(r8a66597, pipenum);
if (!new_td) {
new_td = td;
break;
}
} while (td != new_td && td->address == new_td->address);
start_transfer(r8a66597, new_td);
if (td == new_td)
r8a66597->timeout_map &= ~(1 << pipenum);
else
set_td_timer(r8a66597, new_td);
break;
}
spin_unlock_irqrestore(&r8a66597->lock, flags);
}
static void r8a66597_timer(unsigned long _r8a66597)
{
struct r8a66597 *r8a66597 = (struct r8a66597 *)_r8a66597;
unsigned long flags;
int port;
spin_lock_irqsave(&r8a66597->lock, flags);
for (port = 0; port < r8a66597->max_root_hub; port++)
r8a66597_root_hub_control(r8a66597, port);
spin_unlock_irqrestore(&r8a66597->lock, flags);
}
static int check_pipe_config(struct r8a66597 *r8a66597, struct urb *urb)
{
struct r8a66597_device *dev = get_urb_to_r8a66597_dev(r8a66597, urb);
if (dev && dev->address && dev->state != USB_STATE_CONFIGURED &&
(urb->dev->state == USB_STATE_CONFIGURED))
return 1;
else
return 0;
}
static int r8a66597_start(struct usb_hcd *hcd)
{
struct r8a66597 *r8a66597 = hcd_to_r8a66597(hcd);
hcd->state = HC_STATE_RUNNING;
return enable_controller(r8a66597);
}
static void r8a66597_stop(struct usb_hcd *hcd)
{
struct r8a66597 *r8a66597 = hcd_to_r8a66597(hcd);
disable_controller(r8a66597);
}
static void set_address_zero(struct r8a66597 *r8a66597, struct urb *urb)
{
unsigned int usb_address = usb_pipedevice(urb->pipe);
u16 root_port, hub_port;
if (usb_address == 0) {
get_port_number(r8a66597, urb->dev->devpath,
&root_port, &hub_port);
set_devadd_reg(r8a66597, 0,
get_r8a66597_usb_speed(urb->dev->speed),
get_parent_r8a66597_address(r8a66597, urb->dev),
hub_port, root_port);
}
}
static struct r8a66597_td *r8a66597_make_td(struct r8a66597 *r8a66597,
struct urb *urb,
struct usb_host_endpoint *hep)
{
struct r8a66597_td *td;
u16 pipenum;
td = kzalloc(sizeof(struct r8a66597_td), GFP_ATOMIC);
if (td == NULL)
return NULL;
pipenum = r8a66597_get_pipenum(urb, hep);
td->pipenum = pipenum;
td->pipe = hep->hcpriv;
td->urb = urb;
td->address = get_urb_to_r8a66597_addr(r8a66597, urb);
td->maxpacket = usb_maxpacket(urb->dev, urb->pipe,
!usb_pipein(urb->pipe));
if (usb_pipecontrol(urb->pipe))
td->type = USB_PID_SETUP;
else if (usb_pipein(urb->pipe))
td->type = USB_PID_IN;
else
td->type = USB_PID_OUT;
INIT_LIST_HEAD(&td->queue);
return td;
}
static int r8a66597_urb_enqueue(struct usb_hcd *hcd,
struct urb *urb,
gfp_t mem_flags)
{
struct usb_host_endpoint *hep = urb->ep;
struct r8a66597 *r8a66597 = hcd_to_r8a66597(hcd);
struct r8a66597_td *td = NULL;
int ret, request = 0;
unsigned long flags;
spin_lock_irqsave(&r8a66597->lock, flags);
if (!get_urb_to_r8a66597_dev(r8a66597, urb)) {
ret = -ENODEV;
goto error_not_linked;
}
ret = usb_hcd_link_urb_to_ep(hcd, urb);
if (ret)
goto error_not_linked;
if (!hep->hcpriv) {
hep->hcpriv = kzalloc(sizeof(struct r8a66597_pipe),
GFP_ATOMIC);
if (!hep->hcpriv) {
ret = -ENOMEM;
goto error;
}
set_pipe_reg_addr(hep->hcpriv, R8A66597_PIPE_NO_DMA);
if (usb_pipeendpoint(urb->pipe))
init_pipe_info(r8a66597, urb, hep, &hep->desc);
}
if (unlikely(check_pipe_config(r8a66597, urb)))
init_pipe_config(r8a66597, urb);
set_address_zero(r8a66597, urb);
td = r8a66597_make_td(r8a66597, urb, hep);
if (td == NULL) {
ret = -ENOMEM;
goto error;
}
if (list_empty(&r8a66597->pipe_queue[td->pipenum]))
request = 1;
list_add_tail(&td->queue, &r8a66597->pipe_queue[td->pipenum]);
urb->hcpriv = td;
if (request) {
if (td->pipe->info.timer_interval) {
r8a66597->interval_map |= 1 << td->pipenum;
mod_timer(&r8a66597->interval_timer[td->pipenum],
jiffies + msecs_to_jiffies(
td->pipe->info.timer_interval));
} else {
ret = start_transfer(r8a66597, td);
if (ret < 0) {
list_del(&td->queue);
kfree(td);
}
}
} else
set_td_timer(r8a66597, td);
error:
if (ret)
usb_hcd_unlink_urb_from_ep(hcd, urb);
error_not_linked:
spin_unlock_irqrestore(&r8a66597->lock, flags);
return ret;
}
static int r8a66597_urb_dequeue(struct usb_hcd *hcd, struct urb *urb,
int status)
{
struct r8a66597 *r8a66597 = hcd_to_r8a66597(hcd);
struct r8a66597_td *td;
unsigned long flags;
int rc;
spin_lock_irqsave(&r8a66597->lock, flags);
rc = usb_hcd_check_unlink_urb(hcd, urb, status);
if (rc)
goto done;
if (urb->hcpriv) {
td = urb->hcpriv;
pipe_stop(r8a66597, td->pipe);
pipe_irq_disable(r8a66597, td->pipenum);
disable_irq_empty(r8a66597, td->pipenum);
finish_request(r8a66597, td, td->pipenum, urb, status);
}
done:
spin_unlock_irqrestore(&r8a66597->lock, flags);
return rc;
}
static void r8a66597_endpoint_disable(struct usb_hcd *hcd,
struct usb_host_endpoint *hep)
{
struct r8a66597 *r8a66597 = hcd_to_r8a66597(hcd);
struct r8a66597_pipe *pipe = (struct r8a66597_pipe *)hep->hcpriv;
struct r8a66597_td *td;
struct urb *urb = NULL;
u16 pipenum;
unsigned long flags;
if (pipe == NULL)
return;
pipenum = pipe->info.pipenum;
if (pipenum == 0) {
kfree(hep->hcpriv);
hep->hcpriv = NULL;
return;
}
spin_lock_irqsave(&r8a66597->lock, flags);
pipe_stop(r8a66597, pipe);
pipe_irq_disable(r8a66597, pipenum);
disable_irq_empty(r8a66597, pipenum);
td = r8a66597_get_td(r8a66597, pipenum);
if (td)
urb = td->urb;
finish_request(r8a66597, td, pipenum, urb, -ESHUTDOWN);
kfree(hep->hcpriv);
hep->hcpriv = NULL;
spin_unlock_irqrestore(&r8a66597->lock, flags);
}
static int r8a66597_get_frame(struct usb_hcd *hcd)
{
struct r8a66597 *r8a66597 = hcd_to_r8a66597(hcd);
return r8a66597_read(r8a66597, FRMNUM) & 0x03FF;
}
static void collect_usb_address_map(struct usb_device *udev, unsigned long *map)
{
int chix;
struct usb_device *childdev;
if (udev->state == USB_STATE_CONFIGURED &&
udev->parent && udev->parent->devnum > 1 &&
udev->parent->descriptor.bDeviceClass == USB_CLASS_HUB)
map[udev->devnum/32] |= (1 << (udev->devnum % 32));
usb_hub_for_each_child(udev, chix, childdev)
collect_usb_address_map(childdev, map);
}
/* this function must be called with interrupt disabled */
static struct r8a66597_device *get_r8a66597_device(struct r8a66597 *r8a66597,
int addr)
{
struct r8a66597_device *dev;
struct list_head *list = &r8a66597->child_device;
list_for_each_entry(dev, list, device_list) {
if (dev->usb_address != addr)
continue;
return dev;
}
printk(KERN_ERR "r8a66597: get_r8a66597_device fail.(%d)\n", addr);
return NULL;
}
static void update_usb_address_map(struct r8a66597 *r8a66597,
struct usb_device *root_hub,
unsigned long *map)
{
int i, j, addr;
unsigned long diff;
unsigned long flags;
for (i = 0; i < 4; i++) {
diff = r8a66597->child_connect_map[i] ^ map[i];
if (!diff)
continue;
for (j = 0; j < 32; j++) {
if (!(diff & (1 << j)))
continue;
addr = i * 32 + j;
if (map[i] & (1 << j))
set_child_connect_map(r8a66597, addr);
else {
struct r8a66597_device *dev;
spin_lock_irqsave(&r8a66597->lock, flags);
dev = get_r8a66597_device(r8a66597, addr);
disable_r8a66597_pipe_all(r8a66597, dev);
free_usb_address(r8a66597, dev, 0);
put_child_connect_map(r8a66597, addr);
spin_unlock_irqrestore(&r8a66597->lock, flags);
}
}
}
}
static void r8a66597_check_detect_child(struct r8a66597 *r8a66597,
struct usb_hcd *hcd)
{
struct usb_bus *bus;
unsigned long now_map[4];
memset(now_map, 0, sizeof(now_map));
list_for_each_entry(bus, &usb_bus_list, bus_list) {
if (!bus->root_hub)
continue;
if (bus->busnum != hcd->self.busnum)
continue;
collect_usb_address_map(bus->root_hub, now_map);
update_usb_address_map(r8a66597, bus->root_hub, now_map);
}
}
static int r8a66597_hub_status_data(struct usb_hcd *hcd, char *buf)
{
struct r8a66597 *r8a66597 = hcd_to_r8a66597(hcd);
unsigned long flags;
int i;
r8a66597_check_detect_child(r8a66597, hcd);
spin_lock_irqsave(&r8a66597->lock, flags);
*buf = 0; /* initialize (no change) */
for (i = 0; i < r8a66597->max_root_hub; i++) {
if (r8a66597->root_hub[i].port & 0xffff0000)
*buf |= 1 << (i + 1);
}
spin_unlock_irqrestore(&r8a66597->lock, flags);
return (*buf != 0);
}
static void r8a66597_hub_descriptor(struct r8a66597 *r8a66597,
struct usb_hub_descriptor *desc)
{
desc->bDescriptorType = 0x29;
desc->bHubContrCurrent = 0;
desc->bNbrPorts = r8a66597->max_root_hub;
desc->bDescLength = 9;
desc->bPwrOn2PwrGood = 0;
desc->wHubCharacteristics = cpu_to_le16(0x0011);
desc->u.hs.DeviceRemovable[0] =
((1 << r8a66597->max_root_hub) - 1) << 1;
desc->u.hs.DeviceRemovable[1] = ~0;
}
static int r8a66597_hub_control(struct usb_hcd *hcd, u16 typeReq, u16 wValue,
u16 wIndex, char *buf, u16 wLength)
{
struct r8a66597 *r8a66597 = hcd_to_r8a66597(hcd);
int ret;
int port = (wIndex & 0x00FF) - 1;
struct r8a66597_root_hub *rh = &r8a66597->root_hub[port];
unsigned long flags;
ret = 0;
spin_lock_irqsave(&r8a66597->lock, flags);
switch (typeReq) {
case ClearHubFeature:
case SetHubFeature:
switch (wValue) {
case C_HUB_OVER_CURRENT:
case C_HUB_LOCAL_POWER:
break;
default:
goto error;
}
break;
case ClearPortFeature:
if (wIndex > r8a66597->max_root_hub)
goto error;
if (wLength != 0)
goto error;
switch (wValue) {
case USB_PORT_FEAT_ENABLE:
rh->port &= ~USB_PORT_STAT_POWER;
break;
case USB_PORT_FEAT_SUSPEND:
break;
case USB_PORT_FEAT_POWER:
r8a66597_port_power(r8a66597, port, 0);
break;
case USB_PORT_FEAT_C_ENABLE:
case USB_PORT_FEAT_C_SUSPEND:
case USB_PORT_FEAT_C_CONNECTION:
case USB_PORT_FEAT_C_OVER_CURRENT:
case USB_PORT_FEAT_C_RESET:
break;
default:
goto error;
}
rh->port &= ~(1 << wValue);
break;
case GetHubDescriptor:
r8a66597_hub_descriptor(r8a66597,
(struct usb_hub_descriptor *)buf);
break;
case GetHubStatus:
*buf = 0x00;
break;
case GetPortStatus:
if (wIndex > r8a66597->max_root_hub)
goto error;
*(__le32 *)buf = cpu_to_le32(rh->port);
break;
case SetPortFeature:
if (wIndex > r8a66597->max_root_hub)
goto error;
if (wLength != 0)
goto error;
switch (wValue) {
case USB_PORT_FEAT_SUSPEND:
break;
case USB_PORT_FEAT_POWER:
r8a66597_port_power(r8a66597, port, 1);
rh->port |= USB_PORT_STAT_POWER;
break;
case USB_PORT_FEAT_RESET: {
struct r8a66597_device *dev = rh->dev;
rh->port |= USB_PORT_STAT_RESET;
disable_r8a66597_pipe_all(r8a66597, dev);
free_usb_address(r8a66597, dev, 1);
r8a66597_mdfy(r8a66597, USBRST, USBRST | UACT,
get_dvstctr_reg(port));
mod_timer(&r8a66597->rh_timer,
jiffies + msecs_to_jiffies(50));
}
break;
default:
goto error;
}
rh->port |= 1 << wValue;
break;
default:
error:
ret = -EPIPE;
break;
}
spin_unlock_irqrestore(&r8a66597->lock, flags);
return ret;
}
#if defined(CONFIG_PM)
static int r8a66597_bus_suspend(struct usb_hcd *hcd)
{
struct r8a66597 *r8a66597 = hcd_to_r8a66597(hcd);
int port;
dev_dbg(&r8a66597->device0.udev->dev, "%s\n", __func__);
for (port = 0; port < r8a66597->max_root_hub; port++) {
struct r8a66597_root_hub *rh = &r8a66597->root_hub[port];
unsigned long dvstctr_reg = get_dvstctr_reg(port);
if (!(rh->port & USB_PORT_STAT_ENABLE))
continue;
dev_dbg(&rh->dev->udev->dev, "suspend port = %d\n", port);
r8a66597_bclr(r8a66597, UACT, dvstctr_reg); /* suspend */
rh->port |= USB_PORT_STAT_SUSPEND;
if (rh->dev->udev->do_remote_wakeup) {
msleep(3); /* waiting last SOF */
r8a66597_bset(r8a66597, RWUPE, dvstctr_reg);
r8a66597_write(r8a66597, ~BCHG, get_intsts_reg(port));
r8a66597_bset(r8a66597, BCHGE, get_intenb_reg(port));
}
}
r8a66597->bus_suspended = 1;
return 0;
}
static int r8a66597_bus_resume(struct usb_hcd *hcd)
{
struct r8a66597 *r8a66597 = hcd_to_r8a66597(hcd);
int port;
dev_dbg(&r8a66597->device0.udev->dev, "%s\n", __func__);
for (port = 0; port < r8a66597->max_root_hub; port++) {
struct r8a66597_root_hub *rh = &r8a66597->root_hub[port];
unsigned long dvstctr_reg = get_dvstctr_reg(port);
if (!(rh->port & USB_PORT_STAT_SUSPEND))
continue;
dev_dbg(&rh->dev->udev->dev, "resume port = %d\n", port);
rh->port &= ~USB_PORT_STAT_SUSPEND;
rh->port |= USB_PORT_STAT_C_SUSPEND << 16;
r8a66597_mdfy(r8a66597, RESUME, RESUME | UACT, dvstctr_reg);
msleep(USB_RESUME_TIMEOUT);
r8a66597_mdfy(r8a66597, UACT, RESUME | UACT, dvstctr_reg);
}
return 0;
}
#else
#define r8a66597_bus_suspend NULL
#define r8a66597_bus_resume NULL
#endif
static struct hc_driver r8a66597_hc_driver = {
.description = hcd_name,
.hcd_priv_size = sizeof(struct r8a66597),
.irq = r8a66597_irq,
/*
* generic hardware linkage
*/
.flags = HCD_USB2,
.start = r8a66597_start,
.stop = r8a66597_stop,
/*
* managing i/o requests and associated device resources
*/
.urb_enqueue = r8a66597_urb_enqueue,
.urb_dequeue = r8a66597_urb_dequeue,
.endpoint_disable = r8a66597_endpoint_disable,
/*
* periodic schedule support
*/
.get_frame_number = r8a66597_get_frame,
/*
* root hub support
*/
.hub_status_data = r8a66597_hub_status_data,
.hub_control = r8a66597_hub_control,
.bus_suspend = r8a66597_bus_suspend,
.bus_resume = r8a66597_bus_resume,
};
#if defined(CONFIG_PM)
static int r8a66597_suspend(struct device *dev)
{
struct r8a66597 *r8a66597 = dev_get_drvdata(dev);
int port;
dev_dbg(dev, "%s\n", __func__);
disable_controller(r8a66597);
for (port = 0; port < r8a66597->max_root_hub; port++) {
struct r8a66597_root_hub *rh = &r8a66597->root_hub[port];
rh->port = 0x00000000;
}
return 0;
}
static int r8a66597_resume(struct device *dev)
{
struct r8a66597 *r8a66597 = dev_get_drvdata(dev);
struct usb_hcd *hcd = r8a66597_to_hcd(r8a66597);
dev_dbg(dev, "%s\n", __func__);
enable_controller(r8a66597);
usb_root_hub_lost_power(hcd->self.root_hub);
return 0;
}
static const struct dev_pm_ops r8a66597_dev_pm_ops = {
.suspend = r8a66597_suspend,
.resume = r8a66597_resume,
.poweroff = r8a66597_suspend,
.restore = r8a66597_resume,
};
#define R8A66597_DEV_PM_OPS (&r8a66597_dev_pm_ops)
#else /* if defined(CONFIG_PM) */
#define R8A66597_DEV_PM_OPS NULL
#endif
static int r8a66597_remove(struct platform_device *pdev)
{
struct r8a66597 *r8a66597 = dev_get_drvdata(&pdev->dev);
struct usb_hcd *hcd = r8a66597_to_hcd(r8a66597);
del_timer_sync(&r8a66597->rh_timer);
usb_remove_hcd(hcd);
iounmap(r8a66597->reg);
if (r8a66597->pdata->on_chip)
clk_put(r8a66597->clk);
usb_put_hcd(hcd);
return 0;
}
static int r8a66597_probe(struct platform_device *pdev)
{
char clk_name[8];
struct resource *res = NULL, *ires;
int irq = -1;
void __iomem *reg = NULL;
struct usb_hcd *hcd = NULL;
struct r8a66597 *r8a66597;
int ret = 0;
int i;
unsigned long irq_trigger;
if (usb_disabled())
return -ENODEV;
if (pdev->dev.dma_mask) {
ret = -EINVAL;
dev_err(&pdev->dev, "dma not supported\n");
goto clean_up;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
ret = -ENODEV;
dev_err(&pdev->dev, "platform_get_resource error.\n");
goto clean_up;
}
ires = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!ires) {
ret = -ENODEV;
dev_err(&pdev->dev,
"platform_get_resource IORESOURCE_IRQ error.\n");
goto clean_up;
}
irq = ires->start;
irq_trigger = ires->flags & IRQF_TRIGGER_MASK;
reg = ioremap(res->start, resource_size(res));
if (reg == NULL) {
ret = -ENOMEM;
dev_err(&pdev->dev, "ioremap error.\n");
goto clean_up;
}
if (pdev->dev.platform_data == NULL) {
dev_err(&pdev->dev, "no platform data\n");
ret = -ENODEV;
goto clean_up;
}
/* initialize hcd */
hcd = usb_create_hcd(&r8a66597_hc_driver, &pdev->dev, (char *)hcd_name);
if (!hcd) {
ret = -ENOMEM;
dev_err(&pdev->dev, "Failed to create hcd\n");
goto clean_up;
}
r8a66597 = hcd_to_r8a66597(hcd);
memset(r8a66597, 0, sizeof(struct r8a66597));
dev_set_drvdata(&pdev->dev, r8a66597);
r8a66597->pdata = pdev->dev.platform_data;
r8a66597->irq_sense_low = irq_trigger == IRQF_TRIGGER_LOW;
if (r8a66597->pdata->on_chip) {
snprintf(clk_name, sizeof(clk_name), "usb%d", pdev->id);
r8a66597->clk = clk_get(&pdev->dev, clk_name);
if (IS_ERR(r8a66597->clk)) {
dev_err(&pdev->dev, "cannot get clock \"%s\"\n",
clk_name);
ret = PTR_ERR(r8a66597->clk);
goto clean_up2;
}
r8a66597->max_root_hub = 1;
} else
r8a66597->max_root_hub = 2;
spin_lock_init(&r8a66597->lock);
init_timer(&r8a66597->rh_timer);
r8a66597->rh_timer.function = r8a66597_timer;
r8a66597->rh_timer.data = (unsigned long)r8a66597;
r8a66597->reg = reg;
/* make sure no interrupts are pending */
ret = r8a66597_clock_enable(r8a66597);
if (ret < 0)
goto clean_up3;
disable_controller(r8a66597);
for (i = 0; i < R8A66597_MAX_NUM_PIPE; i++) {
INIT_LIST_HEAD(&r8a66597->pipe_queue[i]);
init_timer(&r8a66597->td_timer[i]);
r8a66597->td_timer[i].function = r8a66597_td_timer;
r8a66597->td_timer[i].data = (unsigned long)r8a66597;
setup_timer(&r8a66597->interval_timer[i],
r8a66597_interval_timer,
(unsigned long)r8a66597);
}
INIT_LIST_HEAD(&r8a66597->child_device);
hcd->rsrc_start = res->start;
hcd->has_tt = 1;
ret = usb_add_hcd(hcd, irq, irq_trigger);
if (ret != 0) {
dev_err(&pdev->dev, "Failed to add hcd\n");
goto clean_up3;
}
return 0;
clean_up3:
if (r8a66597->pdata->on_chip)
clk_put(r8a66597->clk);
clean_up2:
usb_put_hcd(hcd);
clean_up:
if (reg)
iounmap(reg);
return ret;
}
static struct platform_driver r8a66597_driver = {
.probe = r8a66597_probe,
.remove = r8a66597_remove,
.driver = {
.name = (char *) hcd_name,
.owner = THIS_MODULE,
.pm = R8A66597_DEV_PM_OPS,
},
};
module_platform_driver(r8a66597_driver);
| gpl-2.0 |
latlontude/linux | drivers/base/regmap/regcache-flat.c | 975 | 1477 | /*
* Register cache access API - flat caching support
*
* Copyright 2012 Wolfson Microelectronics plc
*
* Author: Mark Brown <broonie@opensource.wolfsonmicro.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/device.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include "internal.h"
static int regcache_flat_init(struct regmap *map)
{
int i;
unsigned int *cache;
map->cache = kzalloc(sizeof(unsigned int) * (map->max_register + 1),
GFP_KERNEL);
if (!map->cache)
return -ENOMEM;
cache = map->cache;
for (i = 0; i < map->num_reg_defaults; i++)
cache[map->reg_defaults[i].reg] = map->reg_defaults[i].def;
return 0;
}
static int regcache_flat_exit(struct regmap *map)
{
kfree(map->cache);
map->cache = NULL;
return 0;
}
static int regcache_flat_read(struct regmap *map,
unsigned int reg, unsigned int *value)
{
unsigned int *cache = map->cache;
*value = cache[reg];
return 0;
}
static int regcache_flat_write(struct regmap *map, unsigned int reg,
unsigned int value)
{
unsigned int *cache = map->cache;
cache[reg] = value;
return 0;
}
struct regcache_ops regcache_flat_ops = {
.type = REGCACHE_FLAT,
.name = "flat",
.init = regcache_flat_init,
.exit = regcache_flat_exit,
.read = regcache_flat_read,
.write = regcache_flat_write,
};
| gpl-2.0 |
esialb/yocto-3.10-edison | sound/usb/6fire/chip.c | 1743 | 5646 | /*
* Linux driver for TerraTec DMX 6Fire USB
*
* Main routines and module definitions.
*
* Author: Torsten Schenk <torsten.schenk@zoho.com>
* Created: Jan 01, 2011
* Copyright: (C) Torsten Schenk
*
* 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 "chip.h"
#include "firmware.h"
#include "pcm.h"
#include "control.h"
#include "comm.h"
#include "midi.h"
#include <linux/moduleparam.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/gfp.h>
#include <sound/initval.h>
MODULE_AUTHOR("Torsten Schenk <torsten.schenk@zoho.com>");
MODULE_DESCRIPTION("TerraTec DMX 6Fire USB audio driver");
MODULE_LICENSE("GPL v2");
MODULE_SUPPORTED_DEVICE("{{TerraTec, DMX 6Fire USB}}");
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-max */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* Id for card */
static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; /* Enable card */
static struct sfire_chip *chips[SNDRV_CARDS] = SNDRV_DEFAULT_PTR;
static struct usb_device *devices[SNDRV_CARDS] = SNDRV_DEFAULT_PTR;
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for the 6fire sound device");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for the 6fire sound device.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable the 6fire sound device.");
static DEFINE_MUTEX(register_mutex);
static void usb6fire_chip_abort(struct sfire_chip *chip)
{
if (chip) {
if (chip->pcm)
usb6fire_pcm_abort(chip);
if (chip->midi)
usb6fire_midi_abort(chip);
if (chip->comm)
usb6fire_comm_abort(chip);
if (chip->control)
usb6fire_control_abort(chip);
if (chip->card) {
snd_card_disconnect(chip->card);
snd_card_free_when_closed(chip->card);
chip->card = NULL;
}
}
}
static void usb6fire_chip_destroy(struct sfire_chip *chip)
{
if (chip) {
if (chip->pcm)
usb6fire_pcm_destroy(chip);
if (chip->midi)
usb6fire_midi_destroy(chip);
if (chip->comm)
usb6fire_comm_destroy(chip);
if (chip->control)
usb6fire_control_destroy(chip);
if (chip->card)
snd_card_free(chip->card);
}
}
static int usb6fire_chip_probe(struct usb_interface *intf,
const struct usb_device_id *usb_id)
{
int ret;
int i;
struct sfire_chip *chip = NULL;
struct usb_device *device = interface_to_usbdev(intf);
int regidx = -1; /* index in module parameter array */
struct snd_card *card = NULL;
/* look if we already serve this card and return if so */
mutex_lock(®ister_mutex);
for (i = 0; i < SNDRV_CARDS; i++) {
if (devices[i] == device) {
if (chips[i])
chips[i]->intf_count++;
usb_set_intfdata(intf, chips[i]);
mutex_unlock(®ister_mutex);
return 0;
} else if (!devices[i] && regidx < 0)
regidx = i;
}
if (regidx < 0) {
mutex_unlock(®ister_mutex);
snd_printk(KERN_ERR PREFIX "too many cards registered.\n");
return -ENODEV;
}
devices[regidx] = device;
mutex_unlock(®ister_mutex);
/* check, if firmware is present on device, upload it if not */
ret = usb6fire_fw_init(intf);
if (ret < 0)
return ret;
else if (ret == FW_NOT_READY) /* firmware update performed */
return 0;
/* if we are here, card can be registered in alsa. */
if (usb_set_interface(device, 0, 0) != 0) {
snd_printk(KERN_ERR PREFIX "can't set first interface.\n");
return -EIO;
}
ret = snd_card_create(index[regidx], id[regidx], THIS_MODULE,
sizeof(struct sfire_chip), &card);
if (ret < 0) {
snd_printk(KERN_ERR PREFIX "cannot create alsa card.\n");
return ret;
}
strcpy(card->driver, "6FireUSB");
strcpy(card->shortname, "TerraTec DMX6FireUSB");
sprintf(card->longname, "%s at %d:%d", card->shortname,
device->bus->busnum, device->devnum);
snd_card_set_dev(card, &intf->dev);
chip = card->private_data;
chips[regidx] = chip;
chip->dev = device;
chip->regidx = regidx;
chip->intf_count = 1;
chip->card = card;
ret = usb6fire_comm_init(chip);
if (ret < 0) {
usb6fire_chip_destroy(chip);
return ret;
}
ret = usb6fire_midi_init(chip);
if (ret < 0) {
usb6fire_chip_destroy(chip);
return ret;
}
ret = usb6fire_pcm_init(chip);
if (ret < 0) {
usb6fire_chip_destroy(chip);
return ret;
}
ret = usb6fire_control_init(chip);
if (ret < 0) {
usb6fire_chip_destroy(chip);
return ret;
}
ret = snd_card_register(card);
if (ret < 0) {
snd_printk(KERN_ERR PREFIX "cannot register card.");
usb6fire_chip_destroy(chip);
return ret;
}
usb_set_intfdata(intf, chip);
return 0;
}
static void usb6fire_chip_disconnect(struct usb_interface *intf)
{
struct sfire_chip *chip;
struct snd_card *card;
chip = usb_get_intfdata(intf);
if (chip) { /* if !chip, fw upload has been performed */
card = chip->card;
chip->intf_count--;
if (!chip->intf_count) {
mutex_lock(®ister_mutex);
devices[chip->regidx] = NULL;
chips[chip->regidx] = NULL;
mutex_unlock(®ister_mutex);
chip->shutdown = true;
usb6fire_chip_abort(chip);
usb6fire_chip_destroy(chip);
}
}
}
static struct usb_device_id device_table[] = {
{
.match_flags = USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x0ccd,
.idProduct = 0x0080
},
{}
};
MODULE_DEVICE_TABLE(usb, device_table);
static struct usb_driver usb_driver = {
.name = "snd-usb-6fire",
.probe = usb6fire_chip_probe,
.disconnect = usb6fire_chip_disconnect,
.id_table = device_table,
};
module_usb_driver(usb_driver);
| gpl-2.0 |
alexax66/LP-Kernel-SM-E500H | sound/usb/6fire/chip.c | 1743 | 5646 | /*
* Linux driver for TerraTec DMX 6Fire USB
*
* Main routines and module definitions.
*
* Author: Torsten Schenk <torsten.schenk@zoho.com>
* Created: Jan 01, 2011
* Copyright: (C) Torsten Schenk
*
* 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 "chip.h"
#include "firmware.h"
#include "pcm.h"
#include "control.h"
#include "comm.h"
#include "midi.h"
#include <linux/moduleparam.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/gfp.h>
#include <sound/initval.h>
MODULE_AUTHOR("Torsten Schenk <torsten.schenk@zoho.com>");
MODULE_DESCRIPTION("TerraTec DMX 6Fire USB audio driver");
MODULE_LICENSE("GPL v2");
MODULE_SUPPORTED_DEVICE("{{TerraTec, DMX 6Fire USB}}");
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-max */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* Id for card */
static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; /* Enable card */
static struct sfire_chip *chips[SNDRV_CARDS] = SNDRV_DEFAULT_PTR;
static struct usb_device *devices[SNDRV_CARDS] = SNDRV_DEFAULT_PTR;
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for the 6fire sound device");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for the 6fire sound device.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable the 6fire sound device.");
static DEFINE_MUTEX(register_mutex);
static void usb6fire_chip_abort(struct sfire_chip *chip)
{
if (chip) {
if (chip->pcm)
usb6fire_pcm_abort(chip);
if (chip->midi)
usb6fire_midi_abort(chip);
if (chip->comm)
usb6fire_comm_abort(chip);
if (chip->control)
usb6fire_control_abort(chip);
if (chip->card) {
snd_card_disconnect(chip->card);
snd_card_free_when_closed(chip->card);
chip->card = NULL;
}
}
}
static void usb6fire_chip_destroy(struct sfire_chip *chip)
{
if (chip) {
if (chip->pcm)
usb6fire_pcm_destroy(chip);
if (chip->midi)
usb6fire_midi_destroy(chip);
if (chip->comm)
usb6fire_comm_destroy(chip);
if (chip->control)
usb6fire_control_destroy(chip);
if (chip->card)
snd_card_free(chip->card);
}
}
static int usb6fire_chip_probe(struct usb_interface *intf,
const struct usb_device_id *usb_id)
{
int ret;
int i;
struct sfire_chip *chip = NULL;
struct usb_device *device = interface_to_usbdev(intf);
int regidx = -1; /* index in module parameter array */
struct snd_card *card = NULL;
/* look if we already serve this card and return if so */
mutex_lock(®ister_mutex);
for (i = 0; i < SNDRV_CARDS; i++) {
if (devices[i] == device) {
if (chips[i])
chips[i]->intf_count++;
usb_set_intfdata(intf, chips[i]);
mutex_unlock(®ister_mutex);
return 0;
} else if (!devices[i] && regidx < 0)
regidx = i;
}
if (regidx < 0) {
mutex_unlock(®ister_mutex);
snd_printk(KERN_ERR PREFIX "too many cards registered.\n");
return -ENODEV;
}
devices[regidx] = device;
mutex_unlock(®ister_mutex);
/* check, if firmware is present on device, upload it if not */
ret = usb6fire_fw_init(intf);
if (ret < 0)
return ret;
else if (ret == FW_NOT_READY) /* firmware update performed */
return 0;
/* if we are here, card can be registered in alsa. */
if (usb_set_interface(device, 0, 0) != 0) {
snd_printk(KERN_ERR PREFIX "can't set first interface.\n");
return -EIO;
}
ret = snd_card_create(index[regidx], id[regidx], THIS_MODULE,
sizeof(struct sfire_chip), &card);
if (ret < 0) {
snd_printk(KERN_ERR PREFIX "cannot create alsa card.\n");
return ret;
}
strcpy(card->driver, "6FireUSB");
strcpy(card->shortname, "TerraTec DMX6FireUSB");
sprintf(card->longname, "%s at %d:%d", card->shortname,
device->bus->busnum, device->devnum);
snd_card_set_dev(card, &intf->dev);
chip = card->private_data;
chips[regidx] = chip;
chip->dev = device;
chip->regidx = regidx;
chip->intf_count = 1;
chip->card = card;
ret = usb6fire_comm_init(chip);
if (ret < 0) {
usb6fire_chip_destroy(chip);
return ret;
}
ret = usb6fire_midi_init(chip);
if (ret < 0) {
usb6fire_chip_destroy(chip);
return ret;
}
ret = usb6fire_pcm_init(chip);
if (ret < 0) {
usb6fire_chip_destroy(chip);
return ret;
}
ret = usb6fire_control_init(chip);
if (ret < 0) {
usb6fire_chip_destroy(chip);
return ret;
}
ret = snd_card_register(card);
if (ret < 0) {
snd_printk(KERN_ERR PREFIX "cannot register card.");
usb6fire_chip_destroy(chip);
return ret;
}
usb_set_intfdata(intf, chip);
return 0;
}
static void usb6fire_chip_disconnect(struct usb_interface *intf)
{
struct sfire_chip *chip;
struct snd_card *card;
chip = usb_get_intfdata(intf);
if (chip) { /* if !chip, fw upload has been performed */
card = chip->card;
chip->intf_count--;
if (!chip->intf_count) {
mutex_lock(®ister_mutex);
devices[chip->regidx] = NULL;
chips[chip->regidx] = NULL;
mutex_unlock(®ister_mutex);
chip->shutdown = true;
usb6fire_chip_abort(chip);
usb6fire_chip_destroy(chip);
}
}
}
static struct usb_device_id device_table[] = {
{
.match_flags = USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x0ccd,
.idProduct = 0x0080
},
{}
};
MODULE_DEVICE_TABLE(usb, device_table);
static struct usb_driver usb_driver = {
.name = "snd-usb-6fire",
.probe = usb6fire_chip_probe,
.disconnect = usb6fire_chip_disconnect,
.id_table = device_table,
};
module_usb_driver(usb_driver);
| gpl-2.0 |
jbats/android_kernel_motorola_msm8992 | drivers/usb/serial/mos7720.c | 1743 | 58296 | /*
* mos7720.c
* Controls the Moschip 7720 usb to dual port serial convertor
*
* Copyright 2006 Moschip Semiconductor Tech. 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.
*
* Developed by:
* Vijaya Kumar <vijaykumar.gn@gmail.com>
* Ajay Kumar <naanuajay@yahoo.com>
* Gurudeva <ngurudeva@yahoo.com>
*
* Cleaned up from the original by:
* Greg Kroah-Hartman <gregkh@suse.de>
*
* Originally based on drivers/usb/serial/io_edgeport.c which is:
* Copyright (C) 2000 Inside Out Networks, All rights reserved.
* Copyright (C) 2001-2002 Greg Kroah-Hartman <greg@kroah.com>
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/serial.h>
#include <linux/serial_reg.h>
#include <linux/usb.h>
#include <linux/usb/serial.h>
#include <linux/uaccess.h>
#include <linux/parport.h>
#define DRIVER_AUTHOR "Aspire Communications pvt Ltd."
#define DRIVER_DESC "Moschip USB Serial Driver"
/* default urb timeout */
#define MOS_WDR_TIMEOUT 5000
#define MOS_MAX_PORT 0x02
#define MOS_WRITE 0x0E
#define MOS_READ 0x0D
/* Interrupt Rotinue Defines */
#define SERIAL_IIR_RLS 0x06
#define SERIAL_IIR_RDA 0x04
#define SERIAL_IIR_CTI 0x0c
#define SERIAL_IIR_THR 0x02
#define SERIAL_IIR_MS 0x00
#define NUM_URBS 16 /* URB Count */
#define URB_TRANSFER_BUFFER_SIZE 32 /* URB Size */
/* This structure holds all of the local serial port information */
struct moschip_port {
__u8 shadowLCR; /* last LCR value received */
__u8 shadowMCR; /* last MCR value received */
__u8 shadowMSR; /* last MSR value received */
char open;
struct usb_serial_port *port; /* loop back to the owner */
struct urb *write_urb_pool[NUM_URBS];
};
static struct usb_serial_driver moschip7720_2port_driver;
#define USB_VENDOR_ID_MOSCHIP 0x9710
#define MOSCHIP_DEVICE_ID_7720 0x7720
#define MOSCHIP_DEVICE_ID_7715 0x7715
static const struct usb_device_id id_table[] = {
{ USB_DEVICE(USB_VENDOR_ID_MOSCHIP, MOSCHIP_DEVICE_ID_7720) },
{ USB_DEVICE(USB_VENDOR_ID_MOSCHIP, MOSCHIP_DEVICE_ID_7715) },
{ } /* terminating entry */
};
MODULE_DEVICE_TABLE(usb, id_table);
#ifdef CONFIG_USB_SERIAL_MOS7715_PARPORT
/* initial values for parport regs */
#define DCR_INIT_VAL 0x0c /* SLCTIN, nINIT */
#define ECR_INIT_VAL 0x00 /* SPP mode */
struct urbtracker {
struct mos7715_parport *mos_parport;
struct list_head urblist_entry;
struct kref ref_count;
struct urb *urb;
struct usb_ctrlrequest *setup;
};
enum mos7715_pp_modes {
SPP = 0<<5,
PS2 = 1<<5, /* moschip calls this 'NIBBLE' mode */
PPF = 2<<5, /* moschip calls this 'CB-FIFO mode */
};
struct mos7715_parport {
struct parport *pp; /* back to containing struct */
struct kref ref_count; /* to instance of this struct */
struct list_head deferred_urbs; /* list deferred async urbs */
struct list_head active_urbs; /* list async urbs in flight */
spinlock_t listlock; /* protects list access */
bool msg_pending; /* usb sync call pending */
struct completion syncmsg_compl; /* usb sync call completed */
struct tasklet_struct urb_tasklet; /* for sending deferred urbs */
struct usb_serial *serial; /* back to containing struct */
__u8 shadowECR; /* parallel port regs... */
__u8 shadowDCR;
atomic_t shadowDSR; /* updated in int-in callback */
};
/* lock guards against dereferencing NULL ptr in parport ops callbacks */
static DEFINE_SPINLOCK(release_lock);
#endif /* CONFIG_USB_SERIAL_MOS7715_PARPORT */
static const unsigned int dummy; /* for clarity in register access fns */
enum mos_regs {
THR, /* serial port regs */
RHR,
IER,
FCR,
ISR,
LCR,
MCR,
LSR,
MSR,
SPR,
DLL,
DLM,
DPR, /* parallel port regs */
DSR,
DCR,
ECR,
SP1_REG, /* device control regs */
SP2_REG, /* serial port 2 (7720 only) */
PP_REG,
SP_CONTROL_REG,
};
/*
* Return the correct value for the Windex field of the setup packet
* for a control endpoint message. See the 7715 datasheet.
*/
static inline __u16 get_reg_index(enum mos_regs reg)
{
static const __u16 mos7715_index_lookup_table[] = {
0x00, /* THR */
0x00, /* RHR */
0x01, /* IER */
0x02, /* FCR */
0x02, /* ISR */
0x03, /* LCR */
0x04, /* MCR */
0x05, /* LSR */
0x06, /* MSR */
0x07, /* SPR */
0x00, /* DLL */
0x01, /* DLM */
0x00, /* DPR */
0x01, /* DSR */
0x02, /* DCR */
0x0a, /* ECR */
0x01, /* SP1_REG */
0x02, /* SP2_REG (7720 only) */
0x04, /* PP_REG (7715 only) */
0x08, /* SP_CONTROL_REG */
};
return mos7715_index_lookup_table[reg];
}
/*
* Return the correct value for the upper byte of the Wvalue field of
* the setup packet for a control endpoint message.
*/
static inline __u16 get_reg_value(enum mos_regs reg,
unsigned int serial_portnum)
{
if (reg >= SP1_REG) /* control reg */
return 0x0000;
else if (reg >= DPR) /* parallel port reg (7715 only) */
return 0x0100;
else /* serial port reg */
return (serial_portnum + 2) << 8;
}
/*
* Write data byte to the specified device register. The data is embedded in
* the value field of the setup packet. serial_portnum is ignored for registers
* not specific to a particular serial port.
*/
static int write_mos_reg(struct usb_serial *serial, unsigned int serial_portnum,
enum mos_regs reg, __u8 data)
{
struct usb_device *usbdev = serial->dev;
unsigned int pipe = usb_sndctrlpipe(usbdev, 0);
__u8 request = (__u8)0x0e;
__u8 requesttype = (__u8)0x40;
__u16 index = get_reg_index(reg);
__u16 value = get_reg_value(reg, serial_portnum) + data;
int status = usb_control_msg(usbdev, pipe, request, requesttype, value,
index, NULL, 0, MOS_WDR_TIMEOUT);
if (status < 0)
dev_err(&usbdev->dev,
"mos7720: usb_control_msg() failed: %d", status);
return status;
}
/*
* Read data byte from the specified device register. The data returned by the
* device is embedded in the value field of the setup packet. serial_portnum is
* ignored for registers that are not specific to a particular serial port.
*/
static int read_mos_reg(struct usb_serial *serial, unsigned int serial_portnum,
enum mos_regs reg, __u8 *data)
{
struct usb_device *usbdev = serial->dev;
unsigned int pipe = usb_rcvctrlpipe(usbdev, 0);
__u8 request = (__u8)0x0d;
__u8 requesttype = (__u8)0xc0;
__u16 index = get_reg_index(reg);
__u16 value = get_reg_value(reg, serial_portnum);
u8 *buf;
int status;
buf = kmalloc(1, GFP_KERNEL);
if (!buf)
return -ENOMEM;
status = usb_control_msg(usbdev, pipe, request, requesttype, value,
index, buf, 1, MOS_WDR_TIMEOUT);
if (status == 1)
*data = *buf;
else if (status < 0)
dev_err(&usbdev->dev,
"mos7720: usb_control_msg() failed: %d", status);
kfree(buf);
return status;
}
#ifdef CONFIG_USB_SERIAL_MOS7715_PARPORT
static inline int mos7715_change_mode(struct mos7715_parport *mos_parport,
enum mos7715_pp_modes mode)
{
mos_parport->shadowECR = mode;
write_mos_reg(mos_parport->serial, dummy, ECR, mos_parport->shadowECR);
return 0;
}
static void destroy_mos_parport(struct kref *kref)
{
struct mos7715_parport *mos_parport =
container_of(kref, struct mos7715_parport, ref_count);
kfree(mos_parport);
}
static void destroy_urbtracker(struct kref *kref)
{
struct urbtracker *urbtrack =
container_of(kref, struct urbtracker, ref_count);
struct mos7715_parport *mos_parport = urbtrack->mos_parport;
usb_free_urb(urbtrack->urb);
kfree(urbtrack->setup);
kfree(urbtrack);
kref_put(&mos_parport->ref_count, destroy_mos_parport);
}
/*
* This runs as a tasklet when sending an urb in a non-blocking parallel
* port callback had to be deferred because the disconnect mutex could not be
* obtained at the time.
*/
static void send_deferred_urbs(unsigned long _mos_parport)
{
int ret_val;
unsigned long flags;
struct mos7715_parport *mos_parport = (void *)_mos_parport;
struct urbtracker *urbtrack, *tmp;
struct list_head *cursor, *next;
struct device *dev;
/* if release function ran, game over */
if (unlikely(mos_parport->serial == NULL))
return;
dev = &mos_parport->serial->dev->dev;
/* try again to get the mutex */
if (!mutex_trylock(&mos_parport->serial->disc_mutex)) {
dev_dbg(dev, "%s: rescheduling tasklet\n", __func__);
tasklet_schedule(&mos_parport->urb_tasklet);
return;
}
/* if device disconnected, game over */
if (unlikely(mos_parport->serial->disconnected)) {
mutex_unlock(&mos_parport->serial->disc_mutex);
return;
}
spin_lock_irqsave(&mos_parport->listlock, flags);
if (list_empty(&mos_parport->deferred_urbs)) {
spin_unlock_irqrestore(&mos_parport->listlock, flags);
mutex_unlock(&mos_parport->serial->disc_mutex);
dev_dbg(dev, "%s: deferred_urbs list empty\n", __func__);
return;
}
/* move contents of deferred_urbs list to active_urbs list and submit */
list_for_each_safe(cursor, next, &mos_parport->deferred_urbs)
list_move_tail(cursor, &mos_parport->active_urbs);
list_for_each_entry_safe(urbtrack, tmp, &mos_parport->active_urbs,
urblist_entry) {
ret_val = usb_submit_urb(urbtrack->urb, GFP_ATOMIC);
dev_dbg(dev, "%s: urb submitted\n", __func__);
if (ret_val) {
dev_err(dev, "usb_submit_urb() failed: %d\n", ret_val);
list_del(&urbtrack->urblist_entry);
kref_put(&urbtrack->ref_count, destroy_urbtracker);
}
}
spin_unlock_irqrestore(&mos_parport->listlock, flags);
mutex_unlock(&mos_parport->serial->disc_mutex);
}
/* callback for parallel port control urbs submitted asynchronously */
static void async_complete(struct urb *urb)
{
struct urbtracker *urbtrack = urb->context;
int status = urb->status;
if (unlikely(status))
dev_dbg(&urb->dev->dev, "%s - nonzero urb status received: %d\n", __func__, status);
/* remove the urbtracker from the active_urbs list */
spin_lock(&urbtrack->mos_parport->listlock);
list_del(&urbtrack->urblist_entry);
spin_unlock(&urbtrack->mos_parport->listlock);
kref_put(&urbtrack->ref_count, destroy_urbtracker);
}
static int write_parport_reg_nonblock(struct mos7715_parport *mos_parport,
enum mos_regs reg, __u8 data)
{
struct urbtracker *urbtrack;
int ret_val;
unsigned long flags;
struct usb_serial *serial = mos_parport->serial;
struct usb_device *usbdev = serial->dev;
/* create and initialize the control urb and containing urbtracker */
urbtrack = kmalloc(sizeof(struct urbtracker), GFP_ATOMIC);
if (urbtrack == NULL) {
dev_err(&usbdev->dev, "out of memory");
return -ENOMEM;
}
kref_get(&mos_parport->ref_count);
urbtrack->mos_parport = mos_parport;
urbtrack->urb = usb_alloc_urb(0, GFP_ATOMIC);
if (urbtrack->urb == NULL) {
dev_err(&usbdev->dev, "out of urbs");
kfree(urbtrack);
return -ENOMEM;
}
urbtrack->setup = kmalloc(sizeof(*urbtrack->setup), GFP_ATOMIC);
if (!urbtrack->setup) {
usb_free_urb(urbtrack->urb);
kfree(urbtrack);
return -ENOMEM;
}
urbtrack->setup->bRequestType = (__u8)0x40;
urbtrack->setup->bRequest = (__u8)0x0e;
urbtrack->setup->wValue = cpu_to_le16(get_reg_value(reg, dummy));
urbtrack->setup->wIndex = cpu_to_le16(get_reg_index(reg));
urbtrack->setup->wLength = 0;
usb_fill_control_urb(urbtrack->urb, usbdev,
usb_sndctrlpipe(usbdev, 0),
(unsigned char *)urbtrack->setup,
NULL, 0, async_complete, urbtrack);
kref_init(&urbtrack->ref_count);
INIT_LIST_HEAD(&urbtrack->urblist_entry);
/*
* get the disconnect mutex, or add tracker to the deferred_urbs list
* and schedule a tasklet to try again later
*/
if (!mutex_trylock(&serial->disc_mutex)) {
spin_lock_irqsave(&mos_parport->listlock, flags);
list_add_tail(&urbtrack->urblist_entry,
&mos_parport->deferred_urbs);
spin_unlock_irqrestore(&mos_parport->listlock, flags);
tasklet_schedule(&mos_parport->urb_tasklet);
dev_dbg(&usbdev->dev, "tasklet scheduled");
return 0;
}
/* bail if device disconnected */
if (serial->disconnected) {
kref_put(&urbtrack->ref_count, destroy_urbtracker);
mutex_unlock(&serial->disc_mutex);
return -ENODEV;
}
/* add the tracker to the active_urbs list and submit */
spin_lock_irqsave(&mos_parport->listlock, flags);
list_add_tail(&urbtrack->urblist_entry, &mos_parport->active_urbs);
spin_unlock_irqrestore(&mos_parport->listlock, flags);
ret_val = usb_submit_urb(urbtrack->urb, GFP_ATOMIC);
mutex_unlock(&serial->disc_mutex);
if (ret_val) {
dev_err(&usbdev->dev,
"%s: submit_urb() failed: %d", __func__, ret_val);
spin_lock_irqsave(&mos_parport->listlock, flags);
list_del(&urbtrack->urblist_entry);
spin_unlock_irqrestore(&mos_parport->listlock, flags);
kref_put(&urbtrack->ref_count, destroy_urbtracker);
return ret_val;
}
return 0;
}
/*
* This is the the common top part of all parallel port callback operations that
* send synchronous messages to the device. This implements convoluted locking
* that avoids two scenarios: (1) a port operation is called after usbserial
* has called our release function, at which point struct mos7715_parport has
* been destroyed, and (2) the device has been disconnected, but usbserial has
* not called the release function yet because someone has a serial port open.
* The shared release_lock prevents the first, and the mutex and disconnected
* flag maintained by usbserial covers the second. We also use the msg_pending
* flag to ensure that all synchronous usb messgage calls have completed before
* our release function can return.
*/
static int parport_prologue(struct parport *pp)
{
struct mos7715_parport *mos_parport;
spin_lock(&release_lock);
mos_parport = pp->private_data;
if (unlikely(mos_parport == NULL)) {
/* release fn called, port struct destroyed */
spin_unlock(&release_lock);
return -1;
}
mos_parport->msg_pending = true; /* synch usb call pending */
INIT_COMPLETION(mos_parport->syncmsg_compl);
spin_unlock(&release_lock);
mutex_lock(&mos_parport->serial->disc_mutex);
if (mos_parport->serial->disconnected) {
/* device disconnected */
mutex_unlock(&mos_parport->serial->disc_mutex);
mos_parport->msg_pending = false;
complete(&mos_parport->syncmsg_compl);
return -1;
}
return 0;
}
/*
* This is the the common bottom part of all parallel port functions that send
* synchronous messages to the device.
*/
static inline void parport_epilogue(struct parport *pp)
{
struct mos7715_parport *mos_parport = pp->private_data;
mutex_unlock(&mos_parport->serial->disc_mutex);
mos_parport->msg_pending = false;
complete(&mos_parport->syncmsg_compl);
}
static void parport_mos7715_write_data(struct parport *pp, unsigned char d)
{
struct mos7715_parport *mos_parport = pp->private_data;
if (parport_prologue(pp) < 0)
return;
mos7715_change_mode(mos_parport, SPP);
write_mos_reg(mos_parport->serial, dummy, DPR, (__u8)d);
parport_epilogue(pp);
}
static unsigned char parport_mos7715_read_data(struct parport *pp)
{
struct mos7715_parport *mos_parport = pp->private_data;
unsigned char d;
if (parport_prologue(pp) < 0)
return 0;
read_mos_reg(mos_parport->serial, dummy, DPR, &d);
parport_epilogue(pp);
return d;
}
static void parport_mos7715_write_control(struct parport *pp, unsigned char d)
{
struct mos7715_parport *mos_parport = pp->private_data;
__u8 data;
if (parport_prologue(pp) < 0)
return;
data = ((__u8)d & 0x0f) | (mos_parport->shadowDCR & 0xf0);
write_mos_reg(mos_parport->serial, dummy, DCR, data);
mos_parport->shadowDCR = data;
parport_epilogue(pp);
}
static unsigned char parport_mos7715_read_control(struct parport *pp)
{
struct mos7715_parport *mos_parport = pp->private_data;
__u8 dcr;
spin_lock(&release_lock);
mos_parport = pp->private_data;
if (unlikely(mos_parport == NULL)) {
spin_unlock(&release_lock);
return 0;
}
dcr = mos_parport->shadowDCR & 0x0f;
spin_unlock(&release_lock);
return dcr;
}
static unsigned char parport_mos7715_frob_control(struct parport *pp,
unsigned char mask,
unsigned char val)
{
struct mos7715_parport *mos_parport = pp->private_data;
__u8 dcr;
mask &= 0x0f;
val &= 0x0f;
if (parport_prologue(pp) < 0)
return 0;
mos_parport->shadowDCR = (mos_parport->shadowDCR & (~mask)) ^ val;
write_mos_reg(mos_parport->serial, dummy, DCR, mos_parport->shadowDCR);
dcr = mos_parport->shadowDCR & 0x0f;
parport_epilogue(pp);
return dcr;
}
static unsigned char parport_mos7715_read_status(struct parport *pp)
{
unsigned char status;
struct mos7715_parport *mos_parport = pp->private_data;
spin_lock(&release_lock);
mos_parport = pp->private_data;
if (unlikely(mos_parport == NULL)) { /* release called */
spin_unlock(&release_lock);
return 0;
}
status = atomic_read(&mos_parport->shadowDSR) & 0xf8;
spin_unlock(&release_lock);
return status;
}
static void parport_mos7715_enable_irq(struct parport *pp)
{
}
static void parport_mos7715_disable_irq(struct parport *pp)
{
}
static void parport_mos7715_data_forward(struct parport *pp)
{
struct mos7715_parport *mos_parport = pp->private_data;
if (parport_prologue(pp) < 0)
return;
mos7715_change_mode(mos_parport, PS2);
mos_parport->shadowDCR &= ~0x20;
write_mos_reg(mos_parport->serial, dummy, DCR, mos_parport->shadowDCR);
parport_epilogue(pp);
}
static void parport_mos7715_data_reverse(struct parport *pp)
{
struct mos7715_parport *mos_parport = pp->private_data;
if (parport_prologue(pp) < 0)
return;
mos7715_change_mode(mos_parport, PS2);
mos_parport->shadowDCR |= 0x20;
write_mos_reg(mos_parport->serial, dummy, DCR, mos_parport->shadowDCR);
parport_epilogue(pp);
}
static void parport_mos7715_init_state(struct pardevice *dev,
struct parport_state *s)
{
s->u.pc.ctr = DCR_INIT_VAL;
s->u.pc.ecr = ECR_INIT_VAL;
}
/* N.B. Parport core code requires that this function not block */
static void parport_mos7715_save_state(struct parport *pp,
struct parport_state *s)
{
struct mos7715_parport *mos_parport;
spin_lock(&release_lock);
mos_parport = pp->private_data;
if (unlikely(mos_parport == NULL)) { /* release called */
spin_unlock(&release_lock);
return;
}
s->u.pc.ctr = mos_parport->shadowDCR;
s->u.pc.ecr = mos_parport->shadowECR;
spin_unlock(&release_lock);
}
/* N.B. Parport core code requires that this function not block */
static void parport_mos7715_restore_state(struct parport *pp,
struct parport_state *s)
{
struct mos7715_parport *mos_parport;
spin_lock(&release_lock);
mos_parport = pp->private_data;
if (unlikely(mos_parport == NULL)) { /* release called */
spin_unlock(&release_lock);
return;
}
write_parport_reg_nonblock(mos_parport, DCR, mos_parport->shadowDCR);
write_parport_reg_nonblock(mos_parport, ECR, mos_parport->shadowECR);
spin_unlock(&release_lock);
}
static size_t parport_mos7715_write_compat(struct parport *pp,
const void *buffer,
size_t len, int flags)
{
int retval;
struct mos7715_parport *mos_parport = pp->private_data;
int actual_len;
if (parport_prologue(pp) < 0)
return 0;
mos7715_change_mode(mos_parport, PPF);
retval = usb_bulk_msg(mos_parport->serial->dev,
usb_sndbulkpipe(mos_parport->serial->dev, 2),
(void *)buffer, len, &actual_len,
MOS_WDR_TIMEOUT);
parport_epilogue(pp);
if (retval) {
dev_err(&mos_parport->serial->dev->dev,
"mos7720: usb_bulk_msg() failed: %d", retval);
return 0;
}
return actual_len;
}
static struct parport_operations parport_mos7715_ops = {
.owner = THIS_MODULE,
.write_data = parport_mos7715_write_data,
.read_data = parport_mos7715_read_data,
.write_control = parport_mos7715_write_control,
.read_control = parport_mos7715_read_control,
.frob_control = parport_mos7715_frob_control,
.read_status = parport_mos7715_read_status,
.enable_irq = parport_mos7715_enable_irq,
.disable_irq = parport_mos7715_disable_irq,
.data_forward = parport_mos7715_data_forward,
.data_reverse = parport_mos7715_data_reverse,
.init_state = parport_mos7715_init_state,
.save_state = parport_mos7715_save_state,
.restore_state = parport_mos7715_restore_state,
.compat_write_data = parport_mos7715_write_compat,
.nibble_read_data = parport_ieee1284_read_nibble,
.byte_read_data = parport_ieee1284_read_byte,
};
/*
* Allocate and initialize parallel port control struct, initialize
* the parallel port hardware device, and register with the parport subsystem.
*/
static int mos7715_parport_init(struct usb_serial *serial)
{
struct mos7715_parport *mos_parport;
/* allocate and initialize parallel port control struct */
mos_parport = kzalloc(sizeof(struct mos7715_parport), GFP_KERNEL);
if (mos_parport == NULL) {
dev_dbg(&serial->dev->dev, "%s: kzalloc failed\n", __func__);
return -ENOMEM;
}
mos_parport->msg_pending = false;
kref_init(&mos_parport->ref_count);
spin_lock_init(&mos_parport->listlock);
INIT_LIST_HEAD(&mos_parport->active_urbs);
INIT_LIST_HEAD(&mos_parport->deferred_urbs);
usb_set_serial_data(serial, mos_parport); /* hijack private pointer */
mos_parport->serial = serial;
tasklet_init(&mos_parport->urb_tasklet, send_deferred_urbs,
(unsigned long) mos_parport);
init_completion(&mos_parport->syncmsg_compl);
/* cycle parallel port reset bit */
write_mos_reg(mos_parport->serial, dummy, PP_REG, (__u8)0x80);
write_mos_reg(mos_parport->serial, dummy, PP_REG, (__u8)0x00);
/* initialize device registers */
mos_parport->shadowDCR = DCR_INIT_VAL;
write_mos_reg(mos_parport->serial, dummy, DCR, mos_parport->shadowDCR);
mos_parport->shadowECR = ECR_INIT_VAL;
write_mos_reg(mos_parport->serial, dummy, ECR, mos_parport->shadowECR);
/* register with parport core */
mos_parport->pp = parport_register_port(0, PARPORT_IRQ_NONE,
PARPORT_DMA_NONE,
&parport_mos7715_ops);
if (mos_parport->pp == NULL) {
dev_err(&serial->interface->dev,
"Could not register parport\n");
kref_put(&mos_parport->ref_count, destroy_mos_parport);
return -EIO;
}
mos_parport->pp->private_data = mos_parport;
mos_parport->pp->modes = PARPORT_MODE_COMPAT | PARPORT_MODE_PCSPP;
mos_parport->pp->dev = &serial->interface->dev;
parport_announce_port(mos_parport->pp);
return 0;
}
#endif /* CONFIG_USB_SERIAL_MOS7715_PARPORT */
/*
* mos7720_interrupt_callback
* this is the callback function for when we have received data on the
* interrupt endpoint.
*/
static void mos7720_interrupt_callback(struct urb *urb)
{
int result;
int length;
int status = urb->status;
struct device *dev = &urb->dev->dev;
__u8 *data;
__u8 sp1;
__u8 sp2;
switch (status) {
case 0:
/* success */
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
/* this urb is terminated, clean up */
dev_dbg(dev, "%s - urb shutting down with status: %d\n", __func__, status);
return;
default:
dev_dbg(dev, "%s - nonzero urb status received: %d\n", __func__, status);
goto exit;
}
length = urb->actual_length;
data = urb->transfer_buffer;
/* Moschip get 4 bytes
* Byte 1 IIR Port 1 (port.number is 0)
* Byte 2 IIR Port 2 (port.number is 1)
* Byte 3 --------------
* Byte 4 FIFO status for both */
/* the above description is inverted
* oneukum 2007-03-14 */
if (unlikely(length != 4)) {
dev_dbg(dev, "Wrong data !!!\n");
return;
}
sp1 = data[3];
sp2 = data[2];
if ((sp1 | sp2) & 0x01) {
/* No Interrupt Pending in both the ports */
dev_dbg(dev, "No Interrupt !!!\n");
} else {
switch (sp1 & 0x0f) {
case SERIAL_IIR_RLS:
dev_dbg(dev, "Serial Port 1: Receiver status error or address bit detected in 9-bit mode\n");
break;
case SERIAL_IIR_CTI:
dev_dbg(dev, "Serial Port 1: Receiver time out\n");
break;
case SERIAL_IIR_MS:
/* dev_dbg(dev, "Serial Port 1: Modem status change\n"); */
break;
}
switch (sp2 & 0x0f) {
case SERIAL_IIR_RLS:
dev_dbg(dev, "Serial Port 2: Receiver status error or address bit detected in 9-bit mode\n");
break;
case SERIAL_IIR_CTI:
dev_dbg(dev, "Serial Port 2: Receiver time out\n");
break;
case SERIAL_IIR_MS:
/* dev_dbg(dev, "Serial Port 2: Modem status change\n"); */
break;
}
}
exit:
result = usb_submit_urb(urb, GFP_ATOMIC);
if (result)
dev_err(dev, "%s - Error %d submitting control urb\n", __func__, result);
}
/*
* mos7715_interrupt_callback
* this is the 7715's callback function for when we have received data on
* the interrupt endpoint.
*/
static void mos7715_interrupt_callback(struct urb *urb)
{
int result;
int length;
int status = urb->status;
struct device *dev = &urb->dev->dev;
__u8 *data;
__u8 iir;
switch (status) {
case 0:
/* success */
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
case -ENODEV:
/* this urb is terminated, clean up */
dev_dbg(dev, "%s - urb shutting down with status: %d\n", __func__, status);
return;
default:
dev_dbg(dev, "%s - nonzero urb status received: %d\n", __func__, status);
goto exit;
}
length = urb->actual_length;
data = urb->transfer_buffer;
/* Structure of data from 7715 device:
* Byte 1: IIR serial Port
* Byte 2: unused
* Byte 2: DSR parallel port
* Byte 4: FIFO status for both */
if (unlikely(length != 4)) {
dev_dbg(dev, "Wrong data !!!\n");
return;
}
iir = data[0];
if (!(iir & 0x01)) { /* serial port interrupt pending */
switch (iir & 0x0f) {
case SERIAL_IIR_RLS:
dev_dbg(dev, "Serial Port: Receiver status error or address bit detected in 9-bit mode\n\n");
break;
case SERIAL_IIR_CTI:
dev_dbg(dev, "Serial Port: Receiver time out\n");
break;
case SERIAL_IIR_MS:
/* dev_dbg(dev, "Serial Port: Modem status change\n"); */
break;
}
}
#ifdef CONFIG_USB_SERIAL_MOS7715_PARPORT
{ /* update local copy of DSR reg */
struct usb_serial_port *port = urb->context;
struct mos7715_parport *mos_parport = port->serial->private;
if (unlikely(mos_parport == NULL))
return;
atomic_set(&mos_parport->shadowDSR, data[2]);
}
#endif
exit:
result = usb_submit_urb(urb, GFP_ATOMIC);
if (result)
dev_err(dev, "%s - Error %d submitting control urb\n", __func__, result);
}
/*
* mos7720_bulk_in_callback
* this is the callback function for when we have received data on the
* bulk in endpoint.
*/
static void mos7720_bulk_in_callback(struct urb *urb)
{
int retval;
unsigned char *data ;
struct usb_serial_port *port;
int status = urb->status;
if (status) {
dev_dbg(&urb->dev->dev, "nonzero read bulk status received: %d\n", status);
return;
}
port = urb->context;
dev_dbg(&port->dev, "Entering...%s\n", __func__);
data = urb->transfer_buffer;
if (urb->actual_length) {
tty_insert_flip_string(&port->port, data, urb->actual_length);
tty_flip_buffer_push(&port->port);
}
if (port->read_urb->status != -EINPROGRESS) {
retval = usb_submit_urb(port->read_urb, GFP_ATOMIC);
if (retval)
dev_dbg(&port->dev, "usb_submit_urb(read bulk) failed, retval = %d\n", retval);
}
}
/*
* mos7720_bulk_out_data_callback
* this is the callback function for when we have finished sending serial
* data on the bulk out endpoint.
*/
static void mos7720_bulk_out_data_callback(struct urb *urb)
{
struct moschip_port *mos7720_port;
int status = urb->status;
if (status) {
dev_dbg(&urb->dev->dev, "nonzero write bulk status received:%d\n", status);
return;
}
mos7720_port = urb->context;
if (!mos7720_port) {
dev_dbg(&urb->dev->dev, "NULL mos7720_port pointer\n");
return ;
}
if (mos7720_port->open)
tty_port_tty_wakeup(&mos7720_port->port->port);
}
/*
* mos77xx_probe
* this function installs the appropriate read interrupt endpoint callback
* depending on whether the device is a 7720 or 7715, thus avoiding costly
* run-time checks in the high-frequency callback routine itself.
*/
static int mos77xx_probe(struct usb_serial *serial,
const struct usb_device_id *id)
{
if (id->idProduct == MOSCHIP_DEVICE_ID_7715)
moschip7720_2port_driver.read_int_callback =
mos7715_interrupt_callback;
else
moschip7720_2port_driver.read_int_callback =
mos7720_interrupt_callback;
return 0;
}
static int mos77xx_calc_num_ports(struct usb_serial *serial)
{
u16 product = le16_to_cpu(serial->dev->descriptor.idProduct);
if (product == MOSCHIP_DEVICE_ID_7715)
return 1;
return 2;
}
static int mos7720_open(struct tty_struct *tty, struct usb_serial_port *port)
{
struct usb_serial *serial;
struct urb *urb;
struct moschip_port *mos7720_port;
int response;
int port_number;
__u8 data;
int allocated_urbs = 0;
int j;
serial = port->serial;
mos7720_port = usb_get_serial_port_data(port);
if (mos7720_port == NULL)
return -ENODEV;
usb_clear_halt(serial->dev, port->write_urb->pipe);
usb_clear_halt(serial->dev, port->read_urb->pipe);
/* Initialising the write urb pool */
for (j = 0; j < NUM_URBS; ++j) {
urb = usb_alloc_urb(0, GFP_KERNEL);
mos7720_port->write_urb_pool[j] = urb;
if (urb == NULL) {
dev_err(&port->dev, "No more urbs???\n");
continue;
}
urb->transfer_buffer = kmalloc(URB_TRANSFER_BUFFER_SIZE,
GFP_KERNEL);
if (!urb->transfer_buffer) {
dev_err(&port->dev,
"%s-out of memory for urb buffers.\n",
__func__);
usb_free_urb(mos7720_port->write_urb_pool[j]);
mos7720_port->write_urb_pool[j] = NULL;
continue;
}
allocated_urbs++;
}
if (!allocated_urbs)
return -ENOMEM;
/* Initialize MCS7720 -- Write Init values to corresponding Registers
*
* Register Index
* 0 : THR/RHR
* 1 : IER
* 2 : FCR
* 3 : LCR
* 4 : MCR
* 5 : LSR
* 6 : MSR
* 7 : SPR
*
* 0x08 : SP1/2 Control Reg
*/
port_number = port->number - port->serial->minor;
read_mos_reg(serial, port_number, LSR, &data);
dev_dbg(&port->dev, "SS::%p LSR:%x\n", mos7720_port, data);
write_mos_reg(serial, dummy, SP1_REG, 0x02);
write_mos_reg(serial, dummy, SP2_REG, 0x02);
write_mos_reg(serial, port_number, IER, 0x00);
write_mos_reg(serial, port_number, FCR, 0x00);
write_mos_reg(serial, port_number, FCR, 0xcf);
mos7720_port->shadowLCR = 0x03;
write_mos_reg(serial, port_number, LCR, mos7720_port->shadowLCR);
mos7720_port->shadowMCR = 0x0b;
write_mos_reg(serial, port_number, MCR, mos7720_port->shadowMCR);
write_mos_reg(serial, port_number, SP_CONTROL_REG, 0x00);
read_mos_reg(serial, dummy, SP_CONTROL_REG, &data);
data = data | (port->number - port->serial->minor + 1);
write_mos_reg(serial, dummy, SP_CONTROL_REG, data);
mos7720_port->shadowLCR = 0x83;
write_mos_reg(serial, port_number, LCR, mos7720_port->shadowLCR);
write_mos_reg(serial, port_number, THR, 0x0c);
write_mos_reg(serial, port_number, IER, 0x00);
mos7720_port->shadowLCR = 0x03;
write_mos_reg(serial, port_number, LCR, mos7720_port->shadowLCR);
write_mos_reg(serial, port_number, IER, 0x0c);
response = usb_submit_urb(port->read_urb, GFP_KERNEL);
if (response)
dev_err(&port->dev, "%s - Error %d submitting read urb\n",
__func__, response);
/* initialize our port settings */
mos7720_port->shadowMCR = UART_MCR_OUT2; /* Must set to enable ints! */
/* send a open port command */
mos7720_port->open = 1;
return 0;
}
/*
* mos7720_chars_in_buffer
* this function is called by the tty driver when it wants to know how many
* bytes of data we currently have outstanding in the port (data that has
* been written, but hasn't made it out the port yet)
* If successful, we return the number of bytes left to be written in the
* system,
* Otherwise we return a negative error number.
*/
static int mos7720_chars_in_buffer(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
int i;
int chars = 0;
struct moschip_port *mos7720_port;
mos7720_port = usb_get_serial_port_data(port);
if (mos7720_port == NULL)
return 0;
for (i = 0; i < NUM_URBS; ++i) {
if (mos7720_port->write_urb_pool[i] &&
mos7720_port->write_urb_pool[i]->status == -EINPROGRESS)
chars += URB_TRANSFER_BUFFER_SIZE;
}
dev_dbg(&port->dev, "%s - returns %d\n", __func__, chars);
return chars;
}
static void mos7720_close(struct usb_serial_port *port)
{
struct usb_serial *serial;
struct moschip_port *mos7720_port;
int j;
serial = port->serial;
mos7720_port = usb_get_serial_port_data(port);
if (mos7720_port == NULL)
return;
for (j = 0; j < NUM_URBS; ++j)
usb_kill_urb(mos7720_port->write_urb_pool[j]);
/* Freeing Write URBs */
for (j = 0; j < NUM_URBS; ++j) {
if (mos7720_port->write_urb_pool[j]) {
kfree(mos7720_port->write_urb_pool[j]->transfer_buffer);
usb_free_urb(mos7720_port->write_urb_pool[j]);
}
}
/* While closing port, shutdown all bulk read, write *
* and interrupt read if they exists, otherwise nop */
usb_kill_urb(port->write_urb);
usb_kill_urb(port->read_urb);
write_mos_reg(serial, port->number - port->serial->minor, MCR, 0x00);
write_mos_reg(serial, port->number - port->serial->minor, IER, 0x00);
mos7720_port->open = 0;
}
static void mos7720_break(struct tty_struct *tty, int break_state)
{
struct usb_serial_port *port = tty->driver_data;
unsigned char data;
struct usb_serial *serial;
struct moschip_port *mos7720_port;
serial = port->serial;
mos7720_port = usb_get_serial_port_data(port);
if (mos7720_port == NULL)
return;
if (break_state == -1)
data = mos7720_port->shadowLCR | UART_LCR_SBC;
else
data = mos7720_port->shadowLCR & ~UART_LCR_SBC;
mos7720_port->shadowLCR = data;
write_mos_reg(serial, port->number - port->serial->minor,
LCR, mos7720_port->shadowLCR);
}
/*
* mos7720_write_room
* this function is called by the tty driver when it wants to know how many
* bytes of data we can accept for a specific port.
* If successful, we return the amount of room that we have for this port
* Otherwise we return a negative error number.
*/
static int mos7720_write_room(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct moschip_port *mos7720_port;
int room = 0;
int i;
mos7720_port = usb_get_serial_port_data(port);
if (mos7720_port == NULL)
return -ENODEV;
/* FIXME: Locking */
for (i = 0; i < NUM_URBS; ++i) {
if (mos7720_port->write_urb_pool[i] &&
mos7720_port->write_urb_pool[i]->status != -EINPROGRESS)
room += URB_TRANSFER_BUFFER_SIZE;
}
dev_dbg(&port->dev, "%s - returns %d\n", __func__, room);
return room;
}
static int mos7720_write(struct tty_struct *tty, struct usb_serial_port *port,
const unsigned char *data, int count)
{
int status;
int i;
int bytes_sent = 0;
int transfer_size;
struct moschip_port *mos7720_port;
struct usb_serial *serial;
struct urb *urb;
const unsigned char *current_position = data;
serial = port->serial;
mos7720_port = usb_get_serial_port_data(port);
if (mos7720_port == NULL)
return -ENODEV;
/* try to find a free urb in the list */
urb = NULL;
for (i = 0; i < NUM_URBS; ++i) {
if (mos7720_port->write_urb_pool[i] &&
mos7720_port->write_urb_pool[i]->status != -EINPROGRESS) {
urb = mos7720_port->write_urb_pool[i];
dev_dbg(&port->dev, "URB:%d\n", i);
break;
}
}
if (urb == NULL) {
dev_dbg(&port->dev, "%s - no more free urbs\n", __func__);
goto exit;
}
if (urb->transfer_buffer == NULL) {
urb->transfer_buffer = kmalloc(URB_TRANSFER_BUFFER_SIZE,
GFP_KERNEL);
if (urb->transfer_buffer == NULL) {
dev_err_console(port, "%s no more kernel memory...\n",
__func__);
goto exit;
}
}
transfer_size = min(count, URB_TRANSFER_BUFFER_SIZE);
memcpy(urb->transfer_buffer, current_position, transfer_size);
usb_serial_debug_data(&port->dev, __func__, transfer_size,
urb->transfer_buffer);
/* fill urb with data and submit */
usb_fill_bulk_urb(urb, serial->dev,
usb_sndbulkpipe(serial->dev,
port->bulk_out_endpointAddress),
urb->transfer_buffer, transfer_size,
mos7720_bulk_out_data_callback, mos7720_port);
/* send it down the pipe */
status = usb_submit_urb(urb, GFP_ATOMIC);
if (status) {
dev_err_console(port, "%s - usb_submit_urb(write bulk) failed "
"with status = %d\n", __func__, status);
bytes_sent = status;
goto exit;
}
bytes_sent = transfer_size;
exit:
return bytes_sent;
}
static void mos7720_throttle(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct moschip_port *mos7720_port;
int status;
mos7720_port = usb_get_serial_port_data(port);
if (mos7720_port == NULL)
return;
if (!mos7720_port->open) {
dev_dbg(&port->dev, "%s - port not opened\n", __func__);
return;
}
/* if we are implementing XON/XOFF, send the stop character */
if (I_IXOFF(tty)) {
unsigned char stop_char = STOP_CHAR(tty);
status = mos7720_write(tty, port, &stop_char, 1);
if (status <= 0)
return;
}
/* if we are implementing RTS/CTS, toggle that line */
if (tty->termios.c_cflag & CRTSCTS) {
mos7720_port->shadowMCR &= ~UART_MCR_RTS;
write_mos_reg(port->serial, port->number - port->serial->minor,
MCR, mos7720_port->shadowMCR);
if (status != 0)
return;
}
}
static void mos7720_unthrottle(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct moschip_port *mos7720_port = usb_get_serial_port_data(port);
int status;
if (mos7720_port == NULL)
return;
if (!mos7720_port->open) {
dev_dbg(&port->dev, "%s - port not opened\n", __func__);
return;
}
/* if we are implementing XON/XOFF, send the start character */
if (I_IXOFF(tty)) {
unsigned char start_char = START_CHAR(tty);
status = mos7720_write(tty, port, &start_char, 1);
if (status <= 0)
return;
}
/* if we are implementing RTS/CTS, toggle that line */
if (tty->termios.c_cflag & CRTSCTS) {
mos7720_port->shadowMCR |= UART_MCR_RTS;
write_mos_reg(port->serial, port->number - port->serial->minor,
MCR, mos7720_port->shadowMCR);
if (status != 0)
return;
}
}
/* FIXME: this function does not work */
static int set_higher_rates(struct moschip_port *mos7720_port,
unsigned int baud)
{
struct usb_serial_port *port;
struct usb_serial *serial;
int port_number;
enum mos_regs sp_reg;
if (mos7720_port == NULL)
return -EINVAL;
port = mos7720_port->port;
serial = port->serial;
/***********************************************
* Init Sequence for higher rates
***********************************************/
dev_dbg(&port->dev, "Sending Setting Commands ..........\n");
port_number = port->number - port->serial->minor;
write_mos_reg(serial, port_number, IER, 0x00);
write_mos_reg(serial, port_number, FCR, 0x00);
write_mos_reg(serial, port_number, FCR, 0xcf);
mos7720_port->shadowMCR = 0x0b;
write_mos_reg(serial, port_number, MCR, mos7720_port->shadowMCR);
write_mos_reg(serial, dummy, SP_CONTROL_REG, 0x00);
/***********************************************
* Set for higher rates *
***********************************************/
/* writing baud rate verbatum into uart clock field clearly not right */
if (port_number == 0)
sp_reg = SP1_REG;
else
sp_reg = SP2_REG;
write_mos_reg(serial, dummy, sp_reg, baud * 0x10);
write_mos_reg(serial, dummy, SP_CONTROL_REG, 0x03);
mos7720_port->shadowMCR = 0x2b;
write_mos_reg(serial, port_number, MCR, mos7720_port->shadowMCR);
/***********************************************
* Set DLL/DLM
***********************************************/
mos7720_port->shadowLCR = mos7720_port->shadowLCR | UART_LCR_DLAB;
write_mos_reg(serial, port_number, LCR, mos7720_port->shadowLCR);
write_mos_reg(serial, port_number, DLL, 0x01);
write_mos_reg(serial, port_number, DLM, 0x00);
mos7720_port->shadowLCR = mos7720_port->shadowLCR & ~UART_LCR_DLAB;
write_mos_reg(serial, port_number, LCR, mos7720_port->shadowLCR);
return 0;
}
/* baud rate information */
struct divisor_table_entry {
__u32 baudrate;
__u16 divisor;
};
/* Define table of divisors for moschip 7720 hardware *
* These assume a 3.6864MHz crystal, the standard /16, and *
* MCR.7 = 0. */
static struct divisor_table_entry divisor_table[] = {
{ 50, 2304},
{ 110, 1047}, /* 2094.545455 => 230450 => .0217 % over */
{ 134, 857}, /* 1713.011152 => 230398.5 => .00065% under */
{ 150, 768},
{ 300, 384},
{ 600, 192},
{ 1200, 96},
{ 1800, 64},
{ 2400, 48},
{ 4800, 24},
{ 7200, 16},
{ 9600, 12},
{ 19200, 6},
{ 38400, 3},
{ 57600, 2},
{ 115200, 1},
};
/*****************************************************************************
* calc_baud_rate_divisor
* this function calculates the proper baud rate divisor for the specified
* baud rate.
*****************************************************************************/
static int calc_baud_rate_divisor(struct usb_serial_port *port, int baudrate, int *divisor)
{
int i;
__u16 custom;
__u16 round1;
__u16 round;
dev_dbg(&port->dev, "%s - %d\n", __func__, baudrate);
for (i = 0; i < ARRAY_SIZE(divisor_table); i++) {
if (divisor_table[i].baudrate == baudrate) {
*divisor = divisor_table[i].divisor;
return 0;
}
}
/* After trying for all the standard baud rates *
* Try calculating the divisor for this baud rate */
if (baudrate > 75 && baudrate < 230400) {
/* get the divisor */
custom = (__u16)(230400L / baudrate);
/* Check for round off */
round1 = (__u16)(2304000L / baudrate);
round = (__u16)(round1 - (custom * 10));
if (round > 4)
custom++;
*divisor = custom;
dev_dbg(&port->dev, "Baud %d = %d\n", baudrate, custom);
return 0;
}
dev_dbg(&port->dev, "Baud calculation Failed...\n");
return -EINVAL;
}
/*
* send_cmd_write_baud_rate
* this function sends the proper command to change the baud rate of the
* specified port.
*/
static int send_cmd_write_baud_rate(struct moschip_port *mos7720_port,
int baudrate)
{
struct usb_serial_port *port;
struct usb_serial *serial;
int divisor;
int status;
unsigned char number;
if (mos7720_port == NULL)
return -1;
port = mos7720_port->port;
serial = port->serial;
number = port->number - port->serial->minor;
dev_dbg(&port->dev, "%s - baud = %d\n", __func__, baudrate);
/* Calculate the Divisor */
status = calc_baud_rate_divisor(port, baudrate, &divisor);
if (status) {
dev_err(&port->dev, "%s - bad baud rate\n", __func__);
return status;
}
/* Enable access to divisor latch */
mos7720_port->shadowLCR = mos7720_port->shadowLCR | UART_LCR_DLAB;
write_mos_reg(serial, number, LCR, mos7720_port->shadowLCR);
/* Write the divisor */
write_mos_reg(serial, number, DLL, (__u8)(divisor & 0xff));
write_mos_reg(serial, number, DLM, (__u8)((divisor & 0xff00) >> 8));
/* Disable access to divisor latch */
mos7720_port->shadowLCR = mos7720_port->shadowLCR & ~UART_LCR_DLAB;
write_mos_reg(serial, number, LCR, mos7720_port->shadowLCR);
return status;
}
/*
* change_port_settings
* This routine is called to set the UART on the device to match
* the specified new settings.
*/
static void change_port_settings(struct tty_struct *tty,
struct moschip_port *mos7720_port,
struct ktermios *old_termios)
{
struct usb_serial_port *port;
struct usb_serial *serial;
int baud;
unsigned cflag;
unsigned iflag;
__u8 mask = 0xff;
__u8 lData;
__u8 lParity;
__u8 lStop;
int status;
int port_number;
if (mos7720_port == NULL)
return ;
port = mos7720_port->port;
serial = port->serial;
port_number = port->number - port->serial->minor;
if (!mos7720_port->open) {
dev_dbg(&port->dev, "%s - port not opened\n", __func__);
return;
}
lData = UART_LCR_WLEN8;
lStop = 0x00; /* 1 stop bit */
lParity = 0x00; /* No parity */
cflag = tty->termios.c_cflag;
iflag = tty->termios.c_iflag;
/* Change the number of bits */
switch (cflag & CSIZE) {
case CS5:
lData = UART_LCR_WLEN5;
mask = 0x1f;
break;
case CS6:
lData = UART_LCR_WLEN6;
mask = 0x3f;
break;
case CS7:
lData = UART_LCR_WLEN7;
mask = 0x7f;
break;
default:
case CS8:
lData = UART_LCR_WLEN8;
break;
}
/* Change the Parity bit */
if (cflag & PARENB) {
if (cflag & PARODD) {
lParity = UART_LCR_PARITY;
dev_dbg(&port->dev, "%s - parity = odd\n", __func__);
} else {
lParity = (UART_LCR_EPAR | UART_LCR_PARITY);
dev_dbg(&port->dev, "%s - parity = even\n", __func__);
}
} else {
dev_dbg(&port->dev, "%s - parity = none\n", __func__);
}
if (cflag & CMSPAR)
lParity = lParity | 0x20;
/* Change the Stop bit */
if (cflag & CSTOPB) {
lStop = UART_LCR_STOP;
dev_dbg(&port->dev, "%s - stop bits = 2\n", __func__);
} else {
lStop = 0x00;
dev_dbg(&port->dev, "%s - stop bits = 1\n", __func__);
}
#define LCR_BITS_MASK 0x03 /* Mask for bits/char field */
#define LCR_STOP_MASK 0x04 /* Mask for stop bits field */
#define LCR_PAR_MASK 0x38 /* Mask for parity field */
/* Update the LCR with the correct value */
mos7720_port->shadowLCR &=
~(LCR_BITS_MASK | LCR_STOP_MASK | LCR_PAR_MASK);
mos7720_port->shadowLCR |= (lData | lParity | lStop);
/* Disable Interrupts */
write_mos_reg(serial, port_number, IER, 0x00);
write_mos_reg(serial, port_number, FCR, 0x00);
write_mos_reg(serial, port_number, FCR, 0xcf);
/* Send the updated LCR value to the mos7720 */
write_mos_reg(serial, port_number, LCR, mos7720_port->shadowLCR);
mos7720_port->shadowMCR = 0x0b;
write_mos_reg(serial, port_number, MCR, mos7720_port->shadowMCR);
/* set up the MCR register and send it to the mos7720 */
mos7720_port->shadowMCR = UART_MCR_OUT2;
if (cflag & CBAUD)
mos7720_port->shadowMCR |= (UART_MCR_DTR | UART_MCR_RTS);
if (cflag & CRTSCTS) {
mos7720_port->shadowMCR |= (UART_MCR_XONANY);
/* To set hardware flow control to the specified *
* serial port, in SP1/2_CONTROL_REG */
if (port_number)
write_mos_reg(serial, dummy, SP_CONTROL_REG, 0x01);
else
write_mos_reg(serial, dummy, SP_CONTROL_REG, 0x02);
} else
mos7720_port->shadowMCR &= ~(UART_MCR_XONANY);
write_mos_reg(serial, port_number, MCR, mos7720_port->shadowMCR);
/* Determine divisor based on baud rate */
baud = tty_get_baud_rate(tty);
if (!baud) {
/* pick a default, any default... */
dev_dbg(&port->dev, "Picked default baud...\n");
baud = 9600;
}
if (baud >= 230400) {
set_higher_rates(mos7720_port, baud);
/* Enable Interrupts */
write_mos_reg(serial, port_number, IER, 0x0c);
return;
}
dev_dbg(&port->dev, "%s - baud rate = %d\n", __func__, baud);
status = send_cmd_write_baud_rate(mos7720_port, baud);
/* FIXME: needs to write actual resulting baud back not just
blindly do so */
if (cflag & CBAUD)
tty_encode_baud_rate(tty, baud, baud);
/* Enable Interrupts */
write_mos_reg(serial, port_number, IER, 0x0c);
if (port->read_urb->status != -EINPROGRESS) {
status = usb_submit_urb(port->read_urb, GFP_ATOMIC);
if (status)
dev_dbg(&port->dev, "usb_submit_urb(read bulk) failed, status = %d\n", status);
}
}
/*
* mos7720_set_termios
* this function is called by the tty driver when it wants to change the
* termios structure.
*/
static void mos7720_set_termios(struct tty_struct *tty,
struct usb_serial_port *port, struct ktermios *old_termios)
{
int status;
unsigned int cflag;
struct usb_serial *serial;
struct moschip_port *mos7720_port;
serial = port->serial;
mos7720_port = usb_get_serial_port_data(port);
if (mos7720_port == NULL)
return;
if (!mos7720_port->open) {
dev_dbg(&port->dev, "%s - port not opened\n", __func__);
return;
}
dev_dbg(&port->dev, "setting termios - ASPIRE\n");
cflag = tty->termios.c_cflag;
dev_dbg(&port->dev, "%s - cflag %08x iflag %08x\n", __func__,
tty->termios.c_cflag, RELEVANT_IFLAG(tty->termios.c_iflag));
dev_dbg(&port->dev, "%s - old cflag %08x old iflag %08x\n", __func__,
old_termios->c_cflag, RELEVANT_IFLAG(old_termios->c_iflag));
/* change the port settings to the new ones specified */
change_port_settings(tty, mos7720_port, old_termios);
if (port->read_urb->status != -EINPROGRESS) {
status = usb_submit_urb(port->read_urb, GFP_ATOMIC);
if (status)
dev_dbg(&port->dev, "usb_submit_urb(read bulk) failed, status = %d\n", status);
}
}
/*
* get_lsr_info - get line status register info
*
* Purpose: Let user call ioctl() to get info when the UART physically
* is emptied. On bus types like RS485, the transmitter must
* release the bus after transmitting. This must be done when
* the transmit shift register is empty, not be done when the
* transmit holding register is empty. This functionality
* allows an RS485 driver to be written in user space.
*/
static int get_lsr_info(struct tty_struct *tty,
struct moschip_port *mos7720_port, unsigned int __user *value)
{
struct usb_serial_port *port = tty->driver_data;
unsigned int result = 0;
unsigned char data = 0;
int port_number = port->number - port->serial->minor;
int count;
count = mos7720_chars_in_buffer(tty);
if (count == 0) {
read_mos_reg(port->serial, port_number, LSR, &data);
if ((data & (UART_LSR_TEMT | UART_LSR_THRE))
== (UART_LSR_TEMT | UART_LSR_THRE)) {
dev_dbg(&port->dev, "%s -- Empty\n", __func__);
result = TIOCSER_TEMT;
}
}
if (copy_to_user(value, &result, sizeof(int)))
return -EFAULT;
return 0;
}
static int mos7720_tiocmget(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct moschip_port *mos7720_port = usb_get_serial_port_data(port);
unsigned int result = 0;
unsigned int mcr ;
unsigned int msr ;
mcr = mos7720_port->shadowMCR;
msr = mos7720_port->shadowMSR;
result = ((mcr & UART_MCR_DTR) ? TIOCM_DTR : 0) /* 0x002 */
| ((mcr & UART_MCR_RTS) ? TIOCM_RTS : 0) /* 0x004 */
| ((msr & UART_MSR_CTS) ? TIOCM_CTS : 0) /* 0x020 */
| ((msr & UART_MSR_DCD) ? TIOCM_CAR : 0) /* 0x040 */
| ((msr & UART_MSR_RI) ? TIOCM_RI : 0) /* 0x080 */
| ((msr & UART_MSR_DSR) ? TIOCM_DSR : 0); /* 0x100 */
return result;
}
static int mos7720_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear)
{
struct usb_serial_port *port = tty->driver_data;
struct moschip_port *mos7720_port = usb_get_serial_port_data(port);
unsigned int mcr ;
mcr = mos7720_port->shadowMCR;
if (set & TIOCM_RTS)
mcr |= UART_MCR_RTS;
if (set & TIOCM_DTR)
mcr |= UART_MCR_DTR;
if (set & TIOCM_LOOP)
mcr |= UART_MCR_LOOP;
if (clear & TIOCM_RTS)
mcr &= ~UART_MCR_RTS;
if (clear & TIOCM_DTR)
mcr &= ~UART_MCR_DTR;
if (clear & TIOCM_LOOP)
mcr &= ~UART_MCR_LOOP;
mos7720_port->shadowMCR = mcr;
write_mos_reg(port->serial, port->number - port->serial->minor,
MCR, mos7720_port->shadowMCR);
return 0;
}
static int set_modem_info(struct moschip_port *mos7720_port, unsigned int cmd,
unsigned int __user *value)
{
unsigned int mcr;
unsigned int arg;
struct usb_serial_port *port;
if (mos7720_port == NULL)
return -1;
port = (struct usb_serial_port *)mos7720_port->port;
mcr = mos7720_port->shadowMCR;
if (copy_from_user(&arg, value, sizeof(int)))
return -EFAULT;
switch (cmd) {
case TIOCMBIS:
if (arg & TIOCM_RTS)
mcr |= UART_MCR_RTS;
if (arg & TIOCM_DTR)
mcr |= UART_MCR_RTS;
if (arg & TIOCM_LOOP)
mcr |= UART_MCR_LOOP;
break;
case TIOCMBIC:
if (arg & TIOCM_RTS)
mcr &= ~UART_MCR_RTS;
if (arg & TIOCM_DTR)
mcr &= ~UART_MCR_RTS;
if (arg & TIOCM_LOOP)
mcr &= ~UART_MCR_LOOP;
break;
}
mos7720_port->shadowMCR = mcr;
write_mos_reg(port->serial, port->number - port->serial->minor,
MCR, mos7720_port->shadowMCR);
return 0;
}
static int get_serial_info(struct moschip_port *mos7720_port,
struct serial_struct __user *retinfo)
{
struct serial_struct tmp;
if (!retinfo)
return -EFAULT;
memset(&tmp, 0, sizeof(tmp));
tmp.type = PORT_16550A;
tmp.line = mos7720_port->port->serial->minor;
tmp.port = mos7720_port->port->number;
tmp.irq = 0;
tmp.flags = ASYNC_SKIP_TEST | ASYNC_AUTO_IRQ;
tmp.xmit_fifo_size = NUM_URBS * URB_TRANSFER_BUFFER_SIZE;
tmp.baud_base = 9600;
tmp.close_delay = 5*HZ;
tmp.closing_wait = 30*HZ;
if (copy_to_user(retinfo, &tmp, sizeof(*retinfo)))
return -EFAULT;
return 0;
}
static int mos7720_ioctl(struct tty_struct *tty,
unsigned int cmd, unsigned long arg)
{
struct usb_serial_port *port = tty->driver_data;
struct moschip_port *mos7720_port;
mos7720_port = usb_get_serial_port_data(port);
if (mos7720_port == NULL)
return -ENODEV;
dev_dbg(&port->dev, "%s - cmd = 0x%x", __func__, cmd);
switch (cmd) {
case TIOCSERGETLSR:
dev_dbg(&port->dev, "%s TIOCSERGETLSR\n", __func__);
return get_lsr_info(tty, mos7720_port,
(unsigned int __user *)arg);
/* FIXME: These should be using the mode methods */
case TIOCMBIS:
case TIOCMBIC:
dev_dbg(&port->dev, "%s TIOCMSET/TIOCMBIC/TIOCMSET\n", __func__);
return set_modem_info(mos7720_port, cmd,
(unsigned int __user *)arg);
case TIOCGSERIAL:
dev_dbg(&port->dev, "%s TIOCGSERIAL\n", __func__);
return get_serial_info(mos7720_port,
(struct serial_struct __user *)arg);
}
return -ENOIOCTLCMD;
}
static int mos7720_startup(struct usb_serial *serial)
{
struct usb_device *dev;
char data;
u16 product;
int ret_val;
product = le16_to_cpu(serial->dev->descriptor.idProduct);
dev = serial->dev;
/*
* The 7715 uses the first bulk in/out endpoint pair for the parallel
* port, and the second for the serial port. Because the usbserial core
* assumes both pairs are serial ports, we must engage in a bit of
* subterfuge and swap the pointers for ports 0 and 1 in order to make
* port 0 point to the serial port. However, both moschip devices use a
* single interrupt-in endpoint for both ports (as mentioned a little
* further down), and this endpoint was assigned to port 0. So after
* the swap, we must copy the interrupt endpoint elements from port 1
* (as newly assigned) to port 0, and null out port 1 pointers.
*/
if (product == MOSCHIP_DEVICE_ID_7715) {
struct usb_serial_port *tmp = serial->port[0];
serial->port[0] = serial->port[1];
serial->port[1] = tmp;
serial->port[0]->interrupt_in_urb = tmp->interrupt_in_urb;
serial->port[0]->interrupt_in_buffer = tmp->interrupt_in_buffer;
serial->port[0]->interrupt_in_endpointAddress =
tmp->interrupt_in_endpointAddress;
serial->port[1]->interrupt_in_urb = NULL;
serial->port[1]->interrupt_in_buffer = NULL;
}
/* setting configuration feature to one */
usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
(__u8)0x03, 0x00, 0x01, 0x00, NULL, 0x00, 5000);
/* start the interrupt urb */
ret_val = usb_submit_urb(serial->port[0]->interrupt_in_urb, GFP_KERNEL);
if (ret_val)
dev_err(&dev->dev,
"%s - Error %d submitting control urb\n",
__func__, ret_val);
#ifdef CONFIG_USB_SERIAL_MOS7715_PARPORT
if (product == MOSCHIP_DEVICE_ID_7715) {
ret_val = mos7715_parport_init(serial);
if (ret_val < 0)
return ret_val;
}
#endif
/* LSR For Port 1 */
read_mos_reg(serial, 0, LSR, &data);
dev_dbg(&dev->dev, "LSR:%x\n", data);
return 0;
}
static void mos7720_release(struct usb_serial *serial)
{
#ifdef CONFIG_USB_SERIAL_MOS7715_PARPORT
/* close the parallel port */
if (le16_to_cpu(serial->dev->descriptor.idProduct)
== MOSCHIP_DEVICE_ID_7715) {
struct urbtracker *urbtrack;
unsigned long flags;
struct mos7715_parport *mos_parport =
usb_get_serial_data(serial);
/* prevent NULL ptr dereference in port callbacks */
spin_lock(&release_lock);
mos_parport->pp->private_data = NULL;
spin_unlock(&release_lock);
/* wait for synchronous usb calls to return */
if (mos_parport->msg_pending)
wait_for_completion_timeout(&mos_parport->syncmsg_compl,
msecs_to_jiffies(MOS_WDR_TIMEOUT));
parport_remove_port(mos_parport->pp);
usb_set_serial_data(serial, NULL);
mos_parport->serial = NULL;
/* if tasklet currently scheduled, wait for it to complete */
tasklet_kill(&mos_parport->urb_tasklet);
/* unlink any urbs sent by the tasklet */
spin_lock_irqsave(&mos_parport->listlock, flags);
list_for_each_entry(urbtrack,
&mos_parport->active_urbs,
urblist_entry)
usb_unlink_urb(urbtrack->urb);
spin_unlock_irqrestore(&mos_parport->listlock, flags);
kref_put(&mos_parport->ref_count, destroy_mos_parport);
}
#endif
}
static int mos7720_port_probe(struct usb_serial_port *port)
{
struct moschip_port *mos7720_port;
mos7720_port = kzalloc(sizeof(*mos7720_port), GFP_KERNEL);
if (!mos7720_port)
return -ENOMEM;
/* Initialize all port interrupt end point to port 0 int endpoint.
* Our device has only one interrupt endpoint common to all ports.
*/
port->interrupt_in_endpointAddress =
port->serial->port[0]->interrupt_in_endpointAddress;
mos7720_port->port = port;
usb_set_serial_port_data(port, mos7720_port);
return 0;
}
static int mos7720_port_remove(struct usb_serial_port *port)
{
struct moschip_port *mos7720_port;
mos7720_port = usb_get_serial_port_data(port);
kfree(mos7720_port);
return 0;
}
static struct usb_serial_driver moschip7720_2port_driver = {
.driver = {
.owner = THIS_MODULE,
.name = "moschip7720",
},
.description = "Moschip 2 port adapter",
.id_table = id_table,
.calc_num_ports = mos77xx_calc_num_ports,
.open = mos7720_open,
.close = mos7720_close,
.throttle = mos7720_throttle,
.unthrottle = mos7720_unthrottle,
.probe = mos77xx_probe,
.attach = mos7720_startup,
.release = mos7720_release,
.port_probe = mos7720_port_probe,
.port_remove = mos7720_port_remove,
.ioctl = mos7720_ioctl,
.tiocmget = mos7720_tiocmget,
.tiocmset = mos7720_tiocmset,
.set_termios = mos7720_set_termios,
.write = mos7720_write,
.write_room = mos7720_write_room,
.chars_in_buffer = mos7720_chars_in_buffer,
.break_ctl = mos7720_break,
.read_bulk_callback = mos7720_bulk_in_callback,
.read_int_callback = NULL /* dynamically assigned in probe() */
};
static struct usb_serial_driver * const serial_drivers[] = {
&moschip7720_2port_driver, NULL
};
module_usb_serial_driver(serial_drivers, id_table);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
| gpl-2.0 |
Scorpio92/android_kernel_mx2 | sound/soc/codecs/da7210.c | 3023 | 16525 | /*
* DA7210 ALSA Soc codec driver
*
* Copyright (c) 2009 Dialog Semiconductor
* Written by David Chen <Dajun.chen@diasemi.com>
*
* Copyright (C) 2009 Renesas Solutions Corp.
* Cleanups by Kuninori Morimoto <morimoto.kuninori@renesas.com>
*
* Tested on SuperH Ecovec24 board with S16/S24 LE in 48KHz using I2S
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/delay.h>
#include <linux/i2c.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/initval.h>
#include <sound/tlv.h>
/* DA7210 register space */
#define DA7210_STATUS 0x02
#define DA7210_STARTUP1 0x03
#define DA7210_MIC_L 0x07
#define DA7210_MIC_R 0x08
#define DA7210_INMIX_L 0x0D
#define DA7210_INMIX_R 0x0E
#define DA7210_ADC_HPF 0x0F
#define DA7210_ADC 0x10
#define DA7210_DAC_HPF 0x14
#define DA7210_DAC_L 0x15
#define DA7210_DAC_R 0x16
#define DA7210_DAC_SEL 0x17
#define DA7210_OUTMIX_L 0x1C
#define DA7210_OUTMIX_R 0x1D
#define DA7210_HP_L_VOL 0x21
#define DA7210_HP_R_VOL 0x22
#define DA7210_HP_CFG 0x23
#define DA7210_DAI_SRC_SEL 0x25
#define DA7210_DAI_CFG1 0x26
#define DA7210_DAI_CFG3 0x28
#define DA7210_PLL_DIV1 0x29
#define DA7210_PLL_DIV2 0x2A
#define DA7210_PLL_DIV3 0x2B
#define DA7210_PLL 0x2C
#define DA7210_A_HID_UNLOCK 0x8A
#define DA7210_A_TEST_UNLOCK 0x8B
#define DA7210_A_PLL1 0x90
#define DA7210_A_CP_MODE 0xA7
/* STARTUP1 bit fields */
#define DA7210_SC_MST_EN (1 << 0)
/* MIC_L bit fields */
#define DA7210_MICBIAS_EN (1 << 6)
#define DA7210_MIC_L_EN (1 << 7)
/* MIC_R bit fields */
#define DA7210_MIC_R_EN (1 << 7)
/* INMIX_L bit fields */
#define DA7210_IN_L_EN (1 << 7)
/* INMIX_R bit fields */
#define DA7210_IN_R_EN (1 << 7)
/* ADC bit fields */
#define DA7210_ADC_L_EN (1 << 3)
#define DA7210_ADC_R_EN (1 << 7)
/* DAC/ADC HPF fields */
#define DA7210_VOICE_F0_MASK (0x7 << 4)
#define DA7210_VOICE_F0_25 (1 << 4)
#define DA7210_VOICE_EN (1 << 7)
/* DAC_SEL bit fields */
#define DA7210_DAC_L_SRC_DAI_L (4 << 0)
#define DA7210_DAC_L_EN (1 << 3)
#define DA7210_DAC_R_SRC_DAI_R (5 << 4)
#define DA7210_DAC_R_EN (1 << 7)
/* OUTMIX_L bit fields */
#define DA7210_OUT_L_EN (1 << 7)
/* OUTMIX_R bit fields */
#define DA7210_OUT_R_EN (1 << 7)
/* HP_CFG bit fields */
#define DA7210_HP_2CAP_MODE (1 << 1)
#define DA7210_HP_SENSE_EN (1 << 2)
#define DA7210_HP_L_EN (1 << 3)
#define DA7210_HP_MODE (1 << 6)
#define DA7210_HP_R_EN (1 << 7)
/* DAI_SRC_SEL bit fields */
#define DA7210_DAI_OUT_L_SRC (6 << 0)
#define DA7210_DAI_OUT_R_SRC (7 << 4)
/* DAI_CFG1 bit fields */
#define DA7210_DAI_WORD_S16_LE (0 << 0)
#define DA7210_DAI_WORD_S24_LE (2 << 0)
#define DA7210_DAI_FLEN_64BIT (1 << 2)
#define DA7210_DAI_MODE_MASTER (1 << 7)
/* DAI_CFG3 bit fields */
#define DA7210_DAI_FORMAT_I2SMODE (0 << 0)
#define DA7210_DAI_OE (1 << 3)
#define DA7210_DAI_EN (1 << 7)
/*PLL_DIV3 bit fields */
#define DA7210_MCLK_RANGE_10_20_MHZ (1 << 4)
#define DA7210_PLL_BYP (1 << 6)
/* PLL bit fields */
#define DA7210_PLL_FS_MASK (0xF << 0)
#define DA7210_PLL_FS_8000 (0x1 << 0)
#define DA7210_PLL_FS_11025 (0x2 << 0)
#define DA7210_PLL_FS_12000 (0x3 << 0)
#define DA7210_PLL_FS_16000 (0x5 << 0)
#define DA7210_PLL_FS_22050 (0x6 << 0)
#define DA7210_PLL_FS_24000 (0x7 << 0)
#define DA7210_PLL_FS_32000 (0x9 << 0)
#define DA7210_PLL_FS_44100 (0xA << 0)
#define DA7210_PLL_FS_48000 (0xB << 0)
#define DA7210_PLL_FS_88200 (0xE << 0)
#define DA7210_PLL_FS_96000 (0xF << 0)
#define DA7210_PLL_EN (0x1 << 7)
#define DA7210_VERSION "0.0.1"
/*
* Playback Volume
*
* max : 0x3F (+15.0 dB)
* (1.5 dB step)
* min : 0x11 (-54.0 dB)
* mute : 0x10
* reserved : 0x00 - 0x0F
*
* ** FIXME **
*
* Reserved area are considered as "mute".
* -> min = -79.5 dB
*/
static const DECLARE_TLV_DB_SCALE(hp_out_tlv, -7950, 150, 1);
static const struct snd_kcontrol_new da7210_snd_controls[] = {
SOC_DOUBLE_R_TLV("HeadPhone Playback Volume",
DA7210_HP_L_VOL, DA7210_HP_R_VOL,
0, 0x3F, 0, hp_out_tlv),
};
/* Codec private data */
struct da7210_priv {
enum snd_soc_control_type control_type;
void *control_data;
};
/*
* Register cache
*/
static const u8 da7210_reg[] = {
0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* R0 - R7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, /* R8 - RF */
0x00, 0x00, 0x00, 0x00, 0x08, 0x10, 0x10, 0x54, /* R10 - R17 */
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* R18 - R1F */
0x00, 0x00, 0x00, 0x02, 0x00, 0x76, 0x00, 0x00, /* R20 - R27 */
0x04, 0x00, 0x00, 0x30, 0x2A, 0x00, 0x40, 0x00, /* R28 - R2F */
0x40, 0x00, 0x40, 0x00, 0x40, 0x00, 0x40, 0x00, /* R30 - R37 */
0x40, 0x00, 0x40, 0x00, 0x40, 0x00, 0x00, 0x00, /* R38 - R3F */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* R40 - R4F */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* R48 - R4F */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* R50 - R57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* R58 - R5F */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* R60 - R67 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* R68 - R6F */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* R70 - R77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x54, 0x54, 0x00, /* R78 - R7F */
0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x00, 0x00, /* R80 - R87 */
0x00, /* R88 */
};
/*
* Read da7210 register cache
*/
static inline u32 da7210_read_reg_cache(struct snd_soc_codec *codec, u32 reg)
{
u8 *cache = codec->reg_cache;
BUG_ON(reg >= ARRAY_SIZE(da7210_reg));
return cache[reg];
}
/*
* Write to the da7210 register space
*/
static int da7210_write(struct snd_soc_codec *codec, u32 reg, u32 value)
{
u8 *cache = codec->reg_cache;
u8 data[2];
BUG_ON(codec->driver->volatile_register);
data[0] = reg & 0xff;
data[1] = value & 0xff;
if (reg >= codec->driver->reg_cache_size)
return -EIO;
if (2 != codec->hw_write(codec->control_data, data, 2))
return -EIO;
cache[reg] = value;
return 0;
}
/*
* Read from the da7210 register space.
*/
static inline u32 da7210_read(struct snd_soc_codec *codec, u32 reg)
{
if (DA7210_STATUS == reg)
return i2c_smbus_read_byte_data(codec->control_data, reg);
return da7210_read_reg_cache(codec, reg);
}
static int da7210_startup(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
int is_play = substream->stream == SNDRV_PCM_STREAM_PLAYBACK;
struct snd_soc_codec *codec = dai->codec;
if (is_play) {
/* Enable Out */
snd_soc_update_bits(codec, DA7210_OUTMIX_L, 0x1F, 0x10);
snd_soc_update_bits(codec, DA7210_OUTMIX_R, 0x1F, 0x10);
} else {
/* Volume 7 */
snd_soc_update_bits(codec, DA7210_MIC_L, 0x7, 0x7);
snd_soc_update_bits(codec, DA7210_MIC_R, 0x7, 0x7);
/* Enable Mic */
snd_soc_update_bits(codec, DA7210_INMIX_L, 0x1F, 0x1);
snd_soc_update_bits(codec, DA7210_INMIX_R, 0x1F, 0x1);
}
return 0;
}
/*
* Set PCM DAI word length.
*/
static int da7210_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_codec *codec = rtd->codec;
u32 dai_cfg1;
u32 hpf_reg, hpf_mask, hpf_value;
u32 fs, bypass;
/* set DAI source to Left and Right ADC */
da7210_write(codec, DA7210_DAI_SRC_SEL,
DA7210_DAI_OUT_R_SRC | DA7210_DAI_OUT_L_SRC);
/* Enable DAI */
da7210_write(codec, DA7210_DAI_CFG3, DA7210_DAI_OE | DA7210_DAI_EN);
dai_cfg1 = 0xFC & da7210_read(codec, DA7210_DAI_CFG1);
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
dai_cfg1 |= DA7210_DAI_WORD_S16_LE;
break;
case SNDRV_PCM_FORMAT_S24_LE:
dai_cfg1 |= DA7210_DAI_WORD_S24_LE;
break;
default:
return -EINVAL;
}
da7210_write(codec, DA7210_DAI_CFG1, dai_cfg1);
hpf_reg = (SNDRV_PCM_STREAM_PLAYBACK == substream->stream) ?
DA7210_DAC_HPF : DA7210_ADC_HPF;
switch (params_rate(params)) {
case 8000:
fs = DA7210_PLL_FS_8000;
hpf_mask = DA7210_VOICE_F0_MASK | DA7210_VOICE_EN;
hpf_value = DA7210_VOICE_F0_25 | DA7210_VOICE_EN;
bypass = DA7210_PLL_BYP;
break;
case 11025:
fs = DA7210_PLL_FS_11025;
hpf_mask = DA7210_VOICE_F0_MASK | DA7210_VOICE_EN;
hpf_value = DA7210_VOICE_F0_25 | DA7210_VOICE_EN;
bypass = 0;
break;
case 12000:
fs = DA7210_PLL_FS_12000;
hpf_mask = DA7210_VOICE_F0_MASK | DA7210_VOICE_EN;
hpf_value = DA7210_VOICE_F0_25 | DA7210_VOICE_EN;
bypass = DA7210_PLL_BYP;
break;
case 16000:
fs = DA7210_PLL_FS_16000;
hpf_mask = DA7210_VOICE_F0_MASK | DA7210_VOICE_EN;
hpf_value = DA7210_VOICE_F0_25 | DA7210_VOICE_EN;
bypass = DA7210_PLL_BYP;
break;
case 22050:
fs = DA7210_PLL_FS_22050;
hpf_mask = DA7210_VOICE_EN;
hpf_value = 0;
bypass = 0;
break;
case 32000:
fs = DA7210_PLL_FS_32000;
hpf_mask = DA7210_VOICE_EN;
hpf_value = 0;
bypass = DA7210_PLL_BYP;
break;
case 44100:
fs = DA7210_PLL_FS_44100;
hpf_mask = DA7210_VOICE_EN;
hpf_value = 0;
bypass = 0;
break;
case 48000:
fs = DA7210_PLL_FS_48000;
hpf_mask = DA7210_VOICE_EN;
hpf_value = 0;
bypass = DA7210_PLL_BYP;
break;
case 88200:
fs = DA7210_PLL_FS_88200;
hpf_mask = DA7210_VOICE_EN;
hpf_value = 0;
bypass = 0;
break;
case 96000:
fs = DA7210_PLL_FS_96000;
hpf_mask = DA7210_VOICE_EN;
hpf_value = 0;
bypass = DA7210_PLL_BYP;
break;
default:
return -EINVAL;
}
/* Disable active mode */
snd_soc_update_bits(codec, DA7210_STARTUP1, DA7210_SC_MST_EN, 0);
snd_soc_update_bits(codec, hpf_reg, hpf_mask, hpf_value);
snd_soc_update_bits(codec, DA7210_PLL, DA7210_PLL_FS_MASK, fs);
snd_soc_update_bits(codec, DA7210_PLL_DIV3, DA7210_PLL_BYP, bypass);
/* Enable active mode */
snd_soc_update_bits(codec, DA7210_STARTUP1,
DA7210_SC_MST_EN, DA7210_SC_MST_EN);
return 0;
}
/*
* Set DAI mode and Format
*/
static int da7210_set_dai_fmt(struct snd_soc_dai *codec_dai, u32 fmt)
{
struct snd_soc_codec *codec = codec_dai->codec;
u32 dai_cfg1;
u32 dai_cfg3;
dai_cfg1 = 0x7f & da7210_read(codec, DA7210_DAI_CFG1);
dai_cfg3 = 0xfc & da7210_read(codec, DA7210_DAI_CFG3);
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM:
dai_cfg1 |= DA7210_DAI_MODE_MASTER;
break;
default:
return -EINVAL;
}
/* FIXME
*
* It support I2S only now
*/
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
dai_cfg3 |= DA7210_DAI_FORMAT_I2SMODE;
break;
default:
return -EINVAL;
}
/* FIXME
*
* It support 64bit data transmission only now
*/
dai_cfg1 |= DA7210_DAI_FLEN_64BIT;
da7210_write(codec, DA7210_DAI_CFG1, dai_cfg1);
da7210_write(codec, DA7210_DAI_CFG3, dai_cfg3);
return 0;
}
#define DA7210_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S24_LE)
/* DAI operations */
static struct snd_soc_dai_ops da7210_dai_ops = {
.startup = da7210_startup,
.hw_params = da7210_hw_params,
.set_fmt = da7210_set_dai_fmt,
};
static struct snd_soc_dai_driver da7210_dai = {
.name = "da7210-hifi",
/* playback capabilities */
.playback = {
.stream_name = "Playback",
.channels_min = 1,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_8000_96000,
.formats = DA7210_FORMATS,
},
/* capture capabilities */
.capture = {
.stream_name = "Capture",
.channels_min = 1,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_8000_96000,
.formats = DA7210_FORMATS,
},
.ops = &da7210_dai_ops,
.symmetric_rates = 1,
};
static int da7210_probe(struct snd_soc_codec *codec)
{
struct da7210_priv *da7210 = snd_soc_codec_get_drvdata(codec);
dev_info(codec->dev, "DA7210 Audio Codec %s\n", DA7210_VERSION);
codec->control_data = da7210->control_data;
codec->hw_write = (hw_write_t)i2c_master_send;
/* FIXME
*
* This driver use fixed value here
* And below settings expects MCLK = 12.288MHz
*
* When you select different MCLK, please check...
* DA7210_PLL_DIV1 val
* DA7210_PLL_DIV2 val
* DA7210_PLL_DIV3 val
* DA7210_PLL_DIV3 :: DA7210_MCLK_RANGExxx
*/
/*
* make sure that DA7210 use bypass mode before start up
*/
da7210_write(codec, DA7210_STARTUP1, 0);
da7210_write(codec, DA7210_PLL_DIV3,
DA7210_MCLK_RANGE_10_20_MHZ | DA7210_PLL_BYP);
/*
* ADC settings
*/
/* Enable Left & Right MIC PGA and Mic Bias */
da7210_write(codec, DA7210_MIC_L, DA7210_MIC_L_EN | DA7210_MICBIAS_EN);
da7210_write(codec, DA7210_MIC_R, DA7210_MIC_R_EN);
/* Enable Left and Right input PGA */
da7210_write(codec, DA7210_INMIX_L, DA7210_IN_L_EN);
da7210_write(codec, DA7210_INMIX_R, DA7210_IN_R_EN);
/* Enable Left and Right ADC */
da7210_write(codec, DA7210_ADC, DA7210_ADC_L_EN | DA7210_ADC_R_EN);
/*
* DAC settings
*/
/* Enable Left and Right DAC */
da7210_write(codec, DA7210_DAC_SEL,
DA7210_DAC_L_SRC_DAI_L | DA7210_DAC_L_EN |
DA7210_DAC_R_SRC_DAI_R | DA7210_DAC_R_EN);
/* Enable Left and Right out PGA */
da7210_write(codec, DA7210_OUTMIX_L, DA7210_OUT_L_EN);
da7210_write(codec, DA7210_OUTMIX_R, DA7210_OUT_R_EN);
/* Enable Left and Right HeadPhone PGA */
da7210_write(codec, DA7210_HP_CFG,
DA7210_HP_2CAP_MODE | DA7210_HP_SENSE_EN |
DA7210_HP_L_EN | DA7210_HP_MODE | DA7210_HP_R_EN);
/* Diable PLL and bypass it */
da7210_write(codec, DA7210_PLL, DA7210_PLL_FS_48000);
/*
* If 48kHz sound came, it use bypass mode,
* and when it is 44.1kHz, it use PLL.
*
* This time, this driver sets PLL always ON
* and controls bypass/PLL mode by switching
* DA7210_PLL_DIV3 :: DA7210_PLL_BYP bit.
* see da7210_hw_params
*/
da7210_write(codec, DA7210_PLL_DIV1, 0xE5); /* MCLK = 12.288MHz */
da7210_write(codec, DA7210_PLL_DIV2, 0x99);
da7210_write(codec, DA7210_PLL_DIV3, 0x0A |
DA7210_MCLK_RANGE_10_20_MHZ | DA7210_PLL_BYP);
snd_soc_update_bits(codec, DA7210_PLL, DA7210_PLL_EN, DA7210_PLL_EN);
/* As suggested by Dialog */
da7210_write(codec, DA7210_A_HID_UNLOCK, 0x8B); /* unlock */
da7210_write(codec, DA7210_A_TEST_UNLOCK, 0xB4);
da7210_write(codec, DA7210_A_PLL1, 0x01);
da7210_write(codec, DA7210_A_CP_MODE, 0x7C);
da7210_write(codec, DA7210_A_HID_UNLOCK, 0x00); /* re-lock */
da7210_write(codec, DA7210_A_TEST_UNLOCK, 0x00);
/* Activate all enabled subsystem */
da7210_write(codec, DA7210_STARTUP1, DA7210_SC_MST_EN);
snd_soc_add_controls(codec, da7210_snd_controls,
ARRAY_SIZE(da7210_snd_controls));
dev_info(codec->dev, "DA7210 Audio Codec %s\n", DA7210_VERSION);
return 0;
}
static struct snd_soc_codec_driver soc_codec_dev_da7210 = {
.probe = da7210_probe,
.read = da7210_read,
.write = da7210_write,
.reg_cache_size = ARRAY_SIZE(da7210_reg),
.reg_word_size = sizeof(u8),
.reg_cache_default = da7210_reg,
};
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
static int __devinit da7210_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct da7210_priv *da7210;
int ret;
da7210 = kzalloc(sizeof(struct da7210_priv), GFP_KERNEL);
if (!da7210)
return -ENOMEM;
i2c_set_clientdata(i2c, da7210);
da7210->control_data = i2c;
da7210->control_type = SND_SOC_I2C;
ret = snd_soc_register_codec(&i2c->dev,
&soc_codec_dev_da7210, &da7210_dai, 1);
if (ret < 0)
kfree(da7210);
return ret;
}
static int __devexit da7210_i2c_remove(struct i2c_client *client)
{
snd_soc_unregister_codec(&client->dev);
kfree(i2c_get_clientdata(client));
return 0;
}
static const struct i2c_device_id da7210_i2c_id[] = {
{ "da7210", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, da7210_i2c_id);
/* I2C codec control layer */
static struct i2c_driver da7210_i2c_driver = {
.driver = {
.name = "da7210-codec",
.owner = THIS_MODULE,
},
.probe = da7210_i2c_probe,
.remove = __devexit_p(da7210_i2c_remove),
.id_table = da7210_i2c_id,
};
#endif
static int __init da7210_modinit(void)
{
int ret = 0;
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
ret = i2c_add_driver(&da7210_i2c_driver);
#endif
return ret;
}
module_init(da7210_modinit);
static void __exit da7210_exit(void)
{
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
i2c_del_driver(&da7210_i2c_driver);
#endif
}
module_exit(da7210_exit);
MODULE_DESCRIPTION("ASoC DA7210 driver");
MODULE_AUTHOR("David Chen, Kuninori Morimoto");
MODULE_LICENSE("GPL");
| gpl-2.0 |
fefifofum/android_kernel_bq_maxwell2plus_3.0.8 | arch/powerpc/platforms/cell/cbe_powerbutton.c | 3791 | 3022 | /*
* driver for powerbutton on IBM cell blades
*
* (C) Copyright IBM Corp. 2005-2008
*
* Author: Christian Krafft <krafft@de.ibm.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/input.h>
#include <linux/platform_device.h>
#include <asm/pmi.h>
#include <asm/prom.h>
static struct input_dev *button_dev;
static struct platform_device *button_pdev;
static void cbe_powerbutton_handle_pmi(pmi_message_t pmi_msg)
{
BUG_ON(pmi_msg.type != PMI_TYPE_POWER_BUTTON);
input_report_key(button_dev, KEY_POWER, 1);
input_sync(button_dev);
input_report_key(button_dev, KEY_POWER, 0);
input_sync(button_dev);
}
static struct pmi_handler cbe_pmi_handler = {
.type = PMI_TYPE_POWER_BUTTON,
.handle_pmi_message = cbe_powerbutton_handle_pmi,
};
static int __init cbe_powerbutton_init(void)
{
int ret = 0;
struct input_dev *dev;
if (!of_machine_is_compatible("IBM,CBPLUS-1.0")) {
printk(KERN_ERR "%s: Not a cell blade.\n", __func__);
ret = -ENODEV;
goto out;
}
dev = input_allocate_device();
if (!dev) {
ret = -ENOMEM;
printk(KERN_ERR "%s: Not enough memory.\n", __func__);
goto out;
}
set_bit(EV_KEY, dev->evbit);
set_bit(KEY_POWER, dev->keybit);
dev->name = "Power Button";
dev->id.bustype = BUS_HOST;
/* this makes the button look like an acpi power button
* no clue whether anyone relies on that though */
dev->id.product = 0x02;
dev->phys = "LNXPWRBN/button/input0";
button_pdev = platform_device_register_simple("power_button", 0, NULL, 0);
if (IS_ERR(button_pdev)) {
ret = PTR_ERR(button_pdev);
goto out_free_input;
}
dev->dev.parent = &button_pdev->dev;
ret = input_register_device(dev);
if (ret) {
printk(KERN_ERR "%s: Failed to register device\n", __func__);
goto out_free_pdev;
}
button_dev = dev;
ret = pmi_register_handler(&cbe_pmi_handler);
if (ret) {
printk(KERN_ERR "%s: Failed to register with pmi.\n", __func__);
goto out_free_pdev;
}
goto out;
out_free_pdev:
platform_device_unregister(button_pdev);
out_free_input:
input_free_device(dev);
out:
return ret;
}
static void __exit cbe_powerbutton_exit(void)
{
pmi_unregister_handler(&cbe_pmi_handler);
platform_device_unregister(button_pdev);
input_free_device(button_dev);
}
module_init(cbe_powerbutton_init);
module_exit(cbe_powerbutton_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Christian Krafft <krafft@de.ibm.com>");
| gpl-2.0 |
liuzhengcn/hc-adm-2.6.36 | drivers/spi/spi_stmp.c | 4047 | 16199 | /*
* Freescale STMP378X SPI master driver
*
* Author: dmitry pervushin <dimka@embeddedalley.com>
*
* Copyright 2008 Freescale Semiconductor, Inc. All Rights Reserved.
* Copyright 2008 Embedded Alley Solutions, Inc All Rights Reserved.
*/
/*
* 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/module.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/spi/spi.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/dma-mapping.h>
#include <linux/delay.h>
#include <mach/platform.h>
#include <mach/stmp3xxx.h>
#include <mach/dma.h>
#include <mach/regs-ssp.h>
#include <mach/regs-apbh.h>
/* 0 means DMA mode(recommended, default), !0 - PIO mode */
static int pio;
static int clock;
/* default timeout for busy waits is 2 seconds */
#define STMP_SPI_TIMEOUT (2 * HZ)
struct stmp_spi {
int id;
void * __iomem regs; /* vaddr of the control registers */
int irq, err_irq;
u32 dma;
struct stmp3xxx_dma_descriptor d;
u32 speed_khz;
u32 saved_timings;
u32 divider;
struct clk *clk;
struct device *master_dev;
struct work_struct work;
struct workqueue_struct *workqueue;
/* lock protects queue access */
spinlock_t lock;
struct list_head queue;
struct completion done;
};
#define busy_wait(cond) \
({ \
unsigned long end_jiffies = jiffies + STMP_SPI_TIMEOUT; \
bool succeeded = false; \
do { \
if (cond) { \
succeeded = true; \
break; \
} \
cpu_relax(); \
} while (time_before(jiffies, end_jiffies)); \
succeeded; \
})
/**
* stmp_spi_init_hw
* Initialize the SSP port
*/
static int stmp_spi_init_hw(struct stmp_spi *ss)
{
int err = 0;
void *pins = ss->master_dev->platform_data;
err = stmp3xxx_request_pin_group(pins, dev_name(ss->master_dev));
if (err)
goto out;
ss->clk = clk_get(NULL, "ssp");
if (IS_ERR(ss->clk)) {
err = PTR_ERR(ss->clk);
goto out_free_pins;
}
clk_enable(ss->clk);
stmp3xxx_reset_block(ss->regs, false);
stmp3xxx_dma_reset_channel(ss->dma);
return 0;
out_free_pins:
stmp3xxx_release_pin_group(pins, dev_name(ss->master_dev));
out:
return err;
}
static void stmp_spi_release_hw(struct stmp_spi *ss)
{
void *pins = ss->master_dev->platform_data;
if (ss->clk && !IS_ERR(ss->clk)) {
clk_disable(ss->clk);
clk_put(ss->clk);
}
stmp3xxx_release_pin_group(pins, dev_name(ss->master_dev));
}
static int stmp_spi_setup_transfer(struct spi_device *spi,
struct spi_transfer *t)
{
u8 bits_per_word;
u32 hz;
struct stmp_spi *ss = spi_master_get_devdata(spi->master);
u16 rate;
bits_per_word = spi->bits_per_word;
if (t && t->bits_per_word)
bits_per_word = t->bits_per_word;
/*
* Calculate speed:
* - by default, use maximum speed from ssp clk
* - if device overrides it, use it
* - if transfer specifies other speed, use transfer's one
*/
hz = 1000 * ss->speed_khz / ss->divider;
if (spi->max_speed_hz)
hz = min(hz, spi->max_speed_hz);
if (t && t->speed_hz)
hz = min(hz, t->speed_hz);
if (hz == 0) {
dev_err(&spi->dev, "Cannot continue with zero clock\n");
return -EINVAL;
}
if (bits_per_word != 8) {
dev_err(&spi->dev, "%s, unsupported bits_per_word=%d\n",
__func__, bits_per_word);
return -EINVAL;
}
dev_dbg(&spi->dev, "Requested clk rate = %uHz, max = %uHz/%d = %uHz\n",
hz, ss->speed_khz, ss->divider,
ss->speed_khz * 1000 / ss->divider);
if (ss->speed_khz * 1000 / ss->divider < hz) {
dev_err(&spi->dev, "%s, unsupported clock rate %uHz\n",
__func__, hz);
return -EINVAL;
}
rate = 1000 * ss->speed_khz/ss->divider/hz;
writel(BF(ss->divider, SSP_TIMING_CLOCK_DIVIDE) |
BF(rate - 1, SSP_TIMING_CLOCK_RATE),
HW_SSP_TIMING + ss->regs);
writel(BF(1 /* mode SPI */, SSP_CTRL1_SSP_MODE) |
BF(4 /* 8 bits */, SSP_CTRL1_WORD_LENGTH) |
((spi->mode & SPI_CPOL) ? BM_SSP_CTRL1_POLARITY : 0) |
((spi->mode & SPI_CPHA) ? BM_SSP_CTRL1_PHASE : 0) |
(pio ? 0 : BM_SSP_CTRL1_DMA_ENABLE),
ss->regs + HW_SSP_CTRL1);
return 0;
}
static int stmp_spi_setup(struct spi_device *spi)
{
/* spi_setup() does basic checks,
* stmp_spi_setup_transfer() does more later
*/
if (spi->bits_per_word != 8) {
dev_err(&spi->dev, "%s, unsupported bits_per_word=%d\n",
__func__, spi->bits_per_word);
return -EINVAL;
}
return 0;
}
static inline u32 stmp_spi_cs(unsigned cs)
{
return ((cs & 1) ? BM_SSP_CTRL0_WAIT_FOR_CMD : 0) |
((cs & 2) ? BM_SSP_CTRL0_WAIT_FOR_IRQ : 0);
}
static int stmp_spi_txrx_dma(struct stmp_spi *ss, int cs,
unsigned char *buf, dma_addr_t dma_buf, int len,
int first, int last, bool write)
{
u32 c0 = 0;
dma_addr_t spi_buf_dma = dma_buf;
int status = 0;
enum dma_data_direction dir = write ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
c0 |= (first ? BM_SSP_CTRL0_LOCK_CS : 0);
c0 |= (last ? BM_SSP_CTRL0_IGNORE_CRC : 0);
c0 |= (write ? 0 : BM_SSP_CTRL0_READ);
c0 |= BM_SSP_CTRL0_DATA_XFER;
c0 |= stmp_spi_cs(cs);
c0 |= BF(len, SSP_CTRL0_XFER_COUNT);
if (!dma_buf)
spi_buf_dma = dma_map_single(ss->master_dev, buf, len, dir);
ss->d.command->cmd =
BF(len, APBH_CHn_CMD_XFER_COUNT) |
BF(1, APBH_CHn_CMD_CMDWORDS) |
BM_APBH_CHn_CMD_WAIT4ENDCMD |
BM_APBH_CHn_CMD_IRQONCMPLT |
BF(write ? BV_APBH_CHn_CMD_COMMAND__DMA_READ :
BV_APBH_CHn_CMD_COMMAND__DMA_WRITE,
APBH_CHn_CMD_COMMAND);
ss->d.command->pio_words[0] = c0;
ss->d.command->buf_ptr = spi_buf_dma;
stmp3xxx_dma_reset_channel(ss->dma);
stmp3xxx_dma_clear_interrupt(ss->dma);
stmp3xxx_dma_enable_interrupt(ss->dma);
init_completion(&ss->done);
stmp3xxx_dma_go(ss->dma, &ss->d, 1);
wait_for_completion(&ss->done);
if (!busy_wait(readl(ss->regs + HW_SSP_CTRL0) & BM_SSP_CTRL0_RUN))
status = -ETIMEDOUT;
if (!dma_buf)
dma_unmap_single(ss->master_dev, spi_buf_dma, len, dir);
return status;
}
static inline void stmp_spi_enable(struct stmp_spi *ss)
{
stmp3xxx_setl(BM_SSP_CTRL0_LOCK_CS, ss->regs + HW_SSP_CTRL0);
stmp3xxx_clearl(BM_SSP_CTRL0_IGNORE_CRC, ss->regs + HW_SSP_CTRL0);
}
static inline void stmp_spi_disable(struct stmp_spi *ss)
{
stmp3xxx_clearl(BM_SSP_CTRL0_LOCK_CS, ss->regs + HW_SSP_CTRL0);
stmp3xxx_setl(BM_SSP_CTRL0_IGNORE_CRC, ss->regs + HW_SSP_CTRL0);
}
static int stmp_spi_txrx_pio(struct stmp_spi *ss, int cs,
unsigned char *buf, int len,
bool first, bool last, bool write)
{
if (first)
stmp_spi_enable(ss);
stmp3xxx_setl(stmp_spi_cs(cs), ss->regs + HW_SSP_CTRL0);
while (len--) {
if (last && len <= 0)
stmp_spi_disable(ss);
stmp3xxx_clearl(BM_SSP_CTRL0_XFER_COUNT,
ss->regs + HW_SSP_CTRL0);
stmp3xxx_setl(1, ss->regs + HW_SSP_CTRL0);
if (write)
stmp3xxx_clearl(BM_SSP_CTRL0_READ,
ss->regs + HW_SSP_CTRL0);
else
stmp3xxx_setl(BM_SSP_CTRL0_READ,
ss->regs + HW_SSP_CTRL0);
/* Run! */
stmp3xxx_setl(BM_SSP_CTRL0_RUN, ss->regs + HW_SSP_CTRL0);
if (!busy_wait(readl(ss->regs + HW_SSP_CTRL0) &
BM_SSP_CTRL0_RUN))
break;
if (write)
writel(*buf, ss->regs + HW_SSP_DATA);
/* Set TRANSFER */
stmp3xxx_setl(BM_SSP_CTRL0_DATA_XFER, ss->regs + HW_SSP_CTRL0);
if (!write) {
if (busy_wait((readl(ss->regs + HW_SSP_STATUS) &
BM_SSP_STATUS_FIFO_EMPTY)))
break;
*buf = readl(ss->regs + HW_SSP_DATA) & 0xFF;
}
if (!busy_wait(readl(ss->regs + HW_SSP_CTRL0) &
BM_SSP_CTRL0_RUN))
break;
/* advance to the next byte */
buf++;
}
return len < 0 ? 0 : -ETIMEDOUT;
}
static int stmp_spi_handle_message(struct stmp_spi *ss, struct spi_message *m)
{
bool first, last;
struct spi_transfer *t, *tmp_t;
int status = 0;
int cs;
cs = m->spi->chip_select;
list_for_each_entry_safe(t, tmp_t, &m->transfers, transfer_list) {
first = (&t->transfer_list == m->transfers.next);
last = (&t->transfer_list == m->transfers.prev);
if (first || t->speed_hz || t->bits_per_word)
stmp_spi_setup_transfer(m->spi, t);
/* reject "not last" transfers which request to change cs */
if (t->cs_change && !last) {
dev_err(&m->spi->dev,
"Message with t->cs_change has been skipped\n");
continue;
}
if (t->tx_buf) {
status = pio ?
stmp_spi_txrx_pio(ss, cs, (void *)t->tx_buf,
t->len, first, last, true) :
stmp_spi_txrx_dma(ss, cs, (void *)t->tx_buf,
t->tx_dma, t->len, first, last, true);
#ifdef DEBUG
if (t->len < 0x10)
print_hex_dump_bytes("Tx ",
DUMP_PREFIX_OFFSET,
t->tx_buf, t->len);
else
pr_debug("Tx: %d bytes\n", t->len);
#endif
}
if (t->rx_buf) {
status = pio ?
stmp_spi_txrx_pio(ss, cs, t->rx_buf,
t->len, first, last, false) :
stmp_spi_txrx_dma(ss, cs, t->rx_buf,
t->rx_dma, t->len, first, last, false);
#ifdef DEBUG
if (t->len < 0x10)
print_hex_dump_bytes("Rx ",
DUMP_PREFIX_OFFSET,
t->rx_buf, t->len);
else
pr_debug("Rx: %d bytes\n", t->len);
#endif
}
if (t->delay_usecs)
udelay(t->delay_usecs);
if (status)
break;
}
return status;
}
/**
* stmp_spi_handle - handle messages from the queue
*/
static void stmp_spi_handle(struct work_struct *w)
{
struct stmp_spi *ss = container_of(w, struct stmp_spi, work);
unsigned long flags;
struct spi_message *m;
spin_lock_irqsave(&ss->lock, flags);
while (!list_empty(&ss->queue)) {
m = list_entry(ss->queue.next, struct spi_message, queue);
list_del_init(&m->queue);
spin_unlock_irqrestore(&ss->lock, flags);
m->status = stmp_spi_handle_message(ss, m);
m->complete(m->context);
spin_lock_irqsave(&ss->lock, flags);
}
spin_unlock_irqrestore(&ss->lock, flags);
return;
}
/**
* stmp_spi_transfer - perform message transfer.
* Called indirectly from spi_async, queues all the messages to
* spi_handle_message.
* @spi: spi device
* @m: message to be queued
*/
static int stmp_spi_transfer(struct spi_device *spi, struct spi_message *m)
{
struct stmp_spi *ss = spi_master_get_devdata(spi->master);
unsigned long flags;
m->status = -EINPROGRESS;
spin_lock_irqsave(&ss->lock, flags);
list_add_tail(&m->queue, &ss->queue);
queue_work(ss->workqueue, &ss->work);
spin_unlock_irqrestore(&ss->lock, flags);
return 0;
}
static irqreturn_t stmp_spi_irq(int irq, void *dev_id)
{
struct stmp_spi *ss = dev_id;
stmp3xxx_dma_clear_interrupt(ss->dma);
complete(&ss->done);
return IRQ_HANDLED;
}
static irqreturn_t stmp_spi_irq_err(int irq, void *dev_id)
{
struct stmp_spi *ss = dev_id;
u32 c1, st;
c1 = readl(ss->regs + HW_SSP_CTRL1);
st = readl(ss->regs + HW_SSP_STATUS);
dev_err(ss->master_dev, "%s: status = 0x%08X, c1 = 0x%08X\n",
__func__, st, c1);
stmp3xxx_clearl(c1 & 0xCCCC0000, ss->regs + HW_SSP_CTRL1);
return IRQ_HANDLED;
}
static int __devinit stmp_spi_probe(struct platform_device *dev)
{
int err = 0;
struct spi_master *master;
struct stmp_spi *ss;
struct resource *r;
master = spi_alloc_master(&dev->dev, sizeof(struct stmp_spi));
if (master == NULL) {
err = -ENOMEM;
goto out0;
}
master->flags = SPI_MASTER_HALF_DUPLEX;
ss = spi_master_get_devdata(master);
platform_set_drvdata(dev, master);
/* Get resources(memory, IRQ) associated with the device */
r = platform_get_resource(dev, IORESOURCE_MEM, 0);
if (r == NULL) {
err = -ENODEV;
goto out_put_master;
}
ss->regs = ioremap(r->start, resource_size(r));
if (!ss->regs) {
err = -EINVAL;
goto out_put_master;
}
ss->master_dev = &dev->dev;
ss->id = dev->id;
INIT_WORK(&ss->work, stmp_spi_handle);
INIT_LIST_HEAD(&ss->queue);
spin_lock_init(&ss->lock);
ss->workqueue = create_singlethread_workqueue(dev_name(&dev->dev));
if (!ss->workqueue) {
err = -ENXIO;
goto out_put_master;
}
master->transfer = stmp_spi_transfer;
master->setup = stmp_spi_setup;
/* the spi->mode bits understood by this driver: */
master->mode_bits = SPI_CPOL | SPI_CPHA;
ss->irq = platform_get_irq(dev, 0);
if (ss->irq < 0) {
err = ss->irq;
goto out_put_master;
}
ss->err_irq = platform_get_irq(dev, 1);
if (ss->err_irq < 0) {
err = ss->err_irq;
goto out_put_master;
}
r = platform_get_resource(dev, IORESOURCE_DMA, 0);
if (r == NULL) {
err = -ENODEV;
goto out_put_master;
}
ss->dma = r->start;
err = stmp3xxx_dma_request(ss->dma, &dev->dev, dev_name(&dev->dev));
if (err)
goto out_put_master;
err = stmp3xxx_dma_allocate_command(ss->dma, &ss->d);
if (err)
goto out_free_dma;
master->bus_num = dev->id;
master->num_chipselect = 1;
/* SPI controller initializations */
err = stmp_spi_init_hw(ss);
if (err) {
dev_dbg(&dev->dev, "cannot initialize hardware\n");
goto out_free_dma_desc;
}
if (clock) {
dev_info(&dev->dev, "clock rate forced to %d\n", clock);
clk_set_rate(ss->clk, clock);
}
ss->speed_khz = clk_get_rate(ss->clk);
ss->divider = 2;
dev_info(&dev->dev, "max possible speed %d = %ld/%d kHz\n",
ss->speed_khz, clk_get_rate(ss->clk), ss->divider);
/* Register for SPI interrupt */
err = request_irq(ss->irq, stmp_spi_irq, 0,
dev_name(&dev->dev), ss);
if (err) {
dev_dbg(&dev->dev, "request_irq failed, %d\n", err);
goto out_release_hw;
}
/* ..and shared interrupt for all SSP controllers */
err = request_irq(ss->err_irq, stmp_spi_irq_err, IRQF_SHARED,
dev_name(&dev->dev), ss);
if (err) {
dev_dbg(&dev->dev, "request_irq(error) failed, %d\n", err);
goto out_free_irq;
}
err = spi_register_master(master);
if (err) {
dev_dbg(&dev->dev, "cannot register spi master, %d\n", err);
goto out_free_irq_2;
}
dev_info(&dev->dev, "at (mapped) 0x%08X, irq=%d, bus %d, %s mode\n",
(u32)ss->regs, ss->irq, master->bus_num,
pio ? "PIO" : "DMA");
return 0;
out_free_irq_2:
free_irq(ss->err_irq, ss);
out_free_irq:
free_irq(ss->irq, ss);
out_free_dma_desc:
stmp3xxx_dma_free_command(ss->dma, &ss->d);
out_free_dma:
stmp3xxx_dma_release(ss->dma);
out_release_hw:
stmp_spi_release_hw(ss);
out_put_master:
if (ss->workqueue)
destroy_workqueue(ss->workqueue);
if (ss->regs)
iounmap(ss->regs);
platform_set_drvdata(dev, NULL);
spi_master_put(master);
out0:
return err;
}
static int __devexit stmp_spi_remove(struct platform_device *dev)
{
struct stmp_spi *ss;
struct spi_master *master;
master = platform_get_drvdata(dev);
if (master == NULL)
goto out0;
ss = spi_master_get_devdata(master);
spi_unregister_master(master);
free_irq(ss->err_irq, ss);
free_irq(ss->irq, ss);
stmp3xxx_dma_free_command(ss->dma, &ss->d);
stmp3xxx_dma_release(ss->dma);
stmp_spi_release_hw(ss);
destroy_workqueue(ss->workqueue);
iounmap(ss->regs);
spi_master_put(master);
platform_set_drvdata(dev, NULL);
out0:
return 0;
}
#ifdef CONFIG_PM
static int stmp_spi_suspend(struct platform_device *pdev, pm_message_t pmsg)
{
struct stmp_spi *ss;
struct spi_master *master;
master = platform_get_drvdata(pdev);
ss = spi_master_get_devdata(master);
ss->saved_timings = readl(HW_SSP_TIMING + ss->regs);
clk_disable(ss->clk);
return 0;
}
static int stmp_spi_resume(struct platform_device *pdev)
{
struct stmp_spi *ss;
struct spi_master *master;
master = platform_get_drvdata(pdev);
ss = spi_master_get_devdata(master);
clk_enable(ss->clk);
stmp3xxx_reset_block(ss->regs, false);
writel(ss->saved_timings, ss->regs + HW_SSP_TIMING);
return 0;
}
#else
#define stmp_spi_suspend NULL
#define stmp_spi_resume NULL
#endif
static struct platform_driver stmp_spi_driver = {
.probe = stmp_spi_probe,
.remove = __devexit_p(stmp_spi_remove),
.driver = {
.name = "stmp3xxx_ssp",
.owner = THIS_MODULE,
},
.suspend = stmp_spi_suspend,
.resume = stmp_spi_resume,
};
static int __init stmp_spi_init(void)
{
return platform_driver_register(&stmp_spi_driver);
}
static void __exit stmp_spi_exit(void)
{
platform_driver_unregister(&stmp_spi_driver);
}
module_init(stmp_spi_init);
module_exit(stmp_spi_exit);
module_param(pio, int, S_IRUGO);
module_param(clock, int, S_IRUGO);
MODULE_AUTHOR("dmitry pervushin <dpervushin@embeddedalley.com>");
MODULE_DESCRIPTION("STMP3xxx SPI/SSP driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
TW-LL-msm8226/samsung_s3ve3g_EUR | fs/jffs2/super.c | 4559 | 10216 | /*
* 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/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/fs.h>
#include <linux/err.h>
#include <linux/mount.h>
#include <linux/parser.h>
#include <linux/jffs2.h>
#include <linux/pagemap.h>
#include <linux/mtd/super.h>
#include <linux/ctype.h>
#include <linux/namei.h>
#include <linux/seq_file.h>
#include <linux/exportfs.h>
#include "compr.h"
#include "nodelist.h"
static void jffs2_put_super(struct super_block *);
static struct kmem_cache *jffs2_inode_cachep;
static struct inode *jffs2_alloc_inode(struct super_block *sb)
{
struct jffs2_inode_info *f;
f = kmem_cache_alloc(jffs2_inode_cachep, GFP_KERNEL);
if (!f)
return NULL;
return &f->vfs_inode;
}
static void jffs2_i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
kmem_cache_free(jffs2_inode_cachep, JFFS2_INODE_INFO(inode));
}
static void jffs2_destroy_inode(struct inode *inode)
{
call_rcu(&inode->i_rcu, jffs2_i_callback);
}
static void jffs2_i_init_once(void *foo)
{
struct jffs2_inode_info *f = foo;
mutex_init(&f->sem);
inode_init_once(&f->vfs_inode);
}
static void jffs2_write_super(struct super_block *sb)
{
struct jffs2_sb_info *c = JFFS2_SB_INFO(sb);
lock_super(sb);
sb->s_dirt = 0;
if (!(sb->s_flags & MS_RDONLY)) {
jffs2_dbg(1, "%s()\n", __func__);
jffs2_flush_wbuf_gc(c, 0);
}
unlock_super(sb);
}
static const char *jffs2_compr_name(unsigned int compr)
{
switch (compr) {
case JFFS2_COMPR_MODE_NONE:
return "none";
#ifdef CONFIG_JFFS2_LZO
case JFFS2_COMPR_MODE_FORCELZO:
return "lzo";
#endif
#ifdef CONFIG_JFFS2_ZLIB
case JFFS2_COMPR_MODE_FORCEZLIB:
return "zlib";
#endif
default:
/* should never happen; programmer error */
WARN_ON(1);
return "";
}
}
static int jffs2_show_options(struct seq_file *s, struct dentry *root)
{
struct jffs2_sb_info *c = JFFS2_SB_INFO(root->d_sb);
struct jffs2_mount_opts *opts = &c->mount_opts;
if (opts->override_compr)
seq_printf(s, ",compr=%s", jffs2_compr_name(opts->compr));
return 0;
}
static int jffs2_sync_fs(struct super_block *sb, int wait)
{
struct jffs2_sb_info *c = JFFS2_SB_INFO(sb);
jffs2_write_super(sb);
mutex_lock(&c->alloc_sem);
jffs2_flush_wbuf_pad(c);
mutex_unlock(&c->alloc_sem);
return 0;
}
static struct inode *jffs2_nfs_get_inode(struct super_block *sb, uint64_t ino,
uint32_t generation)
{
/* We don't care about i_generation. We'll destroy the flash
before we start re-using inode numbers anyway. And even
if that wasn't true, we'd have other problems...*/
return jffs2_iget(sb, ino);
}
static struct dentry *jffs2_fh_to_dentry(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
jffs2_nfs_get_inode);
}
static struct dentry *jffs2_fh_to_parent(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_parent(sb, fid, fh_len, fh_type,
jffs2_nfs_get_inode);
}
static struct dentry *jffs2_get_parent(struct dentry *child)
{
struct jffs2_inode_info *f;
uint32_t pino;
BUG_ON(!S_ISDIR(child->d_inode->i_mode));
f = JFFS2_INODE_INFO(child->d_inode);
pino = f->inocache->pino_nlink;
JFFS2_DEBUG("Parent of directory ino #%u is #%u\n",
f->inocache->ino, pino);
return d_obtain_alias(jffs2_iget(child->d_inode->i_sb, pino));
}
static const struct export_operations jffs2_export_ops = {
.get_parent = jffs2_get_parent,
.fh_to_dentry = jffs2_fh_to_dentry,
.fh_to_parent = jffs2_fh_to_parent,
};
/*
* JFFS2 mount options.
*
* Opt_override_compr: override default compressor
* Opt_err: just end of array marker
*/
enum {
Opt_override_compr,
Opt_err,
};
static const match_table_t tokens = {
{Opt_override_compr, "compr=%s"},
{Opt_err, NULL},
};
static int jffs2_parse_options(struct jffs2_sb_info *c, char *data)
{
substring_t args[MAX_OPT_ARGS];
char *p, *name;
if (!data)
return 0;
while ((p = strsep(&data, ","))) {
int token;
if (!*p)
continue;
token = match_token(p, tokens, args);
switch (token) {
case Opt_override_compr:
name = match_strdup(&args[0]);
if (!name)
return -ENOMEM;
if (!strcmp(name, "none"))
c->mount_opts.compr = JFFS2_COMPR_MODE_NONE;
#ifdef CONFIG_JFFS2_LZO
else if (!strcmp(name, "lzo"))
c->mount_opts.compr = JFFS2_COMPR_MODE_FORCELZO;
#endif
#ifdef CONFIG_JFFS2_ZLIB
else if (!strcmp(name, "zlib"))
c->mount_opts.compr =
JFFS2_COMPR_MODE_FORCEZLIB;
#endif
else {
pr_err("Error: unknown compressor \"%s\"\n",
name);
kfree(name);
return -EINVAL;
}
kfree(name);
c->mount_opts.override_compr = true;
break;
default:
pr_err("Error: unrecognized mount option '%s' or missing value\n",
p);
return -EINVAL;
}
}
return 0;
}
static int jffs2_remount_fs(struct super_block *sb, int *flags, char *data)
{
struct jffs2_sb_info *c = JFFS2_SB_INFO(sb);
int err;
err = jffs2_parse_options(c, data);
if (err)
return -EINVAL;
return jffs2_do_remount_fs(sb, flags, data);
}
static const struct super_operations jffs2_super_operations =
{
.alloc_inode = jffs2_alloc_inode,
.destroy_inode =jffs2_destroy_inode,
.put_super = jffs2_put_super,
.write_super = jffs2_write_super,
.statfs = jffs2_statfs,
.remount_fs = jffs2_remount_fs,
.evict_inode = jffs2_evict_inode,
.dirty_inode = jffs2_dirty_inode,
.show_options = jffs2_show_options,
.sync_fs = jffs2_sync_fs,
};
/*
* fill in the superblock
*/
static int jffs2_fill_super(struct super_block *sb, void *data, int silent)
{
struct jffs2_sb_info *c;
int ret;
jffs2_dbg(1, "jffs2_get_sb_mtd():"
" New superblock for device %d (\"%s\")\n",
sb->s_mtd->index, sb->s_mtd->name);
c = kzalloc(sizeof(*c), GFP_KERNEL);
if (!c)
return -ENOMEM;
c->mtd = sb->s_mtd;
c->os_priv = sb;
sb->s_fs_info = c;
ret = jffs2_parse_options(c, data);
if (ret) {
kfree(c);
return -EINVAL;
}
/* Initialize JFFS2 superblock locks, the further initialization will
* be done later */
mutex_init(&c->alloc_sem);
mutex_init(&c->erase_free_sem);
init_waitqueue_head(&c->erase_wait);
init_waitqueue_head(&c->inocache_wq);
spin_lock_init(&c->erase_completion_lock);
spin_lock_init(&c->inocache_lock);
sb->s_op = &jffs2_super_operations;
sb->s_export_op = &jffs2_export_ops;
sb->s_flags = sb->s_flags | MS_NOATIME;
sb->s_xattr = jffs2_xattr_handlers;
#ifdef CONFIG_JFFS2_FS_POSIX_ACL
sb->s_flags |= MS_POSIXACL;
#endif
ret = jffs2_do_fill_super(sb, data, silent);
return ret;
}
static struct dentry *jffs2_mount(struct file_system_type *fs_type,
int flags, const char *dev_name,
void *data)
{
return mount_mtd(fs_type, flags, dev_name, data, jffs2_fill_super);
}
static void jffs2_put_super (struct super_block *sb)
{
struct jffs2_sb_info *c = JFFS2_SB_INFO(sb);
jffs2_dbg(2, "%s()\n", __func__);
if (sb->s_dirt)
jffs2_write_super(sb);
mutex_lock(&c->alloc_sem);
jffs2_flush_wbuf_pad(c);
mutex_unlock(&c->alloc_sem);
jffs2_sum_exit(c);
jffs2_free_ino_caches(c);
jffs2_free_raw_node_refs(c);
if (jffs2_blocks_use_vmalloc(c))
vfree(c->blocks);
else
kfree(c->blocks);
jffs2_flash_cleanup(c);
kfree(c->inocache_list);
jffs2_clear_xattr_subsystem(c);
mtd_sync(c->mtd);
jffs2_dbg(1, "%s(): returning\n", __func__);
}
static void jffs2_kill_sb(struct super_block *sb)
{
struct jffs2_sb_info *c = JFFS2_SB_INFO(sb);
if (!(sb->s_flags & MS_RDONLY))
jffs2_stop_garbage_collect_thread(c);
kill_mtd_super(sb);
kfree(c);
}
static struct file_system_type jffs2_fs_type = {
.owner = THIS_MODULE,
.name = "jffs2",
.mount = jffs2_mount,
.kill_sb = jffs2_kill_sb,
};
static int __init init_jffs2_fs(void)
{
int ret;
/* Paranoia checks for on-medium structures. If we ask GCC
to pack them with __attribute__((packed)) then it _also_
assumes that they're not aligned -- so it emits crappy
code on some architectures. Ideally we want an attribute
which means just 'no padding', without the alignment
thing. But GCC doesn't have that -- we have to just
hope the structs are the right sizes, instead. */
BUILD_BUG_ON(sizeof(struct jffs2_unknown_node) != 12);
BUILD_BUG_ON(sizeof(struct jffs2_raw_dirent) != 40);
BUILD_BUG_ON(sizeof(struct jffs2_raw_inode) != 68);
BUILD_BUG_ON(sizeof(struct jffs2_raw_summary) != 32);
pr_info("version 2.2."
#ifdef CONFIG_JFFS2_FS_WRITEBUFFER
" (NAND)"
#endif
#ifdef CONFIG_JFFS2_SUMMARY
" (SUMMARY) "
#endif
" © 2001-2006 Red Hat, Inc.\n");
jffs2_inode_cachep = kmem_cache_create("jffs2_i",
sizeof(struct jffs2_inode_info),
0, (SLAB_RECLAIM_ACCOUNT|
SLAB_MEM_SPREAD),
jffs2_i_init_once);
if (!jffs2_inode_cachep) {
pr_err("error: Failed to initialise inode cache\n");
return -ENOMEM;
}
ret = jffs2_compressors_init();
if (ret) {
pr_err("error: Failed to initialise compressors\n");
goto out;
}
ret = jffs2_create_slab_caches();
if (ret) {
pr_err("error: Failed to initialise slab caches\n");
goto out_compressors;
}
ret = register_filesystem(&jffs2_fs_type);
if (ret) {
pr_err("error: Failed to register filesystem\n");
goto out_slab;
}
return 0;
out_slab:
jffs2_destroy_slab_caches();
out_compressors:
jffs2_compressors_exit();
out:
kmem_cache_destroy(jffs2_inode_cachep);
return ret;
}
static void __exit exit_jffs2_fs(void)
{
unregister_filesystem(&jffs2_fs_type);
jffs2_destroy_slab_caches();
jffs2_compressors_exit();
kmem_cache_destroy(jffs2_inode_cachep);
}
module_init(init_jffs2_fs);
module_exit(exit_jffs2_fs);
MODULE_DESCRIPTION("The Journalling Flash File System, v2");
MODULE_AUTHOR("Red Hat, Inc.");
MODULE_LICENSE("GPL"); // Actually dual-licensed, but it doesn't matter for
// the sake of this tag. It's Free Software.
| gpl-2.0 |
SlimRoms/kernel_samsung_jf | drivers/staging/media/lirc/lirc_serial.c | 4815 | 33071 | /*
* lirc_serial.c
*
* lirc_serial - Device driver that records pulse- and pause-lengths
* (space-lengths) between DDCD event on a serial port.
*
* Copyright (C) 1996,97 Ralph Metzler <rjkm@thp.uni-koeln.de>
* Copyright (C) 1998 Trent Piepho <xyzzy@u.washington.edu>
* Copyright (C) 1998 Ben Pfaff <blp@gnu.org>
* Copyright (C) 1999 Christoph Bartelmus <lirc@bartelmus.de>
* Copyright (C) 2007 Andrei Tanas <andrei@tanas.ca> (suspend/resume support)
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*
* Steve's changes to improve transmission fidelity:
* - for systems with the rdtsc instruction and the clock counter, a
* send_pule that times the pulses directly using the counter.
* This means that the LIRC_SERIAL_TRANSMITTER_LATENCY fudge is
* not needed. Measurement shows very stable waveform, even where
* PCI activity slows the access to the UART, which trips up other
* versions.
* - For other system, non-integer-microsecond pulse/space lengths,
* done using fixed point binary. So, much more accurate carrier
* frequency.
* - fine tuned transmitter latency, taking advantage of fractional
* microseconds in previous change
* - Fixed bug in the way transmitter latency was accounted for by
* tuning the pulse lengths down - the send_pulse routine ignored
* this overhead as it timed the overall pulse length - so the
* pulse frequency was right but overall pulse length was too
* long. Fixed by accounting for latency on each pulse/space
* iteration.
*
* Steve Davies <steve@daviesfam.org> July 2001
*/
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/fs.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/kernel.h>
#include <linux/serial_reg.h>
#include <linux/time.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/wait.h>
#include <linux/mm.h>
#include <linux/delay.h>
#include <linux/poll.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/fcntl.h>
#include <linux/spinlock.h>
#ifdef CONFIG_LIRC_SERIAL_NSLU2
#include <asm/hardware.h>
#endif
/* From Intel IXP42X Developer's Manual (#252480-005): */
/* ftp://download.intel.com/design/network/manuals/25248005.pdf */
#define UART_IE_IXP42X_UUE 0x40 /* IXP42X UART Unit enable */
#define UART_IE_IXP42X_RTOIE 0x10 /* IXP42X Receiver Data Timeout int.enable */
#include <media/lirc.h>
#include <media/lirc_dev.h>
#define LIRC_DRIVER_NAME "lirc_serial"
struct lirc_serial {
int signal_pin;
int signal_pin_change;
u8 on;
u8 off;
long (*send_pulse)(unsigned long length);
void (*send_space)(long length);
int features;
spinlock_t lock;
};
#define LIRC_HOMEBREW 0
#define LIRC_IRDEO 1
#define LIRC_IRDEO_REMOTE 2
#define LIRC_ANIMAX 3
#define LIRC_IGOR 4
#define LIRC_NSLU2 5
/*** module parameters ***/
static int type;
static int io;
static int irq;
static bool iommap;
static int ioshift;
static bool softcarrier = 1;
static bool share_irq;
static bool debug;
static int sense = -1; /* -1 = auto, 0 = active high, 1 = active low */
static bool txsense; /* 0 = active high, 1 = active low */
#define dprintk(fmt, args...) \
do { \
if (debug) \
printk(KERN_DEBUG LIRC_DRIVER_NAME ": " \
fmt, ## args); \
} while (0)
/* forward declarations */
static long send_pulse_irdeo(unsigned long length);
static long send_pulse_homebrew(unsigned long length);
static void send_space_irdeo(long length);
static void send_space_homebrew(long length);
static struct lirc_serial hardware[] = {
[LIRC_HOMEBREW] = {
.signal_pin = UART_MSR_DCD,
.signal_pin_change = UART_MSR_DDCD,
.on = (UART_MCR_RTS | UART_MCR_OUT2 | UART_MCR_DTR),
.off = (UART_MCR_RTS | UART_MCR_OUT2),
.send_pulse = send_pulse_homebrew,
.send_space = send_space_homebrew,
#ifdef CONFIG_LIRC_SERIAL_TRANSMITTER
.features = (LIRC_CAN_SET_SEND_DUTY_CYCLE |
LIRC_CAN_SET_SEND_CARRIER |
LIRC_CAN_SEND_PULSE | LIRC_CAN_REC_MODE2)
#else
.features = LIRC_CAN_REC_MODE2
#endif
},
[LIRC_IRDEO] = {
.signal_pin = UART_MSR_DSR,
.signal_pin_change = UART_MSR_DDSR,
.on = UART_MCR_OUT2,
.off = (UART_MCR_RTS | UART_MCR_DTR | UART_MCR_OUT2),
.send_pulse = send_pulse_irdeo,
.send_space = send_space_irdeo,
.features = (LIRC_CAN_SET_SEND_DUTY_CYCLE |
LIRC_CAN_SEND_PULSE | LIRC_CAN_REC_MODE2)
},
[LIRC_IRDEO_REMOTE] = {
.signal_pin = UART_MSR_DSR,
.signal_pin_change = UART_MSR_DDSR,
.on = (UART_MCR_RTS | UART_MCR_DTR | UART_MCR_OUT2),
.off = (UART_MCR_RTS | UART_MCR_DTR | UART_MCR_OUT2),
.send_pulse = send_pulse_irdeo,
.send_space = send_space_irdeo,
.features = (LIRC_CAN_SET_SEND_DUTY_CYCLE |
LIRC_CAN_SEND_PULSE | LIRC_CAN_REC_MODE2)
},
[LIRC_ANIMAX] = {
.signal_pin = UART_MSR_DCD,
.signal_pin_change = UART_MSR_DDCD,
.on = 0,
.off = (UART_MCR_RTS | UART_MCR_DTR | UART_MCR_OUT2),
.send_pulse = NULL,
.send_space = NULL,
.features = LIRC_CAN_REC_MODE2
},
[LIRC_IGOR] = {
.signal_pin = UART_MSR_DSR,
.signal_pin_change = UART_MSR_DDSR,
.on = (UART_MCR_RTS | UART_MCR_OUT2 | UART_MCR_DTR),
.off = (UART_MCR_RTS | UART_MCR_OUT2),
.send_pulse = send_pulse_homebrew,
.send_space = send_space_homebrew,
#ifdef CONFIG_LIRC_SERIAL_TRANSMITTER
.features = (LIRC_CAN_SET_SEND_DUTY_CYCLE |
LIRC_CAN_SET_SEND_CARRIER |
LIRC_CAN_SEND_PULSE | LIRC_CAN_REC_MODE2)
#else
.features = LIRC_CAN_REC_MODE2
#endif
},
#ifdef CONFIG_LIRC_SERIAL_NSLU2
/*
* Modified Linksys Network Storage Link USB 2.0 (NSLU2):
* We receive on CTS of the 2nd serial port (R142,LHS), we
* transmit with a IR diode between GPIO[1] (green status LED),
* and ground (Matthias Goebl <matthias.goebl@goebl.net>).
* See also http://www.nslu2-linux.org for this device
*/
[LIRC_NSLU2] = {
.signal_pin = UART_MSR_CTS,
.signal_pin_change = UART_MSR_DCTS,
.on = (UART_MCR_RTS | UART_MCR_OUT2 | UART_MCR_DTR),
.off = (UART_MCR_RTS | UART_MCR_OUT2),
.send_pulse = send_pulse_homebrew,
.send_space = send_space_homebrew,
#ifdef CONFIG_LIRC_SERIAL_TRANSMITTER
.features = (LIRC_CAN_SET_SEND_DUTY_CYCLE |
LIRC_CAN_SET_SEND_CARRIER |
LIRC_CAN_SEND_PULSE | LIRC_CAN_REC_MODE2)
#else
.features = LIRC_CAN_REC_MODE2
#endif
},
#endif
};
#define RS_ISR_PASS_LIMIT 256
/*
* A long pulse code from a remote might take up to 300 bytes. The
* daemon should read the bytes as soon as they are generated, so take
* the number of keys you think you can push before the daemon runs
* and multiply by 300. The driver will warn you if you overrun this
* buffer. If you have a slow computer or non-busmastering IDE disks,
* maybe you will need to increase this.
*/
/* This MUST be a power of two! It has to be larger than 1 as well. */
#define RBUF_LEN 256
static struct timeval lasttv = {0, 0};
static struct lirc_buffer rbuf;
static unsigned int freq = 38000;
static unsigned int duty_cycle = 50;
/* Initialized in init_timing_params() */
static unsigned long period;
static unsigned long pulse_width;
static unsigned long space_width;
#if defined(__i386__)
/*
* From:
* Linux I/O port programming mini-HOWTO
* Author: Riku Saikkonen <Riku.Saikkonen@hut.fi>
* v, 28 December 1997
*
* [...]
* Actually, a port I/O instruction on most ports in the 0-0x3ff range
* takes almost exactly 1 microsecond, so if you're, for example, using
* the parallel port directly, just do additional inb()s from that port
* to delay.
* [...]
*/
/* transmitter latency 1.5625us 0x1.90 - this figure arrived at from
* comment above plus trimming to match actual measured frequency.
* This will be sensitive to cpu speed, though hopefully most of the 1.5us
* is spent in the uart access. Still - for reference test machine was a
* 1.13GHz Athlon system - Steve
*/
/*
* changed from 400 to 450 as this works better on slower machines;
* faster machines will use the rdtsc code anyway
*/
#define LIRC_SERIAL_TRANSMITTER_LATENCY 450
#else
/* does anybody have information on other platforms ? */
/* 256 = 1<<8 */
#define LIRC_SERIAL_TRANSMITTER_LATENCY 256
#endif /* __i386__ */
/*
* FIXME: should we be using hrtimers instead of this
* LIRC_SERIAL_TRANSMITTER_LATENCY nonsense?
*/
/* fetch serial input packet (1 byte) from register offset */
static u8 sinp(int offset)
{
if (iommap != 0)
/* the register is memory-mapped */
offset <<= ioshift;
return inb(io + offset);
}
/* write serial output packet (1 byte) of value to register offset */
static void soutp(int offset, u8 value)
{
if (iommap != 0)
/* the register is memory-mapped */
offset <<= ioshift;
outb(value, io + offset);
}
static void on(void)
{
#ifdef CONFIG_LIRC_SERIAL_NSLU2
/*
* On NSLU2, we put the transmit diode between the output of the green
* status LED and ground
*/
if (type == LIRC_NSLU2) {
gpio_line_set(NSLU2_LED_GRN, IXP4XX_GPIO_LOW);
return;
}
#endif
if (txsense)
soutp(UART_MCR, hardware[type].off);
else
soutp(UART_MCR, hardware[type].on);
}
static void off(void)
{
#ifdef CONFIG_LIRC_SERIAL_NSLU2
if (type == LIRC_NSLU2) {
gpio_line_set(NSLU2_LED_GRN, IXP4XX_GPIO_HIGH);
return;
}
#endif
if (txsense)
soutp(UART_MCR, hardware[type].on);
else
soutp(UART_MCR, hardware[type].off);
}
#ifndef MAX_UDELAY_MS
#define MAX_UDELAY_US 5000
#else
#define MAX_UDELAY_US (MAX_UDELAY_MS*1000)
#endif
static void safe_udelay(unsigned long usecs)
{
while (usecs > MAX_UDELAY_US) {
udelay(MAX_UDELAY_US);
usecs -= MAX_UDELAY_US;
}
udelay(usecs);
}
#ifdef USE_RDTSC
/*
* This is an overflow/precision juggle, complicated in that we can't
* do long long divide in the kernel
*/
/*
* When we use the rdtsc instruction to measure clocks, we keep the
* pulse and space widths as clock cycles. As this is CPU speed
* dependent, the widths must be calculated in init_port and ioctl
* time
*/
/* So send_pulse can quickly convert microseconds to clocks */
static unsigned long conv_us_to_clocks;
static int init_timing_params(unsigned int new_duty_cycle,
unsigned int new_freq)
{
__u64 loops_per_sec, work;
duty_cycle = new_duty_cycle;
freq = new_freq;
loops_per_sec = __this_cpu_read(cpu.info.loops_per_jiffy);
loops_per_sec *= HZ;
/* How many clocks in a microsecond?, avoiding long long divide */
work = loops_per_sec;
work *= 4295; /* 4295 = 2^32 / 1e6 */
conv_us_to_clocks = (work >> 32);
/*
* Carrier period in clocks, approach good up to 32GHz clock,
* gets carrier frequency within 8Hz
*/
period = loops_per_sec >> 3;
period /= (freq >> 3);
/* Derive pulse and space from the period */
pulse_width = period * duty_cycle / 100;
space_width = period - pulse_width;
dprintk("in init_timing_params, freq=%d, duty_cycle=%d, "
"clk/jiffy=%ld, pulse=%ld, space=%ld, "
"conv_us_to_clocks=%ld\n",
freq, duty_cycle, __this_cpu_read(cpu_info.loops_per_jiffy),
pulse_width, space_width, conv_us_to_clocks);
return 0;
}
#else /* ! USE_RDTSC */
static int init_timing_params(unsigned int new_duty_cycle,
unsigned int new_freq)
{
/*
* period, pulse/space width are kept with 8 binary places -
* IE multiplied by 256.
*/
if (256 * 1000000L / new_freq * new_duty_cycle / 100 <=
LIRC_SERIAL_TRANSMITTER_LATENCY)
return -EINVAL;
if (256 * 1000000L / new_freq * (100 - new_duty_cycle) / 100 <=
LIRC_SERIAL_TRANSMITTER_LATENCY)
return -EINVAL;
duty_cycle = new_duty_cycle;
freq = new_freq;
period = 256 * 1000000L / freq;
pulse_width = period * duty_cycle / 100;
space_width = period - pulse_width;
dprintk("in init_timing_params, freq=%d pulse=%ld, "
"space=%ld\n", freq, pulse_width, space_width);
return 0;
}
#endif /* USE_RDTSC */
/* return value: space length delta */
static long send_pulse_irdeo(unsigned long length)
{
long rawbits, ret;
int i;
unsigned char output;
unsigned char chunk, shifted;
/* how many bits have to be sent ? */
rawbits = length * 1152 / 10000;
if (duty_cycle > 50)
chunk = 3;
else
chunk = 1;
for (i = 0, output = 0x7f; rawbits > 0; rawbits -= 3) {
shifted = chunk << (i * 3);
shifted >>= 1;
output &= (~shifted);
i++;
if (i == 3) {
soutp(UART_TX, output);
while (!(sinp(UART_LSR) & UART_LSR_THRE))
;
output = 0x7f;
i = 0;
}
}
if (i != 0) {
soutp(UART_TX, output);
while (!(sinp(UART_LSR) & UART_LSR_TEMT))
;
}
if (i == 0)
ret = (-rawbits) * 10000 / 1152;
else
ret = (3 - i) * 3 * 10000 / 1152 + (-rawbits) * 10000 / 1152;
return ret;
}
#ifdef USE_RDTSC
/* Version that uses Pentium rdtsc instruction to measure clocks */
/*
* This version does sub-microsecond timing using rdtsc instruction,
* and does away with the fudged LIRC_SERIAL_TRANSMITTER_LATENCY
* Implicitly i586 architecture... - Steve
*/
static long send_pulse_homebrew_softcarrier(unsigned long length)
{
int flag;
unsigned long target, start, now;
/* Get going quick as we can */
rdtscl(start);
on();
/* Convert length from microseconds to clocks */
length *= conv_us_to_clocks;
/* And loop till time is up - flipping at right intervals */
now = start;
target = pulse_width;
flag = 1;
/*
* FIXME: This looks like a hard busy wait, without even an occasional,
* polite, cpu_relax() call. There's got to be a better way?
*
* The i2c code has the result of a lot of bit-banging work, I wonder if
* there's something there which could be helpful here.
*/
while ((now - start) < length) {
/* Delay till flip time */
do {
rdtscl(now);
} while ((now - start) < target);
/* flip */
if (flag) {
rdtscl(now);
off();
target += space_width;
} else {
rdtscl(now); on();
target += pulse_width;
}
flag = !flag;
}
rdtscl(now);
return ((now - start) - length) / conv_us_to_clocks;
}
#else /* ! USE_RDTSC */
/* Version using udelay() */
/*
* here we use fixed point arithmetic, with 8
* fractional bits. that gets us within 0.1% or so of the right average
* frequency, albeit with some jitter in pulse length - Steve
*/
/* To match 8 fractional bits used for pulse/space length */
static long send_pulse_homebrew_softcarrier(unsigned long length)
{
int flag;
unsigned long actual, target, d;
length <<= 8;
actual = 0; target = 0; flag = 0;
while (actual < length) {
if (flag) {
off();
target += space_width;
} else {
on();
target += pulse_width;
}
d = (target - actual -
LIRC_SERIAL_TRANSMITTER_LATENCY + 128) >> 8;
/*
* Note - we've checked in ioctl that the pulse/space
* widths are big enough so that d is > 0
*/
udelay(d);
actual += (d << 8) + LIRC_SERIAL_TRANSMITTER_LATENCY;
flag = !flag;
}
return (actual-length) >> 8;
}
#endif /* USE_RDTSC */
static long send_pulse_homebrew(unsigned long length)
{
if (length <= 0)
return 0;
if (softcarrier)
return send_pulse_homebrew_softcarrier(length);
else {
on();
safe_udelay(length);
return 0;
}
}
static void send_space_irdeo(long length)
{
if (length <= 0)
return;
safe_udelay(length);
}
static void send_space_homebrew(long length)
{
off();
if (length <= 0)
return;
safe_udelay(length);
}
static void rbwrite(int l)
{
if (lirc_buffer_full(&rbuf)) {
/* no new signals will be accepted */
dprintk("Buffer overrun\n");
return;
}
lirc_buffer_write(&rbuf, (void *)&l);
}
static void frbwrite(int l)
{
/* simple noise filter */
static int pulse, space;
static unsigned int ptr;
if (ptr > 0 && (l & PULSE_BIT)) {
pulse += l & PULSE_MASK;
if (pulse > 250) {
rbwrite(space);
rbwrite(pulse | PULSE_BIT);
ptr = 0;
pulse = 0;
}
return;
}
if (!(l & PULSE_BIT)) {
if (ptr == 0) {
if (l > 20000) {
space = l;
ptr++;
return;
}
} else {
if (l > 20000) {
space += pulse;
if (space > PULSE_MASK)
space = PULSE_MASK;
space += l;
if (space > PULSE_MASK)
space = PULSE_MASK;
pulse = 0;
return;
}
rbwrite(space);
rbwrite(pulse | PULSE_BIT);
ptr = 0;
pulse = 0;
}
}
rbwrite(l);
}
static irqreturn_t irq_handler(int i, void *blah)
{
struct timeval tv;
int counter, dcd;
u8 status;
long deltv;
int data;
static int last_dcd = -1;
if ((sinp(UART_IIR) & UART_IIR_NO_INT)) {
/* not our interrupt */
return IRQ_NONE;
}
counter = 0;
do {
counter++;
status = sinp(UART_MSR);
if (counter > RS_ISR_PASS_LIMIT) {
printk(KERN_WARNING LIRC_DRIVER_NAME ": AIEEEE: "
"We're caught!\n");
break;
}
if ((status & hardware[type].signal_pin_change)
&& sense != -1) {
/* get current time */
do_gettimeofday(&tv);
/* New mode, written by Trent Piepho
<xyzzy@u.washington.edu>. */
/*
* The old format was not very portable.
* We now use an int to pass pulses
* and spaces to user space.
*
* If PULSE_BIT is set a pulse has been
* received, otherwise a space has been
* received. The driver needs to know if your
* receiver is active high or active low, or
* the space/pulse sense could be
* inverted. The bits denoted by PULSE_MASK are
* the length in microseconds. Lengths greater
* than or equal to 16 seconds are clamped to
* PULSE_MASK. All other bits are unused.
* This is a much simpler interface for user
* programs, as well as eliminating "out of
* phase" errors with space/pulse
* autodetection.
*/
/* calc time since last interrupt in microseconds */
dcd = (status & hardware[type].signal_pin) ? 1 : 0;
if (dcd == last_dcd) {
printk(KERN_WARNING LIRC_DRIVER_NAME
": ignoring spike: %d %d %lx %lx %lx %lx\n",
dcd, sense,
tv.tv_sec, lasttv.tv_sec,
tv.tv_usec, lasttv.tv_usec);
continue;
}
deltv = tv.tv_sec-lasttv.tv_sec;
if (tv.tv_sec < lasttv.tv_sec ||
(tv.tv_sec == lasttv.tv_sec &&
tv.tv_usec < lasttv.tv_usec)) {
printk(KERN_WARNING LIRC_DRIVER_NAME
": AIEEEE: your clock just jumped "
"backwards\n");
printk(KERN_WARNING LIRC_DRIVER_NAME
": %d %d %lx %lx %lx %lx\n",
dcd, sense,
tv.tv_sec, lasttv.tv_sec,
tv.tv_usec, lasttv.tv_usec);
data = PULSE_MASK;
} else if (deltv > 15) {
data = PULSE_MASK; /* really long time */
if (!(dcd^sense)) {
/* sanity check */
printk(KERN_WARNING LIRC_DRIVER_NAME
": AIEEEE: "
"%d %d %lx %lx %lx %lx\n",
dcd, sense,
tv.tv_sec, lasttv.tv_sec,
tv.tv_usec, lasttv.tv_usec);
/*
* detecting pulse while this
* MUST be a space!
*/
sense = sense ? 0 : 1;
}
} else
data = (int) (deltv*1000000 +
tv.tv_usec -
lasttv.tv_usec);
frbwrite(dcd^sense ? data : (data|PULSE_BIT));
lasttv = tv;
last_dcd = dcd;
wake_up_interruptible(&rbuf.wait_poll);
}
} while (!(sinp(UART_IIR) & UART_IIR_NO_INT)); /* still pending ? */
return IRQ_HANDLED;
}
static int hardware_init_port(void)
{
u8 scratch, scratch2, scratch3;
/*
* This is a simple port existence test, borrowed from the autoconfig
* function in drivers/serial/8250.c
*/
scratch = sinp(UART_IER);
soutp(UART_IER, 0);
#ifdef __i386__
outb(0xff, 0x080);
#endif
scratch2 = sinp(UART_IER) & 0x0f;
soutp(UART_IER, 0x0f);
#ifdef __i386__
outb(0x00, 0x080);
#endif
scratch3 = sinp(UART_IER) & 0x0f;
soutp(UART_IER, scratch);
if (scratch2 != 0 || scratch3 != 0x0f) {
/* we fail, there's nothing here */
printk(KERN_ERR LIRC_DRIVER_NAME ": port existence test "
"failed, cannot continue\n");
return -ENODEV;
}
/* Set DLAB 0. */
soutp(UART_LCR, sinp(UART_LCR) & (~UART_LCR_DLAB));
/* First of all, disable all interrupts */
soutp(UART_IER, sinp(UART_IER) &
(~(UART_IER_MSI|UART_IER_RLSI|UART_IER_THRI|UART_IER_RDI)));
/* Clear registers. */
sinp(UART_LSR);
sinp(UART_RX);
sinp(UART_IIR);
sinp(UART_MSR);
#ifdef CONFIG_LIRC_SERIAL_NSLU2
if (type == LIRC_NSLU2) {
/* Setup NSLU2 UART */
/* Enable UART */
soutp(UART_IER, sinp(UART_IER) | UART_IE_IXP42X_UUE);
/* Disable Receiver data Time out interrupt */
soutp(UART_IER, sinp(UART_IER) & ~UART_IE_IXP42X_RTOIE);
/* set out2 = interrupt unmask; off() doesn't set MCR
on NSLU2 */
soutp(UART_MCR, UART_MCR_RTS|UART_MCR_OUT2);
}
#endif
/* Set line for power source */
off();
/* Clear registers again to be sure. */
sinp(UART_LSR);
sinp(UART_RX);
sinp(UART_IIR);
sinp(UART_MSR);
switch (type) {
case LIRC_IRDEO:
case LIRC_IRDEO_REMOTE:
/* setup port to 7N1 @ 115200 Baud */
/* 7N1+start = 9 bits at 115200 ~ 3 bits at 38kHz */
/* Set DLAB 1. */
soutp(UART_LCR, sinp(UART_LCR) | UART_LCR_DLAB);
/* Set divisor to 1 => 115200 Baud */
soutp(UART_DLM, 0);
soutp(UART_DLL, 1);
/* Set DLAB 0 + 7N1 */
soutp(UART_LCR, UART_LCR_WLEN7);
/* THR interrupt already disabled at this point */
break;
default:
break;
}
return 0;
}
static int __devinit lirc_serial_probe(struct platform_device *dev)
{
int i, nlow, nhigh, result;
result = request_irq(irq, irq_handler,
(share_irq ? IRQF_SHARED : 0),
LIRC_DRIVER_NAME, (void *)&hardware);
if (result < 0) {
if (result == -EBUSY)
printk(KERN_ERR LIRC_DRIVER_NAME ": IRQ %d busy\n",
irq);
else if (result == -EINVAL)
printk(KERN_ERR LIRC_DRIVER_NAME
": Bad irq number or handler\n");
return result;
}
/* Reserve io region. */
/*
* Future MMAP-Developers: Attention!
* For memory mapped I/O you *might* need to use ioremap() first,
* for the NSLU2 it's done in boot code.
*/
if (((iommap != 0)
&& (request_mem_region(iommap, 8 << ioshift,
LIRC_DRIVER_NAME) == NULL))
|| ((iommap == 0)
&& (request_region(io, 8, LIRC_DRIVER_NAME) == NULL))) {
printk(KERN_ERR LIRC_DRIVER_NAME
": port %04x already in use\n", io);
printk(KERN_WARNING LIRC_DRIVER_NAME
": use 'setserial /dev/ttySX uart none'\n");
printk(KERN_WARNING LIRC_DRIVER_NAME
": or compile the serial port driver as module and\n");
printk(KERN_WARNING LIRC_DRIVER_NAME
": make sure this module is loaded first\n");
result = -EBUSY;
goto exit_free_irq;
}
result = hardware_init_port();
if (result < 0)
goto exit_release_region;
/* Initialize pulse/space widths */
init_timing_params(duty_cycle, freq);
/* If pin is high, then this must be an active low receiver. */
if (sense == -1) {
/* wait 1/2 sec for the power supply */
msleep(500);
/*
* probe 9 times every 0.04s, collect "votes" for
* active high/low
*/
nlow = 0;
nhigh = 0;
for (i = 0; i < 9; i++) {
if (sinp(UART_MSR) & hardware[type].signal_pin)
nlow++;
else
nhigh++;
msleep(40);
}
sense = (nlow >= nhigh ? 1 : 0);
printk(KERN_INFO LIRC_DRIVER_NAME ": auto-detected active "
"%s receiver\n", sense ? "low" : "high");
} else
printk(KERN_INFO LIRC_DRIVER_NAME ": Manually using active "
"%s receiver\n", sense ? "low" : "high");
dprintk("Interrupt %d, port %04x obtained\n", irq, io);
return 0;
exit_release_region:
if (iommap != 0)
release_mem_region(iommap, 8 << ioshift);
else
release_region(io, 8);
exit_free_irq:
free_irq(irq, (void *)&hardware);
return result;
}
static int __devexit lirc_serial_remove(struct platform_device *dev)
{
free_irq(irq, (void *)&hardware);
if (iommap != 0)
release_mem_region(iommap, 8 << ioshift);
else
release_region(io, 8);
return 0;
}
static int set_use_inc(void *data)
{
unsigned long flags;
/* initialize timestamp */
do_gettimeofday(&lasttv);
spin_lock_irqsave(&hardware[type].lock, flags);
/* Set DLAB 0. */
soutp(UART_LCR, sinp(UART_LCR) & (~UART_LCR_DLAB));
soutp(UART_IER, sinp(UART_IER)|UART_IER_MSI);
spin_unlock_irqrestore(&hardware[type].lock, flags);
return 0;
}
static void set_use_dec(void *data)
{ unsigned long flags;
spin_lock_irqsave(&hardware[type].lock, flags);
/* Set DLAB 0. */
soutp(UART_LCR, sinp(UART_LCR) & (~UART_LCR_DLAB));
/* First of all, disable all interrupts */
soutp(UART_IER, sinp(UART_IER) &
(~(UART_IER_MSI|UART_IER_RLSI|UART_IER_THRI|UART_IER_RDI)));
spin_unlock_irqrestore(&hardware[type].lock, flags);
}
static ssize_t lirc_write(struct file *file, const char *buf,
size_t n, loff_t *ppos)
{
int i, count;
unsigned long flags;
long delta = 0;
int *wbuf;
if (!(hardware[type].features & LIRC_CAN_SEND_PULSE))
return -EPERM;
count = n / sizeof(int);
if (n % sizeof(int) || count % 2 == 0)
return -EINVAL;
wbuf = memdup_user(buf, n);
if (IS_ERR(wbuf))
return PTR_ERR(wbuf);
spin_lock_irqsave(&hardware[type].lock, flags);
if (type == LIRC_IRDEO) {
/* DTR, RTS down */
on();
}
for (i = 0; i < count; i++) {
if (i%2)
hardware[type].send_space(wbuf[i] - delta);
else
delta = hardware[type].send_pulse(wbuf[i]);
}
off();
spin_unlock_irqrestore(&hardware[type].lock, flags);
kfree(wbuf);
return n;
}
static long lirc_ioctl(struct file *filep, unsigned int cmd, unsigned long arg)
{
int result;
__u32 value;
switch (cmd) {
case LIRC_GET_SEND_MODE:
if (!(hardware[type].features&LIRC_CAN_SEND_MASK))
return -ENOIOCTLCMD;
result = put_user(LIRC_SEND2MODE
(hardware[type].features&LIRC_CAN_SEND_MASK),
(__u32 *) arg);
if (result)
return result;
break;
case LIRC_SET_SEND_MODE:
if (!(hardware[type].features&LIRC_CAN_SEND_MASK))
return -ENOIOCTLCMD;
result = get_user(value, (__u32 *) arg);
if (result)
return result;
/* only LIRC_MODE_PULSE supported */
if (value != LIRC_MODE_PULSE)
return -EINVAL;
break;
case LIRC_GET_LENGTH:
return -ENOIOCTLCMD;
break;
case LIRC_SET_SEND_DUTY_CYCLE:
dprintk("SET_SEND_DUTY_CYCLE\n");
if (!(hardware[type].features&LIRC_CAN_SET_SEND_DUTY_CYCLE))
return -ENOIOCTLCMD;
result = get_user(value, (__u32 *) arg);
if (result)
return result;
if (value <= 0 || value > 100)
return -EINVAL;
return init_timing_params(value, freq);
break;
case LIRC_SET_SEND_CARRIER:
dprintk("SET_SEND_CARRIER\n");
if (!(hardware[type].features&LIRC_CAN_SET_SEND_CARRIER))
return -ENOIOCTLCMD;
result = get_user(value, (__u32 *) arg);
if (result)
return result;
if (value > 500000 || value < 20000)
return -EINVAL;
return init_timing_params(duty_cycle, value);
break;
default:
return lirc_dev_fop_ioctl(filep, cmd, arg);
}
return 0;
}
static const struct file_operations lirc_fops = {
.owner = THIS_MODULE,
.write = lirc_write,
.unlocked_ioctl = lirc_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = lirc_ioctl,
#endif
.read = lirc_dev_fop_read,
.poll = lirc_dev_fop_poll,
.open = lirc_dev_fop_open,
.release = lirc_dev_fop_close,
.llseek = no_llseek,
};
static struct lirc_driver driver = {
.name = LIRC_DRIVER_NAME,
.minor = -1,
.code_length = 1,
.sample_rate = 0,
.data = NULL,
.add_to_buf = NULL,
.rbuf = &rbuf,
.set_use_inc = set_use_inc,
.set_use_dec = set_use_dec,
.fops = &lirc_fops,
.dev = NULL,
.owner = THIS_MODULE,
};
static struct platform_device *lirc_serial_dev;
static int lirc_serial_suspend(struct platform_device *dev,
pm_message_t state)
{
/* Set DLAB 0. */
soutp(UART_LCR, sinp(UART_LCR) & (~UART_LCR_DLAB));
/* Disable all interrupts */
soutp(UART_IER, sinp(UART_IER) &
(~(UART_IER_MSI|UART_IER_RLSI|UART_IER_THRI|UART_IER_RDI)));
/* Clear registers. */
sinp(UART_LSR);
sinp(UART_RX);
sinp(UART_IIR);
sinp(UART_MSR);
return 0;
}
/* twisty maze... need a forward-declaration here... */
static void lirc_serial_exit(void);
static int lirc_serial_resume(struct platform_device *dev)
{
unsigned long flags;
int result;
result = hardware_init_port();
if (result < 0)
return result;
spin_lock_irqsave(&hardware[type].lock, flags);
/* Enable Interrupt */
do_gettimeofday(&lasttv);
soutp(UART_IER, sinp(UART_IER)|UART_IER_MSI);
off();
lirc_buffer_clear(&rbuf);
spin_unlock_irqrestore(&hardware[type].lock, flags);
return 0;
}
static struct platform_driver lirc_serial_driver = {
.probe = lirc_serial_probe,
.remove = __devexit_p(lirc_serial_remove),
.suspend = lirc_serial_suspend,
.resume = lirc_serial_resume,
.driver = {
.name = "lirc_serial",
.owner = THIS_MODULE,
},
};
static int __init lirc_serial_init(void)
{
int result;
/* Init read buffer. */
result = lirc_buffer_init(&rbuf, sizeof(int), RBUF_LEN);
if (result < 0)
return result;
result = platform_driver_register(&lirc_serial_driver);
if (result) {
printk("lirc register returned %d\n", result);
goto exit_buffer_free;
}
lirc_serial_dev = platform_device_alloc("lirc_serial", 0);
if (!lirc_serial_dev) {
result = -ENOMEM;
goto exit_driver_unregister;
}
result = platform_device_add(lirc_serial_dev);
if (result)
goto exit_device_put;
return 0;
exit_device_put:
platform_device_put(lirc_serial_dev);
exit_driver_unregister:
platform_driver_unregister(&lirc_serial_driver);
exit_buffer_free:
lirc_buffer_free(&rbuf);
return result;
}
static void lirc_serial_exit(void)
{
platform_device_unregister(lirc_serial_dev);
platform_driver_unregister(&lirc_serial_driver);
lirc_buffer_free(&rbuf);
}
static int __init lirc_serial_init_module(void)
{
int result;
switch (type) {
case LIRC_HOMEBREW:
case LIRC_IRDEO:
case LIRC_IRDEO_REMOTE:
case LIRC_ANIMAX:
case LIRC_IGOR:
/* if nothing specified, use ttyS0/com1 and irq 4 */
io = io ? io : 0x3f8;
irq = irq ? irq : 4;
break;
#ifdef CONFIG_LIRC_SERIAL_NSLU2
case LIRC_NSLU2:
io = io ? io : IRQ_IXP4XX_UART2;
irq = irq ? irq : (IXP4XX_UART2_BASE_VIRT + REG_OFFSET);
iommap = iommap ? iommap : IXP4XX_UART2_BASE_PHYS;
ioshift = ioshift ? ioshift : 2;
break;
#endif
default:
return -EINVAL;
}
if (!softcarrier) {
switch (type) {
case LIRC_HOMEBREW:
case LIRC_IGOR:
#ifdef CONFIG_LIRC_SERIAL_NSLU2
case LIRC_NSLU2:
#endif
hardware[type].features &=
~(LIRC_CAN_SET_SEND_DUTY_CYCLE|
LIRC_CAN_SET_SEND_CARRIER);
break;
}
}
result = lirc_serial_init();
if (result)
return result;
driver.features = hardware[type].features;
driver.dev = &lirc_serial_dev->dev;
driver.minor = lirc_register_driver(&driver);
if (driver.minor < 0) {
printk(KERN_ERR LIRC_DRIVER_NAME
": register_chrdev failed!\n");
lirc_serial_exit();
return driver.minor;
}
return 0;
}
static void __exit lirc_serial_exit_module(void)
{
lirc_unregister_driver(driver.minor);
lirc_serial_exit();
dprintk("cleaned up module\n");
}
module_init(lirc_serial_init_module);
module_exit(lirc_serial_exit_module);
MODULE_DESCRIPTION("Infra-red receiver driver for serial ports.");
MODULE_AUTHOR("Ralph Metzler, Trent Piepho, Ben Pfaff, "
"Christoph Bartelmus, Andrei Tanas");
MODULE_LICENSE("GPL");
module_param(type, int, S_IRUGO);
MODULE_PARM_DESC(type, "Hardware type (0 = home-brew, 1 = IRdeo,"
" 2 = IRdeo Remote, 3 = AnimaX, 4 = IgorPlug,"
" 5 = NSLU2 RX:CTS2/TX:GreenLED)");
module_param(io, int, S_IRUGO);
MODULE_PARM_DESC(io, "I/O address base (0x3f8 or 0x2f8)");
/* some architectures (e.g. intel xscale) have memory mapped registers */
module_param(iommap, bool, S_IRUGO);
MODULE_PARM_DESC(iommap, "physical base for memory mapped I/O"
" (0 = no memory mapped io)");
/*
* some architectures (e.g. intel xscale) align the 8bit serial registers
* on 32bit word boundaries.
* See linux-kernel/drivers/tty/serial/8250/8250.c serial_in()/out()
*/
module_param(ioshift, int, S_IRUGO);
MODULE_PARM_DESC(ioshift, "shift I/O register offset (0 = no shift)");
module_param(irq, int, S_IRUGO);
MODULE_PARM_DESC(irq, "Interrupt (4 or 3)");
module_param(share_irq, bool, S_IRUGO);
MODULE_PARM_DESC(share_irq, "Share interrupts (0 = off, 1 = on)");
module_param(sense, bool, S_IRUGO);
MODULE_PARM_DESC(sense, "Override autodetection of IR receiver circuit"
" (0 = active high, 1 = active low )");
#ifdef CONFIG_LIRC_SERIAL_TRANSMITTER
module_param(txsense, bool, S_IRUGO);
MODULE_PARM_DESC(txsense, "Sense of transmitter circuit"
" (0 = active high, 1 = active low )");
#endif
module_param(softcarrier, bool, S_IRUGO);
MODULE_PARM_DESC(softcarrier, "Software carrier (0 = off, 1 = on, default on)");
module_param(debug, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Enable debugging messages");
| gpl-2.0 |
spock1104/android_kernel_zte_nex | drivers/media/video/tm6000/tm6000-input.c | 4815 | 11873 | /*
* tm6000-input.c - driver for TM5600/TM6000/TM6010 USB video capture devices
*
* Copyright (C) 2010 Stefan Ringel <stefan.ringel@arcor.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 version 2
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/input.h>
#include <linux/usb.h>
#include <media/rc-core.h>
#include "tm6000.h"
#include "tm6000-regs.h"
static unsigned int ir_debug;
module_param(ir_debug, int, 0644);
MODULE_PARM_DESC(ir_debug, "debug message level");
static unsigned int enable_ir = 1;
module_param(enable_ir, int, 0644);
MODULE_PARM_DESC(enable_ir, "enable ir (default is enable)");
static unsigned int ir_clock_mhz = 12;
module_param(ir_clock_mhz, int, 0644);
MODULE_PARM_DESC(enable_ir, "ir clock, in MHz");
#define URB_SUBMIT_DELAY 100 /* ms - Delay to submit an URB request on retrial and init */
#define URB_INT_LED_DELAY 100 /* ms - Delay to turn led on again on int mode */
#undef dprintk
#define dprintk(level, fmt, arg...) do {\
if (ir_debug >= level) \
printk(KERN_DEBUG "%s/ir: " fmt, ir->name , ## arg); \
} while (0)
struct tm6000_ir_poll_result {
u16 rc_data;
};
struct tm6000_IR {
struct tm6000_core *dev;
struct rc_dev *rc;
char name[32];
char phys[32];
/* poll expernal decoder */
int polling;
struct delayed_work work;
u8 wait:1;
u8 pwled:2;
u8 submit_urb:1;
u16 key_addr;
struct urb *int_urb;
/* IR device properties */
u64 rc_type;
};
void tm6000_ir_wait(struct tm6000_core *dev, u8 state)
{
struct tm6000_IR *ir = dev->ir;
if (!dev->ir)
return;
dprintk(2, "%s: %i\n",__func__, ir->wait);
if (state)
ir->wait = 1;
else
ir->wait = 0;
}
static int tm6000_ir_config(struct tm6000_IR *ir)
{
struct tm6000_core *dev = ir->dev;
u32 pulse = 0, leader = 0;
dprintk(2, "%s\n",__func__);
/*
* The IR decoder supports RC-5 or NEC, with a configurable timing.
* The timing configuration there is not that accurate, as it uses
* approximate values. The NEC spec mentions a 562.5 unit period,
* and RC-5 uses a 888.8 period.
* Currently, driver assumes a clock provided by a 12 MHz XTAL, but
* a modprobe parameter can adjust it.
* Adjustments are required for other timings.
* It seems that the 900ms timing for NEC is used to detect a RC-5
* IR, in order to discard such decoding
*/
switch (ir->rc_type) {
case RC_TYPE_NEC:
leader = 900; /* ms */
pulse = 700; /* ms - the actual value would be 562 */
break;
default:
case RC_TYPE_RC5:
leader = 900; /* ms - from the NEC decoding */
pulse = 1780; /* ms - The actual value would be 1776 */
break;
}
pulse = ir_clock_mhz * pulse;
leader = ir_clock_mhz * leader;
if (ir->rc_type == RC_TYPE_NEC)
leader = leader | 0x8000;
dprintk(2, "%s: %s, %d MHz, leader = 0x%04x, pulse = 0x%06x \n",
__func__,
(ir->rc_type == RC_TYPE_NEC) ? "NEC" : "RC-5",
ir_clock_mhz, leader, pulse);
/* Remote WAKEUP = enable, normal mode, from IR decoder output */
tm6000_set_reg(dev, TM6010_REQ07_RE5_REMOTE_WAKEUP, 0xfe);
/* Enable IR reception on non-busrt mode */
tm6000_set_reg(dev, TM6010_REQ07_RD8_IR, 0x2f);
/* IR_WKUP_SEL = Low byte in decoded IR data */
tm6000_set_reg(dev, TM6010_REQ07_RDA_IR_WAKEUP_SEL, 0xff);
/* IR_WKU_ADD code */
tm6000_set_reg(dev, TM6010_REQ07_RDB_IR_WAKEUP_ADD, 0xff);
tm6000_set_reg(dev, TM6010_REQ07_RDC_IR_LEADER1, leader >> 8);
tm6000_set_reg(dev, TM6010_REQ07_RDD_IR_LEADER0, leader);
tm6000_set_reg(dev, TM6010_REQ07_RDE_IR_PULSE_CNT1, pulse >> 8);
tm6000_set_reg(dev, TM6010_REQ07_RDF_IR_PULSE_CNT0, pulse);
if (!ir->polling)
tm6000_set_reg(dev, REQ_04_EN_DISABLE_MCU_INT, 2, 0);
else
tm6000_set_reg(dev, REQ_04_EN_DISABLE_MCU_INT, 2, 1);
msleep(10);
/* Shows that IR is working via the LED */
tm6000_flash_led(dev, 0);
msleep(100);
tm6000_flash_led(dev, 1);
ir->pwled = 1;
return 0;
}
static void tm6000_ir_urb_received(struct urb *urb)
{
struct tm6000_core *dev = urb->context;
struct tm6000_IR *ir = dev->ir;
struct tm6000_ir_poll_result poll_result;
char *buf;
int rc;
dprintk(2, "%s\n",__func__);
if (urb->status < 0 || urb->actual_length <= 0) {
printk(KERN_INFO "tm6000: IR URB failure: status: %i, length %i\n",
urb->status, urb->actual_length);
ir->submit_urb = 1;
schedule_delayed_work(&ir->work, msecs_to_jiffies(URB_SUBMIT_DELAY));
return;
}
buf = urb->transfer_buffer;
if (ir_debug)
print_hex_dump(KERN_DEBUG, "tm6000: IR data: ",
DUMP_PREFIX_OFFSET,16, 1,
buf, urb->actual_length, false);
poll_result.rc_data = buf[0];
if (urb->actual_length > 1)
poll_result.rc_data |= buf[1] << 8;
dprintk(1, "%s, scancode: 0x%04x\n",__func__, poll_result.rc_data);
rc_keydown(ir->rc, poll_result.rc_data, 0);
rc = usb_submit_urb(urb, GFP_ATOMIC);
/*
* Flash the led. We can't do it here, as it is running on IRQ context.
* So, use the scheduler to do it, in a few ms.
*/
ir->pwled = 2;
schedule_delayed_work(&ir->work, msecs_to_jiffies(10));
}
static void tm6000_ir_handle_key(struct work_struct *work)
{
struct tm6000_IR *ir = container_of(work, struct tm6000_IR, work.work);
struct tm6000_core *dev = ir->dev;
struct tm6000_ir_poll_result poll_result;
int rc;
u8 buf[2];
if (ir->wait)
return;
dprintk(3, "%s\n",__func__);
rc = tm6000_read_write_usb(dev, USB_DIR_IN |
USB_TYPE_VENDOR | USB_RECIP_DEVICE,
REQ_02_GET_IR_CODE, 0, 0, buf, 2);
if (rc < 0)
return;
if (rc > 1)
poll_result.rc_data = buf[0] | buf[1] << 8;
else
poll_result.rc_data = buf[0];
/* Check if something was read */
if ((poll_result.rc_data & 0xff) == 0xff) {
if (!ir->pwled) {
tm6000_flash_led(dev, 1);
ir->pwled = 1;
}
return;
}
dprintk(1, "%s, scancode: 0x%04x\n",__func__, poll_result.rc_data);
rc_keydown(ir->rc, poll_result.rc_data, 0);
tm6000_flash_led(dev, 0);
ir->pwled = 0;
/* Re-schedule polling */
schedule_delayed_work(&ir->work, msecs_to_jiffies(ir->polling));
}
static void tm6000_ir_int_work(struct work_struct *work)
{
struct tm6000_IR *ir = container_of(work, struct tm6000_IR, work.work);
struct tm6000_core *dev = ir->dev;
int rc;
dprintk(3, "%s, submit_urb = %d, pwled = %d\n",__func__, ir->submit_urb,
ir->pwled);
if (ir->submit_urb) {
dprintk(3, "Resubmit urb\n");
tm6000_set_reg(dev, REQ_04_EN_DISABLE_MCU_INT, 2, 0);
rc = usb_submit_urb(ir->int_urb, GFP_ATOMIC);
if (rc < 0) {
printk(KERN_ERR "tm6000: Can't submit an IR interrupt. Error %i\n",
rc);
/* Retry in 100 ms */
schedule_delayed_work(&ir->work, msecs_to_jiffies(URB_SUBMIT_DELAY));
return;
}
ir->submit_urb = 0;
}
/* Led is enabled only if USB submit doesn't fail */
if (ir->pwled == 2) {
tm6000_flash_led(dev, 0);
ir->pwled = 0;
schedule_delayed_work(&ir->work, msecs_to_jiffies(URB_INT_LED_DELAY));
} else if (!ir->pwled) {
tm6000_flash_led(dev, 1);
ir->pwled = 1;
}
}
static int tm6000_ir_start(struct rc_dev *rc)
{
struct tm6000_IR *ir = rc->priv;
dprintk(2, "%s\n",__func__);
schedule_delayed_work(&ir->work, 0);
return 0;
}
static void tm6000_ir_stop(struct rc_dev *rc)
{
struct tm6000_IR *ir = rc->priv;
dprintk(2, "%s\n",__func__);
cancel_delayed_work_sync(&ir->work);
}
static int tm6000_ir_change_protocol(struct rc_dev *rc, u64 rc_type)
{
struct tm6000_IR *ir = rc->priv;
if (!ir)
return 0;
dprintk(2, "%s\n",__func__);
if ((rc->rc_map.scan) && (rc_type == RC_TYPE_NEC))
ir->key_addr = ((rc->rc_map.scan[0].scancode >> 8) & 0xffff);
ir->rc_type = rc_type;
tm6000_ir_config(ir);
/* TODO */
return 0;
}
static int __tm6000_ir_int_start(struct rc_dev *rc)
{
struct tm6000_IR *ir = rc->priv;
struct tm6000_core *dev = ir->dev;
int pipe, size;
int err = -ENOMEM;
if (!ir)
return -ENODEV;
dprintk(2, "%s\n",__func__);
ir->int_urb = usb_alloc_urb(0, GFP_ATOMIC);
if (!ir->int_urb)
return -ENOMEM;
pipe = usb_rcvintpipe(dev->udev,
dev->int_in.endp->desc.bEndpointAddress
& USB_ENDPOINT_NUMBER_MASK);
size = usb_maxpacket(dev->udev, pipe, usb_pipeout(pipe));
dprintk(1, "IR max size: %d\n", size);
ir->int_urb->transfer_buffer = kzalloc(size, GFP_ATOMIC);
if (ir->int_urb->transfer_buffer == NULL) {
usb_free_urb(ir->int_urb);
return err;
}
dprintk(1, "int interval: %d\n", dev->int_in.endp->desc.bInterval);
usb_fill_int_urb(ir->int_urb, dev->udev, pipe,
ir->int_urb->transfer_buffer, size,
tm6000_ir_urb_received, dev,
dev->int_in.endp->desc.bInterval);
ir->submit_urb = 1;
schedule_delayed_work(&ir->work, msecs_to_jiffies(URB_SUBMIT_DELAY));
return 0;
}
static void __tm6000_ir_int_stop(struct rc_dev *rc)
{
struct tm6000_IR *ir = rc->priv;
if (!ir || !ir->int_urb)
return;
dprintk(2, "%s\n",__func__);
usb_kill_urb(ir->int_urb);
kfree(ir->int_urb->transfer_buffer);
usb_free_urb(ir->int_urb);
ir->int_urb = NULL;
}
int tm6000_ir_int_start(struct tm6000_core *dev)
{
struct tm6000_IR *ir = dev->ir;
if (!ir)
return 0;
return __tm6000_ir_int_start(ir->rc);
}
void tm6000_ir_int_stop(struct tm6000_core *dev)
{
struct tm6000_IR *ir = dev->ir;
if (!ir || !ir->rc)
return;
__tm6000_ir_int_stop(ir->rc);
}
int tm6000_ir_init(struct tm6000_core *dev)
{
struct tm6000_IR *ir;
struct rc_dev *rc;
int err = -ENOMEM;
if (!enable_ir)
return -ENODEV;
if (!dev->caps.has_remote)
return 0;
if (!dev->ir_codes)
return 0;
ir = kzalloc(sizeof(*ir), GFP_ATOMIC);
rc = rc_allocate_device();
if (!ir || !rc)
goto out;
dprintk(2, "%s\n", __func__);
/* record handles to ourself */
ir->dev = dev;
dev->ir = ir;
ir->rc = rc;
/* input setup */
rc->allowed_protos = RC_TYPE_RC5 | RC_TYPE_NEC;
/* Neded, in order to support NEC remotes with 24 or 32 bits */
rc->scanmask = 0xffff;
rc->priv = ir;
rc->change_protocol = tm6000_ir_change_protocol;
if (dev->int_in.endp) {
rc->open = __tm6000_ir_int_start;
rc->close = __tm6000_ir_int_stop;
INIT_DELAYED_WORK(&ir->work, tm6000_ir_int_work);
} else {
rc->open = tm6000_ir_start;
rc->close = tm6000_ir_stop;
ir->polling = 50;
INIT_DELAYED_WORK(&ir->work, tm6000_ir_handle_key);
}
rc->driver_type = RC_DRIVER_SCANCODE;
snprintf(ir->name, sizeof(ir->name), "tm5600/60x0 IR (%s)",
dev->name);
usb_make_path(dev->udev, ir->phys, sizeof(ir->phys));
strlcat(ir->phys, "/input0", sizeof(ir->phys));
tm6000_ir_change_protocol(rc, RC_TYPE_UNKNOWN);
rc->input_name = ir->name;
rc->input_phys = ir->phys;
rc->input_id.bustype = BUS_USB;
rc->input_id.version = 1;
rc->input_id.vendor = le16_to_cpu(dev->udev->descriptor.idVendor);
rc->input_id.product = le16_to_cpu(dev->udev->descriptor.idProduct);
rc->map_name = dev->ir_codes;
rc->driver_name = "tm6000";
rc->dev.parent = &dev->udev->dev;
/* ir register */
err = rc_register_device(rc);
if (err)
goto out;
return 0;
out:
dev->ir = NULL;
rc_free_device(rc);
kfree(ir);
return err;
}
int tm6000_ir_fini(struct tm6000_core *dev)
{
struct tm6000_IR *ir = dev->ir;
/* skip detach on non attached board */
if (!ir)
return 0;
dprintk(2, "%s\n",__func__);
if (!ir->polling)
__tm6000_ir_int_stop(ir->rc);
tm6000_ir_stop(ir->rc);
/* Turn off the led */
tm6000_flash_led(dev, 0);
ir->pwled = 0;
rc_unregister_device(ir->rc);
kfree(ir);
dev->ir = NULL;
return 0;
}
| gpl-2.0 |
haiviet2011/android_kernel_ef47s | drivers/staging/rtl8712/rtl871x_ioctl_set.c | 5071 | 11967 | /******************************************************************************
* rtl871x_ioctl_set.c
*
* Copyright(c) 2007 - 2010 Realtek Corporation. All rights reserved.
* Linux device driver for RTL8192SU
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* Modifications for inclusion into the Linux staging tree are
* Copyright(c) 2010 Larry Finger. All rights reserved.
*
* Contact information:
* WLAN FAE <wlanfae@realtek.com>
* Larry Finger <Larry.Finger@lwfinger.net>
*
******************************************************************************/
#define _RTL871X_IOCTL_SET_C_
#include "osdep_service.h"
#include "drv_types.h"
#include "rtl871x_ioctl_set.h"
#include "usb_osintf.h"
#include "usb_ops.h"
#define IS_MAC_ADDRESS_BROADCAST(addr) \
( \
((addr[0] == 0xff) && (addr[1] == 0xff) && \
(addr[2] == 0xff) && (addr[3] == 0xff) && \
(addr[4] == 0xff) && (addr[5] == 0xff)) ? true : false \
)
static u8 validate_ssid(struct ndis_802_11_ssid *ssid)
{
u8 i;
if (ssid->SsidLength > 32)
return false;
for (i = 0; i < ssid->SsidLength; i++) {
/* wifi, printable ascii code must be supported */
if (!((ssid->Ssid[i] >= 0x20) && (ssid->Ssid[i] <= 0x7e)))
return false;
}
return true;
}
static u8 do_join(struct _adapter *padapter)
{
struct list_head *plist, *phead;
u8 *pibss = NULL;
struct mlme_priv *pmlmepriv = &(padapter->mlmepriv);
struct __queue *queue = &(pmlmepriv->scanned_queue);
phead = get_list_head(queue);
plist = get_next(phead);
pmlmepriv->cur_network.join_res = -2;
pmlmepriv->fw_state |= _FW_UNDER_LINKING;
pmlmepriv->pscanned = plist;
pmlmepriv->to_join = true;
/* adhoc mode will start with an empty queue, but skip checking */
if (!check_fwstate(pmlmepriv, WIFI_ADHOC_STATE) &&
_queue_empty(queue)) {
if (pmlmepriv->fw_state & _FW_UNDER_LINKING)
pmlmepriv->fw_state ^= _FW_UNDER_LINKING;
/* when set_ssid/set_bssid for do_join(), but scanning queue
* is empty we try to issue sitesurvey firstly
*/
if (pmlmepriv->sitesurveyctrl.traffic_busy == false)
r8712_sitesurvey_cmd(padapter, &pmlmepriv->assoc_ssid);
return true;
} else {
int ret;
ret = r8712_select_and_join_from_scan(pmlmepriv);
if (ret == _SUCCESS)
_set_timer(&pmlmepriv->assoc_timer, MAX_JOIN_TIMEOUT);
else {
if (check_fwstate(pmlmepriv, WIFI_ADHOC_STATE)) {
/* submit r8712_createbss_cmd to change to an
* ADHOC_MASTER pmlmepriv->lock has been
* acquired by caller...
*/
struct wlan_bssid_ex *pdev_network =
&(padapter->registrypriv.dev_network);
pmlmepriv->fw_state = WIFI_ADHOC_MASTER_STATE;
pibss = padapter->registrypriv.dev_network.
MacAddress;
memset(&pdev_network->Ssid, 0,
sizeof(struct ndis_802_11_ssid));
memcpy(&pdev_network->Ssid,
&pmlmepriv->assoc_ssid,
sizeof(struct ndis_802_11_ssid));
r8712_update_registrypriv_dev_network(padapter);
r8712_generate_random_ibss(pibss);
if (r8712_createbss_cmd(padapter) != _SUCCESS)
return false;
pmlmepriv->to_join = false;
} else {
/* can't associate ; reset under-linking */
if (pmlmepriv->fw_state & _FW_UNDER_LINKING)
pmlmepriv->fw_state ^=
_FW_UNDER_LINKING;
/* when set_ssid/set_bssid for do_join(), but
* there are no desired bss in scanning queue
* we try to issue sitesurvey first
*/
if (!pmlmepriv->sitesurveyctrl.traffic_busy)
r8712_sitesurvey_cmd(padapter,
&pmlmepriv->assoc_ssid);
}
}
}
return true;
}
u8 r8712_set_802_11_bssid(struct _adapter *padapter, u8 *bssid)
{
unsigned long irqL;
u8 status = true;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
if ((bssid[0] == 0x00 && bssid[1] == 0x00 && bssid[2] == 0x00 &&
bssid[3] == 0x00 && bssid[4] == 0x00 && bssid[5] == 0x00) ||
(bssid[0] == 0xFF && bssid[1] == 0xFF && bssid[2] == 0xFF &&
bssid[3] == 0xFF && bssid[4] == 0xFF && bssid[5] == 0xFF)) {
status = false;
return status;
}
spin_lock_irqsave(&pmlmepriv->lock, irqL);
if (check_fwstate(pmlmepriv, _FW_UNDER_SURVEY |
_FW_UNDER_LINKING) == true) {
status = check_fwstate(pmlmepriv, _FW_UNDER_LINKING);
goto _Abort_Set_BSSID;
}
if (check_fwstate(pmlmepriv,
_FW_LINKED|WIFI_ADHOC_MASTER_STATE) == true) {
if (!memcmp(&pmlmepriv->cur_network.network.MacAddress, bssid,
ETH_ALEN)) {
if (check_fwstate(pmlmepriv,
WIFI_STATION_STATE) == false)
goto _Abort_Set_BSSID; /* driver is in
* WIFI_ADHOC_MASTER_STATE */
} else {
r8712_disassoc_cmd(padapter);
if (check_fwstate(pmlmepriv, _FW_LINKED) == true)
r8712_ind_disconnect(padapter);
r8712_free_assoc_resources(padapter);
if ((check_fwstate(pmlmepriv,
WIFI_ADHOC_MASTER_STATE))) {
_clr_fwstate_(pmlmepriv,
WIFI_ADHOC_MASTER_STATE);
set_fwstate(pmlmepriv, WIFI_ADHOC_STATE);
}
}
}
memcpy(&pmlmepriv->assoc_bssid, bssid, ETH_ALEN);
pmlmepriv->assoc_by_bssid = true;
status = do_join(padapter);
goto done;
_Abort_Set_BSSID:
done:
spin_unlock_irqrestore(&pmlmepriv->lock, irqL);
return status;
}
void r8712_set_802_11_ssid(struct _adapter *padapter,
struct ndis_802_11_ssid *ssid)
{
unsigned long irqL;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct wlan_network *pnetwork = &pmlmepriv->cur_network;
if (padapter->hw_init_completed == false)
return;
spin_lock_irqsave(&pmlmepriv->lock, irqL);
if (check_fwstate(pmlmepriv, _FW_UNDER_SURVEY|_FW_UNDER_LINKING)) {
check_fwstate(pmlmepriv, _FW_UNDER_LINKING);
goto _Abort_Set_SSID;
}
if (check_fwstate(pmlmepriv, _FW_LINKED|WIFI_ADHOC_MASTER_STATE)) {
if ((pmlmepriv->assoc_ssid.SsidLength == ssid->SsidLength) &&
(!memcmp(&pmlmepriv->assoc_ssid.Ssid, ssid->Ssid,
ssid->SsidLength))) {
if ((check_fwstate(pmlmepriv,
WIFI_STATION_STATE) == false)) {
if (r8712_is_same_ibss(padapter,
pnetwork) == false) {
/* if in WIFI_ADHOC_MASTER_STATE or
* WIFI_ADHOC_STATE, create bss or
* rejoin again
*/
r8712_disassoc_cmd(padapter);
if (check_fwstate(pmlmepriv,
_FW_LINKED) == true)
r8712_ind_disconnect(padapter);
r8712_free_assoc_resources(padapter);
if (check_fwstate(pmlmepriv,
WIFI_ADHOC_MASTER_STATE)) {
_clr_fwstate_(pmlmepriv,
WIFI_ADHOC_MASTER_STATE);
set_fwstate(pmlmepriv,
WIFI_ADHOC_STATE);
}
} else
goto _Abort_Set_SSID; /* driver is in
* WIFI_ADHOC_MASTER_STATE */
}
} else {
r8712_disassoc_cmd(padapter);
if (check_fwstate(pmlmepriv, _FW_LINKED) == true)
r8712_ind_disconnect(padapter);
r8712_free_assoc_resources(padapter);
if (check_fwstate(pmlmepriv,
WIFI_ADHOC_MASTER_STATE) == true) {
_clr_fwstate_(pmlmepriv,
WIFI_ADHOC_MASTER_STATE);
set_fwstate(pmlmepriv, WIFI_ADHOC_STATE);
}
}
}
if (padapter->securitypriv.btkip_countermeasure == true)
goto _Abort_Set_SSID;
if (validate_ssid(ssid) == false)
goto _Abort_Set_SSID;
memcpy(&pmlmepriv->assoc_ssid, ssid, sizeof(struct ndis_802_11_ssid));
pmlmepriv->assoc_by_bssid = false;
do_join(padapter);
goto done;
_Abort_Set_SSID:
done:
spin_unlock_irqrestore(&pmlmepriv->lock, irqL);
}
void r8712_set_802_11_infrastructure_mode(struct _adapter *padapter,
enum NDIS_802_11_NETWORK_INFRASTRUCTURE networktype)
{
unsigned long irqL;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct wlan_network *cur_network = &pmlmepriv->cur_network;
enum NDIS_802_11_NETWORK_INFRASTRUCTURE *pold_state =
&(cur_network->network.InfrastructureMode);
if (*pold_state != networktype) {
spin_lock_irqsave(&pmlmepriv->lock, irqL);
if ((check_fwstate(pmlmepriv, _FW_LINKED) == true) ||
(*pold_state == Ndis802_11IBSS))
r8712_disassoc_cmd(padapter);
if (check_fwstate(pmlmepriv,
_FW_LINKED|WIFI_ADHOC_MASTER_STATE) == true)
r8712_free_assoc_resources(padapter);
if ((check_fwstate(pmlmepriv, _FW_LINKED) == true) ||
(*pold_state == Ndis802_11Infrastructure) ||
(*pold_state == Ndis802_11IBSS)) {
/* will clr Linked_state before this function,
* we must have chked whether issue dis-assoc_cmd or
* not */
r8712_ind_disconnect(padapter);
}
*pold_state = networktype;
/* clear WIFI_STATION_STATE; WIFI_AP_STATE; WIFI_ADHOC_STATE;
* WIFI_ADHOC_MASTER_STATE */
_clr_fwstate_(pmlmepriv, WIFI_STATION_STATE | WIFI_AP_STATE |
WIFI_ADHOC_STATE | WIFI_ADHOC_MASTER_STATE |
WIFI_AP_STATE);
switch (networktype) {
case Ndis802_11IBSS:
set_fwstate(pmlmepriv, WIFI_ADHOC_STATE);
break;
case Ndis802_11Infrastructure:
set_fwstate(pmlmepriv, WIFI_STATION_STATE);
break;
case Ndis802_11APMode:
set_fwstate(pmlmepriv, WIFI_AP_STATE);
break;
case Ndis802_11AutoUnknown:
case Ndis802_11InfrastructureMax:
break;
}
spin_unlock_irqrestore(&pmlmepriv->lock, irqL);
}
}
u8 r8712_set_802_11_disassociate(struct _adapter *padapter)
{
unsigned long irqL;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
spin_lock_irqsave(&pmlmepriv->lock, irqL);
if (check_fwstate(pmlmepriv, _FW_LINKED) == true) {
r8712_disassoc_cmd(padapter);
r8712_ind_disconnect(padapter);
r8712_free_assoc_resources(padapter);
}
spin_unlock_irqrestore(&pmlmepriv->lock, irqL);
return true;
}
u8 r8712_set_802_11_bssid_list_scan(struct _adapter *padapter)
{
struct mlme_priv *pmlmepriv = NULL;
unsigned long irqL;
u8 ret = true;
if (padapter == NULL)
return false;
pmlmepriv = &padapter->mlmepriv;
if (padapter->hw_init_completed == false)
return false;
spin_lock_irqsave(&pmlmepriv->lock, irqL);
if ((check_fwstate(pmlmepriv, _FW_UNDER_SURVEY|_FW_UNDER_LINKING)) ||
(pmlmepriv->sitesurveyctrl.traffic_busy == true)) {
/* Scan or linking is in progress, do nothing. */
ret = (u8)check_fwstate(pmlmepriv, _FW_UNDER_SURVEY);
} else {
r8712_free_network_queue(padapter);
ret = r8712_sitesurvey_cmd(padapter, NULL);
}
spin_unlock_irqrestore(&pmlmepriv->lock, irqL);
return ret;
}
u8 r8712_set_802_11_authentication_mode(struct _adapter *padapter,
enum NDIS_802_11_AUTHENTICATION_MODE authmode)
{
struct security_priv *psecuritypriv = &padapter->securitypriv;
u8 ret;
psecuritypriv->ndisauthtype = authmode;
if (psecuritypriv->ndisauthtype > 3)
psecuritypriv->AuthAlgrthm = 2; /* 802.1x */
if (r8712_set_auth(padapter, psecuritypriv) == _SUCCESS)
ret = true;
else
ret = false;
return ret;
}
u8 r8712_set_802_11_add_wep(struct _adapter *padapter,
struct NDIS_802_11_WEP *wep)
{
u8 bdefaultkey;
u8 btransmitkey;
sint keyid;
struct security_priv *psecuritypriv = &padapter->securitypriv;
bdefaultkey = (wep->KeyIndex & 0x40000000) > 0 ? false : true;
btransmitkey = (wep->KeyIndex & 0x80000000) > 0 ? true : false;
keyid = wep->KeyIndex & 0x3fffffff;
if (keyid >= WEP_KEYS)
return false;
switch (wep->KeyLength) {
case 5:
psecuritypriv->PrivacyAlgrthm = _WEP40_;
break;
case 13:
psecuritypriv->PrivacyAlgrthm = _WEP104_;
break;
default:
psecuritypriv->PrivacyAlgrthm = _NO_PRIVACY_;
break;
}
memcpy(psecuritypriv->DefKey[keyid].skey, &wep->KeyMaterial,
wep->KeyLength);
psecuritypriv->DefKeylen[keyid] = wep->KeyLength;
psecuritypriv->PrivacyKeyIndex = keyid;
if (r8712_set_key(padapter, psecuritypriv, keyid) == _FAIL)
return false;
return _SUCCESS;
}
| gpl-2.0 |
DJHasis/Kernel-msm8930-common | drivers/block/swim.c | 5071 | 20431 | /*
* Driver for SWIM (Sander Woz Integrated Machine) floppy controller
*
* Copyright (C) 2004,2008 Laurent Vivier <Laurent@lvivier.info>
*
* based on Alastair Bridgewater SWIM analysis, 2001
* based on SWIM3 driver (c) Paul Mackerras, 1996
* based on netBSD IWM driver (c) 1997, 1998 Hauke Fath.
*
* 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.
*
* 2004-08-21 (lv) - Initial implementation
* 2008-10-30 (lv) - Port to 2.6
*/
#include <linux/module.h>
#include <linux/fd.h>
#include <linux/slab.h>
#include <linux/blkdev.h>
#include <linux/mutex.h>
#include <linux/hdreg.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <asm/mac_via.h>
#define CARDNAME "swim"
struct sector_header {
unsigned char side;
unsigned char track;
unsigned char sector;
unsigned char size;
unsigned char crc0;
unsigned char crc1;
} __attribute__((packed));
#define DRIVER_VERSION "Version 0.2 (2008-10-30)"
#define REG(x) unsigned char x, x ## _pad[0x200 - 1];
struct swim {
REG(write_data)
REG(write_mark)
REG(write_CRC)
REG(write_parameter)
REG(write_phase)
REG(write_setup)
REG(write_mode0)
REG(write_mode1)
REG(read_data)
REG(read_mark)
REG(read_error)
REG(read_parameter)
REG(read_phase)
REG(read_setup)
REG(read_status)
REG(read_handshake)
} __attribute__((packed));
#define swim_write(base, reg, v) out_8(&(base)->write_##reg, (v))
#define swim_read(base, reg) in_8(&(base)->read_##reg)
/* IWM registers */
struct iwm {
REG(ph0L)
REG(ph0H)
REG(ph1L)
REG(ph1H)
REG(ph2L)
REG(ph2H)
REG(ph3L)
REG(ph3H)
REG(mtrOff)
REG(mtrOn)
REG(intDrive)
REG(extDrive)
REG(q6L)
REG(q6H)
REG(q7L)
REG(q7H)
} __attribute__((packed));
#define iwm_write(base, reg, v) out_8(&(base)->reg, (v))
#define iwm_read(base, reg) in_8(&(base)->reg)
/* bits in phase register */
#define SEEK_POSITIVE 0x070
#define SEEK_NEGATIVE 0x074
#define STEP 0x071
#define MOTOR_ON 0x072
#define MOTOR_OFF 0x076
#define INDEX 0x073
#define EJECT 0x077
#define SETMFM 0x171
#define SETGCR 0x175
#define RELAX 0x033
#define LSTRB 0x008
#define CA_MASK 0x077
/* Select values for swim_select and swim_readbit */
#define READ_DATA_0 0x074
#define TWOMEG_DRIVE 0x075
#define SINGLE_SIDED 0x076
#define DRIVE_PRESENT 0x077
#define DISK_IN 0x170
#define WRITE_PROT 0x171
#define TRACK_ZERO 0x172
#define TACHO 0x173
#define READ_DATA_1 0x174
#define MFM_MODE 0x175
#define SEEK_COMPLETE 0x176
#define ONEMEG_MEDIA 0x177
/* Bits in handshake register */
#define MARK_BYTE 0x01
#define CRC_ZERO 0x02
#define RDDATA 0x04
#define SENSE 0x08
#define MOTEN 0x10
#define ERROR 0x20
#define DAT2BYTE 0x40
#define DAT1BYTE 0x80
/* bits in setup register */
#define S_INV_WDATA 0x01
#define S_3_5_SELECT 0x02
#define S_GCR 0x04
#define S_FCLK_DIV2 0x08
#define S_ERROR_CORR 0x10
#define S_IBM_DRIVE 0x20
#define S_GCR_WRITE 0x40
#define S_TIMEOUT 0x80
/* bits in mode register */
#define CLFIFO 0x01
#define ENBL1 0x02
#define ENBL2 0x04
#define ACTION 0x08
#define WRITE_MODE 0x10
#define HEDSEL 0x20
#define MOTON 0x80
/*----------------------------------------------------------------------------*/
enum drive_location {
INTERNAL_DRIVE = 0x02,
EXTERNAL_DRIVE = 0x04,
};
enum media_type {
DD_MEDIA,
HD_MEDIA,
};
struct floppy_state {
/* physical properties */
enum drive_location location; /* internal or external drive */
int head_number; /* single- or double-sided drive */
/* media */
int disk_in;
int ejected;
enum media_type type;
int write_protected;
int total_secs;
int secpercyl;
int secpertrack;
/* in-use information */
int track;
int ref_count;
struct gendisk *disk;
/* parent controller */
struct swim_priv *swd;
};
enum motor_action {
OFF,
ON,
};
enum head {
LOWER_HEAD = 0,
UPPER_HEAD = 1,
};
#define FD_MAX_UNIT 2
struct swim_priv {
struct swim __iomem *base;
spinlock_t lock;
struct request_queue *queue;
int floppy_count;
struct floppy_state unit[FD_MAX_UNIT];
};
extern int swim_read_sector_header(struct swim __iomem *base,
struct sector_header *header);
extern int swim_read_sector_data(struct swim __iomem *base,
unsigned char *data);
static DEFINE_MUTEX(swim_mutex);
static inline void set_swim_mode(struct swim __iomem *base, int enable)
{
struct iwm __iomem *iwm_base;
unsigned long flags;
if (!enable) {
swim_write(base, mode0, 0xf8);
return;
}
iwm_base = (struct iwm __iomem *)base;
local_irq_save(flags);
iwm_read(iwm_base, q7L);
iwm_read(iwm_base, mtrOff);
iwm_read(iwm_base, q6H);
iwm_write(iwm_base, q7H, 0x57);
iwm_write(iwm_base, q7H, 0x17);
iwm_write(iwm_base, q7H, 0x57);
iwm_write(iwm_base, q7H, 0x57);
local_irq_restore(flags);
}
static inline int get_swim_mode(struct swim __iomem *base)
{
unsigned long flags;
local_irq_save(flags);
swim_write(base, phase, 0xf5);
if (swim_read(base, phase) != 0xf5)
goto is_iwm;
swim_write(base, phase, 0xf6);
if (swim_read(base, phase) != 0xf6)
goto is_iwm;
swim_write(base, phase, 0xf7);
if (swim_read(base, phase) != 0xf7)
goto is_iwm;
local_irq_restore(flags);
return 1;
is_iwm:
local_irq_restore(flags);
return 0;
}
static inline void swim_select(struct swim __iomem *base, int sel)
{
swim_write(base, phase, RELAX);
via1_set_head(sel & 0x100);
swim_write(base, phase, sel & CA_MASK);
}
static inline void swim_action(struct swim __iomem *base, int action)
{
unsigned long flags;
local_irq_save(flags);
swim_select(base, action);
udelay(1);
swim_write(base, phase, (LSTRB<<4) | LSTRB);
udelay(1);
swim_write(base, phase, (LSTRB<<4) | ((~LSTRB) & 0x0F));
udelay(1);
local_irq_restore(flags);
}
static inline int swim_readbit(struct swim __iomem *base, int bit)
{
int stat;
swim_select(base, bit);
udelay(10);
stat = swim_read(base, handshake);
return (stat & SENSE) == 0;
}
static inline void swim_drive(struct swim __iomem *base,
enum drive_location location)
{
if (location == INTERNAL_DRIVE) {
swim_write(base, mode0, EXTERNAL_DRIVE); /* clear drive 1 bit */
swim_write(base, mode1, INTERNAL_DRIVE); /* set drive 0 bit */
} else if (location == EXTERNAL_DRIVE) {
swim_write(base, mode0, INTERNAL_DRIVE); /* clear drive 0 bit */
swim_write(base, mode1, EXTERNAL_DRIVE); /* set drive 1 bit */
}
}
static inline void swim_motor(struct swim __iomem *base,
enum motor_action action)
{
if (action == ON) {
int i;
swim_action(base, MOTOR_ON);
for (i = 0; i < 2*HZ; i++) {
swim_select(base, RELAX);
if (swim_readbit(base, MOTOR_ON))
break;
current->state = TASK_INTERRUPTIBLE;
schedule_timeout(1);
}
} else if (action == OFF) {
swim_action(base, MOTOR_OFF);
swim_select(base, RELAX);
}
}
static inline void swim_eject(struct swim __iomem *base)
{
int i;
swim_action(base, EJECT);
for (i = 0; i < 2*HZ; i++) {
swim_select(base, RELAX);
if (!swim_readbit(base, DISK_IN))
break;
current->state = TASK_INTERRUPTIBLE;
schedule_timeout(1);
}
swim_select(base, RELAX);
}
static inline void swim_head(struct swim __iomem *base, enum head head)
{
/* wait drive is ready */
if (head == UPPER_HEAD)
swim_select(base, READ_DATA_1);
else if (head == LOWER_HEAD)
swim_select(base, READ_DATA_0);
}
static inline int swim_step(struct swim __iomem *base)
{
int wait;
swim_action(base, STEP);
for (wait = 0; wait < HZ; wait++) {
current->state = TASK_INTERRUPTIBLE;
schedule_timeout(1);
swim_select(base, RELAX);
if (!swim_readbit(base, STEP))
return 0;
}
return -1;
}
static inline int swim_track00(struct swim __iomem *base)
{
int try;
swim_action(base, SEEK_NEGATIVE);
for (try = 0; try < 100; try++) {
swim_select(base, RELAX);
if (swim_readbit(base, TRACK_ZERO))
break;
if (swim_step(base))
return -1;
}
if (swim_readbit(base, TRACK_ZERO))
return 0;
return -1;
}
static inline int swim_seek(struct swim __iomem *base, int step)
{
if (step == 0)
return 0;
if (step < 0) {
swim_action(base, SEEK_NEGATIVE);
step = -step;
} else
swim_action(base, SEEK_POSITIVE);
for ( ; step > 0; step--) {
if (swim_step(base))
return -1;
}
return 0;
}
static inline int swim_track(struct floppy_state *fs, int track)
{
struct swim __iomem *base = fs->swd->base;
int ret;
ret = swim_seek(base, track - fs->track);
if (ret == 0)
fs->track = track;
else {
swim_track00(base);
fs->track = 0;
}
return ret;
}
static int floppy_eject(struct floppy_state *fs)
{
struct swim __iomem *base = fs->swd->base;
swim_drive(base, fs->location);
swim_motor(base, OFF);
swim_eject(base);
fs->disk_in = 0;
fs->ejected = 1;
return 0;
}
static inline int swim_read_sector(struct floppy_state *fs,
int side, int track,
int sector, unsigned char *buffer)
{
struct swim __iomem *base = fs->swd->base;
unsigned long flags;
struct sector_header header;
int ret = -1;
short i;
swim_track(fs, track);
swim_write(base, mode1, MOTON);
swim_head(base, side);
swim_write(base, mode0, side);
local_irq_save(flags);
for (i = 0; i < 36; i++) {
ret = swim_read_sector_header(base, &header);
if (!ret && (header.sector == sector)) {
/* found */
ret = swim_read_sector_data(base, buffer);
break;
}
}
local_irq_restore(flags);
swim_write(base, mode0, MOTON);
if ((header.side != side) || (header.track != track) ||
(header.sector != sector))
return 0;
return ret;
}
static int floppy_read_sectors(struct floppy_state *fs,
int req_sector, int sectors_nb,
unsigned char *buffer)
{
struct swim __iomem *base = fs->swd->base;
int ret;
int side, track, sector;
int i, try;
swim_drive(base, fs->location);
for (i = req_sector; i < req_sector + sectors_nb; i++) {
int x;
track = i / fs->secpercyl;
x = i % fs->secpercyl;
side = x / fs->secpertrack;
sector = x % fs->secpertrack + 1;
try = 5;
do {
ret = swim_read_sector(fs, side, track, sector,
buffer);
if (try-- == 0)
return -EIO;
} while (ret != 512);
buffer += ret;
}
return 0;
}
static void redo_fd_request(struct request_queue *q)
{
struct request *req;
struct floppy_state *fs;
req = blk_fetch_request(q);
while (req) {
int err = -EIO;
fs = req->rq_disk->private_data;
if (blk_rq_pos(req) >= fs->total_secs)
goto done;
if (!fs->disk_in)
goto done;
if (rq_data_dir(req) == WRITE && fs->write_protected)
goto done;
switch (rq_data_dir(req)) {
case WRITE:
/* NOT IMPLEMENTED */
break;
case READ:
err = floppy_read_sectors(fs, blk_rq_pos(req),
blk_rq_cur_sectors(req),
req->buffer);
break;
}
done:
if (!__blk_end_request_cur(req, err))
req = blk_fetch_request(q);
}
}
static void do_fd_request(struct request_queue *q)
{
redo_fd_request(q);
}
static struct floppy_struct floppy_type[4] = {
{ 0, 0, 0, 0, 0, 0x00, 0x00, 0x00, 0x00, NULL }, /* no testing */
{ 720, 9, 1, 80, 0, 0x2A, 0x02, 0xDF, 0x50, NULL }, /* 360KB SS 3.5"*/
{ 1440, 9, 2, 80, 0, 0x2A, 0x02, 0xDF, 0x50, NULL }, /* 720KB 3.5" */
{ 2880, 18, 2, 80, 0, 0x1B, 0x00, 0xCF, 0x6C, NULL }, /* 1.44MB 3.5" */
};
static int get_floppy_geometry(struct floppy_state *fs, int type,
struct floppy_struct **g)
{
if (type >= ARRAY_SIZE(floppy_type))
return -EINVAL;
if (type)
*g = &floppy_type[type];
else if (fs->type == HD_MEDIA) /* High-Density media */
*g = &floppy_type[3];
else if (fs->head_number == 2) /* double-sided */
*g = &floppy_type[2];
else
*g = &floppy_type[1];
return 0;
}
static void setup_medium(struct floppy_state *fs)
{
struct swim __iomem *base = fs->swd->base;
if (swim_readbit(base, DISK_IN)) {
struct floppy_struct *g;
fs->disk_in = 1;
fs->write_protected = swim_readbit(base, WRITE_PROT);
fs->type = swim_readbit(base, ONEMEG_MEDIA);
if (swim_track00(base))
printk(KERN_ERR
"SWIM: cannot move floppy head to track 0\n");
swim_track00(base);
get_floppy_geometry(fs, 0, &g);
fs->total_secs = g->size;
fs->secpercyl = g->head * g->sect;
fs->secpertrack = g->sect;
fs->track = 0;
} else {
fs->disk_in = 0;
}
}
static int floppy_open(struct block_device *bdev, fmode_t mode)
{
struct floppy_state *fs = bdev->bd_disk->private_data;
struct swim __iomem *base = fs->swd->base;
int err;
if (fs->ref_count == -1 || (fs->ref_count && mode & FMODE_EXCL))
return -EBUSY;
if (mode & FMODE_EXCL)
fs->ref_count = -1;
else
fs->ref_count++;
swim_write(base, setup, S_IBM_DRIVE | S_FCLK_DIV2);
udelay(10);
swim_drive(base, INTERNAL_DRIVE);
swim_motor(base, ON);
swim_action(base, SETMFM);
if (fs->ejected)
setup_medium(fs);
if (!fs->disk_in) {
err = -ENXIO;
goto out;
}
if (mode & FMODE_NDELAY)
return 0;
if (mode & (FMODE_READ|FMODE_WRITE)) {
check_disk_change(bdev);
if ((mode & FMODE_WRITE) && fs->write_protected) {
err = -EROFS;
goto out;
}
}
return 0;
out:
if (fs->ref_count < 0)
fs->ref_count = 0;
else if (fs->ref_count > 0)
--fs->ref_count;
if (fs->ref_count == 0)
swim_motor(base, OFF);
return err;
}
static int floppy_unlocked_open(struct block_device *bdev, fmode_t mode)
{
int ret;
mutex_lock(&swim_mutex);
ret = floppy_open(bdev, mode);
mutex_unlock(&swim_mutex);
return ret;
}
static int floppy_release(struct gendisk *disk, fmode_t mode)
{
struct floppy_state *fs = disk->private_data;
struct swim __iomem *base = fs->swd->base;
mutex_lock(&swim_mutex);
if (fs->ref_count < 0)
fs->ref_count = 0;
else if (fs->ref_count > 0)
--fs->ref_count;
if (fs->ref_count == 0)
swim_motor(base, OFF);
mutex_unlock(&swim_mutex);
return 0;
}
static int floppy_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long param)
{
struct floppy_state *fs = bdev->bd_disk->private_data;
int err;
if ((cmd & 0x80) && !capable(CAP_SYS_ADMIN))
return -EPERM;
switch (cmd) {
case FDEJECT:
if (fs->ref_count != 1)
return -EBUSY;
mutex_lock(&swim_mutex);
err = floppy_eject(fs);
mutex_unlock(&swim_mutex);
return err;
case FDGETPRM:
if (copy_to_user((void __user *) param, (void *) &floppy_type,
sizeof(struct floppy_struct)))
return -EFAULT;
break;
default:
printk(KERN_DEBUG "SWIM floppy_ioctl: unknown cmd %d\n",
cmd);
return -ENOSYS;
}
return 0;
}
static int floppy_getgeo(struct block_device *bdev, struct hd_geometry *geo)
{
struct floppy_state *fs = bdev->bd_disk->private_data;
struct floppy_struct *g;
int ret;
ret = get_floppy_geometry(fs, 0, &g);
if (ret)
return ret;
geo->heads = g->head;
geo->sectors = g->sect;
geo->cylinders = g->track;
return 0;
}
static unsigned int floppy_check_events(struct gendisk *disk,
unsigned int clearing)
{
struct floppy_state *fs = disk->private_data;
return fs->ejected ? DISK_EVENT_MEDIA_CHANGE : 0;
}
static int floppy_revalidate(struct gendisk *disk)
{
struct floppy_state *fs = disk->private_data;
struct swim __iomem *base = fs->swd->base;
swim_drive(base, fs->location);
if (fs->ejected)
setup_medium(fs);
if (!fs->disk_in)
swim_motor(base, OFF);
else
fs->ejected = 0;
return !fs->disk_in;
}
static const struct block_device_operations floppy_fops = {
.owner = THIS_MODULE,
.open = floppy_unlocked_open,
.release = floppy_release,
.ioctl = floppy_ioctl,
.getgeo = floppy_getgeo,
.check_events = floppy_check_events,
.revalidate_disk = floppy_revalidate,
};
static struct kobject *floppy_find(dev_t dev, int *part, void *data)
{
struct swim_priv *swd = data;
int drive = (*part & 3);
if (drive > swd->floppy_count)
return NULL;
*part = 0;
return get_disk(swd->unit[drive].disk);
}
static int __devinit swim_add_floppy(struct swim_priv *swd,
enum drive_location location)
{
struct floppy_state *fs = &swd->unit[swd->floppy_count];
struct swim __iomem *base = swd->base;
fs->location = location;
swim_drive(base, location);
swim_motor(base, OFF);
if (swim_readbit(base, SINGLE_SIDED))
fs->head_number = 1;
else
fs->head_number = 2;
fs->ref_count = 0;
fs->ejected = 1;
swd->floppy_count++;
return 0;
}
static int __devinit swim_floppy_init(struct swim_priv *swd)
{
int err;
int drive;
struct swim __iomem *base = swd->base;
/* scan floppy drives */
swim_drive(base, INTERNAL_DRIVE);
if (swim_readbit(base, DRIVE_PRESENT))
swim_add_floppy(swd, INTERNAL_DRIVE);
swim_drive(base, EXTERNAL_DRIVE);
if (swim_readbit(base, DRIVE_PRESENT))
swim_add_floppy(swd, EXTERNAL_DRIVE);
/* register floppy drives */
err = register_blkdev(FLOPPY_MAJOR, "fd");
if (err) {
printk(KERN_ERR "Unable to get major %d for SWIM floppy\n",
FLOPPY_MAJOR);
return -EBUSY;
}
for (drive = 0; drive < swd->floppy_count; drive++) {
swd->unit[drive].disk = alloc_disk(1);
if (swd->unit[drive].disk == NULL) {
err = -ENOMEM;
goto exit_put_disks;
}
swd->unit[drive].swd = swd;
}
swd->queue = blk_init_queue(do_fd_request, &swd->lock);
if (!swd->queue) {
err = -ENOMEM;
goto exit_put_disks;
}
for (drive = 0; drive < swd->floppy_count; drive++) {
swd->unit[drive].disk->flags = GENHD_FL_REMOVABLE;
swd->unit[drive].disk->major = FLOPPY_MAJOR;
swd->unit[drive].disk->first_minor = drive;
sprintf(swd->unit[drive].disk->disk_name, "fd%d", drive);
swd->unit[drive].disk->fops = &floppy_fops;
swd->unit[drive].disk->private_data = &swd->unit[drive];
swd->unit[drive].disk->queue = swd->queue;
set_capacity(swd->unit[drive].disk, 2880);
add_disk(swd->unit[drive].disk);
}
blk_register_region(MKDEV(FLOPPY_MAJOR, 0), 256, THIS_MODULE,
floppy_find, NULL, swd);
return 0;
exit_put_disks:
unregister_blkdev(FLOPPY_MAJOR, "fd");
while (drive--)
put_disk(swd->unit[drive].disk);
return err;
}
static int __devinit swim_probe(struct platform_device *dev)
{
struct resource *res;
struct swim __iomem *swim_base;
struct swim_priv *swd;
int ret;
res = platform_get_resource(dev, IORESOURCE_MEM, 0);
if (!res) {
ret = -ENODEV;
goto out;
}
if (!request_mem_region(res->start, resource_size(res), CARDNAME)) {
ret = -EBUSY;
goto out;
}
swim_base = ioremap(res->start, resource_size(res));
if (!swim_base) {
return -ENOMEM;
goto out_release_io;
}
/* probe device */
set_swim_mode(swim_base, 1);
if (!get_swim_mode(swim_base)) {
printk(KERN_INFO "SWIM device not found !\n");
ret = -ENODEV;
goto out_iounmap;
}
/* set platform driver data */
swd = kzalloc(sizeof(struct swim_priv), GFP_KERNEL);
if (!swd) {
ret = -ENOMEM;
goto out_iounmap;
}
platform_set_drvdata(dev, swd);
swd->base = swim_base;
ret = swim_floppy_init(swd);
if (ret)
goto out_kfree;
return 0;
out_kfree:
platform_set_drvdata(dev, NULL);
kfree(swd);
out_iounmap:
iounmap(swim_base);
out_release_io:
release_mem_region(res->start, resource_size(res));
out:
return ret;
}
static int __devexit swim_remove(struct platform_device *dev)
{
struct swim_priv *swd = platform_get_drvdata(dev);
int drive;
struct resource *res;
blk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256);
for (drive = 0; drive < swd->floppy_count; drive++) {
del_gendisk(swd->unit[drive].disk);
put_disk(swd->unit[drive].disk);
}
unregister_blkdev(FLOPPY_MAJOR, "fd");
blk_cleanup_queue(swd->queue);
/* eject floppies */
for (drive = 0; drive < swd->floppy_count; drive++)
floppy_eject(&swd->unit[drive]);
iounmap(swd->base);
res = platform_get_resource(dev, IORESOURCE_MEM, 0);
if (res)
release_mem_region(res->start, resource_size(res));
platform_set_drvdata(dev, NULL);
kfree(swd);
return 0;
}
static struct platform_driver swim_driver = {
.probe = swim_probe,
.remove = __devexit_p(swim_remove),
.driver = {
.name = CARDNAME,
.owner = THIS_MODULE,
},
};
static int __init swim_init(void)
{
printk(KERN_INFO "SWIM floppy driver %s\n", DRIVER_VERSION);
return platform_driver_register(&swim_driver);
}
module_init(swim_init);
static void __exit swim_exit(void)
{
platform_driver_unregister(&swim_driver);
}
module_exit(swim_exit);
MODULE_DESCRIPTION("Driver for SWIM floppy controller");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Laurent Vivier <laurent@lvivier.info>");
MODULE_ALIAS_BLOCKDEV_MAJOR(FLOPPY_MAJOR);
| gpl-2.0 |
binkybear/android_kernel_samsung_exynos5410 | drivers/staging/cptm1217/clearpad_tm1217.c | 7887 | 17781 | /*
* clearpad_tm1217.c - Touch Screen driver for Synaptics Clearpad
* TM1217 controller
*
* Copyright (C) 2008 Intel Corp
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; ifnot, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*
* Questions/Comments/Bug fixes to Ramesh Agarwal (ramesh.agarwal@intel.com)
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/i2c.h>
#include <linux/timer.h>
#include <linux/gpio.h>
#include <linux/hrtimer.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include "cp_tm1217.h"
#define CPTM1217_DEVICE_NAME "cptm1217"
#define CPTM1217_DRIVER_NAME CPTM1217_DEVICE_NAME
#define MAX_TOUCH_SUPPORTED 2
#define TOUCH_SUPPORTED 1
#define SAMPLING_FREQ 80 /* Frequency in HZ */
#define DELAY_BTWIN_SAMPLE (1000 / SAMPLING_FREQ)
#define WAIT_FOR_RESPONSE 5 /* 5msec just works */
#define MAX_RETRIES 5 /* As above */
#define INCREMENTAL_DELAY 5 /* As above */
/* Regster Definitions */
#define TMA1217_DEV_STATUS 0x13 /* Device Status */
#define TMA1217_INT_STATUS 0x14 /* Interrupt Status */
/* Controller can detect up to 2 possible finger touches.
* Each finger touch provides 12 bit X Y co-ordinates, the values are split
* across 2 registers, and an 8 bit Z value */
#define TMA1217_FINGER_STATE 0x18 /* Finger State */
#define TMA1217_FINGER1_X_HIGHER8 0x19 /* Higher 8 bit of X coordinate */
#define TMA1217_FINGER1_Y_HIGHER8 0x1A /* Higher 8 bit of Y coordinate */
#define TMA1217_FINGER1_XY_LOWER4 0x1B /* Lower 4 bits of X and Y */
#define TMA1217_FINGER1_Z_VALUE 0x1D /* 8 bit Z value for finger 1 */
#define TMA1217_FINGER2_X_HIGHER8 0x1E /* Higher 8 bit of X coordinate */
#define TMA1217_FINGER2_Y_HIGHER8 0x1F /* Higher 8 bit of Y coordinate */
#define TMA1217_FINGER2_XY_LOWER4 0x20 /* Lower 4 bits of X and Y */
#define TMA1217_FINGER2_Z_VALUE 0x22 /* 8 bit Z value for finger 2 */
#define TMA1217_DEVICE_CTRL 0x23 /* Device Control */
#define TMA1217_INTERRUPT_ENABLE 0x24 /* Interrupt Enable */
#define TMA1217_REPORT_MODE 0x2B /* Reporting Mode */
#define TMA1217_MAX_X_LOWER8 0x31 /* Bit 0-7 for Max X */
#define TMA1217_MAX_X_HIGHER4 0x32 /* Bit 8-11 for Max X */
#define TMA1217_MAX_Y_LOWER8 0x33 /* Bit 0-7 for Max Y */
#define TMA1217_MAX_Y_HIGHER4 0x34 /* Bit 8-11 for Max Y */
#define TMA1217_DEVICE_CMD_RESET 0x67 /* Device CMD reg for reset */
#define TMA1217_DEVICE_CMD_REZERO 0x69 /* Device CMD reg for rezero */
#define TMA1217_MANUFACTURER_ID 0x73 /* Manufacturer Id */
#define TMA1217_PRODUCT_FAMILY 0x75 /* Product Family */
#define TMA1217_FIRMWARE_REVISION 0x76 /* Firmware Revision */
#define TMA1217_SERIAL_NO_HIGH 0x7C /* Bit 8-15 of device serial no. */
#define TMA1217_SERIAL_NO_LOW 0x7D /* Bit 0-7 of device serial no. */
#define TMA1217_PRODUCT_ID_START 0x7E /* Start address for 10 byte ID */
#define TMA1217_DEVICE_CAPABILITY 0x8B /* Reporting capability */
/*
* The touch position structure.
*/
struct touch_state {
int x;
int y;
bool button;
};
/* Device Specific info given by the controller */
struct cp_dev_info {
u16 maxX;
u16 maxY;
};
/* Vendor related info given by the controller */
struct cp_vendor_info {
u8 vendor_id;
u8 product_family;
u8 firmware_rev;
u16 serial_no;
};
/*
* Private structure to store the device details
*/
struct cp_tm1217_device {
struct i2c_client *client;
struct device *dev;
struct cp_vendor_info vinfo;
struct cp_dev_info dinfo;
struct input_dev_info {
char phys[32];
char name[128];
struct input_dev *input;
struct touch_state touch;
} cp_input_info[MAX_TOUCH_SUPPORTED];
int thread_running;
struct mutex thread_mutex;
int gpio;
};
/* The following functions are used to read/write registers on the device
* as per the RMI prorocol. Technically, a page select should be written
* before doing read/write but since the register offsets are below 0xFF
* we can use the default value of page which is 0x00
*/
static int cp_tm1217_read(struct cp_tm1217_device *ts,
u8 *req, int size)
{
int i, retval;
/* Send the address */
retval = i2c_master_send(ts->client, &req[0], 1);
if (retval != 1) {
dev_err(ts->dev, "cp_tm1217: I2C send failed\n");
return retval;
}
msleep(WAIT_FOR_RESPONSE);
for (i = 0; i < MAX_RETRIES; i++) {
retval = i2c_master_recv(ts->client, &req[1], size);
if (retval == size) {
break;
} else {
msleep(INCREMENTAL_DELAY);
dev_dbg(ts->dev, "cp_tm1217: Retry count is %d\n", i);
}
}
if (retval != size)
dev_err(ts->dev, "cp_tm1217: Read from device failed\n");
return retval;
}
static int cp_tm1217_write(struct cp_tm1217_device *ts,
u8 *req, int size)
{
int retval;
/* Send the address and the data to be written */
retval = i2c_master_send(ts->client, &req[0], size + 1);
if (retval != size + 1) {
dev_err(ts->dev, "cp_tm1217: I2C write failed: %d\n", retval);
return retval;
}
/* Wait for the write to complete. TBD why this is required */
msleep(WAIT_FOR_RESPONSE);
return size;
}
static int cp_tm1217_mask_interrupt(struct cp_tm1217_device *ts)
{
u8 req[2];
int retval;
req[0] = TMA1217_INTERRUPT_ENABLE;
req[1] = 0x0;
retval = cp_tm1217_write(ts, req, 1);
if (retval != 1)
return -EIO;
return 0;
}
static int cp_tm1217_unmask_interrupt(struct cp_tm1217_device *ts)
{
u8 req[2];
int retval;
req[0] = TMA1217_INTERRUPT_ENABLE;
req[1] = 0xa;
retval = cp_tm1217_write(ts, req, 1);
if (retval != 1)
return -EIO;
return 0;
}
static void process_touch(struct cp_tm1217_device *ts, int index)
{
int retval;
struct input_dev_info *input_info =
(struct input_dev_info *)&ts->cp_input_info[index];
u8 xy_data[6];
if (index == 0)
xy_data[0] = TMA1217_FINGER1_X_HIGHER8;
else
xy_data[0] = TMA1217_FINGER2_X_HIGHER8;
retval = cp_tm1217_read(ts, xy_data, 5);
if (retval < 5) {
dev_err(ts->dev, "cp_tm1217: XY read from device failed\n");
return;
}
/* Note: Currently not using the Z values but may be requried in
the future. */
input_info->touch.x = (xy_data[1] << 4)
| (xy_data[3] & 0x0F);
input_info->touch.y = (xy_data[2] << 4)
| ((xy_data[3] & 0xF0) >> 4);
input_report_abs(input_info->input, ABS_X, input_info->touch.x);
input_report_abs(input_info->input, ABS_Y, input_info->touch.y);
input_sync(input_info->input);
}
static void cp_tm1217_get_data(struct cp_tm1217_device *ts)
{
u8 req[2];
int retval, i, finger_touched = 0;
do {
req[0] = TMA1217_FINGER_STATE;
retval = cp_tm1217_read(ts, req, 1);
if (retval != 1) {
dev_err(ts->dev,
"cp_tm1217: Read from device failed\n");
continue;
}
finger_touched = 0;
/* Start sampling until the pressure is below
threshold */
for (i = 0; i < TOUCH_SUPPORTED; i++) {
if (req[1] & 0x3) {
finger_touched++;
if (ts->cp_input_info[i].touch.button == 0) {
/* send the button touch event */
input_report_key(
ts->cp_input_info[i].input,
BTN_TOUCH, 1);
ts->cp_input_info[i].touch.button = 1;
}
process_touch(ts, i);
} else {
if (ts->cp_input_info[i].touch.button == 1) {
/* send the button release event */
input_report_key(
ts->cp_input_info[i].input,
BTN_TOUCH, 0);
input_sync(ts->cp_input_info[i].input);
ts->cp_input_info[i].touch.button = 0;
}
}
req[1] = req[1] >> 2;
}
msleep(DELAY_BTWIN_SAMPLE);
} while (finger_touched > 0);
}
static irqreturn_t cp_tm1217_sample_thread(int irq, void *handle)
{
struct cp_tm1217_device *ts = (struct cp_tm1217_device *) handle;
u8 req[2];
int retval;
/* Chedk if another thread is already running */
mutex_lock(&ts->thread_mutex);
if (ts->thread_running == 1) {
mutex_unlock(&ts->thread_mutex);
return IRQ_HANDLED;
} else {
ts->thread_running = 1;
mutex_unlock(&ts->thread_mutex);
}
/* Mask the interrupts */
retval = cp_tm1217_mask_interrupt(ts);
/* Read the Interrupt Status register to find the cause of the
Interrupt */
req[0] = TMA1217_INT_STATUS;
retval = cp_tm1217_read(ts, req, 1);
if (retval != 1)
goto exit_thread;
if (!(req[1] & 0x8))
goto exit_thread;
cp_tm1217_get_data(ts);
exit_thread:
/* Unmask the interrupts before going to sleep */
retval = cp_tm1217_unmask_interrupt(ts);
mutex_lock(&ts->thread_mutex);
ts->thread_running = 0;
mutex_unlock(&ts->thread_mutex);
return IRQ_HANDLED;
}
static int cp_tm1217_init_data(struct cp_tm1217_device *ts)
{
int retval;
u8 req[2];
/* Read the vendor id/ fw revision etc. Ignoring return check as this
is non critical info */
req[0] = TMA1217_MANUFACTURER_ID;
retval = cp_tm1217_read(ts, req, 1);
ts->vinfo.vendor_id = req[1];
req[0] = TMA1217_PRODUCT_FAMILY;
retval = cp_tm1217_read(ts, req, 1);
ts->vinfo.product_family = req[1];
req[0] = TMA1217_FIRMWARE_REVISION;
retval = cp_tm1217_read(ts, req, 1);
ts->vinfo.firmware_rev = req[1];
req[0] = TMA1217_SERIAL_NO_HIGH;
retval = cp_tm1217_read(ts, req, 1);
ts->vinfo.serial_no = (req[1] << 8);
req[0] = TMA1217_SERIAL_NO_LOW;
retval = cp_tm1217_read(ts, req, 1);
ts->vinfo.serial_no = ts->vinfo.serial_no | req[1];
req[0] = TMA1217_MAX_X_HIGHER4;
retval = cp_tm1217_read(ts, req, 1);
ts->dinfo.maxX = (req[1] & 0xF) << 8;
req[0] = TMA1217_MAX_X_LOWER8;
retval = cp_tm1217_read(ts, req, 1);
ts->dinfo.maxX = ts->dinfo.maxX | req[1];
req[0] = TMA1217_MAX_Y_HIGHER4;
retval = cp_tm1217_read(ts, req, 1);
ts->dinfo.maxY = (req[1] & 0xF) << 8;
req[0] = TMA1217_MAX_Y_LOWER8;
retval = cp_tm1217_read(ts, req, 1);
ts->dinfo.maxY = ts->dinfo.maxY | req[1];
return 0;
}
/*
* Set up a GPIO for use as the interrupt. We can't simply do this at
* boot time because the GPIO drivers themselves may not be around at
* boot/firmware set up time to do the work. Instead defer it to driver
* detection.
*/
static int cp_tm1217_setup_gpio_irq(struct cp_tm1217_device *ts)
{
int retval;
/* Hook up the irq handler */
retval = gpio_request(ts->gpio, "cp_tm1217_touch");
if (retval < 0) {
dev_err(ts->dev, "cp_tm1217: GPIO request failed error %d\n",
retval);
return retval;
}
retval = gpio_direction_input(ts->gpio);
if (retval < 0) {
dev_err(ts->dev,
"cp_tm1217: GPIO direction configuration failed, error %d\n",
retval);
gpio_free(ts->gpio);
return retval;
}
retval = gpio_to_irq(ts->gpio);
if (retval < 0) {
dev_err(ts->dev, "cp_tm1217: GPIO to IRQ failedi,"
" error %d\n", retval);
gpio_free(ts->gpio);
}
dev_dbg(ts->dev,
"cp_tm1217: Got IRQ number is %d for GPIO %d\n",
retval, ts->gpio);
return retval;
}
static int cp_tm1217_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct cp_tm1217_device *ts;
struct input_dev *input_dev;
struct input_dev_info *input_info;
struct cp_tm1217_platform_data *pdata;
u8 req[2];
int i, retval;
/* No pdata is fine - we then use "normal" IRQ mode */
pdata = client->dev.platform_data;
ts = kzalloc(sizeof(struct cp_tm1217_device), GFP_KERNEL);
if (!ts) {
dev_err(&client->dev,
"cp_tm1217: Private Device Struct alloc failed\n");
return -ENOMEM;
}
ts->client = client;
ts->dev = &client->dev;
i2c_set_clientdata(client, ts);
ts->thread_running = 0;
mutex_init(&ts->thread_mutex);
/* Reset the Controller */
req[0] = TMA1217_DEVICE_CMD_RESET;
req[1] = 0x1;
retval = cp_tm1217_write(ts, req, 1);
if (retval != 1) {
dev_err(ts->dev, "cp_tm1217: Controller reset failed\n");
kfree(ts);
return -EIO;
}
/* Clear up the interrupt status from reset. */
req[0] = TMA1217_INT_STATUS;
retval = cp_tm1217_read(ts, req, 1);
/* Mask all the interrupts */
retval = cp_tm1217_mask_interrupt(ts);
/* Read the controller information */
cp_tm1217_init_data(ts);
/* The following code will register multiple event devices when
multi-pointer is enabled, the code has not been tested
with MPX */
for (i = 0; i < TOUCH_SUPPORTED; i++) {
input_dev = input_allocate_device();
if (input_dev == NULL) {
dev_err(ts->dev,
"cp_tm1217:Input Device Struct alloc failed\n");
retval = -ENOMEM;
goto fail;
}
input_info = &ts->cp_input_info[i];
snprintf(input_info->name, sizeof(input_info->name),
"cp_tm1217_touchscreen_%d", i);
input_dev->name = input_info->name;
snprintf(input_info->phys, sizeof(input_info->phys),
"%s/input%d", dev_name(&client->dev), i);
input_dev->phys = input_info->phys;
input_dev->id.bustype = BUS_I2C;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
input_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH);
input_set_abs_params(input_dev, ABS_X, 0, ts->dinfo.maxX, 0, 0);
input_set_abs_params(input_dev, ABS_Y, 0, ts->dinfo.maxY, 0, 0);
retval = input_register_device(input_dev);
if (retval) {
dev_err(ts->dev,
"Input dev registration failed for %s\n",
input_dev->name);
input_free_device(input_dev);
goto fail;
}
input_info->input = input_dev;
}
/* Setup the reporting mode to send an interrupt only when
finger arrives or departs. */
req[0] = TMA1217_REPORT_MODE;
req[1] = 0x02;
retval = cp_tm1217_write(ts, req, 1);
/* Setup the device to no sleep mode for now and make it configured */
req[0] = TMA1217_DEVICE_CTRL;
req[1] = 0x84;
retval = cp_tm1217_write(ts, req, 1);
/* Check for the status of the device */
req[0] = TMA1217_DEV_STATUS;
retval = cp_tm1217_read(ts, req, 1);
if (req[1] != 0) {
dev_err(ts->dev,
"cp_tm1217: Device Status 0x%x != 0: config failed\n",
req[1]);
retval = -EIO;
goto fail;
}
if (pdata && pdata->gpio) {
ts->gpio = pdata->gpio;
retval = cp_tm1217_setup_gpio_irq(ts);
} else
retval = client->irq;
if (retval < 0) {
dev_err(ts->dev, "cp_tm1217: GPIO request failed error %d\n",
retval);
goto fail;
}
client->irq = retval;
retval = request_threaded_irq(client->irq,
NULL, cp_tm1217_sample_thread,
IRQF_TRIGGER_FALLING, "cp_tm1217_touch", ts);
if (retval < 0) {
dev_err(ts->dev, "cp_tm1217: Request IRQ error %d\n", retval);
goto fail_gpio;
}
/* Unmask the interrupts */
retval = cp_tm1217_unmask_interrupt(ts);
if (retval == 0)
return 0;
free_irq(client->irq, ts);
fail_gpio:
if (ts->gpio)
gpio_free(ts->gpio);
fail:
/* Clean up before returning failure */
for (i = 0; i < TOUCH_SUPPORTED; i++) {
if (ts->cp_input_info[i].input) {
input_unregister_device(ts->cp_input_info[i].input);
input_free_device(ts->cp_input_info[i].input);
}
}
kfree(ts);
return retval;
}
/*
* cp_tm1217 suspend
*
*/
static int cp_tm1217_suspend(struct i2c_client *client, pm_message_t mesg)
{
struct cp_tm1217_device *ts = i2c_get_clientdata(client);
u8 req[2];
int retval;
/* Put the controller to sleep */
req[0] = TMA1217_DEVICE_CTRL;
retval = cp_tm1217_read(ts, req, 1);
req[1] = (req[1] & 0xF8) | 0x1;
retval = cp_tm1217_write(ts, req, 1);
if (device_may_wakeup(&client->dev))
enable_irq_wake(client->irq);
return 0;
}
/*
* cp_tm1217_resume
*
*/
static int cp_tm1217_resume(struct i2c_client *client)
{
struct cp_tm1217_device *ts = i2c_get_clientdata(client);
u8 req[2];
int retval;
/* Take the controller out of sleep */
req[0] = TMA1217_DEVICE_CTRL;
retval = cp_tm1217_read(ts, req, 1);
req[1] = (req[1] & 0xF8) | 0x4;
retval = cp_tm1217_write(ts, req, 1);
/* Restore the register settings sinc the power to the
could have been cut off */
/* Setup the reporting mode to send an interrupt only when
finger arrives or departs. */
req[0] = TMA1217_REPORT_MODE;
req[1] = 0x02;
retval = cp_tm1217_write(ts, req, 1);
/* Setup the device to no sleep mode for now and make it configured */
req[0] = TMA1217_DEVICE_CTRL;
req[1] = 0x84;
retval = cp_tm1217_write(ts, req, 1);
/* Setup the interrupt mask */
retval = cp_tm1217_unmask_interrupt(ts);
if (device_may_wakeup(&client->dev))
disable_irq_wake(client->irq);
return 0;
}
/*
* cp_tm1217_remove
*
*/
static int cp_tm1217_remove(struct i2c_client *client)
{
struct cp_tm1217_device *ts = i2c_get_clientdata(client);
int i;
free_irq(client->irq, ts);
if (ts->gpio)
gpio_free(ts->gpio);
for (i = 0; i < TOUCH_SUPPORTED; i++)
input_unregister_device(ts->cp_input_info[i].input);
kfree(ts);
return 0;
}
static struct i2c_device_id cp_tm1217_idtable[] = {
{ CPTM1217_DEVICE_NAME, 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, cp_tm1217_idtable);
static struct i2c_driver cp_tm1217_driver = {
.driver = {
.owner = THIS_MODULE,
.name = CPTM1217_DRIVER_NAME,
},
.id_table = cp_tm1217_idtable,
.probe = cp_tm1217_probe,
.remove = cp_tm1217_remove,
.suspend = cp_tm1217_suspend,
.resume = cp_tm1217_resume,
};
static int __init clearpad_tm1217_init(void)
{
return i2c_add_driver(&cp_tm1217_driver);
}
static void __exit clearpad_tm1217_exit(void)
{
i2c_del_driver(&cp_tm1217_driver);
}
module_init(clearpad_tm1217_init);
module_exit(clearpad_tm1217_exit);
MODULE_AUTHOR("Ramesh Agarwal <ramesh.agarwal@intel.com>");
MODULE_DESCRIPTION("Synaptics TM1217 TouchScreen Driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
superatmos/android_kernel_samsung_t1 | fs/xfs/xfs_trans_extfree.c | 8143 | 3614 | /*
* Copyright (c) 2000,2005 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_types.h"
#include "xfs_log.h"
#include "xfs_inum.h"
#include "xfs_trans.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_mount.h"
#include "xfs_trans_priv.h"
#include "xfs_extfree_item.h"
/*
* This routine is called to allocate an "extent free intention"
* log item that will hold nextents worth of extents. The
* caller must use all nextents extents, because we are not
* flexible about this at all.
*/
xfs_efi_log_item_t *
xfs_trans_get_efi(xfs_trans_t *tp,
uint nextents)
{
xfs_efi_log_item_t *efip;
ASSERT(tp != NULL);
ASSERT(nextents > 0);
efip = xfs_efi_init(tp->t_mountp, nextents);
ASSERT(efip != NULL);
/*
* Get a log_item_desc to point at the new item.
*/
xfs_trans_add_item(tp, &efip->efi_item);
return efip;
}
/*
* This routine is called to indicate that the described
* extent is to be logged as needing to be freed. It should
* be called once for each extent to be freed.
*/
void
xfs_trans_log_efi_extent(xfs_trans_t *tp,
xfs_efi_log_item_t *efip,
xfs_fsblock_t start_block,
xfs_extlen_t ext_len)
{
uint next_extent;
xfs_extent_t *extp;
tp->t_flags |= XFS_TRANS_DIRTY;
efip->efi_item.li_desc->lid_flags |= XFS_LID_DIRTY;
/*
* atomic_inc_return gives us the value after the increment;
* we want to use it as an array index so we need to subtract 1 from
* it.
*/
next_extent = atomic_inc_return(&efip->efi_next_extent) - 1;
ASSERT(next_extent < efip->efi_format.efi_nextents);
extp = &(efip->efi_format.efi_extents[next_extent]);
extp->ext_start = start_block;
extp->ext_len = ext_len;
}
/*
* This routine is called to allocate an "extent free done"
* log item that will hold nextents worth of extents. The
* caller must use all nextents extents, because we are not
* flexible about this at all.
*/
xfs_efd_log_item_t *
xfs_trans_get_efd(xfs_trans_t *tp,
xfs_efi_log_item_t *efip,
uint nextents)
{
xfs_efd_log_item_t *efdp;
ASSERT(tp != NULL);
ASSERT(nextents > 0);
efdp = xfs_efd_init(tp->t_mountp, efip, nextents);
ASSERT(efdp != NULL);
/*
* Get a log_item_desc to point at the new item.
*/
xfs_trans_add_item(tp, &efdp->efd_item);
return efdp;
}
/*
* This routine is called to indicate that the described
* extent is to be logged as having been freed. It should
* be called once for each extent freed.
*/
void
xfs_trans_log_efd_extent(xfs_trans_t *tp,
xfs_efd_log_item_t *efdp,
xfs_fsblock_t start_block,
xfs_extlen_t ext_len)
{
uint next_extent;
xfs_extent_t *extp;
tp->t_flags |= XFS_TRANS_DIRTY;
efdp->efd_item.li_desc->lid_flags |= XFS_LID_DIRTY;
next_extent = efdp->efd_next_extent;
ASSERT(next_extent < efdp->efd_format.efd_nextents);
extp = &(efdp->efd_format.efd_extents[next_extent]);
extp->ext_start = start_block;
extp->ext_len = ext_len;
efdp->efd_next_extent++;
}
| gpl-2.0 |
KanoComputing/raspberrypi-linux | sound/pci/asihpi/hpidebug.c | 9679 | 1946 | /************************************************************************
AudioScience HPI driver
Copyright (C) 1997-2011 AudioScience Inc. <support@audioscience.com>
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Debug macro translation.
************************************************************************/
#include "hpi_internal.h"
#include "hpidebug.h"
/* Debug level; 0 quiet; 1 informative, 2 debug, 3 verbose debug. */
int hpi_debug_level = HPI_DEBUG_LEVEL_DEFAULT;
void hpi_debug_init(void)
{
printk(KERN_INFO "debug start\n");
}
int hpi_debug_level_set(int level)
{
int old_level;
old_level = hpi_debug_level;
hpi_debug_level = level;
return old_level;
}
int hpi_debug_level_get(void)
{
return hpi_debug_level;
}
void hpi_debug_message(struct hpi_message *phm, char *sz_fileline)
{
if (phm) {
printk(KERN_DEBUG "HPI_MSG%d,%d,%d,%d,%d\n", phm->version,
phm->adapter_index, phm->obj_index, phm->function,
phm->u.c.attribute);
}
}
void hpi_debug_data(u16 *pdata, u32 len)
{
u32 i;
int j;
int k;
int lines;
int cols = 8;
lines = (len + cols - 1) / cols;
if (lines > 8)
lines = 8;
for (i = 0, j = 0; j < lines; j++) {
printk(KERN_DEBUG "%p:", (pdata + i));
for (k = 0; k < cols && i < len; i++, k++)
printk("%s%04x", k == 0 ? "" : " ", pdata[i]);
printk("\n");
}
}
| gpl-2.0 |
Alucard24/SGS4-SAMMY-Kernel | fs/proc/loadavg.c | 11983 | 1141 | #include <linux/fs.h>
#include <linux/init.h>
#include <linux/pid_namespace.h>
#include <linux/proc_fs.h>
#include <linux/sched.h>
#include <linux/seq_file.h>
#include <linux/seqlock.h>
#include <linux/time.h>
#define LOAD_INT(x) ((x) >> FSHIFT)
#define LOAD_FRAC(x) LOAD_INT(((x) & (FIXED_1-1)) * 100)
static int loadavg_proc_show(struct seq_file *m, void *v)
{
unsigned long avnrun[3];
get_avenrun(avnrun, FIXED_1/200, 0);
seq_printf(m, "%lu.%02lu %lu.%02lu %lu.%02lu %ld/%d %d\n",
LOAD_INT(avnrun[0]), LOAD_FRAC(avnrun[0]),
LOAD_INT(avnrun[1]), LOAD_FRAC(avnrun[1]),
LOAD_INT(avnrun[2]), LOAD_FRAC(avnrun[2]),
nr_running(), nr_threads,
task_active_pid_ns(current)->last_pid);
return 0;
}
static int loadavg_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, loadavg_proc_show, NULL);
}
static const struct file_operations loadavg_proc_fops = {
.open = loadavg_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int __init proc_loadavg_init(void)
{
proc_create("loadavg", 0, NULL, &loadavg_proc_fops);
return 0;
}
module_init(proc_loadavg_init);
| gpl-2.0 |
jchuang1977/openwrt_981213 | package/libs/libiconv/src/iconv.c | 208 | 9233 | #include <iconv.h>
#include <errno.h>
#include <wchar.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <limits.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdint.h>
/* builtin charmaps */
#include "charmaps.h"
/* only 0-7 are valid as dest charset */
#define UTF_16BE 000
#define UTF_16LE 001
#define UTF_32BE 002
#define UTF_32LE 003
#define WCHAR_T 004
#define UTF_8 005
#define US_ASCII 006
#define LATIN_1 007
/* additional charsets with algorithmic conversion */
#define LATIN_9 010
#define TIS_620 011
#define JIS_0201 012
/* some programs like php need this */
int _libiconv_version = _LIBICONV_VERSION;
/* these must match the constants above */
static const unsigned char charsets[] =
"\005" "UTF-8" "\0"
"\004" "WCHAR_T" "\0"
"\000" "UTF-16BE" "\0"
"\001" "UTF-16LE" "\0"
"\002" "UTF-32BE" "\0"
"\003" "UTF-32LE" "\0"
"\006" "ASCII" "\0"
"\006" "US-ASCII" "\0"
"\007" "ISO-8859-1" "\0"
"\007" "LATIN1" "\0"
"\010" "ISO-8859-15""\0"
"\010" "LATIN9" "\0"
"\011" "ISO-8859-11""\0"
"\011" "TIS-620" "\0"
"\012" "JIS-0201" "\0"
"\377";
/* separate identifiers for sbcs/dbcs/etc map type */
#define UCS2_8BIT 000
#define UCS3_8BIT 001
#define EUC 002
#define EUC_TW 003
#define SHIFT_JIS 004
#define BIG5 005
#define GBK 006
/* FIXME: these are not implemented yet
// EUC: A1-FE A1-FE
// GBK: 81-FE 40-7E,80-FE
// Big5: A1-FE 40-7E,A1-FE
*/
static const unsigned short maplen[] = {
[UCS2_8BIT] = 4+ 2* 128,
[UCS3_8BIT] = 4+ 3* 128,
[EUC] = 4+ 2* 94*94,
[SHIFT_JIS] = 4+ 2* 94*94,
[BIG5] = 4+ 2* 94*157,
[GBK] = 4+ 2* 126*190,
[EUC_TW] = 4+ 2* 2*94*94,
};
static int find_charmap(const char *name)
{
int i;
for (i = 0; i < (sizeof(charmaps) / sizeof(charmaps[0])); i++)
if (!strcasecmp(charmaps[i].name, name))
return i;
return -1;
}
static int find_charset(const char *name)
{
const unsigned char *s;
for (s=charsets; *s<0xff && strcasecmp(s+1, name); s+=strlen(s)+1);
return *s;
}
iconv_t iconv_open(const char *to, const char *from)
{
unsigned f, t;
int m;
if ((t = find_charset(to)) > 8)
return -1;
if ((f = find_charset(from)) < 255)
return 0 | (t<<1) | (f<<8);
if ((m = find_charmap(from)) > -1)
return 1 | (t<<1) | (m<<8);
return -1;
}
int iconv_close(iconv_t cd)
{
return 0;
}
static inline wchar_t get_16(const unsigned char *s, int endian)
{
endian &= 1;
return s[endian]<<8 | s[endian^1];
}
static inline void put_16(unsigned char *s, wchar_t c, int endian)
{
endian &= 1;
s[endian] = c>>8;
s[endian^1] = c;
}
static inline int utf8enc_wchar(char *outb, wchar_t c)
{
if (c <= 0x7F) {
*outb = c;
return 1;
}
else if (c <= 0x7FF) {
*outb++ = ((c >> 6) & 0x1F) | 0xC0;
*outb++ = ( c & 0x3F) | 0x80;
return 2;
}
else if (c <= 0xFFFF) {
*outb++ = ((c >> 12) & 0x0F) | 0xE0;
*outb++ = ((c >> 6) & 0x3F) | 0x80;
*outb++ = ( c & 0x3F) | 0x80;
return 3;
}
else if (c <= 0x10FFFF) {
*outb++ = ((c >> 18) & 0x07) | 0xF0;
*outb++ = ((c >> 12) & 0x3F) | 0x80;
*outb++ = ((c >> 6) & 0x3F) | 0x80;
*outb++ = ( c & 0x3F) | 0x80;
return 4;
}
else {
*outb++ = '?';
return 1;
}
}
static inline int utf8seq_is_overlong(char *s, int n)
{
switch (n)
{
case 2:
/* 1100000x (10xxxxxx) */
return (((*s >> 1) == 0x60) &&
((*(s+1) >> 6) == 0x02));
case 3:
/* 11100000 100xxxxx (10xxxxxx) */
return ((*s == 0xE0) &&
((*(s+1) >> 5) == 0x04) &&
((*(s+2) >> 6) == 0x02));
case 4:
/* 11110000 1000xxxx (10xxxxxx 10xxxxxx) */
return ((*s == 0xF0) &&
((*(s+1) >> 4) == 0x08) &&
((*(s+2) >> 6) == 0x02) &&
((*(s+3) >> 6) == 0x02));
}
return 0;
}
static inline int utf8seq_is_surrogate(char *s, int n)
{
return ((n == 3) && (*s == 0xED) && (*(s+1) >= 0xA0) && (*(s+1) <= 0xBF));
}
static inline int utf8seq_is_illegal(char *s, int n)
{
return ((n == 3) && (*s == 0xEF) && (*(s+1) == 0xBF) &&
(*(s+2) >= 0xBE) && (*(s+2) <= 0xBF));
}
static inline int utf8dec_wchar(wchar_t *c, unsigned char *in, size_t inb)
{
int i;
int n = -1;
/* trivial char */
if (*in <= 0x7F) {
*c = *in;
return 1;
}
/* find utf8 sequence length */
if ((*in & 0xE0) == 0xC0) n = 2;
else if ((*in & 0xF0) == 0xE0) n = 3;
else if ((*in & 0xF8) == 0xF0) n = 4;
else if ((*in & 0xFC) == 0xF8) n = 5;
else if ((*in & 0xFE) == 0xFC) n = 6;
/* starved? */
if (n > inb)
return -2;
/* decode ... */
if (n > 1 && n < 5) {
/* reject invalid sequences */
if (utf8seq_is_overlong(in, n) ||
utf8seq_is_surrogate(in, n) ||
utf8seq_is_illegal(in, n))
return -1;
/* decode ... */
*c = (char)(*in++ & (0x7F >> n));
for (i = 1; i < n; i++) {
/* illegal continuation byte */
if (*in < 0x80 || *in > 0xBF)
return -1;
*c = (*c << 6) | (*in++ & 0x3F);
}
return n;
}
/* unmapped sequence (> 4) */
return -1;
}
static inline wchar_t latin9_translit(wchar_t c)
{
/* a number of trivial iso-8859-15 <> utf-8 transliterations */
switch (c) {
case 0x20AC: return 0xA4; /* Euro */
case 0x0160: return 0xA6; /* S caron */
case 0x0161: return 0xA8; /* s caron */
case 0x017D: return 0xB4; /* Z caron */
case 0x017E: return 0xB8; /* z caron */
case 0x0152: return 0xBC; /* OE */
case 0x0153: return 0xBD; /* oe */
case 0x0178: return 0xBE; /* Y diaeresis */
default: return 0xFFFD; /* cannot translate */
}
}
size_t iconv(iconv_t cd, char **in, size_t *inb, char **out, size_t *outb)
{
size_t x=0;
unsigned char to = (cd>>1)&127;
unsigned char from = 255;
const unsigned char *map = 0;
char tmp[MB_LEN_MAX];
wchar_t c, d;
size_t k, l;
int err;
if (!in || !*in || !*inb) return 0;
if (cd & 1)
map = charmaps[cd>>8].map;
else
from = cd>>8;
for (; *inb; *in+=l, *inb-=l) {
c = *(unsigned char *)*in;
l = 1;
if (from >= UTF_8 && c < 0x80) goto charok;
switch (from) {
case WCHAR_T:
l = sizeof(wchar_t);
if (*inb < l) goto starved;
c = *(wchar_t *)*in;
break;
case UTF_8:
l = utf8dec_wchar(&c, *in, *inb);
if (!l) l++;
else if (l == (size_t)-1) goto ilseq;
else if (l == (size_t)-2) goto starved;
break;
case US_ASCII:
goto ilseq;
case LATIN_9:
if ((unsigned)c - 0xa4 <= 0xbe - 0xa4) {
static const unsigned char map[] = {
0, 0x60, 0, 0x61, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0x7d, 0, 0, 0, 0x7e, 0, 0, 0,
0x52, 0x53, 0x78
};
if (c == 0xa4) c = 0x20ac;
else if (map[c-0xa5]) c = 0x100 | map[c-0xa5];
}
case LATIN_1:
goto charok;
case TIS_620:
if (c >= 0xa1) c += 0x0e01-0xa1;
goto charok;
case JIS_0201:
if (c >= 0xa1) {
if (c <= 0xdf) c += 0xff61-0xa1;
else goto ilseq;
}
goto charok;
case UTF_16BE:
case UTF_16LE:
l = 2;
if (*inb < 2) goto starved;
c = get_16(*in, from);
if ((unsigned)(c-0xdc00) < 0x400) goto ilseq;
if ((unsigned)(c-0xd800) < 0x400) {
l = 4;
if (*inb < 4) goto starved;
d = get_16(*in + 2, from);
if ((unsigned)(c-0xdc00) >= 0x400) goto ilseq;
c = ((c-0xd800)<<10) | (d-0xdc00);
}
break;
case UTF_32BE:
case UTF_32LE:
l = 4;
if (*inb < 4) goto starved;
// FIXME
// c = get_32(*in, from);
break;
default:
/* only support ascii supersets */
if (c < 0x80) break;
switch (map[0]) {
case UCS2_8BIT:
c -= 0x80;
break;
case EUC:
if ((unsigned)c - 0xa1 >= 94) goto ilseq;
if ((unsigned)in[0][1] - 0xa1 >= 94) goto ilseq;
c = (c-0xa1)*94 + (in[0][1]-0xa1);
l = 2;
break;
case SHIFT_JIS:
if ((unsigned)c - 0xa1 <= 0xdf-0xa1) {
c += 0xff61-0xa1;
goto charok;
}
// FIXME...
l = 2;
break;
default:
goto badf;
}
c = get_16(map + 4 + 2*c, 0);
if (c == 0xffff) goto ilseq;
goto charok;
}
if ((unsigned)c - 0xd800 < 0x800 || (unsigned)c >= 0x110000)
goto ilseq;
charok:
switch (to) {
case WCHAR_T:
if (*outb < sizeof(wchar_t)) goto toobig;
*(wchar_t *)*out = c;
*out += sizeof(wchar_t);
*outb -= sizeof(wchar_t);
break;
case UTF_8:
if (*outb < 4) {
k = utf8enc_wchar(tmp, c);
if (*outb < k) goto toobig;
memcpy(*out, tmp, k);
} else k = utf8enc_wchar(*out, c);
*out += k;
*outb -= k;
break;
case US_ASCII:
if (c > 0x7f) c = 0xfffd;
/* fall thru and count replacement in latin1 case */
case LATIN_9:
if (c >= 0x100 && c != 0xfffd)
c = latin9_translit(c);
/* fall through */
case LATIN_1:
if (c > 0xff) goto ilseq;
if (!*outb) goto toobig;
**out = c;
++*out;
--*outb;
break;
case UTF_16BE:
case UTF_16LE:
if (c < 0x10000) {
if (*outb < 2) goto toobig;
put_16(*out, c, to);
*out += 2;
*outb -= 2;
break;
}
if (*outb < 4) goto toobig;
put_16(*out, (c>>10)|0xd800, to);
put_16(*out + 2, (c&0x3ff)|0xdc00, to);
*out += 4;
*outb -= 4;
break;
default:
goto badf;
}
}
return x;
ilseq:
err = EILSEQ;
x = -1;
goto end;
badf:
err = EBADF;
x = -1;
goto end;
toobig:
err = E2BIG;
x = -1;
goto end;
starved:
err = EINVAL;
end:
errno = err;
return x;
}
| gpl-2.0 |
jingr1/Linux-4.2.1-for-OK6410 | drivers/iommu/intel_irq_remapping.c | 208 | 35637 |
#define pr_fmt(fmt) "DMAR-IR: " fmt
#include <linux/interrupt.h>
#include <linux/dmar.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/hpet.h>
#include <linux/pci.h>
#include <linux/irq.h>
#include <linux/intel-iommu.h>
#include <linux/acpi.h>
#include <linux/irqdomain.h>
#include <linux/crash_dump.h>
#include <asm/io_apic.h>
#include <asm/smp.h>
#include <asm/cpu.h>
#include <asm/irq_remapping.h>
#include <asm/pci-direct.h>
#include <asm/msidef.h>
#include "irq_remapping.h"
enum irq_mode {
IRQ_REMAPPING,
IRQ_POSTING,
};
struct ioapic_scope {
struct intel_iommu *iommu;
unsigned int id;
unsigned int bus; /* PCI bus number */
unsigned int devfn; /* PCI devfn number */
};
struct hpet_scope {
struct intel_iommu *iommu;
u8 id;
unsigned int bus;
unsigned int devfn;
};
struct irq_2_iommu {
struct intel_iommu *iommu;
u16 irte_index;
u16 sub_handle;
u8 irte_mask;
enum irq_mode mode;
};
struct intel_ir_data {
struct irq_2_iommu irq_2_iommu;
struct irte irte_entry;
union {
struct msi_msg msi_entry;
};
};
#define IR_X2APIC_MODE(mode) (mode ? (1 << 11) : 0)
#define IRTE_DEST(dest) ((eim_mode) ? dest : dest << 8)
static int __read_mostly eim_mode;
static struct ioapic_scope ir_ioapic[MAX_IO_APICS];
static struct hpet_scope ir_hpet[MAX_HPET_TBS];
/*
* Lock ordering:
* ->dmar_global_lock
* ->irq_2_ir_lock
* ->qi->q_lock
* ->iommu->register_lock
* Note:
* intel_irq_remap_ops.{supported,prepare,enable,disable,reenable} are called
* in single-threaded environment with interrupt disabled, so no need to tabke
* the dmar_global_lock.
*/
static DEFINE_RAW_SPINLOCK(irq_2_ir_lock);
static struct irq_domain_ops intel_ir_domain_ops;
static void iommu_disable_irq_remapping(struct intel_iommu *iommu);
static int __init parse_ioapics_under_ir(void);
static bool ir_pre_enabled(struct intel_iommu *iommu)
{
return (iommu->flags & VTD_FLAG_IRQ_REMAP_PRE_ENABLED);
}
static void clear_ir_pre_enabled(struct intel_iommu *iommu)
{
iommu->flags &= ~VTD_FLAG_IRQ_REMAP_PRE_ENABLED;
}
static void init_ir_status(struct intel_iommu *iommu)
{
u32 gsts;
gsts = readl(iommu->reg + DMAR_GSTS_REG);
if (gsts & DMA_GSTS_IRES)
iommu->flags |= VTD_FLAG_IRQ_REMAP_PRE_ENABLED;
}
static int alloc_irte(struct intel_iommu *iommu, int irq,
struct irq_2_iommu *irq_iommu, u16 count)
{
struct ir_table *table = iommu->ir_table;
unsigned int mask = 0;
unsigned long flags;
int index;
if (!count || !irq_iommu)
return -1;
if (count > 1) {
count = __roundup_pow_of_two(count);
mask = ilog2(count);
}
if (mask > ecap_max_handle_mask(iommu->ecap)) {
pr_err("Requested mask %x exceeds the max invalidation handle"
" mask value %Lx\n", mask,
ecap_max_handle_mask(iommu->ecap));
return -1;
}
raw_spin_lock_irqsave(&irq_2_ir_lock, flags);
index = bitmap_find_free_region(table->bitmap,
INTR_REMAP_TABLE_ENTRIES, mask);
if (index < 0) {
pr_warn("IR%d: can't allocate an IRTE\n", iommu->seq_id);
} else {
irq_iommu->iommu = iommu;
irq_iommu->irte_index = index;
irq_iommu->sub_handle = 0;
irq_iommu->irte_mask = mask;
irq_iommu->mode = IRQ_REMAPPING;
}
raw_spin_unlock_irqrestore(&irq_2_ir_lock, flags);
return index;
}
static int qi_flush_iec(struct intel_iommu *iommu, int index, int mask)
{
struct qi_desc desc;
desc.low = QI_IEC_IIDEX(index) | QI_IEC_TYPE | QI_IEC_IM(mask)
| QI_IEC_SELECTIVE;
desc.high = 0;
return qi_submit_sync(&desc, iommu);
}
static int modify_irte(struct irq_2_iommu *irq_iommu,
struct irte *irte_modified)
{
struct intel_iommu *iommu;
unsigned long flags;
struct irte *irte;
int rc, index;
if (!irq_iommu)
return -1;
raw_spin_lock_irqsave(&irq_2_ir_lock, flags);
iommu = irq_iommu->iommu;
index = irq_iommu->irte_index + irq_iommu->sub_handle;
irte = &iommu->ir_table->base[index];
set_64bit(&irte->low, irte_modified->low);
set_64bit(&irte->high, irte_modified->high);
__iommu_flush_cache(iommu, irte, sizeof(*irte));
rc = qi_flush_iec(iommu, index, 0);
/* Update iommu mode according to the IRTE mode */
irq_iommu->mode = irte->pst ? IRQ_POSTING : IRQ_REMAPPING;
raw_spin_unlock_irqrestore(&irq_2_ir_lock, flags);
return rc;
}
static struct intel_iommu *map_hpet_to_ir(u8 hpet_id)
{
int i;
for (i = 0; i < MAX_HPET_TBS; i++)
if (ir_hpet[i].id == hpet_id && ir_hpet[i].iommu)
return ir_hpet[i].iommu;
return NULL;
}
static struct intel_iommu *map_ioapic_to_ir(int apic)
{
int i;
for (i = 0; i < MAX_IO_APICS; i++)
if (ir_ioapic[i].id == apic && ir_ioapic[i].iommu)
return ir_ioapic[i].iommu;
return NULL;
}
static struct intel_iommu *map_dev_to_ir(struct pci_dev *dev)
{
struct dmar_drhd_unit *drhd;
drhd = dmar_find_matched_drhd_unit(dev);
if (!drhd)
return NULL;
return drhd->iommu;
}
static int clear_entries(struct irq_2_iommu *irq_iommu)
{
struct irte *start, *entry, *end;
struct intel_iommu *iommu;
int index;
if (irq_iommu->sub_handle)
return 0;
iommu = irq_iommu->iommu;
index = irq_iommu->irte_index;
start = iommu->ir_table->base + index;
end = start + (1 << irq_iommu->irte_mask);
for (entry = start; entry < end; entry++) {
set_64bit(&entry->low, 0);
set_64bit(&entry->high, 0);
}
bitmap_release_region(iommu->ir_table->bitmap, index,
irq_iommu->irte_mask);
return qi_flush_iec(iommu, index, irq_iommu->irte_mask);
}
/*
* source validation type
*/
#define SVT_NO_VERIFY 0x0 /* no verification is required */
#define SVT_VERIFY_SID_SQ 0x1 /* verify using SID and SQ fields */
#define SVT_VERIFY_BUS 0x2 /* verify bus of request-id */
/*
* source-id qualifier
*/
#define SQ_ALL_16 0x0 /* verify all 16 bits of request-id */
#define SQ_13_IGNORE_1 0x1 /* verify most significant 13 bits, ignore
* the third least significant bit
*/
#define SQ_13_IGNORE_2 0x2 /* verify most significant 13 bits, ignore
* the second and third least significant bits
*/
#define SQ_13_IGNORE_3 0x3 /* verify most significant 13 bits, ignore
* the least three significant bits
*/
/*
* set SVT, SQ and SID fields of irte to verify
* source ids of interrupt requests
*/
static void set_irte_sid(struct irte *irte, unsigned int svt,
unsigned int sq, unsigned int sid)
{
if (disable_sourceid_checking)
svt = SVT_NO_VERIFY;
irte->svt = svt;
irte->sq = sq;
irte->sid = sid;
}
static int set_ioapic_sid(struct irte *irte, int apic)
{
int i;
u16 sid = 0;
if (!irte)
return -1;
down_read(&dmar_global_lock);
for (i = 0; i < MAX_IO_APICS; i++) {
if (ir_ioapic[i].iommu && ir_ioapic[i].id == apic) {
sid = (ir_ioapic[i].bus << 8) | ir_ioapic[i].devfn;
break;
}
}
up_read(&dmar_global_lock);
if (sid == 0) {
pr_warn("Failed to set source-id of IOAPIC (%d)\n", apic);
return -1;
}
set_irte_sid(irte, SVT_VERIFY_SID_SQ, SQ_ALL_16, sid);
return 0;
}
static int set_hpet_sid(struct irte *irte, u8 id)
{
int i;
u16 sid = 0;
if (!irte)
return -1;
down_read(&dmar_global_lock);
for (i = 0; i < MAX_HPET_TBS; i++) {
if (ir_hpet[i].iommu && ir_hpet[i].id == id) {
sid = (ir_hpet[i].bus << 8) | ir_hpet[i].devfn;
break;
}
}
up_read(&dmar_global_lock);
if (sid == 0) {
pr_warn("Failed to set source-id of HPET block (%d)\n", id);
return -1;
}
/*
* Should really use SQ_ALL_16. Some platforms are broken.
* While we figure out the right quirks for these broken platforms, use
* SQ_13_IGNORE_3 for now.
*/
set_irte_sid(irte, SVT_VERIFY_SID_SQ, SQ_13_IGNORE_3, sid);
return 0;
}
struct set_msi_sid_data {
struct pci_dev *pdev;
u16 alias;
};
static int set_msi_sid_cb(struct pci_dev *pdev, u16 alias, void *opaque)
{
struct set_msi_sid_data *data = opaque;
data->pdev = pdev;
data->alias = alias;
return 0;
}
static int set_msi_sid(struct irte *irte, struct pci_dev *dev)
{
struct set_msi_sid_data data;
if (!irte || !dev)
return -1;
pci_for_each_dma_alias(dev, set_msi_sid_cb, &data);
/*
* DMA alias provides us with a PCI device and alias. The only case
* where the it will return an alias on a different bus than the
* device is the case of a PCIe-to-PCI bridge, where the alias is for
* the subordinate bus. In this case we can only verify the bus.
*
* If the alias device is on a different bus than our source device
* then we have a topology based alias, use it.
*
* Otherwise, the alias is for a device DMA quirk and we cannot
* assume that MSI uses the same requester ID. Therefore use the
* original device.
*/
if (PCI_BUS_NUM(data.alias) != data.pdev->bus->number)
set_irte_sid(irte, SVT_VERIFY_BUS, SQ_ALL_16,
PCI_DEVID(PCI_BUS_NUM(data.alias),
dev->bus->number));
else if (data.pdev->bus->number != dev->bus->number)
set_irte_sid(irte, SVT_VERIFY_SID_SQ, SQ_ALL_16, data.alias);
else
set_irte_sid(irte, SVT_VERIFY_SID_SQ, SQ_ALL_16,
PCI_DEVID(dev->bus->number, dev->devfn));
return 0;
}
static int iommu_load_old_irte(struct intel_iommu *iommu)
{
struct irte *old_ir_table;
phys_addr_t irt_phys;
unsigned int i;
size_t size;
u64 irta;
if (!is_kdump_kernel()) {
pr_warn("IRQ remapping was enabled on %s but we are not in kdump mode\n",
iommu->name);
clear_ir_pre_enabled(iommu);
iommu_disable_irq_remapping(iommu);
return -EINVAL;
}
/* Check whether the old ir-table has the same size as ours */
irta = dmar_readq(iommu->reg + DMAR_IRTA_REG);
if ((irta & INTR_REMAP_TABLE_REG_SIZE_MASK)
!= INTR_REMAP_TABLE_REG_SIZE)
return -EINVAL;
irt_phys = irta & VTD_PAGE_MASK;
size = INTR_REMAP_TABLE_ENTRIES*sizeof(struct irte);
/* Map the old IR table */
old_ir_table = ioremap_cache(irt_phys, size);
if (!old_ir_table)
return -ENOMEM;
/* Copy data over */
memcpy(iommu->ir_table->base, old_ir_table, size);
__iommu_flush_cache(iommu, iommu->ir_table->base, size);
/*
* Now check the table for used entries and mark those as
* allocated in the bitmap
*/
for (i = 0; i < INTR_REMAP_TABLE_ENTRIES; i++) {
if (iommu->ir_table->base[i].present)
bitmap_set(iommu->ir_table->bitmap, i, 1);
}
return 0;
}
static void iommu_set_irq_remapping(struct intel_iommu *iommu, int mode)
{
unsigned long flags;
u64 addr;
u32 sts;
addr = virt_to_phys((void *)iommu->ir_table->base);
raw_spin_lock_irqsave(&iommu->register_lock, flags);
dmar_writeq(iommu->reg + DMAR_IRTA_REG,
(addr) | IR_X2APIC_MODE(mode) | INTR_REMAP_TABLE_REG_SIZE);
/* Set interrupt-remapping table pointer */
writel(iommu->gcmd | DMA_GCMD_SIRTP, iommu->reg + DMAR_GCMD_REG);
IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
readl, (sts & DMA_GSTS_IRTPS), sts);
raw_spin_unlock_irqrestore(&iommu->register_lock, flags);
/*
* Global invalidation of interrupt entry cache to make sure the
* hardware uses the new irq remapping table.
*/
qi_global_iec(iommu);
}
static void iommu_enable_irq_remapping(struct intel_iommu *iommu)
{
unsigned long flags;
u32 sts;
raw_spin_lock_irqsave(&iommu->register_lock, flags);
/* Enable interrupt-remapping */
iommu->gcmd |= DMA_GCMD_IRE;
iommu->gcmd &= ~DMA_GCMD_CFI; /* Block compatibility-format MSIs */
writel(iommu->gcmd, iommu->reg + DMAR_GCMD_REG);
IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
readl, (sts & DMA_GSTS_IRES), sts);
/*
* With CFI clear in the Global Command register, we should be
* protected from dangerous (i.e. compatibility) interrupts
* regardless of x2apic status. Check just to be sure.
*/
if (sts & DMA_GSTS_CFIS)
WARN(1, KERN_WARNING
"Compatibility-format IRQs enabled despite intr remapping;\n"
"you are vulnerable to IRQ injection.\n");
raw_spin_unlock_irqrestore(&iommu->register_lock, flags);
}
static int intel_setup_irq_remapping(struct intel_iommu *iommu)
{
struct ir_table *ir_table;
struct page *pages;
unsigned long *bitmap;
if (iommu->ir_table)
return 0;
ir_table = kzalloc(sizeof(struct ir_table), GFP_KERNEL);
if (!ir_table)
return -ENOMEM;
pages = alloc_pages_node(iommu->node, GFP_KERNEL | __GFP_ZERO,
INTR_REMAP_PAGE_ORDER);
if (!pages) {
pr_err("IR%d: failed to allocate pages of order %d\n",
iommu->seq_id, INTR_REMAP_PAGE_ORDER);
goto out_free_table;
}
bitmap = kcalloc(BITS_TO_LONGS(INTR_REMAP_TABLE_ENTRIES),
sizeof(long), GFP_ATOMIC);
if (bitmap == NULL) {
pr_err("IR%d: failed to allocate bitmap\n", iommu->seq_id);
goto out_free_pages;
}
iommu->ir_domain = irq_domain_add_hierarchy(arch_get_ir_parent_domain(),
0, INTR_REMAP_TABLE_ENTRIES,
NULL, &intel_ir_domain_ops,
iommu);
if (!iommu->ir_domain) {
pr_err("IR%d: failed to allocate irqdomain\n", iommu->seq_id);
goto out_free_bitmap;
}
iommu->ir_msi_domain = arch_create_msi_irq_domain(iommu->ir_domain);
ir_table->base = page_address(pages);
ir_table->bitmap = bitmap;
iommu->ir_table = ir_table;
/*
* If the queued invalidation is already initialized,
* shouldn't disable it.
*/
if (!iommu->qi) {
/*
* Clear previous faults.
*/
dmar_fault(-1, iommu);
dmar_disable_qi(iommu);
if (dmar_enable_qi(iommu)) {
pr_err("Failed to enable queued invalidation\n");
goto out_free_bitmap;
}
}
init_ir_status(iommu);
if (ir_pre_enabled(iommu)) {
if (iommu_load_old_irte(iommu))
pr_err("Failed to copy IR table for %s from previous kernel\n",
iommu->name);
else
pr_info("Copied IR table for %s from previous kernel\n",
iommu->name);
}
iommu_set_irq_remapping(iommu, eim_mode);
return 0;
out_free_bitmap:
kfree(bitmap);
out_free_pages:
__free_pages(pages, INTR_REMAP_PAGE_ORDER);
out_free_table:
kfree(ir_table);
iommu->ir_table = NULL;
return -ENOMEM;
}
static void intel_teardown_irq_remapping(struct intel_iommu *iommu)
{
if (iommu && iommu->ir_table) {
if (iommu->ir_msi_domain) {
irq_domain_remove(iommu->ir_msi_domain);
iommu->ir_msi_domain = NULL;
}
if (iommu->ir_domain) {
irq_domain_remove(iommu->ir_domain);
iommu->ir_domain = NULL;
}
free_pages((unsigned long)iommu->ir_table->base,
INTR_REMAP_PAGE_ORDER);
kfree(iommu->ir_table->bitmap);
kfree(iommu->ir_table);
iommu->ir_table = NULL;
}
}
/*
* Disable Interrupt Remapping.
*/
static void iommu_disable_irq_remapping(struct intel_iommu *iommu)
{
unsigned long flags;
u32 sts;
if (!ecap_ir_support(iommu->ecap))
return;
/*
* global invalidation of interrupt entry cache before disabling
* interrupt-remapping.
*/
qi_global_iec(iommu);
raw_spin_lock_irqsave(&iommu->register_lock, flags);
sts = dmar_readq(iommu->reg + DMAR_GSTS_REG);
if (!(sts & DMA_GSTS_IRES))
goto end;
iommu->gcmd &= ~DMA_GCMD_IRE;
writel(iommu->gcmd, iommu->reg + DMAR_GCMD_REG);
IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
readl, !(sts & DMA_GSTS_IRES), sts);
end:
raw_spin_unlock_irqrestore(&iommu->register_lock, flags);
}
static int __init dmar_x2apic_optout(void)
{
struct acpi_table_dmar *dmar;
dmar = (struct acpi_table_dmar *)dmar_tbl;
if (!dmar || no_x2apic_optout)
return 0;
return dmar->flags & DMAR_X2APIC_OPT_OUT;
}
static void __init intel_cleanup_irq_remapping(void)
{
struct dmar_drhd_unit *drhd;
struct intel_iommu *iommu;
for_each_iommu(iommu, drhd) {
if (ecap_ir_support(iommu->ecap)) {
iommu_disable_irq_remapping(iommu);
intel_teardown_irq_remapping(iommu);
}
}
if (x2apic_supported())
pr_warn("Failed to enable irq remapping. You are vulnerable to irq-injection attacks.\n");
}
static int __init intel_prepare_irq_remapping(void)
{
struct dmar_drhd_unit *drhd;
struct intel_iommu *iommu;
int eim = 0;
if (irq_remap_broken) {
pr_warn("This system BIOS has enabled interrupt remapping\n"
"on a chipset that contains an erratum making that\n"
"feature unstable. To maintain system stability\n"
"interrupt remapping is being disabled. Please\n"
"contact your BIOS vendor for an update\n");
add_taint(TAINT_FIRMWARE_WORKAROUND, LOCKDEP_STILL_OK);
return -ENODEV;
}
if (dmar_table_init() < 0)
return -ENODEV;
if (!dmar_ir_support())
return -ENODEV;
if (parse_ioapics_under_ir() != 1) {
pr_info("Not enabling interrupt remapping\n");
goto error;
}
/* First make sure all IOMMUs support IRQ remapping */
for_each_iommu(iommu, drhd)
if (!ecap_ir_support(iommu->ecap))
goto error;
/* Detect remapping mode: lapic or x2apic */
if (x2apic_supported()) {
eim = !dmar_x2apic_optout();
if (!eim) {
pr_info("x2apic is disabled because BIOS sets x2apic opt out bit.");
pr_info("Use 'intremap=no_x2apic_optout' to override the BIOS setting.\n");
}
}
for_each_iommu(iommu, drhd) {
if (eim && !ecap_eim_support(iommu->ecap)) {
pr_info("%s does not support EIM\n", iommu->name);
eim = 0;
}
}
eim_mode = eim;
if (eim)
pr_info("Queued invalidation will be enabled to support x2apic and Intr-remapping.\n");
/* Do the initializations early */
for_each_iommu(iommu, drhd) {
if (intel_setup_irq_remapping(iommu)) {
pr_err("Failed to setup irq remapping for %s\n",
iommu->name);
goto error;
}
}
return 0;
error:
intel_cleanup_irq_remapping();
return -ENODEV;
}
/*
* Set Posted-Interrupts capability.
*/
static inline void set_irq_posting_cap(void)
{
struct dmar_drhd_unit *drhd;
struct intel_iommu *iommu;
if (!disable_irq_post) {
intel_irq_remap_ops.capability |= 1 << IRQ_POSTING_CAP;
for_each_iommu(iommu, drhd)
if (!cap_pi_support(iommu->cap)) {
intel_irq_remap_ops.capability &=
~(1 << IRQ_POSTING_CAP);
break;
}
}
}
static int __init intel_enable_irq_remapping(void)
{
struct dmar_drhd_unit *drhd;
struct intel_iommu *iommu;
bool setup = false;
/*
* Setup Interrupt-remapping for all the DRHD's now.
*/
for_each_iommu(iommu, drhd) {
if (!ir_pre_enabled(iommu))
iommu_enable_irq_remapping(iommu);
setup = true;
}
if (!setup)
goto error;
irq_remapping_enabled = 1;
set_irq_posting_cap();
pr_info("Enabled IRQ remapping in %s mode\n", eim_mode ? "x2apic" : "xapic");
return eim_mode ? IRQ_REMAP_X2APIC_MODE : IRQ_REMAP_XAPIC_MODE;
error:
intel_cleanup_irq_remapping();
return -1;
}
static int ir_parse_one_hpet_scope(struct acpi_dmar_device_scope *scope,
struct intel_iommu *iommu,
struct acpi_dmar_hardware_unit *drhd)
{
struct acpi_dmar_pci_path *path;
u8 bus;
int count, free = -1;
bus = scope->bus;
path = (struct acpi_dmar_pci_path *)(scope + 1);
count = (scope->length - sizeof(struct acpi_dmar_device_scope))
/ sizeof(struct acpi_dmar_pci_path);
while (--count > 0) {
/*
* Access PCI directly due to the PCI
* subsystem isn't initialized yet.
*/
bus = read_pci_config_byte(bus, path->device, path->function,
PCI_SECONDARY_BUS);
path++;
}
for (count = 0; count < MAX_HPET_TBS; count++) {
if (ir_hpet[count].iommu == iommu &&
ir_hpet[count].id == scope->enumeration_id)
return 0;
else if (ir_hpet[count].iommu == NULL && free == -1)
free = count;
}
if (free == -1) {
pr_warn("Exceeded Max HPET blocks\n");
return -ENOSPC;
}
ir_hpet[free].iommu = iommu;
ir_hpet[free].id = scope->enumeration_id;
ir_hpet[free].bus = bus;
ir_hpet[free].devfn = PCI_DEVFN(path->device, path->function);
pr_info("HPET id %d under DRHD base 0x%Lx\n",
scope->enumeration_id, drhd->address);
return 0;
}
static int ir_parse_one_ioapic_scope(struct acpi_dmar_device_scope *scope,
struct intel_iommu *iommu,
struct acpi_dmar_hardware_unit *drhd)
{
struct acpi_dmar_pci_path *path;
u8 bus;
int count, free = -1;
bus = scope->bus;
path = (struct acpi_dmar_pci_path *)(scope + 1);
count = (scope->length - sizeof(struct acpi_dmar_device_scope))
/ sizeof(struct acpi_dmar_pci_path);
while (--count > 0) {
/*
* Access PCI directly due to the PCI
* subsystem isn't initialized yet.
*/
bus = read_pci_config_byte(bus, path->device, path->function,
PCI_SECONDARY_BUS);
path++;
}
for (count = 0; count < MAX_IO_APICS; count++) {
if (ir_ioapic[count].iommu == iommu &&
ir_ioapic[count].id == scope->enumeration_id)
return 0;
else if (ir_ioapic[count].iommu == NULL && free == -1)
free = count;
}
if (free == -1) {
pr_warn("Exceeded Max IO APICS\n");
return -ENOSPC;
}
ir_ioapic[free].bus = bus;
ir_ioapic[free].devfn = PCI_DEVFN(path->device, path->function);
ir_ioapic[free].iommu = iommu;
ir_ioapic[free].id = scope->enumeration_id;
pr_info("IOAPIC id %d under DRHD base 0x%Lx IOMMU %d\n",
scope->enumeration_id, drhd->address, iommu->seq_id);
return 0;
}
static int ir_parse_ioapic_hpet_scope(struct acpi_dmar_header *header,
struct intel_iommu *iommu)
{
int ret = 0;
struct acpi_dmar_hardware_unit *drhd;
struct acpi_dmar_device_scope *scope;
void *start, *end;
drhd = (struct acpi_dmar_hardware_unit *)header;
start = (void *)(drhd + 1);
end = ((void *)drhd) + header->length;
while (start < end && ret == 0) {
scope = start;
if (scope->entry_type == ACPI_DMAR_SCOPE_TYPE_IOAPIC)
ret = ir_parse_one_ioapic_scope(scope, iommu, drhd);
else if (scope->entry_type == ACPI_DMAR_SCOPE_TYPE_HPET)
ret = ir_parse_one_hpet_scope(scope, iommu, drhd);
start += scope->length;
}
return ret;
}
static void ir_remove_ioapic_hpet_scope(struct intel_iommu *iommu)
{
int i;
for (i = 0; i < MAX_HPET_TBS; i++)
if (ir_hpet[i].iommu == iommu)
ir_hpet[i].iommu = NULL;
for (i = 0; i < MAX_IO_APICS; i++)
if (ir_ioapic[i].iommu == iommu)
ir_ioapic[i].iommu = NULL;
}
/*
* Finds the assocaition between IOAPIC's and its Interrupt-remapping
* hardware unit.
*/
static int __init parse_ioapics_under_ir(void)
{
struct dmar_drhd_unit *drhd;
struct intel_iommu *iommu;
bool ir_supported = false;
int ioapic_idx;
for_each_iommu(iommu, drhd)
if (ecap_ir_support(iommu->ecap)) {
if (ir_parse_ioapic_hpet_scope(drhd->hdr, iommu))
return -1;
ir_supported = true;
}
if (!ir_supported)
return 0;
for (ioapic_idx = 0; ioapic_idx < nr_ioapics; ioapic_idx++) {
int ioapic_id = mpc_ioapic_id(ioapic_idx);
if (!map_ioapic_to_ir(ioapic_id)) {
pr_err(FW_BUG "ioapic %d has no mapping iommu, "
"interrupt remapping will be disabled\n",
ioapic_id);
return -1;
}
}
return 1;
}
static int __init ir_dev_scope_init(void)
{
int ret;
if (!irq_remapping_enabled)
return 0;
down_write(&dmar_global_lock);
ret = dmar_dev_scope_init();
up_write(&dmar_global_lock);
return ret;
}
rootfs_initcall(ir_dev_scope_init);
static void disable_irq_remapping(void)
{
struct dmar_drhd_unit *drhd;
struct intel_iommu *iommu = NULL;
/*
* Disable Interrupt-remapping for all the DRHD's now.
*/
for_each_iommu(iommu, drhd) {
if (!ecap_ir_support(iommu->ecap))
continue;
iommu_disable_irq_remapping(iommu);
}
/*
* Clear Posted-Interrupts capability.
*/
if (!disable_irq_post)
intel_irq_remap_ops.capability &= ~(1 << IRQ_POSTING_CAP);
}
static int reenable_irq_remapping(int eim)
{
struct dmar_drhd_unit *drhd;
bool setup = false;
struct intel_iommu *iommu = NULL;
for_each_iommu(iommu, drhd)
if (iommu->qi)
dmar_reenable_qi(iommu);
/*
* Setup Interrupt-remapping for all the DRHD's now.
*/
for_each_iommu(iommu, drhd) {
if (!ecap_ir_support(iommu->ecap))
continue;
/* Set up interrupt remapping for iommu.*/
iommu_set_irq_remapping(iommu, eim);
iommu_enable_irq_remapping(iommu);
setup = true;
}
if (!setup)
goto error;
set_irq_posting_cap();
return 0;
error:
/*
* handle error condition gracefully here!
*/
return -1;
}
static void prepare_irte(struct irte *irte, int vector, unsigned int dest)
{
memset(irte, 0, sizeof(*irte));
irte->present = 1;
irte->dst_mode = apic->irq_dest_mode;
/*
* Trigger mode in the IRTE will always be edge, and for IO-APIC, the
* actual level or edge trigger will be setup in the IO-APIC
* RTE. This will help simplify level triggered irq migration.
* For more details, see the comments (in io_apic.c) explainig IO-APIC
* irq migration in the presence of interrupt-remapping.
*/
irte->trigger_mode = 0;
irte->dlvry_mode = apic->irq_delivery_mode;
irte->vector = vector;
irte->dest_id = IRTE_DEST(dest);
irte->redir_hint = 1;
}
static struct irq_domain *intel_get_ir_irq_domain(struct irq_alloc_info *info)
{
struct intel_iommu *iommu = NULL;
if (!info)
return NULL;
switch (info->type) {
case X86_IRQ_ALLOC_TYPE_IOAPIC:
iommu = map_ioapic_to_ir(info->ioapic_id);
break;
case X86_IRQ_ALLOC_TYPE_HPET:
iommu = map_hpet_to_ir(info->hpet_id);
break;
case X86_IRQ_ALLOC_TYPE_MSI:
case X86_IRQ_ALLOC_TYPE_MSIX:
iommu = map_dev_to_ir(info->msi_dev);
break;
default:
BUG_ON(1);
break;
}
return iommu ? iommu->ir_domain : NULL;
}
static struct irq_domain *intel_get_irq_domain(struct irq_alloc_info *info)
{
struct intel_iommu *iommu;
if (!info)
return NULL;
switch (info->type) {
case X86_IRQ_ALLOC_TYPE_MSI:
case X86_IRQ_ALLOC_TYPE_MSIX:
iommu = map_dev_to_ir(info->msi_dev);
if (iommu)
return iommu->ir_msi_domain;
break;
default:
break;
}
return NULL;
}
struct irq_remap_ops intel_irq_remap_ops = {
.prepare = intel_prepare_irq_remapping,
.enable = intel_enable_irq_remapping,
.disable = disable_irq_remapping,
.reenable = reenable_irq_remapping,
.enable_faulting = enable_drhd_fault_handling,
.get_ir_irq_domain = intel_get_ir_irq_domain,
.get_irq_domain = intel_get_irq_domain,
};
/*
* Migrate the IO-APIC irq in the presence of intr-remapping.
*
* For both level and edge triggered, irq migration is a simple atomic
* update(of vector and cpu destination) of IRTE and flush the hardware cache.
*
* For level triggered, we eliminate the io-apic RTE modification (with the
* updated vector information), by using a virtual vector (io-apic pin number).
* Real vector that is used for interrupting cpu will be coming from
* the interrupt-remapping table entry.
*
* As the migration is a simple atomic update of IRTE, the same mechanism
* is used to migrate MSI irq's in the presence of interrupt-remapping.
*/
static int
intel_ir_set_affinity(struct irq_data *data, const struct cpumask *mask,
bool force)
{
struct intel_ir_data *ir_data = data->chip_data;
struct irte *irte = &ir_data->irte_entry;
struct irq_cfg *cfg = irqd_cfg(data);
struct irq_data *parent = data->parent_data;
int ret;
ret = parent->chip->irq_set_affinity(parent, mask, force);
if (ret < 0 || ret == IRQ_SET_MASK_OK_DONE)
return ret;
/*
* Atomically updates the IRTE with the new destination, vector
* and flushes the interrupt entry cache.
*/
irte->vector = cfg->vector;
irte->dest_id = IRTE_DEST(cfg->dest_apicid);
/* Update the hardware only if the interrupt is in remapped mode. */
if (ir_data->irq_2_iommu.mode == IRQ_REMAPPING)
modify_irte(&ir_data->irq_2_iommu, irte);
/*
* After this point, all the interrupts will start arriving
* at the new destination. So, time to cleanup the previous
* vector allocation.
*/
send_cleanup_vector(cfg);
return IRQ_SET_MASK_OK_DONE;
}
static void intel_ir_compose_msi_msg(struct irq_data *irq_data,
struct msi_msg *msg)
{
struct intel_ir_data *ir_data = irq_data->chip_data;
*msg = ir_data->msi_entry;
}
static int intel_ir_set_vcpu_affinity(struct irq_data *data, void *info)
{
struct intel_ir_data *ir_data = data->chip_data;
struct vcpu_data *vcpu_pi_info = info;
/* stop posting interrupts, back to remapping mode */
if (!vcpu_pi_info) {
modify_irte(&ir_data->irq_2_iommu, &ir_data->irte_entry);
} else {
struct irte irte_pi;
/*
* We are not caching the posted interrupt entry. We
* copy the data from the remapped entry and modify
* the fields which are relevant for posted mode. The
* cached remapped entry is used for switching back to
* remapped mode.
*/
memset(&irte_pi, 0, sizeof(irte_pi));
dmar_copy_shared_irte(&irte_pi, &ir_data->irte_entry);
/* Update the posted mode fields */
irte_pi.p_pst = 1;
irte_pi.p_urgent = 0;
irte_pi.p_vector = vcpu_pi_info->vector;
irte_pi.pda_l = (vcpu_pi_info->pi_desc_addr >>
(32 - PDA_LOW_BIT)) & ~(-1UL << PDA_LOW_BIT);
irte_pi.pda_h = (vcpu_pi_info->pi_desc_addr >> 32) &
~(-1UL << PDA_HIGH_BIT);
modify_irte(&ir_data->irq_2_iommu, &irte_pi);
}
return 0;
}
static struct irq_chip intel_ir_chip = {
.irq_ack = ir_ack_apic_edge,
.irq_set_affinity = intel_ir_set_affinity,
.irq_compose_msi_msg = intel_ir_compose_msi_msg,
.irq_set_vcpu_affinity = intel_ir_set_vcpu_affinity,
};
static void intel_irq_remapping_prepare_irte(struct intel_ir_data *data,
struct irq_cfg *irq_cfg,
struct irq_alloc_info *info,
int index, int sub_handle)
{
struct IR_IO_APIC_route_entry *entry;
struct irte *irte = &data->irte_entry;
struct msi_msg *msg = &data->msi_entry;
prepare_irte(irte, irq_cfg->vector, irq_cfg->dest_apicid);
switch (info->type) {
case X86_IRQ_ALLOC_TYPE_IOAPIC:
/* Set source-id of interrupt request */
set_ioapic_sid(irte, info->ioapic_id);
apic_printk(APIC_VERBOSE, KERN_DEBUG "IOAPIC[%d]: Set IRTE entry (P:%d FPD:%d Dst_Mode:%d Redir_hint:%d Trig_Mode:%d Dlvry_Mode:%X Avail:%X Vector:%02X Dest:%08X SID:%04X SQ:%X SVT:%X)\n",
info->ioapic_id, irte->present, irte->fpd,
irte->dst_mode, irte->redir_hint,
irte->trigger_mode, irte->dlvry_mode,
irte->avail, irte->vector, irte->dest_id,
irte->sid, irte->sq, irte->svt);
entry = (struct IR_IO_APIC_route_entry *)info->ioapic_entry;
info->ioapic_entry = NULL;
memset(entry, 0, sizeof(*entry));
entry->index2 = (index >> 15) & 0x1;
entry->zero = 0;
entry->format = 1;
entry->index = (index & 0x7fff);
/*
* IO-APIC RTE will be configured with virtual vector.
* irq handler will do the explicit EOI to the io-apic.
*/
entry->vector = info->ioapic_pin;
entry->mask = 0; /* enable IRQ */
entry->trigger = info->ioapic_trigger;
entry->polarity = info->ioapic_polarity;
if (info->ioapic_trigger)
entry->mask = 1; /* Mask level triggered irqs. */
break;
case X86_IRQ_ALLOC_TYPE_HPET:
case X86_IRQ_ALLOC_TYPE_MSI:
case X86_IRQ_ALLOC_TYPE_MSIX:
if (info->type == X86_IRQ_ALLOC_TYPE_HPET)
set_hpet_sid(irte, info->hpet_id);
else
set_msi_sid(irte, info->msi_dev);
msg->address_hi = MSI_ADDR_BASE_HI;
msg->data = sub_handle;
msg->address_lo = MSI_ADDR_BASE_LO | MSI_ADDR_IR_EXT_INT |
MSI_ADDR_IR_SHV |
MSI_ADDR_IR_INDEX1(index) |
MSI_ADDR_IR_INDEX2(index);
break;
default:
BUG_ON(1);
break;
}
}
static void intel_free_irq_resources(struct irq_domain *domain,
unsigned int virq, unsigned int nr_irqs)
{
struct irq_data *irq_data;
struct intel_ir_data *data;
struct irq_2_iommu *irq_iommu;
unsigned long flags;
int i;
for (i = 0; i < nr_irqs; i++) {
irq_data = irq_domain_get_irq_data(domain, virq + i);
if (irq_data && irq_data->chip_data) {
data = irq_data->chip_data;
irq_iommu = &data->irq_2_iommu;
raw_spin_lock_irqsave(&irq_2_ir_lock, flags);
clear_entries(irq_iommu);
raw_spin_unlock_irqrestore(&irq_2_ir_lock, flags);
irq_domain_reset_irq_data(irq_data);
kfree(data);
}
}
}
static int intel_irq_remapping_alloc(struct irq_domain *domain,
unsigned int virq, unsigned int nr_irqs,
void *arg)
{
struct intel_iommu *iommu = domain->host_data;
struct irq_alloc_info *info = arg;
struct intel_ir_data *data, *ird;
struct irq_data *irq_data;
struct irq_cfg *irq_cfg;
int i, ret, index;
if (!info || !iommu)
return -EINVAL;
if (nr_irqs > 1 && info->type != X86_IRQ_ALLOC_TYPE_MSI &&
info->type != X86_IRQ_ALLOC_TYPE_MSIX)
return -EINVAL;
/*
* With IRQ remapping enabled, don't need contiguous CPU vectors
* to support multiple MSI interrupts.
*/
if (info->type == X86_IRQ_ALLOC_TYPE_MSI)
info->flags &= ~X86_IRQ_ALLOC_CONTIGUOUS_VECTORS;
ret = irq_domain_alloc_irqs_parent(domain, virq, nr_irqs, arg);
if (ret < 0)
return ret;
ret = -ENOMEM;
data = kzalloc(sizeof(*data), GFP_KERNEL);
if (!data)
goto out_free_parent;
down_read(&dmar_global_lock);
index = alloc_irte(iommu, virq, &data->irq_2_iommu, nr_irqs);
up_read(&dmar_global_lock);
if (index < 0) {
pr_warn("Failed to allocate IRTE\n");
kfree(data);
goto out_free_parent;
}
for (i = 0; i < nr_irqs; i++) {
irq_data = irq_domain_get_irq_data(domain, virq + i);
irq_cfg = irqd_cfg(irq_data);
if (!irq_data || !irq_cfg) {
ret = -EINVAL;
goto out_free_data;
}
if (i > 0) {
ird = kzalloc(sizeof(*ird), GFP_KERNEL);
if (!ird)
goto out_free_data;
/* Initialize the common data */
ird->irq_2_iommu = data->irq_2_iommu;
ird->irq_2_iommu.sub_handle = i;
} else {
ird = data;
}
irq_data->hwirq = (index << 16) + i;
irq_data->chip_data = ird;
irq_data->chip = &intel_ir_chip;
intel_irq_remapping_prepare_irte(ird, irq_cfg, info, index, i);
irq_set_status_flags(virq + i, IRQ_MOVE_PCNTXT);
}
return 0;
out_free_data:
intel_free_irq_resources(domain, virq, i);
out_free_parent:
irq_domain_free_irqs_common(domain, virq, nr_irqs);
return ret;
}
static void intel_irq_remapping_free(struct irq_domain *domain,
unsigned int virq, unsigned int nr_irqs)
{
intel_free_irq_resources(domain, virq, nr_irqs);
irq_domain_free_irqs_common(domain, virq, nr_irqs);
}
static void intel_irq_remapping_activate(struct irq_domain *domain,
struct irq_data *irq_data)
{
struct intel_ir_data *data = irq_data->chip_data;
modify_irte(&data->irq_2_iommu, &data->irte_entry);
}
static void intel_irq_remapping_deactivate(struct irq_domain *domain,
struct irq_data *irq_data)
{
struct intel_ir_data *data = irq_data->chip_data;
struct irte entry;
memset(&entry, 0, sizeof(entry));
modify_irte(&data->irq_2_iommu, &entry);
}
static struct irq_domain_ops intel_ir_domain_ops = {
.alloc = intel_irq_remapping_alloc,
.free = intel_irq_remapping_free,
.activate = intel_irq_remapping_activate,
.deactivate = intel_irq_remapping_deactivate,
};
/*
* Support of Interrupt Remapping Unit Hotplug
*/
static int dmar_ir_add(struct dmar_drhd_unit *dmaru, struct intel_iommu *iommu)
{
int ret;
int eim = x2apic_enabled();
if (eim && !ecap_eim_support(iommu->ecap)) {
pr_info("DRHD %Lx: EIM not supported by DRHD, ecap %Lx\n",
iommu->reg_phys, iommu->ecap);
return -ENODEV;
}
if (ir_parse_ioapic_hpet_scope(dmaru->hdr, iommu)) {
pr_warn("DRHD %Lx: failed to parse managed IOAPIC/HPET\n",
iommu->reg_phys);
return -ENODEV;
}
/* TODO: check all IOAPICs are covered by IOMMU */
/* Setup Interrupt-remapping now. */
ret = intel_setup_irq_remapping(iommu);
if (ret) {
pr_err("Failed to setup irq remapping for %s\n",
iommu->name);
intel_teardown_irq_remapping(iommu);
ir_remove_ioapic_hpet_scope(iommu);
} else {
iommu_enable_irq_remapping(iommu);
}
return ret;
}
int dmar_ir_hotplug(struct dmar_drhd_unit *dmaru, bool insert)
{
int ret = 0;
struct intel_iommu *iommu = dmaru->iommu;
if (!irq_remapping_enabled)
return 0;
if (iommu == NULL)
return -EINVAL;
if (!ecap_ir_support(iommu->ecap))
return 0;
if (irq_remapping_cap(IRQ_POSTING_CAP) &&
!cap_pi_support(iommu->cap))
return -EBUSY;
if (insert) {
if (!iommu->ir_table)
ret = dmar_ir_add(dmaru, iommu);
} else {
if (iommu->ir_table) {
if (!bitmap_empty(iommu->ir_table->bitmap,
INTR_REMAP_TABLE_ENTRIES)) {
ret = -EBUSY;
} else {
iommu_disable_irq_remapping(iommu);
intel_teardown_irq_remapping(iommu);
ir_remove_ioapic_hpet_scope(iommu);
}
}
}
return ret;
}
| gpl-2.0 |
puppybane/linux-cyrus | net/rds/ib_rdma.c | 208 | 16602 | /*
* Copyright (c) 2006 Oracle. 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/kernel.h>
#include <linux/slab.h>
#include <linux/rculist.h>
#include <linux/llist.h>
#include "rds_single_path.h"
#include "ib_mr.h"
struct workqueue_struct *rds_ib_mr_wq;
static DEFINE_PER_CPU(unsigned long, clean_list_grace);
#define CLEAN_LIST_BUSY_BIT 0
static struct rds_ib_device *rds_ib_get_device(__be32 ipaddr)
{
struct rds_ib_device *rds_ibdev;
struct rds_ib_ipaddr *i_ipaddr;
rcu_read_lock();
list_for_each_entry_rcu(rds_ibdev, &rds_ib_devices, list) {
list_for_each_entry_rcu(i_ipaddr, &rds_ibdev->ipaddr_list, list) {
if (i_ipaddr->ipaddr == ipaddr) {
atomic_inc(&rds_ibdev->refcount);
rcu_read_unlock();
return rds_ibdev;
}
}
}
rcu_read_unlock();
return NULL;
}
static int rds_ib_add_ipaddr(struct rds_ib_device *rds_ibdev, __be32 ipaddr)
{
struct rds_ib_ipaddr *i_ipaddr;
i_ipaddr = kmalloc(sizeof *i_ipaddr, GFP_KERNEL);
if (!i_ipaddr)
return -ENOMEM;
i_ipaddr->ipaddr = ipaddr;
spin_lock_irq(&rds_ibdev->spinlock);
list_add_tail_rcu(&i_ipaddr->list, &rds_ibdev->ipaddr_list);
spin_unlock_irq(&rds_ibdev->spinlock);
return 0;
}
static void rds_ib_remove_ipaddr(struct rds_ib_device *rds_ibdev, __be32 ipaddr)
{
struct rds_ib_ipaddr *i_ipaddr;
struct rds_ib_ipaddr *to_free = NULL;
spin_lock_irq(&rds_ibdev->spinlock);
list_for_each_entry_rcu(i_ipaddr, &rds_ibdev->ipaddr_list, list) {
if (i_ipaddr->ipaddr == ipaddr) {
list_del_rcu(&i_ipaddr->list);
to_free = i_ipaddr;
break;
}
}
spin_unlock_irq(&rds_ibdev->spinlock);
if (to_free)
kfree_rcu(to_free, rcu);
}
int rds_ib_update_ipaddr(struct rds_ib_device *rds_ibdev, __be32 ipaddr)
{
struct rds_ib_device *rds_ibdev_old;
rds_ibdev_old = rds_ib_get_device(ipaddr);
if (!rds_ibdev_old)
return rds_ib_add_ipaddr(rds_ibdev, ipaddr);
if (rds_ibdev_old != rds_ibdev) {
rds_ib_remove_ipaddr(rds_ibdev_old, ipaddr);
rds_ib_dev_put(rds_ibdev_old);
return rds_ib_add_ipaddr(rds_ibdev, ipaddr);
}
rds_ib_dev_put(rds_ibdev_old);
return 0;
}
void rds_ib_add_conn(struct rds_ib_device *rds_ibdev, struct rds_connection *conn)
{
struct rds_ib_connection *ic = conn->c_transport_data;
/* conn was previously on the nodev_conns_list */
spin_lock_irq(&ib_nodev_conns_lock);
BUG_ON(list_empty(&ib_nodev_conns));
BUG_ON(list_empty(&ic->ib_node));
list_del(&ic->ib_node);
spin_lock(&rds_ibdev->spinlock);
list_add_tail(&ic->ib_node, &rds_ibdev->conn_list);
spin_unlock(&rds_ibdev->spinlock);
spin_unlock_irq(&ib_nodev_conns_lock);
ic->rds_ibdev = rds_ibdev;
atomic_inc(&rds_ibdev->refcount);
}
void rds_ib_remove_conn(struct rds_ib_device *rds_ibdev, struct rds_connection *conn)
{
struct rds_ib_connection *ic = conn->c_transport_data;
/* place conn on nodev_conns_list */
spin_lock(&ib_nodev_conns_lock);
spin_lock_irq(&rds_ibdev->spinlock);
BUG_ON(list_empty(&ic->ib_node));
list_del(&ic->ib_node);
spin_unlock_irq(&rds_ibdev->spinlock);
list_add_tail(&ic->ib_node, &ib_nodev_conns);
spin_unlock(&ib_nodev_conns_lock);
ic->rds_ibdev = NULL;
rds_ib_dev_put(rds_ibdev);
}
void rds_ib_destroy_nodev_conns(void)
{
struct rds_ib_connection *ic, *_ic;
LIST_HEAD(tmp_list);
/* avoid calling conn_destroy with irqs off */
spin_lock_irq(&ib_nodev_conns_lock);
list_splice(&ib_nodev_conns, &tmp_list);
spin_unlock_irq(&ib_nodev_conns_lock);
list_for_each_entry_safe(ic, _ic, &tmp_list, ib_node)
rds_conn_destroy(ic->conn);
}
void rds_ib_get_mr_info(struct rds_ib_device *rds_ibdev, struct rds_info_rdma_connection *iinfo)
{
struct rds_ib_mr_pool *pool_1m = rds_ibdev->mr_1m_pool;
iinfo->rdma_mr_max = pool_1m->max_items;
iinfo->rdma_mr_size = pool_1m->fmr_attr.max_pages;
}
struct rds_ib_mr *rds_ib_reuse_mr(struct rds_ib_mr_pool *pool)
{
struct rds_ib_mr *ibmr = NULL;
struct llist_node *ret;
unsigned long *flag;
preempt_disable();
flag = this_cpu_ptr(&clean_list_grace);
set_bit(CLEAN_LIST_BUSY_BIT, flag);
ret = llist_del_first(&pool->clean_list);
if (ret) {
ibmr = llist_entry(ret, struct rds_ib_mr, llnode);
if (pool->pool_type == RDS_IB_MR_8K_POOL)
rds_ib_stats_inc(s_ib_rdma_mr_8k_reused);
else
rds_ib_stats_inc(s_ib_rdma_mr_1m_reused);
}
clear_bit(CLEAN_LIST_BUSY_BIT, flag);
preempt_enable();
return ibmr;
}
static inline void wait_clean_list_grace(void)
{
int cpu;
unsigned long *flag;
for_each_online_cpu(cpu) {
flag = &per_cpu(clean_list_grace, cpu);
while (test_bit(CLEAN_LIST_BUSY_BIT, flag))
cpu_relax();
}
}
void rds_ib_sync_mr(void *trans_private, int direction)
{
struct rds_ib_mr *ibmr = trans_private;
struct rds_ib_device *rds_ibdev = ibmr->device;
switch (direction) {
case DMA_FROM_DEVICE:
ib_dma_sync_sg_for_cpu(rds_ibdev->dev, ibmr->sg,
ibmr->sg_dma_len, DMA_BIDIRECTIONAL);
break;
case DMA_TO_DEVICE:
ib_dma_sync_sg_for_device(rds_ibdev->dev, ibmr->sg,
ibmr->sg_dma_len, DMA_BIDIRECTIONAL);
break;
}
}
void __rds_ib_teardown_mr(struct rds_ib_mr *ibmr)
{
struct rds_ib_device *rds_ibdev = ibmr->device;
if (ibmr->sg_dma_len) {
ib_dma_unmap_sg(rds_ibdev->dev,
ibmr->sg, ibmr->sg_len,
DMA_BIDIRECTIONAL);
ibmr->sg_dma_len = 0;
}
/* Release the s/g list */
if (ibmr->sg_len) {
unsigned int i;
for (i = 0; i < ibmr->sg_len; ++i) {
struct page *page = sg_page(&ibmr->sg[i]);
/* FIXME we need a way to tell a r/w MR
* from a r/o MR */
WARN_ON(!page->mapping && irqs_disabled());
set_page_dirty(page);
put_page(page);
}
kfree(ibmr->sg);
ibmr->sg = NULL;
ibmr->sg_len = 0;
}
}
void rds_ib_teardown_mr(struct rds_ib_mr *ibmr)
{
unsigned int pinned = ibmr->sg_len;
__rds_ib_teardown_mr(ibmr);
if (pinned) {
struct rds_ib_mr_pool *pool = ibmr->pool;
atomic_sub(pinned, &pool->free_pinned);
}
}
static inline unsigned int rds_ib_flush_goal(struct rds_ib_mr_pool *pool, int free_all)
{
unsigned int item_count;
item_count = atomic_read(&pool->item_count);
if (free_all)
return item_count;
return 0;
}
/*
* given an llist of mrs, put them all into the list_head for more processing
*/
static unsigned int llist_append_to_list(struct llist_head *llist,
struct list_head *list)
{
struct rds_ib_mr *ibmr;
struct llist_node *node;
struct llist_node *next;
unsigned int count = 0;
node = llist_del_all(llist);
while (node) {
next = node->next;
ibmr = llist_entry(node, struct rds_ib_mr, llnode);
list_add_tail(&ibmr->unmap_list, list);
node = next;
count++;
}
return count;
}
/*
* this takes a list head of mrs and turns it into linked llist nodes
* of clusters. Each cluster has linked llist nodes of
* MR_CLUSTER_SIZE mrs that are ready for reuse.
*/
static void list_to_llist_nodes(struct rds_ib_mr_pool *pool,
struct list_head *list,
struct llist_node **nodes_head,
struct llist_node **nodes_tail)
{
struct rds_ib_mr *ibmr;
struct llist_node *cur = NULL;
struct llist_node **next = nodes_head;
list_for_each_entry(ibmr, list, unmap_list) {
cur = &ibmr->llnode;
*next = cur;
next = &cur->next;
}
*next = NULL;
*nodes_tail = cur;
}
/*
* Flush our pool of MRs.
* At a minimum, all currently unused MRs are unmapped.
* If the number of MRs allocated exceeds the limit, we also try
* to free as many MRs as needed to get back to this limit.
*/
int rds_ib_flush_mr_pool(struct rds_ib_mr_pool *pool,
int free_all, struct rds_ib_mr **ibmr_ret)
{
struct rds_ib_mr *ibmr;
struct llist_node *clean_nodes;
struct llist_node *clean_tail;
LIST_HEAD(unmap_list);
unsigned long unpinned = 0;
unsigned int nfreed = 0, dirty_to_clean = 0, free_goal;
if (pool->pool_type == RDS_IB_MR_8K_POOL)
rds_ib_stats_inc(s_ib_rdma_mr_8k_pool_flush);
else
rds_ib_stats_inc(s_ib_rdma_mr_1m_pool_flush);
if (ibmr_ret) {
DEFINE_WAIT(wait);
while (!mutex_trylock(&pool->flush_lock)) {
ibmr = rds_ib_reuse_mr(pool);
if (ibmr) {
*ibmr_ret = ibmr;
finish_wait(&pool->flush_wait, &wait);
goto out_nolock;
}
prepare_to_wait(&pool->flush_wait, &wait,
TASK_UNINTERRUPTIBLE);
if (llist_empty(&pool->clean_list))
schedule();
ibmr = rds_ib_reuse_mr(pool);
if (ibmr) {
*ibmr_ret = ibmr;
finish_wait(&pool->flush_wait, &wait);
goto out_nolock;
}
}
finish_wait(&pool->flush_wait, &wait);
} else
mutex_lock(&pool->flush_lock);
if (ibmr_ret) {
ibmr = rds_ib_reuse_mr(pool);
if (ibmr) {
*ibmr_ret = ibmr;
goto out;
}
}
/* Get the list of all MRs to be dropped. Ordering matters -
* we want to put drop_list ahead of free_list.
*/
dirty_to_clean = llist_append_to_list(&pool->drop_list, &unmap_list);
dirty_to_clean += llist_append_to_list(&pool->free_list, &unmap_list);
if (free_all)
llist_append_to_list(&pool->clean_list, &unmap_list);
free_goal = rds_ib_flush_goal(pool, free_all);
if (list_empty(&unmap_list))
goto out;
if (pool->use_fastreg)
rds_ib_unreg_frmr(&unmap_list, &nfreed, &unpinned, free_goal);
else
rds_ib_unreg_fmr(&unmap_list, &nfreed, &unpinned, free_goal);
if (!list_empty(&unmap_list)) {
/* we have to make sure that none of the things we're about
* to put on the clean list would race with other cpus trying
* to pull items off. The llist would explode if we managed to
* remove something from the clean list and then add it back again
* while another CPU was spinning on that same item in llist_del_first.
*
* This is pretty unlikely, but just in case wait for an llist grace period
* here before adding anything back into the clean list.
*/
wait_clean_list_grace();
list_to_llist_nodes(pool, &unmap_list, &clean_nodes, &clean_tail);
if (ibmr_ret)
*ibmr_ret = llist_entry(clean_nodes, struct rds_ib_mr, llnode);
/* more than one entry in llist nodes */
if (clean_nodes->next)
llist_add_batch(clean_nodes->next, clean_tail, &pool->clean_list);
}
atomic_sub(unpinned, &pool->free_pinned);
atomic_sub(dirty_to_clean, &pool->dirty_count);
atomic_sub(nfreed, &pool->item_count);
out:
mutex_unlock(&pool->flush_lock);
if (waitqueue_active(&pool->flush_wait))
wake_up(&pool->flush_wait);
out_nolock:
return 0;
}
struct rds_ib_mr *rds_ib_try_reuse_ibmr(struct rds_ib_mr_pool *pool)
{
struct rds_ib_mr *ibmr = NULL;
int iter = 0;
if (atomic_read(&pool->dirty_count) >= pool->max_items_soft / 10)
queue_delayed_work(rds_ib_mr_wq, &pool->flush_worker, 10);
while (1) {
ibmr = rds_ib_reuse_mr(pool);
if (ibmr)
return ibmr;
if (atomic_inc_return(&pool->item_count) <= pool->max_items)
break;
atomic_dec(&pool->item_count);
if (++iter > 2) {
if (pool->pool_type == RDS_IB_MR_8K_POOL)
rds_ib_stats_inc(s_ib_rdma_mr_8k_pool_depleted);
else
rds_ib_stats_inc(s_ib_rdma_mr_1m_pool_depleted);
return ERR_PTR(-EAGAIN);
}
/* We do have some empty MRs. Flush them out. */
if (pool->pool_type == RDS_IB_MR_8K_POOL)
rds_ib_stats_inc(s_ib_rdma_mr_8k_pool_wait);
else
rds_ib_stats_inc(s_ib_rdma_mr_1m_pool_wait);
rds_ib_flush_mr_pool(pool, 0, &ibmr);
if (ibmr)
return ibmr;
}
return ibmr;
}
static void rds_ib_mr_pool_flush_worker(struct work_struct *work)
{
struct rds_ib_mr_pool *pool = container_of(work, struct rds_ib_mr_pool, flush_worker.work);
rds_ib_flush_mr_pool(pool, 0, NULL);
}
void rds_ib_free_mr(void *trans_private, int invalidate)
{
struct rds_ib_mr *ibmr = trans_private;
struct rds_ib_mr_pool *pool = ibmr->pool;
struct rds_ib_device *rds_ibdev = ibmr->device;
rdsdebug("RDS/IB: free_mr nents %u\n", ibmr->sg_len);
/* Return it to the pool's free list */
if (rds_ibdev->use_fastreg)
rds_ib_free_frmr_list(ibmr);
else
rds_ib_free_fmr_list(ibmr);
atomic_add(ibmr->sg_len, &pool->free_pinned);
atomic_inc(&pool->dirty_count);
/* If we've pinned too many pages, request a flush */
if (atomic_read(&pool->free_pinned) >= pool->max_free_pinned ||
atomic_read(&pool->dirty_count) >= pool->max_items / 5)
queue_delayed_work(rds_ib_mr_wq, &pool->flush_worker, 10);
if (invalidate) {
if (likely(!in_interrupt())) {
rds_ib_flush_mr_pool(pool, 0, NULL);
} else {
/* We get here if the user created a MR marked
* as use_once and invalidate at the same time.
*/
queue_delayed_work(rds_ib_mr_wq,
&pool->flush_worker, 10);
}
}
rds_ib_dev_put(rds_ibdev);
}
void rds_ib_flush_mrs(void)
{
struct rds_ib_device *rds_ibdev;
down_read(&rds_ib_devices_lock);
list_for_each_entry(rds_ibdev, &rds_ib_devices, list) {
if (rds_ibdev->mr_8k_pool)
rds_ib_flush_mr_pool(rds_ibdev->mr_8k_pool, 0, NULL);
if (rds_ibdev->mr_1m_pool)
rds_ib_flush_mr_pool(rds_ibdev->mr_1m_pool, 0, NULL);
}
up_read(&rds_ib_devices_lock);
}
void *rds_ib_get_mr(struct scatterlist *sg, unsigned long nents,
struct rds_sock *rs, u32 *key_ret)
{
struct rds_ib_device *rds_ibdev;
struct rds_ib_mr *ibmr = NULL;
struct rds_ib_connection *ic = rs->rs_conn->c_transport_data;
int ret;
rds_ibdev = rds_ib_get_device(rs->rs_bound_addr);
if (!rds_ibdev) {
ret = -ENODEV;
goto out;
}
if (!rds_ibdev->mr_8k_pool || !rds_ibdev->mr_1m_pool) {
ret = -ENODEV;
goto out;
}
if (rds_ibdev->use_fastreg)
ibmr = rds_ib_reg_frmr(rds_ibdev, ic, sg, nents, key_ret);
else
ibmr = rds_ib_reg_fmr(rds_ibdev, sg, nents, key_ret);
if (ibmr)
rds_ibdev = NULL;
out:
if (!ibmr)
pr_warn("RDS/IB: rds_ib_get_mr failed (errno=%d)\n", ret);
if (rds_ibdev)
rds_ib_dev_put(rds_ibdev);
return ibmr;
}
void rds_ib_destroy_mr_pool(struct rds_ib_mr_pool *pool)
{
cancel_delayed_work_sync(&pool->flush_worker);
rds_ib_flush_mr_pool(pool, 1, NULL);
WARN_ON(atomic_read(&pool->item_count));
WARN_ON(atomic_read(&pool->free_pinned));
kfree(pool);
}
struct rds_ib_mr_pool *rds_ib_create_mr_pool(struct rds_ib_device *rds_ibdev,
int pool_type)
{
struct rds_ib_mr_pool *pool;
pool = kzalloc(sizeof(*pool), GFP_KERNEL);
if (!pool)
return ERR_PTR(-ENOMEM);
pool->pool_type = pool_type;
init_llist_head(&pool->free_list);
init_llist_head(&pool->drop_list);
init_llist_head(&pool->clean_list);
mutex_init(&pool->flush_lock);
init_waitqueue_head(&pool->flush_wait);
INIT_DELAYED_WORK(&pool->flush_worker, rds_ib_mr_pool_flush_worker);
if (pool_type == RDS_IB_MR_1M_POOL) {
/* +1 allows for unaligned MRs */
pool->fmr_attr.max_pages = RDS_MR_1M_MSG_SIZE + 1;
pool->max_items = RDS_MR_1M_POOL_SIZE;
} else {
/* pool_type == RDS_IB_MR_8K_POOL */
pool->fmr_attr.max_pages = RDS_MR_8K_MSG_SIZE + 1;
pool->max_items = RDS_MR_8K_POOL_SIZE;
}
pool->max_free_pinned = pool->max_items * pool->fmr_attr.max_pages / 4;
pool->fmr_attr.max_maps = rds_ibdev->fmr_max_remaps;
pool->fmr_attr.page_shift = PAGE_SHIFT;
pool->max_items_soft = rds_ibdev->max_mrs * 3 / 4;
pool->use_fastreg = rds_ibdev->use_fastreg;
return pool;
}
int rds_ib_mr_init(void)
{
rds_ib_mr_wq = alloc_workqueue("rds_mr_flushd", WQ_MEM_RECLAIM, 0);
if (!rds_ib_mr_wq)
return -ENOMEM;
return 0;
}
/* By the time this is called all the IB devices should have been torn down and
* had their pools freed. As each pool is freed its work struct is waited on,
* so the pool flushing work queue should be idle by the time we get here.
*/
void rds_ib_mr_exit(void)
{
destroy_workqueue(rds_ib_mr_wq);
}
| gpl-2.0 |
TheGreatSega/RUSH-KERNEL-RC | drivers/scsi/libfc/fc_exch.c | 464 | 53082 | /*
* Copyright(c) 2007 Intel Corporation. All rights reserved.
* Copyright(c) 2008 Red Hat, Inc. All rights reserved.
* Copyright(c) 2008 Mike Christie
*
* 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
*/
/*
* Fibre Channel exchange and sequence handling.
*/
#include <linux/timer.h>
#include <linux/gfp.h>
#include <linux/err.h>
#include <scsi/fc/fc_fc2.h>
#include <scsi/libfc.h>
#include <scsi/fc_encode.h>
u16 fc_cpu_mask; /* cpu mask for possible cpus */
EXPORT_SYMBOL(fc_cpu_mask);
static u16 fc_cpu_order; /* 2's power to represent total possible cpus */
static struct kmem_cache *fc_em_cachep; /* cache for exchanges */
/*
* Structure and function definitions for managing Fibre Channel Exchanges
* and Sequences.
*
* The three primary structures used here are fc_exch_mgr, fc_exch, and fc_seq.
*
* fc_exch_mgr holds the exchange state for an N port
*
* fc_exch holds state for one exchange and links to its active sequence.
*
* fc_seq holds the state for an individual sequence.
*/
/*
* Per cpu exchange pool
*
* This structure manages per cpu exchanges in array of exchange pointers.
* This array is allocated followed by struct fc_exch_pool memory for
* assigned range of exchanges to per cpu pool.
*/
struct fc_exch_pool {
u16 next_index; /* next possible free exchange index */
u16 total_exches; /* total allocated exchanges */
spinlock_t lock; /* exch pool lock */
struct list_head ex_list; /* allocated exchanges list */
};
/*
* Exchange manager.
*
* This structure is the center for creating exchanges and sequences.
* It manages the allocation of exchange IDs.
*/
struct fc_exch_mgr {
enum fc_class class; /* default class for sequences */
struct kref kref; /* exchange mgr reference count */
u16 min_xid; /* min exchange ID */
u16 max_xid; /* max exchange ID */
struct list_head ex_list; /* allocated exchanges list */
mempool_t *ep_pool; /* reserve ep's */
u16 pool_max_index; /* max exch array index in exch pool */
struct fc_exch_pool *pool; /* per cpu exch pool */
/*
* currently exchange mgr stats are updated but not used.
* either stats can be expose via sysfs or remove them
* all together if not used XXX
*/
struct {
atomic_t no_free_exch;
atomic_t no_free_exch_xid;
atomic_t xid_not_found;
atomic_t xid_busy;
atomic_t seq_not_found;
atomic_t non_bls_resp;
} stats;
};
#define fc_seq_exch(sp) container_of(sp, struct fc_exch, seq)
struct fc_exch_mgr_anchor {
struct list_head ema_list;
struct fc_exch_mgr *mp;
bool (*match)(struct fc_frame *);
};
static void fc_exch_rrq(struct fc_exch *);
static void fc_seq_ls_acc(struct fc_seq *);
static void fc_seq_ls_rjt(struct fc_seq *, enum fc_els_rjt_reason,
enum fc_els_rjt_explan);
static void fc_exch_els_rec(struct fc_seq *, struct fc_frame *);
static void fc_exch_els_rrq(struct fc_seq *, struct fc_frame *);
static struct fc_seq *fc_seq_start_next_locked(struct fc_seq *sp);
/*
* Internal implementation notes.
*
* The exchange manager is one by default in libfc but LLD may choose
* to have one per CPU. The sequence manager is one per exchange manager
* and currently never separated.
*
* Section 9.8 in FC-FS-2 specifies: "The SEQ_ID is a one-byte field
* assigned by the Sequence Initiator that shall be unique for a specific
* D_ID and S_ID pair while the Sequence is open." Note that it isn't
* qualified by exchange ID, which one might think it would be.
* In practice this limits the number of open sequences and exchanges to 256
* per session. For most targets we could treat this limit as per exchange.
*
* The exchange and its sequence are freed when the last sequence is received.
* It's possible for the remote port to leave an exchange open without
* sending any sequences.
*
* Notes on reference counts:
*
* Exchanges are reference counted and exchange gets freed when the reference
* count becomes zero.
*
* Timeouts:
* Sequences are timed out for E_D_TOV and R_A_TOV.
*
* Sequence event handling:
*
* The following events may occur on initiator sequences:
*
* Send.
* For now, the whole thing is sent.
* Receive ACK
* This applies only to class F.
* The sequence is marked complete.
* ULP completion.
* The upper layer calls fc_exch_done() when done
* with exchange and sequence tuple.
* RX-inferred completion.
* When we receive the next sequence on the same exchange, we can
* retire the previous sequence ID. (XXX not implemented).
* Timeout.
* R_A_TOV frees the sequence ID. If we're waiting for ACK,
* E_D_TOV causes abort and calls upper layer response handler
* with FC_EX_TIMEOUT error.
* Receive RJT
* XXX defer.
* Send ABTS
* On timeout.
*
* The following events may occur on recipient sequences:
*
* Receive
* Allocate sequence for first frame received.
* Hold during receive handler.
* Release when final frame received.
* Keep status of last N of these for the ELS RES command. XXX TBD.
* Receive ABTS
* Deallocate sequence
* Send RJT
* Deallocate
*
* For now, we neglect conditions where only part of a sequence was
* received or transmitted, or where out-of-order receipt is detected.
*/
/*
* Locking notes:
*
* The EM code run in a per-CPU worker thread.
*
* To protect against concurrency between a worker thread code and timers,
* sequence allocation and deallocation must be locked.
* - exchange refcnt can be done atomicly without locks.
* - sequence allocation must be locked by exch lock.
* - If the EM pool lock and ex_lock must be taken at the same time, then the
* EM pool lock must be taken before the ex_lock.
*/
/*
* opcode names for debugging.
*/
static char *fc_exch_rctl_names[] = FC_RCTL_NAMES_INIT;
#define FC_TABLE_SIZE(x) (sizeof(x) / sizeof(x[0]))
static inline const char *fc_exch_name_lookup(unsigned int op, char **table,
unsigned int max_index)
{
const char *name = NULL;
if (op < max_index)
name = table[op];
if (!name)
name = "unknown";
return name;
}
static const char *fc_exch_rctl_name(unsigned int op)
{
return fc_exch_name_lookup(op, fc_exch_rctl_names,
FC_TABLE_SIZE(fc_exch_rctl_names));
}
/*
* Hold an exchange - keep it from being freed.
*/
static void fc_exch_hold(struct fc_exch *ep)
{
atomic_inc(&ep->ex_refcnt);
}
/*
* setup fc hdr by initializing few more FC header fields and sof/eof.
* Initialized fields by this func:
* - fh_ox_id, fh_rx_id, fh_seq_id, fh_seq_cnt
* - sof and eof
*/
static void fc_exch_setup_hdr(struct fc_exch *ep, struct fc_frame *fp,
u32 f_ctl)
{
struct fc_frame_header *fh = fc_frame_header_get(fp);
u16 fill;
fr_sof(fp) = ep->class;
if (ep->seq.cnt)
fr_sof(fp) = fc_sof_normal(ep->class);
if (f_ctl & FC_FC_END_SEQ) {
fr_eof(fp) = FC_EOF_T;
if (fc_sof_needs_ack(ep->class))
fr_eof(fp) = FC_EOF_N;
/*
* Form f_ctl.
* The number of fill bytes to make the length a 4-byte
* multiple is the low order 2-bits of the f_ctl.
* The fill itself will have been cleared by the frame
* allocation.
* After this, the length will be even, as expected by
* the transport.
*/
fill = fr_len(fp) & 3;
if (fill) {
fill = 4 - fill;
/* TODO, this may be a problem with fragmented skb */
skb_put(fp_skb(fp), fill);
hton24(fh->fh_f_ctl, f_ctl | fill);
}
} else {
WARN_ON(fr_len(fp) % 4 != 0); /* no pad to non last frame */
fr_eof(fp) = FC_EOF_N;
}
/*
* Initialize remainig fh fields
* from fc_fill_fc_hdr
*/
fh->fh_ox_id = htons(ep->oxid);
fh->fh_rx_id = htons(ep->rxid);
fh->fh_seq_id = ep->seq.id;
fh->fh_seq_cnt = htons(ep->seq.cnt);
}
/*
* Release a reference to an exchange.
* If the refcnt goes to zero and the exchange is complete, it is freed.
*/
static void fc_exch_release(struct fc_exch *ep)
{
struct fc_exch_mgr *mp;
if (atomic_dec_and_test(&ep->ex_refcnt)) {
mp = ep->em;
if (ep->destructor)
ep->destructor(&ep->seq, ep->arg);
WARN_ON(!(ep->esb_stat & ESB_ST_COMPLETE));
mempool_free(ep, mp->ep_pool);
}
}
static int fc_exch_done_locked(struct fc_exch *ep)
{
int rc = 1;
/*
* We must check for completion in case there are two threads
* tyring to complete this. But the rrq code will reuse the
* ep, and in that case we only clear the resp and set it as
* complete, so it can be reused by the timer to send the rrq.
*/
ep->resp = NULL;
if (ep->state & FC_EX_DONE)
return rc;
ep->esb_stat |= ESB_ST_COMPLETE;
if (!(ep->esb_stat & ESB_ST_REC_QUAL)) {
ep->state |= FC_EX_DONE;
if (cancel_delayed_work(&ep->timeout_work))
atomic_dec(&ep->ex_refcnt); /* drop hold for timer */
rc = 0;
}
return rc;
}
static inline struct fc_exch *fc_exch_ptr_get(struct fc_exch_pool *pool,
u16 index)
{
struct fc_exch **exches = (struct fc_exch **)(pool + 1);
return exches[index];
}
static inline void fc_exch_ptr_set(struct fc_exch_pool *pool, u16 index,
struct fc_exch *ep)
{
((struct fc_exch **)(pool + 1))[index] = ep;
}
static void fc_exch_delete(struct fc_exch *ep)
{
struct fc_exch_pool *pool;
pool = ep->pool;
spin_lock_bh(&pool->lock);
WARN_ON(pool->total_exches <= 0);
pool->total_exches--;
fc_exch_ptr_set(pool, (ep->xid - ep->em->min_xid) >> fc_cpu_order,
NULL);
list_del(&ep->ex_list);
spin_unlock_bh(&pool->lock);
fc_exch_release(ep); /* drop hold for exch in mp */
}
/*
* Internal version of fc_exch_timer_set - used with lock held.
*/
static inline void fc_exch_timer_set_locked(struct fc_exch *ep,
unsigned int timer_msec)
{
if (ep->state & (FC_EX_RST_CLEANUP | FC_EX_DONE))
return;
FC_EXCH_DBG(ep, "Exchange timer armed\n");
if (schedule_delayed_work(&ep->timeout_work,
msecs_to_jiffies(timer_msec)))
fc_exch_hold(ep); /* hold for timer */
}
/*
* Set timer for an exchange.
* The time is a minimum delay in milliseconds until the timer fires.
* Used for upper level protocols to time out the exchange.
* The timer is cancelled when it fires or when the exchange completes.
* Returns non-zero if a timer couldn't be allocated.
*/
static void fc_exch_timer_set(struct fc_exch *ep, unsigned int timer_msec)
{
spin_lock_bh(&ep->ex_lock);
fc_exch_timer_set_locked(ep, timer_msec);
spin_unlock_bh(&ep->ex_lock);
}
int fc_seq_exch_abort(const struct fc_seq *req_sp, unsigned int timer_msec)
{
struct fc_seq *sp;
struct fc_exch *ep;
struct fc_frame *fp;
int error;
ep = fc_seq_exch(req_sp);
spin_lock_bh(&ep->ex_lock);
if (ep->esb_stat & (ESB_ST_COMPLETE | ESB_ST_ABNORMAL) ||
ep->state & (FC_EX_DONE | FC_EX_RST_CLEANUP)) {
spin_unlock_bh(&ep->ex_lock);
return -ENXIO;
}
/*
* Send the abort on a new sequence if possible.
*/
sp = fc_seq_start_next_locked(&ep->seq);
if (!sp) {
spin_unlock_bh(&ep->ex_lock);
return -ENOMEM;
}
ep->esb_stat |= ESB_ST_SEQ_INIT | ESB_ST_ABNORMAL;
if (timer_msec)
fc_exch_timer_set_locked(ep, timer_msec);
spin_unlock_bh(&ep->ex_lock);
/*
* If not logged into the fabric, don't send ABTS but leave
* sequence active until next timeout.
*/
if (!ep->sid)
return 0;
/*
* Send an abort for the sequence that timed out.
*/
fp = fc_frame_alloc(ep->lp, 0);
if (fp) {
fc_fill_fc_hdr(fp, FC_RCTL_BA_ABTS, ep->did, ep->sid,
FC_TYPE_BLS, FC_FC_END_SEQ | FC_FC_SEQ_INIT, 0);
error = fc_seq_send(ep->lp, sp, fp);
} else
error = -ENOBUFS;
return error;
}
EXPORT_SYMBOL(fc_seq_exch_abort);
/*
* Exchange timeout - handle exchange timer expiration.
* The timer will have been cancelled before this is called.
*/
static void fc_exch_timeout(struct work_struct *work)
{
struct fc_exch *ep = container_of(work, struct fc_exch,
timeout_work.work);
struct fc_seq *sp = &ep->seq;
void (*resp)(struct fc_seq *, struct fc_frame *fp, void *arg);
void *arg;
u32 e_stat;
int rc = 1;
FC_EXCH_DBG(ep, "Exchange timed out\n");
spin_lock_bh(&ep->ex_lock);
if (ep->state & (FC_EX_RST_CLEANUP | FC_EX_DONE))
goto unlock;
e_stat = ep->esb_stat;
if (e_stat & ESB_ST_COMPLETE) {
ep->esb_stat = e_stat & ~ESB_ST_REC_QUAL;
spin_unlock_bh(&ep->ex_lock);
if (e_stat & ESB_ST_REC_QUAL)
fc_exch_rrq(ep);
goto done;
} else {
resp = ep->resp;
arg = ep->arg;
ep->resp = NULL;
if (e_stat & ESB_ST_ABNORMAL)
rc = fc_exch_done_locked(ep);
spin_unlock_bh(&ep->ex_lock);
if (!rc)
fc_exch_delete(ep);
if (resp)
resp(sp, ERR_PTR(-FC_EX_TIMEOUT), arg);
fc_seq_exch_abort(sp, 2 * ep->r_a_tov);
goto done;
}
unlock:
spin_unlock_bh(&ep->ex_lock);
done:
/*
* This release matches the hold taken when the timer was set.
*/
fc_exch_release(ep);
}
/*
* Allocate a sequence.
*
* We don't support multiple originated sequences on the same exchange.
* By implication, any previously originated sequence on this exchange
* is complete, and we reallocate the same sequence.
*/
static struct fc_seq *fc_seq_alloc(struct fc_exch *ep, u8 seq_id)
{
struct fc_seq *sp;
sp = &ep->seq;
sp->ssb_stat = 0;
sp->cnt = 0;
sp->id = seq_id;
return sp;
}
/**
* fc_exch_em_alloc() - allocate an exchange from a specified EM.
* @lport: ptr to the local port
* @mp: ptr to the exchange manager
*
* Returns pointer to allocated fc_exch with exch lock held.
*/
static struct fc_exch *fc_exch_em_alloc(struct fc_lport *lport,
struct fc_exch_mgr *mp)
{
struct fc_exch *ep;
unsigned int cpu;
u16 index;
struct fc_exch_pool *pool;
/* allocate memory for exchange */
ep = mempool_alloc(mp->ep_pool, GFP_ATOMIC);
if (!ep) {
atomic_inc(&mp->stats.no_free_exch);
goto out;
}
memset(ep, 0, sizeof(*ep));
cpu = smp_processor_id();
pool = per_cpu_ptr(mp->pool, cpu);
spin_lock_bh(&pool->lock);
index = pool->next_index;
/* allocate new exch from pool */
while (fc_exch_ptr_get(pool, index)) {
index = index == mp->pool_max_index ? 0 : index + 1;
if (index == pool->next_index)
goto err;
}
pool->next_index = index == mp->pool_max_index ? 0 : index + 1;
fc_exch_hold(ep); /* hold for exch in mp */
spin_lock_init(&ep->ex_lock);
/*
* Hold exch lock for caller to prevent fc_exch_reset()
* from releasing exch while fc_exch_alloc() caller is
* still working on exch.
*/
spin_lock_bh(&ep->ex_lock);
fc_exch_ptr_set(pool, index, ep);
list_add_tail(&ep->ex_list, &pool->ex_list);
fc_seq_alloc(ep, ep->seq_id++);
pool->total_exches++;
spin_unlock_bh(&pool->lock);
/*
* update exchange
*/
ep->oxid = ep->xid = (index << fc_cpu_order | cpu) + mp->min_xid;
ep->em = mp;
ep->pool = pool;
ep->lp = lport;
ep->f_ctl = FC_FC_FIRST_SEQ; /* next seq is first seq */
ep->rxid = FC_XID_UNKNOWN;
ep->class = mp->class;
INIT_DELAYED_WORK(&ep->timeout_work, fc_exch_timeout);
out:
return ep;
err:
spin_unlock_bh(&pool->lock);
atomic_inc(&mp->stats.no_free_exch_xid);
mempool_free(ep, mp->ep_pool);
return NULL;
}
/**
* fc_exch_alloc() - allocate an exchange.
* @lport: ptr to the local port
* @fp: ptr to the FC frame
*
* This function walks the list of the exchange manager(EM)
* anchors to select a EM for new exchange allocation. The
* EM is selected having either a NULL match function pointer
* or call to match function returning true.
*/
struct fc_exch *fc_exch_alloc(struct fc_lport *lport, struct fc_frame *fp)
{
struct fc_exch_mgr_anchor *ema;
struct fc_exch *ep;
list_for_each_entry(ema, &lport->ema_list, ema_list) {
if (!ema->match || ema->match(fp)) {
ep = fc_exch_em_alloc(lport, ema->mp);
if (ep)
return ep;
}
}
return NULL;
}
EXPORT_SYMBOL(fc_exch_alloc);
/*
* Lookup and hold an exchange.
*/
static struct fc_exch *fc_exch_find(struct fc_exch_mgr *mp, u16 xid)
{
struct fc_exch_pool *pool;
struct fc_exch *ep = NULL;
if ((xid >= mp->min_xid) && (xid <= mp->max_xid)) {
pool = per_cpu_ptr(mp->pool, xid & fc_cpu_mask);
spin_lock_bh(&pool->lock);
ep = fc_exch_ptr_get(pool, (xid - mp->min_xid) >> fc_cpu_order);
if (ep) {
fc_exch_hold(ep);
WARN_ON(ep->xid != xid);
}
spin_unlock_bh(&pool->lock);
}
return ep;
}
void fc_exch_done(struct fc_seq *sp)
{
struct fc_exch *ep = fc_seq_exch(sp);
int rc;
spin_lock_bh(&ep->ex_lock);
rc = fc_exch_done_locked(ep);
spin_unlock_bh(&ep->ex_lock);
if (!rc)
fc_exch_delete(ep);
}
EXPORT_SYMBOL(fc_exch_done);
/*
* Allocate a new exchange as responder.
* Sets the responder ID in the frame header.
*/
static struct fc_exch *fc_exch_resp(struct fc_lport *lport,
struct fc_exch_mgr *mp,
struct fc_frame *fp)
{
struct fc_exch *ep;
struct fc_frame_header *fh;
ep = fc_exch_alloc(lport, fp);
if (ep) {
ep->class = fc_frame_class(fp);
/*
* Set EX_CTX indicating we're responding on this exchange.
*/
ep->f_ctl |= FC_FC_EX_CTX; /* we're responding */
ep->f_ctl &= ~FC_FC_FIRST_SEQ; /* not new */
fh = fc_frame_header_get(fp);
ep->sid = ntoh24(fh->fh_d_id);
ep->did = ntoh24(fh->fh_s_id);
ep->oid = ep->did;
/*
* Allocated exchange has placed the XID in the
* originator field. Move it to the responder field,
* and set the originator XID from the frame.
*/
ep->rxid = ep->xid;
ep->oxid = ntohs(fh->fh_ox_id);
ep->esb_stat |= ESB_ST_RESP | ESB_ST_SEQ_INIT;
if ((ntoh24(fh->fh_f_ctl) & FC_FC_SEQ_INIT) == 0)
ep->esb_stat &= ~ESB_ST_SEQ_INIT;
fc_exch_hold(ep); /* hold for caller */
spin_unlock_bh(&ep->ex_lock); /* lock from fc_exch_alloc */
}
return ep;
}
/*
* Find a sequence for receive where the other end is originating the sequence.
* If fc_pf_rjt_reason is FC_RJT_NONE then this function will have a hold
* on the ep that should be released by the caller.
*/
static enum fc_pf_rjt_reason fc_seq_lookup_recip(struct fc_lport *lport,
struct fc_exch_mgr *mp,
struct fc_frame *fp)
{
struct fc_frame_header *fh = fc_frame_header_get(fp);
struct fc_exch *ep = NULL;
struct fc_seq *sp = NULL;
enum fc_pf_rjt_reason reject = FC_RJT_NONE;
u32 f_ctl;
u16 xid;
f_ctl = ntoh24(fh->fh_f_ctl);
WARN_ON((f_ctl & FC_FC_SEQ_CTX) != 0);
/*
* Lookup or create the exchange if we will be creating the sequence.
*/
if (f_ctl & FC_FC_EX_CTX) {
xid = ntohs(fh->fh_ox_id); /* we originated exch */
ep = fc_exch_find(mp, xid);
if (!ep) {
atomic_inc(&mp->stats.xid_not_found);
reject = FC_RJT_OX_ID;
goto out;
}
if (ep->rxid == FC_XID_UNKNOWN)
ep->rxid = ntohs(fh->fh_rx_id);
else if (ep->rxid != ntohs(fh->fh_rx_id)) {
reject = FC_RJT_OX_ID;
goto rel;
}
} else {
xid = ntohs(fh->fh_rx_id); /* we are the responder */
/*
* Special case for MDS issuing an ELS TEST with a
* bad rxid of 0.
* XXX take this out once we do the proper reject.
*/
if (xid == 0 && fh->fh_r_ctl == FC_RCTL_ELS_REQ &&
fc_frame_payload_op(fp) == ELS_TEST) {
fh->fh_rx_id = htons(FC_XID_UNKNOWN);
xid = FC_XID_UNKNOWN;
}
/*
* new sequence - find the exchange
*/
ep = fc_exch_find(mp, xid);
if ((f_ctl & FC_FC_FIRST_SEQ) && fc_sof_is_init(fr_sof(fp))) {
if (ep) {
atomic_inc(&mp->stats.xid_busy);
reject = FC_RJT_RX_ID;
goto rel;
}
ep = fc_exch_resp(lport, mp, fp);
if (!ep) {
reject = FC_RJT_EXCH_EST; /* XXX */
goto out;
}
xid = ep->xid; /* get our XID */
} else if (!ep) {
atomic_inc(&mp->stats.xid_not_found);
reject = FC_RJT_RX_ID; /* XID not found */
goto out;
}
}
/*
* At this point, we have the exchange held.
* Find or create the sequence.
*/
if (fc_sof_is_init(fr_sof(fp))) {
sp = fc_seq_start_next(&ep->seq);
if (!sp) {
reject = FC_RJT_SEQ_XS; /* exchange shortage */
goto rel;
}
sp->id = fh->fh_seq_id;
sp->ssb_stat |= SSB_ST_RESP;
} else {
sp = &ep->seq;
if (sp->id != fh->fh_seq_id) {
atomic_inc(&mp->stats.seq_not_found);
reject = FC_RJT_SEQ_ID; /* sequence/exch should exist */
goto rel;
}
}
WARN_ON(ep != fc_seq_exch(sp));
if (f_ctl & FC_FC_SEQ_INIT)
ep->esb_stat |= ESB_ST_SEQ_INIT;
fr_seq(fp) = sp;
out:
return reject;
rel:
fc_exch_done(&ep->seq);
fc_exch_release(ep); /* hold from fc_exch_find/fc_exch_resp */
return reject;
}
/*
* Find the sequence for a frame being received.
* We originated the sequence, so it should be found.
* We may or may not have originated the exchange.
* Does not hold the sequence for the caller.
*/
static struct fc_seq *fc_seq_lookup_orig(struct fc_exch_mgr *mp,
struct fc_frame *fp)
{
struct fc_frame_header *fh = fc_frame_header_get(fp);
struct fc_exch *ep;
struct fc_seq *sp = NULL;
u32 f_ctl;
u16 xid;
f_ctl = ntoh24(fh->fh_f_ctl);
WARN_ON((f_ctl & FC_FC_SEQ_CTX) != FC_FC_SEQ_CTX);
xid = ntohs((f_ctl & FC_FC_EX_CTX) ? fh->fh_ox_id : fh->fh_rx_id);
ep = fc_exch_find(mp, xid);
if (!ep)
return NULL;
if (ep->seq.id == fh->fh_seq_id) {
/*
* Save the RX_ID if we didn't previously know it.
*/
sp = &ep->seq;
if ((f_ctl & FC_FC_EX_CTX) != 0 &&
ep->rxid == FC_XID_UNKNOWN) {
ep->rxid = ntohs(fh->fh_rx_id);
}
}
fc_exch_release(ep);
return sp;
}
/*
* Set addresses for an exchange.
* Note this must be done before the first sequence of the exchange is sent.
*/
static void fc_exch_set_addr(struct fc_exch *ep,
u32 orig_id, u32 resp_id)
{
ep->oid = orig_id;
if (ep->esb_stat & ESB_ST_RESP) {
ep->sid = resp_id;
ep->did = orig_id;
} else {
ep->sid = orig_id;
ep->did = resp_id;
}
}
static struct fc_seq *fc_seq_start_next_locked(struct fc_seq *sp)
{
struct fc_exch *ep = fc_seq_exch(sp);
sp = fc_seq_alloc(ep, ep->seq_id++);
FC_EXCH_DBG(ep, "f_ctl %6x seq %2x\n",
ep->f_ctl, sp->id);
return sp;
}
/*
* Allocate a new sequence on the same exchange as the supplied sequence.
* This will never return NULL.
*/
struct fc_seq *fc_seq_start_next(struct fc_seq *sp)
{
struct fc_exch *ep = fc_seq_exch(sp);
spin_lock_bh(&ep->ex_lock);
sp = fc_seq_start_next_locked(sp);
spin_unlock_bh(&ep->ex_lock);
return sp;
}
EXPORT_SYMBOL(fc_seq_start_next);
int fc_seq_send(struct fc_lport *lp, struct fc_seq *sp, struct fc_frame *fp)
{
struct fc_exch *ep;
struct fc_frame_header *fh = fc_frame_header_get(fp);
int error;
u32 f_ctl;
ep = fc_seq_exch(sp);
WARN_ON((ep->esb_stat & ESB_ST_SEQ_INIT) != ESB_ST_SEQ_INIT);
f_ctl = ntoh24(fh->fh_f_ctl);
fc_exch_setup_hdr(ep, fp, f_ctl);
/*
* update sequence count if this frame is carrying
* multiple FC frames when sequence offload is enabled
* by LLD.
*/
if (fr_max_payload(fp))
sp->cnt += DIV_ROUND_UP((fr_len(fp) - sizeof(*fh)),
fr_max_payload(fp));
else
sp->cnt++;
/*
* Send the frame.
*/
error = lp->tt.frame_send(lp, fp);
/*
* Update the exchange and sequence flags,
* assuming all frames for the sequence have been sent.
* We can only be called to send once for each sequence.
*/
spin_lock_bh(&ep->ex_lock);
ep->f_ctl = f_ctl & ~FC_FC_FIRST_SEQ; /* not first seq */
if (f_ctl & (FC_FC_END_SEQ | FC_FC_SEQ_INIT))
ep->esb_stat &= ~ESB_ST_SEQ_INIT;
spin_unlock_bh(&ep->ex_lock);
return error;
}
EXPORT_SYMBOL(fc_seq_send);
void fc_seq_els_rsp_send(struct fc_seq *sp, enum fc_els_cmd els_cmd,
struct fc_seq_els_data *els_data)
{
switch (els_cmd) {
case ELS_LS_RJT:
fc_seq_ls_rjt(sp, els_data->reason, els_data->explan);
break;
case ELS_LS_ACC:
fc_seq_ls_acc(sp);
break;
case ELS_RRQ:
fc_exch_els_rrq(sp, els_data->fp);
break;
case ELS_REC:
fc_exch_els_rec(sp, els_data->fp);
break;
default:
FC_EXCH_DBG(fc_seq_exch(sp), "Invalid ELS CMD:%x\n", els_cmd);
}
}
EXPORT_SYMBOL(fc_seq_els_rsp_send);
/*
* Send a sequence, which is also the last sequence in the exchange.
*/
static void fc_seq_send_last(struct fc_seq *sp, struct fc_frame *fp,
enum fc_rctl rctl, enum fc_fh_type fh_type)
{
u32 f_ctl;
struct fc_exch *ep = fc_seq_exch(sp);
f_ctl = FC_FC_LAST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT;
f_ctl |= ep->f_ctl;
fc_fill_fc_hdr(fp, rctl, ep->did, ep->sid, fh_type, f_ctl, 0);
fc_seq_send(ep->lp, sp, fp);
}
/*
* Send ACK_1 (or equiv.) indicating we received something.
* The frame we're acking is supplied.
*/
static void fc_seq_send_ack(struct fc_seq *sp, const struct fc_frame *rx_fp)
{
struct fc_frame *fp;
struct fc_frame_header *rx_fh;
struct fc_frame_header *fh;
struct fc_exch *ep = fc_seq_exch(sp);
struct fc_lport *lp = ep->lp;
unsigned int f_ctl;
/*
* Don't send ACKs for class 3.
*/
if (fc_sof_needs_ack(fr_sof(rx_fp))) {
fp = fc_frame_alloc(lp, 0);
if (!fp)
return;
fh = fc_frame_header_get(fp);
fh->fh_r_ctl = FC_RCTL_ACK_1;
fh->fh_type = FC_TYPE_BLS;
/*
* Form f_ctl by inverting EX_CTX and SEQ_CTX (bits 23, 22).
* Echo FIRST_SEQ, LAST_SEQ, END_SEQ, END_CONN, SEQ_INIT.
* Bits 9-8 are meaningful (retransmitted or unidirectional).
* Last ACK uses bits 7-6 (continue sequence),
* bits 5-4 are meaningful (what kind of ACK to use).
*/
rx_fh = fc_frame_header_get(rx_fp);
f_ctl = ntoh24(rx_fh->fh_f_ctl);
f_ctl &= FC_FC_EX_CTX | FC_FC_SEQ_CTX |
FC_FC_FIRST_SEQ | FC_FC_LAST_SEQ |
FC_FC_END_SEQ | FC_FC_END_CONN | FC_FC_SEQ_INIT |
FC_FC_RETX_SEQ | FC_FC_UNI_TX;
f_ctl ^= FC_FC_EX_CTX | FC_FC_SEQ_CTX;
hton24(fh->fh_f_ctl, f_ctl);
fc_exch_setup_hdr(ep, fp, f_ctl);
fh->fh_seq_id = rx_fh->fh_seq_id;
fh->fh_seq_cnt = rx_fh->fh_seq_cnt;
fh->fh_parm_offset = htonl(1); /* ack single frame */
fr_sof(fp) = fr_sof(rx_fp);
if (f_ctl & FC_FC_END_SEQ)
fr_eof(fp) = FC_EOF_T;
else
fr_eof(fp) = FC_EOF_N;
(void) lp->tt.frame_send(lp, fp);
}
}
/*
* Send BLS Reject.
* This is for rejecting BA_ABTS only.
*/
static void fc_exch_send_ba_rjt(struct fc_frame *rx_fp,
enum fc_ba_rjt_reason reason,
enum fc_ba_rjt_explan explan)
{
struct fc_frame *fp;
struct fc_frame_header *rx_fh;
struct fc_frame_header *fh;
struct fc_ba_rjt *rp;
struct fc_lport *lp;
unsigned int f_ctl;
lp = fr_dev(rx_fp);
fp = fc_frame_alloc(lp, sizeof(*rp));
if (!fp)
return;
fh = fc_frame_header_get(fp);
rx_fh = fc_frame_header_get(rx_fp);
memset(fh, 0, sizeof(*fh) + sizeof(*rp));
rp = fc_frame_payload_get(fp, sizeof(*rp));
rp->br_reason = reason;
rp->br_explan = explan;
/*
* seq_id, cs_ctl, df_ctl and param/offset are zero.
*/
memcpy(fh->fh_s_id, rx_fh->fh_d_id, 3);
memcpy(fh->fh_d_id, rx_fh->fh_s_id, 3);
fh->fh_ox_id = rx_fh->fh_ox_id;
fh->fh_rx_id = rx_fh->fh_rx_id;
fh->fh_seq_cnt = rx_fh->fh_seq_cnt;
fh->fh_r_ctl = FC_RCTL_BA_RJT;
fh->fh_type = FC_TYPE_BLS;
/*
* Form f_ctl by inverting EX_CTX and SEQ_CTX (bits 23, 22).
* Echo FIRST_SEQ, LAST_SEQ, END_SEQ, END_CONN, SEQ_INIT.
* Bits 9-8 are meaningful (retransmitted or unidirectional).
* Last ACK uses bits 7-6 (continue sequence),
* bits 5-4 are meaningful (what kind of ACK to use).
* Always set LAST_SEQ, END_SEQ.
*/
f_ctl = ntoh24(rx_fh->fh_f_ctl);
f_ctl &= FC_FC_EX_CTX | FC_FC_SEQ_CTX |
FC_FC_END_CONN | FC_FC_SEQ_INIT |
FC_FC_RETX_SEQ | FC_FC_UNI_TX;
f_ctl ^= FC_FC_EX_CTX | FC_FC_SEQ_CTX;
f_ctl |= FC_FC_LAST_SEQ | FC_FC_END_SEQ;
f_ctl &= ~FC_FC_FIRST_SEQ;
hton24(fh->fh_f_ctl, f_ctl);
fr_sof(fp) = fc_sof_class(fr_sof(rx_fp));
fr_eof(fp) = FC_EOF_T;
if (fc_sof_needs_ack(fr_sof(fp)))
fr_eof(fp) = FC_EOF_N;
(void) lp->tt.frame_send(lp, fp);
}
/*
* Handle an incoming ABTS. This would be for target mode usually,
* but could be due to lost FCP transfer ready, confirm or RRQ.
* We always handle this as an exchange abort, ignoring the parameter.
*/
static void fc_exch_recv_abts(struct fc_exch *ep, struct fc_frame *rx_fp)
{
struct fc_frame *fp;
struct fc_ba_acc *ap;
struct fc_frame_header *fh;
struct fc_seq *sp;
if (!ep)
goto reject;
spin_lock_bh(&ep->ex_lock);
if (ep->esb_stat & ESB_ST_COMPLETE) {
spin_unlock_bh(&ep->ex_lock);
goto reject;
}
if (!(ep->esb_stat & ESB_ST_REC_QUAL))
fc_exch_hold(ep); /* hold for REC_QUAL */
ep->esb_stat |= ESB_ST_ABNORMAL | ESB_ST_REC_QUAL;
fc_exch_timer_set_locked(ep, ep->r_a_tov);
fp = fc_frame_alloc(ep->lp, sizeof(*ap));
if (!fp) {
spin_unlock_bh(&ep->ex_lock);
goto free;
}
fh = fc_frame_header_get(fp);
ap = fc_frame_payload_get(fp, sizeof(*ap));
memset(ap, 0, sizeof(*ap));
sp = &ep->seq;
ap->ba_high_seq_cnt = htons(0xffff);
if (sp->ssb_stat & SSB_ST_RESP) {
ap->ba_seq_id = sp->id;
ap->ba_seq_id_val = FC_BA_SEQ_ID_VAL;
ap->ba_high_seq_cnt = fh->fh_seq_cnt;
ap->ba_low_seq_cnt = htons(sp->cnt);
}
sp = fc_seq_start_next_locked(sp);
spin_unlock_bh(&ep->ex_lock);
fc_seq_send_last(sp, fp, FC_RCTL_BA_ACC, FC_TYPE_BLS);
fc_frame_free(rx_fp);
return;
reject:
fc_exch_send_ba_rjt(rx_fp, FC_BA_RJT_UNABLE, FC_BA_RJT_INV_XID);
free:
fc_frame_free(rx_fp);
}
/*
* Handle receive where the other end is originating the sequence.
*/
static void fc_exch_recv_req(struct fc_lport *lp, struct fc_exch_mgr *mp,
struct fc_frame *fp)
{
struct fc_frame_header *fh = fc_frame_header_get(fp);
struct fc_seq *sp = NULL;
struct fc_exch *ep = NULL;
enum fc_sof sof;
enum fc_eof eof;
u32 f_ctl;
enum fc_pf_rjt_reason reject;
fr_seq(fp) = NULL;
reject = fc_seq_lookup_recip(lp, mp, fp);
if (reject == FC_RJT_NONE) {
sp = fr_seq(fp); /* sequence will be held */
ep = fc_seq_exch(sp);
sof = fr_sof(fp);
eof = fr_eof(fp);
f_ctl = ntoh24(fh->fh_f_ctl);
fc_seq_send_ack(sp, fp);
/*
* Call the receive function.
*
* The receive function may allocate a new sequence
* over the old one, so we shouldn't change the
* sequence after this.
*
* The frame will be freed by the receive function.
* If new exch resp handler is valid then call that
* first.
*/
if (ep->resp)
ep->resp(sp, fp, ep->arg);
else
lp->tt.lport_recv(lp, sp, fp);
fc_exch_release(ep); /* release from lookup */
} else {
FC_LPORT_DBG(lp, "exch/seq lookup failed: reject %x\n", reject);
fc_frame_free(fp);
}
}
/*
* Handle receive where the other end is originating the sequence in
* response to our exchange.
*/
static void fc_exch_recv_seq_resp(struct fc_exch_mgr *mp, struct fc_frame *fp)
{
struct fc_frame_header *fh = fc_frame_header_get(fp);
struct fc_seq *sp;
struct fc_exch *ep;
enum fc_sof sof;
u32 f_ctl;
void (*resp)(struct fc_seq *, struct fc_frame *fp, void *arg);
void *ex_resp_arg;
int rc;
ep = fc_exch_find(mp, ntohs(fh->fh_ox_id));
if (!ep) {
atomic_inc(&mp->stats.xid_not_found);
goto out;
}
if (ep->esb_stat & ESB_ST_COMPLETE) {
atomic_inc(&mp->stats.xid_not_found);
goto out;
}
if (ep->rxid == FC_XID_UNKNOWN)
ep->rxid = ntohs(fh->fh_rx_id);
if (ep->sid != 0 && ep->sid != ntoh24(fh->fh_d_id)) {
atomic_inc(&mp->stats.xid_not_found);
goto rel;
}
if (ep->did != ntoh24(fh->fh_s_id) &&
ep->did != FC_FID_FLOGI) {
atomic_inc(&mp->stats.xid_not_found);
goto rel;
}
sof = fr_sof(fp);
if (fc_sof_is_init(sof)) {
sp = fc_seq_start_next(&ep->seq);
sp->id = fh->fh_seq_id;
sp->ssb_stat |= SSB_ST_RESP;
} else {
sp = &ep->seq;
if (sp->id != fh->fh_seq_id) {
atomic_inc(&mp->stats.seq_not_found);
goto rel;
}
}
f_ctl = ntoh24(fh->fh_f_ctl);
fr_seq(fp) = sp;
if (f_ctl & FC_FC_SEQ_INIT)
ep->esb_stat |= ESB_ST_SEQ_INIT;
if (fc_sof_needs_ack(sof))
fc_seq_send_ack(sp, fp);
resp = ep->resp;
ex_resp_arg = ep->arg;
if (fh->fh_type != FC_TYPE_FCP && fr_eof(fp) == FC_EOF_T &&
(f_ctl & (FC_FC_LAST_SEQ | FC_FC_END_SEQ)) ==
(FC_FC_LAST_SEQ | FC_FC_END_SEQ)) {
spin_lock_bh(&ep->ex_lock);
rc = fc_exch_done_locked(ep);
WARN_ON(fc_seq_exch(sp) != ep);
spin_unlock_bh(&ep->ex_lock);
if (!rc)
fc_exch_delete(ep);
}
/*
* Call the receive function.
* The sequence is held (has a refcnt) for us,
* but not for the receive function.
*
* The receive function may allocate a new sequence
* over the old one, so we shouldn't change the
* sequence after this.
*
* The frame will be freed by the receive function.
* If new exch resp handler is valid then call that
* first.
*/
if (resp)
resp(sp, fp, ex_resp_arg);
else
fc_frame_free(fp);
fc_exch_release(ep);
return;
rel:
fc_exch_release(ep);
out:
fc_frame_free(fp);
}
/*
* Handle receive for a sequence where other end is responding to our sequence.
*/
static void fc_exch_recv_resp(struct fc_exch_mgr *mp, struct fc_frame *fp)
{
struct fc_seq *sp;
sp = fc_seq_lookup_orig(mp, fp); /* doesn't hold sequence */
if (!sp)
atomic_inc(&mp->stats.xid_not_found);
else
atomic_inc(&mp->stats.non_bls_resp);
fc_frame_free(fp);
}
/*
* Handle the response to an ABTS for exchange or sequence.
* This can be BA_ACC or BA_RJT.
*/
static void fc_exch_abts_resp(struct fc_exch *ep, struct fc_frame *fp)
{
void (*resp)(struct fc_seq *, struct fc_frame *fp, void *arg);
void *ex_resp_arg;
struct fc_frame_header *fh;
struct fc_ba_acc *ap;
struct fc_seq *sp;
u16 low;
u16 high;
int rc = 1, has_rec = 0;
fh = fc_frame_header_get(fp);
FC_EXCH_DBG(ep, "exch: BLS rctl %x - %s\n", fh->fh_r_ctl,
fc_exch_rctl_name(fh->fh_r_ctl));
if (cancel_delayed_work_sync(&ep->timeout_work))
fc_exch_release(ep); /* release from pending timer hold */
spin_lock_bh(&ep->ex_lock);
switch (fh->fh_r_ctl) {
case FC_RCTL_BA_ACC:
ap = fc_frame_payload_get(fp, sizeof(*ap));
if (!ap)
break;
/*
* Decide whether to establish a Recovery Qualifier.
* We do this if there is a non-empty SEQ_CNT range and
* SEQ_ID is the same as the one we aborted.
*/
low = ntohs(ap->ba_low_seq_cnt);
high = ntohs(ap->ba_high_seq_cnt);
if ((ep->esb_stat & ESB_ST_REC_QUAL) == 0 &&
(ap->ba_seq_id_val != FC_BA_SEQ_ID_VAL ||
ap->ba_seq_id == ep->seq_id) && low != high) {
ep->esb_stat |= ESB_ST_REC_QUAL;
fc_exch_hold(ep); /* hold for recovery qualifier */
has_rec = 1;
}
break;
case FC_RCTL_BA_RJT:
break;
default:
break;
}
resp = ep->resp;
ex_resp_arg = ep->arg;
/* do we need to do some other checks here. Can we reuse more of
* fc_exch_recv_seq_resp
*/
sp = &ep->seq;
/*
* do we want to check END_SEQ as well as LAST_SEQ here?
*/
if (ep->fh_type != FC_TYPE_FCP &&
ntoh24(fh->fh_f_ctl) & FC_FC_LAST_SEQ)
rc = fc_exch_done_locked(ep);
spin_unlock_bh(&ep->ex_lock);
if (!rc)
fc_exch_delete(ep);
if (resp)
resp(sp, fp, ex_resp_arg);
else
fc_frame_free(fp);
if (has_rec)
fc_exch_timer_set(ep, ep->r_a_tov);
}
/*
* Receive BLS sequence.
* This is always a sequence initiated by the remote side.
* We may be either the originator or recipient of the exchange.
*/
static void fc_exch_recv_bls(struct fc_exch_mgr *mp, struct fc_frame *fp)
{
struct fc_frame_header *fh;
struct fc_exch *ep;
u32 f_ctl;
fh = fc_frame_header_get(fp);
f_ctl = ntoh24(fh->fh_f_ctl);
fr_seq(fp) = NULL;
ep = fc_exch_find(mp, (f_ctl & FC_FC_EX_CTX) ?
ntohs(fh->fh_ox_id) : ntohs(fh->fh_rx_id));
if (ep && (f_ctl & FC_FC_SEQ_INIT)) {
spin_lock_bh(&ep->ex_lock);
ep->esb_stat |= ESB_ST_SEQ_INIT;
spin_unlock_bh(&ep->ex_lock);
}
if (f_ctl & FC_FC_SEQ_CTX) {
/*
* A response to a sequence we initiated.
* This should only be ACKs for class 2 or F.
*/
switch (fh->fh_r_ctl) {
case FC_RCTL_ACK_1:
case FC_RCTL_ACK_0:
break;
default:
FC_EXCH_DBG(ep, "BLS rctl %x - %s received",
fh->fh_r_ctl,
fc_exch_rctl_name(fh->fh_r_ctl));
break;
}
fc_frame_free(fp);
} else {
switch (fh->fh_r_ctl) {
case FC_RCTL_BA_RJT:
case FC_RCTL_BA_ACC:
if (ep)
fc_exch_abts_resp(ep, fp);
else
fc_frame_free(fp);
break;
case FC_RCTL_BA_ABTS:
fc_exch_recv_abts(ep, fp);
break;
default: /* ignore junk */
fc_frame_free(fp);
break;
}
}
if (ep)
fc_exch_release(ep); /* release hold taken by fc_exch_find */
}
/*
* Accept sequence with LS_ACC.
* If this fails due to allocation or transmit congestion, assume the
* originator will repeat the sequence.
*/
static void fc_seq_ls_acc(struct fc_seq *req_sp)
{
struct fc_seq *sp;
struct fc_els_ls_acc *acc;
struct fc_frame *fp;
sp = fc_seq_start_next(req_sp);
fp = fc_frame_alloc(fc_seq_exch(sp)->lp, sizeof(*acc));
if (fp) {
acc = fc_frame_payload_get(fp, sizeof(*acc));
memset(acc, 0, sizeof(*acc));
acc->la_cmd = ELS_LS_ACC;
fc_seq_send_last(sp, fp, FC_RCTL_ELS_REP, FC_TYPE_ELS);
}
}
/*
* Reject sequence with ELS LS_RJT.
* If this fails due to allocation or transmit congestion, assume the
* originator will repeat the sequence.
*/
static void fc_seq_ls_rjt(struct fc_seq *req_sp, enum fc_els_rjt_reason reason,
enum fc_els_rjt_explan explan)
{
struct fc_seq *sp;
struct fc_els_ls_rjt *rjt;
struct fc_frame *fp;
sp = fc_seq_start_next(req_sp);
fp = fc_frame_alloc(fc_seq_exch(sp)->lp, sizeof(*rjt));
if (fp) {
rjt = fc_frame_payload_get(fp, sizeof(*rjt));
memset(rjt, 0, sizeof(*rjt));
rjt->er_cmd = ELS_LS_RJT;
rjt->er_reason = reason;
rjt->er_explan = explan;
fc_seq_send_last(sp, fp, FC_RCTL_ELS_REP, FC_TYPE_ELS);
}
}
static void fc_exch_reset(struct fc_exch *ep)
{
struct fc_seq *sp;
void (*resp)(struct fc_seq *, struct fc_frame *, void *);
void *arg;
int rc = 1;
spin_lock_bh(&ep->ex_lock);
ep->state |= FC_EX_RST_CLEANUP;
/*
* we really want to call del_timer_sync, but cannot due
* to the lport calling with the lport lock held (some resp
* functions can also grab the lport lock which could cause
* a deadlock).
*/
if (cancel_delayed_work(&ep->timeout_work))
atomic_dec(&ep->ex_refcnt); /* drop hold for timer */
resp = ep->resp;
ep->resp = NULL;
if (ep->esb_stat & ESB_ST_REC_QUAL)
atomic_dec(&ep->ex_refcnt); /* drop hold for rec_qual */
ep->esb_stat &= ~ESB_ST_REC_QUAL;
arg = ep->arg;
sp = &ep->seq;
rc = fc_exch_done_locked(ep);
spin_unlock_bh(&ep->ex_lock);
if (!rc)
fc_exch_delete(ep);
if (resp)
resp(sp, ERR_PTR(-FC_EX_CLOSED), arg);
}
/**
* fc_exch_pool_reset() - Resets an per cpu exches pool.
* @lport: ptr to the local port
* @pool: ptr to the per cpu exches pool
* @sid: source FC ID
* @did: destination FC ID
*
* Resets an per cpu exches pool, releasing its all sequences
* and exchanges. If sid is non-zero, then reset only exchanges
* we sourced from that FID. If did is non-zero, reset only
* exchanges destined to that FID.
*/
static void fc_exch_pool_reset(struct fc_lport *lport,
struct fc_exch_pool *pool,
u32 sid, u32 did)
{
struct fc_exch *ep;
struct fc_exch *next;
spin_lock_bh(&pool->lock);
restart:
list_for_each_entry_safe(ep, next, &pool->ex_list, ex_list) {
if ((lport == ep->lp) &&
(sid == 0 || sid == ep->sid) &&
(did == 0 || did == ep->did)) {
fc_exch_hold(ep);
spin_unlock_bh(&pool->lock);
fc_exch_reset(ep);
fc_exch_release(ep);
spin_lock_bh(&pool->lock);
/*
* must restart loop incase while lock
* was down multiple eps were released.
*/
goto restart;
}
}
spin_unlock_bh(&pool->lock);
}
/**
* fc_exch_mgr_reset() - Resets all EMs of a lport
* @lport: ptr to the local port
* @sid: source FC ID
* @did: destination FC ID
*
* Reset all EMs of a lport, releasing its all sequences and
* exchanges. If sid is non-zero, then reset only exchanges
* we sourced from that FID. If did is non-zero, reset only
* exchanges destined to that FID.
*/
void fc_exch_mgr_reset(struct fc_lport *lport, u32 sid, u32 did)
{
struct fc_exch_mgr_anchor *ema;
unsigned int cpu;
list_for_each_entry(ema, &lport->ema_list, ema_list) {
for_each_possible_cpu(cpu)
fc_exch_pool_reset(lport,
per_cpu_ptr(ema->mp->pool, cpu),
sid, did);
}
}
EXPORT_SYMBOL(fc_exch_mgr_reset);
/*
* Handle incoming ELS REC - Read Exchange Concise.
* Note that the requesting port may be different than the S_ID in the request.
*/
static void fc_exch_els_rec(struct fc_seq *sp, struct fc_frame *rfp)
{
struct fc_frame *fp;
struct fc_exch *ep;
struct fc_exch_mgr *em;
struct fc_els_rec *rp;
struct fc_els_rec_acc *acc;
enum fc_els_rjt_reason reason = ELS_RJT_LOGIC;
enum fc_els_rjt_explan explan;
u32 sid;
u16 rxid;
u16 oxid;
rp = fc_frame_payload_get(rfp, sizeof(*rp));
explan = ELS_EXPL_INV_LEN;
if (!rp)
goto reject;
sid = ntoh24(rp->rec_s_id);
rxid = ntohs(rp->rec_rx_id);
oxid = ntohs(rp->rec_ox_id);
/*
* Currently it's hard to find the local S_ID from the exchange
* manager. This will eventually be fixed, but for now it's easier
* to lookup the subject exchange twice, once as if we were
* the initiator, and then again if we weren't.
*/
em = fc_seq_exch(sp)->em;
ep = fc_exch_find(em, oxid);
explan = ELS_EXPL_OXID_RXID;
if (ep && ep->oid == sid) {
if (ep->rxid != FC_XID_UNKNOWN &&
rxid != FC_XID_UNKNOWN &&
ep->rxid != rxid)
goto rel;
} else {
if (ep)
fc_exch_release(ep);
ep = NULL;
if (rxid != FC_XID_UNKNOWN)
ep = fc_exch_find(em, rxid);
if (!ep)
goto reject;
}
fp = fc_frame_alloc(fc_seq_exch(sp)->lp, sizeof(*acc));
if (!fp) {
fc_exch_done(sp);
goto out;
}
sp = fc_seq_start_next(sp);
acc = fc_frame_payload_get(fp, sizeof(*acc));
memset(acc, 0, sizeof(*acc));
acc->reca_cmd = ELS_LS_ACC;
acc->reca_ox_id = rp->rec_ox_id;
memcpy(acc->reca_ofid, rp->rec_s_id, 3);
acc->reca_rx_id = htons(ep->rxid);
if (ep->sid == ep->oid)
hton24(acc->reca_rfid, ep->did);
else
hton24(acc->reca_rfid, ep->sid);
acc->reca_fc4value = htonl(ep->seq.rec_data);
acc->reca_e_stat = htonl(ep->esb_stat & (ESB_ST_RESP |
ESB_ST_SEQ_INIT |
ESB_ST_COMPLETE));
sp = fc_seq_start_next(sp);
fc_seq_send_last(sp, fp, FC_RCTL_ELS_REP, FC_TYPE_ELS);
out:
fc_exch_release(ep);
fc_frame_free(rfp);
return;
rel:
fc_exch_release(ep);
reject:
fc_seq_ls_rjt(sp, reason, explan);
fc_frame_free(rfp);
}
/*
* Handle response from RRQ.
* Not much to do here, really.
* Should report errors.
*
* TODO: fix error handler.
*/
static void fc_exch_rrq_resp(struct fc_seq *sp, struct fc_frame *fp, void *arg)
{
struct fc_exch *aborted_ep = arg;
unsigned int op;
if (IS_ERR(fp)) {
int err = PTR_ERR(fp);
if (err == -FC_EX_CLOSED || err == -FC_EX_TIMEOUT)
goto cleanup;
FC_EXCH_DBG(aborted_ep, "Cannot process RRQ, "
"frame error %d\n", err);
return;
}
op = fc_frame_payload_op(fp);
fc_frame_free(fp);
switch (op) {
case ELS_LS_RJT:
FC_EXCH_DBG(aborted_ep, "LS_RJT for RRQ");
/* fall through */
case ELS_LS_ACC:
goto cleanup;
default:
FC_EXCH_DBG(aborted_ep, "unexpected response op %x "
"for RRQ", op);
return;
}
cleanup:
fc_exch_done(&aborted_ep->seq);
/* drop hold for rec qual */
fc_exch_release(aborted_ep);
}
/*
* Send ELS RRQ - Reinstate Recovery Qualifier.
* This tells the remote port to stop blocking the use of
* the exchange and the seq_cnt range.
*/
static void fc_exch_rrq(struct fc_exch *ep)
{
struct fc_lport *lp;
struct fc_els_rrq *rrq;
struct fc_frame *fp;
u32 did;
lp = ep->lp;
fp = fc_frame_alloc(lp, sizeof(*rrq));
if (!fp)
goto retry;
rrq = fc_frame_payload_get(fp, sizeof(*rrq));
memset(rrq, 0, sizeof(*rrq));
rrq->rrq_cmd = ELS_RRQ;
hton24(rrq->rrq_s_id, ep->sid);
rrq->rrq_ox_id = htons(ep->oxid);
rrq->rrq_rx_id = htons(ep->rxid);
did = ep->did;
if (ep->esb_stat & ESB_ST_RESP)
did = ep->sid;
fc_fill_fc_hdr(fp, FC_RCTL_ELS_REQ, did,
fc_host_port_id(lp->host), FC_TYPE_ELS,
FC_FC_FIRST_SEQ | FC_FC_END_SEQ | FC_FC_SEQ_INIT, 0);
if (fc_exch_seq_send(lp, fp, fc_exch_rrq_resp, NULL, ep, lp->e_d_tov))
return;
retry:
spin_lock_bh(&ep->ex_lock);
if (ep->state & (FC_EX_RST_CLEANUP | FC_EX_DONE)) {
spin_unlock_bh(&ep->ex_lock);
/* drop hold for rec qual */
fc_exch_release(ep);
return;
}
ep->esb_stat |= ESB_ST_REC_QUAL;
fc_exch_timer_set_locked(ep, ep->r_a_tov);
spin_unlock_bh(&ep->ex_lock);
}
/*
* Handle incoming ELS RRQ - Reset Recovery Qualifier.
*/
static void fc_exch_els_rrq(struct fc_seq *sp, struct fc_frame *fp)
{
struct fc_exch *ep; /* request or subject exchange */
struct fc_els_rrq *rp;
u32 sid;
u16 xid;
enum fc_els_rjt_explan explan;
rp = fc_frame_payload_get(fp, sizeof(*rp));
explan = ELS_EXPL_INV_LEN;
if (!rp)
goto reject;
/*
* lookup subject exchange.
*/
ep = fc_seq_exch(sp);
sid = ntoh24(rp->rrq_s_id); /* subject source */
xid = ep->did == sid ? ntohs(rp->rrq_ox_id) : ntohs(rp->rrq_rx_id);
ep = fc_exch_find(ep->em, xid);
explan = ELS_EXPL_OXID_RXID;
if (!ep)
goto reject;
spin_lock_bh(&ep->ex_lock);
if (ep->oxid != ntohs(rp->rrq_ox_id))
goto unlock_reject;
if (ep->rxid != ntohs(rp->rrq_rx_id) &&
ep->rxid != FC_XID_UNKNOWN)
goto unlock_reject;
explan = ELS_EXPL_SID;
if (ep->sid != sid)
goto unlock_reject;
/*
* Clear Recovery Qualifier state, and cancel timer if complete.
*/
if (ep->esb_stat & ESB_ST_REC_QUAL) {
ep->esb_stat &= ~ESB_ST_REC_QUAL;
atomic_dec(&ep->ex_refcnt); /* drop hold for rec qual */
}
if (ep->esb_stat & ESB_ST_COMPLETE) {
if (cancel_delayed_work(&ep->timeout_work))
atomic_dec(&ep->ex_refcnt); /* drop timer hold */
}
spin_unlock_bh(&ep->ex_lock);
/*
* Send LS_ACC.
*/
fc_seq_ls_acc(sp);
fc_frame_free(fp);
return;
unlock_reject:
spin_unlock_bh(&ep->ex_lock);
fc_exch_release(ep); /* drop hold from fc_exch_find */
reject:
fc_seq_ls_rjt(sp, ELS_RJT_LOGIC, explan);
fc_frame_free(fp);
}
struct fc_exch_mgr_anchor *fc_exch_mgr_add(struct fc_lport *lport,
struct fc_exch_mgr *mp,
bool (*match)(struct fc_frame *))
{
struct fc_exch_mgr_anchor *ema;
ema = kmalloc(sizeof(*ema), GFP_ATOMIC);
if (!ema)
return ema;
ema->mp = mp;
ema->match = match;
/* add EM anchor to EM anchors list */
list_add_tail(&ema->ema_list, &lport->ema_list);
kref_get(&mp->kref);
return ema;
}
EXPORT_SYMBOL(fc_exch_mgr_add);
static void fc_exch_mgr_destroy(struct kref *kref)
{
struct fc_exch_mgr *mp = container_of(kref, struct fc_exch_mgr, kref);
mempool_destroy(mp->ep_pool);
free_percpu(mp->pool);
kfree(mp);
}
void fc_exch_mgr_del(struct fc_exch_mgr_anchor *ema)
{
/* remove EM anchor from EM anchors list */
list_del(&ema->ema_list);
kref_put(&ema->mp->kref, fc_exch_mgr_destroy);
kfree(ema);
}
EXPORT_SYMBOL(fc_exch_mgr_del);
struct fc_exch_mgr *fc_exch_mgr_alloc(struct fc_lport *lp,
enum fc_class class,
u16 min_xid, u16 max_xid,
bool (*match)(struct fc_frame *))
{
struct fc_exch_mgr *mp;
u16 pool_exch_range;
size_t pool_size;
unsigned int cpu;
struct fc_exch_pool *pool;
if (max_xid <= min_xid || max_xid == FC_XID_UNKNOWN ||
(min_xid & fc_cpu_mask) != 0) {
FC_LPORT_DBG(lp, "Invalid min_xid 0x:%x and max_xid 0x:%x\n",
min_xid, max_xid);
return NULL;
}
/*
* allocate memory for EM
*/
mp = kzalloc(sizeof(struct fc_exch_mgr), GFP_ATOMIC);
if (!mp)
return NULL;
mp->class = class;
/* adjust em exch xid range for offload */
mp->min_xid = min_xid;
mp->max_xid = max_xid;
mp->ep_pool = mempool_create_slab_pool(2, fc_em_cachep);
if (!mp->ep_pool)
goto free_mp;
/*
* Setup per cpu exch pool with entire exchange id range equally
* divided across all cpus. The exch pointers array memory is
* allocated for exch range per pool.
*/
pool_exch_range = (mp->max_xid - mp->min_xid + 1) / (fc_cpu_mask + 1);
mp->pool_max_index = pool_exch_range - 1;
/*
* Allocate and initialize per cpu exch pool
*/
pool_size = sizeof(*pool) + pool_exch_range * sizeof(struct fc_exch *);
mp->pool = __alloc_percpu(pool_size, __alignof__(struct fc_exch_pool));
if (!mp->pool)
goto free_mempool;
for_each_possible_cpu(cpu) {
pool = per_cpu_ptr(mp->pool, cpu);
spin_lock_init(&pool->lock);
INIT_LIST_HEAD(&pool->ex_list);
}
kref_init(&mp->kref);
if (!fc_exch_mgr_add(lp, mp, match)) {
free_percpu(mp->pool);
goto free_mempool;
}
/*
* Above kref_init() sets mp->kref to 1 and then
* call to fc_exch_mgr_add incremented mp->kref again,
* so adjust that extra increment.
*/
kref_put(&mp->kref, fc_exch_mgr_destroy);
return mp;
free_mempool:
mempool_destroy(mp->ep_pool);
free_mp:
kfree(mp);
return NULL;
}
EXPORT_SYMBOL(fc_exch_mgr_alloc);
void fc_exch_mgr_free(struct fc_lport *lport)
{
struct fc_exch_mgr_anchor *ema, *next;
list_for_each_entry_safe(ema, next, &lport->ema_list, ema_list)
fc_exch_mgr_del(ema);
}
EXPORT_SYMBOL(fc_exch_mgr_free);
struct fc_seq *fc_exch_seq_send(struct fc_lport *lp,
struct fc_frame *fp,
void (*resp)(struct fc_seq *,
struct fc_frame *fp,
void *arg),
void (*destructor)(struct fc_seq *, void *),
void *arg, u32 timer_msec)
{
struct fc_exch *ep;
struct fc_seq *sp = NULL;
struct fc_frame_header *fh;
int rc = 1;
ep = fc_exch_alloc(lp, fp);
if (!ep) {
fc_frame_free(fp);
return NULL;
}
ep->esb_stat |= ESB_ST_SEQ_INIT;
fh = fc_frame_header_get(fp);
fc_exch_set_addr(ep, ntoh24(fh->fh_s_id), ntoh24(fh->fh_d_id));
ep->resp = resp;
ep->destructor = destructor;
ep->arg = arg;
ep->r_a_tov = FC_DEF_R_A_TOV;
ep->lp = lp;
sp = &ep->seq;
ep->fh_type = fh->fh_type; /* save for possbile timeout handling */
ep->f_ctl = ntoh24(fh->fh_f_ctl);
fc_exch_setup_hdr(ep, fp, ep->f_ctl);
sp->cnt++;
if (ep->xid <= lp->lro_xid)
fc_fcp_ddp_setup(fr_fsp(fp), ep->xid);
if (unlikely(lp->tt.frame_send(lp, fp)))
goto err;
if (timer_msec)
fc_exch_timer_set_locked(ep, timer_msec);
ep->f_ctl &= ~FC_FC_FIRST_SEQ; /* not first seq */
if (ep->f_ctl & FC_FC_SEQ_INIT)
ep->esb_stat &= ~ESB_ST_SEQ_INIT;
spin_unlock_bh(&ep->ex_lock);
return sp;
err:
rc = fc_exch_done_locked(ep);
spin_unlock_bh(&ep->ex_lock);
if (!rc)
fc_exch_delete(ep);
return NULL;
}
EXPORT_SYMBOL(fc_exch_seq_send);
/*
* Receive a frame
*/
void fc_exch_recv(struct fc_lport *lp, struct fc_frame *fp)
{
struct fc_frame_header *fh = fc_frame_header_get(fp);
struct fc_exch_mgr_anchor *ema;
u32 f_ctl, found = 0;
u16 oxid;
/* lport lock ? */
if (!lp || lp->state == LPORT_ST_DISABLED) {
FC_LPORT_DBG(lp, "Receiving frames for an lport that "
"has not been initialized correctly\n");
fc_frame_free(fp);
return;
}
f_ctl = ntoh24(fh->fh_f_ctl);
oxid = ntohs(fh->fh_ox_id);
if (f_ctl & FC_FC_EX_CTX) {
list_for_each_entry(ema, &lp->ema_list, ema_list) {
if ((oxid >= ema->mp->min_xid) &&
(oxid <= ema->mp->max_xid)) {
found = 1;
break;
}
}
if (!found) {
FC_LPORT_DBG(lp, "Received response for out "
"of range oxid:%hx\n", oxid);
fc_frame_free(fp);
return;
}
} else
ema = list_entry(lp->ema_list.prev, typeof(*ema), ema_list);
/*
* If frame is marked invalid, just drop it.
*/
switch (fr_eof(fp)) {
case FC_EOF_T:
if (f_ctl & FC_FC_END_SEQ)
skb_trim(fp_skb(fp), fr_len(fp) - FC_FC_FILL(f_ctl));
/* fall through */
case FC_EOF_N:
if (fh->fh_type == FC_TYPE_BLS)
fc_exch_recv_bls(ema->mp, fp);
else if ((f_ctl & (FC_FC_EX_CTX | FC_FC_SEQ_CTX)) ==
FC_FC_EX_CTX)
fc_exch_recv_seq_resp(ema->mp, fp);
else if (f_ctl & FC_FC_SEQ_CTX)
fc_exch_recv_resp(ema->mp, fp);
else
fc_exch_recv_req(lp, ema->mp, fp);
break;
default:
FC_LPORT_DBG(lp, "dropping invalid frame (eof %x)", fr_eof(fp));
fc_frame_free(fp);
}
}
EXPORT_SYMBOL(fc_exch_recv);
int fc_exch_init(struct fc_lport *lp)
{
if (!lp->tt.seq_start_next)
lp->tt.seq_start_next = fc_seq_start_next;
if (!lp->tt.exch_seq_send)
lp->tt.exch_seq_send = fc_exch_seq_send;
if (!lp->tt.seq_send)
lp->tt.seq_send = fc_seq_send;
if (!lp->tt.seq_els_rsp_send)
lp->tt.seq_els_rsp_send = fc_seq_els_rsp_send;
if (!lp->tt.exch_done)
lp->tt.exch_done = fc_exch_done;
if (!lp->tt.exch_mgr_reset)
lp->tt.exch_mgr_reset = fc_exch_mgr_reset;
if (!lp->tt.seq_exch_abort)
lp->tt.seq_exch_abort = fc_seq_exch_abort;
/*
* Initialize fc_cpu_mask and fc_cpu_order. The
* fc_cpu_mask is set for nr_cpu_ids rounded up
* to order of 2's * power and order is stored
* in fc_cpu_order as this is later required in
* mapping between an exch id and exch array index
* in per cpu exch pool.
*
* This round up is required to align fc_cpu_mask
* to exchange id's lower bits such that all incoming
* frames of an exchange gets delivered to the same
* cpu on which exchange originated by simple bitwise
* AND operation between fc_cpu_mask and exchange id.
*/
fc_cpu_mask = 1;
fc_cpu_order = 0;
while (fc_cpu_mask < nr_cpu_ids) {
fc_cpu_mask <<= 1;
fc_cpu_order++;
}
fc_cpu_mask--;
return 0;
}
EXPORT_SYMBOL(fc_exch_init);
int fc_setup_exch_mgr(void)
{
fc_em_cachep = kmem_cache_create("libfc_em", sizeof(struct fc_exch),
0, SLAB_HWCACHE_ALIGN, NULL);
if (!fc_em_cachep)
return -ENOMEM;
return 0;
}
void fc_destroy_exch_mgr(void)
{
kmem_cache_destroy(fc_em_cachep);
}
| gpl-2.0 |
kyasu/android_kernel_samsung_slte | drivers/scsi/hpsa.c | 464 | 148510 | /*
* Disk Array driver for HP Smart Array SAS controllers
* Copyright 2000, 2009 Hewlett-Packard Development Company, L.P.
*
* 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, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Questions/Comments/Bugfixes to iss_storagedev@hp.com
*
*/
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/pci-aspm.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/fs.h>
#include <linux/timer.h>
#include <linux/seq_file.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/compat.h>
#include <linux/blktrace_api.h>
#include <linux/uaccess.h>
#include <linux/io.h>
#include <linux/dma-mapping.h>
#include <linux/completion.h>
#include <linux/moduleparam.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 <linux/cciss_ioctl.h>
#include <linux/string.h>
#include <linux/bitmap.h>
#include <linux/atomic.h>
#include <linux/kthread.h>
#include <linux/jiffies.h>
#include "hpsa_cmd.h"
#include "hpsa.h"
/* HPSA_DRIVER_VERSION must be 3 byte values (0-255) separated by '.' */
#define HPSA_DRIVER_VERSION "2.0.2-1"
#define DRIVER_NAME "HP HPSA Driver (v " HPSA_DRIVER_VERSION ")"
#define HPSA "hpsa"
/* How long to wait (in milliseconds) for board to go into simple mode */
#define MAX_CONFIG_WAIT 30000
#define MAX_IOCTL_CONFIG_WAIT 1000
/*define how many times we will try a command because of bus resets */
#define MAX_CMD_RETRIES 3
/* Embedded module documentation macros - see modules.h */
MODULE_AUTHOR("Hewlett-Packard Company");
MODULE_DESCRIPTION("Driver for HP Smart Array Controller version " \
HPSA_DRIVER_VERSION);
MODULE_SUPPORTED_DEVICE("HP Smart Array Controllers");
MODULE_VERSION(HPSA_DRIVER_VERSION);
MODULE_LICENSE("GPL");
static int hpsa_allow_any;
module_param(hpsa_allow_any, int, S_IRUGO|S_IWUSR);
MODULE_PARM_DESC(hpsa_allow_any,
"Allow hpsa driver to access unknown HP Smart Array hardware");
static int hpsa_simple_mode;
module_param(hpsa_simple_mode, int, S_IRUGO|S_IWUSR);
MODULE_PARM_DESC(hpsa_simple_mode,
"Use 'simple mode' rather than 'performant mode'");
/* define the PCI info for the cards we can control */
static const struct pci_device_id hpsa_pci_device_id[] = {
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSE, 0x103C, 0x3241},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSE, 0x103C, 0x3243},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSE, 0x103C, 0x3245},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSE, 0x103C, 0x3247},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSE, 0x103C, 0x3249},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSE, 0x103C, 0x324a},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSE, 0x103C, 0x324b},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSE, 0x103C, 0x3233},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSF, 0x103C, 0x3350},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSF, 0x103C, 0x3351},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSF, 0x103C, 0x3352},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSF, 0x103C, 0x3353},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSF, 0x103C, 0x3354},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSF, 0x103C, 0x3355},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSF, 0x103C, 0x3356},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSH, 0x103C, 0x1920},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSH, 0x103C, 0x1921},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSH, 0x103C, 0x1922},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSH, 0x103C, 0x1923},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSH, 0x103C, 0x1924},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSH, 0x103C, 0x1925},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSH, 0x103C, 0x1926},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSH, 0x103C, 0x1928},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSF, 0x103C, 0x334d},
{PCI_VENDOR_ID_HP, PCI_ANY_ID, PCI_ANY_ID, PCI_ANY_ID,
PCI_CLASS_STORAGE_RAID << 8, 0xffff << 8, 0},
{0,}
};
MODULE_DEVICE_TABLE(pci, hpsa_pci_device_id);
/* board_id = Subsystem Device ID & Vendor ID
* product = Marketing Name for the board
* access = Address of the struct of function pointers
*/
static struct board_type products[] = {
{0x3241103C, "Smart Array P212", &SA5_access},
{0x3243103C, "Smart Array P410", &SA5_access},
{0x3245103C, "Smart Array P410i", &SA5_access},
{0x3247103C, "Smart Array P411", &SA5_access},
{0x3249103C, "Smart Array P812", &SA5_access},
{0x324a103C, "Smart Array P712m", &SA5_access},
{0x324b103C, "Smart Array P711m", &SA5_access},
{0x3350103C, "Smart Array P222", &SA5_access},
{0x3351103C, "Smart Array P420", &SA5_access},
{0x3352103C, "Smart Array P421", &SA5_access},
{0x3353103C, "Smart Array P822", &SA5_access},
{0x3354103C, "Smart Array P420i", &SA5_access},
{0x3355103C, "Smart Array P220i", &SA5_access},
{0x3356103C, "Smart Array P721m", &SA5_access},
{0x1920103C, "Smart Array", &SA5_access},
{0x1921103C, "Smart Array", &SA5_access},
{0x1922103C, "Smart Array", &SA5_access},
{0x1923103C, "Smart Array", &SA5_access},
{0x1924103C, "Smart Array", &SA5_access},
{0x1925103C, "Smart Array", &SA5_access},
{0x1926103C, "Smart Array", &SA5_access},
{0x1928103C, "Smart Array", &SA5_access},
{0x334d103C, "Smart Array P822se", &SA5_access},
{0xFFFF103C, "Unknown Smart Array", &SA5_access},
};
static int number_of_controllers;
static struct list_head hpsa_ctlr_list = LIST_HEAD_INIT(hpsa_ctlr_list);
static spinlock_t lockup_detector_lock;
static struct task_struct *hpsa_lockup_detector;
static irqreturn_t do_hpsa_intr_intx(int irq, void *dev_id);
static irqreturn_t do_hpsa_intr_msi(int irq, void *dev_id);
static int hpsa_ioctl(struct scsi_device *dev, int cmd, void *arg);
static void start_io(struct ctlr_info *h);
#ifdef CONFIG_COMPAT
static int hpsa_compat_ioctl(struct scsi_device *dev, int cmd, void *arg);
#endif
static void cmd_free(struct ctlr_info *h, struct CommandList *c);
static void cmd_special_free(struct ctlr_info *h, struct CommandList *c);
static struct CommandList *cmd_alloc(struct ctlr_info *h);
static struct CommandList *cmd_special_alloc(struct ctlr_info *h);
static int fill_cmd(struct CommandList *c, u8 cmd, struct ctlr_info *h,
void *buff, size_t size, u8 page_code, unsigned char *scsi3addr,
int cmd_type);
static int hpsa_scsi_queue_command(struct Scsi_Host *h, struct scsi_cmnd *cmd);
static void hpsa_scan_start(struct Scsi_Host *);
static int hpsa_scan_finished(struct Scsi_Host *sh,
unsigned long elapsed_time);
static int hpsa_change_queue_depth(struct scsi_device *sdev,
int qdepth, int reason);
static int hpsa_eh_device_reset_handler(struct scsi_cmnd *scsicmd);
static int hpsa_eh_abort_handler(struct scsi_cmnd *scsicmd);
static int hpsa_slave_alloc(struct scsi_device *sdev);
static void hpsa_slave_destroy(struct scsi_device *sdev);
static void hpsa_update_scsi_devices(struct ctlr_info *h, int hostno);
static int check_for_unit_attention(struct ctlr_info *h,
struct CommandList *c);
static void check_ioctl_unit_attention(struct ctlr_info *h,
struct CommandList *c);
/* performant mode helper functions */
static void calc_bucket_map(int *bucket, int num_buckets,
int nsgs, int *bucket_map);
static void hpsa_put_ctlr_into_performant_mode(struct ctlr_info *h);
static inline u32 next_command(struct ctlr_info *h, u8 q);
static int hpsa_find_cfg_addrs(struct pci_dev *pdev, void __iomem *vaddr,
u32 *cfg_base_addr, u64 *cfg_base_addr_index,
u64 *cfg_offset);
static int hpsa_pci_find_memory_BAR(struct pci_dev *pdev,
unsigned long *memory_bar);
static int hpsa_lookup_board_id(struct pci_dev *pdev, u32 *board_id);
static int hpsa_wait_for_board_state(struct pci_dev *pdev, void __iomem *vaddr,
int wait_for_ready);
static inline void finish_cmd(struct CommandList *c);
#define BOARD_NOT_READY 0
#define BOARD_READY 1
static inline struct ctlr_info *sdev_to_hba(struct scsi_device *sdev)
{
unsigned long *priv = shost_priv(sdev->host);
return (struct ctlr_info *) *priv;
}
static inline struct ctlr_info *shost_to_hba(struct Scsi_Host *sh)
{
unsigned long *priv = shost_priv(sh);
return (struct ctlr_info *) *priv;
}
static int check_for_unit_attention(struct ctlr_info *h,
struct CommandList *c)
{
if (c->err_info->SenseInfo[2] != UNIT_ATTENTION)
return 0;
switch (c->err_info->SenseInfo[12]) {
case STATE_CHANGED:
dev_warn(&h->pdev->dev, HPSA "%d: a state change "
"detected, command retried\n", h->ctlr);
break;
case LUN_FAILED:
dev_warn(&h->pdev->dev, HPSA "%d: LUN failure "
"detected, action required\n", h->ctlr);
break;
case REPORT_LUNS_CHANGED:
dev_warn(&h->pdev->dev, HPSA "%d: report LUN data "
"changed, action required\n", h->ctlr);
/*
* Note: this REPORT_LUNS_CHANGED condition only occurs on the external
* target (array) devices.
*/
break;
case POWER_OR_RESET:
dev_warn(&h->pdev->dev, HPSA "%d: a power on "
"or device reset detected\n", h->ctlr);
break;
case UNIT_ATTENTION_CLEARED:
dev_warn(&h->pdev->dev, HPSA "%d: unit attention "
"cleared by another initiator\n", h->ctlr);
break;
default:
dev_warn(&h->pdev->dev, HPSA "%d: unknown "
"unit attention detected\n", h->ctlr);
break;
}
return 1;
}
static int check_for_busy(struct ctlr_info *h, struct CommandList *c)
{
if (c->err_info->CommandStatus != CMD_TARGET_STATUS ||
(c->err_info->ScsiStatus != SAM_STAT_BUSY &&
c->err_info->ScsiStatus != SAM_STAT_TASK_SET_FULL))
return 0;
dev_warn(&h->pdev->dev, HPSA "device busy");
return 1;
}
static ssize_t host_store_rescan(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct ctlr_info *h;
struct Scsi_Host *shost = class_to_shost(dev);
h = shost_to_hba(shost);
hpsa_scan_start(h->scsi_host);
return count;
}
static ssize_t host_show_firmware_revision(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct ctlr_info *h;
struct Scsi_Host *shost = class_to_shost(dev);
unsigned char *fwrev;
h = shost_to_hba(shost);
if (!h->hba_inquiry_data)
return 0;
fwrev = &h->hba_inquiry_data[32];
return snprintf(buf, 20, "%c%c%c%c\n",
fwrev[0], fwrev[1], fwrev[2], fwrev[3]);
}
static ssize_t host_show_commands_outstanding(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct ctlr_info *h = shost_to_hba(shost);
return snprintf(buf, 20, "%d\n", h->commands_outstanding);
}
static ssize_t host_show_transport_mode(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct ctlr_info *h;
struct Scsi_Host *shost = class_to_shost(dev);
h = shost_to_hba(shost);
return snprintf(buf, 20, "%s\n",
h->transMethod & CFGTBL_Trans_Performant ?
"performant" : "simple");
}
/* List of controllers which cannot be hard reset on kexec with reset_devices */
static u32 unresettable_controller[] = {
0x324a103C, /* Smart Array P712m */
0x324b103C, /* SmartArray P711m */
0x3223103C, /* Smart Array P800 */
0x3234103C, /* Smart Array P400 */
0x3235103C, /* Smart Array P400i */
0x3211103C, /* Smart Array E200i */
0x3212103C, /* Smart Array E200 */
0x3213103C, /* Smart Array E200i */
0x3214103C, /* Smart Array E200i */
0x3215103C, /* Smart Array E200i */
0x3237103C, /* Smart Array E500 */
0x323D103C, /* Smart Array P700m */
0x40800E11, /* Smart Array 5i */
0x409C0E11, /* Smart Array 6400 */
0x409D0E11, /* Smart Array 6400 EM */
0x40700E11, /* Smart Array 5300 */
0x40820E11, /* Smart Array 532 */
0x40830E11, /* Smart Array 5312 */
0x409A0E11, /* Smart Array 641 */
0x409B0E11, /* Smart Array 642 */
0x40910E11, /* Smart Array 6i */
};
/* List of controllers which cannot even be soft reset */
static u32 soft_unresettable_controller[] = {
0x40800E11, /* Smart Array 5i */
0x40700E11, /* Smart Array 5300 */
0x40820E11, /* Smart Array 532 */
0x40830E11, /* Smart Array 5312 */
0x409A0E11, /* Smart Array 641 */
0x409B0E11, /* Smart Array 642 */
0x40910E11, /* Smart Array 6i */
/* Exclude 640x boards. These are two pci devices in one slot
* which share a battery backed cache module. One controls the
* cache, the other accesses the cache through the one that controls
* it. If we reset the one controlling the cache, the other will
* likely not be happy. Just forbid resetting this conjoined mess.
* The 640x isn't really supported by hpsa anyway.
*/
0x409C0E11, /* Smart Array 6400 */
0x409D0E11, /* Smart Array 6400 EM */
};
static int ctlr_is_hard_resettable(u32 board_id)
{
int i;
for (i = 0; i < ARRAY_SIZE(unresettable_controller); i++)
if (unresettable_controller[i] == board_id)
return 0;
return 1;
}
static int ctlr_is_soft_resettable(u32 board_id)
{
int i;
for (i = 0; i < ARRAY_SIZE(soft_unresettable_controller); i++)
if (soft_unresettable_controller[i] == board_id)
return 0;
return 1;
}
static int ctlr_is_resettable(u32 board_id)
{
return ctlr_is_hard_resettable(board_id) ||
ctlr_is_soft_resettable(board_id);
}
static ssize_t host_show_resettable(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct ctlr_info *h;
struct Scsi_Host *shost = class_to_shost(dev);
h = shost_to_hba(shost);
return snprintf(buf, 20, "%d\n", ctlr_is_resettable(h->board_id));
}
static inline int is_logical_dev_addr_mode(unsigned char scsi3addr[])
{
return (scsi3addr[3] & 0xC0) == 0x40;
}
static const char *raid_label[] = { "0", "4", "1(1+0)", "5", "5+1", "ADG",
"1(ADM)", "UNKNOWN"
};
#define RAID_UNKNOWN (ARRAY_SIZE(raid_label) - 1)
static ssize_t raid_level_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t l = 0;
unsigned char rlevel;
struct ctlr_info *h;
struct scsi_device *sdev;
struct hpsa_scsi_dev_t *hdev;
unsigned long flags;
sdev = to_scsi_device(dev);
h = sdev_to_hba(sdev);
spin_lock_irqsave(&h->lock, flags);
hdev = sdev->hostdata;
if (!hdev) {
spin_unlock_irqrestore(&h->lock, flags);
return -ENODEV;
}
/* Is this even a logical drive? */
if (!is_logical_dev_addr_mode(hdev->scsi3addr)) {
spin_unlock_irqrestore(&h->lock, flags);
l = snprintf(buf, PAGE_SIZE, "N/A\n");
return l;
}
rlevel = hdev->raid_level;
spin_unlock_irqrestore(&h->lock, flags);
if (rlevel > RAID_UNKNOWN)
rlevel = RAID_UNKNOWN;
l = snprintf(buf, PAGE_SIZE, "RAID %s\n", raid_label[rlevel]);
return l;
}
static ssize_t lunid_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct ctlr_info *h;
struct scsi_device *sdev;
struct hpsa_scsi_dev_t *hdev;
unsigned long flags;
unsigned char lunid[8];
sdev = to_scsi_device(dev);
h = sdev_to_hba(sdev);
spin_lock_irqsave(&h->lock, flags);
hdev = sdev->hostdata;
if (!hdev) {
spin_unlock_irqrestore(&h->lock, flags);
return -ENODEV;
}
memcpy(lunid, hdev->scsi3addr, sizeof(lunid));
spin_unlock_irqrestore(&h->lock, flags);
return snprintf(buf, 20, "0x%02x%02x%02x%02x%02x%02x%02x%02x\n",
lunid[0], lunid[1], lunid[2], lunid[3],
lunid[4], lunid[5], lunid[6], lunid[7]);
}
static ssize_t unique_id_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct ctlr_info *h;
struct scsi_device *sdev;
struct hpsa_scsi_dev_t *hdev;
unsigned long flags;
unsigned char sn[16];
sdev = to_scsi_device(dev);
h = sdev_to_hba(sdev);
spin_lock_irqsave(&h->lock, flags);
hdev = sdev->hostdata;
if (!hdev) {
spin_unlock_irqrestore(&h->lock, flags);
return -ENODEV;
}
memcpy(sn, hdev->device_id, sizeof(sn));
spin_unlock_irqrestore(&h->lock, flags);
return snprintf(buf, 16 * 2 + 2,
"%02X%02X%02X%02X%02X%02X%02X%02X"
"%02X%02X%02X%02X%02X%02X%02X%02X\n",
sn[0], sn[1], sn[2], sn[3],
sn[4], sn[5], sn[6], sn[7],
sn[8], sn[9], sn[10], sn[11],
sn[12], sn[13], sn[14], sn[15]);
}
static DEVICE_ATTR(raid_level, S_IRUGO, raid_level_show, NULL);
static DEVICE_ATTR(lunid, S_IRUGO, lunid_show, NULL);
static DEVICE_ATTR(unique_id, S_IRUGO, unique_id_show, NULL);
static DEVICE_ATTR(rescan, S_IWUSR, NULL, host_store_rescan);
static DEVICE_ATTR(firmware_revision, S_IRUGO,
host_show_firmware_revision, NULL);
static DEVICE_ATTR(commands_outstanding, S_IRUGO,
host_show_commands_outstanding, NULL);
static DEVICE_ATTR(transport_mode, S_IRUGO,
host_show_transport_mode, NULL);
static DEVICE_ATTR(resettable, S_IRUGO,
host_show_resettable, NULL);
static struct device_attribute *hpsa_sdev_attrs[] = {
&dev_attr_raid_level,
&dev_attr_lunid,
&dev_attr_unique_id,
NULL,
};
static struct device_attribute *hpsa_shost_attrs[] = {
&dev_attr_rescan,
&dev_attr_firmware_revision,
&dev_attr_commands_outstanding,
&dev_attr_transport_mode,
&dev_attr_resettable,
NULL,
};
static struct scsi_host_template hpsa_driver_template = {
.module = THIS_MODULE,
.name = HPSA,
.proc_name = HPSA,
.queuecommand = hpsa_scsi_queue_command,
.scan_start = hpsa_scan_start,
.scan_finished = hpsa_scan_finished,
.change_queue_depth = hpsa_change_queue_depth,
.this_id = -1,
.use_clustering = ENABLE_CLUSTERING,
.eh_abort_handler = hpsa_eh_abort_handler,
.eh_device_reset_handler = hpsa_eh_device_reset_handler,
.ioctl = hpsa_ioctl,
.slave_alloc = hpsa_slave_alloc,
.slave_destroy = hpsa_slave_destroy,
#ifdef CONFIG_COMPAT
.compat_ioctl = hpsa_compat_ioctl,
#endif
.sdev_attrs = hpsa_sdev_attrs,
.shost_attrs = hpsa_shost_attrs,
.max_sectors = 8192,
};
/* Enqueuing and dequeuing functions for cmdlists. */
static inline void addQ(struct list_head *list, struct CommandList *c)
{
list_add_tail(&c->list, list);
}
static inline u32 next_command(struct ctlr_info *h, u8 q)
{
u32 a;
struct reply_pool *rq = &h->reply_queue[q];
unsigned long flags;
if (unlikely(!(h->transMethod & CFGTBL_Trans_Performant)))
return h->access.command_completed(h, q);
if ((rq->head[rq->current_entry] & 1) == rq->wraparound) {
a = rq->head[rq->current_entry];
rq->current_entry++;
spin_lock_irqsave(&h->lock, flags);
h->commands_outstanding--;
spin_unlock_irqrestore(&h->lock, flags);
} else {
a = FIFO_EMPTY;
}
/* Check for wraparound */
if (rq->current_entry == h->max_commands) {
rq->current_entry = 0;
rq->wraparound ^= 1;
}
return a;
}
/* set_performant_mode: Modify the tag for cciss performant
* set bit 0 for pull model, bits 3-1 for block fetch
* register number
*/
static void set_performant_mode(struct ctlr_info *h, struct CommandList *c)
{
if (likely(h->transMethod & CFGTBL_Trans_Performant)) {
c->busaddr |= 1 | (h->blockFetchTable[c->Header.SGList] << 1);
if (likely(h->msix_vector))
c->Header.ReplyQueue =
smp_processor_id() % h->nreply_queues;
}
}
static int is_firmware_flash_cmd(u8 *cdb)
{
return cdb[0] == BMIC_WRITE && cdb[6] == BMIC_FLASH_FIRMWARE;
}
/*
* During firmware flash, the heartbeat register may not update as frequently
* as it should. So we dial down lockup detection during firmware flash. and
* dial it back up when firmware flash completes.
*/
#define HEARTBEAT_SAMPLE_INTERVAL_DURING_FLASH (240 * HZ)
#define HEARTBEAT_SAMPLE_INTERVAL (30 * HZ)
static void dial_down_lockup_detection_during_fw_flash(struct ctlr_info *h,
struct CommandList *c)
{
if (!is_firmware_flash_cmd(c->Request.CDB))
return;
atomic_inc(&h->firmware_flash_in_progress);
h->heartbeat_sample_interval = HEARTBEAT_SAMPLE_INTERVAL_DURING_FLASH;
}
static void dial_up_lockup_detection_on_fw_flash_complete(struct ctlr_info *h,
struct CommandList *c)
{
if (is_firmware_flash_cmd(c->Request.CDB) &&
atomic_dec_and_test(&h->firmware_flash_in_progress))
h->heartbeat_sample_interval = HEARTBEAT_SAMPLE_INTERVAL;
}
static void enqueue_cmd_and_start_io(struct ctlr_info *h,
struct CommandList *c)
{
unsigned long flags;
set_performant_mode(h, c);
dial_down_lockup_detection_during_fw_flash(h, c);
spin_lock_irqsave(&h->lock, flags);
addQ(&h->reqQ, c);
h->Qdepth++;
spin_unlock_irqrestore(&h->lock, flags);
start_io(h);
}
static inline void removeQ(struct CommandList *c)
{
if (WARN_ON(list_empty(&c->list)))
return;
list_del_init(&c->list);
}
static inline int is_hba_lunid(unsigned char scsi3addr[])
{
return memcmp(scsi3addr, RAID_CTLR_LUNID, 8) == 0;
}
static inline int is_scsi_rev_5(struct ctlr_info *h)
{
if (!h->hba_inquiry_data)
return 0;
if ((h->hba_inquiry_data[2] & 0x07) == 5)
return 1;
return 0;
}
static int hpsa_find_target_lun(struct ctlr_info *h,
unsigned char scsi3addr[], int bus, int *target, int *lun)
{
/* finds an unused bus, target, lun for a new physical device
* assumes h->devlock is held
*/
int i, found = 0;
DECLARE_BITMAP(lun_taken, HPSA_MAX_DEVICES);
bitmap_zero(lun_taken, HPSA_MAX_DEVICES);
for (i = 0; i < h->ndevices; i++) {
if (h->dev[i]->bus == bus && h->dev[i]->target != -1)
__set_bit(h->dev[i]->target, lun_taken);
}
i = find_first_zero_bit(lun_taken, HPSA_MAX_DEVICES);
if (i < HPSA_MAX_DEVICES) {
/* *bus = 1; */
*target = i;
*lun = 0;
found = 1;
}
return !found;
}
/* Add an entry into h->dev[] array. */
static int hpsa_scsi_add_entry(struct ctlr_info *h, int hostno,
struct hpsa_scsi_dev_t *device,
struct hpsa_scsi_dev_t *added[], int *nadded)
{
/* assumes h->devlock is held */
int n = h->ndevices;
int i;
unsigned char addr1[8], addr2[8];
struct hpsa_scsi_dev_t *sd;
if (n >= HPSA_MAX_DEVICES) {
dev_err(&h->pdev->dev, "too many devices, some will be "
"inaccessible.\n");
return -1;
}
/* physical devices do not have lun or target assigned until now. */
if (device->lun != -1)
/* Logical device, lun is already assigned. */
goto lun_assigned;
/* If this device a non-zero lun of a multi-lun device
* byte 4 of the 8-byte LUN addr will contain the logical
* unit no, zero otherise.
*/
if (device->scsi3addr[4] == 0) {
/* This is not a non-zero lun of a multi-lun device */
if (hpsa_find_target_lun(h, device->scsi3addr,
device->bus, &device->target, &device->lun) != 0)
return -1;
goto lun_assigned;
}
/* This is a non-zero lun of a multi-lun device.
* Search through our list and find the device which
* has the same 8 byte LUN address, excepting byte 4.
* Assign the same bus and target for this new LUN.
* Use the logical unit number from the firmware.
*/
memcpy(addr1, device->scsi3addr, 8);
addr1[4] = 0;
for (i = 0; i < n; i++) {
sd = h->dev[i];
memcpy(addr2, sd->scsi3addr, 8);
addr2[4] = 0;
/* differ only in byte 4? */
if (memcmp(addr1, addr2, 8) == 0) {
device->bus = sd->bus;
device->target = sd->target;
device->lun = device->scsi3addr[4];
break;
}
}
if (device->lun == -1) {
dev_warn(&h->pdev->dev, "physical device with no LUN=0,"
" suspect firmware bug or unsupported hardware "
"configuration.\n");
return -1;
}
lun_assigned:
h->dev[n] = device;
h->ndevices++;
added[*nadded] = device;
(*nadded)++;
/* initially, (before registering with scsi layer) we don't
* know our hostno and we don't want to print anything first
* time anyway (the scsi layer's inquiries will show that info)
*/
/* if (hostno != -1) */
dev_info(&h->pdev->dev, "%s device c%db%dt%dl%d added.\n",
scsi_device_type(device->devtype), hostno,
device->bus, device->target, device->lun);
return 0;
}
/* Update an entry in h->dev[] array. */
static void hpsa_scsi_update_entry(struct ctlr_info *h, int hostno,
int entry, struct hpsa_scsi_dev_t *new_entry)
{
/* assumes h->devlock is held */
BUG_ON(entry < 0 || entry >= HPSA_MAX_DEVICES);
/* Raid level changed. */
h->dev[entry]->raid_level = new_entry->raid_level;
dev_info(&h->pdev->dev, "%s device c%db%dt%dl%d updated.\n",
scsi_device_type(new_entry->devtype), hostno, new_entry->bus,
new_entry->target, new_entry->lun);
}
/* Replace an entry from h->dev[] array. */
static void hpsa_scsi_replace_entry(struct ctlr_info *h, int hostno,
int entry, struct hpsa_scsi_dev_t *new_entry,
struct hpsa_scsi_dev_t *added[], int *nadded,
struct hpsa_scsi_dev_t *removed[], int *nremoved)
{
/* assumes h->devlock is held */
BUG_ON(entry < 0 || entry >= HPSA_MAX_DEVICES);
removed[*nremoved] = h->dev[entry];
(*nremoved)++;
/*
* New physical devices won't have target/lun assigned yet
* so we need to preserve the values in the slot we are replacing.
*/
if (new_entry->target == -1) {
new_entry->target = h->dev[entry]->target;
new_entry->lun = h->dev[entry]->lun;
}
h->dev[entry] = new_entry;
added[*nadded] = new_entry;
(*nadded)++;
dev_info(&h->pdev->dev, "%s device c%db%dt%dl%d changed.\n",
scsi_device_type(new_entry->devtype), hostno, new_entry->bus,
new_entry->target, new_entry->lun);
}
/* Remove an entry from h->dev[] array. */
static void hpsa_scsi_remove_entry(struct ctlr_info *h, int hostno, int entry,
struct hpsa_scsi_dev_t *removed[], int *nremoved)
{
/* assumes h->devlock is held */
int i;
struct hpsa_scsi_dev_t *sd;
BUG_ON(entry < 0 || entry >= HPSA_MAX_DEVICES);
sd = h->dev[entry];
removed[*nremoved] = h->dev[entry];
(*nremoved)++;
for (i = entry; i < h->ndevices-1; i++)
h->dev[i] = h->dev[i+1];
h->ndevices--;
dev_info(&h->pdev->dev, "%s device c%db%dt%dl%d removed.\n",
scsi_device_type(sd->devtype), hostno, sd->bus, sd->target,
sd->lun);
}
#define SCSI3ADDR_EQ(a, b) ( \
(a)[7] == (b)[7] && \
(a)[6] == (b)[6] && \
(a)[5] == (b)[5] && \
(a)[4] == (b)[4] && \
(a)[3] == (b)[3] && \
(a)[2] == (b)[2] && \
(a)[1] == (b)[1] && \
(a)[0] == (b)[0])
static void fixup_botched_add(struct ctlr_info *h,
struct hpsa_scsi_dev_t *added)
{
/* called when scsi_add_device fails in order to re-adjust
* h->dev[] to match the mid layer's view.
*/
unsigned long flags;
int i, j;
spin_lock_irqsave(&h->lock, flags);
for (i = 0; i < h->ndevices; i++) {
if (h->dev[i] == added) {
for (j = i; j < h->ndevices-1; j++)
h->dev[j] = h->dev[j+1];
h->ndevices--;
break;
}
}
spin_unlock_irqrestore(&h->lock, flags);
kfree(added);
}
static inline int device_is_the_same(struct hpsa_scsi_dev_t *dev1,
struct hpsa_scsi_dev_t *dev2)
{
/* we compare everything except lun and target as these
* are not yet assigned. Compare parts likely
* to differ first
*/
if (memcmp(dev1->scsi3addr, dev2->scsi3addr,
sizeof(dev1->scsi3addr)) != 0)
return 0;
if (memcmp(dev1->device_id, dev2->device_id,
sizeof(dev1->device_id)) != 0)
return 0;
if (memcmp(dev1->model, dev2->model, sizeof(dev1->model)) != 0)
return 0;
if (memcmp(dev1->vendor, dev2->vendor, sizeof(dev1->vendor)) != 0)
return 0;
if (dev1->devtype != dev2->devtype)
return 0;
if (dev1->bus != dev2->bus)
return 0;
return 1;
}
static inline int device_updated(struct hpsa_scsi_dev_t *dev1,
struct hpsa_scsi_dev_t *dev2)
{
/* Device attributes that can change, but don't mean
* that the device is a different device, nor that the OS
* needs to be told anything about the change.
*/
if (dev1->raid_level != dev2->raid_level)
return 1;
return 0;
}
/* Find needle in haystack. If exact match found, return DEVICE_SAME,
* and return needle location in *index. If scsi3addr matches, but not
* vendor, model, serial num, etc. return DEVICE_CHANGED, and return needle
* location in *index.
* In the case of a minor device attribute change, such as RAID level, just
* return DEVICE_UPDATED, along with the updated device's location in index.
* If needle not found, return DEVICE_NOT_FOUND.
*/
static int hpsa_scsi_find_entry(struct hpsa_scsi_dev_t *needle,
struct hpsa_scsi_dev_t *haystack[], int haystack_size,
int *index)
{
int i;
#define DEVICE_NOT_FOUND 0
#define DEVICE_CHANGED 1
#define DEVICE_SAME 2
#define DEVICE_UPDATED 3
for (i = 0; i < haystack_size; i++) {
if (haystack[i] == NULL) /* previously removed. */
continue;
if (SCSI3ADDR_EQ(needle->scsi3addr, haystack[i]->scsi3addr)) {
*index = i;
if (device_is_the_same(needle, haystack[i])) {
if (device_updated(needle, haystack[i]))
return DEVICE_UPDATED;
return DEVICE_SAME;
} else {
return DEVICE_CHANGED;
}
}
}
*index = -1;
return DEVICE_NOT_FOUND;
}
static void adjust_hpsa_scsi_table(struct ctlr_info *h, int hostno,
struct hpsa_scsi_dev_t *sd[], int nsds)
{
/* sd contains scsi3 addresses and devtypes, and inquiry
* data. This function takes what's in sd to be the current
* reality and updates h->dev[] to reflect that reality.
*/
int i, entry, device_change, changes = 0;
struct hpsa_scsi_dev_t *csd;
unsigned long flags;
struct hpsa_scsi_dev_t **added, **removed;
int nadded, nremoved;
struct Scsi_Host *sh = NULL;
added = kzalloc(sizeof(*added) * HPSA_MAX_DEVICES, GFP_KERNEL);
removed = kzalloc(sizeof(*removed) * HPSA_MAX_DEVICES, GFP_KERNEL);
if (!added || !removed) {
dev_warn(&h->pdev->dev, "out of memory in "
"adjust_hpsa_scsi_table\n");
goto free_and_out;
}
spin_lock_irqsave(&h->devlock, flags);
/* find any devices in h->dev[] that are not in
* sd[] and remove them from h->dev[], and for any
* devices which have changed, remove the old device
* info and add the new device info.
* If minor device attributes change, just update
* the existing device structure.
*/
i = 0;
nremoved = 0;
nadded = 0;
while (i < h->ndevices) {
csd = h->dev[i];
device_change = hpsa_scsi_find_entry(csd, sd, nsds, &entry);
if (device_change == DEVICE_NOT_FOUND) {
changes++;
hpsa_scsi_remove_entry(h, hostno, i,
removed, &nremoved);
continue; /* remove ^^^, hence i not incremented */
} else if (device_change == DEVICE_CHANGED) {
changes++;
hpsa_scsi_replace_entry(h, hostno, i, sd[entry],
added, &nadded, removed, &nremoved);
/* Set it to NULL to prevent it from being freed
* at the bottom of hpsa_update_scsi_devices()
*/
sd[entry] = NULL;
} else if (device_change == DEVICE_UPDATED) {
hpsa_scsi_update_entry(h, hostno, i, sd[entry]);
}
i++;
}
/* Now, make sure every device listed in sd[] is also
* listed in h->dev[], adding them if they aren't found
*/
for (i = 0; i < nsds; i++) {
if (!sd[i]) /* if already added above. */
continue;
device_change = hpsa_scsi_find_entry(sd[i], h->dev,
h->ndevices, &entry);
if (device_change == DEVICE_NOT_FOUND) {
changes++;
if (hpsa_scsi_add_entry(h, hostno, sd[i],
added, &nadded) != 0)
break;
sd[i] = NULL; /* prevent from being freed later. */
} else if (device_change == DEVICE_CHANGED) {
/* should never happen... */
changes++;
dev_warn(&h->pdev->dev,
"device unexpectedly changed.\n");
/* but if it does happen, we just ignore that device */
}
}
spin_unlock_irqrestore(&h->devlock, flags);
/* Don't notify scsi mid layer of any changes the first time through
* (or if there are no changes) scsi_scan_host will do it later the
* first time through.
*/
if (hostno == -1 || !changes)
goto free_and_out;
sh = h->scsi_host;
/* Notify scsi mid layer of any removed devices */
for (i = 0; i < nremoved; i++) {
struct scsi_device *sdev =
scsi_device_lookup(sh, removed[i]->bus,
removed[i]->target, removed[i]->lun);
if (sdev != NULL) {
scsi_remove_device(sdev);
scsi_device_put(sdev);
} else {
/* We don't expect to get here.
* future cmds to this device will get selection
* timeout as if the device was gone.
*/
dev_warn(&h->pdev->dev, "didn't find c%db%dt%dl%d "
" for removal.", hostno, removed[i]->bus,
removed[i]->target, removed[i]->lun);
}
kfree(removed[i]);
removed[i] = NULL;
}
/* Notify scsi mid layer of any added devices */
for (i = 0; i < nadded; i++) {
if (scsi_add_device(sh, added[i]->bus,
added[i]->target, added[i]->lun) == 0)
continue;
dev_warn(&h->pdev->dev, "scsi_add_device c%db%dt%dl%d failed, "
"device not added.\n", hostno, added[i]->bus,
added[i]->target, added[i]->lun);
/* now we have to remove it from h->dev,
* since it didn't get added to scsi mid layer
*/
fixup_botched_add(h, added[i]);
}
free_and_out:
kfree(added);
kfree(removed);
}
/*
* Lookup bus/target/lun and retrun corresponding struct hpsa_scsi_dev_t *
* Assume's h->devlock is held.
*/
static struct hpsa_scsi_dev_t *lookup_hpsa_scsi_dev(struct ctlr_info *h,
int bus, int target, int lun)
{
int i;
struct hpsa_scsi_dev_t *sd;
for (i = 0; i < h->ndevices; i++) {
sd = h->dev[i];
if (sd->bus == bus && sd->target == target && sd->lun == lun)
return sd;
}
return NULL;
}
/* link sdev->hostdata to our per-device structure. */
static int hpsa_slave_alloc(struct scsi_device *sdev)
{
struct hpsa_scsi_dev_t *sd;
unsigned long flags;
struct ctlr_info *h;
h = sdev_to_hba(sdev);
spin_lock_irqsave(&h->devlock, flags);
sd = lookup_hpsa_scsi_dev(h, sdev_channel(sdev),
sdev_id(sdev), sdev->lun);
if (sd != NULL)
sdev->hostdata = sd;
spin_unlock_irqrestore(&h->devlock, flags);
return 0;
}
static void hpsa_slave_destroy(struct scsi_device *sdev)
{
/* nothing to do. */
}
static void hpsa_free_sg_chain_blocks(struct ctlr_info *h)
{
int i;
if (!h->cmd_sg_list)
return;
for (i = 0; i < h->nr_cmds; i++) {
kfree(h->cmd_sg_list[i]);
h->cmd_sg_list[i] = NULL;
}
kfree(h->cmd_sg_list);
h->cmd_sg_list = NULL;
}
static int hpsa_allocate_sg_chain_blocks(struct ctlr_info *h)
{
int i;
if (h->chainsize <= 0)
return 0;
h->cmd_sg_list = kzalloc(sizeof(*h->cmd_sg_list) * h->nr_cmds,
GFP_KERNEL);
if (!h->cmd_sg_list)
return -ENOMEM;
for (i = 0; i < h->nr_cmds; i++) {
h->cmd_sg_list[i] = kmalloc(sizeof(*h->cmd_sg_list[i]) *
h->chainsize, GFP_KERNEL);
if (!h->cmd_sg_list[i])
goto clean;
}
return 0;
clean:
hpsa_free_sg_chain_blocks(h);
return -ENOMEM;
}
static int hpsa_map_sg_chain_block(struct ctlr_info *h,
struct CommandList *c)
{
struct SGDescriptor *chain_sg, *chain_block;
u64 temp64;
chain_sg = &c->SG[h->max_cmd_sg_entries - 1];
chain_block = h->cmd_sg_list[c->cmdindex];
chain_sg->Ext = HPSA_SG_CHAIN;
chain_sg->Len = sizeof(*chain_sg) *
(c->Header.SGTotal - h->max_cmd_sg_entries);
temp64 = pci_map_single(h->pdev, chain_block, chain_sg->Len,
PCI_DMA_TODEVICE);
if (dma_mapping_error(&h->pdev->dev, temp64)) {
/* prevent subsequent unmapping */
chain_sg->Addr.lower = 0;
chain_sg->Addr.upper = 0;
return -1;
}
chain_sg->Addr.lower = (u32) (temp64 & 0x0FFFFFFFFULL);
chain_sg->Addr.upper = (u32) ((temp64 >> 32) & 0x0FFFFFFFFULL);
return 0;
}
static void hpsa_unmap_sg_chain_block(struct ctlr_info *h,
struct CommandList *c)
{
struct SGDescriptor *chain_sg;
union u64bit temp64;
if (c->Header.SGTotal <= h->max_cmd_sg_entries)
return;
chain_sg = &c->SG[h->max_cmd_sg_entries - 1];
temp64.val32.lower = chain_sg->Addr.lower;
temp64.val32.upper = chain_sg->Addr.upper;
pci_unmap_single(h->pdev, temp64.val, chain_sg->Len, PCI_DMA_TODEVICE);
}
static void complete_scsi_command(struct CommandList *cp)
{
struct scsi_cmnd *cmd;
struct ctlr_info *h;
struct ErrorInfo *ei;
unsigned char sense_key;
unsigned char asc; /* additional sense code */
unsigned char ascq; /* additional sense code qualifier */
unsigned long sense_data_size;
ei = cp->err_info;
cmd = (struct scsi_cmnd *) cp->scsi_cmd;
h = cp->h;
scsi_dma_unmap(cmd); /* undo the DMA mappings */
if (cp->Header.SGTotal > h->max_cmd_sg_entries)
hpsa_unmap_sg_chain_block(h, cp);
cmd->result = (DID_OK << 16); /* host byte */
cmd->result |= (COMMAND_COMPLETE << 8); /* msg byte */
cmd->result |= ei->ScsiStatus;
/* copy the sense data whether we need to or not. */
if (SCSI_SENSE_BUFFERSIZE < sizeof(ei->SenseInfo))
sense_data_size = SCSI_SENSE_BUFFERSIZE;
else
sense_data_size = sizeof(ei->SenseInfo);
if (ei->SenseLen < sense_data_size)
sense_data_size = ei->SenseLen;
memcpy(cmd->sense_buffer, ei->SenseInfo, sense_data_size);
scsi_set_resid(cmd, ei->ResidualCnt);
if (ei->CommandStatus == 0) {
cmd->scsi_done(cmd);
cmd_free(h, cp);
return;
}
/* an error has occurred */
switch (ei->CommandStatus) {
case CMD_TARGET_STATUS:
if (ei->ScsiStatus) {
/* Get sense key */
sense_key = 0xf & ei->SenseInfo[2];
/* Get additional sense code */
asc = ei->SenseInfo[12];
/* Get addition sense code qualifier */
ascq = ei->SenseInfo[13];
}
if (ei->ScsiStatus == SAM_STAT_CHECK_CONDITION) {
if (check_for_unit_attention(h, cp)) {
cmd->result = DID_SOFT_ERROR << 16;
break;
}
if (sense_key == ILLEGAL_REQUEST) {
/*
* SCSI REPORT_LUNS is commonly unsupported on
* Smart Array. Suppress noisy complaint.
*/
if (cp->Request.CDB[0] == REPORT_LUNS)
break;
/* If ASC/ASCQ indicate Logical Unit
* Not Supported condition,
*/
if ((asc == 0x25) && (ascq == 0x0)) {
dev_warn(&h->pdev->dev, "cp %p "
"has check condition\n", cp);
break;
}
}
if (sense_key == NOT_READY) {
/* If Sense is Not Ready, Logical Unit
* Not ready, Manual Intervention
* required
*/
if ((asc == 0x04) && (ascq == 0x03)) {
dev_warn(&h->pdev->dev, "cp %p "
"has check condition: unit "
"not ready, manual "
"intervention required\n", cp);
break;
}
}
if (sense_key == ABORTED_COMMAND) {
/* Aborted command is retryable */
dev_warn(&h->pdev->dev, "cp %p "
"has check condition: aborted command: "
"ASC: 0x%x, ASCQ: 0x%x\n",
cp, asc, ascq);
cmd->result = DID_SOFT_ERROR << 16;
break;
}
/* Must be some other type of check condition */
dev_dbg(&h->pdev->dev, "cp %p has check condition: "
"unknown type: "
"Sense: 0x%x, ASC: 0x%x, ASCQ: 0x%x, "
"Returning result: 0x%x, "
"cmd=[%02x %02x %02x %02x %02x "
"%02x %02x %02x %02x %02x %02x "
"%02x %02x %02x %02x %02x]\n",
cp, sense_key, asc, ascq,
cmd->result,
cmd->cmnd[0], cmd->cmnd[1],
cmd->cmnd[2], cmd->cmnd[3],
cmd->cmnd[4], cmd->cmnd[5],
cmd->cmnd[6], cmd->cmnd[7],
cmd->cmnd[8], cmd->cmnd[9],
cmd->cmnd[10], cmd->cmnd[11],
cmd->cmnd[12], cmd->cmnd[13],
cmd->cmnd[14], cmd->cmnd[15]);
break;
}
/* Problem was not a check condition
* Pass it up to the upper layers...
*/
if (ei->ScsiStatus) {
dev_warn(&h->pdev->dev, "cp %p has status 0x%x "
"Sense: 0x%x, ASC: 0x%x, ASCQ: 0x%x, "
"Returning result: 0x%x\n",
cp, ei->ScsiStatus,
sense_key, asc, ascq,
cmd->result);
} else { /* scsi status is zero??? How??? */
dev_warn(&h->pdev->dev, "cp %p SCSI status was 0. "
"Returning no connection.\n", cp),
/* Ordinarily, this case should never happen,
* but there is a bug in some released firmware
* revisions that allows it to happen if, for
* example, a 4100 backplane loses power and
* the tape drive is in it. We assume that
* it's a fatal error of some kind because we
* can't show that it wasn't. We will make it
* look like selection timeout since that is
* the most common reason for this to occur,
* and it's severe enough.
*/
cmd->result = DID_NO_CONNECT << 16;
}
break;
case CMD_DATA_UNDERRUN: /* let mid layer handle it. */
break;
case CMD_DATA_OVERRUN:
dev_warn(&h->pdev->dev, "cp %p has"
" completed with data overrun "
"reported\n", cp);
break;
case CMD_INVALID: {
/* print_bytes(cp, sizeof(*cp), 1, 0);
print_cmd(cp); */
/* We get CMD_INVALID if you address a non-existent device
* instead of a selection timeout (no response). You will
* see this if you yank out a drive, then try to access it.
* This is kind of a shame because it means that any other
* CMD_INVALID (e.g. driver bug) will get interpreted as a
* missing target. */
cmd->result = DID_NO_CONNECT << 16;
}
break;
case CMD_PROTOCOL_ERR:
cmd->result = DID_ERROR << 16;
dev_warn(&h->pdev->dev, "cp %p has "
"protocol error\n", cp);
break;
case CMD_HARDWARE_ERR:
cmd->result = DID_ERROR << 16;
dev_warn(&h->pdev->dev, "cp %p had hardware error\n", cp);
break;
case CMD_CONNECTION_LOST:
cmd->result = DID_ERROR << 16;
dev_warn(&h->pdev->dev, "cp %p had connection lost\n", cp);
break;
case CMD_ABORTED:
cmd->result = DID_ABORT << 16;
dev_warn(&h->pdev->dev, "cp %p was aborted with status 0x%x\n",
cp, ei->ScsiStatus);
break;
case CMD_ABORT_FAILED:
cmd->result = DID_ERROR << 16;
dev_warn(&h->pdev->dev, "cp %p reports abort failed\n", cp);
break;
case CMD_UNSOLICITED_ABORT:
cmd->result = DID_SOFT_ERROR << 16; /* retry the command */
dev_warn(&h->pdev->dev, "cp %p aborted due to an unsolicited "
"abort\n", cp);
break;
case CMD_TIMEOUT:
cmd->result = DID_TIME_OUT << 16;
dev_warn(&h->pdev->dev, "cp %p timedout\n", cp);
break;
case CMD_UNABORTABLE:
cmd->result = DID_ERROR << 16;
dev_warn(&h->pdev->dev, "Command unabortable\n");
break;
default:
cmd->result = DID_ERROR << 16;
dev_warn(&h->pdev->dev, "cp %p returned unknown status %x\n",
cp, ei->CommandStatus);
}
cmd->scsi_done(cmd);
cmd_free(h, cp);
}
static void hpsa_pci_unmap(struct pci_dev *pdev,
struct CommandList *c, int sg_used, int data_direction)
{
int i;
union u64bit addr64;
for (i = 0; i < sg_used; i++) {
addr64.val32.lower = c->SG[i].Addr.lower;
addr64.val32.upper = c->SG[i].Addr.upper;
pci_unmap_single(pdev, (dma_addr_t) addr64.val, c->SG[i].Len,
data_direction);
}
}
static int hpsa_map_one(struct pci_dev *pdev,
struct CommandList *cp,
unsigned char *buf,
size_t buflen,
int data_direction)
{
u64 addr64;
if (buflen == 0 || data_direction == PCI_DMA_NONE) {
cp->Header.SGList = 0;
cp->Header.SGTotal = 0;
return 0;
}
addr64 = (u64) pci_map_single(pdev, buf, buflen, data_direction);
if (dma_mapping_error(&pdev->dev, addr64)) {
/* Prevent subsequent unmap of something never mapped */
cp->Header.SGList = 0;
cp->Header.SGTotal = 0;
return -1;
}
cp->SG[0].Addr.lower =
(u32) (addr64 & (u64) 0x00000000FFFFFFFF);
cp->SG[0].Addr.upper =
(u32) ((addr64 >> 32) & (u64) 0x00000000FFFFFFFF);
cp->SG[0].Len = buflen;
cp->Header.SGList = (u8) 1; /* no. SGs contig in this cmd */
cp->Header.SGTotal = (u16) 1; /* total sgs in this cmd list */
return 0;
}
static inline void hpsa_scsi_do_simple_cmd_core(struct ctlr_info *h,
struct CommandList *c)
{
DECLARE_COMPLETION_ONSTACK(wait);
c->waiting = &wait;
enqueue_cmd_and_start_io(h, c);
wait_for_completion(&wait);
}
static void hpsa_scsi_do_simple_cmd_core_if_no_lockup(struct ctlr_info *h,
struct CommandList *c)
{
unsigned long flags;
/* If controller lockup detected, fake a hardware error. */
spin_lock_irqsave(&h->lock, flags);
if (unlikely(h->lockup_detected)) {
spin_unlock_irqrestore(&h->lock, flags);
c->err_info->CommandStatus = CMD_HARDWARE_ERR;
} else {
spin_unlock_irqrestore(&h->lock, flags);
hpsa_scsi_do_simple_cmd_core(h, c);
}
}
#define MAX_DRIVER_CMD_RETRIES 25
static void hpsa_scsi_do_simple_cmd_with_retry(struct ctlr_info *h,
struct CommandList *c, int data_direction)
{
int backoff_time = 10, retry_count = 0;
do {
memset(c->err_info, 0, sizeof(*c->err_info));
hpsa_scsi_do_simple_cmd_core(h, c);
retry_count++;
if (retry_count > 3) {
msleep(backoff_time);
if (backoff_time < 1000)
backoff_time *= 2;
}
} while ((check_for_unit_attention(h, c) ||
check_for_busy(h, c)) &&
retry_count <= MAX_DRIVER_CMD_RETRIES);
hpsa_pci_unmap(h->pdev, c, 1, data_direction);
}
static void hpsa_scsi_interpret_error(struct CommandList *cp)
{
struct ErrorInfo *ei;
struct device *d = &cp->h->pdev->dev;
ei = cp->err_info;
switch (ei->CommandStatus) {
case CMD_TARGET_STATUS:
dev_warn(d, "cmd %p has completed with errors\n", cp);
dev_warn(d, "cmd %p has SCSI Status = %x\n", cp,
ei->ScsiStatus);
if (ei->ScsiStatus == 0)
dev_warn(d, "SCSI status is abnormally zero. "
"(probably indicates selection timeout "
"reported incorrectly due to a known "
"firmware bug, circa July, 2001.)\n");
break;
case CMD_DATA_UNDERRUN: /* let mid layer handle it. */
dev_info(d, "UNDERRUN\n");
break;
case CMD_DATA_OVERRUN:
dev_warn(d, "cp %p has completed with data overrun\n", cp);
break;
case CMD_INVALID: {
/* controller unfortunately reports SCSI passthru's
* to non-existent targets as invalid commands.
*/
dev_warn(d, "cp %p is reported invalid (probably means "
"target device no longer present)\n", cp);
/* print_bytes((unsigned char *) cp, sizeof(*cp), 1, 0);
print_cmd(cp); */
}
break;
case CMD_PROTOCOL_ERR:
dev_warn(d, "cp %p has protocol error \n", cp);
break;
case CMD_HARDWARE_ERR:
/* cmd->result = DID_ERROR << 16; */
dev_warn(d, "cp %p had hardware error\n", cp);
break;
case CMD_CONNECTION_LOST:
dev_warn(d, "cp %p had connection lost\n", cp);
break;
case CMD_ABORTED:
dev_warn(d, "cp %p was aborted\n", cp);
break;
case CMD_ABORT_FAILED:
dev_warn(d, "cp %p reports abort failed\n", cp);
break;
case CMD_UNSOLICITED_ABORT:
dev_warn(d, "cp %p aborted due to an unsolicited abort\n", cp);
break;
case CMD_TIMEOUT:
dev_warn(d, "cp %p timed out\n", cp);
break;
case CMD_UNABORTABLE:
dev_warn(d, "Command unabortable\n");
break;
default:
dev_warn(d, "cp %p returned unknown status %x\n", cp,
ei->CommandStatus);
}
}
static int hpsa_scsi_do_inquiry(struct ctlr_info *h, unsigned char *scsi3addr,
unsigned char page, unsigned char *buf,
unsigned char bufsize)
{
int rc = IO_OK;
struct CommandList *c;
struct ErrorInfo *ei;
c = cmd_special_alloc(h);
if (c == NULL) { /* trouble... */
dev_warn(&h->pdev->dev, "cmd_special_alloc returned NULL!\n");
return -ENOMEM;
}
if (fill_cmd(c, HPSA_INQUIRY, h, buf, bufsize,
page, scsi3addr, TYPE_CMD)) {
rc = -1;
goto out;
}
hpsa_scsi_do_simple_cmd_with_retry(h, c, PCI_DMA_FROMDEVICE);
ei = c->err_info;
if (ei->CommandStatus != 0 && ei->CommandStatus != CMD_DATA_UNDERRUN) {
hpsa_scsi_interpret_error(c);
rc = -1;
}
out:
cmd_special_free(h, c);
return rc;
}
static int hpsa_send_reset(struct ctlr_info *h, unsigned char *scsi3addr)
{
int rc = IO_OK;
struct CommandList *c;
struct ErrorInfo *ei;
c = cmd_special_alloc(h);
if (c == NULL) { /* trouble... */
dev_warn(&h->pdev->dev, "cmd_special_alloc returned NULL!\n");
return -ENOMEM;
}
/* fill_cmd can't fail here, no data buffer to map. */
(void) fill_cmd(c, HPSA_DEVICE_RESET_MSG, h,
NULL, 0, 0, scsi3addr, TYPE_MSG);
hpsa_scsi_do_simple_cmd_core(h, c);
/* no unmap needed here because no data xfer. */
ei = c->err_info;
if (ei->CommandStatus != 0) {
hpsa_scsi_interpret_error(c);
rc = -1;
}
cmd_special_free(h, c);
return rc;
}
static void hpsa_get_raid_level(struct ctlr_info *h,
unsigned char *scsi3addr, unsigned char *raid_level)
{
int rc;
unsigned char *buf;
*raid_level = RAID_UNKNOWN;
buf = kzalloc(64, GFP_KERNEL);
if (!buf)
return;
rc = hpsa_scsi_do_inquiry(h, scsi3addr, 0xC1, buf, 64);
if (rc == 0)
*raid_level = buf[8];
if (*raid_level > RAID_UNKNOWN)
*raid_level = RAID_UNKNOWN;
kfree(buf);
return;
}
/* Get the device id from inquiry page 0x83 */
static int hpsa_get_device_id(struct ctlr_info *h, unsigned char *scsi3addr,
unsigned char *device_id, int buflen)
{
int rc;
unsigned char *buf;
if (buflen > 16)
buflen = 16;
buf = kzalloc(64, GFP_KERNEL);
if (!buf)
return -1;
rc = hpsa_scsi_do_inquiry(h, scsi3addr, 0x83, buf, 64);
if (rc == 0)
memcpy(device_id, &buf[8], buflen);
kfree(buf);
return rc != 0;
}
static int hpsa_scsi_do_report_luns(struct ctlr_info *h, int logical,
struct ReportLUNdata *buf, int bufsize,
int extended_response)
{
int rc = IO_OK;
struct CommandList *c;
unsigned char scsi3addr[8];
struct ErrorInfo *ei;
c = cmd_special_alloc(h);
if (c == NULL) { /* trouble... */
dev_err(&h->pdev->dev, "cmd_special_alloc returned NULL!\n");
return -1;
}
/* address the controller */
memset(scsi3addr, 0, sizeof(scsi3addr));
if (fill_cmd(c, logical ? HPSA_REPORT_LOG : HPSA_REPORT_PHYS, h,
buf, bufsize, 0, scsi3addr, TYPE_CMD)) {
rc = -1;
goto out;
}
if (extended_response)
c->Request.CDB[1] = extended_response;
hpsa_scsi_do_simple_cmd_with_retry(h, c, PCI_DMA_FROMDEVICE);
ei = c->err_info;
if (ei->CommandStatus != 0 &&
ei->CommandStatus != CMD_DATA_UNDERRUN) {
hpsa_scsi_interpret_error(c);
rc = -1;
}
out:
cmd_special_free(h, c);
return rc;
}
static inline int hpsa_scsi_do_report_phys_luns(struct ctlr_info *h,
struct ReportLUNdata *buf,
int bufsize, int extended_response)
{
return hpsa_scsi_do_report_luns(h, 0, buf, bufsize, extended_response);
}
static inline int hpsa_scsi_do_report_log_luns(struct ctlr_info *h,
struct ReportLUNdata *buf, int bufsize)
{
return hpsa_scsi_do_report_luns(h, 1, buf, bufsize, 0);
}
static inline void hpsa_set_bus_target_lun(struct hpsa_scsi_dev_t *device,
int bus, int target, int lun)
{
device->bus = bus;
device->target = target;
device->lun = lun;
}
static int hpsa_update_device_info(struct ctlr_info *h,
unsigned char scsi3addr[], struct hpsa_scsi_dev_t *this_device,
unsigned char *is_OBDR_device)
{
#define OBDR_SIG_OFFSET 43
#define OBDR_TAPE_SIG "$DR-10"
#define OBDR_SIG_LEN (sizeof(OBDR_TAPE_SIG) - 1)
#define OBDR_TAPE_INQ_SIZE (OBDR_SIG_OFFSET + OBDR_SIG_LEN)
unsigned char *inq_buff;
unsigned char *obdr_sig;
inq_buff = kzalloc(OBDR_TAPE_INQ_SIZE, GFP_KERNEL);
if (!inq_buff)
goto bail_out;
/* Do an inquiry to the device to see what it is. */
if (hpsa_scsi_do_inquiry(h, scsi3addr, 0, inq_buff,
(unsigned char) OBDR_TAPE_INQ_SIZE) != 0) {
/* Inquiry failed (msg printed already) */
dev_err(&h->pdev->dev,
"hpsa_update_device_info: inquiry failed\n");
goto bail_out;
}
this_device->devtype = (inq_buff[0] & 0x1f);
memcpy(this_device->scsi3addr, scsi3addr, 8);
memcpy(this_device->vendor, &inq_buff[8],
sizeof(this_device->vendor));
memcpy(this_device->model, &inq_buff[16],
sizeof(this_device->model));
memset(this_device->device_id, 0,
sizeof(this_device->device_id));
hpsa_get_device_id(h, scsi3addr, this_device->device_id,
sizeof(this_device->device_id));
if (this_device->devtype == TYPE_DISK &&
is_logical_dev_addr_mode(scsi3addr))
hpsa_get_raid_level(h, scsi3addr, &this_device->raid_level);
else
this_device->raid_level = RAID_UNKNOWN;
if (is_OBDR_device) {
/* See if this is a One-Button-Disaster-Recovery device
* by looking for "$DR-10" at offset 43 in inquiry data.
*/
obdr_sig = &inq_buff[OBDR_SIG_OFFSET];
*is_OBDR_device = (this_device->devtype == TYPE_ROM &&
strncmp(obdr_sig, OBDR_TAPE_SIG,
OBDR_SIG_LEN) == 0);
}
kfree(inq_buff);
return 0;
bail_out:
kfree(inq_buff);
return 1;
}
static unsigned char *ext_target_model[] = {
"MSA2012",
"MSA2024",
"MSA2312",
"MSA2324",
"P2000 G3 SAS",
NULL,
};
static int is_ext_target(struct ctlr_info *h, struct hpsa_scsi_dev_t *device)
{
int i;
for (i = 0; ext_target_model[i]; i++)
if (strncmp(device->model, ext_target_model[i],
strlen(ext_target_model[i])) == 0)
return 1;
return 0;
}
/* Helper function to assign bus, target, lun mapping of devices.
* Puts non-external target logical volumes on bus 0, external target logical
* volumes on bus 1, physical devices on bus 2. and the hba on bus 3.
* Logical drive target and lun are assigned at this time, but
* physical device lun and target assignment are deferred (assigned
* in hpsa_find_target_lun, called by hpsa_scsi_add_entry.)
*/
static void figure_bus_target_lun(struct ctlr_info *h,
u8 *lunaddrbytes, struct hpsa_scsi_dev_t *device)
{
u32 lunid = le32_to_cpu(*((__le32 *) lunaddrbytes));
if (!is_logical_dev_addr_mode(lunaddrbytes)) {
/* physical device, target and lun filled in later */
if (is_hba_lunid(lunaddrbytes))
hpsa_set_bus_target_lun(device, 3, 0, lunid & 0x3fff);
else
/* defer target, lun assignment for physical devices */
hpsa_set_bus_target_lun(device, 2, -1, -1);
return;
}
/* It's a logical device */
if (is_ext_target(h, device)) {
/* external target way, put logicals on bus 1
* and match target/lun numbers box
* reports, other smart array, bus 0, target 0, match lunid
*/
hpsa_set_bus_target_lun(device,
1, (lunid >> 16) & 0x3fff, lunid & 0x00ff);
return;
}
hpsa_set_bus_target_lun(device, 0, 0, lunid & 0x3fff);
}
/*
* If there is no lun 0 on a target, linux won't find any devices.
* For the external targets (arrays), we have to manually detect the enclosure
* which is at lun zero, as CCISS_REPORT_PHYSICAL_LUNS doesn't report
* it for some reason. *tmpdevice is the target we're adding,
* this_device is a pointer into the current element of currentsd[]
* that we're building up in update_scsi_devices(), below.
* lunzerobits is a bitmap that tracks which targets already have a
* lun 0 assigned.
* Returns 1 if an enclosure was added, 0 if not.
*/
static int add_ext_target_dev(struct ctlr_info *h,
struct hpsa_scsi_dev_t *tmpdevice,
struct hpsa_scsi_dev_t *this_device, u8 *lunaddrbytes,
unsigned long lunzerobits[], int *n_ext_target_devs)
{
unsigned char scsi3addr[8];
if (test_bit(tmpdevice->target, lunzerobits))
return 0; /* There is already a lun 0 on this target. */
if (!is_logical_dev_addr_mode(lunaddrbytes))
return 0; /* It's the logical targets that may lack lun 0. */
if (!is_ext_target(h, tmpdevice))
return 0; /* Only external target devices have this problem. */
if (tmpdevice->lun == 0) /* if lun is 0, then we have a lun 0. */
return 0;
memset(scsi3addr, 0, 8);
scsi3addr[3] = tmpdevice->target;
if (is_hba_lunid(scsi3addr))
return 0; /* Don't add the RAID controller here. */
if (is_scsi_rev_5(h))
return 0; /* p1210m doesn't need to do this. */
if (*n_ext_target_devs >= MAX_EXT_TARGETS) {
dev_warn(&h->pdev->dev, "Maximum number of external "
"target devices exceeded. Check your hardware "
"configuration.");
return 0;
}
if (hpsa_update_device_info(h, scsi3addr, this_device, NULL))
return 0;
(*n_ext_target_devs)++;
hpsa_set_bus_target_lun(this_device,
tmpdevice->bus, tmpdevice->target, 0);
set_bit(tmpdevice->target, lunzerobits);
return 1;
}
/*
* Do CISS_REPORT_PHYS and CISS_REPORT_LOG. Data is returned in physdev,
* logdev. The number of luns in physdev and logdev are returned in
* *nphysicals and *nlogicals, respectively.
* Returns 0 on success, -1 otherwise.
*/
static int hpsa_gather_lun_info(struct ctlr_info *h,
int reportlunsize,
struct ReportLUNdata *physdev, u32 *nphysicals,
struct ReportLUNdata *logdev, u32 *nlogicals)
{
if (hpsa_scsi_do_report_phys_luns(h, physdev, reportlunsize, 0)) {
dev_err(&h->pdev->dev, "report physical LUNs failed.\n");
return -1;
}
*nphysicals = be32_to_cpu(*((__be32 *)physdev->LUNListLength)) / 8;
if (*nphysicals > HPSA_MAX_PHYS_LUN) {
dev_warn(&h->pdev->dev, "maximum physical LUNs (%d) exceeded."
" %d LUNs ignored.\n", HPSA_MAX_PHYS_LUN,
*nphysicals - HPSA_MAX_PHYS_LUN);
*nphysicals = HPSA_MAX_PHYS_LUN;
}
if (hpsa_scsi_do_report_log_luns(h, logdev, reportlunsize)) {
dev_err(&h->pdev->dev, "report logical LUNs failed.\n");
return -1;
}
*nlogicals = be32_to_cpu(*((__be32 *) logdev->LUNListLength)) / 8;
/* Reject Logicals in excess of our max capability. */
if (*nlogicals > HPSA_MAX_LUN) {
dev_warn(&h->pdev->dev,
"maximum logical LUNs (%d) exceeded. "
"%d LUNs ignored.\n", HPSA_MAX_LUN,
*nlogicals - HPSA_MAX_LUN);
*nlogicals = HPSA_MAX_LUN;
}
if (*nlogicals + *nphysicals > HPSA_MAX_PHYS_LUN) {
dev_warn(&h->pdev->dev,
"maximum logical + physical LUNs (%d) exceeded. "
"%d LUNs ignored.\n", HPSA_MAX_PHYS_LUN,
*nphysicals + *nlogicals - HPSA_MAX_PHYS_LUN);
*nlogicals = HPSA_MAX_PHYS_LUN - *nphysicals;
}
return 0;
}
u8 *figure_lunaddrbytes(struct ctlr_info *h, int raid_ctlr_position, int i,
int nphysicals, int nlogicals, struct ReportLUNdata *physdev_list,
struct ReportLUNdata *logdev_list)
{
/* Helper function, figure out where the LUN ID info is coming from
* given index i, lists of physical and logical devices, where in
* the list the raid controller is supposed to appear (first or last)
*/
int logicals_start = nphysicals + (raid_ctlr_position == 0);
int last_device = nphysicals + nlogicals + (raid_ctlr_position == 0);
if (i == raid_ctlr_position)
return RAID_CTLR_LUNID;
if (i < logicals_start)
return &physdev_list->LUN[i - (raid_ctlr_position == 0)][0];
if (i < last_device)
return &logdev_list->LUN[i - nphysicals -
(raid_ctlr_position == 0)][0];
BUG();
return NULL;
}
static void hpsa_update_scsi_devices(struct ctlr_info *h, int hostno)
{
/* the idea here is we could get notified
* that some devices have changed, so we do a report
* physical luns and report logical luns cmd, and adjust
* our list of devices accordingly.
*
* The scsi3addr's of devices won't change so long as the
* adapter is not reset. That means we can rescan and
* tell which devices we already know about, vs. new
* devices, vs. disappearing devices.
*/
struct ReportLUNdata *physdev_list = NULL;
struct ReportLUNdata *logdev_list = NULL;
u32 nphysicals = 0;
u32 nlogicals = 0;
u32 ndev_allocated = 0;
struct hpsa_scsi_dev_t **currentsd, *this_device, *tmpdevice;
int ncurrent = 0;
int reportlunsize = sizeof(*physdev_list) + HPSA_MAX_PHYS_LUN * 8;
int i, n_ext_target_devs, ndevs_to_allocate;
int raid_ctlr_position;
DECLARE_BITMAP(lunzerobits, MAX_EXT_TARGETS);
currentsd = kzalloc(sizeof(*currentsd) * HPSA_MAX_DEVICES, GFP_KERNEL);
physdev_list = kzalloc(reportlunsize, GFP_KERNEL);
logdev_list = kzalloc(reportlunsize, GFP_KERNEL);
tmpdevice = kzalloc(sizeof(*tmpdevice), GFP_KERNEL);
if (!currentsd || !physdev_list || !logdev_list || !tmpdevice) {
dev_err(&h->pdev->dev, "out of memory\n");
goto out;
}
memset(lunzerobits, 0, sizeof(lunzerobits));
if (hpsa_gather_lun_info(h, reportlunsize, physdev_list, &nphysicals,
logdev_list, &nlogicals))
goto out;
/* We might see up to the maximum number of logical and physical disks
* plus external target devices, and a device for the local RAID
* controller.
*/
ndevs_to_allocate = nphysicals + nlogicals + MAX_EXT_TARGETS + 1;
/* Allocate the per device structures */
for (i = 0; i < ndevs_to_allocate; i++) {
if (i >= HPSA_MAX_DEVICES) {
dev_warn(&h->pdev->dev, "maximum devices (%d) exceeded."
" %d devices ignored.\n", HPSA_MAX_DEVICES,
ndevs_to_allocate - HPSA_MAX_DEVICES);
break;
}
currentsd[i] = kzalloc(sizeof(*currentsd[i]), GFP_KERNEL);
if (!currentsd[i]) {
dev_warn(&h->pdev->dev, "out of memory at %s:%d\n",
__FILE__, __LINE__);
goto out;
}
ndev_allocated++;
}
if (unlikely(is_scsi_rev_5(h)))
raid_ctlr_position = 0;
else
raid_ctlr_position = nphysicals + nlogicals;
/* adjust our table of devices */
n_ext_target_devs = 0;
for (i = 0; i < nphysicals + nlogicals + 1; i++) {
u8 *lunaddrbytes, is_OBDR = 0;
/* Figure out where the LUN ID info is coming from */
lunaddrbytes = figure_lunaddrbytes(h, raid_ctlr_position,
i, nphysicals, nlogicals, physdev_list, logdev_list);
/* skip masked physical devices. */
if (lunaddrbytes[3] & 0xC0 &&
i < nphysicals + (raid_ctlr_position == 0))
continue;
/* Get device type, vendor, model, device id */
if (hpsa_update_device_info(h, lunaddrbytes, tmpdevice,
&is_OBDR))
continue; /* skip it if we can't talk to it. */
figure_bus_target_lun(h, lunaddrbytes, tmpdevice);
this_device = currentsd[ncurrent];
/*
* For external target devices, we have to insert a LUN 0 which
* doesn't show up in CCISS_REPORT_PHYSICAL data, but there
* is nonetheless an enclosure device there. We have to
* present that otherwise linux won't find anything if
* there is no lun 0.
*/
if (add_ext_target_dev(h, tmpdevice, this_device,
lunaddrbytes, lunzerobits,
&n_ext_target_devs)) {
ncurrent++;
this_device = currentsd[ncurrent];
}
*this_device = *tmpdevice;
switch (this_device->devtype) {
case TYPE_ROM:
/* We don't *really* support actual CD-ROM devices,
* just "One Button Disaster Recovery" tape drive
* which temporarily pretends to be a CD-ROM drive.
* So we check that the device is really an OBDR tape
* device by checking for "$DR-10" in bytes 43-48 of
* the inquiry data.
*/
if (is_OBDR)
ncurrent++;
break;
case TYPE_DISK:
if (i < nphysicals)
break;
ncurrent++;
break;
case TYPE_TAPE:
case TYPE_MEDIUM_CHANGER:
ncurrent++;
break;
case TYPE_RAID:
/* Only present the Smartarray HBA as a RAID controller.
* If it's a RAID controller other than the HBA itself
* (an external RAID controller, MSA500 or similar)
* don't present it.
*/
if (!is_hba_lunid(lunaddrbytes))
break;
ncurrent++;
break;
default:
break;
}
if (ncurrent >= HPSA_MAX_DEVICES)
break;
}
adjust_hpsa_scsi_table(h, hostno, currentsd, ncurrent);
out:
kfree(tmpdevice);
for (i = 0; i < ndev_allocated; i++)
kfree(currentsd[i]);
kfree(currentsd);
kfree(physdev_list);
kfree(logdev_list);
}
/* hpsa_scatter_gather takes a struct scsi_cmnd, (cmd), and does the pci
* dma mapping and fills in the scatter gather entries of the
* hpsa command, cp.
*/
static int hpsa_scatter_gather(struct ctlr_info *h,
struct CommandList *cp,
struct scsi_cmnd *cmd)
{
unsigned int len;
struct scatterlist *sg;
u64 addr64;
int use_sg, i, sg_index, chained;
struct SGDescriptor *curr_sg;
BUG_ON(scsi_sg_count(cmd) > h->maxsgentries);
use_sg = scsi_dma_map(cmd);
if (use_sg < 0)
return use_sg;
if (!use_sg)
goto sglist_finished;
curr_sg = cp->SG;
chained = 0;
sg_index = 0;
scsi_for_each_sg(cmd, sg, use_sg, i) {
if (i == h->max_cmd_sg_entries - 1 &&
use_sg > h->max_cmd_sg_entries) {
chained = 1;
curr_sg = h->cmd_sg_list[cp->cmdindex];
sg_index = 0;
}
addr64 = (u64) sg_dma_address(sg);
len = sg_dma_len(sg);
curr_sg->Addr.lower = (u32) (addr64 & 0x0FFFFFFFFULL);
curr_sg->Addr.upper = (u32) ((addr64 >> 32) & 0x0FFFFFFFFULL);
curr_sg->Len = len;
curr_sg->Ext = 0; /* we are not chaining */
curr_sg++;
}
if (use_sg + chained > h->maxSG)
h->maxSG = use_sg + chained;
if (chained) {
cp->Header.SGList = h->max_cmd_sg_entries;
cp->Header.SGTotal = (u16) (use_sg + 1);
if (hpsa_map_sg_chain_block(h, cp)) {
scsi_dma_unmap(cmd);
return -1;
}
return 0;
}
sglist_finished:
cp->Header.SGList = (u8) use_sg; /* no. SGs contig in this cmd */
cp->Header.SGTotal = (u16) use_sg; /* total sgs in this cmd list */
return 0;
}
static int hpsa_scsi_queue_command_lck(struct scsi_cmnd *cmd,
void (*done)(struct scsi_cmnd *))
{
struct ctlr_info *h;
struct hpsa_scsi_dev_t *dev;
unsigned char scsi3addr[8];
struct CommandList *c;
unsigned long flags;
/* Get the ptr to our adapter structure out of cmd->host. */
h = sdev_to_hba(cmd->device);
dev = cmd->device->hostdata;
if (!dev) {
cmd->result = DID_NO_CONNECT << 16;
done(cmd);
return 0;
}
memcpy(scsi3addr, dev->scsi3addr, sizeof(scsi3addr));
spin_lock_irqsave(&h->lock, flags);
if (unlikely(h->lockup_detected)) {
spin_unlock_irqrestore(&h->lock, flags);
cmd->result = DID_ERROR << 16;
done(cmd);
return 0;
}
spin_unlock_irqrestore(&h->lock, flags);
c = cmd_alloc(h);
if (c == NULL) { /* trouble... */
dev_err(&h->pdev->dev, "cmd_alloc returned NULL!\n");
return SCSI_MLQUEUE_HOST_BUSY;
}
/* Fill in the command list header */
cmd->scsi_done = done; /* save this for use by completion code */
/* save c in case we have to abort it */
cmd->host_scribble = (unsigned char *) c;
c->cmd_type = CMD_SCSI;
c->scsi_cmd = cmd;
c->Header.ReplyQueue = 0; /* unused in simple mode */
memcpy(&c->Header.LUN.LunAddrBytes[0], &scsi3addr[0], 8);
c->Header.Tag.lower = (c->cmdindex << DIRECT_LOOKUP_SHIFT);
c->Header.Tag.lower |= DIRECT_LOOKUP_BIT;
/* Fill in the request block... */
c->Request.Timeout = 0;
memset(c->Request.CDB, 0, sizeof(c->Request.CDB));
BUG_ON(cmd->cmd_len > sizeof(c->Request.CDB));
c->Request.CDBLen = cmd->cmd_len;
memcpy(c->Request.CDB, cmd->cmnd, cmd->cmd_len);
c->Request.Type.Type = TYPE_CMD;
c->Request.Type.Attribute = ATTR_SIMPLE;
switch (cmd->sc_data_direction) {
case DMA_TO_DEVICE:
c->Request.Type.Direction = XFER_WRITE;
break;
case DMA_FROM_DEVICE:
c->Request.Type.Direction = XFER_READ;
break;
case DMA_NONE:
c->Request.Type.Direction = XFER_NONE;
break;
case DMA_BIDIRECTIONAL:
/* This can happen if a buggy application does a scsi passthru
* and sets both inlen and outlen to non-zero. ( see
* ../scsi/scsi_ioctl.c:scsi_ioctl_send_command() )
*/
c->Request.Type.Direction = XFER_RSVD;
/* This is technically wrong, and hpsa controllers should
* reject it with CMD_INVALID, which is the most correct
* response, but non-fibre backends appear to let it
* slide by, and give the same results as if this field
* were set correctly. Either way is acceptable for
* our purposes here.
*/
break;
default:
dev_err(&h->pdev->dev, "unknown data direction: %d\n",
cmd->sc_data_direction);
BUG();
break;
}
if (hpsa_scatter_gather(h, c, cmd) < 0) { /* Fill SG list */
cmd_free(h, c);
return SCSI_MLQUEUE_HOST_BUSY;
}
enqueue_cmd_and_start_io(h, c);
/* the cmd'll come back via intr handler in complete_scsi_command() */
return 0;
}
static DEF_SCSI_QCMD(hpsa_scsi_queue_command)
static void hpsa_scan_start(struct Scsi_Host *sh)
{
struct ctlr_info *h = shost_to_hba(sh);
unsigned long flags;
/* wait until any scan already in progress is finished. */
while (1) {
spin_lock_irqsave(&h->scan_lock, flags);
if (h->scan_finished)
break;
spin_unlock_irqrestore(&h->scan_lock, flags);
wait_event(h->scan_wait_queue, h->scan_finished);
/* Note: We don't need to worry about a race between this
* thread and driver unload because the midlayer will
* have incremented the reference count, so unload won't
* happen if we're in here.
*/
}
h->scan_finished = 0; /* mark scan as in progress */
spin_unlock_irqrestore(&h->scan_lock, flags);
hpsa_update_scsi_devices(h, h->scsi_host->host_no);
spin_lock_irqsave(&h->scan_lock, flags);
h->scan_finished = 1; /* mark scan as finished. */
wake_up_all(&h->scan_wait_queue);
spin_unlock_irqrestore(&h->scan_lock, flags);
}
static int hpsa_scan_finished(struct Scsi_Host *sh,
unsigned long elapsed_time)
{
struct ctlr_info *h = shost_to_hba(sh);
unsigned long flags;
int finished;
spin_lock_irqsave(&h->scan_lock, flags);
finished = h->scan_finished;
spin_unlock_irqrestore(&h->scan_lock, flags);
return finished;
}
static int hpsa_change_queue_depth(struct scsi_device *sdev,
int qdepth, int reason)
{
struct ctlr_info *h = sdev_to_hba(sdev);
if (reason != SCSI_QDEPTH_DEFAULT)
return -ENOTSUPP;
if (qdepth < 1)
qdepth = 1;
else
if (qdepth > h->nr_cmds)
qdepth = h->nr_cmds;
scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), qdepth);
return sdev->queue_depth;
}
static void hpsa_unregister_scsi(struct ctlr_info *h)
{
/* we are being forcibly unloaded, and may not refuse. */
scsi_remove_host(h->scsi_host);
scsi_host_put(h->scsi_host);
h->scsi_host = NULL;
}
static int hpsa_register_scsi(struct ctlr_info *h)
{
struct Scsi_Host *sh;
int error;
sh = scsi_host_alloc(&hpsa_driver_template, sizeof(h));
if (sh == NULL)
goto fail;
sh->io_port = 0;
sh->n_io_port = 0;
sh->this_id = -1;
sh->max_channel = 3;
sh->max_cmd_len = MAX_COMMAND_SIZE;
sh->max_lun = HPSA_MAX_LUN;
sh->max_id = HPSA_MAX_LUN;
sh->can_queue = h->nr_cmds;
sh->cmd_per_lun = h->nr_cmds;
sh->sg_tablesize = h->maxsgentries;
h->scsi_host = sh;
sh->hostdata[0] = (unsigned long) h;
sh->irq = h->intr[h->intr_mode];
sh->unique_id = sh->irq;
error = scsi_add_host(sh, &h->pdev->dev);
if (error)
goto fail_host_put;
scsi_scan_host(sh);
return 0;
fail_host_put:
dev_err(&h->pdev->dev, "%s: scsi_add_host"
" failed for controller %d\n", __func__, h->ctlr);
scsi_host_put(sh);
return error;
fail:
dev_err(&h->pdev->dev, "%s: scsi_host_alloc"
" failed for controller %d\n", __func__, h->ctlr);
return -ENOMEM;
}
static int wait_for_device_to_become_ready(struct ctlr_info *h,
unsigned char lunaddr[])
{
int rc = 0;
int count = 0;
int waittime = 1; /* seconds */
struct CommandList *c;
c = cmd_special_alloc(h);
if (!c) {
dev_warn(&h->pdev->dev, "out of memory in "
"wait_for_device_to_become_ready.\n");
return IO_ERROR;
}
/* Send test unit ready until device ready, or give up. */
while (count < HPSA_TUR_RETRY_LIMIT) {
/* Wait for a bit. do this first, because if we send
* the TUR right away, the reset will just abort it.
*/
msleep(1000 * waittime);
count++;
/* Increase wait time with each try, up to a point. */
if (waittime < HPSA_MAX_WAIT_INTERVAL_SECS)
waittime = waittime * 2;
/* Send the Test Unit Ready, fill_cmd can't fail, no mapping */
(void) fill_cmd(c, TEST_UNIT_READY, h,
NULL, 0, 0, lunaddr, TYPE_CMD);
hpsa_scsi_do_simple_cmd_core(h, c);
/* no unmap needed here because no data xfer. */
if (c->err_info->CommandStatus == CMD_SUCCESS)
break;
if (c->err_info->CommandStatus == CMD_TARGET_STATUS &&
c->err_info->ScsiStatus == SAM_STAT_CHECK_CONDITION &&
(c->err_info->SenseInfo[2] == NO_SENSE ||
c->err_info->SenseInfo[2] == UNIT_ATTENTION))
break;
dev_warn(&h->pdev->dev, "waiting %d secs "
"for device to become ready.\n", waittime);
rc = 1; /* device not ready. */
}
if (rc)
dev_warn(&h->pdev->dev, "giving up on device.\n");
else
dev_warn(&h->pdev->dev, "device is ready.\n");
cmd_special_free(h, c);
return rc;
}
/* Need at least one of these error handlers to keep ../scsi/hosts.c from
* complaining. Doing a host- or bus-reset can't do anything good here.
*/
static int hpsa_eh_device_reset_handler(struct scsi_cmnd *scsicmd)
{
int rc;
struct ctlr_info *h;
struct hpsa_scsi_dev_t *dev;
/* find the controller to which the command to be aborted was sent */
h = sdev_to_hba(scsicmd->device);
if (h == NULL) /* paranoia */
return FAILED;
dev = scsicmd->device->hostdata;
if (!dev) {
dev_err(&h->pdev->dev, "hpsa_eh_device_reset_handler: "
"device lookup failed.\n");
return FAILED;
}
dev_warn(&h->pdev->dev, "resetting device %d:%d:%d:%d\n",
h->scsi_host->host_no, dev->bus, dev->target, dev->lun);
/* send a reset to the SCSI LUN which the command was sent to */
rc = hpsa_send_reset(h, dev->scsi3addr);
if (rc == 0 && wait_for_device_to_become_ready(h, dev->scsi3addr) == 0)
return SUCCESS;
dev_warn(&h->pdev->dev, "resetting device failed.\n");
return FAILED;
}
static void swizzle_abort_tag(u8 *tag)
{
u8 original_tag[8];
memcpy(original_tag, tag, 8);
tag[0] = original_tag[3];
tag[1] = original_tag[2];
tag[2] = original_tag[1];
tag[3] = original_tag[0];
tag[4] = original_tag[7];
tag[5] = original_tag[6];
tag[6] = original_tag[5];
tag[7] = original_tag[4];
}
static int hpsa_send_abort(struct ctlr_info *h, unsigned char *scsi3addr,
struct CommandList *abort, int swizzle)
{
int rc = IO_OK;
struct CommandList *c;
struct ErrorInfo *ei;
c = cmd_special_alloc(h);
if (c == NULL) { /* trouble... */
dev_warn(&h->pdev->dev, "cmd_special_alloc returned NULL!\n");
return -ENOMEM;
}
/* fill_cmd can't fail here, no buffer to map */
(void) fill_cmd(c, HPSA_ABORT_MSG, h, abort,
0, 0, scsi3addr, TYPE_MSG);
if (swizzle)
swizzle_abort_tag(&c->Request.CDB[4]);
hpsa_scsi_do_simple_cmd_core(h, c);
dev_dbg(&h->pdev->dev, "%s: Tag:0x%08x:%08x: do_simple_cmd_core completed.\n",
__func__, abort->Header.Tag.upper, abort->Header.Tag.lower);
/* no unmap needed here because no data xfer. */
ei = c->err_info;
switch (ei->CommandStatus) {
case CMD_SUCCESS:
break;
case CMD_UNABORTABLE: /* Very common, don't make noise. */
rc = -1;
break;
default:
dev_dbg(&h->pdev->dev, "%s: Tag:0x%08x:%08x: interpreting error.\n",
__func__, abort->Header.Tag.upper,
abort->Header.Tag.lower);
hpsa_scsi_interpret_error(c);
rc = -1;
break;
}
cmd_special_free(h, c);
dev_dbg(&h->pdev->dev, "%s: Tag:0x%08x:%08x: Finished.\n", __func__,
abort->Header.Tag.upper, abort->Header.Tag.lower);
return rc;
}
/*
* hpsa_find_cmd_in_queue
*
* Used to determine whether a command (find) is still present
* in queue_head. Optionally excludes the last element of queue_head.
*
* This is used to avoid unnecessary aborts. Commands in h->reqQ have
* not yet been submitted, and so can be aborted by the driver without
* sending an abort to the hardware.
*
* Returns pointer to command if found in queue, NULL otherwise.
*/
static struct CommandList *hpsa_find_cmd_in_queue(struct ctlr_info *h,
struct scsi_cmnd *find, struct list_head *queue_head)
{
unsigned long flags;
struct CommandList *c = NULL; /* ptr into cmpQ */
if (!find)
return 0;
spin_lock_irqsave(&h->lock, flags);
list_for_each_entry(c, queue_head, list) {
if (c->scsi_cmd == NULL) /* e.g.: passthru ioctl */
continue;
if (c->scsi_cmd == find) {
spin_unlock_irqrestore(&h->lock, flags);
return c;
}
}
spin_unlock_irqrestore(&h->lock, flags);
return NULL;
}
static struct CommandList *hpsa_find_cmd_in_queue_by_tag(struct ctlr_info *h,
u8 *tag, struct list_head *queue_head)
{
unsigned long flags;
struct CommandList *c;
spin_lock_irqsave(&h->lock, flags);
list_for_each_entry(c, queue_head, list) {
if (memcmp(&c->Header.Tag, tag, 8) != 0)
continue;
spin_unlock_irqrestore(&h->lock, flags);
return c;
}
spin_unlock_irqrestore(&h->lock, flags);
return NULL;
}
/* Some Smart Arrays need the abort tag swizzled, and some don't. It's hard to
* tell which kind we're dealing with, so we send the abort both ways. There
* shouldn't be any collisions between swizzled and unswizzled tags due to the
* way we construct our tags but we check anyway in case the assumptions which
* make this true someday become false.
*/
static int hpsa_send_abort_both_ways(struct ctlr_info *h,
unsigned char *scsi3addr, struct CommandList *abort)
{
u8 swizzled_tag[8];
struct CommandList *c;
int rc = 0, rc2 = 0;
/* we do not expect to find the swizzled tag in our queue, but
* check anyway just to be sure the assumptions which make this
* the case haven't become wrong.
*/
memcpy(swizzled_tag, &abort->Request.CDB[4], 8);
swizzle_abort_tag(swizzled_tag);
c = hpsa_find_cmd_in_queue_by_tag(h, swizzled_tag, &h->cmpQ);
if (c != NULL) {
dev_warn(&h->pdev->dev, "Unexpectedly found byte-swapped tag in completion queue.\n");
return hpsa_send_abort(h, scsi3addr, abort, 0);
}
rc = hpsa_send_abort(h, scsi3addr, abort, 0);
/* if the command is still in our queue, we can't conclude that it was
* aborted (it might have just completed normally) but in any case
* we don't need to try to abort it another way.
*/
c = hpsa_find_cmd_in_queue(h, abort->scsi_cmd, &h->cmpQ);
if (c)
rc2 = hpsa_send_abort(h, scsi3addr, abort, 1);
return rc && rc2;
}
/* Send an abort for the specified command.
* If the device and controller support it,
* send a task abort request.
*/
static int hpsa_eh_abort_handler(struct scsi_cmnd *sc)
{
int i, rc;
struct ctlr_info *h;
struct hpsa_scsi_dev_t *dev;
struct CommandList *abort; /* pointer to command to be aborted */
struct CommandList *found;
struct scsi_cmnd *as; /* ptr to scsi cmd inside aborted command. */
char msg[256]; /* For debug messaging. */
int ml = 0;
/* Find the controller of the command to be aborted */
h = sdev_to_hba(sc->device);
if (WARN(h == NULL,
"ABORT REQUEST FAILED, Controller lookup failed.\n"))
return FAILED;
/* Check that controller supports some kind of task abort */
if (!(HPSATMF_PHYS_TASK_ABORT & h->TMFSupportFlags) &&
!(HPSATMF_LOG_TASK_ABORT & h->TMFSupportFlags))
return FAILED;
memset(msg, 0, sizeof(msg));
ml += sprintf(msg+ml, "ABORT REQUEST on C%d:B%d:T%d:L%d ",
h->scsi_host->host_no, sc->device->channel,
sc->device->id, sc->device->lun);
/* Find the device of the command to be aborted */
dev = sc->device->hostdata;
if (!dev) {
dev_err(&h->pdev->dev, "%s FAILED, Device lookup failed.\n",
msg);
return FAILED;
}
/* Get SCSI command to be aborted */
abort = (struct CommandList *) sc->host_scribble;
if (abort == NULL) {
dev_err(&h->pdev->dev, "%s FAILED, Command to abort is NULL.\n",
msg);
return FAILED;
}
ml += sprintf(msg+ml, "Tag:0x%08x:%08x ",
abort->Header.Tag.upper, abort->Header.Tag.lower);
as = (struct scsi_cmnd *) abort->scsi_cmd;
if (as != NULL)
ml += sprintf(msg+ml, "Command:0x%x SN:0x%lx ",
as->cmnd[0], as->serial_number);
dev_dbg(&h->pdev->dev, "%s\n", msg);
dev_warn(&h->pdev->dev, "Abort request on C%d:B%d:T%d:L%d\n",
h->scsi_host->host_no, dev->bus, dev->target, dev->lun);
/* Search reqQ to See if command is queued but not submitted,
* if so, complete the command with aborted status and remove
* it from the reqQ.
*/
found = hpsa_find_cmd_in_queue(h, sc, &h->reqQ);
if (found) {
found->err_info->CommandStatus = CMD_ABORTED;
finish_cmd(found);
dev_info(&h->pdev->dev, "%s Request SUCCEEDED (driver queue).\n",
msg);
return SUCCESS;
}
/* not in reqQ, if also not in cmpQ, must have already completed */
found = hpsa_find_cmd_in_queue(h, sc, &h->cmpQ);
if (!found) {
dev_dbg(&h->pdev->dev, "%s Request SUCCEEDED (not known to driver).\n",
msg);
return SUCCESS;
}
/*
* Command is in flight, or possibly already completed
* by the firmware (but not to the scsi mid layer) but we can't
* distinguish which. Send the abort down.
*/
rc = hpsa_send_abort_both_ways(h, dev->scsi3addr, abort);
if (rc != 0) {
dev_dbg(&h->pdev->dev, "%s Request FAILED.\n", msg);
dev_warn(&h->pdev->dev, "FAILED abort on device C%d:B%d:T%d:L%d\n",
h->scsi_host->host_no,
dev->bus, dev->target, dev->lun);
return FAILED;
}
dev_info(&h->pdev->dev, "%s REQUEST SUCCEEDED.\n", msg);
/* If the abort(s) above completed and actually aborted the
* command, then the command to be aborted should already be
* completed. If not, wait around a bit more to see if they
* manage to complete normally.
*/
#define ABORT_COMPLETE_WAIT_SECS 30
for (i = 0; i < ABORT_COMPLETE_WAIT_SECS * 10; i++) {
found = hpsa_find_cmd_in_queue(h, sc, &h->cmpQ);
if (!found)
return SUCCESS;
msleep(100);
}
dev_warn(&h->pdev->dev, "%s FAILED. Aborted command has not completed after %d seconds.\n",
msg, ABORT_COMPLETE_WAIT_SECS);
return FAILED;
}
/*
* For operations that cannot sleep, a command block is allocated at init,
* and managed by cmd_alloc() and cmd_free() using a simple bitmap to track
* which ones are free or in use. Lock must be held when calling this.
* cmd_free() is the complement.
*/
static struct CommandList *cmd_alloc(struct ctlr_info *h)
{
struct CommandList *c;
int i;
union u64bit temp64;
dma_addr_t cmd_dma_handle, err_dma_handle;
unsigned long flags;
spin_lock_irqsave(&h->lock, flags);
do {
i = find_first_zero_bit(h->cmd_pool_bits, h->nr_cmds);
if (i == h->nr_cmds) {
spin_unlock_irqrestore(&h->lock, flags);
return NULL;
}
} while (test_and_set_bit
(i & (BITS_PER_LONG - 1),
h->cmd_pool_bits + (i / BITS_PER_LONG)) != 0);
h->nr_allocs++;
spin_unlock_irqrestore(&h->lock, flags);
c = h->cmd_pool + i;
memset(c, 0, sizeof(*c));
cmd_dma_handle = h->cmd_pool_dhandle
+ i * sizeof(*c);
c->err_info = h->errinfo_pool + i;
memset(c->err_info, 0, sizeof(*c->err_info));
err_dma_handle = h->errinfo_pool_dhandle
+ i * sizeof(*c->err_info);
c->cmdindex = i;
INIT_LIST_HEAD(&c->list);
c->busaddr = (u32) cmd_dma_handle;
temp64.val = (u64) err_dma_handle;
c->ErrDesc.Addr.lower = temp64.val32.lower;
c->ErrDesc.Addr.upper = temp64.val32.upper;
c->ErrDesc.Len = sizeof(*c->err_info);
c->h = h;
return c;
}
/* For operations that can wait for kmalloc to possibly sleep,
* this routine can be called. Lock need not be held to call
* cmd_special_alloc. cmd_special_free() is the complement.
*/
static struct CommandList *cmd_special_alloc(struct ctlr_info *h)
{
struct CommandList *c;
union u64bit temp64;
dma_addr_t cmd_dma_handle, err_dma_handle;
c = pci_alloc_consistent(h->pdev, sizeof(*c), &cmd_dma_handle);
if (c == NULL)
return NULL;
memset(c, 0, sizeof(*c));
c->cmdindex = -1;
c->err_info = pci_alloc_consistent(h->pdev, sizeof(*c->err_info),
&err_dma_handle);
if (c->err_info == NULL) {
pci_free_consistent(h->pdev,
sizeof(*c), c, cmd_dma_handle);
return NULL;
}
memset(c->err_info, 0, sizeof(*c->err_info));
INIT_LIST_HEAD(&c->list);
c->busaddr = (u32) cmd_dma_handle;
temp64.val = (u64) err_dma_handle;
c->ErrDesc.Addr.lower = temp64.val32.lower;
c->ErrDesc.Addr.upper = temp64.val32.upper;
c->ErrDesc.Len = sizeof(*c->err_info);
c->h = h;
return c;
}
static void cmd_free(struct ctlr_info *h, struct CommandList *c)
{
int i;
unsigned long flags;
i = c - h->cmd_pool;
spin_lock_irqsave(&h->lock, flags);
clear_bit(i & (BITS_PER_LONG - 1),
h->cmd_pool_bits + (i / BITS_PER_LONG));
h->nr_frees++;
spin_unlock_irqrestore(&h->lock, flags);
}
static void cmd_special_free(struct ctlr_info *h, struct CommandList *c)
{
union u64bit temp64;
temp64.val32.lower = c->ErrDesc.Addr.lower;
temp64.val32.upper = c->ErrDesc.Addr.upper;
pci_free_consistent(h->pdev, sizeof(*c->err_info),
c->err_info, (dma_addr_t) temp64.val);
pci_free_consistent(h->pdev, sizeof(*c),
c, (dma_addr_t) (c->busaddr & DIRECT_LOOKUP_MASK));
}
#ifdef CONFIG_COMPAT
static int hpsa_ioctl32_passthru(struct scsi_device *dev, int cmd, void *arg)
{
IOCTL32_Command_struct __user *arg32 =
(IOCTL32_Command_struct __user *) arg;
IOCTL_Command_struct arg64;
IOCTL_Command_struct __user *p = compat_alloc_user_space(sizeof(arg64));
int err;
u32 cp;
memset(&arg64, 0, sizeof(arg64));
err = 0;
err |= copy_from_user(&arg64.LUN_info, &arg32->LUN_info,
sizeof(arg64.LUN_info));
err |= copy_from_user(&arg64.Request, &arg32->Request,
sizeof(arg64.Request));
err |= copy_from_user(&arg64.error_info, &arg32->error_info,
sizeof(arg64.error_info));
err |= get_user(arg64.buf_size, &arg32->buf_size);
err |= get_user(cp, &arg32->buf);
arg64.buf = compat_ptr(cp);
err |= copy_to_user(p, &arg64, sizeof(arg64));
if (err)
return -EFAULT;
err = hpsa_ioctl(dev, CCISS_PASSTHRU, (void *)p);
if (err)
return err;
err |= copy_in_user(&arg32->error_info, &p->error_info,
sizeof(arg32->error_info));
if (err)
return -EFAULT;
return err;
}
static int hpsa_ioctl32_big_passthru(struct scsi_device *dev,
int cmd, void *arg)
{
BIG_IOCTL32_Command_struct __user *arg32 =
(BIG_IOCTL32_Command_struct __user *) arg;
BIG_IOCTL_Command_struct arg64;
BIG_IOCTL_Command_struct __user *p =
compat_alloc_user_space(sizeof(arg64));
int err;
u32 cp;
memset(&arg64, 0, sizeof(arg64));
err = 0;
err |= copy_from_user(&arg64.LUN_info, &arg32->LUN_info,
sizeof(arg64.LUN_info));
err |= copy_from_user(&arg64.Request, &arg32->Request,
sizeof(arg64.Request));
err |= copy_from_user(&arg64.error_info, &arg32->error_info,
sizeof(arg64.error_info));
err |= get_user(arg64.buf_size, &arg32->buf_size);
err |= get_user(arg64.malloc_size, &arg32->malloc_size);
err |= get_user(cp, &arg32->buf);
arg64.buf = compat_ptr(cp);
err |= copy_to_user(p, &arg64, sizeof(arg64));
if (err)
return -EFAULT;
err = hpsa_ioctl(dev, CCISS_BIG_PASSTHRU, (void *)p);
if (err)
return err;
err |= copy_in_user(&arg32->error_info, &p->error_info,
sizeof(arg32->error_info));
if (err)
return -EFAULT;
return err;
}
static int hpsa_compat_ioctl(struct scsi_device *dev, int cmd, void *arg)
{
switch (cmd) {
case CCISS_GETPCIINFO:
case CCISS_GETINTINFO:
case CCISS_SETINTINFO:
case CCISS_GETNODENAME:
case CCISS_SETNODENAME:
case CCISS_GETHEARTBEAT:
case CCISS_GETBUSTYPES:
case CCISS_GETFIRMVER:
case CCISS_GETDRIVVER:
case CCISS_REVALIDVOLS:
case CCISS_DEREGDISK:
case CCISS_REGNEWDISK:
case CCISS_REGNEWD:
case CCISS_RESCANDISK:
case CCISS_GETLUNINFO:
return hpsa_ioctl(dev, cmd, arg);
case CCISS_PASSTHRU32:
return hpsa_ioctl32_passthru(dev, cmd, arg);
case CCISS_BIG_PASSTHRU32:
return hpsa_ioctl32_big_passthru(dev, cmd, arg);
default:
return -ENOIOCTLCMD;
}
}
#endif
static int hpsa_getpciinfo_ioctl(struct ctlr_info *h, void __user *argp)
{
struct hpsa_pci_info pciinfo;
if (!argp)
return -EINVAL;
pciinfo.domain = pci_domain_nr(h->pdev->bus);
pciinfo.bus = h->pdev->bus->number;
pciinfo.dev_fn = h->pdev->devfn;
pciinfo.board_id = h->board_id;
if (copy_to_user(argp, &pciinfo, sizeof(pciinfo)))
return -EFAULT;
return 0;
}
static int hpsa_getdrivver_ioctl(struct ctlr_info *h, void __user *argp)
{
DriverVer_type DriverVer;
unsigned char vmaj, vmin, vsubmin;
int rc;
rc = sscanf(HPSA_DRIVER_VERSION, "%hhu.%hhu.%hhu",
&vmaj, &vmin, &vsubmin);
if (rc != 3) {
dev_info(&h->pdev->dev, "driver version string '%s' "
"unrecognized.", HPSA_DRIVER_VERSION);
vmaj = 0;
vmin = 0;
vsubmin = 0;
}
DriverVer = (vmaj << 16) | (vmin << 8) | vsubmin;
if (!argp)
return -EINVAL;
if (copy_to_user(argp, &DriverVer, sizeof(DriverVer_type)))
return -EFAULT;
return 0;
}
static int hpsa_passthru_ioctl(struct ctlr_info *h, void __user *argp)
{
IOCTL_Command_struct iocommand;
struct CommandList *c;
char *buff = NULL;
union u64bit temp64;
int rc = 0;
if (!argp)
return -EINVAL;
if (!capable(CAP_SYS_RAWIO))
return -EPERM;
if (copy_from_user(&iocommand, argp, sizeof(iocommand)))
return -EFAULT;
if ((iocommand.buf_size < 1) &&
(iocommand.Request.Type.Direction != XFER_NONE)) {
return -EINVAL;
}
if (iocommand.buf_size > 0) {
buff = kmalloc(iocommand.buf_size, GFP_KERNEL);
if (buff == NULL)
return -EFAULT;
if (iocommand.Request.Type.Direction == XFER_WRITE) {
/* Copy the data into the buffer we created */
if (copy_from_user(buff, iocommand.buf,
iocommand.buf_size)) {
rc = -EFAULT;
goto out_kfree;
}
} else {
memset(buff, 0, iocommand.buf_size);
}
}
c = cmd_special_alloc(h);
if (c == NULL) {
rc = -ENOMEM;
goto out_kfree;
}
/* Fill in the command type */
c->cmd_type = CMD_IOCTL_PEND;
/* Fill in Command Header */
c->Header.ReplyQueue = 0; /* unused in simple mode */
if (iocommand.buf_size > 0) { /* buffer to fill */
c->Header.SGList = 1;
c->Header.SGTotal = 1;
} else { /* no buffers to fill */
c->Header.SGList = 0;
c->Header.SGTotal = 0;
}
memcpy(&c->Header.LUN, &iocommand.LUN_info, sizeof(c->Header.LUN));
/* use the kernel address the cmd block for tag */
c->Header.Tag.lower = c->busaddr;
/* Fill in Request block */
memcpy(&c->Request, &iocommand.Request,
sizeof(c->Request));
/* Fill in the scatter gather information */
if (iocommand.buf_size > 0) {
temp64.val = pci_map_single(h->pdev, buff,
iocommand.buf_size, PCI_DMA_BIDIRECTIONAL);
if (dma_mapping_error(&h->pdev->dev, temp64.val)) {
c->SG[0].Addr.lower = 0;
c->SG[0].Addr.upper = 0;
c->SG[0].Len = 0;
rc = -ENOMEM;
goto out;
}
c->SG[0].Addr.lower = temp64.val32.lower;
c->SG[0].Addr.upper = temp64.val32.upper;
c->SG[0].Len = iocommand.buf_size;
c->SG[0].Ext = 0; /* we are not chaining*/
}
hpsa_scsi_do_simple_cmd_core_if_no_lockup(h, c);
if (iocommand.buf_size > 0)
hpsa_pci_unmap(h->pdev, c, 1, PCI_DMA_BIDIRECTIONAL);
check_ioctl_unit_attention(h, c);
/* Copy the error information out */
memcpy(&iocommand.error_info, c->err_info,
sizeof(iocommand.error_info));
if (copy_to_user(argp, &iocommand, sizeof(iocommand))) {
rc = -EFAULT;
goto out;
}
if (iocommand.Request.Type.Direction == XFER_READ &&
iocommand.buf_size > 0) {
/* Copy the data out of the buffer we created */
if (copy_to_user(iocommand.buf, buff, iocommand.buf_size)) {
rc = -EFAULT;
goto out;
}
}
out:
cmd_special_free(h, c);
out_kfree:
kfree(buff);
return rc;
}
static int hpsa_big_passthru_ioctl(struct ctlr_info *h, void __user *argp)
{
BIG_IOCTL_Command_struct *ioc;
struct CommandList *c;
unsigned char **buff = NULL;
int *buff_size = NULL;
union u64bit temp64;
BYTE sg_used = 0;
int status = 0;
int i;
u32 left;
u32 sz;
BYTE __user *data_ptr;
if (!argp)
return -EINVAL;
if (!capable(CAP_SYS_RAWIO))
return -EPERM;
ioc = (BIG_IOCTL_Command_struct *)
kmalloc(sizeof(*ioc), GFP_KERNEL);
if (!ioc) {
status = -ENOMEM;
goto cleanup1;
}
if (copy_from_user(ioc, argp, sizeof(*ioc))) {
status = -EFAULT;
goto cleanup1;
}
if ((ioc->buf_size < 1) &&
(ioc->Request.Type.Direction != XFER_NONE)) {
status = -EINVAL;
goto cleanup1;
}
/* Check kmalloc limits using all SGs */
if (ioc->malloc_size > MAX_KMALLOC_SIZE) {
status = -EINVAL;
goto cleanup1;
}
if (ioc->buf_size > ioc->malloc_size * SG_ENTRIES_IN_CMD) {
status = -EINVAL;
goto cleanup1;
}
buff = kzalloc(SG_ENTRIES_IN_CMD * sizeof(char *), GFP_KERNEL);
if (!buff) {
status = -ENOMEM;
goto cleanup1;
}
buff_size = kmalloc(SG_ENTRIES_IN_CMD * sizeof(int), GFP_KERNEL);
if (!buff_size) {
status = -ENOMEM;
goto cleanup1;
}
left = ioc->buf_size;
data_ptr = ioc->buf;
while (left) {
sz = (left > ioc->malloc_size) ? ioc->malloc_size : left;
buff_size[sg_used] = sz;
buff[sg_used] = kmalloc(sz, GFP_KERNEL);
if (buff[sg_used] == NULL) {
status = -ENOMEM;
goto cleanup1;
}
if (ioc->Request.Type.Direction == XFER_WRITE) {
if (copy_from_user(buff[sg_used], data_ptr, sz)) {
status = -ENOMEM;
goto cleanup1;
}
} else
memset(buff[sg_used], 0, sz);
left -= sz;
data_ptr += sz;
sg_used++;
}
c = cmd_special_alloc(h);
if (c == NULL) {
status = -ENOMEM;
goto cleanup1;
}
c->cmd_type = CMD_IOCTL_PEND;
c->Header.ReplyQueue = 0;
c->Header.SGList = c->Header.SGTotal = sg_used;
memcpy(&c->Header.LUN, &ioc->LUN_info, sizeof(c->Header.LUN));
c->Header.Tag.lower = c->busaddr;
memcpy(&c->Request, &ioc->Request, sizeof(c->Request));
if (ioc->buf_size > 0) {
int i;
for (i = 0; i < sg_used; i++) {
temp64.val = pci_map_single(h->pdev, buff[i],
buff_size[i], PCI_DMA_BIDIRECTIONAL);
if (dma_mapping_error(&h->pdev->dev, temp64.val)) {
c->SG[i].Addr.lower = 0;
c->SG[i].Addr.upper = 0;
c->SG[i].Len = 0;
hpsa_pci_unmap(h->pdev, c, i,
PCI_DMA_BIDIRECTIONAL);
status = -ENOMEM;
goto cleanup1;
}
c->SG[i].Addr.lower = temp64.val32.lower;
c->SG[i].Addr.upper = temp64.val32.upper;
c->SG[i].Len = buff_size[i];
/* we are not chaining */
c->SG[i].Ext = 0;
}
}
hpsa_scsi_do_simple_cmd_core_if_no_lockup(h, c);
if (sg_used)
hpsa_pci_unmap(h->pdev, c, sg_used, PCI_DMA_BIDIRECTIONAL);
check_ioctl_unit_attention(h, c);
/* Copy the error information out */
memcpy(&ioc->error_info, c->err_info, sizeof(ioc->error_info));
if (copy_to_user(argp, ioc, sizeof(*ioc))) {
cmd_special_free(h, c);
status = -EFAULT;
goto cleanup1;
}
if (ioc->Request.Type.Direction == XFER_READ && ioc->buf_size > 0) {
/* Copy the data out of the buffer we created */
BYTE __user *ptr = ioc->buf;
for (i = 0; i < sg_used; i++) {
if (copy_to_user(ptr, buff[i], buff_size[i])) {
cmd_special_free(h, c);
status = -EFAULT;
goto cleanup1;
}
ptr += buff_size[i];
}
}
cmd_special_free(h, c);
status = 0;
cleanup1:
if (buff) {
for (i = 0; i < sg_used; i++)
kfree(buff[i]);
kfree(buff);
}
kfree(buff_size);
kfree(ioc);
return status;
}
static void check_ioctl_unit_attention(struct ctlr_info *h,
struct CommandList *c)
{
if (c->err_info->CommandStatus == CMD_TARGET_STATUS &&
c->err_info->ScsiStatus != SAM_STAT_CHECK_CONDITION)
(void) check_for_unit_attention(h, c);
}
/*
* ioctl
*/
static int hpsa_ioctl(struct scsi_device *dev, int cmd, void *arg)
{
struct ctlr_info *h;
void __user *argp = (void __user *)arg;
h = sdev_to_hba(dev);
switch (cmd) {
case CCISS_DEREGDISK:
case CCISS_REGNEWDISK:
case CCISS_REGNEWD:
hpsa_scan_start(h->scsi_host);
return 0;
case CCISS_GETPCIINFO:
return hpsa_getpciinfo_ioctl(h, argp);
case CCISS_GETDRIVVER:
return hpsa_getdrivver_ioctl(h, argp);
case CCISS_PASSTHRU:
return hpsa_passthru_ioctl(h, argp);
case CCISS_BIG_PASSTHRU:
return hpsa_big_passthru_ioctl(h, argp);
default:
return -ENOTTY;
}
}
static int hpsa_send_host_reset(struct ctlr_info *h, unsigned char *scsi3addr,
u8 reset_type)
{
struct CommandList *c;
c = cmd_alloc(h);
if (!c)
return -ENOMEM;
/* fill_cmd can't fail here, no data buffer to map */
(void) fill_cmd(c, HPSA_DEVICE_RESET_MSG, h, NULL, 0, 0,
RAID_CTLR_LUNID, TYPE_MSG);
c->Request.CDB[1] = reset_type; /* fill_cmd defaults to target reset */
c->waiting = NULL;
enqueue_cmd_and_start_io(h, c);
/* Don't wait for completion, the reset won't complete. Don't free
* the command either. This is the last command we will send before
* re-initializing everything, so it doesn't matter and won't leak.
*/
return 0;
}
static int fill_cmd(struct CommandList *c, u8 cmd, struct ctlr_info *h,
void *buff, size_t size, u8 page_code, unsigned char *scsi3addr,
int cmd_type)
{
int pci_dir = XFER_NONE;
struct CommandList *a; /* for commands to be aborted */
c->cmd_type = CMD_IOCTL_PEND;
c->Header.ReplyQueue = 0;
if (buff != NULL && size > 0) {
c->Header.SGList = 1;
c->Header.SGTotal = 1;
} else {
c->Header.SGList = 0;
c->Header.SGTotal = 0;
}
c->Header.Tag.lower = c->busaddr;
memcpy(c->Header.LUN.LunAddrBytes, scsi3addr, 8);
c->Request.Type.Type = cmd_type;
if (cmd_type == TYPE_CMD) {
switch (cmd) {
case HPSA_INQUIRY:
/* are we trying to read a vital product page */
if (page_code != 0) {
c->Request.CDB[1] = 0x01;
c->Request.CDB[2] = page_code;
}
c->Request.CDBLen = 6;
c->Request.Type.Attribute = ATTR_SIMPLE;
c->Request.Type.Direction = XFER_READ;
c->Request.Timeout = 0;
c->Request.CDB[0] = HPSA_INQUIRY;
c->Request.CDB[4] = size & 0xFF;
break;
case HPSA_REPORT_LOG:
case HPSA_REPORT_PHYS:
/* Talking to controller so It's a physical command
mode = 00 target = 0. Nothing to write.
*/
c->Request.CDBLen = 12;
c->Request.Type.Attribute = ATTR_SIMPLE;
c->Request.Type.Direction = XFER_READ;
c->Request.Timeout = 0;
c->Request.CDB[0] = cmd;
c->Request.CDB[6] = (size >> 24) & 0xFF; /* MSB */
c->Request.CDB[7] = (size >> 16) & 0xFF;
c->Request.CDB[8] = (size >> 8) & 0xFF;
c->Request.CDB[9] = size & 0xFF;
break;
case HPSA_CACHE_FLUSH:
c->Request.CDBLen = 12;
c->Request.Type.Attribute = ATTR_SIMPLE;
c->Request.Type.Direction = XFER_WRITE;
c->Request.Timeout = 0;
c->Request.CDB[0] = BMIC_WRITE;
c->Request.CDB[6] = BMIC_CACHE_FLUSH;
c->Request.CDB[7] = (size >> 8) & 0xFF;
c->Request.CDB[8] = size & 0xFF;
break;
case TEST_UNIT_READY:
c->Request.CDBLen = 6;
c->Request.Type.Attribute = ATTR_SIMPLE;
c->Request.Type.Direction = XFER_NONE;
c->Request.Timeout = 0;
break;
default:
dev_warn(&h->pdev->dev, "unknown command 0x%c\n", cmd);
BUG();
return -1;
}
} else if (cmd_type == TYPE_MSG) {
switch (cmd) {
case HPSA_DEVICE_RESET_MSG:
c->Request.CDBLen = 16;
c->Request.Type.Type = 1; /* It is a MSG not a CMD */
c->Request.Type.Attribute = ATTR_SIMPLE;
c->Request.Type.Direction = XFER_NONE;
c->Request.Timeout = 0; /* Don't time out */
memset(&c->Request.CDB[0], 0, sizeof(c->Request.CDB));
c->Request.CDB[0] = cmd;
c->Request.CDB[1] = HPSA_RESET_TYPE_LUN;
/* If bytes 4-7 are zero, it means reset the */
/* LunID device */
c->Request.CDB[4] = 0x00;
c->Request.CDB[5] = 0x00;
c->Request.CDB[6] = 0x00;
c->Request.CDB[7] = 0x00;
break;
case HPSA_ABORT_MSG:
a = buff; /* point to command to be aborted */
dev_dbg(&h->pdev->dev, "Abort Tag:0x%08x:%08x using request Tag:0x%08x:%08x\n",
a->Header.Tag.upper, a->Header.Tag.lower,
c->Header.Tag.upper, c->Header.Tag.lower);
c->Request.CDBLen = 16;
c->Request.Type.Type = TYPE_MSG;
c->Request.Type.Attribute = ATTR_SIMPLE;
c->Request.Type.Direction = XFER_WRITE;
c->Request.Timeout = 0; /* Don't time out */
c->Request.CDB[0] = HPSA_TASK_MANAGEMENT;
c->Request.CDB[1] = HPSA_TMF_ABORT_TASK;
c->Request.CDB[2] = 0x00; /* reserved */
c->Request.CDB[3] = 0x00; /* reserved */
/* Tag to abort goes in CDB[4]-CDB[11] */
c->Request.CDB[4] = a->Header.Tag.lower & 0xFF;
c->Request.CDB[5] = (a->Header.Tag.lower >> 8) & 0xFF;
c->Request.CDB[6] = (a->Header.Tag.lower >> 16) & 0xFF;
c->Request.CDB[7] = (a->Header.Tag.lower >> 24) & 0xFF;
c->Request.CDB[8] = a->Header.Tag.upper & 0xFF;
c->Request.CDB[9] = (a->Header.Tag.upper >> 8) & 0xFF;
c->Request.CDB[10] = (a->Header.Tag.upper >> 16) & 0xFF;
c->Request.CDB[11] = (a->Header.Tag.upper >> 24) & 0xFF;
c->Request.CDB[12] = 0x00; /* reserved */
c->Request.CDB[13] = 0x00; /* reserved */
c->Request.CDB[14] = 0x00; /* reserved */
c->Request.CDB[15] = 0x00; /* reserved */
break;
default:
dev_warn(&h->pdev->dev, "unknown message type %d\n",
cmd);
BUG();
}
} else {
dev_warn(&h->pdev->dev, "unknown command type %d\n", cmd_type);
BUG();
}
switch (c->Request.Type.Direction) {
case XFER_READ:
pci_dir = PCI_DMA_FROMDEVICE;
break;
case XFER_WRITE:
pci_dir = PCI_DMA_TODEVICE;
break;
case XFER_NONE:
pci_dir = PCI_DMA_NONE;
break;
default:
pci_dir = PCI_DMA_BIDIRECTIONAL;
}
if (hpsa_map_one(h->pdev, c, buff, size, pci_dir))
return -1;
return 0;
}
/*
* Map (physical) PCI mem into (virtual) kernel space
*/
static void __iomem *remap_pci_mem(ulong base, ulong size)
{
ulong page_base = ((ulong) base) & PAGE_MASK;
ulong page_offs = ((ulong) base) - page_base;
void __iomem *page_remapped = ioremap_nocache(page_base,
page_offs + size);
return page_remapped ? (page_remapped + page_offs) : NULL;
}
/* Takes cmds off the submission queue and sends them to the hardware,
* then puts them on the queue of cmds waiting for completion.
*/
static void start_io(struct ctlr_info *h)
{
struct CommandList *c;
unsigned long flags;
spin_lock_irqsave(&h->lock, flags);
while (!list_empty(&h->reqQ)) {
c = list_entry(h->reqQ.next, struct CommandList, list);
/* can't do anything if fifo is full */
if ((h->access.fifo_full(h))) {
dev_warn(&h->pdev->dev, "fifo full\n");
break;
}
/* Get the first entry from the Request Q */
removeQ(c);
h->Qdepth--;
/* Put job onto the completed Q */
addQ(&h->cmpQ, c);
/* Must increment commands_outstanding before unlocking
* and submitting to avoid race checking for fifo full
* condition.
*/
h->commands_outstanding++;
if (h->commands_outstanding > h->max_outstanding)
h->max_outstanding = h->commands_outstanding;
/* Tell the controller execute command */
spin_unlock_irqrestore(&h->lock, flags);
h->access.submit_command(h, c);
spin_lock_irqsave(&h->lock, flags);
}
spin_unlock_irqrestore(&h->lock, flags);
}
static inline unsigned long get_next_completion(struct ctlr_info *h, u8 q)
{
return h->access.command_completed(h, q);
}
static inline bool interrupt_pending(struct ctlr_info *h)
{
return h->access.intr_pending(h);
}
static inline long interrupt_not_for_us(struct ctlr_info *h)
{
return (h->access.intr_pending(h) == 0) ||
(h->interrupts_enabled == 0);
}
static inline int bad_tag(struct ctlr_info *h, u32 tag_index,
u32 raw_tag)
{
if (unlikely(tag_index >= h->nr_cmds)) {
dev_warn(&h->pdev->dev, "bad tag 0x%08x ignored.\n", raw_tag);
return 1;
}
return 0;
}
static inline void finish_cmd(struct CommandList *c)
{
unsigned long flags;
spin_lock_irqsave(&c->h->lock, flags);
removeQ(c);
spin_unlock_irqrestore(&c->h->lock, flags);
dial_up_lockup_detection_on_fw_flash_complete(c->h, c);
if (likely(c->cmd_type == CMD_SCSI))
complete_scsi_command(c);
else if (c->cmd_type == CMD_IOCTL_PEND)
complete(c->waiting);
}
static inline u32 hpsa_tag_contains_index(u32 tag)
{
return tag & DIRECT_LOOKUP_BIT;
}
static inline u32 hpsa_tag_to_index(u32 tag)
{
return tag >> DIRECT_LOOKUP_SHIFT;
}
static inline u32 hpsa_tag_discard_error_bits(struct ctlr_info *h, u32 tag)
{
#define HPSA_PERF_ERROR_BITS ((1 << DIRECT_LOOKUP_SHIFT) - 1)
#define HPSA_SIMPLE_ERROR_BITS 0x03
if (unlikely(!(h->transMethod & CFGTBL_Trans_Performant)))
return tag & ~HPSA_SIMPLE_ERROR_BITS;
return tag & ~HPSA_PERF_ERROR_BITS;
}
/* process completion of an indexed ("direct lookup") command */
static inline void process_indexed_cmd(struct ctlr_info *h,
u32 raw_tag)
{
u32 tag_index;
struct CommandList *c;
tag_index = hpsa_tag_to_index(raw_tag);
if (!bad_tag(h, tag_index, raw_tag)) {
c = h->cmd_pool + tag_index;
finish_cmd(c);
}
}
/* process completion of a non-indexed command */
static inline void process_nonindexed_cmd(struct ctlr_info *h,
u32 raw_tag)
{
u32 tag;
struct CommandList *c = NULL;
unsigned long flags;
tag = hpsa_tag_discard_error_bits(h, raw_tag);
spin_lock_irqsave(&h->lock, flags);
list_for_each_entry(c, &h->cmpQ, list) {
if ((c->busaddr & 0xFFFFFFE0) == (tag & 0xFFFFFFE0)) {
spin_unlock_irqrestore(&h->lock, flags);
finish_cmd(c);
return;
}
}
spin_unlock_irqrestore(&h->lock, flags);
bad_tag(h, h->nr_cmds + 1, raw_tag);
}
/* Some controllers, like p400, will give us one interrupt
* after a soft reset, even if we turned interrupts off.
* Only need to check for this in the hpsa_xxx_discard_completions
* functions.
*/
static int ignore_bogus_interrupt(struct ctlr_info *h)
{
if (likely(!reset_devices))
return 0;
if (likely(h->interrupts_enabled))
return 0;
dev_info(&h->pdev->dev, "Received interrupt while interrupts disabled "
"(known firmware bug.) Ignoring.\n");
return 1;
}
/*
* Convert &h->q[x] (passed to interrupt handlers) back to h.
* Relies on (h-q[x] == x) being true for x such that
* 0 <= x < MAX_REPLY_QUEUES.
*/
static struct ctlr_info *queue_to_hba(u8 *queue)
{
return container_of((queue - *queue), struct ctlr_info, q[0]);
}
static irqreturn_t hpsa_intx_discard_completions(int irq, void *queue)
{
struct ctlr_info *h = queue_to_hba(queue);
u8 q = *(u8 *) queue;
u32 raw_tag;
if (ignore_bogus_interrupt(h))
return IRQ_NONE;
if (interrupt_not_for_us(h))
return IRQ_NONE;
h->last_intr_timestamp = get_jiffies_64();
while (interrupt_pending(h)) {
raw_tag = get_next_completion(h, q);
while (raw_tag != FIFO_EMPTY)
raw_tag = next_command(h, q);
}
return IRQ_HANDLED;
}
static irqreturn_t hpsa_msix_discard_completions(int irq, void *queue)
{
struct ctlr_info *h = queue_to_hba(queue);
u32 raw_tag;
u8 q = *(u8 *) queue;
if (ignore_bogus_interrupt(h))
return IRQ_NONE;
h->last_intr_timestamp = get_jiffies_64();
raw_tag = get_next_completion(h, q);
while (raw_tag != FIFO_EMPTY)
raw_tag = next_command(h, q);
return IRQ_HANDLED;
}
static irqreturn_t do_hpsa_intr_intx(int irq, void *queue)
{
struct ctlr_info *h = queue_to_hba((u8 *) queue);
u32 raw_tag;
u8 q = *(u8 *) queue;
if (interrupt_not_for_us(h))
return IRQ_NONE;
h->last_intr_timestamp = get_jiffies_64();
while (interrupt_pending(h)) {
raw_tag = get_next_completion(h, q);
while (raw_tag != FIFO_EMPTY) {
if (likely(hpsa_tag_contains_index(raw_tag)))
process_indexed_cmd(h, raw_tag);
else
process_nonindexed_cmd(h, raw_tag);
raw_tag = next_command(h, q);
}
}
return IRQ_HANDLED;
}
static irqreturn_t do_hpsa_intr_msi(int irq, void *queue)
{
struct ctlr_info *h = queue_to_hba(queue);
u32 raw_tag;
u8 q = *(u8 *) queue;
h->last_intr_timestamp = get_jiffies_64();
raw_tag = get_next_completion(h, q);
while (raw_tag != FIFO_EMPTY) {
if (likely(hpsa_tag_contains_index(raw_tag)))
process_indexed_cmd(h, raw_tag);
else
process_nonindexed_cmd(h, raw_tag);
raw_tag = next_command(h, q);
}
return IRQ_HANDLED;
}
/* Send a message CDB to the firmware. Careful, this only works
* in simple mode, not performant mode due to the tag lookup.
* We only ever use this immediately after a controller reset.
*/
static int hpsa_message(struct pci_dev *pdev, unsigned char opcode,
unsigned char type)
{
struct Command {
struct CommandListHeader CommandHeader;
struct RequestBlock Request;
struct ErrDescriptor ErrorDescriptor;
};
struct Command *cmd;
static const size_t cmd_sz = sizeof(*cmd) +
sizeof(cmd->ErrorDescriptor);
dma_addr_t paddr64;
uint32_t paddr32, tag;
void __iomem *vaddr;
int i, err;
vaddr = pci_ioremap_bar(pdev, 0);
if (vaddr == NULL)
return -ENOMEM;
/* The Inbound Post Queue only accepts 32-bit physical addresses for the
* CCISS commands, so they must be allocated from the lower 4GiB of
* memory.
*/
err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
if (err) {
iounmap(vaddr);
return -ENOMEM;
}
cmd = pci_alloc_consistent(pdev, cmd_sz, &paddr64);
if (cmd == NULL) {
iounmap(vaddr);
return -ENOMEM;
}
/* This must fit, because of the 32-bit consistent DMA mask. Also,
* although there's no guarantee, we assume that the address is at
* least 4-byte aligned (most likely, it's page-aligned).
*/
paddr32 = paddr64;
cmd->CommandHeader.ReplyQueue = 0;
cmd->CommandHeader.SGList = 0;
cmd->CommandHeader.SGTotal = 0;
cmd->CommandHeader.Tag.lower = paddr32;
cmd->CommandHeader.Tag.upper = 0;
memset(&cmd->CommandHeader.LUN.LunAddrBytes, 0, 8);
cmd->Request.CDBLen = 16;
cmd->Request.Type.Type = TYPE_MSG;
cmd->Request.Type.Attribute = ATTR_HEADOFQUEUE;
cmd->Request.Type.Direction = XFER_NONE;
cmd->Request.Timeout = 0; /* Don't time out */
cmd->Request.CDB[0] = opcode;
cmd->Request.CDB[1] = type;
memset(&cmd->Request.CDB[2], 0, 14); /* rest of the CDB is reserved */
cmd->ErrorDescriptor.Addr.lower = paddr32 + sizeof(*cmd);
cmd->ErrorDescriptor.Addr.upper = 0;
cmd->ErrorDescriptor.Len = sizeof(struct ErrorInfo);
writel(paddr32, vaddr + SA5_REQUEST_PORT_OFFSET);
for (i = 0; i < HPSA_MSG_SEND_RETRY_LIMIT; i++) {
tag = readl(vaddr + SA5_REPLY_PORT_OFFSET);
if ((tag & ~HPSA_SIMPLE_ERROR_BITS) == paddr32)
break;
msleep(HPSA_MSG_SEND_RETRY_INTERVAL_MSECS);
}
iounmap(vaddr);
/* we leak the DMA buffer here ... no choice since the controller could
* still complete the command.
*/
if (i == HPSA_MSG_SEND_RETRY_LIMIT) {
dev_err(&pdev->dev, "controller message %02x:%02x timed out\n",
opcode, type);
return -ETIMEDOUT;
}
pci_free_consistent(pdev, cmd_sz, cmd, paddr64);
if (tag & HPSA_ERROR_BIT) {
dev_err(&pdev->dev, "controller message %02x:%02x failed\n",
opcode, type);
return -EIO;
}
dev_info(&pdev->dev, "controller message %02x:%02x succeeded\n",
opcode, type);
return 0;
}
#define hpsa_noop(p) hpsa_message(p, 3, 0)
static int hpsa_controller_hard_reset(struct pci_dev *pdev,
void * __iomem vaddr, u32 use_doorbell)
{
u16 pmcsr;
int pos;
if (use_doorbell) {
/* For everything after the P600, the PCI power state method
* of resetting the controller doesn't work, so we have this
* other way using the doorbell register.
*/
dev_info(&pdev->dev, "using doorbell to reset controller\n");
writel(use_doorbell, vaddr + SA5_DOORBELL);
} else { /* Try to do it the PCI power state way */
/* Quoting from the Open CISS Specification: "The Power
* Management Control/Status Register (CSR) controls the power
* state of the device. The normal operating state is D0,
* CSR=00h. The software off state is D3, CSR=03h. To reset
* the controller, place the interface device in D3 then to D0,
* this causes a secondary PCI reset which will reset the
* controller." */
pos = pci_find_capability(pdev, PCI_CAP_ID_PM);
if (pos == 0) {
dev_err(&pdev->dev,
"hpsa_reset_controller: "
"PCI PM not supported\n");
return -ENODEV;
}
dev_info(&pdev->dev, "using PCI PM to reset controller\n");
/* enter the D3hot power management state */
pci_read_config_word(pdev, pos + PCI_PM_CTRL, &pmcsr);
pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
pmcsr |= PCI_D3hot;
pci_write_config_word(pdev, pos + PCI_PM_CTRL, pmcsr);
msleep(500);
/* enter the D0 power management state */
pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
pmcsr |= PCI_D0;
pci_write_config_word(pdev, pos + PCI_PM_CTRL, pmcsr);
/*
* The P600 requires a small delay when changing states.
* Otherwise we may think the board did not reset and we bail.
* This for kdump only and is particular to the P600.
*/
msleep(500);
}
return 0;
}
static void init_driver_version(char *driver_version, int len)
{
memset(driver_version, 0, len);
strncpy(driver_version, HPSA " " HPSA_DRIVER_VERSION, len - 1);
}
static int write_driver_ver_to_cfgtable(struct CfgTable __iomem *cfgtable)
{
char *driver_version;
int i, size = sizeof(cfgtable->driver_version);
driver_version = kmalloc(size, GFP_KERNEL);
if (!driver_version)
return -ENOMEM;
init_driver_version(driver_version, size);
for (i = 0; i < size; i++)
writeb(driver_version[i], &cfgtable->driver_version[i]);
kfree(driver_version);
return 0;
}
static void read_driver_ver_from_cfgtable(struct CfgTable __iomem *cfgtable,
unsigned char *driver_ver)
{
int i;
for (i = 0; i < sizeof(cfgtable->driver_version); i++)
driver_ver[i] = readb(&cfgtable->driver_version[i]);
}
static int controller_reset_failed(struct CfgTable __iomem *cfgtable)
{
char *driver_ver, *old_driver_ver;
int rc, size = sizeof(cfgtable->driver_version);
old_driver_ver = kmalloc(2 * size, GFP_KERNEL);
if (!old_driver_ver)
return -ENOMEM;
driver_ver = old_driver_ver + size;
/* After a reset, the 32 bytes of "driver version" in the cfgtable
* should have been changed, otherwise we know the reset failed.
*/
init_driver_version(old_driver_ver, size);
read_driver_ver_from_cfgtable(cfgtable, driver_ver);
rc = !memcmp(driver_ver, old_driver_ver, size);
kfree(old_driver_ver);
return rc;
}
/* This does a hard reset of the controller using PCI power management
* states or the using the doorbell register.
*/
static int hpsa_kdump_hard_reset_controller(struct pci_dev *pdev)
{
u64 cfg_offset;
u32 cfg_base_addr;
u64 cfg_base_addr_index;
void __iomem *vaddr;
unsigned long paddr;
u32 misc_fw_support;
int rc;
struct CfgTable __iomem *cfgtable;
u32 use_doorbell;
u32 board_id;
u16 command_register;
/* For controllers as old as the P600, this is very nearly
* the same thing as
*
* pci_save_state(pci_dev);
* pci_set_power_state(pci_dev, PCI_D3hot);
* pci_set_power_state(pci_dev, PCI_D0);
* pci_restore_state(pci_dev);
*
* For controllers newer than the P600, the pci power state
* method of resetting doesn't work so we have another way
* using the doorbell register.
*/
rc = hpsa_lookup_board_id(pdev, &board_id);
if (rc < 0 || !ctlr_is_resettable(board_id)) {
dev_warn(&pdev->dev, "Not resetting device.\n");
return -ENODEV;
}
/* if controller is soft- but not hard resettable... */
if (!ctlr_is_hard_resettable(board_id))
return -ENOTSUPP; /* try soft reset later. */
/* Save the PCI command register */
pci_read_config_word(pdev, 4, &command_register);
/* Turn the board off. This is so that later pci_restore_state()
* won't turn the board on before the rest of config space is ready.
*/
pci_disable_device(pdev);
pci_save_state(pdev);
/* find the first memory BAR, so we can find the cfg table */
rc = hpsa_pci_find_memory_BAR(pdev, &paddr);
if (rc)
return rc;
vaddr = remap_pci_mem(paddr, 0x250);
if (!vaddr)
return -ENOMEM;
/* find cfgtable in order to check if reset via doorbell is supported */
rc = hpsa_find_cfg_addrs(pdev, vaddr, &cfg_base_addr,
&cfg_base_addr_index, &cfg_offset);
if (rc)
goto unmap_vaddr;
cfgtable = remap_pci_mem(pci_resource_start(pdev,
cfg_base_addr_index) + cfg_offset, sizeof(*cfgtable));
if (!cfgtable) {
rc = -ENOMEM;
goto unmap_vaddr;
}
rc = write_driver_ver_to_cfgtable(cfgtable);
if (rc)
goto unmap_vaddr;
/* If reset via doorbell register is supported, use that.
* There are two such methods. Favor the newest method.
*/
misc_fw_support = readl(&cfgtable->misc_fw_support);
use_doorbell = misc_fw_support & MISC_FW_DOORBELL_RESET2;
if (use_doorbell) {
use_doorbell = DOORBELL_CTLR_RESET2;
} else {
use_doorbell = misc_fw_support & MISC_FW_DOORBELL_RESET;
if (use_doorbell) {
dev_warn(&pdev->dev, "Soft reset not supported. "
"Firmware update is required.\n");
rc = -ENOTSUPP; /* try soft reset */
goto unmap_cfgtable;
}
}
rc = hpsa_controller_hard_reset(pdev, vaddr, use_doorbell);
if (rc)
goto unmap_cfgtable;
pci_restore_state(pdev);
rc = pci_enable_device(pdev);
if (rc) {
dev_warn(&pdev->dev, "failed to enable device.\n");
goto unmap_cfgtable;
}
pci_write_config_word(pdev, 4, command_register);
/* Some devices (notably the HP Smart Array 5i Controller)
need a little pause here */
msleep(HPSA_POST_RESET_PAUSE_MSECS);
/* Wait for board to become not ready, then ready. */
dev_info(&pdev->dev, "Waiting for board to reset.\n");
rc = hpsa_wait_for_board_state(pdev, vaddr, BOARD_NOT_READY);
if (rc) {
dev_warn(&pdev->dev,
"failed waiting for board to reset."
" Will try soft reset.\n");
rc = -ENOTSUPP; /* Not expected, but try soft reset later */
goto unmap_cfgtable;
}
rc = hpsa_wait_for_board_state(pdev, vaddr, BOARD_READY);
if (rc) {
dev_warn(&pdev->dev,
"failed waiting for board to become ready "
"after hard reset\n");
goto unmap_cfgtable;
}
rc = controller_reset_failed(vaddr);
if (rc < 0)
goto unmap_cfgtable;
if (rc) {
dev_warn(&pdev->dev, "Unable to successfully reset "
"controller. Will try soft reset.\n");
rc = -ENOTSUPP;
} else {
dev_info(&pdev->dev, "board ready after hard reset.\n");
}
unmap_cfgtable:
iounmap(cfgtable);
unmap_vaddr:
iounmap(vaddr);
return rc;
}
/*
* We cannot read the structure directly, for portability we must use
* the io functions.
* This is for debug only.
*/
static void print_cfg_table(struct device *dev, struct CfgTable *tb)
{
#ifdef HPSA_DEBUG
int i;
char temp_name[17];
dev_info(dev, "Controller Configuration information\n");
dev_info(dev, "------------------------------------\n");
for (i = 0; i < 4; i++)
temp_name[i] = readb(&(tb->Signature[i]));
temp_name[4] = '\0';
dev_info(dev, " Signature = %s\n", temp_name);
dev_info(dev, " Spec Number = %d\n", readl(&(tb->SpecValence)));
dev_info(dev, " Transport methods supported = 0x%x\n",
readl(&(tb->TransportSupport)));
dev_info(dev, " Transport methods active = 0x%x\n",
readl(&(tb->TransportActive)));
dev_info(dev, " Requested transport Method = 0x%x\n",
readl(&(tb->HostWrite.TransportRequest)));
dev_info(dev, " Coalesce Interrupt Delay = 0x%x\n",
readl(&(tb->HostWrite.CoalIntDelay)));
dev_info(dev, " Coalesce Interrupt Count = 0x%x\n",
readl(&(tb->HostWrite.CoalIntCount)));
dev_info(dev, " Max outstanding commands = 0x%d\n",
readl(&(tb->CmdsOutMax)));
dev_info(dev, " Bus Types = 0x%x\n", readl(&(tb->BusTypes)));
for (i = 0; i < 16; i++)
temp_name[i] = readb(&(tb->ServerName[i]));
temp_name[16] = '\0';
dev_info(dev, " Server Name = %s\n", temp_name);
dev_info(dev, " Heartbeat Counter = 0x%x\n\n\n",
readl(&(tb->HeartBeat)));
#endif /* HPSA_DEBUG */
}
static int find_PCI_BAR_index(struct pci_dev *pdev, unsigned long pci_bar_addr)
{
int i, offset, mem_type, bar_type;
if (pci_bar_addr == PCI_BASE_ADDRESS_0) /* looking for BAR zero? */
return 0;
offset = 0;
for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
bar_type = pci_resource_flags(pdev, i) & PCI_BASE_ADDRESS_SPACE;
if (bar_type == PCI_BASE_ADDRESS_SPACE_IO)
offset += 4;
else {
mem_type = pci_resource_flags(pdev, i) &
PCI_BASE_ADDRESS_MEM_TYPE_MASK;
switch (mem_type) {
case PCI_BASE_ADDRESS_MEM_TYPE_32:
case PCI_BASE_ADDRESS_MEM_TYPE_1M:
offset += 4; /* 32 bit */
break;
case PCI_BASE_ADDRESS_MEM_TYPE_64:
offset += 8;
break;
default: /* reserved in PCI 2.2 */
dev_warn(&pdev->dev,
"base address is invalid\n");
return -1;
break;
}
}
if (offset == pci_bar_addr - PCI_BASE_ADDRESS_0)
return i + 1;
}
return -1;
}
/* If MSI/MSI-X is supported by the kernel we will try to enable it on
* controllers that are capable. If not, we use IO-APIC mode.
*/
static void hpsa_interrupt_mode(struct ctlr_info *h)
{
#ifdef CONFIG_PCI_MSI
int err, i;
struct msix_entry hpsa_msix_entries[MAX_REPLY_QUEUES];
for (i = 0; i < MAX_REPLY_QUEUES; i++) {
hpsa_msix_entries[i].vector = 0;
hpsa_msix_entries[i].entry = i;
}
/* Some boards advertise MSI but don't really support it */
if ((h->board_id == 0x40700E11) || (h->board_id == 0x40800E11) ||
(h->board_id == 0x40820E11) || (h->board_id == 0x40830E11))
goto default_int_mode;
if (pci_find_capability(h->pdev, PCI_CAP_ID_MSIX)) {
dev_info(&h->pdev->dev, "MSIX\n");
err = pci_enable_msix(h->pdev, hpsa_msix_entries,
MAX_REPLY_QUEUES);
if (!err) {
for (i = 0; i < MAX_REPLY_QUEUES; i++)
h->intr[i] = hpsa_msix_entries[i].vector;
h->msix_vector = 1;
return;
}
if (err > 0) {
dev_warn(&h->pdev->dev, "only %d MSI-X vectors "
"available\n", err);
goto default_int_mode;
} else {
dev_warn(&h->pdev->dev, "MSI-X init failed %d\n",
err);
goto default_int_mode;
}
}
if (pci_find_capability(h->pdev, PCI_CAP_ID_MSI)) {
dev_info(&h->pdev->dev, "MSI\n");
if (!pci_enable_msi(h->pdev))
h->msi_vector = 1;
else
dev_warn(&h->pdev->dev, "MSI init failed\n");
}
default_int_mode:
#endif /* CONFIG_PCI_MSI */
/* if we get here we're going to use the default interrupt mode */
h->intr[h->intr_mode] = h->pdev->irq;
}
static int hpsa_lookup_board_id(struct pci_dev *pdev, u32 *board_id)
{
int i;
u32 subsystem_vendor_id, subsystem_device_id;
subsystem_vendor_id = pdev->subsystem_vendor;
subsystem_device_id = pdev->subsystem_device;
*board_id = ((subsystem_device_id << 16) & 0xffff0000) |
subsystem_vendor_id;
for (i = 0; i < ARRAY_SIZE(products); i++)
if (*board_id == products[i].board_id)
return i;
if ((subsystem_vendor_id != PCI_VENDOR_ID_HP &&
subsystem_vendor_id != PCI_VENDOR_ID_COMPAQ) ||
!hpsa_allow_any) {
dev_warn(&pdev->dev, "unrecognized board ID: "
"0x%08x, ignoring.\n", *board_id);
return -ENODEV;
}
return ARRAY_SIZE(products) - 1; /* generic unknown smart array */
}
static int hpsa_pci_find_memory_BAR(struct pci_dev *pdev,
unsigned long *memory_bar)
{
int i;
for (i = 0; i < DEVICE_COUNT_RESOURCE; i++)
if (pci_resource_flags(pdev, i) & IORESOURCE_MEM) {
/* addressing mode bits already removed */
*memory_bar = pci_resource_start(pdev, i);
dev_dbg(&pdev->dev, "memory BAR = %lx\n",
*memory_bar);
return 0;
}
dev_warn(&pdev->dev, "no memory BAR found\n");
return -ENODEV;
}
static int hpsa_wait_for_board_state(struct pci_dev *pdev, void __iomem *vaddr,
int wait_for_ready)
{
int i, iterations;
u32 scratchpad;
if (wait_for_ready)
iterations = HPSA_BOARD_READY_ITERATIONS;
else
iterations = HPSA_BOARD_NOT_READY_ITERATIONS;
for (i = 0; i < iterations; i++) {
scratchpad = readl(vaddr + SA5_SCRATCHPAD_OFFSET);
if (wait_for_ready) {
if (scratchpad == HPSA_FIRMWARE_READY)
return 0;
} else {
if (scratchpad != HPSA_FIRMWARE_READY)
return 0;
}
msleep(HPSA_BOARD_READY_POLL_INTERVAL_MSECS);
}
dev_warn(&pdev->dev, "board not ready, timed out.\n");
return -ENODEV;
}
static int hpsa_find_cfg_addrs(struct pci_dev *pdev, void __iomem *vaddr,
u32 *cfg_base_addr, u64 *cfg_base_addr_index,
u64 *cfg_offset)
{
*cfg_base_addr = readl(vaddr + SA5_CTCFG_OFFSET);
*cfg_offset = readl(vaddr + SA5_CTMEM_OFFSET);
*cfg_base_addr &= (u32) 0x0000ffff;
*cfg_base_addr_index = find_PCI_BAR_index(pdev, *cfg_base_addr);
if (*cfg_base_addr_index == -1) {
dev_warn(&pdev->dev, "cannot find cfg_base_addr_index\n");
return -ENODEV;
}
return 0;
}
static int hpsa_find_cfgtables(struct ctlr_info *h)
{
u64 cfg_offset;
u32 cfg_base_addr;
u64 cfg_base_addr_index;
u32 trans_offset;
int rc;
rc = hpsa_find_cfg_addrs(h->pdev, h->vaddr, &cfg_base_addr,
&cfg_base_addr_index, &cfg_offset);
if (rc)
return rc;
h->cfgtable = remap_pci_mem(pci_resource_start(h->pdev,
cfg_base_addr_index) + cfg_offset, sizeof(*h->cfgtable));
if (!h->cfgtable)
return -ENOMEM;
rc = write_driver_ver_to_cfgtable(h->cfgtable);
if (rc)
return rc;
/* Find performant mode table. */
trans_offset = readl(&h->cfgtable->TransMethodOffset);
h->transtable = remap_pci_mem(pci_resource_start(h->pdev,
cfg_base_addr_index)+cfg_offset+trans_offset,
sizeof(*h->transtable));
if (!h->transtable)
return -ENOMEM;
return 0;
}
static void hpsa_get_max_perf_mode_cmds(struct ctlr_info *h)
{
h->max_commands = readl(&(h->cfgtable->MaxPerformantModeCommands));
/* Limit commands in memory limited kdump scenario. */
if (reset_devices && h->max_commands > 32)
h->max_commands = 32;
if (h->max_commands < 16) {
dev_warn(&h->pdev->dev, "Controller reports "
"max supported commands of %d, an obvious lie. "
"Using 16. Ensure that firmware is up to date.\n",
h->max_commands);
h->max_commands = 16;
}
}
/* Interrogate the hardware for some limits:
* max commands, max SG elements without chaining, and with chaining,
* SG chain block size, etc.
*/
static void hpsa_find_board_params(struct ctlr_info *h)
{
hpsa_get_max_perf_mode_cmds(h);
h->nr_cmds = h->max_commands - 4; /* Allow room for some ioctls */
h->maxsgentries = readl(&(h->cfgtable->MaxScatterGatherElements));
/*
* Limit in-command s/g elements to 32 save dma'able memory.
* Howvever spec says if 0, use 31
*/
h->max_cmd_sg_entries = 31;
if (h->maxsgentries > 512) {
h->max_cmd_sg_entries = 32;
h->chainsize = h->maxsgentries - h->max_cmd_sg_entries + 1;
h->maxsgentries--; /* save one for chain pointer */
} else {
h->maxsgentries = 31; /* default to traditional values */
h->chainsize = 0;
}
/* Find out what task management functions are supported and cache */
h->TMFSupportFlags = readl(&(h->cfgtable->TMFSupportFlags));
}
static inline bool hpsa_CISS_signature_present(struct ctlr_info *h)
{
if (!check_signature(h->cfgtable->Signature, "CISS", 4)) {
dev_warn(&h->pdev->dev, "not a valid CISS config table\n");
return false;
}
return true;
}
/* Need to enable prefetch in the SCSI core for 6400 in x86 */
static inline void hpsa_enable_scsi_prefetch(struct ctlr_info *h)
{
#ifdef CONFIG_X86
u32 prefetch;
prefetch = readl(&(h->cfgtable->SCSI_Prefetch));
prefetch |= 0x100;
writel(prefetch, &(h->cfgtable->SCSI_Prefetch));
#endif
}
/* Disable DMA prefetch for the P600. Otherwise an ASIC bug may result
* in a prefetch beyond physical memory.
*/
static inline void hpsa_p600_dma_prefetch_quirk(struct ctlr_info *h)
{
u32 dma_prefetch;
if (h->board_id != 0x3225103C)
return;
dma_prefetch = readl(h->vaddr + I2O_DMA1_CFG);
dma_prefetch |= 0x8000;
writel(dma_prefetch, h->vaddr + I2O_DMA1_CFG);
}
static void hpsa_wait_for_mode_change_ack(struct ctlr_info *h)
{
int i;
u32 doorbell_value;
unsigned long flags;
/* under certain very rare conditions, this can take awhile.
* (e.g.: hot replace a failed 144GB drive in a RAID 5 set right
* as we enter this code.)
*/
for (i = 0; i < MAX_CONFIG_WAIT; i++) {
spin_lock_irqsave(&h->lock, flags);
doorbell_value = readl(h->vaddr + SA5_DOORBELL);
spin_unlock_irqrestore(&h->lock, flags);
if (!(doorbell_value & CFGTBL_ChangeReq))
break;
/* delay and try again */
usleep_range(10000, 20000);
}
}
static int hpsa_enter_simple_mode(struct ctlr_info *h)
{
u32 trans_support;
trans_support = readl(&(h->cfgtable->TransportSupport));
if (!(trans_support & SIMPLE_MODE))
return -ENOTSUPP;
h->max_commands = readl(&(h->cfgtable->CmdsOutMax));
/* Update the field, and then ring the doorbell */
writel(CFGTBL_Trans_Simple, &(h->cfgtable->HostWrite.TransportRequest));
writel(CFGTBL_ChangeReq, h->vaddr + SA5_DOORBELL);
hpsa_wait_for_mode_change_ack(h);
print_cfg_table(&h->pdev->dev, h->cfgtable);
if (!(readl(&(h->cfgtable->TransportActive)) & CFGTBL_Trans_Simple)) {
dev_warn(&h->pdev->dev,
"unable to get board into simple mode\n");
return -ENODEV;
}
h->transMethod = CFGTBL_Trans_Simple;
return 0;
}
static int hpsa_pci_init(struct ctlr_info *h)
{
int prod_index, err;
prod_index = hpsa_lookup_board_id(h->pdev, &h->board_id);
if (prod_index < 0)
return -ENODEV;
h->product_name = products[prod_index].product_name;
h->access = *(products[prod_index].access);
pci_disable_link_state(h->pdev, PCIE_LINK_STATE_L0S |
PCIE_LINK_STATE_L1 | PCIE_LINK_STATE_CLKPM);
err = pci_enable_device(h->pdev);
if (err) {
dev_warn(&h->pdev->dev, "unable to enable PCI device\n");
return err;
}
/* Enable bus mastering (pci_disable_device may disable this) */
pci_set_master(h->pdev);
err = pci_request_regions(h->pdev, HPSA);
if (err) {
dev_err(&h->pdev->dev,
"cannot obtain PCI resources, aborting\n");
return err;
}
hpsa_interrupt_mode(h);
err = hpsa_pci_find_memory_BAR(h->pdev, &h->paddr);
if (err)
goto err_out_free_res;
h->vaddr = remap_pci_mem(h->paddr, 0x250);
if (!h->vaddr) {
err = -ENOMEM;
goto err_out_free_res;
}
err = hpsa_wait_for_board_state(h->pdev, h->vaddr, BOARD_READY);
if (err)
goto err_out_free_res;
err = hpsa_find_cfgtables(h);
if (err)
goto err_out_free_res;
hpsa_find_board_params(h);
if (!hpsa_CISS_signature_present(h)) {
err = -ENODEV;
goto err_out_free_res;
}
hpsa_enable_scsi_prefetch(h);
hpsa_p600_dma_prefetch_quirk(h);
err = hpsa_enter_simple_mode(h);
if (err)
goto err_out_free_res;
return 0;
err_out_free_res:
if (h->transtable)
iounmap(h->transtable);
if (h->cfgtable)
iounmap(h->cfgtable);
if (h->vaddr)
iounmap(h->vaddr);
pci_disable_device(h->pdev);
pci_release_regions(h->pdev);
return err;
}
static void hpsa_hba_inquiry(struct ctlr_info *h)
{
int rc;
#define HBA_INQUIRY_BYTE_COUNT 64
h->hba_inquiry_data = kmalloc(HBA_INQUIRY_BYTE_COUNT, GFP_KERNEL);
if (!h->hba_inquiry_data)
return;
rc = hpsa_scsi_do_inquiry(h, RAID_CTLR_LUNID, 0,
h->hba_inquiry_data, HBA_INQUIRY_BYTE_COUNT);
if (rc != 0) {
kfree(h->hba_inquiry_data);
h->hba_inquiry_data = NULL;
}
}
static int hpsa_init_reset_devices(struct pci_dev *pdev)
{
int rc, i;
if (!reset_devices)
return 0;
/* Reset the controller with a PCI power-cycle or via doorbell */
rc = hpsa_kdump_hard_reset_controller(pdev);
/* -ENOTSUPP here means we cannot reset the controller
* but it's already (and still) up and running in
* "performant mode". Or, it might be 640x, which can't reset
* due to concerns about shared bbwc between 6402/6404 pair.
*/
if (rc == -ENOTSUPP)
return rc; /* just try to do the kdump anyhow. */
if (rc)
return -ENODEV;
/* Now try to get the controller to respond to a no-op */
dev_warn(&pdev->dev, "Waiting for controller to respond to no-op\n");
for (i = 0; i < HPSA_POST_RESET_NOOP_RETRIES; i++) {
if (hpsa_noop(pdev) == 0)
break;
else
dev_warn(&pdev->dev, "no-op failed%s\n",
(i < 11 ? "; re-trying" : ""));
}
return 0;
}
static int hpsa_allocate_cmd_pool(struct ctlr_info *h)
{
h->cmd_pool_bits = kzalloc(
DIV_ROUND_UP(h->nr_cmds, BITS_PER_LONG) *
sizeof(unsigned long), GFP_KERNEL);
h->cmd_pool = pci_alloc_consistent(h->pdev,
h->nr_cmds * sizeof(*h->cmd_pool),
&(h->cmd_pool_dhandle));
h->errinfo_pool = pci_alloc_consistent(h->pdev,
h->nr_cmds * sizeof(*h->errinfo_pool),
&(h->errinfo_pool_dhandle));
if ((h->cmd_pool_bits == NULL)
|| (h->cmd_pool == NULL)
|| (h->errinfo_pool == NULL)) {
dev_err(&h->pdev->dev, "out of memory in %s", __func__);
return -ENOMEM;
}
return 0;
}
static void hpsa_free_cmd_pool(struct ctlr_info *h)
{
kfree(h->cmd_pool_bits);
if (h->cmd_pool)
pci_free_consistent(h->pdev,
h->nr_cmds * sizeof(struct CommandList),
h->cmd_pool, h->cmd_pool_dhandle);
if (h->errinfo_pool)
pci_free_consistent(h->pdev,
h->nr_cmds * sizeof(struct ErrorInfo),
h->errinfo_pool,
h->errinfo_pool_dhandle);
}
static int hpsa_request_irq(struct ctlr_info *h,
irqreturn_t (*msixhandler)(int, void *),
irqreturn_t (*intxhandler)(int, void *))
{
int rc, i;
/*
* initialize h->q[x] = x so that interrupt handlers know which
* queue to process.
*/
for (i = 0; i < MAX_REPLY_QUEUES; i++)
h->q[i] = (u8) i;
if (h->intr_mode == PERF_MODE_INT && h->msix_vector) {
/* If performant mode and MSI-X, use multiple reply queues */
for (i = 0; i < MAX_REPLY_QUEUES; i++)
rc = request_irq(h->intr[i], msixhandler,
0, h->devname,
&h->q[i]);
} else {
/* Use single reply pool */
if (h->msix_vector || h->msi_vector) {
rc = request_irq(h->intr[h->intr_mode],
msixhandler, 0, h->devname,
&h->q[h->intr_mode]);
} else {
rc = request_irq(h->intr[h->intr_mode],
intxhandler, IRQF_SHARED, h->devname,
&h->q[h->intr_mode]);
}
}
if (rc) {
dev_err(&h->pdev->dev, "unable to get irq %d for %s\n",
h->intr[h->intr_mode], h->devname);
return -ENODEV;
}
return 0;
}
static int hpsa_kdump_soft_reset(struct ctlr_info *h)
{
if (hpsa_send_host_reset(h, RAID_CTLR_LUNID,
HPSA_RESET_TYPE_CONTROLLER)) {
dev_warn(&h->pdev->dev, "Resetting array controller failed.\n");
return -EIO;
}
dev_info(&h->pdev->dev, "Waiting for board to soft reset.\n");
if (hpsa_wait_for_board_state(h->pdev, h->vaddr, BOARD_NOT_READY)) {
dev_warn(&h->pdev->dev, "Soft reset had no effect.\n");
return -1;
}
dev_info(&h->pdev->dev, "Board reset, awaiting READY status.\n");
if (hpsa_wait_for_board_state(h->pdev, h->vaddr, BOARD_READY)) {
dev_warn(&h->pdev->dev, "Board failed to become ready "
"after soft reset.\n");
return -1;
}
return 0;
}
static void free_irqs(struct ctlr_info *h)
{
int i;
if (!h->msix_vector || h->intr_mode != PERF_MODE_INT) {
/* Single reply queue, only one irq to free */
i = h->intr_mode;
free_irq(h->intr[i], &h->q[i]);
return;
}
for (i = 0; i < MAX_REPLY_QUEUES; i++)
free_irq(h->intr[i], &h->q[i]);
}
static void hpsa_free_irqs_and_disable_msix(struct ctlr_info *h)
{
free_irqs(h);
#ifdef CONFIG_PCI_MSI
if (h->msix_vector) {
if (h->pdev->msix_enabled)
pci_disable_msix(h->pdev);
} else if (h->msi_vector) {
if (h->pdev->msi_enabled)
pci_disable_msi(h->pdev);
}
#endif /* CONFIG_PCI_MSI */
}
static void hpsa_undo_allocations_after_kdump_soft_reset(struct ctlr_info *h)
{
hpsa_free_irqs_and_disable_msix(h);
hpsa_free_sg_chain_blocks(h);
hpsa_free_cmd_pool(h);
kfree(h->blockFetchTable);
pci_free_consistent(h->pdev, h->reply_pool_size,
h->reply_pool, h->reply_pool_dhandle);
if (h->vaddr)
iounmap(h->vaddr);
if (h->transtable)
iounmap(h->transtable);
if (h->cfgtable)
iounmap(h->cfgtable);
pci_release_regions(h->pdev);
kfree(h);
}
static void remove_ctlr_from_lockup_detector_list(struct ctlr_info *h)
{
assert_spin_locked(&lockup_detector_lock);
if (!hpsa_lockup_detector)
return;
if (h->lockup_detected)
return; /* already stopped the lockup detector */
list_del(&h->lockup_list);
}
/* Called when controller lockup detected. */
static void fail_all_cmds_on_list(struct ctlr_info *h, struct list_head *list)
{
struct CommandList *c = NULL;
assert_spin_locked(&h->lock);
/* Mark all outstanding commands as failed and complete them. */
while (!list_empty(list)) {
c = list_entry(list->next, struct CommandList, list);
c->err_info->CommandStatus = CMD_HARDWARE_ERR;
finish_cmd(c);
}
}
static void controller_lockup_detected(struct ctlr_info *h)
{
unsigned long flags;
assert_spin_locked(&lockup_detector_lock);
remove_ctlr_from_lockup_detector_list(h);
h->access.set_intr_mask(h, HPSA_INTR_OFF);
spin_lock_irqsave(&h->lock, flags);
h->lockup_detected = readl(h->vaddr + SA5_SCRATCHPAD_OFFSET);
spin_unlock_irqrestore(&h->lock, flags);
dev_warn(&h->pdev->dev, "Controller lockup detected: 0x%08x\n",
h->lockup_detected);
pci_disable_device(h->pdev);
spin_lock_irqsave(&h->lock, flags);
fail_all_cmds_on_list(h, &h->cmpQ);
fail_all_cmds_on_list(h, &h->reqQ);
spin_unlock_irqrestore(&h->lock, flags);
}
static void detect_controller_lockup(struct ctlr_info *h)
{
u64 now;
u32 heartbeat;
unsigned long flags;
assert_spin_locked(&lockup_detector_lock);
now = get_jiffies_64();
/* If we've received an interrupt recently, we're ok. */
if (time_after64(h->last_intr_timestamp +
(h->heartbeat_sample_interval), now))
return;
/*
* If we've already checked the heartbeat recently, we're ok.
* This could happen if someone sends us a signal. We
* otherwise don't care about signals in this thread.
*/
if (time_after64(h->last_heartbeat_timestamp +
(h->heartbeat_sample_interval), now))
return;
/* If heartbeat has not changed since we last looked, we're not ok. */
spin_lock_irqsave(&h->lock, flags);
heartbeat = readl(&h->cfgtable->HeartBeat);
spin_unlock_irqrestore(&h->lock, flags);
if (h->last_heartbeat == heartbeat) {
controller_lockup_detected(h);
return;
}
/* We're ok. */
h->last_heartbeat = heartbeat;
h->last_heartbeat_timestamp = now;
}
static int detect_controller_lockup_thread(void *notused)
{
struct ctlr_info *h;
unsigned long flags;
while (1) {
struct list_head *this, *tmp;
schedule_timeout_interruptible(HEARTBEAT_SAMPLE_INTERVAL);
if (kthread_should_stop())
break;
spin_lock_irqsave(&lockup_detector_lock, flags);
list_for_each_safe(this, tmp, &hpsa_ctlr_list) {
h = list_entry(this, struct ctlr_info, lockup_list);
detect_controller_lockup(h);
}
spin_unlock_irqrestore(&lockup_detector_lock, flags);
}
return 0;
}
static void add_ctlr_to_lockup_detector_list(struct ctlr_info *h)
{
unsigned long flags;
h->heartbeat_sample_interval = HEARTBEAT_SAMPLE_INTERVAL;
spin_lock_irqsave(&lockup_detector_lock, flags);
list_add_tail(&h->lockup_list, &hpsa_ctlr_list);
spin_unlock_irqrestore(&lockup_detector_lock, flags);
}
static void start_controller_lockup_detector(struct ctlr_info *h)
{
/* Start the lockup detector thread if not already started */
if (!hpsa_lockup_detector) {
spin_lock_init(&lockup_detector_lock);
hpsa_lockup_detector =
kthread_run(detect_controller_lockup_thread,
NULL, HPSA);
}
if (!hpsa_lockup_detector) {
dev_warn(&h->pdev->dev,
"Could not start lockup detector thread\n");
return;
}
add_ctlr_to_lockup_detector_list(h);
}
static void stop_controller_lockup_detector(struct ctlr_info *h)
{
unsigned long flags;
spin_lock_irqsave(&lockup_detector_lock, flags);
remove_ctlr_from_lockup_detector_list(h);
/* If the list of ctlr's to monitor is empty, stop the thread */
if (list_empty(&hpsa_ctlr_list)) {
spin_unlock_irqrestore(&lockup_detector_lock, flags);
kthread_stop(hpsa_lockup_detector);
spin_lock_irqsave(&lockup_detector_lock, flags);
hpsa_lockup_detector = NULL;
}
spin_unlock_irqrestore(&lockup_detector_lock, flags);
}
static int hpsa_init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
{
int dac, rc;
struct ctlr_info *h;
int try_soft_reset = 0;
unsigned long flags;
if (number_of_controllers == 0)
printk(KERN_INFO DRIVER_NAME "\n");
rc = hpsa_init_reset_devices(pdev);
if (rc) {
if (rc != -ENOTSUPP)
return rc;
/* If the reset fails in a particular way (it has no way to do
* a proper hard reset, so returns -ENOTSUPP) we can try to do
* a soft reset once we get the controller configured up to the
* point that it can accept a command.
*/
try_soft_reset = 1;
rc = 0;
}
reinit_after_soft_reset:
/* Command structures must be aligned on a 32-byte boundary because
* the 5 lower bits of the address are used by the hardware. and by
* the driver. See comments in hpsa.h for more info.
*/
#define COMMANDLIST_ALIGNMENT 32
BUILD_BUG_ON(sizeof(struct CommandList) % COMMANDLIST_ALIGNMENT);
h = kzalloc(sizeof(*h), GFP_KERNEL);
if (!h)
return -ENOMEM;
h->pdev = pdev;
h->intr_mode = hpsa_simple_mode ? SIMPLE_MODE_INT : PERF_MODE_INT;
INIT_LIST_HEAD(&h->cmpQ);
INIT_LIST_HEAD(&h->reqQ);
spin_lock_init(&h->lock);
spin_lock_init(&h->scan_lock);
rc = hpsa_pci_init(h);
if (rc != 0)
goto clean1;
sprintf(h->devname, HPSA "%d", number_of_controllers);
h->ctlr = number_of_controllers;
number_of_controllers++;
/* configure PCI DMA stuff */
rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(64));
if (rc == 0) {
dac = 1;
} else {
rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (rc == 0) {
dac = 0;
} else {
dev_err(&pdev->dev, "no suitable DMA available\n");
goto clean1;
}
}
/* make sure the board interrupts are off */
h->access.set_intr_mask(h, HPSA_INTR_OFF);
if (hpsa_request_irq(h, do_hpsa_intr_msi, do_hpsa_intr_intx))
goto clean2;
dev_info(&pdev->dev, "%s: <0x%x> at IRQ %d%s using DAC\n",
h->devname, pdev->device,
h->intr[h->intr_mode], dac ? "" : " not");
if (hpsa_allocate_cmd_pool(h))
goto clean4;
if (hpsa_allocate_sg_chain_blocks(h))
goto clean4;
init_waitqueue_head(&h->scan_wait_queue);
h->scan_finished = 1; /* no scan currently in progress */
pci_set_drvdata(pdev, h);
h->ndevices = 0;
h->scsi_host = NULL;
spin_lock_init(&h->devlock);
hpsa_put_ctlr_into_performant_mode(h);
/* At this point, the controller is ready to take commands.
* Now, if reset_devices and the hard reset didn't work, try
* the soft reset and see if that works.
*/
if (try_soft_reset) {
/* This is kind of gross. We may or may not get a completion
* from the soft reset command, and if we do, then the value
* from the fifo may or may not be valid. So, we wait 10 secs
* after the reset throwing away any completions we get during
* that time. Unregister the interrupt handler and register
* fake ones to scoop up any residual completions.
*/
spin_lock_irqsave(&h->lock, flags);
h->access.set_intr_mask(h, HPSA_INTR_OFF);
spin_unlock_irqrestore(&h->lock, flags);
free_irqs(h);
rc = hpsa_request_irq(h, hpsa_msix_discard_completions,
hpsa_intx_discard_completions);
if (rc) {
dev_warn(&h->pdev->dev, "Failed to request_irq after "
"soft reset.\n");
goto clean4;
}
rc = hpsa_kdump_soft_reset(h);
if (rc)
/* Neither hard nor soft reset worked, we're hosed. */
goto clean4;
dev_info(&h->pdev->dev, "Board READY.\n");
dev_info(&h->pdev->dev,
"Waiting for stale completions to drain.\n");
h->access.set_intr_mask(h, HPSA_INTR_ON);
msleep(10000);
h->access.set_intr_mask(h, HPSA_INTR_OFF);
rc = controller_reset_failed(h->cfgtable);
if (rc)
dev_info(&h->pdev->dev,
"Soft reset appears to have failed.\n");
/* since the controller's reset, we have to go back and re-init
* everything. Easiest to just forget what we've done and do it
* all over again.
*/
hpsa_undo_allocations_after_kdump_soft_reset(h);
try_soft_reset = 0;
if (rc)
/* don't go to clean4, we already unallocated */
return -ENODEV;
goto reinit_after_soft_reset;
}
/* Turn the interrupts on so we can service requests */
h->access.set_intr_mask(h, HPSA_INTR_ON);
hpsa_hba_inquiry(h);
hpsa_register_scsi(h); /* hook ourselves into SCSI subsystem */
start_controller_lockup_detector(h);
return 1;
clean4:
hpsa_free_sg_chain_blocks(h);
hpsa_free_cmd_pool(h);
free_irqs(h);
clean2:
clean1:
kfree(h);
return rc;
}
static void hpsa_flush_cache(struct ctlr_info *h)
{
char *flush_buf;
struct CommandList *c;
flush_buf = kzalloc(4, GFP_KERNEL);
if (!flush_buf)
return;
c = cmd_special_alloc(h);
if (!c) {
dev_warn(&h->pdev->dev, "cmd_special_alloc returned NULL!\n");
goto out_of_memory;
}
if (fill_cmd(c, HPSA_CACHE_FLUSH, h, flush_buf, 4, 0,
RAID_CTLR_LUNID, TYPE_CMD)) {
goto out;
}
hpsa_scsi_do_simple_cmd_with_retry(h, c, PCI_DMA_TODEVICE);
if (c->err_info->CommandStatus != 0)
out:
dev_warn(&h->pdev->dev,
"error flushing cache on controller\n");
cmd_special_free(h, c);
out_of_memory:
kfree(flush_buf);
}
static void hpsa_shutdown(struct pci_dev *pdev)
{
struct ctlr_info *h;
h = pci_get_drvdata(pdev);
/* Turn board interrupts off and send the flush cache command
* sendcmd will turn off interrupt, and send the flush...
* To write all data in the battery backed cache to disks
*/
hpsa_flush_cache(h);
h->access.set_intr_mask(h, HPSA_INTR_OFF);
hpsa_free_irqs_and_disable_msix(h);
}
static void hpsa_free_device_info(struct ctlr_info *h)
{
int i;
for (i = 0; i < h->ndevices; i++)
kfree(h->dev[i]);
}
static void hpsa_remove_one(struct pci_dev *pdev)
{
struct ctlr_info *h;
if (pci_get_drvdata(pdev) == NULL) {
dev_err(&pdev->dev, "unable to remove device\n");
return;
}
h = pci_get_drvdata(pdev);
stop_controller_lockup_detector(h);
hpsa_unregister_scsi(h); /* unhook from SCSI subsystem */
hpsa_shutdown(pdev);
iounmap(h->vaddr);
iounmap(h->transtable);
iounmap(h->cfgtable);
hpsa_free_device_info(h);
hpsa_free_sg_chain_blocks(h);
pci_free_consistent(h->pdev,
h->nr_cmds * sizeof(struct CommandList),
h->cmd_pool, h->cmd_pool_dhandle);
pci_free_consistent(h->pdev,
h->nr_cmds * sizeof(struct ErrorInfo),
h->errinfo_pool, h->errinfo_pool_dhandle);
pci_free_consistent(h->pdev, h->reply_pool_size,
h->reply_pool, h->reply_pool_dhandle);
kfree(h->cmd_pool_bits);
kfree(h->blockFetchTable);
kfree(h->hba_inquiry_data);
pci_disable_device(pdev);
pci_release_regions(pdev);
pci_set_drvdata(pdev, NULL);
kfree(h);
}
static int hpsa_suspend(__attribute__((unused)) struct pci_dev *pdev,
__attribute__((unused)) pm_message_t state)
{
return -ENOSYS;
}
static int hpsa_resume(__attribute__((unused)) struct pci_dev *pdev)
{
return -ENOSYS;
}
static struct pci_driver hpsa_pci_driver = {
.name = HPSA,
.probe = hpsa_init_one,
.remove = hpsa_remove_one,
.id_table = hpsa_pci_device_id, /* id_table */
.shutdown = hpsa_shutdown,
.suspend = hpsa_suspend,
.resume = hpsa_resume,
};
/* Fill in bucket_map[], given nsgs (the max number of
* scatter gather elements supported) and bucket[],
* which is an array of 8 integers. The bucket[] array
* contains 8 different DMA transfer sizes (in 16
* byte increments) which the controller uses to fetch
* commands. This function fills in bucket_map[], which
* maps a given number of scatter gather elements to one of
* the 8 DMA transfer sizes. The point of it is to allow the
* controller to only do as much DMA as needed to fetch the
* command, with the DMA transfer size encoded in the lower
* bits of the command address.
*/
static void calc_bucket_map(int bucket[], int num_buckets,
int nsgs, int *bucket_map)
{
int i, j, b, size;
/* even a command with 0 SGs requires 4 blocks */
#define MINIMUM_TRANSFER_BLOCKS 4
#define NUM_BUCKETS 8
/* Note, bucket_map must have nsgs+1 entries. */
for (i = 0; i <= nsgs; i++) {
/* Compute size of a command with i SG entries */
size = i + MINIMUM_TRANSFER_BLOCKS;
b = num_buckets; /* Assume the biggest bucket */
/* Find the bucket that is just big enough */
for (j = 0; j < 8; j++) {
if (bucket[j] >= size) {
b = j;
break;
}
}
/* for a command with i SG entries, use bucket b. */
bucket_map[i] = b;
}
}
static void hpsa_enter_performant_mode(struct ctlr_info *h, u32 use_short_tags)
{
int i;
unsigned long register_value;
/* This is a bit complicated. There are 8 registers on
* the controller which we write to to tell it 8 different
* sizes of commands which there may be. It's a way of
* reducing the DMA done to fetch each command. Encoded into
* each command's tag are 3 bits which communicate to the controller
* which of the eight sizes that command fits within. The size of
* each command depends on how many scatter gather entries there are.
* Each SG entry requires 16 bytes. The eight registers are programmed
* with the number of 16-byte blocks a command of that size requires.
* The smallest command possible requires 5 such 16 byte blocks.
* the largest command possible requires SG_ENTRIES_IN_CMD + 4 16-byte
* blocks. Note, this only extends to the SG entries contained
* within the command block, and does not extend to chained blocks
* of SG elements. bft[] contains the eight values we write to
* the registers. They are not evenly distributed, but have more
* sizes for small commands, and fewer sizes for larger commands.
*/
int bft[8] = {5, 6, 8, 10, 12, 20, 28, SG_ENTRIES_IN_CMD + 4};
BUILD_BUG_ON(28 > SG_ENTRIES_IN_CMD + 4);
/* 5 = 1 s/g entry or 4k
* 6 = 2 s/g entry or 8k
* 8 = 4 s/g entry or 16k
* 10 = 6 s/g entry or 24k
*/
/* Controller spec: zero out this buffer. */
memset(h->reply_pool, 0, h->reply_pool_size);
bft[7] = SG_ENTRIES_IN_CMD + 4;
calc_bucket_map(bft, ARRAY_SIZE(bft),
SG_ENTRIES_IN_CMD, h->blockFetchTable);
for (i = 0; i < 8; i++)
writel(bft[i], &h->transtable->BlockFetch[i]);
/* size of controller ring buffer */
writel(h->max_commands, &h->transtable->RepQSize);
writel(h->nreply_queues, &h->transtable->RepQCount);
writel(0, &h->transtable->RepQCtrAddrLow32);
writel(0, &h->transtable->RepQCtrAddrHigh32);
for (i = 0; i < h->nreply_queues; i++) {
writel(0, &h->transtable->RepQAddr[i].upper);
writel(h->reply_pool_dhandle +
(h->max_commands * sizeof(u64) * i),
&h->transtable->RepQAddr[i].lower);
}
writel(CFGTBL_Trans_Performant | use_short_tags |
CFGTBL_Trans_enable_directed_msix,
&(h->cfgtable->HostWrite.TransportRequest));
writel(CFGTBL_ChangeReq, h->vaddr + SA5_DOORBELL);
hpsa_wait_for_mode_change_ack(h);
register_value = readl(&(h->cfgtable->TransportActive));
if (!(register_value & CFGTBL_Trans_Performant)) {
dev_warn(&h->pdev->dev, "unable to get board into"
" performant mode\n");
return;
}
/* Change the access methods to the performant access methods */
h->access = SA5_performant_access;
h->transMethod = CFGTBL_Trans_Performant;
}
static void hpsa_put_ctlr_into_performant_mode(struct ctlr_info *h)
{
u32 trans_support;
int i;
if (hpsa_simple_mode)
return;
trans_support = readl(&(h->cfgtable->TransportSupport));
if (!(trans_support & PERFORMANT_MODE))
return;
h->nreply_queues = h->msix_vector ? MAX_REPLY_QUEUES : 1;
hpsa_get_max_perf_mode_cmds(h);
/* Performant mode ring buffer and supporting data structures */
h->reply_pool_size = h->max_commands * sizeof(u64) * h->nreply_queues;
h->reply_pool = pci_alloc_consistent(h->pdev, h->reply_pool_size,
&(h->reply_pool_dhandle));
for (i = 0; i < h->nreply_queues; i++) {
h->reply_queue[i].head = &h->reply_pool[h->max_commands * i];
h->reply_queue[i].size = h->max_commands;
h->reply_queue[i].wraparound = 1; /* spec: init to 1 */
h->reply_queue[i].current_entry = 0;
}
/* Need a block fetch table for performant mode */
h->blockFetchTable = kmalloc(((SG_ENTRIES_IN_CMD + 1) *
sizeof(u32)), GFP_KERNEL);
if ((h->reply_pool == NULL)
|| (h->blockFetchTable == NULL))
goto clean_up;
hpsa_enter_performant_mode(h,
trans_support & CFGTBL_Trans_use_short_tags);
return;
clean_up:
if (h->reply_pool)
pci_free_consistent(h->pdev, h->reply_pool_size,
h->reply_pool, h->reply_pool_dhandle);
kfree(h->blockFetchTable);
}
/*
* This is it. Register the PCI driver information for the cards we control
* the OS will call our registered routines when it finds one of our cards.
*/
static int __init hpsa_init(void)
{
return pci_register_driver(&hpsa_pci_driver);
}
static void __exit hpsa_cleanup(void)
{
pci_unregister_driver(&hpsa_pci_driver);
}
module_init(hpsa_init);
module_exit(hpsa_cleanup);
| gpl-2.0 |
embeddedarm/linux-2.6.35-ts4800 | drivers/hwmon/ibmaem.c | 976 | 27596 | /*
* A hwmon driver for the IBM System Director Active Energy Manager (AEM)
* temperature/power/energy sensors and capping functionality.
* Copyright (C) 2008 IBM
*
* Author: Darrick J. Wong <djwong@us.ibm.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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/ipmi.h>
#include <linux/module.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/jiffies.h>
#include <linux/mutex.h>
#include <linux/kdev_t.h>
#include <linux/spinlock.h>
#include <linux/idr.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/platform_device.h>
#include <linux/math64.h>
#include <linux/time.h>
#define REFRESH_INTERVAL (HZ)
#define IPMI_TIMEOUT (30 * HZ)
#define DRVNAME "aem"
#define AEM_NETFN 0x2E
#define AEM_FIND_FW_CMD 0x80
#define AEM_ELEMENT_CMD 0x81
#define AEM_FW_INSTANCE_CMD 0x82
#define AEM_READ_ELEMENT_CFG 0x80
#define AEM_READ_BUFFER 0x81
#define AEM_READ_REGISTER 0x82
#define AEM_WRITE_REGISTER 0x83
#define AEM_SET_REG_MASK 0x84
#define AEM_CLEAR_REG_MASK 0x85
#define AEM_READ_ELEMENT_CFG2 0x86
#define AEM_CONTROL_ELEMENT 0
#define AEM_ENERGY_ELEMENT 1
#define AEM_CLOCK_ELEMENT 4
#define AEM_POWER_CAP_ELEMENT 7
#define AEM_EXHAUST_ELEMENT 9
#define AEM_POWER_ELEMENT 10
#define AEM_MODULE_TYPE_ID 0x0001
#define AEM2_NUM_ENERGY_REGS 2
#define AEM2_NUM_PCAP_REGS 6
#define AEM2_NUM_TEMP_REGS 2
#define AEM2_NUM_SENSORS 14
#define AEM1_NUM_ENERGY_REGS 1
#define AEM1_NUM_SENSORS 3
/* AEM 2.x has more energy registers */
#define AEM_NUM_ENERGY_REGS AEM2_NUM_ENERGY_REGS
/* AEM 2.x needs more sensor files */
#define AEM_NUM_SENSORS AEM2_NUM_SENSORS
#define POWER_CAP 0
#define POWER_CAP_MAX_HOTPLUG 1
#define POWER_CAP_MAX 2
#define POWER_CAP_MIN_WARNING 3
#define POWER_CAP_MIN 4
#define POWER_AUX 5
#define AEM_DEFAULT_POWER_INTERVAL 1000
#define AEM_MIN_POWER_INTERVAL 200
#define UJ_PER_MJ 1000L
static DEFINE_IDR(aem_idr);
static DEFINE_SPINLOCK(aem_idr_lock);
static struct platform_driver aem_driver = {
.driver = {
.name = DRVNAME,
.bus = &platform_bus_type,
}
};
struct aem_ipmi_data {
struct completion read_complete;
struct ipmi_addr address;
ipmi_user_t user;
int interface;
struct kernel_ipmi_msg tx_message;
long tx_msgid;
void *rx_msg_data;
unsigned short rx_msg_len;
unsigned char rx_result;
int rx_recv_type;
struct device *bmc_device;
};
struct aem_ro_sensor_template {
char *label;
ssize_t (*show)(struct device *dev,
struct device_attribute *devattr,
char *buf);
int index;
};
struct aem_rw_sensor_template {
char *label;
ssize_t (*show)(struct device *dev,
struct device_attribute *devattr,
char *buf);
ssize_t (*set)(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count);
int index;
};
struct aem_data {
struct list_head list;
struct device *hwmon_dev;
struct platform_device *pdev;
struct mutex lock;
char valid;
unsigned long last_updated; /* In jiffies */
u8 ver_major;
u8 ver_minor;
u8 module_handle;
int id;
struct aem_ipmi_data ipmi;
/* Function to update sensors */
void (*update)(struct aem_data *data);
/*
* AEM 1.x sensors:
* Available sensors:
* Energy meter
* Power meter
*
* AEM 2.x sensors:
* Two energy meters
* Two power meters
* Two temperature sensors
* Six power cap registers
*/
/* sysfs attrs */
struct sensor_device_attribute sensors[AEM_NUM_SENSORS];
/* energy use in mJ */
u64 energy[AEM_NUM_ENERGY_REGS];
/* power sampling interval in ms */
unsigned long power_period[AEM_NUM_ENERGY_REGS];
/* Everything past here is for AEM2 only */
/* power caps in dW */
u16 pcap[AEM2_NUM_PCAP_REGS];
/* exhaust temperature in C */
u8 temp[AEM2_NUM_TEMP_REGS];
};
/* Data structures returned by the AEM firmware */
struct aem_iana_id {
u8 bytes[3];
};
static struct aem_iana_id system_x_id = {
.bytes = {0x4D, 0x4F, 0x00}
};
/* These are used to find AEM1 instances */
struct aem_find_firmware_req {
struct aem_iana_id id;
u8 rsvd;
__be16 index;
__be16 module_type_id;
} __packed;
struct aem_find_firmware_resp {
struct aem_iana_id id;
u8 num_instances;
} __packed;
/* These are used to find AEM2 instances */
struct aem_find_instance_req {
struct aem_iana_id id;
u8 instance_number;
__be16 module_type_id;
} __packed;
struct aem_find_instance_resp {
struct aem_iana_id id;
u8 num_instances;
u8 major;
u8 minor;
u8 module_handle;
u16 record_id;
} __packed;
/* These are used to query sensors */
struct aem_read_sensor_req {
struct aem_iana_id id;
u8 module_handle;
u8 element;
u8 subcommand;
u8 reg;
u8 rx_buf_size;
} __packed;
struct aem_read_sensor_resp {
struct aem_iana_id id;
u8 bytes[0];
} __packed;
/* Data structures to talk to the IPMI layer */
struct aem_driver_data {
struct list_head aem_devices;
struct ipmi_smi_watcher bmc_events;
struct ipmi_user_hndl ipmi_hndlrs;
};
static void aem_register_bmc(int iface, struct device *dev);
static void aem_bmc_gone(int iface);
static void aem_msg_handler(struct ipmi_recv_msg *msg, void *user_msg_data);
static void aem_remove_sensors(struct aem_data *data);
static int aem_init_aem1(struct aem_ipmi_data *probe);
static int aem_init_aem2(struct aem_ipmi_data *probe);
static int aem1_find_sensors(struct aem_data *data);
static int aem2_find_sensors(struct aem_data *data);
static void update_aem1_sensors(struct aem_data *data);
static void update_aem2_sensors(struct aem_data *data);
static struct aem_driver_data driver_data = {
.aem_devices = LIST_HEAD_INIT(driver_data.aem_devices),
.bmc_events = {
.owner = THIS_MODULE,
.new_smi = aem_register_bmc,
.smi_gone = aem_bmc_gone,
},
.ipmi_hndlrs = {
.ipmi_recv_hndl = aem_msg_handler,
},
};
/* Functions to talk to the IPMI layer */
/* Initialize IPMI address, message buffers and user data */
static int aem_init_ipmi_data(struct aem_ipmi_data *data, int iface,
struct device *bmc)
{
int err;
init_completion(&data->read_complete);
data->bmc_device = bmc;
/* Initialize IPMI address */
data->address.addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
data->address.channel = IPMI_BMC_CHANNEL;
data->address.data[0] = 0;
data->interface = iface;
/* Initialize message buffers */
data->tx_msgid = 0;
data->tx_message.netfn = AEM_NETFN;
/* Create IPMI messaging interface user */
err = ipmi_create_user(data->interface, &driver_data.ipmi_hndlrs,
data, &data->user);
if (err < 0) {
dev_err(bmc, "Unable to register user with IPMI "
"interface %d\n", data->interface);
return -EACCES;
}
return 0;
}
/* Send an IPMI command */
static int aem_send_message(struct aem_ipmi_data *data)
{
int err;
err = ipmi_validate_addr(&data->address, sizeof(data->address));
if (err)
goto out;
data->tx_msgid++;
err = ipmi_request_settime(data->user, &data->address, data->tx_msgid,
&data->tx_message, data, 0, 0, 0);
if (err)
goto out1;
return 0;
out1:
dev_err(data->bmc_device, "request_settime=%x\n", err);
return err;
out:
dev_err(data->bmc_device, "validate_addr=%x\n", err);
return err;
}
/* Dispatch IPMI messages to callers */
static void aem_msg_handler(struct ipmi_recv_msg *msg, void *user_msg_data)
{
unsigned short rx_len;
struct aem_ipmi_data *data = user_msg_data;
if (msg->msgid != data->tx_msgid) {
dev_err(data->bmc_device, "Mismatch between received msgid "
"(%02x) and transmitted msgid (%02x)!\n",
(int)msg->msgid,
(int)data->tx_msgid);
ipmi_free_recv_msg(msg);
return;
}
data->rx_recv_type = msg->recv_type;
if (msg->msg.data_len > 0)
data->rx_result = msg->msg.data[0];
else
data->rx_result = IPMI_UNKNOWN_ERR_COMPLETION_CODE;
if (msg->msg.data_len > 1) {
rx_len = msg->msg.data_len - 1;
if (data->rx_msg_len < rx_len)
rx_len = data->rx_msg_len;
data->rx_msg_len = rx_len;
memcpy(data->rx_msg_data, msg->msg.data + 1, data->rx_msg_len);
} else
data->rx_msg_len = 0;
ipmi_free_recv_msg(msg);
complete(&data->read_complete);
}
/* ID functions */
/* Obtain an id */
static int aem_idr_get(int *id)
{
int i, err;
again:
if (unlikely(!idr_pre_get(&aem_idr, GFP_KERNEL)))
return -ENOMEM;
spin_lock(&aem_idr_lock);
err = idr_get_new(&aem_idr, NULL, &i);
spin_unlock(&aem_idr_lock);
if (unlikely(err == -EAGAIN))
goto again;
else if (unlikely(err))
return err;
*id = i & MAX_ID_MASK;
return 0;
}
/* Release an object ID */
static void aem_idr_put(int id)
{
spin_lock(&aem_idr_lock);
idr_remove(&aem_idr, id);
spin_unlock(&aem_idr_lock);
}
/* Sensor support functions */
/* Read a sensor value */
static int aem_read_sensor(struct aem_data *data, u8 elt, u8 reg,
void *buf, size_t size)
{
int rs_size, res;
struct aem_read_sensor_req rs_req;
struct aem_read_sensor_resp *rs_resp;
struct aem_ipmi_data *ipmi = &data->ipmi;
/* AEM registers are 1, 2, 4 or 8 bytes */
switch (size) {
case 1:
case 2:
case 4:
case 8:
break;
default:
return -EINVAL;
}
rs_req.id = system_x_id;
rs_req.module_handle = data->module_handle;
rs_req.element = elt;
rs_req.subcommand = AEM_READ_REGISTER;
rs_req.reg = reg;
rs_req.rx_buf_size = size;
ipmi->tx_message.cmd = AEM_ELEMENT_CMD;
ipmi->tx_message.data = (char *)&rs_req;
ipmi->tx_message.data_len = sizeof(rs_req);
rs_size = sizeof(*rs_resp) + size;
rs_resp = kzalloc(rs_size, GFP_KERNEL);
if (!rs_resp)
return -ENOMEM;
ipmi->rx_msg_data = rs_resp;
ipmi->rx_msg_len = rs_size;
aem_send_message(ipmi);
res = wait_for_completion_timeout(&ipmi->read_complete, IPMI_TIMEOUT);
if (!res)
return -ETIMEDOUT;
if (ipmi->rx_result || ipmi->rx_msg_len != rs_size ||
memcmp(&rs_resp->id, &system_x_id, sizeof(system_x_id))) {
kfree(rs_resp);
return -ENOENT;
}
switch (size) {
case 1: {
u8 *x = buf;
*x = rs_resp->bytes[0];
break;
}
case 2: {
u16 *x = buf;
*x = be16_to_cpup((__be16 *)rs_resp->bytes);
break;
}
case 4: {
u32 *x = buf;
*x = be32_to_cpup((__be32 *)rs_resp->bytes);
break;
}
case 8: {
u64 *x = buf;
*x = be64_to_cpup((__be64 *)rs_resp->bytes);
break;
}
}
return 0;
}
/* Update AEM energy registers */
static void update_aem_energy_one(struct aem_data *data, int which)
{
aem_read_sensor(data, AEM_ENERGY_ELEMENT, which,
&data->energy[which], 8);
}
static void update_aem_energy(struct aem_data *data)
{
update_aem_energy_one(data, 0);
if (data->ver_major < 2)
return;
update_aem_energy_one(data, 1);
}
/* Update all AEM1 sensors */
static void update_aem1_sensors(struct aem_data *data)
{
mutex_lock(&data->lock);
if (time_before(jiffies, data->last_updated + REFRESH_INTERVAL) &&
data->valid)
goto out;
update_aem_energy(data);
out:
mutex_unlock(&data->lock);
}
/* Update all AEM2 sensors */
static void update_aem2_sensors(struct aem_data *data)
{
int i;
mutex_lock(&data->lock);
if (time_before(jiffies, data->last_updated + REFRESH_INTERVAL) &&
data->valid)
goto out;
update_aem_energy(data);
aem_read_sensor(data, AEM_EXHAUST_ELEMENT, 0, &data->temp[0], 1);
aem_read_sensor(data, AEM_EXHAUST_ELEMENT, 1, &data->temp[1], 1);
for (i = POWER_CAP; i <= POWER_AUX; i++)
aem_read_sensor(data, AEM_POWER_CAP_ELEMENT, i,
&data->pcap[i], 2);
out:
mutex_unlock(&data->lock);
}
/* Delete an AEM instance */
static void aem_delete(struct aem_data *data)
{
list_del(&data->list);
aem_remove_sensors(data);
hwmon_device_unregister(data->hwmon_dev);
ipmi_destroy_user(data->ipmi.user);
dev_set_drvdata(&data->pdev->dev, NULL);
platform_device_unregister(data->pdev);
aem_idr_put(data->id);
kfree(data);
}
/* Probe functions for AEM1 devices */
/* Retrieve version and module handle for an AEM1 instance */
static int aem_find_aem1_count(struct aem_ipmi_data *data)
{
int res;
struct aem_find_firmware_req ff_req;
struct aem_find_firmware_resp ff_resp;
ff_req.id = system_x_id;
ff_req.index = 0;
ff_req.module_type_id = cpu_to_be16(AEM_MODULE_TYPE_ID);
data->tx_message.cmd = AEM_FIND_FW_CMD;
data->tx_message.data = (char *)&ff_req;
data->tx_message.data_len = sizeof(ff_req);
data->rx_msg_data = &ff_resp;
data->rx_msg_len = sizeof(ff_resp);
aem_send_message(data);
res = wait_for_completion_timeout(&data->read_complete, IPMI_TIMEOUT);
if (!res)
return -ETIMEDOUT;
if (data->rx_result || data->rx_msg_len != sizeof(ff_resp) ||
memcmp(&ff_resp.id, &system_x_id, sizeof(system_x_id)))
return -ENOENT;
return ff_resp.num_instances;
}
/* Find and initialize one AEM1 instance */
static int aem_init_aem1_inst(struct aem_ipmi_data *probe, u8 module_handle)
{
struct aem_data *data;
int i;
int res = -ENOMEM;
data = kzalloc(sizeof(*data), GFP_KERNEL);
if (!data)
return res;
mutex_init(&data->lock);
/* Copy instance data */
data->ver_major = 1;
data->ver_minor = 0;
data->module_handle = module_handle;
for (i = 0; i < AEM1_NUM_ENERGY_REGS; i++)
data->power_period[i] = AEM_DEFAULT_POWER_INTERVAL;
/* Create sub-device for this fw instance */
if (aem_idr_get(&data->id))
goto id_err;
data->pdev = platform_device_alloc(DRVNAME, data->id);
if (!data->pdev)
goto dev_err;
data->pdev->dev.driver = &aem_driver.driver;
res = platform_device_add(data->pdev);
if (res)
goto ipmi_err;
dev_set_drvdata(&data->pdev->dev, data);
/* Set up IPMI interface */
if (aem_init_ipmi_data(&data->ipmi, probe->interface,
probe->bmc_device))
goto ipmi_err;
/* Register with hwmon */
data->hwmon_dev = hwmon_device_register(&data->pdev->dev);
if (IS_ERR(data->hwmon_dev)) {
dev_err(&data->pdev->dev, "Unable to register hwmon "
"device for IPMI interface %d\n",
probe->interface);
goto hwmon_reg_err;
}
data->update = update_aem1_sensors;
/* Find sensors */
if (aem1_find_sensors(data))
goto sensor_err;
/* Add to our list of AEM devices */
list_add_tail(&data->list, &driver_data.aem_devices);
dev_info(data->ipmi.bmc_device, "Found AEM v%d.%d at 0x%X\n",
data->ver_major, data->ver_minor,
data->module_handle);
return 0;
sensor_err:
hwmon_device_unregister(data->hwmon_dev);
hwmon_reg_err:
ipmi_destroy_user(data->ipmi.user);
ipmi_err:
dev_set_drvdata(&data->pdev->dev, NULL);
platform_device_unregister(data->pdev);
dev_err:
aem_idr_put(data->id);
id_err:
kfree(data);
return res;
}
/* Find and initialize all AEM1 instances */
static int aem_init_aem1(struct aem_ipmi_data *probe)
{
int num, i, err;
num = aem_find_aem1_count(probe);
for (i = 0; i < num; i++) {
err = aem_init_aem1_inst(probe, i);
if (err) {
dev_err(probe->bmc_device,
"Error %d initializing AEM1 0x%X\n",
err, i);
return err;
}
}
return 0;
}
/* Probe functions for AEM2 devices */
/* Retrieve version and module handle for an AEM2 instance */
static int aem_find_aem2(struct aem_ipmi_data *data,
struct aem_find_instance_resp *fi_resp,
int instance_num)
{
int res;
struct aem_find_instance_req fi_req;
fi_req.id = system_x_id;
fi_req.instance_number = instance_num;
fi_req.module_type_id = cpu_to_be16(AEM_MODULE_TYPE_ID);
data->tx_message.cmd = AEM_FW_INSTANCE_CMD;
data->tx_message.data = (char *)&fi_req;
data->tx_message.data_len = sizeof(fi_req);
data->rx_msg_data = fi_resp;
data->rx_msg_len = sizeof(*fi_resp);
aem_send_message(data);
res = wait_for_completion_timeout(&data->read_complete, IPMI_TIMEOUT);
if (!res)
return -ETIMEDOUT;
if (data->rx_result || data->rx_msg_len != sizeof(*fi_resp) ||
memcmp(&fi_resp->id, &system_x_id, sizeof(system_x_id)) ||
fi_resp->num_instances <= instance_num)
return -ENOENT;
return 0;
}
/* Find and initialize one AEM2 instance */
static int aem_init_aem2_inst(struct aem_ipmi_data *probe,
struct aem_find_instance_resp *fi_resp)
{
struct aem_data *data;
int i;
int res = -ENOMEM;
data = kzalloc(sizeof(*data), GFP_KERNEL);
if (!data)
return res;
mutex_init(&data->lock);
/* Copy instance data */
data->ver_major = fi_resp->major;
data->ver_minor = fi_resp->minor;
data->module_handle = fi_resp->module_handle;
for (i = 0; i < AEM2_NUM_ENERGY_REGS; i++)
data->power_period[i] = AEM_DEFAULT_POWER_INTERVAL;
/* Create sub-device for this fw instance */
if (aem_idr_get(&data->id))
goto id_err;
data->pdev = platform_device_alloc(DRVNAME, data->id);
if (!data->pdev)
goto dev_err;
data->pdev->dev.driver = &aem_driver.driver;
res = platform_device_add(data->pdev);
if (res)
goto ipmi_err;
dev_set_drvdata(&data->pdev->dev, data);
/* Set up IPMI interface */
if (aem_init_ipmi_data(&data->ipmi, probe->interface,
probe->bmc_device))
goto ipmi_err;
/* Register with hwmon */
data->hwmon_dev = hwmon_device_register(&data->pdev->dev);
if (IS_ERR(data->hwmon_dev)) {
dev_err(&data->pdev->dev, "Unable to register hwmon "
"device for IPMI interface %d\n",
probe->interface);
goto hwmon_reg_err;
}
data->update = update_aem2_sensors;
/* Find sensors */
if (aem2_find_sensors(data))
goto sensor_err;
/* Add to our list of AEM devices */
list_add_tail(&data->list, &driver_data.aem_devices);
dev_info(data->ipmi.bmc_device, "Found AEM v%d.%d at 0x%X\n",
data->ver_major, data->ver_minor,
data->module_handle);
return 0;
sensor_err:
hwmon_device_unregister(data->hwmon_dev);
hwmon_reg_err:
ipmi_destroy_user(data->ipmi.user);
ipmi_err:
dev_set_drvdata(&data->pdev->dev, NULL);
platform_device_unregister(data->pdev);
dev_err:
aem_idr_put(data->id);
id_err:
kfree(data);
return res;
}
/* Find and initialize all AEM2 instances */
static int aem_init_aem2(struct aem_ipmi_data *probe)
{
struct aem_find_instance_resp fi_resp;
int err;
int i = 0;
while (!aem_find_aem2(probe, &fi_resp, i)) {
if (fi_resp.major != 2) {
dev_err(probe->bmc_device, "Unknown AEM v%d; please "
"report this to the maintainer.\n",
fi_resp.major);
i++;
continue;
}
err = aem_init_aem2_inst(probe, &fi_resp);
if (err) {
dev_err(probe->bmc_device,
"Error %d initializing AEM2 0x%X\n",
err, fi_resp.module_handle);
return err;
}
i++;
}
return 0;
}
/* Probe a BMC for AEM firmware instances */
static void aem_register_bmc(int iface, struct device *dev)
{
struct aem_ipmi_data probe;
if (aem_init_ipmi_data(&probe, iface, dev))
return;
/* Ignore probe errors; they won't cause problems */
aem_init_aem1(&probe);
aem_init_aem2(&probe);
ipmi_destroy_user(probe.user);
}
/* Handle BMC deletion */
static void aem_bmc_gone(int iface)
{
struct aem_data *p1, *next1;
list_for_each_entry_safe(p1, next1, &driver_data.aem_devices, list)
if (p1->ipmi.interface == iface)
aem_delete(p1);
}
/* sysfs support functions */
/* AEM device name */
static ssize_t show_name(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct aem_data *data = dev_get_drvdata(dev);
return sprintf(buf, "%s%d\n", DRVNAME, data->ver_major);
}
static SENSOR_DEVICE_ATTR(name, S_IRUGO, show_name, NULL, 0);
/* AEM device version */
static ssize_t show_version(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
struct aem_data *data = dev_get_drvdata(dev);
return sprintf(buf, "%d.%d\n", data->ver_major, data->ver_minor);
}
static SENSOR_DEVICE_ATTR(version, S_IRUGO, show_version, NULL, 0);
/* Display power use */
static ssize_t aem_show_power(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct aem_data *data = dev_get_drvdata(dev);
u64 before, after, delta, time;
signed long leftover;
struct timespec b, a;
mutex_lock(&data->lock);
update_aem_energy_one(data, attr->index);
getnstimeofday(&b);
before = data->energy[attr->index];
leftover = schedule_timeout_interruptible(
msecs_to_jiffies(data->power_period[attr->index])
);
if (leftover) {
mutex_unlock(&data->lock);
return 0;
}
update_aem_energy_one(data, attr->index);
getnstimeofday(&a);
after = data->energy[attr->index];
mutex_unlock(&data->lock);
time = timespec_to_ns(&a) - timespec_to_ns(&b);
delta = (after - before) * UJ_PER_MJ;
return sprintf(buf, "%llu\n",
(unsigned long long)div64_u64(delta * NSEC_PER_SEC, time));
}
/* Display energy use */
static ssize_t aem_show_energy(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct aem_data *a = dev_get_drvdata(dev);
mutex_lock(&a->lock);
update_aem_energy_one(a, attr->index);
mutex_unlock(&a->lock);
return sprintf(buf, "%llu\n",
(unsigned long long)a->energy[attr->index] * 1000);
}
/* Display power interval registers */
static ssize_t aem_show_power_period(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct aem_data *a = dev_get_drvdata(dev);
a->update(a);
return sprintf(buf, "%lu\n", a->power_period[attr->index]);
}
/* Set power interval registers */
static ssize_t aem_set_power_period(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct aem_data *a = dev_get_drvdata(dev);
unsigned long temp;
int res;
res = strict_strtoul(buf, 10, &temp);
if (res)
return res;
if (temp < AEM_MIN_POWER_INTERVAL)
return -EINVAL;
mutex_lock(&a->lock);
a->power_period[attr->index] = temp;
mutex_unlock(&a->lock);
return count;
}
/* Discover sensors on an AEM device */
static int aem_register_sensors(struct aem_data *data,
struct aem_ro_sensor_template *ro,
struct aem_rw_sensor_template *rw)
{
struct device *dev = &data->pdev->dev;
struct sensor_device_attribute *sensors = data->sensors;
int err;
/* Set up read-only sensors */
while (ro->label) {
sensors->dev_attr.attr.name = ro->label;
sensors->dev_attr.attr.mode = S_IRUGO;
sensors->dev_attr.show = ro->show;
sensors->index = ro->index;
err = device_create_file(dev, &sensors->dev_attr);
if (err) {
sensors->dev_attr.attr.name = NULL;
goto error;
}
sensors++;
ro++;
}
/* Set up read-write sensors */
while (rw->label) {
sensors->dev_attr.attr.name = rw->label;
sensors->dev_attr.attr.mode = S_IRUGO | S_IWUSR;
sensors->dev_attr.show = rw->show;
sensors->dev_attr.store = rw->set;
sensors->index = rw->index;
err = device_create_file(dev, &sensors->dev_attr);
if (err) {
sensors->dev_attr.attr.name = NULL;
goto error;
}
sensors++;
rw++;
}
err = device_create_file(dev, &sensor_dev_attr_name.dev_attr);
if (err)
goto error;
err = device_create_file(dev, &sensor_dev_attr_version.dev_attr);
return err;
error:
aem_remove_sensors(data);
return err;
}
/* sysfs support functions for AEM2 sensors */
/* Display temperature use */
static ssize_t aem2_show_temp(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct aem_data *a = dev_get_drvdata(dev);
a->update(a);
return sprintf(buf, "%u\n", a->temp[attr->index] * 1000);
}
/* Display power-capping registers */
static ssize_t aem2_show_pcap_value(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct aem_data *a = dev_get_drvdata(dev);
a->update(a);
return sprintf(buf, "%u\n", a->pcap[attr->index] * 100000);
}
/* Remove sensors attached to an AEM device */
static void aem_remove_sensors(struct aem_data *data)
{
int i;
for (i = 0; i < AEM_NUM_SENSORS; i++) {
if (!data->sensors[i].dev_attr.attr.name)
continue;
device_remove_file(&data->pdev->dev,
&data->sensors[i].dev_attr);
}
device_remove_file(&data->pdev->dev,
&sensor_dev_attr_name.dev_attr);
device_remove_file(&data->pdev->dev,
&sensor_dev_attr_version.dev_attr);
}
/* Sensor probe functions */
/* Description of AEM1 sensors */
static struct aem_ro_sensor_template aem1_ro_sensors[] = {
{"energy1_input", aem_show_energy, 0},
{"power1_average", aem_show_power, 0},
{NULL, NULL, 0},
};
static struct aem_rw_sensor_template aem1_rw_sensors[] = {
{"power1_average_interval", aem_show_power_period, aem_set_power_period, 0},
{NULL, NULL, NULL, 0},
};
/* Description of AEM2 sensors */
static struct aem_ro_sensor_template aem2_ro_sensors[] = {
{"energy1_input", aem_show_energy, 0},
{"energy2_input", aem_show_energy, 1},
{"power1_average", aem_show_power, 0},
{"power2_average", aem_show_power, 1},
{"temp1_input", aem2_show_temp, 0},
{"temp2_input", aem2_show_temp, 1},
{"power4_average", aem2_show_pcap_value, POWER_CAP_MAX_HOTPLUG},
{"power5_average", aem2_show_pcap_value, POWER_CAP_MAX},
{"power6_average", aem2_show_pcap_value, POWER_CAP_MIN_WARNING},
{"power7_average", aem2_show_pcap_value, POWER_CAP_MIN},
{"power3_average", aem2_show_pcap_value, POWER_AUX},
{"power_cap", aem2_show_pcap_value, POWER_CAP},
{NULL, NULL, 0},
};
static struct aem_rw_sensor_template aem2_rw_sensors[] = {
{"power1_average_interval", aem_show_power_period, aem_set_power_period, 0},
{"power2_average_interval", aem_show_power_period, aem_set_power_period, 1},
{NULL, NULL, NULL, 0},
};
/* Set up AEM1 sensor attrs */
static int aem1_find_sensors(struct aem_data *data)
{
return aem_register_sensors(data, aem1_ro_sensors, aem1_rw_sensors);
}
/* Set up AEM2 sensor attrs */
static int aem2_find_sensors(struct aem_data *data)
{
return aem_register_sensors(data, aem2_ro_sensors, aem2_rw_sensors);
}
/* Module init/exit routines */
static int __init aem_init(void)
{
int res;
res = driver_register(&aem_driver.driver);
if (res) {
printk(KERN_ERR "Can't register aem driver\n");
return res;
}
res = ipmi_smi_watcher_register(&driver_data.bmc_events);
if (res)
goto ipmi_reg_err;
return 0;
ipmi_reg_err:
driver_unregister(&aem_driver.driver);
return res;
}
static void __exit aem_exit(void)
{
struct aem_data *p1, *next1;
ipmi_smi_watcher_unregister(&driver_data.bmc_events);
driver_unregister(&aem_driver.driver);
list_for_each_entry_safe(p1, next1, &driver_data.aem_devices, list)
aem_delete(p1);
}
MODULE_AUTHOR("Darrick J. Wong <djwong@us.ibm.com>");
MODULE_DESCRIPTION("IBM AEM power/temp/energy sensor driver");
MODULE_LICENSE("GPL");
module_init(aem_init);
module_exit(aem_exit);
MODULE_ALIAS("dmi:bvnIBM:*:pnIBMSystemx3350-*");
MODULE_ALIAS("dmi:bvnIBM:*:pnIBMSystemx3550-*");
MODULE_ALIAS("dmi:bvnIBM:*:pnIBMSystemx3650-*");
MODULE_ALIAS("dmi:bvnIBM:*:pnIBMSystemx3655-*");
MODULE_ALIAS("dmi:bvnIBM:*:pnIBMSystemx3755-*");
MODULE_ALIAS("dmi:bvnIBM:*:pnIBM3850M2/x3950M2-*");
MODULE_ALIAS("dmi:bvnIBM:*:pnIBMBladeHC10-*");
| gpl-2.0 |
WaRP7/linux-fslc | fs/afs/proc.c | 1744 | 15420 | /* /proc interface for AFS
*
* Copyright (C) 2002 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/sched.h>
#include <asm/uaccess.h>
#include "internal.h"
static struct proc_dir_entry *proc_afs;
static int afs_proc_cells_open(struct inode *inode, struct file *file);
static void *afs_proc_cells_start(struct seq_file *p, loff_t *pos);
static void *afs_proc_cells_next(struct seq_file *p, void *v, loff_t *pos);
static void afs_proc_cells_stop(struct seq_file *p, void *v);
static int afs_proc_cells_show(struct seq_file *m, void *v);
static ssize_t afs_proc_cells_write(struct file *file, const char __user *buf,
size_t size, loff_t *_pos);
static const struct seq_operations afs_proc_cells_ops = {
.start = afs_proc_cells_start,
.next = afs_proc_cells_next,
.stop = afs_proc_cells_stop,
.show = afs_proc_cells_show,
};
static const struct file_operations afs_proc_cells_fops = {
.open = afs_proc_cells_open,
.read = seq_read,
.write = afs_proc_cells_write,
.llseek = seq_lseek,
.release = seq_release,
};
static ssize_t afs_proc_rootcell_read(struct file *file, char __user *buf,
size_t size, loff_t *_pos);
static ssize_t afs_proc_rootcell_write(struct file *file,
const char __user *buf,
size_t size, loff_t *_pos);
static const struct file_operations afs_proc_rootcell_fops = {
.read = afs_proc_rootcell_read,
.write = afs_proc_rootcell_write,
.llseek = no_llseek,
};
static int afs_proc_cell_volumes_open(struct inode *inode, struct file *file);
static void *afs_proc_cell_volumes_start(struct seq_file *p, loff_t *pos);
static void *afs_proc_cell_volumes_next(struct seq_file *p, void *v,
loff_t *pos);
static void afs_proc_cell_volumes_stop(struct seq_file *p, void *v);
static int afs_proc_cell_volumes_show(struct seq_file *m, void *v);
static const struct seq_operations afs_proc_cell_volumes_ops = {
.start = afs_proc_cell_volumes_start,
.next = afs_proc_cell_volumes_next,
.stop = afs_proc_cell_volumes_stop,
.show = afs_proc_cell_volumes_show,
};
static const struct file_operations afs_proc_cell_volumes_fops = {
.open = afs_proc_cell_volumes_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
static int afs_proc_cell_vlservers_open(struct inode *inode,
struct file *file);
static void *afs_proc_cell_vlservers_start(struct seq_file *p, loff_t *pos);
static void *afs_proc_cell_vlservers_next(struct seq_file *p, void *v,
loff_t *pos);
static void afs_proc_cell_vlservers_stop(struct seq_file *p, void *v);
static int afs_proc_cell_vlservers_show(struct seq_file *m, void *v);
static const struct seq_operations afs_proc_cell_vlservers_ops = {
.start = afs_proc_cell_vlservers_start,
.next = afs_proc_cell_vlservers_next,
.stop = afs_proc_cell_vlservers_stop,
.show = afs_proc_cell_vlservers_show,
};
static const struct file_operations afs_proc_cell_vlservers_fops = {
.open = afs_proc_cell_vlservers_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
static int afs_proc_cell_servers_open(struct inode *inode, struct file *file);
static void *afs_proc_cell_servers_start(struct seq_file *p, loff_t *pos);
static void *afs_proc_cell_servers_next(struct seq_file *p, void *v,
loff_t *pos);
static void afs_proc_cell_servers_stop(struct seq_file *p, void *v);
static int afs_proc_cell_servers_show(struct seq_file *m, void *v);
static const struct seq_operations afs_proc_cell_servers_ops = {
.start = afs_proc_cell_servers_start,
.next = afs_proc_cell_servers_next,
.stop = afs_proc_cell_servers_stop,
.show = afs_proc_cell_servers_show,
};
static const struct file_operations afs_proc_cell_servers_fops = {
.open = afs_proc_cell_servers_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
/*
* initialise the /proc/fs/afs/ directory
*/
int afs_proc_init(void)
{
_enter("");
proc_afs = proc_mkdir("fs/afs", NULL);
if (!proc_afs)
goto error_dir;
if (!proc_create("cells", 0644, proc_afs, &afs_proc_cells_fops) ||
!proc_create("rootcell", 0644, proc_afs, &afs_proc_rootcell_fops))
goto error_tree;
_leave(" = 0");
return 0;
error_tree:
remove_proc_subtree("fs/afs", NULL);
error_dir:
_leave(" = -ENOMEM");
return -ENOMEM;
}
/*
* clean up the /proc/fs/afs/ directory
*/
void afs_proc_cleanup(void)
{
remove_proc_subtree("fs/afs", NULL);
}
/*
* open "/proc/fs/afs/cells" which provides a summary of extant cells
*/
static int afs_proc_cells_open(struct inode *inode, struct file *file)
{
struct seq_file *m;
int ret;
ret = seq_open(file, &afs_proc_cells_ops);
if (ret < 0)
return ret;
m = file->private_data;
m->private = PDE_DATA(inode);
return 0;
}
/*
* set up the iterator to start reading from the cells list and return the
* first item
*/
static void *afs_proc_cells_start(struct seq_file *m, loff_t *_pos)
{
/* lock the list against modification */
down_read(&afs_proc_cells_sem);
return seq_list_start_head(&afs_proc_cells, *_pos);
}
/*
* move to next cell in cells list
*/
static void *afs_proc_cells_next(struct seq_file *p, void *v, loff_t *pos)
{
return seq_list_next(v, &afs_proc_cells, pos);
}
/*
* clean up after reading from the cells list
*/
static void afs_proc_cells_stop(struct seq_file *p, void *v)
{
up_read(&afs_proc_cells_sem);
}
/*
* display a header line followed by a load of cell lines
*/
static int afs_proc_cells_show(struct seq_file *m, void *v)
{
struct afs_cell *cell = list_entry(v, struct afs_cell, proc_link);
if (v == &afs_proc_cells) {
/* display header on line 1 */
seq_puts(m, "USE NAME\n");
return 0;
}
/* display one cell per line on subsequent lines */
seq_printf(m, "%3d %s\n",
atomic_read(&cell->usage), cell->name);
return 0;
}
/*
* handle writes to /proc/fs/afs/cells
* - to add cells: echo "add <cellname> <IP>[:<IP>][:<IP>]"
*/
static ssize_t afs_proc_cells_write(struct file *file, const char __user *buf,
size_t size, loff_t *_pos)
{
char *kbuf, *name, *args;
int ret;
/* start by dragging the command into memory */
if (size <= 1 || size >= PAGE_SIZE)
return -EINVAL;
kbuf = kmalloc(size + 1, GFP_KERNEL);
if (!kbuf)
return -ENOMEM;
ret = -EFAULT;
if (copy_from_user(kbuf, buf, size) != 0)
goto done;
kbuf[size] = 0;
/* trim to first NL */
name = memchr(kbuf, '\n', size);
if (name)
*name = 0;
/* split into command, name and argslist */
name = strchr(kbuf, ' ');
if (!name)
goto inval;
do {
*name++ = 0;
} while(*name == ' ');
if (!*name)
goto inval;
args = strchr(name, ' ');
if (!args)
goto inval;
do {
*args++ = 0;
} while(*args == ' ');
if (!*args)
goto inval;
/* determine command to perform */
_debug("cmd=%s name=%s args=%s", kbuf, name, args);
if (strcmp(kbuf, "add") == 0) {
struct afs_cell *cell;
cell = afs_cell_create(name, strlen(name), args, false);
if (IS_ERR(cell)) {
ret = PTR_ERR(cell);
goto done;
}
afs_put_cell(cell);
printk("kAFS: Added new cell '%s'\n", name);
} else {
goto inval;
}
ret = size;
done:
kfree(kbuf);
_leave(" = %d", ret);
return ret;
inval:
ret = -EINVAL;
printk("kAFS: Invalid Command on /proc/fs/afs/cells file\n");
goto done;
}
static ssize_t afs_proc_rootcell_read(struct file *file, char __user *buf,
size_t size, loff_t *_pos)
{
return 0;
}
/*
* handle writes to /proc/fs/afs/rootcell
* - to initialize rootcell: echo "cell.name:192.168.231.14"
*/
static ssize_t afs_proc_rootcell_write(struct file *file,
const char __user *buf,
size_t size, loff_t *_pos)
{
char *kbuf, *s;
int ret;
/* start by dragging the command into memory */
if (size <= 1 || size >= PAGE_SIZE)
return -EINVAL;
ret = -ENOMEM;
kbuf = kmalloc(size + 1, GFP_KERNEL);
if (!kbuf)
goto nomem;
ret = -EFAULT;
if (copy_from_user(kbuf, buf, size) != 0)
goto infault;
kbuf[size] = 0;
/* trim to first NL */
s = memchr(kbuf, '\n', size);
if (s)
*s = 0;
/* determine command to perform */
_debug("rootcell=%s", kbuf);
ret = afs_cell_init(kbuf);
if (ret >= 0)
ret = size; /* consume everything, always */
infault:
kfree(kbuf);
nomem:
_leave(" = %d", ret);
return ret;
}
/*
* initialise /proc/fs/afs/<cell>/
*/
int afs_proc_cell_setup(struct afs_cell *cell)
{
struct proc_dir_entry *dir;
_enter("%p{%s}", cell, cell->name);
dir = proc_mkdir(cell->name, proc_afs);
if (!dir)
goto error_dir;
if (!proc_create_data("servers", 0, dir,
&afs_proc_cell_servers_fops, cell) ||
!proc_create_data("vlservers", 0, dir,
&afs_proc_cell_vlservers_fops, cell) ||
!proc_create_data("volumes", 0, dir,
&afs_proc_cell_volumes_fops, cell))
goto error_tree;
_leave(" = 0");
return 0;
error_tree:
remove_proc_subtree(cell->name, proc_afs);
error_dir:
_leave(" = -ENOMEM");
return -ENOMEM;
}
/*
* remove /proc/fs/afs/<cell>/
*/
void afs_proc_cell_remove(struct afs_cell *cell)
{
_enter("");
remove_proc_subtree(cell->name, proc_afs);
_leave("");
}
/*
* open "/proc/fs/afs/<cell>/volumes" which provides a summary of extant cells
*/
static int afs_proc_cell_volumes_open(struct inode *inode, struct file *file)
{
struct afs_cell *cell;
struct seq_file *m;
int ret;
cell = PDE_DATA(inode);
if (!cell)
return -ENOENT;
ret = seq_open(file, &afs_proc_cell_volumes_ops);
if (ret < 0)
return ret;
m = file->private_data;
m->private = cell;
return 0;
}
/*
* set up the iterator to start reading from the cells list and return the
* first item
*/
static void *afs_proc_cell_volumes_start(struct seq_file *m, loff_t *_pos)
{
struct afs_cell *cell = m->private;
_enter("cell=%p pos=%Ld", cell, *_pos);
/* lock the list against modification */
down_read(&cell->vl_sem);
return seq_list_start_head(&cell->vl_list, *_pos);
}
/*
* move to next cell in cells list
*/
static void *afs_proc_cell_volumes_next(struct seq_file *p, void *v,
loff_t *_pos)
{
struct afs_cell *cell = p->private;
_enter("cell=%p pos=%Ld", cell, *_pos);
return seq_list_next(v, &cell->vl_list, _pos);
}
/*
* clean up after reading from the cells list
*/
static void afs_proc_cell_volumes_stop(struct seq_file *p, void *v)
{
struct afs_cell *cell = p->private;
up_read(&cell->vl_sem);
}
static const char afs_vlocation_states[][4] = {
[AFS_VL_NEW] = "New",
[AFS_VL_CREATING] = "Crt",
[AFS_VL_VALID] = "Val",
[AFS_VL_NO_VOLUME] = "NoV",
[AFS_VL_UPDATING] = "Upd",
[AFS_VL_VOLUME_DELETED] = "Del",
[AFS_VL_UNCERTAIN] = "Unc",
};
/*
* display a header line followed by a load of volume lines
*/
static int afs_proc_cell_volumes_show(struct seq_file *m, void *v)
{
struct afs_cell *cell = m->private;
struct afs_vlocation *vlocation =
list_entry(v, struct afs_vlocation, link);
/* display header on line 1 */
if (v == &cell->vl_list) {
seq_puts(m, "USE STT VLID[0] VLID[1] VLID[2] NAME\n");
return 0;
}
/* display one cell per line on subsequent lines */
seq_printf(m, "%3d %s %08x %08x %08x %s\n",
atomic_read(&vlocation->usage),
afs_vlocation_states[vlocation->state],
vlocation->vldb.vid[0],
vlocation->vldb.vid[1],
vlocation->vldb.vid[2],
vlocation->vldb.name);
return 0;
}
/*
* open "/proc/fs/afs/<cell>/vlservers" which provides a list of volume
* location server
*/
static int afs_proc_cell_vlservers_open(struct inode *inode, struct file *file)
{
struct afs_cell *cell;
struct seq_file *m;
int ret;
cell = PDE_DATA(inode);
if (!cell)
return -ENOENT;
ret = seq_open(file, &afs_proc_cell_vlservers_ops);
if (ret<0)
return ret;
m = file->private_data;
m->private = cell;
return 0;
}
/*
* set up the iterator to start reading from the cells list and return the
* first item
*/
static void *afs_proc_cell_vlservers_start(struct seq_file *m, loff_t *_pos)
{
struct afs_cell *cell = m->private;
loff_t pos = *_pos;
_enter("cell=%p pos=%Ld", cell, *_pos);
/* lock the list against modification */
down_read(&cell->vl_sem);
/* allow for the header line */
if (!pos)
return (void *) 1;
pos--;
if (pos >= cell->vl_naddrs)
return NULL;
return &cell->vl_addrs[pos];
}
/*
* move to next cell in cells list
*/
static void *afs_proc_cell_vlservers_next(struct seq_file *p, void *v,
loff_t *_pos)
{
struct afs_cell *cell = p->private;
loff_t pos;
_enter("cell=%p{nad=%u} pos=%Ld", cell, cell->vl_naddrs, *_pos);
pos = *_pos;
(*_pos)++;
if (pos >= cell->vl_naddrs)
return NULL;
return &cell->vl_addrs[pos];
}
/*
* clean up after reading from the cells list
*/
static void afs_proc_cell_vlservers_stop(struct seq_file *p, void *v)
{
struct afs_cell *cell = p->private;
up_read(&cell->vl_sem);
}
/*
* display a header line followed by a load of volume lines
*/
static int afs_proc_cell_vlservers_show(struct seq_file *m, void *v)
{
struct in_addr *addr = v;
/* display header on line 1 */
if (v == (struct in_addr *) 1) {
seq_puts(m, "ADDRESS\n");
return 0;
}
/* display one cell per line on subsequent lines */
seq_printf(m, "%pI4\n", &addr->s_addr);
return 0;
}
/*
* open "/proc/fs/afs/<cell>/servers" which provides a summary of active
* servers
*/
static int afs_proc_cell_servers_open(struct inode *inode, struct file *file)
{
struct afs_cell *cell;
struct seq_file *m;
int ret;
cell = PDE_DATA(inode);
if (!cell)
return -ENOENT;
ret = seq_open(file, &afs_proc_cell_servers_ops);
if (ret < 0)
return ret;
m = file->private_data;
m->private = cell;
return 0;
}
/*
* set up the iterator to start reading from the cells list and return the
* first item
*/
static void *afs_proc_cell_servers_start(struct seq_file *m, loff_t *_pos)
__acquires(m->private->servers_lock)
{
struct afs_cell *cell = m->private;
_enter("cell=%p pos=%Ld", cell, *_pos);
/* lock the list against modification */
read_lock(&cell->servers_lock);
return seq_list_start_head(&cell->servers, *_pos);
}
/*
* move to next cell in cells list
*/
static void *afs_proc_cell_servers_next(struct seq_file *p, void *v,
loff_t *_pos)
{
struct afs_cell *cell = p->private;
_enter("cell=%p pos=%Ld", cell, *_pos);
return seq_list_next(v, &cell->servers, _pos);
}
/*
* clean up after reading from the cells list
*/
static void afs_proc_cell_servers_stop(struct seq_file *p, void *v)
__releases(p->private->servers_lock)
{
struct afs_cell *cell = p->private;
read_unlock(&cell->servers_lock);
}
/*
* display a header line followed by a load of volume lines
*/
static int afs_proc_cell_servers_show(struct seq_file *m, void *v)
{
struct afs_cell *cell = m->private;
struct afs_server *server = list_entry(v, struct afs_server, link);
char ipaddr[20];
/* display header on line 1 */
if (v == &cell->servers) {
seq_puts(m, "USE ADDR STATE\n");
return 0;
}
/* display one cell per line on subsequent lines */
sprintf(ipaddr, "%pI4", &server->addr);
seq_printf(m, "%3d %-15.15s %5d\n",
atomic_read(&server->usage), ipaddr, server->fs_state);
return 0;
}
| gpl-2.0 |
peyo-hd/kernel_odrc | arch/arm/mach-omap2/clock36xx.c | 2256 | 1887 | /*
* OMAP36xx-specific clkops
*
* Copyright (C) 2010 Texas Instruments, Inc.
* Copyright (C) 2010 Nokia Corporation
*
* Mike Turquette
* Vijaykumar GN
* Paul Walmsley
*
* Parts of this code are based on code written by
* Richard Woodruff, Tony Lindgren, Tuukka Tikkanen, Karthik Dasu,
* Russell King
*
* 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.
*/
#undef DEBUG
#include <linux/kernel.h>
#include <linux/clk.h>
#include <linux/clk-provider.h>
#include <linux/io.h>
#include "clock.h"
#include "clock36xx.h"
#define to_clk_divider(_hw) container_of(_hw, struct clk_divider, hw)
/**
* omap36xx_pwrdn_clk_enable_with_hsdiv_restore - enable clocks suffering
* from HSDivider PWRDN problem Implements Errata ID: i556.
* @clk: DPLL output struct clk
*
* 3630 only: dpll3_m3_ck, dpll4_m2_ck, dpll4_m3_ck, dpll4_m4_ck,
* dpll4_m5_ck & dpll4_m6_ck dividers gets loaded with reset
* valueafter their respective PWRDN bits are set. Any dummy write
* (Any other value different from the Read value) to the
* corresponding CM_CLKSEL register will refresh the dividers.
*/
int omap36xx_pwrdn_clk_enable_with_hsdiv_restore(struct clk_hw *clk)
{
struct clk_divider *parent;
struct clk_hw *parent_hw;
u32 dummy_v, orig_v;
int ret;
/* Clear PWRDN bit of HSDIVIDER */
ret = omap2_dflt_clk_enable(clk);
parent_hw = __clk_get_hw(__clk_get_parent(clk->clk));
parent = to_clk_divider(parent_hw);
/* Restore the dividers */
if (!ret) {
orig_v = __raw_readl(parent->reg);
dummy_v = orig_v;
/* Write any other value different from the Read value */
dummy_v ^= (1 << parent->shift);
__raw_writel(dummy_v, parent->reg);
/* Write the original divider */
__raw_writel(orig_v, parent->reg);
}
return ret;
}
| gpl-2.0 |
hexianren/linux-3.7-Panda | drivers/hwmon/lm95241.c | 2768 | 12620 | /*
* Copyright (C) 2008, 2010 Davide Rizzo <elpa.rizzo@gmail.com>
*
* The LM95241 is a sensor chip made by National Semiconductors.
* It reports up to three temperatures (its own plus up to two external ones).
* Complete datasheet can be obtained from National's website at:
* http://www.national.com/ds.cgi/LM/LM95241.pdf
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/i2c.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/sysfs.h>
#define DEVNAME "lm95241"
static const unsigned short normal_i2c[] = {
0x19, 0x2a, 0x2b, I2C_CLIENT_END };
/* LM95241 registers */
#define LM95241_REG_R_MAN_ID 0xFE
#define LM95241_REG_R_CHIP_ID 0xFF
#define LM95241_REG_R_STATUS 0x02
#define LM95241_REG_RW_CONFIG 0x03
#define LM95241_REG_RW_REM_FILTER 0x06
#define LM95241_REG_RW_TRUTHERM 0x07
#define LM95241_REG_W_ONE_SHOT 0x0F
#define LM95241_REG_R_LOCAL_TEMPH 0x10
#define LM95241_REG_R_REMOTE1_TEMPH 0x11
#define LM95241_REG_R_REMOTE2_TEMPH 0x12
#define LM95241_REG_R_LOCAL_TEMPL 0x20
#define LM95241_REG_R_REMOTE1_TEMPL 0x21
#define LM95241_REG_R_REMOTE2_TEMPL 0x22
#define LM95241_REG_RW_REMOTE_MODEL 0x30
/* LM95241 specific bitfields */
#define CFG_STOP 0x40
#define CFG_CR0076 0x00
#define CFG_CR0182 0x10
#define CFG_CR1000 0x20
#define CFG_CR2700 0x30
#define R1MS_SHIFT 0
#define R2MS_SHIFT 2
#define R1MS_MASK (0x01 << (R1MS_SHIFT))
#define R2MS_MASK (0x01 << (R2MS_SHIFT))
#define R1DF_SHIFT 1
#define R2DF_SHIFT 2
#define R1DF_MASK (0x01 << (R1DF_SHIFT))
#define R2DF_MASK (0x01 << (R2DF_SHIFT))
#define R1FE_MASK 0x01
#define R2FE_MASK 0x05
#define TT1_SHIFT 0
#define TT2_SHIFT 4
#define TT_OFF 0
#define TT_ON 1
#define TT_MASK 7
#define NATSEMI_MAN_ID 0x01
#define LM95231_CHIP_ID 0xA1
#define LM95241_CHIP_ID 0xA4
static const u8 lm95241_reg_address[] = {
LM95241_REG_R_LOCAL_TEMPH,
LM95241_REG_R_LOCAL_TEMPL,
LM95241_REG_R_REMOTE1_TEMPH,
LM95241_REG_R_REMOTE1_TEMPL,
LM95241_REG_R_REMOTE2_TEMPH,
LM95241_REG_R_REMOTE2_TEMPL
};
/* Client data (each client gets its own) */
struct lm95241_data {
struct device *hwmon_dev;
struct mutex update_lock;
unsigned long last_updated, interval; /* in jiffies */
char valid; /* zero until following fields are valid */
/* registers values */
u8 temp[ARRAY_SIZE(lm95241_reg_address)];
u8 config, model, trutherm;
};
/* Conversions */
static int temp_from_reg_signed(u8 val_h, u8 val_l)
{
s16 val_hl = (val_h << 8) | val_l;
return val_hl * 1000 / 256;
}
static int temp_from_reg_unsigned(u8 val_h, u8 val_l)
{
u16 val_hl = (val_h << 8) | val_l;
return val_hl * 1000 / 256;
}
static struct lm95241_data *lm95241_update_device(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm95241_data *data = i2c_get_clientdata(client);
mutex_lock(&data->update_lock);
if (time_after(jiffies, data->last_updated + data->interval) ||
!data->valid) {
int i;
dev_dbg(&client->dev, "Updating lm95241 data.\n");
for (i = 0; i < ARRAY_SIZE(lm95241_reg_address); i++)
data->temp[i]
= i2c_smbus_read_byte_data(client,
lm95241_reg_address[i]);
data->last_updated = jiffies;
data->valid = 1;
}
mutex_unlock(&data->update_lock);
return data;
}
/* Sysfs stuff */
static ssize_t show_input(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct lm95241_data *data = lm95241_update_device(dev);
int index = to_sensor_dev_attr(attr)->index;
return snprintf(buf, PAGE_SIZE - 1, "%d\n",
index == 0 || (data->config & (1 << (index / 2))) ?
temp_from_reg_signed(data->temp[index], data->temp[index + 1]) :
temp_from_reg_unsigned(data->temp[index],
data->temp[index + 1]));
}
static ssize_t show_type(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm95241_data *data = i2c_get_clientdata(client);
return snprintf(buf, PAGE_SIZE - 1,
data->model & to_sensor_dev_attr(attr)->index ? "1\n" : "2\n");
}
static ssize_t set_type(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm95241_data *data = i2c_get_clientdata(client);
unsigned long val;
int shift;
u8 mask = to_sensor_dev_attr(attr)->index;
if (kstrtoul(buf, 10, &val) < 0)
return -EINVAL;
if (val != 1 && val != 2)
return -EINVAL;
shift = mask == R1MS_MASK ? TT1_SHIFT : TT2_SHIFT;
mutex_lock(&data->update_lock);
data->trutherm &= ~(TT_MASK << shift);
if (val == 1) {
data->model |= mask;
data->trutherm |= (TT_ON << shift);
} else {
data->model &= ~mask;
data->trutherm |= (TT_OFF << shift);
}
data->valid = 0;
i2c_smbus_write_byte_data(client, LM95241_REG_RW_REMOTE_MODEL,
data->model);
i2c_smbus_write_byte_data(client, LM95241_REG_RW_TRUTHERM,
data->trutherm);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_min(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm95241_data *data = i2c_get_clientdata(client);
return snprintf(buf, PAGE_SIZE - 1,
data->config & to_sensor_dev_attr(attr)->index ?
"-127000\n" : "0\n");
}
static ssize_t set_min(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm95241_data *data = i2c_get_clientdata(client);
long val;
if (kstrtol(buf, 10, &val) < 0)
return -EINVAL;
if (val < -128000)
return -EINVAL;
mutex_lock(&data->update_lock);
if (val < 0)
data->config |= to_sensor_dev_attr(attr)->index;
else
data->config &= ~to_sensor_dev_attr(attr)->index;
data->valid = 0;
i2c_smbus_write_byte_data(client, LM95241_REG_RW_CONFIG, data->config);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_max(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm95241_data *data = i2c_get_clientdata(client);
return snprintf(buf, PAGE_SIZE - 1,
data->config & to_sensor_dev_attr(attr)->index ?
"127000\n" : "255000\n");
}
static ssize_t set_max(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm95241_data *data = i2c_get_clientdata(client);
long val;
if (kstrtol(buf, 10, &val) < 0)
return -EINVAL;
if (val >= 256000)
return -EINVAL;
mutex_lock(&data->update_lock);
if (val <= 127000)
data->config |= to_sensor_dev_attr(attr)->index;
else
data->config &= ~to_sensor_dev_attr(attr)->index;
data->valid = 0;
i2c_smbus_write_byte_data(client, LM95241_REG_RW_CONFIG, data->config);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_interval(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct lm95241_data *data = lm95241_update_device(dev);
return snprintf(buf, PAGE_SIZE - 1, "%lu\n", 1000 * data->interval
/ HZ);
}
static ssize_t set_interval(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm95241_data *data = i2c_get_clientdata(client);
unsigned long val;
if (kstrtoul(buf, 10, &val) < 0)
return -EINVAL;
data->interval = val * HZ / 1000;
return count;
}
static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, show_input, NULL, 0);
static SENSOR_DEVICE_ATTR(temp2_input, S_IRUGO, show_input, NULL, 2);
static SENSOR_DEVICE_ATTR(temp3_input, S_IRUGO, show_input, NULL, 4);
static SENSOR_DEVICE_ATTR(temp2_type, S_IWUSR | S_IRUGO, show_type, set_type,
R1MS_MASK);
static SENSOR_DEVICE_ATTR(temp3_type, S_IWUSR | S_IRUGO, show_type, set_type,
R2MS_MASK);
static SENSOR_DEVICE_ATTR(temp2_min, S_IWUSR | S_IRUGO, show_min, set_min,
R1DF_MASK);
static SENSOR_DEVICE_ATTR(temp3_min, S_IWUSR | S_IRUGO, show_min, set_min,
R2DF_MASK);
static SENSOR_DEVICE_ATTR(temp2_max, S_IWUSR | S_IRUGO, show_max, set_max,
R1DF_MASK);
static SENSOR_DEVICE_ATTR(temp3_max, S_IWUSR | S_IRUGO, show_max, set_max,
R2DF_MASK);
static DEVICE_ATTR(update_interval, S_IWUSR | S_IRUGO, show_interval,
set_interval);
static struct attribute *lm95241_attributes[] = {
&sensor_dev_attr_temp1_input.dev_attr.attr,
&sensor_dev_attr_temp2_input.dev_attr.attr,
&sensor_dev_attr_temp3_input.dev_attr.attr,
&sensor_dev_attr_temp2_type.dev_attr.attr,
&sensor_dev_attr_temp3_type.dev_attr.attr,
&sensor_dev_attr_temp2_min.dev_attr.attr,
&sensor_dev_attr_temp3_min.dev_attr.attr,
&sensor_dev_attr_temp2_max.dev_attr.attr,
&sensor_dev_attr_temp3_max.dev_attr.attr,
&dev_attr_update_interval.attr,
NULL
};
static const struct attribute_group lm95241_group = {
.attrs = lm95241_attributes,
};
/* Return 0 if detection is successful, -ENODEV otherwise */
static int lm95241_detect(struct i2c_client *new_client,
struct i2c_board_info *info)
{
struct i2c_adapter *adapter = new_client->adapter;
const char *name;
int mfg_id, chip_id;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -ENODEV;
mfg_id = i2c_smbus_read_byte_data(new_client, LM95241_REG_R_MAN_ID);
if (mfg_id != NATSEMI_MAN_ID)
return -ENODEV;
chip_id = i2c_smbus_read_byte_data(new_client, LM95241_REG_R_CHIP_ID);
switch (chip_id) {
case LM95231_CHIP_ID:
name = "lm95231";
break;
case LM95241_CHIP_ID:
name = "lm95241";
break;
default:
return -ENODEV;
}
/* Fill the i2c board info */
strlcpy(info->type, name, I2C_NAME_SIZE);
return 0;
}
static void lm95241_init_client(struct i2c_client *client)
{
struct lm95241_data *data = i2c_get_clientdata(client);
data->interval = HZ; /* 1 sec default */
data->valid = 0;
data->config = CFG_CR0076;
data->model = 0;
data->trutherm = (TT_OFF << TT1_SHIFT) | (TT_OFF << TT2_SHIFT);
i2c_smbus_write_byte_data(client, LM95241_REG_RW_CONFIG, data->config);
i2c_smbus_write_byte_data(client, LM95241_REG_RW_REM_FILTER,
R1FE_MASK | R2FE_MASK);
i2c_smbus_write_byte_data(client, LM95241_REG_RW_TRUTHERM,
data->trutherm);
i2c_smbus_write_byte_data(client, LM95241_REG_RW_REMOTE_MODEL,
data->model);
}
static int lm95241_probe(struct i2c_client *new_client,
const struct i2c_device_id *id)
{
struct lm95241_data *data;
int err;
data = devm_kzalloc(&new_client->dev, sizeof(struct lm95241_data),
GFP_KERNEL);
if (!data)
return -ENOMEM;
i2c_set_clientdata(new_client, data);
mutex_init(&data->update_lock);
/* Initialize the LM95241 chip */
lm95241_init_client(new_client);
/* Register sysfs hooks */
err = sysfs_create_group(&new_client->dev.kobj, &lm95241_group);
if (err)
return err;
data->hwmon_dev = hwmon_device_register(&new_client->dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
goto exit_remove_files;
}
return 0;
exit_remove_files:
sysfs_remove_group(&new_client->dev.kobj, &lm95241_group);
return err;
}
static int lm95241_remove(struct i2c_client *client)
{
struct lm95241_data *data = i2c_get_clientdata(client);
hwmon_device_unregister(data->hwmon_dev);
sysfs_remove_group(&client->dev.kobj, &lm95241_group);
return 0;
}
/* Driver data (common to all clients) */
static const struct i2c_device_id lm95241_id[] = {
{ "lm95231", 0 },
{ "lm95241", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, lm95241_id);
static struct i2c_driver lm95241_driver = {
.class = I2C_CLASS_HWMON,
.driver = {
.name = DEVNAME,
},
.probe = lm95241_probe,
.remove = lm95241_remove,
.id_table = lm95241_id,
.detect = lm95241_detect,
.address_list = normal_i2c,
};
module_i2c_driver(lm95241_driver);
MODULE_AUTHOR("Davide Rizzo <elpa.rizzo@gmail.com>");
MODULE_DESCRIPTION("LM95241 sensor driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
zyrgit/linux-yocto-3.10-work | drivers/isdn/gigaset/capi.c | 2768 | 69612 | /*
* Kernel CAPI interface for the Gigaset driver
*
* Copyright (c) 2009 by Tilman Schmidt <tilman@imap.cc>.
*
* =====================================================================
* 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 "gigaset.h"
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/ratelimit.h>
#include <linux/isdn/capilli.h>
#include <linux/isdn/capicmd.h>
#include <linux/isdn/capiutil.h>
#include <linux/export.h>
/* missing from kernelcapi.h */
#define CapiNcpiNotSupportedByProtocol 0x0001
#define CapiFlagsNotSupportedByProtocol 0x0002
#define CapiAlertAlreadySent 0x0003
#define CapiFacilitySpecificFunctionNotSupported 0x3011
/* missing from capicmd.h */
#define CAPI_CONNECT_IND_BASELEN (CAPI_MSG_BASELEN + 4 + 2 + 8 * 1)
#define CAPI_CONNECT_ACTIVE_IND_BASELEN (CAPI_MSG_BASELEN + 4 + 3 * 1)
#define CAPI_CONNECT_B3_IND_BASELEN (CAPI_MSG_BASELEN + 4 + 1)
#define CAPI_CONNECT_B3_ACTIVE_IND_BASELEN (CAPI_MSG_BASELEN + 4 + 1)
#define CAPI_DATA_B3_REQ_LEN64 (CAPI_MSG_BASELEN + 4 + 4 + 2 + 2 + 2 + 8)
#define CAPI_DATA_B3_CONF_LEN (CAPI_MSG_BASELEN + 4 + 2 + 2)
#define CAPI_DISCONNECT_IND_LEN (CAPI_MSG_BASELEN + 4 + 2)
#define CAPI_DISCONNECT_B3_IND_BASELEN (CAPI_MSG_BASELEN + 4 + 2 + 1)
#define CAPI_FACILITY_CONF_BASELEN (CAPI_MSG_BASELEN + 4 + 2 + 2 + 1)
/* most _CONF messages contain only Controller/PLCI/NCCI and Info parameters */
#define CAPI_STDCONF_LEN (CAPI_MSG_BASELEN + 4 + 2)
#define CAPI_FACILITY_HANDSET 0x0000
#define CAPI_FACILITY_DTMF 0x0001
#define CAPI_FACILITY_V42BIS 0x0002
#define CAPI_FACILITY_SUPPSVC 0x0003
#define CAPI_FACILITY_WAKEUP 0x0004
#define CAPI_FACILITY_LI 0x0005
#define CAPI_SUPPSVC_GETSUPPORTED 0x0000
#define CAPI_SUPPSVC_LISTEN 0x0001
/* missing from capiutil.h */
#define CAPIMSG_PLCI_PART(m) CAPIMSG_U8(m, 9)
#define CAPIMSG_NCCI_PART(m) CAPIMSG_U16(m, 10)
#define CAPIMSG_HANDLE_REQ(m) CAPIMSG_U16(m, 18) /* DATA_B3_REQ/_IND only! */
#define CAPIMSG_FLAGS(m) CAPIMSG_U16(m, 20)
#define CAPIMSG_SETCONTROLLER(m, contr) capimsg_setu8(m, 8, contr)
#define CAPIMSG_SETPLCI_PART(m, plci) capimsg_setu8(m, 9, plci)
#define CAPIMSG_SETNCCI_PART(m, ncci) capimsg_setu16(m, 10, ncci)
#define CAPIMSG_SETFLAGS(m, flags) capimsg_setu16(m, 20, flags)
/* parameters with differing location in DATA_B3_CONF/_RESP: */
#define CAPIMSG_SETHANDLE_CONF(m, handle) capimsg_setu16(m, 12, handle)
#define CAPIMSG_SETINFO_CONF(m, info) capimsg_setu16(m, 14, info)
/* Flags (DATA_B3_REQ/_IND) */
#define CAPI_FLAGS_DELIVERY_CONFIRMATION 0x04
#define CAPI_FLAGS_RESERVED (~0x1f)
/* buffer sizes */
#define MAX_BC_OCTETS 11
#define MAX_HLC_OCTETS 3
#define MAX_NUMBER_DIGITS 20
#define MAX_FMT_IE_LEN 20
/* values for bcs->apconnstate */
#define APCONN_NONE 0 /* inactive/listening */
#define APCONN_SETUP 1 /* connecting */
#define APCONN_ACTIVE 2 /* B channel up */
/* registered application data structure */
struct gigaset_capi_appl {
struct list_head ctrlist;
struct gigaset_capi_appl *bcnext;
u16 id;
struct capi_register_params rp;
u16 nextMessageNumber;
u32 listenInfoMask;
u32 listenCIPmask;
};
/* CAPI specific controller data structure */
struct gigaset_capi_ctr {
struct capi_ctr ctr;
struct list_head appls;
struct sk_buff_head sendqueue;
atomic_t sendqlen;
/* two _cmsg structures possibly used concurrently: */
_cmsg hcmsg; /* for message composition triggered from hardware */
_cmsg acmsg; /* for dissection of messages sent from application */
u8 bc_buf[MAX_BC_OCTETS + 1];
u8 hlc_buf[MAX_HLC_OCTETS + 1];
u8 cgpty_buf[MAX_NUMBER_DIGITS + 3];
u8 cdpty_buf[MAX_NUMBER_DIGITS + 2];
};
/* CIP Value table (from CAPI 2.0 standard, ch. 6.1) */
static struct {
u8 *bc;
u8 *hlc;
} cip2bchlc[] = {
[1] = { "8090A3", NULL }, /* Speech (A-law) */
[2] = { "8890", NULL }, /* Unrestricted digital information */
[3] = { "8990", NULL }, /* Restricted digital information */
[4] = { "9090A3", NULL }, /* 3,1 kHz audio (A-law) */
[5] = { "9190", NULL }, /* 7 kHz audio */
[6] = { "9890", NULL }, /* Video */
[7] = { "88C0C6E6", NULL }, /* Packet mode */
[8] = { "8890218F", NULL }, /* 56 kbit/s rate adaptation */
[9] = { "9190A5", NULL }, /* Unrestricted digital information
* with tones/announcements */
[16] = { "8090A3", "9181" }, /* Telephony */
[17] = { "9090A3", "9184" }, /* Group 2/3 facsimile */
[18] = { "8890", "91A1" }, /* Group 4 facsimile Class 1 */
[19] = { "8890", "91A4" }, /* Teletex service basic and mixed mode
* and Group 4 facsimile service
* Classes II and III */
[20] = { "8890", "91A8" }, /* Teletex service basic and
* processable mode */
[21] = { "8890", "91B1" }, /* Teletex service basic mode */
[22] = { "8890", "91B2" }, /* International interworking for
* Videotex */
[23] = { "8890", "91B5" }, /* Telex */
[24] = { "8890", "91B8" }, /* Message Handling Systems
* in accordance with X.400 */
[25] = { "8890", "91C1" }, /* OSI application
* in accordance with X.200 */
[26] = { "9190A5", "9181" }, /* 7 kHz telephony */
[27] = { "9190A5", "916001" }, /* Video telephony, first connection */
[28] = { "8890", "916002" }, /* Video telephony, second connection */
};
/*
* helper functions
* ================
*/
/*
* emit unsupported parameter warning
*/
static inline void ignore_cstruct_param(struct cardstate *cs, _cstruct param,
char *msgname, char *paramname)
{
if (param && *param)
dev_warn(cs->dev, "%s: ignoring unsupported parameter: %s\n",
msgname, paramname);
}
/*
* convert an IE from Gigaset hex string to ETSI binary representation
* including length byte
* return value: result length, -1 on error
*/
static int encode_ie(char *in, u8 *out, int maxlen)
{
int l = 0;
while (*in) {
if (!isxdigit(in[0]) || !isxdigit(in[1]) || l >= maxlen)
return -1;
out[++l] = (hex_to_bin(in[0]) << 4) + hex_to_bin(in[1]);
in += 2;
}
out[0] = l;
return l;
}
/*
* convert an IE from ETSI binary representation including length byte
* to Gigaset hex string
*/
static void decode_ie(u8 *in, char *out)
{
int i = *in;
while (i-- > 0) {
/* ToDo: conversion to upper case necessary? */
*out++ = toupper(hex_asc_hi(*++in));
*out++ = toupper(hex_asc_lo(*in));
}
}
/*
* retrieve application data structure for an application ID
*/
static inline struct gigaset_capi_appl *
get_appl(struct gigaset_capi_ctr *iif, u16 appl)
{
struct gigaset_capi_appl *ap;
list_for_each_entry(ap, &iif->appls, ctrlist)
if (ap->id == appl)
return ap;
return NULL;
}
/*
* dump CAPI message to kernel messages for debugging
*/
static inline void dump_cmsg(enum debuglevel level, const char *tag, _cmsg *p)
{
#ifdef CONFIG_GIGASET_DEBUG
/* dump at most 20 messages in 20 secs */
static DEFINE_RATELIMIT_STATE(msg_dump_ratelimit, 20 * HZ, 20);
_cdebbuf *cdb;
if (!(gigaset_debuglevel & level))
return;
if (!___ratelimit(&msg_dump_ratelimit, tag))
return;
cdb = capi_cmsg2str(p);
if (cdb) {
gig_dbg(level, "%s: [%d] %s", tag, p->ApplId, cdb->buf);
cdebbuf_free(cdb);
} else {
gig_dbg(level, "%s: [%d] %s", tag, p->ApplId,
capi_cmd2str(p->Command, p->Subcommand));
}
#endif
}
static inline void dump_rawmsg(enum debuglevel level, const char *tag,
unsigned char *data)
{
#ifdef CONFIG_GIGASET_DEBUG
char *dbgline;
int i, l;
if (!(gigaset_debuglevel & level))
return;
l = CAPIMSG_LEN(data);
if (l < 12) {
gig_dbg(level, "%s: ??? LEN=%04d", tag, l);
return;
}
gig_dbg(level, "%s: 0x%02x:0x%02x: ID=%03d #0x%04x LEN=%04d NCCI=0x%x",
tag, CAPIMSG_COMMAND(data), CAPIMSG_SUBCOMMAND(data),
CAPIMSG_APPID(data), CAPIMSG_MSGID(data), l,
CAPIMSG_CONTROL(data));
l -= 12;
if (l <= 0)
return;
dbgline = kmalloc(3 * l, GFP_ATOMIC);
if (!dbgline)
return;
for (i = 0; i < l; i++) {
dbgline[3 * i] = hex_asc_hi(data[12 + i]);
dbgline[3 * i + 1] = hex_asc_lo(data[12 + i]);
dbgline[3 * i + 2] = ' ';
}
dbgline[3 * l - 1] = '\0';
gig_dbg(level, " %s", dbgline);
kfree(dbgline);
if (CAPIMSG_COMMAND(data) == CAPI_DATA_B3 &&
(CAPIMSG_SUBCOMMAND(data) == CAPI_REQ ||
CAPIMSG_SUBCOMMAND(data) == CAPI_IND)) {
l = CAPIMSG_DATALEN(data);
gig_dbg(level, " DataLength=%d", l);
if (l <= 0 || !(gigaset_debuglevel & DEBUG_LLDATA))
return;
if (l > 64)
l = 64; /* arbitrary limit */
dbgline = kmalloc(3 * l, GFP_ATOMIC);
if (!dbgline)
return;
data += CAPIMSG_LEN(data);
for (i = 0; i < l; i++) {
dbgline[3 * i] = hex_asc_hi(data[i]);
dbgline[3 * i + 1] = hex_asc_lo(data[i]);
dbgline[3 * i + 2] = ' ';
}
dbgline[3 * l - 1] = '\0';
gig_dbg(level, " %s", dbgline);
kfree(dbgline);
}
#endif
}
/*
* format CAPI IE as string
*/
#ifdef CONFIG_GIGASET_DEBUG
static const char *format_ie(const char *ie)
{
static char result[3 * MAX_FMT_IE_LEN];
int len, count;
char *pout = result;
if (!ie)
return "NULL";
count = len = ie[0];
if (count > MAX_FMT_IE_LEN)
count = MAX_FMT_IE_LEN - 1;
while (count--) {
*pout++ = hex_asc_hi(*++ie);
*pout++ = hex_asc_lo(*ie);
*pout++ = ' ';
}
if (len > MAX_FMT_IE_LEN) {
*pout++ = '.';
*pout++ = '.';
*pout++ = '.';
}
*--pout = 0;
return result;
}
#endif
/*
* emit DATA_B3_CONF message
*/
static void send_data_b3_conf(struct cardstate *cs, struct capi_ctr *ctr,
u16 appl, u16 msgid, int channel,
u16 handle, u16 info)
{
struct sk_buff *cskb;
u8 *msg;
cskb = alloc_skb(CAPI_DATA_B3_CONF_LEN, GFP_ATOMIC);
if (!cskb) {
dev_err(cs->dev, "%s: out of memory\n", __func__);
return;
}
/* frequent message, avoid _cmsg overhead */
msg = __skb_put(cskb, CAPI_DATA_B3_CONF_LEN);
CAPIMSG_SETLEN(msg, CAPI_DATA_B3_CONF_LEN);
CAPIMSG_SETAPPID(msg, appl);
CAPIMSG_SETCOMMAND(msg, CAPI_DATA_B3);
CAPIMSG_SETSUBCOMMAND(msg, CAPI_CONF);
CAPIMSG_SETMSGID(msg, msgid);
CAPIMSG_SETCONTROLLER(msg, ctr->cnr);
CAPIMSG_SETPLCI_PART(msg, channel);
CAPIMSG_SETNCCI_PART(msg, 1);
CAPIMSG_SETHANDLE_CONF(msg, handle);
CAPIMSG_SETINFO_CONF(msg, info);
/* emit message */
dump_rawmsg(DEBUG_MCMD, __func__, msg);
capi_ctr_handle_message(ctr, appl, cskb);
}
/*
* driver interface functions
* ==========================
*/
/**
* gigaset_skb_sent() - acknowledge transmission of outgoing skb
* @bcs: B channel descriptor structure.
* @skb: sent data.
*
* Called by hardware module {bas,ser,usb}_gigaset when the data in a
* skb has been successfully sent, for signalling completion to the LL.
*/
void gigaset_skb_sent(struct bc_state *bcs, struct sk_buff *dskb)
{
struct cardstate *cs = bcs->cs;
struct gigaset_capi_ctr *iif = cs->iif;
struct gigaset_capi_appl *ap = bcs->ap;
unsigned char *req = skb_mac_header(dskb);
u16 flags;
/* update statistics */
++bcs->trans_up;
if (!ap) {
gig_dbg(DEBUG_MCMD, "%s: application gone", __func__);
return;
}
/* don't send further B3 messages if disconnected */
if (bcs->apconnstate < APCONN_ACTIVE) {
gig_dbg(DEBUG_MCMD, "%s: disconnected", __func__);
return;
}
/*
* send DATA_B3_CONF if "delivery confirmation" bit was set in request;
* otherwise it has already been sent by do_data_b3_req()
*/
flags = CAPIMSG_FLAGS(req);
if (flags & CAPI_FLAGS_DELIVERY_CONFIRMATION)
send_data_b3_conf(cs, &iif->ctr, ap->id, CAPIMSG_MSGID(req),
bcs->channel + 1, CAPIMSG_HANDLE_REQ(req),
(flags & ~CAPI_FLAGS_DELIVERY_CONFIRMATION) ?
CapiFlagsNotSupportedByProtocol :
CAPI_NOERROR);
}
EXPORT_SYMBOL_GPL(gigaset_skb_sent);
/**
* gigaset_skb_rcvd() - pass received skb to LL
* @bcs: B channel descriptor structure.
* @skb: received data.
*
* Called by hardware module {bas,ser,usb}_gigaset when user data has
* been successfully received, for passing to the LL.
* Warning: skb must not be accessed anymore!
*/
void gigaset_skb_rcvd(struct bc_state *bcs, struct sk_buff *skb)
{
struct cardstate *cs = bcs->cs;
struct gigaset_capi_ctr *iif = cs->iif;
struct gigaset_capi_appl *ap = bcs->ap;
int len = skb->len;
/* update statistics */
bcs->trans_down++;
if (!ap) {
gig_dbg(DEBUG_MCMD, "%s: application gone", __func__);
dev_kfree_skb_any(skb);
return;
}
/* don't send further B3 messages if disconnected */
if (bcs->apconnstate < APCONN_ACTIVE) {
gig_dbg(DEBUG_MCMD, "%s: disconnected", __func__);
dev_kfree_skb_any(skb);
return;
}
/*
* prepend DATA_B3_IND message to payload
* Parameters: NCCI = 1, all others 0/unused
* frequent message, avoid _cmsg overhead
*/
skb_push(skb, CAPI_DATA_B3_REQ_LEN);
CAPIMSG_SETLEN(skb->data, CAPI_DATA_B3_REQ_LEN);
CAPIMSG_SETAPPID(skb->data, ap->id);
CAPIMSG_SETCOMMAND(skb->data, CAPI_DATA_B3);
CAPIMSG_SETSUBCOMMAND(skb->data, CAPI_IND);
CAPIMSG_SETMSGID(skb->data, ap->nextMessageNumber++);
CAPIMSG_SETCONTROLLER(skb->data, iif->ctr.cnr);
CAPIMSG_SETPLCI_PART(skb->data, bcs->channel + 1);
CAPIMSG_SETNCCI_PART(skb->data, 1);
/* Data parameter not used */
CAPIMSG_SETDATALEN(skb->data, len);
/* Data handle parameter not used */
CAPIMSG_SETFLAGS(skb->data, 0);
/* Data64 parameter not present */
/* emit message */
dump_rawmsg(DEBUG_MCMD, __func__, skb->data);
capi_ctr_handle_message(&iif->ctr, ap->id, skb);
}
EXPORT_SYMBOL_GPL(gigaset_skb_rcvd);
/**
* gigaset_isdn_rcv_err() - signal receive error
* @bcs: B channel descriptor structure.
*
* Called by hardware module {bas,ser,usb}_gigaset when a receive error
* has occurred, for signalling to the LL.
*/
void gigaset_isdn_rcv_err(struct bc_state *bcs)
{
/* if currently ignoring packets, just count down */
if (bcs->ignore) {
bcs->ignore--;
return;
}
/* update statistics */
bcs->corrupted++;
/* ToDo: signal error -> LL */
}
EXPORT_SYMBOL_GPL(gigaset_isdn_rcv_err);
/**
* gigaset_isdn_icall() - signal incoming call
* @at_state: connection state structure.
*
* Called by main module at tasklet level to notify the LL that an incoming
* call has been received. @at_state contains the parameters of the call.
*
* Return value: call disposition (ICALL_*)
*/
int gigaset_isdn_icall(struct at_state_t *at_state)
{
struct cardstate *cs = at_state->cs;
struct bc_state *bcs = at_state->bcs;
struct gigaset_capi_ctr *iif = cs->iif;
struct gigaset_capi_appl *ap;
u32 actCIPmask;
struct sk_buff *skb;
unsigned int msgsize;
unsigned long flags;
int i;
/*
* ToDo: signal calls without a free B channel, too
* (requires a u8 handle for the at_state structure that can
* be stored in the PLCI and used in the CONNECT_RESP message
* handler to retrieve it)
*/
if (!bcs)
return ICALL_IGNORE;
/* prepare CONNECT_IND message, using B channel number as PLCI */
capi_cmsg_header(&iif->hcmsg, 0, CAPI_CONNECT, CAPI_IND, 0,
iif->ctr.cnr | ((bcs->channel + 1) << 8));
/* minimum size, all structs empty */
msgsize = CAPI_CONNECT_IND_BASELEN;
/* Bearer Capability (mandatory) */
if (at_state->str_var[STR_ZBC]) {
/* pass on BC from Gigaset */
if (encode_ie(at_state->str_var[STR_ZBC], iif->bc_buf,
MAX_BC_OCTETS) < 0) {
dev_warn(cs->dev, "RING ignored - bad BC %s\n",
at_state->str_var[STR_ZBC]);
return ICALL_IGNORE;
}
/* look up corresponding CIP value */
iif->hcmsg.CIPValue = 0; /* default if nothing found */
for (i = 0; i < ARRAY_SIZE(cip2bchlc); i++)
if (cip2bchlc[i].bc != NULL &&
cip2bchlc[i].hlc == NULL &&
!strcmp(cip2bchlc[i].bc,
at_state->str_var[STR_ZBC])) {
iif->hcmsg.CIPValue = i;
break;
}
} else {
/* no BC (internal call): assume CIP 1 (speech, A-law) */
iif->hcmsg.CIPValue = 1;
encode_ie(cip2bchlc[1].bc, iif->bc_buf, MAX_BC_OCTETS);
}
iif->hcmsg.BC = iif->bc_buf;
msgsize += iif->hcmsg.BC[0];
/* High Layer Compatibility (optional) */
if (at_state->str_var[STR_ZHLC]) {
/* pass on HLC from Gigaset */
if (encode_ie(at_state->str_var[STR_ZHLC], iif->hlc_buf,
MAX_HLC_OCTETS) < 0) {
dev_warn(cs->dev, "RING ignored - bad HLC %s\n",
at_state->str_var[STR_ZHLC]);
return ICALL_IGNORE;
}
iif->hcmsg.HLC = iif->hlc_buf;
msgsize += iif->hcmsg.HLC[0];
/* look up corresponding CIP value */
/* keep BC based CIP value if none found */
if (at_state->str_var[STR_ZBC])
for (i = 0; i < ARRAY_SIZE(cip2bchlc); i++)
if (cip2bchlc[i].hlc != NULL &&
!strcmp(cip2bchlc[i].hlc,
at_state->str_var[STR_ZHLC]) &&
!strcmp(cip2bchlc[i].bc,
at_state->str_var[STR_ZBC])) {
iif->hcmsg.CIPValue = i;
break;
}
}
/* Called Party Number (optional) */
if (at_state->str_var[STR_ZCPN]) {
i = strlen(at_state->str_var[STR_ZCPN]);
if (i > MAX_NUMBER_DIGITS) {
dev_warn(cs->dev, "RING ignored - bad number %s\n",
at_state->str_var[STR_ZBC]);
return ICALL_IGNORE;
}
iif->cdpty_buf[0] = i + 1;
iif->cdpty_buf[1] = 0x80; /* type / numbering plan unknown */
memcpy(iif->cdpty_buf + 2, at_state->str_var[STR_ZCPN], i);
iif->hcmsg.CalledPartyNumber = iif->cdpty_buf;
msgsize += iif->hcmsg.CalledPartyNumber[0];
}
/* Calling Party Number (optional) */
if (at_state->str_var[STR_NMBR]) {
i = strlen(at_state->str_var[STR_NMBR]);
if (i > MAX_NUMBER_DIGITS) {
dev_warn(cs->dev, "RING ignored - bad number %s\n",
at_state->str_var[STR_ZBC]);
return ICALL_IGNORE;
}
iif->cgpty_buf[0] = i + 2;
iif->cgpty_buf[1] = 0x00; /* type / numbering plan unknown */
iif->cgpty_buf[2] = 0x80; /* pres. allowed, not screened */
memcpy(iif->cgpty_buf + 3, at_state->str_var[STR_NMBR], i);
iif->hcmsg.CallingPartyNumber = iif->cgpty_buf;
msgsize += iif->hcmsg.CallingPartyNumber[0];
}
/* remaining parameters (not supported, always left NULL):
* - CalledPartySubaddress
* - CallingPartySubaddress
* - AdditionalInfo
* - BChannelinformation
* - Keypadfacility
* - Useruserdata
* - Facilitydataarray
*/
gig_dbg(DEBUG_CMD, "icall: PLCI %x CIP %d BC %s",
iif->hcmsg.adr.adrPLCI, iif->hcmsg.CIPValue,
format_ie(iif->hcmsg.BC));
gig_dbg(DEBUG_CMD, "icall: HLC %s",
format_ie(iif->hcmsg.HLC));
gig_dbg(DEBUG_CMD, "icall: CgPty %s",
format_ie(iif->hcmsg.CallingPartyNumber));
gig_dbg(DEBUG_CMD, "icall: CdPty %s",
format_ie(iif->hcmsg.CalledPartyNumber));
/* scan application list for matching listeners */
spin_lock_irqsave(&bcs->aplock, flags);
if (bcs->ap != NULL || bcs->apconnstate != APCONN_NONE) {
dev_warn(cs->dev, "%s: channel not properly cleared (%p/%d)\n",
__func__, bcs->ap, bcs->apconnstate);
bcs->ap = NULL;
bcs->apconnstate = APCONN_NONE;
}
spin_unlock_irqrestore(&bcs->aplock, flags);
actCIPmask = 1 | (1 << iif->hcmsg.CIPValue);
list_for_each_entry(ap, &iif->appls, ctrlist)
if (actCIPmask & ap->listenCIPmask) {
/* build CONNECT_IND message for this application */
iif->hcmsg.ApplId = ap->id;
iif->hcmsg.Messagenumber = ap->nextMessageNumber++;
skb = alloc_skb(msgsize, GFP_ATOMIC);
if (!skb) {
dev_err(cs->dev, "%s: out of memory\n",
__func__);
break;
}
capi_cmsg2message(&iif->hcmsg, __skb_put(skb, msgsize));
dump_cmsg(DEBUG_CMD, __func__, &iif->hcmsg);
/* add to listeners on this B channel, update state */
spin_lock_irqsave(&bcs->aplock, flags);
ap->bcnext = bcs->ap;
bcs->ap = ap;
bcs->chstate |= CHS_NOTIFY_LL;
bcs->apconnstate = APCONN_SETUP;
spin_unlock_irqrestore(&bcs->aplock, flags);
/* emit message */
capi_ctr_handle_message(&iif->ctr, ap->id, skb);
}
/*
* Return "accept" if any listeners.
* Gigaset will send ALERTING.
* There doesn't seem to be a way to avoid this.
*/
return bcs->ap ? ICALL_ACCEPT : ICALL_IGNORE;
}
/*
* send a DISCONNECT_IND message to an application
* does not sleep, clobbers the controller's hcmsg structure
*/
static void send_disconnect_ind(struct bc_state *bcs,
struct gigaset_capi_appl *ap, u16 reason)
{
struct cardstate *cs = bcs->cs;
struct gigaset_capi_ctr *iif = cs->iif;
struct sk_buff *skb;
if (bcs->apconnstate == APCONN_NONE)
return;
capi_cmsg_header(&iif->hcmsg, ap->id, CAPI_DISCONNECT, CAPI_IND,
ap->nextMessageNumber++,
iif->ctr.cnr | ((bcs->channel + 1) << 8));
iif->hcmsg.Reason = reason;
skb = alloc_skb(CAPI_DISCONNECT_IND_LEN, GFP_ATOMIC);
if (!skb) {
dev_err(cs->dev, "%s: out of memory\n", __func__);
return;
}
capi_cmsg2message(&iif->hcmsg, __skb_put(skb, CAPI_DISCONNECT_IND_LEN));
dump_cmsg(DEBUG_CMD, __func__, &iif->hcmsg);
capi_ctr_handle_message(&iif->ctr, ap->id, skb);
}
/*
* send a DISCONNECT_B3_IND message to an application
* Parameters: NCCI = 1, NCPI empty, Reason_B3 = 0
* does not sleep, clobbers the controller's hcmsg structure
*/
static void send_disconnect_b3_ind(struct bc_state *bcs,
struct gigaset_capi_appl *ap)
{
struct cardstate *cs = bcs->cs;
struct gigaset_capi_ctr *iif = cs->iif;
struct sk_buff *skb;
/* nothing to do if no logical connection active */
if (bcs->apconnstate < APCONN_ACTIVE)
return;
bcs->apconnstate = APCONN_SETUP;
capi_cmsg_header(&iif->hcmsg, ap->id, CAPI_DISCONNECT_B3, CAPI_IND,
ap->nextMessageNumber++,
iif->ctr.cnr | ((bcs->channel + 1) << 8) | (1 << 16));
skb = alloc_skb(CAPI_DISCONNECT_B3_IND_BASELEN, GFP_ATOMIC);
if (!skb) {
dev_err(cs->dev, "%s: out of memory\n", __func__);
return;
}
capi_cmsg2message(&iif->hcmsg,
__skb_put(skb, CAPI_DISCONNECT_B3_IND_BASELEN));
dump_cmsg(DEBUG_CMD, __func__, &iif->hcmsg);
capi_ctr_handle_message(&iif->ctr, ap->id, skb);
}
/**
* gigaset_isdn_connD() - signal D channel connect
* @bcs: B channel descriptor structure.
*
* Called by main module at tasklet level to notify the LL that the D channel
* connection has been established.
*/
void gigaset_isdn_connD(struct bc_state *bcs)
{
struct cardstate *cs = bcs->cs;
struct gigaset_capi_ctr *iif = cs->iif;
struct gigaset_capi_appl *ap;
struct sk_buff *skb;
unsigned int msgsize;
unsigned long flags;
spin_lock_irqsave(&bcs->aplock, flags);
ap = bcs->ap;
if (!ap) {
spin_unlock_irqrestore(&bcs->aplock, flags);
gig_dbg(DEBUG_CMD, "%s: application gone", __func__);
return;
}
if (bcs->apconnstate == APCONN_NONE) {
spin_unlock_irqrestore(&bcs->aplock, flags);
dev_warn(cs->dev, "%s: application %u not connected\n",
__func__, ap->id);
return;
}
spin_unlock_irqrestore(&bcs->aplock, flags);
while (ap->bcnext) {
/* this should never happen */
dev_warn(cs->dev, "%s: dropping extra application %u\n",
__func__, ap->bcnext->id);
send_disconnect_ind(bcs, ap->bcnext,
CapiCallGivenToOtherApplication);
ap->bcnext = ap->bcnext->bcnext;
}
/* prepare CONNECT_ACTIVE_IND message
* Note: LLC not supported by device
*/
capi_cmsg_header(&iif->hcmsg, ap->id, CAPI_CONNECT_ACTIVE, CAPI_IND,
ap->nextMessageNumber++,
iif->ctr.cnr | ((bcs->channel + 1) << 8));
/* minimum size, all structs empty */
msgsize = CAPI_CONNECT_ACTIVE_IND_BASELEN;
/* ToDo: set parameter: Connected number
* (requires ev-layer state machine extension to collect
* ZCON device reply)
*/
/* build and emit CONNECT_ACTIVE_IND message */
skb = alloc_skb(msgsize, GFP_ATOMIC);
if (!skb) {
dev_err(cs->dev, "%s: out of memory\n", __func__);
return;
}
capi_cmsg2message(&iif->hcmsg, __skb_put(skb, msgsize));
dump_cmsg(DEBUG_CMD, __func__, &iif->hcmsg);
capi_ctr_handle_message(&iif->ctr, ap->id, skb);
}
/**
* gigaset_isdn_hupD() - signal D channel hangup
* @bcs: B channel descriptor structure.
*
* Called by main module at tasklet level to notify the LL that the D channel
* connection has been shut down.
*/
void gigaset_isdn_hupD(struct bc_state *bcs)
{
struct gigaset_capi_appl *ap;
unsigned long flags;
/*
* ToDo: pass on reason code reported by device
* (requires ev-layer state machine extension to collect
* ZCAU device reply)
*/
spin_lock_irqsave(&bcs->aplock, flags);
while (bcs->ap != NULL) {
ap = bcs->ap;
bcs->ap = ap->bcnext;
spin_unlock_irqrestore(&bcs->aplock, flags);
send_disconnect_b3_ind(bcs, ap);
send_disconnect_ind(bcs, ap, 0);
spin_lock_irqsave(&bcs->aplock, flags);
}
bcs->apconnstate = APCONN_NONE;
spin_unlock_irqrestore(&bcs->aplock, flags);
}
/**
* gigaset_isdn_connB() - signal B channel connect
* @bcs: B channel descriptor structure.
*
* Called by main module at tasklet level to notify the LL that the B channel
* connection has been established.
*/
void gigaset_isdn_connB(struct bc_state *bcs)
{
struct cardstate *cs = bcs->cs;
struct gigaset_capi_ctr *iif = cs->iif;
struct gigaset_capi_appl *ap;
struct sk_buff *skb;
unsigned long flags;
unsigned int msgsize;
u8 command;
spin_lock_irqsave(&bcs->aplock, flags);
ap = bcs->ap;
if (!ap) {
spin_unlock_irqrestore(&bcs->aplock, flags);
gig_dbg(DEBUG_CMD, "%s: application gone", __func__);
return;
}
if (!bcs->apconnstate) {
spin_unlock_irqrestore(&bcs->aplock, flags);
dev_warn(cs->dev, "%s: application %u not connected\n",
__func__, ap->id);
return;
}
/*
* emit CONNECT_B3_ACTIVE_IND if we already got CONNECT_B3_REQ;
* otherwise we have to emit CONNECT_B3_IND first, and follow up with
* CONNECT_B3_ACTIVE_IND in reply to CONNECT_B3_RESP
* Parameters in both cases always: NCCI = 1, NCPI empty
*/
if (bcs->apconnstate >= APCONN_ACTIVE) {
command = CAPI_CONNECT_B3_ACTIVE;
msgsize = CAPI_CONNECT_B3_ACTIVE_IND_BASELEN;
} else {
command = CAPI_CONNECT_B3;
msgsize = CAPI_CONNECT_B3_IND_BASELEN;
}
bcs->apconnstate = APCONN_ACTIVE;
spin_unlock_irqrestore(&bcs->aplock, flags);
while (ap->bcnext) {
/* this should never happen */
dev_warn(cs->dev, "%s: dropping extra application %u\n",
__func__, ap->bcnext->id);
send_disconnect_ind(bcs, ap->bcnext,
CapiCallGivenToOtherApplication);
ap->bcnext = ap->bcnext->bcnext;
}
capi_cmsg_header(&iif->hcmsg, ap->id, command, CAPI_IND,
ap->nextMessageNumber++,
iif->ctr.cnr | ((bcs->channel + 1) << 8) | (1 << 16));
skb = alloc_skb(msgsize, GFP_ATOMIC);
if (!skb) {
dev_err(cs->dev, "%s: out of memory\n", __func__);
return;
}
capi_cmsg2message(&iif->hcmsg, __skb_put(skb, msgsize));
dump_cmsg(DEBUG_CMD, __func__, &iif->hcmsg);
capi_ctr_handle_message(&iif->ctr, ap->id, skb);
}
/**
* gigaset_isdn_hupB() - signal B channel hangup
* @bcs: B channel descriptor structure.
*
* Called by main module to notify the LL that the B channel connection has
* been shut down.
*/
void gigaset_isdn_hupB(struct bc_state *bcs)
{
struct gigaset_capi_appl *ap = bcs->ap;
/* ToDo: assure order of DISCONNECT_B3_IND and DISCONNECT_IND ? */
if (!ap) {
gig_dbg(DEBUG_CMD, "%s: application gone", __func__);
return;
}
send_disconnect_b3_ind(bcs, ap);
}
/**
* gigaset_isdn_start() - signal device availability
* @cs: device descriptor structure.
*
* Called by main module to notify the LL that the device is available for
* use.
*/
void gigaset_isdn_start(struct cardstate *cs)
{
struct gigaset_capi_ctr *iif = cs->iif;
/* fill profile data: manufacturer name */
strcpy(iif->ctr.manu, "Siemens");
/* CAPI and device version */
iif->ctr.version.majorversion = 2; /* CAPI 2.0 */
iif->ctr.version.minorversion = 0;
/* ToDo: check/assert cs->gotfwver? */
iif->ctr.version.majormanuversion = cs->fwver[0];
iif->ctr.version.minormanuversion = cs->fwver[1];
/* number of B channels supported */
iif->ctr.profile.nbchannel = cs->channels;
/* global options: internal controller, supplementary services */
iif->ctr.profile.goptions = 0x11;
/* B1 protocols: 64 kbit/s HDLC or transparent */
iif->ctr.profile.support1 = 0x03;
/* B2 protocols: transparent only */
/* ToDo: X.75 SLP ? */
iif->ctr.profile.support2 = 0x02;
/* B3 protocols: transparent only */
iif->ctr.profile.support3 = 0x01;
/* no serial number */
strcpy(iif->ctr.serial, "0");
capi_ctr_ready(&iif->ctr);
}
/**
* gigaset_isdn_stop() - signal device unavailability
* @cs: device descriptor structure.
*
* Called by main module to notify the LL that the device is no longer
* available for use.
*/
void gigaset_isdn_stop(struct cardstate *cs)
{
struct gigaset_capi_ctr *iif = cs->iif;
capi_ctr_down(&iif->ctr);
}
/*
* kernel CAPI callback methods
* ============================
*/
/*
* register CAPI application
*/
static void gigaset_register_appl(struct capi_ctr *ctr, u16 appl,
capi_register_params *rp)
{
struct gigaset_capi_ctr *iif
= container_of(ctr, struct gigaset_capi_ctr, ctr);
struct cardstate *cs = ctr->driverdata;
struct gigaset_capi_appl *ap;
gig_dbg(DEBUG_CMD, "%s [%u] l3cnt=%u blkcnt=%u blklen=%u",
__func__, appl, rp->level3cnt, rp->datablkcnt, rp->datablklen);
list_for_each_entry(ap, &iif->appls, ctrlist)
if (ap->id == appl) {
dev_notice(cs->dev,
"application %u already registered\n", appl);
return;
}
ap = kzalloc(sizeof(*ap), GFP_KERNEL);
if (!ap) {
dev_err(cs->dev, "%s: out of memory\n", __func__);
return;
}
ap->id = appl;
ap->rp = *rp;
list_add(&ap->ctrlist, &iif->appls);
dev_info(cs->dev, "application %u registered\n", ap->id);
}
/*
* remove CAPI application from channel
* helper function to keep indentation levels down and stay in 80 columns
*/
static inline void remove_appl_from_channel(struct bc_state *bcs,
struct gigaset_capi_appl *ap)
{
struct cardstate *cs = bcs->cs;
struct gigaset_capi_appl *bcap;
unsigned long flags;
int prevconnstate;
spin_lock_irqsave(&bcs->aplock, flags);
bcap = bcs->ap;
if (bcap == NULL) {
spin_unlock_irqrestore(&bcs->aplock, flags);
return;
}
/* check first application on channel */
if (bcap == ap) {
bcs->ap = ap->bcnext;
if (bcs->ap != NULL) {
spin_unlock_irqrestore(&bcs->aplock, flags);
return;
}
/* none left, clear channel state */
prevconnstate = bcs->apconnstate;
bcs->apconnstate = APCONN_NONE;
spin_unlock_irqrestore(&bcs->aplock, flags);
if (prevconnstate == APCONN_ACTIVE) {
dev_notice(cs->dev, "%s: hanging up channel %u\n",
__func__, bcs->channel);
gigaset_add_event(cs, &bcs->at_state,
EV_HUP, NULL, 0, NULL);
gigaset_schedule_event(cs);
}
return;
}
/* check remaining list */
do {
if (bcap->bcnext == ap) {
bcap->bcnext = bcap->bcnext->bcnext;
spin_unlock_irqrestore(&bcs->aplock, flags);
return;
}
bcap = bcap->bcnext;
} while (bcap != NULL);
spin_unlock_irqrestore(&bcs->aplock, flags);
}
/*
* release CAPI application
*/
static void gigaset_release_appl(struct capi_ctr *ctr, u16 appl)
{
struct gigaset_capi_ctr *iif
= container_of(ctr, struct gigaset_capi_ctr, ctr);
struct cardstate *cs = iif->ctr.driverdata;
struct gigaset_capi_appl *ap, *tmp;
unsigned ch;
gig_dbg(DEBUG_CMD, "%s [%u]", __func__, appl);
list_for_each_entry_safe(ap, tmp, &iif->appls, ctrlist)
if (ap->id == appl) {
/* remove from any channels */
for (ch = 0; ch < cs->channels; ch++)
remove_appl_from_channel(&cs->bcs[ch], ap);
/* remove from registration list */
list_del(&ap->ctrlist);
kfree(ap);
dev_info(cs->dev, "application %u released\n", appl);
}
}
/*
* =====================================================================
* outgoing CAPI message handler
* =====================================================================
*/
/*
* helper function: emit reply message with given Info value
*/
static void send_conf(struct gigaset_capi_ctr *iif,
struct gigaset_capi_appl *ap,
struct sk_buff *skb,
u16 info)
{
/*
* _CONF replies always only have NCCI and Info parameters
* so they'll fit into the _REQ message skb
*/
capi_cmsg_answer(&iif->acmsg);
iif->acmsg.Info = info;
capi_cmsg2message(&iif->acmsg, skb->data);
__skb_trim(skb, CAPI_STDCONF_LEN);
dump_cmsg(DEBUG_CMD, __func__, &iif->acmsg);
capi_ctr_handle_message(&iif->ctr, ap->id, skb);
}
/*
* process FACILITY_REQ message
*/
static void do_facility_req(struct gigaset_capi_ctr *iif,
struct gigaset_capi_appl *ap,
struct sk_buff *skb)
{
struct cardstate *cs = iif->ctr.driverdata;
_cmsg *cmsg = &iif->acmsg;
struct sk_buff *cskb;
u8 *pparam;
unsigned int msgsize = CAPI_FACILITY_CONF_BASELEN;
u16 function, info;
static u8 confparam[10]; /* max. 9 octets + length byte */
/* decode message */
capi_message2cmsg(cmsg, skb->data);
dump_cmsg(DEBUG_CMD, __func__, cmsg);
/*
* Facility Request Parameter is not decoded by capi_message2cmsg()
* encoding depends on Facility Selector
*/
switch (cmsg->FacilitySelector) {
case CAPI_FACILITY_DTMF: /* ToDo */
info = CapiFacilityNotSupported;
confparam[0] = 2; /* length */
/* DTMF information: Unknown DTMF request */
capimsg_setu16(confparam, 1, 2);
break;
case CAPI_FACILITY_V42BIS: /* not supported */
info = CapiFacilityNotSupported;
confparam[0] = 2; /* length */
/* V.42 bis information: not available */
capimsg_setu16(confparam, 1, 1);
break;
case CAPI_FACILITY_SUPPSVC:
/* decode Function parameter */
pparam = cmsg->FacilityRequestParameter;
if (pparam == NULL || pparam[0] < 2) {
dev_notice(cs->dev, "%s: %s missing\n", "FACILITY_REQ",
"Facility Request Parameter");
send_conf(iif, ap, skb, CapiIllMessageParmCoding);
return;
}
function = CAPIMSG_U16(pparam, 1);
switch (function) {
case CAPI_SUPPSVC_GETSUPPORTED:
info = CapiSuccess;
/* Supplementary Service specific parameter */
confparam[3] = 6; /* length */
/* Supplementary services info: Success */
capimsg_setu16(confparam, 4, CapiSuccess);
/* Supported Services: none */
capimsg_setu32(confparam, 6, 0);
break;
case CAPI_SUPPSVC_LISTEN:
if (pparam[0] < 7 || pparam[3] < 4) {
dev_notice(cs->dev, "%s: %s missing\n",
"FACILITY_REQ", "Notification Mask");
send_conf(iif, ap, skb,
CapiIllMessageParmCoding);
return;
}
if (CAPIMSG_U32(pparam, 4) != 0) {
dev_notice(cs->dev,
"%s: unsupported supplementary service notification mask 0x%x\n",
"FACILITY_REQ", CAPIMSG_U32(pparam, 4));
info = CapiFacilitySpecificFunctionNotSupported;
confparam[3] = 2; /* length */
capimsg_setu16(confparam, 4,
CapiSupplementaryServiceNotSupported);
}
info = CapiSuccess;
confparam[3] = 2; /* length */
capimsg_setu16(confparam, 4, CapiSuccess);
break;
/* ToDo: add supported services */
default:
dev_notice(cs->dev,
"%s: unsupported supplementary service function 0x%04x\n",
"FACILITY_REQ", function);
info = CapiFacilitySpecificFunctionNotSupported;
/* Supplementary Service specific parameter */
confparam[3] = 2; /* length */
/* Supplementary services info: not supported */
capimsg_setu16(confparam, 4,
CapiSupplementaryServiceNotSupported);
}
/* Facility confirmation parameter */
confparam[0] = confparam[3] + 3; /* total length */
/* Function: copy from _REQ message */
capimsg_setu16(confparam, 1, function);
/* Supplementary Service specific parameter already set above */
break;
case CAPI_FACILITY_WAKEUP: /* ToDo */
info = CapiFacilityNotSupported;
confparam[0] = 2; /* length */
/* Number of accepted awake request parameters: 0 */
capimsg_setu16(confparam, 1, 0);
break;
default:
info = CapiFacilityNotSupported;
confparam[0] = 0; /* empty struct */
}
/* send FACILITY_CONF with given Info and confirmation parameter */
capi_cmsg_answer(cmsg);
cmsg->Info = info;
cmsg->FacilityConfirmationParameter = confparam;
msgsize += confparam[0]; /* length */
cskb = alloc_skb(msgsize, GFP_ATOMIC);
if (!cskb) {
dev_err(cs->dev, "%s: out of memory\n", __func__);
return;
}
capi_cmsg2message(cmsg, __skb_put(cskb, msgsize));
dump_cmsg(DEBUG_CMD, __func__, cmsg);
capi_ctr_handle_message(&iif->ctr, ap->id, cskb);
}
/*
* process LISTEN_REQ message
* just store the masks in the application data structure
*/
static void do_listen_req(struct gigaset_capi_ctr *iif,
struct gigaset_capi_appl *ap,
struct sk_buff *skb)
{
/* decode message */
capi_message2cmsg(&iif->acmsg, skb->data);
dump_cmsg(DEBUG_CMD, __func__, &iif->acmsg);
/* store listening parameters */
ap->listenInfoMask = iif->acmsg.InfoMask;
ap->listenCIPmask = iif->acmsg.CIPmask;
send_conf(iif, ap, skb, CapiSuccess);
}
/*
* process ALERT_REQ message
* nothing to do, Gigaset always alerts anyway
*/
static void do_alert_req(struct gigaset_capi_ctr *iif,
struct gigaset_capi_appl *ap,
struct sk_buff *skb)
{
/* decode message */
capi_message2cmsg(&iif->acmsg, skb->data);
dump_cmsg(DEBUG_CMD, __func__, &iif->acmsg);
send_conf(iif, ap, skb, CapiAlertAlreadySent);
}
/*
* process CONNECT_REQ message
* allocate a B channel, prepare dial commands, queue a DIAL event,
* emit CONNECT_CONF reply
*/
static void do_connect_req(struct gigaset_capi_ctr *iif,
struct gigaset_capi_appl *ap,
struct sk_buff *skb)
{
struct cardstate *cs = iif->ctr.driverdata;
_cmsg *cmsg = &iif->acmsg;
struct bc_state *bcs;
char **commands;
char *s;
u8 *pp;
unsigned long flags;
int i, l, lbc, lhlc;
u16 info;
/* decode message */
capi_message2cmsg(cmsg, skb->data);
dump_cmsg(DEBUG_CMD, __func__, cmsg);
/* get free B channel & construct PLCI */
bcs = gigaset_get_free_channel(cs);
if (!bcs) {
dev_notice(cs->dev, "%s: no B channel available\n",
"CONNECT_REQ");
send_conf(iif, ap, skb, CapiNoPlciAvailable);
return;
}
spin_lock_irqsave(&bcs->aplock, flags);
if (bcs->ap != NULL || bcs->apconnstate != APCONN_NONE)
dev_warn(cs->dev, "%s: channel not properly cleared (%p/%d)\n",
__func__, bcs->ap, bcs->apconnstate);
ap->bcnext = NULL;
bcs->ap = ap;
bcs->apconnstate = APCONN_SETUP;
spin_unlock_irqrestore(&bcs->aplock, flags);
bcs->rx_bufsize = ap->rp.datablklen;
dev_kfree_skb(bcs->rx_skb);
gigaset_new_rx_skb(bcs);
cmsg->adr.adrPLCI |= (bcs->channel + 1) << 8;
/* build command table */
commands = kzalloc(AT_NUM * (sizeof *commands), GFP_KERNEL);
if (!commands)
goto oom;
/* encode parameter: Called party number */
pp = cmsg->CalledPartyNumber;
if (pp == NULL || *pp == 0) {
dev_notice(cs->dev, "%s: %s missing\n",
"CONNECT_REQ", "Called party number");
info = CapiIllMessageParmCoding;
goto error;
}
l = *pp++;
/* check type of number/numbering plan byte */
switch (*pp) {
case 0x80: /* unknown type / unknown numbering plan */
case 0x81: /* unknown type / ISDN/Telephony numbering plan */
break;
default: /* others: warn about potential misinterpretation */
dev_notice(cs->dev, "%s: %s type/plan 0x%02x unsupported\n",
"CONNECT_REQ", "Called party number", *pp);
}
pp++;
l--;
/* translate "**" internal call prefix to CTP value */
if (l >= 2 && pp[0] == '*' && pp[1] == '*') {
s = "^SCTP=0\r";
pp += 2;
l -= 2;
} else {
s = "^SCTP=1\r";
}
commands[AT_TYPE] = kstrdup(s, GFP_KERNEL);
if (!commands[AT_TYPE])
goto oom;
commands[AT_DIAL] = kmalloc(l + 3, GFP_KERNEL);
if (!commands[AT_DIAL])
goto oom;
snprintf(commands[AT_DIAL], l + 3, "D%.*s\r", l, pp);
/* encode parameter: Calling party number */
pp = cmsg->CallingPartyNumber;
if (pp != NULL && *pp > 0) {
l = *pp++;
/* check type of number/numbering plan byte */
/* ToDo: allow for/handle Ext=1? */
switch (*pp) {
case 0x00: /* unknown type / unknown numbering plan */
case 0x01: /* unknown type / ISDN/Telephony num. plan */
break;
default:
dev_notice(cs->dev,
"%s: %s type/plan 0x%02x unsupported\n",
"CONNECT_REQ", "Calling party number", *pp);
}
pp++;
l--;
/* check presentation indicator */
if (!l) {
dev_notice(cs->dev, "%s: %s IE truncated\n",
"CONNECT_REQ", "Calling party number");
info = CapiIllMessageParmCoding;
goto error;
}
switch (*pp & 0xfc) { /* ignore Screening indicator */
case 0x80: /* Presentation allowed */
s = "^SCLIP=1\r";
break;
case 0xa0: /* Presentation restricted */
s = "^SCLIP=0\r";
break;
default:
dev_notice(cs->dev, "%s: invalid %s 0x%02x\n",
"CONNECT_REQ",
"Presentation/Screening indicator",
*pp);
s = "^SCLIP=1\r";
}
commands[AT_CLIP] = kstrdup(s, GFP_KERNEL);
if (!commands[AT_CLIP])
goto oom;
pp++;
l--;
if (l) {
/* number */
commands[AT_MSN] = kmalloc(l + 8, GFP_KERNEL);
if (!commands[AT_MSN])
goto oom;
snprintf(commands[AT_MSN], l + 8, "^SMSN=%*s\r", l, pp);
}
}
/* check parameter: CIP Value */
if (cmsg->CIPValue >= ARRAY_SIZE(cip2bchlc) ||
(cmsg->CIPValue > 0 && cip2bchlc[cmsg->CIPValue].bc == NULL)) {
dev_notice(cs->dev, "%s: unknown CIP value %d\n",
"CONNECT_REQ", cmsg->CIPValue);
info = CapiCipValueUnknown;
goto error;
}
/*
* check/encode parameters: BC & HLC
* must be encoded together as device doesn't accept HLC separately
* explicit parameters override values derived from CIP
*/
/* determine lengths */
if (cmsg->BC && cmsg->BC[0]) /* BC specified explicitly */
lbc = 2 * cmsg->BC[0];
else if (cip2bchlc[cmsg->CIPValue].bc) /* BC derived from CIP */
lbc = strlen(cip2bchlc[cmsg->CIPValue].bc);
else /* no BC */
lbc = 0;
if (cmsg->HLC && cmsg->HLC[0]) /* HLC specified explicitly */
lhlc = 2 * cmsg->HLC[0];
else if (cip2bchlc[cmsg->CIPValue].hlc) /* HLC derived from CIP */
lhlc = strlen(cip2bchlc[cmsg->CIPValue].hlc);
else /* no HLC */
lhlc = 0;
if (lbc) {
/* have BC: allocate and assemble command string */
l = lbc + 7; /* "^SBC=" + value + "\r" + null byte */
if (lhlc)
l += lhlc + 7; /* ";^SHLC=" + value */
commands[AT_BC] = kmalloc(l, GFP_KERNEL);
if (!commands[AT_BC])
goto oom;
strcpy(commands[AT_BC], "^SBC=");
if (cmsg->BC && cmsg->BC[0]) /* BC specified explicitly */
decode_ie(cmsg->BC, commands[AT_BC] + 5);
else /* BC derived from CIP */
strcpy(commands[AT_BC] + 5,
cip2bchlc[cmsg->CIPValue].bc);
if (lhlc) {
strcpy(commands[AT_BC] + lbc + 5, ";^SHLC=");
if (cmsg->HLC && cmsg->HLC[0])
/* HLC specified explicitly */
decode_ie(cmsg->HLC,
commands[AT_BC] + lbc + 12);
else /* HLC derived from CIP */
strcpy(commands[AT_BC] + lbc + 12,
cip2bchlc[cmsg->CIPValue].hlc);
}
strcpy(commands[AT_BC] + l - 2, "\r");
} else {
/* no BC */
if (lhlc) {
dev_notice(cs->dev, "%s: cannot set HLC without BC\n",
"CONNECT_REQ");
info = CapiIllMessageParmCoding; /* ? */
goto error;
}
}
/* check/encode parameter: B Protocol */
if (cmsg->BProtocol == CAPI_DEFAULT) {
bcs->proto2 = L2_HDLC;
dev_warn(cs->dev,
"B2 Protocol X.75 SLP unsupported, using Transparent\n");
} else {
switch (cmsg->B1protocol) {
case 0:
bcs->proto2 = L2_HDLC;
break;
case 1:
bcs->proto2 = L2_VOICE;
break;
default:
dev_warn(cs->dev,
"B1 Protocol %u unsupported, using Transparent\n",
cmsg->B1protocol);
bcs->proto2 = L2_VOICE;
}
if (cmsg->B2protocol != 1)
dev_warn(cs->dev,
"B2 Protocol %u unsupported, using Transparent\n",
cmsg->B2protocol);
if (cmsg->B3protocol != 0)
dev_warn(cs->dev,
"B3 Protocol %u unsupported, using Transparent\n",
cmsg->B3protocol);
ignore_cstruct_param(cs, cmsg->B1configuration,
"CONNECT_REQ", "B1 Configuration");
ignore_cstruct_param(cs, cmsg->B2configuration,
"CONNECT_REQ", "B2 Configuration");
ignore_cstruct_param(cs, cmsg->B3configuration,
"CONNECT_REQ", "B3 Configuration");
}
commands[AT_PROTO] = kmalloc(9, GFP_KERNEL);
if (!commands[AT_PROTO])
goto oom;
snprintf(commands[AT_PROTO], 9, "^SBPR=%u\r", bcs->proto2);
/* ToDo: check/encode remaining parameters */
ignore_cstruct_param(cs, cmsg->CalledPartySubaddress,
"CONNECT_REQ", "Called pty subaddr");
ignore_cstruct_param(cs, cmsg->CallingPartySubaddress,
"CONNECT_REQ", "Calling pty subaddr");
ignore_cstruct_param(cs, cmsg->LLC,
"CONNECT_REQ", "LLC");
if (cmsg->AdditionalInfo != CAPI_DEFAULT) {
ignore_cstruct_param(cs, cmsg->BChannelinformation,
"CONNECT_REQ", "B Channel Information");
ignore_cstruct_param(cs, cmsg->Keypadfacility,
"CONNECT_REQ", "Keypad Facility");
ignore_cstruct_param(cs, cmsg->Useruserdata,
"CONNECT_REQ", "User-User Data");
ignore_cstruct_param(cs, cmsg->Facilitydataarray,
"CONNECT_REQ", "Facility Data Array");
}
/* encode parameter: B channel to use */
commands[AT_ISO] = kmalloc(9, GFP_KERNEL);
if (!commands[AT_ISO])
goto oom;
snprintf(commands[AT_ISO], 9, "^SISO=%u\r",
(unsigned) bcs->channel + 1);
/* queue & schedule EV_DIAL event */
if (!gigaset_add_event(cs, &bcs->at_state, EV_DIAL, commands,
bcs->at_state.seq_index, NULL)) {
info = CAPI_MSGOSRESOURCEERR;
goto error;
}
gigaset_schedule_event(cs);
send_conf(iif, ap, skb, CapiSuccess);
return;
oom:
dev_err(cs->dev, "%s: out of memory\n", __func__);
info = CAPI_MSGOSRESOURCEERR;
error:
if (commands)
for (i = 0; i < AT_NUM; i++)
kfree(commands[i]);
kfree(commands);
gigaset_free_channel(bcs);
send_conf(iif, ap, skb, info);
}
/*
* process CONNECT_RESP message
* checks protocol parameters and queues an ACCEPT or HUP event
*/
static void do_connect_resp(struct gigaset_capi_ctr *iif,
struct gigaset_capi_appl *ap,
struct sk_buff *skb)
{
struct cardstate *cs = iif->ctr.driverdata;
_cmsg *cmsg = &iif->acmsg;
struct bc_state *bcs;
struct gigaset_capi_appl *oap;
unsigned long flags;
int channel;
/* decode message */
capi_message2cmsg(cmsg, skb->data);
dump_cmsg(DEBUG_CMD, __func__, cmsg);
dev_kfree_skb_any(skb);
/* extract and check channel number from PLCI */
channel = (cmsg->adr.adrPLCI >> 8) & 0xff;
if (!channel || channel > cs->channels) {
dev_notice(cs->dev, "%s: invalid %s 0x%02x\n",
"CONNECT_RESP", "PLCI", cmsg->adr.adrPLCI);
return;
}
bcs = cs->bcs + channel - 1;
switch (cmsg->Reject) {
case 0: /* Accept */
/* drop all competing applications, keep only this one */
spin_lock_irqsave(&bcs->aplock, flags);
while (bcs->ap != NULL) {
oap = bcs->ap;
bcs->ap = oap->bcnext;
if (oap != ap) {
spin_unlock_irqrestore(&bcs->aplock, flags);
send_disconnect_ind(bcs, oap,
CapiCallGivenToOtherApplication);
spin_lock_irqsave(&bcs->aplock, flags);
}
}
ap->bcnext = NULL;
bcs->ap = ap;
spin_unlock_irqrestore(&bcs->aplock, flags);
bcs->rx_bufsize = ap->rp.datablklen;
dev_kfree_skb(bcs->rx_skb);
gigaset_new_rx_skb(bcs);
bcs->chstate |= CHS_NOTIFY_LL;
/* check/encode B channel protocol */
if (cmsg->BProtocol == CAPI_DEFAULT) {
bcs->proto2 = L2_HDLC;
dev_warn(cs->dev,
"B2 Protocol X.75 SLP unsupported, using Transparent\n");
} else {
switch (cmsg->B1protocol) {
case 0:
bcs->proto2 = L2_HDLC;
break;
case 1:
bcs->proto2 = L2_VOICE;
break;
default:
dev_warn(cs->dev,
"B1 Protocol %u unsupported, using Transparent\n",
cmsg->B1protocol);
bcs->proto2 = L2_VOICE;
}
if (cmsg->B2protocol != 1)
dev_warn(cs->dev,
"B2 Protocol %u unsupported, using Transparent\n",
cmsg->B2protocol);
if (cmsg->B3protocol != 0)
dev_warn(cs->dev,
"B3 Protocol %u unsupported, using Transparent\n",
cmsg->B3protocol);
ignore_cstruct_param(cs, cmsg->B1configuration,
"CONNECT_RESP", "B1 Configuration");
ignore_cstruct_param(cs, cmsg->B2configuration,
"CONNECT_RESP", "B2 Configuration");
ignore_cstruct_param(cs, cmsg->B3configuration,
"CONNECT_RESP", "B3 Configuration");
}
/* ToDo: check/encode remaining parameters */
ignore_cstruct_param(cs, cmsg->ConnectedNumber,
"CONNECT_RESP", "Connected Number");
ignore_cstruct_param(cs, cmsg->ConnectedSubaddress,
"CONNECT_RESP", "Connected Subaddress");
ignore_cstruct_param(cs, cmsg->LLC,
"CONNECT_RESP", "LLC");
if (cmsg->AdditionalInfo != CAPI_DEFAULT) {
ignore_cstruct_param(cs, cmsg->BChannelinformation,
"CONNECT_RESP", "BChannel Information");
ignore_cstruct_param(cs, cmsg->Keypadfacility,
"CONNECT_RESP", "Keypad Facility");
ignore_cstruct_param(cs, cmsg->Useruserdata,
"CONNECT_RESP", "User-User Data");
ignore_cstruct_param(cs, cmsg->Facilitydataarray,
"CONNECT_RESP", "Facility Data Array");
}
/* Accept call */
if (!gigaset_add_event(cs, &cs->bcs[channel - 1].at_state,
EV_ACCEPT, NULL, 0, NULL))
return;
gigaset_schedule_event(cs);
return;
case 1: /* Ignore */
/* send DISCONNECT_IND to this application */
send_disconnect_ind(bcs, ap, 0);
/* remove it from the list of listening apps */
spin_lock_irqsave(&bcs->aplock, flags);
if (bcs->ap == ap) {
bcs->ap = ap->bcnext;
if (bcs->ap == NULL) {
/* last one: stop ev-layer hupD notifications */
bcs->apconnstate = APCONN_NONE;
bcs->chstate &= ~CHS_NOTIFY_LL;
}
spin_unlock_irqrestore(&bcs->aplock, flags);
return;
}
for (oap = bcs->ap; oap != NULL; oap = oap->bcnext) {
if (oap->bcnext == ap) {
oap->bcnext = oap->bcnext->bcnext;
spin_unlock_irqrestore(&bcs->aplock, flags);
return;
}
}
spin_unlock_irqrestore(&bcs->aplock, flags);
dev_err(cs->dev, "%s: application %u not found\n",
__func__, ap->id);
return;
default: /* Reject */
/* drop all competing applications, keep only this one */
spin_lock_irqsave(&bcs->aplock, flags);
while (bcs->ap != NULL) {
oap = bcs->ap;
bcs->ap = oap->bcnext;
if (oap != ap) {
spin_unlock_irqrestore(&bcs->aplock, flags);
send_disconnect_ind(bcs, oap,
CapiCallGivenToOtherApplication);
spin_lock_irqsave(&bcs->aplock, flags);
}
}
ap->bcnext = NULL;
bcs->ap = ap;
spin_unlock_irqrestore(&bcs->aplock, flags);
/* reject call - will trigger DISCONNECT_IND for this app */
dev_info(cs->dev, "%s: Reject=%x\n",
"CONNECT_RESP", cmsg->Reject);
if (!gigaset_add_event(cs, &cs->bcs[channel - 1].at_state,
EV_HUP, NULL, 0, NULL))
return;
gigaset_schedule_event(cs);
return;
}
}
/*
* process CONNECT_B3_REQ message
* build NCCI and emit CONNECT_B3_CONF reply
*/
static void do_connect_b3_req(struct gigaset_capi_ctr *iif,
struct gigaset_capi_appl *ap,
struct sk_buff *skb)
{
struct cardstate *cs = iif->ctr.driverdata;
_cmsg *cmsg = &iif->acmsg;
struct bc_state *bcs;
int channel;
/* decode message */
capi_message2cmsg(cmsg, skb->data);
dump_cmsg(DEBUG_CMD, __func__, cmsg);
/* extract and check channel number from PLCI */
channel = (cmsg->adr.adrPLCI >> 8) & 0xff;
if (!channel || channel > cs->channels) {
dev_notice(cs->dev, "%s: invalid %s 0x%02x\n",
"CONNECT_B3_REQ", "PLCI", cmsg->adr.adrPLCI);
send_conf(iif, ap, skb, CapiIllContrPlciNcci);
return;
}
bcs = &cs->bcs[channel - 1];
/* mark logical connection active */
bcs->apconnstate = APCONN_ACTIVE;
/* build NCCI: always 1 (one B3 connection only) */
cmsg->adr.adrNCCI |= 1 << 16;
/* NCPI parameter: not applicable for B3 Transparent */
ignore_cstruct_param(cs, cmsg->NCPI, "CONNECT_B3_REQ", "NCPI");
send_conf(iif, ap, skb,
(cmsg->NCPI && cmsg->NCPI[0]) ?
CapiNcpiNotSupportedByProtocol : CapiSuccess);
}
/*
* process CONNECT_B3_RESP message
* Depending on the Reject parameter, either emit CONNECT_B3_ACTIVE_IND
* or queue EV_HUP and emit DISCONNECT_B3_IND.
* The emitted message is always shorter than the received one,
* allowing to reuse the skb.
*/
static void do_connect_b3_resp(struct gigaset_capi_ctr *iif,
struct gigaset_capi_appl *ap,
struct sk_buff *skb)
{
struct cardstate *cs = iif->ctr.driverdata;
_cmsg *cmsg = &iif->acmsg;
struct bc_state *bcs;
int channel;
unsigned int msgsize;
u8 command;
/* decode message */
capi_message2cmsg(cmsg, skb->data);
dump_cmsg(DEBUG_CMD, __func__, cmsg);
/* extract and check channel number and NCCI */
channel = (cmsg->adr.adrNCCI >> 8) & 0xff;
if (!channel || channel > cs->channels ||
((cmsg->adr.adrNCCI >> 16) & 0xffff) != 1) {
dev_notice(cs->dev, "%s: invalid %s 0x%02x\n",
"CONNECT_B3_RESP", "NCCI", cmsg->adr.adrNCCI);
dev_kfree_skb_any(skb);
return;
}
bcs = &cs->bcs[channel - 1];
if (cmsg->Reject) {
/* Reject: clear B3 connect received flag */
bcs->apconnstate = APCONN_SETUP;
/* trigger hangup, causing eventual DISCONNECT_IND */
if (!gigaset_add_event(cs, &bcs->at_state,
EV_HUP, NULL, 0, NULL)) {
dev_kfree_skb_any(skb);
return;
}
gigaset_schedule_event(cs);
/* emit DISCONNECT_B3_IND */
command = CAPI_DISCONNECT_B3;
msgsize = CAPI_DISCONNECT_B3_IND_BASELEN;
} else {
/*
* Accept: emit CONNECT_B3_ACTIVE_IND immediately, as
* we only send CONNECT_B3_IND if the B channel is up
*/
command = CAPI_CONNECT_B3_ACTIVE;
msgsize = CAPI_CONNECT_B3_ACTIVE_IND_BASELEN;
}
capi_cmsg_header(cmsg, ap->id, command, CAPI_IND,
ap->nextMessageNumber++, cmsg->adr.adrNCCI);
__skb_trim(skb, msgsize);
capi_cmsg2message(cmsg, skb->data);
dump_cmsg(DEBUG_CMD, __func__, cmsg);
capi_ctr_handle_message(&iif->ctr, ap->id, skb);
}
/*
* process DISCONNECT_REQ message
* schedule EV_HUP and emit DISCONNECT_B3_IND if necessary,
* emit DISCONNECT_CONF reply
*/
static void do_disconnect_req(struct gigaset_capi_ctr *iif,
struct gigaset_capi_appl *ap,
struct sk_buff *skb)
{
struct cardstate *cs = iif->ctr.driverdata;
_cmsg *cmsg = &iif->acmsg;
struct bc_state *bcs;
_cmsg *b3cmsg;
struct sk_buff *b3skb;
int channel;
/* decode message */
capi_message2cmsg(cmsg, skb->data);
dump_cmsg(DEBUG_CMD, __func__, cmsg);
/* extract and check channel number from PLCI */
channel = (cmsg->adr.adrPLCI >> 8) & 0xff;
if (!channel || channel > cs->channels) {
dev_notice(cs->dev, "%s: invalid %s 0x%02x\n",
"DISCONNECT_REQ", "PLCI", cmsg->adr.adrPLCI);
send_conf(iif, ap, skb, CapiIllContrPlciNcci);
return;
}
bcs = cs->bcs + channel - 1;
/* ToDo: process parameter: Additional info */
if (cmsg->AdditionalInfo != CAPI_DEFAULT) {
ignore_cstruct_param(cs, cmsg->BChannelinformation,
"DISCONNECT_REQ", "B Channel Information");
ignore_cstruct_param(cs, cmsg->Keypadfacility,
"DISCONNECT_REQ", "Keypad Facility");
ignore_cstruct_param(cs, cmsg->Useruserdata,
"DISCONNECT_REQ", "User-User Data");
ignore_cstruct_param(cs, cmsg->Facilitydataarray,
"DISCONNECT_REQ", "Facility Data Array");
}
/* skip if DISCONNECT_IND already sent */
if (!bcs->apconnstate)
return;
/* check for active logical connection */
if (bcs->apconnstate >= APCONN_ACTIVE) {
/* clear it */
bcs->apconnstate = APCONN_SETUP;
/*
* emit DISCONNECT_B3_IND with cause 0x3301
* use separate cmsg structure, as the content of iif->acmsg
* is still needed for creating the _CONF message
*/
b3cmsg = kmalloc(sizeof(*b3cmsg), GFP_KERNEL);
if (!b3cmsg) {
dev_err(cs->dev, "%s: out of memory\n", __func__);
send_conf(iif, ap, skb, CAPI_MSGOSRESOURCEERR);
return;
}
capi_cmsg_header(b3cmsg, ap->id, CAPI_DISCONNECT_B3, CAPI_IND,
ap->nextMessageNumber++,
cmsg->adr.adrPLCI | (1 << 16));
b3cmsg->Reason_B3 = CapiProtocolErrorLayer1;
b3skb = alloc_skb(CAPI_DISCONNECT_B3_IND_BASELEN, GFP_KERNEL);
if (b3skb == NULL) {
dev_err(cs->dev, "%s: out of memory\n", __func__);
send_conf(iif, ap, skb, CAPI_MSGOSRESOURCEERR);
kfree(b3cmsg);
return;
}
capi_cmsg2message(b3cmsg,
__skb_put(b3skb, CAPI_DISCONNECT_B3_IND_BASELEN));
dump_cmsg(DEBUG_CMD, __func__, b3cmsg);
kfree(b3cmsg);
capi_ctr_handle_message(&iif->ctr, ap->id, b3skb);
}
/* trigger hangup, causing eventual DISCONNECT_IND */
if (!gigaset_add_event(cs, &bcs->at_state, EV_HUP, NULL, 0, NULL)) {
send_conf(iif, ap, skb, CAPI_MSGOSRESOURCEERR);
return;
}
gigaset_schedule_event(cs);
/* emit reply */
send_conf(iif, ap, skb, CapiSuccess);
}
/*
* process DISCONNECT_B3_REQ message
* schedule EV_HUP and emit DISCONNECT_B3_CONF reply
*/
static void do_disconnect_b3_req(struct gigaset_capi_ctr *iif,
struct gigaset_capi_appl *ap,
struct sk_buff *skb)
{
struct cardstate *cs = iif->ctr.driverdata;
_cmsg *cmsg = &iif->acmsg;
struct bc_state *bcs;
int channel;
/* decode message */
capi_message2cmsg(cmsg, skb->data);
dump_cmsg(DEBUG_CMD, __func__, cmsg);
/* extract and check channel number and NCCI */
channel = (cmsg->adr.adrNCCI >> 8) & 0xff;
if (!channel || channel > cs->channels ||
((cmsg->adr.adrNCCI >> 16) & 0xffff) != 1) {
dev_notice(cs->dev, "%s: invalid %s 0x%02x\n",
"DISCONNECT_B3_REQ", "NCCI", cmsg->adr.adrNCCI);
send_conf(iif, ap, skb, CapiIllContrPlciNcci);
return;
}
bcs = &cs->bcs[channel - 1];
/* reject if logical connection not active */
if (bcs->apconnstate < APCONN_ACTIVE) {
send_conf(iif, ap, skb,
CapiMessageNotSupportedInCurrentState);
return;
}
/* trigger hangup, causing eventual DISCONNECT_B3_IND */
if (!gigaset_add_event(cs, &bcs->at_state, EV_HUP, NULL, 0, NULL)) {
send_conf(iif, ap, skb, CAPI_MSGOSRESOURCEERR);
return;
}
gigaset_schedule_event(cs);
/* NCPI parameter: not applicable for B3 Transparent */
ignore_cstruct_param(cs, cmsg->NCPI,
"DISCONNECT_B3_REQ", "NCPI");
send_conf(iif, ap, skb,
(cmsg->NCPI && cmsg->NCPI[0]) ?
CapiNcpiNotSupportedByProtocol : CapiSuccess);
}
/*
* process DATA_B3_REQ message
*/
static void do_data_b3_req(struct gigaset_capi_ctr *iif,
struct gigaset_capi_appl *ap,
struct sk_buff *skb)
{
struct cardstate *cs = iif->ctr.driverdata;
struct bc_state *bcs;
int channel = CAPIMSG_PLCI_PART(skb->data);
u16 ncci = CAPIMSG_NCCI_PART(skb->data);
u16 msglen = CAPIMSG_LEN(skb->data);
u16 datalen = CAPIMSG_DATALEN(skb->data);
u16 flags = CAPIMSG_FLAGS(skb->data);
u16 msgid = CAPIMSG_MSGID(skb->data);
u16 handle = CAPIMSG_HANDLE_REQ(skb->data);
/* frequent message, avoid _cmsg overhead */
dump_rawmsg(DEBUG_MCMD, __func__, skb->data);
/* check parameters */
if (channel == 0 || channel > cs->channels || ncci != 1) {
dev_notice(cs->dev, "%s: invalid %s 0x%02x\n",
"DATA_B3_REQ", "NCCI", CAPIMSG_NCCI(skb->data));
send_conf(iif, ap, skb, CapiIllContrPlciNcci);
return;
}
bcs = &cs->bcs[channel - 1];
if (msglen != CAPI_DATA_B3_REQ_LEN && msglen != CAPI_DATA_B3_REQ_LEN64)
dev_notice(cs->dev, "%s: unexpected length %d\n",
"DATA_B3_REQ", msglen);
if (msglen + datalen != skb->len)
dev_notice(cs->dev, "%s: length mismatch (%d+%d!=%d)\n",
"DATA_B3_REQ", msglen, datalen, skb->len);
if (msglen + datalen > skb->len) {
/* message too short for announced data length */
send_conf(iif, ap, skb, CapiIllMessageParmCoding); /* ? */
return;
}
if (flags & CAPI_FLAGS_RESERVED) {
dev_notice(cs->dev, "%s: reserved flags set (%x)\n",
"DATA_B3_REQ", flags);
send_conf(iif, ap, skb, CapiIllMessageParmCoding);
return;
}
/* reject if logical connection not active */
if (bcs->apconnstate < APCONN_ACTIVE) {
send_conf(iif, ap, skb, CapiMessageNotSupportedInCurrentState);
return;
}
/* pull CAPI message into link layer header */
skb_reset_mac_header(skb);
skb->mac_len = msglen;
skb_pull(skb, msglen);
/* pass to device-specific module */
if (cs->ops->send_skb(bcs, skb) < 0) {
send_conf(iif, ap, skb, CAPI_MSGOSRESOURCEERR);
return;
}
/*
* DATA_B3_CONF will be sent by gigaset_skb_sent() only if "delivery
* confirmation" bit is set; otherwise we have to send it now
*/
if (!(flags & CAPI_FLAGS_DELIVERY_CONFIRMATION))
send_data_b3_conf(cs, &iif->ctr, ap->id, msgid, channel, handle,
flags ? CapiFlagsNotSupportedByProtocol
: CAPI_NOERROR);
}
/*
* process RESET_B3_REQ message
* just always reply "not supported by current protocol"
*/
static void do_reset_b3_req(struct gigaset_capi_ctr *iif,
struct gigaset_capi_appl *ap,
struct sk_buff *skb)
{
/* decode message */
capi_message2cmsg(&iif->acmsg, skb->data);
dump_cmsg(DEBUG_CMD, __func__, &iif->acmsg);
send_conf(iif, ap, skb,
CapiResetProcedureNotSupportedByCurrentProtocol);
}
/*
* unsupported CAPI message handler
*/
static void do_unsupported(struct gigaset_capi_ctr *iif,
struct gigaset_capi_appl *ap,
struct sk_buff *skb)
{
/* decode message */
capi_message2cmsg(&iif->acmsg, skb->data);
dump_cmsg(DEBUG_CMD, __func__, &iif->acmsg);
send_conf(iif, ap, skb, CapiMessageNotSupportedInCurrentState);
}
/*
* CAPI message handler: no-op
*/
static void do_nothing(struct gigaset_capi_ctr *iif,
struct gigaset_capi_appl *ap,
struct sk_buff *skb)
{
/* decode message */
capi_message2cmsg(&iif->acmsg, skb->data);
dump_cmsg(DEBUG_CMD, __func__, &iif->acmsg);
dev_kfree_skb_any(skb);
}
static void do_data_b3_resp(struct gigaset_capi_ctr *iif,
struct gigaset_capi_appl *ap,
struct sk_buff *skb)
{
dump_rawmsg(DEBUG_MCMD, __func__, skb->data);
dev_kfree_skb_any(skb);
}
/* table of outgoing CAPI message handlers with lookup function */
typedef void (*capi_send_handler_t)(struct gigaset_capi_ctr *,
struct gigaset_capi_appl *,
struct sk_buff *);
static struct {
u16 cmd;
capi_send_handler_t handler;
} capi_send_handler_table[] = {
/* most frequent messages first for faster lookup */
{ CAPI_DATA_B3_REQ, do_data_b3_req },
{ CAPI_DATA_B3_RESP, do_data_b3_resp },
{ CAPI_ALERT_REQ, do_alert_req },
{ CAPI_CONNECT_ACTIVE_RESP, do_nothing },
{ CAPI_CONNECT_B3_ACTIVE_RESP, do_nothing },
{ CAPI_CONNECT_B3_REQ, do_connect_b3_req },
{ CAPI_CONNECT_B3_RESP, do_connect_b3_resp },
{ CAPI_CONNECT_B3_T90_ACTIVE_RESP, do_nothing },
{ CAPI_CONNECT_REQ, do_connect_req },
{ CAPI_CONNECT_RESP, do_connect_resp },
{ CAPI_DISCONNECT_B3_REQ, do_disconnect_b3_req },
{ CAPI_DISCONNECT_B3_RESP, do_nothing },
{ CAPI_DISCONNECT_REQ, do_disconnect_req },
{ CAPI_DISCONNECT_RESP, do_nothing },
{ CAPI_FACILITY_REQ, do_facility_req },
{ CAPI_FACILITY_RESP, do_nothing },
{ CAPI_LISTEN_REQ, do_listen_req },
{ CAPI_SELECT_B_PROTOCOL_REQ, do_unsupported },
{ CAPI_RESET_B3_REQ, do_reset_b3_req },
{ CAPI_RESET_B3_RESP, do_nothing },
/*
* ToDo: support overlap sending (requires ev-layer state
* machine extension to generate additional ATD commands)
*/
{ CAPI_INFO_REQ, do_unsupported },
{ CAPI_INFO_RESP, do_nothing },
/*
* ToDo: what's the proper response for these?
*/
{ CAPI_MANUFACTURER_REQ, do_nothing },
{ CAPI_MANUFACTURER_RESP, do_nothing },
};
/* look up handler */
static inline capi_send_handler_t lookup_capi_send_handler(const u16 cmd)
{
size_t i;
for (i = 0; i < ARRAY_SIZE(capi_send_handler_table); i++)
if (capi_send_handler_table[i].cmd == cmd)
return capi_send_handler_table[i].handler;
return NULL;
}
/**
* gigaset_send_message() - accept a CAPI message from an application
* @ctr: controller descriptor structure.
* @skb: CAPI message.
*
* Return value: CAPI error code
* Note: capidrv (and probably others, too) only uses the return value to
* decide whether it has to free the skb (only if result != CAPI_NOERROR (0))
*/
static u16 gigaset_send_message(struct capi_ctr *ctr, struct sk_buff *skb)
{
struct gigaset_capi_ctr *iif
= container_of(ctr, struct gigaset_capi_ctr, ctr);
struct cardstate *cs = ctr->driverdata;
struct gigaset_capi_appl *ap;
capi_send_handler_t handler;
/* can only handle linear sk_buffs */
if (skb_linearize(skb) < 0) {
dev_warn(cs->dev, "%s: skb_linearize failed\n", __func__);
return CAPI_MSGOSRESOURCEERR;
}
/* retrieve application data structure */
ap = get_appl(iif, CAPIMSG_APPID(skb->data));
if (!ap) {
dev_notice(cs->dev, "%s: application %u not registered\n",
__func__, CAPIMSG_APPID(skb->data));
return CAPI_ILLAPPNR;
}
/* look up command */
handler = lookup_capi_send_handler(CAPIMSG_CMD(skb->data));
if (!handler) {
/* unknown/unsupported message type */
if (printk_ratelimit())
dev_notice(cs->dev, "%s: unsupported message %u\n",
__func__, CAPIMSG_CMD(skb->data));
return CAPI_ILLCMDORSUBCMDORMSGTOSMALL;
}
/* serialize */
if (atomic_add_return(1, &iif->sendqlen) > 1) {
/* queue behind other messages */
skb_queue_tail(&iif->sendqueue, skb);
return CAPI_NOERROR;
}
/* process message */
handler(iif, ap, skb);
/* process other messages arrived in the meantime */
while (atomic_sub_return(1, &iif->sendqlen) > 0) {
skb = skb_dequeue(&iif->sendqueue);
if (!skb) {
/* should never happen */
dev_err(cs->dev, "%s: send queue empty\n", __func__);
continue;
}
ap = get_appl(iif, CAPIMSG_APPID(skb->data));
if (!ap) {
/* could that happen? */
dev_warn(cs->dev, "%s: application %u vanished\n",
__func__, CAPIMSG_APPID(skb->data));
continue;
}
handler = lookup_capi_send_handler(CAPIMSG_CMD(skb->data));
if (!handler) {
/* should never happen */
dev_err(cs->dev, "%s: handler %x vanished\n",
__func__, CAPIMSG_CMD(skb->data));
continue;
}
handler(iif, ap, skb);
}
return CAPI_NOERROR;
}
/**
* gigaset_procinfo() - build single line description for controller
* @ctr: controller descriptor structure.
*
* Return value: pointer to generated string (null terminated)
*/
static char *gigaset_procinfo(struct capi_ctr *ctr)
{
return ctr->name; /* ToDo: more? */
}
static int gigaset_proc_show(struct seq_file *m, void *v)
{
struct capi_ctr *ctr = m->private;
struct cardstate *cs = ctr->driverdata;
char *s;
int i;
seq_printf(m, "%-16s %s\n", "name", ctr->name);
seq_printf(m, "%-16s %s %s\n", "dev",
dev_driver_string(cs->dev), dev_name(cs->dev));
seq_printf(m, "%-16s %d\n", "id", cs->myid);
if (cs->gotfwver)
seq_printf(m, "%-16s %d.%d.%d.%d\n", "firmware",
cs->fwver[0], cs->fwver[1], cs->fwver[2], cs->fwver[3]);
seq_printf(m, "%-16s %d\n", "channels", cs->channels);
seq_printf(m, "%-16s %s\n", "onechannel", cs->onechannel ? "yes" : "no");
switch (cs->mode) {
case M_UNKNOWN:
s = "unknown";
break;
case M_CONFIG:
s = "config";
break;
case M_UNIMODEM:
s = "Unimodem";
break;
case M_CID:
s = "CID";
break;
default:
s = "??";
}
seq_printf(m, "%-16s %s\n", "mode", s);
switch (cs->mstate) {
case MS_UNINITIALIZED:
s = "uninitialized";
break;
case MS_INIT:
s = "init";
break;
case MS_LOCKED:
s = "locked";
break;
case MS_SHUTDOWN:
s = "shutdown";
break;
case MS_RECOVER:
s = "recover";
break;
case MS_READY:
s = "ready";
break;
default:
s = "??";
}
seq_printf(m, "%-16s %s\n", "mstate", s);
seq_printf(m, "%-16s %s\n", "running", cs->running ? "yes" : "no");
seq_printf(m, "%-16s %s\n", "connected", cs->connected ? "yes" : "no");
seq_printf(m, "%-16s %s\n", "isdn_up", cs->isdn_up ? "yes" : "no");
seq_printf(m, "%-16s %s\n", "cidmode", cs->cidmode ? "yes" : "no");
for (i = 0; i < cs->channels; i++) {
seq_printf(m, "[%d]%-13s %d\n", i, "corrupted",
cs->bcs[i].corrupted);
seq_printf(m, "[%d]%-13s %d\n", i, "trans_down",
cs->bcs[i].trans_down);
seq_printf(m, "[%d]%-13s %d\n", i, "trans_up",
cs->bcs[i].trans_up);
seq_printf(m, "[%d]%-13s %d\n", i, "chstate",
cs->bcs[i].chstate);
switch (cs->bcs[i].proto2) {
case L2_BITSYNC:
s = "bitsync";
break;
case L2_HDLC:
s = "HDLC";
break;
case L2_VOICE:
s = "voice";
break;
default:
s = "??";
}
seq_printf(m, "[%d]%-13s %s\n", i, "proto2", s);
}
return 0;
}
static int gigaset_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, gigaset_proc_show, PDE_DATA(inode));
}
static const struct file_operations gigaset_proc_fops = {
.owner = THIS_MODULE,
.open = gigaset_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
/**
* gigaset_isdn_regdev() - register device to LL
* @cs: device descriptor structure.
* @isdnid: device name.
*
* Return value: 0 on success, error code < 0 on failure
*/
int gigaset_isdn_regdev(struct cardstate *cs, const char *isdnid)
{
struct gigaset_capi_ctr *iif;
int rc;
iif = kmalloc(sizeof(*iif), GFP_KERNEL);
if (!iif) {
pr_err("%s: out of memory\n", __func__);
return -ENOMEM;
}
/* prepare controller structure */
iif->ctr.owner = THIS_MODULE;
iif->ctr.driverdata = cs;
strncpy(iif->ctr.name, isdnid, sizeof(iif->ctr.name));
iif->ctr.driver_name = "gigaset";
iif->ctr.load_firmware = NULL;
iif->ctr.reset_ctr = NULL;
iif->ctr.register_appl = gigaset_register_appl;
iif->ctr.release_appl = gigaset_release_appl;
iif->ctr.send_message = gigaset_send_message;
iif->ctr.procinfo = gigaset_procinfo;
iif->ctr.proc_fops = &gigaset_proc_fops;
INIT_LIST_HEAD(&iif->appls);
skb_queue_head_init(&iif->sendqueue);
atomic_set(&iif->sendqlen, 0);
/* register controller with CAPI */
rc = attach_capi_ctr(&iif->ctr);
if (rc) {
pr_err("attach_capi_ctr failed (%d)\n", rc);
kfree(iif);
return rc;
}
cs->iif = iif;
cs->hw_hdr_len = CAPI_DATA_B3_REQ_LEN;
return 0;
}
/**
* gigaset_isdn_unregdev() - unregister device from LL
* @cs: device descriptor structure.
*/
void gigaset_isdn_unregdev(struct cardstate *cs)
{
struct gigaset_capi_ctr *iif = cs->iif;
detach_capi_ctr(&iif->ctr);
kfree(iif);
cs->iif = NULL;
}
static struct capi_driver capi_driver_gigaset = {
.name = "gigaset",
.revision = "1.0",
};
/**
* gigaset_isdn_regdrv() - register driver to LL
*/
void gigaset_isdn_regdrv(void)
{
pr_info("Kernel CAPI interface\n");
register_capi_driver(&capi_driver_gigaset);
}
/**
* gigaset_isdn_unregdrv() - unregister driver from LL
*/
void gigaset_isdn_unregdrv(void)
{
unregister_capi_driver(&capi_driver_gigaset);
}
| gpl-2.0 |
sakuramilk/sc06d_kernel_ics | sound/soc/codecs/wm8971.c | 3024 | 22907 | /*
* wm8971.c -- WM8971 ALSA SoC Audio driver
*
* Copyright 2005 Lab126, Inc.
*
* Author: Kenneth Kiraly <kiraly@lab126.com>
*
* Based on wm8753.c by Liam Girdwood
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/pm.h>
#include <linux/i2c.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/initval.h>
#include "wm8971.h"
#define WM8971_REG_COUNT 43
static struct workqueue_struct *wm8971_workq = NULL;
/* codec private data */
struct wm8971_priv {
enum snd_soc_control_type control_type;
unsigned int sysclk;
};
/*
* wm8971 register cache
* We can't read the WM8971 register space when we
* are using 2 wire for device control, so we cache them instead.
*/
static const u16 wm8971_reg[] = {
0x0097, 0x0097, 0x0079, 0x0079, /* 0 */
0x0000, 0x0008, 0x0000, 0x000a, /* 4 */
0x0000, 0x0000, 0x00ff, 0x00ff, /* 8 */
0x000f, 0x000f, 0x0000, 0x0000, /* 12 */
0x0000, 0x007b, 0x0000, 0x0032, /* 16 */
0x0000, 0x00c3, 0x00c3, 0x00c0, /* 20 */
0x0000, 0x0000, 0x0000, 0x0000, /* 24 */
0x0000, 0x0000, 0x0000, 0x0000, /* 28 */
0x0000, 0x0000, 0x0050, 0x0050, /* 32 */
0x0050, 0x0050, 0x0050, 0x0050, /* 36 */
0x0079, 0x0079, 0x0079, /* 40 */
};
#define wm8971_reset(c) snd_soc_write(c, WM8971_RESET, 0)
/* WM8971 Controls */
static const char *wm8971_bass[] = { "Linear Control", "Adaptive Boost" };
static const char *wm8971_bass_filter[] = { "130Hz @ 48kHz",
"200Hz @ 48kHz" };
static const char *wm8971_treble[] = { "8kHz", "4kHz" };
static const char *wm8971_alc_func[] = { "Off", "Right", "Left", "Stereo" };
static const char *wm8971_ng_type[] = { "Constant PGA Gain",
"Mute ADC Output" };
static const char *wm8971_deemp[] = { "None", "32kHz", "44.1kHz", "48kHz" };
static const char *wm8971_mono_mux[] = {"Stereo", "Mono (Left)",
"Mono (Right)", "Digital Mono"};
static const char *wm8971_dac_phase[] = { "Non Inverted", "Inverted" };
static const char *wm8971_lline_mux[] = {"Line", "NC", "NC", "PGA",
"Differential"};
static const char *wm8971_rline_mux[] = {"Line", "Mic", "NC", "PGA",
"Differential"};
static const char *wm8971_lpga_sel[] = {"Line", "NC", "NC", "Differential"};
static const char *wm8971_rpga_sel[] = {"Line", "Mic", "NC", "Differential"};
static const char *wm8971_adcpol[] = {"Normal", "L Invert", "R Invert",
"L + R Invert"};
static const struct soc_enum wm8971_enum[] = {
SOC_ENUM_SINGLE(WM8971_BASS, 7, 2, wm8971_bass), /* 0 */
SOC_ENUM_SINGLE(WM8971_BASS, 6, 2, wm8971_bass_filter),
SOC_ENUM_SINGLE(WM8971_TREBLE, 6, 2, wm8971_treble),
SOC_ENUM_SINGLE(WM8971_ALC1, 7, 4, wm8971_alc_func),
SOC_ENUM_SINGLE(WM8971_NGATE, 1, 2, wm8971_ng_type), /* 4 */
SOC_ENUM_SINGLE(WM8971_ADCDAC, 1, 4, wm8971_deemp),
SOC_ENUM_SINGLE(WM8971_ADCTL1, 4, 4, wm8971_mono_mux),
SOC_ENUM_SINGLE(WM8971_ADCTL1, 1, 2, wm8971_dac_phase),
SOC_ENUM_SINGLE(WM8971_LOUTM1, 0, 5, wm8971_lline_mux), /* 8 */
SOC_ENUM_SINGLE(WM8971_ROUTM1, 0, 5, wm8971_rline_mux),
SOC_ENUM_SINGLE(WM8971_LADCIN, 6, 4, wm8971_lpga_sel),
SOC_ENUM_SINGLE(WM8971_RADCIN, 6, 4, wm8971_rpga_sel),
SOC_ENUM_SINGLE(WM8971_ADCDAC, 5, 4, wm8971_adcpol), /* 12 */
SOC_ENUM_SINGLE(WM8971_ADCIN, 6, 4, wm8971_mono_mux),
};
static const struct snd_kcontrol_new wm8971_snd_controls[] = {
SOC_DOUBLE_R("Capture Volume", WM8971_LINVOL, WM8971_RINVOL, 0, 63, 0),
SOC_DOUBLE_R("Capture ZC Switch", WM8971_LINVOL, WM8971_RINVOL,
6, 1, 0),
SOC_DOUBLE_R("Capture Switch", WM8971_LINVOL, WM8971_RINVOL, 7, 1, 1),
SOC_DOUBLE_R("Headphone Playback ZC Switch", WM8971_LOUT1V,
WM8971_ROUT1V, 7, 1, 0),
SOC_DOUBLE_R("Speaker Playback ZC Switch", WM8971_LOUT2V,
WM8971_ROUT2V, 7, 1, 0),
SOC_SINGLE("Mono Playback ZC Switch", WM8971_MOUTV, 7, 1, 0),
SOC_DOUBLE_R("PCM Volume", WM8971_LDAC, WM8971_RDAC, 0, 255, 0),
SOC_DOUBLE_R("Bypass Left Playback Volume", WM8971_LOUTM1,
WM8971_LOUTM2, 4, 7, 1),
SOC_DOUBLE_R("Bypass Right Playback Volume", WM8971_ROUTM1,
WM8971_ROUTM2, 4, 7, 1),
SOC_DOUBLE_R("Bypass Mono Playback Volume", WM8971_MOUTM1,
WM8971_MOUTM2, 4, 7, 1),
SOC_DOUBLE_R("Headphone Playback Volume", WM8971_LOUT1V,
WM8971_ROUT1V, 0, 127, 0),
SOC_DOUBLE_R("Speaker Playback Volume", WM8971_LOUT2V,
WM8971_ROUT2V, 0, 127, 0),
SOC_ENUM("Bass Boost", wm8971_enum[0]),
SOC_ENUM("Bass Filter", wm8971_enum[1]),
SOC_SINGLE("Bass Volume", WM8971_BASS, 0, 7, 1),
SOC_SINGLE("Treble Volume", WM8971_TREBLE, 0, 7, 0),
SOC_ENUM("Treble Cut-off", wm8971_enum[2]),
SOC_SINGLE("Capture Filter Switch", WM8971_ADCDAC, 0, 1, 1),
SOC_SINGLE("ALC Target Volume", WM8971_ALC1, 0, 7, 0),
SOC_SINGLE("ALC Max Volume", WM8971_ALC1, 4, 7, 0),
SOC_SINGLE("ALC Capture Target Volume", WM8971_ALC1, 0, 7, 0),
SOC_SINGLE("ALC Capture Max Volume", WM8971_ALC1, 4, 7, 0),
SOC_ENUM("ALC Capture Function", wm8971_enum[3]),
SOC_SINGLE("ALC Capture ZC Switch", WM8971_ALC2, 7, 1, 0),
SOC_SINGLE("ALC Capture Hold Time", WM8971_ALC2, 0, 15, 0),
SOC_SINGLE("ALC Capture Decay Time", WM8971_ALC3, 4, 15, 0),
SOC_SINGLE("ALC Capture Attack Time", WM8971_ALC3, 0, 15, 0),
SOC_SINGLE("ALC Capture NG Threshold", WM8971_NGATE, 3, 31, 0),
SOC_ENUM("ALC Capture NG Type", wm8971_enum[4]),
SOC_SINGLE("ALC Capture NG Switch", WM8971_NGATE, 0, 1, 0),
SOC_SINGLE("Capture 6dB Attenuate", WM8971_ADCDAC, 8, 1, 0),
SOC_SINGLE("Playback 6dB Attenuate", WM8971_ADCDAC, 7, 1, 0),
SOC_ENUM("Playback De-emphasis", wm8971_enum[5]),
SOC_ENUM("Playback Function", wm8971_enum[6]),
SOC_ENUM("Playback Phase", wm8971_enum[7]),
SOC_DOUBLE_R("Mic Boost", WM8971_LADCIN, WM8971_RADCIN, 4, 3, 0),
};
/*
* DAPM Controls
*/
/* Left Mixer */
static const struct snd_kcontrol_new wm8971_left_mixer_controls[] = {
SOC_DAPM_SINGLE("Playback Switch", WM8971_LOUTM1, 8, 1, 0),
SOC_DAPM_SINGLE("Left Bypass Switch", WM8971_LOUTM1, 7, 1, 0),
SOC_DAPM_SINGLE("Right Playback Switch", WM8971_LOUTM2, 8, 1, 0),
SOC_DAPM_SINGLE("Right Bypass Switch", WM8971_LOUTM2, 7, 1, 0),
};
/* Right Mixer */
static const struct snd_kcontrol_new wm8971_right_mixer_controls[] = {
SOC_DAPM_SINGLE("Left Playback Switch", WM8971_ROUTM1, 8, 1, 0),
SOC_DAPM_SINGLE("Left Bypass Switch", WM8971_ROUTM1, 7, 1, 0),
SOC_DAPM_SINGLE("Playback Switch", WM8971_ROUTM2, 8, 1, 0),
SOC_DAPM_SINGLE("Right Bypass Switch", WM8971_ROUTM2, 7, 1, 0),
};
/* Mono Mixer */
static const struct snd_kcontrol_new wm8971_mono_mixer_controls[] = {
SOC_DAPM_SINGLE("Left Playback Switch", WM8971_MOUTM1, 8, 1, 0),
SOC_DAPM_SINGLE("Left Bypass Switch", WM8971_MOUTM1, 7, 1, 0),
SOC_DAPM_SINGLE("Right Playback Switch", WM8971_MOUTM2, 8, 1, 0),
SOC_DAPM_SINGLE("Right Bypass Switch", WM8971_MOUTM2, 7, 1, 0),
};
/* Left Line Mux */
static const struct snd_kcontrol_new wm8971_left_line_controls =
SOC_DAPM_ENUM("Route", wm8971_enum[8]);
/* Right Line Mux */
static const struct snd_kcontrol_new wm8971_right_line_controls =
SOC_DAPM_ENUM("Route", wm8971_enum[9]);
/* Left PGA Mux */
static const struct snd_kcontrol_new wm8971_left_pga_controls =
SOC_DAPM_ENUM("Route", wm8971_enum[10]);
/* Right PGA Mux */
static const struct snd_kcontrol_new wm8971_right_pga_controls =
SOC_DAPM_ENUM("Route", wm8971_enum[11]);
/* Mono ADC Mux */
static const struct snd_kcontrol_new wm8971_monomux_controls =
SOC_DAPM_ENUM("Route", wm8971_enum[13]);
static const struct snd_soc_dapm_widget wm8971_dapm_widgets[] = {
SND_SOC_DAPM_MIXER("Left Mixer", SND_SOC_NOPM, 0, 0,
&wm8971_left_mixer_controls[0],
ARRAY_SIZE(wm8971_left_mixer_controls)),
SND_SOC_DAPM_MIXER("Right Mixer", SND_SOC_NOPM, 0, 0,
&wm8971_right_mixer_controls[0],
ARRAY_SIZE(wm8971_right_mixer_controls)),
SND_SOC_DAPM_MIXER("Mono Mixer", WM8971_PWR2, 2, 0,
&wm8971_mono_mixer_controls[0],
ARRAY_SIZE(wm8971_mono_mixer_controls)),
SND_SOC_DAPM_PGA("Right Out 2", WM8971_PWR2, 3, 0, NULL, 0),
SND_SOC_DAPM_PGA("Left Out 2", WM8971_PWR2, 4, 0, NULL, 0),
SND_SOC_DAPM_PGA("Right Out 1", WM8971_PWR2, 5, 0, NULL, 0),
SND_SOC_DAPM_PGA("Left Out 1", WM8971_PWR2, 6, 0, NULL, 0),
SND_SOC_DAPM_DAC("Right DAC", "Right Playback", WM8971_PWR2, 7, 0),
SND_SOC_DAPM_DAC("Left DAC", "Left Playback", WM8971_PWR2, 8, 0),
SND_SOC_DAPM_PGA("Mono Out 1", WM8971_PWR2, 2, 0, NULL, 0),
SND_SOC_DAPM_MICBIAS("Mic Bias", WM8971_PWR1, 1, 0),
SND_SOC_DAPM_ADC("Right ADC", "Right Capture", WM8971_PWR1, 2, 0),
SND_SOC_DAPM_ADC("Left ADC", "Left Capture", WM8971_PWR1, 3, 0),
SND_SOC_DAPM_MUX("Left PGA Mux", WM8971_PWR1, 5, 0,
&wm8971_left_pga_controls),
SND_SOC_DAPM_MUX("Right PGA Mux", WM8971_PWR1, 4, 0,
&wm8971_right_pga_controls),
SND_SOC_DAPM_MUX("Left Line Mux", SND_SOC_NOPM, 0, 0,
&wm8971_left_line_controls),
SND_SOC_DAPM_MUX("Right Line Mux", SND_SOC_NOPM, 0, 0,
&wm8971_right_line_controls),
SND_SOC_DAPM_MUX("Left ADC Mux", SND_SOC_NOPM, 0, 0,
&wm8971_monomux_controls),
SND_SOC_DAPM_MUX("Right ADC Mux", SND_SOC_NOPM, 0, 0,
&wm8971_monomux_controls),
SND_SOC_DAPM_OUTPUT("LOUT1"),
SND_SOC_DAPM_OUTPUT("ROUT1"),
SND_SOC_DAPM_OUTPUT("LOUT2"),
SND_SOC_DAPM_OUTPUT("ROUT2"),
SND_SOC_DAPM_OUTPUT("MONO"),
SND_SOC_DAPM_INPUT("LINPUT1"),
SND_SOC_DAPM_INPUT("RINPUT1"),
SND_SOC_DAPM_INPUT("MIC"),
};
static const struct snd_soc_dapm_route audio_map[] = {
/* left mixer */
{"Left Mixer", "Playback Switch", "Left DAC"},
{"Left Mixer", "Left Bypass Switch", "Left Line Mux"},
{"Left Mixer", "Right Playback Switch", "Right DAC"},
{"Left Mixer", "Right Bypass Switch", "Right Line Mux"},
/* right mixer */
{"Right Mixer", "Left Playback Switch", "Left DAC"},
{"Right Mixer", "Left Bypass Switch", "Left Line Mux"},
{"Right Mixer", "Playback Switch", "Right DAC"},
{"Right Mixer", "Right Bypass Switch", "Right Line Mux"},
/* left out 1 */
{"Left Out 1", NULL, "Left Mixer"},
{"LOUT1", NULL, "Left Out 1"},
/* left out 2 */
{"Left Out 2", NULL, "Left Mixer"},
{"LOUT2", NULL, "Left Out 2"},
/* right out 1 */
{"Right Out 1", NULL, "Right Mixer"},
{"ROUT1", NULL, "Right Out 1"},
/* right out 2 */
{"Right Out 2", NULL, "Right Mixer"},
{"ROUT2", NULL, "Right Out 2"},
/* mono mixer */
{"Mono Mixer", "Left Playback Switch", "Left DAC"},
{"Mono Mixer", "Left Bypass Switch", "Left Line Mux"},
{"Mono Mixer", "Right Playback Switch", "Right DAC"},
{"Mono Mixer", "Right Bypass Switch", "Right Line Mux"},
/* mono out */
{"Mono Out", NULL, "Mono Mixer"},
{"MONO1", NULL, "Mono Out"},
/* Left Line Mux */
{"Left Line Mux", "Line", "LINPUT1"},
{"Left Line Mux", "PGA", "Left PGA Mux"},
{"Left Line Mux", "Differential", "Differential Mux"},
/* Right Line Mux */
{"Right Line Mux", "Line", "RINPUT1"},
{"Right Line Mux", "Mic", "MIC"},
{"Right Line Mux", "PGA", "Right PGA Mux"},
{"Right Line Mux", "Differential", "Differential Mux"},
/* Left PGA Mux */
{"Left PGA Mux", "Line", "LINPUT1"},
{"Left PGA Mux", "Differential", "Differential Mux"},
/* Right PGA Mux */
{"Right PGA Mux", "Line", "RINPUT1"},
{"Right PGA Mux", "Differential", "Differential Mux"},
/* Differential Mux */
{"Differential Mux", "Line", "LINPUT1"},
{"Differential Mux", "Line", "RINPUT1"},
/* Left ADC Mux */
{"Left ADC Mux", "Stereo", "Left PGA Mux"},
{"Left ADC Mux", "Mono (Left)", "Left PGA Mux"},
{"Left ADC Mux", "Digital Mono", "Left PGA Mux"},
/* Right ADC Mux */
{"Right ADC Mux", "Stereo", "Right PGA Mux"},
{"Right ADC Mux", "Mono (Right)", "Right PGA Mux"},
{"Right ADC Mux", "Digital Mono", "Right PGA Mux"},
/* ADC */
{"Left ADC", NULL, "Left ADC Mux"},
{"Right ADC", NULL, "Right ADC Mux"},
};
static int wm8971_add_widgets(struct snd_soc_codec *codec)
{
struct snd_soc_dapm_context *dapm = &codec->dapm;
snd_soc_dapm_new_controls(dapm, wm8971_dapm_widgets,
ARRAY_SIZE(wm8971_dapm_widgets));
snd_soc_dapm_add_routes(dapm, audio_map, ARRAY_SIZE(audio_map));
return 0;
}
struct _coeff_div {
u32 mclk;
u32 rate;
u16 fs;
u8 sr:5;
u8 usb:1;
};
/* codec hifi mclk clock divider coefficients */
static const struct _coeff_div coeff_div[] = {
/* 8k */
{12288000, 8000, 1536, 0x6, 0x0},
{11289600, 8000, 1408, 0x16, 0x0},
{18432000, 8000, 2304, 0x7, 0x0},
{16934400, 8000, 2112, 0x17, 0x0},
{12000000, 8000, 1500, 0x6, 0x1},
/* 11.025k */
{11289600, 11025, 1024, 0x18, 0x0},
{16934400, 11025, 1536, 0x19, 0x0},
{12000000, 11025, 1088, 0x19, 0x1},
/* 16k */
{12288000, 16000, 768, 0xa, 0x0},
{18432000, 16000, 1152, 0xb, 0x0},
{12000000, 16000, 750, 0xa, 0x1},
/* 22.05k */
{11289600, 22050, 512, 0x1a, 0x0},
{16934400, 22050, 768, 0x1b, 0x0},
{12000000, 22050, 544, 0x1b, 0x1},
/* 32k */
{12288000, 32000, 384, 0xc, 0x0},
{18432000, 32000, 576, 0xd, 0x0},
{12000000, 32000, 375, 0xa, 0x1},
/* 44.1k */
{11289600, 44100, 256, 0x10, 0x0},
{16934400, 44100, 384, 0x11, 0x0},
{12000000, 44100, 272, 0x11, 0x1},
/* 48k */
{12288000, 48000, 256, 0x0, 0x0},
{18432000, 48000, 384, 0x1, 0x0},
{12000000, 48000, 250, 0x0, 0x1},
/* 88.2k */
{11289600, 88200, 128, 0x1e, 0x0},
{16934400, 88200, 192, 0x1f, 0x0},
{12000000, 88200, 136, 0x1f, 0x1},
/* 96k */
{12288000, 96000, 128, 0xe, 0x0},
{18432000, 96000, 192, 0xf, 0x0},
{12000000, 96000, 125, 0xe, 0x1},
};
static int get_coeff(int mclk, int rate)
{
int i;
for (i = 0; i < ARRAY_SIZE(coeff_div); i++) {
if (coeff_div[i].rate == rate && coeff_div[i].mclk == mclk)
return i;
}
return -EINVAL;
}
static int wm8971_set_dai_sysclk(struct snd_soc_dai *codec_dai,
int clk_id, unsigned int freq, int dir)
{
struct snd_soc_codec *codec = codec_dai->codec;
struct wm8971_priv *wm8971 = snd_soc_codec_get_drvdata(codec);
switch (freq) {
case 11289600:
case 12000000:
case 12288000:
case 16934400:
case 18432000:
wm8971->sysclk = freq;
return 0;
}
return -EINVAL;
}
static int wm8971_set_dai_fmt(struct snd_soc_dai *codec_dai,
unsigned int fmt)
{
struct snd_soc_codec *codec = codec_dai->codec;
u16 iface = 0;
/* set master/slave audio interface */
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM:
iface = 0x0040;
break;
case SND_SOC_DAIFMT_CBS_CFS:
break;
default:
return -EINVAL;
}
/* interface format */
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
iface |= 0x0002;
break;
case SND_SOC_DAIFMT_RIGHT_J:
break;
case SND_SOC_DAIFMT_LEFT_J:
iface |= 0x0001;
break;
case SND_SOC_DAIFMT_DSP_A:
iface |= 0x0003;
break;
case SND_SOC_DAIFMT_DSP_B:
iface |= 0x0013;
break;
default:
return -EINVAL;
}
/* clock inversion */
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
break;
case SND_SOC_DAIFMT_IB_IF:
iface |= 0x0090;
break;
case SND_SOC_DAIFMT_IB_NF:
iface |= 0x0080;
break;
case SND_SOC_DAIFMT_NB_IF:
iface |= 0x0010;
break;
default:
return -EINVAL;
}
snd_soc_write(codec, WM8971_IFACE, iface);
return 0;
}
static int wm8971_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_codec *codec = rtd->codec;
struct wm8971_priv *wm8971 = snd_soc_codec_get_drvdata(codec);
u16 iface = snd_soc_read(codec, WM8971_IFACE) & 0x1f3;
u16 srate = snd_soc_read(codec, WM8971_SRATE) & 0x1c0;
int coeff = get_coeff(wm8971->sysclk, params_rate(params));
/* bit size */
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
break;
case SNDRV_PCM_FORMAT_S20_3LE:
iface |= 0x0004;
break;
case SNDRV_PCM_FORMAT_S24_LE:
iface |= 0x0008;
break;
case SNDRV_PCM_FORMAT_S32_LE:
iface |= 0x000c;
break;
}
/* set iface & srate */
snd_soc_write(codec, WM8971_IFACE, iface);
if (coeff >= 0)
snd_soc_write(codec, WM8971_SRATE, srate |
(coeff_div[coeff].sr << 1) | coeff_div[coeff].usb);
return 0;
}
static int wm8971_mute(struct snd_soc_dai *dai, int mute)
{
struct snd_soc_codec *codec = dai->codec;
u16 mute_reg = snd_soc_read(codec, WM8971_ADCDAC) & 0xfff7;
if (mute)
snd_soc_write(codec, WM8971_ADCDAC, mute_reg | 0x8);
else
snd_soc_write(codec, WM8971_ADCDAC, mute_reg);
return 0;
}
static int wm8971_set_bias_level(struct snd_soc_codec *codec,
enum snd_soc_bias_level level)
{
u16 pwr_reg = snd_soc_read(codec, WM8971_PWR1) & 0xfe3e;
switch (level) {
case SND_SOC_BIAS_ON:
/* set vmid to 50k and unmute dac */
snd_soc_write(codec, WM8971_PWR1, pwr_reg | 0x00c1);
break;
case SND_SOC_BIAS_PREPARE:
break;
case SND_SOC_BIAS_STANDBY:
/* mute dac and set vmid to 500k, enable VREF */
snd_soc_write(codec, WM8971_PWR1, pwr_reg | 0x0140);
break;
case SND_SOC_BIAS_OFF:
snd_soc_write(codec, WM8971_PWR1, 0x0001);
break;
}
codec->dapm.bias_level = level;
return 0;
}
#define WM8971_RATES (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_11025 |\
SNDRV_PCM_RATE_16000 | SNDRV_PCM_RATE_22050 | SNDRV_PCM_RATE_44100 | \
SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_88200 | SNDRV_PCM_RATE_96000)
#define WM8971_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE |\
SNDRV_PCM_FMTBIT_S24_LE)
static struct snd_soc_dai_ops wm8971_dai_ops = {
.hw_params = wm8971_pcm_hw_params,
.digital_mute = wm8971_mute,
.set_fmt = wm8971_set_dai_fmt,
.set_sysclk = wm8971_set_dai_sysclk,
};
static struct snd_soc_dai_driver wm8971_dai = {
.name = "wm8971-hifi",
.playback = {
.stream_name = "Playback",
.channels_min = 1,
.channels_max = 2,
.rates = WM8971_RATES,
.formats = WM8971_FORMATS,},
.capture = {
.stream_name = "Capture",
.channels_min = 1,
.channels_max = 2,
.rates = WM8971_RATES,
.formats = WM8971_FORMATS,},
.ops = &wm8971_dai_ops,
};
static void wm8971_work(struct work_struct *work)
{
struct snd_soc_dapm_context *dapm =
container_of(work, struct snd_soc_dapm_context,
delayed_work.work);
struct snd_soc_codec *codec = dapm->codec;
wm8971_set_bias_level(codec, codec->dapm.bias_level);
}
static int wm8971_suspend(struct snd_soc_codec *codec, pm_message_t state)
{
wm8971_set_bias_level(codec, SND_SOC_BIAS_OFF);
return 0;
}
static int wm8971_resume(struct snd_soc_codec *codec)
{
int i;
u8 data[2];
u16 *cache = codec->reg_cache;
u16 reg;
/* Sync reg_cache with the hardware */
for (i = 0; i < ARRAY_SIZE(wm8971_reg); i++) {
if (i + 1 == WM8971_RESET)
continue;
data[0] = (i << 1) | ((cache[i] >> 8) & 0x0001);
data[1] = cache[i] & 0x00ff;
codec->hw_write(codec->control_data, data, 2);
}
wm8971_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
/* charge wm8971 caps */
if (codec->dapm.suspend_bias_level == SND_SOC_BIAS_ON) {
reg = snd_soc_read(codec, WM8971_PWR1) & 0xfe3e;
snd_soc_write(codec, WM8971_PWR1, reg | 0x01c0);
codec->dapm.bias_level = SND_SOC_BIAS_ON;
queue_delayed_work(wm8971_workq, &codec->dapm.delayed_work,
msecs_to_jiffies(1000));
}
return 0;
}
static int wm8971_probe(struct snd_soc_codec *codec)
{
struct wm8971_priv *wm8971 = snd_soc_codec_get_drvdata(codec);
int ret = 0;
u16 reg;
ret = snd_soc_codec_set_cache_io(codec, 7, 9, wm8971->control_type);
if (ret < 0) {
printk(KERN_ERR "wm8971: failed to set cache I/O: %d\n", ret);
return ret;
}
INIT_DELAYED_WORK(&codec->dapm.delayed_work, wm8971_work);
wm8971_workq = create_workqueue("wm8971");
if (wm8971_workq == NULL)
return -ENOMEM;
wm8971_reset(codec);
/* charge output caps - set vmid to 5k for quick power up */
reg = snd_soc_read(codec, WM8971_PWR1) & 0xfe3e;
snd_soc_write(codec, WM8971_PWR1, reg | 0x01c0);
codec->dapm.bias_level = SND_SOC_BIAS_STANDBY;
queue_delayed_work(wm8971_workq, &codec->dapm.delayed_work,
msecs_to_jiffies(1000));
/* set the update bits */
reg = snd_soc_read(codec, WM8971_LDAC);
snd_soc_write(codec, WM8971_LDAC, reg | 0x0100);
reg = snd_soc_read(codec, WM8971_RDAC);
snd_soc_write(codec, WM8971_RDAC, reg | 0x0100);
reg = snd_soc_read(codec, WM8971_LOUT1V);
snd_soc_write(codec, WM8971_LOUT1V, reg | 0x0100);
reg = snd_soc_read(codec, WM8971_ROUT1V);
snd_soc_write(codec, WM8971_ROUT1V, reg | 0x0100);
reg = snd_soc_read(codec, WM8971_LOUT2V);
snd_soc_write(codec, WM8971_LOUT2V, reg | 0x0100);
reg = snd_soc_read(codec, WM8971_ROUT2V);
snd_soc_write(codec, WM8971_ROUT2V, reg | 0x0100);
reg = snd_soc_read(codec, WM8971_LINVOL);
snd_soc_write(codec, WM8971_LINVOL, reg | 0x0100);
reg = snd_soc_read(codec, WM8971_RINVOL);
snd_soc_write(codec, WM8971_RINVOL, reg | 0x0100);
snd_soc_add_controls(codec, wm8971_snd_controls,
ARRAY_SIZE(wm8971_snd_controls));
wm8971_add_widgets(codec);
return ret;
}
/* power down chip */
static int wm8971_remove(struct snd_soc_codec *codec)
{
wm8971_set_bias_level(codec, SND_SOC_BIAS_OFF);
if (wm8971_workq)
destroy_workqueue(wm8971_workq);
return 0;
}
static struct snd_soc_codec_driver soc_codec_dev_wm8971 = {
.probe = wm8971_probe,
.remove = wm8971_remove,
.suspend = wm8971_suspend,
.resume = wm8971_resume,
.set_bias_level = wm8971_set_bias_level,
.reg_cache_size = ARRAY_SIZE(wm8971_reg),
.reg_word_size = sizeof(u16),
.reg_cache_default = wm8971_reg,
};
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
static __devinit int wm8971_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct wm8971_priv *wm8971;
int ret;
wm8971 = kzalloc(sizeof(struct wm8971_priv), GFP_KERNEL);
if (wm8971 == NULL)
return -ENOMEM;
wm8971->control_type = SND_SOC_I2C;
i2c_set_clientdata(i2c, wm8971);
ret = snd_soc_register_codec(&i2c->dev,
&soc_codec_dev_wm8971, &wm8971_dai, 1);
if (ret < 0)
kfree(wm8971);
return ret;
}
static __devexit int wm8971_i2c_remove(struct i2c_client *client)
{
snd_soc_unregister_codec(&client->dev);
kfree(i2c_get_clientdata(client));
return 0;
}
static const struct i2c_device_id wm8971_i2c_id[] = {
{ "wm8971", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, wm8971_i2c_id);
static struct i2c_driver wm8971_i2c_driver = {
.driver = {
.name = "wm8971-codec",
.owner = THIS_MODULE,
},
.probe = wm8971_i2c_probe,
.remove = __devexit_p(wm8971_i2c_remove),
.id_table = wm8971_i2c_id,
};
#endif
static int __init wm8971_modinit(void)
{
int ret = 0;
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
ret = i2c_add_driver(&wm8971_i2c_driver);
if (ret != 0) {
printk(KERN_ERR "Failed to register WM8971 I2C driver: %d\n",
ret);
}
#endif
return ret;
}
module_init(wm8971_modinit);
static void __exit wm8971_exit(void)
{
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
i2c_del_driver(&wm8971_i2c_driver);
#endif
}
module_exit(wm8971_exit);
MODULE_DESCRIPTION("ASoC WM8971 driver");
MODULE_AUTHOR("Lab126");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Evervolv/android_kernel_lge_msm8974 | arch/x86/kernel/apic/numaq_32.c | 4560 | 14070 | /*
* Written by: Patricia Gaughen, IBM Corporation
*
* Copyright (C) 2002, IBM Corp.
* Copyright (C) 2009, Red Hat, Inc., Ingo Molnar
*
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Send feedback to <gone@us.ibm.com>
*/
#include <linux/nodemask.h>
#include <linux/topology.h>
#include <linux/bootmem.h>
#include <linux/memblock.h>
#include <linux/threads.h>
#include <linux/cpumask.h>
#include <linux/kernel.h>
#include <linux/mmzone.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/numa.h>
#include <linux/smp.h>
#include <linux/io.h>
#include <linux/mm.h>
#include <asm/processor.h>
#include <asm/fixmap.h>
#include <asm/mpspec.h>
#include <asm/numaq.h>
#include <asm/setup.h>
#include <asm/apic.h>
#include <asm/e820.h>
#include <asm/ipi.h>
int found_numaq;
/*
* Have to match translation table entries to main table entries by counter
* hence the mpc_record variable .... can't see a less disgusting way of
* doing this ....
*/
struct mpc_trans {
unsigned char mpc_type;
unsigned char trans_len;
unsigned char trans_type;
unsigned char trans_quad;
unsigned char trans_global;
unsigned char trans_local;
unsigned short trans_reserved;
};
static int mpc_record;
static struct mpc_trans *translation_table[MAX_MPC_ENTRY];
int mp_bus_id_to_node[MAX_MP_BUSSES];
int mp_bus_id_to_local[MAX_MP_BUSSES];
int quad_local_to_mp_bus_id[NR_CPUS/4][4];
static inline void numaq_register_node(int node, struct sys_cfg_data *scd)
{
struct eachquadmem *eq = scd->eq + node;
u64 start = (u64)(eq->hi_shrd_mem_start - eq->priv_mem_size) << 20;
u64 end = (u64)(eq->hi_shrd_mem_start + eq->hi_shrd_mem_size) << 20;
int ret;
node_set(node, numa_nodes_parsed);
ret = numa_add_memblk(node, start, end);
BUG_ON(ret < 0);
}
/*
* Function: smp_dump_qct()
*
* Description: gets memory layout from the quad config table. This
* function also updates numa_nodes_parsed with the nodes (quads) present.
*/
static void __init smp_dump_qct(void)
{
struct sys_cfg_data *scd;
int node;
scd = (void *)__va(SYS_CFG_DATA_PRIV_ADDR);
for_each_node(node) {
if (scd->quads_present31_0 & (1 << node))
numaq_register_node(node, scd);
}
}
void __cpuinit numaq_tsc_disable(void)
{
if (!found_numaq)
return;
if (num_online_nodes() > 1) {
printk(KERN_DEBUG "NUMAQ: disabling TSC\n");
setup_clear_cpu_cap(X86_FEATURE_TSC);
}
}
static void __init numaq_tsc_init(void)
{
numaq_tsc_disable();
}
static inline int generate_logical_apicid(int quad, int phys_apicid)
{
return (quad << 4) + (phys_apicid ? phys_apicid << 1 : 1);
}
/* x86_quirks member */
static int mpc_apic_id(struct mpc_cpu *m)
{
int quad = translation_table[mpc_record]->trans_quad;
int logical_apicid = generate_logical_apicid(quad, m->apicid);
printk(KERN_DEBUG
"Processor #%d %u:%u APIC version %d (quad %d, apic %d)\n",
m->apicid, (m->cpufeature & CPU_FAMILY_MASK) >> 8,
(m->cpufeature & CPU_MODEL_MASK) >> 4,
m->apicver, quad, logical_apicid);
return logical_apicid;
}
/* x86_quirks member */
static void mpc_oem_bus_info(struct mpc_bus *m, char *name)
{
int quad = translation_table[mpc_record]->trans_quad;
int local = translation_table[mpc_record]->trans_local;
mp_bus_id_to_node[m->busid] = quad;
mp_bus_id_to_local[m->busid] = local;
printk(KERN_INFO "Bus #%d is %s (node %d)\n", m->busid, name, quad);
}
/* x86_quirks member */
static void mpc_oem_pci_bus(struct mpc_bus *m)
{
int quad = translation_table[mpc_record]->trans_quad;
int local = translation_table[mpc_record]->trans_local;
quad_local_to_mp_bus_id[quad][local] = m->busid;
}
/*
* Called from mpparse code.
* mode = 0: prescan
* mode = 1: one mpc entry scanned
*/
static void numaq_mpc_record(unsigned int mode)
{
if (!mode)
mpc_record = 0;
else
mpc_record++;
}
static void __init MP_translation_info(struct mpc_trans *m)
{
printk(KERN_INFO
"Translation: record %d, type %d, quad %d, global %d, local %d\n",
mpc_record, m->trans_type, m->trans_quad, m->trans_global,
m->trans_local);
if (mpc_record >= MAX_MPC_ENTRY)
printk(KERN_ERR "MAX_MPC_ENTRY exceeded!\n");
else
translation_table[mpc_record] = m; /* stash this for later */
if (m->trans_quad < MAX_NUMNODES && !node_online(m->trans_quad))
node_set_online(m->trans_quad);
}
static int __init mpf_checksum(unsigned char *mp, int len)
{
int sum = 0;
while (len--)
sum += *mp++;
return sum & 0xFF;
}
/*
* Read/parse the MPC oem tables
*/
static void __init smp_read_mpc_oem(struct mpc_table *mpc)
{
struct mpc_oemtable *oemtable = (void *)(long)mpc->oemptr;
int count = sizeof(*oemtable); /* the header size */
unsigned char *oemptr = ((unsigned char *)oemtable) + count;
mpc_record = 0;
printk(KERN_INFO
"Found an OEM MPC table at %8p - parsing it...\n", oemtable);
if (memcmp(oemtable->signature, MPC_OEM_SIGNATURE, 4)) {
printk(KERN_WARNING
"SMP mpc oemtable: bad signature [%c%c%c%c]!\n",
oemtable->signature[0], oemtable->signature[1],
oemtable->signature[2], oemtable->signature[3]);
return;
}
if (mpf_checksum((unsigned char *)oemtable, oemtable->length)) {
printk(KERN_WARNING "SMP oem mptable: checksum error!\n");
return;
}
while (count < oemtable->length) {
switch (*oemptr) {
case MP_TRANSLATION:
{
struct mpc_trans *m = (void *)oemptr;
MP_translation_info(m);
oemptr += sizeof(*m);
count += sizeof(*m);
++mpc_record;
break;
}
default:
printk(KERN_WARNING
"Unrecognised OEM table entry type! - %d\n",
(int)*oemptr);
return;
}
}
}
static __init void early_check_numaq(void)
{
/*
* get boot-time SMP configuration:
*/
if (smp_found_config)
early_get_smp_config();
if (found_numaq) {
x86_init.mpparse.mpc_record = numaq_mpc_record;
x86_init.mpparse.setup_ioapic_ids = x86_init_noop;
x86_init.mpparse.mpc_apic_id = mpc_apic_id;
x86_init.mpparse.smp_read_mpc_oem = smp_read_mpc_oem;
x86_init.mpparse.mpc_oem_pci_bus = mpc_oem_pci_bus;
x86_init.mpparse.mpc_oem_bus_info = mpc_oem_bus_info;
x86_init.timers.tsc_pre_init = numaq_tsc_init;
x86_init.pci.init = pci_numaq_init;
}
}
int __init numaq_numa_init(void)
{
early_check_numaq();
if (!found_numaq)
return -ENOENT;
smp_dump_qct();
return 0;
}
#define NUMAQ_APIC_DFR_VALUE (APIC_DFR_CLUSTER)
static inline unsigned int numaq_get_apic_id(unsigned long x)
{
return (x >> 24) & 0x0F;
}
static inline void numaq_send_IPI_mask(const struct cpumask *mask, int vector)
{
default_send_IPI_mask_sequence_logical(mask, vector);
}
static inline void numaq_send_IPI_allbutself(int vector)
{
default_send_IPI_mask_allbutself_logical(cpu_online_mask, vector);
}
static inline void numaq_send_IPI_all(int vector)
{
numaq_send_IPI_mask(cpu_online_mask, vector);
}
#define NUMAQ_TRAMPOLINE_PHYS_LOW (0x8)
#define NUMAQ_TRAMPOLINE_PHYS_HIGH (0xa)
/*
* Because we use NMIs rather than the INIT-STARTUP sequence to
* bootstrap the CPUs, the APIC may be in a weird state. Kick it:
*/
static inline void numaq_smp_callin_clear_local_apic(void)
{
clear_local_APIC();
}
static inline const struct cpumask *numaq_target_cpus(void)
{
return cpu_all_mask;
}
static unsigned long numaq_check_apicid_used(physid_mask_t *map, int apicid)
{
return physid_isset(apicid, *map);
}
static inline unsigned long numaq_check_apicid_present(int bit)
{
return physid_isset(bit, phys_cpu_present_map);
}
static inline int numaq_apic_id_registered(void)
{
return 1;
}
static inline void numaq_init_apic_ldr(void)
{
/* Already done in NUMA-Q firmware */
}
static inline void numaq_setup_apic_routing(void)
{
printk(KERN_INFO
"Enabling APIC mode: NUMA-Q. Using %d I/O APICs\n",
nr_ioapics);
}
/*
* Skip adding the timer int on secondary nodes, which causes
* a small but painful rift in the time-space continuum.
*/
static inline int numaq_multi_timer_check(int apic, int irq)
{
return apic != 0 && irq == 0;
}
static inline void numaq_ioapic_phys_id_map(physid_mask_t *phys_map, physid_mask_t *retmap)
{
/* We don't have a good way to do this yet - hack */
return physids_promote(0xFUL, retmap);
}
/*
* Supporting over 60 cpus on NUMA-Q requires a locality-dependent
* cpu to APIC ID relation to properly interact with the intelligent
* mode of the cluster controller.
*/
static inline int numaq_cpu_present_to_apicid(int mps_cpu)
{
if (mps_cpu < 60)
return ((mps_cpu >> 2) << 4) | (1 << (mps_cpu & 0x3));
else
return BAD_APICID;
}
static inline int numaq_apicid_to_node(int logical_apicid)
{
return logical_apicid >> 4;
}
static int numaq_numa_cpu_node(int cpu)
{
int logical_apicid = early_per_cpu(x86_cpu_to_logical_apicid, cpu);
if (logical_apicid != BAD_APICID)
return numaq_apicid_to_node(logical_apicid);
return NUMA_NO_NODE;
}
static void numaq_apicid_to_cpu_present(int logical_apicid, physid_mask_t *retmap)
{
int node = numaq_apicid_to_node(logical_apicid);
int cpu = __ffs(logical_apicid & 0xf);
physid_set_mask_of_physid(cpu + 4*node, retmap);
}
/* Where the IO area was mapped on multiquad, always 0 otherwise */
void *xquad_portio;
static inline int numaq_check_phys_apicid_present(int phys_apicid)
{
return 1;
}
/*
* We use physical apicids here, not logical, so just return the default
* physical broadcast to stop people from breaking us
*/
static unsigned int numaq_cpu_mask_to_apicid(const struct cpumask *cpumask)
{
return 0x0F;
}
static inline unsigned int
numaq_cpu_mask_to_apicid_and(const struct cpumask *cpumask,
const struct cpumask *andmask)
{
return 0x0F;
}
/* No NUMA-Q box has a HT CPU, but it can't hurt to use the default code. */
static inline int numaq_phys_pkg_id(int cpuid_apic, int index_msb)
{
return cpuid_apic >> index_msb;
}
static int
numaq_mps_oem_check(struct mpc_table *mpc, char *oem, char *productid)
{
if (strncmp(oem, "IBM NUMA", 8))
printk(KERN_ERR "Warning! Not a NUMA-Q system!\n");
else
found_numaq = 1;
return found_numaq;
}
static int probe_numaq(void)
{
/* already know from get_memcfg_numaq() */
return found_numaq;
}
static void numaq_vector_allocation_domain(int cpu, struct cpumask *retmask)
{
/* Careful. Some cpus do not strictly honor the set of cpus
* specified in the interrupt destination when using lowest
* priority interrupt delivery mode.
*
* In particular there was a hyperthreading cpu observed to
* deliver interrupts to the wrong hyperthread when only one
* hyperthread was specified in the interrupt desitination.
*/
cpumask_clear(retmask);
cpumask_bits(retmask)[0] = APIC_ALL_CPUS;
}
static void numaq_setup_portio_remap(void)
{
int num_quads = num_online_nodes();
if (num_quads <= 1)
return;
printk(KERN_INFO
"Remapping cross-quad port I/O for %d quads\n", num_quads);
xquad_portio = ioremap(XQUAD_PORTIO_BASE, num_quads*XQUAD_PORTIO_QUAD);
printk(KERN_INFO
"xquad_portio vaddr 0x%08lx, len %08lx\n",
(u_long) xquad_portio, (u_long) num_quads*XQUAD_PORTIO_QUAD);
}
/* Use __refdata to keep false positive warning calm. */
static struct apic __refdata apic_numaq = {
.name = "NUMAQ",
.probe = probe_numaq,
.acpi_madt_oem_check = NULL,
.apic_id_valid = default_apic_id_valid,
.apic_id_registered = numaq_apic_id_registered,
.irq_delivery_mode = dest_LowestPrio,
/* physical delivery on LOCAL quad: */
.irq_dest_mode = 0,
.target_cpus = numaq_target_cpus,
.disable_esr = 1,
.dest_logical = APIC_DEST_LOGICAL,
.check_apicid_used = numaq_check_apicid_used,
.check_apicid_present = numaq_check_apicid_present,
.vector_allocation_domain = numaq_vector_allocation_domain,
.init_apic_ldr = numaq_init_apic_ldr,
.ioapic_phys_id_map = numaq_ioapic_phys_id_map,
.setup_apic_routing = numaq_setup_apic_routing,
.multi_timer_check = numaq_multi_timer_check,
.cpu_present_to_apicid = numaq_cpu_present_to_apicid,
.apicid_to_cpu_present = numaq_apicid_to_cpu_present,
.setup_portio_remap = numaq_setup_portio_remap,
.check_phys_apicid_present = numaq_check_phys_apicid_present,
.enable_apic_mode = NULL,
.phys_pkg_id = numaq_phys_pkg_id,
.mps_oem_check = numaq_mps_oem_check,
.get_apic_id = numaq_get_apic_id,
.set_apic_id = NULL,
.apic_id_mask = 0x0F << 24,
.cpu_mask_to_apicid = numaq_cpu_mask_to_apicid,
.cpu_mask_to_apicid_and = numaq_cpu_mask_to_apicid_and,
.send_IPI_mask = numaq_send_IPI_mask,
.send_IPI_mask_allbutself = NULL,
.send_IPI_allbutself = numaq_send_IPI_allbutself,
.send_IPI_all = numaq_send_IPI_all,
.send_IPI_self = default_send_IPI_self,
.wakeup_secondary_cpu = wakeup_secondary_cpu_via_nmi,
.trampoline_phys_low = NUMAQ_TRAMPOLINE_PHYS_LOW,
.trampoline_phys_high = NUMAQ_TRAMPOLINE_PHYS_HIGH,
/* We don't do anything here because we use NMI's to boot instead */
.wait_for_init_deassert = NULL,
.smp_callin_clear_local_apic = numaq_smp_callin_clear_local_apic,
.inquire_remote_apic = NULL,
.read = native_apic_mem_read,
.write = native_apic_mem_write,
.icr_read = native_apic_icr_read,
.icr_write = native_apic_icr_write,
.wait_icr_idle = native_apic_wait_icr_idle,
.safe_wait_icr_idle = native_safe_apic_wait_icr_idle,
.x86_32_early_logical_apicid = noop_x86_32_early_logical_apicid,
.x86_32_numa_cpu_node = numaq_numa_cpu_node,
};
apic_driver(apic_numaq);
| gpl-2.0 |
flar2/m7-Sense-4.4.3 | drivers/input/misc/cobalt_btns.c | 5072 | 4430 | /*
* Cobalt button interface driver.
*
* Copyright (C) 2007-2008 Yoichi Yuasa <yuasa@linux-mips.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/init.h>
#include <linux/input-polldev.h>
#include <linux/ioport.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#define BUTTONS_POLL_INTERVAL 30 /* msec */
#define BUTTONS_COUNT_THRESHOLD 3
#define BUTTONS_STATUS_MASK 0xfe000000
static const unsigned short cobalt_map[] = {
KEY_RESERVED,
KEY_RESTART,
KEY_LEFT,
KEY_UP,
KEY_DOWN,
KEY_RIGHT,
KEY_ENTER,
KEY_SELECT
};
struct buttons_dev {
struct input_polled_dev *poll_dev;
unsigned short keymap[ARRAY_SIZE(cobalt_map)];
int count[ARRAY_SIZE(cobalt_map)];
void __iomem *reg;
};
static void handle_buttons(struct input_polled_dev *dev)
{
struct buttons_dev *bdev = dev->private;
struct input_dev *input = dev->input;
uint32_t status;
int i;
status = ~readl(bdev->reg) >> 24;
for (i = 0; i < ARRAY_SIZE(bdev->keymap); i++) {
if (status & (1U << i)) {
if (++bdev->count[i] == BUTTONS_COUNT_THRESHOLD) {
input_event(input, EV_MSC, MSC_SCAN, i);
input_report_key(input, bdev->keymap[i], 1);
input_sync(input);
}
} else {
if (bdev->count[i] >= BUTTONS_COUNT_THRESHOLD) {
input_event(input, EV_MSC, MSC_SCAN, i);
input_report_key(input, bdev->keymap[i], 0);
input_sync(input);
}
bdev->count[i] = 0;
}
}
}
static int __devinit cobalt_buttons_probe(struct platform_device *pdev)
{
struct buttons_dev *bdev;
struct input_polled_dev *poll_dev;
struct input_dev *input;
struct resource *res;
int error, i;
bdev = kzalloc(sizeof(struct buttons_dev), GFP_KERNEL);
poll_dev = input_allocate_polled_device();
if (!bdev || !poll_dev) {
error = -ENOMEM;
goto err_free_mem;
}
memcpy(bdev->keymap, cobalt_map, sizeof(bdev->keymap));
poll_dev->private = bdev;
poll_dev->poll = handle_buttons;
poll_dev->poll_interval = BUTTONS_POLL_INTERVAL;
input = poll_dev->input;
input->name = "Cobalt buttons";
input->phys = "cobalt/input0";
input->id.bustype = BUS_HOST;
input->dev.parent = &pdev->dev;
input->keycode = bdev->keymap;
input->keycodemax = ARRAY_SIZE(bdev->keymap);
input->keycodesize = sizeof(unsigned short);
input_set_capability(input, EV_MSC, MSC_SCAN);
__set_bit(EV_KEY, input->evbit);
for (i = 0; i < ARRAY_SIZE(cobalt_map); i++)
__set_bit(bdev->keymap[i], input->keybit);
__clear_bit(KEY_RESERVED, input->keybit);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
error = -EBUSY;
goto err_free_mem;
}
bdev->poll_dev = poll_dev;
bdev->reg = ioremap(res->start, resource_size(res));
dev_set_drvdata(&pdev->dev, bdev);
error = input_register_polled_device(poll_dev);
if (error)
goto err_iounmap;
return 0;
err_iounmap:
iounmap(bdev->reg);
err_free_mem:
input_free_polled_device(poll_dev);
kfree(bdev);
dev_set_drvdata(&pdev->dev, NULL);
return error;
}
static int __devexit cobalt_buttons_remove(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct buttons_dev *bdev = dev_get_drvdata(dev);
input_unregister_polled_device(bdev->poll_dev);
input_free_polled_device(bdev->poll_dev);
iounmap(bdev->reg);
kfree(bdev);
dev_set_drvdata(dev, NULL);
return 0;
}
MODULE_AUTHOR("Yoichi Yuasa <yuasa@linux-mips.org>");
MODULE_DESCRIPTION("Cobalt button interface driver");
MODULE_LICENSE("GPL");
/* work with hotplug and coldplug */
MODULE_ALIAS("platform:Cobalt buttons");
static struct platform_driver cobalt_buttons_driver = {
.probe = cobalt_buttons_probe,
.remove = __devexit_p(cobalt_buttons_remove),
.driver = {
.name = "Cobalt buttons",
.owner = THIS_MODULE,
},
};
module_platform_driver(cobalt_buttons_driver);
| gpl-2.0 |
itead/ITEADSW_kernel | drivers/input/misc/pcf50633-input.c | 5072 | 3098 | /* NXP PCF50633 Input Driver
*
* (C) 2006-2008 by Openmoko, Inc.
* Author: Balaji Rao <balajirrao@openmoko.org>
* All rights reserved.
*
* Broken down from monstrous PCF50633 driver mainly by
* Harald Welte, Andy Green and Werner Almesberger
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <linux/slab.h>
#include <linux/mfd/pcf50633/core.h>
#define PCF50633_OOCSTAT_ONKEY 0x01
#define PCF50633_REG_OOCSTAT 0x12
#define PCF50633_REG_OOCMODE 0x10
struct pcf50633_input {
struct pcf50633 *pcf;
struct input_dev *input_dev;
};
static void
pcf50633_input_irq(int irq, void *data)
{
struct pcf50633_input *input;
int onkey_released;
input = data;
/* We report only one event depending on the key press status */
onkey_released = pcf50633_reg_read(input->pcf, PCF50633_REG_OOCSTAT)
& PCF50633_OOCSTAT_ONKEY;
if (irq == PCF50633_IRQ_ONKEYF && !onkey_released)
input_report_key(input->input_dev, KEY_POWER, 1);
else if (irq == PCF50633_IRQ_ONKEYR && onkey_released)
input_report_key(input->input_dev, KEY_POWER, 0);
input_sync(input->input_dev);
}
static int __devinit pcf50633_input_probe(struct platform_device *pdev)
{
struct pcf50633_input *input;
struct input_dev *input_dev;
int ret;
input = kzalloc(sizeof(*input), GFP_KERNEL);
if (!input)
return -ENOMEM;
input_dev = input_allocate_device();
if (!input_dev) {
kfree(input);
return -ENOMEM;
}
platform_set_drvdata(pdev, input);
input->pcf = dev_to_pcf50633(pdev->dev.parent);
input->input_dev = input_dev;
input_dev->name = "PCF50633 PMU events";
input_dev->id.bustype = BUS_I2C;
input_dev->evbit[0] = BIT(EV_KEY) | BIT(EV_PWR);
set_bit(KEY_POWER, input_dev->keybit);
ret = input_register_device(input_dev);
if (ret) {
input_free_device(input_dev);
kfree(input);
return ret;
}
pcf50633_register_irq(input->pcf, PCF50633_IRQ_ONKEYR,
pcf50633_input_irq, input);
pcf50633_register_irq(input->pcf, PCF50633_IRQ_ONKEYF,
pcf50633_input_irq, input);
return 0;
}
static int __devexit pcf50633_input_remove(struct platform_device *pdev)
{
struct pcf50633_input *input = platform_get_drvdata(pdev);
pcf50633_free_irq(input->pcf, PCF50633_IRQ_ONKEYR);
pcf50633_free_irq(input->pcf, PCF50633_IRQ_ONKEYF);
input_unregister_device(input->input_dev);
kfree(input);
return 0;
}
static struct platform_driver pcf50633_input_driver = {
.driver = {
.name = "pcf50633-input",
},
.probe = pcf50633_input_probe,
.remove = __devexit_p(pcf50633_input_remove),
};
module_platform_driver(pcf50633_input_driver);
MODULE_AUTHOR("Balaji Rao <balajirrao@openmoko.org>");
MODULE_DESCRIPTION("PCF50633 input driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:pcf50633-input");
| gpl-2.0 |
zaclimon/Quanta-Flo | drivers/input/keyboard/bf54x-keys.c | 5072 | 10009 | /*
* File: drivers/input/keyboard/bf54x-keys.c
* Based on:
* Author: Michael Hennerich <hennerich@blackfin.uclinux.org>
*
* Created:
* Description: keypad driver for Analog Devices Blackfin BF54x Processors
*
*
* Modified:
* Copyright 2007-2008 Analog Devices Inc.
*
* Bugs: Enter bugs at http://blackfin.uclinux.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, see the file COPYING, or write
* to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/pm.h>
#include <linux/sysctl.h>
#include <linux/proc_fs.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <asm/portmux.h>
#include <mach/bf54x_keys.h>
#define DRV_NAME "bf54x-keys"
#define TIME_SCALE 100 /* 100 ns */
#define MAX_MULT (0xFF * TIME_SCALE)
#define MAX_RC 8 /* Max Row/Col */
static const u16 per_rows[] = {
P_KEY_ROW7,
P_KEY_ROW6,
P_KEY_ROW5,
P_KEY_ROW4,
P_KEY_ROW3,
P_KEY_ROW2,
P_KEY_ROW1,
P_KEY_ROW0,
0
};
static const u16 per_cols[] = {
P_KEY_COL7,
P_KEY_COL6,
P_KEY_COL5,
P_KEY_COL4,
P_KEY_COL3,
P_KEY_COL2,
P_KEY_COL1,
P_KEY_COL0,
0
};
struct bf54x_kpad {
struct input_dev *input;
int irq;
unsigned short lastkey;
unsigned short *keycode;
struct timer_list timer;
unsigned int keyup_test_jiffies;
unsigned short kpad_msel;
unsigned short kpad_prescale;
unsigned short kpad_ctl;
};
static inline int bfin_kpad_find_key(struct bf54x_kpad *bf54x_kpad,
struct input_dev *input, u16 keyident)
{
u16 i;
for (i = 0; i < input->keycodemax; i++)
if (bf54x_kpad->keycode[i + input->keycodemax] == keyident)
return bf54x_kpad->keycode[i];
return -1;
}
static inline void bfin_keycodecpy(unsigned short *keycode,
const unsigned int *pdata_kc,
unsigned short keymapsize)
{
unsigned int i;
for (i = 0; i < keymapsize; i++) {
keycode[i] = pdata_kc[i] & 0xffff;
keycode[i + keymapsize] = pdata_kc[i] >> 16;
}
}
static inline u16 bfin_kpad_get_prescale(u32 timescale)
{
u32 sclk = get_sclk();
return ((((sclk / 1000) * timescale) / 1024) - 1);
}
static inline u16 bfin_kpad_get_keypressed(struct bf54x_kpad *bf54x_kpad)
{
return (bfin_read_KPAD_STAT() & KPAD_PRESSED);
}
static inline void bfin_kpad_clear_irq(void)
{
bfin_write_KPAD_STAT(0xFFFF);
bfin_write_KPAD_ROWCOL(0xFFFF);
}
static void bfin_kpad_timer(unsigned long data)
{
struct platform_device *pdev = (struct platform_device *) data;
struct bf54x_kpad *bf54x_kpad = platform_get_drvdata(pdev);
if (bfin_kpad_get_keypressed(bf54x_kpad)) {
/* Try again later */
mod_timer(&bf54x_kpad->timer,
jiffies + bf54x_kpad->keyup_test_jiffies);
return;
}
input_report_key(bf54x_kpad->input, bf54x_kpad->lastkey, 0);
input_sync(bf54x_kpad->input);
/* Clear IRQ Status */
bfin_kpad_clear_irq();
enable_irq(bf54x_kpad->irq);
}
static irqreturn_t bfin_kpad_isr(int irq, void *dev_id)
{
struct platform_device *pdev = dev_id;
struct bf54x_kpad *bf54x_kpad = platform_get_drvdata(pdev);
struct input_dev *input = bf54x_kpad->input;
int key;
u16 rowcol = bfin_read_KPAD_ROWCOL();
key = bfin_kpad_find_key(bf54x_kpad, input, rowcol);
input_report_key(input, key, 1);
input_sync(input);
if (bfin_kpad_get_keypressed(bf54x_kpad)) {
disable_irq_nosync(bf54x_kpad->irq);
bf54x_kpad->lastkey = key;
mod_timer(&bf54x_kpad->timer,
jiffies + bf54x_kpad->keyup_test_jiffies);
} else {
input_report_key(input, key, 0);
input_sync(input);
bfin_kpad_clear_irq();
}
return IRQ_HANDLED;
}
static int __devinit bfin_kpad_probe(struct platform_device *pdev)
{
struct bf54x_kpad *bf54x_kpad;
struct bfin_kpad_platform_data *pdata = pdev->dev.platform_data;
struct input_dev *input;
int i, error;
if (!pdata->rows || !pdata->cols || !pdata->keymap) {
dev_err(&pdev->dev, "no rows, cols or keymap from pdata\n");
return -EINVAL;
}
if (!pdata->keymapsize ||
pdata->keymapsize > (pdata->rows * pdata->cols)) {
dev_err(&pdev->dev, "invalid keymapsize\n");
return -EINVAL;
}
bf54x_kpad = kzalloc(sizeof(struct bf54x_kpad), GFP_KERNEL);
if (!bf54x_kpad)
return -ENOMEM;
platform_set_drvdata(pdev, bf54x_kpad);
/* Allocate memory for keymap followed by private LUT */
bf54x_kpad->keycode = kmalloc(pdata->keymapsize *
sizeof(unsigned short) * 2, GFP_KERNEL);
if (!bf54x_kpad->keycode) {
error = -ENOMEM;
goto out;
}
if (!pdata->debounce_time || pdata->debounce_time > MAX_MULT ||
!pdata->coldrive_time || pdata->coldrive_time > MAX_MULT) {
dev_warn(&pdev->dev,
"invalid platform debounce/columndrive time\n");
bfin_write_KPAD_MSEL(0xFF0); /* Default MSEL */
} else {
bfin_write_KPAD_MSEL(
((pdata->debounce_time / TIME_SCALE)
& DBON_SCALE) |
(((pdata->coldrive_time / TIME_SCALE) << 8)
& COLDRV_SCALE));
}
if (!pdata->keyup_test_interval)
bf54x_kpad->keyup_test_jiffies = msecs_to_jiffies(50);
else
bf54x_kpad->keyup_test_jiffies =
msecs_to_jiffies(pdata->keyup_test_interval);
if (peripheral_request_list((u16 *)&per_rows[MAX_RC - pdata->rows],
DRV_NAME)) {
dev_err(&pdev->dev, "requesting peripherals failed\n");
error = -EFAULT;
goto out0;
}
if (peripheral_request_list((u16 *)&per_cols[MAX_RC - pdata->cols],
DRV_NAME)) {
dev_err(&pdev->dev, "requesting peripherals failed\n");
error = -EFAULT;
goto out1;
}
bf54x_kpad->irq = platform_get_irq(pdev, 0);
if (bf54x_kpad->irq < 0) {
error = -ENODEV;
goto out2;
}
error = request_irq(bf54x_kpad->irq, bfin_kpad_isr,
0, DRV_NAME, pdev);
if (error) {
dev_err(&pdev->dev, "unable to claim irq %d\n",
bf54x_kpad->irq);
goto out2;
}
input = input_allocate_device();
if (!input) {
error = -ENOMEM;
goto out3;
}
bf54x_kpad->input = input;
input->name = pdev->name;
input->phys = "bf54x-keys/input0";
input->dev.parent = &pdev->dev;
input_set_drvdata(input, bf54x_kpad);
input->id.bustype = BUS_HOST;
input->id.vendor = 0x0001;
input->id.product = 0x0001;
input->id.version = 0x0100;
input->keycodesize = sizeof(unsigned short);
input->keycodemax = pdata->keymapsize;
input->keycode = bf54x_kpad->keycode;
bfin_keycodecpy(bf54x_kpad->keycode, pdata->keymap, pdata->keymapsize);
/* setup input device */
__set_bit(EV_KEY, input->evbit);
if (pdata->repeat)
__set_bit(EV_REP, input->evbit);
for (i = 0; i < input->keycodemax; i++)
__set_bit(bf54x_kpad->keycode[i] & KEY_MAX, input->keybit);
__clear_bit(KEY_RESERVED, input->keybit);
error = input_register_device(input);
if (error) {
dev_err(&pdev->dev, "unable to register input device\n");
goto out4;
}
/* Init Keypad Key Up/Release test timer */
setup_timer(&bf54x_kpad->timer, bfin_kpad_timer, (unsigned long) pdev);
bfin_write_KPAD_PRESCALE(bfin_kpad_get_prescale(TIME_SCALE));
bfin_write_KPAD_CTL((((pdata->cols - 1) << 13) & KPAD_COLEN) |
(((pdata->rows - 1) << 10) & KPAD_ROWEN) |
(2 & KPAD_IRQMODE));
bfin_write_KPAD_CTL(bfin_read_KPAD_CTL() | KPAD_EN);
device_init_wakeup(&pdev->dev, 1);
return 0;
out4:
input_free_device(input);
out3:
free_irq(bf54x_kpad->irq, pdev);
out2:
peripheral_free_list((u16 *)&per_cols[MAX_RC - pdata->cols]);
out1:
peripheral_free_list((u16 *)&per_rows[MAX_RC - pdata->rows]);
out0:
kfree(bf54x_kpad->keycode);
out:
kfree(bf54x_kpad);
platform_set_drvdata(pdev, NULL);
return error;
}
static int __devexit bfin_kpad_remove(struct platform_device *pdev)
{
struct bfin_kpad_platform_data *pdata = pdev->dev.platform_data;
struct bf54x_kpad *bf54x_kpad = platform_get_drvdata(pdev);
del_timer_sync(&bf54x_kpad->timer);
free_irq(bf54x_kpad->irq, pdev);
input_unregister_device(bf54x_kpad->input);
peripheral_free_list((u16 *)&per_rows[MAX_RC - pdata->rows]);
peripheral_free_list((u16 *)&per_cols[MAX_RC - pdata->cols]);
kfree(bf54x_kpad->keycode);
kfree(bf54x_kpad);
platform_set_drvdata(pdev, NULL);
return 0;
}
#ifdef CONFIG_PM
static int bfin_kpad_suspend(struct platform_device *pdev, pm_message_t state)
{
struct bf54x_kpad *bf54x_kpad = platform_get_drvdata(pdev);
bf54x_kpad->kpad_msel = bfin_read_KPAD_MSEL();
bf54x_kpad->kpad_prescale = bfin_read_KPAD_PRESCALE();
bf54x_kpad->kpad_ctl = bfin_read_KPAD_CTL();
if (device_may_wakeup(&pdev->dev))
enable_irq_wake(bf54x_kpad->irq);
return 0;
}
static int bfin_kpad_resume(struct platform_device *pdev)
{
struct bf54x_kpad *bf54x_kpad = platform_get_drvdata(pdev);
bfin_write_KPAD_MSEL(bf54x_kpad->kpad_msel);
bfin_write_KPAD_PRESCALE(bf54x_kpad->kpad_prescale);
bfin_write_KPAD_CTL(bf54x_kpad->kpad_ctl);
if (device_may_wakeup(&pdev->dev))
disable_irq_wake(bf54x_kpad->irq);
return 0;
}
#else
# define bfin_kpad_suspend NULL
# define bfin_kpad_resume NULL
#endif
static struct platform_driver bfin_kpad_device_driver = {
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
},
.probe = bfin_kpad_probe,
.remove = __devexit_p(bfin_kpad_remove),
.suspend = bfin_kpad_suspend,
.resume = bfin_kpad_resume,
};
module_platform_driver(bfin_kpad_device_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Michael Hennerich <hennerich@blackfin.uclinux.org>");
MODULE_DESCRIPTION("Keypad driver for BF54x Processors");
MODULE_ALIAS("platform:bf54x-keys");
| gpl-2.0 |
CyanogenMod/android_kernel_lge_msm8974 | drivers/input/misc/rb532_button.c | 5072 | 2723 | /*
* Support for the S1 button on Routerboard 532
*
* Copyright (C) 2009 Phil Sutter <n0-1@freewrt.org>
*/
#include <linux/input-polldev.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <asm/mach-rc32434/gpio.h>
#include <asm/mach-rc32434/rb.h>
#define DRV_NAME "rb532-button"
#define RB532_BTN_RATE 100 /* msec */
#define RB532_BTN_KSYM BTN_0
/* The S1 button state is provided by GPIO pin 1. But as this
* pin is also used for uart input as alternate function, the
* operational modes must be switched first:
* 1) disable uart using set_latch_u5()
* 2) turn off alternate function implicitly through
* gpio_direction_input()
* 3) read the GPIO's current value
* 4) undo step 2 by enabling alternate function (in this
* mode the GPIO direction is fixed, so no change needed)
* 5) turn on uart again
* The GPIO value occurs to be inverted, so pin high means
* button is not pressed.
*/
static bool rb532_button_pressed(void)
{
int val;
set_latch_u5(0, LO_FOFF);
gpio_direction_input(GPIO_BTN_S1);
val = gpio_get_value(GPIO_BTN_S1);
rb532_gpio_set_func(GPIO_BTN_S1);
set_latch_u5(LO_FOFF, 0);
return !val;
}
static void rb532_button_poll(struct input_polled_dev *poll_dev)
{
input_report_key(poll_dev->input, RB532_BTN_KSYM,
rb532_button_pressed());
input_sync(poll_dev->input);
}
static int __devinit rb532_button_probe(struct platform_device *pdev)
{
struct input_polled_dev *poll_dev;
int error;
poll_dev = input_allocate_polled_device();
if (!poll_dev)
return -ENOMEM;
poll_dev->poll = rb532_button_poll;
poll_dev->poll_interval = RB532_BTN_RATE;
poll_dev->input->name = "rb532 button";
poll_dev->input->phys = "rb532/button0";
poll_dev->input->id.bustype = BUS_HOST;
poll_dev->input->dev.parent = &pdev->dev;
dev_set_drvdata(&pdev->dev, poll_dev);
input_set_capability(poll_dev->input, EV_KEY, RB532_BTN_KSYM);
error = input_register_polled_device(poll_dev);
if (error) {
input_free_polled_device(poll_dev);
return error;
}
return 0;
}
static int __devexit rb532_button_remove(struct platform_device *pdev)
{
struct input_polled_dev *poll_dev = dev_get_drvdata(&pdev->dev);
input_unregister_polled_device(poll_dev);
input_free_polled_device(poll_dev);
dev_set_drvdata(&pdev->dev, NULL);
return 0;
}
static struct platform_driver rb532_button_driver = {
.probe = rb532_button_probe,
.remove = __devexit_p(rb532_button_remove),
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
},
};
module_platform_driver(rb532_button_driver);
MODULE_AUTHOR("Phil Sutter <n0-1@freewrt.org>");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Support for S1 button on Routerboard 532");
MODULE_ALIAS("platform:" DRV_NAME);
| gpl-2.0 |
XperianPro/android_kernel_xiaomi_aries-port | arch/mips/kernel/csrc-sb1250.c | 7632 | 2151 | /*
* Copyright (C) 2000, 2001 Broadcom Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; 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/clocksource.h>
#include <asm/addrspace.h>
#include <asm/io.h>
#include <asm/time.h>
#include <asm/sibyte/sb1250.h>
#include <asm/sibyte/sb1250_regs.h>
#include <asm/sibyte/sb1250_int.h>
#include <asm/sibyte/sb1250_scd.h>
#define SB1250_HPT_NUM 3
#define SB1250_HPT_VALUE M_SCD_TIMER_CNT /* max value */
/*
* The HPT is free running from SB1250_HPT_VALUE down to 0 then starts over
* again.
*/
static cycle_t sb1250_hpt_read(struct clocksource *cs)
{
unsigned int count;
count = G_SCD_TIMER_CNT(__raw_readq(IOADDR(A_SCD_TIMER_REGISTER(SB1250_HPT_NUM, R_SCD_TIMER_CNT))));
return SB1250_HPT_VALUE - count;
}
struct clocksource bcm1250_clocksource = {
.name = "bcm1250-counter-3",
.rating = 200,
.read = sb1250_hpt_read,
.mask = CLOCKSOURCE_MASK(23),
.flags = CLOCK_SOURCE_IS_CONTINUOUS,
};
void __init sb1250_clocksource_init(void)
{
struct clocksource *cs = &bcm1250_clocksource;
/* Setup hpt using timer #3 but do not enable irq for it */
__raw_writeq(0,
IOADDR(A_SCD_TIMER_REGISTER(SB1250_HPT_NUM,
R_SCD_TIMER_CFG)));
__raw_writeq(SB1250_HPT_VALUE,
IOADDR(A_SCD_TIMER_REGISTER(SB1250_HPT_NUM,
R_SCD_TIMER_INIT)));
__raw_writeq(M_SCD_TIMER_ENABLE | M_SCD_TIMER_MODE_CONTINUOUS,
IOADDR(A_SCD_TIMER_REGISTER(SB1250_HPT_NUM,
R_SCD_TIMER_CFG)));
clocksource_register_hz(cs, V_SCD_TIMER_FREQ);
}
| gpl-2.0 |
sailesh341/lge-kernel-p880 | arch/arm/mach-kirkwood/lacie_v2-common.c | 8144 | 2949 | /*
* arch/arm/mach-kirkwood/lacie_v2-common.c
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/mtd/physmap.h>
#include <linux/spi/flash.h>
#include <linux/spi/spi.h>
#include <linux/i2c.h>
#include <linux/i2c/at24.h>
#include <linux/gpio.h>
#include <asm/mach/time.h>
#include <mach/kirkwood.h>
#include <mach/irqs.h>
#include <plat/time.h>
#include "common.h"
/*****************************************************************************
* 512KB SPI Flash on Boot Device (MACRONIX MX25L4005)
****************************************************************************/
static struct mtd_partition lacie_v2_flash_parts[] = {
{
.name = "u-boot",
.size = MTDPART_SIZ_FULL,
.offset = 0,
.mask_flags = MTD_WRITEABLE, /* force read-only */
},
};
static const struct flash_platform_data lacie_v2_flash = {
.type = "mx25l4005a",
.name = "spi_flash",
.parts = lacie_v2_flash_parts,
.nr_parts = ARRAY_SIZE(lacie_v2_flash_parts),
};
static struct spi_board_info __initdata lacie_v2_spi_slave_info[] = {
{
.modalias = "m25p80",
.platform_data = &lacie_v2_flash,
.irq = -1,
.max_speed_hz = 20000000,
.bus_num = 0,
.chip_select = 0,
},
};
void __init lacie_v2_register_flash(void)
{
spi_register_board_info(lacie_v2_spi_slave_info,
ARRAY_SIZE(lacie_v2_spi_slave_info));
kirkwood_spi_init();
}
/*****************************************************************************
* I2C devices
****************************************************************************/
static struct at24_platform_data at24c04 = {
.byte_len = SZ_4K / 8,
.page_size = 16,
};
/*
* i2c addr | chip | description
* 0x50 | HT24LC04 | eeprom (512B)
*/
static struct i2c_board_info __initdata lacie_v2_i2c_info[] = {
{
I2C_BOARD_INFO("24c04", 0x50),
.platform_data = &at24c04,
}
};
void __init lacie_v2_register_i2c_devices(void)
{
kirkwood_i2c_init();
i2c_register_board_info(0, lacie_v2_i2c_info,
ARRAY_SIZE(lacie_v2_i2c_info));
}
/*****************************************************************************
* Hard Disk power
****************************************************************************/
static int __initdata lacie_v2_gpio_hdd_power[] = { 16, 17, 41, 42, 43 };
void __init lacie_v2_hdd_power_init(int hdd_num)
{
int i;
int err;
/* Power up all hard disks. */
for (i = 0; i < hdd_num; i++) {
err = gpio_request(lacie_v2_gpio_hdd_power[i], NULL);
if (err == 0) {
err = gpio_direction_output(
lacie_v2_gpio_hdd_power[i], 1);
/* Free the HDD power GPIOs. This allow user-space to
* configure them via the gpiolib sysfs interface. */
gpio_free(lacie_v2_gpio_hdd_power[i]);
}
if (err)
pr_err("Failed to power up HDD%d\n", i + 1);
}
}
| gpl-2.0 |
shinobisoft/android_kernel_lge_msm8226 | net/ipv6/netfilter/ip6t_hbh.c | 8656 | 5093 | /* Kernel module to match Hop-by-Hop and Destination parameters. */
/* (C) 2001-2002 Andras Kis-Szabo <kisza@sch.bme.hu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/ipv6.h>
#include <linux/types.h>
#include <net/checksum.h>
#include <net/ipv6.h>
#include <asm/byteorder.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter_ipv6/ip6_tables.h>
#include <linux/netfilter_ipv6/ip6t_opts.h>
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Xtables: IPv6 Hop-By-Hop and Destination Header match");
MODULE_AUTHOR("Andras Kis-Szabo <kisza@sch.bme.hu>");
MODULE_ALIAS("ip6t_dst");
/*
* (Type & 0xC0) >> 6
* 0 -> ignorable
* 1 -> must drop the packet
* 2 -> send ICMP PARM PROB regardless and drop packet
* 3 -> Send ICMP if not a multicast address and drop packet
* (Type & 0x20) >> 5
* 0 -> invariant
* 1 -> can change the routing
* (Type & 0x1F) Type
* 0 -> Pad1 (only 1 byte!)
* 1 -> PadN LENGTH info (total length = length + 2)
* C0 | 2 -> JUMBO 4 x x x x ( xxxx > 64k )
* 5 -> RTALERT 2 x x
*/
static struct xt_match hbh_mt6_reg[] __read_mostly;
static bool
hbh_mt6(const struct sk_buff *skb, struct xt_action_param *par)
{
struct ipv6_opt_hdr _optsh;
const struct ipv6_opt_hdr *oh;
const struct ip6t_opts *optinfo = par->matchinfo;
unsigned int temp;
unsigned int ptr;
unsigned int hdrlen = 0;
bool ret = false;
u8 _opttype;
u8 _optlen;
const u_int8_t *tp = NULL;
const u_int8_t *lp = NULL;
unsigned int optlen;
int err;
err = ipv6_find_hdr(skb, &ptr,
(par->match == &hbh_mt6_reg[0]) ?
NEXTHDR_HOP : NEXTHDR_DEST, NULL);
if (err < 0) {
if (err != -ENOENT)
par->hotdrop = true;
return false;
}
oh = skb_header_pointer(skb, ptr, sizeof(_optsh), &_optsh);
if (oh == NULL) {
par->hotdrop = true;
return false;
}
hdrlen = ipv6_optlen(oh);
if (skb->len - ptr < hdrlen) {
/* Packet smaller than it's length field */
return false;
}
pr_debug("IPv6 OPTS LEN %u %u ", hdrlen, oh->hdrlen);
pr_debug("len %02X %04X %02X ",
optinfo->hdrlen, hdrlen,
(!(optinfo->flags & IP6T_OPTS_LEN) ||
((optinfo->hdrlen == hdrlen) ^
!!(optinfo->invflags & IP6T_OPTS_INV_LEN))));
ret = (oh != NULL) &&
(!(optinfo->flags & IP6T_OPTS_LEN) ||
((optinfo->hdrlen == hdrlen) ^
!!(optinfo->invflags & IP6T_OPTS_INV_LEN)));
ptr += 2;
hdrlen -= 2;
if (!(optinfo->flags & IP6T_OPTS_OPTS)) {
return ret;
} else {
pr_debug("Strict ");
pr_debug("#%d ", optinfo->optsnr);
for (temp = 0; temp < optinfo->optsnr; temp++) {
/* type field exists ? */
if (hdrlen < 1)
break;
tp = skb_header_pointer(skb, ptr, sizeof(_opttype),
&_opttype);
if (tp == NULL)
break;
/* Type check */
if (*tp != (optinfo->opts[temp] & 0xFF00) >> 8) {
pr_debug("Tbad %02X %02X\n", *tp,
(optinfo->opts[temp] & 0xFF00) >> 8);
return false;
} else {
pr_debug("Tok ");
}
/* Length check */
if (*tp) {
u16 spec_len;
/* length field exists ? */
if (hdrlen < 2)
break;
lp = skb_header_pointer(skb, ptr + 1,
sizeof(_optlen),
&_optlen);
if (lp == NULL)
break;
spec_len = optinfo->opts[temp] & 0x00FF;
if (spec_len != 0x00FF && spec_len != *lp) {
pr_debug("Lbad %02X %04X\n", *lp,
spec_len);
return false;
}
pr_debug("Lok ");
optlen = *lp + 2;
} else {
pr_debug("Pad1\n");
optlen = 1;
}
/* Step to the next */
pr_debug("len%04X\n", optlen);
if ((ptr > skb->len - optlen || hdrlen < optlen) &&
temp < optinfo->optsnr - 1) {
pr_debug("new pointer is too large!\n");
break;
}
ptr += optlen;
hdrlen -= optlen;
}
if (temp == optinfo->optsnr)
return ret;
else
return false;
}
return false;
}
static int hbh_mt6_check(const struct xt_mtchk_param *par)
{
const struct ip6t_opts *optsinfo = par->matchinfo;
if (optsinfo->invflags & ~IP6T_OPTS_INV_MASK) {
pr_debug("unknown flags %X\n", optsinfo->invflags);
return -EINVAL;
}
if (optsinfo->flags & IP6T_OPTS_NSTRICT) {
pr_debug("Not strict - not implemented");
return -EINVAL;
}
return 0;
}
static struct xt_match hbh_mt6_reg[] __read_mostly = {
{
/* Note, hbh_mt6 relies on the order of hbh_mt6_reg */
.name = "hbh",
.family = NFPROTO_IPV6,
.match = hbh_mt6,
.matchsize = sizeof(struct ip6t_opts),
.checkentry = hbh_mt6_check,
.me = THIS_MODULE,
},
{
.name = "dst",
.family = NFPROTO_IPV6,
.match = hbh_mt6,
.matchsize = sizeof(struct ip6t_opts),
.checkentry = hbh_mt6_check,
.me = THIS_MODULE,
},
};
static int __init hbh_mt6_init(void)
{
return xt_register_matches(hbh_mt6_reg, ARRAY_SIZE(hbh_mt6_reg));
}
static void __exit hbh_mt6_exit(void)
{
xt_unregister_matches(hbh_mt6_reg, ARRAY_SIZE(hbh_mt6_reg));
}
module_init(hbh_mt6_init);
module_exit(hbh_mt6_exit);
| gpl-2.0 |
iskandar1023/Velvet-N4 | arch/sparc/kernel/prom_32.c | 9424 | 7659 | /*
* Procedures for creating, accessing and interpreting the device tree.
*
* Paul Mackerras August 1996.
* Copyright (C) 1996-2005 Paul Mackerras.
*
* Adapted for 64bit PowerPC by Dave Engebretsen and Peter Bergner.
* {engebret|bergner}@us.ibm.com
*
* Adapted for sparc32 by David S. Miller davem@davemloft.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.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/bootmem.h>
#include <asm/prom.h>
#include <asm/oplib.h>
#include <asm/leon.h>
#include <asm/leon_amba.h>
#include "prom.h"
void * __init prom_early_alloc(unsigned long size)
{
void *ret;
ret = __alloc_bootmem(size, SMP_CACHE_BYTES, 0UL);
if (ret != NULL)
memset(ret, 0, size);
prom_early_allocated += size;
return ret;
}
/* The following routines deal with the black magic of fully naming a
* node.
*
* Certain well known named nodes are just the simple name string.
*
* Actual devices have an address specifier appended to the base name
* string, like this "foo@addr". The "addr" can be in any number of
* formats, and the platform plus the type of the node determine the
* format and how it is constructed.
*
* For children of the ROOT node, the naming convention is fixed and
* determined by whether this is a sun4u or sun4v system.
*
* For children of other nodes, it is bus type specific. So
* we walk up the tree until we discover a "device_type" property
* we recognize and we go from there.
*/
static void __init sparc32_path_component(struct device_node *dp, char *tmp_buf)
{
struct linux_prom_registers *regs;
struct property *rprop;
rprop = of_find_property(dp, "reg", NULL);
if (!rprop)
return;
regs = rprop->value;
sprintf(tmp_buf, "%s@%x,%x",
dp->name,
regs->which_io, regs->phys_addr);
}
/* "name@slot,offset" */
static void __init sbus_path_component(struct device_node *dp, char *tmp_buf)
{
struct linux_prom_registers *regs;
struct property *prop;
prop = of_find_property(dp, "reg", NULL);
if (!prop)
return;
regs = prop->value;
sprintf(tmp_buf, "%s@%x,%x",
dp->name,
regs->which_io,
regs->phys_addr);
}
/* "name@devnum[,func]" */
static void __init pci_path_component(struct device_node *dp, char *tmp_buf)
{
struct linux_prom_pci_registers *regs;
struct property *prop;
unsigned int devfn;
prop = of_find_property(dp, "reg", NULL);
if (!prop)
return;
regs = prop->value;
devfn = (regs->phys_hi >> 8) & 0xff;
if (devfn & 0x07) {
sprintf(tmp_buf, "%s@%x,%x",
dp->name,
devfn >> 3,
devfn & 0x07);
} else {
sprintf(tmp_buf, "%s@%x",
dp->name,
devfn >> 3);
}
}
/* "name@addrhi,addrlo" */
static void __init ebus_path_component(struct device_node *dp, char *tmp_buf)
{
struct linux_prom_registers *regs;
struct property *prop;
prop = of_find_property(dp, "reg", NULL);
if (!prop)
return;
regs = prop->value;
sprintf(tmp_buf, "%s@%x,%x",
dp->name,
regs->which_io, regs->phys_addr);
}
/* "name:vendor:device@irq,addrlo" */
static void __init ambapp_path_component(struct device_node *dp, char *tmp_buf)
{
struct amba_prom_registers *regs;
unsigned int *intr, *device, *vendor, reg0;
struct property *prop;
int interrupt = 0;
/* In order to get a unique ID in the device tree (multiple AMBA devices
* may have the same name) the node number is printed
*/
prop = of_find_property(dp, "reg", NULL);
if (!prop) {
reg0 = (unsigned int)dp->phandle;
} else {
regs = prop->value;
reg0 = regs->phys_addr;
}
/* Not all cores have Interrupt */
prop = of_find_property(dp, "interrupts", NULL);
if (!prop)
intr = &interrupt; /* IRQ0 does not exist */
else
intr = prop->value;
prop = of_find_property(dp, "vendor", NULL);
if (!prop)
return;
vendor = prop->value;
prop = of_find_property(dp, "device", NULL);
if (!prop)
return;
device = prop->value;
sprintf(tmp_buf, "%s:%d:%d@%x,%x",
dp->name, *vendor, *device,
*intr, reg0);
}
static void __init __build_path_component(struct device_node *dp, char *tmp_buf)
{
struct device_node *parent = dp->parent;
if (parent != NULL) {
if (!strcmp(parent->type, "pci") ||
!strcmp(parent->type, "pciex"))
return pci_path_component(dp, tmp_buf);
if (!strcmp(parent->type, "sbus"))
return sbus_path_component(dp, tmp_buf);
if (!strcmp(parent->type, "ebus"))
return ebus_path_component(dp, tmp_buf);
if (!strcmp(parent->type, "ambapp"))
return ambapp_path_component(dp, tmp_buf);
/* "isa" is handled with platform naming */
}
/* Use platform naming convention. */
return sparc32_path_component(dp, tmp_buf);
}
char * __init build_path_component(struct device_node *dp)
{
char tmp_buf[64], *n;
tmp_buf[0] = '\0';
__build_path_component(dp, tmp_buf);
if (tmp_buf[0] == '\0')
strcpy(tmp_buf, dp->name);
n = prom_early_alloc(strlen(tmp_buf) + 1);
strcpy(n, tmp_buf);
return n;
}
extern void restore_current(void);
void __init of_console_init(void)
{
char *msg = "OF stdout device is: %s\n";
struct device_node *dp;
unsigned long flags;
const char *type;
phandle node;
int skip, tmp, fd;
of_console_path = prom_early_alloc(256);
switch (prom_vers) {
case PROM_V0:
skip = 0;
switch (*romvec->pv_stdout) {
case PROMDEV_SCREEN:
type = "display";
break;
case PROMDEV_TTYB:
skip = 1;
/* FALLTHRU */
case PROMDEV_TTYA:
type = "serial";
break;
default:
prom_printf("Invalid PROM_V0 stdout value %u\n",
*romvec->pv_stdout);
prom_halt();
}
tmp = skip;
for_each_node_by_type(dp, type) {
if (!tmp--)
break;
}
if (!dp) {
prom_printf("Cannot find PROM_V0 console node.\n");
prom_halt();
}
of_console_device = dp;
strcpy(of_console_path, dp->full_name);
if (!strcmp(type, "serial")) {
strcat(of_console_path,
(skip ? ":b" : ":a"));
}
break;
default:
case PROM_V2:
case PROM_V3:
fd = *romvec->pv_v2bootargs.fd_stdout;
spin_lock_irqsave(&prom_lock, flags);
node = (*romvec->pv_v2devops.v2_inst2pkg)(fd);
restore_current();
spin_unlock_irqrestore(&prom_lock, flags);
if (!node) {
prom_printf("Cannot resolve stdout node from "
"instance %08x.\n", fd);
prom_halt();
}
dp = of_find_node_by_phandle(node);
type = of_get_property(dp, "device_type", NULL);
if (!type) {
prom_printf("Console stdout lacks "
"device_type property.\n");
prom_halt();
}
if (strcmp(type, "display") && strcmp(type, "serial")) {
prom_printf("Console device_type is neither display "
"nor serial.\n");
prom_halt();
}
of_console_device = dp;
if (prom_vers == PROM_V2) {
strcpy(of_console_path, dp->full_name);
switch (*romvec->pv_stdout) {
case PROMDEV_TTYA:
strcat(of_console_path, ":a");
break;
case PROMDEV_TTYB:
strcat(of_console_path, ":b");
break;
}
} else {
const char *path;
dp = of_find_node_by_path("/");
path = of_get_property(dp, "stdout-path", NULL);
if (!path) {
prom_printf("No stdout-path in root node.\n");
prom_halt();
}
strcpy(of_console_path, path);
}
break;
}
of_console_options = strrchr(of_console_path, ':');
if (of_console_options) {
of_console_options++;
if (*of_console_options == '\0')
of_console_options = NULL;
}
printk(msg, of_console_path);
}
void __init of_fill_in_cpu_data(void)
{
}
void __init irq_trans_init(struct device_node *dp)
{
}
| gpl-2.0 |
genesi/linux-testing | arch/mips/sgi-ip27/ip27-klconfig.c | 10192 | 2941 | /*
* Copyright (C) 1999, 2000 Ralf Baechle (ralf@gnu.org)
* Copyright (C) 1999, 2000 Silicon Graphics, Inc.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/kernel_stat.h>
#include <linux/param.h>
#include <linux/timex.h>
#include <linux/mm.h>
#include <asm/sn/klconfig.h>
#include <asm/sn/arch.h>
#include <asm/sn/gda.h>
klinfo_t *find_component(lboard_t *brd, klinfo_t *kli, unsigned char struct_type)
{
int index, j;
if (kli == (klinfo_t *)NULL) {
index = 0;
} else {
for (j = 0; j < KLCF_NUM_COMPS(brd); j++)
if (kli == KLCF_COMP(brd, j))
break;
index = j;
if (index == KLCF_NUM_COMPS(brd)) {
printk("find_component: Bad pointer: 0x%p\n", kli);
return (klinfo_t *)NULL;
}
index++; /* next component */
}
for (; index < KLCF_NUM_COMPS(brd); index++) {
kli = KLCF_COMP(brd, index);
if (KLCF_COMP_TYPE(kli) == struct_type)
return kli;
}
/* Didn't find it. */
return (klinfo_t *)NULL;
}
klinfo_t *find_first_component(lboard_t *brd, unsigned char struct_type)
{
return find_component(brd, (klinfo_t *)NULL, struct_type);
}
lboard_t *find_lboard(lboard_t *start, unsigned char brd_type)
{
/* Search all boards stored on this node. */
while (start) {
if (start->brd_type == brd_type)
return start;
start = KLCF_NEXT(start);
}
/* Didn't find it. */
return (lboard_t *)NULL;
}
lboard_t *find_lboard_class(lboard_t *start, unsigned char brd_type)
{
/* Search all boards stored on this node. */
while (start) {
if (KLCLASS(start->brd_type) == KLCLASS(brd_type))
return start;
start = KLCF_NEXT(start);
}
/* Didn't find it. */
return (lboard_t *)NULL;
}
cnodeid_t get_cpu_cnode(cpuid_t cpu)
{
return CPUID_TO_COMPACT_NODEID(cpu);
}
klcpu_t *nasid_slice_to_cpuinfo(nasid_t nasid, int slice)
{
lboard_t *brd;
klcpu_t *acpu;
if (!(brd = find_lboard((lboard_t *)KL_CONFIG_INFO(nasid), KLTYPE_IP27)))
return (klcpu_t *)NULL;
if (!(acpu = (klcpu_t *)find_first_component(brd, KLSTRUCT_CPU)))
return (klcpu_t *)NULL;
do {
if ((acpu->cpu_info.physid) == slice)
return acpu;
} while ((acpu = (klcpu_t *)find_component(brd, (klinfo_t *)acpu,
KLSTRUCT_CPU)));
return (klcpu_t *)NULL;
}
klcpu_t *sn_get_cpuinfo(cpuid_t cpu)
{
nasid_t nasid;
int slice;
klcpu_t *acpu;
gda_t *gdap = GDA;
cnodeid_t cnode;
if (!(cpu < MAXCPUS)) {
printk("sn_get_cpuinfo: illegal cpuid 0x%lx\n", cpu);
return NULL;
}
cnode = get_cpu_cnode(cpu);
if (cnode == INVALID_CNODEID)
return NULL;
if ((nasid = gdap->g_nasidtable[cnode]) == INVALID_NASID)
return NULL;
for (slice = 0; slice < CPUS_PER_NODE; slice++) {
acpu = nasid_slice_to_cpuinfo(nasid, slice);
if (acpu && acpu->cpu_info.virtid == cpu)
return acpu;
}
return NULL;
}
int get_cpu_slice(cpuid_t cpu)
{
klcpu_t *acpu;
if ((acpu = sn_get_cpuinfo(cpu)) == NULL)
return -1;
return acpu->cpu_info.physid;
}
| gpl-2.0 |
KangBangKreations/KangBangKore-Kernel | lib/textsearch.c | 10704 | 9800 | /*
* lib/textsearch.c Generic text search interface
*
* 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: Thomas Graf <tgraf@suug.ch>
* Pablo Neira Ayuso <pablo@netfilter.org>
*
* ==========================================================================
*
* INTRODUCTION
*
* The textsearch infrastructure provides text searching facilities for
* both linear and non-linear data. Individual search algorithms are
* implemented in modules and chosen by the user.
*
* ARCHITECTURE
*
* User
* +----------------+
* | finish()|<--------------(6)-----------------+
* |get_next_block()|<--------------(5)---------------+ |
* | | Algorithm | |
* | | +------------------------------+
* | | | init() find() destroy() |
* | | +------------------------------+
* | | Core API ^ ^ ^
* | | +---------------+ (2) (4) (8)
* | (1)|----->| prepare() |---+ | |
* | (3)|----->| find()/next() |-----------+ |
* | (7)|----->| destroy() |----------------------+
* +----------------+ +---------------+
*
* (1) User configures a search by calling _prepare() specifying the
* search parameters such as the pattern and algorithm name.
* (2) Core requests the algorithm to allocate and initialize a search
* configuration according to the specified parameters.
* (3) User starts the search(es) by calling _find() or _next() to
* fetch subsequent occurrences. A state variable is provided
* to the algorithm to store persistent variables.
* (4) Core eventually resets the search offset and forwards the find()
* request to the algorithm.
* (5) Algorithm calls get_next_block() provided by the user continuously
* to fetch the data to be searched in block by block.
* (6) Algorithm invokes finish() after the last call to get_next_block
* to clean up any leftovers from get_next_block. (Optional)
* (7) User destroys the configuration by calling _destroy().
* (8) Core notifies the algorithm to destroy algorithm specific
* allocations. (Optional)
*
* USAGE
*
* Before a search can be performed, a configuration must be created
* by calling textsearch_prepare() specifying the searching algorithm,
* the pattern to look for and flags. As a flag, you can set TS_IGNORECASE
* to perform case insensitive matching. But it might slow down
* performance of algorithm, so you should use it at own your risk.
* The returned configuration may then be used for an arbitrary
* amount of times and even in parallel as long as a separate struct
* ts_state variable is provided to every instance.
*
* The actual search is performed by either calling textsearch_find_-
* continuous() for linear data or by providing an own get_next_block()
* implementation and calling textsearch_find(). Both functions return
* the position of the first occurrence of the pattern or UINT_MAX if
* no match was found. Subsequent occurrences can be found by calling
* textsearch_next() regardless of the linearity of the data.
*
* Once you're done using a configuration it must be given back via
* textsearch_destroy.
*
* EXAMPLE
*
* int pos;
* struct ts_config *conf;
* struct ts_state state;
* const char *pattern = "chicken";
* const char *example = "We dance the funky chicken";
*
* conf = textsearch_prepare("kmp", pattern, strlen(pattern),
* GFP_KERNEL, TS_AUTOLOAD);
* if (IS_ERR(conf)) {
* err = PTR_ERR(conf);
* goto errout;
* }
*
* pos = textsearch_find_continuous(conf, &state, example, strlen(example));
* if (pos != UINT_MAX)
* panic("Oh my god, dancing chickens at %d\n", pos);
*
* textsearch_destroy(conf);
* ==========================================================================
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/rculist.h>
#include <linux/rcupdate.h>
#include <linux/err.h>
#include <linux/textsearch.h>
#include <linux/slab.h>
static LIST_HEAD(ts_ops);
static DEFINE_SPINLOCK(ts_mod_lock);
static inline struct ts_ops *lookup_ts_algo(const char *name)
{
struct ts_ops *o;
rcu_read_lock();
list_for_each_entry_rcu(o, &ts_ops, list) {
if (!strcmp(name, o->name)) {
if (!try_module_get(o->owner))
o = NULL;
rcu_read_unlock();
return o;
}
}
rcu_read_unlock();
return NULL;
}
/**
* textsearch_register - register a textsearch module
* @ops: operations lookup table
*
* This function must be called by textsearch modules to announce
* their presence. The specified &@ops must have %name set to a
* unique identifier and the callbacks find(), init(), get_pattern(),
* and get_pattern_len() must be implemented.
*
* Returns 0 or -EEXISTS if another module has already registered
* with same name.
*/
int textsearch_register(struct ts_ops *ops)
{
int err = -EEXIST;
struct ts_ops *o;
if (ops->name == NULL || ops->find == NULL || ops->init == NULL ||
ops->get_pattern == NULL || ops->get_pattern_len == NULL)
return -EINVAL;
spin_lock(&ts_mod_lock);
list_for_each_entry(o, &ts_ops, list) {
if (!strcmp(ops->name, o->name))
goto errout;
}
list_add_tail_rcu(&ops->list, &ts_ops);
err = 0;
errout:
spin_unlock(&ts_mod_lock);
return err;
}
/**
* textsearch_unregister - unregister a textsearch module
* @ops: operations lookup table
*
* This function must be called by textsearch modules to announce
* their disappearance for examples when the module gets unloaded.
* The &ops parameter must be the same as the one during the
* registration.
*
* Returns 0 on success or -ENOENT if no matching textsearch
* registration was found.
*/
int textsearch_unregister(struct ts_ops *ops)
{
int err = 0;
struct ts_ops *o;
spin_lock(&ts_mod_lock);
list_for_each_entry(o, &ts_ops, list) {
if (o == ops) {
list_del_rcu(&o->list);
goto out;
}
}
err = -ENOENT;
out:
spin_unlock(&ts_mod_lock);
return err;
}
struct ts_linear_state
{
unsigned int len;
const void *data;
};
static unsigned int get_linear_data(unsigned int consumed, const u8 **dst,
struct ts_config *conf,
struct ts_state *state)
{
struct ts_linear_state *st = (struct ts_linear_state *) state->cb;
if (likely(consumed < st->len)) {
*dst = st->data + consumed;
return st->len - consumed;
}
return 0;
}
/**
* textsearch_find_continuous - search a pattern in continuous/linear data
* @conf: search configuration
* @state: search state
* @data: data to search in
* @len: length of data
*
* A simplified version of textsearch_find() for continuous/linear data.
* Call textsearch_next() to retrieve subsequent matches.
*
* Returns the position of first occurrence of the pattern or
* %UINT_MAX if no occurrence was found.
*/
unsigned int textsearch_find_continuous(struct ts_config *conf,
struct ts_state *state,
const void *data, unsigned int len)
{
struct ts_linear_state *st = (struct ts_linear_state *) state->cb;
conf->get_next_block = get_linear_data;
st->data = data;
st->len = len;
return textsearch_find(conf, state);
}
/**
* textsearch_prepare - Prepare a search
* @algo: name of search algorithm
* @pattern: pattern data
* @len: length of pattern
* @gfp_mask: allocation mask
* @flags: search flags
*
* Looks up the search algorithm module and creates a new textsearch
* configuration for the specified pattern. Upon completion all
* necessary refcnts are held and the configuration must be put back
* using textsearch_put() after usage.
*
* Note: The format of the pattern may not be compatible between
* the various search algorithms.
*
* Returns a new textsearch configuration according to the specified
* parameters or a ERR_PTR(). If a zero length pattern is passed, this
* function returns EINVAL.
*/
struct ts_config *textsearch_prepare(const char *algo, const void *pattern,
unsigned int len, gfp_t gfp_mask, int flags)
{
int err = -ENOENT;
struct ts_config *conf;
struct ts_ops *ops;
if (len == 0)
return ERR_PTR(-EINVAL);
ops = lookup_ts_algo(algo);
#ifdef CONFIG_MODULES
/*
* Why not always autoload you may ask. Some users are
* in a situation where requesting a module may deadlock,
* especially when the module is located on a NFS mount.
*/
if (ops == NULL && flags & TS_AUTOLOAD) {
request_module("ts_%s", algo);
ops = lookup_ts_algo(algo);
}
#endif
if (ops == NULL)
goto errout;
conf = ops->init(pattern, len, gfp_mask, flags);
if (IS_ERR(conf)) {
err = PTR_ERR(conf);
goto errout;
}
conf->ops = ops;
return conf;
errout:
if (ops)
module_put(ops->owner);
return ERR_PTR(err);
}
/**
* textsearch_destroy - destroy a search configuration
* @conf: search configuration
*
* Releases all references of the configuration and frees
* up the memory.
*/
void textsearch_destroy(struct ts_config *conf)
{
if (conf->ops) {
if (conf->ops->destroy)
conf->ops->destroy(conf);
module_put(conf->ops->owner);
}
kfree(conf);
}
EXPORT_SYMBOL(textsearch_register);
EXPORT_SYMBOL(textsearch_unregister);
EXPORT_SYMBOL(textsearch_prepare);
EXPORT_SYMBOL(textsearch_find_continuous);
EXPORT_SYMBOL(textsearch_destroy);
| gpl-2.0 |
Negamann303/kernel-ng2-negalite | drivers/scsi/pcmcia/aha152x_stub.c | 12752 | 6854 | /*======================================================================
A driver for Adaptec AHA152X-compatible PCMCIA SCSI cards.
This driver supports the Adaptec AHA-1460, the New Media Bus
Toaster, and the New Media Toast & Jam.
aha152x_cs.c 1.54 2000/06/12 21:27:25
The contents of this file are subject to the Mozilla Public
License Version 1.1 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of
the License at http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS
IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
implied. See the License for the specific language governing
rights and limitations under the License.
The initial developer of the original code is David A. Hinds
<dahinds@users.sourceforge.net>. Portions created by David A. Hinds
are Copyright (C) 1999 David A. Hinds. All Rights Reserved.
Alternatively, the contents of this file may be used under the
terms of the GNU General Public License version 2 (the "GPL"), in which
case the provisions of the GPL are applicable instead of the
above. If you wish to allow the use of your version of this file
only under the terms of the GPL and not to allow others to use
your version of this file under the MPL, indicate your decision
by deleting the provisions above and replace them with the notice
and other provisions required by the GPL. If you do not delete
the provisions above, a recipient may use your version of this
file under either the MPL or the GPL.
======================================================================*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/ioport.h>
#include <scsi/scsi.h>
#include <linux/major.h>
#include <linux/blkdev.h>
#include <scsi/scsi_ioctl.h>
#include "scsi.h"
#include <scsi/scsi_host.h>
#include "aha152x.h"
#include <pcmcia/cistpl.h>
#include <pcmcia/ds.h>
/*====================================================================*/
/* Parameters that can be set with 'insmod' */
/* SCSI bus setup options */
static int host_id = 7;
static int reconnect = 1;
static int parity = 1;
static int synchronous = 1;
static int reset_delay = 100;
static int ext_trans = 0;
module_param(host_id, int, 0);
module_param(reconnect, int, 0);
module_param(parity, int, 0);
module_param(synchronous, int, 0);
module_param(reset_delay, int, 0);
module_param(ext_trans, int, 0);
MODULE_LICENSE("Dual MPL/GPL");
/*====================================================================*/
typedef struct scsi_info_t {
struct pcmcia_device *p_dev;
struct Scsi_Host *host;
} scsi_info_t;
static void aha152x_release_cs(struct pcmcia_device *link);
static void aha152x_detach(struct pcmcia_device *p_dev);
static int aha152x_config_cs(struct pcmcia_device *link);
static int aha152x_probe(struct pcmcia_device *link)
{
scsi_info_t *info;
dev_dbg(&link->dev, "aha152x_attach()\n");
/* Create new SCSI device */
info = kzalloc(sizeof(*info), GFP_KERNEL);
if (!info) return -ENOMEM;
info->p_dev = link;
link->priv = info;
link->config_flags |= CONF_ENABLE_IRQ | CONF_AUTO_SET_IO;
link->config_regs = PRESENT_OPTION;
return aha152x_config_cs(link);
} /* aha152x_attach */
/*====================================================================*/
static void aha152x_detach(struct pcmcia_device *link)
{
dev_dbg(&link->dev, "aha152x_detach\n");
aha152x_release_cs(link);
/* Unlink device structure, free bits */
kfree(link->priv);
} /* aha152x_detach */
/*====================================================================*/
static int aha152x_config_check(struct pcmcia_device *p_dev, void *priv_data)
{
p_dev->io_lines = 10;
/* For New Media T&J, look for a SCSI window */
if ((p_dev->resource[0]->end < 0x20) &&
(p_dev->resource[1]->end >= 0x20))
p_dev->resource[0]->start = p_dev->resource[1]->start;
if (p_dev->resource[0]->start >= 0xffff)
return -EINVAL;
p_dev->resource[1]->start = p_dev->resource[1]->end = 0;
p_dev->resource[0]->end = 0x20;
p_dev->resource[0]->flags &= ~IO_DATA_PATH_WIDTH;
p_dev->resource[0]->flags |= IO_DATA_PATH_WIDTH_AUTO;
return pcmcia_request_io(p_dev);
}
static int aha152x_config_cs(struct pcmcia_device *link)
{
scsi_info_t *info = link->priv;
struct aha152x_setup s;
int ret;
struct Scsi_Host *host;
dev_dbg(&link->dev, "aha152x_config\n");
ret = pcmcia_loop_config(link, aha152x_config_check, NULL);
if (ret)
goto failed;
if (!link->irq)
goto failed;
ret = pcmcia_enable_device(link);
if (ret)
goto failed;
/* Set configuration options for the aha152x driver */
memset(&s, 0, sizeof(s));
s.conf = "PCMCIA setup";
s.io_port = link->resource[0]->start;
s.irq = link->irq;
s.scsiid = host_id;
s.reconnect = reconnect;
s.parity = parity;
s.synchronous = synchronous;
s.delay = reset_delay;
if (ext_trans)
s.ext_trans = ext_trans;
host = aha152x_probe_one(&s);
if (host == NULL) {
printk(KERN_INFO "aha152x_cs: no SCSI devices found\n");
goto failed;
}
info->host = host;
return 0;
failed:
aha152x_release_cs(link);
return -ENODEV;
}
static void aha152x_release_cs(struct pcmcia_device *link)
{
scsi_info_t *info = link->priv;
aha152x_release(info->host);
pcmcia_disable_device(link);
}
static int aha152x_resume(struct pcmcia_device *link)
{
scsi_info_t *info = link->priv;
aha152x_host_reset_host(info->host);
return 0;
}
static const struct pcmcia_device_id aha152x_ids[] = {
PCMCIA_DEVICE_PROD_ID123("New Media", "SCSI", "Bus Toaster", 0xcdf7e4cc, 0x35f26476, 0xa8851d6e),
PCMCIA_DEVICE_PROD_ID123("NOTEWORTHY", "SCSI", "Bus Toaster", 0xad89c6e8, 0x35f26476, 0xa8851d6e),
PCMCIA_DEVICE_PROD_ID12("Adaptec, Inc.", "APA-1460 SCSI Host Adapter", 0x24ba9738, 0x3a3c3d20),
PCMCIA_DEVICE_PROD_ID12("New Media Corporation", "Multimedia Sound/SCSI", 0x085a850b, 0x80a6535c),
PCMCIA_DEVICE_PROD_ID12("NOTEWORTHY", "NWCOMB02 SCSI/AUDIO COMBO CARD", 0xad89c6e8, 0x5f9a615b),
PCMCIA_DEVICE_NULL,
};
MODULE_DEVICE_TABLE(pcmcia, aha152x_ids);
static struct pcmcia_driver aha152x_cs_driver = {
.owner = THIS_MODULE,
.name = "aha152x_cs",
.probe = aha152x_probe,
.remove = aha152x_detach,
.id_table = aha152x_ids,
.resume = aha152x_resume,
};
static int __init init_aha152x_cs(void)
{
return pcmcia_register_driver(&aha152x_cs_driver);
}
static void __exit exit_aha152x_cs(void)
{
pcmcia_unregister_driver(&aha152x_cs_driver);
}
module_init(init_aha152x_cs);
module_exit(exit_aha152x_cs);
| gpl-2.0 |
mdeejay/msm7x30-ics | fs/ubifs/debug.c | 209 | 75193 | /*
* This file is part of UBIFS.
*
* Copyright (C) 2006-2008 Nokia Corporation
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Authors: Artem Bityutskiy (Битюцкий Артём)
* Adrian Hunter
*/
/*
* This file implements most of the debugging stuff which is compiled in only
* when it is enabled. But some debugging check functions are implemented in
* corresponding subsystem, just because they are closely related and utilize
* various local functions of those subsystems.
*/
#define UBIFS_DBG_PRESERVE_UBI
#include "ubifs.h"
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/debugfs.h>
#include <linux/math64.h>
#include <linux/slab.h>
#ifdef CONFIG_UBIFS_FS_DEBUG
DEFINE_SPINLOCK(dbg_lock);
static char dbg_key_buf0[128];
static char dbg_key_buf1[128];
unsigned int ubifs_msg_flags = UBIFS_MSG_FLAGS_DEFAULT;
unsigned int ubifs_chk_flags = UBIFS_CHK_FLAGS_DEFAULT;
unsigned int ubifs_tst_flags;
module_param_named(debug_msgs, ubifs_msg_flags, uint, S_IRUGO | S_IWUSR);
module_param_named(debug_chks, ubifs_chk_flags, uint, S_IRUGO | S_IWUSR);
module_param_named(debug_tsts, ubifs_tst_flags, uint, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug_msgs, "Debug message type flags");
MODULE_PARM_DESC(debug_chks, "Debug check flags");
MODULE_PARM_DESC(debug_tsts, "Debug special test flags");
static const char *get_key_fmt(int fmt)
{
switch (fmt) {
case UBIFS_SIMPLE_KEY_FMT:
return "simple";
default:
return "unknown/invalid format";
}
}
static const char *get_key_hash(int hash)
{
switch (hash) {
case UBIFS_KEY_HASH_R5:
return "R5";
case UBIFS_KEY_HASH_TEST:
return "test";
default:
return "unknown/invalid name hash";
}
}
static const char *get_key_type(int type)
{
switch (type) {
case UBIFS_INO_KEY:
return "inode";
case UBIFS_DENT_KEY:
return "direntry";
case UBIFS_XENT_KEY:
return "xentry";
case UBIFS_DATA_KEY:
return "data";
case UBIFS_TRUN_KEY:
return "truncate";
default:
return "unknown/invalid key";
}
}
static void sprintf_key(const struct ubifs_info *c, const union ubifs_key *key,
char *buffer)
{
char *p = buffer;
int type = key_type(c, key);
if (c->key_fmt == UBIFS_SIMPLE_KEY_FMT) {
switch (type) {
case UBIFS_INO_KEY:
sprintf(p, "(%lu, %s)", (unsigned long)key_inum(c, key),
get_key_type(type));
break;
case UBIFS_DENT_KEY:
case UBIFS_XENT_KEY:
sprintf(p, "(%lu, %s, %#08x)",
(unsigned long)key_inum(c, key),
get_key_type(type), key_hash(c, key));
break;
case UBIFS_DATA_KEY:
sprintf(p, "(%lu, %s, %u)",
(unsigned long)key_inum(c, key),
get_key_type(type), key_block(c, key));
break;
case UBIFS_TRUN_KEY:
sprintf(p, "(%lu, %s)",
(unsigned long)key_inum(c, key),
get_key_type(type));
break;
default:
sprintf(p, "(bad key type: %#08x, %#08x)",
key->u32[0], key->u32[1]);
}
} else
sprintf(p, "bad key format %d", c->key_fmt);
}
const char *dbg_key_str0(const struct ubifs_info *c, const union ubifs_key *key)
{
/* dbg_lock must be held */
sprintf_key(c, key, dbg_key_buf0);
return dbg_key_buf0;
}
const char *dbg_key_str1(const struct ubifs_info *c, const union ubifs_key *key)
{
/* dbg_lock must be held */
sprintf_key(c, key, dbg_key_buf1);
return dbg_key_buf1;
}
const char *dbg_ntype(int type)
{
switch (type) {
case UBIFS_PAD_NODE:
return "padding node";
case UBIFS_SB_NODE:
return "superblock node";
case UBIFS_MST_NODE:
return "master node";
case UBIFS_REF_NODE:
return "reference node";
case UBIFS_INO_NODE:
return "inode node";
case UBIFS_DENT_NODE:
return "direntry node";
case UBIFS_XENT_NODE:
return "xentry node";
case UBIFS_DATA_NODE:
return "data node";
case UBIFS_TRUN_NODE:
return "truncate node";
case UBIFS_IDX_NODE:
return "indexing node";
case UBIFS_CS_NODE:
return "commit start node";
case UBIFS_ORPH_NODE:
return "orphan node";
default:
return "unknown node";
}
}
static const char *dbg_gtype(int type)
{
switch (type) {
case UBIFS_NO_NODE_GROUP:
return "no node group";
case UBIFS_IN_NODE_GROUP:
return "in node group";
case UBIFS_LAST_OF_NODE_GROUP:
return "last of node group";
default:
return "unknown";
}
}
const char *dbg_cstate(int cmt_state)
{
switch (cmt_state) {
case COMMIT_RESTING:
return "commit resting";
case COMMIT_BACKGROUND:
return "background commit requested";
case COMMIT_REQUIRED:
return "commit required";
case COMMIT_RUNNING_BACKGROUND:
return "BACKGROUND commit running";
case COMMIT_RUNNING_REQUIRED:
return "commit running and required";
case COMMIT_BROKEN:
return "broken commit";
default:
return "unknown commit state";
}
}
const char *dbg_jhead(int jhead)
{
switch (jhead) {
case GCHD:
return "0 (GC)";
case BASEHD:
return "1 (base)";
case DATAHD:
return "2 (data)";
default:
return "unknown journal head";
}
}
static void dump_ch(const struct ubifs_ch *ch)
{
printk(KERN_DEBUG "\tmagic %#x\n", le32_to_cpu(ch->magic));
printk(KERN_DEBUG "\tcrc %#x\n", le32_to_cpu(ch->crc));
printk(KERN_DEBUG "\tnode_type %d (%s)\n", ch->node_type,
dbg_ntype(ch->node_type));
printk(KERN_DEBUG "\tgroup_type %d (%s)\n", ch->group_type,
dbg_gtype(ch->group_type));
printk(KERN_DEBUG "\tsqnum %llu\n",
(unsigned long long)le64_to_cpu(ch->sqnum));
printk(KERN_DEBUG "\tlen %u\n", le32_to_cpu(ch->len));
}
void dbg_dump_inode(const struct ubifs_info *c, const struct inode *inode)
{
const struct ubifs_inode *ui = ubifs_inode(inode);
printk(KERN_DEBUG "Dump in-memory inode:");
printk(KERN_DEBUG "\tinode %lu\n", inode->i_ino);
printk(KERN_DEBUG "\tsize %llu\n",
(unsigned long long)i_size_read(inode));
printk(KERN_DEBUG "\tnlink %u\n", inode->i_nlink);
printk(KERN_DEBUG "\tuid %u\n", (unsigned int)inode->i_uid);
printk(KERN_DEBUG "\tgid %u\n", (unsigned int)inode->i_gid);
printk(KERN_DEBUG "\tatime %u.%u\n",
(unsigned int)inode->i_atime.tv_sec,
(unsigned int)inode->i_atime.tv_nsec);
printk(KERN_DEBUG "\tmtime %u.%u\n",
(unsigned int)inode->i_mtime.tv_sec,
(unsigned int)inode->i_mtime.tv_nsec);
printk(KERN_DEBUG "\tctime %u.%u\n",
(unsigned int)inode->i_ctime.tv_sec,
(unsigned int)inode->i_ctime.tv_nsec);
printk(KERN_DEBUG "\tcreat_sqnum %llu\n", ui->creat_sqnum);
printk(KERN_DEBUG "\txattr_size %u\n", ui->xattr_size);
printk(KERN_DEBUG "\txattr_cnt %u\n", ui->xattr_cnt);
printk(KERN_DEBUG "\txattr_names %u\n", ui->xattr_names);
printk(KERN_DEBUG "\tdirty %u\n", ui->dirty);
printk(KERN_DEBUG "\txattr %u\n", ui->xattr);
printk(KERN_DEBUG "\tbulk_read %u\n", ui->xattr);
printk(KERN_DEBUG "\tsynced_i_size %llu\n",
(unsigned long long)ui->synced_i_size);
printk(KERN_DEBUG "\tui_size %llu\n",
(unsigned long long)ui->ui_size);
printk(KERN_DEBUG "\tflags %d\n", ui->flags);
printk(KERN_DEBUG "\tcompr_type %d\n", ui->compr_type);
printk(KERN_DEBUG "\tlast_page_read %lu\n", ui->last_page_read);
printk(KERN_DEBUG "\tread_in_a_row %lu\n", ui->read_in_a_row);
printk(KERN_DEBUG "\tdata_len %d\n", ui->data_len);
}
void dbg_dump_node(const struct ubifs_info *c, const void *node)
{
int i, n;
union ubifs_key key;
const struct ubifs_ch *ch = node;
if (dbg_failure_mode)
return;
/* If the magic is incorrect, just hexdump the first bytes */
if (le32_to_cpu(ch->magic) != UBIFS_NODE_MAGIC) {
printk(KERN_DEBUG "Not a node, first %zu bytes:", UBIFS_CH_SZ);
print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 32, 1,
(void *)node, UBIFS_CH_SZ, 1);
return;
}
spin_lock(&dbg_lock);
dump_ch(node);
switch (ch->node_type) {
case UBIFS_PAD_NODE:
{
const struct ubifs_pad_node *pad = node;
printk(KERN_DEBUG "\tpad_len %u\n",
le32_to_cpu(pad->pad_len));
break;
}
case UBIFS_SB_NODE:
{
const struct ubifs_sb_node *sup = node;
unsigned int sup_flags = le32_to_cpu(sup->flags);
printk(KERN_DEBUG "\tkey_hash %d (%s)\n",
(int)sup->key_hash, get_key_hash(sup->key_hash));
printk(KERN_DEBUG "\tkey_fmt %d (%s)\n",
(int)sup->key_fmt, get_key_fmt(sup->key_fmt));
printk(KERN_DEBUG "\tflags %#x\n", sup_flags);
printk(KERN_DEBUG "\t big_lpt %u\n",
!!(sup_flags & UBIFS_FLG_BIGLPT));
printk(KERN_DEBUG "\tmin_io_size %u\n",
le32_to_cpu(sup->min_io_size));
printk(KERN_DEBUG "\tleb_size %u\n",
le32_to_cpu(sup->leb_size));
printk(KERN_DEBUG "\tleb_cnt %u\n",
le32_to_cpu(sup->leb_cnt));
printk(KERN_DEBUG "\tmax_leb_cnt %u\n",
le32_to_cpu(sup->max_leb_cnt));
printk(KERN_DEBUG "\tmax_bud_bytes %llu\n",
(unsigned long long)le64_to_cpu(sup->max_bud_bytes));
printk(KERN_DEBUG "\tlog_lebs %u\n",
le32_to_cpu(sup->log_lebs));
printk(KERN_DEBUG "\tlpt_lebs %u\n",
le32_to_cpu(sup->lpt_lebs));
printk(KERN_DEBUG "\torph_lebs %u\n",
le32_to_cpu(sup->orph_lebs));
printk(KERN_DEBUG "\tjhead_cnt %u\n",
le32_to_cpu(sup->jhead_cnt));
printk(KERN_DEBUG "\tfanout %u\n",
le32_to_cpu(sup->fanout));
printk(KERN_DEBUG "\tlsave_cnt %u\n",
le32_to_cpu(sup->lsave_cnt));
printk(KERN_DEBUG "\tdefault_compr %u\n",
(int)le16_to_cpu(sup->default_compr));
printk(KERN_DEBUG "\trp_size %llu\n",
(unsigned long long)le64_to_cpu(sup->rp_size));
printk(KERN_DEBUG "\trp_uid %u\n",
le32_to_cpu(sup->rp_uid));
printk(KERN_DEBUG "\trp_gid %u\n",
le32_to_cpu(sup->rp_gid));
printk(KERN_DEBUG "\tfmt_version %u\n",
le32_to_cpu(sup->fmt_version));
printk(KERN_DEBUG "\ttime_gran %u\n",
le32_to_cpu(sup->time_gran));
printk(KERN_DEBUG "\tUUID %pUB\n",
sup->uuid);
break;
}
case UBIFS_MST_NODE:
{
const struct ubifs_mst_node *mst = node;
printk(KERN_DEBUG "\thighest_inum %llu\n",
(unsigned long long)le64_to_cpu(mst->highest_inum));
printk(KERN_DEBUG "\tcommit number %llu\n",
(unsigned long long)le64_to_cpu(mst->cmt_no));
printk(KERN_DEBUG "\tflags %#x\n",
le32_to_cpu(mst->flags));
printk(KERN_DEBUG "\tlog_lnum %u\n",
le32_to_cpu(mst->log_lnum));
printk(KERN_DEBUG "\troot_lnum %u\n",
le32_to_cpu(mst->root_lnum));
printk(KERN_DEBUG "\troot_offs %u\n",
le32_to_cpu(mst->root_offs));
printk(KERN_DEBUG "\troot_len %u\n",
le32_to_cpu(mst->root_len));
printk(KERN_DEBUG "\tgc_lnum %u\n",
le32_to_cpu(mst->gc_lnum));
printk(KERN_DEBUG "\tihead_lnum %u\n",
le32_to_cpu(mst->ihead_lnum));
printk(KERN_DEBUG "\tihead_offs %u\n",
le32_to_cpu(mst->ihead_offs));
printk(KERN_DEBUG "\tindex_size %llu\n",
(unsigned long long)le64_to_cpu(mst->index_size));
printk(KERN_DEBUG "\tlpt_lnum %u\n",
le32_to_cpu(mst->lpt_lnum));
printk(KERN_DEBUG "\tlpt_offs %u\n",
le32_to_cpu(mst->lpt_offs));
printk(KERN_DEBUG "\tnhead_lnum %u\n",
le32_to_cpu(mst->nhead_lnum));
printk(KERN_DEBUG "\tnhead_offs %u\n",
le32_to_cpu(mst->nhead_offs));
printk(KERN_DEBUG "\tltab_lnum %u\n",
le32_to_cpu(mst->ltab_lnum));
printk(KERN_DEBUG "\tltab_offs %u\n",
le32_to_cpu(mst->ltab_offs));
printk(KERN_DEBUG "\tlsave_lnum %u\n",
le32_to_cpu(mst->lsave_lnum));
printk(KERN_DEBUG "\tlsave_offs %u\n",
le32_to_cpu(mst->lsave_offs));
printk(KERN_DEBUG "\tlscan_lnum %u\n",
le32_to_cpu(mst->lscan_lnum));
printk(KERN_DEBUG "\tleb_cnt %u\n",
le32_to_cpu(mst->leb_cnt));
printk(KERN_DEBUG "\tempty_lebs %u\n",
le32_to_cpu(mst->empty_lebs));
printk(KERN_DEBUG "\tidx_lebs %u\n",
le32_to_cpu(mst->idx_lebs));
printk(KERN_DEBUG "\ttotal_free %llu\n",
(unsigned long long)le64_to_cpu(mst->total_free));
printk(KERN_DEBUG "\ttotal_dirty %llu\n",
(unsigned long long)le64_to_cpu(mst->total_dirty));
printk(KERN_DEBUG "\ttotal_used %llu\n",
(unsigned long long)le64_to_cpu(mst->total_used));
printk(KERN_DEBUG "\ttotal_dead %llu\n",
(unsigned long long)le64_to_cpu(mst->total_dead));
printk(KERN_DEBUG "\ttotal_dark %llu\n",
(unsigned long long)le64_to_cpu(mst->total_dark));
break;
}
case UBIFS_REF_NODE:
{
const struct ubifs_ref_node *ref = node;
printk(KERN_DEBUG "\tlnum %u\n",
le32_to_cpu(ref->lnum));
printk(KERN_DEBUG "\toffs %u\n",
le32_to_cpu(ref->offs));
printk(KERN_DEBUG "\tjhead %u\n",
le32_to_cpu(ref->jhead));
break;
}
case UBIFS_INO_NODE:
{
const struct ubifs_ino_node *ino = node;
key_read(c, &ino->key, &key);
printk(KERN_DEBUG "\tkey %s\n", DBGKEY(&key));
printk(KERN_DEBUG "\tcreat_sqnum %llu\n",
(unsigned long long)le64_to_cpu(ino->creat_sqnum));
printk(KERN_DEBUG "\tsize %llu\n",
(unsigned long long)le64_to_cpu(ino->size));
printk(KERN_DEBUG "\tnlink %u\n",
le32_to_cpu(ino->nlink));
printk(KERN_DEBUG "\tatime %lld.%u\n",
(long long)le64_to_cpu(ino->atime_sec),
le32_to_cpu(ino->atime_nsec));
printk(KERN_DEBUG "\tmtime %lld.%u\n",
(long long)le64_to_cpu(ino->mtime_sec),
le32_to_cpu(ino->mtime_nsec));
printk(KERN_DEBUG "\tctime %lld.%u\n",
(long long)le64_to_cpu(ino->ctime_sec),
le32_to_cpu(ino->ctime_nsec));
printk(KERN_DEBUG "\tuid %u\n",
le32_to_cpu(ino->uid));
printk(KERN_DEBUG "\tgid %u\n",
le32_to_cpu(ino->gid));
printk(KERN_DEBUG "\tmode %u\n",
le32_to_cpu(ino->mode));
printk(KERN_DEBUG "\tflags %#x\n",
le32_to_cpu(ino->flags));
printk(KERN_DEBUG "\txattr_cnt %u\n",
le32_to_cpu(ino->xattr_cnt));
printk(KERN_DEBUG "\txattr_size %u\n",
le32_to_cpu(ino->xattr_size));
printk(KERN_DEBUG "\txattr_names %u\n",
le32_to_cpu(ino->xattr_names));
printk(KERN_DEBUG "\tcompr_type %#x\n",
(int)le16_to_cpu(ino->compr_type));
printk(KERN_DEBUG "\tdata len %u\n",
le32_to_cpu(ino->data_len));
break;
}
case UBIFS_DENT_NODE:
case UBIFS_XENT_NODE:
{
const struct ubifs_dent_node *dent = node;
int nlen = le16_to_cpu(dent->nlen);
key_read(c, &dent->key, &key);
printk(KERN_DEBUG "\tkey %s\n", DBGKEY(&key));
printk(KERN_DEBUG "\tinum %llu\n",
(unsigned long long)le64_to_cpu(dent->inum));
printk(KERN_DEBUG "\ttype %d\n", (int)dent->type);
printk(KERN_DEBUG "\tnlen %d\n", nlen);
printk(KERN_DEBUG "\tname ");
if (nlen > UBIFS_MAX_NLEN)
printk(KERN_DEBUG "(bad name length, not printing, "
"bad or corrupted node)");
else {
for (i = 0; i < nlen && dent->name[i]; i++)
printk(KERN_CONT "%c", dent->name[i]);
}
printk(KERN_CONT "\n");
break;
}
case UBIFS_DATA_NODE:
{
const struct ubifs_data_node *dn = node;
int dlen = le32_to_cpu(ch->len) - UBIFS_DATA_NODE_SZ;
key_read(c, &dn->key, &key);
printk(KERN_DEBUG "\tkey %s\n", DBGKEY(&key));
printk(KERN_DEBUG "\tsize %u\n",
le32_to_cpu(dn->size));
printk(KERN_DEBUG "\tcompr_typ %d\n",
(int)le16_to_cpu(dn->compr_type));
printk(KERN_DEBUG "\tdata size %d\n",
dlen);
printk(KERN_DEBUG "\tdata:\n");
print_hex_dump(KERN_DEBUG, "\t", DUMP_PREFIX_OFFSET, 32, 1,
(void *)&dn->data, dlen, 0);
break;
}
case UBIFS_TRUN_NODE:
{
const struct ubifs_trun_node *trun = node;
printk(KERN_DEBUG "\tinum %u\n",
le32_to_cpu(trun->inum));
printk(KERN_DEBUG "\told_size %llu\n",
(unsigned long long)le64_to_cpu(trun->old_size));
printk(KERN_DEBUG "\tnew_size %llu\n",
(unsigned long long)le64_to_cpu(trun->new_size));
break;
}
case UBIFS_IDX_NODE:
{
const struct ubifs_idx_node *idx = node;
n = le16_to_cpu(idx->child_cnt);
printk(KERN_DEBUG "\tchild_cnt %d\n", n);
printk(KERN_DEBUG "\tlevel %d\n",
(int)le16_to_cpu(idx->level));
printk(KERN_DEBUG "\tBranches:\n");
for (i = 0; i < n && i < c->fanout - 1; i++) {
const struct ubifs_branch *br;
br = ubifs_idx_branch(c, idx, i);
key_read(c, &br->key, &key);
printk(KERN_DEBUG "\t%d: LEB %d:%d len %d key %s\n",
i, le32_to_cpu(br->lnum), le32_to_cpu(br->offs),
le32_to_cpu(br->len), DBGKEY(&key));
}
break;
}
case UBIFS_CS_NODE:
break;
case UBIFS_ORPH_NODE:
{
const struct ubifs_orph_node *orph = node;
printk(KERN_DEBUG "\tcommit number %llu\n",
(unsigned long long)
le64_to_cpu(orph->cmt_no) & LLONG_MAX);
printk(KERN_DEBUG "\tlast node flag %llu\n",
(unsigned long long)(le64_to_cpu(orph->cmt_no)) >> 63);
n = (le32_to_cpu(ch->len) - UBIFS_ORPH_NODE_SZ) >> 3;
printk(KERN_DEBUG "\t%d orphan inode numbers:\n", n);
for (i = 0; i < n; i++)
printk(KERN_DEBUG "\t ino %llu\n",
(unsigned long long)le64_to_cpu(orph->inos[i]));
break;
}
default:
printk(KERN_DEBUG "node type %d was not recognized\n",
(int)ch->node_type);
}
spin_unlock(&dbg_lock);
}
void dbg_dump_budget_req(const struct ubifs_budget_req *req)
{
spin_lock(&dbg_lock);
printk(KERN_DEBUG "Budgeting request: new_ino %d, dirtied_ino %d\n",
req->new_ino, req->dirtied_ino);
printk(KERN_DEBUG "\tnew_ino_d %d, dirtied_ino_d %d\n",
req->new_ino_d, req->dirtied_ino_d);
printk(KERN_DEBUG "\tnew_page %d, dirtied_page %d\n",
req->new_page, req->dirtied_page);
printk(KERN_DEBUG "\tnew_dent %d, mod_dent %d\n",
req->new_dent, req->mod_dent);
printk(KERN_DEBUG "\tidx_growth %d\n", req->idx_growth);
printk(KERN_DEBUG "\tdata_growth %d dd_growth %d\n",
req->data_growth, req->dd_growth);
spin_unlock(&dbg_lock);
}
void dbg_dump_lstats(const struct ubifs_lp_stats *lst)
{
spin_lock(&dbg_lock);
printk(KERN_DEBUG "(pid %d) Lprops statistics: empty_lebs %d, "
"idx_lebs %d\n", current->pid, lst->empty_lebs, lst->idx_lebs);
printk(KERN_DEBUG "\ttaken_empty_lebs %d, total_free %lld, "
"total_dirty %lld\n", lst->taken_empty_lebs, lst->total_free,
lst->total_dirty);
printk(KERN_DEBUG "\ttotal_used %lld, total_dark %lld, "
"total_dead %lld\n", lst->total_used, lst->total_dark,
lst->total_dead);
spin_unlock(&dbg_lock);
}
void dbg_dump_budg(struct ubifs_info *c)
{
int i;
struct rb_node *rb;
struct ubifs_bud *bud;
struct ubifs_gced_idx_leb *idx_gc;
long long available, outstanding, free;
ubifs_assert(spin_is_locked(&c->space_lock));
spin_lock(&dbg_lock);
printk(KERN_DEBUG "(pid %d) Budgeting info: budg_data_growth %lld, "
"budg_dd_growth %lld, budg_idx_growth %lld\n", current->pid,
c->budg_data_growth, c->budg_dd_growth, c->budg_idx_growth);
printk(KERN_DEBUG "\tdata budget sum %lld, total budget sum %lld, "
"freeable_cnt %d\n", c->budg_data_growth + c->budg_dd_growth,
c->budg_data_growth + c->budg_dd_growth + c->budg_idx_growth,
c->freeable_cnt);
printk(KERN_DEBUG "\tmin_idx_lebs %d, old_idx_sz %lld, "
"calc_idx_sz %lld, idx_gc_cnt %d\n", c->min_idx_lebs,
c->old_idx_sz, c->calc_idx_sz, c->idx_gc_cnt);
printk(KERN_DEBUG "\tdirty_pg_cnt %ld, dirty_zn_cnt %ld, "
"clean_zn_cnt %ld\n", atomic_long_read(&c->dirty_pg_cnt),
atomic_long_read(&c->dirty_zn_cnt),
atomic_long_read(&c->clean_zn_cnt));
printk(KERN_DEBUG "\tdark_wm %d, dead_wm %d, max_idx_node_sz %d\n",
c->dark_wm, c->dead_wm, c->max_idx_node_sz);
printk(KERN_DEBUG "\tgc_lnum %d, ihead_lnum %d\n",
c->gc_lnum, c->ihead_lnum);
/* If we are in R/O mode, journal heads do not exist */
if (c->jheads)
for (i = 0; i < c->jhead_cnt; i++)
printk(KERN_DEBUG "\tjhead %s\t LEB %d\n",
dbg_jhead(c->jheads[i].wbuf.jhead),
c->jheads[i].wbuf.lnum);
for (rb = rb_first(&c->buds); rb; rb = rb_next(rb)) {
bud = rb_entry(rb, struct ubifs_bud, rb);
printk(KERN_DEBUG "\tbud LEB %d\n", bud->lnum);
}
list_for_each_entry(bud, &c->old_buds, list)
printk(KERN_DEBUG "\told bud LEB %d\n", bud->lnum);
list_for_each_entry(idx_gc, &c->idx_gc, list)
printk(KERN_DEBUG "\tGC'ed idx LEB %d unmap %d\n",
idx_gc->lnum, idx_gc->unmap);
printk(KERN_DEBUG "\tcommit state %d\n", c->cmt_state);
/* Print budgeting predictions */
available = ubifs_calc_available(c, c->min_idx_lebs);
outstanding = c->budg_data_growth + c->budg_dd_growth;
free = ubifs_get_free_space_nolock(c);
printk(KERN_DEBUG "Budgeting predictions:\n");
printk(KERN_DEBUG "\tavailable: %lld, outstanding %lld, free %lld\n",
available, outstanding, free);
spin_unlock(&dbg_lock);
}
void dbg_dump_lprop(const struct ubifs_info *c, const struct ubifs_lprops *lp)
{
int i, spc, dark = 0, dead = 0;
struct rb_node *rb;
struct ubifs_bud *bud;
spc = lp->free + lp->dirty;
if (spc < c->dead_wm)
dead = spc;
else
dark = ubifs_calc_dark(c, spc);
if (lp->flags & LPROPS_INDEX)
printk(KERN_DEBUG "LEB %-7d free %-8d dirty %-8d used %-8d "
"free + dirty %-8d flags %#x (", lp->lnum, lp->free,
lp->dirty, c->leb_size - spc, spc, lp->flags);
else
printk(KERN_DEBUG "LEB %-7d free %-8d dirty %-8d used %-8d "
"free + dirty %-8d dark %-4d dead %-4d nodes fit %-3d "
"flags %#-4x (", lp->lnum, lp->free, lp->dirty,
c->leb_size - spc, spc, dark, dead,
(int)(spc / UBIFS_MAX_NODE_SZ), lp->flags);
if (lp->flags & LPROPS_TAKEN) {
if (lp->flags & LPROPS_INDEX)
printk(KERN_CONT "index, taken");
else
printk(KERN_CONT "taken");
} else {
const char *s;
if (lp->flags & LPROPS_INDEX) {
switch (lp->flags & LPROPS_CAT_MASK) {
case LPROPS_DIRTY_IDX:
s = "dirty index";
break;
case LPROPS_FRDI_IDX:
s = "freeable index";
break;
default:
s = "index";
}
} else {
switch (lp->flags & LPROPS_CAT_MASK) {
case LPROPS_UNCAT:
s = "not categorized";
break;
case LPROPS_DIRTY:
s = "dirty";
break;
case LPROPS_FREE:
s = "free";
break;
case LPROPS_EMPTY:
s = "empty";
break;
case LPROPS_FREEABLE:
s = "freeable";
break;
default:
s = NULL;
break;
}
}
printk(KERN_CONT "%s", s);
}
for (rb = rb_first((struct rb_root *)&c->buds); rb; rb = rb_next(rb)) {
bud = rb_entry(rb, struct ubifs_bud, rb);
if (bud->lnum == lp->lnum) {
int head = 0;
for (i = 0; i < c->jhead_cnt; i++) {
if (lp->lnum == c->jheads[i].wbuf.lnum) {
printk(KERN_CONT ", jhead %s",
dbg_jhead(i));
head = 1;
}
}
if (!head)
printk(KERN_CONT ", bud of jhead %s",
dbg_jhead(bud->jhead));
}
}
if (lp->lnum == c->gc_lnum)
printk(KERN_CONT ", GC LEB");
printk(KERN_CONT ")\n");
}
void dbg_dump_lprops(struct ubifs_info *c)
{
int lnum, err;
struct ubifs_lprops lp;
struct ubifs_lp_stats lst;
printk(KERN_DEBUG "(pid %d) start dumping LEB properties\n",
current->pid);
ubifs_get_lp_stats(c, &lst);
dbg_dump_lstats(&lst);
for (lnum = c->main_first; lnum < c->leb_cnt; lnum++) {
err = ubifs_read_one_lp(c, lnum, &lp);
if (err)
ubifs_err("cannot read lprops for LEB %d", lnum);
dbg_dump_lprop(c, &lp);
}
printk(KERN_DEBUG "(pid %d) finish dumping LEB properties\n",
current->pid);
}
void dbg_dump_lpt_info(struct ubifs_info *c)
{
int i;
spin_lock(&dbg_lock);
printk(KERN_DEBUG "(pid %d) dumping LPT information\n", current->pid);
printk(KERN_DEBUG "\tlpt_sz: %lld\n", c->lpt_sz);
printk(KERN_DEBUG "\tpnode_sz: %d\n", c->pnode_sz);
printk(KERN_DEBUG "\tnnode_sz: %d\n", c->nnode_sz);
printk(KERN_DEBUG "\tltab_sz: %d\n", c->ltab_sz);
printk(KERN_DEBUG "\tlsave_sz: %d\n", c->lsave_sz);
printk(KERN_DEBUG "\tbig_lpt: %d\n", c->big_lpt);
printk(KERN_DEBUG "\tlpt_hght: %d\n", c->lpt_hght);
printk(KERN_DEBUG "\tpnode_cnt: %d\n", c->pnode_cnt);
printk(KERN_DEBUG "\tnnode_cnt: %d\n", c->nnode_cnt);
printk(KERN_DEBUG "\tdirty_pn_cnt: %d\n", c->dirty_pn_cnt);
printk(KERN_DEBUG "\tdirty_nn_cnt: %d\n", c->dirty_nn_cnt);
printk(KERN_DEBUG "\tlsave_cnt: %d\n", c->lsave_cnt);
printk(KERN_DEBUG "\tspace_bits: %d\n", c->space_bits);
printk(KERN_DEBUG "\tlpt_lnum_bits: %d\n", c->lpt_lnum_bits);
printk(KERN_DEBUG "\tlpt_offs_bits: %d\n", c->lpt_offs_bits);
printk(KERN_DEBUG "\tlpt_spc_bits: %d\n", c->lpt_spc_bits);
printk(KERN_DEBUG "\tpcnt_bits: %d\n", c->pcnt_bits);
printk(KERN_DEBUG "\tlnum_bits: %d\n", c->lnum_bits);
printk(KERN_DEBUG "\tLPT root is at %d:%d\n", c->lpt_lnum, c->lpt_offs);
printk(KERN_DEBUG "\tLPT head is at %d:%d\n",
c->nhead_lnum, c->nhead_offs);
printk(KERN_DEBUG "\tLPT ltab is at %d:%d\n",
c->ltab_lnum, c->ltab_offs);
if (c->big_lpt)
printk(KERN_DEBUG "\tLPT lsave is at %d:%d\n",
c->lsave_lnum, c->lsave_offs);
for (i = 0; i < c->lpt_lebs; i++)
printk(KERN_DEBUG "\tLPT LEB %d free %d dirty %d tgc %d "
"cmt %d\n", i + c->lpt_first, c->ltab[i].free,
c->ltab[i].dirty, c->ltab[i].tgc, c->ltab[i].cmt);
spin_unlock(&dbg_lock);
}
void dbg_dump_leb(const struct ubifs_info *c, int lnum)
{
struct ubifs_scan_leb *sleb;
struct ubifs_scan_node *snod;
if (dbg_failure_mode)
return;
printk(KERN_DEBUG "(pid %d) start dumping LEB %d\n",
current->pid, lnum);
sleb = ubifs_scan(c, lnum, 0, c->dbg->buf, 0);
if (IS_ERR(sleb)) {
ubifs_err("scan error %d", (int)PTR_ERR(sleb));
return;
}
printk(KERN_DEBUG "LEB %d has %d nodes ending at %d\n", lnum,
sleb->nodes_cnt, sleb->endpt);
list_for_each_entry(snod, &sleb->nodes, list) {
cond_resched();
printk(KERN_DEBUG "Dumping node at LEB %d:%d len %d\n", lnum,
snod->offs, snod->len);
dbg_dump_node(c, snod->node);
}
printk(KERN_DEBUG "(pid %d) finish dumping LEB %d\n",
current->pid, lnum);
ubifs_scan_destroy(sleb);
return;
}
void dbg_dump_znode(const struct ubifs_info *c,
const struct ubifs_znode *znode)
{
int n;
const struct ubifs_zbranch *zbr;
spin_lock(&dbg_lock);
if (znode->parent)
zbr = &znode->parent->zbranch[znode->iip];
else
zbr = &c->zroot;
printk(KERN_DEBUG "znode %p, LEB %d:%d len %d parent %p iip %d level %d"
" child_cnt %d flags %lx\n", znode, zbr->lnum, zbr->offs,
zbr->len, znode->parent, znode->iip, znode->level,
znode->child_cnt, znode->flags);
if (znode->child_cnt <= 0 || znode->child_cnt > c->fanout) {
spin_unlock(&dbg_lock);
return;
}
printk(KERN_DEBUG "zbranches:\n");
for (n = 0; n < znode->child_cnt; n++) {
zbr = &znode->zbranch[n];
if (znode->level > 0)
printk(KERN_DEBUG "\t%d: znode %p LEB %d:%d len %d key "
"%s\n", n, zbr->znode, zbr->lnum,
zbr->offs, zbr->len,
DBGKEY(&zbr->key));
else
printk(KERN_DEBUG "\t%d: LNC %p LEB %d:%d len %d key "
"%s\n", n, zbr->znode, zbr->lnum,
zbr->offs, zbr->len,
DBGKEY(&zbr->key));
}
spin_unlock(&dbg_lock);
}
void dbg_dump_heap(struct ubifs_info *c, struct ubifs_lpt_heap *heap, int cat)
{
int i;
printk(KERN_DEBUG "(pid %d) start dumping heap cat %d (%d elements)\n",
current->pid, cat, heap->cnt);
for (i = 0; i < heap->cnt; i++) {
struct ubifs_lprops *lprops = heap->arr[i];
printk(KERN_DEBUG "\t%d. LEB %d hpos %d free %d dirty %d "
"flags %d\n", i, lprops->lnum, lprops->hpos,
lprops->free, lprops->dirty, lprops->flags);
}
printk(KERN_DEBUG "(pid %d) finish dumping heap\n", current->pid);
}
void dbg_dump_pnode(struct ubifs_info *c, struct ubifs_pnode *pnode,
struct ubifs_nnode *parent, int iip)
{
int i;
printk(KERN_DEBUG "(pid %d) dumping pnode:\n", current->pid);
printk(KERN_DEBUG "\taddress %zx parent %zx cnext %zx\n",
(size_t)pnode, (size_t)parent, (size_t)pnode->cnext);
printk(KERN_DEBUG "\tflags %lu iip %d level %d num %d\n",
pnode->flags, iip, pnode->level, pnode->num);
for (i = 0; i < UBIFS_LPT_FANOUT; i++) {
struct ubifs_lprops *lp = &pnode->lprops[i];
printk(KERN_DEBUG "\t%d: free %d dirty %d flags %d lnum %d\n",
i, lp->free, lp->dirty, lp->flags, lp->lnum);
}
}
void dbg_dump_tnc(struct ubifs_info *c)
{
struct ubifs_znode *znode;
int level;
printk(KERN_DEBUG "\n");
printk(KERN_DEBUG "(pid %d) start dumping TNC tree\n", current->pid);
znode = ubifs_tnc_levelorder_next(c->zroot.znode, NULL);
level = znode->level;
printk(KERN_DEBUG "== Level %d ==\n", level);
while (znode) {
if (level != znode->level) {
level = znode->level;
printk(KERN_DEBUG "== Level %d ==\n", level);
}
dbg_dump_znode(c, znode);
znode = ubifs_tnc_levelorder_next(c->zroot.znode, znode);
}
printk(KERN_DEBUG "(pid %d) finish dumping TNC tree\n", current->pid);
}
static int dump_znode(struct ubifs_info *c, struct ubifs_znode *znode,
void *priv)
{
dbg_dump_znode(c, znode);
return 0;
}
/**
* dbg_dump_index - dump the on-flash index.
* @c: UBIFS file-system description object
*
* This function dumps whole UBIFS indexing B-tree, unlike 'dbg_dump_tnc()'
* which dumps only in-memory znodes and does not read znodes which from flash.
*/
void dbg_dump_index(struct ubifs_info *c)
{
dbg_walk_index(c, NULL, dump_znode, NULL);
}
/**
* dbg_save_space_info - save information about flash space.
* @c: UBIFS file-system description object
*
* This function saves information about UBIFS free space, dirty space, etc, in
* order to check it later.
*/
void dbg_save_space_info(struct ubifs_info *c)
{
struct ubifs_debug_info *d = c->dbg;
int freeable_cnt;
spin_lock(&c->space_lock);
memcpy(&d->saved_lst, &c->lst, sizeof(struct ubifs_lp_stats));
/*
* We use a dirty hack here and zero out @c->freeable_cnt, because it
* affects the free space calculations, and UBIFS might not know about
* all freeable eraseblocks. Indeed, we know about freeable eraseblocks
* only when we read their lprops, and we do this only lazily, upon the
* need. So at any given point of time @c->freeable_cnt might be not
* exactly accurate.
*
* Just one example about the issue we hit when we did not zero
* @c->freeable_cnt.
* 1. The file-system is mounted R/O, c->freeable_cnt is %0. We save the
* amount of free space in @d->saved_free
* 2. We re-mount R/W, which makes UBIFS to read the "lsave"
* information from flash, where we cache LEBs from various
* categories ('ubifs_remount_fs()' -> 'ubifs_lpt_init()'
* -> 'lpt_init_wr()' -> 'read_lsave()' -> 'ubifs_lpt_lookup()'
* -> 'ubifs_get_pnode()' -> 'update_cats()'
* -> 'ubifs_add_to_cat()').
* 3. Lsave contains a freeable eraseblock, and @c->freeable_cnt
* becomes %1.
* 4. We calculate the amount of free space when the re-mount is
* finished in 'dbg_check_space_info()' and it does not match
* @d->saved_free.
*/
freeable_cnt = c->freeable_cnt;
c->freeable_cnt = 0;
d->saved_free = ubifs_get_free_space_nolock(c);
c->freeable_cnt = freeable_cnt;
spin_unlock(&c->space_lock);
}
/**
* dbg_check_space_info - check flash space information.
* @c: UBIFS file-system description object
*
* This function compares current flash space information with the information
* which was saved when the 'dbg_save_space_info()' function was called.
* Returns zero if the information has not changed, and %-EINVAL it it has
* changed.
*/
int dbg_check_space_info(struct ubifs_info *c)
{
struct ubifs_debug_info *d = c->dbg;
struct ubifs_lp_stats lst;
long long free;
int freeable_cnt;
spin_lock(&c->space_lock);
freeable_cnt = c->freeable_cnt;
c->freeable_cnt = 0;
free = ubifs_get_free_space_nolock(c);
c->freeable_cnt = freeable_cnt;
spin_unlock(&c->space_lock);
if (free != d->saved_free) {
ubifs_err("free space changed from %lld to %lld",
d->saved_free, free);
goto out;
}
return 0;
out:
ubifs_msg("saved lprops statistics dump");
dbg_dump_lstats(&d->saved_lst);
ubifs_get_lp_stats(c, &lst);
ubifs_msg("current lprops statistics dump");
dbg_dump_lstats(&lst);
spin_lock(&c->space_lock);
dbg_dump_budg(c);
spin_unlock(&c->space_lock);
dump_stack();
return -EINVAL;
}
/**
* dbg_check_synced_i_size - check synchronized inode size.
* @inode: inode to check
*
* If inode is clean, synchronized inode size has to be equivalent to current
* inode size. This function has to be called only for locked inodes (@i_mutex
* has to be locked). Returns %0 if synchronized inode size if correct, and
* %-EINVAL if not.
*/
int dbg_check_synced_i_size(struct inode *inode)
{
int err = 0;
struct ubifs_inode *ui = ubifs_inode(inode);
if (!(ubifs_chk_flags & UBIFS_CHK_GEN))
return 0;
if (!S_ISREG(inode->i_mode))
return 0;
mutex_lock(&ui->ui_mutex);
spin_lock(&ui->ui_lock);
if (ui->ui_size != ui->synced_i_size && !ui->dirty) {
ubifs_err("ui_size is %lld, synced_i_size is %lld, but inode "
"is clean", ui->ui_size, ui->synced_i_size);
ubifs_err("i_ino %lu, i_mode %#x, i_size %lld", inode->i_ino,
inode->i_mode, i_size_read(inode));
dbg_dump_stack();
err = -EINVAL;
}
spin_unlock(&ui->ui_lock);
mutex_unlock(&ui->ui_mutex);
return err;
}
/*
* dbg_check_dir - check directory inode size and link count.
* @c: UBIFS file-system description object
* @dir: the directory to calculate size for
* @size: the result is returned here
*
* This function makes sure that directory size and link count are correct.
* Returns zero in case of success and a negative error code in case of
* failure.
*
* Note, it is good idea to make sure the @dir->i_mutex is locked before
* calling this function.
*/
int dbg_check_dir_size(struct ubifs_info *c, const struct inode *dir)
{
unsigned int nlink = 2;
union ubifs_key key;
struct ubifs_dent_node *dent, *pdent = NULL;
struct qstr nm = { .name = NULL };
loff_t size = UBIFS_INO_NODE_SZ;
if (!(ubifs_chk_flags & UBIFS_CHK_GEN))
return 0;
if (!S_ISDIR(dir->i_mode))
return 0;
lowest_dent_key(c, &key, dir->i_ino);
while (1) {
int err;
dent = ubifs_tnc_next_ent(c, &key, &nm);
if (IS_ERR(dent)) {
err = PTR_ERR(dent);
if (err == -ENOENT)
break;
return err;
}
nm.name = dent->name;
nm.len = le16_to_cpu(dent->nlen);
size += CALC_DENT_SIZE(nm.len);
if (dent->type == UBIFS_ITYPE_DIR)
nlink += 1;
kfree(pdent);
pdent = dent;
key_read(c, &dent->key, &key);
}
kfree(pdent);
if (i_size_read(dir) != size) {
ubifs_err("directory inode %lu has size %llu, "
"but calculated size is %llu", dir->i_ino,
(unsigned long long)i_size_read(dir),
(unsigned long long)size);
dump_stack();
return -EINVAL;
}
if (dir->i_nlink != nlink) {
ubifs_err("directory inode %lu has nlink %u, but calculated "
"nlink is %u", dir->i_ino, dir->i_nlink, nlink);
dump_stack();
return -EINVAL;
}
return 0;
}
/**
* dbg_check_key_order - make sure that colliding keys are properly ordered.
* @c: UBIFS file-system description object
* @zbr1: first zbranch
* @zbr2: following zbranch
*
* In UBIFS indexing B-tree colliding keys has to be sorted in binary order of
* names of the direntries/xentries which are referred by the keys. This
* function reads direntries/xentries referred by @zbr1 and @zbr2 and makes
* sure the name of direntry/xentry referred by @zbr1 is less than
* direntry/xentry referred by @zbr2. Returns zero if this is true, %1 if not,
* and a negative error code in case of failure.
*/
static int dbg_check_key_order(struct ubifs_info *c, struct ubifs_zbranch *zbr1,
struct ubifs_zbranch *zbr2)
{
int err, nlen1, nlen2, cmp;
struct ubifs_dent_node *dent1, *dent2;
union ubifs_key key;
ubifs_assert(!keys_cmp(c, &zbr1->key, &zbr2->key));
dent1 = kmalloc(UBIFS_MAX_DENT_NODE_SZ, GFP_NOFS);
if (!dent1)
return -ENOMEM;
dent2 = kmalloc(UBIFS_MAX_DENT_NODE_SZ, GFP_NOFS);
if (!dent2) {
err = -ENOMEM;
goto out_free;
}
err = ubifs_tnc_read_node(c, zbr1, dent1);
if (err)
goto out_free;
err = ubifs_validate_entry(c, dent1);
if (err)
goto out_free;
err = ubifs_tnc_read_node(c, zbr2, dent2);
if (err)
goto out_free;
err = ubifs_validate_entry(c, dent2);
if (err)
goto out_free;
/* Make sure node keys are the same as in zbranch */
err = 1;
key_read(c, &dent1->key, &key);
if (keys_cmp(c, &zbr1->key, &key)) {
dbg_err("1st entry at %d:%d has key %s", zbr1->lnum,
zbr1->offs, DBGKEY(&key));
dbg_err("but it should have key %s according to tnc",
DBGKEY(&zbr1->key));
dbg_dump_node(c, dent1);
goto out_free;
}
key_read(c, &dent2->key, &key);
if (keys_cmp(c, &zbr2->key, &key)) {
dbg_err("2nd entry at %d:%d has key %s", zbr1->lnum,
zbr1->offs, DBGKEY(&key));
dbg_err("but it should have key %s according to tnc",
DBGKEY(&zbr2->key));
dbg_dump_node(c, dent2);
goto out_free;
}
nlen1 = le16_to_cpu(dent1->nlen);
nlen2 = le16_to_cpu(dent2->nlen);
cmp = memcmp(dent1->name, dent2->name, min_t(int, nlen1, nlen2));
if (cmp < 0 || (cmp == 0 && nlen1 < nlen2)) {
err = 0;
goto out_free;
}
if (cmp == 0 && nlen1 == nlen2)
dbg_err("2 xent/dent nodes with the same name");
else
dbg_err("bad order of colliding key %s",
DBGKEY(&key));
ubifs_msg("first node at %d:%d\n", zbr1->lnum, zbr1->offs);
dbg_dump_node(c, dent1);
ubifs_msg("second node at %d:%d\n", zbr2->lnum, zbr2->offs);
dbg_dump_node(c, dent2);
out_free:
kfree(dent2);
kfree(dent1);
return err;
}
/**
* dbg_check_znode - check if znode is all right.
* @c: UBIFS file-system description object
* @zbr: zbranch which points to this znode
*
* This function makes sure that znode referred to by @zbr is all right.
* Returns zero if it is, and %-EINVAL if it is not.
*/
static int dbg_check_znode(struct ubifs_info *c, struct ubifs_zbranch *zbr)
{
struct ubifs_znode *znode = zbr->znode;
struct ubifs_znode *zp = znode->parent;
int n, err, cmp;
if (znode->child_cnt <= 0 || znode->child_cnt > c->fanout) {
err = 1;
goto out;
}
if (znode->level < 0) {
err = 2;
goto out;
}
if (znode->iip < 0 || znode->iip >= c->fanout) {
err = 3;
goto out;
}
if (zbr->len == 0)
/* Only dirty zbranch may have no on-flash nodes */
if (!ubifs_zn_dirty(znode)) {
err = 4;
goto out;
}
if (ubifs_zn_dirty(znode)) {
/*
* If znode is dirty, its parent has to be dirty as well. The
* order of the operation is important, so we have to have
* memory barriers.
*/
smp_mb();
if (zp && !ubifs_zn_dirty(zp)) {
/*
* The dirty flag is atomic and is cleared outside the
* TNC mutex, so znode's dirty flag may now have
* been cleared. The child is always cleared before the
* parent, so we just need to check again.
*/
smp_mb();
if (ubifs_zn_dirty(znode)) {
err = 5;
goto out;
}
}
}
if (zp) {
const union ubifs_key *min, *max;
if (znode->level != zp->level - 1) {
err = 6;
goto out;
}
/* Make sure the 'parent' pointer in our znode is correct */
err = ubifs_search_zbranch(c, zp, &zbr->key, &n);
if (!err) {
/* This zbranch does not exist in the parent */
err = 7;
goto out;
}
if (znode->iip >= zp->child_cnt) {
err = 8;
goto out;
}
if (znode->iip != n) {
/* This may happen only in case of collisions */
if (keys_cmp(c, &zp->zbranch[n].key,
&zp->zbranch[znode->iip].key)) {
err = 9;
goto out;
}
n = znode->iip;
}
/*
* Make sure that the first key in our znode is greater than or
* equal to the key in the pointing zbranch.
*/
min = &zbr->key;
cmp = keys_cmp(c, min, &znode->zbranch[0].key);
if (cmp == 1) {
err = 10;
goto out;
}
if (n + 1 < zp->child_cnt) {
max = &zp->zbranch[n + 1].key;
/*
* Make sure the last key in our znode is less or
* equivalent than the key in the zbranch which goes
* after our pointing zbranch.
*/
cmp = keys_cmp(c, max,
&znode->zbranch[znode->child_cnt - 1].key);
if (cmp == -1) {
err = 11;
goto out;
}
}
} else {
/* This may only be root znode */
if (zbr != &c->zroot) {
err = 12;
goto out;
}
}
/*
* Make sure that next key is greater or equivalent then the previous
* one.
*/
for (n = 1; n < znode->child_cnt; n++) {
cmp = keys_cmp(c, &znode->zbranch[n - 1].key,
&znode->zbranch[n].key);
if (cmp > 0) {
err = 13;
goto out;
}
if (cmp == 0) {
/* This can only be keys with colliding hash */
if (!is_hash_key(c, &znode->zbranch[n].key)) {
err = 14;
goto out;
}
if (znode->level != 0 || c->replaying)
continue;
/*
* Colliding keys should follow binary order of
* corresponding xentry/dentry names.
*/
err = dbg_check_key_order(c, &znode->zbranch[n - 1],
&znode->zbranch[n]);
if (err < 0)
return err;
if (err) {
err = 15;
goto out;
}
}
}
for (n = 0; n < znode->child_cnt; n++) {
if (!znode->zbranch[n].znode &&
(znode->zbranch[n].lnum == 0 ||
znode->zbranch[n].len == 0)) {
err = 16;
goto out;
}
if (znode->zbranch[n].lnum != 0 &&
znode->zbranch[n].len == 0) {
err = 17;
goto out;
}
if (znode->zbranch[n].lnum == 0 &&
znode->zbranch[n].len != 0) {
err = 18;
goto out;
}
if (znode->zbranch[n].lnum == 0 &&
znode->zbranch[n].offs != 0) {
err = 19;
goto out;
}
if (znode->level != 0 && znode->zbranch[n].znode)
if (znode->zbranch[n].znode->parent != znode) {
err = 20;
goto out;
}
}
return 0;
out:
ubifs_err("failed, error %d", err);
ubifs_msg("dump of the znode");
dbg_dump_znode(c, znode);
if (zp) {
ubifs_msg("dump of the parent znode");
dbg_dump_znode(c, zp);
}
dump_stack();
return -EINVAL;
}
/**
* dbg_check_tnc - check TNC tree.
* @c: UBIFS file-system description object
* @extra: do extra checks that are possible at start commit
*
* This function traverses whole TNC tree and checks every znode. Returns zero
* if everything is all right and %-EINVAL if something is wrong with TNC.
*/
int dbg_check_tnc(struct ubifs_info *c, int extra)
{
struct ubifs_znode *znode;
long clean_cnt = 0, dirty_cnt = 0;
int err, last;
if (!(ubifs_chk_flags & UBIFS_CHK_TNC))
return 0;
ubifs_assert(mutex_is_locked(&c->tnc_mutex));
if (!c->zroot.znode)
return 0;
znode = ubifs_tnc_postorder_first(c->zroot.znode);
while (1) {
struct ubifs_znode *prev;
struct ubifs_zbranch *zbr;
if (!znode->parent)
zbr = &c->zroot;
else
zbr = &znode->parent->zbranch[znode->iip];
err = dbg_check_znode(c, zbr);
if (err)
return err;
if (extra) {
if (ubifs_zn_dirty(znode))
dirty_cnt += 1;
else
clean_cnt += 1;
}
prev = znode;
znode = ubifs_tnc_postorder_next(znode);
if (!znode)
break;
/*
* If the last key of this znode is equivalent to the first key
* of the next znode (collision), then check order of the keys.
*/
last = prev->child_cnt - 1;
if (prev->level == 0 && znode->level == 0 && !c->replaying &&
!keys_cmp(c, &prev->zbranch[last].key,
&znode->zbranch[0].key)) {
err = dbg_check_key_order(c, &prev->zbranch[last],
&znode->zbranch[0]);
if (err < 0)
return err;
if (err) {
ubifs_msg("first znode");
dbg_dump_znode(c, prev);
ubifs_msg("second znode");
dbg_dump_znode(c, znode);
return -EINVAL;
}
}
}
if (extra) {
if (clean_cnt != atomic_long_read(&c->clean_zn_cnt)) {
ubifs_err("incorrect clean_zn_cnt %ld, calculated %ld",
atomic_long_read(&c->clean_zn_cnt),
clean_cnt);
return -EINVAL;
}
if (dirty_cnt != atomic_long_read(&c->dirty_zn_cnt)) {
ubifs_err("incorrect dirty_zn_cnt %ld, calculated %ld",
atomic_long_read(&c->dirty_zn_cnt),
dirty_cnt);
return -EINVAL;
}
}
return 0;
}
/**
* dbg_walk_index - walk the on-flash index.
* @c: UBIFS file-system description object
* @leaf_cb: called for each leaf node
* @znode_cb: called for each indexing node
* @priv: private data which is passed to callbacks
*
* This function walks the UBIFS index and calls the @leaf_cb for each leaf
* node and @znode_cb for each indexing node. Returns zero in case of success
* and a negative error code in case of failure.
*
* It would be better if this function removed every znode it pulled to into
* the TNC, so that the behavior more closely matched the non-debugging
* behavior.
*/
int dbg_walk_index(struct ubifs_info *c, dbg_leaf_callback leaf_cb,
dbg_znode_callback znode_cb, void *priv)
{
int err;
struct ubifs_zbranch *zbr;
struct ubifs_znode *znode, *child;
mutex_lock(&c->tnc_mutex);
/* If the root indexing node is not in TNC - pull it */
if (!c->zroot.znode) {
c->zroot.znode = ubifs_load_znode(c, &c->zroot, NULL, 0);
if (IS_ERR(c->zroot.znode)) {
err = PTR_ERR(c->zroot.znode);
c->zroot.znode = NULL;
goto out_unlock;
}
}
/*
* We are going to traverse the indexing tree in the postorder manner.
* Go down and find the leftmost indexing node where we are going to
* start from.
*/
znode = c->zroot.znode;
while (znode->level > 0) {
zbr = &znode->zbranch[0];
child = zbr->znode;
if (!child) {
child = ubifs_load_znode(c, zbr, znode, 0);
if (IS_ERR(child)) {
err = PTR_ERR(child);
goto out_unlock;
}
zbr->znode = child;
}
znode = child;
}
/* Iterate over all indexing nodes */
while (1) {
int idx;
cond_resched();
if (znode_cb) {
err = znode_cb(c, znode, priv);
if (err) {
ubifs_err("znode checking function returned "
"error %d", err);
dbg_dump_znode(c, znode);
goto out_dump;
}
}
if (leaf_cb && znode->level == 0) {
for (idx = 0; idx < znode->child_cnt; idx++) {
zbr = &znode->zbranch[idx];
err = leaf_cb(c, zbr, priv);
if (err) {
ubifs_err("leaf checking function "
"returned error %d, for leaf "
"at LEB %d:%d",
err, zbr->lnum, zbr->offs);
goto out_dump;
}
}
}
if (!znode->parent)
break;
idx = znode->iip + 1;
znode = znode->parent;
if (idx < znode->child_cnt) {
/* Switch to the next index in the parent */
zbr = &znode->zbranch[idx];
child = zbr->znode;
if (!child) {
child = ubifs_load_znode(c, zbr, znode, idx);
if (IS_ERR(child)) {
err = PTR_ERR(child);
goto out_unlock;
}
zbr->znode = child;
}
znode = child;
} else
/*
* This is the last child, switch to the parent and
* continue.
*/
continue;
/* Go to the lowest leftmost znode in the new sub-tree */
while (znode->level > 0) {
zbr = &znode->zbranch[0];
child = zbr->znode;
if (!child) {
child = ubifs_load_znode(c, zbr, znode, 0);
if (IS_ERR(child)) {
err = PTR_ERR(child);
goto out_unlock;
}
zbr->znode = child;
}
znode = child;
}
}
mutex_unlock(&c->tnc_mutex);
return 0;
out_dump:
if (znode->parent)
zbr = &znode->parent->zbranch[znode->iip];
else
zbr = &c->zroot;
ubifs_msg("dump of znode at LEB %d:%d", zbr->lnum, zbr->offs);
dbg_dump_znode(c, znode);
out_unlock:
mutex_unlock(&c->tnc_mutex);
return err;
}
/**
* add_size - add znode size to partially calculated index size.
* @c: UBIFS file-system description object
* @znode: znode to add size for
* @priv: partially calculated index size
*
* This is a helper function for 'dbg_check_idx_size()' which is called for
* every indexing node and adds its size to the 'long long' variable pointed to
* by @priv.
*/
static int add_size(struct ubifs_info *c, struct ubifs_znode *znode, void *priv)
{
long long *idx_size = priv;
int add;
add = ubifs_idx_node_sz(c, znode->child_cnt);
add = ALIGN(add, 8);
*idx_size += add;
return 0;
}
/**
* dbg_check_idx_size - check index size.
* @c: UBIFS file-system description object
* @idx_size: size to check
*
* This function walks the UBIFS index, calculates its size and checks that the
* size is equivalent to @idx_size. Returns zero in case of success and a
* negative error code in case of failure.
*/
int dbg_check_idx_size(struct ubifs_info *c, long long idx_size)
{
int err;
long long calc = 0;
if (!(ubifs_chk_flags & UBIFS_CHK_IDX_SZ))
return 0;
err = dbg_walk_index(c, NULL, add_size, &calc);
if (err) {
ubifs_err("error %d while walking the index", err);
return err;
}
if (calc != idx_size) {
ubifs_err("index size check failed: calculated size is %lld, "
"should be %lld", calc, idx_size);
dump_stack();
return -EINVAL;
}
return 0;
}
/**
* struct fsck_inode - information about an inode used when checking the file-system.
* @rb: link in the RB-tree of inodes
* @inum: inode number
* @mode: inode type, permissions, etc
* @nlink: inode link count
* @xattr_cnt: count of extended attributes
* @references: how many directory/xattr entries refer this inode (calculated
* while walking the index)
* @calc_cnt: for directory inode count of child directories
* @size: inode size (read from on-flash inode)
* @xattr_sz: summary size of all extended attributes (read from on-flash
* inode)
* @calc_sz: for directories calculated directory size
* @calc_xcnt: count of extended attributes
* @calc_xsz: calculated summary size of all extended attributes
* @xattr_nms: sum of lengths of all extended attribute names belonging to this
* inode (read from on-flash inode)
* @calc_xnms: calculated sum of lengths of all extended attribute names
*/
struct fsck_inode {
struct rb_node rb;
ino_t inum;
umode_t mode;
unsigned int nlink;
unsigned int xattr_cnt;
int references;
int calc_cnt;
long long size;
unsigned int xattr_sz;
long long calc_sz;
long long calc_xcnt;
long long calc_xsz;
unsigned int xattr_nms;
long long calc_xnms;
};
/**
* struct fsck_data - private FS checking information.
* @inodes: RB-tree of all inodes (contains @struct fsck_inode objects)
*/
struct fsck_data {
struct rb_root inodes;
};
/**
* add_inode - add inode information to RB-tree of inodes.
* @c: UBIFS file-system description object
* @fsckd: FS checking information
* @ino: raw UBIFS inode to add
*
* This is a helper function for 'check_leaf()' which adds information about
* inode @ino to the RB-tree of inodes. Returns inode information pointer in
* case of success and a negative error code in case of failure.
*/
static struct fsck_inode *add_inode(struct ubifs_info *c,
struct fsck_data *fsckd,
struct ubifs_ino_node *ino)
{
struct rb_node **p, *parent = NULL;
struct fsck_inode *fscki;
ino_t inum = key_inum_flash(c, &ino->key);
p = &fsckd->inodes.rb_node;
while (*p) {
parent = *p;
fscki = rb_entry(parent, struct fsck_inode, rb);
if (inum < fscki->inum)
p = &(*p)->rb_left;
else if (inum > fscki->inum)
p = &(*p)->rb_right;
else
return fscki;
}
if (inum > c->highest_inum) {
ubifs_err("too high inode number, max. is %lu",
(unsigned long)c->highest_inum);
return ERR_PTR(-EINVAL);
}
fscki = kzalloc(sizeof(struct fsck_inode), GFP_NOFS);
if (!fscki)
return ERR_PTR(-ENOMEM);
fscki->inum = inum;
fscki->nlink = le32_to_cpu(ino->nlink);
fscki->size = le64_to_cpu(ino->size);
fscki->xattr_cnt = le32_to_cpu(ino->xattr_cnt);
fscki->xattr_sz = le32_to_cpu(ino->xattr_size);
fscki->xattr_nms = le32_to_cpu(ino->xattr_names);
fscki->mode = le32_to_cpu(ino->mode);
if (S_ISDIR(fscki->mode)) {
fscki->calc_sz = UBIFS_INO_NODE_SZ;
fscki->calc_cnt = 2;
}
rb_link_node(&fscki->rb, parent, p);
rb_insert_color(&fscki->rb, &fsckd->inodes);
return fscki;
}
/**
* search_inode - search inode in the RB-tree of inodes.
* @fsckd: FS checking information
* @inum: inode number to search
*
* This is a helper function for 'check_leaf()' which searches inode @inum in
* the RB-tree of inodes and returns an inode information pointer or %NULL if
* the inode was not found.
*/
static struct fsck_inode *search_inode(struct fsck_data *fsckd, ino_t inum)
{
struct rb_node *p;
struct fsck_inode *fscki;
p = fsckd->inodes.rb_node;
while (p) {
fscki = rb_entry(p, struct fsck_inode, rb);
if (inum < fscki->inum)
p = p->rb_left;
else if (inum > fscki->inum)
p = p->rb_right;
else
return fscki;
}
return NULL;
}
/**
* read_add_inode - read inode node and add it to RB-tree of inodes.
* @c: UBIFS file-system description object
* @fsckd: FS checking information
* @inum: inode number to read
*
* This is a helper function for 'check_leaf()' which finds inode node @inum in
* the index, reads it, and adds it to the RB-tree of inodes. Returns inode
* information pointer in case of success and a negative error code in case of
* failure.
*/
static struct fsck_inode *read_add_inode(struct ubifs_info *c,
struct fsck_data *fsckd, ino_t inum)
{
int n, err;
union ubifs_key key;
struct ubifs_znode *znode;
struct ubifs_zbranch *zbr;
struct ubifs_ino_node *ino;
struct fsck_inode *fscki;
fscki = search_inode(fsckd, inum);
if (fscki)
return fscki;
ino_key_init(c, &key, inum);
err = ubifs_lookup_level0(c, &key, &znode, &n);
if (!err) {
ubifs_err("inode %lu not found in index", (unsigned long)inum);
return ERR_PTR(-ENOENT);
} else if (err < 0) {
ubifs_err("error %d while looking up inode %lu",
err, (unsigned long)inum);
return ERR_PTR(err);
}
zbr = &znode->zbranch[n];
if (zbr->len < UBIFS_INO_NODE_SZ) {
ubifs_err("bad node %lu node length %d",
(unsigned long)inum, zbr->len);
return ERR_PTR(-EINVAL);
}
ino = kmalloc(zbr->len, GFP_NOFS);
if (!ino)
return ERR_PTR(-ENOMEM);
err = ubifs_tnc_read_node(c, zbr, ino);
if (err) {
ubifs_err("cannot read inode node at LEB %d:%d, error %d",
zbr->lnum, zbr->offs, err);
kfree(ino);
return ERR_PTR(err);
}
fscki = add_inode(c, fsckd, ino);
kfree(ino);
if (IS_ERR(fscki)) {
ubifs_err("error %ld while adding inode %lu node",
PTR_ERR(fscki), (unsigned long)inum);
return fscki;
}
return fscki;
}
/**
* check_leaf - check leaf node.
* @c: UBIFS file-system description object
* @zbr: zbranch of the leaf node to check
* @priv: FS checking information
*
* This is a helper function for 'dbg_check_filesystem()' which is called for
* every single leaf node while walking the indexing tree. It checks that the
* leaf node referred from the indexing tree exists, has correct CRC, and does
* some other basic validation. This function is also responsible for building
* an RB-tree of inodes - it adds all inodes into the RB-tree. It also
* calculates reference count, size, etc for each inode in order to later
* compare them to the information stored inside the inodes and detect possible
* inconsistencies. Returns zero in case of success and a negative error code
* in case of failure.
*/
static int check_leaf(struct ubifs_info *c, struct ubifs_zbranch *zbr,
void *priv)
{
ino_t inum;
void *node;
struct ubifs_ch *ch;
int err, type = key_type(c, &zbr->key);
struct fsck_inode *fscki;
if (zbr->len < UBIFS_CH_SZ) {
ubifs_err("bad leaf length %d (LEB %d:%d)",
zbr->len, zbr->lnum, zbr->offs);
return -EINVAL;
}
node = kmalloc(zbr->len, GFP_NOFS);
if (!node)
return -ENOMEM;
err = ubifs_tnc_read_node(c, zbr, node);
if (err) {
ubifs_err("cannot read leaf node at LEB %d:%d, error %d",
zbr->lnum, zbr->offs, err);
goto out_free;
}
/* If this is an inode node, add it to RB-tree of inodes */
if (type == UBIFS_INO_KEY) {
fscki = add_inode(c, priv, node);
if (IS_ERR(fscki)) {
err = PTR_ERR(fscki);
ubifs_err("error %d while adding inode node", err);
goto out_dump;
}
goto out;
}
if (type != UBIFS_DENT_KEY && type != UBIFS_XENT_KEY &&
type != UBIFS_DATA_KEY) {
ubifs_err("unexpected node type %d at LEB %d:%d",
type, zbr->lnum, zbr->offs);
err = -EINVAL;
goto out_free;
}
ch = node;
if (le64_to_cpu(ch->sqnum) > c->max_sqnum) {
ubifs_err("too high sequence number, max. is %llu",
c->max_sqnum);
err = -EINVAL;
goto out_dump;
}
if (type == UBIFS_DATA_KEY) {
long long blk_offs;
struct ubifs_data_node *dn = node;
/*
* Search the inode node this data node belongs to and insert
* it to the RB-tree of inodes.
*/
inum = key_inum_flash(c, &dn->key);
fscki = read_add_inode(c, priv, inum);
if (IS_ERR(fscki)) {
err = PTR_ERR(fscki);
ubifs_err("error %d while processing data node and "
"trying to find inode node %lu",
err, (unsigned long)inum);
goto out_dump;
}
/* Make sure the data node is within inode size */
blk_offs = key_block_flash(c, &dn->key);
blk_offs <<= UBIFS_BLOCK_SHIFT;
blk_offs += le32_to_cpu(dn->size);
if (blk_offs > fscki->size) {
ubifs_err("data node at LEB %d:%d is not within inode "
"size %lld", zbr->lnum, zbr->offs,
fscki->size);
err = -EINVAL;
goto out_dump;
}
} else {
int nlen;
struct ubifs_dent_node *dent = node;
struct fsck_inode *fscki1;
err = ubifs_validate_entry(c, dent);
if (err)
goto out_dump;
/*
* Search the inode node this entry refers to and the parent
* inode node and insert them to the RB-tree of inodes.
*/
inum = le64_to_cpu(dent->inum);
fscki = read_add_inode(c, priv, inum);
if (IS_ERR(fscki)) {
err = PTR_ERR(fscki);
ubifs_err("error %d while processing entry node and "
"trying to find inode node %lu",
err, (unsigned long)inum);
goto out_dump;
}
/* Count how many direntries or xentries refers this inode */
fscki->references += 1;
inum = key_inum_flash(c, &dent->key);
fscki1 = read_add_inode(c, priv, inum);
if (IS_ERR(fscki1)) {
err = PTR_ERR(fscki1);
ubifs_err("error %d while processing entry node and "
"trying to find parent inode node %lu",
err, (unsigned long)inum);
goto out_dump;
}
nlen = le16_to_cpu(dent->nlen);
if (type == UBIFS_XENT_KEY) {
fscki1->calc_xcnt += 1;
fscki1->calc_xsz += CALC_DENT_SIZE(nlen);
fscki1->calc_xsz += CALC_XATTR_BYTES(fscki->size);
fscki1->calc_xnms += nlen;
} else {
fscki1->calc_sz += CALC_DENT_SIZE(nlen);
if (dent->type == UBIFS_ITYPE_DIR)
fscki1->calc_cnt += 1;
}
}
out:
kfree(node);
return 0;
out_dump:
ubifs_msg("dump of node at LEB %d:%d", zbr->lnum, zbr->offs);
dbg_dump_node(c, node);
out_free:
kfree(node);
return err;
}
/**
* free_inodes - free RB-tree of inodes.
* @fsckd: FS checking information
*/
static void free_inodes(struct fsck_data *fsckd)
{
struct rb_node *this = fsckd->inodes.rb_node;
struct fsck_inode *fscki;
while (this) {
if (this->rb_left)
this = this->rb_left;
else if (this->rb_right)
this = this->rb_right;
else {
fscki = rb_entry(this, struct fsck_inode, rb);
this = rb_parent(this);
if (this) {
if (this->rb_left == &fscki->rb)
this->rb_left = NULL;
else
this->rb_right = NULL;
}
kfree(fscki);
}
}
}
/**
* check_inodes - checks all inodes.
* @c: UBIFS file-system description object
* @fsckd: FS checking information
*
* This is a helper function for 'dbg_check_filesystem()' which walks the
* RB-tree of inodes after the index scan has been finished, and checks that
* inode nlink, size, etc are correct. Returns zero if inodes are fine,
* %-EINVAL if not, and a negative error code in case of failure.
*/
static int check_inodes(struct ubifs_info *c, struct fsck_data *fsckd)
{
int n, err;
union ubifs_key key;
struct ubifs_znode *znode;
struct ubifs_zbranch *zbr;
struct ubifs_ino_node *ino;
struct fsck_inode *fscki;
struct rb_node *this = rb_first(&fsckd->inodes);
while (this) {
fscki = rb_entry(this, struct fsck_inode, rb);
this = rb_next(this);
if (S_ISDIR(fscki->mode)) {
/*
* Directories have to have exactly one reference (they
* cannot have hardlinks), although root inode is an
* exception.
*/
if (fscki->inum != UBIFS_ROOT_INO &&
fscki->references != 1) {
ubifs_err("directory inode %lu has %d "
"direntries which refer it, but "
"should be 1",
(unsigned long)fscki->inum,
fscki->references);
goto out_dump;
}
if (fscki->inum == UBIFS_ROOT_INO &&
fscki->references != 0) {
ubifs_err("root inode %lu has non-zero (%d) "
"direntries which refer it",
(unsigned long)fscki->inum,
fscki->references);
goto out_dump;
}
if (fscki->calc_sz != fscki->size) {
ubifs_err("directory inode %lu size is %lld, "
"but calculated size is %lld",
(unsigned long)fscki->inum,
fscki->size, fscki->calc_sz);
goto out_dump;
}
if (fscki->calc_cnt != fscki->nlink) {
ubifs_err("directory inode %lu nlink is %d, "
"but calculated nlink is %d",
(unsigned long)fscki->inum,
fscki->nlink, fscki->calc_cnt);
goto out_dump;
}
} else {
if (fscki->references != fscki->nlink) {
ubifs_err("inode %lu nlink is %d, but "
"calculated nlink is %d",
(unsigned long)fscki->inum,
fscki->nlink, fscki->references);
goto out_dump;
}
}
if (fscki->xattr_sz != fscki->calc_xsz) {
ubifs_err("inode %lu has xattr size %u, but "
"calculated size is %lld",
(unsigned long)fscki->inum, fscki->xattr_sz,
fscki->calc_xsz);
goto out_dump;
}
if (fscki->xattr_cnt != fscki->calc_xcnt) {
ubifs_err("inode %lu has %u xattrs, but "
"calculated count is %lld",
(unsigned long)fscki->inum,
fscki->xattr_cnt, fscki->calc_xcnt);
goto out_dump;
}
if (fscki->xattr_nms != fscki->calc_xnms) {
ubifs_err("inode %lu has xattr names' size %u, but "
"calculated names' size is %lld",
(unsigned long)fscki->inum, fscki->xattr_nms,
fscki->calc_xnms);
goto out_dump;
}
}
return 0;
out_dump:
/* Read the bad inode and dump it */
ino_key_init(c, &key, fscki->inum);
err = ubifs_lookup_level0(c, &key, &znode, &n);
if (!err) {
ubifs_err("inode %lu not found in index",
(unsigned long)fscki->inum);
return -ENOENT;
} else if (err < 0) {
ubifs_err("error %d while looking up inode %lu",
err, (unsigned long)fscki->inum);
return err;
}
zbr = &znode->zbranch[n];
ino = kmalloc(zbr->len, GFP_NOFS);
if (!ino)
return -ENOMEM;
err = ubifs_tnc_read_node(c, zbr, ino);
if (err) {
ubifs_err("cannot read inode node at LEB %d:%d, error %d",
zbr->lnum, zbr->offs, err);
kfree(ino);
return err;
}
ubifs_msg("dump of the inode %lu sitting in LEB %d:%d",
(unsigned long)fscki->inum, zbr->lnum, zbr->offs);
dbg_dump_node(c, ino);
kfree(ino);
return -EINVAL;
}
/**
* dbg_check_filesystem - check the file-system.
* @c: UBIFS file-system description object
*
* This function checks the file system, namely:
* o makes sure that all leaf nodes exist and their CRCs are correct;
* o makes sure inode nlink, size, xattr size/count are correct (for all
* inodes).
*
* The function reads whole indexing tree and all nodes, so it is pretty
* heavy-weight. Returns zero if the file-system is consistent, %-EINVAL if
* not, and a negative error code in case of failure.
*/
int dbg_check_filesystem(struct ubifs_info *c)
{
int err;
struct fsck_data fsckd;
if (!(ubifs_chk_flags & UBIFS_CHK_FS))
return 0;
fsckd.inodes = RB_ROOT;
err = dbg_walk_index(c, check_leaf, NULL, &fsckd);
if (err)
goto out_free;
err = check_inodes(c, &fsckd);
if (err)
goto out_free;
free_inodes(&fsckd);
return 0;
out_free:
ubifs_err("file-system check failed with error %d", err);
dump_stack();
free_inodes(&fsckd);
return err;
}
static int invocation_cnt;
int dbg_force_in_the_gaps(void)
{
if (!dbg_force_in_the_gaps_enabled)
return 0;
/* Force in-the-gaps every 8th commit */
return !((invocation_cnt++) & 0x7);
}
/* Failure mode for recovery testing */
#define chance(n, d) (simple_rand() <= (n) * 32768LL / (d))
struct failure_mode_info {
struct list_head list;
struct ubifs_info *c;
};
static LIST_HEAD(fmi_list);
static DEFINE_SPINLOCK(fmi_lock);
static unsigned int next;
static int simple_rand(void)
{
if (next == 0)
next = current->pid;
next = next * 1103515245 + 12345;
return (next >> 16) & 32767;
}
static void failure_mode_init(struct ubifs_info *c)
{
struct failure_mode_info *fmi;
fmi = kmalloc(sizeof(struct failure_mode_info), GFP_NOFS);
if (!fmi) {
ubifs_err("Failed to register failure mode - no memory");
return;
}
fmi->c = c;
spin_lock(&fmi_lock);
list_add_tail(&fmi->list, &fmi_list);
spin_unlock(&fmi_lock);
}
static void failure_mode_exit(struct ubifs_info *c)
{
struct failure_mode_info *fmi, *tmp;
spin_lock(&fmi_lock);
list_for_each_entry_safe(fmi, tmp, &fmi_list, list)
if (fmi->c == c) {
list_del(&fmi->list);
kfree(fmi);
}
spin_unlock(&fmi_lock);
}
static struct ubifs_info *dbg_find_info(struct ubi_volume_desc *desc)
{
struct failure_mode_info *fmi;
spin_lock(&fmi_lock);
list_for_each_entry(fmi, &fmi_list, list)
if (fmi->c->ubi == desc) {
struct ubifs_info *c = fmi->c;
spin_unlock(&fmi_lock);
return c;
}
spin_unlock(&fmi_lock);
return NULL;
}
static int in_failure_mode(struct ubi_volume_desc *desc)
{
struct ubifs_info *c = dbg_find_info(desc);
if (c && dbg_failure_mode)
return c->dbg->failure_mode;
return 0;
}
static int do_fail(struct ubi_volume_desc *desc, int lnum, int write)
{
struct ubifs_info *c = dbg_find_info(desc);
struct ubifs_debug_info *d;
if (!c || !dbg_failure_mode)
return 0;
d = c->dbg;
if (d->failure_mode)
return 1;
if (!d->fail_cnt) {
/* First call - decide delay to failure */
if (chance(1, 2)) {
unsigned int delay = 1 << (simple_rand() >> 11);
if (chance(1, 2)) {
d->fail_delay = 1;
d->fail_timeout = jiffies +
msecs_to_jiffies(delay);
dbg_rcvry("failing after %ums", delay);
} else {
d->fail_delay = 2;
d->fail_cnt_max = delay;
dbg_rcvry("failing after %u calls", delay);
}
}
d->fail_cnt += 1;
}
/* Determine if failure delay has expired */
if (d->fail_delay == 1) {
if (time_before(jiffies, d->fail_timeout))
return 0;
} else if (d->fail_delay == 2)
if (d->fail_cnt++ < d->fail_cnt_max)
return 0;
if (lnum == UBIFS_SB_LNUM) {
if (write) {
if (chance(1, 2))
return 0;
} else if (chance(19, 20))
return 0;
dbg_rcvry("failing in super block LEB %d", lnum);
} else if (lnum == UBIFS_MST_LNUM || lnum == UBIFS_MST_LNUM + 1) {
if (chance(19, 20))
return 0;
dbg_rcvry("failing in master LEB %d", lnum);
} else if (lnum >= UBIFS_LOG_LNUM && lnum <= c->log_last) {
if (write) {
if (chance(99, 100))
return 0;
} else if (chance(399, 400))
return 0;
dbg_rcvry("failing in log LEB %d", lnum);
} else if (lnum >= c->lpt_first && lnum <= c->lpt_last) {
if (write) {
if (chance(7, 8))
return 0;
} else if (chance(19, 20))
return 0;
dbg_rcvry("failing in LPT LEB %d", lnum);
} else if (lnum >= c->orph_first && lnum <= c->orph_last) {
if (write) {
if (chance(1, 2))
return 0;
} else if (chance(9, 10))
return 0;
dbg_rcvry("failing in orphan LEB %d", lnum);
} else if (lnum == c->ihead_lnum) {
if (chance(99, 100))
return 0;
dbg_rcvry("failing in index head LEB %d", lnum);
} else if (c->jheads && lnum == c->jheads[GCHD].wbuf.lnum) {
if (chance(9, 10))
return 0;
dbg_rcvry("failing in GC head LEB %d", lnum);
} else if (write && !RB_EMPTY_ROOT(&c->buds) &&
!ubifs_search_bud(c, lnum)) {
if (chance(19, 20))
return 0;
dbg_rcvry("failing in non-bud LEB %d", lnum);
} else if (c->cmt_state == COMMIT_RUNNING_BACKGROUND ||
c->cmt_state == COMMIT_RUNNING_REQUIRED) {
if (chance(999, 1000))
return 0;
dbg_rcvry("failing in bud LEB %d commit running", lnum);
} else {
if (chance(9999, 10000))
return 0;
dbg_rcvry("failing in bud LEB %d commit not running", lnum);
}
ubifs_err("*** SETTING FAILURE MODE ON (LEB %d) ***", lnum);
d->failure_mode = 1;
dump_stack();
return 1;
}
static void cut_data(const void *buf, int len)
{
int flen, i;
unsigned char *p = (void *)buf;
flen = (len * (long long)simple_rand()) >> 15;
for (i = flen; i < len; i++)
p[i] = 0xff;
}
int dbg_leb_read(struct ubi_volume_desc *desc, int lnum, char *buf, int offset,
int len, int check)
{
if (in_failure_mode(desc))
return -EIO;
return ubi_leb_read(desc, lnum, buf, offset, len, check);
}
int dbg_leb_write(struct ubi_volume_desc *desc, int lnum, const void *buf,
int offset, int len, int dtype)
{
int err, failing;
if (in_failure_mode(desc))
return -EIO;
failing = do_fail(desc, lnum, 1);
if (failing)
cut_data(buf, len);
err = ubi_leb_write(desc, lnum, buf, offset, len, dtype);
if (err)
return err;
if (failing)
return -EIO;
return 0;
}
int dbg_leb_change(struct ubi_volume_desc *desc, int lnum, const void *buf,
int len, int dtype)
{
int err;
if (do_fail(desc, lnum, 1))
return -EIO;
err = ubi_leb_change(desc, lnum, buf, len, dtype);
if (err)
return err;
if (do_fail(desc, lnum, 1))
return -EIO;
return 0;
}
int dbg_leb_erase(struct ubi_volume_desc *desc, int lnum)
{
int err;
if (do_fail(desc, lnum, 0))
return -EIO;
err = ubi_leb_erase(desc, lnum);
if (err)
return err;
if (do_fail(desc, lnum, 0))
return -EIO;
return 0;
}
int dbg_leb_unmap(struct ubi_volume_desc *desc, int lnum)
{
int err;
if (do_fail(desc, lnum, 0))
return -EIO;
err = ubi_leb_unmap(desc, lnum);
if (err)
return err;
if (do_fail(desc, lnum, 0))
return -EIO;
return 0;
}
int dbg_is_mapped(struct ubi_volume_desc *desc, int lnum)
{
if (in_failure_mode(desc))
return -EIO;
return ubi_is_mapped(desc, lnum);
}
int dbg_leb_map(struct ubi_volume_desc *desc, int lnum, int dtype)
{
int err;
if (do_fail(desc, lnum, 0))
return -EIO;
err = ubi_leb_map(desc, lnum, dtype);
if (err)
return err;
if (do_fail(desc, lnum, 0))
return -EIO;
return 0;
}
/**
* ubifs_debugging_init - initialize UBIFS debugging.
* @c: UBIFS file-system description object
*
* This function initializes debugging-related data for the file system.
* Returns zero in case of success and a negative error code in case of
* failure.
*/
int ubifs_debugging_init(struct ubifs_info *c)
{
c->dbg = kzalloc(sizeof(struct ubifs_debug_info), GFP_KERNEL);
if (!c->dbg)
return -ENOMEM;
c->dbg->buf = vmalloc(c->leb_size);
if (!c->dbg->buf)
goto out;
failure_mode_init(c);
return 0;
out:
kfree(c->dbg);
return -ENOMEM;
}
/**
* ubifs_debugging_exit - free debugging data.
* @c: UBIFS file-system description object
*/
void ubifs_debugging_exit(struct ubifs_info *c)
{
failure_mode_exit(c);
vfree(c->dbg->buf);
kfree(c->dbg);
}
/*
* Root directory for UBIFS stuff in debugfs. Contains sub-directories which
* contain the stuff specific to particular file-system mounts.
*/
static struct dentry *dfs_rootdir;
/**
* dbg_debugfs_init - initialize debugfs file-system.
*
* UBIFS uses debugfs file-system to expose various debugging knobs to
* user-space. This function creates "ubifs" directory in the debugfs
* file-system. Returns zero in case of success and a negative error code in
* case of failure.
*/
int dbg_debugfs_init(void)
{
dfs_rootdir = debugfs_create_dir("ubifs", NULL);
if (IS_ERR(dfs_rootdir)) {
int err = PTR_ERR(dfs_rootdir);
ubifs_err("cannot create \"ubifs\" debugfs directory, "
"error %d\n", err);
return err;
}
return 0;
}
/**
* dbg_debugfs_exit - remove the "ubifs" directory from debugfs file-system.
*/
void dbg_debugfs_exit(void)
{
debugfs_remove(dfs_rootdir);
}
static int open_debugfs_file(struct inode *inode, struct file *file)
{
file->private_data = inode->i_private;
return 0;
}
static ssize_t write_debugfs_file(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
struct ubifs_info *c = file->private_data;
struct ubifs_debug_info *d = c->dbg;
if (file->f_path.dentry == d->dfs_dump_lprops)
dbg_dump_lprops(c);
else if (file->f_path.dentry == d->dfs_dump_budg) {
spin_lock(&c->space_lock);
dbg_dump_budg(c);
spin_unlock(&c->space_lock);
} else if (file->f_path.dentry == d->dfs_dump_tnc) {
mutex_lock(&c->tnc_mutex);
dbg_dump_tnc(c);
mutex_unlock(&c->tnc_mutex);
} else
return -EINVAL;
*ppos += count;
return count;
}
static const struct file_operations dfs_fops = {
.open = open_debugfs_file,
.write = write_debugfs_file,
.owner = THIS_MODULE,
};
/**
* dbg_debugfs_init_fs - initialize debugfs for UBIFS instance.
* @c: UBIFS file-system description object
*
* This function creates all debugfs files for this instance of UBIFS. Returns
* zero in case of success and a negative error code in case of failure.
*
* Note, the only reason we have not merged this function with the
* 'ubifs_debugging_init()' function is because it is better to initialize
* debugfs interfaces at the very end of the mount process, and remove them at
* the very beginning of the mount process.
*/
int dbg_debugfs_init_fs(struct ubifs_info *c)
{
int err;
const char *fname;
struct dentry *dent;
struct ubifs_debug_info *d = c->dbg;
sprintf(d->dfs_dir_name, "ubi%d_%d", c->vi.ubi_num, c->vi.vol_id);
d->dfs_dir = debugfs_create_dir(d->dfs_dir_name, dfs_rootdir);
if (IS_ERR(d->dfs_dir)) {
err = PTR_ERR(d->dfs_dir);
ubifs_err("cannot create \"%s\" debugfs directory, error %d\n",
d->dfs_dir_name, err);
goto out;
}
fname = "dump_lprops";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, c, &dfs_fops);
if (IS_ERR(dent))
goto out_remove;
d->dfs_dump_lprops = dent;
fname = "dump_budg";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, c, &dfs_fops);
if (IS_ERR(dent))
goto out_remove;
d->dfs_dump_budg = dent;
fname = "dump_tnc";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, c, &dfs_fops);
if (IS_ERR(dent))
goto out_remove;
d->dfs_dump_tnc = dent;
return 0;
out_remove:
err = PTR_ERR(dent);
ubifs_err("cannot create \"%s\" debugfs directory, error %d\n",
fname, err);
debugfs_remove_recursive(d->dfs_dir);
out:
return err;
}
/**
* dbg_debugfs_exit_fs - remove all debugfs files.
* @c: UBIFS file-system description object
*/
void dbg_debugfs_exit_fs(struct ubifs_info *c)
{
debugfs_remove_recursive(c->dbg->dfs_dir);
}
#endif /* CONFIG_UBIFS_FS_DEBUG */
| gpl-2.0 |
sjp38/linux.doc_trans_membarrier | net/ipv4/netfilter/nf_defrag_ipv4.c | 209 | 3022 | /* (C) 1999-2001 Paul `Rusty' Russell
* (C) 2002-2004 Netfilter Core Team <coreteam@netfilter.org>
*
* 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/types.h>
#include <linux/ip.h>
#include <linux/netfilter.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <net/route.h>
#include <net/ip.h>
#include <linux/netfilter_bridge.h>
#include <linux/netfilter_ipv4.h>
#include <net/netfilter/ipv4/nf_defrag_ipv4.h>
#if IS_ENABLED(CONFIG_NF_CONNTRACK)
#include <net/netfilter/nf_conntrack.h>
#endif
#include <net/netfilter/nf_conntrack_zones.h>
static int nf_ct_ipv4_gather_frags(struct net *net, struct sk_buff *skb,
u_int32_t user)
{
int err;
local_bh_disable();
err = ip_defrag(net, skb, user);
local_bh_enable();
if (!err)
skb->ignore_df = 1;
return err;
}
static enum ip_defrag_users nf_ct_defrag_user(unsigned int hooknum,
struct sk_buff *skb)
{
u16 zone_id = NF_CT_DEFAULT_ZONE_ID;
#if IS_ENABLED(CONFIG_NF_CONNTRACK)
if (skb->nfct) {
enum ip_conntrack_info ctinfo;
const struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
zone_id = nf_ct_zone_id(nf_ct_zone(ct), CTINFO2DIR(ctinfo));
}
#endif
if (nf_bridge_in_prerouting(skb))
return IP_DEFRAG_CONNTRACK_BRIDGE_IN + zone_id;
if (hooknum == NF_INET_PRE_ROUTING)
return IP_DEFRAG_CONNTRACK_IN + zone_id;
else
return IP_DEFRAG_CONNTRACK_OUT + zone_id;
}
static unsigned int ipv4_conntrack_defrag(void *priv,
struct sk_buff *skb,
const struct nf_hook_state *state)
{
struct sock *sk = skb->sk;
if (sk && sk_fullsock(sk) && (sk->sk_family == PF_INET) &&
inet_sk(sk)->nodefrag)
return NF_ACCEPT;
#if IS_ENABLED(CONFIG_NF_CONNTRACK)
#if !IS_ENABLED(CONFIG_NF_NAT)
/* Previously seen (loopback)? Ignore. Do this before
fragment check. */
if (skb->nfct && !nf_ct_is_template((struct nf_conn *)skb->nfct))
return NF_ACCEPT;
#endif
#endif
/* Gather fragments. */
if (ip_is_fragment(ip_hdr(skb))) {
enum ip_defrag_users user =
nf_ct_defrag_user(state->hook, skb);
if (nf_ct_ipv4_gather_frags(state->net, skb, user))
return NF_STOLEN;
}
return NF_ACCEPT;
}
static struct nf_hook_ops ipv4_defrag_ops[] = {
{
.hook = ipv4_conntrack_defrag,
.pf = NFPROTO_IPV4,
.hooknum = NF_INET_PRE_ROUTING,
.priority = NF_IP_PRI_CONNTRACK_DEFRAG,
},
{
.hook = ipv4_conntrack_defrag,
.pf = NFPROTO_IPV4,
.hooknum = NF_INET_LOCAL_OUT,
.priority = NF_IP_PRI_CONNTRACK_DEFRAG,
},
};
static int __init nf_defrag_init(void)
{
return nf_register_hooks(ipv4_defrag_ops, ARRAY_SIZE(ipv4_defrag_ops));
}
static void __exit nf_defrag_fini(void)
{
nf_unregister_hooks(ipv4_defrag_ops, ARRAY_SIZE(ipv4_defrag_ops));
}
void nf_defrag_ipv4_enable(void)
{
}
EXPORT_SYMBOL_GPL(nf_defrag_ipv4_enable);
module_init(nf_defrag_init);
module_exit(nf_defrag_fini);
MODULE_LICENSE("GPL");
| gpl-2.0 |
diegocortassa/android-kernel-mediacom-mp810c | drivers/scsi/qla2xxx/qla_mbx.c | 465 | 92719 | /*
* QLogic Fibre Channel HBA Driver
* Copyright (c) 2003-2008 QLogic Corporation
*
* See LICENSE.qla2xxx for copyright and licensing details.
*/
#include "qla_def.h"
#include <linux/delay.h>
/*
* qla2x00_mailbox_command
* Issue mailbox command and waits for completion.
*
* Input:
* ha = adapter block pointer.
* mcp = driver internal mbx struct pointer.
*
* Output:
* mb[MAX_MAILBOX_REGISTER_COUNT] = returned mailbox data.
*
* Returns:
* 0 : QLA_SUCCESS = cmd performed success
* 1 : QLA_FUNCTION_FAILED (error encountered)
* 6 : QLA_FUNCTION_TIMEOUT (timeout condition encountered)
*
* Context:
* Kernel context.
*/
static int
qla2x00_mailbox_command(scsi_qla_host_t *vha, mbx_cmd_t *mcp)
{
int rval;
unsigned long flags = 0;
device_reg_t __iomem *reg;
uint8_t abort_active;
uint8_t io_lock_on;
uint16_t command;
uint16_t *iptr;
uint16_t __iomem *optr;
uint32_t cnt;
uint32_t mboxes;
unsigned long wait_time;
struct qla_hw_data *ha = vha->hw;
scsi_qla_host_t *base_vha = pci_get_drvdata(ha->pdev);
if (ha->pdev->error_state > pci_channel_io_frozen)
return QLA_FUNCTION_TIMEOUT;
reg = ha->iobase;
io_lock_on = base_vha->flags.init_done;
rval = QLA_SUCCESS;
abort_active = test_bit(ABORT_ISP_ACTIVE, &base_vha->dpc_flags);
DEBUG11(printk("%s(%ld): entered.\n", __func__, base_vha->host_no));
/*
* Wait for active mailbox commands to finish by waiting at most tov
* seconds. This is to serialize actual issuing of mailbox cmds during
* non ISP abort time.
*/
if (!wait_for_completion_timeout(&ha->mbx_cmd_comp, mcp->tov * HZ)) {
/* Timeout occurred. Return error. */
DEBUG2_3_11(printk("%s(%ld): cmd access timeout. "
"Exiting.\n", __func__, base_vha->host_no));
return QLA_FUNCTION_TIMEOUT;
}
ha->flags.mbox_busy = 1;
/* Save mailbox command for debug */
ha->mcp = mcp;
DEBUG11(printk("scsi(%ld): prepare to issue mbox cmd=0x%x.\n",
base_vha->host_no, mcp->mb[0]));
spin_lock_irqsave(&ha->hardware_lock, flags);
/* Load mailbox registers. */
if (IS_FWI2_CAPABLE(ha))
optr = (uint16_t __iomem *)®->isp24.mailbox0;
else
optr = (uint16_t __iomem *)MAILBOX_REG(ha, ®->isp, 0);
iptr = mcp->mb;
command = mcp->mb[0];
mboxes = mcp->out_mb;
for (cnt = 0; cnt < ha->mbx_count; cnt++) {
if (IS_QLA2200(ha) && cnt == 8)
optr =
(uint16_t __iomem *)MAILBOX_REG(ha, ®->isp, 8);
if (mboxes & BIT_0)
WRT_REG_WORD(optr, *iptr);
mboxes >>= 1;
optr++;
iptr++;
}
#if defined(QL_DEBUG_LEVEL_1)
printk("%s(%ld): Loaded MBX registers (displayed in bytes) = \n",
__func__, base_vha->host_no);
qla2x00_dump_buffer((uint8_t *)mcp->mb, 16);
printk("\n");
qla2x00_dump_buffer(((uint8_t *)mcp->mb + 0x10), 16);
printk("\n");
qla2x00_dump_buffer(((uint8_t *)mcp->mb + 0x20), 8);
printk("\n");
printk("%s(%ld): I/O address = %p.\n", __func__, base_vha->host_no,
optr);
qla2x00_dump_regs(base_vha);
#endif
/* Issue set host interrupt command to send cmd out. */
ha->flags.mbox_int = 0;
clear_bit(MBX_INTERRUPT, &ha->mbx_cmd_flags);
/* Unlock mbx registers and wait for interrupt */
DEBUG11(printk("%s(%ld): going to unlock irq & waiting for interrupt. "
"jiffies=%lx.\n", __func__, base_vha->host_no, jiffies));
/* Wait for mbx cmd completion until timeout */
if ((!abort_active && io_lock_on) || IS_NOPOLLING_TYPE(ha)) {
set_bit(MBX_INTR_WAIT, &ha->mbx_cmd_flags);
if (IS_FWI2_CAPABLE(ha))
WRT_REG_DWORD(®->isp24.hccr, HCCRX_SET_HOST_INT);
else
WRT_REG_WORD(®->isp.hccr, HCCR_SET_HOST_INT);
spin_unlock_irqrestore(&ha->hardware_lock, flags);
wait_for_completion_timeout(&ha->mbx_intr_comp, mcp->tov * HZ);
clear_bit(MBX_INTR_WAIT, &ha->mbx_cmd_flags);
} else {
DEBUG3_11(printk("%s(%ld): cmd=%x POLLING MODE.\n", __func__,
base_vha->host_no, command));
if (IS_FWI2_CAPABLE(ha))
WRT_REG_DWORD(®->isp24.hccr, HCCRX_SET_HOST_INT);
else
WRT_REG_WORD(®->isp.hccr, HCCR_SET_HOST_INT);
spin_unlock_irqrestore(&ha->hardware_lock, flags);
wait_time = jiffies + mcp->tov * HZ; /* wait at most tov secs */
while (!ha->flags.mbox_int) {
if (time_after(jiffies, wait_time))
break;
/* Check for pending interrupts. */
qla2x00_poll(ha->rsp_q_map[0]);
if (command != MBC_LOAD_RISC_RAM_EXTENDED &&
!ha->flags.mbox_int)
msleep(10);
} /* while */
}
/* Check whether we timed out */
if (ha->flags.mbox_int) {
uint16_t *iptr2;
DEBUG3_11(printk("%s(%ld): cmd %x completed.\n", __func__,
base_vha->host_no, command));
/* Got interrupt. Clear the flag. */
ha->flags.mbox_int = 0;
clear_bit(MBX_INTERRUPT, &ha->mbx_cmd_flags);
if (ha->mailbox_out[0] != MBS_COMMAND_COMPLETE)
rval = QLA_FUNCTION_FAILED;
/* Load return mailbox registers. */
iptr2 = mcp->mb;
iptr = (uint16_t *)&ha->mailbox_out[0];
mboxes = mcp->in_mb;
for (cnt = 0; cnt < ha->mbx_count; cnt++) {
if (mboxes & BIT_0)
*iptr2 = *iptr;
mboxes >>= 1;
iptr2++;
iptr++;
}
} else {
#if defined(QL_DEBUG_LEVEL_2) || defined(QL_DEBUG_LEVEL_3) || \
defined(QL_DEBUG_LEVEL_11)
uint16_t mb0;
uint32_t ictrl;
if (IS_FWI2_CAPABLE(ha)) {
mb0 = RD_REG_WORD(®->isp24.mailbox0);
ictrl = RD_REG_DWORD(®->isp24.ictrl);
} else {
mb0 = RD_MAILBOX_REG(ha, ®->isp, 0);
ictrl = RD_REG_WORD(®->isp.ictrl);
}
printk("%s(%ld): **** MB Command Timeout for cmd %x ****\n",
__func__, base_vha->host_no, command);
printk("%s(%ld): icontrol=%x jiffies=%lx\n", __func__,
base_vha->host_no, ictrl, jiffies);
printk("%s(%ld): *** mailbox[0] = 0x%x ***\n", __func__,
base_vha->host_no, mb0);
qla2x00_dump_regs(base_vha);
#endif
rval = QLA_FUNCTION_TIMEOUT;
}
ha->flags.mbox_busy = 0;
/* Clean up */
ha->mcp = NULL;
if ((abort_active || !io_lock_on) && !IS_NOPOLLING_TYPE(ha)) {
DEBUG11(printk("%s(%ld): checking for additional resp "
"interrupt.\n", __func__, base_vha->host_no));
/* polling mode for non isp_abort commands. */
qla2x00_poll(ha->rsp_q_map[0]);
}
if (rval == QLA_FUNCTION_TIMEOUT &&
mcp->mb[0] != MBC_GEN_SYSTEM_ERROR) {
if (!io_lock_on || (mcp->flags & IOCTL_CMD)) {
/* not in dpc. schedule it for dpc to take over. */
DEBUG(printk("%s(%ld): timeout schedule "
"isp_abort_needed.\n", __func__,
base_vha->host_no));
DEBUG2_3_11(printk("%s(%ld): timeout schedule "
"isp_abort_needed.\n", __func__,
base_vha->host_no));
qla_printk(KERN_WARNING, ha,
"Mailbox command timeout occurred. Scheduling ISP "
"abort.\n");
set_bit(ISP_ABORT_NEEDED, &base_vha->dpc_flags);
qla2xxx_wake_dpc(vha);
} else if (!abort_active) {
/* call abort directly since we are in the DPC thread */
DEBUG(printk("%s(%ld): timeout calling abort_isp\n",
__func__, base_vha->host_no));
DEBUG2_3_11(printk("%s(%ld): timeout calling "
"abort_isp\n", __func__, base_vha->host_no));
qla_printk(KERN_WARNING, ha,
"Mailbox command timeout occurred. Issuing ISP "
"abort.\n");
set_bit(ABORT_ISP_ACTIVE, &base_vha->dpc_flags);
clear_bit(ISP_ABORT_NEEDED, &base_vha->dpc_flags);
if (qla2x00_abort_isp(base_vha)) {
/* Failed. retry later. */
set_bit(ISP_ABORT_NEEDED, &base_vha->dpc_flags);
}
clear_bit(ABORT_ISP_ACTIVE, &base_vha->dpc_flags);
DEBUG(printk("%s(%ld): finished abort_isp\n", __func__,
base_vha->host_no));
DEBUG2_3_11(printk("%s(%ld): finished abort_isp\n",
__func__, base_vha->host_no));
}
}
/* Allow next mbx cmd to come in. */
complete(&ha->mbx_cmd_comp);
if (rval) {
DEBUG2_3_11(printk("%s(%ld): **** FAILED. mbx0=%x, mbx1=%x, "
"mbx2=%x, cmd=%x ****\n", __func__, base_vha->host_no,
mcp->mb[0], mcp->mb[1], mcp->mb[2], command));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__,
base_vha->host_no));
}
return rval;
}
int
qla2x00_load_ram(scsi_qla_host_t *vha, dma_addr_t req_dma, uint32_t risc_addr,
uint32_t risc_code_size)
{
int rval;
struct qla_hw_data *ha = vha->hw;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
if (MSW(risc_addr) || IS_FWI2_CAPABLE(ha)) {
mcp->mb[0] = MBC_LOAD_RISC_RAM_EXTENDED;
mcp->mb[8] = MSW(risc_addr);
mcp->out_mb = MBX_8|MBX_0;
} else {
mcp->mb[0] = MBC_LOAD_RISC_RAM;
mcp->out_mb = MBX_0;
}
mcp->mb[1] = LSW(risc_addr);
mcp->mb[2] = MSW(req_dma);
mcp->mb[3] = LSW(req_dma);
mcp->mb[6] = MSW(MSD(req_dma));
mcp->mb[7] = LSW(MSD(req_dma));
mcp->out_mb |= MBX_7|MBX_6|MBX_3|MBX_2|MBX_1;
if (IS_FWI2_CAPABLE(ha)) {
mcp->mb[4] = MSW(risc_code_size);
mcp->mb[5] = LSW(risc_code_size);
mcp->out_mb |= MBX_5|MBX_4;
} else {
mcp->mb[4] = LSW(risc_code_size);
mcp->out_mb |= MBX_4;
}
mcp->in_mb = MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x mb[0]=%x.\n", __func__,
vha->host_no, rval, mcp->mb[0]));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
/*
* qla2x00_execute_fw
* Start adapter firmware.
*
* Input:
* ha = adapter block pointer.
* TARGET_QUEUE_LOCK must be released.
* ADAPTER_STATE_LOCK must be released.
*
* Returns:
* qla2x00 local function return status code.
*
* Context:
* Kernel context.
*/
int
qla2x00_execute_fw(scsi_qla_host_t *vha, uint32_t risc_addr)
{
int rval;
struct qla_hw_data *ha = vha->hw;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_EXECUTE_FIRMWARE;
mcp->out_mb = MBX_0;
mcp->in_mb = MBX_0;
if (IS_FWI2_CAPABLE(ha)) {
mcp->mb[1] = MSW(risc_addr);
mcp->mb[2] = LSW(risc_addr);
mcp->mb[3] = 0;
mcp->mb[4] = 0;
mcp->out_mb |= MBX_4|MBX_3|MBX_2|MBX_1;
mcp->in_mb |= MBX_1;
} else {
mcp->mb[1] = LSW(risc_addr);
mcp->out_mb |= MBX_1;
if (IS_QLA2322(ha) || IS_QLA6322(ha)) {
mcp->mb[2] = 0;
mcp->out_mb |= MBX_2;
}
}
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x mb[0]=%x.\n", __func__,
vha->host_no, rval, mcp->mb[0]));
} else {
if (IS_FWI2_CAPABLE(ha)) {
DEBUG11(printk("%s(%ld): done exchanges=%x.\n",
__func__, vha->host_no, mcp->mb[1]));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__,
vha->host_no));
}
}
return rval;
}
/*
* qla2x00_get_fw_version
* Get firmware version.
*
* Input:
* ha: adapter state pointer.
* major: pointer for major number.
* minor: pointer for minor number.
* subminor: pointer for subminor number.
*
* Returns:
* qla2x00 local function return status code.
*
* Context:
* Kernel context.
*/
int
qla2x00_get_fw_version(scsi_qla_host_t *vha, uint16_t *major, uint16_t *minor,
uint16_t *subminor, uint16_t *attributes, uint32_t *memory, uint8_t *mpi,
uint32_t *mpi_caps, uint8_t *phy)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_GET_FIRMWARE_VERSION;
mcp->out_mb = MBX_0;
mcp->in_mb = MBX_6|MBX_5|MBX_4|MBX_3|MBX_2|MBX_1|MBX_0;
if (IS_QLA81XX(vha->hw))
mcp->in_mb |= MBX_13|MBX_12|MBX_11|MBX_10|MBX_9|MBX_8;
mcp->flags = 0;
mcp->tov = MBX_TOV_SECONDS;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS)
goto failed;
/* Return mailbox data. */
*major = mcp->mb[1];
*minor = mcp->mb[2];
*subminor = mcp->mb[3];
*attributes = mcp->mb[6];
if (IS_QLA2100(vha->hw) || IS_QLA2200(vha->hw))
*memory = 0x1FFFF; /* Defaults to 128KB. */
else
*memory = (mcp->mb[5] << 16) | mcp->mb[4];
if (IS_QLA81XX(vha->hw)) {
mpi[0] = mcp->mb[10] & 0xff;
mpi[1] = mcp->mb[11] >> 8;
mpi[2] = mcp->mb[11] & 0xff;
*mpi_caps = (mcp->mb[12] << 16) | mcp->mb[13];
phy[0] = mcp->mb[8] & 0xff;
phy[1] = mcp->mb[9] >> 8;
phy[2] = mcp->mb[9] & 0xff;
}
failed:
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3_11(printk("%s(%ld): failed=%x.\n", __func__,
vha->host_no, rval));
} else {
/*EMPTY*/
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
/*
* qla2x00_get_fw_options
* Set firmware options.
*
* Input:
* ha = adapter block pointer.
* fwopt = pointer for firmware options.
*
* Returns:
* qla2x00 local function return status code.
*
* Context:
* Kernel context.
*/
int
qla2x00_get_fw_options(scsi_qla_host_t *vha, uint16_t *fwopts)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_GET_FIRMWARE_OPTION;
mcp->out_mb = MBX_0;
mcp->in_mb = MBX_3|MBX_2|MBX_1|MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3_11(printk("%s(%ld): failed=%x.\n", __func__,
vha->host_no, rval));
} else {
fwopts[0] = mcp->mb[0];
fwopts[1] = mcp->mb[1];
fwopts[2] = mcp->mb[2];
fwopts[3] = mcp->mb[3];
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
/*
* qla2x00_set_fw_options
* Set firmware options.
*
* Input:
* ha = adapter block pointer.
* fwopt = pointer for firmware options.
*
* Returns:
* qla2x00 local function return status code.
*
* Context:
* Kernel context.
*/
int
qla2x00_set_fw_options(scsi_qla_host_t *vha, uint16_t *fwopts)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_SET_FIRMWARE_OPTION;
mcp->mb[1] = fwopts[1];
mcp->mb[2] = fwopts[2];
mcp->mb[3] = fwopts[3];
mcp->out_mb = MBX_3|MBX_2|MBX_1|MBX_0;
mcp->in_mb = MBX_0;
if (IS_FWI2_CAPABLE(vha->hw)) {
mcp->in_mb |= MBX_1;
} else {
mcp->mb[10] = fwopts[10];
mcp->mb[11] = fwopts[11];
mcp->mb[12] = 0; /* Undocumented, but used */
mcp->out_mb |= MBX_12|MBX_11|MBX_10;
}
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
fwopts[0] = mcp->mb[0];
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3_11(printk("%s(%ld): failed=%x (%x/%x).\n", __func__,
vha->host_no, rval, mcp->mb[0], mcp->mb[1]));
} else {
/*EMPTY*/
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
/*
* qla2x00_mbx_reg_test
* Mailbox register wrap test.
*
* Input:
* ha = adapter block pointer.
* TARGET_QUEUE_LOCK must be released.
* ADAPTER_STATE_LOCK must be released.
*
* Returns:
* qla2x00 local function return status code.
*
* Context:
* Kernel context.
*/
int
qla2x00_mbx_reg_test(scsi_qla_host_t *vha)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
DEBUG11(printk("qla2x00_mbx_reg_test(%ld): entered.\n", vha->host_no));
mcp->mb[0] = MBC_MAILBOX_REGISTER_TEST;
mcp->mb[1] = 0xAAAA;
mcp->mb[2] = 0x5555;
mcp->mb[3] = 0xAA55;
mcp->mb[4] = 0x55AA;
mcp->mb[5] = 0xA5A5;
mcp->mb[6] = 0x5A5A;
mcp->mb[7] = 0x2525;
mcp->out_mb = MBX_7|MBX_6|MBX_5|MBX_4|MBX_3|MBX_2|MBX_1|MBX_0;
mcp->in_mb = MBX_7|MBX_6|MBX_5|MBX_4|MBX_3|MBX_2|MBX_1|MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval == QLA_SUCCESS) {
if (mcp->mb[1] != 0xAAAA || mcp->mb[2] != 0x5555 ||
mcp->mb[3] != 0xAA55 || mcp->mb[4] != 0x55AA)
rval = QLA_FUNCTION_FAILED;
if (mcp->mb[5] != 0xA5A5 || mcp->mb[6] != 0x5A5A ||
mcp->mb[7] != 0x2525)
rval = QLA_FUNCTION_FAILED;
}
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3_11(printk("qla2x00_mbx_reg_test(%ld): failed=%x.\n",
vha->host_no, rval));
} else {
/*EMPTY*/
DEBUG11(printk("qla2x00_mbx_reg_test(%ld): done.\n",
vha->host_no));
}
return rval;
}
/*
* qla2x00_verify_checksum
* Verify firmware checksum.
*
* Input:
* ha = adapter block pointer.
* TARGET_QUEUE_LOCK must be released.
* ADAPTER_STATE_LOCK must be released.
*
* Returns:
* qla2x00 local function return status code.
*
* Context:
* Kernel context.
*/
int
qla2x00_verify_checksum(scsi_qla_host_t *vha, uint32_t risc_addr)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_VERIFY_CHECKSUM;
mcp->out_mb = MBX_0;
mcp->in_mb = MBX_0;
if (IS_FWI2_CAPABLE(vha->hw)) {
mcp->mb[1] = MSW(risc_addr);
mcp->mb[2] = LSW(risc_addr);
mcp->out_mb |= MBX_2|MBX_1;
mcp->in_mb |= MBX_2|MBX_1;
} else {
mcp->mb[1] = LSW(risc_addr);
mcp->out_mb |= MBX_1;
mcp->in_mb |= MBX_1;
}
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x chk sum=%x.\n", __func__,
vha->host_no, rval, IS_FWI2_CAPABLE(vha->hw) ?
(mcp->mb[2] << 16) | mcp->mb[1]: mcp->mb[1]));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
/*
* qla2x00_issue_iocb
* Issue IOCB using mailbox command
*
* Input:
* ha = adapter state pointer.
* buffer = buffer pointer.
* phys_addr = physical address of buffer.
* size = size of buffer.
* TARGET_QUEUE_LOCK must be released.
* ADAPTER_STATE_LOCK must be released.
*
* Returns:
* qla2x00 local function return status code.
*
* Context:
* Kernel context.
*/
static int
qla2x00_issue_iocb_timeout(scsi_qla_host_t *vha, void *buffer,
dma_addr_t phys_addr, size_t size, uint32_t tov)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
mcp->mb[0] = MBC_IOCB_COMMAND_A64;
mcp->mb[1] = 0;
mcp->mb[2] = MSW(phys_addr);
mcp->mb[3] = LSW(phys_addr);
mcp->mb[6] = MSW(MSD(phys_addr));
mcp->mb[7] = LSW(MSD(phys_addr));
mcp->out_mb = MBX_7|MBX_6|MBX_3|MBX_2|MBX_1|MBX_0;
mcp->in_mb = MBX_2|MBX_0;
mcp->tov = tov;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG(printk("qla2x00_issue_iocb(%ld): failed rval 0x%x\n",
vha->host_no, rval));
} else {
sts_entry_t *sts_entry = (sts_entry_t *) buffer;
/* Mask reserved bits. */
sts_entry->entry_status &=
IS_FWI2_CAPABLE(vha->hw) ? RF_MASK_24XX : RF_MASK;
}
return rval;
}
int
qla2x00_issue_iocb(scsi_qla_host_t *vha, void *buffer, dma_addr_t phys_addr,
size_t size)
{
return qla2x00_issue_iocb_timeout(vha, buffer, phys_addr, size,
MBX_TOV_SECONDS);
}
/*
* qla2x00_abort_command
* Abort command aborts a specified IOCB.
*
* Input:
* ha = adapter block pointer.
* sp = SB structure pointer.
*
* Returns:
* qla2x00 local function return status code.
*
* Context:
* Kernel context.
*/
int
qla2x00_abort_command(srb_t *sp)
{
unsigned long flags = 0;
int rval;
uint32_t handle = 0;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
fc_port_t *fcport = sp->fcport;
scsi_qla_host_t *vha = fcport->vha;
struct qla_hw_data *ha = vha->hw;
struct req_que *req = vha->req;
DEBUG11(printk("qla2x00_abort_command(%ld): entered.\n", vha->host_no));
spin_lock_irqsave(&ha->hardware_lock, flags);
for (handle = 1; handle < MAX_OUTSTANDING_COMMANDS; handle++) {
if (req->outstanding_cmds[handle] == sp)
break;
}
spin_unlock_irqrestore(&ha->hardware_lock, flags);
if (handle == MAX_OUTSTANDING_COMMANDS) {
/* command not found */
return QLA_FUNCTION_FAILED;
}
mcp->mb[0] = MBC_ABORT_COMMAND;
if (HAS_EXTENDED_IDS(ha))
mcp->mb[1] = fcport->loop_id;
else
mcp->mb[1] = fcport->loop_id << 8;
mcp->mb[2] = (uint16_t)handle;
mcp->mb[3] = (uint16_t)(handle >> 16);
mcp->mb[6] = (uint16_t)sp->cmd->device->lun;
mcp->out_mb = MBX_6|MBX_3|MBX_2|MBX_1|MBX_0;
mcp->in_mb = MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("qla2x00_abort_command(%ld): failed=%x.\n",
vha->host_no, rval));
} else {
DEBUG11(printk("qla2x00_abort_command(%ld): done.\n",
vha->host_no));
}
return rval;
}
int
qla2x00_abort_target(struct fc_port *fcport, unsigned int l, int tag)
{
int rval, rval2;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
scsi_qla_host_t *vha;
struct req_que *req;
struct rsp_que *rsp;
DEBUG11(printk("%s(%ld): entered.\n", __func__, fcport->vha->host_no));
l = l;
vha = fcport->vha;
req = vha->hw->req_q_map[tag];
rsp = vha->hw->rsp_q_map[tag];
mcp->mb[0] = MBC_ABORT_TARGET;
mcp->out_mb = MBX_9|MBX_2|MBX_1|MBX_0;
if (HAS_EXTENDED_IDS(vha->hw)) {
mcp->mb[1] = fcport->loop_id;
mcp->mb[10] = 0;
mcp->out_mb |= MBX_10;
} else {
mcp->mb[1] = fcport->loop_id << 8;
}
mcp->mb[2] = vha->hw->loop_reset_delay;
mcp->mb[9] = vha->vp_idx;
mcp->in_mb = MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x.\n", __func__,
vha->host_no, rval));
}
/* Issue marker IOCB. */
rval2 = qla2x00_marker(vha, req, rsp, fcport->loop_id, 0,
MK_SYNC_ID);
if (rval2 != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed to issue Marker IOCB "
"(%x).\n", __func__, vha->host_no, rval2));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
int
qla2x00_lun_reset(struct fc_port *fcport, unsigned int l, int tag)
{
int rval, rval2;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
scsi_qla_host_t *vha;
struct req_que *req;
struct rsp_que *rsp;
DEBUG11(printk("%s(%ld): entered.\n", __func__, fcport->vha->host_no));
vha = fcport->vha;
req = vha->hw->req_q_map[tag];
rsp = vha->hw->rsp_q_map[tag];
mcp->mb[0] = MBC_LUN_RESET;
mcp->out_mb = MBX_9|MBX_3|MBX_2|MBX_1|MBX_0;
if (HAS_EXTENDED_IDS(vha->hw))
mcp->mb[1] = fcport->loop_id;
else
mcp->mb[1] = fcport->loop_id << 8;
mcp->mb[2] = l;
mcp->mb[3] = 0;
mcp->mb[9] = vha->vp_idx;
mcp->in_mb = MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x.\n", __func__,
vha->host_no, rval));
}
/* Issue marker IOCB. */
rval2 = qla2x00_marker(vha, req, rsp, fcport->loop_id, l,
MK_SYNC_ID_LUN);
if (rval2 != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed to issue Marker IOCB "
"(%x).\n", __func__, vha->host_no, rval2));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
/*
* qla2x00_get_adapter_id
* Get adapter ID and topology.
*
* Input:
* ha = adapter block pointer.
* id = pointer for loop ID.
* al_pa = pointer for AL_PA.
* area = pointer for area.
* domain = pointer for domain.
* top = pointer for topology.
* TARGET_QUEUE_LOCK must be released.
* ADAPTER_STATE_LOCK must be released.
*
* Returns:
* qla2x00 local function return status code.
*
* Context:
* Kernel context.
*/
int
qla2x00_get_adapter_id(scsi_qla_host_t *vha, uint16_t *id, uint8_t *al_pa,
uint8_t *area, uint8_t *domain, uint16_t *top, uint16_t *sw_cap)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
DEBUG11(printk("qla2x00_get_adapter_id(%ld): entered.\n",
vha->host_no));
mcp->mb[0] = MBC_GET_ADAPTER_LOOP_ID;
mcp->mb[9] = vha->vp_idx;
mcp->out_mb = MBX_9|MBX_0;
mcp->in_mb = MBX_9|MBX_7|MBX_6|MBX_3|MBX_2|MBX_1|MBX_0;
if (IS_QLA81XX(vha->hw))
mcp->in_mb |= MBX_13|MBX_12|MBX_11|MBX_10;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (mcp->mb[0] == MBS_COMMAND_ERROR)
rval = QLA_COMMAND_ERROR;
else if (mcp->mb[0] == MBS_INVALID_COMMAND)
rval = QLA_INVALID_COMMAND;
/* Return data. */
*id = mcp->mb[1];
*al_pa = LSB(mcp->mb[2]);
*area = MSB(mcp->mb[2]);
*domain = LSB(mcp->mb[3]);
*top = mcp->mb[6];
*sw_cap = mcp->mb[7];
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3_11(printk("qla2x00_get_adapter_id(%ld): failed=%x.\n",
vha->host_no, rval));
} else {
DEBUG11(printk("qla2x00_get_adapter_id(%ld): done.\n",
vha->host_no));
if (IS_QLA81XX(vha->hw)) {
vha->fcoe_vlan_id = mcp->mb[9] & 0xfff;
vha->fcoe_fcf_idx = mcp->mb[10];
vha->fcoe_vn_port_mac[5] = mcp->mb[11] >> 8;
vha->fcoe_vn_port_mac[4] = mcp->mb[11] & 0xff;
vha->fcoe_vn_port_mac[3] = mcp->mb[12] >> 8;
vha->fcoe_vn_port_mac[2] = mcp->mb[12] & 0xff;
vha->fcoe_vn_port_mac[1] = mcp->mb[13] >> 8;
vha->fcoe_vn_port_mac[0] = mcp->mb[13] & 0xff;
}
}
return rval;
}
/*
* qla2x00_get_retry_cnt
* Get current firmware login retry count and delay.
*
* Input:
* ha = adapter block pointer.
* retry_cnt = pointer to login retry count.
* tov = pointer to login timeout value.
*
* Returns:
* qla2x00 local function return status code.
*
* Context:
* Kernel context.
*/
int
qla2x00_get_retry_cnt(scsi_qla_host_t *vha, uint8_t *retry_cnt, uint8_t *tov,
uint16_t *r_a_tov)
{
int rval;
uint16_t ratov;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
DEBUG11(printk("qla2x00_get_retry_cnt(%ld): entered.\n",
vha->host_no));
mcp->mb[0] = MBC_GET_RETRY_COUNT;
mcp->out_mb = MBX_0;
mcp->in_mb = MBX_3|MBX_2|MBX_1|MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3_11(printk("qla2x00_get_retry_cnt(%ld): failed = %x.\n",
vha->host_no, mcp->mb[0]));
} else {
/* Convert returned data and check our values. */
*r_a_tov = mcp->mb[3] / 2;
ratov = (mcp->mb[3]/2) / 10; /* mb[3] value is in 100ms */
if (mcp->mb[1] * ratov > (*retry_cnt) * (*tov)) {
/* Update to the larger values */
*retry_cnt = (uint8_t)mcp->mb[1];
*tov = ratov;
}
DEBUG11(printk("qla2x00_get_retry_cnt(%ld): done. mb3=%d "
"ratov=%d.\n", vha->host_no, mcp->mb[3], ratov));
}
return rval;
}
/*
* qla2x00_init_firmware
* Initialize adapter firmware.
*
* Input:
* ha = adapter block pointer.
* dptr = Initialization control block pointer.
* size = size of initialization control block.
* TARGET_QUEUE_LOCK must be released.
* ADAPTER_STATE_LOCK must be released.
*
* Returns:
* qla2x00 local function return status code.
*
* Context:
* Kernel context.
*/
int
qla2x00_init_firmware(scsi_qla_host_t *vha, uint16_t size)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
struct qla_hw_data *ha = vha->hw;
DEBUG11(printk("qla2x00_init_firmware(%ld): entered.\n",
vha->host_no));
if (ha->flags.npiv_supported)
mcp->mb[0] = MBC_MID_INITIALIZE_FIRMWARE;
else
mcp->mb[0] = MBC_INITIALIZE_FIRMWARE;
mcp->mb[1] = 0;
mcp->mb[2] = MSW(ha->init_cb_dma);
mcp->mb[3] = LSW(ha->init_cb_dma);
mcp->mb[6] = MSW(MSD(ha->init_cb_dma));
mcp->mb[7] = LSW(MSD(ha->init_cb_dma));
mcp->out_mb = MBX_7|MBX_6|MBX_3|MBX_2|MBX_1|MBX_0;
if (IS_QLA81XX(ha) && ha->ex_init_cb->ex_version) {
mcp->mb[1] = BIT_0;
mcp->mb[10] = MSW(ha->ex_init_cb_dma);
mcp->mb[11] = LSW(ha->ex_init_cb_dma);
mcp->mb[12] = MSW(MSD(ha->ex_init_cb_dma));
mcp->mb[13] = LSW(MSD(ha->ex_init_cb_dma));
mcp->mb[14] = sizeof(*ha->ex_init_cb);
mcp->out_mb |= MBX_14|MBX_13|MBX_12|MBX_11|MBX_10;
}
mcp->in_mb = MBX_0;
mcp->buf_size = size;
mcp->flags = MBX_DMA_OUT;
mcp->tov = MBX_TOV_SECONDS;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3_11(printk("qla2x00_init_firmware(%ld): failed=%x "
"mb0=%x.\n",
vha->host_no, rval, mcp->mb[0]));
} else {
/*EMPTY*/
DEBUG11(printk("qla2x00_init_firmware(%ld): done.\n",
vha->host_no));
}
return rval;
}
/*
* qla2x00_get_port_database
* Issue normal/enhanced get port database mailbox command
* and copy device name as necessary.
*
* Input:
* ha = adapter state pointer.
* dev = structure pointer.
* opt = enhanced cmd option byte.
*
* Returns:
* qla2x00 local function return status code.
*
* Context:
* Kernel context.
*/
int
qla2x00_get_port_database(scsi_qla_host_t *vha, fc_port_t *fcport, uint8_t opt)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
port_database_t *pd;
struct port_database_24xx *pd24;
dma_addr_t pd_dma;
struct qla_hw_data *ha = vha->hw;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
pd24 = NULL;
pd = dma_pool_alloc(ha->s_dma_pool, GFP_KERNEL, &pd_dma);
if (pd == NULL) {
DEBUG2_3(printk("%s(%ld): failed to allocate Port Database "
"structure.\n", __func__, vha->host_no));
return QLA_MEMORY_ALLOC_FAILED;
}
memset(pd, 0, max(PORT_DATABASE_SIZE, PORT_DATABASE_24XX_SIZE));
mcp->mb[0] = MBC_GET_PORT_DATABASE;
if (opt != 0 && !IS_FWI2_CAPABLE(ha))
mcp->mb[0] = MBC_ENHANCED_GET_PORT_DATABASE;
mcp->mb[2] = MSW(pd_dma);
mcp->mb[3] = LSW(pd_dma);
mcp->mb[6] = MSW(MSD(pd_dma));
mcp->mb[7] = LSW(MSD(pd_dma));
mcp->mb[9] = vha->vp_idx;
mcp->out_mb = MBX_9|MBX_7|MBX_6|MBX_3|MBX_2|MBX_0;
mcp->in_mb = MBX_0;
if (IS_FWI2_CAPABLE(ha)) {
mcp->mb[1] = fcport->loop_id;
mcp->mb[10] = opt;
mcp->out_mb |= MBX_10|MBX_1;
mcp->in_mb |= MBX_1;
} else if (HAS_EXTENDED_IDS(ha)) {
mcp->mb[1] = fcport->loop_id;
mcp->mb[10] = opt;
mcp->out_mb |= MBX_10|MBX_1;
} else {
mcp->mb[1] = fcport->loop_id << 8 | opt;
mcp->out_mb |= MBX_1;
}
mcp->buf_size = IS_FWI2_CAPABLE(ha) ?
PORT_DATABASE_24XX_SIZE : PORT_DATABASE_SIZE;
mcp->flags = MBX_DMA_IN;
mcp->tov = (ha->login_timeout * 2) + (ha->login_timeout / 2);
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS)
goto gpd_error_out;
if (IS_FWI2_CAPABLE(ha)) {
pd24 = (struct port_database_24xx *) pd;
/* Check for logged in state. */
if (pd24->current_login_state != PDS_PRLI_COMPLETE &&
pd24->last_login_state != PDS_PRLI_COMPLETE) {
DEBUG2(printk("%s(%ld): Unable to verify "
"login-state (%x/%x) for loop_id %x\n",
__func__, vha->host_no,
pd24->current_login_state,
pd24->last_login_state, fcport->loop_id));
rval = QLA_FUNCTION_FAILED;
goto gpd_error_out;
}
/* Names are little-endian. */
memcpy(fcport->node_name, pd24->node_name, WWN_SIZE);
memcpy(fcport->port_name, pd24->port_name, WWN_SIZE);
/* Get port_id of device. */
fcport->d_id.b.domain = pd24->port_id[0];
fcport->d_id.b.area = pd24->port_id[1];
fcport->d_id.b.al_pa = pd24->port_id[2];
fcport->d_id.b.rsvd_1 = 0;
/* If not target must be initiator or unknown type. */
if ((pd24->prli_svc_param_word_3[0] & BIT_4) == 0)
fcport->port_type = FCT_INITIATOR;
else
fcport->port_type = FCT_TARGET;
} else {
/* Check for logged in state. */
if (pd->master_state != PD_STATE_PORT_LOGGED_IN &&
pd->slave_state != PD_STATE_PORT_LOGGED_IN) {
rval = QLA_FUNCTION_FAILED;
goto gpd_error_out;
}
/* Names are little-endian. */
memcpy(fcport->node_name, pd->node_name, WWN_SIZE);
memcpy(fcport->port_name, pd->port_name, WWN_SIZE);
/* Get port_id of device. */
fcport->d_id.b.domain = pd->port_id[0];
fcport->d_id.b.area = pd->port_id[3];
fcport->d_id.b.al_pa = pd->port_id[2];
fcport->d_id.b.rsvd_1 = 0;
/* If not target must be initiator or unknown type. */
if ((pd->prli_svc_param_word_3[0] & BIT_4) == 0)
fcport->port_type = FCT_INITIATOR;
else
fcport->port_type = FCT_TARGET;
/* Passback COS information. */
fcport->supported_classes = (pd->options & BIT_4) ?
FC_COS_CLASS2: FC_COS_CLASS3;
}
gpd_error_out:
dma_pool_free(ha->s_dma_pool, pd, pd_dma);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x mb[0]=%x mb[1]=%x.\n",
__func__, vha->host_no, rval, mcp->mb[0], mcp->mb[1]));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
/*
* qla2x00_get_firmware_state
* Get adapter firmware state.
*
* Input:
* ha = adapter block pointer.
* dptr = pointer for firmware state.
* TARGET_QUEUE_LOCK must be released.
* ADAPTER_STATE_LOCK must be released.
*
* Returns:
* qla2x00 local function return status code.
*
* Context:
* Kernel context.
*/
int
qla2x00_get_firmware_state(scsi_qla_host_t *vha, uint16_t *states)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
DEBUG11(printk("qla2x00_get_firmware_state(%ld): entered.\n",
vha->host_no));
mcp->mb[0] = MBC_GET_FIRMWARE_STATE;
mcp->out_mb = MBX_0;
if (IS_FWI2_CAPABLE(vha->hw))
mcp->in_mb = MBX_5|MBX_4|MBX_3|MBX_2|MBX_1|MBX_0;
else
mcp->in_mb = MBX_1|MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
/* Return firmware states. */
states[0] = mcp->mb[1];
if (IS_FWI2_CAPABLE(vha->hw)) {
states[1] = mcp->mb[2];
states[2] = mcp->mb[3];
states[3] = mcp->mb[4];
states[4] = mcp->mb[5];
}
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3_11(printk("qla2x00_get_firmware_state(%ld): "
"failed=%x.\n", vha->host_no, rval));
} else {
/*EMPTY*/
DEBUG11(printk("qla2x00_get_firmware_state(%ld): done.\n",
vha->host_no));
}
return rval;
}
/*
* qla2x00_get_port_name
* Issue get port name mailbox command.
* Returned name is in big endian format.
*
* Input:
* ha = adapter block pointer.
* loop_id = loop ID of device.
* name = pointer for name.
* TARGET_QUEUE_LOCK must be released.
* ADAPTER_STATE_LOCK must be released.
*
* Returns:
* qla2x00 local function return status code.
*
* Context:
* Kernel context.
*/
int
qla2x00_get_port_name(scsi_qla_host_t *vha, uint16_t loop_id, uint8_t *name,
uint8_t opt)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
DEBUG11(printk("qla2x00_get_port_name(%ld): entered.\n",
vha->host_no));
mcp->mb[0] = MBC_GET_PORT_NAME;
mcp->mb[9] = vha->vp_idx;
mcp->out_mb = MBX_9|MBX_1|MBX_0;
if (HAS_EXTENDED_IDS(vha->hw)) {
mcp->mb[1] = loop_id;
mcp->mb[10] = opt;
mcp->out_mb |= MBX_10;
} else {
mcp->mb[1] = loop_id << 8 | opt;
}
mcp->in_mb = MBX_7|MBX_6|MBX_3|MBX_2|MBX_1|MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3_11(printk("qla2x00_get_port_name(%ld): failed=%x.\n",
vha->host_no, rval));
} else {
if (name != NULL) {
/* This function returns name in big endian. */
name[0] = MSB(mcp->mb[2]);
name[1] = LSB(mcp->mb[2]);
name[2] = MSB(mcp->mb[3]);
name[3] = LSB(mcp->mb[3]);
name[4] = MSB(mcp->mb[6]);
name[5] = LSB(mcp->mb[6]);
name[6] = MSB(mcp->mb[7]);
name[7] = LSB(mcp->mb[7]);
}
DEBUG11(printk("qla2x00_get_port_name(%ld): done.\n",
vha->host_no));
}
return rval;
}
/*
* qla2x00_lip_reset
* Issue LIP reset mailbox command.
*
* Input:
* ha = adapter block pointer.
* TARGET_QUEUE_LOCK must be released.
* ADAPTER_STATE_LOCK must be released.
*
* Returns:
* qla2x00 local function return status code.
*
* Context:
* Kernel context.
*/
int
qla2x00_lip_reset(scsi_qla_host_t *vha)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
if (IS_QLA81XX(vha->hw)) {
/* Logout across all FCFs. */
mcp->mb[0] = MBC_LIP_FULL_LOGIN;
mcp->mb[1] = BIT_1;
mcp->mb[2] = 0;
mcp->out_mb = MBX_2|MBX_1|MBX_0;
} else if (IS_FWI2_CAPABLE(vha->hw)) {
mcp->mb[0] = MBC_LIP_FULL_LOGIN;
mcp->mb[1] = BIT_6;
mcp->mb[2] = 0;
mcp->mb[3] = vha->hw->loop_reset_delay;
mcp->out_mb = MBX_3|MBX_2|MBX_1|MBX_0;
} else {
mcp->mb[0] = MBC_LIP_RESET;
mcp->out_mb = MBX_3|MBX_2|MBX_1|MBX_0;
if (HAS_EXTENDED_IDS(vha->hw)) {
mcp->mb[1] = 0x00ff;
mcp->mb[10] = 0;
mcp->out_mb |= MBX_10;
} else {
mcp->mb[1] = 0xff00;
}
mcp->mb[2] = vha->hw->loop_reset_delay;
mcp->mb[3] = 0;
}
mcp->in_mb = MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3_11(printk("%s(%ld): failed=%x.\n",
__func__, vha->host_no, rval));
} else {
/*EMPTY*/
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
/*
* qla2x00_send_sns
* Send SNS command.
*
* Input:
* ha = adapter block pointer.
* sns = pointer for command.
* cmd_size = command size.
* buf_size = response/command size.
* TARGET_QUEUE_LOCK must be released.
* ADAPTER_STATE_LOCK must be released.
*
* Returns:
* qla2x00 local function return status code.
*
* Context:
* Kernel context.
*/
int
qla2x00_send_sns(scsi_qla_host_t *vha, dma_addr_t sns_phys_address,
uint16_t cmd_size, size_t buf_size)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
DEBUG11(printk("qla2x00_send_sns(%ld): entered.\n",
vha->host_no));
DEBUG11(printk("qla2x00_send_sns: retry cnt=%d ratov=%d total "
"tov=%d.\n", vha->hw->retry_count, vha->hw->login_timeout,
mcp->tov));
mcp->mb[0] = MBC_SEND_SNS_COMMAND;
mcp->mb[1] = cmd_size;
mcp->mb[2] = MSW(sns_phys_address);
mcp->mb[3] = LSW(sns_phys_address);
mcp->mb[6] = MSW(MSD(sns_phys_address));
mcp->mb[7] = LSW(MSD(sns_phys_address));
mcp->out_mb = MBX_7|MBX_6|MBX_3|MBX_2|MBX_1|MBX_0;
mcp->in_mb = MBX_0|MBX_1;
mcp->buf_size = buf_size;
mcp->flags = MBX_DMA_OUT|MBX_DMA_IN;
mcp->tov = (vha->hw->login_timeout * 2) + (vha->hw->login_timeout / 2);
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG(printk("qla2x00_send_sns(%ld): failed=%x mb[0]=%x "
"mb[1]=%x.\n", vha->host_no, rval, mcp->mb[0], mcp->mb[1]));
DEBUG2_3_11(printk("qla2x00_send_sns(%ld): failed=%x mb[0]=%x "
"mb[1]=%x.\n", vha->host_no, rval, mcp->mb[0], mcp->mb[1]));
} else {
/*EMPTY*/
DEBUG11(printk("qla2x00_send_sns(%ld): done.\n", vha->host_no));
}
return rval;
}
int
qla24xx_login_fabric(scsi_qla_host_t *vha, uint16_t loop_id, uint8_t domain,
uint8_t area, uint8_t al_pa, uint16_t *mb, uint8_t opt)
{
int rval;
struct logio_entry_24xx *lg;
dma_addr_t lg_dma;
uint32_t iop[2];
struct qla_hw_data *ha = vha->hw;
struct req_que *req;
struct rsp_que *rsp;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
if (ha->flags.cpu_affinity_enabled)
req = ha->req_q_map[0];
else
req = vha->req;
rsp = req->rsp;
lg = dma_pool_alloc(ha->s_dma_pool, GFP_KERNEL, &lg_dma);
if (lg == NULL) {
DEBUG2_3(printk("%s(%ld): failed to allocate Login IOCB.\n",
__func__, vha->host_no));
return QLA_MEMORY_ALLOC_FAILED;
}
memset(lg, 0, sizeof(struct logio_entry_24xx));
lg->entry_type = LOGINOUT_PORT_IOCB_TYPE;
lg->entry_count = 1;
lg->handle = MAKE_HANDLE(req->id, lg->handle);
lg->nport_handle = cpu_to_le16(loop_id);
lg->control_flags = __constant_cpu_to_le16(LCF_COMMAND_PLOGI);
if (opt & BIT_0)
lg->control_flags |= __constant_cpu_to_le16(LCF_COND_PLOGI);
if (opt & BIT_1)
lg->control_flags |= __constant_cpu_to_le16(LCF_SKIP_PRLI);
lg->port_id[0] = al_pa;
lg->port_id[1] = area;
lg->port_id[2] = domain;
lg->vp_index = vha->vp_idx;
rval = qla2x00_issue_iocb(vha, lg, lg_dma, 0);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed to issue Login IOCB "
"(%x).\n", __func__, vha->host_no, rval));
} else if (lg->entry_status != 0) {
DEBUG2_3_11(printk("%s(%ld): failed to complete IOCB "
"-- error status (%x).\n", __func__, vha->host_no,
lg->entry_status));
rval = QLA_FUNCTION_FAILED;
} else if (lg->comp_status != __constant_cpu_to_le16(CS_COMPLETE)) {
iop[0] = le32_to_cpu(lg->io_parameter[0]);
iop[1] = le32_to_cpu(lg->io_parameter[1]);
DEBUG2_3_11(printk("%s(%ld): failed to complete IOCB "
"-- completion status (%x) ioparam=%x/%x.\n", __func__,
vha->host_no, le16_to_cpu(lg->comp_status), iop[0],
iop[1]));
switch (iop[0]) {
case LSC_SCODE_PORTID_USED:
mb[0] = MBS_PORT_ID_USED;
mb[1] = LSW(iop[1]);
break;
case LSC_SCODE_NPORT_USED:
mb[0] = MBS_LOOP_ID_USED;
break;
case LSC_SCODE_NOLINK:
case LSC_SCODE_NOIOCB:
case LSC_SCODE_NOXCB:
case LSC_SCODE_CMD_FAILED:
case LSC_SCODE_NOFABRIC:
case LSC_SCODE_FW_NOT_READY:
case LSC_SCODE_NOT_LOGGED_IN:
case LSC_SCODE_NOPCB:
case LSC_SCODE_ELS_REJECT:
case LSC_SCODE_CMD_PARAM_ERR:
case LSC_SCODE_NONPORT:
case LSC_SCODE_LOGGED_IN:
case LSC_SCODE_NOFLOGI_ACC:
default:
mb[0] = MBS_COMMAND_ERROR;
break;
}
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
iop[0] = le32_to_cpu(lg->io_parameter[0]);
mb[0] = MBS_COMMAND_COMPLETE;
mb[1] = 0;
if (iop[0] & BIT_4) {
if (iop[0] & BIT_8)
mb[1] |= BIT_1;
} else
mb[1] = BIT_0;
/* Passback COS information. */
mb[10] = 0;
if (lg->io_parameter[7] || lg->io_parameter[8])
mb[10] |= BIT_0; /* Class 2. */
if (lg->io_parameter[9] || lg->io_parameter[10])
mb[10] |= BIT_1; /* Class 3. */
}
dma_pool_free(ha->s_dma_pool, lg, lg_dma);
return rval;
}
/*
* qla2x00_login_fabric
* Issue login fabric port mailbox command.
*
* Input:
* ha = adapter block pointer.
* loop_id = device loop ID.
* domain = device domain.
* area = device area.
* al_pa = device AL_PA.
* status = pointer for return status.
* opt = command options.
* TARGET_QUEUE_LOCK must be released.
* ADAPTER_STATE_LOCK must be released.
*
* Returns:
* qla2x00 local function return status code.
*
* Context:
* Kernel context.
*/
int
qla2x00_login_fabric(scsi_qla_host_t *vha, uint16_t loop_id, uint8_t domain,
uint8_t area, uint8_t al_pa, uint16_t *mb, uint8_t opt)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
struct qla_hw_data *ha = vha->hw;
DEBUG11(printk("qla2x00_login_fabric(%ld): entered.\n", vha->host_no));
mcp->mb[0] = MBC_LOGIN_FABRIC_PORT;
mcp->out_mb = MBX_3|MBX_2|MBX_1|MBX_0;
if (HAS_EXTENDED_IDS(ha)) {
mcp->mb[1] = loop_id;
mcp->mb[10] = opt;
mcp->out_mb |= MBX_10;
} else {
mcp->mb[1] = (loop_id << 8) | opt;
}
mcp->mb[2] = domain;
mcp->mb[3] = area << 8 | al_pa;
mcp->in_mb = MBX_7|MBX_6|MBX_2|MBX_1|MBX_0;
mcp->tov = (ha->login_timeout * 2) + (ha->login_timeout / 2);
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
/* Return mailbox statuses. */
if (mb != NULL) {
mb[0] = mcp->mb[0];
mb[1] = mcp->mb[1];
mb[2] = mcp->mb[2];
mb[6] = mcp->mb[6];
mb[7] = mcp->mb[7];
/* COS retrieved from Get-Port-Database mailbox command. */
mb[10] = 0;
}
if (rval != QLA_SUCCESS) {
/* RLU tmp code: need to change main mailbox_command function to
* return ok even when the mailbox completion value is not
* SUCCESS. The caller needs to be responsible to interpret
* the return values of this mailbox command if we're not
* to change too much of the existing code.
*/
if (mcp->mb[0] == 0x4001 || mcp->mb[0] == 0x4002 ||
mcp->mb[0] == 0x4003 || mcp->mb[0] == 0x4005 ||
mcp->mb[0] == 0x4006)
rval = QLA_SUCCESS;
/*EMPTY*/
DEBUG2_3_11(printk("qla2x00_login_fabric(%ld): failed=%x "
"mb[0]=%x mb[1]=%x mb[2]=%x.\n", vha->host_no, rval,
mcp->mb[0], mcp->mb[1], mcp->mb[2]));
} else {
/*EMPTY*/
DEBUG11(printk("qla2x00_login_fabric(%ld): done.\n",
vha->host_no));
}
return rval;
}
/*
* qla2x00_login_local_device
* Issue login loop port mailbox command.
*
* Input:
* ha = adapter block pointer.
* loop_id = device loop ID.
* opt = command options.
*
* Returns:
* Return status code.
*
* Context:
* Kernel context.
*
*/
int
qla2x00_login_local_device(scsi_qla_host_t *vha, fc_port_t *fcport,
uint16_t *mb_ret, uint8_t opt)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
struct qla_hw_data *ha = vha->hw;
if (IS_FWI2_CAPABLE(ha))
return qla24xx_login_fabric(vha, fcport->loop_id,
fcport->d_id.b.domain, fcport->d_id.b.area,
fcport->d_id.b.al_pa, mb_ret, opt);
DEBUG3(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_LOGIN_LOOP_PORT;
if (HAS_EXTENDED_IDS(ha))
mcp->mb[1] = fcport->loop_id;
else
mcp->mb[1] = fcport->loop_id << 8;
mcp->mb[2] = opt;
mcp->out_mb = MBX_2|MBX_1|MBX_0;
mcp->in_mb = MBX_7|MBX_6|MBX_1|MBX_0;
mcp->tov = (ha->login_timeout * 2) + (ha->login_timeout / 2);
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
/* Return mailbox statuses. */
if (mb_ret != NULL) {
mb_ret[0] = mcp->mb[0];
mb_ret[1] = mcp->mb[1];
mb_ret[6] = mcp->mb[6];
mb_ret[7] = mcp->mb[7];
}
if (rval != QLA_SUCCESS) {
/* AV tmp code: need to change main mailbox_command function to
* return ok even when the mailbox completion value is not
* SUCCESS. The caller needs to be responsible to interpret
* the return values of this mailbox command if we're not
* to change too much of the existing code.
*/
if (mcp->mb[0] == 0x4005 || mcp->mb[0] == 0x4006)
rval = QLA_SUCCESS;
DEBUG(printk("%s(%ld): failed=%x mb[0]=%x mb[1]=%x "
"mb[6]=%x mb[7]=%x.\n", __func__, vha->host_no, rval,
mcp->mb[0], mcp->mb[1], mcp->mb[6], mcp->mb[7]));
DEBUG2_3(printk("%s(%ld): failed=%x mb[0]=%x mb[1]=%x "
"mb[6]=%x mb[7]=%x.\n", __func__, vha->host_no, rval,
mcp->mb[0], mcp->mb[1], mcp->mb[6], mcp->mb[7]));
} else {
/*EMPTY*/
DEBUG3(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return (rval);
}
int
qla24xx_fabric_logout(scsi_qla_host_t *vha, uint16_t loop_id, uint8_t domain,
uint8_t area, uint8_t al_pa)
{
int rval;
struct logio_entry_24xx *lg;
dma_addr_t lg_dma;
struct qla_hw_data *ha = vha->hw;
struct req_que *req;
struct rsp_que *rsp;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
lg = dma_pool_alloc(ha->s_dma_pool, GFP_KERNEL, &lg_dma);
if (lg == NULL) {
DEBUG2_3(printk("%s(%ld): failed to allocate Logout IOCB.\n",
__func__, vha->host_no));
return QLA_MEMORY_ALLOC_FAILED;
}
memset(lg, 0, sizeof(struct logio_entry_24xx));
if (ql2xmaxqueues > 1)
req = ha->req_q_map[0];
else
req = vha->req;
rsp = req->rsp;
lg->entry_type = LOGINOUT_PORT_IOCB_TYPE;
lg->entry_count = 1;
lg->handle = MAKE_HANDLE(req->id, lg->handle);
lg->nport_handle = cpu_to_le16(loop_id);
lg->control_flags =
__constant_cpu_to_le16(LCF_COMMAND_LOGO|LCF_IMPL_LOGO);
lg->port_id[0] = al_pa;
lg->port_id[1] = area;
lg->port_id[2] = domain;
lg->vp_index = vha->vp_idx;
rval = qla2x00_issue_iocb(vha, lg, lg_dma, 0);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed to issue Logout IOCB "
"(%x).\n", __func__, vha->host_no, rval));
} else if (lg->entry_status != 0) {
DEBUG2_3_11(printk("%s(%ld): failed to complete IOCB "
"-- error status (%x).\n", __func__, vha->host_no,
lg->entry_status));
rval = QLA_FUNCTION_FAILED;
} else if (lg->comp_status != __constant_cpu_to_le16(CS_COMPLETE)) {
DEBUG2_3_11(printk("%s(%ld %d): failed to complete IOCB "
"-- completion status (%x) ioparam=%x/%x.\n", __func__,
vha->host_no, vha->vp_idx, le16_to_cpu(lg->comp_status),
le32_to_cpu(lg->io_parameter[0]),
le32_to_cpu(lg->io_parameter[1])));
} else {
/*EMPTY*/
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
dma_pool_free(ha->s_dma_pool, lg, lg_dma);
return rval;
}
/*
* qla2x00_fabric_logout
* Issue logout fabric port mailbox command.
*
* Input:
* ha = adapter block pointer.
* loop_id = device loop ID.
* TARGET_QUEUE_LOCK must be released.
* ADAPTER_STATE_LOCK must be released.
*
* Returns:
* qla2x00 local function return status code.
*
* Context:
* Kernel context.
*/
int
qla2x00_fabric_logout(scsi_qla_host_t *vha, uint16_t loop_id, uint8_t domain,
uint8_t area, uint8_t al_pa)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
DEBUG11(printk("qla2x00_fabric_logout(%ld): entered.\n",
vha->host_no));
mcp->mb[0] = MBC_LOGOUT_FABRIC_PORT;
mcp->out_mb = MBX_1|MBX_0;
if (HAS_EXTENDED_IDS(vha->hw)) {
mcp->mb[1] = loop_id;
mcp->mb[10] = 0;
mcp->out_mb |= MBX_10;
} else {
mcp->mb[1] = loop_id << 8;
}
mcp->in_mb = MBX_1|MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3_11(printk("qla2x00_fabric_logout(%ld): failed=%x "
"mbx1=%x.\n", vha->host_no, rval, mcp->mb[1]));
} else {
/*EMPTY*/
DEBUG11(printk("qla2x00_fabric_logout(%ld): done.\n",
vha->host_no));
}
return rval;
}
/*
* qla2x00_full_login_lip
* Issue full login LIP mailbox command.
*
* Input:
* ha = adapter block pointer.
* TARGET_QUEUE_LOCK must be released.
* ADAPTER_STATE_LOCK must be released.
*
* Returns:
* qla2x00 local function return status code.
*
* Context:
* Kernel context.
*/
int
qla2x00_full_login_lip(scsi_qla_host_t *vha)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
DEBUG11(printk("qla2x00_full_login_lip(%ld): entered.\n",
vha->host_no));
mcp->mb[0] = MBC_LIP_FULL_LOGIN;
mcp->mb[1] = IS_FWI2_CAPABLE(vha->hw) ? BIT_3 : 0;
mcp->mb[2] = 0;
mcp->mb[3] = 0;
mcp->out_mb = MBX_3|MBX_2|MBX_1|MBX_0;
mcp->in_mb = MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3_11(printk("qla2x00_full_login_lip(%ld): failed=%x.\n",
vha->host_no, rval));
} else {
/*EMPTY*/
DEBUG11(printk("qla2x00_full_login_lip(%ld): done.\n",
vha->host_no));
}
return rval;
}
/*
* qla2x00_get_id_list
*
* Input:
* ha = adapter block pointer.
*
* Returns:
* qla2x00 local function return status code.
*
* Context:
* Kernel context.
*/
int
qla2x00_get_id_list(scsi_qla_host_t *vha, void *id_list, dma_addr_t id_list_dma,
uint16_t *entries)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
DEBUG11(printk("qla2x00_get_id_list(%ld): entered.\n",
vha->host_no));
if (id_list == NULL)
return QLA_FUNCTION_FAILED;
mcp->mb[0] = MBC_GET_ID_LIST;
mcp->out_mb = MBX_0;
if (IS_FWI2_CAPABLE(vha->hw)) {
mcp->mb[2] = MSW(id_list_dma);
mcp->mb[3] = LSW(id_list_dma);
mcp->mb[6] = MSW(MSD(id_list_dma));
mcp->mb[7] = LSW(MSD(id_list_dma));
mcp->mb[8] = 0;
mcp->mb[9] = vha->vp_idx;
mcp->out_mb |= MBX_9|MBX_8|MBX_7|MBX_6|MBX_3|MBX_2;
} else {
mcp->mb[1] = MSW(id_list_dma);
mcp->mb[2] = LSW(id_list_dma);
mcp->mb[3] = MSW(MSD(id_list_dma));
mcp->mb[6] = LSW(MSD(id_list_dma));
mcp->out_mb |= MBX_6|MBX_3|MBX_2|MBX_1;
}
mcp->in_mb = MBX_1|MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3_11(printk("qla2x00_get_id_list(%ld): failed=%x.\n",
vha->host_no, rval));
} else {
*entries = mcp->mb[1];
DEBUG11(printk("qla2x00_get_id_list(%ld): done.\n",
vha->host_no));
}
return rval;
}
/*
* qla2x00_get_resource_cnts
* Get current firmware resource counts.
*
* Input:
* ha = adapter block pointer.
*
* Returns:
* qla2x00 local function return status code.
*
* Context:
* Kernel context.
*/
int
qla2x00_get_resource_cnts(scsi_qla_host_t *vha, uint16_t *cur_xchg_cnt,
uint16_t *orig_xchg_cnt, uint16_t *cur_iocb_cnt,
uint16_t *orig_iocb_cnt, uint16_t *max_npiv_vports)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_GET_RESOURCE_COUNTS;
mcp->out_mb = MBX_0;
mcp->in_mb = MBX_11|MBX_10|MBX_7|MBX_6|MBX_3|MBX_2|MBX_1|MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3_11(printk("%s(%ld): failed = %x.\n", __func__,
vha->host_no, mcp->mb[0]));
} else {
DEBUG11(printk("%s(%ld): done. mb1=%x mb2=%x mb3=%x mb6=%x "
"mb7=%x mb10=%x mb11=%x.\n", __func__, vha->host_no,
mcp->mb[1], mcp->mb[2], mcp->mb[3], mcp->mb[6], mcp->mb[7],
mcp->mb[10], mcp->mb[11]));
if (cur_xchg_cnt)
*cur_xchg_cnt = mcp->mb[3];
if (orig_xchg_cnt)
*orig_xchg_cnt = mcp->mb[6];
if (cur_iocb_cnt)
*cur_iocb_cnt = mcp->mb[7];
if (orig_iocb_cnt)
*orig_iocb_cnt = mcp->mb[10];
if (vha->hw->flags.npiv_supported && max_npiv_vports)
*max_npiv_vports = mcp->mb[11];
}
return (rval);
}
#if defined(QL_DEBUG_LEVEL_3)
/*
* qla2x00_get_fcal_position_map
* Get FCAL (LILP) position map using mailbox command
*
* Input:
* ha = adapter state pointer.
* pos_map = buffer pointer (can be NULL).
*
* Returns:
* qla2x00 local function return status code.
*
* Context:
* Kernel context.
*/
int
qla2x00_get_fcal_position_map(scsi_qla_host_t *vha, char *pos_map)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
char *pmap;
dma_addr_t pmap_dma;
struct qla_hw_data *ha = vha->hw;
pmap = dma_pool_alloc(ha->s_dma_pool, GFP_KERNEL, &pmap_dma);
if (pmap == NULL) {
DEBUG2_3_11(printk("%s(%ld): **** Mem Alloc Failed ****",
__func__, vha->host_no));
return QLA_MEMORY_ALLOC_FAILED;
}
memset(pmap, 0, FCAL_MAP_SIZE);
mcp->mb[0] = MBC_GET_FC_AL_POSITION_MAP;
mcp->mb[2] = MSW(pmap_dma);
mcp->mb[3] = LSW(pmap_dma);
mcp->mb[6] = MSW(MSD(pmap_dma));
mcp->mb[7] = LSW(MSD(pmap_dma));
mcp->out_mb = MBX_7|MBX_6|MBX_3|MBX_2|MBX_0;
mcp->in_mb = MBX_1|MBX_0;
mcp->buf_size = FCAL_MAP_SIZE;
mcp->flags = MBX_DMA_IN;
mcp->tov = (ha->login_timeout * 2) + (ha->login_timeout / 2);
rval = qla2x00_mailbox_command(vha, mcp);
if (rval == QLA_SUCCESS) {
DEBUG11(printk("%s(%ld): (mb0=%x/mb1=%x) FC/AL Position Map "
"size (%x)\n", __func__, vha->host_no, mcp->mb[0],
mcp->mb[1], (unsigned)pmap[0]));
DEBUG11(qla2x00_dump_buffer(pmap, pmap[0] + 1));
if (pos_map)
memcpy(pos_map, pmap, FCAL_MAP_SIZE);
}
dma_pool_free(ha->s_dma_pool, pmap, pmap_dma);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x.\n", __func__,
vha->host_no, rval));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
#endif
/*
* qla2x00_get_link_status
*
* Input:
* ha = adapter block pointer.
* loop_id = device loop ID.
* ret_buf = pointer to link status return buffer.
*
* Returns:
* 0 = success.
* BIT_0 = mem alloc error.
* BIT_1 = mailbox error.
*/
int
qla2x00_get_link_status(scsi_qla_host_t *vha, uint16_t loop_id,
struct link_statistics *stats, dma_addr_t stats_dma)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
uint32_t *siter, *diter, dwords;
struct qla_hw_data *ha = vha->hw;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_GET_LINK_STATUS;
mcp->mb[2] = MSW(stats_dma);
mcp->mb[3] = LSW(stats_dma);
mcp->mb[6] = MSW(MSD(stats_dma));
mcp->mb[7] = LSW(MSD(stats_dma));
mcp->out_mb = MBX_7|MBX_6|MBX_3|MBX_2|MBX_0;
mcp->in_mb = MBX_0;
if (IS_FWI2_CAPABLE(ha)) {
mcp->mb[1] = loop_id;
mcp->mb[4] = 0;
mcp->mb[10] = 0;
mcp->out_mb |= MBX_10|MBX_4|MBX_1;
mcp->in_mb |= MBX_1;
} else if (HAS_EXTENDED_IDS(ha)) {
mcp->mb[1] = loop_id;
mcp->mb[10] = 0;
mcp->out_mb |= MBX_10|MBX_1;
} else {
mcp->mb[1] = loop_id << 8;
mcp->out_mb |= MBX_1;
}
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = IOCTL_CMD;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval == QLA_SUCCESS) {
if (mcp->mb[0] != MBS_COMMAND_COMPLETE) {
DEBUG2_3_11(printk("%s(%ld): cmd failed. mbx0=%x.\n",
__func__, vha->host_no, mcp->mb[0]));
rval = QLA_FUNCTION_FAILED;
} else {
/* Copy over data -- firmware data is LE. */
dwords = offsetof(struct link_statistics, unused1) / 4;
siter = diter = &stats->link_fail_cnt;
while (dwords--)
*diter++ = le32_to_cpu(*siter++);
}
} else {
/* Failed. */
DEBUG2_3_11(printk("%s(%ld): failed=%x.\n", __func__,
vha->host_no, rval));
}
return rval;
}
int
qla24xx_get_isp_stats(scsi_qla_host_t *vha, struct link_statistics *stats,
dma_addr_t stats_dma)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
uint32_t *siter, *diter, dwords;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_GET_LINK_PRIV_STATS;
mcp->mb[2] = MSW(stats_dma);
mcp->mb[3] = LSW(stats_dma);
mcp->mb[6] = MSW(MSD(stats_dma));
mcp->mb[7] = LSW(MSD(stats_dma));
mcp->mb[8] = sizeof(struct link_statistics) / 4;
mcp->mb[9] = vha->vp_idx;
mcp->mb[10] = 0;
mcp->out_mb = MBX_10|MBX_9|MBX_8|MBX_7|MBX_6|MBX_3|MBX_2|MBX_0;
mcp->in_mb = MBX_2|MBX_1|MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = IOCTL_CMD;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval == QLA_SUCCESS) {
if (mcp->mb[0] != MBS_COMMAND_COMPLETE) {
DEBUG2_3_11(printk("%s(%ld): cmd failed. mbx0=%x.\n",
__func__, vha->host_no, mcp->mb[0]));
rval = QLA_FUNCTION_FAILED;
} else {
/* Copy over data -- firmware data is LE. */
dwords = sizeof(struct link_statistics) / 4;
siter = diter = &stats->link_fail_cnt;
while (dwords--)
*diter++ = le32_to_cpu(*siter++);
}
} else {
/* Failed. */
DEBUG2_3_11(printk("%s(%ld): failed=%x.\n", __func__,
vha->host_no, rval));
}
return rval;
}
int
qla24xx_abort_command(srb_t *sp)
{
int rval;
unsigned long flags = 0;
struct abort_entry_24xx *abt;
dma_addr_t abt_dma;
uint32_t handle;
fc_port_t *fcport = sp->fcport;
struct scsi_qla_host *vha = fcport->vha;
struct qla_hw_data *ha = vha->hw;
struct req_que *req = vha->req;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
spin_lock_irqsave(&ha->hardware_lock, flags);
for (handle = 1; handle < MAX_OUTSTANDING_COMMANDS; handle++) {
if (req->outstanding_cmds[handle] == sp)
break;
}
spin_unlock_irqrestore(&ha->hardware_lock, flags);
if (handle == MAX_OUTSTANDING_COMMANDS) {
/* Command not found. */
return QLA_FUNCTION_FAILED;
}
abt = dma_pool_alloc(ha->s_dma_pool, GFP_KERNEL, &abt_dma);
if (abt == NULL) {
DEBUG2_3(printk("%s(%ld): failed to allocate Abort IOCB.\n",
__func__, vha->host_no));
return QLA_MEMORY_ALLOC_FAILED;
}
memset(abt, 0, sizeof(struct abort_entry_24xx));
abt->entry_type = ABORT_IOCB_TYPE;
abt->entry_count = 1;
abt->handle = MAKE_HANDLE(req->id, abt->handle);
abt->nport_handle = cpu_to_le16(fcport->loop_id);
abt->handle_to_abort = handle;
abt->port_id[0] = fcport->d_id.b.al_pa;
abt->port_id[1] = fcport->d_id.b.area;
abt->port_id[2] = fcport->d_id.b.domain;
abt->vp_index = fcport->vp_idx;
abt->req_que_no = cpu_to_le16(req->id);
rval = qla2x00_issue_iocb(vha, abt, abt_dma, 0);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed to issue IOCB (%x).\n",
__func__, vha->host_no, rval));
} else if (abt->entry_status != 0) {
DEBUG2_3_11(printk("%s(%ld): failed to complete IOCB "
"-- error status (%x).\n", __func__, vha->host_no,
abt->entry_status));
rval = QLA_FUNCTION_FAILED;
} else if (abt->nport_handle != __constant_cpu_to_le16(0)) {
DEBUG2_3_11(printk("%s(%ld): failed to complete IOCB "
"-- completion status (%x).\n", __func__, vha->host_no,
le16_to_cpu(abt->nport_handle)));
rval = QLA_FUNCTION_FAILED;
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
dma_pool_free(ha->s_dma_pool, abt, abt_dma);
return rval;
}
struct tsk_mgmt_cmd {
union {
struct tsk_mgmt_entry tsk;
struct sts_entry_24xx sts;
} p;
};
static int
__qla24xx_issue_tmf(char *name, uint32_t type, struct fc_port *fcport,
unsigned int l, int tag)
{
int rval, rval2;
struct tsk_mgmt_cmd *tsk;
dma_addr_t tsk_dma;
scsi_qla_host_t *vha;
struct qla_hw_data *ha;
struct req_que *req;
struct rsp_que *rsp;
DEBUG11(printk("%s(%ld): entered.\n", __func__, fcport->vha->host_no));
vha = fcport->vha;
ha = vha->hw;
req = vha->req;
if (ha->flags.cpu_affinity_enabled)
rsp = ha->rsp_q_map[tag + 1];
else
rsp = req->rsp;
tsk = dma_pool_alloc(ha->s_dma_pool, GFP_KERNEL, &tsk_dma);
if (tsk == NULL) {
DEBUG2_3(printk("%s(%ld): failed to allocate Task Management "
"IOCB.\n", __func__, vha->host_no));
return QLA_MEMORY_ALLOC_FAILED;
}
memset(tsk, 0, sizeof(struct tsk_mgmt_cmd));
tsk->p.tsk.entry_type = TSK_MGMT_IOCB_TYPE;
tsk->p.tsk.entry_count = 1;
tsk->p.tsk.handle = MAKE_HANDLE(req->id, tsk->p.tsk.handle);
tsk->p.tsk.nport_handle = cpu_to_le16(fcport->loop_id);
tsk->p.tsk.timeout = cpu_to_le16(ha->r_a_tov / 10 * 2);
tsk->p.tsk.control_flags = cpu_to_le32(type);
tsk->p.tsk.port_id[0] = fcport->d_id.b.al_pa;
tsk->p.tsk.port_id[1] = fcport->d_id.b.area;
tsk->p.tsk.port_id[2] = fcport->d_id.b.domain;
tsk->p.tsk.vp_index = fcport->vp_idx;
if (type == TCF_LUN_RESET) {
int_to_scsilun(l, &tsk->p.tsk.lun);
host_to_fcp_swap((uint8_t *)&tsk->p.tsk.lun,
sizeof(tsk->p.tsk.lun));
}
rval = qla2x00_issue_iocb(vha, tsk, tsk_dma, 0);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed to issue %s Reset IOCB "
"(%x).\n", __func__, vha->host_no, name, rval));
} else if (tsk->p.sts.entry_status != 0) {
DEBUG2_3_11(printk("%s(%ld): failed to complete IOCB "
"-- error status (%x).\n", __func__, vha->host_no,
tsk->p.sts.entry_status));
rval = QLA_FUNCTION_FAILED;
} else if (tsk->p.sts.comp_status !=
__constant_cpu_to_le16(CS_COMPLETE)) {
DEBUG2_3_11(printk("%s(%ld): failed to complete IOCB "
"-- completion status (%x).\n", __func__,
vha->host_no, le16_to_cpu(tsk->p.sts.comp_status)));
rval = QLA_FUNCTION_FAILED;
}
/* Issue marker IOCB. */
rval2 = qla2x00_marker(vha, req, rsp, fcport->loop_id, l,
type == TCF_LUN_RESET ? MK_SYNC_ID_LUN: MK_SYNC_ID);
if (rval2 != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed to issue Marker IOCB "
"(%x).\n", __func__, vha->host_no, rval2));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
dma_pool_free(ha->s_dma_pool, tsk, tsk_dma);
return rval;
}
int
qla24xx_abort_target(struct fc_port *fcport, unsigned int l, int tag)
{
return __qla24xx_issue_tmf("Target", TCF_TARGET_RESET, fcport, l, tag);
}
int
qla24xx_lun_reset(struct fc_port *fcport, unsigned int l, int tag)
{
return __qla24xx_issue_tmf("Lun", TCF_LUN_RESET, fcport, l, tag);
}
int
qla2x00_system_error(scsi_qla_host_t *vha)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
struct qla_hw_data *ha = vha->hw;
if (!IS_QLA23XX(ha) && !IS_FWI2_CAPABLE(ha))
return QLA_FUNCTION_FAILED;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_GEN_SYSTEM_ERROR;
mcp->out_mb = MBX_0;
mcp->in_mb = MBX_0;
mcp->tov = 5;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x.\n", __func__,
vha->host_no, rval));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
/**
* qla2x00_set_serdes_params() -
* @ha: HA context
*
* Returns
*/
int
qla2x00_set_serdes_params(scsi_qla_host_t *vha, uint16_t sw_em_1g,
uint16_t sw_em_2g, uint16_t sw_em_4g)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_SERDES_PARAMS;
mcp->mb[1] = BIT_0;
mcp->mb[2] = sw_em_1g | BIT_15;
mcp->mb[3] = sw_em_2g | BIT_15;
mcp->mb[4] = sw_em_4g | BIT_15;
mcp->out_mb = MBX_4|MBX_3|MBX_2|MBX_1|MBX_0;
mcp->in_mb = MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
/*EMPTY*/
DEBUG2_3_11(printk("%s(%ld): failed=%x (%x).\n", __func__,
vha->host_no, rval, mcp->mb[0]));
} else {
/*EMPTY*/
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
int
qla2x00_stop_firmware(scsi_qla_host_t *vha)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
if (!IS_FWI2_CAPABLE(vha->hw))
return QLA_FUNCTION_FAILED;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_STOP_FIRMWARE;
mcp->out_mb = MBX_0;
mcp->in_mb = MBX_0;
mcp->tov = 5;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x.\n", __func__,
vha->host_no, rval));
if (mcp->mb[0] == MBS_INVALID_COMMAND)
rval = QLA_INVALID_COMMAND;
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
int
qla2x00_enable_eft_trace(scsi_qla_host_t *vha, dma_addr_t eft_dma,
uint16_t buffers)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
if (!IS_FWI2_CAPABLE(vha->hw))
return QLA_FUNCTION_FAILED;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_TRACE_CONTROL;
mcp->mb[1] = TC_EFT_ENABLE;
mcp->mb[2] = LSW(eft_dma);
mcp->mb[3] = MSW(eft_dma);
mcp->mb[4] = LSW(MSD(eft_dma));
mcp->mb[5] = MSW(MSD(eft_dma));
mcp->mb[6] = buffers;
mcp->mb[7] = TC_AEN_DISABLE;
mcp->out_mb = MBX_7|MBX_6|MBX_5|MBX_4|MBX_3|MBX_2|MBX_1|MBX_0;
mcp->in_mb = MBX_1|MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x mb[0]=%x mb[1]=%x.\n",
__func__, vha->host_no, rval, mcp->mb[0], mcp->mb[1]));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
int
qla2x00_disable_eft_trace(scsi_qla_host_t *vha)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
if (!IS_FWI2_CAPABLE(vha->hw))
return QLA_FUNCTION_FAILED;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_TRACE_CONTROL;
mcp->mb[1] = TC_EFT_DISABLE;
mcp->out_mb = MBX_1|MBX_0;
mcp->in_mb = MBX_1|MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x mb[0]=%x mb[1]=%x.\n",
__func__, vha->host_no, rval, mcp->mb[0], mcp->mb[1]));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
int
qla2x00_enable_fce_trace(scsi_qla_host_t *vha, dma_addr_t fce_dma,
uint16_t buffers, uint16_t *mb, uint32_t *dwords)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
if (!IS_QLA25XX(vha->hw) && !IS_QLA81XX(vha->hw))
return QLA_FUNCTION_FAILED;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_TRACE_CONTROL;
mcp->mb[1] = TC_FCE_ENABLE;
mcp->mb[2] = LSW(fce_dma);
mcp->mb[3] = MSW(fce_dma);
mcp->mb[4] = LSW(MSD(fce_dma));
mcp->mb[5] = MSW(MSD(fce_dma));
mcp->mb[6] = buffers;
mcp->mb[7] = TC_AEN_DISABLE;
mcp->mb[8] = 0;
mcp->mb[9] = TC_FCE_DEFAULT_RX_SIZE;
mcp->mb[10] = TC_FCE_DEFAULT_TX_SIZE;
mcp->out_mb = MBX_10|MBX_9|MBX_8|MBX_7|MBX_6|MBX_5|MBX_4|MBX_3|MBX_2|
MBX_1|MBX_0;
mcp->in_mb = MBX_6|MBX_5|MBX_4|MBX_3|MBX_2|MBX_1|MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x mb[0]=%x mb[1]=%x.\n",
__func__, vha->host_no, rval, mcp->mb[0], mcp->mb[1]));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
if (mb)
memcpy(mb, mcp->mb, 8 * sizeof(*mb));
if (dwords)
*dwords = buffers;
}
return rval;
}
int
qla2x00_disable_fce_trace(scsi_qla_host_t *vha, uint64_t *wr, uint64_t *rd)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
if (!IS_FWI2_CAPABLE(vha->hw))
return QLA_FUNCTION_FAILED;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_TRACE_CONTROL;
mcp->mb[1] = TC_FCE_DISABLE;
mcp->mb[2] = TC_FCE_DISABLE_TRACE;
mcp->out_mb = MBX_2|MBX_1|MBX_0;
mcp->in_mb = MBX_9|MBX_8|MBX_7|MBX_6|MBX_5|MBX_4|MBX_3|MBX_2|
MBX_1|MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x mb[0]=%x mb[1]=%x.\n",
__func__, vha->host_no, rval, mcp->mb[0], mcp->mb[1]));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
if (wr)
*wr = (uint64_t) mcp->mb[5] << 48 |
(uint64_t) mcp->mb[4] << 32 |
(uint64_t) mcp->mb[3] << 16 |
(uint64_t) mcp->mb[2];
if (rd)
*rd = (uint64_t) mcp->mb[9] << 48 |
(uint64_t) mcp->mb[8] << 32 |
(uint64_t) mcp->mb[7] << 16 |
(uint64_t) mcp->mb[6];
}
return rval;
}
int
qla2x00_read_sfp(scsi_qla_host_t *vha, dma_addr_t sfp_dma, uint16_t addr,
uint16_t off, uint16_t count)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
if (!IS_FWI2_CAPABLE(vha->hw))
return QLA_FUNCTION_FAILED;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_READ_SFP;
mcp->mb[1] = addr;
mcp->mb[2] = MSW(sfp_dma);
mcp->mb[3] = LSW(sfp_dma);
mcp->mb[6] = MSW(MSD(sfp_dma));
mcp->mb[7] = LSW(MSD(sfp_dma));
mcp->mb[8] = count;
mcp->mb[9] = off;
mcp->mb[10] = 0;
mcp->out_mb = MBX_10|MBX_9|MBX_8|MBX_7|MBX_6|MBX_3|MBX_2|MBX_1|MBX_0;
mcp->in_mb = MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x (%x).\n", __func__,
vha->host_no, rval, mcp->mb[0]));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
int
qla2x00_set_idma_speed(scsi_qla_host_t *vha, uint16_t loop_id,
uint16_t port_speed, uint16_t *mb)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
if (!IS_IIDMA_CAPABLE(vha->hw))
return QLA_FUNCTION_FAILED;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_PORT_PARAMS;
mcp->mb[1] = loop_id;
mcp->mb[2] = BIT_0;
if (IS_QLA81XX(vha->hw))
mcp->mb[3] = port_speed & (BIT_5|BIT_4|BIT_3|BIT_2|BIT_1|BIT_0);
else
mcp->mb[3] = port_speed & (BIT_2|BIT_1|BIT_0);
mcp->mb[9] = vha->vp_idx;
mcp->out_mb = MBX_9|MBX_3|MBX_2|MBX_1|MBX_0;
mcp->in_mb = MBX_3|MBX_1|MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
/* Return mailbox statuses. */
if (mb != NULL) {
mb[0] = mcp->mb[0];
mb[1] = mcp->mb[1];
mb[3] = mcp->mb[3];
}
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x.\n", __func__,
vha->host_no, rval));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
void
qla24xx_report_id_acquisition(scsi_qla_host_t *vha,
struct vp_rpt_id_entry_24xx *rptid_entry)
{
uint8_t vp_idx;
uint16_t stat = le16_to_cpu(rptid_entry->vp_idx);
struct qla_hw_data *ha = vha->hw;
scsi_qla_host_t *vp;
scsi_qla_host_t *tvp;
if (rptid_entry->entry_status != 0)
return;
if (rptid_entry->format == 0) {
DEBUG15(printk("%s:format 0 : scsi(%ld) number of VPs setup %d,"
" number of VPs acquired %d\n", __func__, vha->host_no,
MSB(le16_to_cpu(rptid_entry->vp_count)),
LSB(le16_to_cpu(rptid_entry->vp_count))));
DEBUG15(printk("%s primary port id %02x%02x%02x\n", __func__,
rptid_entry->port_id[2], rptid_entry->port_id[1],
rptid_entry->port_id[0]));
} else if (rptid_entry->format == 1) {
vp_idx = LSB(stat);
DEBUG15(printk("%s:format 1: scsi(%ld): VP[%d] enabled "
"- status %d - "
"with port id %02x%02x%02x\n", __func__, vha->host_no,
vp_idx, MSB(stat),
rptid_entry->port_id[2], rptid_entry->port_id[1],
rptid_entry->port_id[0]));
if (vp_idx == 0)
return;
if (MSB(stat) == 1) {
DEBUG2(printk("scsi(%ld): Could not acquire ID for "
"VP[%d].\n", vha->host_no, vp_idx));
return;
}
list_for_each_entry_safe(vp, tvp, &ha->vp_list, list)
if (vp_idx == vp->vp_idx)
break;
if (!vp)
return;
vp->d_id.b.domain = rptid_entry->port_id[2];
vp->d_id.b.area = rptid_entry->port_id[1];
vp->d_id.b.al_pa = rptid_entry->port_id[0];
/*
* Cannot configure here as we are still sitting on the
* response queue. Handle it in dpc context.
*/
set_bit(VP_IDX_ACQUIRED, &vp->vp_flags);
set_bit(VP_DPC_NEEDED, &vha->dpc_flags);
qla2xxx_wake_dpc(vha);
}
}
/*
* qla24xx_modify_vp_config
* Change VP configuration for vha
*
* Input:
* vha = adapter block pointer.
*
* Returns:
* qla2xxx local function return status code.
*
* Context:
* Kernel context.
*/
int
qla24xx_modify_vp_config(scsi_qla_host_t *vha)
{
int rval;
struct vp_config_entry_24xx *vpmod;
dma_addr_t vpmod_dma;
struct qla_hw_data *ha = vha->hw;
struct scsi_qla_host *base_vha = pci_get_drvdata(ha->pdev);
/* This can be called by the parent */
vpmod = dma_pool_alloc(ha->s_dma_pool, GFP_KERNEL, &vpmod_dma);
if (!vpmod) {
DEBUG2_3(printk("%s(%ld): failed to allocate Modify VP "
"IOCB.\n", __func__, vha->host_no));
return QLA_MEMORY_ALLOC_FAILED;
}
memset(vpmod, 0, sizeof(struct vp_config_entry_24xx));
vpmod->entry_type = VP_CONFIG_IOCB_TYPE;
vpmod->entry_count = 1;
vpmod->command = VCT_COMMAND_MOD_ENABLE_VPS;
vpmod->vp_count = 1;
vpmod->vp_index1 = vha->vp_idx;
vpmod->options_idx1 = BIT_3|BIT_4|BIT_5;
memcpy(vpmod->node_name_idx1, vha->node_name, WWN_SIZE);
memcpy(vpmod->port_name_idx1, vha->port_name, WWN_SIZE);
vpmod->entry_count = 1;
rval = qla2x00_issue_iocb(base_vha, vpmod, vpmod_dma, 0);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed to issue VP config IOCB"
"(%x).\n", __func__, base_vha->host_no, rval));
} else if (vpmod->comp_status != 0) {
DEBUG2_3_11(printk("%s(%ld): failed to complete IOCB "
"-- error status (%x).\n", __func__, base_vha->host_no,
vpmod->comp_status));
rval = QLA_FUNCTION_FAILED;
} else if (vpmod->comp_status != __constant_cpu_to_le16(CS_COMPLETE)) {
DEBUG2_3_11(printk("%s(%ld): failed to complete IOCB "
"-- completion status (%x).\n", __func__, base_vha->host_no,
le16_to_cpu(vpmod->comp_status)));
rval = QLA_FUNCTION_FAILED;
} else {
/* EMPTY */
DEBUG11(printk("%s(%ld): done.\n", __func__,
base_vha->host_no));
fc_vport_set_state(vha->fc_vport, FC_VPORT_INITIALIZING);
}
dma_pool_free(ha->s_dma_pool, vpmod, vpmod_dma);
return rval;
}
/*
* qla24xx_control_vp
* Enable a virtual port for given host
*
* Input:
* ha = adapter block pointer.
* vhba = virtual adapter (unused)
* index = index number for enabled VP
*
* Returns:
* qla2xxx local function return status code.
*
* Context:
* Kernel context.
*/
int
qla24xx_control_vp(scsi_qla_host_t *vha, int cmd)
{
int rval;
int map, pos;
struct vp_ctrl_entry_24xx *vce;
dma_addr_t vce_dma;
struct qla_hw_data *ha = vha->hw;
int vp_index = vha->vp_idx;
struct scsi_qla_host *base_vha = pci_get_drvdata(ha->pdev);
DEBUG11(printk("%s(%ld): entered. Enabling index %d\n", __func__,
vha->host_no, vp_index));
if (vp_index == 0 || vp_index >= ha->max_npiv_vports)
return QLA_PARAMETER_ERROR;
vce = dma_pool_alloc(ha->s_dma_pool, GFP_KERNEL, &vce_dma);
if (!vce) {
DEBUG2_3(printk("%s(%ld): "
"failed to allocate VP Control IOCB.\n", __func__,
base_vha->host_no));
return QLA_MEMORY_ALLOC_FAILED;
}
memset(vce, 0, sizeof(struct vp_ctrl_entry_24xx));
vce->entry_type = VP_CTRL_IOCB_TYPE;
vce->entry_count = 1;
vce->command = cpu_to_le16(cmd);
vce->vp_count = __constant_cpu_to_le16(1);
/* index map in firmware starts with 1; decrement index
* this is ok as we never use index 0
*/
map = (vp_index - 1) / 8;
pos = (vp_index - 1) & 7;
mutex_lock(&ha->vport_lock);
vce->vp_idx_map[map] |= 1 << pos;
mutex_unlock(&ha->vport_lock);
rval = qla2x00_issue_iocb(base_vha, vce, vce_dma, 0);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed to issue VP control IOCB"
"(%x).\n", __func__, base_vha->host_no, rval));
printk("%s(%ld): failed to issue VP control IOCB"
"(%x).\n", __func__, base_vha->host_no, rval);
} else if (vce->entry_status != 0) {
DEBUG2_3_11(printk("%s(%ld): failed to complete IOCB "
"-- error status (%x).\n", __func__, base_vha->host_no,
vce->entry_status));
printk("%s(%ld): failed to complete IOCB "
"-- error status (%x).\n", __func__, base_vha->host_no,
vce->entry_status);
rval = QLA_FUNCTION_FAILED;
} else if (vce->comp_status != __constant_cpu_to_le16(CS_COMPLETE)) {
DEBUG2_3_11(printk("%s(%ld): failed to complete IOCB "
"-- completion status (%x).\n", __func__, base_vha->host_no,
le16_to_cpu(vce->comp_status)));
printk("%s(%ld): failed to complete IOCB "
"-- completion status (%x).\n", __func__, base_vha->host_no,
le16_to_cpu(vce->comp_status));
rval = QLA_FUNCTION_FAILED;
} else {
DEBUG2(printk("%s(%ld): done.\n", __func__, base_vha->host_no));
}
dma_pool_free(ha->s_dma_pool, vce, vce_dma);
return rval;
}
/*
* qla2x00_send_change_request
* Receive or disable RSCN request from fabric controller
*
* Input:
* ha = adapter block pointer
* format = registration format:
* 0 - Reserved
* 1 - Fabric detected registration
* 2 - N_port detected registration
* 3 - Full registration
* FF - clear registration
* vp_idx = Virtual port index
*
* Returns:
* qla2x00 local function return status code.
*
* Context:
* Kernel Context
*/
int
qla2x00_send_change_request(scsi_qla_host_t *vha, uint16_t format,
uint16_t vp_idx)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
/*
* This command is implicitly executed by firmware during login for the
* physical hosts
*/
if (vp_idx == 0)
return QLA_FUNCTION_FAILED;
mcp->mb[0] = MBC_SEND_CHANGE_REQUEST;
mcp->mb[1] = format;
mcp->mb[9] = vp_idx;
mcp->out_mb = MBX_9|MBX_1|MBX_0;
mcp->in_mb = MBX_0|MBX_1;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval == QLA_SUCCESS) {
if (mcp->mb[0] != MBS_COMMAND_COMPLETE) {
rval = BIT_1;
}
} else
rval = BIT_1;
return rval;
}
int
qla2x00_dump_ram(scsi_qla_host_t *vha, dma_addr_t req_dma, uint32_t addr,
uint32_t size)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
if (MSW(addr) || IS_FWI2_CAPABLE(vha->hw)) {
mcp->mb[0] = MBC_DUMP_RISC_RAM_EXTENDED;
mcp->mb[8] = MSW(addr);
mcp->out_mb = MBX_8|MBX_0;
} else {
mcp->mb[0] = MBC_DUMP_RISC_RAM;
mcp->out_mb = MBX_0;
}
mcp->mb[1] = LSW(addr);
mcp->mb[2] = MSW(req_dma);
mcp->mb[3] = LSW(req_dma);
mcp->mb[6] = MSW(MSD(req_dma));
mcp->mb[7] = LSW(MSD(req_dma));
mcp->out_mb |= MBX_7|MBX_6|MBX_3|MBX_2|MBX_1;
if (IS_FWI2_CAPABLE(vha->hw)) {
mcp->mb[4] = MSW(size);
mcp->mb[5] = LSW(size);
mcp->out_mb |= MBX_5|MBX_4;
} else {
mcp->mb[4] = LSW(size);
mcp->out_mb |= MBX_4;
}
mcp->in_mb = MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x mb[0]=%x.\n", __func__,
vha->host_no, rval, mcp->mb[0]));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
/* 84XX Support **************************************************************/
struct cs84xx_mgmt_cmd {
union {
struct verify_chip_entry_84xx req;
struct verify_chip_rsp_84xx rsp;
} p;
};
int
qla84xx_verify_chip(struct scsi_qla_host *vha, uint16_t *status)
{
int rval, retry;
struct cs84xx_mgmt_cmd *mn;
dma_addr_t mn_dma;
uint16_t options;
unsigned long flags;
struct qla_hw_data *ha = vha->hw;
DEBUG16(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mn = dma_pool_alloc(ha->s_dma_pool, GFP_KERNEL, &mn_dma);
if (mn == NULL) {
DEBUG2_3(printk("%s(%ld): failed to allocate Verify ISP84XX "
"IOCB.\n", __func__, vha->host_no));
return QLA_MEMORY_ALLOC_FAILED;
}
/* Force Update? */
options = ha->cs84xx->fw_update ? VCO_FORCE_UPDATE : 0;
/* Diagnostic firmware? */
/* options |= MENLO_DIAG_FW; */
/* We update the firmware with only one data sequence. */
options |= VCO_END_OF_DATA;
do {
retry = 0;
memset(mn, 0, sizeof(*mn));
mn->p.req.entry_type = VERIFY_CHIP_IOCB_TYPE;
mn->p.req.entry_count = 1;
mn->p.req.options = cpu_to_le16(options);
DEBUG16(printk("%s(%ld): Dump of Verify Request.\n", __func__,
vha->host_no));
DEBUG16(qla2x00_dump_buffer((uint8_t *)mn,
sizeof(*mn)));
rval = qla2x00_issue_iocb_timeout(vha, mn, mn_dma, 0, 120);
if (rval != QLA_SUCCESS) {
DEBUG2_16(printk("%s(%ld): failed to issue Verify "
"IOCB (%x).\n", __func__, vha->host_no, rval));
goto verify_done;
}
DEBUG16(printk("%s(%ld): Dump of Verify Response.\n", __func__,
vha->host_no));
DEBUG16(qla2x00_dump_buffer((uint8_t *)mn,
sizeof(*mn)));
status[0] = le16_to_cpu(mn->p.rsp.comp_status);
status[1] = status[0] == CS_VCS_CHIP_FAILURE ?
le16_to_cpu(mn->p.rsp.failure_code) : 0;
DEBUG2_16(printk("%s(%ld): cs=%x fc=%x\n", __func__,
vha->host_no, status[0], status[1]));
if (status[0] != CS_COMPLETE) {
rval = QLA_FUNCTION_FAILED;
if (!(options & VCO_DONT_UPDATE_FW)) {
DEBUG2_16(printk("%s(%ld): Firmware update "
"failed. Retrying without update "
"firmware.\n", __func__, vha->host_no));
options |= VCO_DONT_UPDATE_FW;
options &= ~VCO_FORCE_UPDATE;
retry = 1;
}
} else {
DEBUG2_16(printk("%s(%ld): firmware updated to %x.\n",
__func__, vha->host_no,
le32_to_cpu(mn->p.rsp.fw_ver)));
/* NOTE: we only update OP firmware. */
spin_lock_irqsave(&ha->cs84xx->access_lock, flags);
ha->cs84xx->op_fw_version =
le32_to_cpu(mn->p.rsp.fw_ver);
spin_unlock_irqrestore(&ha->cs84xx->access_lock,
flags);
}
} while (retry);
verify_done:
dma_pool_free(ha->s_dma_pool, mn, mn_dma);
if (rval != QLA_SUCCESS) {
DEBUG2_16(printk("%s(%ld): failed=%x.\n", __func__,
vha->host_no, rval));
} else {
DEBUG16(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
int
qla25xx_init_req_que(struct scsi_qla_host *vha, struct req_que *req)
{
int rval;
unsigned long flags;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
struct device_reg_25xxmq __iomem *reg;
struct qla_hw_data *ha = vha->hw;
mcp->mb[0] = MBC_INITIALIZE_MULTIQ;
mcp->mb[1] = req->options;
mcp->mb[2] = MSW(LSD(req->dma));
mcp->mb[3] = LSW(LSD(req->dma));
mcp->mb[6] = MSW(MSD(req->dma));
mcp->mb[7] = LSW(MSD(req->dma));
mcp->mb[5] = req->length;
if (req->rsp)
mcp->mb[10] = req->rsp->id;
mcp->mb[12] = req->qos;
mcp->mb[11] = req->vp_idx;
mcp->mb[13] = req->rid;
reg = (struct device_reg_25xxmq *)((void *)(ha->mqiobase) +
QLA_QUE_PAGE * req->id);
mcp->mb[4] = req->id;
/* que in ptr index */
mcp->mb[8] = 0;
/* que out ptr index */
mcp->mb[9] = 0;
mcp->out_mb = MBX_14|MBX_13|MBX_12|MBX_11|MBX_10|MBX_9|MBX_8|MBX_7|
MBX_6|MBX_5|MBX_4|MBX_3|MBX_2|MBX_1|MBX_0;
mcp->in_mb = MBX_0;
mcp->flags = MBX_DMA_OUT;
mcp->tov = 60;
spin_lock_irqsave(&ha->hardware_lock, flags);
if (!(req->options & BIT_0)) {
WRT_REG_DWORD(®->req_q_in, 0);
WRT_REG_DWORD(®->req_q_out, 0);
}
req->req_q_in = ®->req_q_in;
req->req_q_out = ®->req_q_out;
spin_unlock_irqrestore(&ha->hardware_lock, flags);
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS)
DEBUG2_3_11(printk(KERN_WARNING "%s(%ld): failed=%x mb0=%x.\n",
__func__, vha->host_no, rval, mcp->mb[0]));
return rval;
}
int
qla25xx_init_rsp_que(struct scsi_qla_host *vha, struct rsp_que *rsp)
{
int rval;
unsigned long flags;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
struct device_reg_25xxmq __iomem *reg;
struct qla_hw_data *ha = vha->hw;
mcp->mb[0] = MBC_INITIALIZE_MULTIQ;
mcp->mb[1] = rsp->options;
mcp->mb[2] = MSW(LSD(rsp->dma));
mcp->mb[3] = LSW(LSD(rsp->dma));
mcp->mb[6] = MSW(MSD(rsp->dma));
mcp->mb[7] = LSW(MSD(rsp->dma));
mcp->mb[5] = rsp->length;
mcp->mb[14] = rsp->msix->entry;
mcp->mb[13] = rsp->rid;
reg = (struct device_reg_25xxmq *)((void *)(ha->mqiobase) +
QLA_QUE_PAGE * rsp->id);
mcp->mb[4] = rsp->id;
/* que in ptr index */
mcp->mb[8] = 0;
/* que out ptr index */
mcp->mb[9] = 0;
mcp->out_mb = MBX_14|MBX_13|MBX_9|MBX_8|MBX_7
|MBX_6|MBX_5|MBX_4|MBX_3|MBX_2|MBX_1|MBX_0;
mcp->in_mb = MBX_0;
mcp->flags = MBX_DMA_OUT;
mcp->tov = 60;
spin_lock_irqsave(&ha->hardware_lock, flags);
if (!(rsp->options & BIT_0)) {
WRT_REG_DWORD(®->rsp_q_out, 0);
WRT_REG_DWORD(®->rsp_q_in, 0);
}
spin_unlock_irqrestore(&ha->hardware_lock, flags);
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS)
DEBUG2_3_11(printk(KERN_WARNING "%s(%ld): failed=%x "
"mb0=%x.\n", __func__,
vha->host_no, rval, mcp->mb[0]));
return rval;
}
int
qla81xx_idc_ack(scsi_qla_host_t *vha, uint16_t *mb)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_IDC_ACK;
memcpy(&mcp->mb[1], mb, QLA_IDC_ACK_REGS * sizeof(uint16_t));
mcp->out_mb = MBX_7|MBX_6|MBX_5|MBX_4|MBX_3|MBX_2|MBX_1|MBX_0;
mcp->in_mb = MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x (%x).\n", __func__,
vha->host_no, rval, mcp->mb[0]));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
int
qla81xx_fac_get_sector_size(scsi_qla_host_t *vha, uint32_t *sector_size)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
if (!IS_QLA81XX(vha->hw))
return QLA_FUNCTION_FAILED;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_FLASH_ACCESS_CTRL;
mcp->mb[1] = FAC_OPT_CMD_GET_SECTOR_SIZE;
mcp->out_mb = MBX_1|MBX_0;
mcp->in_mb = MBX_1|MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x mb[0]=%x mb[1]=%x.\n",
__func__, vha->host_no, rval, mcp->mb[0], mcp->mb[1]));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
*sector_size = mcp->mb[1];
}
return rval;
}
int
qla81xx_fac_do_write_enable(scsi_qla_host_t *vha, int enable)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
if (!IS_QLA81XX(vha->hw))
return QLA_FUNCTION_FAILED;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_FLASH_ACCESS_CTRL;
mcp->mb[1] = enable ? FAC_OPT_CMD_WRITE_ENABLE :
FAC_OPT_CMD_WRITE_PROTECT;
mcp->out_mb = MBX_1|MBX_0;
mcp->in_mb = MBX_1|MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x mb[0]=%x mb[1]=%x.\n",
__func__, vha->host_no, rval, mcp->mb[0], mcp->mb[1]));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
int
qla81xx_fac_erase_sector(scsi_qla_host_t *vha, uint32_t start, uint32_t finish)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
if (!IS_QLA81XX(vha->hw))
return QLA_FUNCTION_FAILED;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_FLASH_ACCESS_CTRL;
mcp->mb[1] = FAC_OPT_CMD_ERASE_SECTOR;
mcp->mb[2] = LSW(start);
mcp->mb[3] = MSW(start);
mcp->mb[4] = LSW(finish);
mcp->mb[5] = MSW(finish);
mcp->out_mb = MBX_5|MBX_4|MBX_3|MBX_2|MBX_1|MBX_0;
mcp->in_mb = MBX_2|MBX_1|MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x mb[0]=%x mb[1]=%x "
"mb[2]=%x.\n", __func__, vha->host_no, rval, mcp->mb[0],
mcp->mb[1], mcp->mb[2]));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
int
qla81xx_restart_mpi_firmware(scsi_qla_host_t *vha)
{
int rval = 0;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_RESTART_MPI_FW;
mcp->out_mb = MBX_0;
mcp->in_mb = MBX_0|MBX_1;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x mb[0]=0x%x mb[1]=0x%x.\n",
__func__, vha->host_no, rval, mcp->mb[0], mcp->mb[1]));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
int
qla2x00_read_edc(scsi_qla_host_t *vha, uint16_t dev, uint16_t adr,
dma_addr_t sfp_dma, uint8_t *sfp, uint16_t len, uint16_t opt)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_READ_SFP;
mcp->mb[1] = dev;
mcp->mb[2] = MSW(sfp_dma);
mcp->mb[3] = LSW(sfp_dma);
mcp->mb[6] = MSW(MSD(sfp_dma));
mcp->mb[7] = LSW(MSD(sfp_dma));
mcp->mb[8] = len;
mcp->mb[9] = adr;
mcp->mb[10] = opt;
mcp->out_mb = MBX_10|MBX_9|MBX_8|MBX_7|MBX_6|MBX_3|MBX_2|MBX_1|MBX_0;
mcp->in_mb = MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (opt & BIT_0)
if (sfp)
*sfp = mcp->mb[8];
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x (%x).\n", __func__,
vha->host_no, rval, mcp->mb[0]));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
int
qla2x00_write_edc(scsi_qla_host_t *vha, uint16_t dev, uint16_t adr,
dma_addr_t sfp_dma, uint8_t *sfp, uint16_t len, uint16_t opt)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
if (opt & BIT_0)
if (sfp)
len = *sfp;
mcp->mb[0] = MBC_WRITE_SFP;
mcp->mb[1] = dev;
mcp->mb[2] = MSW(sfp_dma);
mcp->mb[3] = LSW(sfp_dma);
mcp->mb[6] = MSW(MSD(sfp_dma));
mcp->mb[7] = LSW(MSD(sfp_dma));
mcp->mb[8] = len;
mcp->mb[9] = adr;
mcp->mb[10] = opt;
mcp->out_mb = MBX_10|MBX_9|MBX_8|MBX_7|MBX_6|MBX_3|MBX_2|MBX_1|MBX_0;
mcp->in_mb = MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x (%x).\n", __func__,
vha->host_no, rval, mcp->mb[0]));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
int
qla2x00_get_xgmac_stats(scsi_qla_host_t *vha, dma_addr_t stats_dma,
uint16_t size_in_bytes, uint16_t *actual_size)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
if (!IS_QLA81XX(vha->hw))
return QLA_FUNCTION_FAILED;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_GET_XGMAC_STATS;
mcp->mb[2] = MSW(stats_dma);
mcp->mb[3] = LSW(stats_dma);
mcp->mb[6] = MSW(MSD(stats_dma));
mcp->mb[7] = LSW(MSD(stats_dma));
mcp->mb[8] = size_in_bytes >> 2;
mcp->out_mb = MBX_8|MBX_7|MBX_6|MBX_3|MBX_2|MBX_0;
mcp->in_mb = MBX_2|MBX_1|MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x mb[0]=0x%x "
"mb[1]=0x%x mb[2]=0x%x.\n", __func__, vha->host_no, rval,
mcp->mb[0], mcp->mb[1], mcp->mb[2]));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
*actual_size = mcp->mb[2] << 2;
}
return rval;
}
int
qla2x00_get_dcbx_params(scsi_qla_host_t *vha, dma_addr_t tlv_dma,
uint16_t size)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
if (!IS_QLA81XX(vha->hw))
return QLA_FUNCTION_FAILED;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_GET_DCBX_PARAMS;
mcp->mb[1] = 0;
mcp->mb[2] = MSW(tlv_dma);
mcp->mb[3] = LSW(tlv_dma);
mcp->mb[6] = MSW(MSD(tlv_dma));
mcp->mb[7] = LSW(MSD(tlv_dma));
mcp->mb[8] = size;
mcp->out_mb = MBX_8|MBX_7|MBX_6|MBX_3|MBX_2|MBX_1|MBX_0;
mcp->in_mb = MBX_2|MBX_1|MBX_0;
mcp->tov = MBX_TOV_SECONDS;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x mb[0]=0x%x "
"mb[1]=0x%x mb[2]=0x%x.\n", __func__, vha->host_no, rval,
mcp->mb[0], mcp->mb[1], mcp->mb[2]));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
int
qla2x00_read_ram_word(scsi_qla_host_t *vha, uint32_t risc_addr, uint32_t *data)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
if (!IS_FWI2_CAPABLE(vha->hw))
return QLA_FUNCTION_FAILED;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_READ_RAM_EXTENDED;
mcp->mb[1] = LSW(risc_addr);
mcp->mb[8] = MSW(risc_addr);
mcp->out_mb = MBX_8|MBX_1|MBX_0;
mcp->in_mb = MBX_3|MBX_2|MBX_0;
mcp->tov = 30;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x mb[0]=%x.\n", __func__,
vha->host_no, rval, mcp->mb[0]));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
*data = mcp->mb[3] << 16 | mcp->mb[2];
}
return rval;
}
int
qla2x00_write_ram_word(scsi_qla_host_t *vha, uint32_t risc_addr, uint32_t data)
{
int rval;
mbx_cmd_t mc;
mbx_cmd_t *mcp = &mc;
if (!IS_FWI2_CAPABLE(vha->hw))
return QLA_FUNCTION_FAILED;
DEBUG11(printk("%s(%ld): entered.\n", __func__, vha->host_no));
mcp->mb[0] = MBC_WRITE_RAM_WORD_EXTENDED;
mcp->mb[1] = LSW(risc_addr);
mcp->mb[2] = LSW(data);
mcp->mb[3] = MSW(data);
mcp->mb[8] = MSW(risc_addr);
mcp->out_mb = MBX_8|MBX_3|MBX_2|MBX_1|MBX_0;
mcp->in_mb = MBX_0;
mcp->tov = 30;
mcp->flags = 0;
rval = qla2x00_mailbox_command(vha, mcp);
if (rval != QLA_SUCCESS) {
DEBUG2_3_11(printk("%s(%ld): failed=%x mb[0]=%x.\n", __func__,
vha->host_no, rval, mcp->mb[0]));
} else {
DEBUG11(printk("%s(%ld): done.\n", __func__, vha->host_no));
}
return rval;
}
| gpl-2.0 |
fergy/iPhone_kernel_26 | drivers/spi/omap2_mcspi.c | 465 | 30867 | /*
* OMAP2 McSPI controller driver
*
* Copyright (C) 2005, 2006 Nokia Corporation
* Author: Samuel Ortiz <samuel.ortiz@nokia.com> and
* Juha Yrjölä <juha.yrjola@nokia.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include <linux/platform_device.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/spi/spi.h>
#include <mach/dma.h>
#include <mach/clock.h>
#define OMAP2_MCSPI_MAX_FREQ 48000000
/* OMAP2 has 3 SPI controllers, while OMAP3 has 4 */
#define OMAP2_MCSPI_MAX_CTRL 4
#define OMAP2_MCSPI_REVISION 0x00
#define OMAP2_MCSPI_SYSCONFIG 0x10
#define OMAP2_MCSPI_SYSSTATUS 0x14
#define OMAP2_MCSPI_IRQSTATUS 0x18
#define OMAP2_MCSPI_IRQENABLE 0x1c
#define OMAP2_MCSPI_WAKEUPENABLE 0x20
#define OMAP2_MCSPI_SYST 0x24
#define OMAP2_MCSPI_MODULCTRL 0x28
/* per-channel banks, 0x14 bytes each, first is: */
#define OMAP2_MCSPI_CHCONF0 0x2c
#define OMAP2_MCSPI_CHSTAT0 0x30
#define OMAP2_MCSPI_CHCTRL0 0x34
#define OMAP2_MCSPI_TX0 0x38
#define OMAP2_MCSPI_RX0 0x3c
/* per-register bitmasks: */
#define OMAP2_MCSPI_SYSCONFIG_SMARTIDLE BIT(4)
#define OMAP2_MCSPI_SYSCONFIG_ENAWAKEUP BIT(2)
#define OMAP2_MCSPI_SYSCONFIG_AUTOIDLE BIT(0)
#define OMAP2_MCSPI_SYSCONFIG_SOFTRESET BIT(1)
#define OMAP2_MCSPI_SYSSTATUS_RESETDONE BIT(0)
#define OMAP2_MCSPI_MODULCTRL_SINGLE BIT(0)
#define OMAP2_MCSPI_MODULCTRL_MS BIT(2)
#define OMAP2_MCSPI_MODULCTRL_STEST BIT(3)
#define OMAP2_MCSPI_CHCONF_PHA BIT(0)
#define OMAP2_MCSPI_CHCONF_POL BIT(1)
#define OMAP2_MCSPI_CHCONF_CLKD_MASK (0x0f << 2)
#define OMAP2_MCSPI_CHCONF_EPOL BIT(6)
#define OMAP2_MCSPI_CHCONF_WL_MASK (0x1f << 7)
#define OMAP2_MCSPI_CHCONF_TRM_RX_ONLY BIT(12)
#define OMAP2_MCSPI_CHCONF_TRM_TX_ONLY BIT(13)
#define OMAP2_MCSPI_CHCONF_TRM_MASK (0x03 << 12)
#define OMAP2_MCSPI_CHCONF_DMAW BIT(14)
#define OMAP2_MCSPI_CHCONF_DMAR BIT(15)
#define OMAP2_MCSPI_CHCONF_DPE0 BIT(16)
#define OMAP2_MCSPI_CHCONF_DPE1 BIT(17)
#define OMAP2_MCSPI_CHCONF_IS BIT(18)
#define OMAP2_MCSPI_CHCONF_TURBO BIT(19)
#define OMAP2_MCSPI_CHCONF_FORCE BIT(20)
#define OMAP2_MCSPI_CHSTAT_RXS BIT(0)
#define OMAP2_MCSPI_CHSTAT_TXS BIT(1)
#define OMAP2_MCSPI_CHSTAT_EOT BIT(2)
#define OMAP2_MCSPI_CHCTRL_EN BIT(0)
#define OMAP2_MCSPI_WAKEUPENABLE_WKEN BIT(0)
/* We have 2 DMA channels per CS, one for RX and one for TX */
struct omap2_mcspi_dma {
int dma_tx_channel;
int dma_rx_channel;
int dma_tx_sync_dev;
int dma_rx_sync_dev;
struct completion dma_tx_completion;
struct completion dma_rx_completion;
};
/* use PIO for small transfers, avoiding DMA setup/teardown overhead and
* cache operations; better heuristics consider wordsize and bitrate.
*/
#define DMA_MIN_BYTES 8
struct omap2_mcspi {
struct work_struct work;
/* lock protects queue and registers */
spinlock_t lock;
struct list_head msg_queue;
struct spi_master *master;
struct clk *ick;
struct clk *fck;
/* Virtual base address of the controller */
void __iomem *base;
unsigned long phys;
/* SPI1 has 4 channels, while SPI2 has 2 */
struct omap2_mcspi_dma *dma_channels;
};
struct omap2_mcspi_cs {
void __iomem *base;
unsigned long phys;
int word_len;
struct list_head node;
/* Context save and restore shadow register */
u32 chconf0;
};
/* used for context save and restore, structure members to be updated whenever
* corresponding registers are modified.
*/
struct omap2_mcspi_regs {
u32 sysconfig;
u32 modulctrl;
u32 wakeupenable;
struct list_head cs;
};
static struct omap2_mcspi_regs omap2_mcspi_ctx[OMAP2_MCSPI_MAX_CTRL];
static struct workqueue_struct *omap2_mcspi_wq;
#define MOD_REG_BIT(val, mask, set) do { \
if (set) \
val |= mask; \
else \
val &= ~mask; \
} while (0)
static inline void mcspi_write_reg(struct spi_master *master,
int idx, u32 val)
{
struct omap2_mcspi *mcspi = spi_master_get_devdata(master);
__raw_writel(val, mcspi->base + idx);
}
static inline u32 mcspi_read_reg(struct spi_master *master, int idx)
{
struct omap2_mcspi *mcspi = spi_master_get_devdata(master);
return __raw_readl(mcspi->base + idx);
}
static inline void mcspi_write_cs_reg(const struct spi_device *spi,
int idx, u32 val)
{
struct omap2_mcspi_cs *cs = spi->controller_state;
__raw_writel(val, cs->base + idx);
}
static inline u32 mcspi_read_cs_reg(const struct spi_device *spi, int idx)
{
struct omap2_mcspi_cs *cs = spi->controller_state;
return __raw_readl(cs->base + idx);
}
static inline u32 mcspi_cached_chconf0(const struct spi_device *spi)
{
struct omap2_mcspi_cs *cs = spi->controller_state;
return cs->chconf0;
}
static inline void mcspi_write_chconf0(const struct spi_device *spi, u32 val)
{
struct omap2_mcspi_cs *cs = spi->controller_state;
cs->chconf0 = val;
mcspi_write_cs_reg(spi, OMAP2_MCSPI_CHCONF0, val);
}
static void omap2_mcspi_set_dma_req(const struct spi_device *spi,
int is_read, int enable)
{
u32 l, rw;
l = mcspi_cached_chconf0(spi);
if (is_read) /* 1 is read, 0 write */
rw = OMAP2_MCSPI_CHCONF_DMAR;
else
rw = OMAP2_MCSPI_CHCONF_DMAW;
MOD_REG_BIT(l, rw, enable);
mcspi_write_chconf0(spi, l);
}
static void omap2_mcspi_set_enable(const struct spi_device *spi, int enable)
{
u32 l;
l = enable ? OMAP2_MCSPI_CHCTRL_EN : 0;
mcspi_write_cs_reg(spi, OMAP2_MCSPI_CHCTRL0, l);
}
static void omap2_mcspi_force_cs(struct spi_device *spi, int cs_active)
{
u32 l;
l = mcspi_cached_chconf0(spi);
MOD_REG_BIT(l, OMAP2_MCSPI_CHCONF_FORCE, cs_active);
mcspi_write_chconf0(spi, l);
}
static void omap2_mcspi_set_master_mode(struct spi_master *master)
{
u32 l;
/* setup when switching from (reset default) slave mode
* to single-channel master mode
*/
l = mcspi_read_reg(master, OMAP2_MCSPI_MODULCTRL);
MOD_REG_BIT(l, OMAP2_MCSPI_MODULCTRL_STEST, 0);
MOD_REG_BIT(l, OMAP2_MCSPI_MODULCTRL_MS, 0);
MOD_REG_BIT(l, OMAP2_MCSPI_MODULCTRL_SINGLE, 1);
mcspi_write_reg(master, OMAP2_MCSPI_MODULCTRL, l);
omap2_mcspi_ctx[master->bus_num - 1].modulctrl = l;
}
static void omap2_mcspi_restore_ctx(struct omap2_mcspi *mcspi)
{
struct spi_master *spi_cntrl;
struct omap2_mcspi_cs *cs;
spi_cntrl = mcspi->master;
/* McSPI: context restore */
mcspi_write_reg(spi_cntrl, OMAP2_MCSPI_MODULCTRL,
omap2_mcspi_ctx[spi_cntrl->bus_num - 1].modulctrl);
mcspi_write_reg(spi_cntrl, OMAP2_MCSPI_SYSCONFIG,
omap2_mcspi_ctx[spi_cntrl->bus_num - 1].sysconfig);
mcspi_write_reg(spi_cntrl, OMAP2_MCSPI_WAKEUPENABLE,
omap2_mcspi_ctx[spi_cntrl->bus_num - 1].wakeupenable);
list_for_each_entry(cs, &omap2_mcspi_ctx[spi_cntrl->bus_num - 1].cs,
node)
__raw_writel(cs->chconf0, cs->base + OMAP2_MCSPI_CHCONF0);
}
static void omap2_mcspi_disable_clocks(struct omap2_mcspi *mcspi)
{
clk_disable(mcspi->ick);
clk_disable(mcspi->fck);
}
static int omap2_mcspi_enable_clocks(struct omap2_mcspi *mcspi)
{
if (clk_enable(mcspi->ick))
return -ENODEV;
if (clk_enable(mcspi->fck))
return -ENODEV;
omap2_mcspi_restore_ctx(mcspi);
return 0;
}
static unsigned
omap2_mcspi_txrx_dma(struct spi_device *spi, struct spi_transfer *xfer)
{
struct omap2_mcspi *mcspi;
struct omap2_mcspi_cs *cs = spi->controller_state;
struct omap2_mcspi_dma *mcspi_dma;
unsigned int count, c;
unsigned long base, tx_reg, rx_reg;
int word_len, data_type, element_count;
u8 * rx;
const u8 * tx;
mcspi = spi_master_get_devdata(spi->master);
mcspi_dma = &mcspi->dma_channels[spi->chip_select];
count = xfer->len;
c = count;
word_len = cs->word_len;
base = cs->phys;
tx_reg = base + OMAP2_MCSPI_TX0;
rx_reg = base + OMAP2_MCSPI_RX0;
rx = xfer->rx_buf;
tx = xfer->tx_buf;
if (word_len <= 8) {
data_type = OMAP_DMA_DATA_TYPE_S8;
element_count = count;
} else if (word_len <= 16) {
data_type = OMAP_DMA_DATA_TYPE_S16;
element_count = count >> 1;
} else /* word_len <= 32 */ {
data_type = OMAP_DMA_DATA_TYPE_S32;
element_count = count >> 2;
}
if (tx != NULL) {
omap_set_dma_transfer_params(mcspi_dma->dma_tx_channel,
data_type, element_count, 1,
OMAP_DMA_SYNC_ELEMENT,
mcspi_dma->dma_tx_sync_dev, 0);
omap_set_dma_dest_params(mcspi_dma->dma_tx_channel, 0,
OMAP_DMA_AMODE_CONSTANT,
tx_reg, 0, 0);
omap_set_dma_src_params(mcspi_dma->dma_tx_channel, 0,
OMAP_DMA_AMODE_POST_INC,
xfer->tx_dma, 0, 0);
}
if (rx != NULL) {
omap_set_dma_transfer_params(mcspi_dma->dma_rx_channel,
data_type, element_count - 1, 1,
OMAP_DMA_SYNC_ELEMENT,
mcspi_dma->dma_rx_sync_dev, 1);
omap_set_dma_src_params(mcspi_dma->dma_rx_channel, 0,
OMAP_DMA_AMODE_CONSTANT,
rx_reg, 0, 0);
omap_set_dma_dest_params(mcspi_dma->dma_rx_channel, 0,
OMAP_DMA_AMODE_POST_INC,
xfer->rx_dma, 0, 0);
}
if (tx != NULL) {
omap_start_dma(mcspi_dma->dma_tx_channel);
omap2_mcspi_set_dma_req(spi, 0, 1);
}
if (rx != NULL) {
omap_start_dma(mcspi_dma->dma_rx_channel);
omap2_mcspi_set_dma_req(spi, 1, 1);
}
if (tx != NULL) {
wait_for_completion(&mcspi_dma->dma_tx_completion);
dma_unmap_single(NULL, xfer->tx_dma, count, DMA_TO_DEVICE);
}
if (rx != NULL) {
wait_for_completion(&mcspi_dma->dma_rx_completion);
dma_unmap_single(NULL, xfer->rx_dma, count, DMA_FROM_DEVICE);
omap2_mcspi_set_enable(spi, 0);
if (likely(mcspi_read_cs_reg(spi, OMAP2_MCSPI_CHSTAT0)
& OMAP2_MCSPI_CHSTAT_RXS)) {
u32 w;
w = mcspi_read_cs_reg(spi, OMAP2_MCSPI_RX0);
if (word_len <= 8)
((u8 *)xfer->rx_buf)[element_count - 1] = w;
else if (word_len <= 16)
((u16 *)xfer->rx_buf)[element_count - 1] = w;
else /* word_len <= 32 */
((u32 *)xfer->rx_buf)[element_count - 1] = w;
} else {
dev_err(&spi->dev, "DMA RX last word empty");
count -= (word_len <= 8) ? 1 :
(word_len <= 16) ? 2 :
/* word_len <= 32 */ 4;
}
omap2_mcspi_set_enable(spi, 1);
}
return count;
}
static int mcspi_wait_for_reg_bit(void __iomem *reg, unsigned long bit)
{
unsigned long timeout;
timeout = jiffies + msecs_to_jiffies(1000);
while (!(__raw_readl(reg) & bit)) {
if (time_after(jiffies, timeout))
return -1;
cpu_relax();
}
return 0;
}
static unsigned
omap2_mcspi_txrx_pio(struct spi_device *spi, struct spi_transfer *xfer)
{
struct omap2_mcspi *mcspi;
struct omap2_mcspi_cs *cs = spi->controller_state;
unsigned int count, c;
u32 l;
void __iomem *base = cs->base;
void __iomem *tx_reg;
void __iomem *rx_reg;
void __iomem *chstat_reg;
int word_len;
mcspi = spi_master_get_devdata(spi->master);
count = xfer->len;
c = count;
word_len = cs->word_len;
l = mcspi_cached_chconf0(spi);
l &= ~OMAP2_MCSPI_CHCONF_TRM_MASK;
/* We store the pre-calculated register addresses on stack to speed
* up the transfer loop. */
tx_reg = base + OMAP2_MCSPI_TX0;
rx_reg = base + OMAP2_MCSPI_RX0;
chstat_reg = base + OMAP2_MCSPI_CHSTAT0;
if (word_len <= 8) {
u8 *rx;
const u8 *tx;
rx = xfer->rx_buf;
tx = xfer->tx_buf;
do {
c -= 1;
if (tx != NULL) {
if (mcspi_wait_for_reg_bit(chstat_reg,
OMAP2_MCSPI_CHSTAT_TXS) < 0) {
dev_err(&spi->dev, "TXS timed out\n");
goto out;
}
#ifdef VERBOSE
dev_dbg(&spi->dev, "write-%d %02x\n",
word_len, *tx);
#endif
__raw_writel(*tx++, tx_reg);
}
if (rx != NULL) {
if (mcspi_wait_for_reg_bit(chstat_reg,
OMAP2_MCSPI_CHSTAT_RXS) < 0) {
dev_err(&spi->dev, "RXS timed out\n");
goto out;
}
/* prevent last RX_ONLY read from triggering
* more word i/o: switch to rx+tx
*/
if (c == 0 && tx == NULL)
mcspi_write_chconf0(spi, l);
*rx++ = __raw_readl(rx_reg);
#ifdef VERBOSE
dev_dbg(&spi->dev, "read-%d %02x\n",
word_len, *(rx - 1));
#endif
}
} while (c);
} else if (word_len <= 16) {
u16 *rx;
const u16 *tx;
rx = xfer->rx_buf;
tx = xfer->tx_buf;
do {
c -= 2;
if (tx != NULL) {
if (mcspi_wait_for_reg_bit(chstat_reg,
OMAP2_MCSPI_CHSTAT_TXS) < 0) {
dev_err(&spi->dev, "TXS timed out\n");
goto out;
}
#ifdef VERBOSE
dev_dbg(&spi->dev, "write-%d %04x\n",
word_len, *tx);
#endif
__raw_writel(*tx++, tx_reg);
}
if (rx != NULL) {
if (mcspi_wait_for_reg_bit(chstat_reg,
OMAP2_MCSPI_CHSTAT_RXS) < 0) {
dev_err(&spi->dev, "RXS timed out\n");
goto out;
}
/* prevent last RX_ONLY read from triggering
* more word i/o: switch to rx+tx
*/
if (c == 0 && tx == NULL)
mcspi_write_chconf0(spi, l);
*rx++ = __raw_readl(rx_reg);
#ifdef VERBOSE
dev_dbg(&spi->dev, "read-%d %04x\n",
word_len, *(rx - 1));
#endif
}
} while (c);
} else if (word_len <= 32) {
u32 *rx;
const u32 *tx;
rx = xfer->rx_buf;
tx = xfer->tx_buf;
do {
c -= 4;
if (tx != NULL) {
if (mcspi_wait_for_reg_bit(chstat_reg,
OMAP2_MCSPI_CHSTAT_TXS) < 0) {
dev_err(&spi->dev, "TXS timed out\n");
goto out;
}
#ifdef VERBOSE
dev_dbg(&spi->dev, "write-%d %04x\n",
word_len, *tx);
#endif
__raw_writel(*tx++, tx_reg);
}
if (rx != NULL) {
if (mcspi_wait_for_reg_bit(chstat_reg,
OMAP2_MCSPI_CHSTAT_RXS) < 0) {
dev_err(&spi->dev, "RXS timed out\n");
goto out;
}
/* prevent last RX_ONLY read from triggering
* more word i/o: switch to rx+tx
*/
if (c == 0 && tx == NULL)
mcspi_write_chconf0(spi, l);
*rx++ = __raw_readl(rx_reg);
#ifdef VERBOSE
dev_dbg(&spi->dev, "read-%d %04x\n",
word_len, *(rx - 1));
#endif
}
} while (c);
}
/* for TX_ONLY mode, be sure all words have shifted out */
if (xfer->rx_buf == NULL) {
if (mcspi_wait_for_reg_bit(chstat_reg,
OMAP2_MCSPI_CHSTAT_TXS) < 0) {
dev_err(&spi->dev, "TXS timed out\n");
} else if (mcspi_wait_for_reg_bit(chstat_reg,
OMAP2_MCSPI_CHSTAT_EOT) < 0)
dev_err(&spi->dev, "EOT timed out\n");
}
out:
return count - c;
}
/* called only when no transfer is active to this device */
static int omap2_mcspi_setup_transfer(struct spi_device *spi,
struct spi_transfer *t)
{
struct omap2_mcspi_cs *cs = spi->controller_state;
struct omap2_mcspi *mcspi;
struct spi_master *spi_cntrl;
u32 l = 0, div = 0;
u8 word_len = spi->bits_per_word;
mcspi = spi_master_get_devdata(spi->master);
spi_cntrl = mcspi->master;
if (t != NULL && t->bits_per_word)
word_len = t->bits_per_word;
cs->word_len = word_len;
if (spi->max_speed_hz) {
while (div <= 15 && (OMAP2_MCSPI_MAX_FREQ / (1 << div))
> spi->max_speed_hz)
div++;
} else
div = 15;
l = mcspi_cached_chconf0(spi);
/* standard 4-wire master mode: SCK, MOSI/out, MISO/in, nCS
* REVISIT: this controller could support SPI_3WIRE mode.
*/
l &= ~(OMAP2_MCSPI_CHCONF_IS|OMAP2_MCSPI_CHCONF_DPE1);
l |= OMAP2_MCSPI_CHCONF_DPE0;
/* wordlength */
l &= ~OMAP2_MCSPI_CHCONF_WL_MASK;
l |= (word_len - 1) << 7;
/* set chipselect polarity; manage with FORCE */
if (!(spi->mode & SPI_CS_HIGH))
l |= OMAP2_MCSPI_CHCONF_EPOL; /* active-low; normal */
else
l &= ~OMAP2_MCSPI_CHCONF_EPOL;
/* set clock divisor */
l &= ~OMAP2_MCSPI_CHCONF_CLKD_MASK;
l |= div << 2;
/* set SPI mode 0..3 */
if (spi->mode & SPI_CPOL)
l |= OMAP2_MCSPI_CHCONF_POL;
else
l &= ~OMAP2_MCSPI_CHCONF_POL;
if (spi->mode & SPI_CPHA)
l |= OMAP2_MCSPI_CHCONF_PHA;
else
l &= ~OMAP2_MCSPI_CHCONF_PHA;
mcspi_write_chconf0(spi, l);
dev_dbg(&spi->dev, "setup: speed %d, sample %s edge, clk %s\n",
OMAP2_MCSPI_MAX_FREQ / (1 << div),
(spi->mode & SPI_CPHA) ? "trailing" : "leading",
(spi->mode & SPI_CPOL) ? "inverted" : "normal");
return 0;
}
static void omap2_mcspi_dma_rx_callback(int lch, u16 ch_status, void *data)
{
struct spi_device *spi = data;
struct omap2_mcspi *mcspi;
struct omap2_mcspi_dma *mcspi_dma;
mcspi = spi_master_get_devdata(spi->master);
mcspi_dma = &(mcspi->dma_channels[spi->chip_select]);
complete(&mcspi_dma->dma_rx_completion);
/* We must disable the DMA RX request */
omap2_mcspi_set_dma_req(spi, 1, 0);
}
static void omap2_mcspi_dma_tx_callback(int lch, u16 ch_status, void *data)
{
struct spi_device *spi = data;
struct omap2_mcspi *mcspi;
struct omap2_mcspi_dma *mcspi_dma;
mcspi = spi_master_get_devdata(spi->master);
mcspi_dma = &(mcspi->dma_channels[spi->chip_select]);
complete(&mcspi_dma->dma_tx_completion);
/* We must disable the DMA TX request */
omap2_mcspi_set_dma_req(spi, 0, 0);
}
static int omap2_mcspi_request_dma(struct spi_device *spi)
{
struct spi_master *master = spi->master;
struct omap2_mcspi *mcspi;
struct omap2_mcspi_dma *mcspi_dma;
mcspi = spi_master_get_devdata(master);
mcspi_dma = mcspi->dma_channels + spi->chip_select;
if (omap_request_dma(mcspi_dma->dma_rx_sync_dev, "McSPI RX",
omap2_mcspi_dma_rx_callback, spi,
&mcspi_dma->dma_rx_channel)) {
dev_err(&spi->dev, "no RX DMA channel for McSPI\n");
return -EAGAIN;
}
if (omap_request_dma(mcspi_dma->dma_tx_sync_dev, "McSPI TX",
omap2_mcspi_dma_tx_callback, spi,
&mcspi_dma->dma_tx_channel)) {
omap_free_dma(mcspi_dma->dma_rx_channel);
mcspi_dma->dma_rx_channel = -1;
dev_err(&spi->dev, "no TX DMA channel for McSPI\n");
return -EAGAIN;
}
init_completion(&mcspi_dma->dma_rx_completion);
init_completion(&mcspi_dma->dma_tx_completion);
return 0;
}
static int omap2_mcspi_setup(struct spi_device *spi)
{
int ret;
struct omap2_mcspi *mcspi;
struct omap2_mcspi_dma *mcspi_dma;
struct omap2_mcspi_cs *cs = spi->controller_state;
if (spi->bits_per_word < 4 || spi->bits_per_word > 32) {
dev_dbg(&spi->dev, "setup: unsupported %d bit words\n",
spi->bits_per_word);
return -EINVAL;
}
mcspi = spi_master_get_devdata(spi->master);
mcspi_dma = &mcspi->dma_channels[spi->chip_select];
if (!cs) {
cs = kzalloc(sizeof *cs, GFP_KERNEL);
if (!cs)
return -ENOMEM;
cs->base = mcspi->base + spi->chip_select * 0x14;
cs->phys = mcspi->phys + spi->chip_select * 0x14;
cs->chconf0 = 0;
spi->controller_state = cs;
/* Link this to context save list */
list_add_tail(&cs->node,
&omap2_mcspi_ctx[mcspi->master->bus_num - 1].cs);
}
if (mcspi_dma->dma_rx_channel == -1
|| mcspi_dma->dma_tx_channel == -1) {
ret = omap2_mcspi_request_dma(spi);
if (ret < 0)
return ret;
}
if (omap2_mcspi_enable_clocks(mcspi))
return -ENODEV;
ret = omap2_mcspi_setup_transfer(spi, NULL);
omap2_mcspi_disable_clocks(mcspi);
return ret;
}
static void omap2_mcspi_cleanup(struct spi_device *spi)
{
struct omap2_mcspi *mcspi;
struct omap2_mcspi_dma *mcspi_dma;
struct omap2_mcspi_cs *cs;
mcspi = spi_master_get_devdata(spi->master);
mcspi_dma = &mcspi->dma_channels[spi->chip_select];
/* Unlink controller state from context save list */
cs = spi->controller_state;
list_del(&cs->node);
kfree(spi->controller_state);
if (mcspi_dma->dma_rx_channel != -1) {
omap_free_dma(mcspi_dma->dma_rx_channel);
mcspi_dma->dma_rx_channel = -1;
}
if (mcspi_dma->dma_tx_channel != -1) {
omap_free_dma(mcspi_dma->dma_tx_channel);
mcspi_dma->dma_tx_channel = -1;
}
}
static void omap2_mcspi_work(struct work_struct *work)
{
struct omap2_mcspi *mcspi;
mcspi = container_of(work, struct omap2_mcspi, work);
spin_lock_irq(&mcspi->lock);
if (omap2_mcspi_enable_clocks(mcspi))
goto out;
/* We only enable one channel at a time -- the one whose message is
* at the head of the queue -- although this controller would gladly
* arbitrate among multiple channels. This corresponds to "single
* channel" master mode. As a side effect, we need to manage the
* chipselect with the FORCE bit ... CS != channel enable.
*/
while (!list_empty(&mcspi->msg_queue)) {
struct spi_message *m;
struct spi_device *spi;
struct spi_transfer *t = NULL;
int cs_active = 0;
struct omap2_mcspi_cs *cs;
int par_override = 0;
int status = 0;
u32 chconf;
m = container_of(mcspi->msg_queue.next, struct spi_message,
queue);
list_del_init(&m->queue);
spin_unlock_irq(&mcspi->lock);
spi = m->spi;
cs = spi->controller_state;
omap2_mcspi_set_enable(spi, 1);
list_for_each_entry(t, &m->transfers, transfer_list) {
if (t->tx_buf == NULL && t->rx_buf == NULL && t->len) {
status = -EINVAL;
break;
}
if (par_override || t->speed_hz || t->bits_per_word) {
par_override = 1;
status = omap2_mcspi_setup_transfer(spi, t);
if (status < 0)
break;
if (!t->speed_hz && !t->bits_per_word)
par_override = 0;
}
if (!cs_active) {
omap2_mcspi_force_cs(spi, 1);
cs_active = 1;
}
chconf = mcspi_cached_chconf0(spi);
chconf &= ~OMAP2_MCSPI_CHCONF_TRM_MASK;
if (t->tx_buf == NULL)
chconf |= OMAP2_MCSPI_CHCONF_TRM_RX_ONLY;
else if (t->rx_buf == NULL)
chconf |= OMAP2_MCSPI_CHCONF_TRM_TX_ONLY;
mcspi_write_chconf0(spi, chconf);
if (t->len) {
unsigned count;
/* RX_ONLY mode needs dummy data in TX reg */
if (t->tx_buf == NULL)
__raw_writel(0, cs->base
+ OMAP2_MCSPI_TX0);
if (m->is_dma_mapped || t->len >= DMA_MIN_BYTES)
count = omap2_mcspi_txrx_dma(spi, t);
else
count = omap2_mcspi_txrx_pio(spi, t);
m->actual_length += count;
if (count != t->len) {
status = -EIO;
break;
}
}
if (t->delay_usecs)
udelay(t->delay_usecs);
/* ignore the "leave it on after last xfer" hint */
if (t->cs_change) {
omap2_mcspi_force_cs(spi, 0);
cs_active = 0;
}
}
/* Restore defaults if they were overriden */
if (par_override) {
par_override = 0;
status = omap2_mcspi_setup_transfer(spi, NULL);
}
if (cs_active)
omap2_mcspi_force_cs(spi, 0);
omap2_mcspi_set_enable(spi, 0);
m->status = status;
m->complete(m->context);
spin_lock_irq(&mcspi->lock);
}
omap2_mcspi_disable_clocks(mcspi);
out:
spin_unlock_irq(&mcspi->lock);
}
static int omap2_mcspi_transfer(struct spi_device *spi, struct spi_message *m)
{
struct omap2_mcspi *mcspi;
unsigned long flags;
struct spi_transfer *t;
m->actual_length = 0;
m->status = 0;
/* reject invalid messages and transfers */
if (list_empty(&m->transfers) || !m->complete)
return -EINVAL;
list_for_each_entry(t, &m->transfers, transfer_list) {
const void *tx_buf = t->tx_buf;
void *rx_buf = t->rx_buf;
unsigned len = t->len;
if (t->speed_hz > OMAP2_MCSPI_MAX_FREQ
|| (len && !(rx_buf || tx_buf))
|| (t->bits_per_word &&
( t->bits_per_word < 4
|| t->bits_per_word > 32))) {
dev_dbg(&spi->dev, "transfer: %d Hz, %d %s%s, %d bpw\n",
t->speed_hz,
len,
tx_buf ? "tx" : "",
rx_buf ? "rx" : "",
t->bits_per_word);
return -EINVAL;
}
if (t->speed_hz && t->speed_hz < OMAP2_MCSPI_MAX_FREQ/(1<<16)) {
dev_dbg(&spi->dev, "%d Hz max exceeds %d\n",
t->speed_hz,
OMAP2_MCSPI_MAX_FREQ/(1<<16));
return -EINVAL;
}
if (m->is_dma_mapped || len < DMA_MIN_BYTES)
continue;
/* Do DMA mapping "early" for better error reporting and
* dcache use. Note that if dma_unmap_single() ever starts
* to do real work on ARM, we'd need to clean up mappings
* for previous transfers on *ALL* exits of this loop...
*/
if (tx_buf != NULL) {
t->tx_dma = dma_map_single(&spi->dev, (void *) tx_buf,
len, DMA_TO_DEVICE);
if (dma_mapping_error(&spi->dev, t->tx_dma)) {
dev_dbg(&spi->dev, "dma %cX %d bytes error\n",
'T', len);
return -EINVAL;
}
}
if (rx_buf != NULL) {
t->rx_dma = dma_map_single(&spi->dev, rx_buf, t->len,
DMA_FROM_DEVICE);
if (dma_mapping_error(&spi->dev, t->rx_dma)) {
dev_dbg(&spi->dev, "dma %cX %d bytes error\n",
'R', len);
if (tx_buf != NULL)
dma_unmap_single(NULL, t->tx_dma,
len, DMA_TO_DEVICE);
return -EINVAL;
}
}
}
mcspi = spi_master_get_devdata(spi->master);
spin_lock_irqsave(&mcspi->lock, flags);
list_add_tail(&m->queue, &mcspi->msg_queue);
queue_work(omap2_mcspi_wq, &mcspi->work);
spin_unlock_irqrestore(&mcspi->lock, flags);
return 0;
}
static int __init omap2_mcspi_reset(struct omap2_mcspi *mcspi)
{
struct spi_master *master = mcspi->master;
u32 tmp;
if (omap2_mcspi_enable_clocks(mcspi))
return -1;
mcspi_write_reg(master, OMAP2_MCSPI_SYSCONFIG,
OMAP2_MCSPI_SYSCONFIG_SOFTRESET);
do {
tmp = mcspi_read_reg(master, OMAP2_MCSPI_SYSSTATUS);
} while (!(tmp & OMAP2_MCSPI_SYSSTATUS_RESETDONE));
tmp = OMAP2_MCSPI_SYSCONFIG_AUTOIDLE |
OMAP2_MCSPI_SYSCONFIG_ENAWAKEUP |
OMAP2_MCSPI_SYSCONFIG_SMARTIDLE;
mcspi_write_reg(master, OMAP2_MCSPI_SYSCONFIG, tmp);
omap2_mcspi_ctx[master->bus_num - 1].sysconfig = tmp;
tmp = OMAP2_MCSPI_WAKEUPENABLE_WKEN;
mcspi_write_reg(master, OMAP2_MCSPI_WAKEUPENABLE, tmp);
omap2_mcspi_ctx[master->bus_num - 1].wakeupenable = tmp;
omap2_mcspi_set_master_mode(master);
omap2_mcspi_disable_clocks(mcspi);
return 0;
}
static u8 __initdata spi1_rxdma_id [] = {
OMAP24XX_DMA_SPI1_RX0,
OMAP24XX_DMA_SPI1_RX1,
OMAP24XX_DMA_SPI1_RX2,
OMAP24XX_DMA_SPI1_RX3,
};
static u8 __initdata spi1_txdma_id [] = {
OMAP24XX_DMA_SPI1_TX0,
OMAP24XX_DMA_SPI1_TX1,
OMAP24XX_DMA_SPI1_TX2,
OMAP24XX_DMA_SPI1_TX3,
};
static u8 __initdata spi2_rxdma_id[] = {
OMAP24XX_DMA_SPI2_RX0,
OMAP24XX_DMA_SPI2_RX1,
};
static u8 __initdata spi2_txdma_id[] = {
OMAP24XX_DMA_SPI2_TX0,
OMAP24XX_DMA_SPI2_TX1,
};
#if defined(CONFIG_ARCH_OMAP2430) || defined(CONFIG_ARCH_OMAP34XX) \
|| defined(CONFIG_ARCH_OMAP4)
static u8 __initdata spi3_rxdma_id[] = {
OMAP24XX_DMA_SPI3_RX0,
OMAP24XX_DMA_SPI3_RX1,
};
static u8 __initdata spi3_txdma_id[] = {
OMAP24XX_DMA_SPI3_TX0,
OMAP24XX_DMA_SPI3_TX1,
};
#endif
#if defined(CONFIG_ARCH_OMAP3) || defined(CONFIG_ARCH_OMAP4)
static u8 __initdata spi4_rxdma_id[] = {
OMAP34XX_DMA_SPI4_RX0,
};
static u8 __initdata spi4_txdma_id[] = {
OMAP34XX_DMA_SPI4_TX0,
};
#endif
static int __init omap2_mcspi_probe(struct platform_device *pdev)
{
struct spi_master *master;
struct omap2_mcspi *mcspi;
struct resource *r;
int status = 0, i;
const u8 *rxdma_id, *txdma_id;
unsigned num_chipselect;
switch (pdev->id) {
case 1:
rxdma_id = spi1_rxdma_id;
txdma_id = spi1_txdma_id;
num_chipselect = 4;
break;
case 2:
rxdma_id = spi2_rxdma_id;
txdma_id = spi2_txdma_id;
num_chipselect = 2;
break;
#if defined(CONFIG_ARCH_OMAP2430) || defined(CONFIG_ARCH_OMAP3) \
|| defined(CONFIG_ARCH_OMAP4)
case 3:
rxdma_id = spi3_rxdma_id;
txdma_id = spi3_txdma_id;
num_chipselect = 2;
break;
#endif
#if defined(CONFIG_ARCH_OMAP3) || defined(CONFIG_ARCH_OMAP4)
case 4:
rxdma_id = spi4_rxdma_id;
txdma_id = spi4_txdma_id;
num_chipselect = 1;
break;
#endif
default:
return -EINVAL;
}
master = spi_alloc_master(&pdev->dev, sizeof *mcspi);
if (master == NULL) {
dev_dbg(&pdev->dev, "master allocation failed\n");
return -ENOMEM;
}
/* the spi->mode bits understood by this driver: */
master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_CS_HIGH;
if (pdev->id != -1)
master->bus_num = pdev->id;
master->setup = omap2_mcspi_setup;
master->transfer = omap2_mcspi_transfer;
master->cleanup = omap2_mcspi_cleanup;
master->num_chipselect = num_chipselect;
dev_set_drvdata(&pdev->dev, master);
mcspi = spi_master_get_devdata(master);
mcspi->master = master;
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (r == NULL) {
status = -ENODEV;
goto err1;
}
if (!request_mem_region(r->start, (r->end - r->start) + 1,
dev_name(&pdev->dev))) {
status = -EBUSY;
goto err1;
}
mcspi->phys = r->start;
mcspi->base = ioremap(r->start, r->end - r->start + 1);
if (!mcspi->base) {
dev_dbg(&pdev->dev, "can't ioremap MCSPI\n");
status = -ENOMEM;
goto err1aa;
}
INIT_WORK(&mcspi->work, omap2_mcspi_work);
spin_lock_init(&mcspi->lock);
INIT_LIST_HEAD(&mcspi->msg_queue);
INIT_LIST_HEAD(&omap2_mcspi_ctx[master->bus_num - 1].cs);
mcspi->ick = clk_get(&pdev->dev, "ick");
if (IS_ERR(mcspi->ick)) {
dev_dbg(&pdev->dev, "can't get mcspi_ick\n");
status = PTR_ERR(mcspi->ick);
goto err1a;
}
mcspi->fck = clk_get(&pdev->dev, "fck");
if (IS_ERR(mcspi->fck)) {
dev_dbg(&pdev->dev, "can't get mcspi_fck\n");
status = PTR_ERR(mcspi->fck);
goto err2;
}
mcspi->dma_channels = kcalloc(master->num_chipselect,
sizeof(struct omap2_mcspi_dma),
GFP_KERNEL);
if (mcspi->dma_channels == NULL)
goto err3;
for (i = 0; i < num_chipselect; i++) {
mcspi->dma_channels[i].dma_rx_channel = -1;
mcspi->dma_channels[i].dma_rx_sync_dev = rxdma_id[i];
mcspi->dma_channels[i].dma_tx_channel = -1;
mcspi->dma_channels[i].dma_tx_sync_dev = txdma_id[i];
}
if (omap2_mcspi_reset(mcspi) < 0)
goto err4;
status = spi_register_master(master);
if (status < 0)
goto err4;
return status;
err4:
kfree(mcspi->dma_channels);
err3:
clk_put(mcspi->fck);
err2:
clk_put(mcspi->ick);
err1a:
iounmap(mcspi->base);
err1aa:
release_mem_region(r->start, (r->end - r->start) + 1);
err1:
spi_master_put(master);
return status;
}
static int __exit omap2_mcspi_remove(struct platform_device *pdev)
{
struct spi_master *master;
struct omap2_mcspi *mcspi;
struct omap2_mcspi_dma *dma_channels;
struct resource *r;
void __iomem *base;
master = dev_get_drvdata(&pdev->dev);
mcspi = spi_master_get_devdata(master);
dma_channels = mcspi->dma_channels;
clk_put(mcspi->fck);
clk_put(mcspi->ick);
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(r->start, (r->end - r->start) + 1);
base = mcspi->base;
spi_unregister_master(master);
iounmap(base);
kfree(dma_channels);
return 0;
}
/* work with hotplug and coldplug */
MODULE_ALIAS("platform:omap2_mcspi");
static struct platform_driver omap2_mcspi_driver = {
.driver = {
.name = "omap2_mcspi",
.owner = THIS_MODULE,
},
.remove = __exit_p(omap2_mcspi_remove),
};
static int __init omap2_mcspi_init(void)
{
omap2_mcspi_wq = create_singlethread_workqueue(
omap2_mcspi_driver.driver.name);
if (omap2_mcspi_wq == NULL)
return -1;
return platform_driver_probe(&omap2_mcspi_driver, omap2_mcspi_probe);
}
subsys_initcall(omap2_mcspi_init);
static void __exit omap2_mcspi_exit(void)
{
platform_driver_unregister(&omap2_mcspi_driver);
destroy_workqueue(omap2_mcspi_wq);
}
module_exit(omap2_mcspi_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
serj/kernel_graph_2.6.32_rhel | drivers/net/loopback.c | 465 | 5672 | /*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* Pseudo-driver for the loopback interface.
*
* Version: @(#)loopback.c 1.0.4b 08/16/93
*
* Authors: Ross Biro
* Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
* Donald Becker, <becker@scyld.com>
*
* Alan Cox : Fixed oddments for NET3.014
* Alan Cox : Rejig for NET3.029 snap #3
* Alan Cox : Fixed NET3.029 bugs and sped up
* Larry McVoy : Tiny tweak to double performance
* Alan Cox : Backed out LMV's tweak - the linux mm
* can't take it...
* Michael Griffith: Don't bother computing the checksums
* on packets received on the loopback
* interface.
* Alexey Kuznetsov: Potential hang under some extreme
* cases removed.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/jiffies.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/fs.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/socket.h>
#include <linux/errno.h>
#include <linux/fcntl.h>
#include <linux/in.h>
#include <linux/init.h>
#include <asm/system.h>
#include <asm/uaccess.h>
#include <asm/io.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/ethtool.h>
#include <net/sock.h>
#include <net/checksum.h>
#include <linux/if_ether.h> /* For the statistics structure. */
#include <linux/if_arp.h> /* For ARPHRD_ETHER */
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/percpu.h>
#include <net/net_namespace.h>
struct pcpu_lstats {
unsigned long packets;
unsigned long bytes;
unsigned long drops;
};
/*
* The higher levels take care of making this non-reentrant (it's
* called with bh's disabled).
*/
static netdev_tx_t loopback_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct pcpu_lstats *pcpu_lstats, *lb_stats;
int len;
skb_orphan(skb);
skb->protocol = eth_type_trans(skb, dev);
/* it's OK to use per_cpu_ptr() because BHs are off */
pcpu_lstats = dev->ml_priv;
lb_stats = per_cpu_ptr(pcpu_lstats, smp_processor_id());
len = skb->len;
if (likely(netif_rx(skb) == NET_RX_SUCCESS)) {
lb_stats->bytes += len;
lb_stats->packets++;
} else
lb_stats->drops++;
return NETDEV_TX_OK;
}
static struct net_device_stats *loopback_get_stats(struct net_device *dev)
{
const struct pcpu_lstats *pcpu_lstats;
struct net_device_stats *stats = &dev->stats;
unsigned long bytes = 0;
unsigned long packets = 0;
unsigned long drops = 0;
int i;
pcpu_lstats = dev->ml_priv;
for_each_possible_cpu(i) {
const struct pcpu_lstats *lb_stats;
lb_stats = per_cpu_ptr(pcpu_lstats, i);
bytes += lb_stats->bytes;
packets += lb_stats->packets;
drops += lb_stats->drops;
}
stats->rx_packets = packets;
stats->tx_packets = packets;
stats->rx_dropped = drops;
stats->rx_errors = drops;
stats->rx_bytes = bytes;
stats->tx_bytes = bytes;
return stats;
}
static u32 always_on(struct net_device *dev)
{
return 1;
}
static const struct ethtool_ops loopback_ethtool_ops = {
.get_link = always_on,
.set_tso = ethtool_op_set_tso,
.get_tx_csum = always_on,
.get_sg = always_on,
.get_rx_csum = always_on,
};
static int loopback_dev_init(struct net_device *dev)
{
struct pcpu_lstats *lstats;
lstats = alloc_percpu(struct pcpu_lstats);
if (!lstats)
return -ENOMEM;
dev->ml_priv = lstats;
return 0;
}
static void loopback_dev_free(struct net_device *dev)
{
struct pcpu_lstats *lstats = dev->ml_priv;
free_percpu(lstats);
free_netdev(dev);
}
static const struct net_device_ops loopback_ops = {
.ndo_init = loopback_dev_init,
.ndo_start_xmit= loopback_xmit,
.ndo_get_stats = loopback_get_stats,
};
/*
* The loopback device is special. There is only one instance
* per network namespace.
*/
static void loopback_setup(struct net_device *dev)
{
dev->mtu = (16 * 1024) + 20 + 20 + 12;
dev->hard_header_len = ETH_HLEN; /* 14 */
dev->addr_len = ETH_ALEN; /* 6 */
dev->tx_queue_len = 0;
dev->type = ARPHRD_LOOPBACK; /* 0x0001*/
dev->flags = IFF_LOOPBACK;
dev->priv_flags &= ~IFF_XMIT_DST_RELEASE;
dev->features = NETIF_F_SG | NETIF_F_FRAGLIST
| NETIF_F_TSO
| NETIF_F_NO_CSUM
| NETIF_F_HIGHDMA
| NETIF_F_LLTX
| NETIF_F_NETNS_LOCAL;
dev->ethtool_ops = &loopback_ethtool_ops;
dev->header_ops = ð_header_ops;
dev->netdev_ops = &loopback_ops;
dev->destructor = loopback_dev_free;
}
/* Setup and register the loopback device. */
static __net_init int loopback_net_init(struct net *net)
{
struct net_device *dev;
int err;
err = -ENOMEM;
dev = alloc_netdev(0, "lo", loopback_setup);
if (!dev)
goto out;
dev_net_set(dev, net);
err = register_netdev(dev);
if (err)
goto out_free_netdev;
net->loopback_dev = dev;
return 0;
out_free_netdev:
free_netdev(dev);
out:
if (net == &init_net)
panic("loopback: Failed to register netdevice: %d\n", err);
return err;
}
static __net_exit void loopback_net_exit(struct net *net)
{
struct net_device *dev = net->loopback_dev;
unregister_netdev(dev);
}
/* Registered in net/core/dev.c */
struct pernet_operations __net_initdata loopback_net_ops = {
.init = loopback_net_init,
.exit = loopback_net_exit,
};
| gpl-2.0 |
nushor/samsung_aries_ics_OLD | sound/usb/mixer.c | 721 | 61199 | /*
* (Tentative) USB Audio Driver for ALSA
*
* Mixer control part
*
* Copyright (c) 2002 by Takashi Iwai <tiwai@suse.de>
*
* Many codes borrowed from audio.c by
* Alan Cox (alan@lxorguk.ukuu.org.uk)
* Thomas Sailer (sailer@ife.ee.ethz.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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/bitops.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/usb.h>
#include <linux/usb/audio.h>
#include <linux/usb/audio-v2.h>
#include <sound/core.h>
#include <sound/control.h>
#include <sound/hwdep.h>
#include <sound/info.h>
#include <sound/tlv.h>
#include "usbaudio.h"
#include "mixer.h"
#include "helper.h"
#include "mixer_quirks.h"
#define MAX_ID_ELEMS 256
struct usb_audio_term {
int id;
int type;
int channels;
unsigned int chconfig;
int name;
};
struct usbmix_name_map;
struct mixer_build {
struct snd_usb_audio *chip;
struct usb_mixer_interface *mixer;
unsigned char *buffer;
unsigned int buflen;
DECLARE_BITMAP(unitbitmap, MAX_ID_ELEMS);
struct usb_audio_term oterm;
const struct usbmix_name_map *map;
const struct usbmix_selector_map *selector_map;
};
enum {
USB_MIXER_BOOLEAN,
USB_MIXER_INV_BOOLEAN,
USB_MIXER_S8,
USB_MIXER_U8,
USB_MIXER_S16,
USB_MIXER_U16,
};
/*E-mu 0202(0404) eXtension Unit(XU) control*/
enum {
USB_XU_CLOCK_RATE = 0xe301,
USB_XU_CLOCK_SOURCE = 0xe302,
USB_XU_DIGITAL_IO_STATUS = 0xe303,
USB_XU_DEVICE_OPTIONS = 0xe304,
USB_XU_DIRECT_MONITORING = 0xe305,
USB_XU_METERING = 0xe306
};
enum {
USB_XU_CLOCK_SOURCE_SELECTOR = 0x02, /* clock source*/
USB_XU_CLOCK_RATE_SELECTOR = 0x03, /* clock rate */
USB_XU_DIGITAL_FORMAT_SELECTOR = 0x01, /* the spdif format */
USB_XU_SOFT_LIMIT_SELECTOR = 0x03 /* soft limiter */
};
/*
* manual mapping of mixer names
* if the mixer topology is too complicated and the parsed names are
* ambiguous, add the entries in usbmixer_maps.c.
*/
#include "mixer_maps.c"
static const struct usbmix_name_map *
find_map(struct mixer_build *state, int unitid, int control)
{
const struct usbmix_name_map *p = state->map;
if (!p)
return NULL;
for (p = state->map; p->id; p++) {
if (p->id == unitid &&
(!control || !p->control || control == p->control))
return p;
}
return NULL;
}
/* get the mapped name if the unit matches */
static int
check_mapped_name(const struct usbmix_name_map *p, char *buf, int buflen)
{
if (!p || !p->name)
return 0;
buflen--;
return strlcpy(buf, p->name, buflen);
}
/* check whether the control should be ignored */
static inline int
check_ignored_ctl(const struct usbmix_name_map *p)
{
if (!p || p->name || p->dB)
return 0;
return 1;
}
/* dB mapping */
static inline void check_mapped_dB(const struct usbmix_name_map *p,
struct usb_mixer_elem_info *cval)
{
if (p && p->dB) {
cval->dBmin = p->dB->min;
cval->dBmax = p->dB->max;
}
}
/* get the mapped selector source name */
static int check_mapped_selector_name(struct mixer_build *state, int unitid,
int index, char *buf, int buflen)
{
const struct usbmix_selector_map *p;
if (! state->selector_map)
return 0;
for (p = state->selector_map; p->id; p++) {
if (p->id == unitid && index < p->count)
return strlcpy(buf, p->names[index], buflen);
}
return 0;
}
/*
* find an audio control unit with the given unit id
*/
static void *find_audio_control_unit(struct mixer_build *state, unsigned char unit)
{
/* we just parse the header */
struct uac_feature_unit_descriptor *hdr = NULL;
while ((hdr = snd_usb_find_desc(state->buffer, state->buflen, hdr,
USB_DT_CS_INTERFACE)) != NULL) {
if (hdr->bLength >= 4 &&
hdr->bDescriptorSubtype >= UAC_INPUT_TERMINAL &&
hdr->bDescriptorSubtype <= UAC2_SAMPLE_RATE_CONVERTER &&
hdr->bUnitID == unit)
return hdr;
}
return NULL;
}
/*
* copy a string with the given id
*/
static int snd_usb_copy_string_desc(struct mixer_build *state, int index, char *buf, int maxlen)
{
int len = usb_string(state->chip->dev, index, buf, maxlen - 1);
buf[len] = 0;
return len;
}
/*
* convert from the byte/word on usb descriptor to the zero-based integer
*/
static int convert_signed_value(struct usb_mixer_elem_info *cval, int val)
{
switch (cval->val_type) {
case USB_MIXER_BOOLEAN:
return !!val;
case USB_MIXER_INV_BOOLEAN:
return !val;
case USB_MIXER_U8:
val &= 0xff;
break;
case USB_MIXER_S8:
val &= 0xff;
if (val >= 0x80)
val -= 0x100;
break;
case USB_MIXER_U16:
val &= 0xffff;
break;
case USB_MIXER_S16:
val &= 0xffff;
if (val >= 0x8000)
val -= 0x10000;
break;
}
return val;
}
/*
* convert from the zero-based int to the byte/word for usb descriptor
*/
static int convert_bytes_value(struct usb_mixer_elem_info *cval, int val)
{
switch (cval->val_type) {
case USB_MIXER_BOOLEAN:
return !!val;
case USB_MIXER_INV_BOOLEAN:
return !val;
case USB_MIXER_S8:
case USB_MIXER_U8:
return val & 0xff;
case USB_MIXER_S16:
case USB_MIXER_U16:
return val & 0xffff;
}
return 0; /* not reached */
}
static int get_relative_value(struct usb_mixer_elem_info *cval, int val)
{
if (! cval->res)
cval->res = 1;
if (val < cval->min)
return 0;
else if (val >= cval->max)
return (cval->max - cval->min + cval->res - 1) / cval->res;
else
return (val - cval->min) / cval->res;
}
static int get_abs_value(struct usb_mixer_elem_info *cval, int val)
{
if (val < 0)
return cval->min;
if (! cval->res)
cval->res = 1;
val *= cval->res;
val += cval->min;
if (val > cval->max)
return cval->max;
return val;
}
/*
* retrieve a mixer value
*/
static int get_ctl_value_v1(struct usb_mixer_elem_info *cval, int request, int validx, int *value_ret)
{
unsigned char buf[2];
int val_len = cval->val_type >= USB_MIXER_S16 ? 2 : 1;
int timeout = 10;
while (timeout-- > 0) {
if (snd_usb_ctl_msg(cval->mixer->chip->dev,
usb_rcvctrlpipe(cval->mixer->chip->dev, 0),
request,
USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
validx, cval->mixer->ctrlif | (cval->id << 8),
buf, val_len, 100) >= val_len) {
*value_ret = convert_signed_value(cval, snd_usb_combine_bytes(buf, val_len));
return 0;
}
}
snd_printdd(KERN_ERR "cannot get ctl value: req = %#x, wValue = %#x, wIndex = %#x, type = %d\n",
request, validx, cval->mixer->ctrlif | (cval->id << 8), cval->val_type);
return -EINVAL;
}
static int get_ctl_value_v2(struct usb_mixer_elem_info *cval, int request, int validx, int *value_ret)
{
unsigned char buf[2 + 3*sizeof(__u16)]; /* enough space for one range */
unsigned char *val;
int ret, size;
__u8 bRequest;
if (request == UAC_GET_CUR) {
bRequest = UAC2_CS_CUR;
size = sizeof(__u16);
} else {
bRequest = UAC2_CS_RANGE;
size = sizeof(buf);
}
memset(buf, 0, sizeof(buf));
ret = snd_usb_ctl_msg(cval->mixer->chip->dev,
usb_rcvctrlpipe(cval->mixer->chip->dev, 0),
bRequest,
USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
validx, cval->mixer->ctrlif | (cval->id << 8),
buf, size, 1000);
if (ret < 0) {
snd_printk(KERN_ERR "cannot get ctl value: req = %#x, wValue = %#x, wIndex = %#x, type = %d\n",
request, validx, cval->mixer->ctrlif | (cval->id << 8), cval->val_type);
return ret;
}
/* FIXME: how should we handle multiple triplets here? */
switch (request) {
case UAC_GET_CUR:
val = buf;
break;
case UAC_GET_MIN:
val = buf + sizeof(__u16);
break;
case UAC_GET_MAX:
val = buf + sizeof(__u16) * 2;
break;
case UAC_GET_RES:
val = buf + sizeof(__u16) * 3;
break;
default:
return -EINVAL;
}
*value_ret = convert_signed_value(cval, snd_usb_combine_bytes(val, sizeof(__u16)));
return 0;
}
static int get_ctl_value(struct usb_mixer_elem_info *cval, int request, int validx, int *value_ret)
{
return (cval->mixer->protocol == UAC_VERSION_1) ?
get_ctl_value_v1(cval, request, validx, value_ret) :
get_ctl_value_v2(cval, request, validx, value_ret);
}
static int get_cur_ctl_value(struct usb_mixer_elem_info *cval, int validx, int *value)
{
return get_ctl_value(cval, UAC_GET_CUR, validx, value);
}
/* channel = 0: master, 1 = first channel */
static inline int get_cur_mix_raw(struct usb_mixer_elem_info *cval,
int channel, int *value)
{
return get_ctl_value(cval, UAC_GET_CUR, (cval->control << 8) | channel, value);
}
static int get_cur_mix_value(struct usb_mixer_elem_info *cval,
int channel, int index, int *value)
{
int err;
if (cval->cached & (1 << channel)) {
*value = cval->cache_val[index];
return 0;
}
err = get_cur_mix_raw(cval, channel, value);
if (err < 0) {
if (!cval->mixer->ignore_ctl_error)
snd_printd(KERN_ERR "cannot get current value for control %d ch %d: err = %d\n",
cval->control, channel, err);
return err;
}
cval->cached |= 1 << channel;
cval->cache_val[index] = *value;
return 0;
}
/*
* set a mixer value
*/
int snd_usb_mixer_set_ctl_value(struct usb_mixer_elem_info *cval,
int request, int validx, int value_set)
{
unsigned char buf[2];
int val_len, timeout = 10;
if (cval->mixer->protocol == UAC_VERSION_1) {
val_len = cval->val_type >= USB_MIXER_S16 ? 2 : 1;
} else { /* UAC_VERSION_2 */
/* audio class v2 controls are always 2 bytes in size */
val_len = sizeof(__u16);
/* FIXME */
if (request != UAC_SET_CUR) {
snd_printdd(KERN_WARNING "RANGE setting not yet supported\n");
return -EINVAL;
}
request = UAC2_CS_CUR;
}
value_set = convert_bytes_value(cval, value_set);
buf[0] = value_set & 0xff;
buf[1] = (value_set >> 8) & 0xff;
while (timeout-- > 0)
if (snd_usb_ctl_msg(cval->mixer->chip->dev,
usb_sndctrlpipe(cval->mixer->chip->dev, 0),
request,
USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_OUT,
validx, cval->mixer->ctrlif | (cval->id << 8),
buf, val_len, 100) >= 0)
return 0;
snd_printdd(KERN_ERR "cannot set ctl value: req = %#x, wValue = %#x, wIndex = %#x, type = %d, data = %#x/%#x\n",
request, validx, cval->mixer->ctrlif | (cval->id << 8), cval->val_type, buf[0], buf[1]);
return -EINVAL;
}
static int set_cur_ctl_value(struct usb_mixer_elem_info *cval, int validx, int value)
{
return snd_usb_mixer_set_ctl_value(cval, UAC_SET_CUR, validx, value);
}
static int set_cur_mix_value(struct usb_mixer_elem_info *cval, int channel,
int index, int value)
{
int err;
unsigned int read_only = (channel == 0) ?
cval->master_readonly :
cval->ch_readonly & (1 << (channel - 1));
if (read_only) {
snd_printdd(KERN_INFO "%s(): channel %d of control %d is read_only\n",
__func__, channel, cval->control);
return 0;
}
err = snd_usb_mixer_set_ctl_value(cval, UAC_SET_CUR, (cval->control << 8) | channel,
value);
if (err < 0)
return err;
cval->cached |= 1 << channel;
cval->cache_val[index] = value;
return 0;
}
/*
* TLV callback for mixer volume controls
*/
static int mixer_vol_tlv(struct snd_kcontrol *kcontrol, int op_flag,
unsigned int size, unsigned int __user *_tlv)
{
struct usb_mixer_elem_info *cval = kcontrol->private_data;
DECLARE_TLV_DB_MINMAX(scale, 0, 0);
if (size < sizeof(scale))
return -ENOMEM;
scale[2] = cval->dBmin;
scale[3] = cval->dBmax;
if (copy_to_user(_tlv, scale, sizeof(scale)))
return -EFAULT;
return 0;
}
/*
* parser routines begin here...
*/
static int parse_audio_unit(struct mixer_build *state, int unitid);
/*
* check if the input/output channel routing is enabled on the given bitmap.
* used for mixer unit parser
*/
static int check_matrix_bitmap(unsigned char *bmap, int ich, int och, int num_outs)
{
int idx = ich * num_outs + och;
return bmap[idx >> 3] & (0x80 >> (idx & 7));
}
/*
* add an alsa control element
* search and increment the index until an empty slot is found.
*
* if failed, give up and free the control instance.
*/
static int add_control_to_empty(struct mixer_build *state, struct snd_kcontrol *kctl)
{
struct usb_mixer_elem_info *cval = kctl->private_data;
int err;
while (snd_ctl_find_id(state->chip->card, &kctl->id))
kctl->id.index++;
if ((err = snd_ctl_add(state->chip->card, kctl)) < 0) {
snd_printd(KERN_ERR "cannot add control (err = %d)\n", err);
return err;
}
cval->elem_id = &kctl->id;
cval->next_id_elem = state->mixer->id_elems[cval->id];
state->mixer->id_elems[cval->id] = cval;
return 0;
}
/*
* get a terminal name string
*/
static struct iterm_name_combo {
int type;
char *name;
} iterm_names[] = {
{ 0x0300, "Output" },
{ 0x0301, "Speaker" },
{ 0x0302, "Headphone" },
{ 0x0303, "HMD Audio" },
{ 0x0304, "Desktop Speaker" },
{ 0x0305, "Room Speaker" },
{ 0x0306, "Com Speaker" },
{ 0x0307, "LFE" },
{ 0x0600, "External In" },
{ 0x0601, "Analog In" },
{ 0x0602, "Digital In" },
{ 0x0603, "Line" },
{ 0x0604, "Legacy In" },
{ 0x0605, "IEC958 In" },
{ 0x0606, "1394 DA Stream" },
{ 0x0607, "1394 DV Stream" },
{ 0x0700, "Embedded" },
{ 0x0701, "Noise Source" },
{ 0x0702, "Equalization Noise" },
{ 0x0703, "CD" },
{ 0x0704, "DAT" },
{ 0x0705, "DCC" },
{ 0x0706, "MiniDisk" },
{ 0x0707, "Analog Tape" },
{ 0x0708, "Phonograph" },
{ 0x0709, "VCR Audio" },
{ 0x070a, "Video Disk Audio" },
{ 0x070b, "DVD Audio" },
{ 0x070c, "TV Tuner Audio" },
{ 0x070d, "Satellite Rec Audio" },
{ 0x070e, "Cable Tuner Audio" },
{ 0x070f, "DSS Audio" },
{ 0x0710, "Radio Receiver" },
{ 0x0711, "Radio Transmitter" },
{ 0x0712, "Multi-Track Recorder" },
{ 0x0713, "Synthesizer" },
{ 0 },
};
static int get_term_name(struct mixer_build *state, struct usb_audio_term *iterm,
unsigned char *name, int maxlen, int term_only)
{
struct iterm_name_combo *names;
if (iterm->name)
return snd_usb_copy_string_desc(state, iterm->name, name, maxlen);
/* virtual type - not a real terminal */
if (iterm->type >> 16) {
if (term_only)
return 0;
switch (iterm->type >> 16) {
case UAC_SELECTOR_UNIT:
strcpy(name, "Selector"); return 8;
case UAC_PROCESSING_UNIT_V1:
strcpy(name, "Process Unit"); return 12;
case UAC_EXTENSION_UNIT_V1:
strcpy(name, "Ext Unit"); return 8;
case UAC_MIXER_UNIT:
strcpy(name, "Mixer"); return 5;
default:
return sprintf(name, "Unit %d", iterm->id);
}
}
switch (iterm->type & 0xff00) {
case 0x0100:
strcpy(name, "PCM"); return 3;
case 0x0200:
strcpy(name, "Mic"); return 3;
case 0x0400:
strcpy(name, "Headset"); return 7;
case 0x0500:
strcpy(name, "Phone"); return 5;
}
for (names = iterm_names; names->type; names++)
if (names->type == iterm->type) {
strcpy(name, names->name);
return strlen(names->name);
}
return 0;
}
/*
* parse the source unit recursively until it reaches to a terminal
* or a branched unit.
*/
static int check_input_term(struct mixer_build *state, int id, struct usb_audio_term *term)
{
int err;
void *p1;
memset(term, 0, sizeof(*term));
while ((p1 = find_audio_control_unit(state, id)) != NULL) {
unsigned char *hdr = p1;
term->id = id;
switch (hdr[2]) {
case UAC_INPUT_TERMINAL:
if (state->mixer->protocol == UAC_VERSION_1) {
struct uac_input_terminal_descriptor *d = p1;
term->type = le16_to_cpu(d->wTerminalType);
term->channels = d->bNrChannels;
term->chconfig = le16_to_cpu(d->wChannelConfig);
term->name = d->iTerminal;
} else { /* UAC_VERSION_2 */
struct uac2_input_terminal_descriptor *d = p1;
term->type = le16_to_cpu(d->wTerminalType);
term->channels = d->bNrChannels;
term->chconfig = le32_to_cpu(d->bmChannelConfig);
term->name = d->iTerminal;
/* call recursively to get the clock selectors */
err = check_input_term(state, d->bCSourceID, term);
if (err < 0)
return err;
}
return 0;
case UAC_FEATURE_UNIT: {
/* the header is the same for v1 and v2 */
struct uac_feature_unit_descriptor *d = p1;
id = d->bSourceID;
break; /* continue to parse */
}
case UAC_MIXER_UNIT: {
struct uac_mixer_unit_descriptor *d = p1;
term->type = d->bDescriptorSubtype << 16; /* virtual type */
term->channels = uac_mixer_unit_bNrChannels(d);
term->chconfig = uac_mixer_unit_wChannelConfig(d, state->mixer->protocol);
term->name = uac_mixer_unit_iMixer(d);
return 0;
}
case UAC_SELECTOR_UNIT:
case UAC2_CLOCK_SELECTOR: {
struct uac_selector_unit_descriptor *d = p1;
/* call recursively to retrieve the channel info */
if (check_input_term(state, d->baSourceID[0], term) < 0)
return -ENODEV;
term->type = d->bDescriptorSubtype << 16; /* virtual type */
term->id = id;
term->name = uac_selector_unit_iSelector(d);
return 0;
}
case UAC_PROCESSING_UNIT_V1:
case UAC_EXTENSION_UNIT_V1: {
struct uac_processing_unit_descriptor *d = p1;
if (d->bNrInPins) {
id = d->baSourceID[0];
break; /* continue to parse */
}
term->type = d->bDescriptorSubtype << 16; /* virtual type */
term->channels = uac_processing_unit_bNrChannels(d);
term->chconfig = uac_processing_unit_wChannelConfig(d, state->mixer->protocol);
term->name = uac_processing_unit_iProcessing(d, state->mixer->protocol);
return 0;
}
case UAC2_CLOCK_SOURCE: {
struct uac_clock_source_descriptor *d = p1;
term->type = d->bDescriptorSubtype << 16; /* virtual type */
term->id = id;
term->name = d->iClockSource;
return 0;
}
default:
return -ENODEV;
}
}
return -ENODEV;
}
/*
* Feature Unit
*/
/* feature unit control information */
struct usb_feature_control_info {
const char *name;
unsigned int type; /* control type (mute, volume, etc.) */
};
static struct usb_feature_control_info audio_feature_info[] = {
{ "Mute", USB_MIXER_INV_BOOLEAN },
{ "Volume", USB_MIXER_S16 },
{ "Tone Control - Bass", USB_MIXER_S8 },
{ "Tone Control - Mid", USB_MIXER_S8 },
{ "Tone Control - Treble", USB_MIXER_S8 },
{ "Graphic Equalizer", USB_MIXER_S8 }, /* FIXME: not implemeted yet */
{ "Auto Gain Control", USB_MIXER_BOOLEAN },
{ "Delay Control", USB_MIXER_U16 },
{ "Bass Boost", USB_MIXER_BOOLEAN },
{ "Loudness", USB_MIXER_BOOLEAN },
/* UAC2 specific */
{ "Input Gain Control", USB_MIXER_U16 },
{ "Input Gain Pad Control", USB_MIXER_BOOLEAN },
{ "Phase Inverter Control", USB_MIXER_BOOLEAN },
};
/* private_free callback */
static void usb_mixer_elem_free(struct snd_kcontrol *kctl)
{
kfree(kctl->private_data);
kctl->private_data = NULL;
}
/*
* interface to ALSA control for feature/mixer units
*/
/*
* retrieve the minimum and maximum values for the specified control
*/
static int get_min_max(struct usb_mixer_elem_info *cval, int default_min)
{
/* for failsafe */
cval->min = default_min;
cval->max = cval->min + 1;
cval->res = 1;
cval->dBmin = cval->dBmax = 0;
if (cval->val_type == USB_MIXER_BOOLEAN ||
cval->val_type == USB_MIXER_INV_BOOLEAN) {
cval->initialized = 1;
} else {
int minchn = 0;
if (cval->cmask) {
int i;
for (i = 0; i < MAX_CHANNELS; i++)
if (cval->cmask & (1 << i)) {
minchn = i + 1;
break;
}
}
if (get_ctl_value(cval, UAC_GET_MAX, (cval->control << 8) | minchn, &cval->max) < 0 ||
get_ctl_value(cval, UAC_GET_MIN, (cval->control << 8) | minchn, &cval->min) < 0) {
snd_printd(KERN_ERR "%d:%d: cannot get min/max values for control %d (id %d)\n",
cval->id, cval->mixer->ctrlif, cval->control, cval->id);
return -EINVAL;
}
if (get_ctl_value(cval, UAC_GET_RES, (cval->control << 8) | minchn, &cval->res) < 0) {
cval->res = 1;
} else {
int last_valid_res = cval->res;
while (cval->res > 1) {
if (snd_usb_mixer_set_ctl_value(cval, UAC_SET_RES,
(cval->control << 8) | minchn, cval->res / 2) < 0)
break;
cval->res /= 2;
}
if (get_ctl_value(cval, UAC_GET_RES, (cval->control << 8) | minchn, &cval->res) < 0)
cval->res = last_valid_res;
}
if (cval->res == 0)
cval->res = 1;
/* Additional checks for the proper resolution
*
* Some devices report smaller resolutions than actually
* reacting. They don't return errors but simply clip
* to the lower aligned value.
*/
if (cval->min + cval->res < cval->max) {
int last_valid_res = cval->res;
int saved, test, check;
get_cur_mix_raw(cval, minchn, &saved);
for (;;) {
test = saved;
if (test < cval->max)
test += cval->res;
else
test -= cval->res;
if (test < cval->min || test > cval->max ||
set_cur_mix_value(cval, minchn, 0, test) ||
get_cur_mix_raw(cval, minchn, &check)) {
cval->res = last_valid_res;
break;
}
if (test == check)
break;
cval->res *= 2;
}
set_cur_mix_value(cval, minchn, 0, saved);
}
cval->initialized = 1;
}
/* USB descriptions contain the dB scale in 1/256 dB unit
* while ALSA TLV contains in 1/100 dB unit
*/
cval->dBmin = (convert_signed_value(cval, cval->min) * 100) / 256;
cval->dBmax = (convert_signed_value(cval, cval->max) * 100) / 256;
if (cval->dBmin > cval->dBmax) {
/* something is wrong; assume it's either from/to 0dB */
if (cval->dBmin < 0)
cval->dBmax = 0;
else if (cval->dBmin > 0)
cval->dBmin = 0;
if (cval->dBmin > cval->dBmax) {
/* totally crap, return an error */
return -EINVAL;
}
}
return 0;
}
/* get a feature/mixer unit info */
static int mixer_ctl_feature_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
struct usb_mixer_elem_info *cval = kcontrol->private_data;
if (cval->val_type == USB_MIXER_BOOLEAN ||
cval->val_type == USB_MIXER_INV_BOOLEAN)
uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
else
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = cval->channels;
if (cval->val_type == USB_MIXER_BOOLEAN ||
cval->val_type == USB_MIXER_INV_BOOLEAN) {
uinfo->value.integer.min = 0;
uinfo->value.integer.max = 1;
} else {
if (! cval->initialized)
get_min_max(cval, 0);
uinfo->value.integer.min = 0;
uinfo->value.integer.max =
(cval->max - cval->min + cval->res - 1) / cval->res;
}
return 0;
}
/* get the current value from feature/mixer unit */
static int mixer_ctl_feature_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct usb_mixer_elem_info *cval = kcontrol->private_data;
int c, cnt, val, err;
ucontrol->value.integer.value[0] = cval->min;
if (cval->cmask) {
cnt = 0;
for (c = 0; c < MAX_CHANNELS; c++) {
if (!(cval->cmask & (1 << c)))
continue;
err = get_cur_mix_value(cval, c + 1, cnt, &val);
if (err < 0)
return cval->mixer->ignore_ctl_error ? 0 : err;
val = get_relative_value(cval, val);
ucontrol->value.integer.value[cnt] = val;
cnt++;
}
return 0;
} else {
/* master channel */
err = get_cur_mix_value(cval, 0, 0, &val);
if (err < 0)
return cval->mixer->ignore_ctl_error ? 0 : err;
val = get_relative_value(cval, val);
ucontrol->value.integer.value[0] = val;
}
return 0;
}
/* put the current value to feature/mixer unit */
static int mixer_ctl_feature_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct usb_mixer_elem_info *cval = kcontrol->private_data;
int c, cnt, val, oval, err;
int changed = 0;
if (cval->cmask) {
cnt = 0;
for (c = 0; c < MAX_CHANNELS; c++) {
if (!(cval->cmask & (1 << c)))
continue;
err = get_cur_mix_value(cval, c + 1, cnt, &oval);
if (err < 0)
return cval->mixer->ignore_ctl_error ? 0 : err;
val = ucontrol->value.integer.value[cnt];
val = get_abs_value(cval, val);
if (oval != val) {
set_cur_mix_value(cval, c + 1, cnt, val);
changed = 1;
}
cnt++;
}
} else {
/* master channel */
err = get_cur_mix_value(cval, 0, 0, &oval);
if (err < 0)
return cval->mixer->ignore_ctl_error ? 0 : err;
val = ucontrol->value.integer.value[0];
val = get_abs_value(cval, val);
if (val != oval) {
set_cur_mix_value(cval, 0, 0, val);
changed = 1;
}
}
return changed;
}
static struct snd_kcontrol_new usb_feature_unit_ctl = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "", /* will be filled later manually */
.info = mixer_ctl_feature_info,
.get = mixer_ctl_feature_get,
.put = mixer_ctl_feature_put,
};
/* the read-only variant */
static struct snd_kcontrol_new usb_feature_unit_ctl_ro = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "", /* will be filled later manually */
.info = mixer_ctl_feature_info,
.get = mixer_ctl_feature_get,
.put = NULL,
};
/*
* build a feature control
*/
static size_t append_ctl_name(struct snd_kcontrol *kctl, const char *str)
{
return strlcat(kctl->id.name, str, sizeof(kctl->id.name));
}
static void build_feature_ctl(struct mixer_build *state, void *raw_desc,
unsigned int ctl_mask, int control,
struct usb_audio_term *iterm, int unitid,
int readonly_mask)
{
struct uac_feature_unit_descriptor *desc = raw_desc;
unsigned int len = 0;
int mapped_name = 0;
int nameid = uac_feature_unit_iFeature(desc);
struct snd_kcontrol *kctl;
struct usb_mixer_elem_info *cval;
const struct usbmix_name_map *map;
control++; /* change from zero-based to 1-based value */
if (control == UAC_FU_GRAPHIC_EQUALIZER) {
/* FIXME: not supported yet */
return;
}
map = find_map(state, unitid, control);
if (check_ignored_ctl(map))
return;
cval = kzalloc(sizeof(*cval), GFP_KERNEL);
if (! cval) {
snd_printk(KERN_ERR "cannot malloc kcontrol\n");
return;
}
cval->mixer = state->mixer;
cval->id = unitid;
cval->control = control;
cval->cmask = ctl_mask;
cval->val_type = audio_feature_info[control-1].type;
if (ctl_mask == 0) {
cval->channels = 1; /* master channel */
cval->master_readonly = readonly_mask;
} else {
int i, c = 0;
for (i = 0; i < 16; i++)
if (ctl_mask & (1 << i))
c++;
cval->channels = c;
cval->ch_readonly = readonly_mask;
}
/* get min/max values */
get_min_max(cval, 0);
/* if all channels in the mask are marked read-only, make the control
* read-only. set_cur_mix_value() will check the mask again and won't
* issue write commands to read-only channels. */
if (cval->channels == readonly_mask)
kctl = snd_ctl_new1(&usb_feature_unit_ctl_ro, cval);
else
kctl = snd_ctl_new1(&usb_feature_unit_ctl, cval);
if (! kctl) {
snd_printk(KERN_ERR "cannot malloc kcontrol\n");
kfree(cval);
return;
}
kctl->private_free = usb_mixer_elem_free;
len = check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name));
mapped_name = len != 0;
if (! len && nameid)
len = snd_usb_copy_string_desc(state, nameid,
kctl->id.name, sizeof(kctl->id.name));
switch (control) {
case UAC_FU_MUTE:
case UAC_FU_VOLUME:
/* determine the control name. the rule is:
* - if a name id is given in descriptor, use it.
* - if the connected input can be determined, then use the name
* of terminal type.
* - if the connected output can be determined, use it.
* - otherwise, anonymous name.
*/
if (! len) {
len = get_term_name(state, iterm, kctl->id.name, sizeof(kctl->id.name), 1);
if (! len)
len = get_term_name(state, &state->oterm, kctl->id.name, sizeof(kctl->id.name), 1);
if (! len)
len = snprintf(kctl->id.name, sizeof(kctl->id.name),
"Feature %d", unitid);
}
/* determine the stream direction:
* if the connected output is USB stream, then it's likely a
* capture stream. otherwise it should be playback (hopefully :)
*/
if (! mapped_name && ! (state->oterm.type >> 16)) {
if ((state->oterm.type & 0xff00) == 0x0100) {
len = append_ctl_name(kctl, " Capture");
} else {
len = append_ctl_name(kctl, " Playback");
}
}
append_ctl_name(kctl, control == UAC_FU_MUTE ?
" Switch" : " Volume");
if (control == UAC_FU_VOLUME) {
kctl->tlv.c = mixer_vol_tlv;
kctl->vd[0].access |=
SNDRV_CTL_ELEM_ACCESS_TLV_READ |
SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK;
check_mapped_dB(map, cval);
}
break;
default:
if (! len)
strlcpy(kctl->id.name, audio_feature_info[control-1].name,
sizeof(kctl->id.name));
break;
}
/* volume control quirks */
switch (state->chip->usb_id) {
case USB_ID(0x0471, 0x0101):
case USB_ID(0x0471, 0x0104):
case USB_ID(0x0471, 0x0105):
case USB_ID(0x0672, 0x1041):
/* quirk for UDA1321/N101.
* note that detection between firmware 2.1.1.7 (N101)
* and later 2.1.1.21 is not very clear from datasheets.
* I hope that the min value is -15360 for newer firmware --jk
*/
if (!strcmp(kctl->id.name, "PCM Playback Volume") &&
cval->min == -15616) {
snd_printk(KERN_INFO
"set volume quirk for UDA1321/N101 chip\n");
cval->max = -256;
}
break;
case USB_ID(0x046d, 0x09a4):
if (!strcmp(kctl->id.name, "Mic Capture Volume")) {
snd_printk(KERN_INFO
"set volume quirk for QuickCam E3500\n");
cval->min = 6080;
cval->max = 8768;
cval->res = 192;
}
break;
case USB_ID(0x046d, 0x0809):
case USB_ID(0x046d, 0x0991):
/* Most audio usb devices lie about volume resolution.
* Most Logitech webcams have res = 384.
* Proboly there is some logitech magic behind this number --fishor
*/
if (!strcmp(kctl->id.name, "Mic Capture Volume")) {
snd_printk(KERN_INFO
"set resolution quirk: cval->res = 384\n");
cval->res = 384;
}
break;
}
snd_printdd(KERN_INFO "[%d] FU [%s] ch = %d, val = %d/%d/%d\n",
cval->id, kctl->id.name, cval->channels, cval->min, cval->max, cval->res);
add_control_to_empty(state, kctl);
}
/*
* parse a feature unit
*
* most of controlls are defined here.
*/
static int parse_audio_feature_unit(struct mixer_build *state, int unitid, void *_ftr)
{
int channels, i, j;
struct usb_audio_term iterm;
unsigned int master_bits, first_ch_bits;
int err, csize;
struct uac_feature_unit_descriptor *hdr = _ftr;
__u8 *bmaControls;
if (state->mixer->protocol == UAC_VERSION_1) {
csize = hdr->bControlSize;
channels = (hdr->bLength - 7) / csize - 1;
bmaControls = hdr->bmaControls;
} else {
struct uac2_feature_unit_descriptor *ftr = _ftr;
csize = 4;
channels = (hdr->bLength - 6) / 4 - 1;
bmaControls = ftr->bmaControls;
}
if (hdr->bLength < 7 || !csize || hdr->bLength < 7 + csize) {
snd_printk(KERN_ERR "usbaudio: unit %u: invalid UAC_FEATURE_UNIT descriptor\n", unitid);
return -EINVAL;
}
/* parse the source unit */
if ((err = parse_audio_unit(state, hdr->bSourceID)) < 0)
return err;
/* determine the input source type and name */
if (check_input_term(state, hdr->bSourceID, &iterm) < 0)
return -EINVAL;
master_bits = snd_usb_combine_bytes(bmaControls, csize);
/* master configuration quirks */
switch (state->chip->usb_id) {
case USB_ID(0x08bb, 0x2702):
snd_printk(KERN_INFO
"usbmixer: master volume quirk for PCM2702 chip\n");
/* disable non-functional volume control */
master_bits &= ~UAC_CONTROL_BIT(UAC_FU_VOLUME);
break;
}
if (channels > 0)
first_ch_bits = snd_usb_combine_bytes(bmaControls + csize, csize);
else
first_ch_bits = 0;
if (state->mixer->protocol == UAC_VERSION_1) {
/* check all control types */
for (i = 0; i < 10; i++) {
unsigned int ch_bits = 0;
for (j = 0; j < channels; j++) {
unsigned int mask = snd_usb_combine_bytes(bmaControls + csize * (j+1), csize);
if (mask & (1 << i))
ch_bits |= (1 << j);
}
/* audio class v1 controls are never read-only */
if (ch_bits & 1) /* the first channel must be set (for ease of programming) */
build_feature_ctl(state, _ftr, ch_bits, i, &iterm, unitid, 0);
if (master_bits & (1 << i))
build_feature_ctl(state, _ftr, 0, i, &iterm, unitid, 0);
}
} else { /* UAC_VERSION_2 */
for (i = 0; i < 30/2; i++) {
/* From the USB Audio spec v2.0:
bmaControls() is a (ch+1)-element array of 4-byte bitmaps,
each containing a set of bit pairs. If a Control is present,
it must be Host readable. If a certain Control is not
present then the bit pair must be set to 0b00.
If a Control is present but read-only, the bit pair must be
set to 0b01. If a Control is also Host programmable, the bit
pair must be set to 0b11. The value 0b10 is not allowed. */
unsigned int ch_bits = 0;
unsigned int ch_read_only = 0;
for (j = 0; j < channels; j++) {
unsigned int mask = snd_usb_combine_bytes(bmaControls + csize * (j+1), csize);
if (uac2_control_is_readable(mask, i)) {
ch_bits |= (1 << j);
if (!uac2_control_is_writeable(mask, i))
ch_read_only |= (1 << j);
}
}
/* NOTE: build_feature_ctl() will mark the control read-only if all channels
* are marked read-only in the descriptors. Otherwise, the control will be
* reported as writeable, but the driver will not actually issue a write
* command for read-only channels */
if (ch_bits & 1) /* the first channel must be set (for ease of programming) */
build_feature_ctl(state, _ftr, ch_bits, i, &iterm, unitid, ch_read_only);
if (uac2_control_is_readable(master_bits, i))
build_feature_ctl(state, _ftr, 0, i, &iterm, unitid,
!uac2_control_is_writeable(master_bits, i));
}
}
return 0;
}
/*
* Mixer Unit
*/
/*
* build a mixer unit control
*
* the callbacks are identical with feature unit.
* input channel number (zero based) is given in control field instead.
*/
static void build_mixer_unit_ctl(struct mixer_build *state,
struct uac_mixer_unit_descriptor *desc,
int in_pin, int in_ch, int unitid,
struct usb_audio_term *iterm)
{
struct usb_mixer_elem_info *cval;
unsigned int num_outs = uac_mixer_unit_bNrChannels(desc);
unsigned int i, len;
struct snd_kcontrol *kctl;
const struct usbmix_name_map *map;
map = find_map(state, unitid, 0);
if (check_ignored_ctl(map))
return;
cval = kzalloc(sizeof(*cval), GFP_KERNEL);
if (! cval)
return;
cval->mixer = state->mixer;
cval->id = unitid;
cval->control = in_ch + 1; /* based on 1 */
cval->val_type = USB_MIXER_S16;
for (i = 0; i < num_outs; i++) {
if (check_matrix_bitmap(uac_mixer_unit_bmControls(desc, state->mixer->protocol), in_ch, i, num_outs)) {
cval->cmask |= (1 << i);
cval->channels++;
}
}
/* get min/max values */
get_min_max(cval, 0);
kctl = snd_ctl_new1(&usb_feature_unit_ctl, cval);
if (! kctl) {
snd_printk(KERN_ERR "cannot malloc kcontrol\n");
kfree(cval);
return;
}
kctl->private_free = usb_mixer_elem_free;
len = check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name));
if (! len)
len = get_term_name(state, iterm, kctl->id.name, sizeof(kctl->id.name), 0);
if (! len)
len = sprintf(kctl->id.name, "Mixer Source %d", in_ch + 1);
append_ctl_name(kctl, " Volume");
snd_printdd(KERN_INFO "[%d] MU [%s] ch = %d, val = %d/%d\n",
cval->id, kctl->id.name, cval->channels, cval->min, cval->max);
add_control_to_empty(state, kctl);
}
/*
* parse a mixer unit
*/
static int parse_audio_mixer_unit(struct mixer_build *state, int unitid, void *raw_desc)
{
struct uac_mixer_unit_descriptor *desc = raw_desc;
struct usb_audio_term iterm;
int input_pins, num_ins, num_outs;
int pin, ich, err;
if (desc->bLength < 11 || ! (input_pins = desc->bNrInPins) || ! (num_outs = uac_mixer_unit_bNrChannels(desc))) {
snd_printk(KERN_ERR "invalid MIXER UNIT descriptor %d\n", unitid);
return -EINVAL;
}
/* no bmControls field (e.g. Maya44) -> ignore */
if (desc->bLength <= 10 + input_pins) {
snd_printdd(KERN_INFO "MU %d has no bmControls field\n", unitid);
return 0;
}
num_ins = 0;
ich = 0;
for (pin = 0; pin < input_pins; pin++) {
err = parse_audio_unit(state, desc->baSourceID[pin]);
if (err < 0)
return err;
err = check_input_term(state, desc->baSourceID[pin], &iterm);
if (err < 0)
return err;
num_ins += iterm.channels;
for (; ich < num_ins; ++ich) {
int och, ich_has_controls = 0;
for (och = 0; och < num_outs; ++och) {
if (check_matrix_bitmap(uac_mixer_unit_bmControls(desc, state->mixer->protocol),
ich, och, num_outs)) {
ich_has_controls = 1;
break;
}
}
if (ich_has_controls)
build_mixer_unit_ctl(state, desc, pin, ich,
unitid, &iterm);
}
}
return 0;
}
/*
* Processing Unit / Extension Unit
*/
/* get callback for processing/extension unit */
static int mixer_ctl_procunit_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct usb_mixer_elem_info *cval = kcontrol->private_data;
int err, val;
err = get_cur_ctl_value(cval, cval->control << 8, &val);
if (err < 0 && cval->mixer->ignore_ctl_error) {
ucontrol->value.integer.value[0] = cval->min;
return 0;
}
if (err < 0)
return err;
val = get_relative_value(cval, val);
ucontrol->value.integer.value[0] = val;
return 0;
}
/* put callback for processing/extension unit */
static int mixer_ctl_procunit_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct usb_mixer_elem_info *cval = kcontrol->private_data;
int val, oval, err;
err = get_cur_ctl_value(cval, cval->control << 8, &oval);
if (err < 0) {
if (cval->mixer->ignore_ctl_error)
return 0;
return err;
}
val = ucontrol->value.integer.value[0];
val = get_abs_value(cval, val);
if (val != oval) {
set_cur_ctl_value(cval, cval->control << 8, val);
return 1;
}
return 0;
}
/* alsa control interface for processing/extension unit */
static struct snd_kcontrol_new mixer_procunit_ctl = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "", /* will be filled later */
.info = mixer_ctl_feature_info,
.get = mixer_ctl_procunit_get,
.put = mixer_ctl_procunit_put,
};
/*
* predefined data for processing units
*/
struct procunit_value_info {
int control;
char *suffix;
int val_type;
int min_value;
};
struct procunit_info {
int type;
char *name;
struct procunit_value_info *values;
};
static struct procunit_value_info updown_proc_info[] = {
{ UAC_UD_ENABLE, "Switch", USB_MIXER_BOOLEAN },
{ UAC_UD_MODE_SELECT, "Mode Select", USB_MIXER_U8, 1 },
{ 0 }
};
static struct procunit_value_info prologic_proc_info[] = {
{ UAC_DP_ENABLE, "Switch", USB_MIXER_BOOLEAN },
{ UAC_DP_MODE_SELECT, "Mode Select", USB_MIXER_U8, 1 },
{ 0 }
};
static struct procunit_value_info threed_enh_proc_info[] = {
{ UAC_3D_ENABLE, "Switch", USB_MIXER_BOOLEAN },
{ UAC_3D_SPACE, "Spaciousness", USB_MIXER_U8 },
{ 0 }
};
static struct procunit_value_info reverb_proc_info[] = {
{ UAC_REVERB_ENABLE, "Switch", USB_MIXER_BOOLEAN },
{ UAC_REVERB_LEVEL, "Level", USB_MIXER_U8 },
{ UAC_REVERB_TIME, "Time", USB_MIXER_U16 },
{ UAC_REVERB_FEEDBACK, "Feedback", USB_MIXER_U8 },
{ 0 }
};
static struct procunit_value_info chorus_proc_info[] = {
{ UAC_CHORUS_ENABLE, "Switch", USB_MIXER_BOOLEAN },
{ UAC_CHORUS_LEVEL, "Level", USB_MIXER_U8 },
{ UAC_CHORUS_RATE, "Rate", USB_MIXER_U16 },
{ UAC_CHORUS_DEPTH, "Depth", USB_MIXER_U16 },
{ 0 }
};
static struct procunit_value_info dcr_proc_info[] = {
{ UAC_DCR_ENABLE, "Switch", USB_MIXER_BOOLEAN },
{ UAC_DCR_RATE, "Ratio", USB_MIXER_U16 },
{ UAC_DCR_MAXAMPL, "Max Amp", USB_MIXER_S16 },
{ UAC_DCR_THRESHOLD, "Threshold", USB_MIXER_S16 },
{ UAC_DCR_ATTACK_TIME, "Attack Time", USB_MIXER_U16 },
{ UAC_DCR_RELEASE_TIME, "Release Time", USB_MIXER_U16 },
{ 0 }
};
static struct procunit_info procunits[] = {
{ UAC_PROCESS_UP_DOWNMIX, "Up Down", updown_proc_info },
{ UAC_PROCESS_DOLBY_PROLOGIC, "Dolby Prologic", prologic_proc_info },
{ UAC_PROCESS_STEREO_EXTENDER, "3D Stereo Extender", threed_enh_proc_info },
{ UAC_PROCESS_REVERB, "Reverb", reverb_proc_info },
{ UAC_PROCESS_CHORUS, "Chorus", chorus_proc_info },
{ UAC_PROCESS_DYN_RANGE_COMP, "DCR", dcr_proc_info },
{ 0 },
};
/*
* predefined data for extension units
*/
static struct procunit_value_info clock_rate_xu_info[] = {
{ USB_XU_CLOCK_RATE_SELECTOR, "Selector", USB_MIXER_U8, 0 },
{ 0 }
};
static struct procunit_value_info clock_source_xu_info[] = {
{ USB_XU_CLOCK_SOURCE_SELECTOR, "External", USB_MIXER_BOOLEAN },
{ 0 }
};
static struct procunit_value_info spdif_format_xu_info[] = {
{ USB_XU_DIGITAL_FORMAT_SELECTOR, "SPDIF/AC3", USB_MIXER_BOOLEAN },
{ 0 }
};
static struct procunit_value_info soft_limit_xu_info[] = {
{ USB_XU_SOFT_LIMIT_SELECTOR, " ", USB_MIXER_BOOLEAN },
{ 0 }
};
static struct procunit_info extunits[] = {
{ USB_XU_CLOCK_RATE, "Clock rate", clock_rate_xu_info },
{ USB_XU_CLOCK_SOURCE, "DigitalIn CLK source", clock_source_xu_info },
{ USB_XU_DIGITAL_IO_STATUS, "DigitalOut format:", spdif_format_xu_info },
{ USB_XU_DEVICE_OPTIONS, "AnalogueIn Soft Limit", soft_limit_xu_info },
{ 0 }
};
/*
* build a processing/extension unit
*/
static int build_audio_procunit(struct mixer_build *state, int unitid, void *raw_desc, struct procunit_info *list, char *name)
{
struct uac_processing_unit_descriptor *desc = raw_desc;
int num_ins = desc->bNrInPins;
struct usb_mixer_elem_info *cval;
struct snd_kcontrol *kctl;
int i, err, nameid, type, len;
struct procunit_info *info;
struct procunit_value_info *valinfo;
const struct usbmix_name_map *map;
static struct procunit_value_info default_value_info[] = {
{ 0x01, "Switch", USB_MIXER_BOOLEAN },
{ 0 }
};
static struct procunit_info default_info = {
0, NULL, default_value_info
};
if (desc->bLength < 13 || desc->bLength < 13 + num_ins ||
desc->bLength < num_ins + uac_processing_unit_bControlSize(desc, state->mixer->protocol)) {
snd_printk(KERN_ERR "invalid %s descriptor (id %d)\n", name, unitid);
return -EINVAL;
}
for (i = 0; i < num_ins; i++) {
if ((err = parse_audio_unit(state, desc->baSourceID[i])) < 0)
return err;
}
type = le16_to_cpu(desc->wProcessType);
for (info = list; info && info->type; info++)
if (info->type == type)
break;
if (! info || ! info->type)
info = &default_info;
for (valinfo = info->values; valinfo->control; valinfo++) {
__u8 *controls = uac_processing_unit_bmControls(desc, state->mixer->protocol);
if (! (controls[valinfo->control / 8] & (1 << ((valinfo->control % 8) - 1))))
continue;
map = find_map(state, unitid, valinfo->control);
if (check_ignored_ctl(map))
continue;
cval = kzalloc(sizeof(*cval), GFP_KERNEL);
if (! cval) {
snd_printk(KERN_ERR "cannot malloc kcontrol\n");
return -ENOMEM;
}
cval->mixer = state->mixer;
cval->id = unitid;
cval->control = valinfo->control;
cval->val_type = valinfo->val_type;
cval->channels = 1;
/* get min/max values */
if (type == UAC_PROCESS_UP_DOWNMIX && cval->control == UAC_UD_MODE_SELECT) {
__u8 *control_spec = uac_processing_unit_specific(desc, state->mixer->protocol);
/* FIXME: hard-coded */
cval->min = 1;
cval->max = control_spec[0];
cval->res = 1;
cval->initialized = 1;
} else {
if (type == USB_XU_CLOCK_RATE) {
/* E-Mu USB 0404/0202/TrackerPre
* samplerate control quirk
*/
cval->min = 0;
cval->max = 5;
cval->res = 1;
cval->initialized = 1;
} else
get_min_max(cval, valinfo->min_value);
}
kctl = snd_ctl_new1(&mixer_procunit_ctl, cval);
if (! kctl) {
snd_printk(KERN_ERR "cannot malloc kcontrol\n");
kfree(cval);
return -ENOMEM;
}
kctl->private_free = usb_mixer_elem_free;
if (check_mapped_name(map, kctl->id.name,
sizeof(kctl->id.name)))
/* nothing */ ;
else if (info->name)
strlcpy(kctl->id.name, info->name, sizeof(kctl->id.name));
else {
nameid = uac_processing_unit_iProcessing(desc, state->mixer->protocol);
len = 0;
if (nameid)
len = snd_usb_copy_string_desc(state, nameid, kctl->id.name, sizeof(kctl->id.name));
if (! len)
strlcpy(kctl->id.name, name, sizeof(kctl->id.name));
}
append_ctl_name(kctl, " ");
append_ctl_name(kctl, valinfo->suffix);
snd_printdd(KERN_INFO "[%d] PU [%s] ch = %d, val = %d/%d\n",
cval->id, kctl->id.name, cval->channels, cval->min, cval->max);
if ((err = add_control_to_empty(state, kctl)) < 0)
return err;
}
return 0;
}
static int parse_audio_processing_unit(struct mixer_build *state, int unitid, void *raw_desc)
{
return build_audio_procunit(state, unitid, raw_desc, procunits, "Processing Unit");
}
static int parse_audio_extension_unit(struct mixer_build *state, int unitid, void *raw_desc)
{
/* Note that we parse extension units with processing unit descriptors.
* That's ok as the layout is the same */
return build_audio_procunit(state, unitid, raw_desc, extunits, "Extension Unit");
}
/*
* Selector Unit
*/
/* info callback for selector unit
* use an enumerator type for routing
*/
static int mixer_ctl_selector_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
struct usb_mixer_elem_info *cval = kcontrol->private_data;
char **itemlist = (char **)kcontrol->private_value;
if (snd_BUG_ON(!itemlist))
return -EINVAL;
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = cval->max;
if ((int)uinfo->value.enumerated.item >= cval->max)
uinfo->value.enumerated.item = cval->max - 1;
strcpy(uinfo->value.enumerated.name, itemlist[uinfo->value.enumerated.item]);
return 0;
}
/* get callback for selector unit */
static int mixer_ctl_selector_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct usb_mixer_elem_info *cval = kcontrol->private_data;
int val, err;
err = get_cur_ctl_value(cval, cval->control << 8, &val);
if (err < 0) {
if (cval->mixer->ignore_ctl_error) {
ucontrol->value.enumerated.item[0] = 0;
return 0;
}
return err;
}
val = get_relative_value(cval, val);
ucontrol->value.enumerated.item[0] = val;
return 0;
}
/* put callback for selector unit */
static int mixer_ctl_selector_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct usb_mixer_elem_info *cval = kcontrol->private_data;
int val, oval, err;
err = get_cur_ctl_value(cval, cval->control << 8, &oval);
if (err < 0) {
if (cval->mixer->ignore_ctl_error)
return 0;
return err;
}
val = ucontrol->value.enumerated.item[0];
val = get_abs_value(cval, val);
if (val != oval) {
set_cur_ctl_value(cval, cval->control << 8, val);
return 1;
}
return 0;
}
/* alsa control interface for selector unit */
static struct snd_kcontrol_new mixer_selectunit_ctl = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "", /* will be filled later */
.info = mixer_ctl_selector_info,
.get = mixer_ctl_selector_get,
.put = mixer_ctl_selector_put,
};
/* private free callback.
* free both private_data and private_value
*/
static void usb_mixer_selector_elem_free(struct snd_kcontrol *kctl)
{
int i, num_ins = 0;
if (kctl->private_data) {
struct usb_mixer_elem_info *cval = kctl->private_data;
num_ins = cval->max;
kfree(cval);
kctl->private_data = NULL;
}
if (kctl->private_value) {
char **itemlist = (char **)kctl->private_value;
for (i = 0; i < num_ins; i++)
kfree(itemlist[i]);
kfree(itemlist);
kctl->private_value = 0;
}
}
/*
* parse a selector unit
*/
static int parse_audio_selector_unit(struct mixer_build *state, int unitid, void *raw_desc)
{
struct uac_selector_unit_descriptor *desc = raw_desc;
unsigned int i, nameid, len;
int err;
struct usb_mixer_elem_info *cval;
struct snd_kcontrol *kctl;
const struct usbmix_name_map *map;
char **namelist;
if (!desc->bNrInPins || desc->bLength < 5 + desc->bNrInPins) {
snd_printk(KERN_ERR "invalid SELECTOR UNIT descriptor %d\n", unitid);
return -EINVAL;
}
for (i = 0; i < desc->bNrInPins; i++) {
if ((err = parse_audio_unit(state, desc->baSourceID[i])) < 0)
return err;
}
if (desc->bNrInPins == 1) /* only one ? nonsense! */
return 0;
map = find_map(state, unitid, 0);
if (check_ignored_ctl(map))
return 0;
cval = kzalloc(sizeof(*cval), GFP_KERNEL);
if (! cval) {
snd_printk(KERN_ERR "cannot malloc kcontrol\n");
return -ENOMEM;
}
cval->mixer = state->mixer;
cval->id = unitid;
cval->val_type = USB_MIXER_U8;
cval->channels = 1;
cval->min = 1;
cval->max = desc->bNrInPins;
cval->res = 1;
cval->initialized = 1;
if (desc->bDescriptorSubtype == UAC2_CLOCK_SELECTOR)
cval->control = UAC2_CX_CLOCK_SELECTOR;
else
cval->control = 0;
namelist = kmalloc(sizeof(char *) * desc->bNrInPins, GFP_KERNEL);
if (! namelist) {
snd_printk(KERN_ERR "cannot malloc\n");
kfree(cval);
return -ENOMEM;
}
#define MAX_ITEM_NAME_LEN 64
for (i = 0; i < desc->bNrInPins; i++) {
struct usb_audio_term iterm;
len = 0;
namelist[i] = kmalloc(MAX_ITEM_NAME_LEN, GFP_KERNEL);
if (! namelist[i]) {
snd_printk(KERN_ERR "cannot malloc\n");
while (i--)
kfree(namelist[i]);
kfree(namelist);
kfree(cval);
return -ENOMEM;
}
len = check_mapped_selector_name(state, unitid, i, namelist[i],
MAX_ITEM_NAME_LEN);
if (! len && check_input_term(state, desc->baSourceID[i], &iterm) >= 0)
len = get_term_name(state, &iterm, namelist[i], MAX_ITEM_NAME_LEN, 0);
if (! len)
sprintf(namelist[i], "Input %d", i);
}
kctl = snd_ctl_new1(&mixer_selectunit_ctl, cval);
if (! kctl) {
snd_printk(KERN_ERR "cannot malloc kcontrol\n");
kfree(namelist);
kfree(cval);
return -ENOMEM;
}
kctl->private_value = (unsigned long)namelist;
kctl->private_free = usb_mixer_selector_elem_free;
nameid = uac_selector_unit_iSelector(desc);
len = check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name));
if (len)
;
else if (nameid)
snd_usb_copy_string_desc(state, nameid, kctl->id.name, sizeof(kctl->id.name));
else {
len = get_term_name(state, &state->oterm,
kctl->id.name, sizeof(kctl->id.name), 0);
if (! len)
strlcpy(kctl->id.name, "USB", sizeof(kctl->id.name));
if (desc->bDescriptorSubtype == UAC2_CLOCK_SELECTOR)
append_ctl_name(kctl, " Clock Source");
else if ((state->oterm.type & 0xff00) == 0x0100)
append_ctl_name(kctl, " Capture Source");
else
append_ctl_name(kctl, " Playback Source");
}
snd_printdd(KERN_INFO "[%d] SU [%s] items = %d\n",
cval->id, kctl->id.name, desc->bNrInPins);
if ((err = add_control_to_empty(state, kctl)) < 0)
return err;
return 0;
}
/*
* parse an audio unit recursively
*/
static int parse_audio_unit(struct mixer_build *state, int unitid)
{
unsigned char *p1;
if (test_and_set_bit(unitid, state->unitbitmap))
return 0; /* the unit already visited */
p1 = find_audio_control_unit(state, unitid);
if (!p1) {
snd_printk(KERN_ERR "usbaudio: unit %d not found!\n", unitid);
return -EINVAL;
}
switch (p1[2]) {
case UAC_INPUT_TERMINAL:
case UAC2_CLOCK_SOURCE:
return 0; /* NOP */
case UAC_MIXER_UNIT:
return parse_audio_mixer_unit(state, unitid, p1);
case UAC_SELECTOR_UNIT:
case UAC2_CLOCK_SELECTOR:
return parse_audio_selector_unit(state, unitid, p1);
case UAC_FEATURE_UNIT:
return parse_audio_feature_unit(state, unitid, p1);
case UAC_PROCESSING_UNIT_V1:
/* UAC2_EFFECT_UNIT has the same value */
if (state->mixer->protocol == UAC_VERSION_1)
return parse_audio_processing_unit(state, unitid, p1);
else
return 0; /* FIXME - effect units not implemented yet */
case UAC_EXTENSION_UNIT_V1:
/* UAC2_PROCESSING_UNIT_V2 has the same value */
if (state->mixer->protocol == UAC_VERSION_1)
return parse_audio_extension_unit(state, unitid, p1);
else /* UAC_VERSION_2 */
return parse_audio_processing_unit(state, unitid, p1);
default:
snd_printk(KERN_ERR "usbaudio: unit %u: unexpected type 0x%02x\n", unitid, p1[2]);
return -EINVAL;
}
}
static void snd_usb_mixer_free(struct usb_mixer_interface *mixer)
{
kfree(mixer->id_elems);
if (mixer->urb) {
kfree(mixer->urb->transfer_buffer);
usb_free_urb(mixer->urb);
}
usb_free_urb(mixer->rc_urb);
kfree(mixer->rc_setup_packet);
kfree(mixer);
}
static int snd_usb_mixer_dev_free(struct snd_device *device)
{
struct usb_mixer_interface *mixer = device->device_data;
snd_usb_mixer_free(mixer);
return 0;
}
/*
* create mixer controls
*
* walk through all UAC_OUTPUT_TERMINAL descriptors to search for mixers
*/
static int snd_usb_mixer_controls(struct usb_mixer_interface *mixer)
{
struct mixer_build state;
int err;
const struct usbmix_ctl_map *map;
struct usb_host_interface *hostif;
void *p;
hostif = &usb_ifnum_to_if(mixer->chip->dev, mixer->ctrlif)->altsetting[0];
memset(&state, 0, sizeof(state));
state.chip = mixer->chip;
state.mixer = mixer;
state.buffer = hostif->extra;
state.buflen = hostif->extralen;
/* check the mapping table */
for (map = usbmix_ctl_maps; map->id; map++) {
if (map->id == state.chip->usb_id) {
state.map = map->map;
state.selector_map = map->selector_map;
mixer->ignore_ctl_error = map->ignore_ctl_error;
break;
}
}
p = NULL;
while ((p = snd_usb_find_csint_desc(hostif->extra, hostif->extralen, p, UAC_OUTPUT_TERMINAL)) != NULL) {
if (mixer->protocol == UAC_VERSION_1) {
struct uac_output_terminal_descriptor_v1 *desc = p;
if (desc->bLength < sizeof(*desc))
continue; /* invalid descriptor? */
set_bit(desc->bTerminalID, state.unitbitmap); /* mark terminal ID as visited */
state.oterm.id = desc->bTerminalID;
state.oterm.type = le16_to_cpu(desc->wTerminalType);
state.oterm.name = desc->iTerminal;
err = parse_audio_unit(&state, desc->bSourceID);
if (err < 0)
return err;
} else { /* UAC_VERSION_2 */
struct uac2_output_terminal_descriptor *desc = p;
if (desc->bLength < sizeof(*desc))
continue; /* invalid descriptor? */
set_bit(desc->bTerminalID, state.unitbitmap); /* mark terminal ID as visited */
state.oterm.id = desc->bTerminalID;
state.oterm.type = le16_to_cpu(desc->wTerminalType);
state.oterm.name = desc->iTerminal;
err = parse_audio_unit(&state, desc->bSourceID);
if (err < 0)
return err;
/* for UAC2, use the same approach to also add the clock selectors */
err = parse_audio_unit(&state, desc->bCSourceID);
if (err < 0)
return err;
}
}
return 0;
}
void snd_usb_mixer_notify_id(struct usb_mixer_interface *mixer, int unitid)
{
struct usb_mixer_elem_info *info;
for (info = mixer->id_elems[unitid]; info; info = info->next_id_elem)
snd_ctl_notify(mixer->chip->card, SNDRV_CTL_EVENT_MASK_VALUE,
info->elem_id);
}
static void snd_usb_mixer_dump_cval(struct snd_info_buffer *buffer,
int unitid,
struct usb_mixer_elem_info *cval)
{
static char *val_types[] = {"BOOLEAN", "INV_BOOLEAN",
"S8", "U8", "S16", "U16"};
snd_iprintf(buffer, " Unit: %i\n", unitid);
if (cval->elem_id)
snd_iprintf(buffer, " Control: name=\"%s\", index=%i\n",
cval->elem_id->name, cval->elem_id->index);
snd_iprintf(buffer, " Info: id=%i, control=%i, cmask=0x%x, "
"channels=%i, type=\"%s\"\n", cval->id,
cval->control, cval->cmask, cval->channels,
val_types[cval->val_type]);
snd_iprintf(buffer, " Volume: min=%i, max=%i, dBmin=%i, dBmax=%i\n",
cval->min, cval->max, cval->dBmin, cval->dBmax);
}
static void snd_usb_mixer_proc_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_usb_audio *chip = entry->private_data;
struct usb_mixer_interface *mixer;
struct usb_mixer_elem_info *cval;
int unitid;
list_for_each_entry(mixer, &chip->mixer_list, list) {
snd_iprintf(buffer,
"USB Mixer: usb_id=0x%08x, ctrlif=%i, ctlerr=%i\n",
chip->usb_id, mixer->ctrlif,
mixer->ignore_ctl_error);
snd_iprintf(buffer, "Card: %s\n", chip->card->longname);
for (unitid = 0; unitid < MAX_ID_ELEMS; unitid++) {
for (cval = mixer->id_elems[unitid]; cval;
cval = cval->next_id_elem)
snd_usb_mixer_dump_cval(buffer, unitid, cval);
}
}
}
static void snd_usb_mixer_interrupt_v2(struct usb_mixer_interface *mixer,
int attribute, int value, int index)
{
struct usb_mixer_elem_info *info;
__u8 unitid = (index >> 8) & 0xff;
__u8 control = (value >> 8) & 0xff;
__u8 channel = value & 0xff;
if (channel >= MAX_CHANNELS) {
snd_printk(KERN_DEBUG "%s(): bogus channel number %d\n",
__func__, channel);
return;
}
for (info = mixer->id_elems[unitid]; info; info = info->next_id_elem) {
if (info->control != control)
continue;
switch (attribute) {
case UAC2_CS_CUR:
/* invalidate cache, so the value is read from the device */
if (channel)
info->cached &= ~(1 << channel);
else /* master channel */
info->cached = 0;
snd_ctl_notify(mixer->chip->card, SNDRV_CTL_EVENT_MASK_VALUE,
info->elem_id);
break;
case UAC2_CS_RANGE:
/* TODO */
break;
case UAC2_CS_MEM:
/* TODO */
break;
default:
snd_printk(KERN_DEBUG "unknown attribute %d in interrupt\n",
attribute);
break;
} /* switch */
}
}
static void snd_usb_mixer_interrupt(struct urb *urb)
{
struct usb_mixer_interface *mixer = urb->context;
int len = urb->actual_length;
if (urb->status != 0)
goto requeue;
if (mixer->protocol == UAC_VERSION_1) {
struct uac1_status_word *status;
for (status = urb->transfer_buffer;
len >= sizeof(*status);
len -= sizeof(*status), status++) {
snd_printd(KERN_DEBUG "status interrupt: %02x %02x\n",
status->bStatusType,
status->bOriginator);
/* ignore any notifications not from the control interface */
if ((status->bStatusType & UAC1_STATUS_TYPE_ORIG_MASK) !=
UAC1_STATUS_TYPE_ORIG_AUDIO_CONTROL_IF)
continue;
if (status->bStatusType & UAC1_STATUS_TYPE_MEM_CHANGED)
snd_usb_mixer_rc_memory_change(mixer, status->bOriginator);
else
snd_usb_mixer_notify_id(mixer, status->bOriginator);
}
} else { /* UAC_VERSION_2 */
struct uac2_interrupt_data_msg *msg;
for (msg = urb->transfer_buffer;
len >= sizeof(*msg);
len -= sizeof(*msg), msg++) {
/* drop vendor specific and endpoint requests */
if ((msg->bInfo & UAC2_INTERRUPT_DATA_MSG_VENDOR) ||
(msg->bInfo & UAC2_INTERRUPT_DATA_MSG_EP))
continue;
snd_usb_mixer_interrupt_v2(mixer, msg->bAttribute,
le16_to_cpu(msg->wValue),
le16_to_cpu(msg->wIndex));
}
}
requeue:
if (urb->status != -ENOENT && urb->status != -ECONNRESET) {
urb->dev = mixer->chip->dev;
usb_submit_urb(urb, GFP_ATOMIC);
}
}
/* create the handler for the optional status interrupt endpoint */
static int snd_usb_mixer_status_create(struct usb_mixer_interface *mixer)
{
struct usb_host_interface *hostif;
struct usb_endpoint_descriptor *ep;
void *transfer_buffer;
int buffer_length;
unsigned int epnum;
hostif = &usb_ifnum_to_if(mixer->chip->dev, mixer->ctrlif)->altsetting[0];
/* we need one interrupt input endpoint */
if (get_iface_desc(hostif)->bNumEndpoints < 1)
return 0;
ep = get_endpoint(hostif, 0);
if (!usb_endpoint_dir_in(ep) || !usb_endpoint_xfer_int(ep))
return 0;
epnum = usb_endpoint_num(ep);
buffer_length = le16_to_cpu(ep->wMaxPacketSize);
transfer_buffer = kmalloc(buffer_length, GFP_KERNEL);
if (!transfer_buffer)
return -ENOMEM;
mixer->urb = usb_alloc_urb(0, GFP_KERNEL);
if (!mixer->urb) {
kfree(transfer_buffer);
return -ENOMEM;
}
usb_fill_int_urb(mixer->urb, mixer->chip->dev,
usb_rcvintpipe(mixer->chip->dev, epnum),
transfer_buffer, buffer_length,
snd_usb_mixer_interrupt, mixer, ep->bInterval);
usb_submit_urb(mixer->urb, GFP_KERNEL);
return 0;
}
int snd_usb_create_mixer(struct snd_usb_audio *chip, int ctrlif,
int ignore_error)
{
static struct snd_device_ops dev_ops = {
.dev_free = snd_usb_mixer_dev_free
};
struct usb_mixer_interface *mixer;
struct snd_info_entry *entry;
struct usb_host_interface *host_iface;
int err;
strcpy(chip->card->mixername, "USB Mixer");
mixer = kzalloc(sizeof(*mixer), GFP_KERNEL);
if (!mixer)
return -ENOMEM;
mixer->chip = chip;
mixer->ctrlif = ctrlif;
mixer->ignore_ctl_error = ignore_error;
mixer->id_elems = kcalloc(MAX_ID_ELEMS, sizeof(*mixer->id_elems),
GFP_KERNEL);
if (!mixer->id_elems) {
kfree(mixer);
return -ENOMEM;
}
host_iface = &usb_ifnum_to_if(chip->dev, ctrlif)->altsetting[0];
switch (get_iface_desc(host_iface)->bInterfaceProtocol) {
case UAC_VERSION_1:
default:
mixer->protocol = UAC_VERSION_1;
break;
case UAC_VERSION_2:
mixer->protocol = UAC_VERSION_2;
break;
}
if ((err = snd_usb_mixer_controls(mixer)) < 0 ||
(err = snd_usb_mixer_status_create(mixer)) < 0)
goto _error;
snd_usb_mixer_apply_create_quirk(mixer);
err = snd_device_new(chip->card, SNDRV_DEV_LOWLEVEL, mixer, &dev_ops);
if (err < 0)
goto _error;
if (list_empty(&chip->mixer_list) &&
!snd_card_proc_new(chip->card, "usbmixer", &entry))
snd_info_set_text_ops(entry, chip, snd_usb_mixer_proc_read);
list_add(&mixer->list, &chip->mixer_list);
return 0;
_error:
snd_usb_mixer_free(mixer);
return err;
}
void snd_usb_mixer_disconnect(struct list_head *p)
{
struct usb_mixer_interface *mixer;
mixer = list_entry(p, struct usb_mixer_interface, list);
usb_kill_urb(mixer->urb);
usb_kill_urb(mixer->rc_urb);
}
| gpl-2.0 |
dmeadows013/Ds_Kernel_Gingerbread | arch/powerpc/kernel/machine_kexec.c | 721 | 5648 | /*
* Code to handle transition of Linux booting another kernel.
*
* Copyright (C) 2002-2003 Eric Biederman <ebiederm@xmission.com>
* GameCube/ppc32 port Copyright (C) 2004 Albert Herranz
* Copyright (C) 2005 IBM Corporation.
*
* This source code is licensed under the GNU General Public License,
* Version 2. See the file COPYING for more details.
*/
#include <linux/kexec.h>
#include <linux/reboot.h>
#include <linux/threads.h>
#include <linux/memblock.h>
#include <linux/of.h>
#include <asm/machdep.h>
#include <asm/prom.h>
#include <asm/sections.h>
void machine_crash_shutdown(struct pt_regs *regs)
{
if (ppc_md.machine_crash_shutdown)
ppc_md.machine_crash_shutdown(regs);
else
default_machine_crash_shutdown(regs);
}
/*
* Do what every setup is needed on image and the
* reboot code buffer to allow us to avoid allocations
* later.
*/
int machine_kexec_prepare(struct kimage *image)
{
if (ppc_md.machine_kexec_prepare)
return ppc_md.machine_kexec_prepare(image);
else
return default_machine_kexec_prepare(image);
}
void machine_kexec_cleanup(struct kimage *image)
{
if (ppc_md.machine_kexec_cleanup)
ppc_md.machine_kexec_cleanup(image);
}
/*
* Do not allocate memory (or fail in any way) in machine_kexec().
* We are past the point of no return, committed to rebooting now.
*/
void machine_kexec(struct kimage *image)
{
if (ppc_md.machine_kexec)
ppc_md.machine_kexec(image);
else
default_machine_kexec(image);
/* Fall back to normal restart if we're still alive. */
machine_restart(NULL);
for(;;);
}
void __init reserve_crashkernel(void)
{
unsigned long long crash_size, crash_base;
int ret;
/* this is necessary because of memblock_phys_mem_size() */
memblock_analyze();
/* use common parsing */
ret = parse_crashkernel(boot_command_line, memblock_phys_mem_size(),
&crash_size, &crash_base);
if (ret == 0 && crash_size > 0) {
crashk_res.start = crash_base;
crashk_res.end = crash_base + crash_size - 1;
}
if (crashk_res.end == crashk_res.start) {
crashk_res.start = crashk_res.end = 0;
return;
}
/* We might have got these values via the command line or the
* device tree, either way sanitise them now. */
crash_size = crashk_res.end - crashk_res.start + 1;
#ifndef CONFIG_RELOCATABLE
if (crashk_res.start != KDUMP_KERNELBASE)
printk("Crash kernel location must be 0x%x\n",
KDUMP_KERNELBASE);
crashk_res.start = KDUMP_KERNELBASE;
#else
if (!crashk_res.start) {
/*
* unspecified address, choose a region of specified size
* can overlap with initrd (ignoring corruption when retained)
* ppc64 requires kernel and some stacks to be in first segemnt
*/
crashk_res.start = KDUMP_KERNELBASE;
}
crash_base = PAGE_ALIGN(crashk_res.start);
if (crash_base != crashk_res.start) {
printk("Crash kernel base must be aligned to 0x%lx\n",
PAGE_SIZE);
crashk_res.start = crash_base;
}
#endif
crash_size = PAGE_ALIGN(crash_size);
crashk_res.end = crashk_res.start + crash_size - 1;
/* The crash region must not overlap the current kernel */
if (overlaps_crashkernel(__pa(_stext), _end - _stext)) {
printk(KERN_WARNING
"Crash kernel can not overlap current kernel\n");
crashk_res.start = crashk_res.end = 0;
return;
}
/* Crash kernel trumps memory limit */
if (memory_limit && memory_limit <= crashk_res.end) {
memory_limit = crashk_res.end + 1;
printk("Adjusted memory limit for crashkernel, now 0x%llx\n",
(unsigned long long)memory_limit);
}
printk(KERN_INFO "Reserving %ldMB of memory at %ldMB "
"for crashkernel (System RAM: %ldMB)\n",
(unsigned long)(crash_size >> 20),
(unsigned long)(crashk_res.start >> 20),
(unsigned long)(memblock_phys_mem_size() >> 20));
memblock_reserve(crashk_res.start, crash_size);
}
int overlaps_crashkernel(unsigned long start, unsigned long size)
{
return (start + size) > crashk_res.start && start <= crashk_res.end;
}
/* Values we need to export to the second kernel via the device tree. */
static unsigned long kernel_end;
static unsigned long crashk_size;
static struct property kernel_end_prop = {
.name = "linux,kernel-end",
.length = sizeof(unsigned long),
.value = &kernel_end,
};
static struct property crashk_base_prop = {
.name = "linux,crashkernel-base",
.length = sizeof(unsigned long),
.value = &crashk_res.start,
};
static struct property crashk_size_prop = {
.name = "linux,crashkernel-size",
.length = sizeof(unsigned long),
.value = &crashk_size,
};
static void __init export_crashk_values(struct device_node *node)
{
struct property *prop;
/* There might be existing crash kernel properties, but we can't
* be sure what's in them, so remove them. */
prop = of_find_property(node, "linux,crashkernel-base", NULL);
if (prop)
prom_remove_property(node, prop);
prop = of_find_property(node, "linux,crashkernel-size", NULL);
if (prop)
prom_remove_property(node, prop);
if (crashk_res.start != 0) {
prom_add_property(node, &crashk_base_prop);
crashk_size = crashk_res.end - crashk_res.start + 1;
prom_add_property(node, &crashk_size_prop);
}
}
static int __init kexec_setup(void)
{
struct device_node *node;
struct property *prop;
node = of_find_node_by_path("/chosen");
if (!node)
return -ENOENT;
/* remove any stale properties so ours can be found */
prop = of_find_property(node, kernel_end_prop.name, NULL);
if (prop)
prom_remove_property(node, prop);
/* information needed by userspace when using default_machine_kexec */
kernel_end = __pa(_end);
prom_add_property(node, &kernel_end_prop);
export_crashk_values(node);
of_node_put(node);
return 0;
}
late_initcall(kexec_setup);
| gpl-2.0 |
Mr-AW/Kernel_TeLo_LP_LenovoA6000 | drivers/acpi/ec.c | 1745 | 28946 | /*
* ec.c - ACPI Embedded Controller Driver (v2.1)
*
* Copyright (C) 2006-2008 Alexey Starikovskiy <astarikovskiy@suse.de>
* Copyright (C) 2006 Denis Sadykov <denis.m.sadykov@intel.com>
* Copyright (C) 2004 Luming Yu <luming.yu@intel.com>
* Copyright (C) 2001, 2002 Andy Grover <andrew.grover@intel.com>
* Copyright (C) 2001, 2002 Paul Diefenbaugh <paul.s.diefenbaugh@intel.com>
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; 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.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
/* Uncomment next line to get verbose printout */
/* #define DEBUG */
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <asm/io.h>
#include <acpi/acpi_bus.h>
#include <acpi/acpi_drivers.h>
#include <linux/dmi.h>
#include "internal.h"
#define ACPI_EC_CLASS "embedded_controller"
#define ACPI_EC_DEVICE_NAME "Embedded Controller"
#define ACPI_EC_FILE_INFO "info"
#undef PREFIX
#define PREFIX "ACPI: EC: "
/* EC status register */
#define ACPI_EC_FLAG_OBF 0x01 /* Output buffer full */
#define ACPI_EC_FLAG_IBF 0x02 /* Input buffer full */
#define ACPI_EC_FLAG_BURST 0x10 /* burst mode */
#define ACPI_EC_FLAG_SCI 0x20 /* EC-SCI occurred */
/* EC commands */
enum ec_command {
ACPI_EC_COMMAND_READ = 0x80,
ACPI_EC_COMMAND_WRITE = 0x81,
ACPI_EC_BURST_ENABLE = 0x82,
ACPI_EC_BURST_DISABLE = 0x83,
ACPI_EC_COMMAND_QUERY = 0x84,
};
#define ACPI_EC_DELAY 500 /* Wait 500ms max. during EC ops */
#define ACPI_EC_UDELAY_GLK 1000 /* Wait 1ms max. to get global lock */
#define ACPI_EC_MSI_UDELAY 550 /* Wait 550us for MSI EC */
enum {
EC_FLAGS_QUERY_PENDING, /* Query is pending */
EC_FLAGS_GPE_STORM, /* GPE storm detected */
EC_FLAGS_HANDLERS_INSTALLED, /* Handlers for GPE and
* OpReg are installed */
EC_FLAGS_BLOCKED, /* Transactions are blocked */
};
/* ec.c is compiled in acpi namespace so this shows up as acpi.ec_delay param */
static unsigned int ec_delay __read_mostly = ACPI_EC_DELAY;
module_param(ec_delay, uint, 0644);
MODULE_PARM_DESC(ec_delay, "Timeout(ms) waited until an EC command completes");
/*
* If the number of false interrupts per one transaction exceeds
* this threshold, will think there is a GPE storm happened and
* will disable the GPE for normal transaction.
*/
static unsigned int ec_storm_threshold __read_mostly = 8;
module_param(ec_storm_threshold, uint, 0644);
MODULE_PARM_DESC(ec_storm_threshold, "Maxim false GPE numbers not considered as GPE storm");
/* If we find an EC via the ECDT, we need to keep a ptr to its context */
/* External interfaces use first EC only, so remember */
typedef int (*acpi_ec_query_func) (void *data);
struct acpi_ec_query_handler {
struct list_head node;
acpi_ec_query_func func;
acpi_handle handle;
void *data;
u8 query_bit;
};
struct transaction {
const u8 *wdata;
u8 *rdata;
unsigned short irq_count;
u8 command;
u8 wi;
u8 ri;
u8 wlen;
u8 rlen;
bool done;
};
struct acpi_ec *boot_ec, *first_ec;
EXPORT_SYMBOL(first_ec);
static int EC_FLAGS_MSI; /* Out-of-spec MSI controller */
static int EC_FLAGS_VALIDATE_ECDT; /* ASUStec ECDTs need to be validated */
static int EC_FLAGS_SKIP_DSDT_SCAN; /* Not all BIOS survive early DSDT scan */
/* --------------------------------------------------------------------------
Transaction Management
-------------------------------------------------------------------------- */
static inline u8 acpi_ec_read_status(struct acpi_ec *ec)
{
u8 x = inb(ec->command_addr);
pr_debug(PREFIX "---> status = 0x%2.2x\n", x);
return x;
}
static inline u8 acpi_ec_read_data(struct acpi_ec *ec)
{
u8 x = inb(ec->data_addr);
pr_debug(PREFIX "---> data = 0x%2.2x\n", x);
return x;
}
static inline void acpi_ec_write_cmd(struct acpi_ec *ec, u8 command)
{
pr_debug(PREFIX "<--- command = 0x%2.2x\n", command);
outb(command, ec->command_addr);
}
static inline void acpi_ec_write_data(struct acpi_ec *ec, u8 data)
{
pr_debug(PREFIX "<--- data = 0x%2.2x\n", data);
outb(data, ec->data_addr);
}
static int ec_transaction_done(struct acpi_ec *ec)
{
unsigned long flags;
int ret = 0;
spin_lock_irqsave(&ec->lock, flags);
if (!ec->curr || ec->curr->done)
ret = 1;
spin_unlock_irqrestore(&ec->lock, flags);
return ret;
}
static void start_transaction(struct acpi_ec *ec)
{
ec->curr->irq_count = ec->curr->wi = ec->curr->ri = 0;
ec->curr->done = false;
acpi_ec_write_cmd(ec, ec->curr->command);
}
static void advance_transaction(struct acpi_ec *ec, u8 status)
{
unsigned long flags;
struct transaction *t;
spin_lock_irqsave(&ec->lock, flags);
t = ec->curr;
if (!t)
goto unlock;
if (t->wlen > t->wi) {
if ((status & ACPI_EC_FLAG_IBF) == 0)
acpi_ec_write_data(ec,
t->wdata[t->wi++]);
else
goto err;
} else if (t->rlen > t->ri) {
if ((status & ACPI_EC_FLAG_OBF) == 1) {
t->rdata[t->ri++] = acpi_ec_read_data(ec);
if (t->rlen == t->ri)
t->done = true;
} else
goto err;
} else if (t->wlen == t->wi &&
(status & ACPI_EC_FLAG_IBF) == 0)
t->done = true;
goto unlock;
err:
/*
* If SCI bit is set, then don't think it's a false IRQ
* otherwise will take a not handled IRQ as a false one.
*/
if (in_interrupt() && !(status & ACPI_EC_FLAG_SCI))
++t->irq_count;
unlock:
spin_unlock_irqrestore(&ec->lock, flags);
}
static int acpi_ec_sync_query(struct acpi_ec *ec);
static int ec_check_sci_sync(struct acpi_ec *ec, u8 state)
{
if (state & ACPI_EC_FLAG_SCI) {
if (!test_and_set_bit(EC_FLAGS_QUERY_PENDING, &ec->flags))
return acpi_ec_sync_query(ec);
}
return 0;
}
static int ec_poll(struct acpi_ec *ec)
{
unsigned long flags;
int repeat = 5; /* number of command restarts */
while (repeat--) {
unsigned long delay = jiffies +
msecs_to_jiffies(ec_delay);
do {
/* don't sleep with disabled interrupts */
if (EC_FLAGS_MSI || irqs_disabled()) {
udelay(ACPI_EC_MSI_UDELAY);
if (ec_transaction_done(ec))
return 0;
} else {
if (wait_event_timeout(ec->wait,
ec_transaction_done(ec),
msecs_to_jiffies(1)))
return 0;
}
advance_transaction(ec, acpi_ec_read_status(ec));
} while (time_before(jiffies, delay));
pr_debug(PREFIX "controller reset, restart transaction\n");
spin_lock_irqsave(&ec->lock, flags);
start_transaction(ec);
spin_unlock_irqrestore(&ec->lock, flags);
}
return -ETIME;
}
static int acpi_ec_transaction_unlocked(struct acpi_ec *ec,
struct transaction *t)
{
unsigned long tmp;
int ret = 0;
if (EC_FLAGS_MSI)
udelay(ACPI_EC_MSI_UDELAY);
/* start transaction */
spin_lock_irqsave(&ec->lock, tmp);
/* following two actions should be kept atomic */
ec->curr = t;
start_transaction(ec);
if (ec->curr->command == ACPI_EC_COMMAND_QUERY)
clear_bit(EC_FLAGS_QUERY_PENDING, &ec->flags);
spin_unlock_irqrestore(&ec->lock, tmp);
ret = ec_poll(ec);
spin_lock_irqsave(&ec->lock, tmp);
ec->curr = NULL;
spin_unlock_irqrestore(&ec->lock, tmp);
return ret;
}
static int ec_check_ibf0(struct acpi_ec *ec)
{
u8 status = acpi_ec_read_status(ec);
return (status & ACPI_EC_FLAG_IBF) == 0;
}
static int ec_wait_ibf0(struct acpi_ec *ec)
{
unsigned long delay = jiffies + msecs_to_jiffies(ec_delay);
/* interrupt wait manually if GPE mode is not active */
while (time_before(jiffies, delay))
if (wait_event_timeout(ec->wait, ec_check_ibf0(ec),
msecs_to_jiffies(1)))
return 0;
return -ETIME;
}
static int acpi_ec_transaction(struct acpi_ec *ec, struct transaction *t)
{
int status;
u32 glk;
if (!ec || (!t) || (t->wlen && !t->wdata) || (t->rlen && !t->rdata))
return -EINVAL;
if (t->rdata)
memset(t->rdata, 0, t->rlen);
mutex_lock(&ec->mutex);
if (test_bit(EC_FLAGS_BLOCKED, &ec->flags)) {
status = -EINVAL;
goto unlock;
}
if (ec->global_lock) {
status = acpi_acquire_global_lock(ACPI_EC_UDELAY_GLK, &glk);
if (ACPI_FAILURE(status)) {
status = -ENODEV;
goto unlock;
}
}
if (ec_wait_ibf0(ec)) {
pr_err(PREFIX "input buffer is not empty, "
"aborting transaction\n");
status = -ETIME;
goto end;
}
pr_debug(PREFIX "transaction start (cmd=0x%02x, addr=0x%02x)\n",
t->command, t->wdata ? t->wdata[0] : 0);
/* disable GPE during transaction if storm is detected */
if (test_bit(EC_FLAGS_GPE_STORM, &ec->flags)) {
/* It has to be disabled, so that it doesn't trigger. */
acpi_disable_gpe(NULL, ec->gpe);
}
status = acpi_ec_transaction_unlocked(ec, t);
/* check if we received SCI during transaction */
ec_check_sci_sync(ec, acpi_ec_read_status(ec));
if (test_bit(EC_FLAGS_GPE_STORM, &ec->flags)) {
msleep(1);
/* It is safe to enable the GPE outside of the transaction. */
acpi_enable_gpe(NULL, ec->gpe);
} else if (t->irq_count > ec_storm_threshold) {
pr_info(PREFIX "GPE storm detected(%d GPEs), "
"transactions will use polling mode\n",
t->irq_count);
set_bit(EC_FLAGS_GPE_STORM, &ec->flags);
}
pr_debug(PREFIX "transaction end\n");
end:
if (ec->global_lock)
acpi_release_global_lock(glk);
unlock:
mutex_unlock(&ec->mutex);
return status;
}
static int acpi_ec_burst_enable(struct acpi_ec *ec)
{
u8 d;
struct transaction t = {.command = ACPI_EC_BURST_ENABLE,
.wdata = NULL, .rdata = &d,
.wlen = 0, .rlen = 1};
return acpi_ec_transaction(ec, &t);
}
static int acpi_ec_burst_disable(struct acpi_ec *ec)
{
struct transaction t = {.command = ACPI_EC_BURST_DISABLE,
.wdata = NULL, .rdata = NULL,
.wlen = 0, .rlen = 0};
return (acpi_ec_read_status(ec) & ACPI_EC_FLAG_BURST) ?
acpi_ec_transaction(ec, &t) : 0;
}
static int acpi_ec_read(struct acpi_ec *ec, u8 address, u8 * data)
{
int result;
u8 d;
struct transaction t = {.command = ACPI_EC_COMMAND_READ,
.wdata = &address, .rdata = &d,
.wlen = 1, .rlen = 1};
result = acpi_ec_transaction(ec, &t);
*data = d;
return result;
}
static int acpi_ec_write(struct acpi_ec *ec, u8 address, u8 data)
{
u8 wdata[2] = { address, data };
struct transaction t = {.command = ACPI_EC_COMMAND_WRITE,
.wdata = wdata, .rdata = NULL,
.wlen = 2, .rlen = 0};
return acpi_ec_transaction(ec, &t);
}
/*
* Externally callable EC access functions. For now, assume 1 EC only
*/
int ec_burst_enable(void)
{
if (!first_ec)
return -ENODEV;
return acpi_ec_burst_enable(first_ec);
}
EXPORT_SYMBOL(ec_burst_enable);
int ec_burst_disable(void)
{
if (!first_ec)
return -ENODEV;
return acpi_ec_burst_disable(first_ec);
}
EXPORT_SYMBOL(ec_burst_disable);
int ec_read(u8 addr, u8 *val)
{
int err;
u8 temp_data;
if (!first_ec)
return -ENODEV;
err = acpi_ec_read(first_ec, addr, &temp_data);
if (!err) {
*val = temp_data;
return 0;
} else
return err;
}
EXPORT_SYMBOL(ec_read);
int ec_write(u8 addr, u8 val)
{
int err;
if (!first_ec)
return -ENODEV;
err = acpi_ec_write(first_ec, addr, val);
return err;
}
EXPORT_SYMBOL(ec_write);
int ec_transaction(u8 command,
const u8 * wdata, unsigned wdata_len,
u8 * rdata, unsigned rdata_len)
{
struct transaction t = {.command = command,
.wdata = wdata, .rdata = rdata,
.wlen = wdata_len, .rlen = rdata_len};
if (!first_ec)
return -ENODEV;
return acpi_ec_transaction(first_ec, &t);
}
EXPORT_SYMBOL(ec_transaction);
/* Get the handle to the EC device */
acpi_handle ec_get_handle(void)
{
if (!first_ec)
return NULL;
return first_ec->handle;
}
EXPORT_SYMBOL(ec_get_handle);
void acpi_ec_block_transactions(void)
{
struct acpi_ec *ec = first_ec;
if (!ec)
return;
mutex_lock(&ec->mutex);
/* Prevent transactions from being carried out */
set_bit(EC_FLAGS_BLOCKED, &ec->flags);
mutex_unlock(&ec->mutex);
}
void acpi_ec_unblock_transactions(void)
{
struct acpi_ec *ec = first_ec;
if (!ec)
return;
mutex_lock(&ec->mutex);
/* Allow transactions to be carried out again */
clear_bit(EC_FLAGS_BLOCKED, &ec->flags);
mutex_unlock(&ec->mutex);
}
void acpi_ec_unblock_transactions_early(void)
{
/*
* Allow transactions to happen again (this function is called from
* atomic context during wakeup, so we don't need to acquire the mutex).
*/
if (first_ec)
clear_bit(EC_FLAGS_BLOCKED, &first_ec->flags);
}
static int acpi_ec_query_unlocked(struct acpi_ec *ec, u8 * data)
{
int result;
u8 d;
struct transaction t = {.command = ACPI_EC_COMMAND_QUERY,
.wdata = NULL, .rdata = &d,
.wlen = 0, .rlen = 1};
if (!ec || !data)
return -EINVAL;
/*
* Query the EC to find out which _Qxx method we need to evaluate.
* Note that successful completion of the query causes the ACPI_EC_SCI
* bit to be cleared (and thus clearing the interrupt source).
*/
result = acpi_ec_transaction_unlocked(ec, &t);
if (result)
return result;
if (!d)
return -ENODATA;
*data = d;
return 0;
}
/* --------------------------------------------------------------------------
Event Management
-------------------------------------------------------------------------- */
int acpi_ec_add_query_handler(struct acpi_ec *ec, u8 query_bit,
acpi_handle handle, acpi_ec_query_func func,
void *data)
{
struct acpi_ec_query_handler *handler =
kzalloc(sizeof(struct acpi_ec_query_handler), GFP_KERNEL);
if (!handler)
return -ENOMEM;
handler->query_bit = query_bit;
handler->handle = handle;
handler->func = func;
handler->data = data;
mutex_lock(&ec->mutex);
list_add(&handler->node, &ec->list);
mutex_unlock(&ec->mutex);
return 0;
}
EXPORT_SYMBOL_GPL(acpi_ec_add_query_handler);
void acpi_ec_remove_query_handler(struct acpi_ec *ec, u8 query_bit)
{
struct acpi_ec_query_handler *handler, *tmp;
mutex_lock(&ec->mutex);
list_for_each_entry_safe(handler, tmp, &ec->list, node) {
if (query_bit == handler->query_bit) {
list_del(&handler->node);
kfree(handler);
}
}
mutex_unlock(&ec->mutex);
}
EXPORT_SYMBOL_GPL(acpi_ec_remove_query_handler);
static void acpi_ec_run(void *cxt)
{
struct acpi_ec_query_handler *handler = cxt;
if (!handler)
return;
pr_debug(PREFIX "start query execution\n");
if (handler->func)
handler->func(handler->data);
else if (handler->handle)
acpi_evaluate_object(handler->handle, NULL, NULL, NULL);
pr_debug(PREFIX "stop query execution\n");
kfree(handler);
}
static int acpi_ec_sync_query(struct acpi_ec *ec)
{
u8 value = 0;
int status;
struct acpi_ec_query_handler *handler, *copy;
if ((status = acpi_ec_query_unlocked(ec, &value)))
return status;
list_for_each_entry(handler, &ec->list, node) {
if (value == handler->query_bit) {
/* have custom handler for this bit */
copy = kmalloc(sizeof(*handler), GFP_KERNEL);
if (!copy)
return -ENOMEM;
memcpy(copy, handler, sizeof(*copy));
pr_debug(PREFIX "push query execution (0x%2x) on queue\n", value);
return acpi_os_execute((copy->func) ?
OSL_NOTIFY_HANDLER : OSL_GPE_HANDLER,
acpi_ec_run, copy);
}
}
return 0;
}
static void acpi_ec_gpe_query(void *ec_cxt)
{
struct acpi_ec *ec = ec_cxt;
if (!ec)
return;
mutex_lock(&ec->mutex);
acpi_ec_sync_query(ec);
mutex_unlock(&ec->mutex);
}
static int ec_check_sci(struct acpi_ec *ec, u8 state)
{
if (state & ACPI_EC_FLAG_SCI) {
if (!test_and_set_bit(EC_FLAGS_QUERY_PENDING, &ec->flags)) {
pr_debug(PREFIX "push gpe query to the queue\n");
return acpi_os_execute(OSL_NOTIFY_HANDLER,
acpi_ec_gpe_query, ec);
}
}
return 0;
}
static u32 acpi_ec_gpe_handler(acpi_handle gpe_device,
u32 gpe_number, void *data)
{
struct acpi_ec *ec = data;
u8 status = acpi_ec_read_status(ec);
pr_debug(PREFIX "~~~> interrupt, status:0x%02x\n", status);
advance_transaction(ec, status);
if (ec_transaction_done(ec) &&
(acpi_ec_read_status(ec) & ACPI_EC_FLAG_IBF) == 0) {
wake_up(&ec->wait);
ec_check_sci(ec, acpi_ec_read_status(ec));
}
return ACPI_INTERRUPT_HANDLED | ACPI_REENABLE_GPE;
}
/* --------------------------------------------------------------------------
Address Space Management
-------------------------------------------------------------------------- */
static acpi_status
acpi_ec_space_handler(u32 function, acpi_physical_address address,
u32 bits, u64 *value64,
void *handler_context, void *region_context)
{
struct acpi_ec *ec = handler_context;
int result = 0, i, bytes = bits / 8;
u8 *value = (u8 *)value64;
if ((address > 0xFF) || !value || !handler_context)
return AE_BAD_PARAMETER;
if (function != ACPI_READ && function != ACPI_WRITE)
return AE_BAD_PARAMETER;
if (EC_FLAGS_MSI || bits > 8)
acpi_ec_burst_enable(ec);
for (i = 0; i < bytes; ++i, ++address, ++value)
result = (function == ACPI_READ) ?
acpi_ec_read(ec, address, value) :
acpi_ec_write(ec, address, *value);
if (EC_FLAGS_MSI || bits > 8)
acpi_ec_burst_disable(ec);
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;
}
}
/* --------------------------------------------------------------------------
Driver Interface
-------------------------------------------------------------------------- */
static acpi_status
ec_parse_io_ports(struct acpi_resource *resource, void *context);
static struct acpi_ec *make_acpi_ec(void)
{
struct acpi_ec *ec = kzalloc(sizeof(struct acpi_ec), GFP_KERNEL);
if (!ec)
return NULL;
ec->flags = 1 << EC_FLAGS_QUERY_PENDING;
mutex_init(&ec->mutex);
init_waitqueue_head(&ec->wait);
INIT_LIST_HEAD(&ec->list);
spin_lock_init(&ec->lock);
return ec;
}
static acpi_status
acpi_ec_register_query_methods(acpi_handle handle, u32 level,
void *context, void **return_value)
{
char node_name[5];
struct acpi_buffer buffer = { sizeof(node_name), node_name };
struct acpi_ec *ec = context;
int value = 0;
acpi_status status;
status = acpi_get_name(handle, ACPI_SINGLE_NAME, &buffer);
if (ACPI_SUCCESS(status) && sscanf(node_name, "_Q%x", &value) == 1) {
acpi_ec_add_query_handler(ec, value, handle, NULL, NULL);
}
return AE_OK;
}
static acpi_status
ec_parse_device(acpi_handle handle, u32 Level, void *context, void **retval)
{
acpi_status status;
unsigned long long tmp = 0;
struct acpi_ec *ec = context;
/* clear addr values, ec_parse_io_ports depend on it */
ec->command_addr = ec->data_addr = 0;
status = acpi_walk_resources(handle, METHOD_NAME__CRS,
ec_parse_io_ports, ec);
if (ACPI_FAILURE(status))
return status;
/* Get GPE bit assignment (EC events). */
/* TODO: Add support for _GPE returning a package */
status = acpi_evaluate_integer(handle, "_GPE", NULL, &tmp);
if (ACPI_FAILURE(status))
return status;
ec->gpe = tmp;
/* Use the global lock for all EC transactions? */
tmp = 0;
acpi_evaluate_integer(handle, "_GLK", NULL, &tmp);
ec->global_lock = tmp;
ec->handle = handle;
return AE_CTRL_TERMINATE;
}
static int ec_install_handlers(struct acpi_ec *ec)
{
acpi_status status;
if (test_bit(EC_FLAGS_HANDLERS_INSTALLED, &ec->flags))
return 0;
status = acpi_install_gpe_handler(NULL, ec->gpe,
ACPI_GPE_EDGE_TRIGGERED,
&acpi_ec_gpe_handler, ec);
if (ACPI_FAILURE(status))
return -ENODEV;
acpi_enable_gpe(NULL, ec->gpe);
status = acpi_install_address_space_handler(ec->handle,
ACPI_ADR_SPACE_EC,
&acpi_ec_space_handler,
NULL, ec);
if (ACPI_FAILURE(status)) {
if (status == AE_NOT_FOUND) {
/*
* Maybe OS fails in evaluating the _REG object.
* The AE_NOT_FOUND error will be ignored and OS
* continue to initialize EC.
*/
printk(KERN_ERR "Fail in evaluating the _REG object"
" of EC device. Broken bios is suspected.\n");
} else {
acpi_remove_gpe_handler(NULL, ec->gpe,
&acpi_ec_gpe_handler);
acpi_disable_gpe(NULL, ec->gpe);
return -ENODEV;
}
}
set_bit(EC_FLAGS_HANDLERS_INSTALLED, &ec->flags);
return 0;
}
static void ec_remove_handlers(struct acpi_ec *ec)
{
acpi_disable_gpe(NULL, ec->gpe);
if (ACPI_FAILURE(acpi_remove_address_space_handler(ec->handle,
ACPI_ADR_SPACE_EC, &acpi_ec_space_handler)))
pr_err(PREFIX "failed to remove space handler\n");
if (ACPI_FAILURE(acpi_remove_gpe_handler(NULL, ec->gpe,
&acpi_ec_gpe_handler)))
pr_err(PREFIX "failed to remove gpe handler\n");
clear_bit(EC_FLAGS_HANDLERS_INSTALLED, &ec->flags);
}
static int acpi_ec_add(struct acpi_device *device)
{
struct acpi_ec *ec = NULL;
int ret;
strcpy(acpi_device_name(device), ACPI_EC_DEVICE_NAME);
strcpy(acpi_device_class(device), ACPI_EC_CLASS);
/* Check for boot EC */
if (boot_ec &&
(boot_ec->handle == device->handle ||
boot_ec->handle == ACPI_ROOT_OBJECT)) {
ec = boot_ec;
boot_ec = NULL;
} else {
ec = make_acpi_ec();
if (!ec)
return -ENOMEM;
}
if (ec_parse_device(device->handle, 0, ec, NULL) !=
AE_CTRL_TERMINATE) {
kfree(ec);
return -EINVAL;
}
/* Find and register all query methods */
acpi_walk_namespace(ACPI_TYPE_METHOD, ec->handle, 1,
acpi_ec_register_query_methods, NULL, ec, NULL);
if (!first_ec)
first_ec = ec;
device->driver_data = ec;
ret = !!request_region(ec->data_addr, 1, "EC data");
WARN(!ret, "Could not request EC data io port 0x%lx", ec->data_addr);
ret = !!request_region(ec->command_addr, 1, "EC cmd");
WARN(!ret, "Could not request EC cmd io port 0x%lx", ec->command_addr);
pr_info(PREFIX "GPE = 0x%lx, I/O: command/status = 0x%lx, data = 0x%lx\n",
ec->gpe, ec->command_addr, ec->data_addr);
ret = ec_install_handlers(ec);
/* EC is fully operational, allow queries */
clear_bit(EC_FLAGS_QUERY_PENDING, &ec->flags);
return ret;
}
static int acpi_ec_remove(struct acpi_device *device)
{
struct acpi_ec *ec;
struct acpi_ec_query_handler *handler, *tmp;
if (!device)
return -EINVAL;
ec = acpi_driver_data(device);
ec_remove_handlers(ec);
mutex_lock(&ec->mutex);
list_for_each_entry_safe(handler, tmp, &ec->list, node) {
list_del(&handler->node);
kfree(handler);
}
mutex_unlock(&ec->mutex);
release_region(ec->data_addr, 1);
release_region(ec->command_addr, 1);
device->driver_data = NULL;
if (ec == first_ec)
first_ec = NULL;
kfree(ec);
return 0;
}
static acpi_status
ec_parse_io_ports(struct acpi_resource *resource, void *context)
{
struct acpi_ec *ec = context;
if (resource->type != ACPI_RESOURCE_TYPE_IO)
return AE_OK;
/*
* The first address region returned is the data port, and
* the second address region returned is the status/command
* port.
*/
if (ec->data_addr == 0)
ec->data_addr = resource->data.io.minimum;
else if (ec->command_addr == 0)
ec->command_addr = resource->data.io.minimum;
else
return AE_CTRL_TERMINATE;
return AE_OK;
}
int __init acpi_boot_ec_enable(void)
{
if (!boot_ec || test_bit(EC_FLAGS_HANDLERS_INSTALLED, &boot_ec->flags))
return 0;
if (!ec_install_handlers(boot_ec)) {
first_ec = boot_ec;
return 0;
}
return -EFAULT;
}
static const struct acpi_device_id ec_device_ids[] = {
{"PNP0C09", 0},
{"", 0},
};
/* Some BIOS do not survive early DSDT scan, skip it */
static int ec_skip_dsdt_scan(const struct dmi_system_id *id)
{
EC_FLAGS_SKIP_DSDT_SCAN = 1;
return 0;
}
/* ASUStek often supplies us with broken ECDT, validate it */
static int ec_validate_ecdt(const struct dmi_system_id *id)
{
EC_FLAGS_VALIDATE_ECDT = 1;
return 0;
}
/* MSI EC needs special treatment, enable it */
static int ec_flag_msi(const struct dmi_system_id *id)
{
printk(KERN_DEBUG PREFIX "Detected MSI hardware, enabling workarounds.\n");
EC_FLAGS_MSI = 1;
EC_FLAGS_VALIDATE_ECDT = 1;
return 0;
}
/*
* Clevo M720 notebook actually works ok with IRQ mode, if we lifted
* the GPE storm threshold back to 20
*/
static int ec_enlarge_storm_threshold(const struct dmi_system_id *id)
{
pr_debug("Setting the EC GPE storm threshold to 20\n");
ec_storm_threshold = 20;
return 0;
}
static struct dmi_system_id __initdata ec_dmi_table[] = {
{
ec_skip_dsdt_scan, "Compal JFL92", {
DMI_MATCH(DMI_BIOS_VENDOR, "COMPAL"),
DMI_MATCH(DMI_BOARD_NAME, "JFL92") }, NULL},
{
ec_flag_msi, "MSI hardware", {
DMI_MATCH(DMI_BIOS_VENDOR, "Micro-Star")}, NULL},
{
ec_flag_msi, "MSI hardware", {
DMI_MATCH(DMI_SYS_VENDOR, "Micro-Star")}, NULL},
{
ec_flag_msi, "MSI hardware", {
DMI_MATCH(DMI_CHASSIS_VENDOR, "MICRO-Star")}, NULL},
{
ec_flag_msi, "MSI hardware", {
DMI_MATCH(DMI_CHASSIS_VENDOR, "MICRO-STAR")}, NULL},
{
ec_flag_msi, "Quanta hardware", {
DMI_MATCH(DMI_SYS_VENDOR, "Quanta"),
DMI_MATCH(DMI_PRODUCT_NAME, "TW8/SW8/DW8"),}, NULL},
{
ec_flag_msi, "Quanta hardware", {
DMI_MATCH(DMI_SYS_VENDOR, "Quanta"),
DMI_MATCH(DMI_PRODUCT_NAME, "TW9/SW9"),}, NULL},
{
ec_validate_ecdt, "ASUS hardware", {
DMI_MATCH(DMI_BIOS_VENDOR, "ASUS") }, NULL},
{
ec_validate_ecdt, "ASUS hardware", {
DMI_MATCH(DMI_BOARD_VENDOR, "ASUSTeK Computer Inc.") }, NULL},
{
ec_enlarge_storm_threshold, "CLEVO hardware", {
DMI_MATCH(DMI_SYS_VENDOR, "CLEVO Co."),
DMI_MATCH(DMI_PRODUCT_NAME, "M720T/M730T"),}, NULL},
{
ec_skip_dsdt_scan, "HP Folio 13", {
DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"),
DMI_MATCH(DMI_PRODUCT_NAME, "HP Folio 13"),}, NULL},
{
ec_validate_ecdt, "ASUS hardware", {
DMI_MATCH(DMI_SYS_VENDOR, "ASUSTek Computer Inc."),
DMI_MATCH(DMI_PRODUCT_NAME, "L4R"),}, NULL},
{},
};
int __init acpi_ec_ecdt_probe(void)
{
acpi_status status;
struct acpi_ec *saved_ec = NULL;
struct acpi_table_ecdt *ecdt_ptr;
boot_ec = make_acpi_ec();
if (!boot_ec)
return -ENOMEM;
/*
* Generate a boot ec context
*/
dmi_check_system(ec_dmi_table);
status = acpi_get_table(ACPI_SIG_ECDT, 1,
(struct acpi_table_header **)&ecdt_ptr);
if (ACPI_SUCCESS(status)) {
pr_info(PREFIX "EC description table is found, configuring boot EC\n");
boot_ec->command_addr = ecdt_ptr->control.address;
boot_ec->data_addr = ecdt_ptr->data.address;
boot_ec->gpe = ecdt_ptr->gpe;
boot_ec->handle = ACPI_ROOT_OBJECT;
acpi_get_handle(ACPI_ROOT_OBJECT, ecdt_ptr->id, &boot_ec->handle);
/* Don't trust ECDT, which comes from ASUSTek */
if (!EC_FLAGS_VALIDATE_ECDT)
goto install;
saved_ec = kmemdup(boot_ec, sizeof(struct acpi_ec), GFP_KERNEL);
if (!saved_ec)
return -ENOMEM;
/* fall through */
}
if (EC_FLAGS_SKIP_DSDT_SCAN)
return -ENODEV;
/* This workaround is needed only on some broken machines,
* which require early EC, but fail to provide ECDT */
printk(KERN_DEBUG PREFIX "Look up EC in DSDT\n");
status = acpi_get_devices(ec_device_ids[0].id, ec_parse_device,
boot_ec, NULL);
/* Check that acpi_get_devices actually find something */
if (ACPI_FAILURE(status) || !boot_ec->handle)
goto error;
if (saved_ec) {
/* try to find good ECDT from ASUSTek */
if (saved_ec->command_addr != boot_ec->command_addr ||
saved_ec->data_addr != boot_ec->data_addr ||
saved_ec->gpe != boot_ec->gpe ||
saved_ec->handle != boot_ec->handle)
pr_info(PREFIX "ASUSTek keeps feeding us with broken "
"ECDT tables, which are very hard to workaround. "
"Trying to use DSDT EC info instead. Please send "
"output of acpidump to linux-acpi@vger.kernel.org\n");
kfree(saved_ec);
saved_ec = NULL;
} else {
/* We really need to limit this workaround, the only ASUS,
* which needs it, has fake EC._INI method, so use it as flag.
* Keep boot_ec struct as it will be needed soon.
*/
acpi_handle dummy;
if (!dmi_name_in_vendors("ASUS") ||
ACPI_FAILURE(acpi_get_handle(boot_ec->handle, "_INI",
&dummy)))
return -ENODEV;
}
install:
if (!ec_install_handlers(boot_ec)) {
first_ec = boot_ec;
return 0;
}
error:
kfree(boot_ec);
boot_ec = NULL;
return -ENODEV;
}
static struct acpi_driver acpi_ec_driver = {
.name = "ec",
.class = ACPI_EC_CLASS,
.ids = ec_device_ids,
.ops = {
.add = acpi_ec_add,
.remove = acpi_ec_remove,
},
};
int __init acpi_ec_init(void)
{
int result = 0;
/* Now register the driver for the EC */
result = acpi_bus_register_driver(&acpi_ec_driver);
if (result < 0)
return -ENODEV;
return result;
}
/* EC driver currently not unloadable */
#if 0
static void __exit acpi_ec_exit(void)
{
acpi_bus_unregister_driver(&acpi_ec_driver);
return;
}
#endif /* 0 */
| gpl-2.0 |
solring/GT-I9300_JB_Kernel_alarmAlign | drivers/gpu/drm/radeon/radeon_legacy_encoders.c | 2257 | 51913 | /*
* Copyright 2007-8 Advanced Micro Devices, Inc.
* Copyright 2008 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: Dave Airlie
* Alex Deucher
*/
#include "drmP.h"
#include "drm_crtc_helper.h"
#include "radeon_drm.h"
#include "radeon.h"
#include "atom.h"
#include <linux/backlight.h>
#ifdef CONFIG_PMAC_BACKLIGHT
#include <asm/backlight.h>
#endif
static void radeon_legacy_encoder_disable(struct drm_encoder *encoder)
{
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct drm_encoder_helper_funcs *encoder_funcs;
encoder_funcs = encoder->helper_private;
encoder_funcs->dpms(encoder, DRM_MODE_DPMS_OFF);
radeon_encoder->active_device = 0;
}
static void radeon_legacy_lvds_update(struct drm_encoder *encoder, int mode)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
uint32_t lvds_gen_cntl, lvds_pll_cntl, pixclks_cntl, disp_pwr_man;
int panel_pwr_delay = 2000;
bool is_mac = false;
uint8_t backlight_level;
DRM_DEBUG_KMS("\n");
lvds_gen_cntl = RREG32(RADEON_LVDS_GEN_CNTL);
backlight_level = (lvds_gen_cntl >> RADEON_LVDS_BL_MOD_LEVEL_SHIFT) & 0xff;
if (radeon_encoder->enc_priv) {
if (rdev->is_atom_bios) {
struct radeon_encoder_atom_dig *lvds = radeon_encoder->enc_priv;
panel_pwr_delay = lvds->panel_pwr_delay;
if (lvds->bl_dev)
backlight_level = lvds->backlight_level;
} else {
struct radeon_encoder_lvds *lvds = radeon_encoder->enc_priv;
panel_pwr_delay = lvds->panel_pwr_delay;
if (lvds->bl_dev)
backlight_level = lvds->backlight_level;
}
}
/* macs (and possibly some x86 oem systems?) wire up LVDS strangely
* Taken from radeonfb.
*/
if ((rdev->mode_info.connector_table == CT_IBOOK) ||
(rdev->mode_info.connector_table == CT_POWERBOOK_EXTERNAL) ||
(rdev->mode_info.connector_table == CT_POWERBOOK_INTERNAL) ||
(rdev->mode_info.connector_table == CT_POWERBOOK_VGA))
is_mac = true;
switch (mode) {
case DRM_MODE_DPMS_ON:
disp_pwr_man = RREG32(RADEON_DISP_PWR_MAN);
disp_pwr_man |= RADEON_AUTO_PWRUP_EN;
WREG32(RADEON_DISP_PWR_MAN, disp_pwr_man);
lvds_pll_cntl = RREG32(RADEON_LVDS_PLL_CNTL);
lvds_pll_cntl |= RADEON_LVDS_PLL_EN;
WREG32(RADEON_LVDS_PLL_CNTL, lvds_pll_cntl);
udelay(1000);
lvds_pll_cntl = RREG32(RADEON_LVDS_PLL_CNTL);
lvds_pll_cntl &= ~RADEON_LVDS_PLL_RESET;
WREG32(RADEON_LVDS_PLL_CNTL, lvds_pll_cntl);
lvds_gen_cntl &= ~(RADEON_LVDS_DISPLAY_DIS |
RADEON_LVDS_BL_MOD_LEVEL_MASK);
lvds_gen_cntl |= (RADEON_LVDS_ON | RADEON_LVDS_EN |
RADEON_LVDS_DIGON | RADEON_LVDS_BLON |
(backlight_level << RADEON_LVDS_BL_MOD_LEVEL_SHIFT));
if (is_mac)
lvds_gen_cntl |= RADEON_LVDS_BL_MOD_EN;
udelay(panel_pwr_delay * 1000);
WREG32(RADEON_LVDS_GEN_CNTL, lvds_gen_cntl);
break;
case DRM_MODE_DPMS_STANDBY:
case DRM_MODE_DPMS_SUSPEND:
case DRM_MODE_DPMS_OFF:
pixclks_cntl = RREG32_PLL(RADEON_PIXCLKS_CNTL);
WREG32_PLL_P(RADEON_PIXCLKS_CNTL, 0, ~RADEON_PIXCLK_LVDS_ALWAYS_ONb);
lvds_gen_cntl |= RADEON_LVDS_DISPLAY_DIS;
if (is_mac) {
lvds_gen_cntl &= ~RADEON_LVDS_BL_MOD_EN;
WREG32(RADEON_LVDS_GEN_CNTL, lvds_gen_cntl);
lvds_gen_cntl &= ~(RADEON_LVDS_ON | RADEON_LVDS_EN);
} else {
WREG32(RADEON_LVDS_GEN_CNTL, lvds_gen_cntl);
lvds_gen_cntl &= ~(RADEON_LVDS_ON | RADEON_LVDS_BLON | RADEON_LVDS_EN | RADEON_LVDS_DIGON);
}
udelay(panel_pwr_delay * 1000);
WREG32(RADEON_LVDS_GEN_CNTL, lvds_gen_cntl);
WREG32_PLL(RADEON_PIXCLKS_CNTL, pixclks_cntl);
udelay(panel_pwr_delay * 1000);
break;
}
if (rdev->is_atom_bios)
radeon_atombios_encoder_dpms_scratch_regs(encoder, (mode == DRM_MODE_DPMS_ON) ? true : false);
else
radeon_combios_encoder_dpms_scratch_regs(encoder, (mode == DRM_MODE_DPMS_ON) ? true : false);
}
static void radeon_legacy_lvds_dpms(struct drm_encoder *encoder, int mode)
{
struct radeon_device *rdev = encoder->dev->dev_private;
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
DRM_DEBUG("\n");
if (radeon_encoder->enc_priv) {
if (rdev->is_atom_bios) {
struct radeon_encoder_atom_dig *lvds = radeon_encoder->enc_priv;
lvds->dpms_mode = mode;
} else {
struct radeon_encoder_lvds *lvds = radeon_encoder->enc_priv;
lvds->dpms_mode = mode;
}
}
radeon_legacy_lvds_update(encoder, mode);
}
static void radeon_legacy_lvds_prepare(struct drm_encoder *encoder)
{
struct radeon_device *rdev = encoder->dev->dev_private;
if (rdev->is_atom_bios)
radeon_atom_output_lock(encoder, true);
else
radeon_combios_output_lock(encoder, true);
radeon_legacy_lvds_dpms(encoder, DRM_MODE_DPMS_OFF);
}
static void radeon_legacy_lvds_commit(struct drm_encoder *encoder)
{
struct radeon_device *rdev = encoder->dev->dev_private;
radeon_legacy_lvds_dpms(encoder, DRM_MODE_DPMS_ON);
if (rdev->is_atom_bios)
radeon_atom_output_lock(encoder, false);
else
radeon_combios_output_lock(encoder, false);
}
static void radeon_legacy_lvds_mode_set(struct drm_encoder *encoder,
struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_crtc *radeon_crtc = to_radeon_crtc(encoder->crtc);
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
uint32_t lvds_pll_cntl, lvds_gen_cntl, lvds_ss_gen_cntl;
DRM_DEBUG_KMS("\n");
lvds_pll_cntl = RREG32(RADEON_LVDS_PLL_CNTL);
lvds_pll_cntl &= ~RADEON_LVDS_PLL_EN;
lvds_ss_gen_cntl = RREG32(RADEON_LVDS_SS_GEN_CNTL);
if (rdev->is_atom_bios) {
/* LVDS_GEN_CNTL parameters are computed in LVDSEncoderControl
* need to call that on resume to set up the reg properly.
*/
radeon_encoder->pixel_clock = adjusted_mode->clock;
atombios_digital_setup(encoder, PANEL_ENCODER_ACTION_ENABLE);
lvds_gen_cntl = RREG32(RADEON_LVDS_GEN_CNTL);
} else {
struct radeon_encoder_lvds *lvds = (struct radeon_encoder_lvds *)radeon_encoder->enc_priv;
if (lvds) {
DRM_DEBUG_KMS("bios LVDS_GEN_CNTL: 0x%x\n", lvds->lvds_gen_cntl);
lvds_gen_cntl = lvds->lvds_gen_cntl;
lvds_ss_gen_cntl &= ~((0xf << RADEON_LVDS_PWRSEQ_DELAY1_SHIFT) |
(0xf << RADEON_LVDS_PWRSEQ_DELAY2_SHIFT));
lvds_ss_gen_cntl |= ((lvds->panel_digon_delay << RADEON_LVDS_PWRSEQ_DELAY1_SHIFT) |
(lvds->panel_blon_delay << RADEON_LVDS_PWRSEQ_DELAY2_SHIFT));
} else
lvds_gen_cntl = RREG32(RADEON_LVDS_GEN_CNTL);
}
lvds_gen_cntl |= RADEON_LVDS_DISPLAY_DIS;
lvds_gen_cntl &= ~(RADEON_LVDS_ON |
RADEON_LVDS_BLON |
RADEON_LVDS_EN |
RADEON_LVDS_RST_FM);
if (ASIC_IS_R300(rdev))
lvds_pll_cntl &= ~(R300_LVDS_SRC_SEL_MASK);
if (radeon_crtc->crtc_id == 0) {
if (ASIC_IS_R300(rdev)) {
if (radeon_encoder->rmx_type != RMX_OFF)
lvds_pll_cntl |= R300_LVDS_SRC_SEL_RMX;
} else
lvds_gen_cntl &= ~RADEON_LVDS_SEL_CRTC2;
} else {
if (ASIC_IS_R300(rdev))
lvds_pll_cntl |= R300_LVDS_SRC_SEL_CRTC2;
else
lvds_gen_cntl |= RADEON_LVDS_SEL_CRTC2;
}
WREG32(RADEON_LVDS_GEN_CNTL, lvds_gen_cntl);
WREG32(RADEON_LVDS_PLL_CNTL, lvds_pll_cntl);
WREG32(RADEON_LVDS_SS_GEN_CNTL, lvds_ss_gen_cntl);
if (rdev->family == CHIP_RV410)
WREG32(RADEON_CLOCK_CNTL_INDEX, 0);
if (rdev->is_atom_bios)
radeon_atombios_encoder_crtc_scratch_regs(encoder, radeon_crtc->crtc_id);
else
radeon_combios_encoder_crtc_scratch_regs(encoder, radeon_crtc->crtc_id);
}
static bool radeon_legacy_mode_fixup(struct drm_encoder *encoder,
struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
/* set the active encoder to connector routing */
radeon_encoder_set_active_device(encoder);
drm_mode_set_crtcinfo(adjusted_mode, 0);
/* get the native mode for LVDS */
if (radeon_encoder->active_device & (ATOM_DEVICE_LCD_SUPPORT))
radeon_panel_mode_fixup(encoder, adjusted_mode);
return true;
}
static const struct drm_encoder_helper_funcs radeon_legacy_lvds_helper_funcs = {
.dpms = radeon_legacy_lvds_dpms,
.mode_fixup = radeon_legacy_mode_fixup,
.prepare = radeon_legacy_lvds_prepare,
.mode_set = radeon_legacy_lvds_mode_set,
.commit = radeon_legacy_lvds_commit,
.disable = radeon_legacy_encoder_disable,
};
#if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) || defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
#define MAX_RADEON_LEVEL 0xFF
struct radeon_backlight_privdata {
struct radeon_encoder *encoder;
uint8_t negative;
};
static uint8_t radeon_legacy_lvds_level(struct backlight_device *bd)
{
struct radeon_backlight_privdata *pdata = bl_get_data(bd);
uint8_t level;
/* Convert brightness to hardware level */
if (bd->props.brightness < 0)
level = 0;
else if (bd->props.brightness > MAX_RADEON_LEVEL)
level = MAX_RADEON_LEVEL;
else
level = bd->props.brightness;
if (pdata->negative)
level = MAX_RADEON_LEVEL - level;
return level;
}
static int radeon_legacy_backlight_update_status(struct backlight_device *bd)
{
struct radeon_backlight_privdata *pdata = bl_get_data(bd);
struct radeon_encoder *radeon_encoder = pdata->encoder;
struct drm_device *dev = radeon_encoder->base.dev;
struct radeon_device *rdev = dev->dev_private;
int dpms_mode = DRM_MODE_DPMS_ON;
if (radeon_encoder->enc_priv) {
if (rdev->is_atom_bios) {
struct radeon_encoder_atom_dig *lvds = radeon_encoder->enc_priv;
dpms_mode = lvds->dpms_mode;
lvds->backlight_level = radeon_legacy_lvds_level(bd);
} else {
struct radeon_encoder_lvds *lvds = radeon_encoder->enc_priv;
dpms_mode = lvds->dpms_mode;
lvds->backlight_level = radeon_legacy_lvds_level(bd);
}
}
if (bd->props.brightness > 0)
radeon_legacy_lvds_update(&radeon_encoder->base, dpms_mode);
else
radeon_legacy_lvds_update(&radeon_encoder->base, DRM_MODE_DPMS_OFF);
return 0;
}
static int radeon_legacy_backlight_get_brightness(struct backlight_device *bd)
{
struct radeon_backlight_privdata *pdata = bl_get_data(bd);
struct radeon_encoder *radeon_encoder = pdata->encoder;
struct drm_device *dev = radeon_encoder->base.dev;
struct radeon_device *rdev = dev->dev_private;
uint8_t backlight_level;
backlight_level = (RREG32(RADEON_LVDS_GEN_CNTL) >>
RADEON_LVDS_BL_MOD_LEVEL_SHIFT) & 0xff;
return pdata->negative ? MAX_RADEON_LEVEL - backlight_level : backlight_level;
}
static const struct backlight_ops radeon_backlight_ops = {
.get_brightness = radeon_legacy_backlight_get_brightness,
.update_status = radeon_legacy_backlight_update_status,
};
void radeon_legacy_backlight_init(struct radeon_encoder *radeon_encoder,
struct drm_connector *drm_connector)
{
struct drm_device *dev = radeon_encoder->base.dev;
struct radeon_device *rdev = dev->dev_private;
struct backlight_device *bd;
struct backlight_properties props;
struct radeon_backlight_privdata *pdata;
uint8_t backlight_level;
if (!radeon_encoder->enc_priv)
return;
#ifdef CONFIG_PMAC_BACKLIGHT
if (!pmac_has_backlight_type("ati") &&
!pmac_has_backlight_type("mnca"))
return;
#endif
pdata = kmalloc(sizeof(struct radeon_backlight_privdata), GFP_KERNEL);
if (!pdata) {
DRM_ERROR("Memory allocation failed\n");
goto error;
}
props.max_brightness = MAX_RADEON_LEVEL;
props.type = BACKLIGHT_RAW;
bd = backlight_device_register("radeon_bl", &drm_connector->kdev,
pdata, &radeon_backlight_ops, &props);
if (IS_ERR(bd)) {
DRM_ERROR("Backlight registration failed\n");
goto error;
}
pdata->encoder = radeon_encoder;
backlight_level = (RREG32(RADEON_LVDS_GEN_CNTL) >>
RADEON_LVDS_BL_MOD_LEVEL_SHIFT) & 0xff;
/* First, try to detect backlight level sense based on the assumption
* that firmware set it up at full brightness
*/
if (backlight_level == 0)
pdata->negative = true;
else if (backlight_level == 0xff)
pdata->negative = false;
else {
/* XXX hack... maybe some day we can figure out in what direction
* backlight should work on a given panel?
*/
pdata->negative = (rdev->family != CHIP_RV200 &&
rdev->family != CHIP_RV250 &&
rdev->family != CHIP_RV280 &&
rdev->family != CHIP_RV350);
#ifdef CONFIG_PMAC_BACKLIGHT
pdata->negative = (pdata->negative ||
of_machine_is_compatible("PowerBook4,3") ||
of_machine_is_compatible("PowerBook6,3") ||
of_machine_is_compatible("PowerBook6,5"));
#endif
}
if (rdev->is_atom_bios) {
struct radeon_encoder_atom_dig *lvds = radeon_encoder->enc_priv;
lvds->bl_dev = bd;
} else {
struct radeon_encoder_lvds *lvds = radeon_encoder->enc_priv;
lvds->bl_dev = bd;
}
bd->props.brightness = radeon_legacy_backlight_get_brightness(bd);
bd->props.power = FB_BLANK_UNBLANK;
backlight_update_status(bd);
DRM_INFO("radeon legacy LVDS backlight initialized\n");
return;
error:
kfree(pdata);
return;
}
static void radeon_legacy_backlight_exit(struct radeon_encoder *radeon_encoder)
{
struct drm_device *dev = radeon_encoder->base.dev;
struct radeon_device *rdev = dev->dev_private;
struct backlight_device *bd = NULL;
if (!radeon_encoder->enc_priv)
return;
if (rdev->is_atom_bios) {
struct radeon_encoder_atom_dig *lvds = radeon_encoder->enc_priv;
bd = lvds->bl_dev;
lvds->bl_dev = NULL;
} else {
struct radeon_encoder_lvds *lvds = radeon_encoder->enc_priv;
bd = lvds->bl_dev;
lvds->bl_dev = NULL;
}
if (bd) {
struct radeon_legacy_backlight_privdata *pdata;
pdata = bl_get_data(bd);
backlight_device_unregister(bd);
kfree(pdata);
DRM_INFO("radeon legacy LVDS backlight unloaded\n");
}
}
#else /* !CONFIG_BACKLIGHT_CLASS_DEVICE */
void radeon_legacy_backlight_init(struct radeon_encoder *encoder)
{
}
static void radeon_legacy_backlight_exit(struct radeon_encoder *encoder)
{
}
#endif
static void radeon_lvds_enc_destroy(struct drm_encoder *encoder)
{
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
if (radeon_encoder->enc_priv) {
radeon_legacy_backlight_exit(radeon_encoder);
kfree(radeon_encoder->enc_priv);
}
drm_encoder_cleanup(encoder);
kfree(radeon_encoder);
}
static const struct drm_encoder_funcs radeon_legacy_lvds_enc_funcs = {
.destroy = radeon_lvds_enc_destroy,
};
static void radeon_legacy_primary_dac_dpms(struct drm_encoder *encoder, int mode)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
uint32_t crtc_ext_cntl = RREG32(RADEON_CRTC_EXT_CNTL);
uint32_t dac_cntl = RREG32(RADEON_DAC_CNTL);
uint32_t dac_macro_cntl = RREG32(RADEON_DAC_MACRO_CNTL);
DRM_DEBUG_KMS("\n");
switch (mode) {
case DRM_MODE_DPMS_ON:
crtc_ext_cntl |= RADEON_CRTC_CRT_ON;
dac_cntl &= ~RADEON_DAC_PDWN;
dac_macro_cntl &= ~(RADEON_DAC_PDWN_R |
RADEON_DAC_PDWN_G |
RADEON_DAC_PDWN_B);
break;
case DRM_MODE_DPMS_STANDBY:
case DRM_MODE_DPMS_SUSPEND:
case DRM_MODE_DPMS_OFF:
crtc_ext_cntl &= ~RADEON_CRTC_CRT_ON;
dac_cntl |= RADEON_DAC_PDWN;
dac_macro_cntl |= (RADEON_DAC_PDWN_R |
RADEON_DAC_PDWN_G |
RADEON_DAC_PDWN_B);
break;
}
WREG32(RADEON_CRTC_EXT_CNTL, crtc_ext_cntl);
WREG32(RADEON_DAC_CNTL, dac_cntl);
WREG32(RADEON_DAC_MACRO_CNTL, dac_macro_cntl);
if (rdev->is_atom_bios)
radeon_atombios_encoder_dpms_scratch_regs(encoder, (mode == DRM_MODE_DPMS_ON) ? true : false);
else
radeon_combios_encoder_dpms_scratch_regs(encoder, (mode == DRM_MODE_DPMS_ON) ? true : false);
}
static void radeon_legacy_primary_dac_prepare(struct drm_encoder *encoder)
{
struct radeon_device *rdev = encoder->dev->dev_private;
if (rdev->is_atom_bios)
radeon_atom_output_lock(encoder, true);
else
radeon_combios_output_lock(encoder, true);
radeon_legacy_primary_dac_dpms(encoder, DRM_MODE_DPMS_OFF);
}
static void radeon_legacy_primary_dac_commit(struct drm_encoder *encoder)
{
struct radeon_device *rdev = encoder->dev->dev_private;
radeon_legacy_primary_dac_dpms(encoder, DRM_MODE_DPMS_ON);
if (rdev->is_atom_bios)
radeon_atom_output_lock(encoder, false);
else
radeon_combios_output_lock(encoder, false);
}
static void radeon_legacy_primary_dac_mode_set(struct drm_encoder *encoder,
struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_crtc *radeon_crtc = to_radeon_crtc(encoder->crtc);
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
uint32_t disp_output_cntl, dac_cntl, dac2_cntl, dac_macro_cntl;
DRM_DEBUG_KMS("\n");
if (radeon_crtc->crtc_id == 0) {
if (rdev->family == CHIP_R200 || ASIC_IS_R300(rdev)) {
disp_output_cntl = RREG32(RADEON_DISP_OUTPUT_CNTL) &
~(RADEON_DISP_DAC_SOURCE_MASK);
WREG32(RADEON_DISP_OUTPUT_CNTL, disp_output_cntl);
} else {
dac2_cntl = RREG32(RADEON_DAC_CNTL2) & ~(RADEON_DAC2_DAC_CLK_SEL);
WREG32(RADEON_DAC_CNTL2, dac2_cntl);
}
} else {
if (rdev->family == CHIP_R200 || ASIC_IS_R300(rdev)) {
disp_output_cntl = RREG32(RADEON_DISP_OUTPUT_CNTL) &
~(RADEON_DISP_DAC_SOURCE_MASK);
disp_output_cntl |= RADEON_DISP_DAC_SOURCE_CRTC2;
WREG32(RADEON_DISP_OUTPUT_CNTL, disp_output_cntl);
} else {
dac2_cntl = RREG32(RADEON_DAC_CNTL2) | RADEON_DAC2_DAC_CLK_SEL;
WREG32(RADEON_DAC_CNTL2, dac2_cntl);
}
}
dac_cntl = (RADEON_DAC_MASK_ALL |
RADEON_DAC_VGA_ADR_EN |
/* TODO 6-bits */
RADEON_DAC_8BIT_EN);
WREG32_P(RADEON_DAC_CNTL,
dac_cntl,
RADEON_DAC_RANGE_CNTL |
RADEON_DAC_BLANKING);
if (radeon_encoder->enc_priv) {
struct radeon_encoder_primary_dac *p_dac = (struct radeon_encoder_primary_dac *)radeon_encoder->enc_priv;
dac_macro_cntl = p_dac->ps2_pdac_adj;
} else
dac_macro_cntl = RREG32(RADEON_DAC_MACRO_CNTL);
dac_macro_cntl |= RADEON_DAC_PDWN_R | RADEON_DAC_PDWN_G | RADEON_DAC_PDWN_B;
WREG32(RADEON_DAC_MACRO_CNTL, dac_macro_cntl);
if (rdev->is_atom_bios)
radeon_atombios_encoder_crtc_scratch_regs(encoder, radeon_crtc->crtc_id);
else
radeon_combios_encoder_crtc_scratch_regs(encoder, radeon_crtc->crtc_id);
}
static enum drm_connector_status radeon_legacy_primary_dac_detect(struct drm_encoder *encoder,
struct drm_connector *connector)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
uint32_t vclk_ecp_cntl, crtc_ext_cntl;
uint32_t dac_ext_cntl, dac_cntl, dac_macro_cntl, tmp;
enum drm_connector_status found = connector_status_disconnected;
bool color = true;
/* save the regs we need */
vclk_ecp_cntl = RREG32_PLL(RADEON_VCLK_ECP_CNTL);
crtc_ext_cntl = RREG32(RADEON_CRTC_EXT_CNTL);
dac_ext_cntl = RREG32(RADEON_DAC_EXT_CNTL);
dac_cntl = RREG32(RADEON_DAC_CNTL);
dac_macro_cntl = RREG32(RADEON_DAC_MACRO_CNTL);
tmp = vclk_ecp_cntl &
~(RADEON_PIXCLK_ALWAYS_ONb | RADEON_PIXCLK_DAC_ALWAYS_ONb);
WREG32_PLL(RADEON_VCLK_ECP_CNTL, tmp);
tmp = crtc_ext_cntl | RADEON_CRTC_CRT_ON;
WREG32(RADEON_CRTC_EXT_CNTL, tmp);
tmp = RADEON_DAC_FORCE_BLANK_OFF_EN |
RADEON_DAC_FORCE_DATA_EN;
if (color)
tmp |= RADEON_DAC_FORCE_DATA_SEL_RGB;
else
tmp |= RADEON_DAC_FORCE_DATA_SEL_G;
if (ASIC_IS_R300(rdev))
tmp |= (0x1b6 << RADEON_DAC_FORCE_DATA_SHIFT);
else
tmp |= (0x180 << RADEON_DAC_FORCE_DATA_SHIFT);
WREG32(RADEON_DAC_EXT_CNTL, tmp);
tmp = dac_cntl & ~(RADEON_DAC_RANGE_CNTL_MASK | RADEON_DAC_PDWN);
tmp |= RADEON_DAC_RANGE_CNTL_PS2 | RADEON_DAC_CMP_EN;
WREG32(RADEON_DAC_CNTL, tmp);
tmp &= ~(RADEON_DAC_PDWN_R |
RADEON_DAC_PDWN_G |
RADEON_DAC_PDWN_B);
WREG32(RADEON_DAC_MACRO_CNTL, tmp);
udelay(2000);
if (RREG32(RADEON_DAC_CNTL) & RADEON_DAC_CMP_OUTPUT)
found = connector_status_connected;
/* restore the regs we used */
WREG32(RADEON_DAC_CNTL, dac_cntl);
WREG32(RADEON_DAC_MACRO_CNTL, dac_macro_cntl);
WREG32(RADEON_DAC_EXT_CNTL, dac_ext_cntl);
WREG32(RADEON_CRTC_EXT_CNTL, crtc_ext_cntl);
WREG32_PLL(RADEON_VCLK_ECP_CNTL, vclk_ecp_cntl);
return found;
}
static const struct drm_encoder_helper_funcs radeon_legacy_primary_dac_helper_funcs = {
.dpms = radeon_legacy_primary_dac_dpms,
.mode_fixup = radeon_legacy_mode_fixup,
.prepare = radeon_legacy_primary_dac_prepare,
.mode_set = radeon_legacy_primary_dac_mode_set,
.commit = radeon_legacy_primary_dac_commit,
.detect = radeon_legacy_primary_dac_detect,
.disable = radeon_legacy_encoder_disable,
};
static const struct drm_encoder_funcs radeon_legacy_primary_dac_enc_funcs = {
.destroy = radeon_enc_destroy,
};
static void radeon_legacy_tmds_int_dpms(struct drm_encoder *encoder, int mode)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
uint32_t fp_gen_cntl = RREG32(RADEON_FP_GEN_CNTL);
DRM_DEBUG_KMS("\n");
switch (mode) {
case DRM_MODE_DPMS_ON:
fp_gen_cntl |= (RADEON_FP_FPON | RADEON_FP_TMDS_EN);
break;
case DRM_MODE_DPMS_STANDBY:
case DRM_MODE_DPMS_SUSPEND:
case DRM_MODE_DPMS_OFF:
fp_gen_cntl &= ~(RADEON_FP_FPON | RADEON_FP_TMDS_EN);
break;
}
WREG32(RADEON_FP_GEN_CNTL, fp_gen_cntl);
if (rdev->is_atom_bios)
radeon_atombios_encoder_dpms_scratch_regs(encoder, (mode == DRM_MODE_DPMS_ON) ? true : false);
else
radeon_combios_encoder_dpms_scratch_regs(encoder, (mode == DRM_MODE_DPMS_ON) ? true : false);
}
static void radeon_legacy_tmds_int_prepare(struct drm_encoder *encoder)
{
struct radeon_device *rdev = encoder->dev->dev_private;
if (rdev->is_atom_bios)
radeon_atom_output_lock(encoder, true);
else
radeon_combios_output_lock(encoder, true);
radeon_legacy_tmds_int_dpms(encoder, DRM_MODE_DPMS_OFF);
}
static void radeon_legacy_tmds_int_commit(struct drm_encoder *encoder)
{
struct radeon_device *rdev = encoder->dev->dev_private;
radeon_legacy_tmds_int_dpms(encoder, DRM_MODE_DPMS_ON);
if (rdev->is_atom_bios)
radeon_atom_output_lock(encoder, true);
else
radeon_combios_output_lock(encoder, true);
}
static void radeon_legacy_tmds_int_mode_set(struct drm_encoder *encoder,
struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_crtc *radeon_crtc = to_radeon_crtc(encoder->crtc);
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
uint32_t tmp, tmds_pll_cntl, tmds_transmitter_cntl, fp_gen_cntl;
int i;
DRM_DEBUG_KMS("\n");
tmp = tmds_pll_cntl = RREG32(RADEON_TMDS_PLL_CNTL);
tmp &= 0xfffff;
if (rdev->family == CHIP_RV280) {
/* bit 22 of TMDS_PLL_CNTL is read-back inverted */
tmp ^= (1 << 22);
tmds_pll_cntl ^= (1 << 22);
}
if (radeon_encoder->enc_priv) {
struct radeon_encoder_int_tmds *tmds = (struct radeon_encoder_int_tmds *)radeon_encoder->enc_priv;
for (i = 0; i < 4; i++) {
if (tmds->tmds_pll[i].freq == 0)
break;
if ((uint32_t)(mode->clock / 10) < tmds->tmds_pll[i].freq) {
tmp = tmds->tmds_pll[i].value ;
break;
}
}
}
if (ASIC_IS_R300(rdev) || (rdev->family == CHIP_RV280)) {
if (tmp & 0xfff00000)
tmds_pll_cntl = tmp;
else {
tmds_pll_cntl &= 0xfff00000;
tmds_pll_cntl |= tmp;
}
} else
tmds_pll_cntl = tmp;
tmds_transmitter_cntl = RREG32(RADEON_TMDS_TRANSMITTER_CNTL) &
~(RADEON_TMDS_TRANSMITTER_PLLRST);
if (rdev->family == CHIP_R200 ||
rdev->family == CHIP_R100 ||
ASIC_IS_R300(rdev))
tmds_transmitter_cntl &= ~(RADEON_TMDS_TRANSMITTER_PLLEN);
else /* RV chips got this bit reversed */
tmds_transmitter_cntl |= RADEON_TMDS_TRANSMITTER_PLLEN;
fp_gen_cntl = (RREG32(RADEON_FP_GEN_CNTL) |
(RADEON_FP_CRTC_DONT_SHADOW_VPAR |
RADEON_FP_CRTC_DONT_SHADOW_HEND));
fp_gen_cntl &= ~(RADEON_FP_FPON | RADEON_FP_TMDS_EN);
fp_gen_cntl &= ~(RADEON_FP_RMX_HVSYNC_CONTROL_EN |
RADEON_FP_DFP_SYNC_SEL |
RADEON_FP_CRT_SYNC_SEL |
RADEON_FP_CRTC_LOCK_8DOT |
RADEON_FP_USE_SHADOW_EN |
RADEON_FP_CRTC_USE_SHADOW_VEND |
RADEON_FP_CRT_SYNC_ALT);
if (1) /* FIXME rgbBits == 8 */
fp_gen_cntl |= RADEON_FP_PANEL_FORMAT; /* 24 bit format */
else
fp_gen_cntl &= ~RADEON_FP_PANEL_FORMAT;/* 18 bit format */
if (radeon_crtc->crtc_id == 0) {
if (ASIC_IS_R300(rdev) || rdev->family == CHIP_R200) {
fp_gen_cntl &= ~R200_FP_SOURCE_SEL_MASK;
if (radeon_encoder->rmx_type != RMX_OFF)
fp_gen_cntl |= R200_FP_SOURCE_SEL_RMX;
else
fp_gen_cntl |= R200_FP_SOURCE_SEL_CRTC1;
} else
fp_gen_cntl &= ~RADEON_FP_SEL_CRTC2;
} else {
if (ASIC_IS_R300(rdev) || rdev->family == CHIP_R200) {
fp_gen_cntl &= ~R200_FP_SOURCE_SEL_MASK;
fp_gen_cntl |= R200_FP_SOURCE_SEL_CRTC2;
} else
fp_gen_cntl |= RADEON_FP_SEL_CRTC2;
}
WREG32(RADEON_TMDS_PLL_CNTL, tmds_pll_cntl);
WREG32(RADEON_TMDS_TRANSMITTER_CNTL, tmds_transmitter_cntl);
WREG32(RADEON_FP_GEN_CNTL, fp_gen_cntl);
if (rdev->is_atom_bios)
radeon_atombios_encoder_crtc_scratch_regs(encoder, radeon_crtc->crtc_id);
else
radeon_combios_encoder_crtc_scratch_regs(encoder, radeon_crtc->crtc_id);
}
static const struct drm_encoder_helper_funcs radeon_legacy_tmds_int_helper_funcs = {
.dpms = radeon_legacy_tmds_int_dpms,
.mode_fixup = radeon_legacy_mode_fixup,
.prepare = radeon_legacy_tmds_int_prepare,
.mode_set = radeon_legacy_tmds_int_mode_set,
.commit = radeon_legacy_tmds_int_commit,
.disable = radeon_legacy_encoder_disable,
};
static const struct drm_encoder_funcs radeon_legacy_tmds_int_enc_funcs = {
.destroy = radeon_enc_destroy,
};
static void radeon_legacy_tmds_ext_dpms(struct drm_encoder *encoder, int mode)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
uint32_t fp2_gen_cntl = RREG32(RADEON_FP2_GEN_CNTL);
DRM_DEBUG_KMS("\n");
switch (mode) {
case DRM_MODE_DPMS_ON:
fp2_gen_cntl &= ~RADEON_FP2_BLANK_EN;
fp2_gen_cntl |= (RADEON_FP2_ON | RADEON_FP2_DVO_EN);
break;
case DRM_MODE_DPMS_STANDBY:
case DRM_MODE_DPMS_SUSPEND:
case DRM_MODE_DPMS_OFF:
fp2_gen_cntl |= RADEON_FP2_BLANK_EN;
fp2_gen_cntl &= ~(RADEON_FP2_ON | RADEON_FP2_DVO_EN);
break;
}
WREG32(RADEON_FP2_GEN_CNTL, fp2_gen_cntl);
if (rdev->is_atom_bios)
radeon_atombios_encoder_dpms_scratch_regs(encoder, (mode == DRM_MODE_DPMS_ON) ? true : false);
else
radeon_combios_encoder_dpms_scratch_regs(encoder, (mode == DRM_MODE_DPMS_ON) ? true : false);
}
static void radeon_legacy_tmds_ext_prepare(struct drm_encoder *encoder)
{
struct radeon_device *rdev = encoder->dev->dev_private;
if (rdev->is_atom_bios)
radeon_atom_output_lock(encoder, true);
else
radeon_combios_output_lock(encoder, true);
radeon_legacy_tmds_ext_dpms(encoder, DRM_MODE_DPMS_OFF);
}
static void radeon_legacy_tmds_ext_commit(struct drm_encoder *encoder)
{
struct radeon_device *rdev = encoder->dev->dev_private;
radeon_legacy_tmds_ext_dpms(encoder, DRM_MODE_DPMS_ON);
if (rdev->is_atom_bios)
radeon_atom_output_lock(encoder, false);
else
radeon_combios_output_lock(encoder, false);
}
static void radeon_legacy_tmds_ext_mode_set(struct drm_encoder *encoder,
struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_crtc *radeon_crtc = to_radeon_crtc(encoder->crtc);
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
uint32_t fp2_gen_cntl;
DRM_DEBUG_KMS("\n");
if (rdev->is_atom_bios) {
radeon_encoder->pixel_clock = adjusted_mode->clock;
atombios_dvo_setup(encoder, ATOM_ENABLE);
fp2_gen_cntl = RREG32(RADEON_FP2_GEN_CNTL);
} else {
fp2_gen_cntl = RREG32(RADEON_FP2_GEN_CNTL);
if (1) /* FIXME rgbBits == 8 */
fp2_gen_cntl |= RADEON_FP2_PANEL_FORMAT; /* 24 bit format, */
else
fp2_gen_cntl &= ~RADEON_FP2_PANEL_FORMAT;/* 18 bit format, */
fp2_gen_cntl &= ~(RADEON_FP2_ON |
RADEON_FP2_DVO_EN |
RADEON_FP2_DVO_RATE_SEL_SDR);
/* XXX: these are oem specific */
if (ASIC_IS_R300(rdev)) {
if ((dev->pdev->device == 0x4850) &&
(dev->pdev->subsystem_vendor == 0x1028) &&
(dev->pdev->subsystem_device == 0x2001)) /* Dell Inspiron 8600 */
fp2_gen_cntl |= R300_FP2_DVO_CLOCK_MODE_SINGLE;
else
fp2_gen_cntl |= RADEON_FP2_PAD_FLOP_EN | R300_FP2_DVO_CLOCK_MODE_SINGLE;
/*if (mode->clock > 165000)
fp2_gen_cntl |= R300_FP2_DVO_DUAL_CHANNEL_EN;*/
}
if (!radeon_combios_external_tmds_setup(encoder))
radeon_external_tmds_setup(encoder);
}
if (radeon_crtc->crtc_id == 0) {
if ((rdev->family == CHIP_R200) || ASIC_IS_R300(rdev)) {
fp2_gen_cntl &= ~R200_FP2_SOURCE_SEL_MASK;
if (radeon_encoder->rmx_type != RMX_OFF)
fp2_gen_cntl |= R200_FP2_SOURCE_SEL_RMX;
else
fp2_gen_cntl |= R200_FP2_SOURCE_SEL_CRTC1;
} else
fp2_gen_cntl &= ~RADEON_FP2_SRC_SEL_CRTC2;
} else {
if ((rdev->family == CHIP_R200) || ASIC_IS_R300(rdev)) {
fp2_gen_cntl &= ~R200_FP2_SOURCE_SEL_MASK;
fp2_gen_cntl |= R200_FP2_SOURCE_SEL_CRTC2;
} else
fp2_gen_cntl |= RADEON_FP2_SRC_SEL_CRTC2;
}
WREG32(RADEON_FP2_GEN_CNTL, fp2_gen_cntl);
if (rdev->is_atom_bios)
radeon_atombios_encoder_crtc_scratch_regs(encoder, radeon_crtc->crtc_id);
else
radeon_combios_encoder_crtc_scratch_regs(encoder, radeon_crtc->crtc_id);
}
static void radeon_ext_tmds_enc_destroy(struct drm_encoder *encoder)
{
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct radeon_encoder_ext_tmds *tmds = radeon_encoder->enc_priv;
if (tmds) {
if (tmds->i2c_bus)
radeon_i2c_destroy(tmds->i2c_bus);
}
kfree(radeon_encoder->enc_priv);
drm_encoder_cleanup(encoder);
kfree(radeon_encoder);
}
static const struct drm_encoder_helper_funcs radeon_legacy_tmds_ext_helper_funcs = {
.dpms = radeon_legacy_tmds_ext_dpms,
.mode_fixup = radeon_legacy_mode_fixup,
.prepare = radeon_legacy_tmds_ext_prepare,
.mode_set = radeon_legacy_tmds_ext_mode_set,
.commit = radeon_legacy_tmds_ext_commit,
.disable = radeon_legacy_encoder_disable,
};
static const struct drm_encoder_funcs radeon_legacy_tmds_ext_enc_funcs = {
.destroy = radeon_ext_tmds_enc_destroy,
};
static void radeon_legacy_tv_dac_dpms(struct drm_encoder *encoder, int mode)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
uint32_t fp2_gen_cntl = 0, crtc2_gen_cntl = 0, tv_dac_cntl = 0;
uint32_t tv_master_cntl = 0;
bool is_tv;
DRM_DEBUG_KMS("\n");
is_tv = radeon_encoder->active_device & ATOM_DEVICE_TV_SUPPORT ? true : false;
if (rdev->family == CHIP_R200)
fp2_gen_cntl = RREG32(RADEON_FP2_GEN_CNTL);
else {
if (is_tv)
tv_master_cntl = RREG32(RADEON_TV_MASTER_CNTL);
else
crtc2_gen_cntl = RREG32(RADEON_CRTC2_GEN_CNTL);
tv_dac_cntl = RREG32(RADEON_TV_DAC_CNTL);
}
switch (mode) {
case DRM_MODE_DPMS_ON:
if (rdev->family == CHIP_R200) {
fp2_gen_cntl |= (RADEON_FP2_ON | RADEON_FP2_DVO_EN);
} else {
if (is_tv)
tv_master_cntl |= RADEON_TV_ON;
else
crtc2_gen_cntl |= RADEON_CRTC2_CRT2_ON;
if (rdev->family == CHIP_R420 ||
rdev->family == CHIP_R423 ||
rdev->family == CHIP_RV410)
tv_dac_cntl &= ~(R420_TV_DAC_RDACPD |
R420_TV_DAC_GDACPD |
R420_TV_DAC_BDACPD |
RADEON_TV_DAC_BGSLEEP);
else
tv_dac_cntl &= ~(RADEON_TV_DAC_RDACPD |
RADEON_TV_DAC_GDACPD |
RADEON_TV_DAC_BDACPD |
RADEON_TV_DAC_BGSLEEP);
}
break;
case DRM_MODE_DPMS_STANDBY:
case DRM_MODE_DPMS_SUSPEND:
case DRM_MODE_DPMS_OFF:
if (rdev->family == CHIP_R200)
fp2_gen_cntl &= ~(RADEON_FP2_ON | RADEON_FP2_DVO_EN);
else {
if (is_tv)
tv_master_cntl &= ~RADEON_TV_ON;
else
crtc2_gen_cntl &= ~RADEON_CRTC2_CRT2_ON;
if (rdev->family == CHIP_R420 ||
rdev->family == CHIP_R423 ||
rdev->family == CHIP_RV410)
tv_dac_cntl |= (R420_TV_DAC_RDACPD |
R420_TV_DAC_GDACPD |
R420_TV_DAC_BDACPD |
RADEON_TV_DAC_BGSLEEP);
else
tv_dac_cntl |= (RADEON_TV_DAC_RDACPD |
RADEON_TV_DAC_GDACPD |
RADEON_TV_DAC_BDACPD |
RADEON_TV_DAC_BGSLEEP);
}
break;
}
if (rdev->family == CHIP_R200) {
WREG32(RADEON_FP2_GEN_CNTL, fp2_gen_cntl);
} else {
if (is_tv)
WREG32(RADEON_TV_MASTER_CNTL, tv_master_cntl);
else
WREG32(RADEON_CRTC2_GEN_CNTL, crtc2_gen_cntl);
WREG32(RADEON_TV_DAC_CNTL, tv_dac_cntl);
}
if (rdev->is_atom_bios)
radeon_atombios_encoder_dpms_scratch_regs(encoder, (mode == DRM_MODE_DPMS_ON) ? true : false);
else
radeon_combios_encoder_dpms_scratch_regs(encoder, (mode == DRM_MODE_DPMS_ON) ? true : false);
}
static void radeon_legacy_tv_dac_prepare(struct drm_encoder *encoder)
{
struct radeon_device *rdev = encoder->dev->dev_private;
if (rdev->is_atom_bios)
radeon_atom_output_lock(encoder, true);
else
radeon_combios_output_lock(encoder, true);
radeon_legacy_tv_dac_dpms(encoder, DRM_MODE_DPMS_OFF);
}
static void radeon_legacy_tv_dac_commit(struct drm_encoder *encoder)
{
struct radeon_device *rdev = encoder->dev->dev_private;
radeon_legacy_tv_dac_dpms(encoder, DRM_MODE_DPMS_ON);
if (rdev->is_atom_bios)
radeon_atom_output_lock(encoder, true);
else
radeon_combios_output_lock(encoder, true);
}
static void radeon_legacy_tv_dac_mode_set(struct drm_encoder *encoder,
struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_crtc *radeon_crtc = to_radeon_crtc(encoder->crtc);
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct radeon_encoder_tv_dac *tv_dac = radeon_encoder->enc_priv;
uint32_t tv_dac_cntl, gpiopad_a = 0, dac2_cntl, disp_output_cntl = 0;
uint32_t disp_hw_debug = 0, fp2_gen_cntl = 0, disp_tv_out_cntl = 0;
bool is_tv = false;
DRM_DEBUG_KMS("\n");
is_tv = radeon_encoder->active_device & ATOM_DEVICE_TV_SUPPORT ? true : false;
if (rdev->family != CHIP_R200) {
tv_dac_cntl = RREG32(RADEON_TV_DAC_CNTL);
if (rdev->family == CHIP_R420 ||
rdev->family == CHIP_R423 ||
rdev->family == CHIP_RV410) {
tv_dac_cntl &= ~(RADEON_TV_DAC_STD_MASK |
RADEON_TV_DAC_BGADJ_MASK |
R420_TV_DAC_DACADJ_MASK |
R420_TV_DAC_RDACPD |
R420_TV_DAC_GDACPD |
R420_TV_DAC_BDACPD |
R420_TV_DAC_TVENABLE);
} else {
tv_dac_cntl &= ~(RADEON_TV_DAC_STD_MASK |
RADEON_TV_DAC_BGADJ_MASK |
RADEON_TV_DAC_DACADJ_MASK |
RADEON_TV_DAC_RDACPD |
RADEON_TV_DAC_GDACPD |
RADEON_TV_DAC_BDACPD);
}
tv_dac_cntl |= RADEON_TV_DAC_NBLANK | RADEON_TV_DAC_NHOLD;
if (is_tv) {
if (tv_dac->tv_std == TV_STD_NTSC ||
tv_dac->tv_std == TV_STD_NTSC_J ||
tv_dac->tv_std == TV_STD_PAL_M ||
tv_dac->tv_std == TV_STD_PAL_60)
tv_dac_cntl |= tv_dac->ntsc_tvdac_adj;
else
tv_dac_cntl |= tv_dac->pal_tvdac_adj;
if (tv_dac->tv_std == TV_STD_NTSC ||
tv_dac->tv_std == TV_STD_NTSC_J)
tv_dac_cntl |= RADEON_TV_DAC_STD_NTSC;
else
tv_dac_cntl |= RADEON_TV_DAC_STD_PAL;
} else
tv_dac_cntl |= (RADEON_TV_DAC_STD_PS2 |
tv_dac->ps2_tvdac_adj);
WREG32(RADEON_TV_DAC_CNTL, tv_dac_cntl);
}
if (ASIC_IS_R300(rdev)) {
gpiopad_a = RREG32(RADEON_GPIOPAD_A) | 1;
disp_output_cntl = RREG32(RADEON_DISP_OUTPUT_CNTL);
} else if (rdev->family != CHIP_R200)
disp_hw_debug = RREG32(RADEON_DISP_HW_DEBUG);
else if (rdev->family == CHIP_R200)
fp2_gen_cntl = RREG32(RADEON_FP2_GEN_CNTL);
if (rdev->family >= CHIP_R200)
disp_tv_out_cntl = RREG32(RADEON_DISP_TV_OUT_CNTL);
if (is_tv) {
uint32_t dac_cntl;
dac_cntl = RREG32(RADEON_DAC_CNTL);
dac_cntl &= ~RADEON_DAC_TVO_EN;
WREG32(RADEON_DAC_CNTL, dac_cntl);
if (ASIC_IS_R300(rdev))
gpiopad_a = RREG32(RADEON_GPIOPAD_A) & ~1;
dac2_cntl = RREG32(RADEON_DAC_CNTL2) & ~RADEON_DAC2_DAC2_CLK_SEL;
if (radeon_crtc->crtc_id == 0) {
if (ASIC_IS_R300(rdev)) {
disp_output_cntl &= ~RADEON_DISP_TVDAC_SOURCE_MASK;
disp_output_cntl |= (RADEON_DISP_TVDAC_SOURCE_CRTC |
RADEON_DISP_TV_SOURCE_CRTC);
}
if (rdev->family >= CHIP_R200) {
disp_tv_out_cntl &= ~RADEON_DISP_TV_PATH_SRC_CRTC2;
} else {
disp_hw_debug |= RADEON_CRT2_DISP1_SEL;
}
} else {
if (ASIC_IS_R300(rdev)) {
disp_output_cntl &= ~RADEON_DISP_TVDAC_SOURCE_MASK;
disp_output_cntl |= RADEON_DISP_TV_SOURCE_CRTC;
}
if (rdev->family >= CHIP_R200) {
disp_tv_out_cntl |= RADEON_DISP_TV_PATH_SRC_CRTC2;
} else {
disp_hw_debug &= ~RADEON_CRT2_DISP1_SEL;
}
}
WREG32(RADEON_DAC_CNTL2, dac2_cntl);
} else {
dac2_cntl = RREG32(RADEON_DAC_CNTL2) | RADEON_DAC2_DAC2_CLK_SEL;
if (radeon_crtc->crtc_id == 0) {
if (ASIC_IS_R300(rdev)) {
disp_output_cntl &= ~RADEON_DISP_TVDAC_SOURCE_MASK;
disp_output_cntl |= RADEON_DISP_TVDAC_SOURCE_CRTC;
} else if (rdev->family == CHIP_R200) {
fp2_gen_cntl &= ~(R200_FP2_SOURCE_SEL_MASK |
RADEON_FP2_DVO_RATE_SEL_SDR);
} else
disp_hw_debug |= RADEON_CRT2_DISP1_SEL;
} else {
if (ASIC_IS_R300(rdev)) {
disp_output_cntl &= ~RADEON_DISP_TVDAC_SOURCE_MASK;
disp_output_cntl |= RADEON_DISP_TVDAC_SOURCE_CRTC2;
} else if (rdev->family == CHIP_R200) {
fp2_gen_cntl &= ~(R200_FP2_SOURCE_SEL_MASK |
RADEON_FP2_DVO_RATE_SEL_SDR);
fp2_gen_cntl |= R200_FP2_SOURCE_SEL_CRTC2;
} else
disp_hw_debug &= ~RADEON_CRT2_DISP1_SEL;
}
WREG32(RADEON_DAC_CNTL2, dac2_cntl);
}
if (ASIC_IS_R300(rdev)) {
WREG32_P(RADEON_GPIOPAD_A, gpiopad_a, ~1);
WREG32(RADEON_DISP_OUTPUT_CNTL, disp_output_cntl);
} else if (rdev->family != CHIP_R200)
WREG32(RADEON_DISP_HW_DEBUG, disp_hw_debug);
else if (rdev->family == CHIP_R200)
WREG32(RADEON_FP2_GEN_CNTL, fp2_gen_cntl);
if (rdev->family >= CHIP_R200)
WREG32(RADEON_DISP_TV_OUT_CNTL, disp_tv_out_cntl);
if (is_tv)
radeon_legacy_tv_mode_set(encoder, mode, adjusted_mode);
if (rdev->is_atom_bios)
radeon_atombios_encoder_crtc_scratch_regs(encoder, radeon_crtc->crtc_id);
else
radeon_combios_encoder_crtc_scratch_regs(encoder, radeon_crtc->crtc_id);
}
static bool r300_legacy_tv_detect(struct drm_encoder *encoder,
struct drm_connector *connector)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
uint32_t crtc2_gen_cntl, tv_dac_cntl, dac_cntl2, dac_ext_cntl;
uint32_t disp_output_cntl, gpiopad_a, tmp;
bool found = false;
/* save regs needed */
gpiopad_a = RREG32(RADEON_GPIOPAD_A);
dac_cntl2 = RREG32(RADEON_DAC_CNTL2);
crtc2_gen_cntl = RREG32(RADEON_CRTC2_GEN_CNTL);
dac_ext_cntl = RREG32(RADEON_DAC_EXT_CNTL);
tv_dac_cntl = RREG32(RADEON_TV_DAC_CNTL);
disp_output_cntl = RREG32(RADEON_DISP_OUTPUT_CNTL);
WREG32_P(RADEON_GPIOPAD_A, 0, ~1);
WREG32(RADEON_DAC_CNTL2, RADEON_DAC2_DAC2_CLK_SEL);
WREG32(RADEON_CRTC2_GEN_CNTL,
RADEON_CRTC2_CRT2_ON | RADEON_CRTC2_VSYNC_TRISTAT);
tmp = disp_output_cntl & ~RADEON_DISP_TVDAC_SOURCE_MASK;
tmp |= RADEON_DISP_TVDAC_SOURCE_CRTC2;
WREG32(RADEON_DISP_OUTPUT_CNTL, tmp);
WREG32(RADEON_DAC_EXT_CNTL,
RADEON_DAC2_FORCE_BLANK_OFF_EN |
RADEON_DAC2_FORCE_DATA_EN |
RADEON_DAC_FORCE_DATA_SEL_RGB |
(0xec << RADEON_DAC_FORCE_DATA_SHIFT));
WREG32(RADEON_TV_DAC_CNTL,
RADEON_TV_DAC_STD_NTSC |
(8 << RADEON_TV_DAC_BGADJ_SHIFT) |
(6 << RADEON_TV_DAC_DACADJ_SHIFT));
RREG32(RADEON_TV_DAC_CNTL);
mdelay(4);
WREG32(RADEON_TV_DAC_CNTL,
RADEON_TV_DAC_NBLANK |
RADEON_TV_DAC_NHOLD |
RADEON_TV_MONITOR_DETECT_EN |
RADEON_TV_DAC_STD_NTSC |
(8 << RADEON_TV_DAC_BGADJ_SHIFT) |
(6 << RADEON_TV_DAC_DACADJ_SHIFT));
RREG32(RADEON_TV_DAC_CNTL);
mdelay(6);
tmp = RREG32(RADEON_TV_DAC_CNTL);
if ((tmp & RADEON_TV_DAC_GDACDET) != 0) {
found = true;
DRM_DEBUG_KMS("S-video TV connection detected\n");
} else if ((tmp & RADEON_TV_DAC_BDACDET) != 0) {
found = true;
DRM_DEBUG_KMS("Composite TV connection detected\n");
}
WREG32(RADEON_TV_DAC_CNTL, tv_dac_cntl);
WREG32(RADEON_DAC_EXT_CNTL, dac_ext_cntl);
WREG32(RADEON_CRTC2_GEN_CNTL, crtc2_gen_cntl);
WREG32(RADEON_DISP_OUTPUT_CNTL, disp_output_cntl);
WREG32(RADEON_DAC_CNTL2, dac_cntl2);
WREG32_P(RADEON_GPIOPAD_A, gpiopad_a, ~1);
return found;
}
static bool radeon_legacy_tv_detect(struct drm_encoder *encoder,
struct drm_connector *connector)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
uint32_t tv_dac_cntl, dac_cntl2;
uint32_t config_cntl, tv_pre_dac_mux_cntl, tv_master_cntl, tmp;
bool found = false;
if (ASIC_IS_R300(rdev))
return r300_legacy_tv_detect(encoder, connector);
dac_cntl2 = RREG32(RADEON_DAC_CNTL2);
tv_master_cntl = RREG32(RADEON_TV_MASTER_CNTL);
tv_dac_cntl = RREG32(RADEON_TV_DAC_CNTL);
config_cntl = RREG32(RADEON_CONFIG_CNTL);
tv_pre_dac_mux_cntl = RREG32(RADEON_TV_PRE_DAC_MUX_CNTL);
tmp = dac_cntl2 & ~RADEON_DAC2_DAC2_CLK_SEL;
WREG32(RADEON_DAC_CNTL2, tmp);
tmp = tv_master_cntl | RADEON_TV_ON;
tmp &= ~(RADEON_TV_ASYNC_RST |
RADEON_RESTART_PHASE_FIX |
RADEON_CRT_FIFO_CE_EN |
RADEON_TV_FIFO_CE_EN |
RADEON_RE_SYNC_NOW_SEL_MASK);
tmp |= RADEON_TV_FIFO_ASYNC_RST | RADEON_CRT_ASYNC_RST;
WREG32(RADEON_TV_MASTER_CNTL, tmp);
tmp = RADEON_TV_DAC_NBLANK | RADEON_TV_DAC_NHOLD |
RADEON_TV_MONITOR_DETECT_EN | RADEON_TV_DAC_STD_NTSC |
(8 << RADEON_TV_DAC_BGADJ_SHIFT);
if (config_cntl & RADEON_CFG_ATI_REV_ID_MASK)
tmp |= (4 << RADEON_TV_DAC_DACADJ_SHIFT);
else
tmp |= (8 << RADEON_TV_DAC_DACADJ_SHIFT);
WREG32(RADEON_TV_DAC_CNTL, tmp);
tmp = RADEON_C_GRN_EN | RADEON_CMP_BLU_EN |
RADEON_RED_MX_FORCE_DAC_DATA |
RADEON_GRN_MX_FORCE_DAC_DATA |
RADEON_BLU_MX_FORCE_DAC_DATA |
(0x109 << RADEON_TV_FORCE_DAC_DATA_SHIFT);
WREG32(RADEON_TV_PRE_DAC_MUX_CNTL, tmp);
mdelay(3);
tmp = RREG32(RADEON_TV_DAC_CNTL);
if (tmp & RADEON_TV_DAC_GDACDET) {
found = true;
DRM_DEBUG_KMS("S-video TV connection detected\n");
} else if ((tmp & RADEON_TV_DAC_BDACDET) != 0) {
found = true;
DRM_DEBUG_KMS("Composite TV connection detected\n");
}
WREG32(RADEON_TV_PRE_DAC_MUX_CNTL, tv_pre_dac_mux_cntl);
WREG32(RADEON_TV_DAC_CNTL, tv_dac_cntl);
WREG32(RADEON_TV_MASTER_CNTL, tv_master_cntl);
WREG32(RADEON_DAC_CNTL2, dac_cntl2);
return found;
}
static enum drm_connector_status radeon_legacy_tv_dac_detect(struct drm_encoder *encoder,
struct drm_connector *connector)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
uint32_t crtc2_gen_cntl, tv_dac_cntl, dac_cntl2, dac_ext_cntl;
uint32_t disp_hw_debug, disp_output_cntl, gpiopad_a, pixclks_cntl, tmp;
enum drm_connector_status found = connector_status_disconnected;
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct radeon_encoder_tv_dac *tv_dac = radeon_encoder->enc_priv;
bool color = true;
struct drm_crtc *crtc;
/* find out if crtc2 is in use or if this encoder is using it */
list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
struct radeon_crtc *radeon_crtc = to_radeon_crtc(crtc);
if ((radeon_crtc->crtc_id == 1) && crtc->enabled) {
if (encoder->crtc != crtc) {
return connector_status_disconnected;
}
}
}
if (connector->connector_type == DRM_MODE_CONNECTOR_SVIDEO ||
connector->connector_type == DRM_MODE_CONNECTOR_Composite ||
connector->connector_type == DRM_MODE_CONNECTOR_9PinDIN) {
bool tv_detect;
if (radeon_encoder->active_device && !(radeon_encoder->active_device & ATOM_DEVICE_TV_SUPPORT))
return connector_status_disconnected;
tv_detect = radeon_legacy_tv_detect(encoder, connector);
if (tv_detect && tv_dac)
found = connector_status_connected;
return found;
}
/* don't probe if the encoder is being used for something else not CRT related */
if (radeon_encoder->active_device && !(radeon_encoder->active_device & ATOM_DEVICE_CRT_SUPPORT)) {
DRM_INFO("not detecting due to %08x\n", radeon_encoder->active_device);
return connector_status_disconnected;
}
/* save the regs we need */
pixclks_cntl = RREG32_PLL(RADEON_PIXCLKS_CNTL);
gpiopad_a = ASIC_IS_R300(rdev) ? RREG32(RADEON_GPIOPAD_A) : 0;
disp_output_cntl = ASIC_IS_R300(rdev) ? RREG32(RADEON_DISP_OUTPUT_CNTL) : 0;
disp_hw_debug = ASIC_IS_R300(rdev) ? 0 : RREG32(RADEON_DISP_HW_DEBUG);
crtc2_gen_cntl = RREG32(RADEON_CRTC2_GEN_CNTL);
tv_dac_cntl = RREG32(RADEON_TV_DAC_CNTL);
dac_ext_cntl = RREG32(RADEON_DAC_EXT_CNTL);
dac_cntl2 = RREG32(RADEON_DAC_CNTL2);
tmp = pixclks_cntl & ~(RADEON_PIX2CLK_ALWAYS_ONb
| RADEON_PIX2CLK_DAC_ALWAYS_ONb);
WREG32_PLL(RADEON_PIXCLKS_CNTL, tmp);
if (ASIC_IS_R300(rdev))
WREG32_P(RADEON_GPIOPAD_A, 1, ~1);
tmp = crtc2_gen_cntl & ~RADEON_CRTC2_PIX_WIDTH_MASK;
tmp |= RADEON_CRTC2_CRT2_ON |
(2 << RADEON_CRTC2_PIX_WIDTH_SHIFT);
WREG32(RADEON_CRTC2_GEN_CNTL, tmp);
if (ASIC_IS_R300(rdev)) {
tmp = disp_output_cntl & ~RADEON_DISP_TVDAC_SOURCE_MASK;
tmp |= RADEON_DISP_TVDAC_SOURCE_CRTC2;
WREG32(RADEON_DISP_OUTPUT_CNTL, tmp);
} else {
tmp = disp_hw_debug & ~RADEON_CRT2_DISP1_SEL;
WREG32(RADEON_DISP_HW_DEBUG, tmp);
}
tmp = RADEON_TV_DAC_NBLANK |
RADEON_TV_DAC_NHOLD |
RADEON_TV_MONITOR_DETECT_EN |
RADEON_TV_DAC_STD_PS2;
WREG32(RADEON_TV_DAC_CNTL, tmp);
tmp = RADEON_DAC2_FORCE_BLANK_OFF_EN |
RADEON_DAC2_FORCE_DATA_EN;
if (color)
tmp |= RADEON_DAC_FORCE_DATA_SEL_RGB;
else
tmp |= RADEON_DAC_FORCE_DATA_SEL_G;
if (ASIC_IS_R300(rdev))
tmp |= (0x1b6 << RADEON_DAC_FORCE_DATA_SHIFT);
else
tmp |= (0x180 << RADEON_DAC_FORCE_DATA_SHIFT);
WREG32(RADEON_DAC_EXT_CNTL, tmp);
tmp = dac_cntl2 | RADEON_DAC2_DAC2_CLK_SEL | RADEON_DAC2_CMP_EN;
WREG32(RADEON_DAC_CNTL2, tmp);
udelay(10000);
if (ASIC_IS_R300(rdev)) {
if (RREG32(RADEON_DAC_CNTL2) & RADEON_DAC2_CMP_OUT_B)
found = connector_status_connected;
} else {
if (RREG32(RADEON_DAC_CNTL2) & RADEON_DAC2_CMP_OUTPUT)
found = connector_status_connected;
}
/* restore regs we used */
WREG32(RADEON_DAC_CNTL2, dac_cntl2);
WREG32(RADEON_DAC_EXT_CNTL, dac_ext_cntl);
WREG32(RADEON_TV_DAC_CNTL, tv_dac_cntl);
WREG32(RADEON_CRTC2_GEN_CNTL, crtc2_gen_cntl);
if (ASIC_IS_R300(rdev)) {
WREG32(RADEON_DISP_OUTPUT_CNTL, disp_output_cntl);
WREG32_P(RADEON_GPIOPAD_A, gpiopad_a, ~1);
} else {
WREG32(RADEON_DISP_HW_DEBUG, disp_hw_debug);
}
WREG32_PLL(RADEON_PIXCLKS_CNTL, pixclks_cntl);
return found;
}
static const struct drm_encoder_helper_funcs radeon_legacy_tv_dac_helper_funcs = {
.dpms = radeon_legacy_tv_dac_dpms,
.mode_fixup = radeon_legacy_mode_fixup,
.prepare = radeon_legacy_tv_dac_prepare,
.mode_set = radeon_legacy_tv_dac_mode_set,
.commit = radeon_legacy_tv_dac_commit,
.detect = radeon_legacy_tv_dac_detect,
.disable = radeon_legacy_encoder_disable,
};
static const struct drm_encoder_funcs radeon_legacy_tv_dac_enc_funcs = {
.destroy = radeon_enc_destroy,
};
static struct radeon_encoder_int_tmds *radeon_legacy_get_tmds_info(struct radeon_encoder *encoder)
{
struct drm_device *dev = encoder->base.dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_encoder_int_tmds *tmds = NULL;
bool ret;
tmds = kzalloc(sizeof(struct radeon_encoder_int_tmds), GFP_KERNEL);
if (!tmds)
return NULL;
if (rdev->is_atom_bios)
ret = radeon_atombios_get_tmds_info(encoder, tmds);
else
ret = radeon_legacy_get_tmds_info_from_combios(encoder, tmds);
if (ret == false)
radeon_legacy_get_tmds_info_from_table(encoder, tmds);
return tmds;
}
static struct radeon_encoder_ext_tmds *radeon_legacy_get_ext_tmds_info(struct radeon_encoder *encoder)
{
struct drm_device *dev = encoder->base.dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_encoder_ext_tmds *tmds = NULL;
bool ret;
if (rdev->is_atom_bios)
return NULL;
tmds = kzalloc(sizeof(struct radeon_encoder_ext_tmds), GFP_KERNEL);
if (!tmds)
return NULL;
ret = radeon_legacy_get_ext_tmds_info_from_combios(encoder, tmds);
if (ret == false)
radeon_legacy_get_ext_tmds_info_from_table(encoder, tmds);
return tmds;
}
void
radeon_add_legacy_encoder(struct drm_device *dev, uint32_t encoder_enum, uint32_t supported_device)
{
struct radeon_device *rdev = dev->dev_private;
struct drm_encoder *encoder;
struct radeon_encoder *radeon_encoder;
/* see if we already added it */
list_for_each_entry(encoder, &dev->mode_config.encoder_list, head) {
radeon_encoder = to_radeon_encoder(encoder);
if (radeon_encoder->encoder_enum == encoder_enum) {
radeon_encoder->devices |= supported_device;
return;
}
}
/* add a new one */
radeon_encoder = kzalloc(sizeof(struct radeon_encoder), GFP_KERNEL);
if (!radeon_encoder)
return;
encoder = &radeon_encoder->base;
if (rdev->flags & RADEON_SINGLE_CRTC)
encoder->possible_crtcs = 0x1;
else
encoder->possible_crtcs = 0x3;
radeon_encoder->enc_priv = NULL;
radeon_encoder->encoder_enum = encoder_enum;
radeon_encoder->encoder_id = (encoder_enum & OBJECT_ID_MASK) >> OBJECT_ID_SHIFT;
radeon_encoder->devices = supported_device;
radeon_encoder->rmx_type = RMX_OFF;
switch (radeon_encoder->encoder_id) {
case ENCODER_OBJECT_ID_INTERNAL_LVDS:
encoder->possible_crtcs = 0x1;
drm_encoder_init(dev, encoder, &radeon_legacy_lvds_enc_funcs, DRM_MODE_ENCODER_LVDS);
drm_encoder_helper_add(encoder, &radeon_legacy_lvds_helper_funcs);
if (rdev->is_atom_bios)
radeon_encoder->enc_priv = radeon_atombios_get_lvds_info(radeon_encoder);
else
radeon_encoder->enc_priv = radeon_combios_get_lvds_info(radeon_encoder);
radeon_encoder->rmx_type = RMX_FULL;
break;
case ENCODER_OBJECT_ID_INTERNAL_TMDS1:
drm_encoder_init(dev, encoder, &radeon_legacy_tmds_int_enc_funcs, DRM_MODE_ENCODER_TMDS);
drm_encoder_helper_add(encoder, &radeon_legacy_tmds_int_helper_funcs);
radeon_encoder->enc_priv = radeon_legacy_get_tmds_info(radeon_encoder);
break;
case ENCODER_OBJECT_ID_INTERNAL_DAC1:
drm_encoder_init(dev, encoder, &radeon_legacy_primary_dac_enc_funcs, DRM_MODE_ENCODER_DAC);
drm_encoder_helper_add(encoder, &radeon_legacy_primary_dac_helper_funcs);
if (rdev->is_atom_bios)
radeon_encoder->enc_priv = radeon_atombios_get_primary_dac_info(radeon_encoder);
else
radeon_encoder->enc_priv = radeon_combios_get_primary_dac_info(radeon_encoder);
break;
case ENCODER_OBJECT_ID_INTERNAL_DAC2:
drm_encoder_init(dev, encoder, &radeon_legacy_tv_dac_enc_funcs, DRM_MODE_ENCODER_TVDAC);
drm_encoder_helper_add(encoder, &radeon_legacy_tv_dac_helper_funcs);
if (rdev->is_atom_bios)
radeon_encoder->enc_priv = radeon_atombios_get_tv_dac_info(radeon_encoder);
else
radeon_encoder->enc_priv = radeon_combios_get_tv_dac_info(radeon_encoder);
break;
case ENCODER_OBJECT_ID_INTERNAL_DVO1:
drm_encoder_init(dev, encoder, &radeon_legacy_tmds_ext_enc_funcs, DRM_MODE_ENCODER_TMDS);
drm_encoder_helper_add(encoder, &radeon_legacy_tmds_ext_helper_funcs);
if (!rdev->is_atom_bios)
radeon_encoder->enc_priv = radeon_legacy_get_ext_tmds_info(radeon_encoder);
break;
}
}
| gpl-2.0 |
farleylai/linux | drivers/net/eepro.c | 2769 | 52205 | /* eepro.c: Intel EtherExpress Pro/10 device driver for Linux. */
/*
Written 1994, 1995,1996 by Bao C. Ha.
Copyright (C) 1994, 1995,1996 by Bao C. Ha.
This software may be used and distributed
according to the terms of the GNU General Public License,
incorporated herein by reference.
The author may be reached at bao.ha@srs.gov
or 418 Hastings Place, Martinez, GA 30907.
Things remaining to do:
Better record keeping of errors.
Eliminate transmit interrupt to reduce overhead.
Implement "concurrent processing". I won't be doing it!
Bugs:
If you have a problem of not detecting the 82595 during a
reboot (warm reset), disable the FLASH memory should fix it.
This is a compatibility hardware problem.
Versions:
0.13b basic ethtool support (aris, 09/13/2004)
0.13a in memory shortage, drop packets also in board
(Michael Westermann <mw@microdata-pos.de>, 07/30/2002)
0.13 irq sharing, rewrote probe function, fixed a nasty bug in
hardware_send_packet and a major cleanup (aris, 11/08/2001)
0.12d fixing a problem with single card detected as eight eth devices
fixing a problem with sudden drop in card performance
(chris (asdn@go2.pl), 10/29/2001)
0.12c fixing some problems with old cards (aris, 01/08/2001)
0.12b misc fixes (aris, 06/26/2000)
0.12a port of version 0.12a of 2.2.x kernels to 2.3.x
(aris (aris@conectiva.com.br), 05/19/2000)
0.11e some tweaks about multiple cards support (PdP, jul/aug 1999)
0.11d added __initdata, __init stuff; call spin_lock_init
in eepro_probe1. Replaced "eepro" by dev->name. Augmented
the code protected by spin_lock in interrupt routine
(PdP, 12/12/1998)
0.11c minor cleanup (PdP, RMC, 09/12/1998)
0.11b Pascal Dupuis (dupuis@lei.ucl.ac.be): works as a module
under 2.1.xx. Debug messages are flagged as KERN_DEBUG to
avoid console flooding. Added locking at critical parts. Now
the dawn thing is SMP safe.
0.11a Attempt to get 2.1.xx support up (RMC)
0.11 Brian Candler added support for multiple cards. Tested as
a module, no idea if it works when compiled into kernel.
0.10e Rick Bressler notified me that ifconfig up;ifconfig down fails
because the irq is lost somewhere. Fixed that by moving
request_irq and free_irq to eepro_open and eepro_close respectively.
0.10d Ugh! Now Wakeup works. Was seriously broken in my first attempt.
I'll need to find a way to specify an ioport other than
the default one in the PnP case. PnP definitively sucks.
And, yes, this is not the only reason.
0.10c PnP Wakeup Test for 595FX. uncomment #define PnPWakeup;
to use.
0.10b Should work now with (some) Pro/10+. At least for
me (and my two cards) it does. _No_ guarantee for
function with non-Pro/10+ cards! (don't have any)
(RMC, 9/11/96)
0.10 Added support for the Etherexpress Pro/10+. The
IRQ map was changed significantly from the old
pro/10. The new interrupt map was provided by
Rainer M. Canavan (Canavan@Zeus.cs.bonn.edu).
(BCH, 9/3/96)
0.09 Fixed a race condition in the transmit algorithm,
which causes crashes under heavy load with fast
pentium computers. The performance should also
improve a bit. The size of RX buffer, and hence
TX buffer, can also be changed via lilo or insmod.
(BCH, 7/31/96)
0.08 Implement 32-bit I/O for the 82595TX and 82595FX
based lan cards. Disable full-duplex mode if TPE
is not used. (BCH, 4/8/96)
0.07a Fix a stat report which counts every packet as a
heart-beat failure. (BCH, 6/3/95)
0.07 Modified to support all other 82595-based lan cards.
The IRQ vector of the EtherExpress Pro will be set
according to the value saved in the EEPROM. For other
cards, I will do autoirq_request() to grab the next
available interrupt vector. (BCH, 3/17/95)
0.06a,b Interim released. Minor changes in the comments and
print out format. (BCH, 3/9/95 and 3/14/95)
0.06 First stable release that I am comfortable with. (BCH,
3/2/95)
0.05 Complete testing of multicast. (BCH, 2/23/95)
0.04 Adding multicast support. (BCH, 2/14/95)
0.03 First widely alpha release for public testing.
(BCH, 2/14/95)
*/
static const char version[] =
"eepro.c: v0.13b 09/13/2004 aris@cathedrallabs.org\n";
#include <linux/module.h>
/*
Sources:
This driver wouldn't have been written without the availability
of the Crynwr's Lan595 driver source code. It helps me to
familiarize with the 82595 chipset while waiting for the Intel
documentation. I also learned how to detect the 82595 using
the packet driver's technique.
This driver is written by cutting and pasting the skeleton.c driver
provided by Donald Becker. I also borrowed the EEPROM routine from
Donald Becker's 82586 driver.
Datasheet for the Intel 82595 (including the TX and FX version). It
provides just enough info that the casual reader might think that it
documents the i82595.
The User Manual for the 82595. It provides a lot of the missing
information.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/in.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/spinlock.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/bitops.h>
#include <linux/ethtool.h>
#include <asm/system.h>
#include <asm/io.h>
#include <asm/dma.h>
#define DRV_NAME "eepro"
#define DRV_VERSION "0.13c"
#define compat_dev_kfree_skb( skb, mode ) dev_kfree_skb( (skb) )
/* I had reports of looong delays with SLOW_DOWN defined as udelay(2) */
#define SLOW_DOWN inb(0x80)
/* udelay(2) */
#define compat_init_data __initdata
enum iftype { AUI=0, BNC=1, TPE=2 };
/* First, a few definitions that the brave might change. */
/* A zero-terminated list of I/O addresses to be probed. */
static unsigned int eepro_portlist[] compat_init_data =
{ 0x300, 0x210, 0x240, 0x280, 0x2C0, 0x200, 0x320, 0x340, 0x360, 0};
/* note: 0x300 is default, the 595FX supports ALL IO Ports
from 0x000 to 0x3F0, some of which are reserved in PCs */
/* To try the (not-really PnP Wakeup: */
/*
#define PnPWakeup
*/
/* use 0 for production, 1 for verification, >2 for debug */
#ifndef NET_DEBUG
#define NET_DEBUG 0
#endif
static unsigned int net_debug = NET_DEBUG;
/* The number of low I/O ports used by the ethercard. */
#define EEPRO_IO_EXTENT 16
/* Different 82595 chips */
#define LAN595 0
#define LAN595TX 1
#define LAN595FX 2
#define LAN595FX_10ISA 3
/* Information that need to be kept for each board. */
struct eepro_local {
unsigned rx_start;
unsigned tx_start; /* start of the transmit chain */
int tx_last; /* pointer to last packet in the transmit chain */
unsigned tx_end; /* end of the transmit chain (plus 1) */
int eepro; /* 1 for the EtherExpress Pro/10,
2 for the EtherExpress Pro/10+,
3 for the EtherExpress 10 (blue cards),
0 for other 82595-based lan cards. */
int version; /* a flag to indicate if this is a TX or FX
version of the 82595 chip. */
int stepping;
spinlock_t lock; /* Serializing lock */
unsigned rcv_ram; /* pre-calculated space for rx */
unsigned xmt_ram; /* pre-calculated space for tx */
unsigned char xmt_bar;
unsigned char xmt_lower_limit_reg;
unsigned char xmt_upper_limit_reg;
short xmt_lower_limit;
short xmt_upper_limit;
short rcv_lower_limit;
short rcv_upper_limit;
unsigned char eeprom_reg;
unsigned short word[8];
};
/* The station (ethernet) address prefix, used for IDing the board. */
#define SA_ADDR0 0x00 /* Etherexpress Pro/10 */
#define SA_ADDR1 0xaa
#define SA_ADDR2 0x00
#define GetBit(x,y) ((x & (1<<y))>>y)
/* EEPROM Word 0: */
#define ee_PnP 0 /* Plug 'n Play enable bit */
#define ee_Word1 1 /* Word 1? */
#define ee_BusWidth 2 /* 8/16 bit */
#define ee_FlashAddr 3 /* Flash Address */
#define ee_FlashMask 0x7 /* Mask */
#define ee_AutoIO 6 /* */
#define ee_reserved0 7 /* =0! */
#define ee_Flash 8 /* Flash there? */
#define ee_AutoNeg 9 /* Auto Negotiation enabled? */
#define ee_IO0 10 /* IO Address LSB */
#define ee_IO0Mask 0x /*...*/
#define ee_IO1 15 /* IO MSB */
/* EEPROM Word 1: */
#define ee_IntSel 0 /* Interrupt */
#define ee_IntMask 0x7
#define ee_LI 3 /* Link Integrity 0= enabled */
#define ee_PC 4 /* Polarity Correction 0= enabled */
#define ee_TPE_AUI 5 /* PortSelection 1=TPE */
#define ee_Jabber 6 /* Jabber prevention 0= enabled */
#define ee_AutoPort 7 /* Auto Port Selection 1= Disabled */
#define ee_SMOUT 8 /* SMout Pin Control 0= Input */
#define ee_PROM 9 /* Flash EPROM / PROM 0=Flash */
#define ee_reserved1 10 /* .. 12 =0! */
#define ee_AltReady 13 /* Alternate Ready, 0=normal */
#define ee_reserved2 14 /* =0! */
#define ee_Duplex 15
/* Word2,3,4: */
#define ee_IA5 0 /*bit start for individual Addr Byte 5 */
#define ee_IA4 8 /*bit start for individual Addr Byte 5 */
#define ee_IA3 0 /*bit start for individual Addr Byte 5 */
#define ee_IA2 8 /*bit start for individual Addr Byte 5 */
#define ee_IA1 0 /*bit start for individual Addr Byte 5 */
#define ee_IA0 8 /*bit start for individual Addr Byte 5 */
/* Word 5: */
#define ee_BNC_TPE 0 /* 0=TPE */
#define ee_BootType 1 /* 00=None, 01=IPX, 10=ODI, 11=NDIS */
#define ee_BootTypeMask 0x3
#define ee_NumConn 3 /* Number of Connections 0= One or Two */
#define ee_FlashSock 4 /* Presence of Flash Socket 0= Present */
#define ee_PortTPE 5
#define ee_PortBNC 6
#define ee_PortAUI 7
#define ee_PowerMgt 10 /* 0= disabled */
#define ee_CP 13 /* Concurrent Processing */
#define ee_CPMask 0x7
/* Word 6: */
#define ee_Stepping 0 /* Stepping info */
#define ee_StepMask 0x0F
#define ee_BoardID 4 /* Manucaturer Board ID, reserved */
#define ee_BoardMask 0x0FFF
/* Word 7: */
#define ee_INT_TO_IRQ 0 /* int to IRQ Mapping = 0x1EB8 for Pro/10+ */
#define ee_FX_INT2IRQ 0x1EB8 /* the _only_ mapping allowed for FX chips */
/*..*/
#define ee_SIZE 0x40 /* total EEprom Size */
#define ee_Checksum 0xBABA /* initial and final value for adding checksum */
/* Card identification via EEprom: */
#define ee_addr_vendor 0x10 /* Word offset for EISA Vendor ID */
#define ee_addr_id 0x11 /* Word offset for Card ID */
#define ee_addr_SN 0x12 /* Serial Number */
#define ee_addr_CRC_8 0x14 /* CRC over last thee Bytes */
#define ee_vendor_intel0 0x25 /* Vendor ID Intel */
#define ee_vendor_intel1 0xD4
#define ee_id_eepro10p0 0x10 /* ID for eepro/10+ */
#define ee_id_eepro10p1 0x31
#define TX_TIMEOUT ((4*HZ)/10)
/* Index to functions, as function prototypes. */
static int eepro_probe1(struct net_device *dev, int autoprobe);
static int eepro_open(struct net_device *dev);
static netdev_tx_t eepro_send_packet(struct sk_buff *skb,
struct net_device *dev);
static irqreturn_t eepro_interrupt(int irq, void *dev_id);
static void eepro_rx(struct net_device *dev);
static void eepro_transmit_interrupt(struct net_device *dev);
static int eepro_close(struct net_device *dev);
static void set_multicast_list(struct net_device *dev);
static void eepro_tx_timeout (struct net_device *dev);
static int read_eeprom(int ioaddr, int location, struct net_device *dev);
static int hardware_send_packet(struct net_device *dev, void *buf, short length);
static int eepro_grab_irq(struct net_device *dev);
/*
Details of the i82595.
You will need either the datasheet or the user manual to understand what
is going on here. The 82595 is very different from the 82586, 82593.
The receive algorithm in eepro_rx() is just an implementation of the
RCV ring structure that the Intel 82595 imposes at the hardware level.
The receive buffer is set at 24K, and the transmit buffer is 8K. I
am assuming that the total buffer memory is 32K, which is true for the
Intel EtherExpress Pro/10. If it is less than that on a generic card,
the driver will be broken.
The transmit algorithm in the hardware_send_packet() is similar to the
one in the eepro_rx(). The transmit buffer is a ring linked list.
I just queue the next available packet to the end of the list. In my
system, the 82595 is so fast that the list seems to always contain a
single packet. In other systems with faster computers and more congested
network traffics, the ring linked list should improve performance by
allowing up to 8K worth of packets to be queued.
The sizes of the receive and transmit buffers can now be changed via lilo
or insmod. Lilo uses the appended line "ether=io,irq,debug,rx-buffer,eth0"
where rx-buffer is in KB unit. Modules uses the parameter mem which is
also in KB unit, for example "insmod io=io-address irq=0 mem=rx-buffer."
The receive buffer has to be more than 3K or less than 29K. Otherwise,
it is reset to the default of 24K, and, hence, 8K for the trasnmit
buffer (transmit-buffer = 32K - receive-buffer).
*/
#define RAM_SIZE 0x8000
#define RCV_HEADER 8
#define RCV_DEFAULT_RAM 0x6000
#define XMT_HEADER 8
#define XMT_DEFAULT_RAM (RAM_SIZE - RCV_DEFAULT_RAM)
#define XMT_START_PRO RCV_DEFAULT_RAM
#define XMT_START_10 0x0000
#define RCV_START_PRO 0x0000
#define RCV_START_10 XMT_DEFAULT_RAM
#define RCV_DONE 0x0008
#define RX_OK 0x2000
#define RX_ERROR 0x0d81
#define TX_DONE_BIT 0x0080
#define TX_OK 0x2000
#define CHAIN_BIT 0x8000
#define XMT_STATUS 0x02
#define XMT_CHAIN 0x04
#define XMT_COUNT 0x06
#define BANK0_SELECT 0x00
#define BANK1_SELECT 0x40
#define BANK2_SELECT 0x80
/* Bank 0 registers */
#define COMMAND_REG 0x00 /* Register 0 */
#define MC_SETUP 0x03
#define XMT_CMD 0x04
#define DIAGNOSE_CMD 0x07
#define RCV_ENABLE_CMD 0x08
#define RCV_DISABLE_CMD 0x0a
#define STOP_RCV_CMD 0x0b
#define RESET_CMD 0x0e
#define POWER_DOWN_CMD 0x18
#define RESUME_XMT_CMD 0x1c
#define SEL_RESET_CMD 0x1e
#define STATUS_REG 0x01 /* Register 1 */
#define RX_INT 0x02
#define TX_INT 0x04
#define EXEC_STATUS 0x30
#define ID_REG 0x02 /* Register 2 */
#define R_ROBIN_BITS 0xc0 /* round robin counter */
#define ID_REG_MASK 0x2c
#define ID_REG_SIG 0x24
#define AUTO_ENABLE 0x10
#define INT_MASK_REG 0x03 /* Register 3 */
#define RX_STOP_MASK 0x01
#define RX_MASK 0x02
#define TX_MASK 0x04
#define EXEC_MASK 0x08
#define ALL_MASK 0x0f
#define IO_32_BIT 0x10
#define RCV_BAR 0x04 /* The following are word (16-bit) registers */
#define RCV_STOP 0x06
#define XMT_BAR_PRO 0x0a
#define XMT_BAR_10 0x0b
#define HOST_ADDRESS_REG 0x0c
#define IO_PORT 0x0e
#define IO_PORT_32_BIT 0x0c
/* Bank 1 registers */
#define REG1 0x01
#define WORD_WIDTH 0x02
#define INT_ENABLE 0x80
#define INT_NO_REG 0x02
#define RCV_LOWER_LIMIT_REG 0x08
#define RCV_UPPER_LIMIT_REG 0x09
#define XMT_LOWER_LIMIT_REG_PRO 0x0a
#define XMT_UPPER_LIMIT_REG_PRO 0x0b
#define XMT_LOWER_LIMIT_REG_10 0x0b
#define XMT_UPPER_LIMIT_REG_10 0x0a
/* Bank 2 registers */
#define XMT_Chain_Int 0x20 /* Interrupt at the end of the transmit chain */
#define XMT_Chain_ErrStop 0x40 /* Interrupt at the end of the chain even if there are errors */
#define RCV_Discard_BadFrame 0x80 /* Throw bad frames away, and continue to receive others */
#define REG2 0x02
#define PRMSC_Mode 0x01
#define Multi_IA 0x20
#define REG3 0x03
#define TPE_BIT 0x04
#define BNC_BIT 0x20
#define REG13 0x0d
#define FDX 0x00
#define A_N_ENABLE 0x02
#define I_ADD_REG0 0x04
#define I_ADD_REG1 0x05
#define I_ADD_REG2 0x06
#define I_ADD_REG3 0x07
#define I_ADD_REG4 0x08
#define I_ADD_REG5 0x09
#define EEPROM_REG_PRO 0x0a
#define EEPROM_REG_10 0x0b
#define EESK 0x01
#define EECS 0x02
#define EEDI 0x04
#define EEDO 0x08
/* do a full reset */
#define eepro_reset(ioaddr) outb(RESET_CMD, ioaddr)
/* do a nice reset */
#define eepro_sel_reset(ioaddr) { \
outb(SEL_RESET_CMD, ioaddr); \
SLOW_DOWN; \
SLOW_DOWN; \
}
/* disable all interrupts */
#define eepro_dis_int(ioaddr) outb(ALL_MASK, ioaddr + INT_MASK_REG)
/* clear all interrupts */
#define eepro_clear_int(ioaddr) outb(ALL_MASK, ioaddr + STATUS_REG)
/* enable tx/rx */
#define eepro_en_int(ioaddr) outb(ALL_MASK & ~(RX_MASK | TX_MASK), \
ioaddr + INT_MASK_REG)
/* enable exec event interrupt */
#define eepro_en_intexec(ioaddr) outb(ALL_MASK & ~(EXEC_MASK), ioaddr + INT_MASK_REG)
/* enable rx */
#define eepro_en_rx(ioaddr) outb(RCV_ENABLE_CMD, ioaddr)
/* disable rx */
#define eepro_dis_rx(ioaddr) outb(RCV_DISABLE_CMD, ioaddr)
/* switch bank */
#define eepro_sw2bank0(ioaddr) outb(BANK0_SELECT, ioaddr)
#define eepro_sw2bank1(ioaddr) outb(BANK1_SELECT, ioaddr)
#define eepro_sw2bank2(ioaddr) outb(BANK2_SELECT, ioaddr)
/* enable interrupt line */
#define eepro_en_intline(ioaddr) outb(inb(ioaddr + REG1) | INT_ENABLE,\
ioaddr + REG1)
/* disable interrupt line */
#define eepro_dis_intline(ioaddr) outb(inb(ioaddr + REG1) & 0x7f, \
ioaddr + REG1);
/* set diagnose flag */
#define eepro_diag(ioaddr) outb(DIAGNOSE_CMD, ioaddr)
/* ack for rx int */
#define eepro_ack_rx(ioaddr) outb (RX_INT, ioaddr + STATUS_REG)
/* ack for tx int */
#define eepro_ack_tx(ioaddr) outb (TX_INT, ioaddr + STATUS_REG)
/* a complete sel reset */
#define eepro_complete_selreset(ioaddr) { \
dev->stats.tx_errors++;\
eepro_sel_reset(ioaddr);\
lp->tx_end = \
lp->xmt_lower_limit;\
lp->tx_start = lp->tx_end;\
lp->tx_last = 0;\
dev->trans_start = jiffies;\
netif_wake_queue(dev);\
eepro_en_rx(ioaddr);\
}
/* Check for a network adaptor of this type, and return '0' if one exists.
If dev->base_addr == 0, probe all likely locations.
If dev->base_addr == 1, always return failure.
If dev->base_addr == 2, allocate space for the device and return success
(detachable devices only).
*/
static int __init do_eepro_probe(struct net_device *dev)
{
int i;
int base_addr = dev->base_addr;
int irq = dev->irq;
#ifdef PnPWakeup
/* XXXX for multiple cards should this only be run once? */
/* Wakeup: */
#define WakeupPort 0x279
#define WakeupSeq {0x6A, 0xB5, 0xDA, 0xED, 0xF6, 0xFB, 0x7D, 0xBE,\
0xDF, 0x6F, 0x37, 0x1B, 0x0D, 0x86, 0xC3, 0x61,\
0xB0, 0x58, 0x2C, 0x16, 0x8B, 0x45, 0xA2, 0xD1,\
0xE8, 0x74, 0x3A, 0x9D, 0xCE, 0xE7, 0x73, 0x43}
{
unsigned short int WS[32]=WakeupSeq;
if (request_region(WakeupPort, 2, "eepro wakeup")) {
if (net_debug>5)
printk(KERN_DEBUG "Waking UP\n");
outb_p(0,WakeupPort);
outb_p(0,WakeupPort);
for (i=0; i<32; i++) {
outb_p(WS[i],WakeupPort);
if (net_debug>5) printk(KERN_DEBUG ": %#x ",WS[i]);
}
release_region(WakeupPort, 2);
} else
printk(KERN_WARNING "PnP wakeup region busy!\n");
}
#endif
if (base_addr > 0x1ff) /* Check a single specified location. */
return eepro_probe1(dev, 0);
else if (base_addr != 0) /* Don't probe at all. */
return -ENXIO;
for (i = 0; eepro_portlist[i]; i++) {
dev->base_addr = eepro_portlist[i];
dev->irq = irq;
if (eepro_probe1(dev, 1) == 0)
return 0;
}
return -ENODEV;
}
#ifndef MODULE
struct net_device * __init eepro_probe(int unit)
{
struct net_device *dev = alloc_etherdev(sizeof(struct eepro_local));
int err;
if (!dev)
return ERR_PTR(-ENODEV);
sprintf(dev->name, "eth%d", unit);
netdev_boot_setup_check(dev);
err = do_eepro_probe(dev);
if (err)
goto out;
return dev;
out:
free_netdev(dev);
return ERR_PTR(err);
}
#endif
static void __init printEEPROMInfo(struct net_device *dev)
{
struct eepro_local *lp = netdev_priv(dev);
int ioaddr = dev->base_addr;
unsigned short Word;
int i,j;
j = ee_Checksum;
for (i = 0; i < 8; i++)
j += lp->word[i];
for ( ; i < ee_SIZE; i++)
j += read_eeprom(ioaddr, i, dev);
printk(KERN_DEBUG "Checksum: %#x\n",j&0xffff);
Word = lp->word[0];
printk(KERN_DEBUG "Word0:\n");
printk(KERN_DEBUG " Plug 'n Pray: %d\n",GetBit(Word,ee_PnP));
printk(KERN_DEBUG " Buswidth: %d\n",(GetBit(Word,ee_BusWidth)+1)*8 );
printk(KERN_DEBUG " AutoNegotiation: %d\n",GetBit(Word,ee_AutoNeg));
printk(KERN_DEBUG " IO Address: %#x\n", (Word>>ee_IO0)<<4);
if (net_debug>4) {
Word = lp->word[1];
printk(KERN_DEBUG "Word1:\n");
printk(KERN_DEBUG " INT: %d\n", Word & ee_IntMask);
printk(KERN_DEBUG " LI: %d\n", GetBit(Word,ee_LI));
printk(KERN_DEBUG " PC: %d\n", GetBit(Word,ee_PC));
printk(KERN_DEBUG " TPE/AUI: %d\n", GetBit(Word,ee_TPE_AUI));
printk(KERN_DEBUG " Jabber: %d\n", GetBit(Word,ee_Jabber));
printk(KERN_DEBUG " AutoPort: %d\n", !GetBit(Word,ee_AutoPort));
printk(KERN_DEBUG " Duplex: %d\n", GetBit(Word,ee_Duplex));
}
Word = lp->word[5];
printk(KERN_DEBUG "Word5:\n");
printk(KERN_DEBUG " BNC: %d\n",GetBit(Word,ee_BNC_TPE));
printk(KERN_DEBUG " NumConnectors: %d\n",GetBit(Word,ee_NumConn));
printk(KERN_DEBUG " Has ");
if (GetBit(Word,ee_PortTPE)) printk(KERN_DEBUG "TPE ");
if (GetBit(Word,ee_PortBNC)) printk(KERN_DEBUG "BNC ");
if (GetBit(Word,ee_PortAUI)) printk(KERN_DEBUG "AUI ");
printk(KERN_DEBUG "port(s)\n");
Word = lp->word[6];
printk(KERN_DEBUG "Word6:\n");
printk(KERN_DEBUG " Stepping: %d\n",Word & ee_StepMask);
printk(KERN_DEBUG " BoardID: %d\n",Word>>ee_BoardID);
Word = lp->word[7];
printk(KERN_DEBUG "Word7:\n");
printk(KERN_DEBUG " INT to IRQ:\n");
for (i=0, j=0; i<15; i++)
if (GetBit(Word,i)) printk(KERN_DEBUG " INT%d -> IRQ %d;",j++,i);
printk(KERN_DEBUG "\n");
}
/* function to recalculate the limits of buffer based on rcv_ram */
static void eepro_recalc (struct net_device *dev)
{
struct eepro_local * lp;
lp = netdev_priv(dev);
lp->xmt_ram = RAM_SIZE - lp->rcv_ram;
if (lp->eepro == LAN595FX_10ISA) {
lp->xmt_lower_limit = XMT_START_10;
lp->xmt_upper_limit = (lp->xmt_ram - 2);
lp->rcv_lower_limit = lp->xmt_ram;
lp->rcv_upper_limit = (RAM_SIZE - 2);
}
else {
lp->rcv_lower_limit = RCV_START_PRO;
lp->rcv_upper_limit = (lp->rcv_ram - 2);
lp->xmt_lower_limit = lp->rcv_ram;
lp->xmt_upper_limit = (RAM_SIZE - 2);
}
}
/* prints boot-time info */
static void __init eepro_print_info (struct net_device *dev)
{
struct eepro_local * lp = netdev_priv(dev);
int i;
const char * ifmap[] = {"AUI", "10Base2", "10BaseT"};
i = inb(dev->base_addr + ID_REG);
printk(KERN_DEBUG " id: %#x ",i);
printk(" io: %#x ", (unsigned)dev->base_addr);
switch (lp->eepro) {
case LAN595FX_10ISA:
printk("%s: Intel EtherExpress 10 ISA\n at %#x,",
dev->name, (unsigned)dev->base_addr);
break;
case LAN595FX:
printk("%s: Intel EtherExpress Pro/10+ ISA\n at %#x,",
dev->name, (unsigned)dev->base_addr);
break;
case LAN595TX:
printk("%s: Intel EtherExpress Pro/10 ISA at %#x,",
dev->name, (unsigned)dev->base_addr);
break;
case LAN595:
printk("%s: Intel 82595-based lan card at %#x,",
dev->name, (unsigned)dev->base_addr);
break;
}
printk(" %pM", dev->dev_addr);
if (net_debug > 3)
printk(KERN_DEBUG ", %dK RCV buffer",
(int)(lp->rcv_ram)/1024);
if (dev->irq > 2)
printk(", IRQ %d, %s.\n", dev->irq, ifmap[dev->if_port]);
else
printk(", %s.\n", ifmap[dev->if_port]);
if (net_debug > 3) {
i = lp->word[5];
if (i & 0x2000) /* bit 13 of EEPROM word 5 */
printk(KERN_DEBUG "%s: Concurrent Processing is "
"enabled but not used!\n", dev->name);
}
/* Check the station address for the manufacturer's code */
if (net_debug>3)
printEEPROMInfo(dev);
}
static const struct ethtool_ops eepro_ethtool_ops;
static const struct net_device_ops eepro_netdev_ops = {
.ndo_open = eepro_open,
.ndo_stop = eepro_close,
.ndo_start_xmit = eepro_send_packet,
.ndo_set_multicast_list = set_multicast_list,
.ndo_tx_timeout = eepro_tx_timeout,
.ndo_change_mtu = eth_change_mtu,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
};
/* This is the real probe routine. Linux has a history of friendly device
probes on the ISA bus. A good device probe avoids doing writes, and
verifies that the correct device exists and functions. */
static int __init eepro_probe1(struct net_device *dev, int autoprobe)
{
unsigned short station_addr[3], id, counter;
int i;
struct eepro_local *lp;
int ioaddr = dev->base_addr;
int err;
/* Grab the region so we can find another board if autoIRQ fails. */
if (!request_region(ioaddr, EEPRO_IO_EXTENT, DRV_NAME)) {
if (!autoprobe)
printk(KERN_WARNING "EEPRO: io-port 0x%04x in use\n",
ioaddr);
return -EBUSY;
}
/* Now, we are going to check for the signature of the
ID_REG (register 2 of bank 0) */
id = inb(ioaddr + ID_REG);
if ((id & ID_REG_MASK) != ID_REG_SIG)
goto exit;
/* We seem to have the 82595 signature, let's
play with its counter (last 2 bits of
register 2 of bank 0) to be sure. */
counter = id & R_ROBIN_BITS;
if ((inb(ioaddr + ID_REG) & R_ROBIN_BITS) != (counter + 0x40))
goto exit;
lp = netdev_priv(dev);
memset(lp, 0, sizeof(struct eepro_local));
lp->xmt_bar = XMT_BAR_PRO;
lp->xmt_lower_limit_reg = XMT_LOWER_LIMIT_REG_PRO;
lp->xmt_upper_limit_reg = XMT_UPPER_LIMIT_REG_PRO;
lp->eeprom_reg = EEPROM_REG_PRO;
spin_lock_init(&lp->lock);
/* Now, get the ethernet hardware address from
the EEPROM */
station_addr[0] = read_eeprom(ioaddr, 2, dev);
/* FIXME - find another way to know that we've found
* an Etherexpress 10
*/
if (station_addr[0] == 0x0000 || station_addr[0] == 0xffff) {
lp->eepro = LAN595FX_10ISA;
lp->eeprom_reg = EEPROM_REG_10;
lp->xmt_lower_limit_reg = XMT_LOWER_LIMIT_REG_10;
lp->xmt_upper_limit_reg = XMT_UPPER_LIMIT_REG_10;
lp->xmt_bar = XMT_BAR_10;
station_addr[0] = read_eeprom(ioaddr, 2, dev);
}
/* get all words at once. will be used here and for ethtool */
for (i = 0; i < 8; i++) {
lp->word[i] = read_eeprom(ioaddr, i, dev);
}
station_addr[1] = lp->word[3];
station_addr[2] = lp->word[4];
if (!lp->eepro) {
if (lp->word[7] == ee_FX_INT2IRQ)
lp->eepro = 2;
else if (station_addr[2] == SA_ADDR1)
lp->eepro = 1;
}
/* Fill in the 'dev' fields. */
for (i=0; i < 6; i++)
dev->dev_addr[i] = ((unsigned char *) station_addr)[5-i];
/* RX buffer must be more than 3K and less than 29K */
if (dev->mem_end < 3072 || dev->mem_end > 29696)
lp->rcv_ram = RCV_DEFAULT_RAM;
/* calculate {xmt,rcv}_{lower,upper}_limit */
eepro_recalc(dev);
if (GetBit(lp->word[5], ee_BNC_TPE))
dev->if_port = BNC;
else
dev->if_port = TPE;
if (dev->irq < 2 && lp->eepro != 0) {
/* Mask off INT number */
int count = lp->word[1] & 7;
unsigned irqMask = lp->word[7];
while (count--)
irqMask &= irqMask - 1;
count = ffs(irqMask);
if (count)
dev->irq = count - 1;
if (dev->irq < 2) {
printk(KERN_ERR " Duh! illegal interrupt vector stored in EEPROM.\n");
goto exit;
} else if (dev->irq == 2) {
dev->irq = 9;
}
}
dev->netdev_ops = &eepro_netdev_ops;
dev->watchdog_timeo = TX_TIMEOUT;
dev->ethtool_ops = &eepro_ethtool_ops;
/* print boot time info */
eepro_print_info(dev);
/* reset 82595 */
eepro_reset(ioaddr);
err = register_netdev(dev);
if (err)
goto err;
return 0;
exit:
err = -ENODEV;
err:
release_region(dev->base_addr, EEPRO_IO_EXTENT);
return err;
}
/* Open/initialize the board. This is called (in the current kernel)
sometime after booting when the 'ifconfig' program is run.
This routine should set everything up anew at each open, even
registers that "should" only need to be set once at boot, so that
there is non-reboot way to recover if something goes wrong.
*/
static const char irqrmap[] = {-1,-1,0,1,-1,2,-1,-1,-1,0,3,4,-1,-1,-1,-1};
static const char irqrmap2[] = {-1,-1,4,0,1,2,-1,3,-1,4,5,6,7,-1,-1,-1};
static int eepro_grab_irq(struct net_device *dev)
{
static const int irqlist[] = { 3, 4, 5, 7, 9, 10, 11, 12, 0 };
const int *irqp = irqlist;
int temp_reg, ioaddr = dev->base_addr;
eepro_sw2bank1(ioaddr); /* be CAREFUL, BANK 1 now */
/* Enable the interrupt line. */
eepro_en_intline(ioaddr);
/* be CAREFUL, BANK 0 now */
eepro_sw2bank0(ioaddr);
/* clear all interrupts */
eepro_clear_int(ioaddr);
/* Let EXEC event to interrupt */
eepro_en_intexec(ioaddr);
do {
eepro_sw2bank1(ioaddr); /* be CAREFUL, BANK 1 now */
temp_reg = inb(ioaddr + INT_NO_REG);
outb((temp_reg & 0xf8) | irqrmap[*irqp], ioaddr + INT_NO_REG);
eepro_sw2bank0(ioaddr); /* Switch back to Bank 0 */
if (request_irq (*irqp, NULL, IRQF_SHARED, "bogus", dev) != EBUSY) {
unsigned long irq_mask;
/* Twinkle the interrupt, and check if it's seen */
irq_mask = probe_irq_on();
eepro_diag(ioaddr); /* RESET the 82595 */
mdelay(20);
if (*irqp == probe_irq_off(irq_mask)) /* It's a good IRQ line */
break;
/* clear all interrupts */
eepro_clear_int(ioaddr);
}
} while (*++irqp);
eepro_sw2bank1(ioaddr); /* Switch back to Bank 1 */
/* Disable the physical interrupt line. */
eepro_dis_intline(ioaddr);
eepro_sw2bank0(ioaddr); /* Switch back to Bank 0 */
/* Mask all the interrupts. */
eepro_dis_int(ioaddr);
/* clear all interrupts */
eepro_clear_int(ioaddr);
return dev->irq;
}
static int eepro_open(struct net_device *dev)
{
unsigned short temp_reg, old8, old9;
int irqMask;
int i, ioaddr = dev->base_addr;
struct eepro_local *lp = netdev_priv(dev);
if (net_debug > 3)
printk(KERN_DEBUG "%s: entering eepro_open routine.\n", dev->name);
irqMask = lp->word[7];
if (lp->eepro == LAN595FX_10ISA) {
if (net_debug > 3) printk(KERN_DEBUG "p->eepro = 3;\n");
}
else if (irqMask == ee_FX_INT2IRQ) /* INT to IRQ Mask */
{
lp->eepro = 2; /* Yes, an Intel EtherExpress Pro/10+ */
if (net_debug > 3) printk(KERN_DEBUG "p->eepro = 2;\n");
}
else if ((dev->dev_addr[0] == SA_ADDR0 &&
dev->dev_addr[1] == SA_ADDR1 &&
dev->dev_addr[2] == SA_ADDR2))
{
lp->eepro = 1;
if (net_debug > 3) printk(KERN_DEBUG "p->eepro = 1;\n");
} /* Yes, an Intel EtherExpress Pro/10 */
else lp->eepro = 0; /* No, it is a generic 82585 lan card */
/* Get the interrupt vector for the 82595 */
if (dev->irq < 2 && eepro_grab_irq(dev) == 0) {
printk(KERN_ERR "%s: unable to get IRQ %d.\n", dev->name, dev->irq);
return -EAGAIN;
}
if (request_irq(dev->irq , eepro_interrupt, 0, dev->name, dev)) {
printk(KERN_ERR "%s: unable to get IRQ %d.\n", dev->name, dev->irq);
return -EAGAIN;
}
/* Initialize the 82595. */
eepro_sw2bank2(ioaddr); /* be CAREFUL, BANK 2 now */
temp_reg = inb(ioaddr + lp->eeprom_reg);
lp->stepping = temp_reg >> 5; /* Get the stepping number of the 595 */
if (net_debug > 3)
printk(KERN_DEBUG "The stepping of the 82595 is %d\n", lp->stepping);
if (temp_reg & 0x10) /* Check the TurnOff Enable bit */
outb(temp_reg & 0xef, ioaddr + lp->eeprom_reg);
for (i=0; i < 6; i++)
outb(dev->dev_addr[i] , ioaddr + I_ADD_REG0 + i);
temp_reg = inb(ioaddr + REG1); /* Setup Transmit Chaining */
outb(temp_reg | XMT_Chain_Int | XMT_Chain_ErrStop /* and discard bad RCV frames */
| RCV_Discard_BadFrame, ioaddr + REG1);
temp_reg = inb(ioaddr + REG2); /* Match broadcast */
outb(temp_reg | 0x14, ioaddr + REG2);
temp_reg = inb(ioaddr + REG3);
outb(temp_reg & 0x3f, ioaddr + REG3); /* clear test mode */
/* Set the receiving mode */
eepro_sw2bank1(ioaddr); /* be CAREFUL, BANK 1 now */
/* Set the interrupt vector */
temp_reg = inb(ioaddr + INT_NO_REG);
if (lp->eepro == LAN595FX || lp->eepro == LAN595FX_10ISA)
outb((temp_reg & 0xf8) | irqrmap2[dev->irq], ioaddr + INT_NO_REG);
else outb((temp_reg & 0xf8) | irqrmap[dev->irq], ioaddr + INT_NO_REG);
temp_reg = inb(ioaddr + INT_NO_REG);
if (lp->eepro == LAN595FX || lp->eepro == LAN595FX_10ISA)
outb((temp_reg & 0xf0) | irqrmap2[dev->irq] | 0x08,ioaddr+INT_NO_REG);
else outb((temp_reg & 0xf8) | irqrmap[dev->irq], ioaddr + INT_NO_REG);
if (net_debug > 3)
printk(KERN_DEBUG "eepro_open: content of INT Reg is %x\n", temp_reg);
/* Initialize the RCV and XMT upper and lower limits */
outb(lp->rcv_lower_limit >> 8, ioaddr + RCV_LOWER_LIMIT_REG);
outb(lp->rcv_upper_limit >> 8, ioaddr + RCV_UPPER_LIMIT_REG);
outb(lp->xmt_lower_limit >> 8, ioaddr + lp->xmt_lower_limit_reg);
outb(lp->xmt_upper_limit >> 8, ioaddr + lp->xmt_upper_limit_reg);
/* Enable the interrupt line. */
eepro_en_intline(ioaddr);
/* Switch back to Bank 0 */
eepro_sw2bank0(ioaddr);
/* Let RX and TX events to interrupt */
eepro_en_int(ioaddr);
/* clear all interrupts */
eepro_clear_int(ioaddr);
/* Initialize RCV */
outw(lp->rcv_lower_limit, ioaddr + RCV_BAR);
lp->rx_start = lp->rcv_lower_limit;
outw(lp->rcv_upper_limit | 0xfe, ioaddr + RCV_STOP);
/* Initialize XMT */
outw(lp->xmt_lower_limit, ioaddr + lp->xmt_bar);
lp->tx_start = lp->tx_end = lp->xmt_lower_limit;
lp->tx_last = 0;
/* Check for the i82595TX and i82595FX */
old8 = inb(ioaddr + 8);
outb(~old8, ioaddr + 8);
if ((temp_reg = inb(ioaddr + 8)) == old8) {
if (net_debug > 3)
printk(KERN_DEBUG "i82595 detected!\n");
lp->version = LAN595;
}
else {
lp->version = LAN595TX;
outb(old8, ioaddr + 8);
old9 = inb(ioaddr + 9);
if (irqMask==ee_FX_INT2IRQ) {
if (net_debug > 3) {
printk(KERN_DEBUG "IrqMask: %#x\n",irqMask);
printk(KERN_DEBUG "i82595FX detected!\n");
}
lp->version = LAN595FX;
outb(old9, ioaddr + 9);
if (dev->if_port != TPE) { /* Hopefully, this will fix the
problem of using Pentiums and
pro/10 w/ BNC. */
eepro_sw2bank2(ioaddr); /* be CAREFUL, BANK 2 now */
temp_reg = inb(ioaddr + REG13);
/* disable the full duplex mode since it is not
applicable with the 10Base2 cable. */
outb(temp_reg & ~(FDX | A_N_ENABLE), REG13);
eepro_sw2bank0(ioaddr); /* be CAREFUL, BANK 0 now */
}
}
else if (net_debug > 3) {
printk(KERN_DEBUG "temp_reg: %#x ~old9: %#x\n",temp_reg,((~old9)&0xff));
printk(KERN_DEBUG "i82595TX detected!\n");
}
}
eepro_sel_reset(ioaddr);
netif_start_queue(dev);
if (net_debug > 3)
printk(KERN_DEBUG "%s: exiting eepro_open routine.\n", dev->name);
/* enabling rx */
eepro_en_rx(ioaddr);
return 0;
}
static void eepro_tx_timeout (struct net_device *dev)
{
struct eepro_local *lp = netdev_priv(dev);
int ioaddr = dev->base_addr;
/* if (net_debug > 1) */
printk (KERN_ERR "%s: transmit timed out, %s?\n", dev->name,
"network cable problem");
/* This is not a duplicate. One message for the console,
one for the log file */
printk (KERN_DEBUG "%s: transmit timed out, %s?\n", dev->name,
"network cable problem");
eepro_complete_selreset(ioaddr);
}
static netdev_tx_t eepro_send_packet(struct sk_buff *skb,
struct net_device *dev)
{
struct eepro_local *lp = netdev_priv(dev);
unsigned long flags;
int ioaddr = dev->base_addr;
short length = skb->len;
if (net_debug > 5)
printk(KERN_DEBUG "%s: entering eepro_send_packet routine.\n", dev->name);
if (length < ETH_ZLEN) {
if (skb_padto(skb, ETH_ZLEN))
return NETDEV_TX_OK;
length = ETH_ZLEN;
}
netif_stop_queue (dev);
eepro_dis_int(ioaddr);
spin_lock_irqsave(&lp->lock, flags);
{
unsigned char *buf = skb->data;
if (hardware_send_packet(dev, buf, length))
/* we won't wake queue here because we're out of space */
dev->stats.tx_dropped++;
else {
dev->stats.tx_bytes+=skb->len;
netif_wake_queue(dev);
}
}
dev_kfree_skb (skb);
/* You might need to clean up and record Tx statistics here. */
/* dev->stats.tx_aborted_errors++; */
if (net_debug > 5)
printk(KERN_DEBUG "%s: exiting eepro_send_packet routine.\n", dev->name);
eepro_en_int(ioaddr);
spin_unlock_irqrestore(&lp->lock, flags);
return NETDEV_TX_OK;
}
/* The typical workload of the driver:
Handle the network interface interrupts. */
static irqreturn_t
eepro_interrupt(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
struct eepro_local *lp;
int ioaddr, status, boguscount = 20;
int handled = 0;
lp = netdev_priv(dev);
spin_lock(&lp->lock);
if (net_debug > 5)
printk(KERN_DEBUG "%s: entering eepro_interrupt routine.\n", dev->name);
ioaddr = dev->base_addr;
while (((status = inb(ioaddr + STATUS_REG)) & (RX_INT|TX_INT)) && (boguscount--))
{
handled = 1;
if (status & RX_INT) {
if (net_debug > 4)
printk(KERN_DEBUG "%s: packet received interrupt.\n", dev->name);
eepro_dis_int(ioaddr);
/* Get the received packets */
eepro_ack_rx(ioaddr);
eepro_rx(dev);
eepro_en_int(ioaddr);
}
if (status & TX_INT) {
if (net_debug > 4)
printk(KERN_DEBUG "%s: packet transmit interrupt.\n", dev->name);
eepro_dis_int(ioaddr);
/* Process the status of transmitted packets */
eepro_ack_tx(ioaddr);
eepro_transmit_interrupt(dev);
eepro_en_int(ioaddr);
}
}
if (net_debug > 5)
printk(KERN_DEBUG "%s: exiting eepro_interrupt routine.\n", dev->name);
spin_unlock(&lp->lock);
return IRQ_RETVAL(handled);
}
static int eepro_close(struct net_device *dev)
{
struct eepro_local *lp = netdev_priv(dev);
int ioaddr = dev->base_addr;
short temp_reg;
netif_stop_queue(dev);
eepro_sw2bank1(ioaddr); /* Switch back to Bank 1 */
/* Disable the physical interrupt line. */
temp_reg = inb(ioaddr + REG1);
outb(temp_reg & 0x7f, ioaddr + REG1);
eepro_sw2bank0(ioaddr); /* Switch back to Bank 0 */
/* Flush the Tx and disable Rx. */
outb(STOP_RCV_CMD, ioaddr);
lp->tx_start = lp->tx_end = lp->xmt_lower_limit;
lp->tx_last = 0;
/* Mask all the interrupts. */
eepro_dis_int(ioaddr);
/* clear all interrupts */
eepro_clear_int(ioaddr);
/* Reset the 82595 */
eepro_reset(ioaddr);
/* release the interrupt */
free_irq(dev->irq, dev);
/* Update the statistics here. What statistics? */
return 0;
}
/* Set or clear the multicast filter for this adaptor.
*/
static void
set_multicast_list(struct net_device *dev)
{
struct eepro_local *lp = netdev_priv(dev);
short ioaddr = dev->base_addr;
unsigned short mode;
struct netdev_hw_addr *ha;
int mc_count = netdev_mc_count(dev);
if (dev->flags&(IFF_ALLMULTI|IFF_PROMISC) || mc_count > 63)
{
eepro_sw2bank2(ioaddr); /* be CAREFUL, BANK 2 now */
mode = inb(ioaddr + REG2);
outb(mode | PRMSC_Mode, ioaddr + REG2);
mode = inb(ioaddr + REG3);
outb(mode, ioaddr + REG3); /* writing reg. 3 to complete the update */
eepro_sw2bank0(ioaddr); /* Return to BANK 0 now */
}
else if (mc_count == 0)
{
eepro_sw2bank2(ioaddr); /* be CAREFUL, BANK 2 now */
mode = inb(ioaddr + REG2);
outb(mode & 0xd6, ioaddr + REG2); /* Turn off Multi-IA and PRMSC_Mode bits */
mode = inb(ioaddr + REG3);
outb(mode, ioaddr + REG3); /* writing reg. 3 to complete the update */
eepro_sw2bank0(ioaddr); /* Return to BANK 0 now */
}
else
{
unsigned short status, *eaddrs;
int i, boguscount = 0;
/* Disable RX and TX interrupts. Necessary to avoid
corruption of the HOST_ADDRESS_REG by interrupt
service routines. */
eepro_dis_int(ioaddr);
eepro_sw2bank2(ioaddr); /* be CAREFUL, BANK 2 now */
mode = inb(ioaddr + REG2);
outb(mode | Multi_IA, ioaddr + REG2);
mode = inb(ioaddr + REG3);
outb(mode, ioaddr + REG3); /* writing reg. 3 to complete the update */
eepro_sw2bank0(ioaddr); /* Return to BANK 0 now */
outw(lp->tx_end, ioaddr + HOST_ADDRESS_REG);
outw(MC_SETUP, ioaddr + IO_PORT);
outw(0, ioaddr + IO_PORT);
outw(0, ioaddr + IO_PORT);
outw(6 * (mc_count + 1), ioaddr + IO_PORT);
netdev_for_each_mc_addr(ha, dev) {
eaddrs = (unsigned short *) ha->addr;
outw(*eaddrs++, ioaddr + IO_PORT);
outw(*eaddrs++, ioaddr + IO_PORT);
outw(*eaddrs++, ioaddr + IO_PORT);
}
eaddrs = (unsigned short *) dev->dev_addr;
outw(eaddrs[0], ioaddr + IO_PORT);
outw(eaddrs[1], ioaddr + IO_PORT);
outw(eaddrs[2], ioaddr + IO_PORT);
outw(lp->tx_end, ioaddr + lp->xmt_bar);
outb(MC_SETUP, ioaddr);
/* Update the transmit queue */
i = lp->tx_end + XMT_HEADER + 6 * (mc_count + 1);
if (lp->tx_start != lp->tx_end)
{
/* update the next address and the chain bit in the
last packet */
outw(lp->tx_last + XMT_CHAIN, ioaddr + HOST_ADDRESS_REG);
outw(i, ioaddr + IO_PORT);
outw(lp->tx_last + XMT_COUNT, ioaddr + HOST_ADDRESS_REG);
status = inw(ioaddr + IO_PORT);
outw(status | CHAIN_BIT, ioaddr + IO_PORT);
lp->tx_end = i ;
}
else {
lp->tx_start = lp->tx_end = i ;
}
/* Acknowledge that the MC setup is done */
do { /* We should be doing this in the eepro_interrupt()! */
SLOW_DOWN;
SLOW_DOWN;
if (inb(ioaddr + STATUS_REG) & 0x08)
{
i = inb(ioaddr);
outb(0x08, ioaddr + STATUS_REG);
if (i & 0x20) { /* command ABORTed */
printk(KERN_NOTICE "%s: multicast setup failed.\n",
dev->name);
break;
} else if ((i & 0x0f) == 0x03) { /* MC-Done */
printk(KERN_DEBUG "%s: set Rx mode to %d address%s.\n",
dev->name, mc_count,
mc_count > 1 ? "es":"");
break;
}
}
} while (++boguscount < 100);
/* Re-enable RX and TX interrupts */
eepro_en_int(ioaddr);
}
if (lp->eepro == LAN595FX_10ISA) {
eepro_complete_selreset(ioaddr);
}
else
eepro_en_rx(ioaddr);
}
/* The horrible routine to read a word from the serial EEPROM. */
/* IMPORTANT - the 82595 will be set to Bank 0 after the eeprom is read */
/* The delay between EEPROM clock transitions. */
#define eeprom_delay() { udelay(40); }
#define EE_READ_CMD (6 << 6)
static int
read_eeprom(int ioaddr, int location, struct net_device *dev)
{
int i;
unsigned short retval = 0;
struct eepro_local *lp = netdev_priv(dev);
short ee_addr = ioaddr + lp->eeprom_reg;
int read_cmd = location | EE_READ_CMD;
short ctrl_val = EECS ;
/* XXXX - black magic */
eepro_sw2bank1(ioaddr);
outb(0x00, ioaddr + STATUS_REG);
/* XXXX - black magic */
eepro_sw2bank2(ioaddr);
outb(ctrl_val, ee_addr);
/* Shift the read command bits out. */
for (i = 8; i >= 0; i--) {
short outval = (read_cmd & (1 << i)) ? ctrl_val | EEDI
: ctrl_val;
outb(outval, ee_addr);
outb(outval | EESK, ee_addr); /* EEPROM clock tick. */
eeprom_delay();
outb(outval, ee_addr); /* Finish EEPROM a clock tick. */
eeprom_delay();
}
outb(ctrl_val, ee_addr);
for (i = 16; i > 0; i--) {
outb(ctrl_val | EESK, ee_addr); eeprom_delay();
retval = (retval << 1) | ((inb(ee_addr) & EEDO) ? 1 : 0);
outb(ctrl_val, ee_addr); eeprom_delay();
}
/* Terminate the EEPROM access. */
ctrl_val &= ~EECS;
outb(ctrl_val | EESK, ee_addr);
eeprom_delay();
outb(ctrl_val, ee_addr);
eeprom_delay();
eepro_sw2bank0(ioaddr);
return retval;
}
static int
hardware_send_packet(struct net_device *dev, void *buf, short length)
{
struct eepro_local *lp = netdev_priv(dev);
short ioaddr = dev->base_addr;
unsigned status, tx_available, last, end;
if (net_debug > 5)
printk(KERN_DEBUG "%s: entering hardware_send_packet routine.\n", dev->name);
/* determine how much of the transmit buffer space is available */
if (lp->tx_end > lp->tx_start)
tx_available = lp->xmt_ram - (lp->tx_end - lp->tx_start);
else if (lp->tx_end < lp->tx_start)
tx_available = lp->tx_start - lp->tx_end;
else tx_available = lp->xmt_ram;
if (((((length + 3) >> 1) << 1) + 2*XMT_HEADER) >= tx_available) {
/* No space available ??? */
return 1;
}
last = lp->tx_end;
end = last + (((length + 3) >> 1) << 1) + XMT_HEADER;
if (end >= lp->xmt_upper_limit + 2) { /* the transmit buffer is wrapped around */
if ((lp->xmt_upper_limit + 2 - last) <= XMT_HEADER) {
/* Arrrr!!!, must keep the xmt header together,
several days were lost to chase this one down. */
last = lp->xmt_lower_limit;
end = last + (((length + 3) >> 1) << 1) + XMT_HEADER;
}
else end = lp->xmt_lower_limit + (end -
lp->xmt_upper_limit + 2);
}
outw(last, ioaddr + HOST_ADDRESS_REG);
outw(XMT_CMD, ioaddr + IO_PORT);
outw(0, ioaddr + IO_PORT);
outw(end, ioaddr + IO_PORT);
outw(length, ioaddr + IO_PORT);
if (lp->version == LAN595)
outsw(ioaddr + IO_PORT, buf, (length + 3) >> 1);
else { /* LAN595TX or LAN595FX, capable of 32-bit I/O processing */
unsigned short temp = inb(ioaddr + INT_MASK_REG);
outb(temp | IO_32_BIT, ioaddr + INT_MASK_REG);
outsl(ioaddr + IO_PORT_32_BIT, buf, (length + 3) >> 2);
outb(temp & ~(IO_32_BIT), ioaddr + INT_MASK_REG);
}
/* A dummy read to flush the DRAM write pipeline */
status = inw(ioaddr + IO_PORT);
if (lp->tx_start == lp->tx_end) {
outw(last, ioaddr + lp->xmt_bar);
outb(XMT_CMD, ioaddr);
lp->tx_start = last; /* I don't like to change tx_start here */
}
else {
/* update the next address and the chain bit in the
last packet */
if (lp->tx_end != last) {
outw(lp->tx_last + XMT_CHAIN, ioaddr + HOST_ADDRESS_REG);
outw(last, ioaddr + IO_PORT);
}
outw(lp->tx_last + XMT_COUNT, ioaddr + HOST_ADDRESS_REG);
status = inw(ioaddr + IO_PORT);
outw(status | CHAIN_BIT, ioaddr + IO_PORT);
/* Continue the transmit command */
outb(RESUME_XMT_CMD, ioaddr);
}
lp->tx_last = last;
lp->tx_end = end;
if (net_debug > 5)
printk(KERN_DEBUG "%s: exiting hardware_send_packet routine.\n", dev->name);
return 0;
}
static void
eepro_rx(struct net_device *dev)
{
struct eepro_local *lp = netdev_priv(dev);
short ioaddr = dev->base_addr;
short boguscount = 20;
short rcv_car = lp->rx_start;
unsigned rcv_event, rcv_status, rcv_next_frame, rcv_size;
if (net_debug > 5)
printk(KERN_DEBUG "%s: entering eepro_rx routine.\n", dev->name);
/* Set the read pointer to the start of the RCV */
outw(rcv_car, ioaddr + HOST_ADDRESS_REG);
rcv_event = inw(ioaddr + IO_PORT);
while (rcv_event == RCV_DONE) {
rcv_status = inw(ioaddr + IO_PORT);
rcv_next_frame = inw(ioaddr + IO_PORT);
rcv_size = inw(ioaddr + IO_PORT);
if ((rcv_status & (RX_OK | RX_ERROR)) == RX_OK) {
/* Malloc up new buffer. */
struct sk_buff *skb;
dev->stats.rx_bytes+=rcv_size;
rcv_size &= 0x3fff;
skb = dev_alloc_skb(rcv_size+5);
if (skb == NULL) {
printk(KERN_NOTICE "%s: Memory squeeze, dropping packet.\n", dev->name);
dev->stats.rx_dropped++;
rcv_car = lp->rx_start + RCV_HEADER + rcv_size;
lp->rx_start = rcv_next_frame;
outw(rcv_next_frame, ioaddr + HOST_ADDRESS_REG);
break;
}
skb_reserve(skb,2);
if (lp->version == LAN595)
insw(ioaddr+IO_PORT, skb_put(skb,rcv_size), (rcv_size + 3) >> 1);
else { /* LAN595TX or LAN595FX, capable of 32-bit I/O processing */
unsigned short temp = inb(ioaddr + INT_MASK_REG);
outb(temp | IO_32_BIT, ioaddr + INT_MASK_REG);
insl(ioaddr+IO_PORT_32_BIT, skb_put(skb,rcv_size),
(rcv_size + 3) >> 2);
outb(temp & ~(IO_32_BIT), ioaddr + INT_MASK_REG);
}
skb->protocol = eth_type_trans(skb,dev);
netif_rx(skb);
dev->stats.rx_packets++;
}
else { /* Not sure will ever reach here,
I set the 595 to discard bad received frames */
dev->stats.rx_errors++;
if (rcv_status & 0x0100)
dev->stats.rx_over_errors++;
else if (rcv_status & 0x0400)
dev->stats.rx_frame_errors++;
else if (rcv_status & 0x0800)
dev->stats.rx_crc_errors++;
printk(KERN_DEBUG "%s: event = %#x, status = %#x, next = %#x, size = %#x\n",
dev->name, rcv_event, rcv_status, rcv_next_frame, rcv_size);
}
if (rcv_status & 0x1000)
dev->stats.rx_length_errors++;
rcv_car = lp->rx_start + RCV_HEADER + rcv_size;
lp->rx_start = rcv_next_frame;
if (--boguscount == 0)
break;
outw(rcv_next_frame, ioaddr + HOST_ADDRESS_REG);
rcv_event = inw(ioaddr + IO_PORT);
}
if (rcv_car == 0)
rcv_car = lp->rcv_upper_limit | 0xff;
outw(rcv_car - 1, ioaddr + RCV_STOP);
if (net_debug > 5)
printk(KERN_DEBUG "%s: exiting eepro_rx routine.\n", dev->name);
}
static void
eepro_transmit_interrupt(struct net_device *dev)
{
struct eepro_local *lp = netdev_priv(dev);
short ioaddr = dev->base_addr;
short boguscount = 25;
short xmt_status;
while ((lp->tx_start != lp->tx_end) && boguscount--) {
outw(lp->tx_start, ioaddr + HOST_ADDRESS_REG);
xmt_status = inw(ioaddr+IO_PORT);
if (!(xmt_status & TX_DONE_BIT))
break;
xmt_status = inw(ioaddr+IO_PORT);
lp->tx_start = inw(ioaddr+IO_PORT);
netif_wake_queue (dev);
if (xmt_status & TX_OK)
dev->stats.tx_packets++;
else {
dev->stats.tx_errors++;
if (xmt_status & 0x0400) {
dev->stats.tx_carrier_errors++;
printk(KERN_DEBUG "%s: carrier error\n",
dev->name);
printk(KERN_DEBUG "%s: XMT status = %#x\n",
dev->name, xmt_status);
}
else {
printk(KERN_DEBUG "%s: XMT status = %#x\n",
dev->name, xmt_status);
printk(KERN_DEBUG "%s: XMT status = %#x\n",
dev->name, xmt_status);
}
}
if (xmt_status & 0x000f) {
dev->stats.collisions += (xmt_status & 0x000f);
}
if ((xmt_status & 0x0040) == 0x0) {
dev->stats.tx_heartbeat_errors++;
}
}
}
static int eepro_ethtool_get_settings(struct net_device *dev,
struct ethtool_cmd *cmd)
{
struct eepro_local *lp = netdev_priv(dev);
cmd->supported = SUPPORTED_10baseT_Half |
SUPPORTED_10baseT_Full |
SUPPORTED_Autoneg;
cmd->advertising = ADVERTISED_10baseT_Half |
ADVERTISED_10baseT_Full |
ADVERTISED_Autoneg;
if (GetBit(lp->word[5], ee_PortTPE)) {
cmd->supported |= SUPPORTED_TP;
cmd->advertising |= ADVERTISED_TP;
}
if (GetBit(lp->word[5], ee_PortBNC)) {
cmd->supported |= SUPPORTED_BNC;
cmd->advertising |= ADVERTISED_BNC;
}
if (GetBit(lp->word[5], ee_PortAUI)) {
cmd->supported |= SUPPORTED_AUI;
cmd->advertising |= ADVERTISED_AUI;
}
ethtool_cmd_speed_set(cmd, SPEED_10);
if (dev->if_port == TPE && lp->word[1] & ee_Duplex) {
cmd->duplex = DUPLEX_FULL;
}
else {
cmd->duplex = DUPLEX_HALF;
}
cmd->port = dev->if_port;
cmd->phy_address = dev->base_addr;
cmd->transceiver = XCVR_INTERNAL;
if (lp->word[0] & ee_AutoNeg) {
cmd->autoneg = 1;
}
return 0;
}
static void eepro_ethtool_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *drvinfo)
{
strcpy(drvinfo->driver, DRV_NAME);
strcpy(drvinfo->version, DRV_VERSION);
sprintf(drvinfo->bus_info, "ISA 0x%lx", dev->base_addr);
}
static const struct ethtool_ops eepro_ethtool_ops = {
.get_settings = eepro_ethtool_get_settings,
.get_drvinfo = eepro_ethtool_get_drvinfo,
};
#ifdef MODULE
#define MAX_EEPRO 8
static struct net_device *dev_eepro[MAX_EEPRO];
static int io[MAX_EEPRO] = {
[0 ... MAX_EEPRO-1] = -1
};
static int irq[MAX_EEPRO];
static int mem[MAX_EEPRO] = { /* Size of the rx buffer in KB */
[0 ... MAX_EEPRO-1] = RCV_DEFAULT_RAM/1024
};
static int autodetect;
static int n_eepro;
/* For linux 2.1.xx */
MODULE_AUTHOR("Pascal Dupuis and others");
MODULE_DESCRIPTION("Intel i82595 ISA EtherExpressPro10/10+ driver");
MODULE_LICENSE("GPL");
module_param_array(io, int, NULL, 0);
module_param_array(irq, int, NULL, 0);
module_param_array(mem, int, NULL, 0);
module_param(autodetect, int, 0);
MODULE_PARM_DESC(io, "EtherExpress Pro/10 I/O base address(es)");
MODULE_PARM_DESC(irq, "EtherExpress Pro/10 IRQ number(s)");
MODULE_PARM_DESC(mem, "EtherExpress Pro/10 Rx buffer size(es) in kB (3-29)");
MODULE_PARM_DESC(autodetect, "EtherExpress Pro/10 force board(s) detection (0-1)");
int __init init_module(void)
{
struct net_device *dev;
int i;
if (io[0] == -1 && autodetect == 0) {
printk(KERN_WARNING "eepro_init_module: Probe is very dangerous in ISA boards!\n");
printk(KERN_WARNING "eepro_init_module: Please add \"autodetect=1\" to force probe\n");
return -ENODEV;
}
else if (autodetect) {
/* if autodetect is set then we must force detection */
for (i = 0; i < MAX_EEPRO; i++) {
io[i] = 0;
}
printk(KERN_INFO "eepro_init_module: Auto-detecting boards (May God protect us...)\n");
}
for (i = 0; i < MAX_EEPRO && io[i] != -1; i++) {
dev = alloc_etherdev(sizeof(struct eepro_local));
if (!dev)
break;
dev->mem_end = mem[i];
dev->base_addr = io[i];
dev->irq = irq[i];
if (do_eepro_probe(dev) == 0) {
dev_eepro[n_eepro++] = dev;
continue;
}
free_netdev(dev);
break;
}
if (n_eepro)
printk(KERN_INFO "%s", version);
return n_eepro ? 0 : -ENODEV;
}
void __exit
cleanup_module(void)
{
int i;
for (i=0; i<n_eepro; i++) {
struct net_device *dev = dev_eepro[i];
unregister_netdev(dev);
release_region(dev->base_addr, EEPRO_IO_EXTENT);
free_netdev(dev);
}
}
#endif /* MODULE */
| gpl-2.0 |
TeamWin/android_kernel_htc_msm8660 | drivers/media/video/gspca/zc3xx.c | 2769 | 260234 | /*
* Z-Star/Vimicro zc301/zc302p/vc30x library
*
* Copyright (C) 2009-2011 Jean-Francois Moine <http://moinejf.free.fr>
* Copyright (C) 2004 2005 2006 Michel Xhaard mxhaard@magic.fr
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#define MODULE_NAME "zc3xx"
#include <linux/input.h>
#include "gspca.h"
#include "jpeg.h"
MODULE_AUTHOR("Jean-Francois Moine <http://moinejf.free.fr>, "
"Serge A. Suchkov <Serge.A.S@tochka.ru>");
MODULE_DESCRIPTION("GSPCA ZC03xx/VC3xx USB Camera Driver");
MODULE_LICENSE("GPL");
static int force_sensor = -1;
#define QUANT_VAL 1 /* quantization table */
#include "zc3xx-reg.h"
/* controls */
enum e_ctrl {
BRIGHTNESS,
CONTRAST,
EXPOSURE,
GAMMA,
AUTOGAIN,
LIGHTFREQ,
SHARPNESS,
NCTRLS /* number of controls */
};
#define AUTOGAIN_DEF 1
/* specific webcam descriptor */
struct sd {
struct gspca_dev gspca_dev; /* !! must be the first item */
struct gspca_ctrl ctrls[NCTRLS];
u8 quality; /* image quality */
#define QUALITY_MIN 50
#define QUALITY_MAX 80
#define QUALITY_DEF 70
u8 bridge;
u8 sensor; /* Type of image sensor chip */
u16 chip_revision;
u8 jpeg_hdr[JPEG_HDR_SZ];
};
enum bridges {
BRIDGE_ZC301,
BRIDGE_ZC303,
};
enum sensors {
SENSOR_ADCM2700,
SENSOR_CS2102,
SENSOR_CS2102K,
SENSOR_GC0303,
SENSOR_GC0305,
SENSOR_HDCS2020,
SENSOR_HV7131B,
SENSOR_HV7131R,
SENSOR_ICM105A,
SENSOR_MC501CB,
SENSOR_MT9V111_1, /* (mi360soc) zc301 */
SENSOR_MT9V111_3, /* (mi360soc) zc303 */
SENSOR_OV7620, /* OV7648 - same values */
SENSOR_OV7630C,
SENSOR_PAS106,
SENSOR_PAS202B,
SENSOR_PB0330,
SENSOR_PO2030,
SENSOR_TAS5130C,
SENSOR_MAX
};
/* V4L2 controls supported by the driver */
static void setcontrast(struct gspca_dev *gspca_dev);
static void setexposure(struct gspca_dev *gspca_dev);
static int sd_setautogain(struct gspca_dev *gspca_dev, __s32 val);
static void setlightfreq(struct gspca_dev *gspca_dev);
static void setsharpness(struct gspca_dev *gspca_dev);
static const struct ctrl sd_ctrls[NCTRLS] = {
[BRIGHTNESS] = {
{
.id = V4L2_CID_BRIGHTNESS,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Brightness",
.minimum = 0,
.maximum = 255,
.step = 1,
.default_value = 128,
},
.set_control = setcontrast
},
[CONTRAST] = {
{
.id = V4L2_CID_CONTRAST,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Contrast",
.minimum = 0,
.maximum = 255,
.step = 1,
.default_value = 128,
},
.set_control = setcontrast
},
[EXPOSURE] = {
{
.id = V4L2_CID_EXPOSURE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Exposure",
.minimum = 0x30d,
.maximum = 0x493e,
.step = 1,
.default_value = 0x927
},
.set_control = setexposure
},
[GAMMA] = {
{
.id = V4L2_CID_GAMMA,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Gamma",
.minimum = 1,
.maximum = 6,
.step = 1,
.default_value = 4,
},
.set_control = setcontrast
},
[AUTOGAIN] = {
{
.id = V4L2_CID_AUTOGAIN,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Auto Gain",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = AUTOGAIN_DEF,
.flags = V4L2_CTRL_FLAG_UPDATE
},
.set = sd_setautogain
},
[LIGHTFREQ] = {
{
.id = V4L2_CID_POWER_LINE_FREQUENCY,
.type = V4L2_CTRL_TYPE_MENU,
.name = "Light frequency filter",
.minimum = 0,
.maximum = 2, /* 0: 0, 1: 50Hz, 2:60Hz */
.step = 1,
.default_value = 0,
},
.set_control = setlightfreq
},
[SHARPNESS] = {
{
.id = V4L2_CID_SHARPNESS,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Sharpness",
.minimum = 0,
.maximum = 3,
.step = 1,
.default_value = 2,
},
.set_control = setsharpness
},
};
static const struct v4l2_pix_format vga_mode[] = {
{320, 240, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 1},
{640, 480, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 640 * 480 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 0},
};
static const struct v4l2_pix_format broken_vga_mode[] = {
{320, 232, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 232 * 4 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 1},
{640, 472, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 640 * 472 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 0},
};
static const struct v4l2_pix_format sif_mode[] = {
{176, 144, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 176,
.sizeimage = 176 * 144 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 1},
{352, 288, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 352,
.sizeimage = 352 * 288 * 3 / 8 + 590,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 0},
};
/* usb exchanges */
struct usb_action {
u8 req;
u8 val;
u16 idx;
};
static const struct usb_action adcm2700_Initial[] = {
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */
{0xa0, 0x04, ZC3XX_R002_CLOCKSELECT}, /* 00,02,04,cc */
{0xa0, 0x00, ZC3XX_R008_CLOCKSETTING}, /* 00,08,03,cc */
{0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */
{0xa0, 0xd3, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,d3,cc */
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */
{0xa0, 0xd8, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,d8,cc */
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc */
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc */
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc */
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc */
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc */
{0xa0, 0xde, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,de,cc */
{0xa0, 0x86, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,86,cc */
{0xbb, 0x00, 0x0400}, /* 04,00,00,bb */
{0xdd, 0x00, 0x0010}, /* 00,00,10,dd */
{0xbb, 0x0f, 0x140f}, /* 14,0f,0f,bb */
{0xa0, 0xb7, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,37,cc */
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, /* 01,89,06,cc */
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */
{0xa0, 0x58, ZC3XX_R116_RGAIN}, /* 01,16,58,cc */
{0xa0, 0x5a, ZC3XX_R118_BGAIN}, /* 01,18,5a,cc */
{0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,02,cc */
{0xa0, 0xd3, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,d3,cc */
{0xbb, 0x00, 0x0408}, /* 04,00,08,bb */
{0xdd, 0x00, 0x0200}, /* 00,02,00,dd */
{0xbb, 0x00, 0x0400}, /* 04,00,00,bb */
{0xdd, 0x00, 0x0010}, /* 00,00,10,dd */
{0xbb, 0x0f, 0x140f}, /* 14,0f,0f,bb */
{0xbb, 0xe0, 0x0c2e}, /* 0c,e0,2e,bb */
{0xbb, 0x01, 0x2000}, /* 20,01,00,bb */
{0xbb, 0x96, 0x2400}, /* 24,96,00,bb */
{0xbb, 0x06, 0x1006}, /* 10,06,06,bb */
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xdd, 0x00, 0x0010}, /* 00,00,10,dd */
{0xaa, 0xfe, 0x0002}, /* 00,fe,02,aa */
{0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */
{0xdd, 0x00, 0x0010}, /* 00,00,10,dd */
{0xbb, 0x5f, 0x2090}, /* 20,5f,90,bb */
{0xbb, 0x01, 0x8000}, /* 80,01,00,bb */
{0xbb, 0x09, 0x8400}, /* 84,09,00,bb */
{0xbb, 0x86, 0x0002}, /* 00,86,02,bb */
{0xbb, 0xe6, 0x0401}, /* 04,e6,01,bb */
{0xbb, 0x86, 0x0802}, /* 08,86,02,bb */
{0xbb, 0xe6, 0x0c01}, /* 0c,e6,01,bb */
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xdd, 0x00, 0x0010}, /* 00,00,10,dd */
{0xaa, 0xfe, 0x0000}, /* 00,fe,00,aa */
{0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */
{0xdd, 0x00, 0x0010}, /* 00,00,10,dd */
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xaa, 0xfe, 0x0020}, /* 00,fe,20,aa */
/*mswin+*/
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT},
{0xaa, 0xfe, 0x0002},
{0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT},
{0xaa, 0xb4, 0xcd37},
{0xaa, 0xa4, 0x0004},
{0xaa, 0xa8, 0x0007},
{0xaa, 0xac, 0x0004},
/*mswin-*/
{0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xdd, 0x00, 0x0010}, /* 00,00,10,dd */
{0xaa, 0xfe, 0x0000}, /* 00,fe,00,aa */
{0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */
{0xdd, 0x00, 0x0010}, /* 00,00,10,dd */
{0xbb, 0x04, 0x0400}, /* 04,04,00,bb */
{0xdd, 0x00, 0x0100}, /* 00,01,00,dd */
{0xbb, 0x01, 0x0400}, /* 04,01,00,bb */
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xaa, 0xfe, 0x0002}, /* 00,fe,02,aa */
{0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */
{0xbb, 0x41, 0x2803}, /* 28,41,03,bb */
{0xbb, 0x40, 0x2c03}, /* 2c,40,03,bb */
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xaa, 0xfe, 0x0010}, /* 00,fe,10,aa */
{}
};
static const struct usb_action adcm2700_InitialScale[] = {
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */
{0xa0, 0x10, ZC3XX_R002_CLOCKSELECT}, /* 00,02,10,cc */
{0xa0, 0x00, ZC3XX_R008_CLOCKSETTING}, /* 00,08,03,cc */
{0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */
{0xa0, 0xd3, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,d3,cc */
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */
{0xa0, 0xd0, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,d0,cc */
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc */
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc */
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc */
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc */
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc */
{0xa0, 0xd8, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,d8,cc */
{0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,88,cc */
{0xbb, 0x00, 0x0400}, /* 04,00,00,bb */
{0xdd, 0x00, 0x0010}, /* 00,00,10,dd */
{0xbb, 0x0f, 0x140f}, /* 14,0f,0f,bb */
{0xa0, 0xb7, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,37,cc */
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, /* 01,89,06,cc */
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */
{0xa0, 0x58, ZC3XX_R116_RGAIN}, /* 01,16,58,cc */
{0xa0, 0x5a, ZC3XX_R118_BGAIN}, /* 01,18,5a,cc */
{0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,02,cc */
{0xa0, 0xd3, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,d3,cc */
{0xbb, 0x00, 0x0408}, /* 04,00,08,bb */
{0xdd, 0x00, 0x0200}, /* 00,02,00,dd */
{0xbb, 0x00, 0x0400}, /* 04,00,00,bb */
{0xdd, 0x00, 0x0050}, /* 00,00,50,dd */
{0xbb, 0x0f, 0x140f}, /* 14,0f,0f,bb */
{0xbb, 0xe0, 0x0c2e}, /* 0c,e0,2e,bb */
{0xbb, 0x01, 0x2000}, /* 20,01,00,bb */
{0xbb, 0x96, 0x2400}, /* 24,96,00,bb */
{0xbb, 0x06, 0x1006}, /* 10,06,06,bb */
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xdd, 0x00, 0x0010}, /* 00,00,10,dd */
{0xaa, 0xfe, 0x0002}, /* 00,fe,02,aa */
{0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */
{0xdd, 0x00, 0x0010}, /* 00,00,10,dd */
{0xbb, 0x5f, 0x2090}, /* 20,5f,90,bb */
{0xbb, 0x01, 0x8000}, /* 80,01,00,bb */
{0xbb, 0x09, 0x8400}, /* 84,09,00,bb */
{0xbb, 0x86, 0x0002}, /* 00,88,02,bb */
{0xbb, 0xe6, 0x0401}, /* 04,e6,01,bb */
{0xbb, 0x86, 0x0802}, /* 08,88,02,bb */
{0xbb, 0xe6, 0x0c01}, /* 0c,e6,01,bb */
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xdd, 0x00, 0x0010}, /* 00,00,10,dd */
{0xaa, 0xfe, 0x0000}, /* 00,fe,00,aa */
{0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */
{0xdd, 0x00, 0x0010}, /* 00,00,10,dd */
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xaa, 0xfe, 0x0020}, /* 00,fe,20,aa */
/*******/
{0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xdd, 0x00, 0x0010}, /* 00,00,10,dd */
{0xaa, 0xfe, 0x0000}, /* 00,fe,00,aa */
{0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */
{0xdd, 0x00, 0x0010}, /* 00,00,10,dd */
{0xbb, 0x04, 0x0400}, /* 04,04,00,bb */
{0xdd, 0x00, 0x0100}, /* 00,01,00,dd */
{0xbb, 0x01, 0x0400}, /* 04,01,00,bb */
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xaa, 0xfe, 0x0002}, /* 00,fe,02,aa */
{0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */
{0xbb, 0x41, 0x2803}, /* 28,41,03,bb */
{0xbb, 0x40, 0x2c03}, /* 2c,40,03,bb */
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xaa, 0xfe, 0x0010}, /* 00,fe,10,aa */
{}
};
static const struct usb_action adcm2700_50HZ[] = {
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xaa, 0xfe, 0x0002}, /* 00,fe,02,aa */
{0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */
{0xbb, 0x05, 0x8400}, /* 84,05,00,bb */
{0xbb, 0xd0, 0xb007}, /* b0,d0,07,bb */
{0xbb, 0xa0, 0xb80f}, /* b8,a0,0f,bb */
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xaa, 0xfe, 0x0010}, /* 00,fe,10,aa */
{0xaa, 0x26, 0x00d0}, /* 00,26,d0,aa */
{0xaa, 0x28, 0x0002}, /* 00,28,02,aa */
{}
};
static const struct usb_action adcm2700_60HZ[] = {
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xaa, 0xfe, 0x0002}, /* 00,fe,02,aa */
{0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */
{0xbb, 0x07, 0x8400}, /* 84,07,00,bb */
{0xbb, 0x82, 0xb006}, /* b0,82,06,bb */
{0xbb, 0x04, 0xb80d}, /* b8,04,0d,bb */
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xaa, 0xfe, 0x0010}, /* 00,fe,10,aa */
{0xaa, 0x26, 0x0057}, /* 00,26,57,aa */
{0xaa, 0x28, 0x0002}, /* 00,28,02,aa */
{}
};
static const struct usb_action adcm2700_NoFliker[] = {
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xaa, 0xfe, 0x0002}, /* 00,fe,02,aa */
{0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */
{0xbb, 0x07, 0x8400}, /* 84,07,00,bb */
{0xbb, 0x05, 0xb000}, /* b0,05,00,bb */
{0xbb, 0xa0, 0xb801}, /* b8,a0,01,bb */
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xaa, 0xfe, 0x0010}, /* 00,fe,10,aa */
{}
};
static const struct usb_action cs2102_InitialScale[] = { /* 320x240 */
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL},
{0xa0, 0x10, ZC3XX_R002_CLOCKSELECT},
{0xa0, 0x00, ZC3XX_R010_CMOSSENSORSELECT},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x20, ZC3XX_R080_HBLANKHIGH},
{0xa0, 0x21, ZC3XX_R081_HBLANKLOW},
{0xa0, 0x30, ZC3XX_R083_RGAINADDR},
{0xa0, 0x31, ZC3XX_R084_GGAINADDR},
{0xa0, 0x32, ZC3XX_R085_BGAINADDR},
{0xa0, 0x23, ZC3XX_R086_EXPTIMEHIGH},
{0xa0, 0x24, ZC3XX_R087_EXPTIMEMID},
{0xa0, 0x25, ZC3XX_R088_EXPTIMELOW},
{0xa0, 0xb3, ZC3XX_R08B_I2CDEVICEADDR},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00 */
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW},
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW},
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW},
{0xaa, 0x02, 0x0008},
{0xaa, 0x03, 0x0000},
{0xaa, 0x11, 0x0000},
{0xaa, 0x12, 0x0089},
{0xaa, 0x13, 0x0000},
{0xaa, 0x14, 0x00e9},
{0xaa, 0x20, 0x0000},
{0xaa, 0x22, 0x0000},
{0xaa, 0x0b, 0x0004},
{0xaa, 0x30, 0x0030},
{0xaa, 0x31, 0x0030},
{0xaa, 0x32, 0x0030},
{0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
{0xa0, 0x10, 0x01ae},
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
{0xa0, 0x68, ZC3XX_R18D_YTARGET},
{0xa0, 0x00, 0x01ad},
{}
};
static const struct usb_action cs2102_Initial[] = { /* 640x480 */
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL},
{0xa0, 0x00, ZC3XX_R002_CLOCKSELECT},
{0xa0, 0x00, ZC3XX_R010_CMOSSENSORSELECT},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x20, ZC3XX_R080_HBLANKHIGH},
{0xa0, 0x21, ZC3XX_R081_HBLANKLOW},
{0xa0, 0x30, ZC3XX_R083_RGAINADDR},
{0xa0, 0x31, ZC3XX_R084_GGAINADDR},
{0xa0, 0x32, ZC3XX_R085_BGAINADDR},
{0xa0, 0x23, ZC3XX_R086_EXPTIMEHIGH},
{0xa0, 0x24, ZC3XX_R087_EXPTIMEMID},
{0xa0, 0x25, ZC3XX_R088_EXPTIMELOW},
{0xa0, 0xb3, ZC3XX_R08B_I2CDEVICEADDR},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00 */
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW},
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW},
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW},
{0xaa, 0x02, 0x0008},
{0xaa, 0x03, 0x0000},
{0xaa, 0x11, 0x0001},
{0xaa, 0x12, 0x0087},
{0xaa, 0x13, 0x0001},
{0xaa, 0x14, 0x00e7},
{0xaa, 0x20, 0x0000},
{0xaa, 0x22, 0x0000},
{0xaa, 0x0b, 0x0004},
{0xaa, 0x30, 0x0030},
{0xaa, 0x31, 0x0030},
{0xaa, 0x32, 0x0030},
{0xa0, 0x77, ZC3XX_R101_SENSORCORRECTION},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
{0xa0, 0x15, 0x01ae},
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
{0xa0, 0x68, ZC3XX_R18D_YTARGET},
{0xa0, 0x00, 0x01ad},
{}
};
static const struct usb_action cs2102_50HZScale[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xaa, 0x23, 0x0001},
{0xaa, 0x24, 0x005f},
{0xaa, 0x25, 0x0090},
{0xaa, 0x21, 0x00dd},
{0xa0, 0x02, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0xbf, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x20, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x3a, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x98, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0xdd, ZC3XX_R01D_HSYNC_0},
{0xa0, 0xe4, ZC3XX_R01E_HSYNC_1},
{0xa0, 0xf0, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xff, ZC3XX_R020_HSYNC_3},
{}
};
static const struct usb_action cs2102_50HZ[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xaa, 0x23, 0x0000},
{0xaa, 0x24, 0x00af},
{0xaa, 0x25, 0x00c8},
{0xaa, 0x21, 0x0068},
{0xa0, 0x01, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x5f, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x90, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x1d, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x4c, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x68, ZC3XX_R01D_HSYNC_0},
{0xa0, 0xe3, ZC3XX_R01E_HSYNC_1},
{0xa0, 0xf0, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xff, ZC3XX_R020_HSYNC_3},
{}
};
static const struct usb_action cs2102_60HZScale[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xaa, 0x23, 0x0001},
{0xaa, 0x24, 0x0055},
{0xaa, 0x25, 0x00cc},
{0xaa, 0x21, 0x003f},
{0xa0, 0x02, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0xab, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x98, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x30, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0xd4, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x39, ZC3XX_R01D_HSYNC_0},
{0xa0, 0x70, ZC3XX_R01E_HSYNC_1},
{0xa0, 0xb0, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xff, ZC3XX_R020_HSYNC_3},
{}
};
static const struct usb_action cs2102_60HZ[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xaa, 0x23, 0x0000},
{0xaa, 0x24, 0x00aa},
{0xaa, 0x25, 0x00e6},
{0xaa, 0x21, 0x003f},
{0xa0, 0x01, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x55, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xcc, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x18, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x6a, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x3f, ZC3XX_R01D_HSYNC_0},
{0xa0, 0xa5, ZC3XX_R01E_HSYNC_1},
{0xa0, 0xf0, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xff, ZC3XX_R020_HSYNC_3},
{}
};
static const struct usb_action cs2102_NoFlikerScale[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xaa, 0x23, 0x0001},
{0xaa, 0x24, 0x005f},
{0xaa, 0x25, 0x0000},
{0xaa, 0x21, 0x0001},
{0xa0, 0x02, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0xbf, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x00, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x80, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x01, ZC3XX_R01D_HSYNC_0},
{0xa0, 0x40, ZC3XX_R01E_HSYNC_1},
{0xa0, 0xa0, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xff, ZC3XX_R020_HSYNC_3},
{}
};
static const struct usb_action cs2102_NoFliker[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xaa, 0x23, 0x0000},
{0xaa, 0x24, 0x00af},
{0xaa, 0x25, 0x0080},
{0xaa, 0x21, 0x0001},
{0xa0, 0x01, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x5f, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x80, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x80, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x01, ZC3XX_R01D_HSYNC_0},
{0xa0, 0x40, ZC3XX_R01E_HSYNC_1},
{0xa0, 0xa0, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xff, ZC3XX_R020_HSYNC_3},
{}
};
/* CS2102_KOCOM */
static const struct usb_action cs2102K_InitialScale[] = {
{0xa0, 0x11, ZC3XX_R002_CLOCKSELECT},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING},
{0xa0, 0x08, ZC3XX_R010_CMOSSENSORSELECT},
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW},
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW},
{0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW},
{0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW},
{0xa0, 0x55, ZC3XX_R08B_I2CDEVICEADDR},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x00, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x0a, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x02, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x0b, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x02, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x0c, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x7c, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x0d, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0xa3, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x03, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0xfb, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x05, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x00, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x06, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x03, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x09, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x08, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x0e, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x04, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x0f, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x18, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x10, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x18, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x11, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x18, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x12, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x18, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x15, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x00, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x16, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x0c, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x17, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x0c, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x04, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0xb7, ZC3XX_R101_SENSORCORRECTION},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x78, ZC3XX_R18D_YTARGET},
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
{0xa0, 0x20, ZC3XX_R087_EXPTIMEMID},
{0xa0, 0x21, ZC3XX_R088_EXPTIMELOW},
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
{0xa0, 0x00, 0x01ad},
{0xa0, 0x01, 0x01b1},
{0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x60, ZC3XX_R116_RGAIN},
{0xa0, 0x40, ZC3XX_R117_GGAIN},
{0xa0, 0x4c, ZC3XX_R118_BGAIN},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* clock ? */
{0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00}, /* sharpness+ */
{0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05}, /* sharpness- */
{0xa0, 0x13, ZC3XX_R120_GAMMA00}, /* gamma 4 */
{0xa0, 0x38, ZC3XX_R121_GAMMA01},
{0xa0, 0x59, ZC3XX_R122_GAMMA02},
{0xa0, 0x79, ZC3XX_R123_GAMMA03},
{0xa0, 0x92, ZC3XX_R124_GAMMA04},
{0xa0, 0xa7, ZC3XX_R125_GAMMA05},
{0xa0, 0xb9, ZC3XX_R126_GAMMA06},
{0xa0, 0xc8, ZC3XX_R127_GAMMA07},
{0xa0, 0xd4, ZC3XX_R128_GAMMA08},
{0xa0, 0xdf, ZC3XX_R129_GAMMA09},
{0xa0, 0xe7, ZC3XX_R12A_GAMMA0A},
{0xa0, 0xee, ZC3XX_R12B_GAMMA0B},
{0xa0, 0xf4, ZC3XX_R12C_GAMMA0C},
{0xa0, 0xf9, ZC3XX_R12D_GAMMA0D},
{0xa0, 0xfc, ZC3XX_R12E_GAMMA0E},
{0xa0, 0xff, ZC3XX_R12F_GAMMA0F},
{0xa0, 0x26, ZC3XX_R130_GAMMA10},
{0xa0, 0x22, ZC3XX_R131_GAMMA11},
{0xa0, 0x20, ZC3XX_R132_GAMMA12},
{0xa0, 0x1c, ZC3XX_R133_GAMMA13},
{0xa0, 0x16, ZC3XX_R134_GAMMA14},
{0xa0, 0x13, ZC3XX_R135_GAMMA15},
{0xa0, 0x10, ZC3XX_R136_GAMMA16},
{0xa0, 0x0d, ZC3XX_R137_GAMMA17},
{0xa0, 0x0b, ZC3XX_R138_GAMMA18},
{0xa0, 0x09, ZC3XX_R139_GAMMA19},
{0xa0, 0x07, ZC3XX_R13A_GAMMA1A},
{0xa0, 0x06, ZC3XX_R13B_GAMMA1B},
{0xa0, 0x05, ZC3XX_R13C_GAMMA1C},
{0xa0, 0x04, ZC3XX_R13D_GAMMA1D},
{0xa0, 0x03, ZC3XX_R13E_GAMMA1E},
{0xa0, 0x02, ZC3XX_R13F_GAMMA1F},
{0xa0, 0x58, ZC3XX_R10A_RGB00}, /* matrix */
{0xa0, 0xf4, ZC3XX_R10B_RGB01},
{0xa0, 0xf4, ZC3XX_R10C_RGB02},
{0xa0, 0xf4, ZC3XX_R10D_RGB10},
{0xa0, 0x58, ZC3XX_R10E_RGB11},
{0xa0, 0xf4, ZC3XX_R10F_RGB12},
{0xa0, 0xf4, ZC3XX_R110_RGB20},
{0xa0, 0xf4, ZC3XX_R111_RGB21},
{0xa0, 0x58, ZC3XX_R112_RGB22},
{0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x00, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x13, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x22, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x14, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x01, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x20, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x01, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x21, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x22, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x04, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x01, ZC3XX_R0A3_EXPOSURETIMEHIGH},
{0xa0, 0x22, ZC3XX_R0A4_EXPOSURETIMELOW},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xee, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x3a, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x0c, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x28, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x04, ZC3XX_R01D_HSYNC_0},
{0xa0, 0x0f, ZC3XX_R01E_HSYNC_1},
{0xa0, 0x19, ZC3XX_R01F_HSYNC_2},
{0xa0, 0x1f, ZC3XX_R020_HSYNC_3},
{0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN},
{0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x60, ZC3XX_R116_RGAIN},
{0xa0, 0x40, ZC3XX_R117_GGAIN},
{0xa0, 0x4c, ZC3XX_R118_BGAIN},
{0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x20, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x01, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x21, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x5c, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x00, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x13, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x5c, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x14, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x01, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x04, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x20, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x01, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x21, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x96, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x00, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x13, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x96, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x14, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x01, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x04, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN},
{}
};
static const struct usb_action cs2102K_Initial[] = {
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL},
{0xa0, 0x00, ZC3XX_R002_CLOCKSELECT},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING},
{0xa0, 0x08, ZC3XX_R010_CMOSSENSORSELECT},
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW},
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW},
{0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW},
{0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW},
/*fixme: next sequence = i2c exchanges*/
{0xa0, 0x55, ZC3XX_R08B_I2CDEVICEADDR},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x00, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x0a, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x02, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x0b, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x02, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x0c, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x7b, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x0d, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0xa3, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x03, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0xfb, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x05, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x00, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x06, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x03, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x09, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x08, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x0e, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x04, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x0f, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x18, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x10, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x18, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x11, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x18, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x12, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x18, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x15, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x00, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x16, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x0c, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x17, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x0c, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x04, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0xf7, ZC3XX_R101_SENSORCORRECTION},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x78, ZC3XX_R18D_YTARGET},
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
{0xa0, 0x20, ZC3XX_R087_EXPTIMEMID},
{0xa0, 0x21, ZC3XX_R088_EXPTIMELOW},
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
{0xa0, 0x00, 0x01ad},
{0xa0, 0x01, 0x01b1},
{0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x60, ZC3XX_R116_RGAIN},
{0xa0, 0x40, ZC3XX_R117_GGAIN},
{0xa0, 0x4c, ZC3XX_R118_BGAIN},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* clock ? */
{0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00}, /* sharpness+ */
{0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05}, /* sharpness- */
{0xa0, 0x13, ZC3XX_R120_GAMMA00}, /* gamma 4 */
{0xa0, 0x38, ZC3XX_R121_GAMMA01},
{0xa0, 0x59, ZC3XX_R122_GAMMA02},
{0xa0, 0x79, ZC3XX_R123_GAMMA03},
{0xa0, 0x92, ZC3XX_R124_GAMMA04},
{0xa0, 0xa7, ZC3XX_R125_GAMMA05},
{0xa0, 0xb9, ZC3XX_R126_GAMMA06},
{0xa0, 0xc8, ZC3XX_R127_GAMMA07},
{0xa0, 0xd4, ZC3XX_R128_GAMMA08},
{0xa0, 0xdf, ZC3XX_R129_GAMMA09},
{0xa0, 0xe7, ZC3XX_R12A_GAMMA0A},
{0xa0, 0xee, ZC3XX_R12B_GAMMA0B},
{0xa0, 0xf4, ZC3XX_R12C_GAMMA0C},
{0xa0, 0xf9, ZC3XX_R12D_GAMMA0D},
{0xa0, 0xfc, ZC3XX_R12E_GAMMA0E},
{0xa0, 0xff, ZC3XX_R12F_GAMMA0F},
{0xa0, 0x26, ZC3XX_R130_GAMMA10},
{0xa0, 0x22, ZC3XX_R131_GAMMA11},
{0xa0, 0x20, ZC3XX_R132_GAMMA12},
{0xa0, 0x1c, ZC3XX_R133_GAMMA13},
{0xa0, 0x16, ZC3XX_R134_GAMMA14},
{0xa0, 0x13, ZC3XX_R135_GAMMA15},
{0xa0, 0x10, ZC3XX_R136_GAMMA16},
{0xa0, 0x0d, ZC3XX_R137_GAMMA17},
{0xa0, 0x0b, ZC3XX_R138_GAMMA18},
{0xa0, 0x09, ZC3XX_R139_GAMMA19},
{0xa0, 0x07, ZC3XX_R13A_GAMMA1A},
{0xa0, 0x06, ZC3XX_R13B_GAMMA1B},
{0xa0, 0x05, ZC3XX_R13C_GAMMA1C},
{0xa0, 0x04, ZC3XX_R13D_GAMMA1D},
{0xa0, 0x03, ZC3XX_R13E_GAMMA1E},
{0xa0, 0x02, ZC3XX_R13F_GAMMA1F},
{0xa0, 0x58, ZC3XX_R10A_RGB00}, /* matrix */
{0xa0, 0xf4, ZC3XX_R10B_RGB01},
{0xa0, 0xf4, ZC3XX_R10C_RGB02},
{0xa0, 0xf4, ZC3XX_R10D_RGB10},
{0xa0, 0x58, ZC3XX_R10E_RGB11},
{0xa0, 0xf4, ZC3XX_R10F_RGB12},
{0xa0, 0xf4, ZC3XX_R110_RGB20},
{0xa0, 0xf4, ZC3XX_R111_RGB21},
{0xa0, 0x58, ZC3XX_R112_RGB22},
{0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x00, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x13, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x22, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x14, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x01, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x20, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x01, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x21, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x22, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x04, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x01, ZC3XX_R0A3_EXPOSURETIMEHIGH},
{0xa0, 0x22, ZC3XX_R0A4_EXPOSURETIMELOW},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xee, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x3a, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x0c, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x28, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x04, ZC3XX_R01D_HSYNC_0},
{0xa0, 0x0f, ZC3XX_R01E_HSYNC_1},
{0xa0, 0x19, ZC3XX_R01F_HSYNC_2},
{0xa0, 0x1f, ZC3XX_R020_HSYNC_3},
{0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN},
{0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x60, ZC3XX_R116_RGAIN},
{0xa0, 0x40, ZC3XX_R117_GGAIN},
{0xa0, 0x4c, ZC3XX_R118_BGAIN},
{0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x20, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x01, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x21, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x5c, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x00, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x13, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x5c, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x14, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x01, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x04, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x20, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x01, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x21, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x96, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x00, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x13, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x96, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x14, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x01, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x04, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN},
/*fixme:what does the next sequence?*/
{0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x20, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x01, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x21, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0xd0, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x00, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x13, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0xd0, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x14, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x01, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x04, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x02, ZC3XX_R008_CLOCKSETTING},
{0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x20, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x02, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x21, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x0a, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x00, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x13, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x0a, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x14, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x02, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x04, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x20, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x02, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x21, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x44, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x00, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x13, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x44, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x14, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x02, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x04, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x20, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x02, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x21, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x7e, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x00, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x13, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x7e, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x14, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x02, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x04, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x00, ZC3XX_R094_I2CWRITEACK},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN},
{}
};
static const struct usb_action gc0305_Initial[] = { /* 640x480 */
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00,08,03,cc */
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xa0, 0x04, ZC3XX_R002_CLOCKSELECT}, /* 00,02,04,cc */
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,e0,cc */
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc */
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc */
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc */
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc */
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc */
{0xa0, 0xe6, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,e6,cc */
{0xa0, 0x86, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,86,cc */
{0xa0, 0x98, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,98,cc */
{0xaa, 0x13, 0x0002}, /* 00,13,02,aa */
{0xaa, 0x15, 0x0003}, /* 00,15,03,aa */
{0xaa, 0x01, 0x0000}, /* 00,01,00,aa */
{0xaa, 0x02, 0x0000}, /* 00,02,00,aa */
{0xaa, 0x1a, 0x0000}, /* 00,1a,00,aa */
{0xaa, 0x1c, 0x0017}, /* 00,1c,17,aa */
{0xaa, 0x1d, 0x0080}, /* 00,1d,80,aa */
{0xaa, 0x1f, 0x0008}, /* 00,1f,08,aa */
{0xaa, 0x21, 0x0012}, /* 00,21,12,aa */
{0xa0, 0x82, ZC3XX_R086_EXPTIMEHIGH}, /* 00,86,82,cc */
{0xa0, 0x83, ZC3XX_R087_EXPTIMEMID}, /* 00,87,83,cc */
{0xa0, 0x84, ZC3XX_R088_EXPTIMELOW}, /* 00,88,84,cc */
{0xaa, 0x05, 0x0000}, /* 00,05,00,aa */
{0xaa, 0x0a, 0x0000}, /* 00,0a,00,aa */
{0xaa, 0x0b, 0x00b0}, /* 00,0b,b0,aa */
{0xaa, 0x0c, 0x0000}, /* 00,0c,00,aa */
{0xaa, 0x0d, 0x00b0}, /* 00,0d,b0,aa */
{0xaa, 0x0e, 0x0000}, /* 00,0e,00,aa */
{0xaa, 0x0f, 0x00b0}, /* 00,0f,b0,aa */
{0xaa, 0x10, 0x0000}, /* 00,10,00,aa */
{0xaa, 0x11, 0x00b0}, /* 00,11,b0,aa */
{0xaa, 0x16, 0x0001}, /* 00,16,01,aa */
{0xaa, 0x17, 0x00e6}, /* 00,17,e6,aa */
{0xaa, 0x18, 0x0002}, /* 00,18,02,aa */
{0xaa, 0x19, 0x0086}, /* 00,19,86,aa */
{0xaa, 0x20, 0x0000}, /* 00,20,00,aa */
{0xaa, 0x1b, 0x0020}, /* 00,1b,20,aa */
{0xa0, 0xb7, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,b7,cc */
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */
{0xa0, 0x76, ZC3XX_R189_AWBSTATUS}, /* 01,89,76,cc */
{0xa0, 0x09, 0x01ad}, /* 01,ad,09,cc */
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */
{0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN}, /* 01,a8,60,cc */
{0xa0, 0x85, ZC3XX_R18D_YTARGET}, /* 01,8d,85,cc */
{0xa0, 0x00, 0x011e}, /* 01,1e,00,cc */
{0xa0, 0x52, ZC3XX_R116_RGAIN}, /* 01,16,52,cc */
{0xa0, 0x40, ZC3XX_R117_GGAIN}, /* 01,17,40,cc */
{0xa0, 0x52, ZC3XX_R118_BGAIN}, /* 01,18,52,cc */
{0xa0, 0x03, ZC3XX_R113_RGB03}, /* 01,13,03,cc */
{}
};
static const struct usb_action gc0305_InitialScale[] = { /* 320x240 */
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00,08,03,cc */
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xa0, 0x10, ZC3XX_R002_CLOCKSELECT}, /* 00,02,10,cc */
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,e0,cc */
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc */
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc */
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc */
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc */
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc */
{0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,e8,cc */
{0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,88,cc */
{0xa0, 0x98, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,98,cc */
{0xaa, 0x13, 0x0000}, /* 00,13,00,aa */
{0xaa, 0x15, 0x0001}, /* 00,15,01,aa */
{0xaa, 0x01, 0x0000}, /* 00,01,00,aa */
{0xaa, 0x02, 0x0000}, /* 00,02,00,aa */
{0xaa, 0x1a, 0x0000}, /* 00,1a,00,aa */
{0xaa, 0x1c, 0x0017}, /* 00,1c,17,aa */
{0xaa, 0x1d, 0x0080}, /* 00,1d,80,aa */
{0xaa, 0x1f, 0x0008}, /* 00,1f,08,aa */
{0xaa, 0x21, 0x0012}, /* 00,21,12,aa */
{0xa0, 0x82, ZC3XX_R086_EXPTIMEHIGH}, /* 00,86,82,cc */
{0xa0, 0x83, ZC3XX_R087_EXPTIMEMID}, /* 00,87,83,cc */
{0xa0, 0x84, ZC3XX_R088_EXPTIMELOW}, /* 00,88,84,cc */
{0xaa, 0x05, 0x0000}, /* 00,05,00,aa */
{0xaa, 0x0a, 0x0000}, /* 00,0a,00,aa */
{0xaa, 0x0b, 0x00b0}, /* 00,0b,b0,aa */
{0xaa, 0x0c, 0x0000}, /* 00,0c,00,aa */
{0xaa, 0x0d, 0x00b0}, /* 00,0d,b0,aa */
{0xaa, 0x0e, 0x0000}, /* 00,0e,00,aa */
{0xaa, 0x0f, 0x00b0}, /* 00,0f,b0,aa */
{0xaa, 0x10, 0x0000}, /* 00,10,00,aa */
{0xaa, 0x11, 0x00b0}, /* 00,11,b0,aa */
{0xaa, 0x16, 0x0001}, /* 00,16,01,aa */
{0xaa, 0x17, 0x00e8}, /* 00,17,e8,aa */
{0xaa, 0x18, 0x0002}, /* 00,18,02,aa */
{0xaa, 0x19, 0x0088}, /* 00,19,88,aa */
{0xaa, 0x20, 0x0000}, /* 00,20,00,aa */
{0xaa, 0x1b, 0x0020}, /* 00,1b,20,aa */
{0xa0, 0xb7, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,b7,cc */
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */
{0xa0, 0x76, ZC3XX_R189_AWBSTATUS}, /* 01,89,76,cc */
{0xa0, 0x09, 0x01ad}, /* 01,ad,09,cc */
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */
{0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN}, /* 01,a8,60,cc */
{0xa0, 0x00, 0x011e}, /* 01,1e,00,cc */
{0xa0, 0x52, ZC3XX_R116_RGAIN}, /* 01,16,52,cc */
{0xa0, 0x40, ZC3XX_R117_GGAIN}, /* 01,17,40,cc */
{0xa0, 0x52, ZC3XX_R118_BGAIN}, /* 01,18,52,cc */
{0xa0, 0x03, ZC3XX_R113_RGB03}, /* 01,13,03,cc */
{}
};
static const struct usb_action gc0305_50HZ[] = {
{0xaa, 0x82, 0x0000}, /* 00,82,00,aa */
{0xaa, 0x83, 0x0002}, /* 00,83,02,aa */
{0xaa, 0x84, 0x0038}, /* 00,84,38,aa */ /* win: 00,84,ec */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x0b, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,0b,cc */
{0xa0, 0x18, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,18,cc */
/* win: 01,92,10 */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x8e, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,8e,cc */
/* win: 01,97,ec */
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0e,cc */
{0xa0, 0x15, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,15,cc */
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,10,cc */
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc */
{0xa0, 0x62, ZC3XX_R01D_HSYNC_0}, /* 00,1d,62,cc */
{0xa0, 0x90, ZC3XX_R01E_HSYNC_1}, /* 00,1e,90,cc */
{0xa0, 0xc8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,c8,cc */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */
{0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,60,cc */
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,42,cc */
/* {0xa0, 0x85, ZC3XX_R18D_YTARGET}, * 01,8d,85,cc *
* if 640x480 */
{}
};
static const struct usb_action gc0305_60HZ[] = {
{0xaa, 0x82, 0x0000}, /* 00,82,00,aa */
{0xaa, 0x83, 0x0000}, /* 00,83,00,aa */
{0xaa, 0x84, 0x00ec}, /* 00,84,ec,aa */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x0b, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,0b,cc */
{0xa0, 0x10, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,10,cc */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0xec, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,ec,cc */
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0e,cc */
{0xa0, 0x15, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,15,cc */
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,10,cc */
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc */
{0xa0, 0x62, ZC3XX_R01D_HSYNC_0}, /* 00,1d,62,cc */
{0xa0, 0x90, ZC3XX_R01E_HSYNC_1}, /* 00,1e,90,cc */
{0xa0, 0xc8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,c8,cc */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */
{0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,60,cc */
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,42,cc */
{0xa0, 0x80, ZC3XX_R18D_YTARGET}, /* 01,8d,80,cc */
{}
};
static const struct usb_action gc0305_NoFliker[] = {
{0xa0, 0x0c, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0c,cc */
{0xaa, 0x82, 0x0000}, /* 00,82,00,aa */
{0xaa, 0x83, 0x0000}, /* 00,83,00,aa */
{0xaa, 0x84, 0x0020}, /* 00,84,20,aa */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x00, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,00,cc */
{0xa0, 0x48, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,48,cc */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x10, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,10,cc */
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0e,cc */
{0xa0, 0x15, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,15,cc */
{0xa0, 0x62, ZC3XX_R01D_HSYNC_0}, /* 00,1d,62,cc */
{0xa0, 0x90, ZC3XX_R01E_HSYNC_1}, /* 00,1e,90,cc */
{0xa0, 0xc8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,c8,cc */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */
{0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,60,cc */
{0xa0, 0x03, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,03,cc */
{0xa0, 0x80, ZC3XX_R18D_YTARGET}, /* 01,8d,80,cc */
{}
};
static const struct usb_action hdcs2020_InitialScale[] = {
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL},
{0xa0, 0x11, ZC3XX_R002_CLOCKSELECT},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* qtable 0x05 */
{0xa0, 0x08, ZC3XX_R010_CMOSSENSORSELECT},
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW},
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW},
{0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW},
{0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW},
{0xaa, 0x1c, 0x0000},
{0xaa, 0x0a, 0x0001},
{0xaa, 0x0b, 0x0006},
{0xaa, 0x0c, 0x007b},
{0xaa, 0x0d, 0x00a7},
{0xaa, 0x03, 0x00fb},
{0xaa, 0x05, 0x0000},
{0xaa, 0x06, 0x0003},
{0xaa, 0x09, 0x0008},
{0xaa, 0x0f, 0x0018}, /* set sensor gain */
{0xaa, 0x10, 0x0018},
{0xaa, 0x11, 0x0018},
{0xaa, 0x12, 0x0018},
{0xaa, 0x15, 0x004e},
{0xaa, 0x1c, 0x0004},
{0xa0, 0xb7, ZC3XX_R101_SENSORCORRECTION},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x70, ZC3XX_R18D_YTARGET},
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
{0xa1, 0x01, 0x0002},
{0xa1, 0x01, 0x0008},
{0xa1, 0x01, 0x0180},
{0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x40, ZC3XX_R116_RGAIN},
{0xa0, 0x40, ZC3XX_R117_GGAIN},
{0xa0, 0x40, ZC3XX_R118_BGAIN},
{0xa1, 0x01, 0x0008},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* clock ? */
{0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00}, /* sharpness+ */
{0xa1, 0x01, 0x01c8},
{0xa1, 0x01, 0x01c9},
{0xa1, 0x01, 0x01ca},
{0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05}, /* sharpness- */
{0xa0, 0x13, ZC3XX_R120_GAMMA00}, /* gamma 4 */
{0xa0, 0x38, ZC3XX_R121_GAMMA01},
{0xa0, 0x59, ZC3XX_R122_GAMMA02},
{0xa0, 0x79, ZC3XX_R123_GAMMA03},
{0xa0, 0x92, ZC3XX_R124_GAMMA04},
{0xa0, 0xa7, ZC3XX_R125_GAMMA05},
{0xa0, 0xb9, ZC3XX_R126_GAMMA06},
{0xa0, 0xc8, ZC3XX_R127_GAMMA07},
{0xa0, 0xd4, ZC3XX_R128_GAMMA08},
{0xa0, 0xdf, ZC3XX_R129_GAMMA09},
{0xa0, 0xe7, ZC3XX_R12A_GAMMA0A},
{0xa0, 0xee, ZC3XX_R12B_GAMMA0B},
{0xa0, 0xf4, ZC3XX_R12C_GAMMA0C},
{0xa0, 0xf9, ZC3XX_R12D_GAMMA0D},
{0xa0, 0xfc, ZC3XX_R12E_GAMMA0E},
{0xa0, 0xff, ZC3XX_R12F_GAMMA0F},
{0xa0, 0x26, ZC3XX_R130_GAMMA10},
{0xa0, 0x22, ZC3XX_R131_GAMMA11},
{0xa0, 0x20, ZC3XX_R132_GAMMA12},
{0xa0, 0x1c, ZC3XX_R133_GAMMA13},
{0xa0, 0x16, ZC3XX_R134_GAMMA14},
{0xa0, 0x13, ZC3XX_R135_GAMMA15},
{0xa0, 0x10, ZC3XX_R136_GAMMA16},
{0xa0, 0x0d, ZC3XX_R137_GAMMA17},
{0xa0, 0x0b, ZC3XX_R138_GAMMA18},
{0xa0, 0x09, ZC3XX_R139_GAMMA19},
{0xa0, 0x07, ZC3XX_R13A_GAMMA1A},
{0xa0, 0x06, ZC3XX_R13B_GAMMA1B},
{0xa0, 0x05, ZC3XX_R13C_GAMMA1C},
{0xa0, 0x04, ZC3XX_R13D_GAMMA1D},
{0xa0, 0x03, ZC3XX_R13E_GAMMA1E},
{0xa0, 0x02, ZC3XX_R13F_GAMMA1F},
{0xa0, 0x66, ZC3XX_R10A_RGB00}, /* matrix */
{0xa0, 0xed, ZC3XX_R10B_RGB01},
{0xa0, 0xed, ZC3XX_R10C_RGB02},
{0xa0, 0xed, ZC3XX_R10D_RGB10},
{0xa0, 0x66, ZC3XX_R10E_RGB11},
{0xa0, 0xed, ZC3XX_R10F_RGB12},
{0xa0, 0xed, ZC3XX_R110_RGB20},
{0xa0, 0xed, ZC3XX_R111_RGB21},
{0xa0, 0x66, ZC3XX_R112_RGB22},
{0xa1, 0x01, 0x0180},
{0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xaa, 0x13, 0x0031},
{0xaa, 0x14, 0x0001},
{0xaa, 0x0e, 0x0004},
{0xaa, 0x19, 0x00cd},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x02, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x62, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x3d, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x0c, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 0x14 */
{0xa0, 0x28, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x04, ZC3XX_R01D_HSYNC_0},
{0xa0, 0x18, ZC3XX_R01E_HSYNC_1},
{0xa0, 0x2c, ZC3XX_R01F_HSYNC_2},
{0xa0, 0x41, ZC3XX_R020_HSYNC_3},
{0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa1, 0x01, 0x0180},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x40, ZC3XX_R116_RGAIN},
{0xa0, 0x40, ZC3XX_R117_GGAIN},
{0xa0, 0x40, ZC3XX_R118_BGAIN},
{}
};
static const struct usb_action hdcs2020_Initial[] = {
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL},
{0xa0, 0x00, ZC3XX_R002_CLOCKSELECT},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING},
{0xa0, 0x08, ZC3XX_R010_CMOSSENSORSELECT},
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW},
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW},
{0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW},
{0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW},
{0xaa, 0x1c, 0x0000},
{0xaa, 0x0a, 0x0001},
{0xaa, 0x0b, 0x0006},
{0xaa, 0x0c, 0x007a},
{0xaa, 0x0d, 0x00a7},
{0xaa, 0x03, 0x00fb},
{0xaa, 0x05, 0x0000},
{0xaa, 0x06, 0x0003},
{0xaa, 0x09, 0x0008},
{0xaa, 0x0f, 0x0018}, /* original setting */
{0xaa, 0x10, 0x0018},
{0xaa, 0x11, 0x0018},
{0xaa, 0x12, 0x0018},
{0xaa, 0x15, 0x004e},
{0xaa, 0x1c, 0x0004},
{0xa0, 0xf7, ZC3XX_R101_SENSORCORRECTION},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x70, ZC3XX_R18D_YTARGET},
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
{0xa1, 0x01, 0x0002},
{0xa1, 0x01, 0x0008},
{0xa1, 0x01, 0x0180},
{0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x40, ZC3XX_R116_RGAIN},
{0xa0, 0x40, ZC3XX_R117_GGAIN},
{0xa0, 0x40, ZC3XX_R118_BGAIN},
{0xa1, 0x01, 0x0008},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* clock ? */
{0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00}, /* sharpness+ */
{0xa1, 0x01, 0x01c8},
{0xa1, 0x01, 0x01c9},
{0xa1, 0x01, 0x01ca},
{0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05}, /* sharpness- */
{0xa0, 0x13, ZC3XX_R120_GAMMA00}, /* gamma 4 */
{0xa0, 0x38, ZC3XX_R121_GAMMA01},
{0xa0, 0x59, ZC3XX_R122_GAMMA02},
{0xa0, 0x79, ZC3XX_R123_GAMMA03},
{0xa0, 0x92, ZC3XX_R124_GAMMA04},
{0xa0, 0xa7, ZC3XX_R125_GAMMA05},
{0xa0, 0xb9, ZC3XX_R126_GAMMA06},
{0xa0, 0xc8, ZC3XX_R127_GAMMA07},
{0xa0, 0xd4, ZC3XX_R128_GAMMA08},
{0xa0, 0xdf, ZC3XX_R129_GAMMA09},
{0xa0, 0xe7, ZC3XX_R12A_GAMMA0A},
{0xa0, 0xee, ZC3XX_R12B_GAMMA0B},
{0xa0, 0xf4, ZC3XX_R12C_GAMMA0C},
{0xa0, 0xf9, ZC3XX_R12D_GAMMA0D},
{0xa0, 0xfc, ZC3XX_R12E_GAMMA0E},
{0xa0, 0xff, ZC3XX_R12F_GAMMA0F},
{0xa0, 0x26, ZC3XX_R130_GAMMA10},
{0xa0, 0x22, ZC3XX_R131_GAMMA11},
{0xa0, 0x20, ZC3XX_R132_GAMMA12},
{0xa0, 0x1c, ZC3XX_R133_GAMMA13},
{0xa0, 0x16, ZC3XX_R134_GAMMA14},
{0xa0, 0x13, ZC3XX_R135_GAMMA15},
{0xa0, 0x10, ZC3XX_R136_GAMMA16},
{0xa0, 0x0d, ZC3XX_R137_GAMMA17},
{0xa0, 0x0b, ZC3XX_R138_GAMMA18},
{0xa0, 0x09, ZC3XX_R139_GAMMA19},
{0xa0, 0x07, ZC3XX_R13A_GAMMA1A},
{0xa0, 0x06, ZC3XX_R13B_GAMMA1B},
{0xa0, 0x05, ZC3XX_R13C_GAMMA1C},
{0xa0, 0x04, ZC3XX_R13D_GAMMA1D},
{0xa0, 0x03, ZC3XX_R13E_GAMMA1E},
{0xa0, 0x02, ZC3XX_R13F_GAMMA1F},
{0xa0, 0x66, ZC3XX_R10A_RGB00}, /* matrix */
{0xa0, 0xed, ZC3XX_R10B_RGB01},
{0xa0, 0xed, ZC3XX_R10C_RGB02},
{0xa0, 0xed, ZC3XX_R10D_RGB10},
{0xa0, 0x66, ZC3XX_R10E_RGB11},
{0xa0, 0xed, ZC3XX_R10F_RGB12},
{0xa0, 0xed, ZC3XX_R110_RGB20},
{0xa0, 0xed, ZC3XX_R111_RGB21},
{0xa0, 0x66, ZC3XX_R112_RGB22},
{0xa1, 0x01, 0x0180},
{0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
/**** set exposure ***/
{0xaa, 0x13, 0x0031},
{0xaa, 0x14, 0x0001},
{0xaa, 0x0e, 0x0004},
{0xaa, 0x19, 0x00cd},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x02, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x62, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x3d, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x0c, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x28, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x04, ZC3XX_R01D_HSYNC_0},
{0xa0, 0x18, ZC3XX_R01E_HSYNC_1},
{0xa0, 0x2c, ZC3XX_R01F_HSYNC_2},
{0xa0, 0x41, ZC3XX_R020_HSYNC_3},
{0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa1, 0x01, 0x0180},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x40, ZC3XX_R116_RGAIN},
{0xa0, 0x40, ZC3XX_R117_GGAIN},
{0xa0, 0x40, ZC3XX_R118_BGAIN},
{}
};
static const struct usb_action hdcs2020_50HZ[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xaa, 0x13, 0x0018}, /* 00,13,18,aa */
{0xaa, 0x14, 0x0001}, /* 00,14,01,aa */
{0xaa, 0x0e, 0x0005}, /* 00,0e,05,aa */
{0xaa, 0x19, 0x001f}, /* 00,19,1f,aa */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x02, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,02,cc */
{0xa0, 0x76, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,76,cc */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x46, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,46,cc */
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */
{0xa0, 0x0c, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,0c,cc */
{0xa0, 0x28, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,28,cc */
{0xa0, 0x05, ZC3XX_R01D_HSYNC_0}, /* 00,1d,05,cc */
{0xa0, 0x1a, ZC3XX_R01E_HSYNC_1}, /* 00,1e,1a,cc */
{0xa0, 0x2f, ZC3XX_R01F_HSYNC_2}, /* 00,1f,2f,cc */
{}
};
static const struct usb_action hdcs2020_60HZ[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xaa, 0x13, 0x0031}, /* 00,13,31,aa */
{0xaa, 0x14, 0x0001}, /* 00,14,01,aa */
{0xaa, 0x0e, 0x0004}, /* 00,0e,04,aa */
{0xaa, 0x19, 0x00cd}, /* 00,19,cd,aa */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x02, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,02,cc */
{0xa0, 0x62, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,62,cc */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x3d, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,3d,cc */
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */
{0xa0, 0x0c, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,0c,cc */
{0xa0, 0x28, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,28,cc */
{0xa0, 0x04, ZC3XX_R01D_HSYNC_0}, /* 00,1d,04,cc */
{0xa0, 0x18, ZC3XX_R01E_HSYNC_1}, /* 00,1e,18,cc */
{0xa0, 0x2c, ZC3XX_R01F_HSYNC_2}, /* 00,1f,2c,cc */
{}
};
static const struct usb_action hdcs2020_NoFliker[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xaa, 0x13, 0x0010}, /* 00,13,10,aa */
{0xaa, 0x14, 0x0001}, /* 00,14,01,aa */
{0xaa, 0x0e, 0x0004}, /* 00,0e,04,aa */
{0xaa, 0x19, 0x0000}, /* 00,19,00,aa */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x02, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,02,cc */
{0xa0, 0x70, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,70,cc */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x10, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,10,cc */
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */
{0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,00,cc */
{0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,00,cc */
{0xa0, 0x04, ZC3XX_R01D_HSYNC_0}, /* 00,1d,04,cc */
{0xa0, 0x17, ZC3XX_R01E_HSYNC_1}, /* 00,1e,17,cc */
{0xa0, 0x2a, ZC3XX_R01F_HSYNC_2}, /* 00,1f,2a,cc */
{}
};
static const struct usb_action hv7131b_InitialScale[] = { /* 320x240 */
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL},
{0xa0, 0x10, ZC3XX_R002_CLOCKSELECT},
{0xa0, 0x00, ZC3XX_R010_CMOSSENSORSELECT},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x77, ZC3XX_R101_SENSORCORRECTION},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00 */
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW},
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW},
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW},
{0xaa, 0x30, 0x002d},
{0xaa, 0x01, 0x0005},
{0xaa, 0x11, 0x0000},
{0xaa, 0x13, 0x0001}, /* {0xaa, 0x13, 0x0000}, */
{0xaa, 0x14, 0x0001},
{0xaa, 0x15, 0x00e8},
{0xaa, 0x16, 0x0002},
{0xaa, 0x17, 0x0086}, /* 00,17,88,aa */
{0xaa, 0x31, 0x0038},
{0xaa, 0x32, 0x0038},
{0xaa, 0x33, 0x0038},
{0xaa, 0x5b, 0x0001},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
{0xa0, 0x68, ZC3XX_R18D_YTARGET},
{0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN},
{0xa0, 0x00, 0x01ad},
{0xa0, 0xc0, 0x019b},
{0xa0, 0xa0, 0x019c},
{0xa0, 0x02, ZC3XX_R188_MINGAIN},
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
{0xaa, 0x02, 0x0090}, /* 00,02,80,aa */
{}
};
static const struct usb_action hv7131b_Initial[] = { /* 640x480*/
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL},
{0xa0, 0x00, ZC3XX_R002_CLOCKSELECT},
{0xa0, 0x00, ZC3XX_R010_CMOSSENSORSELECT},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00 */
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW},
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW},
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW},
{0xaa, 0x30, 0x002d},
{0xaa, 0x01, 0x0005},
{0xaa, 0x11, 0x0001},
{0xaa, 0x13, 0x0000}, /* {0xaa, 0x13, 0x0001}; */
{0xaa, 0x14, 0x0001},
{0xaa, 0x15, 0x00e6},
{0xaa, 0x16, 0x0002},
{0xaa, 0x17, 0x0086},
{0xaa, 0x31, 0x0038},
{0xaa, 0x32, 0x0038},
{0xaa, 0x33, 0x0038},
{0xaa, 0x5b, 0x0001},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
{0xa0, 0x70, ZC3XX_R18D_YTARGET},
{0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN},
{0xa0, 0x00, 0x01ad},
{0xa0, 0xc0, 0x019b},
{0xa0, 0xa0, 0x019c},
{0xa0, 0x02, ZC3XX_R188_MINGAIN},
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
{0xaa, 0x02, 0x0090}, /* {0xaa, 0x02, 0x0080}, */
{}
};
static const struct usb_action hv7131b_50HZ[] = { /* 640x480*/
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xaa, 0x25, 0x0007}, /* 00,25,07,aa */
{0xaa, 0x26, 0x0053}, /* 00,26,53,aa */
{0xaa, 0x27, 0x0000}, /* 00,27,00,aa */
{0xaa, 0x20, 0x0000}, /* 00,20,00,aa */
{0xaa, 0x21, 0x0050}, /* 00,21,50,aa */
{0xaa, 0x22, 0x001b}, /* 00,22,1b,aa */
{0xaa, 0x23, 0x00fc}, /* 00,23,fc,aa */
{0xa0, 0x2f, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,2f,cc */
{0xa0, 0x9b, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,9b,cc */
{0xa0, 0x80, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,80,cc */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0xea, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,ea,cc */
{0xa0, 0x60, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,60,cc */
{0xa0, 0x0c, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0c,cc */
{0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,18,cc */
{0xa0, 0x18, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,18,cc */
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc */
{0xa0, 0x00, ZC3XX_R01D_HSYNC_0}, /* 00,1d,00,cc */
{0xa0, 0x50, ZC3XX_R01E_HSYNC_1}, /* 00,1e,50,cc */
{0xa0, 0x1b, ZC3XX_R01F_HSYNC_2}, /* 00,1f,1b,cc */
{0xa0, 0xfc, ZC3XX_R020_HSYNC_3}, /* 00,20,fc,cc */
{}
};
static const struct usb_action hv7131b_50HZScale[] = { /* 320x240 */
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xaa, 0x25, 0x0007}, /* 00,25,07,aa */
{0xaa, 0x26, 0x0053}, /* 00,26,53,aa */
{0xaa, 0x27, 0x0000}, /* 00,27,00,aa */
{0xaa, 0x20, 0x0000}, /* 00,20,00,aa */
{0xaa, 0x21, 0x0050}, /* 00,21,50,aa */
{0xaa, 0x22, 0x0012}, /* 00,22,12,aa */
{0xaa, 0x23, 0x0080}, /* 00,23,80,aa */
{0xa0, 0x2f, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,2f,cc */
{0xa0, 0x9b, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,9b,cc */
{0xa0, 0x80, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,80,cc */
{0xa0, 0x01, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,01,cc */
{0xa0, 0xd4, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,d4,cc */
{0xa0, 0xc0, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,c0,cc */
{0xa0, 0x07, ZC3XX_R18C_AEFREEZE}, /* 01,8c,07,cc */
{0xa0, 0x0f, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,0f,cc */
{0xa0, 0x18, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,18,cc */
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc */
{0xa0, 0x00, ZC3XX_R01D_HSYNC_0}, /* 00,1d,00,cc */
{0xa0, 0x50, ZC3XX_R01E_HSYNC_1}, /* 00,1e,50,cc */
{0xa0, 0x12, ZC3XX_R01F_HSYNC_2}, /* 00,1f,12,cc */
{0xa0, 0x80, ZC3XX_R020_HSYNC_3}, /* 00,20,80,cc */
{}
};
static const struct usb_action hv7131b_60HZ[] = { /* 640x480*/
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xaa, 0x25, 0x0007}, /* 00,25,07,aa */
{0xaa, 0x26, 0x00a1}, /* 00,26,a1,aa */
{0xaa, 0x27, 0x0020}, /* 00,27,20,aa */
{0xaa, 0x20, 0x0000}, /* 00,20,00,aa */
{0xaa, 0x21, 0x0040}, /* 00,21,40,aa */
{0xaa, 0x22, 0x0013}, /* 00,22,13,aa */
{0xaa, 0x23, 0x004c}, /* 00,23,4c,aa */
{0xa0, 0x2f, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,2f,cc */
{0xa0, 0x4d, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,4d,cc */
{0xa0, 0x60, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,60,cc */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0xc3, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,c3,cc */
{0xa0, 0x50, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,50,cc */
{0xa0, 0x0c, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0c,cc */
{0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,18,cc */
{0xa0, 0x18, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,18,cc */
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc */
{0xa0, 0x00, ZC3XX_R01D_HSYNC_0}, /* 00,1d,00,cc */
{0xa0, 0x40, ZC3XX_R01E_HSYNC_1}, /* 00,1e,40,cc */
{0xa0, 0x13, ZC3XX_R01F_HSYNC_2}, /* 00,1f,13,cc */
{0xa0, 0x4c, ZC3XX_R020_HSYNC_3}, /* 00,20,4c,cc */
{}
};
static const struct usb_action hv7131b_60HZScale[] = { /* 320x240 */
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xaa, 0x25, 0x0007}, /* 00,25,07,aa */
{0xaa, 0x26, 0x00a1}, /* 00,26,a1,aa */
{0xaa, 0x27, 0x0020}, /* 00,27,20,aa */
{0xaa, 0x20, 0x0000}, /* 00,20,00,aa */
{0xaa, 0x21, 0x00a0}, /* 00,21,a0,aa */
{0xaa, 0x22, 0x0016}, /* 00,22,16,aa */
{0xaa, 0x23, 0x0040}, /* 00,23,40,aa */
{0xa0, 0x2f, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,2f,cc */
{0xa0, 0x4d, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,4d,cc */
{0xa0, 0x60, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,60,cc */
{0xa0, 0x01, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,01,cc */
{0xa0, 0x86, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,86,cc */
{0xa0, 0xa0, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,a0,cc */
{0xa0, 0x07, ZC3XX_R18C_AEFREEZE}, /* 01,8c,07,cc */
{0xa0, 0x0f, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,0f,cc */
{0xa0, 0x18, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,18,cc */
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc */
{0xa0, 0x00, ZC3XX_R01D_HSYNC_0}, /* 00,1d,00,cc */
{0xa0, 0xa0, ZC3XX_R01E_HSYNC_1}, /* 00,1e,a0,cc */
{0xa0, 0x16, ZC3XX_R01F_HSYNC_2}, /* 00,1f,16,cc */
{0xa0, 0x40, ZC3XX_R020_HSYNC_3}, /* 00,20,40,cc */
{}
};
static const struct usb_action hv7131b_NoFliker[] = { /* 640x480*/
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xaa, 0x25, 0x0003}, /* 00,25,03,aa */
{0xaa, 0x26, 0x0000}, /* 00,26,00,aa */
{0xaa, 0x27, 0x0000}, /* 00,27,00,aa */
{0xaa, 0x20, 0x0000}, /* 00,20,00,aa */
{0xaa, 0x21, 0x0010}, /* 00,21,10,aa */
{0xaa, 0x22, 0x0000}, /* 00,22,00,aa */
{0xaa, 0x23, 0x0003}, /* 00,23,03,aa */
{0xa0, 0x2f, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,2f,cc */
{0xa0, 0xf8, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,f8,cc */
{0xa0, 0x00, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,00,cc */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x02, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,02,cc */
{0xa0, 0x00, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,00,cc */
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */
{0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,00,cc */
{0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,00,cc */
{0xa0, 0x00, ZC3XX_R01D_HSYNC_0}, /* 00,1d,00,cc */
{0xa0, 0x10, ZC3XX_R01E_HSYNC_1}, /* 00,1e,10,cc */
{0xa0, 0x00, ZC3XX_R01F_HSYNC_2}, /* 00,1f,00,cc */
{0xa0, 0x03, ZC3XX_R020_HSYNC_3}, /* 00,20,03,cc */
{}
};
static const struct usb_action hv7131b_NoFlikerScale[] = { /* 320x240 */
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xaa, 0x25, 0x0003}, /* 00,25,03,aa */
{0xaa, 0x26, 0x0000}, /* 00,26,00,aa */
{0xaa, 0x27, 0x0000}, /* 00,27,00,aa */
{0xaa, 0x20, 0x0000}, /* 00,20,00,aa */
{0xaa, 0x21, 0x00a0}, /* 00,21,a0,aa */
{0xaa, 0x22, 0x0016}, /* 00,22,16,aa */
{0xaa, 0x23, 0x0040}, /* 00,23,40,aa */
{0xa0, 0x2f, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,2f,cc */
{0xa0, 0xf8, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,f8,cc */
{0xa0, 0x00, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,00,cc */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x02, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,02,cc */
{0xa0, 0x00, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,00,cc */
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */
{0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,00,cc */
{0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,00,cc */
{0xa0, 0x00, ZC3XX_R01D_HSYNC_0}, /* 00,1d,00,cc */
{0xa0, 0xa0, ZC3XX_R01E_HSYNC_1}, /* 00,1e,a0,cc */
{0xa0, 0x16, ZC3XX_R01F_HSYNC_2}, /* 00,1f,16,cc */
{0xa0, 0x40, ZC3XX_R020_HSYNC_3}, /* 00,20,40,cc */
{}
};
/* from lPEPI264v.inf (hv7131b!) */
static const struct usb_action hv7131r_InitialScale[] = {
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL},
{0xa0, 0x10, ZC3XX_R002_CLOCKSELECT},
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x77, ZC3XX_R101_SENSORCORRECTION},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING},
{0xa0, 0x07, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW},
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW},
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x01, ZC3XX_R09B_WINHEIGHTHIGH},
{0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW},
{0xa0, 0x02, ZC3XX_R09D_WINWIDTHHIGH},
{0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW},
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW},
{0xa0, 0x07, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xdd, 0x00, 0x0200},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xaa, 0x01, 0x000c},
{0xaa, 0x11, 0x0000},
{0xaa, 0x13, 0x0000},
{0xaa, 0x14, 0x0001},
{0xaa, 0x15, 0x00e8},
{0xaa, 0x16, 0x0002},
{0xaa, 0x17, 0x0088},
{0xaa, 0x30, 0x000b},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
{0xa0, 0x78, ZC3XX_R18D_YTARGET},
{0xa0, 0x50, ZC3XX_R1A8_DIGITALGAIN},
{0xa0, 0x00, 0x01ad},
{0xa0, 0xc0, 0x019b},
{0xa0, 0xa0, 0x019c},
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
{}
};
static const struct usb_action hv7131r_Initial[] = {
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL},
{0xa0, 0x00, ZC3XX_R002_CLOCKSELECT},
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x77, ZC3XX_R101_SENSORCORRECTION},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING},
{0xa0, 0x07, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW},
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW},
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x01, ZC3XX_R09B_WINHEIGHTHIGH},
{0xa0, 0xe6, ZC3XX_R09C_WINHEIGHTLOW},
{0xa0, 0x02, ZC3XX_R09D_WINWIDTHHIGH},
{0xa0, 0x86, ZC3XX_R09E_WINWIDTHLOW},
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW},
{0xa0, 0x07, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xdd, 0x00, 0x0200},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xaa, 0x01, 0x000c},
{0xaa, 0x11, 0x0000},
{0xaa, 0x13, 0x0000},
{0xaa, 0x14, 0x0001},
{0xaa, 0x15, 0x00e6},
{0xaa, 0x16, 0x0002},
{0xaa, 0x17, 0x0086},
{0xaa, 0x30, 0x000b},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
{0xa0, 0x78, ZC3XX_R18D_YTARGET},
{0xa0, 0x50, ZC3XX_R1A8_DIGITALGAIN},
{0xa0, 0x00, 0x01ad},
{0xa0, 0xc0, 0x019b},
{0xa0, 0xa0, 0x019c},
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
{}
};
static const struct usb_action hv7131r_50HZ[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xa0, 0x06, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x68, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xa0, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0xea, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x60, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x18, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x66, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x00, ZC3XX_R01D_HSYNC_0},
{0xa0, 0xd0, ZC3XX_R01E_HSYNC_1},
{0xa0, 0x00, ZC3XX_R01F_HSYNC_2},
{0xa0, 0x08, ZC3XX_R020_HSYNC_3},
{}
};
static const struct usb_action hv7131r_50HZScale[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xa0, 0x0c, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0xd1, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x40, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x01, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0xd4, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0xc0, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x18, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x66, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x00, ZC3XX_R01D_HSYNC_0},
{0xa0, 0xd0, ZC3XX_R01E_HSYNC_1},
{0xa0, 0x00, ZC3XX_R01F_HSYNC_2},
{0xa0, 0x08, ZC3XX_R020_HSYNC_3},
{}
};
static const struct usb_action hv7131r_60HZ[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xa0, 0x06, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x1a, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x80, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0xc3, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x50, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x18, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x66, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x00, ZC3XX_R01D_HSYNC_0},
{0xa0, 0xd0, ZC3XX_R01E_HSYNC_1},
{0xa0, 0x00, ZC3XX_R01F_HSYNC_2},
{0xa0, 0x08, ZC3XX_R020_HSYNC_3},
{}
};
static const struct usb_action hv7131r_60HZScale[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xa0, 0x0c, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x35, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x00, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x01, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x86, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0xa0, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x18, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x66, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x00, ZC3XX_R01D_HSYNC_0},
{0xa0, 0xd0, ZC3XX_R01E_HSYNC_1},
{0xa0, 0x00, ZC3XX_R01F_HSYNC_2},
{0xa0, 0x08, ZC3XX_R020_HSYNC_3},
{}
};
static const struct usb_action hv7131r_NoFliker[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xa0, 0x2f, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0xf8, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x00, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x02, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x58, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x0c, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x00, ZC3XX_R01D_HSYNC_0},
{0xa0, 0xd0, ZC3XX_R01E_HSYNC_1},
{0xa0, 0x00, ZC3XX_R01F_HSYNC_2},
{0xa0, 0x08, ZC3XX_R020_HSYNC_3},
{}
};
static const struct usb_action hv7131r_NoFlikerScale[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xa0, 0x2f, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0xf8, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x00, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x04, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0xb0, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x0c, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x00, ZC3XX_R01D_HSYNC_0},
{0xa0, 0xd0, ZC3XX_R01E_HSYNC_1},
{0xa0, 0x00, ZC3XX_R01F_HSYNC_2},
{0xa0, 0x08, ZC3XX_R020_HSYNC_3},
{}
};
static const struct usb_action icm105a_InitialScale[] = {
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL},
{0xa0, 0x10, ZC3XX_R002_CLOCKSELECT},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING},
{0xa0, 0x0c, ZC3XX_R010_CMOSSENSORSELECT},
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0xa1, ZC3XX_R08B_I2CDEVICEADDR},
{0xa0, 0x00, ZC3XX_R097_WINYSTARTHIGH},
{0xa0, 0x01, ZC3XX_R098_WINYSTARTLOW},
{0xa0, 0x00, ZC3XX_R099_WINXSTARTHIGH},
{0xa0, 0x01, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x01, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x01, ZC3XX_R11C_FIRSTXLOW},
{0xa0, 0x01, ZC3XX_R09B_WINHEIGHTHIGH},
{0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW},
{0xa0, 0x02, ZC3XX_R09D_WINWIDTHHIGH},
{0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW},
{0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION},
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
{0xaa, 0x01, 0x0010},
{0xaa, 0x03, 0x0000},
{0xaa, 0x04, 0x0001},
{0xaa, 0x05, 0x0020},
{0xaa, 0x06, 0x0001},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x0001},
{0xaa, 0x04, 0x0011},
{0xaa, 0x05, 0x00a0},
{0xaa, 0x06, 0x0001},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x0002},
{0xaa, 0x04, 0x0013},
{0xaa, 0x05, 0x0020},
{0xaa, 0x06, 0x0001},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x0003},
{0xaa, 0x04, 0x0015},
{0xaa, 0x05, 0x0020},
{0xaa, 0x06, 0x0005},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x0004},
{0xaa, 0x04, 0x0017},
{0xaa, 0x05, 0x0020},
{0xaa, 0x06, 0x000d},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x0005},
{0xaa, 0x04, 0x0019},
{0xaa, 0x05, 0x0020},
{0xaa, 0x06, 0x0005},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x0006},
{0xaa, 0x04, 0x0017},
{0xaa, 0x05, 0x0026},
{0xaa, 0x06, 0x0005},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x0007},
{0xaa, 0x04, 0x0019},
{0xaa, 0x05, 0x0022},
{0xaa, 0x06, 0x0005},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x0008},
{0xaa, 0x04, 0x0021},
{0xaa, 0x05, 0x00aa},
{0xaa, 0x06, 0x0005},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x0009},
{0xaa, 0x04, 0x0023},
{0xaa, 0x05, 0x00aa},
{0xaa, 0x06, 0x000d},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x000a},
{0xaa, 0x04, 0x0025},
{0xaa, 0x05, 0x00aa},
{0xaa, 0x06, 0x0005},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x000b},
{0xaa, 0x04, 0x00ec},
{0xaa, 0x05, 0x002e},
{0xaa, 0x06, 0x0005},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x000c},
{0xaa, 0x04, 0x00fa},
{0xaa, 0x05, 0x002a},
{0xaa, 0x06, 0x0005},
{0xaa, 0x08, 0x0000},
{0xaa, 0x07, 0x000d},
{0xaa, 0x01, 0x0005},
{0xaa, 0x94, 0x0002},
{0xaa, 0x90, 0x0000},
{0xaa, 0x91, 0x001f},
{0xaa, 0x10, 0x0064},
{0xaa, 0x9b, 0x00f0},
{0xaa, 0x9c, 0x0002},
{0xaa, 0x14, 0x001a},
{0xaa, 0x20, 0x0080},
{0xaa, 0x22, 0x0080},
{0xaa, 0x24, 0x0080},
{0xaa, 0x26, 0x0080},
{0xaa, 0x00, 0x0084},
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
{0xaa, 0xa8, 0x00c0},
{0xa1, 0x01, 0x0002},
{0xa1, 0x01, 0x0008},
{0xa1, 0x01, 0x0180},
{0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x40, ZC3XX_R116_RGAIN},
{0xa0, 0x40, ZC3XX_R117_GGAIN},
{0xa0, 0x40, ZC3XX_R118_BGAIN},
{0xa1, 0x01, 0x0008},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* clock ? */
{0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00}, /* sharpness+ */
{0xa1, 0x01, 0x01c8},
{0xa1, 0x01, 0x01c9},
{0xa1, 0x01, 0x01ca},
{0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05}, /* sharpness- */
{0xa0, 0x52, ZC3XX_R10A_RGB00}, /* matrix */
{0xa0, 0xf7, ZC3XX_R10B_RGB01},
{0xa0, 0xf7, ZC3XX_R10C_RGB02},
{0xa0, 0xf7, ZC3XX_R10D_RGB10},
{0xa0, 0x52, ZC3XX_R10E_RGB11},
{0xa0, 0xf7, ZC3XX_R10F_RGB12},
{0xa0, 0xf7, ZC3XX_R110_RGB20},
{0xa0, 0xf7, ZC3XX_R111_RGB21},
{0xa0, 0x52, ZC3XX_R112_RGB22},
{0xa1, 0x01, 0x0180},
{0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xaa, 0x0d, 0x0003},
{0xaa, 0x0c, 0x008c},
{0xaa, 0x0e, 0x0095},
{0xaa, 0x0f, 0x0002},
{0xaa, 0x1c, 0x0094},
{0xaa, 0x1d, 0x0002},
{0xaa, 0x20, 0x0080},
{0xaa, 0x22, 0x0080},
{0xaa, 0x24, 0x0080},
{0xaa, 0x26, 0x0080},
{0xaa, 0x00, 0x0084},
{0xa0, 0x02, ZC3XX_R0A3_EXPOSURETIMEHIGH},
{0xa0, 0x94, ZC3XX_R0A4_EXPOSURETIMELOW},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x20, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x84, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x12, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0xe3, ZC3XX_R01D_HSYNC_0},
{0xa0, 0xec, ZC3XX_R01E_HSYNC_1},
{0xa0, 0xf5, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xff, ZC3XX_R020_HSYNC_3},
{0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0xc0, ZC3XX_R1A8_DIGITALGAIN},
{0xa0, 0xc0, ZC3XX_R11D_GLOBALGAIN},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa1, 0x01, 0x0180},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x40, ZC3XX_R116_RGAIN},
{0xa0, 0x40, ZC3XX_R117_GGAIN},
{0xa0, 0x40, ZC3XX_R118_BGAIN},
{}
};
static const struct usb_action icm105a_Initial[] = {
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL},
{0xa0, 0x00, ZC3XX_R002_CLOCKSELECT},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING},
{0xa0, 0x0c, ZC3XX_R010_CMOSSENSORSELECT},
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0xa1, ZC3XX_R08B_I2CDEVICEADDR},
{0xa0, 0x00, ZC3XX_R097_WINYSTARTHIGH},
{0xa0, 0x02, ZC3XX_R098_WINYSTARTLOW},
{0xa0, 0x00, ZC3XX_R099_WINXSTARTHIGH},
{0xa0, 0x02, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x02, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x02, ZC3XX_R11C_FIRSTXLOW},
{0xa0, 0x01, ZC3XX_R09B_WINHEIGHTHIGH},
{0xa0, 0xe6, ZC3XX_R09C_WINHEIGHTLOW},
{0xa0, 0x02, ZC3XX_R09D_WINWIDTHHIGH},
{0xa0, 0x86, ZC3XX_R09E_WINWIDTHLOW},
{0xa0, 0x77, ZC3XX_R101_SENSORCORRECTION},
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
{0xaa, 0x01, 0x0010},
{0xaa, 0x03, 0x0000},
{0xaa, 0x04, 0x0001},
{0xaa, 0x05, 0x0020},
{0xaa, 0x06, 0x0001},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x0001},
{0xaa, 0x04, 0x0011},
{0xaa, 0x05, 0x00a0},
{0xaa, 0x06, 0x0001},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x0002},
{0xaa, 0x04, 0x0013},
{0xaa, 0x05, 0x0020},
{0xaa, 0x06, 0x0001},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x0003},
{0xaa, 0x04, 0x0015},
{0xaa, 0x05, 0x0020},
{0xaa, 0x06, 0x0005},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x0004},
{0xaa, 0x04, 0x0017},
{0xaa, 0x05, 0x0020},
{0xaa, 0x06, 0x000d},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x0005},
{0xa0, 0x04, ZC3XX_R092_I2CADDRESSSELECT},
{0xa0, 0x19, ZC3XX_R093_I2CSETVALUE},
{0xa0, 0x01, ZC3XX_R090_I2CCOMMAND},
{0xa1, 0x01, 0x0091},
{0xaa, 0x05, 0x0020},
{0xaa, 0x06, 0x0005},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x0006},
{0xaa, 0x04, 0x0017},
{0xaa, 0x05, 0x0026},
{0xaa, 0x06, 0x0005},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x0007},
{0xaa, 0x04, 0x0019},
{0xaa, 0x05, 0x0022},
{0xaa, 0x06, 0x0005},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x0008},
{0xaa, 0x04, 0x0021},
{0xaa, 0x05, 0x00aa},
{0xaa, 0x06, 0x0005},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x0009},
{0xaa, 0x04, 0x0023},
{0xaa, 0x05, 0x00aa},
{0xaa, 0x06, 0x000d},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x000a},
{0xaa, 0x04, 0x0025},
{0xaa, 0x05, 0x00aa},
{0xaa, 0x06, 0x0005},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x000b},
{0xaa, 0x04, 0x00ec},
{0xaa, 0x05, 0x002e},
{0xaa, 0x06, 0x0005},
{0xaa, 0x08, 0x0000},
{0xaa, 0x03, 0x000c},
{0xaa, 0x04, 0x00fa},
{0xaa, 0x05, 0x002a},
{0xaa, 0x06, 0x0005},
{0xaa, 0x08, 0x0000},
{0xaa, 0x07, 0x000d},
{0xaa, 0x01, 0x0005},
{0xaa, 0x94, 0x0002},
{0xaa, 0x90, 0x0000},
{0xaa, 0x91, 0x0010},
{0xaa, 0x10, 0x0064},
{0xaa, 0x9b, 0x00f0},
{0xaa, 0x9c, 0x0002},
{0xaa, 0x14, 0x001a},
{0xaa, 0x20, 0x0080},
{0xaa, 0x22, 0x0080},
{0xaa, 0x24, 0x0080},
{0xaa, 0x26, 0x0080},
{0xaa, 0x00, 0x0084},
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
{0xaa, 0xa8, 0x0080},
{0xa0, 0x78, ZC3XX_R18D_YTARGET},
{0xa1, 0x01, 0x0002},
{0xa1, 0x01, 0x0008},
{0xa1, 0x01, 0x0180},
{0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x40, ZC3XX_R116_RGAIN},
{0xa0, 0x40, ZC3XX_R117_GGAIN},
{0xa0, 0x40, ZC3XX_R118_BGAIN},
{0xa1, 0x01, 0x0008},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* clock ? */
{0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00}, /* sharpness+ */
{0xa1, 0x01, 0x01c8},
{0xa1, 0x01, 0x01c9},
{0xa1, 0x01, 0x01ca},
{0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05}, /* sharpness- */
{0xa0, 0x52, ZC3XX_R10A_RGB00}, /* matrix */
{0xa0, 0xf7, ZC3XX_R10B_RGB01},
{0xa0, 0xf7, ZC3XX_R10C_RGB02},
{0xa0, 0xf7, ZC3XX_R10D_RGB10},
{0xa0, 0x52, ZC3XX_R10E_RGB11},
{0xa0, 0xf7, ZC3XX_R10F_RGB12},
{0xa0, 0xf7, ZC3XX_R110_RGB20},
{0xa0, 0xf7, ZC3XX_R111_RGB21},
{0xa0, 0x52, ZC3XX_R112_RGB22},
{0xa1, 0x01, 0x0180},
{0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xaa, 0x0d, 0x0003},
{0xaa, 0x0c, 0x0020},
{0xaa, 0x0e, 0x000e},
{0xaa, 0x0f, 0x0002},
{0xaa, 0x1c, 0x000d},
{0xaa, 0x1d, 0x0002},
{0xaa, 0x20, 0x0080},
{0xaa, 0x22, 0x0080},
{0xaa, 0x24, 0x0080},
{0xaa, 0x26, 0x0080},
{0xaa, 0x00, 0x0084},
{0xa0, 0x02, ZC3XX_R0A3_EXPOSURETIMEHIGH},
{0xa0, 0x0d, ZC3XX_R0A4_EXPOSURETIMELOW},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x1a, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x4b, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x12, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0xc8, ZC3XX_R01D_HSYNC_0},
{0xa0, 0xd8, ZC3XX_R01E_HSYNC_1},
{0xa0, 0xea, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xff, ZC3XX_R020_HSYNC_3},
{0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa1, 0x01, 0x0180},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x40, ZC3XX_R116_RGAIN},
{0xa0, 0x40, ZC3XX_R117_GGAIN},
{0xa0, 0x40, ZC3XX_R118_BGAIN},
{}
};
static const struct usb_action icm105a_50HZScale[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xaa, 0x0d, 0x0003}, /* 00,0d,03,aa */
{0xaa, 0x0c, 0x0020}, /* 00,0c,20,aa */
{0xaa, 0x0e, 0x000e}, /* 00,0e,0e,aa */
{0xaa, 0x0f, 0x0002}, /* 00,0f,02,aa */
{0xaa, 0x1c, 0x000d}, /* 00,1c,0d,aa */
{0xaa, 0x1d, 0x0002}, /* 00,1d,02,aa */
{0xaa, 0x20, 0x0080}, /* 00,20,80,aa */
{0xaa, 0x22, 0x0080}, /* 00,22,80,aa */
{0xaa, 0x24, 0x0080}, /* 00,24,80,aa */
{0xaa, 0x26, 0x0080}, /* 00,26,80,aa */
{0xaa, 0x00, 0x0084}, /* 00,00,84,aa */
{0xa0, 0x02, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,02,cc */
{0xa0, 0x0d, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,0d,cc */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,04,cc */
{0xa0, 0x1a, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,1a,cc */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x4b, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,4b,cc */
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,10,cc */
{0xa0, 0x12, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,12,cc */
{0xa0, 0xc8, ZC3XX_R01D_HSYNC_0}, /* 00,1d,c8,cc */
{0xa0, 0xd8, ZC3XX_R01E_HSYNC_1}, /* 00,1e,d8,cc */
{0xa0, 0xea, ZC3XX_R01F_HSYNC_2}, /* 00,1f,ea,cc */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */
{}
};
static const struct usb_action icm105a_50HZ[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xaa, 0x0d, 0x0003}, /* 00,0d,03,aa */
{0xaa, 0x0c, 0x008c}, /* 00,0c,8c,aa */
{0xaa, 0x0e, 0x0095}, /* 00,0e,95,aa */
{0xaa, 0x0f, 0x0002}, /* 00,0f,02,aa */
{0xaa, 0x1c, 0x0094}, /* 00,1c,94,aa */
{0xaa, 0x1d, 0x0002}, /* 00,1d,02,aa */
{0xaa, 0x20, 0x0080}, /* 00,20,80,aa */
{0xaa, 0x22, 0x0080}, /* 00,22,80,aa */
{0xaa, 0x24, 0x0080}, /* 00,24,80,aa */
{0xaa, 0x26, 0x0080}, /* 00,26,80,aa */
{0xaa, 0x00, 0x0084}, /* 00,00,84,aa */
{0xa0, 0x02, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,02,cc */
{0xa0, 0x94, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,94,cc */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,04,cc */
{0xa0, 0x20, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,20,cc */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x84, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,84,cc */
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,10,cc */
{0xa0, 0x12, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,12,cc */
{0xa0, 0xe3, ZC3XX_R01D_HSYNC_0}, /* 00,1d,e3,cc */
{0xa0, 0xec, ZC3XX_R01E_HSYNC_1}, /* 00,1e,ec,cc */
{0xa0, 0xf5, ZC3XX_R01F_HSYNC_2}, /* 00,1f,f5,cc */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */
{0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, /* 01,a7,00,cc */
{0xa0, 0xc0, ZC3XX_R1A8_DIGITALGAIN}, /* 01,a8,c0,cc */
{}
};
static const struct usb_action icm105a_60HZScale[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xaa, 0x0d, 0x0003}, /* 00,0d,03,aa */
{0xaa, 0x0c, 0x0004}, /* 00,0c,04,aa */
{0xaa, 0x0e, 0x000d}, /* 00,0e,0d,aa */
{0xaa, 0x0f, 0x0002}, /* 00,0f,02,aa */
{0xaa, 0x1c, 0x0008}, /* 00,1c,08,aa */
{0xaa, 0x1d, 0x0002}, /* 00,1d,02,aa */
{0xaa, 0x20, 0x0080}, /* 00,20,80,aa */
{0xaa, 0x22, 0x0080}, /* 00,22,80,aa */
{0xaa, 0x24, 0x0080}, /* 00,24,80,aa */
{0xaa, 0x26, 0x0080}, /* 00,26,80,aa */
{0xaa, 0x00, 0x0084}, /* 00,00,84,aa */
{0xa0, 0x02, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,02,cc */
{0xa0, 0x08, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,08,cc */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,04,cc */
{0xa0, 0x10, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,10,cc */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x41, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,41,cc */
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,10,cc */
{0xa0, 0x12, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,12,cc */
{0xa0, 0xc1, ZC3XX_R01D_HSYNC_0}, /* 00,1d,c1,cc */
{0xa0, 0xd4, ZC3XX_R01E_HSYNC_1}, /* 00,1e,d4,cc */
{0xa0, 0xe8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,e8,cc */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */
{}
};
static const struct usb_action icm105a_60HZ[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xaa, 0x0d, 0x0003}, /* 00,0d,03,aa */
{0xaa, 0x0c, 0x0008}, /* 00,0c,08,aa */
{0xaa, 0x0e, 0x0086}, /* 00,0e,86,aa */
{0xaa, 0x0f, 0x0002}, /* 00,0f,02,aa */
{0xaa, 0x1c, 0x0085}, /* 00,1c,85,aa */
{0xaa, 0x1d, 0x0002}, /* 00,1d,02,aa */
{0xaa, 0x20, 0x0080}, /* 00,20,80,aa */
{0xaa, 0x22, 0x0080}, /* 00,22,80,aa */
{0xaa, 0x24, 0x0080}, /* 00,24,80,aa */
{0xaa, 0x26, 0x0080}, /* 00,26,80,aa */
{0xaa, 0x00, 0x0084}, /* 00,00,84,aa */
{0xa0, 0x02, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,02,cc */
{0xa0, 0x85, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,85,cc */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,04,cc */
{0xa0, 0x08, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,08,cc */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x81, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,81,cc */
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,10,cc */
{0xa0, 0x12, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,12,cc */
{0xa0, 0xc2, ZC3XX_R01D_HSYNC_0}, /* 00,1d,c2,cc */
{0xa0, 0xd6, ZC3XX_R01E_HSYNC_1}, /* 00,1e,d6,cc */
{0xa0, 0xea, ZC3XX_R01F_HSYNC_2}, /* 00,1f,ea,cc */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */
{0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, /* 01,a7,00,cc */
{0xa0, 0xc0, ZC3XX_R1A8_DIGITALGAIN}, /* 01,a8,c0,cc */
{}
};
static const struct usb_action icm105a_NoFlikerScale[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xaa, 0x0d, 0x0003}, /* 00,0d,03,aa */
{0xaa, 0x0c, 0x0004}, /* 00,0c,04,aa */
{0xaa, 0x0e, 0x000d}, /* 00,0e,0d,aa */
{0xaa, 0x0f, 0x0002}, /* 00,0f,02,aa */
{0xaa, 0x1c, 0x0000}, /* 00,1c,00,aa */
{0xaa, 0x1d, 0x0002}, /* 00,1d,02,aa */
{0xaa, 0x20, 0x0080}, /* 00,20,80,aa */
{0xaa, 0x22, 0x0080}, /* 00,22,80,aa */
{0xaa, 0x24, 0x0080}, /* 00,24,80,aa */
{0xaa, 0x26, 0x0080}, /* 00,26,80,aa */
{0xaa, 0x00, 0x0084}, /* 00,00,84,aa */
{0xa0, 0x02, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,02,cc */
{0xa0, 0x00, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,00,cc */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,04,cc */
{0xa0, 0x20, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,20,cc */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x10, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,10,cc */
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */
{0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,00,cc */
{0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,00,cc */
{0xa0, 0xc1, ZC3XX_R01D_HSYNC_0}, /* 00,1d,c1,cc */
{0xa0, 0xd4, ZC3XX_R01E_HSYNC_1}, /* 00,1e,d4,cc */
{0xa0, 0xe8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,e8,cc */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */
{}
};
static const struct usb_action icm105a_NoFliker[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xaa, 0x0d, 0x0003}, /* 00,0d,03,aa */
{0xaa, 0x0c, 0x0004}, /* 00,0c,04,aa */
{0xaa, 0x0e, 0x0081}, /* 00,0e,81,aa */
{0xaa, 0x0f, 0x0002}, /* 00,0f,02,aa */
{0xaa, 0x1c, 0x0080}, /* 00,1c,80,aa */
{0xaa, 0x1d, 0x0002}, /* 00,1d,02,aa */
{0xaa, 0x20, 0x0080}, /* 00,20,80,aa */
{0xaa, 0x22, 0x0080}, /* 00,22,80,aa */
{0xaa, 0x24, 0x0080}, /* 00,24,80,aa */
{0xaa, 0x26, 0x0080}, /* 00,26,80,aa */
{0xaa, 0x00, 0x0084}, /* 00,00,84,aa */
{0xa0, 0x02, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,02,cc */
{0xa0, 0x80, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,80,cc */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,04,cc */
{0xa0, 0x20, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,20,cc */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x10, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,10,cc */
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */
{0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,00,cc */
{0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,00,cc */
{0xa0, 0xc1, ZC3XX_R01D_HSYNC_0}, /* 00,1d,c1,cc */
{0xa0, 0xd4, ZC3XX_R01E_HSYNC_1}, /* 00,1e,d4,cc */
{0xa0, 0xe8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,e8,cc */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */
{0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, /* 01,a7,00,cc */
{0xa0, 0xc0, ZC3XX_R1A8_DIGITALGAIN}, /* 01,a8,c0,cc */
{}
};
static const struct usb_action mc501cb_Initial[] = {
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */
{0xa0, 0x00, ZC3XX_R002_CLOCKSELECT}, /* 00,02,00,cc */
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00,08,03,cc */
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */
{0xa0, 0xd8, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,d8,cc */
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc */
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc */
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc */
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc */
{0xa0, 0x01, ZC3XX_R09B_WINHEIGHTHIGH}, /* 00,9b,01,cc */
{0xa0, 0xde, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,de,cc */
{0xa0, 0x02, ZC3XX_R09D_WINWIDTHHIGH}, /* 00,9d,02,cc */
{0xa0, 0x86, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,86,cc */
{0xa0, 0x33, ZC3XX_R086_EXPTIMEHIGH}, /* 00,86,33,cc */
{0xa0, 0x34, ZC3XX_R087_EXPTIMEMID}, /* 00,87,34,cc */
{0xa0, 0x35, ZC3XX_R088_EXPTIMELOW}, /* 00,88,35,cc */
{0xa0, 0xb0, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,b0,cc */
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */
{0xaa, 0x01, 0x0001}, /* 00,01,01,aa */
{0xaa, 0x01, 0x0003}, /* 00,01,03,aa */
{0xaa, 0x01, 0x0001}, /* 00,01,01,aa */
{0xaa, 0x03, 0x0000}, /* 00,03,00,aa */
{0xaa, 0x10, 0x0000}, /* 00,10,00,aa */
{0xaa, 0x11, 0x0080}, /* 00,11,80,aa */
{0xaa, 0x12, 0x0000}, /* 00,12,00,aa */
{0xaa, 0x13, 0x0000}, /* 00,13,00,aa */
{0xaa, 0x14, 0x0000}, /* 00,14,00,aa */
{0xaa, 0x15, 0x0000}, /* 00,15,00,aa */
{0xaa, 0x16, 0x0000}, /* 00,16,00,aa */
{0xaa, 0x17, 0x0001}, /* 00,17,01,aa */
{0xaa, 0x18, 0x00de}, /* 00,18,de,aa */
{0xaa, 0x19, 0x0002}, /* 00,19,02,aa */
{0xaa, 0x1a, 0x0086}, /* 00,1a,86,aa */
{0xaa, 0x20, 0x00a8}, /* 00,20,a8,aa */
{0xaa, 0x22, 0x0000}, /* 00,22,00,aa */
{0xaa, 0x23, 0x0000}, /* 00,23,00,aa */
{0xaa, 0x24, 0x0000}, /* 00,24,00,aa */
{0xaa, 0x40, 0x0033}, /* 00,40,33,aa */
{0xaa, 0x41, 0x0077}, /* 00,41,77,aa */
{0xaa, 0x42, 0x0053}, /* 00,42,53,aa */
{0xaa, 0x43, 0x00b0}, /* 00,43,b0,aa */
{0xaa, 0x4b, 0x0001}, /* 00,4b,01,aa */
{0xaa, 0x72, 0x0020}, /* 00,72,20,aa */
{0xaa, 0x73, 0x0000}, /* 00,73,00,aa */
{0xaa, 0x80, 0x0000}, /* 00,80,00,aa */
{0xaa, 0x85, 0x0050}, /* 00,85,50,aa */
{0xaa, 0x91, 0x0070}, /* 00,91,70,aa */
{0xaa, 0x92, 0x0072}, /* 00,92,72,aa */
{0xaa, 0x03, 0x0001}, /* 00,03,01,aa */
{0xaa, 0x10, 0x00a0}, /* 00,10,a0,aa */
{0xaa, 0x11, 0x0001}, /* 00,11,01,aa */
{0xaa, 0x30, 0x0000}, /* 00,30,00,aa */
{0xaa, 0x60, 0x0000}, /* 00,60,00,aa */
{0xaa, 0xa0, 0x001a}, /* 00,a0,1a,aa */
{0xaa, 0xa1, 0x0000}, /* 00,a1,00,aa */
{0xaa, 0xa2, 0x003f}, /* 00,a2,3f,aa */
{0xaa, 0xa3, 0x0028}, /* 00,a3,28,aa */
{0xaa, 0xa4, 0x0010}, /* 00,a4,10,aa */
{0xaa, 0xa5, 0x0020}, /* 00,a5,20,aa */
{0xaa, 0xb1, 0x0044}, /* 00,b1,44,aa */
{0xaa, 0xd0, 0x0001}, /* 00,d0,01,aa */
{0xaa, 0xd1, 0x0085}, /* 00,d1,85,aa */
{0xaa, 0xd2, 0x0080}, /* 00,d2,80,aa */
{0xaa, 0xd3, 0x0080}, /* 00,d3,80,aa */
{0xaa, 0xd4, 0x0080}, /* 00,d4,80,aa */
{0xaa, 0xd5, 0x0080}, /* 00,d5,80,aa */
{0xaa, 0xc0, 0x00c3}, /* 00,c0,c3,aa */
{0xaa, 0xc2, 0x0044}, /* 00,c2,44,aa */
{0xaa, 0xc4, 0x0040}, /* 00,c4,40,aa */
{0xaa, 0xc5, 0x0020}, /* 00,c5,20,aa */
{0xaa, 0xc6, 0x0008}, /* 00,c6,08,aa */
{0xaa, 0x03, 0x0004}, /* 00,03,04,aa */
{0xaa, 0x10, 0x0000}, /* 00,10,00,aa */
{0xaa, 0x40, 0x0030}, /* 00,40,30,aa */
{0xaa, 0x41, 0x0020}, /* 00,41,20,aa */
{0xaa, 0x42, 0x002d}, /* 00,42,2d,aa */
{0xaa, 0x03, 0x0003}, /* 00,03,03,aa */
{0xaa, 0x1c, 0x0050}, /* 00,1C,50,aa */
{0xaa, 0x11, 0x0081}, /* 00,11,81,aa */
{0xaa, 0x3b, 0x001d}, /* 00,3b,1D,aa */
{0xaa, 0x3c, 0x004c}, /* 00,3c,4C,aa */
{0xaa, 0x3d, 0x0018}, /* 00,3d,18,aa */
{0xaa, 0x3e, 0x006a}, /* 00,3e,6A,aa */
{0xaa, 0x01, 0x0000}, /* 00,01,00,aa */
{0xaa, 0x52, 0x00ff}, /* 00,52,FF,aa */
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */
{0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,37,cc */
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, /* 01,89,06,cc */
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */
{0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,02,cc */
{0xaa, 0x03, 0x0002}, /* 00,03,02,aa */
{0xaa, 0x51, 0x0027}, /* 00,51,27,aa */
{0xaa, 0x52, 0x0020}, /* 00,52,20,aa */
{0xaa, 0x03, 0x0003}, /* 00,03,03,aa */
{0xaa, 0x50, 0x0010}, /* 00,50,10,aa */
{0xaa, 0x51, 0x0010}, /* 00,51,10,aa */
{0xaa, 0x54, 0x0010}, /* 00,54,10,aa */
{0xaa, 0x55, 0x0010}, /* 00,55,10,aa */
{0xa0, 0xf0, 0x0199}, /* 01,99,F0,cc */
{0xa0, 0x80, 0x019a}, /* 01,9A,80,cc */
{0xaa, 0x03, 0x0003}, /* 00,03,03,aa */
{0xaa, 0x10, 0x00fc}, /* 00,10,fc,aa */
{0xaa, 0x36, 0x001d}, /* 00,36,1D,aa */
{0xaa, 0x37, 0x004c}, /* 00,37,4C,aa */
{0xaa, 0x3b, 0x001d}, /* 00,3B,1D,aa */
{}
};
static const struct usb_action mc501cb_InitialScale[] = { /* 320x240 */
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */
{0xa0, 0x10, ZC3XX_R002_CLOCKSELECT}, /* 00,02,10,cc */
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00,08,03,cc */
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */
{0xa0, 0xd0, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,d0,cc */
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc */
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc */
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc */
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc */
{0xa0, 0x01, ZC3XX_R09B_WINHEIGHTHIGH}, /* 00,9b,01,cc */
{0xa0, 0xd8, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,d8,cc */
{0xa0, 0x02, ZC3XX_R09D_WINWIDTHHIGH}, /* 00,9d,02,cc */
{0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,88,cc */
{0xa0, 0x33, ZC3XX_R086_EXPTIMEHIGH}, /* 00,86,33,cc */
{0xa0, 0x34, ZC3XX_R087_EXPTIMEMID}, /* 00,87,34,cc */
{0xa0, 0x35, ZC3XX_R088_EXPTIMELOW}, /* 00,88,35,cc */
{0xa0, 0xb0, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,b0,cc */
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */
{0xaa, 0x01, 0x0001}, /* 00,01,01,aa */
{0xaa, 0x01, 0x0003}, /* 00,01,03,aa */
{0xaa, 0x01, 0x0001}, /* 00,01,01,aa */
{0xaa, 0x03, 0x0000}, /* 00,03,00,aa */
{0xaa, 0x10, 0x0000}, /* 00,10,00,aa */
{0xaa, 0x11, 0x0080}, /* 00,11,80,aa */
{0xaa, 0x12, 0x0000}, /* 00,12,00,aa */
{0xaa, 0x13, 0x0000}, /* 00,13,00,aa */
{0xaa, 0x14, 0x0000}, /* 00,14,00,aa */
{0xaa, 0x15, 0x0000}, /* 00,15,00,aa */
{0xaa, 0x16, 0x0000}, /* 00,16,00,aa */
{0xaa, 0x17, 0x0001}, /* 00,17,01,aa */
{0xaa, 0x18, 0x00d8}, /* 00,18,d8,aa */
{0xaa, 0x19, 0x0002}, /* 00,19,02,aa */
{0xaa, 0x1a, 0x0088}, /* 00,1a,88,aa */
{0xaa, 0x20, 0x00a8}, /* 00,20,a8,aa */
{0xaa, 0x22, 0x0000}, /* 00,22,00,aa */
{0xaa, 0x23, 0x0000}, /* 00,23,00,aa */
{0xaa, 0x24, 0x0000}, /* 00,24,00,aa */
{0xaa, 0x40, 0x0033}, /* 00,40,33,aa */
{0xaa, 0x41, 0x0077}, /* 00,41,77,aa */
{0xaa, 0x42, 0x0053}, /* 00,42,53,aa */
{0xaa, 0x43, 0x00b0}, /* 00,43,b0,aa */
{0xaa, 0x4b, 0x0001}, /* 00,4b,01,aa */
{0xaa, 0x72, 0x0020}, /* 00,72,20,aa */
{0xaa, 0x73, 0x0000}, /* 00,73,00,aa */
{0xaa, 0x80, 0x0000}, /* 00,80,00,aa */
{0xaa, 0x85, 0x0050}, /* 00,85,50,aa */
{0xaa, 0x91, 0x0070}, /* 00,91,70,aa */
{0xaa, 0x92, 0x0072}, /* 00,92,72,aa */
{0xaa, 0x03, 0x0001}, /* 00,03,01,aa */
{0xaa, 0x10, 0x00a0}, /* 00,10,a0,aa */
{0xaa, 0x11, 0x0001}, /* 00,11,01,aa */
{0xaa, 0x30, 0x0000}, /* 00,30,00,aa */
{0xaa, 0x60, 0x0000}, /* 00,60,00,aa */
{0xaa, 0xa0, 0x001a}, /* 00,a0,1a,aa */
{0xaa, 0xa1, 0x0000}, /* 00,a1,00,aa */
{0xaa, 0xa2, 0x003f}, /* 00,a2,3f,aa */
{0xaa, 0xa3, 0x0028}, /* 00,a3,28,aa */
{0xaa, 0xa4, 0x0010}, /* 00,a4,10,aa */
{0xaa, 0xa5, 0x0020}, /* 00,a5,20,aa */
{0xaa, 0xb1, 0x0044}, /* 00,b1,44,aa */
{0xaa, 0xd0, 0x0001}, /* 00,d0,01,aa */
{0xaa, 0xd1, 0x0085}, /* 00,d1,85,aa */
{0xaa, 0xd2, 0x0080}, /* 00,d2,80,aa */
{0xaa, 0xd3, 0x0080}, /* 00,d3,80,aa */
{0xaa, 0xd4, 0x0080}, /* 00,d4,80,aa */
{0xaa, 0xd5, 0x0080}, /* 00,d5,80,aa */
{0xaa, 0xc0, 0x00c3}, /* 00,c0,c3,aa */
{0xaa, 0xc2, 0x0044}, /* 00,c2,44,aa */
{0xaa, 0xc4, 0x0040}, /* 00,c4,40,aa */
{0xaa, 0xc5, 0x0020}, /* 00,c5,20,aa */
{0xaa, 0xc6, 0x0008}, /* 00,c6,08,aa */
{0xaa, 0x03, 0x0004}, /* 00,03,04,aa */
{0xaa, 0x10, 0x0000}, /* 00,10,00,aa */
{0xaa, 0x40, 0x0030}, /* 00,40,30,aa */
{0xaa, 0x41, 0x0020}, /* 00,41,20,aa */
{0xaa, 0x42, 0x002d}, /* 00,42,2d,aa */
{0xaa, 0x03, 0x0003}, /* 00,03,03,aa */
{0xaa, 0x1c, 0x0050}, /* 00,1c,50,aa */
{0xaa, 0x11, 0x0081}, /* 00,11,81,aa */
{0xaa, 0x3b, 0x003a}, /* 00,3b,3A,aa */
{0xaa, 0x3c, 0x0098}, /* 00,3c,98,aa */
{0xaa, 0x3d, 0x0030}, /* 00,3d,30,aa */
{0xaa, 0x3e, 0x00d4}, /* 00,3E,D4,aa */
{0xaa, 0x01, 0x0000}, /* 00,01,00,aa */
{0xaa, 0x52, 0x00ff}, /* 00,52,FF,aa */
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */
{0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,37,cc */
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, /* 01,89,06,cc */
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */
{0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,02,cc */
{0xaa, 0x03, 0x0002}, /* 00,03,02,aa */
{0xaa, 0x51, 0x004e}, /* 00,51,4E,aa */
{0xaa, 0x52, 0x0041}, /* 00,52,41,aa */
{0xaa, 0x03, 0x0003}, /* 00,03,03,aa */
{0xaa, 0x50, 0x0010}, /* 00,50,10,aa */
{0xaa, 0x51, 0x0010}, /* 00,51,10,aa */
{0xaa, 0x54, 0x0010}, /* 00,54,10,aa */
{0xaa, 0x55, 0x0010}, /* 00,55,10,aa */
{0xa0, 0xf0, 0x0199}, /* 01,99,F0,cc */
{0xa0, 0x80, 0x019a}, /* 01,9A,80,cc */
{}
};
static const struct usb_action mc501cb_50HZ[] = {
{0xaa, 0x03, 0x0003}, /* 00,03,03,aa */
{0xaa, 0x10, 0x00fc}, /* 00,10,fc,aa */
{0xaa, 0x36, 0x001d}, /* 00,36,1D,aa */
{0xaa, 0x37, 0x004c}, /* 00,37,4C,aa */
{0xaa, 0x3b, 0x001d}, /* 00,3B,1D,aa */
{0xaa, 0x3c, 0x004c}, /* 00,3C,4C,aa */
{0xaa, 0x3d, 0x001d}, /* 00,3D,1D,aa */
{0xaa, 0x3e, 0x004c}, /* 00,3E,4C,aa */
{}
};
static const struct usb_action mc501cb_50HZScale[] = {
{0xaa, 0x03, 0x0003}, /* 00,03,03,aa */
{0xaa, 0x10, 0x00fc}, /* 00,10,fc,aa */
{0xaa, 0x36, 0x003a}, /* 00,36,3A,aa */
{0xaa, 0x37, 0x0098}, /* 00,37,98,aa */
{0xaa, 0x3b, 0x003a}, /* 00,3B,3A,aa */
{0xaa, 0x3c, 0x0098}, /* 00,3C,98,aa */
{0xaa, 0x3d, 0x003a}, /* 00,3D,3A,aa */
{0xaa, 0x3e, 0x0098}, /* 00,3E,98,aa */
{}
};
static const struct usb_action mc501cb_60HZ[] = {
{0xaa, 0x03, 0x0003}, /* 00,03,03,aa */
{0xaa, 0x10, 0x00fc}, /* 00,10,fc,aa */
{0xaa, 0x36, 0x0018}, /* 00,36,18,aa */
{0xaa, 0x37, 0x006a}, /* 00,37,6A,aa */
{0xaa, 0x3d, 0x0018}, /* 00,3D,18,aa */
{0xaa, 0x3e, 0x006a}, /* 00,3E,6A,aa */
{0xaa, 0x3b, 0x0018}, /* 00,3B,18,aa */
{0xaa, 0x3c, 0x006a}, /* 00,3C,6A,aa */
{}
};
static const struct usb_action mc501cb_60HZScale[] = {
{0xaa, 0x03, 0x0003}, /* 00,03,03,aa */
{0xaa, 0x10, 0x00fc}, /* 00,10,fc,aa */
{0xaa, 0x36, 0x0030}, /* 00,36,30,aa */
{0xaa, 0x37, 0x00d4}, /* 00,37,D4,aa */
{0xaa, 0x3d, 0x0030}, /* 00,3D,30,aa */
{0xaa, 0x3e, 0x00d4}, /* 00,3E,D4,aa */
{0xaa, 0x3b, 0x0030}, /* 00,3B,30,aa */
{0xaa, 0x3c, 0x00d4}, /* 00,3C,D4,aa */
{}
};
static const struct usb_action mc501cb_NoFliker[] = {
{0xaa, 0x03, 0x0003}, /* 00,03,03,aa */
{0xaa, 0x10, 0x00fc}, /* 00,10,fc,aa */
{0xaa, 0x36, 0x0018}, /* 00,36,18,aa */
{0xaa, 0x37, 0x006a}, /* 00,37,6A,aa */
{0xaa, 0x3d, 0x0018}, /* 00,3D,18,aa */
{0xaa, 0x3e, 0x006a}, /* 00,3E,6A,aa */
{0xaa, 0x3b, 0x0018}, /* 00,3B,18,aa */
{0xaa, 0x3c, 0x006a}, /* 00,3C,6A,aa */
{}
};
static const struct usb_action mc501cb_NoFlikerScale[] = {
{0xaa, 0x03, 0x0003}, /* 00,03,03,aa */
{0xaa, 0x10, 0x00fc}, /* 00,10,fc,aa */
{0xaa, 0x36, 0x0030}, /* 00,36,30,aa */
{0xaa, 0x37, 0x00d4}, /* 00,37,D4,aa */
{0xaa, 0x3d, 0x0030}, /* 00,3D,30,aa */
{0xaa, 0x3e, 0x00d4}, /* 00,3E,D4,aa */
{0xaa, 0x3b, 0x0030}, /* 00,3B,30,aa */
{0xaa, 0x3c, 0x00d4}, /* 00,3C,D4,aa */
{}
};
/* from zs211.inf */
static const struct usb_action ov7620_Initial[] = { /* 640x480 */
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */
{0xa0, 0x40, ZC3XX_R002_CLOCKSELECT}, /* 00,02,40,cc */
{0xa0, 0x00, ZC3XX_R008_CLOCKSETTING}, /* 00,08,00,cc */
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */
{0xa0, 0x06, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,06,cc */
{0xa0, 0x02, ZC3XX_R083_RGAINADDR}, /* 00,83,02,cc */
{0xa0, 0x01, ZC3XX_R085_BGAINADDR}, /* 00,85,01,cc */
{0xa0, 0x80, ZC3XX_R086_EXPTIMEHIGH}, /* 00,86,80,cc */
{0xa0, 0x81, ZC3XX_R087_EXPTIMEMID}, /* 00,87,81,cc */
{0xa0, 0x10, ZC3XX_R088_EXPTIMELOW}, /* 00,88,10,cc */
{0xa0, 0xa1, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,a1,cc */
{0xa0, 0x08, ZC3XX_R08D_COMPABILITYMODE}, /* 00,8d,08,cc */
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */
{0xa0, 0xd8, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,d8,cc */
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc */
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc */
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc */
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc */
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc */
{0xa0, 0xde, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,de,cc */
{0xa0, 0x86, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,86,cc */
{0xaa, 0x12, 0x0088}, /* 00,12,88,aa */
{0xaa, 0x12, 0x0048}, /* 00,12,48,aa */
{0xaa, 0x75, 0x008a}, /* 00,75,8a,aa */
{0xaa, 0x13, 0x00a3}, /* 00,13,a3,aa */
{0xaa, 0x04, 0x0000}, /* 00,04,00,aa */
{0xaa, 0x05, 0x0000}, /* 00,05,00,aa */
{0xaa, 0x14, 0x0000}, /* 00,14,00,aa */
{0xaa, 0x15, 0x0004}, /* 00,15,04,aa */
{0xaa, 0x17, 0x0018}, /* 00,17,18,aa */
{0xaa, 0x18, 0x00ba}, /* 00,18,ba,aa */
{0xaa, 0x19, 0x0002}, /* 00,19,02,aa */
{0xaa, 0x1a, 0x00f1}, /* 00,1a,f1,aa */
{0xaa, 0x20, 0x0040}, /* 00,20,40,aa */
{0xaa, 0x24, 0x0088}, /* 00,24,88,aa */
{0xaa, 0x25, 0x0078}, /* 00,25,78,aa */
{0xaa, 0x27, 0x00f6}, /* 00,27,f6,aa */
{0xaa, 0x28, 0x00a0}, /* 00,28,a0,aa */
{0xaa, 0x21, 0x0000}, /* 00,21,00,aa */
{0xaa, 0x2a, 0x0083}, /* 00,2a,83,aa */
{0xaa, 0x2b, 0x0096}, /* 00,2b,96,aa */
{0xaa, 0x2d, 0x0005}, /* 00,2d,05,aa */
{0xaa, 0x74, 0x0020}, /* 00,74,20,aa */
{0xaa, 0x61, 0x0068}, /* 00,61,68,aa */
{0xaa, 0x64, 0x0088}, /* 00,64,88,aa */
{0xaa, 0x00, 0x0000}, /* 00,00,00,aa */
{0xaa, 0x06, 0x0080}, /* 00,06,80,aa */
{0xaa, 0x01, 0x0090}, /* 00,01,90,aa */
{0xaa, 0x02, 0x0030}, /* 00,02,30,aa */
{0xa0, 0x77, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,77,cc */
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, /* 01,89,06,cc */
{0xa0, 0x00, 0x01ad}, /* 01,ad,00,cc */
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */
{0xa0, 0x68, ZC3XX_R116_RGAIN}, /* 01,16,68,cc */
{0xa0, 0x52, ZC3XX_R118_BGAIN}, /* 01,18,52,cc */
{0xa0, 0x40, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,40,cc */
{0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,02,cc */
{0xa0, 0x50, ZC3XX_R1A8_DIGITALGAIN}, /* 01,a8,50,cc */
{}
};
static const struct usb_action ov7620_InitialScale[] = { /* 320x240 */
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */
{0xa0, 0x50, ZC3XX_R002_CLOCKSELECT}, /* 00,02,50,cc */
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00,08,00,cc */
/* mx change? */
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */
{0xa0, 0x06, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,06,cc */
{0xa0, 0x02, ZC3XX_R083_RGAINADDR}, /* 00,83,02,cc */
{0xa0, 0x01, ZC3XX_R085_BGAINADDR}, /* 00,85,01,cc */
{0xa0, 0x80, ZC3XX_R086_EXPTIMEHIGH}, /* 00,86,80,cc */
{0xa0, 0x81, ZC3XX_R087_EXPTIMEMID}, /* 00,87,81,cc */
{0xa0, 0x10, ZC3XX_R088_EXPTIMELOW}, /* 00,88,10,cc */
{0xa0, 0xa1, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,a1,cc */
{0xa0, 0x08, ZC3XX_R08D_COMPABILITYMODE}, /* 00,8d,08,cc */
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */
{0xa0, 0xd0, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,d0,cc */
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc */
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc */
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc */
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc */
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc */
{0xa0, 0xd6, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,d6,cc */
/* OV7648 00,9c,d8,cc */
{0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,88,cc */
{0xaa, 0x12, 0x0088}, /* 00,12,88,aa */
{0xaa, 0x12, 0x0048}, /* 00,12,48,aa */
{0xaa, 0x75, 0x008a}, /* 00,75,8a,aa */
{0xaa, 0x13, 0x00a3}, /* 00,13,a3,aa */
{0xaa, 0x04, 0x0000}, /* 00,04,00,aa */
{0xaa, 0x05, 0x0000}, /* 00,05,00,aa */
{0xaa, 0x14, 0x0000}, /* 00,14,00,aa */
{0xaa, 0x15, 0x0004}, /* 00,15,04,aa */
{0xaa, 0x24, 0x0088}, /* 00,24,88,aa */
{0xaa, 0x25, 0x0078}, /* 00,25,78,aa */
{0xaa, 0x17, 0x0018}, /* 00,17,18,aa */
{0xaa, 0x18, 0x00ba}, /* 00,18,ba,aa */
{0xaa, 0x19, 0x0002}, /* 00,19,02,aa */
{0xaa, 0x1a, 0x00f2}, /* 00,1a,f2,aa */
{0xaa, 0x20, 0x0040}, /* 00,20,40,aa */
{0xaa, 0x27, 0x00f6}, /* 00,27,f6,aa */
{0xaa, 0x28, 0x00a0}, /* 00,28,a0,aa */
{0xaa, 0x21, 0x0000}, /* 00,21,00,aa */
{0xaa, 0x2a, 0x0083}, /* 00,2a,83,aa */
{0xaa, 0x2b, 0x0096}, /* 00,2b,96,aa */
{0xaa, 0x2d, 0x0005}, /* 00,2d,05,aa */
{0xaa, 0x74, 0x0020}, /* 00,74,20,aa */
{0xaa, 0x61, 0x0068}, /* 00,61,68,aa */
{0xaa, 0x64, 0x0088}, /* 00,64,88,aa */
{0xaa, 0x00, 0x0000}, /* 00,00,00,aa */
{0xaa, 0x06, 0x0080}, /* 00,06,80,aa */
{0xaa, 0x01, 0x0090}, /* 00,01,90,aa */
{0xaa, 0x02, 0x0030}, /* 00,02,30,aa */
{0xa0, 0x77, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,77,cc */
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, /* 01,89,06,cc */
{0xa0, 0x00, 0x01ad}, /* 01,ad,00,cc */
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */
{0xa0, 0x68, ZC3XX_R116_RGAIN}, /* 01,16,68,cc */
{0xa0, 0x52, ZC3XX_R118_BGAIN}, /* 01,18,52,cc */
{0xa0, 0x50, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,50,cc */
{0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,02,cc */
{0xa0, 0x50, ZC3XX_R1A8_DIGITALGAIN}, /* 01,a8,50,cc */
{}
};
static const struct usb_action ov7620_50HZ[] = {
{0xaa, 0x13, 0x00a3}, /* 00,13,a3,aa */
{0xdd, 0x00, 0x0100}, /* 00,01,00,dd */
{0xaa, 0x2b, 0x0096}, /* 00,2b,96,aa */
{0xaa, 0x75, 0x008a}, /* 00,75,8a,aa */
{0xaa, 0x2d, 0x0005}, /* 00,2d,05,aa */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,04,cc */
{0xa0, 0x18, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,18,cc */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x83, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,83,cc */
{0xaa, 0x10, 0x0082}, /* 00,10,82,aa */
{0xaa, 0x76, 0x0003}, /* 00,76,03,aa */
/* {0xa0, 0x40, ZC3XX_R002_CLOCKSELECT}, * 00,02,40,cc
* if mode0 (640x480) */
{}
};
static const struct usb_action ov7620_60HZ[] = {
{0xaa, 0x13, 0x00a3}, /* 00,13,a3,aa */
/* (bug in zs211.inf) */
{0xdd, 0x00, 0x0100}, /* 00,01,00,dd */
{0xaa, 0x2b, 0x0000}, /* 00,2b,00,aa */
{0xaa, 0x75, 0x008a}, /* 00,75,8a,aa */
{0xaa, 0x2d, 0x0005}, /* 00,2d,05,aa */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,04,cc */
{0xa0, 0x18, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,18,cc */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x83, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,83,cc */
{0xaa, 0x10, 0x0020}, /* 00,10,20,aa */
{0xaa, 0x76, 0x0003}, /* 00,76,03,aa */
/* {0xa0, 0x40, ZC3XX_R002_CLOCKSELECT}, * 00,02,40,cc
* if mode0 (640x480) */
/* ?? in gspca v1, it was
{0xa0, 0x00, 0x0039}, * 00,00,00,dd *
{0xa1, 0x01, 0x0037}, */
{}
};
static const struct usb_action ov7620_NoFliker[] = {
{0xaa, 0x13, 0x00a3}, /* 00,13,a3,aa */
/* (bug in zs211.inf) */
{0xdd, 0x00, 0x0100}, /* 00,01,00,dd */
{0xaa, 0x2b, 0x0000}, /* 00,2b,00,aa */
{0xaa, 0x75, 0x008e}, /* 00,75,8e,aa */
{0xaa, 0x2d, 0x0001}, /* 00,2d,01,aa */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,04,cc */
{0xa0, 0x18, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,18,cc */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x01, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,01,cc */
/* {0xa0, 0x44, ZC3XX_R002_CLOCKSELECT}, * 00,02,44,cc
* if mode1 (320x240) */
/* ?? was
{0xa0, 0x00, 0x0039}, * 00,00,00,dd *
{0xa1, 0x01, 0x0037}, */
{}
};
static const struct usb_action ov7630c_InitialScale[] = {
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL},
{0xa0, 0x10, ZC3XX_R002_CLOCKSELECT},
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL},
{0xa0, 0x10, ZC3XX_R002_CLOCKSELECT},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x06, ZC3XX_R010_CMOSSENSORSELECT},
{0xa0, 0xa1, ZC3XX_R08B_I2CDEVICEADDR},
{0xa0, 0x08, ZC3XX_R08D_COMPABILITYMODE},
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW},
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xaa, 0x12, 0x0080},
{0xa0, 0x02, ZC3XX_R083_RGAINADDR},
{0xa0, 0x01, ZC3XX_R085_BGAINADDR},
{0xa0, 0x90, ZC3XX_R086_EXPTIMEHIGH},
{0xa0, 0x91, ZC3XX_R087_EXPTIMEMID},
{0xa0, 0x10, ZC3XX_R088_EXPTIMELOW},
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW},
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW},
{0xa0, 0xd8, ZC3XX_R09C_WINHEIGHTLOW},
{0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW},
{0xaa, 0x12, 0x0069},
{0xaa, 0x04, 0x0020},
{0xaa, 0x06, 0x0050},
{0xaa, 0x13, 0x0083},
{0xaa, 0x14, 0x0000},
{0xaa, 0x15, 0x0024},
{0xaa, 0x17, 0x0018},
{0xaa, 0x18, 0x00ba},
{0xaa, 0x19, 0x0002},
{0xaa, 0x1a, 0x00f6},
{0xaa, 0x1b, 0x0002},
{0xaa, 0x20, 0x00c2},
{0xaa, 0x24, 0x0060},
{0xaa, 0x25, 0x0040},
{0xaa, 0x26, 0x0030},
{0xaa, 0x27, 0x00ea},
{0xaa, 0x28, 0x00a0},
{0xaa, 0x21, 0x0000},
{0xaa, 0x2a, 0x0081},
{0xaa, 0x2b, 0x0096},
{0xaa, 0x2d, 0x0094},
{0xaa, 0x2f, 0x003d},
{0xaa, 0x30, 0x0024},
{0xaa, 0x60, 0x0000},
{0xaa, 0x61, 0x0040},
{0xaa, 0x68, 0x007c},
{0xaa, 0x6f, 0x0015},
{0xaa, 0x75, 0x0088},
{0xaa, 0x77, 0x00b5},
{0xaa, 0x01, 0x0060},
{0xaa, 0x02, 0x0060},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x77, ZC3XX_R101_SENSORCORRECTION},
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
{0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x00, 0x01ad},
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
{0xa0, 0x60, ZC3XX_R116_RGAIN},
{0xa0, 0x46, ZC3XX_R118_BGAIN},
{0xa0, 0x04, ZC3XX_R113_RGB03},
/* 0x10, */
{0xa1, 0x01, 0x0002},
{0xa0, 0x50, ZC3XX_R10A_RGB00}, /* matrix */
{0xa0, 0xf8, ZC3XX_R10B_RGB01},
{0xa0, 0xf8, ZC3XX_R10C_RGB02},
{0xa0, 0xf8, ZC3XX_R10D_RGB10},
{0xa0, 0x50, ZC3XX_R10E_RGB11},
{0xa0, 0xf8, ZC3XX_R10F_RGB12},
{0xa0, 0xf8, ZC3XX_R110_RGB20},
{0xa0, 0xf8, ZC3XX_R111_RGB21},
{0xa0, 0x50, ZC3XX_R112_RGB22},
{0xa1, 0x01, 0x0008},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* clock ? */
{0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00}, /* sharpness+ */
{0xa1, 0x01, 0x01c8},
{0xa1, 0x01, 0x01c9},
{0xa1, 0x01, 0x01ca},
{0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05}, /* sharpness- */
{0xa0, 0x01, ZC3XX_R120_GAMMA00}, /* gamma 2 ?*/
{0xa0, 0x0c, ZC3XX_R121_GAMMA01},
{0xa0, 0x1f, ZC3XX_R122_GAMMA02},
{0xa0, 0x3a, ZC3XX_R123_GAMMA03},
{0xa0, 0x53, ZC3XX_R124_GAMMA04},
{0xa0, 0x6d, ZC3XX_R125_GAMMA05},
{0xa0, 0x85, ZC3XX_R126_GAMMA06},
{0xa0, 0x9c, ZC3XX_R127_GAMMA07},
{0xa0, 0xb0, ZC3XX_R128_GAMMA08},
{0xa0, 0xc2, ZC3XX_R129_GAMMA09},
{0xa0, 0xd1, ZC3XX_R12A_GAMMA0A},
{0xa0, 0xde, ZC3XX_R12B_GAMMA0B},
{0xa0, 0xe9, ZC3XX_R12C_GAMMA0C},
{0xa0, 0xf2, ZC3XX_R12D_GAMMA0D},
{0xa0, 0xf9, ZC3XX_R12E_GAMMA0E},
{0xa0, 0xff, ZC3XX_R12F_GAMMA0F},
{0xa0, 0x05, ZC3XX_R130_GAMMA10},
{0xa0, 0x0f, ZC3XX_R131_GAMMA11},
{0xa0, 0x16, ZC3XX_R132_GAMMA12},
{0xa0, 0x1a, ZC3XX_R133_GAMMA13},
{0xa0, 0x19, ZC3XX_R134_GAMMA14},
{0xa0, 0x19, ZC3XX_R135_GAMMA15},
{0xa0, 0x17, ZC3XX_R136_GAMMA16},
{0xa0, 0x15, ZC3XX_R137_GAMMA17},
{0xa0, 0x12, ZC3XX_R138_GAMMA18},
{0xa0, 0x10, ZC3XX_R139_GAMMA19},
{0xa0, 0x0e, ZC3XX_R13A_GAMMA1A},
{0xa0, 0x0b, ZC3XX_R13B_GAMMA1B},
{0xa0, 0x09, ZC3XX_R13C_GAMMA1C},
{0xa0, 0x08, ZC3XX_R13D_GAMMA1D},
{0xa0, 0x06, ZC3XX_R13E_GAMMA1E},
{0xa0, 0x03, ZC3XX_R13F_GAMMA1F},
{0xa0, 0x50, ZC3XX_R10A_RGB00}, /* matrix */
{0xa0, 0xf8, ZC3XX_R10B_RGB01},
{0xa0, 0xf8, ZC3XX_R10C_RGB02},
{0xa0, 0xf8, ZC3XX_R10D_RGB10},
{0xa0, 0x50, ZC3XX_R10E_RGB11},
{0xa0, 0xf8, ZC3XX_R10F_RGB12},
{0xa0, 0xf8, ZC3XX_R110_RGB20},
{0xa0, 0xf8, ZC3XX_R111_RGB21},
{0xa0, 0x50, ZC3XX_R112_RGB22},
{0xa1, 0x01, 0x0180},
{0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE},
{0xaa, 0x10, 0x001b},
{0xaa, 0x76, 0x0002},
{0xaa, 0x2a, 0x0081},
{0xaa, 0x2b, 0x0000},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x01, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xb8, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x37, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x26, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x50, ZC3XX_R11D_GLOBALGAIN},
{0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x40, ZC3XX_R180_AUTOCORRECTENABLE},
{0xaa, 0x13, 0x0083}, /* 40 */
{0xa1, 0x01, 0x0180},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{}
};
static const struct usb_action ov7630c_Initial[] = {
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL},
{0xa0, 0x00, ZC3XX_R002_CLOCKSELECT},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x06, ZC3XX_R010_CMOSSENSORSELECT},
{0xa0, 0xa1, ZC3XX_R08B_I2CDEVICEADDR},
{0xa0, 0x08, ZC3XX_R08D_COMPABILITYMODE},
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW},
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xaa, 0x12, 0x0080},
{0xa0, 0x02, ZC3XX_R083_RGAINADDR},
{0xa0, 0x01, ZC3XX_R085_BGAINADDR},
{0xa0, 0x90, ZC3XX_R086_EXPTIMEHIGH},
{0xa0, 0x91, ZC3XX_R087_EXPTIMEMID},
{0xa0, 0x10, ZC3XX_R088_EXPTIMELOW},
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW},
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW},
{0xa0, 0xe6, ZC3XX_R09C_WINHEIGHTLOW},
{0xa0, 0x86, ZC3XX_R09E_WINWIDTHLOW},
{0xaa, 0x12, 0x0069}, /* i2c */
{0xaa, 0x04, 0x0020},
{0xaa, 0x06, 0x0050},
{0xaa, 0x13, 0x00c3},
{0xaa, 0x14, 0x0000},
{0xaa, 0x15, 0x0024},
{0xaa, 0x19, 0x0003},
{0xaa, 0x1a, 0x00f6},
{0xaa, 0x1b, 0x0002},
{0xaa, 0x20, 0x00c2},
{0xaa, 0x24, 0x0060},
{0xaa, 0x25, 0x0040},
{0xaa, 0x26, 0x0030},
{0xaa, 0x27, 0x00ea},
{0xaa, 0x28, 0x00a0},
{0xaa, 0x21, 0x0000},
{0xaa, 0x2a, 0x0081},
{0xaa, 0x2b, 0x0096},
{0xaa, 0x2d, 0x0084},
{0xaa, 0x2f, 0x003d},
{0xaa, 0x30, 0x0024},
{0xaa, 0x60, 0x0000},
{0xaa, 0x61, 0x0040},
{0xaa, 0x68, 0x007c},
{0xaa, 0x6f, 0x0015},
{0xaa, 0x75, 0x0088},
{0xaa, 0x77, 0x00b5},
{0xaa, 0x01, 0x0060},
{0xaa, 0x02, 0x0060},
{0xaa, 0x17, 0x0018},
{0xaa, 0x18, 0x00ba},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x77, ZC3XX_R101_SENSORCORRECTION},
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
{0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN},
{0xa0, 0x00, 0x01ad},
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
{0xa0, 0x60, ZC3XX_R116_RGAIN},
{0xa0, 0x46, ZC3XX_R118_BGAIN},
{0xa0, 0x04, ZC3XX_R113_RGB03},
{0xa1, 0x01, 0x0002},
{0xa0, 0x4e, ZC3XX_R10A_RGB00}, /* matrix */
{0xa0, 0xfe, ZC3XX_R10B_RGB01},
{0xa0, 0xf4, ZC3XX_R10C_RGB02},
{0xa0, 0xf7, ZC3XX_R10D_RGB10},
{0xa0, 0x4d, ZC3XX_R10E_RGB11},
{0xa0, 0xfc, ZC3XX_R10F_RGB12},
{0xa0, 0x00, ZC3XX_R110_RGB20},
{0xa0, 0xf6, ZC3XX_R111_RGB21},
{0xa0, 0x4a, ZC3XX_R112_RGB22},
{0xa1, 0x01, 0x0008},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* clock ? */
{0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00}, /* sharpness+ */
{0xa1, 0x01, 0x01c8},
{0xa1, 0x01, 0x01c9},
{0xa1, 0x01, 0x01ca},
{0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05}, /* sharpness- */
{0xa0, 0x16, ZC3XX_R120_GAMMA00}, /* gamma ~4 */
{0xa0, 0x3a, ZC3XX_R121_GAMMA01},
{0xa0, 0x5b, ZC3XX_R122_GAMMA02},
{0xa0, 0x7c, ZC3XX_R123_GAMMA03},
{0xa0, 0x94, ZC3XX_R124_GAMMA04},
{0xa0, 0xa9, ZC3XX_R125_GAMMA05},
{0xa0, 0xbb, ZC3XX_R126_GAMMA06},
{0xa0, 0xca, ZC3XX_R127_GAMMA07},
{0xa0, 0xd7, ZC3XX_R128_GAMMA08},
{0xa0, 0xe1, ZC3XX_R129_GAMMA09},
{0xa0, 0xea, ZC3XX_R12A_GAMMA0A},
{0xa0, 0xf1, ZC3XX_R12B_GAMMA0B},
{0xa0, 0xf7, ZC3XX_R12C_GAMMA0C},
{0xa0, 0xfc, ZC3XX_R12D_GAMMA0D},
{0xa0, 0xff, ZC3XX_R12E_GAMMA0E},
{0xa0, 0xff, ZC3XX_R12F_GAMMA0F},
{0xa0, 0x20, ZC3XX_R130_GAMMA10},
{0xa0, 0x22, ZC3XX_R131_GAMMA11},
{0xa0, 0x20, ZC3XX_R132_GAMMA12},
{0xa0, 0x1c, ZC3XX_R133_GAMMA13},
{0xa0, 0x16, ZC3XX_R134_GAMMA14},
{0xa0, 0x13, ZC3XX_R135_GAMMA15},
{0xa0, 0x10, ZC3XX_R136_GAMMA16},
{0xa0, 0x0d, ZC3XX_R137_GAMMA17},
{0xa0, 0x0b, ZC3XX_R138_GAMMA18},
{0xa0, 0x09, ZC3XX_R139_GAMMA19},
{0xa0, 0x07, ZC3XX_R13A_GAMMA1A},
{0xa0, 0x06, ZC3XX_R13B_GAMMA1B},
{0xa0, 0x05, ZC3XX_R13C_GAMMA1C},
{0xa0, 0x04, ZC3XX_R13D_GAMMA1D},
{0xa0, 0x00, ZC3XX_R13E_GAMMA1E},
{0xa0, 0x01, ZC3XX_R13F_GAMMA1F},
{0xa0, 0x4e, ZC3XX_R10A_RGB00}, /* matrix */
{0xa0, 0xfe, ZC3XX_R10B_RGB01},
{0xa0, 0xf4, ZC3XX_R10C_RGB02},
{0xa0, 0xf7, ZC3XX_R10D_RGB10},
{0xa0, 0x4d, ZC3XX_R10E_RGB11},
{0xa0, 0xfc, ZC3XX_R10F_RGB12},
{0xa0, 0x00, ZC3XX_R110_RGB20},
{0xa0, 0xf6, ZC3XX_R111_RGB21},
{0xa0, 0x4a, ZC3XX_R112_RGB22},
{0xa1, 0x01, 0x0180},
{0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE},
{0xaa, 0x10, 0x000d},
{0xaa, 0x76, 0x0002},
{0xaa, 0x2a, 0x0081},
{0xaa, 0x2b, 0x0000},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x00, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xd8, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x1b, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x26, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x50, ZC3XX_R11D_GLOBALGAIN},
{0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x40, ZC3XX_R180_AUTOCORRECTENABLE},
{0xaa, 0x13, 0x00c3},
{0xa1, 0x01, 0x0180},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{}
};
static const struct usb_action pas106b_Initial_com[] = {
/* Sream and Sensor specific */
{0xa1, 0x01, 0x0010}, /* CMOSSensorSelect */
/* System */
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* SystemControl */
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* SystemControl */
/* Picture size */
{0xa0, 0x00, ZC3XX_R002_CLOCKSELECT}, /* ClockSelect */
{0xa0, 0x03, 0x003a},
{0xa0, 0x0c, 0x003b},
{0xa0, 0x04, 0x0038},
{}
};
static const struct usb_action pas106b_InitialScale[] = { /* 176x144 */
/* JPEG control */
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING},
/* Sream and Sensor specific */
{0xa0, 0x0f, ZC3XX_R010_CMOSSENSORSELECT},
/* Picture size */
{0xa0, 0x00, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0xb0, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x00, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0x90, ZC3XX_R006_FRAMEHEIGHTLOW},
/* System */
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
/* Sream and Sensor specific */
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC},
/* Sensor Interface */
{0xa0, 0x08, ZC3XX_R08D_COMPABILITYMODE},
/* Window inside sensor array */
{0xa0, 0x03, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x03, ZC3XX_R11C_FIRSTXLOW},
{0xa0, 0x28, ZC3XX_R09C_WINHEIGHTLOW},
{0xa0, 0x68, ZC3XX_R09E_WINWIDTHLOW},
/* Init the sensor */
{0xaa, 0x02, 0x0004},
{0xaa, 0x08, 0x0000},
{0xaa, 0x09, 0x0005},
{0xaa, 0x0a, 0x0002},
{0xaa, 0x0b, 0x0002},
{0xaa, 0x0c, 0x0005},
{0xaa, 0x0d, 0x0000},
{0xaa, 0x0e, 0x0002},
{0xaa, 0x14, 0x0081},
/* Other registers */
{0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION},
/* Frame retreiving */
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
/* Gains */
{0xa0, 0xa0, ZC3XX_R1A8_DIGITALGAIN},
/* Unknown */
{0xa0, 0x00, 0x01ad},
/* Sharpness */
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
/* Other registers */
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
/* Auto exposure and white balance */
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
/*Dead pixels */
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
/* EEPROM */
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
/* JPEG control */
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING},
{0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00},
{0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05},
/* Other registers */
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
/* Auto exposure and white balance */
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
/*Dead pixels */
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
/* EEPROM */
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
/* JPEG control */
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING},
{0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00},
{0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05},
{0xa0, 0x58, ZC3XX_R10A_RGB00}, /* matrix */
{0xa0, 0xf4, ZC3XX_R10B_RGB01},
{0xa0, 0xf4, ZC3XX_R10C_RGB02},
{0xa0, 0xf4, ZC3XX_R10D_RGB10},
{0xa0, 0x58, ZC3XX_R10E_RGB11},
{0xa0, 0xf4, ZC3XX_R10F_RGB12},
{0xa0, 0xf4, ZC3XX_R110_RGB20},
{0xa0, 0xf4, ZC3XX_R111_RGB21},
{0xa0, 0x58, ZC3XX_R112_RGB22},
/* Auto correction */
{0xa0, 0x03, ZC3XX_R181_WINXSTART},
{0xa0, 0x08, ZC3XX_R182_WINXWIDTH},
{0xa0, 0x16, ZC3XX_R183_WINXCENTER},
{0xa0, 0x03, ZC3XX_R184_WINYSTART},
{0xa0, 0x05, ZC3XX_R185_WINYWIDTH},
{0xa0, 0x14, ZC3XX_R186_WINYCENTER},
{0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE},
/* Auto exposure and white balance */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x03, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xb1, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x87, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x0c, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE},
/* sensor on */
{0xaa, 0x07, 0x00b1},
{0xaa, 0x05, 0x0003},
{0xaa, 0x04, 0x0001},
{0xaa, 0x03, 0x003b},
/* Gains */
{0xa0, 0x20, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x26, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0xa0, ZC3XX_R11D_GLOBALGAIN},
{0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN},
/* Auto correction */
{0xa0, 0x40, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa1, 0x01, 0x0180}, /* AutoCorrectEnable */
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
/* Gains */
{0xa0, 0x40, ZC3XX_R116_RGAIN},
{0xa0, 0x40, ZC3XX_R117_GGAIN},
{0xa0, 0x40, ZC3XX_R118_BGAIN},
{}
};
static const struct usb_action pas106b_Initial[] = { /* 352x288 */
/* JPEG control */
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING},
/* Sream and Sensor specific */
{0xa0, 0x0f, ZC3XX_R010_CMOSSENSORSELECT},
/* Picture size */
{0xa0, 0x01, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0x60, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0x20, ZC3XX_R006_FRAMEHEIGHTLOW},
/* System */
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
/* Sream and Sensor specific */
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC},
/* Sensor Interface */
{0xa0, 0x08, ZC3XX_R08D_COMPABILITYMODE},
/* Window inside sensor array */
{0xa0, 0x03, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x03, ZC3XX_R11C_FIRSTXLOW},
{0xa0, 0x28, ZC3XX_R09C_WINHEIGHTLOW},
{0xa0, 0x68, ZC3XX_R09E_WINWIDTHLOW},
/* Init the sensor */
{0xaa, 0x02, 0x0004},
{0xaa, 0x08, 0x0000},
{0xaa, 0x09, 0x0005},
{0xaa, 0x0a, 0x0002},
{0xaa, 0x0b, 0x0002},
{0xaa, 0x0c, 0x0005},
{0xaa, 0x0d, 0x0000},
{0xaa, 0x0e, 0x0002},
{0xaa, 0x14, 0x0081},
/* Other registers */
{0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION},
/* Frame retreiving */
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
/* Gains */
{0xa0, 0xa0, ZC3XX_R1A8_DIGITALGAIN},
/* Unknown */
{0xa0, 0x00, 0x01ad},
/* Sharpness */
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
/* Other registers */
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
/* Auto exposure and white balance */
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
{0xa0, 0x80, ZC3XX_R18D_YTARGET},
/*Dead pixels */
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
/* EEPROM */
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
/* JPEG control */
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING},
{0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00},
{0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05},
/* Other registers */
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
/* Auto exposure and white balance */
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
/*Dead pixels */
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
/* EEPROM */
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
/* JPEG control */
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING},
{0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00},
{0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05},
{0xa0, 0x58, ZC3XX_R10A_RGB00}, /* matrix */
{0xa0, 0xf4, ZC3XX_R10B_RGB01},
{0xa0, 0xf4, ZC3XX_R10C_RGB02},
{0xa0, 0xf4, ZC3XX_R10D_RGB10},
{0xa0, 0x58, ZC3XX_R10E_RGB11},
{0xa0, 0xf4, ZC3XX_R10F_RGB12},
{0xa0, 0xf4, ZC3XX_R110_RGB20},
{0xa0, 0xf4, ZC3XX_R111_RGB21},
{0xa0, 0x58, ZC3XX_R112_RGB22},
/* Auto correction */
{0xa0, 0x03, ZC3XX_R181_WINXSTART},
{0xa0, 0x08, ZC3XX_R182_WINXWIDTH},
{0xa0, 0x16, ZC3XX_R183_WINXCENTER},
{0xa0, 0x03, ZC3XX_R184_WINYSTART},
{0xa0, 0x05, ZC3XX_R185_WINYWIDTH},
{0xa0, 0x14, ZC3XX_R186_WINYCENTER},
{0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE},
/* Auto exposure and white balance */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x03, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xb1, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x87, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE},
/* sensor on */
{0xaa, 0x07, 0x00b1},
{0xaa, 0x05, 0x0003},
{0xaa, 0x04, 0x0001},
{0xaa, 0x03, 0x003b},
/* Gains */
{0xa0, 0x20, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x26, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0xa0, ZC3XX_R11D_GLOBALGAIN},
{0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN},
/* Auto correction */
{0xa0, 0x40, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa1, 0x01, 0x0180}, /* AutoCorrectEnable */
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
/* Gains */
{0xa0, 0x40, ZC3XX_R116_RGAIN},
{0xa0, 0x40, ZC3XX_R117_GGAIN},
{0xa0, 0x40, ZC3XX_R118_BGAIN},
{0xa0, 0x00, 0x0007}, /* AutoCorrectEnable */
{0xa0, 0xff, ZC3XX_R018_FRAMELOST}, /* Frame adjust */
{}
};
static const struct usb_action pas106b_50HZ[] = {
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x06, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,06,cc */
{0xa0, 0x54, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,54,cc */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x87, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,87,cc */
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */
{0xa0, 0x30, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,30,cc */
{0xaa, 0x03, 0x0021}, /* 00,03,21,aa */
{0xaa, 0x04, 0x000c}, /* 00,04,0c,aa */
{0xaa, 0x05, 0x0002}, /* 00,05,02,aa */
{0xaa, 0x07, 0x001c}, /* 00,07,1c,aa */
{0xa0, 0x04, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,04,cc */
{}
};
static const struct usb_action pas106b_60HZ[] = {
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x06, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,06,cc */
{0xa0, 0x2e, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,2e,cc */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x71, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,71,cc */
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */
{0xa0, 0x30, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,30,cc */
{0xaa, 0x03, 0x001c}, /* 00,03,1c,aa */
{0xaa, 0x04, 0x0004}, /* 00,04,04,aa */
{0xaa, 0x05, 0x0001}, /* 00,05,01,aa */
{0xaa, 0x07, 0x00c4}, /* 00,07,c4,aa */
{0xa0, 0x04, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,04,cc */
{}
};
static const struct usb_action pas106b_NoFliker[] = {
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x06, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,06,cc */
{0xa0, 0x50, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,50,cc */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x10, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,10,cc */
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */
{0xaa, 0x03, 0x0013}, /* 00,03,13,aa */
{0xaa, 0x04, 0x0000}, /* 00,04,00,aa */
{0xaa, 0x05, 0x0001}, /* 00,05,01,aa */
{0xaa, 0x07, 0x0030}, /* 00,07,30,aa */
{0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,00,cc */
{}
};
/* from lvWIMv.inf 046d:08a2/:08aa 2007/06/03 */
static const struct usb_action pas202b_Initial[] = { /* 640x480 */
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING},
{0xa0, 0x0e, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0e,cc */
{0xa0, 0x00, ZC3XX_R002_CLOCKSELECT}, /* 00,02,00,cc */
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,e0,cc */
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc */
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */
{0xa0, 0x08, ZC3XX_R08D_COMPABILITYMODE}, /* 00,8d,08,cc */
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc */
{0xa0, 0x03, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,03,cc */
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc */
{0xa0, 0x03, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,03,cc */
{0xa0, 0x01, ZC3XX_R09B_WINHEIGHTHIGH}, /* 00,9b,01,cc */
{0xa0, 0xe6, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,e6,cc */
{0xa0, 0x02, ZC3XX_R09D_WINWIDTHHIGH}, /* 00,9d,02,cc */
{0xa0, 0x86, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,86,cc */
{0xaa, 0x02, 0x0002}, /* 00,02,04,aa --> 02 */
{0xaa, 0x07, 0x0006}, /* 00,07,06,aa */
{0xaa, 0x08, 0x0002}, /* 00,08,02,aa */
{0xaa, 0x09, 0x0006}, /* 00,09,06,aa */
{0xaa, 0x0a, 0x0001}, /* 00,0a,01,aa */
{0xaa, 0x0b, 0x0001}, /* 00,0b,01,aa */
{0xaa, 0x0c, 0x0006},
{0xaa, 0x0d, 0x0000}, /* 00,0d,00,aa */
{0xaa, 0x10, 0x0000}, /* 00,10,00,aa */
{0xaa, 0x12, 0x0005}, /* 00,12,05,aa */
{0xaa, 0x13, 0x0063}, /* 00,13,63,aa */
{0xaa, 0x15, 0x0070}, /* 00,15,70,aa */
{0xa0, 0xb7, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,b7,cc */
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, /* 01,89,06,cc */
{0xa0, 0x00, 0x01ad}, /* 01,ad,00,cc */
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */
{0xa0, 0x70, ZC3XX_R18D_YTARGET}, /* 01,8d,70,cc */
{}
};
static const struct usb_action pas202b_InitialScale[] = { /* 320x240 */
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING},
{0xa0, 0x0e, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0e,cc */
{0xa0, 0x10, ZC3XX_R002_CLOCKSELECT}, /* 00,02,10,cc */
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc */
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */
{0xa0, 0x08, ZC3XX_R08D_COMPABILITYMODE}, /* 00,8d,08,cc */
{0xa0, 0x08, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,08,cc */
{0xa0, 0x02, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,02,cc */
{0xa0, 0x08, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,08,cc */
{0xa0, 0x02, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,02,cc */
{0xa0, 0x01, ZC3XX_R09B_WINHEIGHTHIGH}, /* 00,9b,01,cc */
{0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW},
{0xa0, 0x02, ZC3XX_R09D_WINWIDTHHIGH}, /* 00,9d,02,cc */
{0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,88,cc */
{0xaa, 0x02, 0x0002}, /* 00,02,02,aa */
{0xaa, 0x07, 0x0006}, /* 00,07,06,aa */
{0xaa, 0x08, 0x0002}, /* 00,08,02,aa */
{0xaa, 0x09, 0x0006}, /* 00,09,06,aa */
{0xaa, 0x0a, 0x0001}, /* 00,0a,01,aa */
{0xaa, 0x0b, 0x0001}, /* 00,0b,01,aa */
{0xaa, 0x0c, 0x0006},
{0xaa, 0x0d, 0x0000}, /* 00,0d,00,aa */
{0xaa, 0x10, 0x0000}, /* 00,10,00,aa */
{0xaa, 0x12, 0x0005}, /* 00,12,05,aa */
{0xaa, 0x13, 0x0063}, /* 00,13,63,aa */
{0xaa, 0x15, 0x0070}, /* 00,15,70,aa */
{0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,37,cc */
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, /* 01,89,06,cc */
{0xa0, 0x00, 0x01ad}, /* 01,ad,00,cc */
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */
{0xa0, 0x70, ZC3XX_R18D_YTARGET}, /* 01,8d,70,cc */
{0xa0, 0xff, ZC3XX_R097_WINYSTARTHIGH},
{0xa0, 0xfe, ZC3XX_R098_WINYSTARTLOW},
{}
};
static const struct usb_action pas202b_50HZ[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xa0, 0x20, ZC3XX_R087_EXPTIMEMID}, /* 00,87,20,cc */
{0xa0, 0x21, ZC3XX_R088_EXPTIMELOW}, /* 00,88,21,cc */
{0xaa, 0x20, 0x0002}, /* 00,20,02,aa */
{0xaa, 0x21, 0x001b},
{0xaa, 0x03, 0x0044}, /* 00,03,44,aa */
{0xaa, 0x04, 0x0008},
{0xaa, 0x05, 0x001b},
{0xaa, 0x0e, 0x0001}, /* 00,0e,01,aa */
{0xaa, 0x0f, 0x0000}, /* 00,0f,00,aa */
{0xa0, 0x1c, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x02, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x1b, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x4d, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,4d,cc */
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x1b, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x44, ZC3XX_R01D_HSYNC_0}, /* 00,1d,44,cc */
{0xa0, 0x6f, ZC3XX_R01E_HSYNC_1}, /* 00,1e,6f,cc */
{0xa0, 0xad, ZC3XX_R01F_HSYNC_2}, /* 00,1f,ad,cc */
{0xa0, 0xeb, ZC3XX_R020_HSYNC_3}, /* 00,20,eb,cc */
{0xa0, 0x0f, ZC3XX_R087_EXPTIMEMID}, /* 00,87,0f,cc */
{0xa0, 0x0e, ZC3XX_R088_EXPTIMELOW}, /* 00,88,0e,cc */
{}
};
static const struct usb_action pas202b_50HZScale[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xa0, 0x20, ZC3XX_R087_EXPTIMEMID}, /* 00,87,20,cc */
{0xa0, 0x21, ZC3XX_R088_EXPTIMELOW}, /* 00,88,21,cc */
{0xaa, 0x20, 0x0004},
{0xaa, 0x21, 0x003d},
{0xaa, 0x03, 0x0041}, /* 00,03,41,aa */
{0xaa, 0x04, 0x0010},
{0xaa, 0x05, 0x003d},
{0xaa, 0x0e, 0x0001}, /* 00,0e,01,aa */
{0xaa, 0x0f, 0x0000}, /* 00,0f,00,aa */
{0xa0, 0x1c, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x3d, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x9b, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,9b,cc */
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x1b, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x41, ZC3XX_R01D_HSYNC_0}, /* 00,1d,41,cc */
{0xa0, 0x6f, ZC3XX_R01E_HSYNC_1}, /* 00,1e,6f,cc */
{0xa0, 0xad, ZC3XX_R01F_HSYNC_2}, /* 00,1f,ad,cc */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */
{0xa0, 0x0f, ZC3XX_R087_EXPTIMEMID}, /* 00,87,0f,cc */
{0xa0, 0x0e, ZC3XX_R088_EXPTIMELOW}, /* 00,88,0e,cc */
{}
};
static const struct usb_action pas202b_60HZ[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xa0, 0x20, ZC3XX_R087_EXPTIMEMID}, /* 00,87,20,cc */
{0xa0, 0x21, ZC3XX_R088_EXPTIMELOW}, /* 00,88,21,cc */
{0xaa, 0x20, 0x0002}, /* 00,20,02,aa */
{0xaa, 0x21, 0x0000}, /* 00,21,00,aa */
{0xaa, 0x03, 0x0045}, /* 00,03,45,aa */
{0xaa, 0x04, 0x0008}, /* 00,04,08,aa */
{0xaa, 0x05, 0x0000}, /* 00,05,00,aa */
{0xaa, 0x0e, 0x0001}, /* 00,0e,01,aa */
{0xaa, 0x0f, 0x0000}, /* 00,0f,00,aa */
{0xa0, 0x1c, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x02, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x00, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x40, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,40,cc */
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x1b, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x45, ZC3XX_R01D_HSYNC_0}, /* 00,1d,45,cc */
{0xa0, 0x8e, ZC3XX_R01E_HSYNC_1}, /* 00,1e,8e,cc */
{0xa0, 0xc1, ZC3XX_R01F_HSYNC_2}, /* 00,1f,c1,cc */
{0xa0, 0xf5, ZC3XX_R020_HSYNC_3}, /* 00,20,f5,cc */
{0xa0, 0x0f, ZC3XX_R087_EXPTIMEMID}, /* 00,87,0f,cc */
{0xa0, 0x0e, ZC3XX_R088_EXPTIMELOW}, /* 00,88,0e,cc */
{}
};
static const struct usb_action pas202b_60HZScale[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xa0, 0x20, ZC3XX_R087_EXPTIMEMID}, /* 00,87,20,cc */
{0xa0, 0x21, ZC3XX_R088_EXPTIMELOW}, /* 00,88,21,cc */
{0xaa, 0x20, 0x0004},
{0xaa, 0x21, 0x0008},
{0xaa, 0x03, 0x0042}, /* 00,03,42,aa */
{0xaa, 0x04, 0x0010},
{0xaa, 0x05, 0x0008},
{0xaa, 0x0e, 0x0001}, /* 00,0e,01,aa */
{0xaa, 0x0f, 0x0000}, /* 00,0f,00,aa */
{0xa0, 0x1c, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x08, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x81, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,81,cc */
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x1b, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x42, ZC3XX_R01D_HSYNC_0}, /* 00,1d,42,cc */
{0xa0, 0x6f, ZC3XX_R01E_HSYNC_1}, /* 00,1e,6f,cc */
{0xa0, 0xaf, ZC3XX_R01F_HSYNC_2}, /* 00,1f,af,cc */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */
{0xa0, 0x0f, ZC3XX_R087_EXPTIMEMID}, /* 00,87,0f,cc */
{0xa0, 0x0e, ZC3XX_R088_EXPTIMELOW}, /* 00,88,0e,cc */
{}
};
static const struct usb_action pas202b_NoFliker[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xa0, 0x20, ZC3XX_R087_EXPTIMEMID}, /* 00,87,20,cc */
{0xa0, 0x21, ZC3XX_R088_EXPTIMELOW}, /* 00,88,21,cc */
{0xaa, 0x20, 0x0002}, /* 00,20,02,aa */
{0xaa, 0x21, 0x0006},
{0xaa, 0x03, 0x0040}, /* 00,03,40,aa */
{0xaa, 0x04, 0x0008}, /* 00,04,08,aa */
{0xaa, 0x05, 0x0006},
{0xaa, 0x0e, 0x0001}, /* 00,0e,01,aa */
{0xaa, 0x0f, 0x0000}, /* 00,0f,00,aa */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x02, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x06, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x01, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */
{0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,00,cc */
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x40, ZC3XX_R01D_HSYNC_0}, /* 00,1d,40,cc */
{0xa0, 0x60, ZC3XX_R01E_HSYNC_1}, /* 00,1e,60,cc */
{0xa0, 0x90, ZC3XX_R01F_HSYNC_2}, /* 00,1f,90,cc */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */
{0xa0, 0x0f, ZC3XX_R087_EXPTIMEMID}, /* 00,87,0f,cc */
{0xa0, 0x0e, ZC3XX_R088_EXPTIMELOW}, /* 00,88,0e,cc */
{}
};
static const struct usb_action pas202b_NoFlikerScale[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xa0, 0x20, ZC3XX_R087_EXPTIMEMID}, /* 00,87,20,cc */
{0xa0, 0x21, ZC3XX_R088_EXPTIMELOW}, /* 00,88,21,cc */
{0xaa, 0x20, 0x0004},
{0xaa, 0x21, 0x000c},
{0xaa, 0x03, 0x0040}, /* 00,03,40,aa */
{0xaa, 0x04, 0x0010},
{0xaa, 0x05, 0x000c},
{0xaa, 0x0e, 0x0001}, /* 00,0e,01,aa */
{0xaa, 0x0f, 0x0000}, /* 00,0f,00,aa */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x0c, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x02, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,02,cc */
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */
{0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,00,cc */
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x40, ZC3XX_R01D_HSYNC_0}, /* 00,1d,40,cc */
{0xa0, 0x60, ZC3XX_R01E_HSYNC_1}, /* 00,1e,60,cc */
{0xa0, 0x90, ZC3XX_R01F_HSYNC_2}, /* 00,1f,90,cc */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */
{0xa0, 0x0f, ZC3XX_R087_EXPTIMEMID}, /* 00,87,0f,cc */
{0xa0, 0x0e, ZC3XX_R088_EXPTIMELOW}, /* 00,88,0e,cc */
{}
};
/* mt9v111 (mi0360soc) and pb0330 from vm30x.inf 0ac8:301b 07/02/13 */
static const struct usb_action mt9v111_1_Initial[] = { /* 640x480 */
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING},
{0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT},
{0xa0, 0x00, ZC3XX_R002_CLOCKSELECT},
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW},
{0xa0, 0xdc, ZC3XX_R08B_I2CDEVICEADDR},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x07, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW},
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW},
{0xa0, 0xdc, ZC3XX_R08B_I2CDEVICEADDR},
{0xdd, 0x00, 0x0200},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xaa, 0x01, 0x0001},
{0xaa, 0x06, 0x0000},
{0xaa, 0x08, 0x0483},
{0xaa, 0x01, 0x0004},
{0xaa, 0x08, 0x0006},
{0xaa, 0x02, 0x0011},
{0xaa, 0x03, 0x01e5}, /*jfm: was 01e7*/
{0xaa, 0x04, 0x0285}, /*jfm: was 0287*/
{0xaa, 0x07, 0x3002},
{0xaa, 0x20, 0x5100},
{0xaa, 0x35, 0x507f},
{0xaa, 0x30, 0x0005},
{0xaa, 0x31, 0x0000},
{0xaa, 0x58, 0x0078},
{0xaa, 0x62, 0x0411},
{0xaa, 0x2b, 0x007f},
{0xaa, 0x2c, 0x007f}, /*jfm: was 0030*/
{0xaa, 0x2d, 0x007f}, /*jfm: was 0030*/
{0xaa, 0x2e, 0x007f}, /*jfm: was 0030*/
{0xa0, 0x10, ZC3XX_R087_EXPTIMEMID},
{0xa0, 0xb7, ZC3XX_R101_SENSORCORRECTION},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
{0xa0, 0x09, 0x01ad}, /*jfm: was 00*/
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
{0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN},
{0xa0, 0x6c, ZC3XX_R18D_YTARGET},
{0xa0, 0x61, ZC3XX_R116_RGAIN},
{0xa0, 0x65, ZC3XX_R118_BGAIN},
{}
};
static const struct usb_action mt9v111_1_InitialScale[] = { /* 320x240 */
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING},
{0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT},
{0xa0, 0x10, ZC3XX_R002_CLOCKSELECT},
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW},
{0xa0, 0xdc, ZC3XX_R08B_I2CDEVICEADDR},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x07, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW},
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW},
{0xa0, 0xdc, ZC3XX_R08B_I2CDEVICEADDR},
{0xdd, 0x00, 0x0200},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xaa, 0x01, 0x0001},
{0xaa, 0x06, 0x0000},
{0xaa, 0x08, 0x0483},
{0xaa, 0x01, 0x0004},
{0xaa, 0x08, 0x0006},
{0xaa, 0x02, 0x0011},
{0xaa, 0x03, 0x01e7},
{0xaa, 0x04, 0x0287},
{0xaa, 0x07, 0x3002},
{0xaa, 0x20, 0x5100},
{0xaa, 0x35, 0x007f}, /*jfm: was 0050*/
{0xaa, 0x30, 0x0005},
{0xaa, 0x31, 0x0000},
{0xaa, 0x58, 0x0078},
{0xaa, 0x62, 0x0411},
{0xaa, 0x2b, 0x007f}, /*jfm: was 28*/
{0xaa, 0x2c, 0x007f}, /*jfm: was 30*/
{0xaa, 0x2d, 0x007f}, /*jfm: was 30*/
{0xaa, 0x2e, 0x007f}, /*jfm: was 28*/
{0xa0, 0x10, ZC3XX_R087_EXPTIMEMID},
{0xa0, 0xb7, ZC3XX_R101_SENSORCORRECTION},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
{0xa0, 0x09, 0x01ad}, /*jfm: was 00*/
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
{0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN},
{0xa0, 0x6c, ZC3XX_R18D_YTARGET},
{0xa0, 0x61, ZC3XX_R116_RGAIN},
{0xa0, 0x65, ZC3XX_R118_BGAIN},
{}
};
static const struct usb_action mt9v111_1_AE50HZ[] = {
{0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xbb, 0x00, 0x0562},
{0xbb, 0x01, 0x09aa},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x03, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x9b, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x47, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x66, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x62, ZC3XX_R01D_HSYNC_0},
{0xa0, 0x90, ZC3XX_R01E_HSYNC_1},
{0xa0, 0xc8, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xff, ZC3XX_R020_HSYNC_3},
{0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{}
};
static const struct usb_action mt9v111_1_AE50HZScale[] = {
{0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xbb, 0x00, 0x0509},
{0xbb, 0x01, 0x0934},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xd2, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x9a, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x66, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0xd7, ZC3XX_R01D_HSYNC_0},
{0xa0, 0xf4, ZC3XX_R01E_HSYNC_1},
{0xa0, 0xf9, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xff, ZC3XX_R020_HSYNC_3},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{}
};
static const struct usb_action mt9v111_1_AE60HZ[] = {
{0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xaa, 0x05, 0x003d},
{0xaa, 0x09, 0x016e},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xdd, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x3d, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x62, ZC3XX_R01D_HSYNC_0},
{0xa0, 0x90, ZC3XX_R01E_HSYNC_1},
{0xa0, 0xc8, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xff, ZC3XX_R020_HSYNC_3},
{0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{}
};
static const struct usb_action mt9v111_1_AE60HZScale[] = {
{0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xbb, 0x00, 0x0509},
{0xbb, 0x01, 0x0983},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x8f, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x81, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0xd7, ZC3XX_R01D_HSYNC_0},
{0xa0, 0xf4, ZC3XX_R01E_HSYNC_1},
{0xa0, 0xf9, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xff, ZC3XX_R020_HSYNC_3},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{}
};
static const struct usb_action mt9v111_1_AENoFliker[] = {
{0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xbb, 0x00, 0x0509},
{0xbb, 0x01, 0x0960},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xf0, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x04, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x09, ZC3XX_R01D_HSYNC_0},
{0xa0, 0x40, ZC3XX_R01E_HSYNC_1},
{0xa0, 0x90, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xe0, ZC3XX_R020_HSYNC_3},
{0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{}
};
static const struct usb_action mt9v111_1_AENoFlikerScale[] = {
{0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xbb, 0x00, 0x0534},
{0xbb, 0x02, 0x0960},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xf0, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x04, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x34, ZC3XX_R01D_HSYNC_0},
{0xa0, 0x60, ZC3XX_R01E_HSYNC_1},
{0xa0, 0x90, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xe0, ZC3XX_R020_HSYNC_3},
{0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{}
};
/* from usbvm303.inf 0ac8:303b 07/03/25 (3 - tas5130c) */
static const struct usb_action mt9v111_3_Initial[] = {
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING},
{0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT},
{0xa0, 0x00, ZC3XX_R002_CLOCKSELECT},
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW},
{0xa0, 0xdc, ZC3XX_R08B_I2CDEVICEADDR},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x07, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW},
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW},
{0xa0, 0xdc, ZC3XX_R08B_I2CDEVICEADDR},
{0xdd, 0x00, 0x0200},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xaa, 0x01, 0x0001}, /* select IFP/SOC registers */
{0xaa, 0x06, 0x0000}, /* operating mode control */
{0xaa, 0x08, 0x0483}, /* output format control */
/* H red first, V red or blue first,
* raw Bayer, auto flicker */
{0xaa, 0x01, 0x0004}, /* select sensor core registers */
{0xaa, 0x08, 0x0006}, /* row start */
{0xaa, 0x02, 0x0011}, /* column start */
{0xaa, 0x03, 0x01e5}, /* window height - 1 */
{0xaa, 0x04, 0x0285}, /* window width - 1 */
{0xaa, 0x07, 0x3002}, /* output control */
{0xaa, 0x20, 0x1100}, /* read mode: bits 8 & 12 (?) */
{0xaa, 0x35, 0x007f}, /* global gain */
{0xaa, 0x30, 0x0005},
{0xaa, 0x31, 0x0000},
{0xaa, 0x58, 0x0078},
{0xaa, 0x62, 0x0411},
{0xaa, 0x2b, 0x007f}, /* green1 gain */
{0xaa, 0x2c, 0x007f}, /* blue gain */
{0xaa, 0x2d, 0x007f}, /* red gain */
{0xaa, 0x2e, 0x007f}, /* green2 gain */
{0xa0, 0x10, ZC3XX_R087_EXPTIMEMID},
{0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
{0xa0, 0x00, 0x01ad},
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
{0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN},
{0xa0, 0x80, ZC3XX_R18D_YTARGET},
{0xa0, 0x61, ZC3XX_R116_RGAIN},
{0xa0, 0x65, ZC3XX_R118_BGAIN},
{}
};
static const struct usb_action mt9v111_3_InitialScale[] = {
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING},
{0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT},
{0xa0, 0x10, ZC3XX_R002_CLOCKSELECT},
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW},
{0xa0, 0xdc, ZC3XX_R08B_I2CDEVICEADDR},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x07, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW},
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW},
{0xa0, 0xdc, ZC3XX_R08B_I2CDEVICEADDR},
{0xdd, 0x00, 0x0200},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xaa, 0x01, 0x0001},
{0xaa, 0x06, 0x0000},
{0xaa, 0x08, 0x0483},
{0xaa, 0x01, 0x0004},
{0xaa, 0x08, 0x0006},
{0xaa, 0x02, 0x0011},
{0xaa, 0x03, 0x01e7},
{0xaa, 0x04, 0x0287},
{0xaa, 0x07, 0x3002},
{0xaa, 0x20, 0x1100},
{0xaa, 0x35, 0x007f},
{0xaa, 0x30, 0x0005},
{0xaa, 0x31, 0x0000},
{0xaa, 0x58, 0x0078},
{0xaa, 0x62, 0x0411},
{0xaa, 0x2b, 0x007f},
{0xaa, 0x2c, 0x007f},
{0xaa, 0x2d, 0x007f},
{0xaa, 0x2e, 0x007f},
{0xa0, 0x10, ZC3XX_R087_EXPTIMEMID},
{0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
{0xa0, 0x00, 0x01ad},
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
{0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN},
{0xa0, 0x80, ZC3XX_R18D_YTARGET},
{0xa0, 0x61, ZC3XX_R116_RGAIN},
{0xa0, 0x65, ZC3XX_R118_BGAIN},
{}
};
static const struct usb_action mt9v111_3_AE50HZ[] = {
{0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xaa, 0x05, 0x0009}, /* horizontal blanking */
{0xaa, 0x09, 0x01ce}, /* shutter width */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xd2, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x9a, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0xd7, ZC3XX_R01D_HSYNC_0},
{0xa0, 0xf4, ZC3XX_R01E_HSYNC_1},
{0xa0, 0xf9, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xff, ZC3XX_R020_HSYNC_3},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{}
};
static const struct usb_action mt9v111_3_AE50HZScale[] = {
{0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xaa, 0x05, 0x0009},
{0xaa, 0x09, 0x01ce},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xd2, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x9a, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0xd7, ZC3XX_R01D_HSYNC_0},
{0xa0, 0xf4, ZC3XX_R01E_HSYNC_1},
{0xa0, 0xf9, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xff, ZC3XX_R020_HSYNC_3},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{}
};
static const struct usb_action mt9v111_3_AE60HZ[] = {
{0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xaa, 0x05, 0x0009},
{0xaa, 0x09, 0x0083},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x8f, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x81, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0xd7, ZC3XX_R01D_HSYNC_0},
{0xa0, 0xf4, ZC3XX_R01E_HSYNC_1},
{0xa0, 0xf9, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xff, ZC3XX_R020_HSYNC_3},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{}
};
static const struct usb_action mt9v111_3_AE60HZScale[] = {
{0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xaa, 0x05, 0x0009},
{0xaa, 0x09, 0x0083},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x8f, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x81, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0xd7, ZC3XX_R01D_HSYNC_0},
{0xa0, 0xf4, ZC3XX_R01E_HSYNC_1},
{0xa0, 0xf9, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xff, ZC3XX_R020_HSYNC_3},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{}
};
static const struct usb_action mt9v111_3_AENoFliker[] = {
{0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xaa, 0x05, 0x0034},
{0xaa, 0x09, 0x0260},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xf0, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x04, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x34, ZC3XX_R01D_HSYNC_0},
{0xa0, 0x60, ZC3XX_R01E_HSYNC_1},
{0xa0, 0x90, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xe0, ZC3XX_R020_HSYNC_3},
{0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{}
};
static const struct usb_action mt9v111_3_AENoFlikerScale[] = {
{0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE},
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xaa, 0x05, 0x0034},
{0xaa, 0x09, 0x0260},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xf0, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x04, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x34, ZC3XX_R01D_HSYNC_0},
{0xa0, 0x60, ZC3XX_R01E_HSYNC_1},
{0xa0, 0x90, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xe0, ZC3XX_R020_HSYNC_3},
{0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN},
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE},
{}
};
static const struct usb_action pb0330_Initial[] = { /* 640x480 */
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00 */
{0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT},
{0xa0, 0x00, ZC3XX_R002_CLOCKSELECT},
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x07, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW},
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW},
{0xdd, 0x00, 0x0200},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xaa, 0x01, 0x0006},
{0xaa, 0x02, 0x0011},
{0xaa, 0x03, 0x01e5}, /*jfm: was 1e7*/
{0xaa, 0x04, 0x0285}, /*jfm: was 0287*/
{0xaa, 0x06, 0x0003},
{0xaa, 0x07, 0x3002},
{0xaa, 0x20, 0x1100},
{0xaa, 0x2f, 0xf7b0},
{0xaa, 0x30, 0x0005},
{0xaa, 0x31, 0x0000},
{0xaa, 0x34, 0x0100},
{0xaa, 0x35, 0x0060},
{0xaa, 0x3d, 0x068f},
{0xaa, 0x40, 0x01e0},
{0xaa, 0x58, 0x0078},
{0xaa, 0x62, 0x0411},
{0xa0, 0x10, ZC3XX_R087_EXPTIMEMID},
{0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
{0xa0, 0x09, 0x01ad}, /*jfm: was 00 */
{0xa0, 0x15, 0x01ae},
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
{0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN},
{0xa0, 0x78, ZC3XX_R18D_YTARGET}, /*jfm: was 6c*/
{}
};
static const struct usb_action pb0330_InitialScale[] = { /* 320x240 */
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00 */
{0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT},
{0xa0, 0x10, ZC3XX_R002_CLOCKSELECT},
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x07, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW},
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW},
{0xdd, 0x00, 0x0200},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xaa, 0x01, 0x0006},
{0xaa, 0x02, 0x0011},
{0xaa, 0x03, 0x01e7},
{0xaa, 0x04, 0x0287},
{0xaa, 0x06, 0x0003},
{0xaa, 0x07, 0x3002},
{0xaa, 0x20, 0x1100},
{0xaa, 0x2f, 0xf7b0},
{0xaa, 0x30, 0x0005},
{0xaa, 0x31, 0x0000},
{0xaa, 0x34, 0x0100},
{0xaa, 0x35, 0x0060},
{0xaa, 0x3d, 0x068f},
{0xaa, 0x40, 0x01e0},
{0xaa, 0x58, 0x0078},
{0xaa, 0x62, 0x0411},
{0xa0, 0x10, ZC3XX_R087_EXPTIMEMID},
{0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
{0xa0, 0x09, 0x01ad},
{0xa0, 0x15, 0x01ae},
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
{0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN},
{0xa0, 0x78, ZC3XX_R18D_YTARGET}, /*jfm: was 6c*/
{}
};
static const struct usb_action pb0330_50HZ[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xbb, 0x00, 0x055c},
{0xbb, 0x01, 0x09aa},
{0xbb, 0x00, 0x1001},
{0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xc4, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x47, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x1a, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x66, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x5c, ZC3XX_R01D_HSYNC_0},
{0xa0, 0x90, ZC3XX_R01E_HSYNC_1},
{0xa0, 0xc8, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xff, ZC3XX_R020_HSYNC_3},
{}
};
static const struct usb_action pb0330_50HZScale[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xbb, 0x00, 0x0566},
{0xbb, 0x02, 0x09b2},
{0xbb, 0x00, 0x1002},
{0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x8c, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x8a, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x1a, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x66, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0xd7, ZC3XX_R01D_HSYNC_0},
{0xa0, 0xf0, ZC3XX_R01E_HSYNC_1},
{0xa0, 0xf8, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xff, ZC3XX_R020_HSYNC_3},
{}
};
static const struct usb_action pb0330_60HZ[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xbb, 0x00, 0x0535},
{0xbb, 0x01, 0x0974},
{0xbb, 0x00, 0x1001},
{0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xfe, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x3e, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x1a, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x66, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x35, ZC3XX_R01D_HSYNC_0},
{0xa0, 0x50, ZC3XX_R01E_HSYNC_1},
{0xa0, 0x90, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xd0, ZC3XX_R020_HSYNC_3},
{}
};
static const struct usb_action pb0330_60HZScale[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xbb, 0x00, 0x0535},
{0xbb, 0x02, 0x096c},
{0xbb, 0x00, 0x1002},
{0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xc0, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x7c, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x1a, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x66, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x35, ZC3XX_R01D_HSYNC_0},
{0xa0, 0x50, ZC3XX_R01E_HSYNC_1},
{0xa0, 0x90, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xd0, ZC3XX_R020_HSYNC_3},
{}
};
static const struct usb_action pb0330_NoFliker[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xbb, 0x00, 0x0509},
{0xbb, 0x02, 0x0940},
{0xbb, 0x00, 0x1002},
{0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xf0, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x01, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x09, ZC3XX_R01D_HSYNC_0},
{0xa0, 0x40, ZC3XX_R01E_HSYNC_1},
{0xa0, 0x90, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xe0, ZC3XX_R020_HSYNC_3},
{}
};
static const struct usb_action pb0330_NoFlikerScale[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS},
{0xbb, 0x00, 0x0535},
{0xbb, 0x01, 0x0980},
{0xbb, 0x00, 0x1001},
{0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN},
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH},
{0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xf0, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x01, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x10, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0x35, ZC3XX_R01D_HSYNC_0},
{0xa0, 0x60, ZC3XX_R01E_HSYNC_1},
{0xa0, 0x90, ZC3XX_R01F_HSYNC_2},
{0xa0, 0xe0, ZC3XX_R020_HSYNC_3},
{}
};
/* from oem9.inf */
static const struct usb_action po2030_Initial[] = { /* 640x480 */
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */
{0xa0, 0x04, ZC3XX_R002_CLOCKSELECT}, /* 00,02,04,cc */
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */
{0xa0, 0x04, ZC3XX_R080_HBLANKHIGH}, /* 00,80,04,cc */
{0xa0, 0x05, ZC3XX_R081_HBLANKLOW}, /* 00,81,05,cc */
{0xa0, 0x16, ZC3XX_R083_RGAINADDR}, /* 00,83,16,cc */
{0xa0, 0x18, ZC3XX_R085_BGAINADDR}, /* 00,85,18,cc */
{0xa0, 0x1a, ZC3XX_R086_EXPTIMEHIGH}, /* 00,86,1a,cc */
{0xa0, 0x1b, ZC3XX_R087_EXPTIMEMID}, /* 00,87,1b,cc */
{0xa0, 0x1c, ZC3XX_R088_EXPTIMELOW}, /* 00,88,1c,cc */
{0xa0, 0xee, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,ee,cc */
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00,08,03,cc */
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc */
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,e0,cc */
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,42,cc */
{0xaa, 0x8d, 0x0008}, /* 00,8d,08,aa */
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc */
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc */
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc */
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc */
{0xa0, 0xe6, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,e6,cc */
{0xa0, 0x86, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,86,cc */
{0xaa, 0x09, 0x00ce}, /* 00,09,ce,aa */
{0xaa, 0x0b, 0x0005}, /* 00,0b,05,aa */
{0xaa, 0x0d, 0x0054}, /* 00,0d,54,aa */
{0xaa, 0x0f, 0x00eb}, /* 00,0f,eb,aa */
{0xaa, 0x87, 0x0000}, /* 00,87,00,aa */
{0xaa, 0x88, 0x0004}, /* 00,88,04,aa */
{0xaa, 0x89, 0x0000}, /* 00,89,00,aa */
{0xaa, 0x8a, 0x0005}, /* 00,8a,05,aa */
{0xaa, 0x13, 0x0003}, /* 00,13,03,aa */
{0xaa, 0x16, 0x0040}, /* 00,16,40,aa */
{0xaa, 0x18, 0x0040}, /* 00,18,40,aa */
{0xaa, 0x1d, 0x0002}, /* 00,1d,02,aa */
{0xaa, 0x29, 0x00e8}, /* 00,29,e8,aa */
{0xaa, 0x45, 0x0045}, /* 00,45,45,aa */
{0xaa, 0x50, 0x00ed}, /* 00,50,ed,aa */
{0xaa, 0x51, 0x0025}, /* 00,51,25,aa */
{0xaa, 0x52, 0x0042}, /* 00,52,42,aa */
{0xaa, 0x53, 0x002f}, /* 00,53,2f,aa */
{0xaa, 0x79, 0x0025}, /* 00,79,25,aa */
{0xaa, 0x7b, 0x0000}, /* 00,7b,00,aa */
{0xaa, 0x7e, 0x0025}, /* 00,7e,25,aa */
{0xaa, 0x7f, 0x0025}, /* 00,7f,25,aa */
{0xaa, 0x21, 0x0000}, /* 00,21,00,aa */
{0xaa, 0x33, 0x0036}, /* 00,33,36,aa */
{0xaa, 0x36, 0x0060}, /* 00,36,60,aa */
{0xaa, 0x37, 0x0008}, /* 00,37,08,aa */
{0xaa, 0x3b, 0x0031}, /* 00,3b,31,aa */
{0xaa, 0x44, 0x000f}, /* 00,44,0f,aa */
{0xaa, 0x58, 0x0002}, /* 00,58,02,aa */
{0xaa, 0x66, 0x00c0}, /* 00,66,c0,aa */
{0xaa, 0x67, 0x0044}, /* 00,67,44,aa */
{0xaa, 0x6b, 0x00a0}, /* 00,6b,a0,aa */
{0xaa, 0x6c, 0x0054}, /* 00,6c,54,aa */
{0xaa, 0xd6, 0x0007}, /* 00,d6,07,aa */
{0xa0, 0xf7, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,f7,cc */
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, /* 01,89,06,cc */
{0xa0, 0x00, 0x01ad}, /* 01,ad,00,cc */
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */
{0xa0, 0x7a, ZC3XX_R116_RGAIN}, /* 01,16,7a,cc */
{0xa0, 0x4a, ZC3XX_R118_BGAIN}, /* 01,18,4a,cc */
{}
};
/* from oem9.inf */
static const struct usb_action po2030_InitialScale[] = { /* 320x240 */
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */
{0xa0, 0x10, ZC3XX_R002_CLOCKSELECT}, /* 00,02,10,cc */
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */
{0xa0, 0x04, ZC3XX_R080_HBLANKHIGH}, /* 00,80,04,cc */
{0xa0, 0x05, ZC3XX_R081_HBLANKLOW}, /* 00,81,05,cc */
{0xa0, 0x16, ZC3XX_R083_RGAINADDR}, /* 00,83,16,cc */
{0xa0, 0x18, ZC3XX_R085_BGAINADDR}, /* 00,85,18,cc */
{0xa0, 0x1a, ZC3XX_R086_EXPTIMEHIGH}, /* 00,86,1a,cc */
{0xa0, 0x1b, ZC3XX_R087_EXPTIMEMID}, /* 00,87,1b,cc */
{0xa0, 0x1c, ZC3XX_R088_EXPTIMELOW}, /* 00,88,1c,cc */
{0xa0, 0xee, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,ee,cc */
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00,08,03,cc */
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc */
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,e0,cc */
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,42,cc */
{0xaa, 0x8d, 0x0008}, /* 00,8d,08,aa */
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc */
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc */
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc */
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc */
{0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,e8,cc */
{0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,88,cc */
{0xaa, 0x09, 0x00cc}, /* 00,09,cc,aa */
{0xaa, 0x0b, 0x0005}, /* 00,0b,05,aa */
{0xaa, 0x0d, 0x0058}, /* 00,0d,58,aa */
{0xaa, 0x0f, 0x00ed}, /* 00,0f,ed,aa */
{0xaa, 0x87, 0x0000}, /* 00,87,00,aa */
{0xaa, 0x88, 0x0004}, /* 00,88,04,aa */
{0xaa, 0x89, 0x0000}, /* 00,89,00,aa */
{0xaa, 0x8a, 0x0005}, /* 00,8a,05,aa */
{0xaa, 0x13, 0x0003}, /* 00,13,03,aa */
{0xaa, 0x16, 0x0040}, /* 00,16,40,aa */
{0xaa, 0x18, 0x0040}, /* 00,18,40,aa */
{0xaa, 0x1d, 0x0002}, /* 00,1d,02,aa */
{0xaa, 0x29, 0x00e8}, /* 00,29,e8,aa */
{0xaa, 0x45, 0x0045}, /* 00,45,45,aa */
{0xaa, 0x50, 0x00ed}, /* 00,50,ed,aa */
{0xaa, 0x51, 0x0025}, /* 00,51,25,aa */
{0xaa, 0x52, 0x0042}, /* 00,52,42,aa */
{0xaa, 0x53, 0x002f}, /* 00,53,2f,aa */
{0xaa, 0x79, 0x0025}, /* 00,79,25,aa */
{0xaa, 0x7b, 0x0000}, /* 00,7b,00,aa */
{0xaa, 0x7e, 0x0025}, /* 00,7e,25,aa */
{0xaa, 0x7f, 0x0025}, /* 00,7f,25,aa */
{0xaa, 0x21, 0x0000}, /* 00,21,00,aa */
{0xaa, 0x33, 0x0036}, /* 00,33,36,aa */
{0xaa, 0x36, 0x0060}, /* 00,36,60,aa */
{0xaa, 0x37, 0x0008}, /* 00,37,08,aa */
{0xaa, 0x3b, 0x0031}, /* 00,3b,31,aa */
{0xaa, 0x44, 0x000f}, /* 00,44,0f,aa */
{0xaa, 0x58, 0x0002}, /* 00,58,02,aa */
{0xaa, 0x66, 0x00c0}, /* 00,66,c0,aa */
{0xaa, 0x67, 0x0044}, /* 00,67,44,aa */
{0xaa, 0x6b, 0x00a0}, /* 00,6b,a0,aa */
{0xaa, 0x6c, 0x0054}, /* 00,6c,54,aa */
{0xaa, 0xd6, 0x0007}, /* 00,d6,07,aa */
{0xa0, 0xf7, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,f7,cc */
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, /* 01,89,06,cc */
{0xa0, 0x00, 0x01ad}, /* 01,ad,00,cc */
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */
{0xa0, 0x7a, ZC3XX_R116_RGAIN}, /* 01,16,7a,cc */
{0xa0, 0x4a, ZC3XX_R118_BGAIN}, /* 01,18,4a,cc */
{}
};
static const struct usb_action po2030_50HZ[] = {
{0xaa, 0x8d, 0x0008}, /* 00,8d,08,aa */
{0xaa, 0x1a, 0x0001}, /* 00,1a,01,aa */
{0xaa, 0x1b, 0x000a}, /* 00,1b,0a,aa */
{0xaa, 0x1c, 0x00b0}, /* 00,1c,b0,aa */
{0xa0, 0x05, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,05,cc */
{0xa0, 0x35, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,35,cc */
{0xa0, 0x70, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,70,cc */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x85, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,85,cc */
{0xa0, 0x58, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,58,cc */
{0xa0, 0x0c, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0c,cc */
{0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,18,cc */
{0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN}, /* 01,a8,60,cc */
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,10,cc */
{0xa0, 0x22, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,22,cc */
{0xa0, 0x88, ZC3XX_R18D_YTARGET}, /* 01,8d,88,cc */
{0xa0, 0x58, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,58,cc */
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,42,cc */
{}
};
static const struct usb_action po2030_60HZ[] = {
{0xaa, 0x8d, 0x0008}, /* 00,8d,08,aa */
{0xaa, 0x1a, 0x0000}, /* 00,1a,00,aa */
{0xaa, 0x1b, 0x00de}, /* 00,1b,de,aa */
{0xaa, 0x1c, 0x0040}, /* 00,1c,40,aa */
{0xa0, 0x08, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,08,cc */
{0xa0, 0xae, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,ae,cc */
{0xa0, 0x80, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,80,cc */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x6f, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,6f,cc */
{0xa0, 0x20, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,20,cc */
{0xa0, 0x0c, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0c,cc */
{0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,18,cc */
{0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN}, /* 01,a8,60,cc */
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,10,cc */
{0xa0, 0x22, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,22,cc */
{0xa0, 0x88, ZC3XX_R18D_YTARGET}, /* 01,8d,88,cc */
/* win: 01,8d,80 */
{0xa0, 0x58, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,58,cc */
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,42,cc */
{}
};
static const struct usb_action po2030_NoFliker[] = {
{0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,02,cc */
{0xaa, 0x8d, 0x000d}, /* 00,8d,0d,aa */
{0xaa, 0x1a, 0x0000}, /* 00,1a,00,aa */
{0xaa, 0x1b, 0x0002}, /* 00,1b,02,aa */
{0xaa, 0x1c, 0x0078}, /* 00,1c,78,aa */
{0xaa, 0x46, 0x0000}, /* 00,46,00,aa */
{0xaa, 0x15, 0x0000}, /* 00,15,00,aa */
{}
};
static const struct usb_action tas5130c_InitialScale[] = { /* 320x240 */
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL},
{0xa0, 0x50, ZC3XX_R002_CLOCKSELECT},
{0xa0, 0x03, ZC3XX_R008_CLOCKSETTING},
{0xa0, 0x02, ZC3XX_R010_CMOSSENSORSELECT},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x00, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW},
{0xa0, 0x04, ZC3XX_R098_WINYSTARTLOW},
{0xa0, 0x0f, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x04, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x0f, ZC3XX_R11C_FIRSTXLOW},
{0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW},
{0xa0, 0x02, ZC3XX_R09D_WINWIDTHHIGH},
{0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW},
{0xa0, 0x06, ZC3XX_R08D_COMPABILITYMODE},
{0xa0, 0xf7, ZC3XX_R101_SENSORCORRECTION},
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
{0xa0, 0x70, ZC3XX_R18D_YTARGET},
{0xa0, 0x50, ZC3XX_R1A8_DIGITALGAIN},
{0xa0, 0x00, 0x01ad},
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
{0xa0, 0x07, ZC3XX_R0A5_EXPOSUREGAIN},
{0xa0, 0x02, ZC3XX_R0A6_EXPOSUREBLACKLVL},
{}
};
static const struct usb_action tas5130c_Initial[] = { /* 640x480 */
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL},
{0xa0, 0x40, ZC3XX_R002_CLOCKSELECT},
{0xa0, 0x00, ZC3XX_R008_CLOCKSETTING},
{0xa0, 0x02, ZC3XX_R010_CMOSSENSORSELECT},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x00, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING},
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC},
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH},
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW},
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH},
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW},
{0xa0, 0x05, ZC3XX_R098_WINYSTARTLOW},
{0xa0, 0x0f, ZC3XX_R09A_WINXSTARTLOW},
{0xa0, 0x05, ZC3XX_R11A_FIRSTYLOW},
{0xa0, 0x0f, ZC3XX_R11C_FIRSTXLOW},
{0xa0, 0xe6, ZC3XX_R09C_WINHEIGHTLOW},
{0xa0, 0x02, ZC3XX_R09D_WINWIDTHHIGH},
{0xa0, 0x86, ZC3XX_R09E_WINWIDTHLOW},
{0xa0, 0x06, ZC3XX_R08D_COMPABILITYMODE},
{0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION},
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE},
{0xa0, 0x06, ZC3XX_R189_AWBSTATUS},
{0xa0, 0x70, ZC3XX_R18D_YTARGET},
{0xa0, 0x50, ZC3XX_R1A8_DIGITALGAIN},
{0xa0, 0x00, 0x01ad},
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE},
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05},
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE},
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS},
{0xa0, 0x07, ZC3XX_R0A5_EXPOSUREGAIN},
{0xa0, 0x02, ZC3XX_R0A6_EXPOSUREBLACKLVL},
{}
};
static const struct usb_action tas5130c_50HZ[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xaa, 0xa3, 0x0001}, /* 00,a3,01,aa */
{0xaa, 0xa4, 0x0063}, /* 00,a4,63,aa */
{0xa0, 0x01, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,01,cc */
{0xa0, 0x63, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,63,cc */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xfe, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x47, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,47,cc */
{0xa0, 0x0c, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x08, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0xd3, ZC3XX_R01D_HSYNC_0}, /* 00,1d,d3,cc */
{0xa0, 0xda, ZC3XX_R01E_HSYNC_1}, /* 00,1e,da,cc */
{0xa0, 0xea, ZC3XX_R01F_HSYNC_2}, /* 00,1f,ea,cc */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */
{0xa0, 0x03, ZC3XX_R09F_MAXXHIGH}, /* 00,9f,03,cc */
{0xa0, 0x4c, ZC3XX_R0A0_MAXXLOW},
{0xa0, 0x50, ZC3XX_R11D_GLOBALGAIN},
{}
};
static const struct usb_action tas5130c_50HZScale[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xaa, 0xa3, 0x0001}, /* 00,a3,01,aa */
{0xaa, 0xa4, 0x0077}, /* 00,a4,77,aa */
{0xa0, 0x01, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,01,cc */
{0xa0, 0x77, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,77,cc */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xd0, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x7d, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,7d,cc */
{0xa0, 0x0c, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x08, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0xf0, ZC3XX_R01D_HSYNC_0}, /* 00,1d,f0,cc */
{0xa0, 0xf4, ZC3XX_R01E_HSYNC_1}, /* 00,1e,f4,cc */
{0xa0, 0xf8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,f8,cc */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */
{0xa0, 0x03, ZC3XX_R09F_MAXXHIGH}, /* 00,9f,03,cc */
{0xa0, 0xc0, ZC3XX_R0A0_MAXXLOW},
{0xa0, 0x50, ZC3XX_R11D_GLOBALGAIN},
{}
};
static const struct usb_action tas5130c_60HZ[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xaa, 0xa3, 0x0001}, /* 00,a3,01,aa */
{0xaa, 0xa4, 0x0036}, /* 00,a4,36,aa */
{0xa0, 0x01, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,01,cc */
{0xa0, 0x36, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,36,cc */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x05, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x54, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x3e, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,3e,cc */
{0xa0, 0x0c, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x08, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0xca, ZC3XX_R01D_HSYNC_0}, /* 00,1d,ca,cc */
{0xa0, 0xd0, ZC3XX_R01E_HSYNC_1}, /* 00,1e,d0,cc */
{0xa0, 0xe0, ZC3XX_R01F_HSYNC_2}, /* 00,1f,e0,cc */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */
{0xa0, 0x03, ZC3XX_R09F_MAXXHIGH}, /* 00,9f,03,cc */
{0xa0, 0x28, ZC3XX_R0A0_MAXXLOW},
{0xa0, 0x50, ZC3XX_R11D_GLOBALGAIN},
{}
};
static const struct usb_action tas5130c_60HZScale[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xaa, 0xa3, 0x0001}, /* 00,a3,01,aa */
{0xaa, 0xa4, 0x0077}, /* 00,a4,77,aa */
{0xa0, 0x01, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,01,cc */
{0xa0, 0x77, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,77,cc */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x09, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x47, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */
{0xa0, 0x7d, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,7d,cc */
{0xa0, 0x0c, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x08, ZC3XX_R1A9_DIGITALLIMITDIFF},
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP},
{0xa0, 0xc8, ZC3XX_R01D_HSYNC_0}, /* 00,1d,c8,cc */
{0xa0, 0xd0, ZC3XX_R01E_HSYNC_1}, /* 00,1e,d0,cc */
{0xa0, 0xe0, ZC3XX_R01F_HSYNC_2}, /* 00,1f,e0,cc */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */
{0xa0, 0x03, ZC3XX_R09F_MAXXHIGH}, /* 00,9f,03,cc */
{0xa0, 0x20, ZC3XX_R0A0_MAXXLOW},
{0xa0, 0x50, ZC3XX_R11D_GLOBALGAIN},
{}
};
static const struct usb_action tas5130c_NoFliker[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xaa, 0xa3, 0x0001}, /* 00,a3,01,aa */
{0xaa, 0xa4, 0x0040}, /* 00,a4,40,aa */
{0xa0, 0x01, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,01,cc */
{0xa0, 0x40, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,40,cc */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x05, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0xa0, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x04, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x0c, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,00,cc */
{0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,00,cc */
{0xa0, 0xbc, ZC3XX_R01D_HSYNC_0}, /* 00,1d,bc,cc */
{0xa0, 0xd0, ZC3XX_R01E_HSYNC_1}, /* 00,1e,d0,cc */
{0xa0, 0xe0, ZC3XX_R01F_HSYNC_2}, /* 00,1f,e0,cc */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */
{0xa0, 0x02, ZC3XX_R09F_MAXXHIGH}, /* 00,9f,02,cc */
{0xa0, 0xf0, ZC3XX_R0A0_MAXXLOW},
{0xa0, 0x50, ZC3XX_R11D_GLOBALGAIN},
{}
};
static const struct usb_action tas5130c_NoFlikerScale[] = {
{0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */
{0xaa, 0xa3, 0x0001}, /* 00,a3,01,aa */
{0xaa, 0xa4, 0x0090}, /* 00,a4,90,aa */
{0xa0, 0x01, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,01,cc */
{0xa0, 0x90, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,90,cc */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */
{0xa0, 0x0a, ZC3XX_R191_EXPOSURELIMITMID},
{0xa0, 0x00, ZC3XX_R192_EXPOSURELIMITLOW},
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH},
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID},
{0xa0, 0x04, ZC3XX_R197_ANTIFLICKERLOW},
{0xa0, 0x0c, ZC3XX_R18C_AEFREEZE},
{0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE},
{0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,00,cc */
{0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,00,cc */
{0xa0, 0xbc, ZC3XX_R01D_HSYNC_0}, /* 00,1d,bc,cc */
{0xa0, 0xd0, ZC3XX_R01E_HSYNC_1}, /* 00,1e,d0,cc */
{0xa0, 0xe0, ZC3XX_R01F_HSYNC_2}, /* 00,1f,e0,cc */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */
{0xa0, 0x02, ZC3XX_R09F_MAXXHIGH}, /* 00,9f,02,cc */
{0xa0, 0xf0, ZC3XX_R0A0_MAXXLOW},
{0xa0, 0x50, ZC3XX_R11D_GLOBALGAIN},
{}
};
static const struct usb_action gc0303_InitialScale[] = {
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc, */
{0xa0, 0x02, ZC3XX_R008_CLOCKSETTING}, /* 00,08,02,cc, */
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc, */
{0xa0, 0x10, ZC3XX_R002_CLOCKSELECT}, /* 00,02,00,cc,
* 0<->10 */
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc, */
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc, */
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc, */
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,e0,cc, */
{0xa0, 0x98, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,98,cc, */
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc, */
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc, */
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc, */
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc, */
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc, */
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc, */
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc, */
{0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,e6,cc,
* 6<->8 */
{0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,86,cc,
* 6<->8 */
{0xa0, 0x10, ZC3XX_R087_EXPTIMEMID}, /* 00,87,10,cc, */
{0xa0, 0x98, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,98,cc, */
{0xaa, 0x1b, 0x0024}, /* 00,1b,24,aa, */
{0xdd, 0x00, 0x0080}, /* 00,00,80,dd, */
{0xaa, 0x1b, 0x0000}, /* 00,1b,00,aa, */
{0xaa, 0x13, 0x0002}, /* 00,13,02,aa, */
{0xaa, 0x15, 0x0004}, /* 00,15,04,aa */
/*?? {0xaa, 0x01, 0x0000}, */
{0xaa, 0x01, 0x0000},
{0xaa, 0x1a, 0x0000}, /* 00,1a,00,aa, */
{0xaa, 0x1c, 0x0017}, /* 00,1c,17,aa, */
{0xa0, 0x82, ZC3XX_R086_EXPTIMEHIGH}, /* 00,86,82,cc, */
{0xa0, 0x83, ZC3XX_R087_EXPTIMEMID}, /* 00,87,83,cc, */
{0xa0, 0x84, ZC3XX_R088_EXPTIMELOW}, /* 00,88,84,cc, */
{0xaa, 0x05, 0x0010}, /* 00,05,10,aa, */
{0xaa, 0x0a, 0x0000}, /* 00,0a,00,aa, */
{0xaa, 0x0b, 0x00a0}, /* 00,0b,a0,aa, */
{0xaa, 0x0c, 0x0000}, /* 00,0c,00,aa, */
{0xaa, 0x0d, 0x00a0}, /* 00,0d,a0,aa, */
{0xaa, 0x0e, 0x0000}, /* 00,0e,00,aa, */
{0xaa, 0x0f, 0x00a0}, /* 00,0f,a0,aa, */
{0xaa, 0x10, 0x0000}, /* 00,10,00,aa, */
{0xaa, 0x11, 0x00a0}, /* 00,11,a0,aa, */
/*?? {0xa0, 0x00, 0x0039},
{0xa1, 0x01, 0x0037}, */
{0xaa, 0x16, 0x0001}, /* 00,16,01,aa, */
{0xaa, 0x17, 0x00e8}, /* 00,17,e6,aa, (e6 -> e8) */
{0xaa, 0x18, 0x0002}, /* 00,18,02,aa, */
{0xaa, 0x19, 0x0088}, /* 00,19,86,aa, */
{0xaa, 0x20, 0x0020}, /* 00,20,20,aa, */
{0xa0, 0xb7, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,b7,cc, */
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc, */
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc, */
{0xa0, 0x76, ZC3XX_R189_AWBSTATUS}, /* 01,89,76,cc, */
{0xa0, 0x09, 0x01ad}, /* 01,ad,09,cc, */
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc, */
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc, */
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc, */
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc, */
{0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN}, /* 01,a8,60,cc, */
{0xa0, 0x61, ZC3XX_R116_RGAIN}, /* 01,16,61,cc, */
{0xa0, 0x65, ZC3XX_R118_BGAIN}, /* 01,18,65,cc */
{}
};
static const struct usb_action gc0303_Initial[] = {
{0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc, */
{0xa0, 0x02, ZC3XX_R008_CLOCKSETTING}, /* 00,08,02,cc, */
{0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc, */
{0xa0, 0x00, ZC3XX_R002_CLOCKSELECT}, /* 00,02,10,cc, */
{0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc, */
{0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc, */
{0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc, */
{0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,e0,cc, */
{0xa0, 0x98, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,98,cc, */
{0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc, */
{0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc, */
{0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc, */
{0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc, */
{0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc, */
{0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc, */
{0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc, */
{0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,e8,cc,
* 8<->6 */
{0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,88,cc,
* 8<->6 */
{0xa0, 0x10, ZC3XX_R087_EXPTIMEMID}, /* 00,87,10,cc, */
{0xa0, 0x98, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,98,cc, */
{0xaa, 0x1b, 0x0024}, /* 00,1b,24,aa, */
{0xdd, 0x00, 0x0080}, /* 00,00,80,dd, */
{0xaa, 0x1b, 0x0000}, /* 00,1b,00,aa, */
{0xaa, 0x13, 0x0002}, /* 00,13,02,aa, */
{0xaa, 0x15, 0x0004}, /* 00,15,04,aa */
/*?? {0xaa, 0x01, 0x0000}, */
{0xaa, 0x01, 0x0000},
{0xaa, 0x1a, 0x0000}, /* 00,1a,00,aa, */
{0xaa, 0x1c, 0x0017}, /* 00,1c,17,aa, */
{0xa0, 0x82, ZC3XX_R086_EXPTIMEHIGH}, /* 00,86,82,cc, */
{0xa0, 0x83, ZC3XX_R087_EXPTIMEMID}, /* 00,87,83,cc, */
{0xa0, 0x84, ZC3XX_R088_EXPTIMELOW}, /* 00,88,84,cc, */
{0xaa, 0x05, 0x0010}, /* 00,05,10,aa, */
{0xaa, 0x0a, 0x0000}, /* 00,0a,00,aa, */
{0xaa, 0x0b, 0x00a0}, /* 00,0b,a0,aa, */
{0xaa, 0x0c, 0x0000}, /* 00,0c,00,aa, */
{0xaa, 0x0d, 0x00a0}, /* 00,0d,a0,aa, */
{0xaa, 0x0e, 0x0000}, /* 00,0e,00,aa, */
{0xaa, 0x0f, 0x00a0}, /* 00,0f,a0,aa, */
{0xaa, 0x10, 0x0000}, /* 00,10,00,aa, */
{0xaa, 0x11, 0x00a0}, /* 00,11,a0,aa, */
/*?? {0xa0, 0x00, 0x0039},
{0xa1, 0x01, 0x0037}, */
{0xaa, 0x16, 0x0001}, /* 00,16,01,aa, */
{0xaa, 0x17, 0x00e8}, /* 00,17,e6,aa (e6 -> e8) */
{0xaa, 0x18, 0x0002}, /* 00,18,02,aa, */
{0xaa, 0x19, 0x0088}, /* 00,19,88,aa, */
{0xaa, 0x20, 0x0020}, /* 00,20,20,aa, */
{0xa0, 0xb7, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,b7,cc, */
{0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc, */
{0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc, */
{0xa0, 0x76, ZC3XX_R189_AWBSTATUS}, /* 01,89,76,cc, */
{0xa0, 0x09, 0x01ad}, /* 01,ad,09,cc, */
{0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc, */
{0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc, */
{0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc, */
{0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc, */
{0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN}, /* 01,a8,60,cc, */
{0xa0, 0x61, ZC3XX_R116_RGAIN}, /* 01,16,61,cc, */
{0xa0, 0x65, ZC3XX_R118_BGAIN}, /* 01,18,65,cc */
{}
};
static const struct usb_action gc0303_50HZScale[] = {
{0xaa, 0x82, 0x0000}, /* 00,82,00,aa */
{0xaa, 0x83, 0x0001}, /* 00,83,01,aa */
{0xaa, 0x84, 0x00aa}, /* 00,84,aa,aa */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc, */
{0xa0, 0x06, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,0d,cc, */
{0xa0, 0xa8, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,50,cc, */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc, */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc, */
{0xa0, 0x8e, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,47,cc, */
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0e,cc, */
{0xa0, 0x15, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,15,cc, */
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,10,cc, */
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc, */
{0xa0, 0x62, ZC3XX_R01D_HSYNC_0}, /* 00,1d,62,cc, */
{0xa0, 0x90, ZC3XX_R01E_HSYNC_1}, /* 00,1e,90,cc, */
{0xa0, 0xc8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,c8,cc, */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc, */
{0xa0, 0x58, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,58,cc, */
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,42,cc, */
{0xa0, 0x78, ZC3XX_R18D_YTARGET}, /* 01,8d,78,cc */
{}
};
static const struct usb_action gc0303_50HZ[] = {
{0xaa, 0x82, 0x0000}, /* 00,82,00,aa */
{0xaa, 0x83, 0x0003}, /* 00,83,03,aa */
{0xaa, 0x84, 0x0054}, /* 00,84,54,aa */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc, */
{0xa0, 0x0d, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,0d,cc, */
{0xa0, 0x50, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,50,cc, */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc, */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc, */
{0xa0, 0x8e, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,8e,cc, */
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0e,cc, */
{0xa0, 0x15, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,15,cc, */
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,10,cc, */
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc, */
{0xa0, 0x62, ZC3XX_R01D_HSYNC_0}, /* 00,1d,62,cc, */
{0xa0, 0x90, ZC3XX_R01E_HSYNC_1}, /* 00,1e,90,cc, */
{0xa0, 0xc8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,c8,cc, */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc, */
{0xa0, 0x58, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,58,cc, */
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,42,cc, */
{0xa0, 0x78, ZC3XX_R18D_YTARGET}, /* 01,8d,78,cc */
{}
};
static const struct usb_action gc0303_60HZScale[] = {
{0xaa, 0x82, 0x0000}, /* 00,82,00,aa */
{0xaa, 0x83, 0x0001}, /* 00,83,01,aa */
{0xaa, 0x84, 0x0062}, /* 00,84,62,aa */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc, */
{0xa0, 0x05, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,05,cc, */
{0xa0, 0x88, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,88,cc, */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc, */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc, */
{0xa0, 0x3b, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,3b,cc, */
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0e,cc, */
{0xa0, 0x15, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,15,cc, */
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,10,cc, */
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc, */
{0xa0, 0x62, ZC3XX_R01D_HSYNC_0}, /* 00,1d,62,cc, */
{0xa0, 0x90, ZC3XX_R01E_HSYNC_1}, /* 00,1e,90,cc, */
{0xa0, 0xc8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,c8,cc, */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc, */
{0xa0, 0x58, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,58,cc, */
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,42,cc, */
{0xa0, 0x78, ZC3XX_R18D_YTARGET}, /* 01,8d,78,cc */
{}
};
static const struct usb_action gc0303_60HZ[] = {
{0xaa, 0x82, 0x0000}, /* 00,82,00,aa */
{0xaa, 0x83, 0x0002}, /* 00,83,02,aa */
{0xaa, 0x84, 0x00c4}, /* 00,84,c4,aa */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc, */
{0xa0, 0x0b, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,1,0b,cc, */
{0xa0, 0x10, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,2,10,cc, */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,5,00,cc, */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,6,00,cc, */
{0xa0, 0x76, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,7,76,cc, */
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, /* 01,c,0e,cc, */
{0xa0, 0x15, ZC3XX_R18F_AEUNFREEZE}, /* 01,f,15,cc, */
{0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,9,10,cc, */
{0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,a,24,cc, */
{0xa0, 0x62, ZC3XX_R01D_HSYNC_0}, /* 00,d,62,cc, */
{0xa0, 0x90, ZC3XX_R01E_HSYNC_1}, /* 00,e,90,cc, */
{0xa0, 0xc8, ZC3XX_R01F_HSYNC_2}, /* 00,f,c8,cc, */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,0,ff,cc, */
{0xa0, 0x58, ZC3XX_R11D_GLOBALGAIN}, /* 01,d,58,cc, */
{0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,42,cc, */
{0xa0, 0x78, ZC3XX_R18D_YTARGET}, /* 01,d,78,cc */
{}
};
static const struct usb_action gc0303_NoFlikerScale[] = {
{0xa0, 0x0c, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0c,cc, */
{0xaa, 0x82, 0x0000}, /* 00,82,00,aa */
{0xaa, 0x83, 0x0000}, /* 00,83,00,aa */
{0xaa, 0x84, 0x0020}, /* 00,84,20,aa */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,0,00,cc, */
{0xa0, 0x05, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,05,cc, */
{0xa0, 0x88, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,88,cc, */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc, */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc, */
{0xa0, 0x10, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,10,cc, */
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0e,cc, */
{0xa0, 0x15, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,15,cc, */
{0xa0, 0x62, ZC3XX_R01D_HSYNC_0}, /* 00,1d,62,cc, */
{0xa0, 0x90, ZC3XX_R01E_HSYNC_1}, /* 00,1e,90,cc, */
{0xa0, 0xc8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,c8,cc, */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc, */
{0xa0, 0x58, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,58,cc, */
{0xa0, 0x03, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,03,cc */
{}
};
static const struct usb_action gc0303_NoFliker[] = {
{0xa0, 0x0c, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0c,cc, */
{0xaa, 0x82, 0x0000}, /* 00,82,00,aa */
{0xaa, 0x83, 0x0000}, /* 00,83,00,aa */
{0xaa, 0x84, 0x0020}, /* 00,84,20,aa */
{0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc, */
{0xa0, 0x0b, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,0b,cc, */
{0xa0, 0x10, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,10,cc, */
{0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc, */
{0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc, */
{0xa0, 0x10, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,10,cc, */
{0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0e,cc, */
{0xa0, 0x15, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,15,cc, */
{0xa0, 0x62, ZC3XX_R01D_HSYNC_0}, /* 00,1d,62,cc, */
{0xa0, 0x90, ZC3XX_R01E_HSYNC_1}, /* 00,1e,90,cc, */
{0xa0, 0xc8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,c8,cc, */
{0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc, */
{0xa0, 0x58, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,58,cc, */
{0xa0, 0x03, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,03,cc */
{}
};
static u8 reg_r_i(struct gspca_dev *gspca_dev,
u16 index)
{
int ret;
if (gspca_dev->usb_err < 0)
return 0;
ret = usb_control_msg(gspca_dev->dev,
usb_rcvctrlpipe(gspca_dev->dev, 0),
0xa1,
USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
0x01, /* value */
index, gspca_dev->usb_buf, 1,
500);
if (ret < 0) {
err("reg_r_i err %d", ret);
gspca_dev->usb_err = ret;
return 0;
}
return gspca_dev->usb_buf[0];
}
static u8 reg_r(struct gspca_dev *gspca_dev,
u16 index)
{
u8 ret;
ret = reg_r_i(gspca_dev, index);
PDEBUG(D_USBI, "reg r [%04x] -> %02x", index, ret);
return ret;
}
static void reg_w_i(struct gspca_dev *gspca_dev,
u8 value,
u16 index)
{
int ret;
if (gspca_dev->usb_err < 0)
return;
ret = usb_control_msg(gspca_dev->dev,
usb_sndctrlpipe(gspca_dev->dev, 0),
0xa0,
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
value, index, NULL, 0,
500);
if (ret < 0) {
err("reg_w_i err %d", ret);
gspca_dev->usb_err = ret;
}
}
static void reg_w(struct gspca_dev *gspca_dev,
u8 value,
u16 index)
{
PDEBUG(D_USBO, "reg w [%04x] = %02x", index, value);
reg_w_i(gspca_dev, value, index);
}
static u16 i2c_read(struct gspca_dev *gspca_dev,
u8 reg)
{
u8 retbyte;
u16 retval;
if (gspca_dev->usb_err < 0)
return 0;
reg_w_i(gspca_dev, reg, 0x0092);
reg_w_i(gspca_dev, 0x02, 0x0090); /* <- read command */
msleep(20);
retbyte = reg_r_i(gspca_dev, 0x0091); /* read status */
if (retbyte != 0x00)
err("i2c_r status error %02x", retbyte);
retval = reg_r_i(gspca_dev, 0x0095); /* read Lowbyte */
retval |= reg_r_i(gspca_dev, 0x0096) << 8; /* read Hightbyte */
PDEBUG(D_USBI, "i2c r [%02x] -> %04x (%02x)",
reg, retval, retbyte);
return retval;
}
static u8 i2c_write(struct gspca_dev *gspca_dev,
u8 reg,
u8 valL,
u8 valH)
{
u8 retbyte;
if (gspca_dev->usb_err < 0)
return 0;
reg_w_i(gspca_dev, reg, 0x92);
reg_w_i(gspca_dev, valL, 0x93);
reg_w_i(gspca_dev, valH, 0x94);
reg_w_i(gspca_dev, 0x01, 0x90); /* <- write command */
msleep(1);
retbyte = reg_r_i(gspca_dev, 0x0091); /* read status */
if (retbyte != 0x00)
err("i2c_w status error %02x", retbyte);
PDEBUG(D_USBO, "i2c w [%02x] = %02x%02x (%02x)",
reg, valH, valL, retbyte);
return retbyte;
}
static void usb_exchange(struct gspca_dev *gspca_dev,
const struct usb_action *action)
{
while (action->req) {
switch (action->req) {
case 0xa0: /* write register */
reg_w(gspca_dev, action->val, action->idx);
break;
case 0xa1: /* read status */
reg_r(gspca_dev, action->idx);
break;
case 0xaa:
i2c_write(gspca_dev,
action->val, /* reg */
action->idx & 0xff, /* valL */
action->idx >> 8); /* valH */
break;
case 0xbb:
i2c_write(gspca_dev,
action->idx >> 8, /* reg */
action->idx & 0xff, /* valL */
action->val); /* valH */
break;
default:
/* case 0xdd: * delay */
msleep(action->idx);
break;
}
action++;
msleep(1);
}
}
static void setmatrix(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int i;
const u8 *matrix;
static const u8 adcm2700_matrix[9] =
/* {0x66, 0xed, 0xed, 0xed, 0x66, 0xed, 0xed, 0xed, 0x66}; */
/*ms-win*/
{0x74, 0xed, 0xed, 0xed, 0x74, 0xed, 0xed, 0xed, 0x74};
static const u8 gc0305_matrix[9] =
{0x50, 0xf8, 0xf8, 0xf8, 0x50, 0xf8, 0xf8, 0xf8, 0x50};
static const u8 ov7620_matrix[9] =
{0x58, 0xf4, 0xf4, 0xf4, 0x58, 0xf4, 0xf4, 0xf4, 0x58};
static const u8 pas202b_matrix[9] =
{0x4c, 0xf5, 0xff, 0xf9, 0x51, 0xf5, 0xfb, 0xed, 0x5f};
static const u8 po2030_matrix[9] =
{0x60, 0xf0, 0xf0, 0xf0, 0x60, 0xf0, 0xf0, 0xf0, 0x60};
static const u8 tas5130c_matrix[9] =
{0x68, 0xec, 0xec, 0xec, 0x68, 0xec, 0xec, 0xec, 0x68};
static const u8 gc0303_matrix[9] =
{0x7b, 0xea, 0xea, 0xea, 0x7b, 0xea, 0xea, 0xea, 0x7b};
static const u8 *matrix_tb[SENSOR_MAX] = {
[SENSOR_ADCM2700] = adcm2700_matrix,
[SENSOR_CS2102] = ov7620_matrix,
[SENSOR_CS2102K] = NULL,
[SENSOR_GC0303] = gc0303_matrix,
[SENSOR_GC0305] = gc0305_matrix,
[SENSOR_HDCS2020] = NULL,
[SENSOR_HV7131B] = NULL,
[SENSOR_HV7131R] = po2030_matrix,
[SENSOR_ICM105A] = po2030_matrix,
[SENSOR_MC501CB] = NULL,
[SENSOR_MT9V111_1] = gc0305_matrix,
[SENSOR_MT9V111_3] = gc0305_matrix,
[SENSOR_OV7620] = ov7620_matrix,
[SENSOR_OV7630C] = NULL,
[SENSOR_PAS106] = NULL,
[SENSOR_PAS202B] = pas202b_matrix,
[SENSOR_PB0330] = gc0305_matrix,
[SENSOR_PO2030] = po2030_matrix,
[SENSOR_TAS5130C] = tas5130c_matrix,
};
matrix = matrix_tb[sd->sensor];
if (matrix == NULL)
return; /* matrix already loaded */
for (i = 0; i < ARRAY_SIZE(ov7620_matrix); i++)
reg_w(gspca_dev, matrix[i], 0x010a + i);
}
static void setsharpness(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int sharpness;
static const u8 sharpness_tb[][2] = {
{0x02, 0x03},
{0x04, 0x07},
{0x08, 0x0f},
{0x10, 0x1e}
};
sharpness = sd->ctrls[SHARPNESS].val;
reg_w(gspca_dev, sharpness_tb[sharpness][0], 0x01c6);
reg_r(gspca_dev, 0x01c8);
reg_r(gspca_dev, 0x01c9);
reg_r(gspca_dev, 0x01ca);
reg_w(gspca_dev, sharpness_tb[sharpness][1], 0x01cb);
}
static void setcontrast(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
const u8 *Tgamma;
int g, i, brightness, contrast, adj, gp1, gp2;
u8 gr[16];
static const u8 delta_b[16] = /* delta for brightness */
{0x50, 0x38, 0x2d, 0x28, 0x24, 0x21, 0x1e, 0x1d,
0x1d, 0x1b, 0x1b, 0x1b, 0x19, 0x18, 0x18, 0x18};
static const u8 delta_c[16] = /* delta for contrast */
{0x2c, 0x1a, 0x12, 0x0c, 0x0a, 0x06, 0x06, 0x06,
0x04, 0x06, 0x04, 0x04, 0x03, 0x03, 0x02, 0x02};
static const u8 gamma_tb[6][16] = {
{0x00, 0x00, 0x03, 0x0d, 0x1b, 0x2e, 0x45, 0x5f,
0x79, 0x93, 0xab, 0xc1, 0xd4, 0xe5, 0xf3, 0xff},
{0x01, 0x0c, 0x1f, 0x3a, 0x53, 0x6d, 0x85, 0x9c,
0xb0, 0xc2, 0xd1, 0xde, 0xe9, 0xf2, 0xf9, 0xff},
{0x04, 0x16, 0x30, 0x4e, 0x68, 0x81, 0x98, 0xac,
0xbe, 0xcd, 0xda, 0xe4, 0xed, 0xf5, 0xfb, 0xff},
{0x13, 0x38, 0x59, 0x79, 0x92, 0xa7, 0xb9, 0xc8,
0xd4, 0xdf, 0xe7, 0xee, 0xf4, 0xf9, 0xfc, 0xff},
{0x20, 0x4b, 0x6e, 0x8d, 0xa3, 0xb5, 0xc5, 0xd2,
0xdc, 0xe5, 0xec, 0xf2, 0xf6, 0xfa, 0xfd, 0xff},
{0x24, 0x44, 0x64, 0x84, 0x9d, 0xb2, 0xc4, 0xd3,
0xe0, 0xeb, 0xf4, 0xff, 0xff, 0xff, 0xff, 0xff},
};
Tgamma = gamma_tb[sd->ctrls[GAMMA].val - 1];
contrast = ((int) sd->ctrls[CONTRAST].val - 128); /* -128 / 127 */
brightness = ((int) sd->ctrls[BRIGHTNESS].val - 128); /* -128 / 92 */
adj = 0;
gp1 = gp2 = 0;
for (i = 0; i < 16; i++) {
g = Tgamma[i] + delta_b[i] * brightness / 256
- delta_c[i] * contrast / 256 - adj / 2;
if (g > 0xff)
g = 0xff;
else if (g < 0)
g = 0;
reg_w(gspca_dev, g, 0x0120 + i); /* gamma */
if (contrast > 0)
adj--;
else if (contrast < 0)
adj++;
if (i > 1)
gr[i - 1] = (g - gp2) / 2;
else if (i != 0)
gr[0] = gp1 == 0 ? 0 : (g - gp1);
gp2 = gp1;
gp1 = g;
}
gr[15] = (0xff - gp2) / 2;
for (i = 0; i < 16; i++)
reg_w(gspca_dev, gr[i], 0x0130 + i); /* gradient */
}
static void getexposure(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->ctrls[EXPOSURE].val = (i2c_read(gspca_dev, 0x25) << 9)
| (i2c_read(gspca_dev, 0x26) << 1)
| (i2c_read(gspca_dev, 0x27) >> 7);
}
static void setexposure(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int val;
val = sd->ctrls[EXPOSURE].val;
i2c_write(gspca_dev, 0x25, val >> 9, 0x00);
i2c_write(gspca_dev, 0x26, val >> 1, 0x00);
i2c_write(gspca_dev, 0x27, val << 7, 0x00);
}
static void setquality(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
u8 frxt;
switch (sd->sensor) {
case SENSOR_ADCM2700:
case SENSOR_GC0305:
case SENSOR_HV7131B:
case SENSOR_HV7131R:
case SENSOR_OV7620:
case SENSOR_PAS202B:
case SENSOR_PO2030:
return;
}
/*fixme: is it really 0008 0007 0018 for all other sensors? */
reg_w(gspca_dev, QUANT_VAL, 0x0008);
frxt = 0x30;
reg_w(gspca_dev, frxt, 0x0007);
#if QUANT_VAL == 0 || QUANT_VAL == 1 || QUANT_VAL == 2
frxt = 0xff;
#elif QUANT_VAL == 3
frxt = 0xf0;
#elif QUANT_VAL == 4
frxt = 0xe0;
#else
frxt = 0x20;
#endif
reg_w(gspca_dev, frxt, 0x0018);
}
/* Matches the sensor's internal frame rate to the lighting frequency.
* Valid frequencies are:
* 50Hz, for European and Asian lighting (default)
* 60Hz, for American lighting
* 0 = No Fliker (for outdoore usage)
*/
static void setlightfreq(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int i, mode;
const struct usb_action *zc3_freq;
static const struct usb_action *freq_tb[SENSOR_MAX][6] = {
[SENSOR_ADCM2700] =
{adcm2700_NoFliker, adcm2700_NoFliker,
adcm2700_50HZ, adcm2700_50HZ,
adcm2700_60HZ, adcm2700_60HZ},
[SENSOR_CS2102] =
{cs2102_NoFliker, cs2102_NoFlikerScale,
cs2102_50HZ, cs2102_50HZScale,
cs2102_60HZ, cs2102_60HZScale},
[SENSOR_CS2102K] =
{cs2102_NoFliker, cs2102_NoFlikerScale,
NULL, NULL, /* currently disabled */
NULL, NULL},
[SENSOR_GC0303] =
{gc0303_NoFliker, gc0303_NoFlikerScale,
gc0303_50HZ, gc0303_50HZScale,
gc0303_60HZ, gc0303_60HZScale},
[SENSOR_GC0305] =
{gc0305_NoFliker, gc0305_NoFliker,
gc0305_50HZ, gc0305_50HZ,
gc0305_60HZ, gc0305_60HZ},
[SENSOR_HDCS2020] =
{hdcs2020_NoFliker, hdcs2020_NoFliker,
hdcs2020_50HZ, hdcs2020_50HZ,
hdcs2020_60HZ, hdcs2020_60HZ},
[SENSOR_HV7131B] =
{hv7131b_NoFliker, hv7131b_NoFlikerScale,
hv7131b_50HZ, hv7131b_50HZScale,
hv7131b_60HZ, hv7131b_60HZScale},
[SENSOR_HV7131R] =
{hv7131r_NoFliker, hv7131r_NoFlikerScale,
hv7131r_50HZ, hv7131r_50HZScale,
hv7131r_60HZ, hv7131r_60HZScale},
[SENSOR_ICM105A] =
{icm105a_NoFliker, icm105a_NoFlikerScale,
icm105a_50HZ, icm105a_50HZScale,
icm105a_60HZ, icm105a_60HZScale},
[SENSOR_MC501CB] =
{mc501cb_NoFliker, mc501cb_NoFlikerScale,
mc501cb_50HZ, mc501cb_50HZScale,
mc501cb_60HZ, mc501cb_60HZScale},
[SENSOR_MT9V111_1] =
{mt9v111_1_AENoFliker, mt9v111_1_AENoFlikerScale,
mt9v111_1_AE50HZ, mt9v111_1_AE50HZScale,
mt9v111_1_AE60HZ, mt9v111_1_AE60HZScale},
[SENSOR_MT9V111_3] =
{mt9v111_3_AENoFliker, mt9v111_3_AENoFlikerScale,
mt9v111_3_AE50HZ, mt9v111_3_AE50HZScale,
mt9v111_3_AE60HZ, mt9v111_3_AE60HZScale},
[SENSOR_OV7620] =
{ov7620_NoFliker, ov7620_NoFliker,
ov7620_50HZ, ov7620_50HZ,
ov7620_60HZ, ov7620_60HZ},
[SENSOR_OV7630C] =
{NULL, NULL,
NULL, NULL,
NULL, NULL},
[SENSOR_PAS106] =
{pas106b_NoFliker, pas106b_NoFliker,
pas106b_50HZ, pas106b_50HZ,
pas106b_60HZ, pas106b_60HZ},
[SENSOR_PAS202B] =
{pas202b_NoFliker, pas202b_NoFlikerScale,
pas202b_50HZ, pas202b_50HZScale,
pas202b_60HZ, pas202b_60HZScale},
[SENSOR_PB0330] =
{pb0330_NoFliker, pb0330_NoFlikerScale,
pb0330_50HZ, pb0330_50HZScale,
pb0330_60HZ, pb0330_60HZScale},
[SENSOR_PO2030] =
{po2030_NoFliker, po2030_NoFliker,
po2030_50HZ, po2030_50HZ,
po2030_60HZ, po2030_60HZ},
[SENSOR_TAS5130C] =
{tas5130c_NoFliker, tas5130c_NoFlikerScale,
tas5130c_50HZ, tas5130c_50HZScale,
tas5130c_60HZ, tas5130c_60HZScale},
};
i = sd->ctrls[LIGHTFREQ].val * 2;
mode = gspca_dev->cam.cam_mode[gspca_dev->curr_mode].priv;
if (mode)
i++; /* 320x240 */
zc3_freq = freq_tb[sd->sensor][i];
if (zc3_freq == NULL)
return;
usb_exchange(gspca_dev, zc3_freq);
switch (sd->sensor) {
case SENSOR_GC0305:
if (mode /* if 320x240 */
&& sd->ctrls[LIGHTFREQ].val == 1) /* and 50Hz */
reg_w(gspca_dev, 0x85, 0x018d);
/* win: 0x80, 0x018d */
break;
case SENSOR_OV7620:
if (!mode) { /* if 640x480 */
if (sd->ctrls[LIGHTFREQ].val != 0) /* and filter */
reg_w(gspca_dev, 0x40, 0x0002);
else
reg_w(gspca_dev, 0x44, 0x0002);
}
break;
case SENSOR_PAS202B:
reg_w(gspca_dev, 0x00, 0x01a7);
break;
}
}
static void setautogain(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
u8 autoval;
if (sd->ctrls[AUTOGAIN].val)
autoval = 0x42;
else
autoval = 0x02;
reg_w(gspca_dev, autoval, 0x0180);
}
static void send_unknown(struct gspca_dev *gspca_dev, int sensor)
{
reg_w(gspca_dev, 0x01, 0x0000); /* bridge reset */
switch (sensor) {
case SENSOR_PAS106:
reg_w(gspca_dev, 0x03, 0x003a);
reg_w(gspca_dev, 0x0c, 0x003b);
reg_w(gspca_dev, 0x08, 0x0038);
break;
case SENSOR_ADCM2700:
case SENSOR_GC0305:
case SENSOR_OV7620:
case SENSOR_MT9V111_1:
case SENSOR_MT9V111_3:
case SENSOR_PB0330:
case SENSOR_PO2030:
reg_w(gspca_dev, 0x0d, 0x003a);
reg_w(gspca_dev, 0x02, 0x003b);
reg_w(gspca_dev, 0x00, 0x0038);
break;
case SENSOR_HV7131R:
case SENSOR_PAS202B:
reg_w(gspca_dev, 0x03, 0x003b);
reg_w(gspca_dev, 0x0c, 0x003a);
reg_w(gspca_dev, 0x0b, 0x0039);
if (sensor == SENSOR_PAS202B)
reg_w(gspca_dev, 0x0b, 0x0038);
break;
}
}
/* start probe 2 wires */
static void start_2wr_probe(struct gspca_dev *gspca_dev, int sensor)
{
reg_w(gspca_dev, 0x01, 0x0000);
reg_w(gspca_dev, sensor, 0x0010);
reg_w(gspca_dev, 0x01, 0x0001);
reg_w(gspca_dev, 0x03, 0x0012);
reg_w(gspca_dev, 0x01, 0x0012);
/* msleep(2); */
}
static int sif_probe(struct gspca_dev *gspca_dev)
{
u16 checkword;
start_2wr_probe(gspca_dev, 0x0f); /* PAS106 */
reg_w(gspca_dev, 0x08, 0x008d);
msleep(150);
checkword = ((i2c_read(gspca_dev, 0x00) & 0x0f) << 4)
| ((i2c_read(gspca_dev, 0x01) & 0xf0) >> 4);
PDEBUG(D_PROBE, "probe sif 0x%04x", checkword);
if (checkword == 0x0007) {
send_unknown(gspca_dev, SENSOR_PAS106);
return 0x0f; /* PAS106 */
}
return -1;
}
static int vga_2wr_probe(struct gspca_dev *gspca_dev)
{
u16 retword;
start_2wr_probe(gspca_dev, 0x00); /* HV7131B */
i2c_write(gspca_dev, 0x01, 0xaa, 0x00);
retword = i2c_read(gspca_dev, 0x01);
if (retword != 0)
return 0x00; /* HV7131B */
start_2wr_probe(gspca_dev, 0x04); /* CS2102 */
i2c_write(gspca_dev, 0x01, 0xaa, 0x00);
retword = i2c_read(gspca_dev, 0x01);
if (retword != 0)
return 0x04; /* CS2102 */
start_2wr_probe(gspca_dev, 0x06); /* OmniVision */
reg_w(gspca_dev, 0x08, 0x008d);
i2c_write(gspca_dev, 0x11, 0xaa, 0x00);
retword = i2c_read(gspca_dev, 0x11);
if (retword != 0) {
/* (should have returned 0xaa) --> Omnivision? */
/* reg_r 0x10 -> 0x06 --> */
goto ov_check;
}
start_2wr_probe(gspca_dev, 0x08); /* HDCS2020 */
i2c_write(gspca_dev, 0x1c, 0x00, 0x00);
i2c_write(gspca_dev, 0x15, 0xaa, 0x00);
retword = i2c_read(gspca_dev, 0x15);
if (retword != 0)
return 0x08; /* HDCS2020 */
start_2wr_probe(gspca_dev, 0x0a); /* PB0330 */
i2c_write(gspca_dev, 0x07, 0xaa, 0xaa);
retword = i2c_read(gspca_dev, 0x07);
if (retword != 0)
return 0x0a; /* PB0330 */
retword = i2c_read(gspca_dev, 0x03);
if (retword != 0)
return 0x0a; /* PB0330 ?? */
retword = i2c_read(gspca_dev, 0x04);
if (retword != 0)
return 0x0a; /* PB0330 ?? */
start_2wr_probe(gspca_dev, 0x0c); /* ICM105A */
i2c_write(gspca_dev, 0x01, 0x11, 0x00);
retword = i2c_read(gspca_dev, 0x01);
if (retword != 0)
return 0x0c; /* ICM105A */
start_2wr_probe(gspca_dev, 0x0e); /* PAS202BCB */
reg_w(gspca_dev, 0x08, 0x008d);
i2c_write(gspca_dev, 0x03, 0xaa, 0x00);
msleep(50);
retword = i2c_read(gspca_dev, 0x03);
if (retword != 0) {
send_unknown(gspca_dev, SENSOR_PAS202B);
return 0x0e; /* PAS202BCB */
}
start_2wr_probe(gspca_dev, 0x02); /* TAS5130C */
i2c_write(gspca_dev, 0x01, 0xaa, 0x00);
retword = i2c_read(gspca_dev, 0x01);
if (retword != 0)
return 0x02; /* TAS5130C */
ov_check:
reg_r(gspca_dev, 0x0010); /* ?? */
reg_r(gspca_dev, 0x0010);
reg_w(gspca_dev, 0x01, 0x0000);
reg_w(gspca_dev, 0x01, 0x0001);
reg_w(gspca_dev, 0x06, 0x0010); /* OmniVision */
reg_w(gspca_dev, 0xa1, 0x008b);
reg_w(gspca_dev, 0x08, 0x008d);
msleep(500);
reg_w(gspca_dev, 0x01, 0x0012);
i2c_write(gspca_dev, 0x12, 0x80, 0x00); /* sensor reset */
retword = i2c_read(gspca_dev, 0x0a) << 8;
retword |= i2c_read(gspca_dev, 0x0b);
PDEBUG(D_PROBE, "probe 2wr ov vga 0x%04x", retword);
switch (retword) {
case 0x7631: /* OV7630C */
reg_w(gspca_dev, 0x06, 0x0010);
break;
case 0x7620: /* OV7620 */
case 0x7648: /* OV7648 */
break;
default:
return -1; /* not OmniVision */
}
return retword;
}
struct sensor_by_chipset_revision {
u16 revision;
u8 internal_sensor_id;
};
static const struct sensor_by_chipset_revision chipset_revision_sensor[] = {
{0xc000, 0x12}, /* TAS5130C */
{0xc001, 0x13}, /* MT9V111 */
{0xe001, 0x13},
{0x8001, 0x13},
{0x8000, 0x14}, /* CS2102K */
{0x8400, 0x15}, /* MT9V111 */
{0xe400, 0x15},
};
static int vga_3wr_probe(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int i;
u16 retword;
/*fixme: lack of 8b=b3 (11,12)-> 10, 8b=e0 (14,15,16)-> 12 found in gspcav1*/
reg_w(gspca_dev, 0x02, 0x0010);
reg_r(gspca_dev, 0x0010);
reg_w(gspca_dev, 0x01, 0x0000);
reg_w(gspca_dev, 0x00, 0x0010);
reg_w(gspca_dev, 0x01, 0x0001);
reg_w(gspca_dev, 0x91, 0x008b);
reg_w(gspca_dev, 0x03, 0x0012);
reg_w(gspca_dev, 0x01, 0x0012);
reg_w(gspca_dev, 0x05, 0x0012);
retword = i2c_read(gspca_dev, 0x14);
if (retword != 0)
return 0x11; /* HV7131R */
retword = i2c_read(gspca_dev, 0x15);
if (retword != 0)
return 0x11; /* HV7131R */
retword = i2c_read(gspca_dev, 0x16);
if (retword != 0)
return 0x11; /* HV7131R */
reg_w(gspca_dev, 0x02, 0x0010);
retword = reg_r(gspca_dev, 0x000b) << 8;
retword |= reg_r(gspca_dev, 0x000a);
PDEBUG(D_PROBE, "probe 3wr vga 1 0x%04x", retword);
reg_r(gspca_dev, 0x0010);
if ((retword & 0xff00) == 0x6400)
return 0x02; /* TAS5130C */
for (i = 0; i < ARRAY_SIZE(chipset_revision_sensor); i++) {
if (chipset_revision_sensor[i].revision == retword) {
sd->chip_revision = retword;
send_unknown(gspca_dev, SENSOR_PB0330);
return chipset_revision_sensor[i].internal_sensor_id;
}
}
reg_w(gspca_dev, 0x01, 0x0000); /* check PB0330 */
reg_w(gspca_dev, 0x01, 0x0001);
reg_w(gspca_dev, 0xdd, 0x008b);
reg_w(gspca_dev, 0x0a, 0x0010);
reg_w(gspca_dev, 0x03, 0x0012);
reg_w(gspca_dev, 0x01, 0x0012);
retword = i2c_read(gspca_dev, 0x00);
if (retword != 0) {
PDEBUG(D_PROBE, "probe 3wr vga type 0a");
return 0x0a; /* PB0330 */
}
/* probe gc0303 / gc0305 */
reg_w(gspca_dev, 0x01, 0x0000);
reg_w(gspca_dev, 0x01, 0x0001);
reg_w(gspca_dev, 0x98, 0x008b);
reg_w(gspca_dev, 0x01, 0x0010);
reg_w(gspca_dev, 0x03, 0x0012);
msleep(2);
reg_w(gspca_dev, 0x01, 0x0012);
retword = i2c_read(gspca_dev, 0x00);
if (retword != 0) {
PDEBUG(D_PROBE, "probe 3wr vga type %02x", retword);
if (retword == 0x0011) /* gc0303 */
return 0x0303;
if (retword == 0x0029) /* gc0305 */
send_unknown(gspca_dev, SENSOR_GC0305);
return retword;
}
reg_w(gspca_dev, 0x01, 0x0000); /* check OmniVision */
reg_w(gspca_dev, 0x01, 0x0001);
reg_w(gspca_dev, 0xa1, 0x008b);
reg_w(gspca_dev, 0x08, 0x008d);
reg_w(gspca_dev, 0x06, 0x0010);
reg_w(gspca_dev, 0x01, 0x0012);
reg_w(gspca_dev, 0x05, 0x0012);
if (i2c_read(gspca_dev, 0x1c) == 0x007f /* OV7610 - manufacturer ID */
&& i2c_read(gspca_dev, 0x1d) == 0x00a2) {
send_unknown(gspca_dev, SENSOR_OV7620);
return 0x06; /* OmniVision confirm ? */
}
reg_w(gspca_dev, 0x01, 0x0000);
reg_w(gspca_dev, 0x00, 0x0002);
reg_w(gspca_dev, 0x01, 0x0010);
reg_w(gspca_dev, 0x01, 0x0001);
reg_w(gspca_dev, 0xee, 0x008b);
reg_w(gspca_dev, 0x03, 0x0012);
reg_w(gspca_dev, 0x01, 0x0012);
reg_w(gspca_dev, 0x05, 0x0012);
retword = i2c_read(gspca_dev, 0x00) << 8; /* ID 0 */
retword |= i2c_read(gspca_dev, 0x01); /* ID 1 */
PDEBUG(D_PROBE, "probe 3wr vga 2 0x%04x", retword);
if (retword == 0x2030) {
#ifdef GSPCA_DEBUG
u8 retbyte;
retbyte = i2c_read(gspca_dev, 0x02); /* revision number */
PDEBUG(D_PROBE, "sensor PO2030 rev 0x%02x", retbyte);
#endif
send_unknown(gspca_dev, SENSOR_PO2030);
return retword;
}
reg_w(gspca_dev, 0x01, 0x0000);
reg_w(gspca_dev, 0x0a, 0x0010);
reg_w(gspca_dev, 0xd3, 0x008b);
reg_w(gspca_dev, 0x01, 0x0001);
reg_w(gspca_dev, 0x03, 0x0012);
reg_w(gspca_dev, 0x01, 0x0012);
reg_w(gspca_dev, 0x05, 0x0012);
reg_w(gspca_dev, 0xd3, 0x008b);
retword = i2c_read(gspca_dev, 0x01);
if (retword != 0) {
PDEBUG(D_PROBE, "probe 3wr vga type 0a ? ret: %04x", retword);
return 0x16; /* adcm2700 (6100/6200) */
}
return -1;
}
static int zcxx_probeSensor(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int sensor;
switch (sd->sensor) {
case SENSOR_MC501CB:
return -1; /* don't probe */
case SENSOR_GC0303:
/* may probe but with no write in reg 0x0010 */
return -1; /* don't probe */
case SENSOR_PAS106:
sensor = sif_probe(gspca_dev);
if (sensor >= 0)
return sensor;
break;
}
sensor = vga_2wr_probe(gspca_dev);
if (sensor >= 0)
return sensor;
return vga_3wr_probe(gspca_dev);
}
/* this function is called at probe time */
static int sd_config(struct gspca_dev *gspca_dev,
const struct usb_device_id *id)
{
struct sd *sd = (struct sd *) gspca_dev;
if (id->idProduct == 0x301b)
sd->bridge = BRIDGE_ZC301;
else
sd->bridge = BRIDGE_ZC303;
/* define some sensors from the vendor/product */
sd->sensor = id->driver_info;
gspca_dev->cam.ctrls = sd->ctrls;
sd->quality = QUALITY_DEF;
/* if USB 1.1, let some bandwidth for the audio device */
if (gspca_dev->audio && gspca_dev->dev->speed < USB_SPEED_HIGH)
gspca_dev->nbalt--;
return 0;
}
/* this function is called at probe and resume time */
static int sd_init(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
struct cam *cam;
int sensor;
static const u8 gamma[SENSOR_MAX] = {
[SENSOR_ADCM2700] = 4,
[SENSOR_CS2102] = 4,
[SENSOR_CS2102K] = 5,
[SENSOR_GC0303] = 3,
[SENSOR_GC0305] = 4,
[SENSOR_HDCS2020] = 4,
[SENSOR_HV7131B] = 4,
[SENSOR_HV7131R] = 4,
[SENSOR_ICM105A] = 4,
[SENSOR_MC501CB] = 4,
[SENSOR_MT9V111_1] = 4,
[SENSOR_MT9V111_3] = 4,
[SENSOR_OV7620] = 3,
[SENSOR_OV7630C] = 4,
[SENSOR_PAS106] = 4,
[SENSOR_PAS202B] = 4,
[SENSOR_PB0330] = 4,
[SENSOR_PO2030] = 4,
[SENSOR_TAS5130C] = 3,
};
static const u8 mode_tb[SENSOR_MAX] = {
[SENSOR_ADCM2700] = 2,
[SENSOR_CS2102] = 1,
[SENSOR_CS2102K] = 1,
[SENSOR_GC0303] = 1,
[SENSOR_GC0305] = 1,
[SENSOR_HDCS2020] = 1,
[SENSOR_HV7131B] = 1,
[SENSOR_HV7131R] = 1,
[SENSOR_ICM105A] = 1,
[SENSOR_MC501CB] = 2,
[SENSOR_MT9V111_1] = 1,
[SENSOR_MT9V111_3] = 1,
[SENSOR_OV7620] = 2,
[SENSOR_OV7630C] = 1,
[SENSOR_PAS106] = 0,
[SENSOR_PAS202B] = 1,
[SENSOR_PB0330] = 1,
[SENSOR_PO2030] = 1,
[SENSOR_TAS5130C] = 1,
};
sensor = zcxx_probeSensor(gspca_dev);
if (sensor >= 0)
PDEBUG(D_PROBE, "probe sensor -> %04x", sensor);
if ((unsigned) force_sensor < SENSOR_MAX) {
sd->sensor = force_sensor;
PDEBUG(D_PROBE, "sensor forced to %d", force_sensor);
} else {
switch (sensor) {
case -1:
switch (sd->sensor) {
case SENSOR_MC501CB:
PDEBUG(D_PROBE, "Sensor MC501CB");
break;
case SENSOR_GC0303:
PDEBUG(D_PROBE, "Sensor GC0303");
break;
default:
warn("Unknown sensor - set to TAS5130C");
sd->sensor = SENSOR_TAS5130C;
}
break;
case 0:
/* check the sensor type */
sensor = i2c_read(gspca_dev, 0x00);
PDEBUG(D_PROBE, "Sensor hv7131 type %d", sensor);
switch (sensor) {
case 0: /* hv7131b */
case 1: /* hv7131e */
PDEBUG(D_PROBE, "Find Sensor HV7131B");
sd->sensor = SENSOR_HV7131B;
break;
default:
/* case 2: * hv7131r */
PDEBUG(D_PROBE, "Find Sensor HV7131R");
sd->sensor = SENSOR_HV7131R;
break;
}
break;
case 0x02:
PDEBUG(D_PROBE, "Sensor TAS5130C");
sd->sensor = SENSOR_TAS5130C;
break;
case 0x04:
PDEBUG(D_PROBE, "Find Sensor CS2102");
sd->sensor = SENSOR_CS2102;
break;
case 0x08:
PDEBUG(D_PROBE, "Find Sensor HDCS2020");
sd->sensor = SENSOR_HDCS2020;
break;
case 0x0a:
PDEBUG(D_PROBE,
"Find Sensor PB0330. Chip revision %x",
sd->chip_revision);
sd->sensor = SENSOR_PB0330;
break;
case 0x0c:
PDEBUG(D_PROBE, "Find Sensor ICM105A");
sd->sensor = SENSOR_ICM105A;
break;
case 0x0e:
PDEBUG(D_PROBE, "Find Sensor PAS202B");
sd->sensor = SENSOR_PAS202B;
/* sd->sharpness = 1; */
break;
case 0x0f:
PDEBUG(D_PROBE, "Find Sensor PAS106");
sd->sensor = SENSOR_PAS106;
break;
case 0x10:
case 0x12:
PDEBUG(D_PROBE, "Find Sensor TAS5130C");
sd->sensor = SENSOR_TAS5130C;
break;
case 0x11:
PDEBUG(D_PROBE, "Find Sensor HV7131R");
sd->sensor = SENSOR_HV7131R;
break;
case 0x13:
case 0x15:
PDEBUG(D_PROBE,
"Sensor MT9V111. Chip revision %04x",
sd->chip_revision);
sd->sensor = sd->bridge == BRIDGE_ZC301
? SENSOR_MT9V111_1
: SENSOR_MT9V111_3;
break;
case 0x14:
PDEBUG(D_PROBE,
"Find Sensor CS2102K?. Chip revision %x",
sd->chip_revision);
sd->sensor = SENSOR_CS2102K;
break;
case 0x16:
PDEBUG(D_PROBE, "Find Sensor ADCM2700");
sd->sensor = SENSOR_ADCM2700;
break;
case 0x29:
PDEBUG(D_PROBE, "Find Sensor GC0305");
sd->sensor = SENSOR_GC0305;
break;
case 0x0303:
PDEBUG(D_PROBE, "Sensor GC0303");
sd->sensor = SENSOR_GC0303;
break;
case 0x2030:
PDEBUG(D_PROBE, "Find Sensor PO2030");
sd->sensor = SENSOR_PO2030;
sd->ctrls[SHARPNESS].def = 0; /* from win traces */
break;
case 0x7620:
PDEBUG(D_PROBE, "Find Sensor OV7620");
sd->sensor = SENSOR_OV7620;
break;
case 0x7631:
PDEBUG(D_PROBE, "Find Sensor OV7630C");
sd->sensor = SENSOR_OV7630C;
break;
case 0x7648:
PDEBUG(D_PROBE, "Find Sensor OV7648");
sd->sensor = SENSOR_OV7620; /* same sensor (?) */
break;
default:
err("Unknown sensor %04x", sensor);
return -EINVAL;
}
}
if (sensor < 0x20) {
if (sensor == -1 || sensor == 0x10 || sensor == 0x12)
reg_w(gspca_dev, 0x02, 0x0010);
reg_r(gspca_dev, 0x0010);
}
cam = &gspca_dev->cam;
switch (mode_tb[sd->sensor]) {
case 0:
cam->cam_mode = sif_mode;
cam->nmodes = ARRAY_SIZE(sif_mode);
break;
case 1:
cam->cam_mode = vga_mode;
cam->nmodes = ARRAY_SIZE(vga_mode);
break;
default:
/* case 2: */
cam->cam_mode = broken_vga_mode;
cam->nmodes = ARRAY_SIZE(broken_vga_mode);
break;
}
sd->ctrls[GAMMA].def = gamma[sd->sensor];
switch (sd->sensor) {
case SENSOR_HV7131R:
break;
case SENSOR_OV7630C:
gspca_dev->ctrl_dis = (1 << LIGHTFREQ) | (1 << EXPOSURE);
break;
default:
gspca_dev->ctrl_dis = (1 << EXPOSURE);
break;
}
#if AUTOGAIN_DEF
if (sd->ctrls[AUTOGAIN].val)
gspca_dev->ctrl_inac = (1 << EXPOSURE);
#endif
/* switch off the led */
reg_w(gspca_dev, 0x01, 0x0000);
return gspca_dev->usb_err;
}
static int sd_start(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
int mode;
static const struct usb_action *init_tb[SENSOR_MAX][2] = {
[SENSOR_ADCM2700] =
{adcm2700_Initial, adcm2700_InitialScale},
[SENSOR_CS2102] =
{cs2102_Initial, cs2102_InitialScale},
[SENSOR_CS2102K] =
{cs2102K_Initial, cs2102K_InitialScale},
[SENSOR_GC0303] =
{gc0303_Initial, gc0303_InitialScale},
[SENSOR_GC0305] =
{gc0305_Initial, gc0305_InitialScale},
[SENSOR_HDCS2020] =
{hdcs2020_Initial, hdcs2020_InitialScale},
[SENSOR_HV7131B] =
{hv7131b_Initial, hv7131b_InitialScale},
[SENSOR_HV7131R] =
{hv7131r_Initial, hv7131r_InitialScale},
[SENSOR_ICM105A] =
{icm105a_Initial, icm105a_InitialScale},
[SENSOR_MC501CB] =
{mc501cb_Initial, mc501cb_InitialScale},
[SENSOR_MT9V111_1] =
{mt9v111_1_Initial, mt9v111_1_InitialScale},
[SENSOR_MT9V111_3] =
{mt9v111_3_Initial, mt9v111_3_InitialScale},
[SENSOR_OV7620] =
{ov7620_Initial, ov7620_InitialScale},
[SENSOR_OV7630C] =
{ov7630c_Initial, ov7630c_InitialScale},
[SENSOR_PAS106] =
{pas106b_Initial, pas106b_InitialScale},
[SENSOR_PAS202B] =
{pas202b_Initial, pas202b_InitialScale},
[SENSOR_PB0330] =
{pb0330_Initial, pb0330_InitialScale},
[SENSOR_PO2030] =
{po2030_Initial, po2030_InitialScale},
[SENSOR_TAS5130C] =
{tas5130c_Initial, tas5130c_InitialScale},
};
/* create the JPEG header */
jpeg_define(sd->jpeg_hdr, gspca_dev->height, gspca_dev->width,
0x21); /* JPEG 422 */
jpeg_set_qual(sd->jpeg_hdr, sd->quality);
mode = gspca_dev->cam.cam_mode[gspca_dev->curr_mode].priv;
switch (sd->sensor) {
case SENSOR_HV7131R:
zcxx_probeSensor(gspca_dev);
break;
case SENSOR_PAS106:
usb_exchange(gspca_dev, pas106b_Initial_com);
break;
}
usb_exchange(gspca_dev, init_tb[sd->sensor][mode]);
switch (sd->sensor) {
case SENSOR_ADCM2700:
case SENSOR_GC0305:
case SENSOR_OV7620:
case SENSOR_PO2030:
case SENSOR_TAS5130C:
case SENSOR_GC0303:
/* msleep(100); * ?? */
reg_r(gspca_dev, 0x0002); /* --> 0x40 */
reg_w(gspca_dev, 0x09, 0x01ad); /* (from win traces) */
reg_w(gspca_dev, 0x15, 0x01ae);
if (sd->sensor == SENSOR_TAS5130C)
break;
reg_w(gspca_dev, 0x0d, 0x003a);
reg_w(gspca_dev, 0x02, 0x003b);
reg_w(gspca_dev, 0x00, 0x0038);
break;
case SENSOR_HV7131R:
case SENSOR_PAS202B:
reg_w(gspca_dev, 0x03, 0x003b);
reg_w(gspca_dev, 0x0c, 0x003a);
reg_w(gspca_dev, 0x0b, 0x0039);
if (sd->sensor == SENSOR_HV7131R)
reg_w(gspca_dev, 0x50, ZC3XX_R11D_GLOBALGAIN);
break;
}
setmatrix(gspca_dev);
switch (sd->sensor) {
case SENSOR_ADCM2700:
case SENSOR_OV7620:
reg_r(gspca_dev, 0x0008);
reg_w(gspca_dev, 0x00, 0x0008);
break;
case SENSOR_PAS202B:
case SENSOR_GC0305:
case SENSOR_HV7131R:
case SENSOR_TAS5130C:
reg_r(gspca_dev, 0x0008);
/* fall thru */
case SENSOR_PO2030:
reg_w(gspca_dev, 0x03, 0x0008);
break;
}
setsharpness(gspca_dev);
/* set the gamma tables when not set */
switch (sd->sensor) {
case SENSOR_CS2102K: /* gamma set in xxx_Initial */
case SENSOR_HDCS2020:
case SENSOR_OV7630C:
break;
default:
setcontrast(gspca_dev);
break;
}
setmatrix(gspca_dev); /* one more time? */
switch (sd->sensor) {
case SENSOR_OV7620:
case SENSOR_PAS202B:
reg_r(gspca_dev, 0x0180); /* from win */
reg_w(gspca_dev, 0x00, 0x0180);
break;
default:
setquality(gspca_dev);
break;
}
setlightfreq(gspca_dev);
switch (sd->sensor) {
case SENSOR_ADCM2700:
reg_w(gspca_dev, 0x09, 0x01ad); /* (from win traces) */
reg_w(gspca_dev, 0x15, 0x01ae);
reg_w(gspca_dev, 0x02, 0x0180);
/* ms-win + */
reg_w(gspca_dev, 0x40, 0x0117);
break;
case SENSOR_HV7131R:
if (!sd->ctrls[AUTOGAIN].val)
setexposure(gspca_dev);
reg_w(gspca_dev, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN);
break;
case SENSOR_GC0305:
case SENSOR_TAS5130C:
reg_w(gspca_dev, 0x09, 0x01ad); /* (from win traces) */
reg_w(gspca_dev, 0x15, 0x01ae);
/* fall thru */
case SENSOR_PAS202B:
case SENSOR_PO2030:
/* reg_w(gspca_dev, 0x40, ZC3XX_R117_GGAIN); in win traces */
reg_r(gspca_dev, 0x0180);
break;
case SENSOR_OV7620:
reg_w(gspca_dev, 0x09, 0x01ad);
reg_w(gspca_dev, 0x15, 0x01ae);
i2c_read(gspca_dev, 0x13); /*fixme: returns 0xa3 */
i2c_write(gspca_dev, 0x13, 0xa3, 0x00);
/*fixme: returned value to send? */
reg_w(gspca_dev, 0x40, 0x0117);
reg_r(gspca_dev, 0x0180);
break;
}
setautogain(gspca_dev);
switch (sd->sensor) {
case SENSOR_PO2030:
msleep(50);
reg_w(gspca_dev, 0x00, 0x0007); /* (from win traces) */
reg_w(gspca_dev, 0x02, ZC3XX_R008_CLOCKSETTING);
break;
}
return gspca_dev->usb_err;
}
/* called on streamoff with alt 0 and on disconnect */
static void sd_stop0(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *) gspca_dev;
if (!gspca_dev->present)
return;
send_unknown(gspca_dev, sd->sensor);
}
static void sd_pkt_scan(struct gspca_dev *gspca_dev,
u8 *data,
int len)
{
struct sd *sd = (struct sd *) gspca_dev;
/* check the JPEG end of frame */
if (len >= 3
&& data[len - 3] == 0xff && data[len - 2] == 0xd9) {
/*fixme: what does the last byte mean?*/
gspca_frame_add(gspca_dev, LAST_PACKET,
data, len - 1);
return;
}
/* check the JPEG start of a frame */
if (data[0] == 0xff && data[1] == 0xd8) {
/* put the JPEG header in the new frame */
gspca_frame_add(gspca_dev, FIRST_PACKET,
sd->jpeg_hdr, JPEG_HDR_SZ);
/* remove the webcam's header:
* ff d8 ff fe 00 0e 00 00 ss ss 00 01 ww ww hh hh pp pp
* - 'ss ss' is the frame sequence number (BE)
* - 'ww ww' and 'hh hh' are the window dimensions (BE)
* - 'pp pp' is the packet sequence number (BE)
*/
data += 18;
len -= 18;
}
gspca_frame_add(gspca_dev, INTER_PACKET, data, len);
}
static int sd_setautogain(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
sd->ctrls[AUTOGAIN].val = val;
if (val) {
gspca_dev->ctrl_inac |= (1 << EXPOSURE);
} else {
gspca_dev->ctrl_inac &= ~(1 << EXPOSURE);
if (gspca_dev->streaming)
getexposure(gspca_dev);
}
if (gspca_dev->streaming)
setautogain(gspca_dev);
return gspca_dev->usb_err;
}
static int sd_querymenu(struct gspca_dev *gspca_dev,
struct v4l2_querymenu *menu)
{
switch (menu->id) {
case V4L2_CID_POWER_LINE_FREQUENCY:
switch (menu->index) {
case 0: /* V4L2_CID_POWER_LINE_FREQUENCY_DISABLED */
strcpy((char *) menu->name, "NoFliker");
return 0;
case 1: /* V4L2_CID_POWER_LINE_FREQUENCY_50HZ */
strcpy((char *) menu->name, "50 Hz");
return 0;
case 2: /* V4L2_CID_POWER_LINE_FREQUENCY_60HZ */
strcpy((char *) menu->name, "60 Hz");
return 0;
}
break;
}
return -EINVAL;
}
static int sd_set_jcomp(struct gspca_dev *gspca_dev,
struct v4l2_jpegcompression *jcomp)
{
struct sd *sd = (struct sd *) gspca_dev;
if (jcomp->quality < QUALITY_MIN)
sd->quality = QUALITY_MIN;
else if (jcomp->quality > QUALITY_MAX)
sd->quality = QUALITY_MAX;
else
sd->quality = jcomp->quality;
if (gspca_dev->streaming)
jpeg_set_qual(sd->jpeg_hdr, sd->quality);
return gspca_dev->usb_err;
}
static int sd_get_jcomp(struct gspca_dev *gspca_dev,
struct v4l2_jpegcompression *jcomp)
{
struct sd *sd = (struct sd *) gspca_dev;
memset(jcomp, 0, sizeof *jcomp);
jcomp->quality = sd->quality;
jcomp->jpeg_markers = V4L2_JPEG_MARKER_DHT
| V4L2_JPEG_MARKER_DQT;
return 0;
}
#if defined(CONFIG_INPUT) || defined(CONFIG_INPUT_MODULE)
static int sd_int_pkt_scan(struct gspca_dev *gspca_dev,
u8 *data, /* interrupt packet data */
int len) /* interrput packet length */
{
if (len == 8 && data[4] == 1) {
input_report_key(gspca_dev->input_dev, KEY_CAMERA, 1);
input_sync(gspca_dev->input_dev);
input_report_key(gspca_dev->input_dev, KEY_CAMERA, 0);
input_sync(gspca_dev->input_dev);
}
return 0;
}
#endif
static const struct sd_desc sd_desc = {
.name = MODULE_NAME,
.ctrls = sd_ctrls,
.nctrls = ARRAY_SIZE(sd_ctrls),
.config = sd_config,
.init = sd_init,
.start = sd_start,
.stop0 = sd_stop0,
.pkt_scan = sd_pkt_scan,
.querymenu = sd_querymenu,
.get_jcomp = sd_get_jcomp,
.set_jcomp = sd_set_jcomp,
#if defined(CONFIG_INPUT) || defined(CONFIG_INPUT_MODULE)
.int_pkt_scan = sd_int_pkt_scan,
#endif
};
static const struct usb_device_id device_table[] = {
{USB_DEVICE(0x041e, 0x041e)},
{USB_DEVICE(0x041e, 0x4017)},
{USB_DEVICE(0x041e, 0x401c), .driver_info = SENSOR_PAS106},
{USB_DEVICE(0x041e, 0x401e)},
{USB_DEVICE(0x041e, 0x401f)},
{USB_DEVICE(0x041e, 0x4022)},
{USB_DEVICE(0x041e, 0x4029)},
{USB_DEVICE(0x041e, 0x4034), .driver_info = SENSOR_PAS106},
{USB_DEVICE(0x041e, 0x4035), .driver_info = SENSOR_PAS106},
{USB_DEVICE(0x041e, 0x4036)},
{USB_DEVICE(0x041e, 0x403a)},
{USB_DEVICE(0x041e, 0x4051), .driver_info = SENSOR_GC0303},
{USB_DEVICE(0x041e, 0x4053), .driver_info = SENSOR_GC0303},
{USB_DEVICE(0x0458, 0x7007)},
{USB_DEVICE(0x0458, 0x700c)},
{USB_DEVICE(0x0458, 0x700f)},
{USB_DEVICE(0x0461, 0x0a00)},
{USB_DEVICE(0x046d, 0x089d), .driver_info = SENSOR_MC501CB},
{USB_DEVICE(0x046d, 0x08a0)},
{USB_DEVICE(0x046d, 0x08a1)},
{USB_DEVICE(0x046d, 0x08a2)},
{USB_DEVICE(0x046d, 0x08a3)},
{USB_DEVICE(0x046d, 0x08a6)},
{USB_DEVICE(0x046d, 0x08a7)},
{USB_DEVICE(0x046d, 0x08a9)},
{USB_DEVICE(0x046d, 0x08aa)},
{USB_DEVICE(0x046d, 0x08ac)},
{USB_DEVICE(0x046d, 0x08ad)},
{USB_DEVICE(0x046d, 0x08ae)},
{USB_DEVICE(0x046d, 0x08af)},
{USB_DEVICE(0x046d, 0x08b9)},
{USB_DEVICE(0x046d, 0x08d7)},
{USB_DEVICE(0x046d, 0x08d8)},
{USB_DEVICE(0x046d, 0x08d9)},
{USB_DEVICE(0x046d, 0x08da)},
{USB_DEVICE(0x046d, 0x08dd), .driver_info = SENSOR_MC501CB},
{USB_DEVICE(0x0471, 0x0325), .driver_info = SENSOR_PAS106},
{USB_DEVICE(0x0471, 0x0326), .driver_info = SENSOR_PAS106},
{USB_DEVICE(0x0471, 0x032d), .driver_info = SENSOR_PAS106},
{USB_DEVICE(0x0471, 0x032e), .driver_info = SENSOR_PAS106},
{USB_DEVICE(0x055f, 0xc005)},
{USB_DEVICE(0x055f, 0xd003)},
{USB_DEVICE(0x055f, 0xd004)},
{USB_DEVICE(0x0698, 0x2003)},
{USB_DEVICE(0x0ac8, 0x0301), .driver_info = SENSOR_PAS106},
{USB_DEVICE(0x0ac8, 0x0302), .driver_info = SENSOR_PAS106},
{USB_DEVICE(0x0ac8, 0x301b)},
{USB_DEVICE(0x0ac8, 0x303b)},
{USB_DEVICE(0x0ac8, 0x305b)},
{USB_DEVICE(0x0ac8, 0x307b)},
{USB_DEVICE(0x10fd, 0x0128)},
{USB_DEVICE(0x10fd, 0x804d)},
{USB_DEVICE(0x10fd, 0x8050)},
{} /* end of entry */
};
MODULE_DEVICE_TABLE(usb, device_table);
/* -- device connect -- */
static int sd_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
return gspca_dev_probe(intf, id, &sd_desc, sizeof(struct sd),
THIS_MODULE);
}
/* USB driver */
static struct usb_driver sd_driver = {
.name = MODULE_NAME,
.id_table = device_table,
.probe = sd_probe,
.disconnect = gspca_disconnect,
#ifdef CONFIG_PM
.suspend = gspca_suspend,
.resume = gspca_resume,
#endif
};
static int __init sd_mod_init(void)
{
return usb_register(&sd_driver);
}
static void __exit sd_mod_exit(void)
{
usb_deregister(&sd_driver);
}
module_init(sd_mod_init);
module_exit(sd_mod_exit);
module_param(force_sensor, int, 0644);
MODULE_PARM_DESC(force_sensor,
"Force sensor. Only for experts!!!");
| gpl-2.0 |
bcnice20/android-kernel-common | drivers/char/ipmi/ipmi_msghandler.c | 3025 | 117719 | /*
* ipmi_msghandler.c
*
* Incoming and outgoing message routing for an IPMI interface.
*
* Author: MontaVista Software, Inc.
* Corey Minyard <minyard@mvista.com>
* source@mvista.com
*
* Copyright 2002 MontaVista Software Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/errno.h>
#include <asm/system.h>
#include <linux/poll.h>
#include <linux/sched.h>
#include <linux/seq_file.h>
#include <linux/spinlock.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/ipmi.h>
#include <linux/ipmi_smi.h>
#include <linux/notifier.h>
#include <linux/init.h>
#include <linux/proc_fs.h>
#include <linux/rcupdate.h>
#define PFX "IPMI message handler: "
#define IPMI_DRIVER_VERSION "39.2"
static struct ipmi_recv_msg *ipmi_alloc_recv_msg(void);
static int ipmi_init_msghandler(void);
static int initialized;
#ifdef CONFIG_PROC_FS
static struct proc_dir_entry *proc_ipmi_root;
#endif /* CONFIG_PROC_FS */
/* Remain in auto-maintenance mode for this amount of time (in ms). */
#define IPMI_MAINTENANCE_MODE_TIMEOUT 30000
#define MAX_EVENTS_IN_QUEUE 25
/*
* Don't let a message sit in a queue forever, always time it with at lest
* the max message timer. This is in milliseconds.
*/
#define MAX_MSG_TIMEOUT 60000
/*
* The main "user" data structure.
*/
struct ipmi_user {
struct list_head link;
/* Set to "0" when the user is destroyed. */
int valid;
struct kref refcount;
/* The upper layer that handles receive messages. */
struct ipmi_user_hndl *handler;
void *handler_data;
/* The interface this user is bound to. */
ipmi_smi_t intf;
/* Does this interface receive IPMI events? */
int gets_events;
};
struct cmd_rcvr {
struct list_head link;
ipmi_user_t user;
unsigned char netfn;
unsigned char cmd;
unsigned int chans;
/*
* This is used to form a linked lised during mass deletion.
* Since this is in an RCU list, we cannot use the link above
* or change any data until the RCU period completes. So we
* use this next variable during mass deletion so we can have
* a list and don't have to wait and restart the search on
* every individual deletion of a command.
*/
struct cmd_rcvr *next;
};
struct seq_table {
unsigned int inuse : 1;
unsigned int broadcast : 1;
unsigned long timeout;
unsigned long orig_timeout;
unsigned int retries_left;
/*
* To verify on an incoming send message response that this is
* the message that the response is for, we keep a sequence id
* and increment it every time we send a message.
*/
long seqid;
/*
* This is held so we can properly respond to the message on a
* timeout, and it is used to hold the temporary data for
* retransmission, too.
*/
struct ipmi_recv_msg *recv_msg;
};
/*
* Store the information in a msgid (long) to allow us to find a
* sequence table entry from the msgid.
*/
#define STORE_SEQ_IN_MSGID(seq, seqid) (((seq&0xff)<<26) | (seqid&0x3ffffff))
#define GET_SEQ_FROM_MSGID(msgid, seq, seqid) \
do { \
seq = ((msgid >> 26) & 0x3f); \
seqid = (msgid & 0x3fffff); \
} while (0)
#define NEXT_SEQID(seqid) (((seqid) + 1) & 0x3fffff)
struct ipmi_channel {
unsigned char medium;
unsigned char protocol;
/*
* My slave address. This is initialized to IPMI_BMC_SLAVE_ADDR,
* but may be changed by the user.
*/
unsigned char address;
/*
* My LUN. This should generally stay the SMS LUN, but just in
* case...
*/
unsigned char lun;
};
#ifdef CONFIG_PROC_FS
struct ipmi_proc_entry {
char *name;
struct ipmi_proc_entry *next;
};
#endif
struct bmc_device {
struct platform_device *dev;
struct ipmi_device_id id;
unsigned char guid[16];
int guid_set;
struct kref refcount;
/* bmc device attributes */
struct device_attribute device_id_attr;
struct device_attribute provides_dev_sdrs_attr;
struct device_attribute revision_attr;
struct device_attribute firmware_rev_attr;
struct device_attribute version_attr;
struct device_attribute add_dev_support_attr;
struct device_attribute manufacturer_id_attr;
struct device_attribute product_id_attr;
struct device_attribute guid_attr;
struct device_attribute aux_firmware_rev_attr;
};
/*
* Various statistics for IPMI, these index stats[] in the ipmi_smi
* structure.
*/
enum ipmi_stat_indexes {
/* Commands we got from the user that were invalid. */
IPMI_STAT_sent_invalid_commands = 0,
/* Commands we sent to the MC. */
IPMI_STAT_sent_local_commands,
/* Responses from the MC that were delivered to a user. */
IPMI_STAT_handled_local_responses,
/* Responses from the MC that were not delivered to a user. */
IPMI_STAT_unhandled_local_responses,
/* Commands we sent out to the IPMB bus. */
IPMI_STAT_sent_ipmb_commands,
/* Commands sent on the IPMB that had errors on the SEND CMD */
IPMI_STAT_sent_ipmb_command_errs,
/* Each retransmit increments this count. */
IPMI_STAT_retransmitted_ipmb_commands,
/*
* When a message times out (runs out of retransmits) this is
* incremented.
*/
IPMI_STAT_timed_out_ipmb_commands,
/*
* This is like above, but for broadcasts. Broadcasts are
* *not* included in the above count (they are expected to
* time out).
*/
IPMI_STAT_timed_out_ipmb_broadcasts,
/* Responses I have sent to the IPMB bus. */
IPMI_STAT_sent_ipmb_responses,
/* The response was delivered to the user. */
IPMI_STAT_handled_ipmb_responses,
/* The response had invalid data in it. */
IPMI_STAT_invalid_ipmb_responses,
/* The response didn't have anyone waiting for it. */
IPMI_STAT_unhandled_ipmb_responses,
/* Commands we sent out to the IPMB bus. */
IPMI_STAT_sent_lan_commands,
/* Commands sent on the IPMB that had errors on the SEND CMD */
IPMI_STAT_sent_lan_command_errs,
/* Each retransmit increments this count. */
IPMI_STAT_retransmitted_lan_commands,
/*
* When a message times out (runs out of retransmits) this is
* incremented.
*/
IPMI_STAT_timed_out_lan_commands,
/* Responses I have sent to the IPMB bus. */
IPMI_STAT_sent_lan_responses,
/* The response was delivered to the user. */
IPMI_STAT_handled_lan_responses,
/* The response had invalid data in it. */
IPMI_STAT_invalid_lan_responses,
/* The response didn't have anyone waiting for it. */
IPMI_STAT_unhandled_lan_responses,
/* The command was delivered to the user. */
IPMI_STAT_handled_commands,
/* The command had invalid data in it. */
IPMI_STAT_invalid_commands,
/* The command didn't have anyone waiting for it. */
IPMI_STAT_unhandled_commands,
/* Invalid data in an event. */
IPMI_STAT_invalid_events,
/* Events that were received with the proper format. */
IPMI_STAT_events,
/* Retransmissions on IPMB that failed. */
IPMI_STAT_dropped_rexmit_ipmb_commands,
/* Retransmissions on LAN that failed. */
IPMI_STAT_dropped_rexmit_lan_commands,
/* This *must* remain last, add new values above this. */
IPMI_NUM_STATS
};
#define IPMI_IPMB_NUM_SEQ 64
#define IPMI_MAX_CHANNELS 16
struct ipmi_smi {
/* What interface number are we? */
int intf_num;
struct kref refcount;
/* Used for a list of interfaces. */
struct list_head link;
/*
* The list of upper layers that are using me. seq_lock
* protects this.
*/
struct list_head users;
/* Information to supply to users. */
unsigned char ipmi_version_major;
unsigned char ipmi_version_minor;
/* Used for wake ups at startup. */
wait_queue_head_t waitq;
struct bmc_device *bmc;
char *my_dev_name;
char *sysfs_name;
/*
* This is the lower-layer's sender routine. Note that you
* must either be holding the ipmi_interfaces_mutex or be in
* an umpreemptible region to use this. You must fetch the
* value into a local variable and make sure it is not NULL.
*/
struct ipmi_smi_handlers *handlers;
void *send_info;
#ifdef CONFIG_PROC_FS
/* A list of proc entries for this interface. */
struct mutex proc_entry_lock;
struct ipmi_proc_entry *proc_entries;
#endif
/* Driver-model device for the system interface. */
struct device *si_dev;
/*
* A table of sequence numbers for this interface. We use the
* sequence numbers for IPMB messages that go out of the
* interface to match them up with their responses. A routine
* is called periodically to time the items in this list.
*/
spinlock_t seq_lock;
struct seq_table seq_table[IPMI_IPMB_NUM_SEQ];
int curr_seq;
/*
* Messages that were delayed for some reason (out of memory,
* for instance), will go in here to be processed later in a
* periodic timer interrupt.
*/
spinlock_t waiting_msgs_lock;
struct list_head waiting_msgs;
/*
* The list of command receivers that are registered for commands
* on this interface.
*/
struct mutex cmd_rcvrs_mutex;
struct list_head cmd_rcvrs;
/*
* Events that were queues because no one was there to receive
* them.
*/
spinlock_t events_lock; /* For dealing with event stuff. */
struct list_head waiting_events;
unsigned int waiting_events_count; /* How many events in queue? */
char delivering_events;
char event_msg_printed;
/*
* The event receiver for my BMC, only really used at panic
* shutdown as a place to store this.
*/
unsigned char event_receiver;
unsigned char event_receiver_lun;
unsigned char local_sel_device;
unsigned char local_event_generator;
/* For handling of maintenance mode. */
int maintenance_mode;
int maintenance_mode_enable;
int auto_maintenance_timeout;
spinlock_t maintenance_mode_lock; /* Used in a timer... */
/*
* A cheap hack, if this is non-null and a message to an
* interface comes in with a NULL user, call this routine with
* it. Note that the message will still be freed by the
* caller. This only works on the system interface.
*/
void (*null_user_handler)(ipmi_smi_t intf, struct ipmi_recv_msg *msg);
/*
* When we are scanning the channels for an SMI, this will
* tell which channel we are scanning.
*/
int curr_channel;
/* Channel information */
struct ipmi_channel channels[IPMI_MAX_CHANNELS];
/* Proc FS stuff. */
struct proc_dir_entry *proc_dir;
char proc_dir_name[10];
atomic_t stats[IPMI_NUM_STATS];
/*
* run_to_completion duplicate of smb_info, smi_info
* and ipmi_serial_info structures. Used to decrease numbers of
* parameters passed by "low" level IPMI code.
*/
int run_to_completion;
};
#define to_si_intf_from_dev(device) container_of(device, struct ipmi_smi, dev)
/**
* The driver model view of the IPMI messaging driver.
*/
static struct platform_driver ipmidriver = {
.driver = {
.name = "ipmi",
.bus = &platform_bus_type
}
};
static DEFINE_MUTEX(ipmidriver_mutex);
static LIST_HEAD(ipmi_interfaces);
static DEFINE_MUTEX(ipmi_interfaces_mutex);
/*
* List of watchers that want to know when smi's are added and deleted.
*/
static LIST_HEAD(smi_watchers);
static DEFINE_MUTEX(smi_watchers_mutex);
#define ipmi_inc_stat(intf, stat) \
atomic_inc(&(intf)->stats[IPMI_STAT_ ## stat])
#define ipmi_get_stat(intf, stat) \
((unsigned int) atomic_read(&(intf)->stats[IPMI_STAT_ ## stat]))
static int is_lan_addr(struct ipmi_addr *addr)
{
return addr->addr_type == IPMI_LAN_ADDR_TYPE;
}
static int is_ipmb_addr(struct ipmi_addr *addr)
{
return addr->addr_type == IPMI_IPMB_ADDR_TYPE;
}
static int is_ipmb_bcast_addr(struct ipmi_addr *addr)
{
return addr->addr_type == IPMI_IPMB_BROADCAST_ADDR_TYPE;
}
static void free_recv_msg_list(struct list_head *q)
{
struct ipmi_recv_msg *msg, *msg2;
list_for_each_entry_safe(msg, msg2, q, link) {
list_del(&msg->link);
ipmi_free_recv_msg(msg);
}
}
static void free_smi_msg_list(struct list_head *q)
{
struct ipmi_smi_msg *msg, *msg2;
list_for_each_entry_safe(msg, msg2, q, link) {
list_del(&msg->link);
ipmi_free_smi_msg(msg);
}
}
static void clean_up_interface_data(ipmi_smi_t intf)
{
int i;
struct cmd_rcvr *rcvr, *rcvr2;
struct list_head list;
free_smi_msg_list(&intf->waiting_msgs);
free_recv_msg_list(&intf->waiting_events);
/*
* Wholesale remove all the entries from the list in the
* interface and wait for RCU to know that none are in use.
*/
mutex_lock(&intf->cmd_rcvrs_mutex);
INIT_LIST_HEAD(&list);
list_splice_init_rcu(&intf->cmd_rcvrs, &list, synchronize_rcu);
mutex_unlock(&intf->cmd_rcvrs_mutex);
list_for_each_entry_safe(rcvr, rcvr2, &list, link)
kfree(rcvr);
for (i = 0; i < IPMI_IPMB_NUM_SEQ; i++) {
if ((intf->seq_table[i].inuse)
&& (intf->seq_table[i].recv_msg))
ipmi_free_recv_msg(intf->seq_table[i].recv_msg);
}
}
static void intf_free(struct kref *ref)
{
ipmi_smi_t intf = container_of(ref, struct ipmi_smi, refcount);
clean_up_interface_data(intf);
kfree(intf);
}
struct watcher_entry {
int intf_num;
ipmi_smi_t intf;
struct list_head link;
};
int ipmi_smi_watcher_register(struct ipmi_smi_watcher *watcher)
{
ipmi_smi_t intf;
LIST_HEAD(to_deliver);
struct watcher_entry *e, *e2;
mutex_lock(&smi_watchers_mutex);
mutex_lock(&ipmi_interfaces_mutex);
/* Build a list of things to deliver. */
list_for_each_entry(intf, &ipmi_interfaces, link) {
if (intf->intf_num == -1)
continue;
e = kmalloc(sizeof(*e), GFP_KERNEL);
if (!e)
goto out_err;
kref_get(&intf->refcount);
e->intf = intf;
e->intf_num = intf->intf_num;
list_add_tail(&e->link, &to_deliver);
}
/* We will succeed, so add it to the list. */
list_add(&watcher->link, &smi_watchers);
mutex_unlock(&ipmi_interfaces_mutex);
list_for_each_entry_safe(e, e2, &to_deliver, link) {
list_del(&e->link);
watcher->new_smi(e->intf_num, e->intf->si_dev);
kref_put(&e->intf->refcount, intf_free);
kfree(e);
}
mutex_unlock(&smi_watchers_mutex);
return 0;
out_err:
mutex_unlock(&ipmi_interfaces_mutex);
mutex_unlock(&smi_watchers_mutex);
list_for_each_entry_safe(e, e2, &to_deliver, link) {
list_del(&e->link);
kref_put(&e->intf->refcount, intf_free);
kfree(e);
}
return -ENOMEM;
}
EXPORT_SYMBOL(ipmi_smi_watcher_register);
int ipmi_smi_watcher_unregister(struct ipmi_smi_watcher *watcher)
{
mutex_lock(&smi_watchers_mutex);
list_del(&(watcher->link));
mutex_unlock(&smi_watchers_mutex);
return 0;
}
EXPORT_SYMBOL(ipmi_smi_watcher_unregister);
/*
* Must be called with smi_watchers_mutex held.
*/
static void
call_smi_watchers(int i, struct device *dev)
{
struct ipmi_smi_watcher *w;
list_for_each_entry(w, &smi_watchers, link) {
if (try_module_get(w->owner)) {
w->new_smi(i, dev);
module_put(w->owner);
}
}
}
static int
ipmi_addr_equal(struct ipmi_addr *addr1, struct ipmi_addr *addr2)
{
if (addr1->addr_type != addr2->addr_type)
return 0;
if (addr1->channel != addr2->channel)
return 0;
if (addr1->addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE) {
struct ipmi_system_interface_addr *smi_addr1
= (struct ipmi_system_interface_addr *) addr1;
struct ipmi_system_interface_addr *smi_addr2
= (struct ipmi_system_interface_addr *) addr2;
return (smi_addr1->lun == smi_addr2->lun);
}
if (is_ipmb_addr(addr1) || is_ipmb_bcast_addr(addr1)) {
struct ipmi_ipmb_addr *ipmb_addr1
= (struct ipmi_ipmb_addr *) addr1;
struct ipmi_ipmb_addr *ipmb_addr2
= (struct ipmi_ipmb_addr *) addr2;
return ((ipmb_addr1->slave_addr == ipmb_addr2->slave_addr)
&& (ipmb_addr1->lun == ipmb_addr2->lun));
}
if (is_lan_addr(addr1)) {
struct ipmi_lan_addr *lan_addr1
= (struct ipmi_lan_addr *) addr1;
struct ipmi_lan_addr *lan_addr2
= (struct ipmi_lan_addr *) addr2;
return ((lan_addr1->remote_SWID == lan_addr2->remote_SWID)
&& (lan_addr1->local_SWID == lan_addr2->local_SWID)
&& (lan_addr1->session_handle
== lan_addr2->session_handle)
&& (lan_addr1->lun == lan_addr2->lun));
}
return 1;
}
int ipmi_validate_addr(struct ipmi_addr *addr, int len)
{
if (len < sizeof(struct ipmi_system_interface_addr))
return -EINVAL;
if (addr->addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE) {
if (addr->channel != IPMI_BMC_CHANNEL)
return -EINVAL;
return 0;
}
if ((addr->channel == IPMI_BMC_CHANNEL)
|| (addr->channel >= IPMI_MAX_CHANNELS)
|| (addr->channel < 0))
return -EINVAL;
if (is_ipmb_addr(addr) || is_ipmb_bcast_addr(addr)) {
if (len < sizeof(struct ipmi_ipmb_addr))
return -EINVAL;
return 0;
}
if (is_lan_addr(addr)) {
if (len < sizeof(struct ipmi_lan_addr))
return -EINVAL;
return 0;
}
return -EINVAL;
}
EXPORT_SYMBOL(ipmi_validate_addr);
unsigned int ipmi_addr_length(int addr_type)
{
if (addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE)
return sizeof(struct ipmi_system_interface_addr);
if ((addr_type == IPMI_IPMB_ADDR_TYPE)
|| (addr_type == IPMI_IPMB_BROADCAST_ADDR_TYPE))
return sizeof(struct ipmi_ipmb_addr);
if (addr_type == IPMI_LAN_ADDR_TYPE)
return sizeof(struct ipmi_lan_addr);
return 0;
}
EXPORT_SYMBOL(ipmi_addr_length);
static void deliver_response(struct ipmi_recv_msg *msg)
{
if (!msg->user) {
ipmi_smi_t intf = msg->user_msg_data;
/* Special handling for NULL users. */
if (intf->null_user_handler) {
intf->null_user_handler(intf, msg);
ipmi_inc_stat(intf, handled_local_responses);
} else {
/* No handler, so give up. */
ipmi_inc_stat(intf, unhandled_local_responses);
}
ipmi_free_recv_msg(msg);
} else {
ipmi_user_t user = msg->user;
user->handler->ipmi_recv_hndl(msg, user->handler_data);
}
}
static void
deliver_err_response(struct ipmi_recv_msg *msg, int err)
{
msg->recv_type = IPMI_RESPONSE_RECV_TYPE;
msg->msg_data[0] = err;
msg->msg.netfn |= 1; /* Convert to a response. */
msg->msg.data_len = 1;
msg->msg.data = msg->msg_data;
deliver_response(msg);
}
/*
* Find the next sequence number not being used and add the given
* message with the given timeout to the sequence table. This must be
* called with the interface's seq_lock held.
*/
static int intf_next_seq(ipmi_smi_t intf,
struct ipmi_recv_msg *recv_msg,
unsigned long timeout,
int retries,
int broadcast,
unsigned char *seq,
long *seqid)
{
int rv = 0;
unsigned int i;
for (i = intf->curr_seq; (i+1)%IPMI_IPMB_NUM_SEQ != intf->curr_seq;
i = (i+1)%IPMI_IPMB_NUM_SEQ) {
if (!intf->seq_table[i].inuse)
break;
}
if (!intf->seq_table[i].inuse) {
intf->seq_table[i].recv_msg = recv_msg;
/*
* Start with the maximum timeout, when the send response
* comes in we will start the real timer.
*/
intf->seq_table[i].timeout = MAX_MSG_TIMEOUT;
intf->seq_table[i].orig_timeout = timeout;
intf->seq_table[i].retries_left = retries;
intf->seq_table[i].broadcast = broadcast;
intf->seq_table[i].inuse = 1;
intf->seq_table[i].seqid = NEXT_SEQID(intf->seq_table[i].seqid);
*seq = i;
*seqid = intf->seq_table[i].seqid;
intf->curr_seq = (i+1)%IPMI_IPMB_NUM_SEQ;
} else {
rv = -EAGAIN;
}
return rv;
}
/*
* Return the receive message for the given sequence number and
* release the sequence number so it can be reused. Some other data
* is passed in to be sure the message matches up correctly (to help
* guard against message coming in after their timeout and the
* sequence number being reused).
*/
static int intf_find_seq(ipmi_smi_t intf,
unsigned char seq,
short channel,
unsigned char cmd,
unsigned char netfn,
struct ipmi_addr *addr,
struct ipmi_recv_msg **recv_msg)
{
int rv = -ENODEV;
unsigned long flags;
if (seq >= IPMI_IPMB_NUM_SEQ)
return -EINVAL;
spin_lock_irqsave(&(intf->seq_lock), flags);
if (intf->seq_table[seq].inuse) {
struct ipmi_recv_msg *msg = intf->seq_table[seq].recv_msg;
if ((msg->addr.channel == channel) && (msg->msg.cmd == cmd)
&& (msg->msg.netfn == netfn)
&& (ipmi_addr_equal(addr, &(msg->addr)))) {
*recv_msg = msg;
intf->seq_table[seq].inuse = 0;
rv = 0;
}
}
spin_unlock_irqrestore(&(intf->seq_lock), flags);
return rv;
}
/* Start the timer for a specific sequence table entry. */
static int intf_start_seq_timer(ipmi_smi_t intf,
long msgid)
{
int rv = -ENODEV;
unsigned long flags;
unsigned char seq;
unsigned long seqid;
GET_SEQ_FROM_MSGID(msgid, seq, seqid);
spin_lock_irqsave(&(intf->seq_lock), flags);
/*
* We do this verification because the user can be deleted
* while a message is outstanding.
*/
if ((intf->seq_table[seq].inuse)
&& (intf->seq_table[seq].seqid == seqid)) {
struct seq_table *ent = &(intf->seq_table[seq]);
ent->timeout = ent->orig_timeout;
rv = 0;
}
spin_unlock_irqrestore(&(intf->seq_lock), flags);
return rv;
}
/* Got an error for the send message for a specific sequence number. */
static int intf_err_seq(ipmi_smi_t intf,
long msgid,
unsigned int err)
{
int rv = -ENODEV;
unsigned long flags;
unsigned char seq;
unsigned long seqid;
struct ipmi_recv_msg *msg = NULL;
GET_SEQ_FROM_MSGID(msgid, seq, seqid);
spin_lock_irqsave(&(intf->seq_lock), flags);
/*
* We do this verification because the user can be deleted
* while a message is outstanding.
*/
if ((intf->seq_table[seq].inuse)
&& (intf->seq_table[seq].seqid == seqid)) {
struct seq_table *ent = &(intf->seq_table[seq]);
ent->inuse = 0;
msg = ent->recv_msg;
rv = 0;
}
spin_unlock_irqrestore(&(intf->seq_lock), flags);
if (msg)
deliver_err_response(msg, err);
return rv;
}
int ipmi_create_user(unsigned int if_num,
struct ipmi_user_hndl *handler,
void *handler_data,
ipmi_user_t *user)
{
unsigned long flags;
ipmi_user_t new_user;
int rv = 0;
ipmi_smi_t intf;
/*
* There is no module usecount here, because it's not
* required. Since this can only be used by and called from
* other modules, they will implicitly use this module, and
* thus this can't be removed unless the other modules are
* removed.
*/
if (handler == NULL)
return -EINVAL;
/*
* Make sure the driver is actually initialized, this handles
* problems with initialization order.
*/
if (!initialized) {
rv = ipmi_init_msghandler();
if (rv)
return rv;
/*
* The init code doesn't return an error if it was turned
* off, but it won't initialize. Check that.
*/
if (!initialized)
return -ENODEV;
}
new_user = kmalloc(sizeof(*new_user), GFP_KERNEL);
if (!new_user)
return -ENOMEM;
mutex_lock(&ipmi_interfaces_mutex);
list_for_each_entry_rcu(intf, &ipmi_interfaces, link) {
if (intf->intf_num == if_num)
goto found;
}
/* Not found, return an error */
rv = -EINVAL;
goto out_kfree;
found:
/* Note that each existing user holds a refcount to the interface. */
kref_get(&intf->refcount);
kref_init(&new_user->refcount);
new_user->handler = handler;
new_user->handler_data = handler_data;
new_user->intf = intf;
new_user->gets_events = 0;
if (!try_module_get(intf->handlers->owner)) {
rv = -ENODEV;
goto out_kref;
}
if (intf->handlers->inc_usecount) {
rv = intf->handlers->inc_usecount(intf->send_info);
if (rv) {
module_put(intf->handlers->owner);
goto out_kref;
}
}
/*
* Hold the lock so intf->handlers is guaranteed to be good
* until now
*/
mutex_unlock(&ipmi_interfaces_mutex);
new_user->valid = 1;
spin_lock_irqsave(&intf->seq_lock, flags);
list_add_rcu(&new_user->link, &intf->users);
spin_unlock_irqrestore(&intf->seq_lock, flags);
*user = new_user;
return 0;
out_kref:
kref_put(&intf->refcount, intf_free);
out_kfree:
mutex_unlock(&ipmi_interfaces_mutex);
kfree(new_user);
return rv;
}
EXPORT_SYMBOL(ipmi_create_user);
int ipmi_get_smi_info(int if_num, struct ipmi_smi_info *data)
{
int rv = 0;
ipmi_smi_t intf;
struct ipmi_smi_handlers *handlers;
mutex_lock(&ipmi_interfaces_mutex);
list_for_each_entry_rcu(intf, &ipmi_interfaces, link) {
if (intf->intf_num == if_num)
goto found;
}
/* Not found, return an error */
rv = -EINVAL;
mutex_unlock(&ipmi_interfaces_mutex);
return rv;
found:
handlers = intf->handlers;
rv = -ENOSYS;
if (handlers->get_smi_info)
rv = handlers->get_smi_info(intf->send_info, data);
mutex_unlock(&ipmi_interfaces_mutex);
return rv;
}
EXPORT_SYMBOL(ipmi_get_smi_info);
static void free_user(struct kref *ref)
{
ipmi_user_t user = container_of(ref, struct ipmi_user, refcount);
kfree(user);
}
int ipmi_destroy_user(ipmi_user_t user)
{
ipmi_smi_t intf = user->intf;
int i;
unsigned long flags;
struct cmd_rcvr *rcvr;
struct cmd_rcvr *rcvrs = NULL;
user->valid = 0;
/* Remove the user from the interface's sequence table. */
spin_lock_irqsave(&intf->seq_lock, flags);
list_del_rcu(&user->link);
for (i = 0; i < IPMI_IPMB_NUM_SEQ; i++) {
if (intf->seq_table[i].inuse
&& (intf->seq_table[i].recv_msg->user == user)) {
intf->seq_table[i].inuse = 0;
ipmi_free_recv_msg(intf->seq_table[i].recv_msg);
}
}
spin_unlock_irqrestore(&intf->seq_lock, flags);
/*
* Remove the user from the command receiver's table. First
* we build a list of everything (not using the standard link,
* since other things may be using it till we do
* synchronize_rcu()) then free everything in that list.
*/
mutex_lock(&intf->cmd_rcvrs_mutex);
list_for_each_entry_rcu(rcvr, &intf->cmd_rcvrs, link) {
if (rcvr->user == user) {
list_del_rcu(&rcvr->link);
rcvr->next = rcvrs;
rcvrs = rcvr;
}
}
mutex_unlock(&intf->cmd_rcvrs_mutex);
synchronize_rcu();
while (rcvrs) {
rcvr = rcvrs;
rcvrs = rcvr->next;
kfree(rcvr);
}
mutex_lock(&ipmi_interfaces_mutex);
if (intf->handlers) {
module_put(intf->handlers->owner);
if (intf->handlers->dec_usecount)
intf->handlers->dec_usecount(intf->send_info);
}
mutex_unlock(&ipmi_interfaces_mutex);
kref_put(&intf->refcount, intf_free);
kref_put(&user->refcount, free_user);
return 0;
}
EXPORT_SYMBOL(ipmi_destroy_user);
void ipmi_get_version(ipmi_user_t user,
unsigned char *major,
unsigned char *minor)
{
*major = user->intf->ipmi_version_major;
*minor = user->intf->ipmi_version_minor;
}
EXPORT_SYMBOL(ipmi_get_version);
int ipmi_set_my_address(ipmi_user_t user,
unsigned int channel,
unsigned char address)
{
if (channel >= IPMI_MAX_CHANNELS)
return -EINVAL;
user->intf->channels[channel].address = address;
return 0;
}
EXPORT_SYMBOL(ipmi_set_my_address);
int ipmi_get_my_address(ipmi_user_t user,
unsigned int channel,
unsigned char *address)
{
if (channel >= IPMI_MAX_CHANNELS)
return -EINVAL;
*address = user->intf->channels[channel].address;
return 0;
}
EXPORT_SYMBOL(ipmi_get_my_address);
int ipmi_set_my_LUN(ipmi_user_t user,
unsigned int channel,
unsigned char LUN)
{
if (channel >= IPMI_MAX_CHANNELS)
return -EINVAL;
user->intf->channels[channel].lun = LUN & 0x3;
return 0;
}
EXPORT_SYMBOL(ipmi_set_my_LUN);
int ipmi_get_my_LUN(ipmi_user_t user,
unsigned int channel,
unsigned char *address)
{
if (channel >= IPMI_MAX_CHANNELS)
return -EINVAL;
*address = user->intf->channels[channel].lun;
return 0;
}
EXPORT_SYMBOL(ipmi_get_my_LUN);
int ipmi_get_maintenance_mode(ipmi_user_t user)
{
int mode;
unsigned long flags;
spin_lock_irqsave(&user->intf->maintenance_mode_lock, flags);
mode = user->intf->maintenance_mode;
spin_unlock_irqrestore(&user->intf->maintenance_mode_lock, flags);
return mode;
}
EXPORT_SYMBOL(ipmi_get_maintenance_mode);
static void maintenance_mode_update(ipmi_smi_t intf)
{
if (intf->handlers->set_maintenance_mode)
intf->handlers->set_maintenance_mode(
intf->send_info, intf->maintenance_mode_enable);
}
int ipmi_set_maintenance_mode(ipmi_user_t user, int mode)
{
int rv = 0;
unsigned long flags;
ipmi_smi_t intf = user->intf;
spin_lock_irqsave(&intf->maintenance_mode_lock, flags);
if (intf->maintenance_mode != mode) {
switch (mode) {
case IPMI_MAINTENANCE_MODE_AUTO:
intf->maintenance_mode = mode;
intf->maintenance_mode_enable
= (intf->auto_maintenance_timeout > 0);
break;
case IPMI_MAINTENANCE_MODE_OFF:
intf->maintenance_mode = mode;
intf->maintenance_mode_enable = 0;
break;
case IPMI_MAINTENANCE_MODE_ON:
intf->maintenance_mode = mode;
intf->maintenance_mode_enable = 1;
break;
default:
rv = -EINVAL;
goto out_unlock;
}
maintenance_mode_update(intf);
}
out_unlock:
spin_unlock_irqrestore(&intf->maintenance_mode_lock, flags);
return rv;
}
EXPORT_SYMBOL(ipmi_set_maintenance_mode);
int ipmi_set_gets_events(ipmi_user_t user, int val)
{
unsigned long flags;
ipmi_smi_t intf = user->intf;
struct ipmi_recv_msg *msg, *msg2;
struct list_head msgs;
INIT_LIST_HEAD(&msgs);
spin_lock_irqsave(&intf->events_lock, flags);
user->gets_events = val;
if (intf->delivering_events)
/*
* Another thread is delivering events for this, so
* let it handle any new events.
*/
goto out;
/* Deliver any queued events. */
while (user->gets_events && !list_empty(&intf->waiting_events)) {
list_for_each_entry_safe(msg, msg2, &intf->waiting_events, link)
list_move_tail(&msg->link, &msgs);
intf->waiting_events_count = 0;
if (intf->event_msg_printed) {
printk(KERN_WARNING PFX "Event queue no longer"
" full\n");
intf->event_msg_printed = 0;
}
intf->delivering_events = 1;
spin_unlock_irqrestore(&intf->events_lock, flags);
list_for_each_entry_safe(msg, msg2, &msgs, link) {
msg->user = user;
kref_get(&user->refcount);
deliver_response(msg);
}
spin_lock_irqsave(&intf->events_lock, flags);
intf->delivering_events = 0;
}
out:
spin_unlock_irqrestore(&intf->events_lock, flags);
return 0;
}
EXPORT_SYMBOL(ipmi_set_gets_events);
static struct cmd_rcvr *find_cmd_rcvr(ipmi_smi_t intf,
unsigned char netfn,
unsigned char cmd,
unsigned char chan)
{
struct cmd_rcvr *rcvr;
list_for_each_entry_rcu(rcvr, &intf->cmd_rcvrs, link) {
if ((rcvr->netfn == netfn) && (rcvr->cmd == cmd)
&& (rcvr->chans & (1 << chan)))
return rcvr;
}
return NULL;
}
static int is_cmd_rcvr_exclusive(ipmi_smi_t intf,
unsigned char netfn,
unsigned char cmd,
unsigned int chans)
{
struct cmd_rcvr *rcvr;
list_for_each_entry_rcu(rcvr, &intf->cmd_rcvrs, link) {
if ((rcvr->netfn == netfn) && (rcvr->cmd == cmd)
&& (rcvr->chans & chans))
return 0;
}
return 1;
}
int ipmi_register_for_cmd(ipmi_user_t user,
unsigned char netfn,
unsigned char cmd,
unsigned int chans)
{
ipmi_smi_t intf = user->intf;
struct cmd_rcvr *rcvr;
int rv = 0;
rcvr = kmalloc(sizeof(*rcvr), GFP_KERNEL);
if (!rcvr)
return -ENOMEM;
rcvr->cmd = cmd;
rcvr->netfn = netfn;
rcvr->chans = chans;
rcvr->user = user;
mutex_lock(&intf->cmd_rcvrs_mutex);
/* Make sure the command/netfn is not already registered. */
if (!is_cmd_rcvr_exclusive(intf, netfn, cmd, chans)) {
rv = -EBUSY;
goto out_unlock;
}
list_add_rcu(&rcvr->link, &intf->cmd_rcvrs);
out_unlock:
mutex_unlock(&intf->cmd_rcvrs_mutex);
if (rv)
kfree(rcvr);
return rv;
}
EXPORT_SYMBOL(ipmi_register_for_cmd);
int ipmi_unregister_for_cmd(ipmi_user_t user,
unsigned char netfn,
unsigned char cmd,
unsigned int chans)
{
ipmi_smi_t intf = user->intf;
struct cmd_rcvr *rcvr;
struct cmd_rcvr *rcvrs = NULL;
int i, rv = -ENOENT;
mutex_lock(&intf->cmd_rcvrs_mutex);
for (i = 0; i < IPMI_NUM_CHANNELS; i++) {
if (((1 << i) & chans) == 0)
continue;
rcvr = find_cmd_rcvr(intf, netfn, cmd, i);
if (rcvr == NULL)
continue;
if (rcvr->user == user) {
rv = 0;
rcvr->chans &= ~chans;
if (rcvr->chans == 0) {
list_del_rcu(&rcvr->link);
rcvr->next = rcvrs;
rcvrs = rcvr;
}
}
}
mutex_unlock(&intf->cmd_rcvrs_mutex);
synchronize_rcu();
while (rcvrs) {
rcvr = rcvrs;
rcvrs = rcvr->next;
kfree(rcvr);
}
return rv;
}
EXPORT_SYMBOL(ipmi_unregister_for_cmd);
static unsigned char
ipmb_checksum(unsigned char *data, int size)
{
unsigned char csum = 0;
for (; size > 0; size--, data++)
csum += *data;
return -csum;
}
static inline void format_ipmb_msg(struct ipmi_smi_msg *smi_msg,
struct kernel_ipmi_msg *msg,
struct ipmi_ipmb_addr *ipmb_addr,
long msgid,
unsigned char ipmb_seq,
int broadcast,
unsigned char source_address,
unsigned char source_lun)
{
int i = broadcast;
/* Format the IPMB header data. */
smi_msg->data[0] = (IPMI_NETFN_APP_REQUEST << 2);
smi_msg->data[1] = IPMI_SEND_MSG_CMD;
smi_msg->data[2] = ipmb_addr->channel;
if (broadcast)
smi_msg->data[3] = 0;
smi_msg->data[i+3] = ipmb_addr->slave_addr;
smi_msg->data[i+4] = (msg->netfn << 2) | (ipmb_addr->lun & 0x3);
smi_msg->data[i+5] = ipmb_checksum(&(smi_msg->data[i+3]), 2);
smi_msg->data[i+6] = source_address;
smi_msg->data[i+7] = (ipmb_seq << 2) | source_lun;
smi_msg->data[i+8] = msg->cmd;
/* Now tack on the data to the message. */
if (msg->data_len > 0)
memcpy(&(smi_msg->data[i+9]), msg->data,
msg->data_len);
smi_msg->data_size = msg->data_len + 9;
/* Now calculate the checksum and tack it on. */
smi_msg->data[i+smi_msg->data_size]
= ipmb_checksum(&(smi_msg->data[i+6]),
smi_msg->data_size-6);
/*
* Add on the checksum size and the offset from the
* broadcast.
*/
smi_msg->data_size += 1 + i;
smi_msg->msgid = msgid;
}
static inline void format_lan_msg(struct ipmi_smi_msg *smi_msg,
struct kernel_ipmi_msg *msg,
struct ipmi_lan_addr *lan_addr,
long msgid,
unsigned char ipmb_seq,
unsigned char source_lun)
{
/* Format the IPMB header data. */
smi_msg->data[0] = (IPMI_NETFN_APP_REQUEST << 2);
smi_msg->data[1] = IPMI_SEND_MSG_CMD;
smi_msg->data[2] = lan_addr->channel;
smi_msg->data[3] = lan_addr->session_handle;
smi_msg->data[4] = lan_addr->remote_SWID;
smi_msg->data[5] = (msg->netfn << 2) | (lan_addr->lun & 0x3);
smi_msg->data[6] = ipmb_checksum(&(smi_msg->data[4]), 2);
smi_msg->data[7] = lan_addr->local_SWID;
smi_msg->data[8] = (ipmb_seq << 2) | source_lun;
smi_msg->data[9] = msg->cmd;
/* Now tack on the data to the message. */
if (msg->data_len > 0)
memcpy(&(smi_msg->data[10]), msg->data,
msg->data_len);
smi_msg->data_size = msg->data_len + 10;
/* Now calculate the checksum and tack it on. */
smi_msg->data[smi_msg->data_size]
= ipmb_checksum(&(smi_msg->data[7]),
smi_msg->data_size-7);
/*
* Add on the checksum size and the offset from the
* broadcast.
*/
smi_msg->data_size += 1;
smi_msg->msgid = msgid;
}
/*
* Separate from ipmi_request so that the user does not have to be
* supplied in certain circumstances (mainly at panic time). If
* messages are supplied, they will be freed, even if an error
* occurs.
*/
static int i_ipmi_request(ipmi_user_t user,
ipmi_smi_t intf,
struct ipmi_addr *addr,
long msgid,
struct kernel_ipmi_msg *msg,
void *user_msg_data,
void *supplied_smi,
struct ipmi_recv_msg *supplied_recv,
int priority,
unsigned char source_address,
unsigned char source_lun,
int retries,
unsigned int retry_time_ms)
{
int rv = 0;
struct ipmi_smi_msg *smi_msg;
struct ipmi_recv_msg *recv_msg;
unsigned long flags;
struct ipmi_smi_handlers *handlers;
if (supplied_recv)
recv_msg = supplied_recv;
else {
recv_msg = ipmi_alloc_recv_msg();
if (recv_msg == NULL)
return -ENOMEM;
}
recv_msg->user_msg_data = user_msg_data;
if (supplied_smi)
smi_msg = (struct ipmi_smi_msg *) supplied_smi;
else {
smi_msg = ipmi_alloc_smi_msg();
if (smi_msg == NULL) {
ipmi_free_recv_msg(recv_msg);
return -ENOMEM;
}
}
rcu_read_lock();
handlers = intf->handlers;
if (!handlers) {
rv = -ENODEV;
goto out_err;
}
recv_msg->user = user;
if (user)
kref_get(&user->refcount);
recv_msg->msgid = msgid;
/*
* Store the message to send in the receive message so timeout
* responses can get the proper response data.
*/
recv_msg->msg = *msg;
if (addr->addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE) {
struct ipmi_system_interface_addr *smi_addr;
if (msg->netfn & 1) {
/* Responses are not allowed to the SMI. */
rv = -EINVAL;
goto out_err;
}
smi_addr = (struct ipmi_system_interface_addr *) addr;
if (smi_addr->lun > 3) {
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EINVAL;
goto out_err;
}
memcpy(&recv_msg->addr, smi_addr, sizeof(*smi_addr));
if ((msg->netfn == IPMI_NETFN_APP_REQUEST)
&& ((msg->cmd == IPMI_SEND_MSG_CMD)
|| (msg->cmd == IPMI_GET_MSG_CMD)
|| (msg->cmd == IPMI_READ_EVENT_MSG_BUFFER_CMD))) {
/*
* We don't let the user do these, since we manage
* the sequence numbers.
*/
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EINVAL;
goto out_err;
}
if (((msg->netfn == IPMI_NETFN_APP_REQUEST)
&& ((msg->cmd == IPMI_COLD_RESET_CMD)
|| (msg->cmd == IPMI_WARM_RESET_CMD)))
|| (msg->netfn == IPMI_NETFN_FIRMWARE_REQUEST)) {
spin_lock_irqsave(&intf->maintenance_mode_lock, flags);
intf->auto_maintenance_timeout
= IPMI_MAINTENANCE_MODE_TIMEOUT;
if (!intf->maintenance_mode
&& !intf->maintenance_mode_enable) {
intf->maintenance_mode_enable = 1;
maintenance_mode_update(intf);
}
spin_unlock_irqrestore(&intf->maintenance_mode_lock,
flags);
}
if ((msg->data_len + 2) > IPMI_MAX_MSG_LENGTH) {
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EMSGSIZE;
goto out_err;
}
smi_msg->data[0] = (msg->netfn << 2) | (smi_addr->lun & 0x3);
smi_msg->data[1] = msg->cmd;
smi_msg->msgid = msgid;
smi_msg->user_data = recv_msg;
if (msg->data_len > 0)
memcpy(&(smi_msg->data[2]), msg->data, msg->data_len);
smi_msg->data_size = msg->data_len + 2;
ipmi_inc_stat(intf, sent_local_commands);
} else if (is_ipmb_addr(addr) || is_ipmb_bcast_addr(addr)) {
struct ipmi_ipmb_addr *ipmb_addr;
unsigned char ipmb_seq;
long seqid;
int broadcast = 0;
if (addr->channel >= IPMI_MAX_CHANNELS) {
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EINVAL;
goto out_err;
}
if (intf->channels[addr->channel].medium
!= IPMI_CHANNEL_MEDIUM_IPMB) {
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EINVAL;
goto out_err;
}
if (retries < 0) {
if (addr->addr_type == IPMI_IPMB_BROADCAST_ADDR_TYPE)
retries = 0; /* Don't retry broadcasts. */
else
retries = 4;
}
if (addr->addr_type == IPMI_IPMB_BROADCAST_ADDR_TYPE) {
/*
* Broadcasts add a zero at the beginning of the
* message, but otherwise is the same as an IPMB
* address.
*/
addr->addr_type = IPMI_IPMB_ADDR_TYPE;
broadcast = 1;
}
/* Default to 1 second retries. */
if (retry_time_ms == 0)
retry_time_ms = 1000;
/*
* 9 for the header and 1 for the checksum, plus
* possibly one for the broadcast.
*/
if ((msg->data_len + 10 + broadcast) > IPMI_MAX_MSG_LENGTH) {
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EMSGSIZE;
goto out_err;
}
ipmb_addr = (struct ipmi_ipmb_addr *) addr;
if (ipmb_addr->lun > 3) {
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EINVAL;
goto out_err;
}
memcpy(&recv_msg->addr, ipmb_addr, sizeof(*ipmb_addr));
if (recv_msg->msg.netfn & 0x1) {
/*
* It's a response, so use the user's sequence
* from msgid.
*/
ipmi_inc_stat(intf, sent_ipmb_responses);
format_ipmb_msg(smi_msg, msg, ipmb_addr, msgid,
msgid, broadcast,
source_address, source_lun);
/*
* Save the receive message so we can use it
* to deliver the response.
*/
smi_msg->user_data = recv_msg;
} else {
/* It's a command, so get a sequence for it. */
spin_lock_irqsave(&(intf->seq_lock), flags);
/*
* Create a sequence number with a 1 second
* timeout and 4 retries.
*/
rv = intf_next_seq(intf,
recv_msg,
retry_time_ms,
retries,
broadcast,
&ipmb_seq,
&seqid);
if (rv) {
/*
* We have used up all the sequence numbers,
* probably, so abort.
*/
spin_unlock_irqrestore(&(intf->seq_lock),
flags);
goto out_err;
}
ipmi_inc_stat(intf, sent_ipmb_commands);
/*
* Store the sequence number in the message,
* so that when the send message response
* comes back we can start the timer.
*/
format_ipmb_msg(smi_msg, msg, ipmb_addr,
STORE_SEQ_IN_MSGID(ipmb_seq, seqid),
ipmb_seq, broadcast,
source_address, source_lun);
/*
* Copy the message into the recv message data, so we
* can retransmit it later if necessary.
*/
memcpy(recv_msg->msg_data, smi_msg->data,
smi_msg->data_size);
recv_msg->msg.data = recv_msg->msg_data;
recv_msg->msg.data_len = smi_msg->data_size;
/*
* We don't unlock until here, because we need
* to copy the completed message into the
* recv_msg before we release the lock.
* Otherwise, race conditions may bite us. I
* know that's pretty paranoid, but I prefer
* to be correct.
*/
spin_unlock_irqrestore(&(intf->seq_lock), flags);
}
} else if (is_lan_addr(addr)) {
struct ipmi_lan_addr *lan_addr;
unsigned char ipmb_seq;
long seqid;
if (addr->channel >= IPMI_MAX_CHANNELS) {
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EINVAL;
goto out_err;
}
if ((intf->channels[addr->channel].medium
!= IPMI_CHANNEL_MEDIUM_8023LAN)
&& (intf->channels[addr->channel].medium
!= IPMI_CHANNEL_MEDIUM_ASYNC)) {
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EINVAL;
goto out_err;
}
retries = 4;
/* Default to 1 second retries. */
if (retry_time_ms == 0)
retry_time_ms = 1000;
/* 11 for the header and 1 for the checksum. */
if ((msg->data_len + 12) > IPMI_MAX_MSG_LENGTH) {
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EMSGSIZE;
goto out_err;
}
lan_addr = (struct ipmi_lan_addr *) addr;
if (lan_addr->lun > 3) {
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EINVAL;
goto out_err;
}
memcpy(&recv_msg->addr, lan_addr, sizeof(*lan_addr));
if (recv_msg->msg.netfn & 0x1) {
/*
* It's a response, so use the user's sequence
* from msgid.
*/
ipmi_inc_stat(intf, sent_lan_responses);
format_lan_msg(smi_msg, msg, lan_addr, msgid,
msgid, source_lun);
/*
* Save the receive message so we can use it
* to deliver the response.
*/
smi_msg->user_data = recv_msg;
} else {
/* It's a command, so get a sequence for it. */
spin_lock_irqsave(&(intf->seq_lock), flags);
/*
* Create a sequence number with a 1 second
* timeout and 4 retries.
*/
rv = intf_next_seq(intf,
recv_msg,
retry_time_ms,
retries,
0,
&ipmb_seq,
&seqid);
if (rv) {
/*
* We have used up all the sequence numbers,
* probably, so abort.
*/
spin_unlock_irqrestore(&(intf->seq_lock),
flags);
goto out_err;
}
ipmi_inc_stat(intf, sent_lan_commands);
/*
* Store the sequence number in the message,
* so that when the send message response
* comes back we can start the timer.
*/
format_lan_msg(smi_msg, msg, lan_addr,
STORE_SEQ_IN_MSGID(ipmb_seq, seqid),
ipmb_seq, source_lun);
/*
* Copy the message into the recv message data, so we
* can retransmit it later if necessary.
*/
memcpy(recv_msg->msg_data, smi_msg->data,
smi_msg->data_size);
recv_msg->msg.data = recv_msg->msg_data;
recv_msg->msg.data_len = smi_msg->data_size;
/*
* We don't unlock until here, because we need
* to copy the completed message into the
* recv_msg before we release the lock.
* Otherwise, race conditions may bite us. I
* know that's pretty paranoid, but I prefer
* to be correct.
*/
spin_unlock_irqrestore(&(intf->seq_lock), flags);
}
} else {
/* Unknown address type. */
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EINVAL;
goto out_err;
}
#ifdef DEBUG_MSGING
{
int m;
for (m = 0; m < smi_msg->data_size; m++)
printk(" %2.2x", smi_msg->data[m]);
printk("\n");
}
#endif
handlers->sender(intf->send_info, smi_msg, priority);
rcu_read_unlock();
return 0;
out_err:
rcu_read_unlock();
ipmi_free_smi_msg(smi_msg);
ipmi_free_recv_msg(recv_msg);
return rv;
}
static int check_addr(ipmi_smi_t intf,
struct ipmi_addr *addr,
unsigned char *saddr,
unsigned char *lun)
{
if (addr->channel >= IPMI_MAX_CHANNELS)
return -EINVAL;
*lun = intf->channels[addr->channel].lun;
*saddr = intf->channels[addr->channel].address;
return 0;
}
int ipmi_request_settime(ipmi_user_t user,
struct ipmi_addr *addr,
long msgid,
struct kernel_ipmi_msg *msg,
void *user_msg_data,
int priority,
int retries,
unsigned int retry_time_ms)
{
unsigned char saddr, lun;
int rv;
if (!user)
return -EINVAL;
rv = check_addr(user->intf, addr, &saddr, &lun);
if (rv)
return rv;
return i_ipmi_request(user,
user->intf,
addr,
msgid,
msg,
user_msg_data,
NULL, NULL,
priority,
saddr,
lun,
retries,
retry_time_ms);
}
EXPORT_SYMBOL(ipmi_request_settime);
int ipmi_request_supply_msgs(ipmi_user_t user,
struct ipmi_addr *addr,
long msgid,
struct kernel_ipmi_msg *msg,
void *user_msg_data,
void *supplied_smi,
struct ipmi_recv_msg *supplied_recv,
int priority)
{
unsigned char saddr, lun;
int rv;
if (!user)
return -EINVAL;
rv = check_addr(user->intf, addr, &saddr, &lun);
if (rv)
return rv;
return i_ipmi_request(user,
user->intf,
addr,
msgid,
msg,
user_msg_data,
supplied_smi,
supplied_recv,
priority,
saddr,
lun,
-1, 0);
}
EXPORT_SYMBOL(ipmi_request_supply_msgs);
#ifdef CONFIG_PROC_FS
static int smi_ipmb_proc_show(struct seq_file *m, void *v)
{
ipmi_smi_t intf = m->private;
int i;
seq_printf(m, "%x", intf->channels[0].address);
for (i = 1; i < IPMI_MAX_CHANNELS; i++)
seq_printf(m, " %x", intf->channels[i].address);
return seq_putc(m, '\n');
}
static int smi_ipmb_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, smi_ipmb_proc_show, PDE(inode)->data);
}
static const struct file_operations smi_ipmb_proc_ops = {
.open = smi_ipmb_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int smi_version_proc_show(struct seq_file *m, void *v)
{
ipmi_smi_t intf = m->private;
return seq_printf(m, "%u.%u\n",
ipmi_version_major(&intf->bmc->id),
ipmi_version_minor(&intf->bmc->id));
}
static int smi_version_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, smi_version_proc_show, PDE(inode)->data);
}
static const struct file_operations smi_version_proc_ops = {
.open = smi_version_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int smi_stats_proc_show(struct seq_file *m, void *v)
{
ipmi_smi_t intf = m->private;
seq_printf(m, "sent_invalid_commands: %u\n",
ipmi_get_stat(intf, sent_invalid_commands));
seq_printf(m, "sent_local_commands: %u\n",
ipmi_get_stat(intf, sent_local_commands));
seq_printf(m, "handled_local_responses: %u\n",
ipmi_get_stat(intf, handled_local_responses));
seq_printf(m, "unhandled_local_responses: %u\n",
ipmi_get_stat(intf, unhandled_local_responses));
seq_printf(m, "sent_ipmb_commands: %u\n",
ipmi_get_stat(intf, sent_ipmb_commands));
seq_printf(m, "sent_ipmb_command_errs: %u\n",
ipmi_get_stat(intf, sent_ipmb_command_errs));
seq_printf(m, "retransmitted_ipmb_commands: %u\n",
ipmi_get_stat(intf, retransmitted_ipmb_commands));
seq_printf(m, "timed_out_ipmb_commands: %u\n",
ipmi_get_stat(intf, timed_out_ipmb_commands));
seq_printf(m, "timed_out_ipmb_broadcasts: %u\n",
ipmi_get_stat(intf, timed_out_ipmb_broadcasts));
seq_printf(m, "sent_ipmb_responses: %u\n",
ipmi_get_stat(intf, sent_ipmb_responses));
seq_printf(m, "handled_ipmb_responses: %u\n",
ipmi_get_stat(intf, handled_ipmb_responses));
seq_printf(m, "invalid_ipmb_responses: %u\n",
ipmi_get_stat(intf, invalid_ipmb_responses));
seq_printf(m, "unhandled_ipmb_responses: %u\n",
ipmi_get_stat(intf, unhandled_ipmb_responses));
seq_printf(m, "sent_lan_commands: %u\n",
ipmi_get_stat(intf, sent_lan_commands));
seq_printf(m, "sent_lan_command_errs: %u\n",
ipmi_get_stat(intf, sent_lan_command_errs));
seq_printf(m, "retransmitted_lan_commands: %u\n",
ipmi_get_stat(intf, retransmitted_lan_commands));
seq_printf(m, "timed_out_lan_commands: %u\n",
ipmi_get_stat(intf, timed_out_lan_commands));
seq_printf(m, "sent_lan_responses: %u\n",
ipmi_get_stat(intf, sent_lan_responses));
seq_printf(m, "handled_lan_responses: %u\n",
ipmi_get_stat(intf, handled_lan_responses));
seq_printf(m, "invalid_lan_responses: %u\n",
ipmi_get_stat(intf, invalid_lan_responses));
seq_printf(m, "unhandled_lan_responses: %u\n",
ipmi_get_stat(intf, unhandled_lan_responses));
seq_printf(m, "handled_commands: %u\n",
ipmi_get_stat(intf, handled_commands));
seq_printf(m, "invalid_commands: %u\n",
ipmi_get_stat(intf, invalid_commands));
seq_printf(m, "unhandled_commands: %u\n",
ipmi_get_stat(intf, unhandled_commands));
seq_printf(m, "invalid_events: %u\n",
ipmi_get_stat(intf, invalid_events));
seq_printf(m, "events: %u\n",
ipmi_get_stat(intf, events));
seq_printf(m, "failed rexmit LAN msgs: %u\n",
ipmi_get_stat(intf, dropped_rexmit_lan_commands));
seq_printf(m, "failed rexmit IPMB msgs: %u\n",
ipmi_get_stat(intf, dropped_rexmit_ipmb_commands));
return 0;
}
static int smi_stats_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, smi_stats_proc_show, PDE(inode)->data);
}
static const struct file_operations smi_stats_proc_ops = {
.open = smi_stats_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#endif /* CONFIG_PROC_FS */
int ipmi_smi_add_proc_entry(ipmi_smi_t smi, char *name,
const struct file_operations *proc_ops,
void *data)
{
int rv = 0;
#ifdef CONFIG_PROC_FS
struct proc_dir_entry *file;
struct ipmi_proc_entry *entry;
/* Create a list element. */
entry = kmalloc(sizeof(*entry), GFP_KERNEL);
if (!entry)
return -ENOMEM;
entry->name = kmalloc(strlen(name)+1, GFP_KERNEL);
if (!entry->name) {
kfree(entry);
return -ENOMEM;
}
strcpy(entry->name, name);
file = proc_create_data(name, 0, smi->proc_dir, proc_ops, data);
if (!file) {
kfree(entry->name);
kfree(entry);
rv = -ENOMEM;
} else {
mutex_lock(&smi->proc_entry_lock);
/* Stick it on the list. */
entry->next = smi->proc_entries;
smi->proc_entries = entry;
mutex_unlock(&smi->proc_entry_lock);
}
#endif /* CONFIG_PROC_FS */
return rv;
}
EXPORT_SYMBOL(ipmi_smi_add_proc_entry);
static int add_proc_entries(ipmi_smi_t smi, int num)
{
int rv = 0;
#ifdef CONFIG_PROC_FS
sprintf(smi->proc_dir_name, "%d", num);
smi->proc_dir = proc_mkdir(smi->proc_dir_name, proc_ipmi_root);
if (!smi->proc_dir)
rv = -ENOMEM;
if (rv == 0)
rv = ipmi_smi_add_proc_entry(smi, "stats",
&smi_stats_proc_ops,
smi);
if (rv == 0)
rv = ipmi_smi_add_proc_entry(smi, "ipmb",
&smi_ipmb_proc_ops,
smi);
if (rv == 0)
rv = ipmi_smi_add_proc_entry(smi, "version",
&smi_version_proc_ops,
smi);
#endif /* CONFIG_PROC_FS */
return rv;
}
static void remove_proc_entries(ipmi_smi_t smi)
{
#ifdef CONFIG_PROC_FS
struct ipmi_proc_entry *entry;
mutex_lock(&smi->proc_entry_lock);
while (smi->proc_entries) {
entry = smi->proc_entries;
smi->proc_entries = entry->next;
remove_proc_entry(entry->name, smi->proc_dir);
kfree(entry->name);
kfree(entry);
}
mutex_unlock(&smi->proc_entry_lock);
remove_proc_entry(smi->proc_dir_name, proc_ipmi_root);
#endif /* CONFIG_PROC_FS */
}
static int __find_bmc_guid(struct device *dev, void *data)
{
unsigned char *id = data;
struct bmc_device *bmc = dev_get_drvdata(dev);
return memcmp(bmc->guid, id, 16) == 0;
}
static struct bmc_device *ipmi_find_bmc_guid(struct device_driver *drv,
unsigned char *guid)
{
struct device *dev;
dev = driver_find_device(drv, NULL, guid, __find_bmc_guid);
if (dev)
return dev_get_drvdata(dev);
else
return NULL;
}
struct prod_dev_id {
unsigned int product_id;
unsigned char device_id;
};
static int __find_bmc_prod_dev_id(struct device *dev, void *data)
{
struct prod_dev_id *id = data;
struct bmc_device *bmc = dev_get_drvdata(dev);
return (bmc->id.product_id == id->product_id
&& bmc->id.device_id == id->device_id);
}
static struct bmc_device *ipmi_find_bmc_prod_dev_id(
struct device_driver *drv,
unsigned int product_id, unsigned char device_id)
{
struct prod_dev_id id = {
.product_id = product_id,
.device_id = device_id,
};
struct device *dev;
dev = driver_find_device(drv, NULL, &id, __find_bmc_prod_dev_id);
if (dev)
return dev_get_drvdata(dev);
else
return NULL;
}
static ssize_t device_id_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct bmc_device *bmc = dev_get_drvdata(dev);
return snprintf(buf, 10, "%u\n", bmc->id.device_id);
}
static ssize_t provides_dev_sdrs_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct bmc_device *bmc = dev_get_drvdata(dev);
return snprintf(buf, 10, "%u\n",
(bmc->id.device_revision & 0x80) >> 7);
}
static ssize_t revision_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct bmc_device *bmc = dev_get_drvdata(dev);
return snprintf(buf, 20, "%u\n",
bmc->id.device_revision & 0x0F);
}
static ssize_t firmware_rev_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct bmc_device *bmc = dev_get_drvdata(dev);
return snprintf(buf, 20, "%u.%x\n", bmc->id.firmware_revision_1,
bmc->id.firmware_revision_2);
}
static ssize_t ipmi_version_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct bmc_device *bmc = dev_get_drvdata(dev);
return snprintf(buf, 20, "%u.%u\n",
ipmi_version_major(&bmc->id),
ipmi_version_minor(&bmc->id));
}
static ssize_t add_dev_support_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct bmc_device *bmc = dev_get_drvdata(dev);
return snprintf(buf, 10, "0x%02x\n",
bmc->id.additional_device_support);
}
static ssize_t manufacturer_id_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct bmc_device *bmc = dev_get_drvdata(dev);
return snprintf(buf, 20, "0x%6.6x\n", bmc->id.manufacturer_id);
}
static ssize_t product_id_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct bmc_device *bmc = dev_get_drvdata(dev);
return snprintf(buf, 10, "0x%4.4x\n", bmc->id.product_id);
}
static ssize_t aux_firmware_rev_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct bmc_device *bmc = dev_get_drvdata(dev);
return snprintf(buf, 21, "0x%02x 0x%02x 0x%02x 0x%02x\n",
bmc->id.aux_firmware_revision[3],
bmc->id.aux_firmware_revision[2],
bmc->id.aux_firmware_revision[1],
bmc->id.aux_firmware_revision[0]);
}
static ssize_t guid_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct bmc_device *bmc = dev_get_drvdata(dev);
return snprintf(buf, 100, "%Lx%Lx\n",
(long long) bmc->guid[0],
(long long) bmc->guid[8]);
}
static void remove_files(struct bmc_device *bmc)
{
if (!bmc->dev)
return;
device_remove_file(&bmc->dev->dev,
&bmc->device_id_attr);
device_remove_file(&bmc->dev->dev,
&bmc->provides_dev_sdrs_attr);
device_remove_file(&bmc->dev->dev,
&bmc->revision_attr);
device_remove_file(&bmc->dev->dev,
&bmc->firmware_rev_attr);
device_remove_file(&bmc->dev->dev,
&bmc->version_attr);
device_remove_file(&bmc->dev->dev,
&bmc->add_dev_support_attr);
device_remove_file(&bmc->dev->dev,
&bmc->manufacturer_id_attr);
device_remove_file(&bmc->dev->dev,
&bmc->product_id_attr);
if (bmc->id.aux_firmware_revision_set)
device_remove_file(&bmc->dev->dev,
&bmc->aux_firmware_rev_attr);
if (bmc->guid_set)
device_remove_file(&bmc->dev->dev,
&bmc->guid_attr);
}
static void
cleanup_bmc_device(struct kref *ref)
{
struct bmc_device *bmc;
bmc = container_of(ref, struct bmc_device, refcount);
remove_files(bmc);
platform_device_unregister(bmc->dev);
kfree(bmc);
}
static void ipmi_bmc_unregister(ipmi_smi_t intf)
{
struct bmc_device *bmc = intf->bmc;
if (intf->sysfs_name) {
sysfs_remove_link(&intf->si_dev->kobj, intf->sysfs_name);
kfree(intf->sysfs_name);
intf->sysfs_name = NULL;
}
if (intf->my_dev_name) {
sysfs_remove_link(&bmc->dev->dev.kobj, intf->my_dev_name);
kfree(intf->my_dev_name);
intf->my_dev_name = NULL;
}
mutex_lock(&ipmidriver_mutex);
kref_put(&bmc->refcount, cleanup_bmc_device);
intf->bmc = NULL;
mutex_unlock(&ipmidriver_mutex);
}
static int create_files(struct bmc_device *bmc)
{
int err;
bmc->device_id_attr.attr.name = "device_id";
bmc->device_id_attr.attr.mode = S_IRUGO;
bmc->device_id_attr.show = device_id_show;
sysfs_attr_init(&bmc->device_id_attr.attr);
bmc->provides_dev_sdrs_attr.attr.name = "provides_device_sdrs";
bmc->provides_dev_sdrs_attr.attr.mode = S_IRUGO;
bmc->provides_dev_sdrs_attr.show = provides_dev_sdrs_show;
sysfs_attr_init(&bmc->provides_dev_sdrs_attr.attr);
bmc->revision_attr.attr.name = "revision";
bmc->revision_attr.attr.mode = S_IRUGO;
bmc->revision_attr.show = revision_show;
sysfs_attr_init(&bmc->revision_attr.attr);
bmc->firmware_rev_attr.attr.name = "firmware_revision";
bmc->firmware_rev_attr.attr.mode = S_IRUGO;
bmc->firmware_rev_attr.show = firmware_rev_show;
sysfs_attr_init(&bmc->firmware_rev_attr.attr);
bmc->version_attr.attr.name = "ipmi_version";
bmc->version_attr.attr.mode = S_IRUGO;
bmc->version_attr.show = ipmi_version_show;
sysfs_attr_init(&bmc->version_attr.attr);
bmc->add_dev_support_attr.attr.name = "additional_device_support";
bmc->add_dev_support_attr.attr.mode = S_IRUGO;
bmc->add_dev_support_attr.show = add_dev_support_show;
sysfs_attr_init(&bmc->add_dev_support_attr.attr);
bmc->manufacturer_id_attr.attr.name = "manufacturer_id";
bmc->manufacturer_id_attr.attr.mode = S_IRUGO;
bmc->manufacturer_id_attr.show = manufacturer_id_show;
sysfs_attr_init(&bmc->manufacturer_id_attr.attr);
bmc->product_id_attr.attr.name = "product_id";
bmc->product_id_attr.attr.mode = S_IRUGO;
bmc->product_id_attr.show = product_id_show;
sysfs_attr_init(&bmc->product_id_attr.attr);
bmc->guid_attr.attr.name = "guid";
bmc->guid_attr.attr.mode = S_IRUGO;
bmc->guid_attr.show = guid_show;
sysfs_attr_init(&bmc->guid_attr.attr);
bmc->aux_firmware_rev_attr.attr.name = "aux_firmware_revision";
bmc->aux_firmware_rev_attr.attr.mode = S_IRUGO;
bmc->aux_firmware_rev_attr.show = aux_firmware_rev_show;
sysfs_attr_init(&bmc->aux_firmware_rev_attr.attr);
err = device_create_file(&bmc->dev->dev,
&bmc->device_id_attr);
if (err)
goto out;
err = device_create_file(&bmc->dev->dev,
&bmc->provides_dev_sdrs_attr);
if (err)
goto out_devid;
err = device_create_file(&bmc->dev->dev,
&bmc->revision_attr);
if (err)
goto out_sdrs;
err = device_create_file(&bmc->dev->dev,
&bmc->firmware_rev_attr);
if (err)
goto out_rev;
err = device_create_file(&bmc->dev->dev,
&bmc->version_attr);
if (err)
goto out_firm;
err = device_create_file(&bmc->dev->dev,
&bmc->add_dev_support_attr);
if (err)
goto out_version;
err = device_create_file(&bmc->dev->dev,
&bmc->manufacturer_id_attr);
if (err)
goto out_add_dev;
err = device_create_file(&bmc->dev->dev,
&bmc->product_id_attr);
if (err)
goto out_manu;
if (bmc->id.aux_firmware_revision_set) {
err = device_create_file(&bmc->dev->dev,
&bmc->aux_firmware_rev_attr);
if (err)
goto out_prod_id;
}
if (bmc->guid_set) {
err = device_create_file(&bmc->dev->dev,
&bmc->guid_attr);
if (err)
goto out_aux_firm;
}
return 0;
out_aux_firm:
if (bmc->id.aux_firmware_revision_set)
device_remove_file(&bmc->dev->dev,
&bmc->aux_firmware_rev_attr);
out_prod_id:
device_remove_file(&bmc->dev->dev,
&bmc->product_id_attr);
out_manu:
device_remove_file(&bmc->dev->dev,
&bmc->manufacturer_id_attr);
out_add_dev:
device_remove_file(&bmc->dev->dev,
&bmc->add_dev_support_attr);
out_version:
device_remove_file(&bmc->dev->dev,
&bmc->version_attr);
out_firm:
device_remove_file(&bmc->dev->dev,
&bmc->firmware_rev_attr);
out_rev:
device_remove_file(&bmc->dev->dev,
&bmc->revision_attr);
out_sdrs:
device_remove_file(&bmc->dev->dev,
&bmc->provides_dev_sdrs_attr);
out_devid:
device_remove_file(&bmc->dev->dev,
&bmc->device_id_attr);
out:
return err;
}
static int ipmi_bmc_register(ipmi_smi_t intf, int ifnum,
const char *sysfs_name)
{
int rv;
struct bmc_device *bmc = intf->bmc;
struct bmc_device *old_bmc;
int size;
char dummy[1];
mutex_lock(&ipmidriver_mutex);
/*
* Try to find if there is an bmc_device struct
* representing the interfaced BMC already
*/
if (bmc->guid_set)
old_bmc = ipmi_find_bmc_guid(&ipmidriver.driver, bmc->guid);
else
old_bmc = ipmi_find_bmc_prod_dev_id(&ipmidriver.driver,
bmc->id.product_id,
bmc->id.device_id);
/*
* If there is already an bmc_device, free the new one,
* otherwise register the new BMC device
*/
if (old_bmc) {
kfree(bmc);
intf->bmc = old_bmc;
bmc = old_bmc;
kref_get(&bmc->refcount);
mutex_unlock(&ipmidriver_mutex);
printk(KERN_INFO
"ipmi: interfacing existing BMC (man_id: 0x%6.6x,"
" prod_id: 0x%4.4x, dev_id: 0x%2.2x)\n",
bmc->id.manufacturer_id,
bmc->id.product_id,
bmc->id.device_id);
} else {
char name[14];
unsigned char orig_dev_id = bmc->id.device_id;
int warn_printed = 0;
snprintf(name, sizeof(name),
"ipmi_bmc.%4.4x", bmc->id.product_id);
while (ipmi_find_bmc_prod_dev_id(&ipmidriver.driver,
bmc->id.product_id,
bmc->id.device_id)) {
if (!warn_printed) {
printk(KERN_WARNING PFX
"This machine has two different BMCs"
" with the same product id and device"
" id. This is an error in the"
" firmware, but incrementing the"
" device id to work around the problem."
" Prod ID = 0x%x, Dev ID = 0x%x\n",
bmc->id.product_id, bmc->id.device_id);
warn_printed = 1;
}
bmc->id.device_id++; /* Wraps at 255 */
if (bmc->id.device_id == orig_dev_id) {
printk(KERN_ERR PFX
"Out of device ids!\n");
break;
}
}
bmc->dev = platform_device_alloc(name, bmc->id.device_id);
if (!bmc->dev) {
mutex_unlock(&ipmidriver_mutex);
printk(KERN_ERR
"ipmi_msghandler:"
" Unable to allocate platform device\n");
return -ENOMEM;
}
bmc->dev->dev.driver = &ipmidriver.driver;
dev_set_drvdata(&bmc->dev->dev, bmc);
kref_init(&bmc->refcount);
rv = platform_device_add(bmc->dev);
mutex_unlock(&ipmidriver_mutex);
if (rv) {
platform_device_put(bmc->dev);
bmc->dev = NULL;
printk(KERN_ERR
"ipmi_msghandler:"
" Unable to register bmc device: %d\n",
rv);
/*
* Don't go to out_err, you can only do that if
* the device is registered already.
*/
return rv;
}
rv = create_files(bmc);
if (rv) {
mutex_lock(&ipmidriver_mutex);
platform_device_unregister(bmc->dev);
mutex_unlock(&ipmidriver_mutex);
return rv;
}
dev_info(intf->si_dev, "Found new BMC (man_id: 0x%6.6x, "
"prod_id: 0x%4.4x, dev_id: 0x%2.2x)\n",
bmc->id.manufacturer_id,
bmc->id.product_id,
bmc->id.device_id);
}
/*
* create symlink from system interface device to bmc device
* and back.
*/
intf->sysfs_name = kstrdup(sysfs_name, GFP_KERNEL);
if (!intf->sysfs_name) {
rv = -ENOMEM;
printk(KERN_ERR
"ipmi_msghandler: allocate link to BMC: %d\n",
rv);
goto out_err;
}
rv = sysfs_create_link(&intf->si_dev->kobj,
&bmc->dev->dev.kobj, intf->sysfs_name);
if (rv) {
kfree(intf->sysfs_name);
intf->sysfs_name = NULL;
printk(KERN_ERR
"ipmi_msghandler: Unable to create bmc symlink: %d\n",
rv);
goto out_err;
}
size = snprintf(dummy, 0, "ipmi%d", ifnum);
intf->my_dev_name = kmalloc(size+1, GFP_KERNEL);
if (!intf->my_dev_name) {
kfree(intf->sysfs_name);
intf->sysfs_name = NULL;
rv = -ENOMEM;
printk(KERN_ERR
"ipmi_msghandler: allocate link from BMC: %d\n",
rv);
goto out_err;
}
snprintf(intf->my_dev_name, size+1, "ipmi%d", ifnum);
rv = sysfs_create_link(&bmc->dev->dev.kobj, &intf->si_dev->kobj,
intf->my_dev_name);
if (rv) {
kfree(intf->sysfs_name);
intf->sysfs_name = NULL;
kfree(intf->my_dev_name);
intf->my_dev_name = NULL;
printk(KERN_ERR
"ipmi_msghandler:"
" Unable to create symlink to bmc: %d\n",
rv);
goto out_err;
}
return 0;
out_err:
ipmi_bmc_unregister(intf);
return rv;
}
static int
send_guid_cmd(ipmi_smi_t intf, int chan)
{
struct kernel_ipmi_msg msg;
struct ipmi_system_interface_addr si;
si.addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
si.channel = IPMI_BMC_CHANNEL;
si.lun = 0;
msg.netfn = IPMI_NETFN_APP_REQUEST;
msg.cmd = IPMI_GET_DEVICE_GUID_CMD;
msg.data = NULL;
msg.data_len = 0;
return i_ipmi_request(NULL,
intf,
(struct ipmi_addr *) &si,
0,
&msg,
intf,
NULL,
NULL,
0,
intf->channels[0].address,
intf->channels[0].lun,
-1, 0);
}
static void
guid_handler(ipmi_smi_t intf, struct ipmi_recv_msg *msg)
{
if ((msg->addr.addr_type != IPMI_SYSTEM_INTERFACE_ADDR_TYPE)
|| (msg->msg.netfn != IPMI_NETFN_APP_RESPONSE)
|| (msg->msg.cmd != IPMI_GET_DEVICE_GUID_CMD))
/* Not for me */
return;
if (msg->msg.data[0] != 0) {
/* Error from getting the GUID, the BMC doesn't have one. */
intf->bmc->guid_set = 0;
goto out;
}
if (msg->msg.data_len < 17) {
intf->bmc->guid_set = 0;
printk(KERN_WARNING PFX
"guid_handler: The GUID response from the BMC was too"
" short, it was %d but should have been 17. Assuming"
" GUID is not available.\n",
msg->msg.data_len);
goto out;
}
memcpy(intf->bmc->guid, msg->msg.data, 16);
intf->bmc->guid_set = 1;
out:
wake_up(&intf->waitq);
}
static void
get_guid(ipmi_smi_t intf)
{
int rv;
intf->bmc->guid_set = 0x2;
intf->null_user_handler = guid_handler;
rv = send_guid_cmd(intf, 0);
if (rv)
/* Send failed, no GUID available. */
intf->bmc->guid_set = 0;
wait_event(intf->waitq, intf->bmc->guid_set != 2);
intf->null_user_handler = NULL;
}
static int
send_channel_info_cmd(ipmi_smi_t intf, int chan)
{
struct kernel_ipmi_msg msg;
unsigned char data[1];
struct ipmi_system_interface_addr si;
si.addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
si.channel = IPMI_BMC_CHANNEL;
si.lun = 0;
msg.netfn = IPMI_NETFN_APP_REQUEST;
msg.cmd = IPMI_GET_CHANNEL_INFO_CMD;
msg.data = data;
msg.data_len = 1;
data[0] = chan;
return i_ipmi_request(NULL,
intf,
(struct ipmi_addr *) &si,
0,
&msg,
intf,
NULL,
NULL,
0,
intf->channels[0].address,
intf->channels[0].lun,
-1, 0);
}
static void
channel_handler(ipmi_smi_t intf, struct ipmi_recv_msg *msg)
{
int rv = 0;
int chan;
if ((msg->addr.addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE)
&& (msg->msg.netfn == IPMI_NETFN_APP_RESPONSE)
&& (msg->msg.cmd == IPMI_GET_CHANNEL_INFO_CMD)) {
/* It's the one we want */
if (msg->msg.data[0] != 0) {
/* Got an error from the channel, just go on. */
if (msg->msg.data[0] == IPMI_INVALID_COMMAND_ERR) {
/*
* If the MC does not support this
* command, that is legal. We just
* assume it has one IPMB at channel
* zero.
*/
intf->channels[0].medium
= IPMI_CHANNEL_MEDIUM_IPMB;
intf->channels[0].protocol
= IPMI_CHANNEL_PROTOCOL_IPMB;
rv = -ENOSYS;
intf->curr_channel = IPMI_MAX_CHANNELS;
wake_up(&intf->waitq);
goto out;
}
goto next_channel;
}
if (msg->msg.data_len < 4) {
/* Message not big enough, just go on. */
goto next_channel;
}
chan = intf->curr_channel;
intf->channels[chan].medium = msg->msg.data[2] & 0x7f;
intf->channels[chan].protocol = msg->msg.data[3] & 0x1f;
next_channel:
intf->curr_channel++;
if (intf->curr_channel >= IPMI_MAX_CHANNELS)
wake_up(&intf->waitq);
else
rv = send_channel_info_cmd(intf, intf->curr_channel);
if (rv) {
/* Got an error somehow, just give up. */
intf->curr_channel = IPMI_MAX_CHANNELS;
wake_up(&intf->waitq);
printk(KERN_WARNING PFX
"Error sending channel information: %d\n",
rv);
}
}
out:
return;
}
void ipmi_poll_interface(ipmi_user_t user)
{
ipmi_smi_t intf = user->intf;
if (intf->handlers->poll)
intf->handlers->poll(intf->send_info);
}
EXPORT_SYMBOL(ipmi_poll_interface);
int ipmi_register_smi(struct ipmi_smi_handlers *handlers,
void *send_info,
struct ipmi_device_id *device_id,
struct device *si_dev,
const char *sysfs_name,
unsigned char slave_addr)
{
int i, j;
int rv;
ipmi_smi_t intf;
ipmi_smi_t tintf;
struct list_head *link;
/*
* Make sure the driver is actually initialized, this handles
* problems with initialization order.
*/
if (!initialized) {
rv = ipmi_init_msghandler();
if (rv)
return rv;
/*
* The init code doesn't return an error if it was turned
* off, but it won't initialize. Check that.
*/
if (!initialized)
return -ENODEV;
}
intf = kzalloc(sizeof(*intf), GFP_KERNEL);
if (!intf)
return -ENOMEM;
intf->ipmi_version_major = ipmi_version_major(device_id);
intf->ipmi_version_minor = ipmi_version_minor(device_id);
intf->bmc = kzalloc(sizeof(*intf->bmc), GFP_KERNEL);
if (!intf->bmc) {
kfree(intf);
return -ENOMEM;
}
intf->intf_num = -1; /* Mark it invalid for now. */
kref_init(&intf->refcount);
intf->bmc->id = *device_id;
intf->si_dev = si_dev;
for (j = 0; j < IPMI_MAX_CHANNELS; j++) {
intf->channels[j].address = IPMI_BMC_SLAVE_ADDR;
intf->channels[j].lun = 2;
}
if (slave_addr != 0)
intf->channels[0].address = slave_addr;
INIT_LIST_HEAD(&intf->users);
intf->handlers = handlers;
intf->send_info = send_info;
spin_lock_init(&intf->seq_lock);
for (j = 0; j < IPMI_IPMB_NUM_SEQ; j++) {
intf->seq_table[j].inuse = 0;
intf->seq_table[j].seqid = 0;
}
intf->curr_seq = 0;
#ifdef CONFIG_PROC_FS
mutex_init(&intf->proc_entry_lock);
#endif
spin_lock_init(&intf->waiting_msgs_lock);
INIT_LIST_HEAD(&intf->waiting_msgs);
spin_lock_init(&intf->events_lock);
INIT_LIST_HEAD(&intf->waiting_events);
intf->waiting_events_count = 0;
mutex_init(&intf->cmd_rcvrs_mutex);
spin_lock_init(&intf->maintenance_mode_lock);
INIT_LIST_HEAD(&intf->cmd_rcvrs);
init_waitqueue_head(&intf->waitq);
for (i = 0; i < IPMI_NUM_STATS; i++)
atomic_set(&intf->stats[i], 0);
intf->proc_dir = NULL;
mutex_lock(&smi_watchers_mutex);
mutex_lock(&ipmi_interfaces_mutex);
/* Look for a hole in the numbers. */
i = 0;
link = &ipmi_interfaces;
list_for_each_entry_rcu(tintf, &ipmi_interfaces, link) {
if (tintf->intf_num != i) {
link = &tintf->link;
break;
}
i++;
}
/* Add the new interface in numeric order. */
if (i == 0)
list_add_rcu(&intf->link, &ipmi_interfaces);
else
list_add_tail_rcu(&intf->link, link);
rv = handlers->start_processing(send_info, intf);
if (rv)
goto out;
get_guid(intf);
if ((intf->ipmi_version_major > 1)
|| ((intf->ipmi_version_major == 1)
&& (intf->ipmi_version_minor >= 5))) {
/*
* Start scanning the channels to see what is
* available.
*/
intf->null_user_handler = channel_handler;
intf->curr_channel = 0;
rv = send_channel_info_cmd(intf, 0);
if (rv)
goto out;
/* Wait for the channel info to be read. */
wait_event(intf->waitq,
intf->curr_channel >= IPMI_MAX_CHANNELS);
intf->null_user_handler = NULL;
} else {
/* Assume a single IPMB channel at zero. */
intf->channels[0].medium = IPMI_CHANNEL_MEDIUM_IPMB;
intf->channels[0].protocol = IPMI_CHANNEL_PROTOCOL_IPMB;
intf->curr_channel = IPMI_MAX_CHANNELS;
}
if (rv == 0)
rv = add_proc_entries(intf, i);
rv = ipmi_bmc_register(intf, i, sysfs_name);
out:
if (rv) {
if (intf->proc_dir)
remove_proc_entries(intf);
intf->handlers = NULL;
list_del_rcu(&intf->link);
mutex_unlock(&ipmi_interfaces_mutex);
mutex_unlock(&smi_watchers_mutex);
synchronize_rcu();
kref_put(&intf->refcount, intf_free);
} else {
/*
* Keep memory order straight for RCU readers. Make
* sure everything else is committed to memory before
* setting intf_num to mark the interface valid.
*/
smp_wmb();
intf->intf_num = i;
mutex_unlock(&ipmi_interfaces_mutex);
/* After this point the interface is legal to use. */
call_smi_watchers(i, intf->si_dev);
mutex_unlock(&smi_watchers_mutex);
}
return rv;
}
EXPORT_SYMBOL(ipmi_register_smi);
static void cleanup_smi_msgs(ipmi_smi_t intf)
{
int i;
struct seq_table *ent;
/* No need for locks, the interface is down. */
for (i = 0; i < IPMI_IPMB_NUM_SEQ; i++) {
ent = &(intf->seq_table[i]);
if (!ent->inuse)
continue;
deliver_err_response(ent->recv_msg, IPMI_ERR_UNSPECIFIED);
}
}
int ipmi_unregister_smi(ipmi_smi_t intf)
{
struct ipmi_smi_watcher *w;
int intf_num = intf->intf_num;
ipmi_bmc_unregister(intf);
mutex_lock(&smi_watchers_mutex);
mutex_lock(&ipmi_interfaces_mutex);
intf->intf_num = -1;
intf->handlers = NULL;
list_del_rcu(&intf->link);
mutex_unlock(&ipmi_interfaces_mutex);
synchronize_rcu();
cleanup_smi_msgs(intf);
remove_proc_entries(intf);
/*
* Call all the watcher interfaces to tell them that
* an interface is gone.
*/
list_for_each_entry(w, &smi_watchers, link)
w->smi_gone(intf_num);
mutex_unlock(&smi_watchers_mutex);
kref_put(&intf->refcount, intf_free);
return 0;
}
EXPORT_SYMBOL(ipmi_unregister_smi);
static int handle_ipmb_get_msg_rsp(ipmi_smi_t intf,
struct ipmi_smi_msg *msg)
{
struct ipmi_ipmb_addr ipmb_addr;
struct ipmi_recv_msg *recv_msg;
/*
* This is 11, not 10, because the response must contain a
* completion code.
*/
if (msg->rsp_size < 11) {
/* Message not big enough, just ignore it. */
ipmi_inc_stat(intf, invalid_ipmb_responses);
return 0;
}
if (msg->rsp[2] != 0) {
/* An error getting the response, just ignore it. */
return 0;
}
ipmb_addr.addr_type = IPMI_IPMB_ADDR_TYPE;
ipmb_addr.slave_addr = msg->rsp[6];
ipmb_addr.channel = msg->rsp[3] & 0x0f;
ipmb_addr.lun = msg->rsp[7] & 3;
/*
* It's a response from a remote entity. Look up the sequence
* number and handle the response.
*/
if (intf_find_seq(intf,
msg->rsp[7] >> 2,
msg->rsp[3] & 0x0f,
msg->rsp[8],
(msg->rsp[4] >> 2) & (~1),
(struct ipmi_addr *) &(ipmb_addr),
&recv_msg)) {
/*
* We were unable to find the sequence number,
* so just nuke the message.
*/
ipmi_inc_stat(intf, unhandled_ipmb_responses);
return 0;
}
memcpy(recv_msg->msg_data,
&(msg->rsp[9]),
msg->rsp_size - 9);
/*
* The other fields matched, so no need to set them, except
* for netfn, which needs to be the response that was
* returned, not the request value.
*/
recv_msg->msg.netfn = msg->rsp[4] >> 2;
recv_msg->msg.data = recv_msg->msg_data;
recv_msg->msg.data_len = msg->rsp_size - 10;
recv_msg->recv_type = IPMI_RESPONSE_RECV_TYPE;
ipmi_inc_stat(intf, handled_ipmb_responses);
deliver_response(recv_msg);
return 0;
}
static int handle_ipmb_get_msg_cmd(ipmi_smi_t intf,
struct ipmi_smi_msg *msg)
{
struct cmd_rcvr *rcvr;
int rv = 0;
unsigned char netfn;
unsigned char cmd;
unsigned char chan;
ipmi_user_t user = NULL;
struct ipmi_ipmb_addr *ipmb_addr;
struct ipmi_recv_msg *recv_msg;
struct ipmi_smi_handlers *handlers;
if (msg->rsp_size < 10) {
/* Message not big enough, just ignore it. */
ipmi_inc_stat(intf, invalid_commands);
return 0;
}
if (msg->rsp[2] != 0) {
/* An error getting the response, just ignore it. */
return 0;
}
netfn = msg->rsp[4] >> 2;
cmd = msg->rsp[8];
chan = msg->rsp[3] & 0xf;
rcu_read_lock();
rcvr = find_cmd_rcvr(intf, netfn, cmd, chan);
if (rcvr) {
user = rcvr->user;
kref_get(&user->refcount);
} else
user = NULL;
rcu_read_unlock();
if (user == NULL) {
/* We didn't find a user, deliver an error response. */
ipmi_inc_stat(intf, unhandled_commands);
msg->data[0] = (IPMI_NETFN_APP_REQUEST << 2);
msg->data[1] = IPMI_SEND_MSG_CMD;
msg->data[2] = msg->rsp[3];
msg->data[3] = msg->rsp[6];
msg->data[4] = ((netfn + 1) << 2) | (msg->rsp[7] & 0x3);
msg->data[5] = ipmb_checksum(&(msg->data[3]), 2);
msg->data[6] = intf->channels[msg->rsp[3] & 0xf].address;
/* rqseq/lun */
msg->data[7] = (msg->rsp[7] & 0xfc) | (msg->rsp[4] & 0x3);
msg->data[8] = msg->rsp[8]; /* cmd */
msg->data[9] = IPMI_INVALID_CMD_COMPLETION_CODE;
msg->data[10] = ipmb_checksum(&(msg->data[6]), 4);
msg->data_size = 11;
#ifdef DEBUG_MSGING
{
int m;
printk("Invalid command:");
for (m = 0; m < msg->data_size; m++)
printk(" %2.2x", msg->data[m]);
printk("\n");
}
#endif
rcu_read_lock();
handlers = intf->handlers;
if (handlers) {
handlers->sender(intf->send_info, msg, 0);
/*
* We used the message, so return the value
* that causes it to not be freed or
* queued.
*/
rv = -1;
}
rcu_read_unlock();
} else {
/* Deliver the message to the user. */
ipmi_inc_stat(intf, handled_commands);
recv_msg = ipmi_alloc_recv_msg();
if (!recv_msg) {
/*
* We couldn't allocate memory for the
* message, so requeue it for handling
* later.
*/
rv = 1;
kref_put(&user->refcount, free_user);
} else {
/* Extract the source address from the data. */
ipmb_addr = (struct ipmi_ipmb_addr *) &recv_msg->addr;
ipmb_addr->addr_type = IPMI_IPMB_ADDR_TYPE;
ipmb_addr->slave_addr = msg->rsp[6];
ipmb_addr->lun = msg->rsp[7] & 3;
ipmb_addr->channel = msg->rsp[3] & 0xf;
/*
* Extract the rest of the message information
* from the IPMB header.
*/
recv_msg->user = user;
recv_msg->recv_type = IPMI_CMD_RECV_TYPE;
recv_msg->msgid = msg->rsp[7] >> 2;
recv_msg->msg.netfn = msg->rsp[4] >> 2;
recv_msg->msg.cmd = msg->rsp[8];
recv_msg->msg.data = recv_msg->msg_data;
/*
* We chop off 10, not 9 bytes because the checksum
* at the end also needs to be removed.
*/
recv_msg->msg.data_len = msg->rsp_size - 10;
memcpy(recv_msg->msg_data,
&(msg->rsp[9]),
msg->rsp_size - 10);
deliver_response(recv_msg);
}
}
return rv;
}
static int handle_lan_get_msg_rsp(ipmi_smi_t intf,
struct ipmi_smi_msg *msg)
{
struct ipmi_lan_addr lan_addr;
struct ipmi_recv_msg *recv_msg;
/*
* This is 13, not 12, because the response must contain a
* completion code.
*/
if (msg->rsp_size < 13) {
/* Message not big enough, just ignore it. */
ipmi_inc_stat(intf, invalid_lan_responses);
return 0;
}
if (msg->rsp[2] != 0) {
/* An error getting the response, just ignore it. */
return 0;
}
lan_addr.addr_type = IPMI_LAN_ADDR_TYPE;
lan_addr.session_handle = msg->rsp[4];
lan_addr.remote_SWID = msg->rsp[8];
lan_addr.local_SWID = msg->rsp[5];
lan_addr.channel = msg->rsp[3] & 0x0f;
lan_addr.privilege = msg->rsp[3] >> 4;
lan_addr.lun = msg->rsp[9] & 3;
/*
* It's a response from a remote entity. Look up the sequence
* number and handle the response.
*/
if (intf_find_seq(intf,
msg->rsp[9] >> 2,
msg->rsp[3] & 0x0f,
msg->rsp[10],
(msg->rsp[6] >> 2) & (~1),
(struct ipmi_addr *) &(lan_addr),
&recv_msg)) {
/*
* We were unable to find the sequence number,
* so just nuke the message.
*/
ipmi_inc_stat(intf, unhandled_lan_responses);
return 0;
}
memcpy(recv_msg->msg_data,
&(msg->rsp[11]),
msg->rsp_size - 11);
/*
* The other fields matched, so no need to set them, except
* for netfn, which needs to be the response that was
* returned, not the request value.
*/
recv_msg->msg.netfn = msg->rsp[6] >> 2;
recv_msg->msg.data = recv_msg->msg_data;
recv_msg->msg.data_len = msg->rsp_size - 12;
recv_msg->recv_type = IPMI_RESPONSE_RECV_TYPE;
ipmi_inc_stat(intf, handled_lan_responses);
deliver_response(recv_msg);
return 0;
}
static int handle_lan_get_msg_cmd(ipmi_smi_t intf,
struct ipmi_smi_msg *msg)
{
struct cmd_rcvr *rcvr;
int rv = 0;
unsigned char netfn;
unsigned char cmd;
unsigned char chan;
ipmi_user_t user = NULL;
struct ipmi_lan_addr *lan_addr;
struct ipmi_recv_msg *recv_msg;
if (msg->rsp_size < 12) {
/* Message not big enough, just ignore it. */
ipmi_inc_stat(intf, invalid_commands);
return 0;
}
if (msg->rsp[2] != 0) {
/* An error getting the response, just ignore it. */
return 0;
}
netfn = msg->rsp[6] >> 2;
cmd = msg->rsp[10];
chan = msg->rsp[3] & 0xf;
rcu_read_lock();
rcvr = find_cmd_rcvr(intf, netfn, cmd, chan);
if (rcvr) {
user = rcvr->user;
kref_get(&user->refcount);
} else
user = NULL;
rcu_read_unlock();
if (user == NULL) {
/* We didn't find a user, just give up. */
ipmi_inc_stat(intf, unhandled_commands);
/*
* Don't do anything with these messages, just allow
* them to be freed.
*/
rv = 0;
} else {
/* Deliver the message to the user. */
ipmi_inc_stat(intf, handled_commands);
recv_msg = ipmi_alloc_recv_msg();
if (!recv_msg) {
/*
* We couldn't allocate memory for the
* message, so requeue it for handling later.
*/
rv = 1;
kref_put(&user->refcount, free_user);
} else {
/* Extract the source address from the data. */
lan_addr = (struct ipmi_lan_addr *) &recv_msg->addr;
lan_addr->addr_type = IPMI_LAN_ADDR_TYPE;
lan_addr->session_handle = msg->rsp[4];
lan_addr->remote_SWID = msg->rsp[8];
lan_addr->local_SWID = msg->rsp[5];
lan_addr->lun = msg->rsp[9] & 3;
lan_addr->channel = msg->rsp[3] & 0xf;
lan_addr->privilege = msg->rsp[3] >> 4;
/*
* Extract the rest of the message information
* from the IPMB header.
*/
recv_msg->user = user;
recv_msg->recv_type = IPMI_CMD_RECV_TYPE;
recv_msg->msgid = msg->rsp[9] >> 2;
recv_msg->msg.netfn = msg->rsp[6] >> 2;
recv_msg->msg.cmd = msg->rsp[10];
recv_msg->msg.data = recv_msg->msg_data;
/*
* We chop off 12, not 11 bytes because the checksum
* at the end also needs to be removed.
*/
recv_msg->msg.data_len = msg->rsp_size - 12;
memcpy(recv_msg->msg_data,
&(msg->rsp[11]),
msg->rsp_size - 12);
deliver_response(recv_msg);
}
}
return rv;
}
/*
* This routine will handle "Get Message" command responses with
* channels that use an OEM Medium. The message format belongs to
* the OEM. See IPMI 2.0 specification, Chapter 6 and
* Chapter 22, sections 22.6 and 22.24 for more details.
*/
static int handle_oem_get_msg_cmd(ipmi_smi_t intf,
struct ipmi_smi_msg *msg)
{
struct cmd_rcvr *rcvr;
int rv = 0;
unsigned char netfn;
unsigned char cmd;
unsigned char chan;
ipmi_user_t user = NULL;
struct ipmi_system_interface_addr *smi_addr;
struct ipmi_recv_msg *recv_msg;
/*
* We expect the OEM SW to perform error checking
* so we just do some basic sanity checks
*/
if (msg->rsp_size < 4) {
/* Message not big enough, just ignore it. */
ipmi_inc_stat(intf, invalid_commands);
return 0;
}
if (msg->rsp[2] != 0) {
/* An error getting the response, just ignore it. */
return 0;
}
/*
* This is an OEM Message so the OEM needs to know how
* handle the message. We do no interpretation.
*/
netfn = msg->rsp[0] >> 2;
cmd = msg->rsp[1];
chan = msg->rsp[3] & 0xf;
rcu_read_lock();
rcvr = find_cmd_rcvr(intf, netfn, cmd, chan);
if (rcvr) {
user = rcvr->user;
kref_get(&user->refcount);
} else
user = NULL;
rcu_read_unlock();
if (user == NULL) {
/* We didn't find a user, just give up. */
ipmi_inc_stat(intf, unhandled_commands);
/*
* Don't do anything with these messages, just allow
* them to be freed.
*/
rv = 0;
} else {
/* Deliver the message to the user. */
ipmi_inc_stat(intf, handled_commands);
recv_msg = ipmi_alloc_recv_msg();
if (!recv_msg) {
/*
* We couldn't allocate memory for the
* message, so requeue it for handling
* later.
*/
rv = 1;
kref_put(&user->refcount, free_user);
} else {
/*
* OEM Messages are expected to be delivered via
* the system interface to SMS software. We might
* need to visit this again depending on OEM
* requirements
*/
smi_addr = ((struct ipmi_system_interface_addr *)
&(recv_msg->addr));
smi_addr->addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
smi_addr->channel = IPMI_BMC_CHANNEL;
smi_addr->lun = msg->rsp[0] & 3;
recv_msg->user = user;
recv_msg->user_msg_data = NULL;
recv_msg->recv_type = IPMI_OEM_RECV_TYPE;
recv_msg->msg.netfn = msg->rsp[0] >> 2;
recv_msg->msg.cmd = msg->rsp[1];
recv_msg->msg.data = recv_msg->msg_data;
/*
* The message starts at byte 4 which follows the
* the Channel Byte in the "GET MESSAGE" command
*/
recv_msg->msg.data_len = msg->rsp_size - 4;
memcpy(recv_msg->msg_data,
&(msg->rsp[4]),
msg->rsp_size - 4);
deliver_response(recv_msg);
}
}
return rv;
}
static void copy_event_into_recv_msg(struct ipmi_recv_msg *recv_msg,
struct ipmi_smi_msg *msg)
{
struct ipmi_system_interface_addr *smi_addr;
recv_msg->msgid = 0;
smi_addr = (struct ipmi_system_interface_addr *) &(recv_msg->addr);
smi_addr->addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
smi_addr->channel = IPMI_BMC_CHANNEL;
smi_addr->lun = msg->rsp[0] & 3;
recv_msg->recv_type = IPMI_ASYNC_EVENT_RECV_TYPE;
recv_msg->msg.netfn = msg->rsp[0] >> 2;
recv_msg->msg.cmd = msg->rsp[1];
memcpy(recv_msg->msg_data, &(msg->rsp[3]), msg->rsp_size - 3);
recv_msg->msg.data = recv_msg->msg_data;
recv_msg->msg.data_len = msg->rsp_size - 3;
}
static int handle_read_event_rsp(ipmi_smi_t intf,
struct ipmi_smi_msg *msg)
{
struct ipmi_recv_msg *recv_msg, *recv_msg2;
struct list_head msgs;
ipmi_user_t user;
int rv = 0;
int deliver_count = 0;
unsigned long flags;
if (msg->rsp_size < 19) {
/* Message is too small to be an IPMB event. */
ipmi_inc_stat(intf, invalid_events);
return 0;
}
if (msg->rsp[2] != 0) {
/* An error getting the event, just ignore it. */
return 0;
}
INIT_LIST_HEAD(&msgs);
spin_lock_irqsave(&intf->events_lock, flags);
ipmi_inc_stat(intf, events);
/*
* Allocate and fill in one message for every user that is
* getting events.
*/
rcu_read_lock();
list_for_each_entry_rcu(user, &intf->users, link) {
if (!user->gets_events)
continue;
recv_msg = ipmi_alloc_recv_msg();
if (!recv_msg) {
rcu_read_unlock();
list_for_each_entry_safe(recv_msg, recv_msg2, &msgs,
link) {
list_del(&recv_msg->link);
ipmi_free_recv_msg(recv_msg);
}
/*
* We couldn't allocate memory for the
* message, so requeue it for handling
* later.
*/
rv = 1;
goto out;
}
deliver_count++;
copy_event_into_recv_msg(recv_msg, msg);
recv_msg->user = user;
kref_get(&user->refcount);
list_add_tail(&(recv_msg->link), &msgs);
}
rcu_read_unlock();
if (deliver_count) {
/* Now deliver all the messages. */
list_for_each_entry_safe(recv_msg, recv_msg2, &msgs, link) {
list_del(&recv_msg->link);
deliver_response(recv_msg);
}
} else if (intf->waiting_events_count < MAX_EVENTS_IN_QUEUE) {
/*
* No one to receive the message, put it in queue if there's
* not already too many things in the queue.
*/
recv_msg = ipmi_alloc_recv_msg();
if (!recv_msg) {
/*
* We couldn't allocate memory for the
* message, so requeue it for handling
* later.
*/
rv = 1;
goto out;
}
copy_event_into_recv_msg(recv_msg, msg);
list_add_tail(&(recv_msg->link), &(intf->waiting_events));
intf->waiting_events_count++;
} else if (!intf->event_msg_printed) {
/*
* There's too many things in the queue, discard this
* message.
*/
printk(KERN_WARNING PFX "Event queue full, discarding"
" incoming events\n");
intf->event_msg_printed = 1;
}
out:
spin_unlock_irqrestore(&(intf->events_lock), flags);
return rv;
}
static int handle_bmc_rsp(ipmi_smi_t intf,
struct ipmi_smi_msg *msg)
{
struct ipmi_recv_msg *recv_msg;
struct ipmi_user *user;
recv_msg = (struct ipmi_recv_msg *) msg->user_data;
if (recv_msg == NULL) {
printk(KERN_WARNING
"IPMI message received with no owner. This\n"
"could be because of a malformed message, or\n"
"because of a hardware error. Contact your\n"
"hardware vender for assistance\n");
return 0;
}
user = recv_msg->user;
/* Make sure the user still exists. */
if (user && !user->valid) {
/* The user for the message went away, so give up. */
ipmi_inc_stat(intf, unhandled_local_responses);
ipmi_free_recv_msg(recv_msg);
} else {
struct ipmi_system_interface_addr *smi_addr;
ipmi_inc_stat(intf, handled_local_responses);
recv_msg->recv_type = IPMI_RESPONSE_RECV_TYPE;
recv_msg->msgid = msg->msgid;
smi_addr = ((struct ipmi_system_interface_addr *)
&(recv_msg->addr));
smi_addr->addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
smi_addr->channel = IPMI_BMC_CHANNEL;
smi_addr->lun = msg->rsp[0] & 3;
recv_msg->msg.netfn = msg->rsp[0] >> 2;
recv_msg->msg.cmd = msg->rsp[1];
memcpy(recv_msg->msg_data,
&(msg->rsp[2]),
msg->rsp_size - 2);
recv_msg->msg.data = recv_msg->msg_data;
recv_msg->msg.data_len = msg->rsp_size - 2;
deliver_response(recv_msg);
}
return 0;
}
/*
* Handle a new message. Return 1 if the message should be requeued,
* 0 if the message should be freed, or -1 if the message should not
* be freed or requeued.
*/
static int handle_new_recv_msg(ipmi_smi_t intf,
struct ipmi_smi_msg *msg)
{
int requeue;
int chan;
#ifdef DEBUG_MSGING
int m;
printk("Recv:");
for (m = 0; m < msg->rsp_size; m++)
printk(" %2.2x", msg->rsp[m]);
printk("\n");
#endif
if (msg->rsp_size < 2) {
/* Message is too small to be correct. */
printk(KERN_WARNING PFX "BMC returned to small a message"
" for netfn %x cmd %x, got %d bytes\n",
(msg->data[0] >> 2) | 1, msg->data[1], msg->rsp_size);
/* Generate an error response for the message. */
msg->rsp[0] = msg->data[0] | (1 << 2);
msg->rsp[1] = msg->data[1];
msg->rsp[2] = IPMI_ERR_UNSPECIFIED;
msg->rsp_size = 3;
} else if (((msg->rsp[0] >> 2) != ((msg->data[0] >> 2) | 1))
|| (msg->rsp[1] != msg->data[1])) {
/*
* The NetFN and Command in the response is not even
* marginally correct.
*/
printk(KERN_WARNING PFX "BMC returned incorrect response,"
" expected netfn %x cmd %x, got netfn %x cmd %x\n",
(msg->data[0] >> 2) | 1, msg->data[1],
msg->rsp[0] >> 2, msg->rsp[1]);
/* Generate an error response for the message. */
msg->rsp[0] = msg->data[0] | (1 << 2);
msg->rsp[1] = msg->data[1];
msg->rsp[2] = IPMI_ERR_UNSPECIFIED;
msg->rsp_size = 3;
}
if ((msg->rsp[0] == ((IPMI_NETFN_APP_REQUEST|1) << 2))
&& (msg->rsp[1] == IPMI_SEND_MSG_CMD)
&& (msg->user_data != NULL)) {
/*
* It's a response to a response we sent. For this we
* deliver a send message response to the user.
*/
struct ipmi_recv_msg *recv_msg = msg->user_data;
requeue = 0;
if (msg->rsp_size < 2)
/* Message is too small to be correct. */
goto out;
chan = msg->data[2] & 0x0f;
if (chan >= IPMI_MAX_CHANNELS)
/* Invalid channel number */
goto out;
if (!recv_msg)
goto out;
/* Make sure the user still exists. */
if (!recv_msg->user || !recv_msg->user->valid)
goto out;
recv_msg->recv_type = IPMI_RESPONSE_RESPONSE_TYPE;
recv_msg->msg.data = recv_msg->msg_data;
recv_msg->msg.data_len = 1;
recv_msg->msg_data[0] = msg->rsp[2];
deliver_response(recv_msg);
} else if ((msg->rsp[0] == ((IPMI_NETFN_APP_REQUEST|1) << 2))
&& (msg->rsp[1] == IPMI_GET_MSG_CMD)) {
/* It's from the receive queue. */
chan = msg->rsp[3] & 0xf;
if (chan >= IPMI_MAX_CHANNELS) {
/* Invalid channel number */
requeue = 0;
goto out;
}
/*
* We need to make sure the channels have been initialized.
* The channel_handler routine will set the "curr_channel"
* equal to or greater than IPMI_MAX_CHANNELS when all the
* channels for this interface have been initialized.
*/
if (intf->curr_channel < IPMI_MAX_CHANNELS) {
requeue = 0; /* Throw the message away */
goto out;
}
switch (intf->channels[chan].medium) {
case IPMI_CHANNEL_MEDIUM_IPMB:
if (msg->rsp[4] & 0x04) {
/*
* It's a response, so find the
* requesting message and send it up.
*/
requeue = handle_ipmb_get_msg_rsp(intf, msg);
} else {
/*
* It's a command to the SMS from some other
* entity. Handle that.
*/
requeue = handle_ipmb_get_msg_cmd(intf, msg);
}
break;
case IPMI_CHANNEL_MEDIUM_8023LAN:
case IPMI_CHANNEL_MEDIUM_ASYNC:
if (msg->rsp[6] & 0x04) {
/*
* It's a response, so find the
* requesting message and send it up.
*/
requeue = handle_lan_get_msg_rsp(intf, msg);
} else {
/*
* It's a command to the SMS from some other
* entity. Handle that.
*/
requeue = handle_lan_get_msg_cmd(intf, msg);
}
break;
default:
/* Check for OEM Channels. Clients had better
register for these commands. */
if ((intf->channels[chan].medium
>= IPMI_CHANNEL_MEDIUM_OEM_MIN)
&& (intf->channels[chan].medium
<= IPMI_CHANNEL_MEDIUM_OEM_MAX)) {
requeue = handle_oem_get_msg_cmd(intf, msg);
} else {
/*
* We don't handle the channel type, so just
* free the message.
*/
requeue = 0;
}
}
} else if ((msg->rsp[0] == ((IPMI_NETFN_APP_REQUEST|1) << 2))
&& (msg->rsp[1] == IPMI_READ_EVENT_MSG_BUFFER_CMD)) {
/* It's an asyncronous event. */
requeue = handle_read_event_rsp(intf, msg);
} else {
/* It's a response from the local BMC. */
requeue = handle_bmc_rsp(intf, msg);
}
out:
return requeue;
}
/* Handle a new message from the lower layer. */
void ipmi_smi_msg_received(ipmi_smi_t intf,
struct ipmi_smi_msg *msg)
{
unsigned long flags = 0; /* keep us warning-free. */
int rv;
int run_to_completion;
if ((msg->data_size >= 2)
&& (msg->data[0] == (IPMI_NETFN_APP_REQUEST << 2))
&& (msg->data[1] == IPMI_SEND_MSG_CMD)
&& (msg->user_data == NULL)) {
/*
* This is the local response to a command send, start
* the timer for these. The user_data will not be
* NULL if this is a response send, and we will let
* response sends just go through.
*/
/*
* Check for errors, if we get certain errors (ones
* that mean basically we can try again later), we
* ignore them and start the timer. Otherwise we
* report the error immediately.
*/
if ((msg->rsp_size >= 3) && (msg->rsp[2] != 0)
&& (msg->rsp[2] != IPMI_NODE_BUSY_ERR)
&& (msg->rsp[2] != IPMI_LOST_ARBITRATION_ERR)
&& (msg->rsp[2] != IPMI_BUS_ERR)
&& (msg->rsp[2] != IPMI_NAK_ON_WRITE_ERR)) {
int chan = msg->rsp[3] & 0xf;
/* Got an error sending the message, handle it. */
if (chan >= IPMI_MAX_CHANNELS)
; /* This shouldn't happen */
else if ((intf->channels[chan].medium
== IPMI_CHANNEL_MEDIUM_8023LAN)
|| (intf->channels[chan].medium
== IPMI_CHANNEL_MEDIUM_ASYNC))
ipmi_inc_stat(intf, sent_lan_command_errs);
else
ipmi_inc_stat(intf, sent_ipmb_command_errs);
intf_err_seq(intf, msg->msgid, msg->rsp[2]);
} else
/* The message was sent, start the timer. */
intf_start_seq_timer(intf, msg->msgid);
ipmi_free_smi_msg(msg);
goto out;
}
/*
* To preserve message order, if the list is not empty, we
* tack this message onto the end of the list.
*/
run_to_completion = intf->run_to_completion;
if (!run_to_completion)
spin_lock_irqsave(&intf->waiting_msgs_lock, flags);
if (!list_empty(&intf->waiting_msgs)) {
list_add_tail(&msg->link, &intf->waiting_msgs);
if (!run_to_completion)
spin_unlock_irqrestore(&intf->waiting_msgs_lock, flags);
goto out;
}
if (!run_to_completion)
spin_unlock_irqrestore(&intf->waiting_msgs_lock, flags);
rv = handle_new_recv_msg(intf, msg);
if (rv > 0) {
/*
* Could not handle the message now, just add it to a
* list to handle later.
*/
run_to_completion = intf->run_to_completion;
if (!run_to_completion)
spin_lock_irqsave(&intf->waiting_msgs_lock, flags);
list_add_tail(&msg->link, &intf->waiting_msgs);
if (!run_to_completion)
spin_unlock_irqrestore(&intf->waiting_msgs_lock, flags);
} else if (rv == 0) {
ipmi_free_smi_msg(msg);
}
out:
return;
}
EXPORT_SYMBOL(ipmi_smi_msg_received);
void ipmi_smi_watchdog_pretimeout(ipmi_smi_t intf)
{
ipmi_user_t user;
rcu_read_lock();
list_for_each_entry_rcu(user, &intf->users, link) {
if (!user->handler->ipmi_watchdog_pretimeout)
continue;
user->handler->ipmi_watchdog_pretimeout(user->handler_data);
}
rcu_read_unlock();
}
EXPORT_SYMBOL(ipmi_smi_watchdog_pretimeout);
static struct ipmi_smi_msg *
smi_from_recv_msg(ipmi_smi_t intf, struct ipmi_recv_msg *recv_msg,
unsigned char seq, long seqid)
{
struct ipmi_smi_msg *smi_msg = ipmi_alloc_smi_msg();
if (!smi_msg)
/*
* If we can't allocate the message, then just return, we
* get 4 retries, so this should be ok.
*/
return NULL;
memcpy(smi_msg->data, recv_msg->msg.data, recv_msg->msg.data_len);
smi_msg->data_size = recv_msg->msg.data_len;
smi_msg->msgid = STORE_SEQ_IN_MSGID(seq, seqid);
#ifdef DEBUG_MSGING
{
int m;
printk("Resend: ");
for (m = 0; m < smi_msg->data_size; m++)
printk(" %2.2x", smi_msg->data[m]);
printk("\n");
}
#endif
return smi_msg;
}
static void check_msg_timeout(ipmi_smi_t intf, struct seq_table *ent,
struct list_head *timeouts, long timeout_period,
int slot, unsigned long *flags)
{
struct ipmi_recv_msg *msg;
struct ipmi_smi_handlers *handlers;
if (intf->intf_num == -1)
return;
if (!ent->inuse)
return;
ent->timeout -= timeout_period;
if (ent->timeout > 0)
return;
if (ent->retries_left == 0) {
/* The message has used all its retries. */
ent->inuse = 0;
msg = ent->recv_msg;
list_add_tail(&msg->link, timeouts);
if (ent->broadcast)
ipmi_inc_stat(intf, timed_out_ipmb_broadcasts);
else if (is_lan_addr(&ent->recv_msg->addr))
ipmi_inc_stat(intf, timed_out_lan_commands);
else
ipmi_inc_stat(intf, timed_out_ipmb_commands);
} else {
struct ipmi_smi_msg *smi_msg;
/* More retries, send again. */
/*
* Start with the max timer, set to normal timer after
* the message is sent.
*/
ent->timeout = MAX_MSG_TIMEOUT;
ent->retries_left--;
smi_msg = smi_from_recv_msg(intf, ent->recv_msg, slot,
ent->seqid);
if (!smi_msg) {
if (is_lan_addr(&ent->recv_msg->addr))
ipmi_inc_stat(intf,
dropped_rexmit_lan_commands);
else
ipmi_inc_stat(intf,
dropped_rexmit_ipmb_commands);
return;
}
spin_unlock_irqrestore(&intf->seq_lock, *flags);
/*
* Send the new message. We send with a zero
* priority. It timed out, I doubt time is that
* critical now, and high priority messages are really
* only for messages to the local MC, which don't get
* resent.
*/
handlers = intf->handlers;
if (handlers) {
if (is_lan_addr(&ent->recv_msg->addr))
ipmi_inc_stat(intf,
retransmitted_lan_commands);
else
ipmi_inc_stat(intf,
retransmitted_ipmb_commands);
intf->handlers->sender(intf->send_info,
smi_msg, 0);
} else
ipmi_free_smi_msg(smi_msg);
spin_lock_irqsave(&intf->seq_lock, *flags);
}
}
static void ipmi_timeout_handler(long timeout_period)
{
ipmi_smi_t intf;
struct list_head timeouts;
struct ipmi_recv_msg *msg, *msg2;
struct ipmi_smi_msg *smi_msg, *smi_msg2;
unsigned long flags;
int i;
rcu_read_lock();
list_for_each_entry_rcu(intf, &ipmi_interfaces, link) {
/* See if any waiting messages need to be processed. */
spin_lock_irqsave(&intf->waiting_msgs_lock, flags);
list_for_each_entry_safe(smi_msg, smi_msg2,
&intf->waiting_msgs, link) {
if (!handle_new_recv_msg(intf, smi_msg)) {
list_del(&smi_msg->link);
ipmi_free_smi_msg(smi_msg);
} else {
/*
* To preserve message order, quit if we
* can't handle a message.
*/
break;
}
}
spin_unlock_irqrestore(&intf->waiting_msgs_lock, flags);
/*
* Go through the seq table and find any messages that
* have timed out, putting them in the timeouts
* list.
*/
INIT_LIST_HEAD(&timeouts);
spin_lock_irqsave(&intf->seq_lock, flags);
for (i = 0; i < IPMI_IPMB_NUM_SEQ; i++)
check_msg_timeout(intf, &(intf->seq_table[i]),
&timeouts, timeout_period, i,
&flags);
spin_unlock_irqrestore(&intf->seq_lock, flags);
list_for_each_entry_safe(msg, msg2, &timeouts, link)
deliver_err_response(msg, IPMI_TIMEOUT_COMPLETION_CODE);
/*
* Maintenance mode handling. Check the timeout
* optimistically before we claim the lock. It may
* mean a timeout gets missed occasionally, but that
* only means the timeout gets extended by one period
* in that case. No big deal, and it avoids the lock
* most of the time.
*/
if (intf->auto_maintenance_timeout > 0) {
spin_lock_irqsave(&intf->maintenance_mode_lock, flags);
if (intf->auto_maintenance_timeout > 0) {
intf->auto_maintenance_timeout
-= timeout_period;
if (!intf->maintenance_mode
&& (intf->auto_maintenance_timeout <= 0)) {
intf->maintenance_mode_enable = 0;
maintenance_mode_update(intf);
}
}
spin_unlock_irqrestore(&intf->maintenance_mode_lock,
flags);
}
}
rcu_read_unlock();
}
static void ipmi_request_event(void)
{
ipmi_smi_t intf;
struct ipmi_smi_handlers *handlers;
rcu_read_lock();
/*
* Called from the timer, no need to check if handlers is
* valid.
*/
list_for_each_entry_rcu(intf, &ipmi_interfaces, link) {
/* No event requests when in maintenance mode. */
if (intf->maintenance_mode_enable)
continue;
handlers = intf->handlers;
if (handlers)
handlers->request_events(intf->send_info);
}
rcu_read_unlock();
}
static struct timer_list ipmi_timer;
/* Call every ~1000 ms. */
#define IPMI_TIMEOUT_TIME 1000
/* How many jiffies does it take to get to the timeout time. */
#define IPMI_TIMEOUT_JIFFIES ((IPMI_TIMEOUT_TIME * HZ) / 1000)
/*
* Request events from the queue every second (this is the number of
* IPMI_TIMEOUT_TIMES between event requests). Hopefully, in the
* future, IPMI will add a way to know immediately if an event is in
* the queue and this silliness can go away.
*/
#define IPMI_REQUEST_EV_TIME (1000 / (IPMI_TIMEOUT_TIME))
static atomic_t stop_operation;
static unsigned int ticks_to_req_ev = IPMI_REQUEST_EV_TIME;
static void ipmi_timeout(unsigned long data)
{
if (atomic_read(&stop_operation))
return;
ticks_to_req_ev--;
if (ticks_to_req_ev == 0) {
ipmi_request_event();
ticks_to_req_ev = IPMI_REQUEST_EV_TIME;
}
ipmi_timeout_handler(IPMI_TIMEOUT_TIME);
mod_timer(&ipmi_timer, jiffies + IPMI_TIMEOUT_JIFFIES);
}
static atomic_t smi_msg_inuse_count = ATOMIC_INIT(0);
static atomic_t recv_msg_inuse_count = ATOMIC_INIT(0);
/* FIXME - convert these to slabs. */
static void free_smi_msg(struct ipmi_smi_msg *msg)
{
atomic_dec(&smi_msg_inuse_count);
kfree(msg);
}
struct ipmi_smi_msg *ipmi_alloc_smi_msg(void)
{
struct ipmi_smi_msg *rv;
rv = kmalloc(sizeof(struct ipmi_smi_msg), GFP_ATOMIC);
if (rv) {
rv->done = free_smi_msg;
rv->user_data = NULL;
atomic_inc(&smi_msg_inuse_count);
}
return rv;
}
EXPORT_SYMBOL(ipmi_alloc_smi_msg);
static void free_recv_msg(struct ipmi_recv_msg *msg)
{
atomic_dec(&recv_msg_inuse_count);
kfree(msg);
}
static struct ipmi_recv_msg *ipmi_alloc_recv_msg(void)
{
struct ipmi_recv_msg *rv;
rv = kmalloc(sizeof(struct ipmi_recv_msg), GFP_ATOMIC);
if (rv) {
rv->user = NULL;
rv->done = free_recv_msg;
atomic_inc(&recv_msg_inuse_count);
}
return rv;
}
void ipmi_free_recv_msg(struct ipmi_recv_msg *msg)
{
if (msg->user)
kref_put(&msg->user->refcount, free_user);
msg->done(msg);
}
EXPORT_SYMBOL(ipmi_free_recv_msg);
#ifdef CONFIG_IPMI_PANIC_EVENT
static void dummy_smi_done_handler(struct ipmi_smi_msg *msg)
{
}
static void dummy_recv_done_handler(struct ipmi_recv_msg *msg)
{
}
#ifdef CONFIG_IPMI_PANIC_STRING
static void event_receiver_fetcher(ipmi_smi_t intf, struct ipmi_recv_msg *msg)
{
if ((msg->addr.addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE)
&& (msg->msg.netfn == IPMI_NETFN_SENSOR_EVENT_RESPONSE)
&& (msg->msg.cmd == IPMI_GET_EVENT_RECEIVER_CMD)
&& (msg->msg.data[0] == IPMI_CC_NO_ERROR)) {
/* A get event receiver command, save it. */
intf->event_receiver = msg->msg.data[1];
intf->event_receiver_lun = msg->msg.data[2] & 0x3;
}
}
static void device_id_fetcher(ipmi_smi_t intf, struct ipmi_recv_msg *msg)
{
if ((msg->addr.addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE)
&& (msg->msg.netfn == IPMI_NETFN_APP_RESPONSE)
&& (msg->msg.cmd == IPMI_GET_DEVICE_ID_CMD)
&& (msg->msg.data[0] == IPMI_CC_NO_ERROR)) {
/*
* A get device id command, save if we are an event
* receiver or generator.
*/
intf->local_sel_device = (msg->msg.data[6] >> 2) & 1;
intf->local_event_generator = (msg->msg.data[6] >> 5) & 1;
}
}
#endif
static void send_panic_events(char *str)
{
struct kernel_ipmi_msg msg;
ipmi_smi_t intf;
unsigned char data[16];
struct ipmi_system_interface_addr *si;
struct ipmi_addr addr;
struct ipmi_smi_msg smi_msg;
struct ipmi_recv_msg recv_msg;
si = (struct ipmi_system_interface_addr *) &addr;
si->addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
si->channel = IPMI_BMC_CHANNEL;
si->lun = 0;
/* Fill in an event telling that we have failed. */
msg.netfn = 0x04; /* Sensor or Event. */
msg.cmd = 2; /* Platform event command. */
msg.data = data;
msg.data_len = 8;
data[0] = 0x41; /* Kernel generator ID, IPMI table 5-4 */
data[1] = 0x03; /* This is for IPMI 1.0. */
data[2] = 0x20; /* OS Critical Stop, IPMI table 36-3 */
data[4] = 0x6f; /* Sensor specific, IPMI table 36-1 */
data[5] = 0xa1; /* Runtime stop OEM bytes 2 & 3. */
/*
* Put a few breadcrumbs in. Hopefully later we can add more things
* to make the panic events more useful.
*/
if (str) {
data[3] = str[0];
data[6] = str[1];
data[7] = str[2];
}
smi_msg.done = dummy_smi_done_handler;
recv_msg.done = dummy_recv_done_handler;
/* For every registered interface, send the event. */
list_for_each_entry_rcu(intf, &ipmi_interfaces, link) {
if (!intf->handlers)
/* Interface is not ready. */
continue;
intf->run_to_completion = 1;
/* Send the event announcing the panic. */
intf->handlers->set_run_to_completion(intf->send_info, 1);
i_ipmi_request(NULL,
intf,
&addr,
0,
&msg,
intf,
&smi_msg,
&recv_msg,
0,
intf->channels[0].address,
intf->channels[0].lun,
0, 1); /* Don't retry, and don't wait. */
}
#ifdef CONFIG_IPMI_PANIC_STRING
/*
* On every interface, dump a bunch of OEM event holding the
* string.
*/
if (!str)
return;
/* For every registered interface, send the event. */
list_for_each_entry_rcu(intf, &ipmi_interfaces, link) {
char *p = str;
struct ipmi_ipmb_addr *ipmb;
int j;
if (intf->intf_num == -1)
/* Interface was not ready yet. */
continue;
/*
* intf_num is used as an marker to tell if the
* interface is valid. Thus we need a read barrier to
* make sure data fetched before checking intf_num
* won't be used.
*/
smp_rmb();
/*
* First job here is to figure out where to send the
* OEM events. There's no way in IPMI to send OEM
* events using an event send command, so we have to
* find the SEL to put them in and stick them in
* there.
*/
/* Get capabilities from the get device id. */
intf->local_sel_device = 0;
intf->local_event_generator = 0;
intf->event_receiver = 0;
/* Request the device info from the local MC. */
msg.netfn = IPMI_NETFN_APP_REQUEST;
msg.cmd = IPMI_GET_DEVICE_ID_CMD;
msg.data = NULL;
msg.data_len = 0;
intf->null_user_handler = device_id_fetcher;
i_ipmi_request(NULL,
intf,
&addr,
0,
&msg,
intf,
&smi_msg,
&recv_msg,
0,
intf->channels[0].address,
intf->channels[0].lun,
0, 1); /* Don't retry, and don't wait. */
if (intf->local_event_generator) {
/* Request the event receiver from the local MC. */
msg.netfn = IPMI_NETFN_SENSOR_EVENT_REQUEST;
msg.cmd = IPMI_GET_EVENT_RECEIVER_CMD;
msg.data = NULL;
msg.data_len = 0;
intf->null_user_handler = event_receiver_fetcher;
i_ipmi_request(NULL,
intf,
&addr,
0,
&msg,
intf,
&smi_msg,
&recv_msg,
0,
intf->channels[0].address,
intf->channels[0].lun,
0, 1); /* no retry, and no wait. */
}
intf->null_user_handler = NULL;
/*
* Validate the event receiver. The low bit must not
* be 1 (it must be a valid IPMB address), it cannot
* be zero, and it must not be my address.
*/
if (((intf->event_receiver & 1) == 0)
&& (intf->event_receiver != 0)
&& (intf->event_receiver != intf->channels[0].address)) {
/*
* The event receiver is valid, send an IPMB
* message.
*/
ipmb = (struct ipmi_ipmb_addr *) &addr;
ipmb->addr_type = IPMI_IPMB_ADDR_TYPE;
ipmb->channel = 0; /* FIXME - is this right? */
ipmb->lun = intf->event_receiver_lun;
ipmb->slave_addr = intf->event_receiver;
} else if (intf->local_sel_device) {
/*
* The event receiver was not valid (or was
* me), but I am an SEL device, just dump it
* in my SEL.
*/
si = (struct ipmi_system_interface_addr *) &addr;
si->addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
si->channel = IPMI_BMC_CHANNEL;
si->lun = 0;
} else
continue; /* No where to send the event. */
msg.netfn = IPMI_NETFN_STORAGE_REQUEST; /* Storage. */
msg.cmd = IPMI_ADD_SEL_ENTRY_CMD;
msg.data = data;
msg.data_len = 16;
j = 0;
while (*p) {
int size = strlen(p);
if (size > 11)
size = 11;
data[0] = 0;
data[1] = 0;
data[2] = 0xf0; /* OEM event without timestamp. */
data[3] = intf->channels[0].address;
data[4] = j++; /* sequence # */
/*
* Always give 11 bytes, so strncpy will fill
* it with zeroes for me.
*/
strncpy(data+5, p, 11);
p += size;
i_ipmi_request(NULL,
intf,
&addr,
0,
&msg,
intf,
&smi_msg,
&recv_msg,
0,
intf->channels[0].address,
intf->channels[0].lun,
0, 1); /* no retry, and no wait. */
}
}
#endif /* CONFIG_IPMI_PANIC_STRING */
}
#endif /* CONFIG_IPMI_PANIC_EVENT */
static int has_panicked;
static int panic_event(struct notifier_block *this,
unsigned long event,
void *ptr)
{
ipmi_smi_t intf;
if (has_panicked)
return NOTIFY_DONE;
has_panicked = 1;
/* For every registered interface, set it to run to completion. */
list_for_each_entry_rcu(intf, &ipmi_interfaces, link) {
if (!intf->handlers)
/* Interface is not ready. */
continue;
intf->run_to_completion = 1;
intf->handlers->set_run_to_completion(intf->send_info, 1);
}
#ifdef CONFIG_IPMI_PANIC_EVENT
send_panic_events(ptr);
#endif
return NOTIFY_DONE;
}
static struct notifier_block panic_block = {
.notifier_call = panic_event,
.next = NULL,
.priority = 200 /* priority: INT_MAX >= x >= 0 */
};
static int ipmi_init_msghandler(void)
{
int rv;
if (initialized)
return 0;
rv = driver_register(&ipmidriver.driver);
if (rv) {
printk(KERN_ERR PFX "Could not register IPMI driver\n");
return rv;
}
printk(KERN_INFO "ipmi message handler version "
IPMI_DRIVER_VERSION "\n");
#ifdef CONFIG_PROC_FS
proc_ipmi_root = proc_mkdir("ipmi", NULL);
if (!proc_ipmi_root) {
printk(KERN_ERR PFX "Unable to create IPMI proc dir");
return -ENOMEM;
}
#endif /* CONFIG_PROC_FS */
setup_timer(&ipmi_timer, ipmi_timeout, 0);
mod_timer(&ipmi_timer, jiffies + IPMI_TIMEOUT_JIFFIES);
atomic_notifier_chain_register(&panic_notifier_list, &panic_block);
initialized = 1;
return 0;
}
static int __init ipmi_init_msghandler_mod(void)
{
ipmi_init_msghandler();
return 0;
}
static void __exit cleanup_ipmi(void)
{
int count;
if (!initialized)
return;
atomic_notifier_chain_unregister(&panic_notifier_list, &panic_block);
/*
* This can't be called if any interfaces exist, so no worry
* about shutting down the interfaces.
*/
/*
* Tell the timer to stop, then wait for it to stop. This
* avoids problems with race conditions removing the timer
* here.
*/
atomic_inc(&stop_operation);
del_timer_sync(&ipmi_timer);
#ifdef CONFIG_PROC_FS
remove_proc_entry(proc_ipmi_root->name, NULL);
#endif /* CONFIG_PROC_FS */
driver_unregister(&ipmidriver.driver);
initialized = 0;
/* Check for buffer leaks. */
count = atomic_read(&smi_msg_inuse_count);
if (count != 0)
printk(KERN_WARNING PFX "SMI message count %d at exit\n",
count);
count = atomic_read(&recv_msg_inuse_count);
if (count != 0)
printk(KERN_WARNING PFX "recv message count %d at exit\n",
count);
}
module_exit(cleanup_ipmi);
module_init(ipmi_init_msghandler_mod);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Corey Minyard <minyard@mvista.com>");
MODULE_DESCRIPTION("Incoming and outgoing message routing for an IPMI"
" interface.");
MODULE_VERSION(IPMI_DRIVER_VERSION);
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.